date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/16
| 762 | 2,917 |
<issue_start>username_0: Im trying to change between two colors when I click on the event listener using JavaScript. When I trigger the `click` event, it changes the color to black. When I click on it again, I want it to change back to the default, which is white. I think that an if statement is involved, but Im not sure how the logic would work in this case.
```
Light Switch
Submit
```
```
function start() {
var submit = document.getElementById("submit");
submit.addEventListener("click", toggle);
};
function toggle() {
var color = document.getElementById("body");
color.style.backgroundColor = "black";
};
start();
```<issue_comment>username_1: You can use `toggle` function on the `classList` of that element. Add a class and toggle it.
```js
function start() {
var submit = document.getElementById("submit");
submit.addEventListener("click", toggle);
};
function toggle() {
var color = document.getElementById("body");
color.classList.toggle('black');
};
start();
```
```css
.black {
background-color: black;
}
```
```html
Submit
```
You can also just check the current color and switch every time.
```js
function start() {
var submit = document.getElementById("submit");
submit.addEventListener("click", toggle);
};
function toggle() {
var color = document.getElementById("body");
var backColor = color.style.backgroundColor;
color.style.backgroundColor = backColor === "black" ? "white" : "black";
};
start();
```
```html
Submit
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Instead of manipulating `backgroundColor`, You can create CSS class and add/remove it to the element using [`classList`](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList) property
```js
function start() {
var submit = document.getElementById("submit");
submit.addEventListener("click", toggle);
};
function toggle() {
var color = document.getElementById("body");
color.classList.toggle("black");
};
start();
```
```css
.black {
background-color: black;
}
```
```html
Submit
```
Upvotes: 2 <issue_comment>username_3: Do like this, i think it work for you...
```
var background = document.getElementById(id).style.background;
var btn = addEventListener("click", function (){
if(background = "rgb(255,145,0)"){
document.getElementById(id).style.background = "red";
}
else
{
document.getElementById(id).style.background = "white";
}
});
```
Upvotes: 0 <issue_comment>username_4: ```js
function start() {
var submit = document.getElementById("submit");
submit.addEventListener("click", toggle);
};
function toggle() {
var color = document.getElementById("body");
if(color.style.backgroundColor==='black')
color.style.backgroundColor='';
else
color.style.backgroundColor = "black";
};
start();
```
Upvotes: 0
|
2018/03/16
| 762 | 2,315 |
<issue_start>username_0: **CodeIgniter / PHP / MYSQL**
I have Two Tables with this structure.
1. COUNTRY : id, country\_name (1,Indonesia,2,India)
2. STATE : id, country\_id, state\_name (1,1,Sulawesi Selatan) (2,1,Sulawesi Tengah) (3,1,Sumatera Utara) (4,2,Gujarat)
I want to make search with multiple tables.
For Example, If I type "si" then it will give results like
---
Indonesia ------- Sulawesi Selatan
Indonesia ------- Sulawesi Tengah
India ------------- Gujarat
---
How to find this result in codeingniter query :
I am trying this query :
```
SELECT ts.id,ts.state_name,tc.country_name
FROM STATE ts
LEFT JOIN COUNTRY tc
ON tc.id = ts.country_id
WHERE ts.state_name LIKE '%si%' || tc.country_name LIKE '%si%'
```
My Output With This Query :
---
Sulawesi Selatan ------- Indonesia
Sulawesi Tengah ------- Indonesia
Sumatera Utara ------- Indonesia
---<issue_comment>username_1: you can try this code:
**Controller**
```
public function search_general_medicine() {
ini_set("memory_limit", "512M");
$keyword = $this->input->post('keyword');
$medical_id = $this->input->post('medical_id');
if ($keyword != '' && $medical_id != '') {
$result_medicine = $this->ws->get_medicine_details($keyword);
print_r($result_medicine);
}
```
**Model**
```
function get_medicine_details($keyword)
{
$query = "SELECT * FROM (
SELECT medicine_id, medicine_name,medicine_package,medical_id,'g' FROM tbl_general_medicine
UNION
SELECT medicine_id, medicine_name,medicine_package,medical_id,'c' FROM tbl_medicine
) AS t
WHERE medicine_name LIKE '%" . $keyword . "%' limit 20;";
$result_medicine = $this->db->query($query);
if ($result_medicine->num_rows() > 0) {
return $result_medicine->result_array();
} else {
return array();
}
}
```
Upvotes: 0 <issue_comment>username_2: Using the or\_like() / orlike(), For more info please ref :<https://codeigniter.com/userguide2/database/active_record.html>
```
$this->db->select("ts.id,ts.state_name,tc.country_name");
$this->db->from("STATE ts")
$this->db->join("COUNTRY tc","tc.id = ts.country_id","Left");
$this->db->like('ts.state_name', $word);
$this->db->or_like('tc.country_name',$word);
```
Upvotes: 1
|
2018/03/16
| 668 | 2,117 |
<issue_start>username_0: I am trying to implement max drawdown for my loss function using code with the format of:
```
x = cumulative product of returns tensor
z = cumulative max of x
g = minimum of z / x
```
But I'm stuck on how to calculate cumulative maximum of `x` in Tensorflow. For example: given an array `[0,2,5,3,8,1,7]`, the cumulative maximum of that array would be `[0,2,5,5,8,8,8]`. It creates an array with the max value so far.
Any tips would be greatly appreciated.<issue_comment>username_1: Here's an implementation of `cumulative_max` using a tensorflow while loop which takes `n=len(x)` iterations. The code is copy-paste runnable on TF 2.x as an example.
```
import tensorflow as tf
def tf_while_condition(x, loop_counter):
return tf.not_equal(loop_counter, 0)
def tf_while_body(x, loop_counter):
loop_counter -= 1
y = tf.concat(([x[0]], x[:-1]), axis=0)
new_x = tf.maximum(x, y)
return new_x, loop_counter
x = tf.constant([0,2,5,3,8,1,7])
cumulative_max, _ = tf.while_loop(cond=tf_while_condition,
body=tf_while_body,
loop_vars=(x, tf.shape(x)[0]))
print(cumulative_max)
```
**Result:**
```
[0 2 5 5 8 8 8]
```
Note: If you have a large vector to compute and you don't need backprop, it's probably worthwhile to include `back_prop=False` in the `tf.while_loop`.
A key to understanding TF while loops is to understand that your python based functions, `tf_while_condition` and `tf_while_body`, are only called once to produce the relevant tensorflow operations. Those two functions are *NOT* called in a loop. The operations they return will be executed in a loop within the tensorflow graph during `sess.run` computations.
Upvotes: 3 <issue_comment>username_2: The `tf.scan` op allows you to make all kinds of cumulative operations, a bit nicer solution might be the following (tested using `TF 2.8.0`)
```
tensor = tf.constant([0, 2, 5, 3, 8, 1, 7])
cumulative_max = tf.scan(lambda a, b: tf.maximum(a, b), tensor, initializer=tf.reduce_min(tensor))
# Result: [0, 2, 5, 5, 8, 8, 8]
```
Upvotes: 2
|
2018/03/16
| 711 | 2,260 |
<issue_start>username_0: Here I am searching for a number say 4, Although it is presented in my array num[] but still not founded by using if condition . If I remove else condition it is prints founded..quite confusing for me that why this happening.
```
int n=0;
Scanner sc= new Scanner(System.in);
int num[]={1,2,3,4,5};
System.out.print("Enter Number To Search");
n=sc.nextInt();
for(int i=1;i<=num.length;i++)
{
if(n==num[i])
{
System.out.println("Founded !");
break;
}
else
{
System.out.println("Not Found !");
break;
}
}
```<issue_comment>username_1: Here's an implementation of `cumulative_max` using a tensorflow while loop which takes `n=len(x)` iterations. The code is copy-paste runnable on TF 2.x as an example.
```
import tensorflow as tf
def tf_while_condition(x, loop_counter):
return tf.not_equal(loop_counter, 0)
def tf_while_body(x, loop_counter):
loop_counter -= 1
y = tf.concat(([x[0]], x[:-1]), axis=0)
new_x = tf.maximum(x, y)
return new_x, loop_counter
x = tf.constant([0,2,5,3,8,1,7])
cumulative_max, _ = tf.while_loop(cond=tf_while_condition,
body=tf_while_body,
loop_vars=(x, tf.shape(x)[0]))
print(cumulative_max)
```
**Result:**
```
[0 2 5 5 8 8 8]
```
Note: If you have a large vector to compute and you don't need backprop, it's probably worthwhile to include `back_prop=False` in the `tf.while_loop`.
A key to understanding TF while loops is to understand that your python based functions, `tf_while_condition` and `tf_while_body`, are only called once to produce the relevant tensorflow operations. Those two functions are *NOT* called in a loop. The operations they return will be executed in a loop within the tensorflow graph during `sess.run` computations.
Upvotes: 3 <issue_comment>username_2: The `tf.scan` op allows you to make all kinds of cumulative operations, a bit nicer solution might be the following (tested using `TF 2.8.0`)
```
tensor = tf.constant([0, 2, 5, 3, 8, 1, 7])
cumulative_max = tf.scan(lambda a, b: tf.maximum(a, b), tensor, initializer=tf.reduce_min(tensor))
# Result: [0, 2, 5, 5, 8, 8, 8]
```
Upvotes: 2
|
2018/03/16
| 811 | 2,448 |
<issue_start>username_0: I was hoping this would o/p the last letter of my argv[1]:
```
$ cat input_string_fu.c
#include
int main(int argc, char \*argv[])
{
if (argc !=2){
printf("Error: Invalid syntax\n");
return 1;
};
int a;
a = strlen(argv[1]);
if (a >= 2){
printf("Last char of %s : %c\n", argv[1], argv[1][a-1] );
printf("Last char of %s : %s\n", argv[1], argv[1][a-1] );
}
return 0;
}
```
I am confused as to why is printf("%s") on argv[1][a-1] segfaulting.
```
$ ./a.out stackoverflow
Last char of stackoverflow : w
Segmentation fault
$
```
Thank you for your time and expertise!
**EDIT 1:**
Thanks for the guidance. TIL, `printf("%s\n", argv[1][a-1]);` was segfaulting because the %s format specification in printf expects the corresponding argument to be a null terminated char array.
either, **(1)** pass a pointer:
```
printf("%s\n", &argv[1][a-1]);
```
or, as :
```
char *ptr = argv[1];
printf("%s\n", &ptr[a-1]);
```
Or, **(2)** use char:
```
printf("%c\n", argv[1][a-1]);
```<issue_comment>username_1: Format string for second printf `"Last char of %s : %s\n"` requires a pointer to a null-terminated string as a second parameter while you supply char.
Upvotes: 2 <issue_comment>username_2: In Second line you have to write `%c` Because `%s` need `const char *` argument
and you are passing `const char`
```
if (a >= 2){
printf("Last char of %s : %c\n", argv[1], argv[1][a-1] );
printf("Last char of %s : %c\n", argv[1], argv[1][a-1] );
}
```
Upvotes: 0 <issue_comment>username_3: Because `%s` format specifier used for string, but you are trying to print character using `%s`.
According to [printf](https://linux.die.net/man/3/printf):
>
> **s**
>
>
> If no l modifier is present: The const char \* argument is **expected
> to be a pointer to an array of character type (pointer to a string)**.
> Characters from the array are written up to (but not including) a
> terminating null byte ('\0'); if a precision is specified, no more
> than the number specified are written. If a precision is given, no
> null byte need be present; if the precision is not specified, or is
> greater than the size of the array, the array must contain a
> terminating null byte.
>
>
>
Upvotes: 4 [selected_answer]<issue_comment>username_4: Because `argv[1][a-1]` is a `char` value, ok for `%c`, not the address of a `char` array zero terminated usable for `%s`.
Upvotes: 2
|
2018/03/16
| 1,114 | 3,798 |
<issue_start>username_0: I'm having trouble casting a a response from a valueset expansion to the valueset resource object in c#.
I'm currently using RestSharp, the REST call is successful, and the following outputs the expected JSON.
```
IRestResponse response = client.Execute(request);
var result = JsonConvert.DeserializeObject(response.Content);
Console.WriteLine(result);
```
I've tried
```
var result = JsonConvert.DeserializeObject(response.Content);
```
But it produces a null object. I'm sure I'm making some rookie error, and perhaps should look into using the Hl7.Fhir.Rest instead of RestSharp?<issue_comment>username_1: So I did end up being able to deserialise the RestSharp JSON response, by creating custom ValueSet class (I just used <http://json2csharp.com/> for my experiment).
However I took @Mirjam's advice, and used **Hl7.Fhir.Rest** instead (And ValueSet class from **HL7.Fhir.Model** - which contains so much more goodness than could be achieved using a custom class.
```
// using using Hl7.Fhir.Model;
// using Hl7.Fhir.Rest;
const string Endpoint = "https://ontoserver.csiro.au/stu3-latest";
var client = new FhirClient(Endpoint);
//uri for the value set to be searched, and text filter
var filter = new FhirString("inr");
var vs_uri = new FhirUri("http://snomed.info/sct?fhir_vs=refset/1072351000168102");
ValueSet result = client.ExpandValueSet(vs_uri, filter);
//Write out the display term of the first result.
Console.WriteLine(result.Expansion.Contains.FirstOrDefault().Display);
```
There's a couple of other approaches, that support additional parameters...
Code available - <https://gist.github.com/MattCordell/32f3c62b4e66bd1ecb17b65f2f498acb>
Upvotes: 3 [selected_answer]<issue_comment>username_2: First, you should check out
A REST client for working with FHIR-compliant servers;
<https://www.nuget.org/packages/Hl7.Fhir.R4/4.3.0>
(and "examples" via unit-tests here)
<https://github.com/FirelyTeam/firely-net-sdk/blob/release/4.0.0-r4/src/Hl7.Fhir.Core.Tests/Rest/FhirClientTests.cs>
You should try really hard to use the above. It avoids "re-invent the wheel syndrome", especially "un happy paths" and how fhir-servers handle paging.
HOWEVER, if you do not follow the above advice:
You can use HttpClient and <https://www.nuget.org/packages/Hl7.Fhir.DSTU2/> (or <https://www.nuget.org/packages/Hl7.Fhir.STU3/>) ( or <https://www.nuget.org/packages/Hl7.Fhir.R4/> ) (or whatever is the latest)
```
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
/* magic ones */
using Hl7.Fhir.Serialization;
using Hl7.Fhir.Model;
string url = "https://www.somebody.com/FHIR/api/Patient?given=Jason&family=Smith";
HttpClient client = new HttpClient();
{
using (HttpResponseMessage response = await client.GetAsync(url))
{
using (HttpContent content = response.Content)
{
string responseString = await content.ReadAsStringAsync();
response.EnsureSuccessStatusCode();
/* Hl7.Fhir.DSTU2 \.nuget\packages\hl7.fhir.dstu2\0.96.0 */
FhirJsonParser fjp = new FhirJsonParser(); /* there is a FhirXmlParser as well */
/* You may need to Parse as something besides a Bundle depending on the return payload */
Hl7.Fhir.Model.Bundle bund = fjp.Parse(responseString);
if (null != bund)
{
Hl7.Fhir.Model.Bundle.EntryComponent ec = bund.Entry.FirstOrDefault();
if (null != ec && null != ec.Resource)
{
/\* again, this may be a different kind of object based on which rest url you hit \*/
Hl7.Fhir.Model.Patient pat = ec.Resource as Hl7.Fhir.Model.Patient;
}
}
}
}
}
```
Upvotes: 3
|
2018/03/16
| 414 | 1,220 |
<issue_start>username_0: This is my code
```
SELECT IDENTITY(INT, 1, 2) AS Orderid , CODE , [DATE] , [TIME] INTO #Temp
FROM Table1 ORDER BY CODE ,[DATE],[TIME]
SELECT * FROM #Temp
```
Output from this code is here:

But I need the following output:

So what can I do ...<issue_comment>username_1: Your method, aside from not generating sequence numbers partitioned by `CODE`, does not guarantee that records will be insert into `#temp` in the order they are selected.
You can use `ROW_NUMBER` to generate the sequence numbers during the `INSERT`:
```
SELECT 2 * ROW_NUMBER() OVER (PARTITION BY CODE
ORDER BY CODE,[DATE], [TIME]) - 1,
CODE, [DATE], [TIME]
INTO #Temp
FROM Table1
ORDER BY CODE,[DATE],[TIME]
```
This will generate sequence numbers:
```
ID CODE, DATE
--------------
1, 2210, ...
3, 2210, ...
5, 2210, ...
1, 10484, ...
3, 10484, ...
5, 10484, ...
7, 10484, ...
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Use this
```
SELECT (ROW_NUMBER() OVER (ORDER BY CODE ,[DATE],[TIME])) AS Orderid ........
```
Upvotes: 0
|
2018/03/16
| 631 | 1,806 |
<issue_start>username_0: stuck with create dbf file in python3 with dbf lib.
im tried this -
```
import dbf
Tbl = dbf.Table( 'sample.dbf', 'ID N(6,0); FCODE C(10)')
Tbl.open('read-write')
Tbl.append()
with Tbl.last_record as rec:
rec.ID = 5
rec.FCODE = 'GA24850000'
```
and have next error:
```
Traceback (most recent call last):
File "c:\Users\operator\Desktop\2.py", line 3, in
Tbl.open('read-write')
File "C:\Users\operator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\dbf\\_\_init\_\_.py", line 5778, in open
raise DbfError("mode for open must be 'read-write' or 'read-only', not %r" % mode)
dbf.DbfError: mode for open must be 'read-write' or 'read-only', not 'read-write'
```
if im remove 'read-write' - next:
```
Traceback (most recent call last):
File "c:\Users\operator\Desktop\2.py", line 4, in
Tbl.append()
File "C:\Users\operator\AppData\Local\Programs\Python\Python36-32\lib\site-packages\dbf\\_\_init\_\_.py", line 5492, in append
raise DbfError('%s not in read/write mode, unable to append records' % meta.filename)
dbf.DbfError: sample.dbf not in read/write mode, unable to append records
```
thats im doing wrong? if im not try append, im just get .dbf with right columns, so dbf library works.<issue_comment>username_1: I had the same error.
In the older versions of the dbf module, I was able to write dbf files by opening them just with
`Tbl.open()`
However, with the new version (dbf.0.97), I have to open the files with
`Tbl.open(mode=dbf.READ_WRITE)`
in order to be able to write them.
Upvotes: 3 [selected_answer]<issue_comment>username_2: here's an append example:
```
table = dbf.Table('sample.dbf', 'cod N(1,0); name C(30)')
table.open(mode=dbf.READ_WRITE)
row_tuple = (1, 'Name')
table.append(row_tuple)
```
Upvotes: 2
|
2018/03/16
| 3,346 | 15,809 |
<issue_start>username_0: I have created an Android app in Android Studio and linked it with Firebase Realtime database. I have used Firebase's Authentication by phone and Notification Services to send OTP to the CUG phone no. and then verify it(The code is given below).
```
public class PhoneLogin extends AppCompatActivity {
private static final String TAG = "PhoneLogin";
private boolean mVerificationInProgress = false;
private String mVerificationId;
private PhoneAuthProvider.ForceResendingToken mResendToken;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
private FirebaseAuth mAuth;
TextView t1,t2;
ImageView i1;
EditText e1,e2;
Button b1,b2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_login);
e1 = (EditText) findViewById(R.id.Phonenoedittext); //Enter Phone no.
b1 = (Button) findViewById(R.id.PhoneVerify); //Send OTP button
t1 = (TextView)findViewById(R.id.textView2Phone); //Telling user to enter phone no.
i1 = (ImageView)findViewById(R.id.imageView2Phone); //Phone icon
e2 = (EditText) findViewById(R.id.OTPeditText); //Enter OTP
b2 = (Button)findViewById(R.id.OTPVERIFY); //Verify OTP button
t2 = (TextView)findViewById(R.id.textViewVerified); //Telling user to enter otp
mAuth = FirebaseAuth.getInstance();
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
@Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
// Log.d(TAG, "onVerificationCompleted:" + credential);
mVerificationInProgress = false;
Toast.makeText(PhoneLogin.this,"Verification Complete",Toast.LENGTH_SHORT).show();
signInWithPhoneAuthCredential(credential);
}
@Override
public void onVerificationFailed(FirebaseException e) {
// Log.w(TAG, "onVerificationFailed", e);
Toast.makeText(PhoneLogin.this,"Verification Failed",Toast.LENGTH_SHORT).show();
if (e instanceof FirebaseAuthInvalidCredentialsException) {
// Invalid request
Toast.makeText(PhoneLogin.this,"InValid Phone Number",Toast.LENGTH_SHORT).show();
// ...
} else if (e instanceof FirebaseTooManyRequestsException) {
}
}
@Override
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken token) {
// Log.d(TAG, "onCodeSent:" + verificationId);
Toast.makeText(PhoneLogin.this,"Verification code has been sent",Toast.LENGTH_SHORT).show();
// Save verification ID and resending token so we can use them later
mVerificationId = verificationId;
mResendToken = token;
e1.setVisibility(View.GONE);
b1.setVisibility(View.GONE);
t1.setVisibility(View.GONE);
i1.setVisibility(View.GONE);
t2.setVisibility(View.VISIBLE);
e2.setVisibility(View.VISIBLE);
b2.setVisibility(View.VISIBLE);
// ...
}
};
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PhoneAuthProvider.getInstance().verifyPhoneNumber(
e1.getText().toString(),
60,
java.util.concurrent.TimeUnit.SECONDS,
PhoneLogin.this,
mCallbacks);
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, e2.getText().toString());
// [END verify_with_code]
signInWithPhoneAuthCredential(credential);
}
});
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()) {
// Log.d(TAG, "signInWithCredential:success");
startActivity(new Intent(PhoneLogin.this,NavigationDrawer.class));
Toast.makeText(PhoneLogin.this,"Verification Done",Toast.LENGTH\_SHORT).show();
// ...
} else {
// Log.w(TAG, "signInWithCredential:failure", task.getException());
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
// The verification code entered was invalid
Toast.makeText(PhoneLogin.this,"Invalid Verification",Toast.LENGTH\_SHORT).show();
}
}
}
});
}
}
```
Now I want to add another verification that the entered CUG no. exists in my database and then only the OTP authentication should take place. My database looks like this:
[My database](https://i.stack.imgur.com/DglmK.png)
and the code to access this database could be
```
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference phoneNumberRef =
rootRef.child("Employees").child(PhoneNumberenteredByUser);
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
//do something
} else {
//do something else
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
phoneNumberRef.addListenerForSingleValueEvent(eventListener);
```
Also, when I saw about the rules of Firebase Realtime database I noticed that it shouldn't be left public but if I need to keep it private then the user should be authenticated first, so do I need to first authenticate the user by OTP and then check if the user CUG no. exists in my database?
Edited code which is authenticating any no. even if it's not in my database:
```
public class PhoneLogin extends AppCompatActivity {
private static final String TAG = "PhoneLogin";
private boolean mVerificationInProgress = false;
private String mVerificationId;
private PhoneAuthProvider.ForceResendingToken mResendToken;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
private FirebaseAuth mAuth;
TextView t1,t2;
ImageView i1;
EditText e1,e2;
Button b1,b2;
//DBA1
private DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
private DatabaseReference phoneNumberRef;
String mobno;
//DBA1 End
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_login);
e1 = (EditText) findViewById(R.id.Phonenoedittext);
b1 = (Button) findViewById(R.id.PhoneVerify);
t1 = (TextView) findViewById(R.id.textView2Phone);
i1 = (ImageView) findViewById(R.id.imageView2Phone);
e2 = (EditText) findViewById(R.id.OTPeditText);
b2 = (Button) findViewById(R.id.OTPVERIFY);
t2 = (TextView) findViewById(R.id.textViewVerified);
mobno=e1.getText().toString();
//DBA2
phoneNumberRef = rootRef.child("Employees").child(mobno);
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
mAuth = FirebaseAuth.getInstance();
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
@Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
// Log.d(TAG, "onVerificationCompleted:" + credential);
mVerificationInProgress = false;
Toast.makeText(PhoneLogin.this,"Verification Complete",Toast.LENGTH_SHORT).show();
signInWithPhoneAuthCredential(credential);
}
@Override
public void onVerificationFailed(FirebaseException e) {
// Log.w(TAG, "onVerificationFailed", e);
Toast.makeText(PhoneLogin.this,"Verification Failed",Toast.LENGTH_SHORT).show();
if (e instanceof FirebaseAuthInvalidCredentialsException) {
// Invalid request
Toast.makeText(PhoneLogin.this,"InValid Phone Number",Toast.LENGTH_SHORT).show();
// ...
} else if (e instanceof FirebaseTooManyRequestsException) {
}
}
@Override
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken token) {
// Log.d(TAG, "onCodeSent:" + verificationId);
Toast.makeText(PhoneLogin.this,"Verification code has been sent",Toast.LENGTH_SHORT).show();
// Save verification ID and resending token so we can use them later
mVerificationId = verificationId;
mResendToken = token;
e1.setVisibility(View.GONE);
b1.setVisibility(View.GONE);
t1.setVisibility(View.GONE);
i1.setVisibility(View.GONE);
t2.setVisibility(View.VISIBLE);
e2.setVisibility(View.VISIBLE);
b2.setVisibility(View.VISIBLE);
// ...
}
};
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PhoneAuthProvider.getInstance().verifyPhoneNumber(
e1.getText().toString(),
60,
java.util.concurrent.TimeUnit.SECONDS,
PhoneLogin.this,
mCallbacks);
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, e2.getText().toString());
// [END verify_with_code]
signInWithPhoneAuthCredential(credential);
}
});
} else {
Toast.makeText(getApplicationContext(),"Incorrect CUG",Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
phoneNumberRef.addListenerForSingleValueEvent(eventListener);
//DBA2 End
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()) {
startActivity(new Intent(PhoneLogin.this,NavigationDrawer.class));
Toast.makeText(PhoneLogin.this,"Verification Done",Toast.LENGTH\_SHORT).show();
// Log.d(TAG, "signInWithCredential:success");
//startActivity(new Intent(PhoneLogin.this,NavigationDrawer.class));
Toast.makeText(PhoneLogin.this,"Verification Done",Toast.LENGTH\_SHORT).show();
// ...
} else {
// Log.w(TAG, "signInWithCredential:failure", task.getException());
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
// The verification code entered was invalid
Toast.makeText(PhoneLogin.this,"Invalid Verification",Toast.LENGTH\_SHORT).show();
}
}
}
});
}
}
```<issue_comment>username_1: No, by the time you are trying to authenticate the user, you need to check if the user exists. So you need to check first and then authenticate. Your code looks perfectly fine.
Regarding the rules, it's true, it shouldn't be left public. So allow only the authenticated users to make changes in your database.
Upvotes: 0 <issue_comment>username_2: I hope this helps! I had such a scenario but had a workaroud to it.
First when adding data to "Employees", you can get the userId add an extra node with the userID. Lets try this
```
DatabaseReference rootRef=FirebaseDatabase.getInstance().getReference("Employees");
FirebaseAuth firebaseAuth;
FirebaseUser user=firebaseAuth.getInstance().getCurrentUser();
rootRef.child(user.getUid()).setValue(youModelClassObject);//rootRef is your database reference
```
This means on every user added to "Employees" there will be a node with their userID. Now when trying to access the database and check whether the userId which has been authenticated can be found under the employees. I would have done the following..
```
rootRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Object obj=ds.getKey(); //
Firebase user = firebaseAuth.getInstance().getCurrentUser();
String myId=user.getUid();
//Specify your model class here
ModelClass modelObject=new ModelClass();
if(Objects.equals(myId, obj.toString()))
{
//assuming you've set getters and setters in your model class
modelObject.setPhone(ds.getValue(ModelClass.class).getPhone());
String myDatabasePhone=modelObject.getPhone();
if (myDatabasePhone!=null)
{
//Now call the second OTP verification method and pass 'myDatabasePhone'
}
}else {
//User not found
//direct them to a signup Activy
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});`enter code here`
```
Upvotes: 1 <issue_comment>username_3: It's easy,
edit your
```
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, e2.getText().toString());
// [END verify_with_code]
signInWithPhoneAuthCredential(credential);
}
});
```
with:
```
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Write your database reference and check in the database for entered mobno.
rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(mobno).exists()){
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, e2.getText().toString());
// [END verify_with_code]
signInWithPhoneAuthCredential(credential);
}
else{
Toast.makeText(PhoneLogin.this,"No such CUG No. found",Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
```
Upvotes: 2 [selected_answer]
|
2018/03/16
| 877 | 4,233 |
<issue_start>username_0: Can someone please help me how to get only specific file extension(for example: .sql) changed from svn command line between two dates
Following command gets all files
```
svn diff -r{2017-10-12}:{2017-10-28} --summarize https://svn.blah.com/../ > output.txt
```<issue_comment>username_1: No, by the time you are trying to authenticate the user, you need to check if the user exists. So you need to check first and then authenticate. Your code looks perfectly fine.
Regarding the rules, it's true, it shouldn't be left public. So allow only the authenticated users to make changes in your database.
Upvotes: 0 <issue_comment>username_2: I hope this helps! I had such a scenario but had a workaroud to it.
First when adding data to "Employees", you can get the userId add an extra node with the userID. Lets try this
```
DatabaseReference rootRef=FirebaseDatabase.getInstance().getReference("Employees");
FirebaseAuth firebaseAuth;
FirebaseUser user=firebaseAuth.getInstance().getCurrentUser();
rootRef.child(user.getUid()).setValue(youModelClassObject);//rootRef is your database reference
```
This means on every user added to "Employees" there will be a node with their userID. Now when trying to access the database and check whether the userId which has been authenticated can be found under the employees. I would have done the following..
```
rootRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Object obj=ds.getKey(); //
Firebase user = firebaseAuth.getInstance().getCurrentUser();
String myId=user.getUid();
//Specify your model class here
ModelClass modelObject=new ModelClass();
if(Objects.equals(myId, obj.toString()))
{
//assuming you've set getters and setters in your model class
modelObject.setPhone(ds.getValue(ModelClass.class).getPhone());
String myDatabasePhone=modelObject.getPhone();
if (myDatabasePhone!=null)
{
//Now call the second OTP verification method and pass 'myDatabasePhone'
}
}else {
//User not found
//direct them to a signup Activy
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});`enter code here`
```
Upvotes: 1 <issue_comment>username_3: It's easy,
edit your
```
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, e2.getText().toString());
// [END verify_with_code]
signInWithPhoneAuthCredential(credential);
}
});
```
with:
```
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Write your database reference and check in the database for entered mobno.
rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(mobno).exists()){
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, e2.getText().toString());
// [END verify_with_code]
signInWithPhoneAuthCredential(credential);
}
else{
Toast.makeText(PhoneLogin.this,"No such CUG No. found",Toast.LENGTH_SHORT).show();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
```
Upvotes: 2 [selected_answer]
|
2018/03/16
| 914 | 3,319 |
<issue_start>username_0: I am unable to import pandas profiling in jupyter notebook. Could someone please tell me whats wrong.
[](https://i.stack.imgur.com/o1L7F.png)<issue_comment>username_1: `conda install -c conda-forge pandas-profiling` Try this command to install
If it doesn't work then try `pip install pandas-profiling`
Upvotes: 2 <issue_comment>username_2: Thanks a lot to all who tried to help me out. This worked.
```
import sys
!{sys.executable} -m pip install pandas-profiling
```
Upvotes: 5 [selected_answer]<issue_comment>username_3: If you run jupyter notebook so:
```
python -m jupyter notebook
```
You can install the packages so:
```
python -m pip install pandas-profiling
```
I had a lot of trouble because the 'python' of the jupyter notebook when I ran only `jupyter notebook` was another installation of python than the one on my bash.
If you run the module 'jupyter notebook' and the module 'pip' with the commands 'python -m' before, you ensure that you are using the same installation.
Upvotes: 1 <issue_comment>username_4: Sure, you can install via pip but I like to use conda for as many installs as possible to help keep the environment easier to work with.
The conda page shows multiple versions for pandas-profiling: <https://anaconda.org/conda-forge/pandas-profiling>
You need to specify the latest one when installing:
```
conda install -c conda-forge pandas-profiling=2.6.0
```
Replace 2.6.0 with the latest version.
Upvotes: 3 <issue_comment>username_5: For Mac
```
pip install pandas-profiling
```
And For Ubuntu
```
!pip install pandas-profiling
```
Upvotes: 2 <issue_comment>username_6: There are multiple option to do so.
1. Go to CMD & then type python -m pip install pandas-profiling
2. Go to CMD & conda install -c conda-forge pandas-profiling=2.6.0
3. import sys class in Jupyter note book & enter below line & enter
!{sys.executable} -m pip install pandas-profiling
Above is really cool to use.
4. Little manual but works most of the time.
Download pandas-profile lib from <https://pypi.org/project/pandas-profiling/#modal-close>
extract it and paste C:\anaconda\Lib\site-packages
Restart your Anaconda & happy to use.
I hope this will help.
Upvotes: 1 <issue_comment>username_7: Run "pip install pandas-profiling" in Anaconda command prompt then import panadas\_profiling, it will work
Upvotes: 0 <issue_comment>username_8: Sometimes it's an issue with the version.
Try this
```
!pip install -U pandas-profiling
```
It's working for me.
Upvotes: 1 <issue_comment>username_9: If you are using Anaconda distribution then use this:
```
conda install -c conda-forge pandas-profiling
conda install -c conda-forge/label/cf201901 pandas-profiling
conda install -c conda-forge/label/cf202003 pandas-profiling
```
I was getting the same problem and it worked for me.
Upvotes: 2 <issue_comment>username_10: you can run your anaconda prompt as administrator and do:
conda intall -c anaconda pandas-profiling
While running it may ask for updating the present libraries, do "y" for it.
After completion go to jupyter notebook and do "import pandas\_profiling"
Hope it works!!
Upvotes: 0 <issue_comment>username_11: Try this:
```
!pip install pandas-profiling[notebook]
```
Upvotes: 0
|
2018/03/16
| 2,363 | 6,791 |
<issue_start>username_0: I'm debugging some recursive code via Codeception and it's only showing the last 10 calls, so I don't know what the path through the code is. Xdebug is set to show as much information as possible so, I don't think it's that.
I haven't yet found any configuration option to increase the number of stack trace levels show in Codeception's output.
How can I increase the number of calls in Codeception's output?
Truncated error message:
```
There was 1 error:
---------
1) Hl7MessageHeaderSegmentWriterTest: Should build a message header segment
Test tests\unit\HMRX\CoreBundle\Utils\Hl7Writer\Segment\Hl7MessageHeaderSegmentWriterTest.php:testShouldBuildAMessageHeaderSegment
[PHPUnit_Framework_Exception] Object of class DateTimeImmutable could not be converted to string
#1 Codeception\Subscriber\ErrorHandler->errorHandler
#2 C:\server\Apache24\htdocs\dev.hmr-app\hmrex\HMRX_App\src\HMRX\CoreBundle\Utils\Hl7Writer\Hl7ElementFormatter.php:283
#3 C:\server\Apache24\htdocs\dev.hmr-app\hmrex\HMRX_App\src\HMRX\CoreBundle\Utils\Hl7Writer\Hl7ElementFormatter.php:251
#4 C:\server\Apache24\htdocs\dev.hmr-app\hmrex\HMRX_App\src\HMRX\CoreBundle\Utils\Hl7Writer\Hl7SimpleElementWriter.php:49
#5 C:\server\Apache24\htdocs\dev.hmr-app\hmrex\HMRX_App\src\HMRX\CoreBundle\Utils\Hl7Writer\Hl7ElementFormatter.php:54
#6 C:\server\Apache24\htdocs\dev.hmr-app\hmrex\HMRX_App\src\HMRX\CoreBundle\Utils\Hl7Writer\Hl7ElementFormatter.php:29
#7 C:\server\Apache24\htdocs\dev.hmr-app\hmrex\HMRX_App\src\HMRX\CoreBundle\Utils\Hl7Writer\Hl7ElementFormatter.php:54
#8 C:\server\Apache24\htdocs\dev.hmr-app\hmrex\HMRX_App\src\HMRX\CoreBundle\Utils\Hl7Writer\Hl7ElementFormatter.php:29
#9 C:\server\Apache24\htdocs\dev.hmr-app\hmrex\HMRX_App\src\HMRX\CoreBundle\Utils\Hl7Writer\Hl7ElementFormatter.php:54
#10 C:\server\Apache24\htdocs\dev.hmr-app\hmrex\HMRX_App\src\HMRX\CoreBundle\Utils\Hl7Writer\Segment\Hl7HeaderSegmentWriter.php:18
FAILURES!
Tests: 1, Assertions: 0, Errors: 1.
```
Normal error message (note the last line is the entry point from codecept.phar):
```
There was 1 error:
---------
1) Hl7MessageHeaderSegmentWriterTest: Should build a message header segment
Test tests\unit\HMRX\CoreBundle\Utils\Hl7Writer\Segment\Hl7MessageHeaderSegmentWriterTest.php:testShouldBuildAMessageHeaderSegment
[Exception] foo
#1 C:\server\Apache24\htdocs\dev.hmr-app\hmrex\HMRX_App\src\HMRX\CoreBundle\Utils\Hl7Writer\Data\Hl7DateTimeWrapperDataWriter.php:45
#2 C:\server\Apache24\htdocs\dev.hmr-app\hmrex\HMRX_App\src\HMRX\CoreBundle\Utils\Hl7Writer\Data\Hl7TimeStampDataWriter.php:54
#3 C:\server\Apache24\htdocs\dev.hmr-app\hmrex\HMRX_App\src\HMRX\CoreBundle\Utils\Hl7Writer\Hl7DataForwarder.php:30
#4 C:\server\Apache24\htdocs\dev.hmr-app\hmrex\HMRX_App\src\HMRX\CoreBundle\Utils\Hl7Writer\Hl7DataForwarder.php:24
#5 C:\server\Apache24\htdocs\dev.hmr-app\hmrex\HMRX_App\src\HMRX\CoreBundle\Utils\Hl7Writer\Hl7DataForwarder.php:20
#6 C:\server\Apache24\htdocs\dev.hmr-app\hmrex\HMRX_App\src\HMRX\CoreBundle\Utils\Hl7Writer\Hl7DataForwarder.php:13
#7 C:\server\Apache24\htdocs\dev.hmr-app\tests\unit\HMRX\CoreBundle\Utils\Hl7Writer\Segment\Hl7MessageHeaderSegmentWriterTest.php:53
#8 HMRX\CoreBundle\Utils\Hl7Writer\Hl7MessageHeaderSegmentWriterTest->testShouldBuildAMessageHeaderSegment
#9 C:\usr\bin\codecept.phar:7
FAILURES!
Tests: 1, Assertions: 0, Errors: 1.
```
Xdebug config from phpinfo():
```
xdebug
xdebug support => enabled
Version => 2.5.5
Supported protocols => Revision
DBGp - Common DeBuGger Protocol => $Revision: 1.145 $
Directive => Local Value => Master Value
xdebug.auto_trace => Off => Off
xdebug.cli_color => 0 => 0
xdebug.collect_assignments => Off => Off
xdebug.collect_includes => On => On
xdebug.collect_params => 0 => 0
xdebug.collect_return => Off => Off
xdebug.collect_vars => Off => Off
xdebug.coverage_enable => On => On
xdebug.default_enable => On => On
xdebug.dump.COOKIE => no value => no value
xdebug.dump.ENV => no value => no value
xdebug.dump.FILES => no value => no value
xdebug.dump.GET => no value => no value
xdebug.dump.POST => no value => no value
xdebug.dump.REQUEST => no value => no value
xdebug.dump.SERVER => no value => no value
xdebug.dump.SESSION => no value => no value
xdebug.dump_globals => On => On
xdebug.dump_once => On => On
xdebug.dump_undefined => Off => Off
xdebug.extended_info => On => On
xdebug.file_link_format => no value => no value
xdebug.force_display_errors => Off => Off
xdebug.force_error_reporting => 0 => 0
xdebug.halt_level => 0 => 0
xdebug.idekey => no value => no value
xdebug.max_nesting_level => 256 => 256
xdebug.max_stack_frames => -1 => -1
xdebug.overload_var_dump => 2 => 2
xdebug.profiler_aggregate => Off => Off
xdebug.profiler_append => Off => Off
xdebug.profiler_enable => Off => Off
xdebug.profiler_enable_trigger => Off => Off
xdebug.profiler_enable_trigger_value => no value => no value
xdebug.profiler_output_dir => \ => \
xdebug.profiler_output_name => cachegrind.out.%p => cachegrind.out.%p
xdebug.remote_addr_header => no value => no value
xdebug.remote_autostart => Off => Off
xdebug.remote_connect_back => Off => Off
xdebug.remote_cookie_expire_time => 3600 => 3600
xdebug.remote_enable => On => On
xdebug.remote_handler => dbgp => dbgp
xdebug.remote_host => localhost => localhost
xdebug.remote_log => no value => no value
xdebug.remote_mode => req => req
xdebug.remote_port => 9000 => 9000
xdebug.scream => Off => Off
xdebug.show_error_trace => Off => Off
xdebug.show_exception_trace => Off => Off
xdebug.show_local_vars => Off => Off
xdebug.show_mem_delta => Off => Off
xdebug.trace_enable_trigger => Off => Off
xdebug.trace_enable_trigger_value => no value => no value
xdebug.trace_format => 0 => 0
xdebug.trace_options => 0 => 0
xdebug.trace_output_dir => \ => \
xdebug.trace_output_name => trace.%c => trace.%c
xdebug.var_display_max_children => -1 => -1
xdebug.var_display_max_data => -1 => -1
xdebug.var_display_max_depth => -1 => -1
```<issue_comment>username_1: Run codeception with `-vvv` flag to get a full stacktrace.
Upvotes: 3 [selected_answer]<issue_comment>username_2: The number `$limit = 10` is hard-coded in `\Codeception\Subscriber\Console::printExceptionTrace`
you could temporarily edit that number to be slightly higher.
The `$this->rawStackTrace` is the codeception flag which is set from the `-vvv` Symfony Console parameter, and which bypasses the limited rendering loop and just dumps the raw stack trace.
Both of them also skip the filtered classes defined in `\PHPUnit\Util\Filter::$filteredClassesPattern` so you could add more classes to that array to remove the application stuff (if that's what you mean by the phar calls, I'm not using a phar, I'm using it via composer which is simpler to edit).
Upvotes: 0
|
2018/03/16
| 1,670 | 7,167 |
<issue_start>username_0: so i have this **button** to take a picture contains Text :
```
takePic.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,100);
}
});
```
then i get the image from the onActivityResult :
```
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 100) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
}
}
```
**the problem now is when i pass this bitmap to textRecognizer detector i get no result**:
```
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
textRecognizer = new TextRecognizer.Builder(this).build();
SparseArray item = textRecognizer.detect(frame);
```
**if the image was stored in drawable folder** i can easily do this:
```
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.myImage);
```
and i'm good to go with TextRecognizer ..
but i can't figure out how to deal with an image taken by the camera.
**EDIT :**
full example:
```
public class MainActivity extends AppCompatActivity {
private TextRecognizer textRecognizer;
private ImageView imageView;
private TextView Result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
Result = findViewById(R.id.tvResult);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.image);
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
textRecognizer = new TextRecognizer.Builder(this).build();
SparseArray item = textRecognizer.detect(frame);
StringBuilder stringBuilder = new StringBuilder();
for (int i=0; i
```
activity\_main.xml:
```
```<issue_comment>username_1: It's better to give a file to the camera intent, so It saves the file for you.
According to [This Answer](https://stackoverflow.com/a/32329569/450356):
```
private static final int CAMERA_PHOTO = 111;
private Uri imageToUploadUri;
private void captureCameraImage() {
Intent chooserIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(Environment.getExternalStorageDirectory(), "POST_IMAGE.jpg");
chooserIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
imageToUploadUri = Uri.fromFile(f);
startActivityForResult(chooserIntent, CAMERA_PHOTO);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
if(imageToUploadUri != null){
Uri selectedImage = imageToUploadUri;
getContentResolver().notifyChange(selectedImage, null);
Bitmap reducedSizeBitmap = getBitmap(imageToUploadUri.getPath());
if(reducedSizeBitmap != null){
ImgPhoto.setImageBitmap(reducedSizeBitmap);
Button uploadImageButton = (Button) findViewById(R.id.uploadUserImageButton);
uploadImageButton.setVisibility(View.VISIBLE);
}else{
Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(this,"Error while capturing Image",Toast.LENGTH_LONG).show();
}
}
}
private Bitmap getBitmap(String path) {
Uri uri = Uri.fromFile(new File(path));
InputStream in = null;
try {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
in = getContentResolver().openInputStream(uri);
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, o);
in.close();
int scale = 1;
while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
IMAGE_MAX_SIZE) {
scale++;
}
Log.d("", "scale = " + scale + ", orig-width: " + o.outWidth + ", orig-height: " + o.outHeight);
Bitmap b = null;
in = getContentResolver().openInputStream(uri);
if (scale > 1) {
scale--;
// scale to max possible inSampleSize that still yields an image
// larger than target
o = new BitmapFactory.Options();
o.inSampleSize = scale;
b = BitmapFactory.decodeStream(in, null, o);
// resize to desired dimensions
int height = b.getHeight();
int width = b.getWidth();
Log.d("", "1th scale operation dimenions - width: " + width + ", height: " + height);
double y = Math.sqrt(IMAGE_MAX_SIZE
/ (((double) width) / height));
double x = (y / height) * width;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x,
(int) y, true);
b.recycle();
b = scaledBitmap;
System.gc();
} else {
b = BitmapFactory.decodeStream(in);
}
in.close();
Log.d("", "bitmap size - width: " + b.getWidth() + ", height: " +
b.getHeight());
return b;
} catch (IOException e) {
Log.e("", e.getMessage(), e);
return null;
}
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: First you can convert bitmap to **byte array** like that
```
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
byte[] byteArray = outputStream.toByteArray();
```
After that you can use BitmapFactory' s decodeByteArray() function with option
```
BitmapFactory.decodeByteArray(byteArray , 0 ,byteArray.length,*option)
```
\*option is your bitmap factory option
Upvotes: 0 <issue_comment>username_3: That is one of the simplest ways to get `Bitmap` from taken image by using `InputStream` and `BitmapFactory`.
```
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
InputStream stream;
if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
try {
stream = getContentResolver().openInputStream(data.getData());
Bitmap bitmap = BitmapFactory.decodeStream(stream);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
Upvotes: 0
|
2018/03/16
| 728 | 2,502 |
<issue_start>username_0: There are Code A、Code B and Code C.
1. Is Code A equivalent Code B ?
2. Is Code A equivalent Code C ?
**Code A**
```
if (IsRegistered(myContext) ) {
}
```
**Code B**
```
if (IsRegistered(myContext) == true) {
}
```
**Code C**
```
if (IsRegistered(myContext) === true) {
}
```
**Function**
```
fun IsRegistered(myContext: Context): Boolean {
val prefs = PreferenceManager.getDefaultSharedPreferences(myContext)
var registeredStatus: Boolean? = prefs.getBoolean("IsRegistered", false)
val isPro = myContext.resources.getBoolean(R.bool.IsProVersion)
if (isPro) {
registeredStatus = true
}
return registeredStatus!!
}
```<issue_comment>username_1: Code A is equivalent Code B since
>
> a === b evaluates to true if and only if a and b point to the same
> object.
>
>
>
Upvotes: -1 <issue_comment>username_2: ```
if (IsRegistered(myContext) ) {
}
```
Code in if will be executed if method IsRegistered returns true.
```
if (IsRegistered(myContext) == true) {
}
```
This will be executed if methods returns true. Actually it unnecessary comparison, but can be useful if IsRegistered may return null (because null isn't true), but in this case, its just additional 8 chars.
```
if (IsRegistered(myContext) === true) {
}
```
This is also equivalent to A and B, because Boolean is an primitive type, and === operator is the same as == (ref: <https://kotlinlang.org/docs/reference/equality.html#referential-equality>)
Upvotes: -1 <issue_comment>username_3: Code A and B are totally identical. The first one isn preferable since the equality check in B is just noisy. Code C, on the other hand, checks for [*referential equality*](https://kotlinlang.org/docs/reference/equality.html#referential-equality):
>
> Referential equality is checked by the `===` operation (and its negated counterpart `!==`). `a === b` evaluates to `true` if and only if a and b point to the same object. For **values which are represented as primitive types** at runtime (for example, Int), the `===` equality check is **equivalent** to the `==` check.
>
>
>
If you use your Code C though, the IDE (at least IDEA) does not like it and tells you that it's "deprecated" to use `===` on the `Boolean` type.
It has been discussed [here](https://stackoverflow.com/questions/45222144/identity-equality-for-arguments-of-types-int-and-int-is-deprecated?noredirect=1&lq=1).
Code B should be recommended here.
Upvotes: 2 [selected_answer]
|
2018/03/16
| 912 | 3,224 |
<issue_start>username_0: I am posting my form data to A controller but when I post data I am not getting in the controller when I call `print_r($_POST);` its returning null array I don't know what I have missed
Please let me know what inputs you want from my side
```
var data2 = [];
data2['user_firstname'] = user_firstname;
data2['user_lastname'] = user_lastname;
data2['user_phone'] = user_phone;
data2['user_email'] = user_email;
data2['user_username'] = user_username;
data2['user_password'] = <PASSWORD>;
console.log(data2);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "http://localhost/shago/register/submit",
data: { 'data2': data2 },
// dataType: "text",
success: function(resultData) { console.log(resultData); }
});
```
controller code
```
public function submit()
{
print_r($_POST);
}
```<issue_comment>username_1: You can use the following
```
public function submit(Request $request)
{
dump($request);
}
```
Upvotes: 1 <issue_comment>username_2: Try adding Request as parameter on your submit function
```
public function submit(Request $request)
{
print_r($request);
}
```
Also, do you really need to pass your information as an array?
You could just create a new object and pass that as well.
```
var data2={
'user_firstname': user_firstname,
'user_lastname': user_lastname,
'user_phone': user_phone,
'user_email': user_email,
'user_username': user_username,
'user_password': <PASSWORD>
};
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "http://localhost/shago/register/submit",
data: data2,
success: function(resultData) { console.log(resultData); }
});
```
Upvotes: 1 <issue_comment>username_3: You need to inject Request Class injection into submit method. This can help you:
```
public function submit(\Illuminate\Http\Request $request)
{
dd($request->all()); // will print all data
}
```
of if you don't want to inject Request then this code may helps you
```
public function submit()
{
dd(request()->all()); // will print all data
}
```
Good Luck !!!
Upvotes: 1 <issue_comment>username_4: Thanks all i found error in when i am sending array data now i have modified code and its working fine
see code
```
$.ajax({
url: "register/submit",
type: "post",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {'user_firstname':user_firstname,'user_lastname':user_lastname,'user_phone':user_phone,'user_email':user_email,'user_username':user_username,'user_password':<PASSWORD>},
success: function(result){
console.log(result);
}
});
}
```
Upvotes: 0 <issue_comment>username_5: Maybe the request was intercepted by Laravel CSRF Protection policy.In order to prove it, you should add request URL in VerifyCsrfToken middleware file, like following:
`protected $except = [
'yoururl'
];`
If you can get the data you expect in your controller, then I am right.
Upvotes: 1
|
2018/03/16
| 572 | 1,799 |
<issue_start>username_0: I am updating a table which has 4 columns together as primary key.
```
|Col1|Col2|Col3|Col4|val|
| 1| 2| 3| 4|234|
```
Col 1-4 make primary key
I need to update Col1 in some rows. But some rows already have the value which i want to update. Thus when i run the query it gives :
```
ERROR: duplicate key value violates unique constraint "datavalue_pkey"
DETAIL: Key (Col1, Col2, Col3, Col4)=(609, 76911, 164, 1) already exists.
```
How can i ignore the cases which are already present so that update query runs fully??
Update Query :
```
update datavalue dv set Col1 = 6009
where concat( dv.Col1 ,'-',dv.Col2,'-',Col3,'-',dv.Col4)
in (
Select concatenated id ... from same table
)
```
Thanks
POSTGRES - 9.5.12<issue_comment>username_1: Depending on your application, I would suggest to write a function, but I guess what you're looking for is something like this (quick & dirty):
Test table and dataset:
```
CREATE TEMP TABLE t (id INT UNIQUE, des TEXT);
INSERT INTO t VALUES (1,'foo'),(2,'bar');
```
Update ignoring conflicts.
```
DO $$
DECLARE r RECORD;
BEGIN
FOR r IN SELECT * FROM t LOOP
BEGIN
UPDATE t SET id = 2 WHERE des = 'foo' AND id = r.id;
UPDATE t SET des = 'bar2' WHERE id = 2 AND id = r.id;
EXCEPTION WHEN unique_violation THEN
RAISE NOTICE 'Oups .. there was a conflict on % - %',r.id,r.des;
END;
END LOOP;
END$$;
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: If I understand your example correctly, you should be able to use a subquery to simply exclude rows with the Col1 value you are trying to set.
```
UPDATE datavalue SET Col1 = '6009'
WHERE [your conditions]
AND Col1 NOT IN (SELECT Col1 FROM datavalue WHERE Col1 = '6009')
```
Upvotes: 0
|
2018/03/16
| 826 | 3,373 |
<issue_start>username_0: When creating a react app, service worker is invoked by default. Why service worker is used? What is the reason for default invoking?<issue_comment>username_1: You may not need a service worker for your application. If you are creating a project with create-react-app it is invoked by default
Service workers are well explained in this **[article](https://developers.google.com/web/fundamentals/primers/service-workers/)**. To Summarise from it
>
> A `service worker` is a script that your browser runs in the
> background, separate from a web page, opening the door to features
> that don't need a web page or user interaction. Today, they already
> include features like `push notifications` and `background sync` and have
> `ability to intercept and handle network requests`, including
> `programmatically managing a cache of responses`.
>
>
> In the future, service workers might support other things like
> `periodic sync` or `geofencing`.
>
>
>
According to this **[PR to create-react-app](https://github.com/facebook/create-react-app/pull/1728)**
>
> `Service workers` are introduced with create-react-app via
> `SWPrecacheWebpackPlugin`.
>
>
> Using a server worker with a cache-first strategy offers performance
> advantages, since the network is no longer a bottleneck for fulfilling
> navigation requests. It does mean, however, that developers (and
> users) will only see deployed updates on the "N+1"
> visit to a page, since previously cached resources are updated in the
> background.
>
>
>
The call to `register service worker` is enabled by default in new apps but you can always remove it and then you’re back to regular behaviour.
Upvotes: 8 [selected_answer]<issue_comment>username_2: **In simple and plain words, it’s a script that browser runs in the background and has whatsoever no relation with web pages or the DOM, and provide out of the box features. It also helps you cache your assets and other files so that when the user is offline or on slow network.**
*Some of these features are proxying network requests, push notifications and background sync. Service workers ensure that the user has a rich offline experience.*
You can think of the service worker as someone who sits between the client and server and all the requests that are made to the server pass through the service worker. Basically, a middle man. Since all the request pass through the service worker, it is capable to intercept these requests on the fly.
[](https://i.stack.imgur.com/ldRJk.png)
Upvotes: 5 <issue_comment>username_3: I'd like to add 2 important considerations about Service Workers to take into account:
1. Service Workers require HTTPS. But to enable local testing, this restriction doesn't apply to `localhost`. This is for security reasons as a Service Worker acts like a *man in the middle* between the web application and the server.
2. With **Create React App** Service Worker is only enabled in the production environment, for example when running `npm run build`.
Service Worker is here to help developing a [Progressive Web App](https://web.dev/what-are-pwas/). A good resource about it in the context of Create React App can be found in their website [here](https://create-react-app.dev/docs/making-a-progressive-web-app/).
Upvotes: 3
|
2018/03/16
| 989 | 3,750 |
<issue_start>username_0: I've come across a peculiar focusing issue. I have created the following "search" program:
1. It runs in the background.
2. When you double-tap the `Ctrl` key it becomes visible.
3. You can type in the textbox because the form has focus.
4. If the form loses focus (I click on my desktop, for example), it disappears after 3 seconds.
5. I double-tap the `Ctrl` key again, and again it becomes visible.
6. But this time, no matter what I try, the form is not focused and I cannot type in the textbox without first manually clicking on the form.
What's particularly interesting is that when I run this program in debug mode from Visual Studios, the program regains focus upon double-tapping `Ctrl` key and becoming visible, and I can immediately start typing in the text box. However, when I build this program and run it alone, the program appears but does not regain focus upon double-tapping `Ctrl` key, and therefore I cannot type in the text box until I manually click the form.
After Me.Show() I have tried:
* Me.Focus()
* Me.Validate()
* Me.Select()
* Textbox1.Select()
* Textbox1.Focus()
The form is topmost and normally running in administrator, but the same problem arises regardless.
The issue can be recreated in a more simple manner. Create a form with
* Button ("Button1")
* TextBox
* Two timers ("hideForm", "showForm") both with intervals of 1000
Code:
```
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
hideForm.Start()
sender.Enabled = False
End Sub
Private Sub hideForm_Tick(sender As Object, e As EventArgs) Handles hideForm.Tick
Me.Hide()
hideForm.Stop()
showForm.Start()
End Sub
Private Sub showForm_Tick(sender As Object, e As EventArgs) Handles showForm.Tick
showForm.Stop()
Me.Show()
Me.Activate()
End Sub
End Class
```
Click the button, and immediately click on a different window (so the form loses focus). Wait until the form is hidden and shown again. The textbox should have focus. Try typing.
**If the program is run in debugging mode in Visual Studios, it works as expected. If you build the program and run it outside of VS, the form will reappear without focus, and you cannot type in the textbox without manually selecting the form.**
Sorry for the long-winded explanation. It's a difficult issue to properly describe.<issue_comment>username_1: Try an event handler for `Form_Activate`, and within that handler pass the focus to your textbox.
Instead of `Focus`, you can also try `TextBox1.Select`. [This SO link](https://stackoverflow.com/questions/16294248/setting-focus-to-a-textbox-control) provides some additional information and something about the difference between `Focus` and `Select`.
Upvotes: 0 <issue_comment>username_2: Try the form event handler `Activate`. Inside that method, you can use `setFocus` to gain focus for that particular Text Box. I know this answer is too late. But hope this helps someone.
```
Private Sub Form_Activate()
TextBox1.SetFocus
End Sub
```
Upvotes: 1 <issue_comment>username_3: What I tried (and worked for me), was to set the `Focus()` of the Textbox in the event handler `Shown()` [VB]:
```
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
Me.Textbox1.Focus()
End Sub
```
Note: the `Select()` method just didn't do the job. I hope this helps anyone else that comes with this same issue.
Upvotes: 0 <issue_comment>username_4: Select the Textbox you want to assign a focus to in the Design View Window.
Under the Properties window, set the `TabIndex` to 0 (zero).
I didn't even have to use the `TextBox1.Focus()` command. It still bothers me that the `TabIndex` overrides the Focus command.
Upvotes: 0
|
2018/03/16
| 662 | 1,698 |
<issue_start>username_0: ```js
const uniqBy = (arr, fn) => {
let res = []
const hash = new Set()
for (let i = 0; i < arr.length; i++) {
const foo = typeof fn === 'function' ? fn(arr[i]) : arr[i][fn]
if (!hash.has(foo)) {
res.push(arr[i])
hash.add(foo)
}
}
return res
}
console.log(uniqBy([2.1, 1.2, 2.3], Math.floor)) // [2.1, 1.2]
console.log(uniqBy([{
x: 1
}, {
x: 2
}, {
x: 1
}], 'x')) // [{x: 1 },{ x: 2 }]
```
That's my code to achieve uniqBy, but the code is too much, I want to get a better way with less code<issue_comment>username_1: ```
const uniqBy = (arr, fn, set = new Set) => arr.filter(el => (v => !set.has(v) && set.add(v))(typeof fn === "function" ? fn(el) : el[fn]));
```
Upvotes: 2 <issue_comment>username_2: [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) is a decent alternative to [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) when comparing the uniqueness of `variables` using `keys`.
```js
// UniqBy.
const uniqBy = (arr, fn) => [...new Map(arr.reverse().map((x) => [typeof fn === 'function' ? fn(x) : x[fn], x])).values()]
// Proof.
console.log(uniqBy([2.1, 1.2, 2.3], Math.floor)) // [2.1, 1.2]
console.log(uniqBy([{x: 1}, {x: 2}, {x: 1}], 'x')) // [{x: 1},{x: 2}]
```
Upvotes: 1 <issue_comment>username_3: This is my take at it
```js
const uniqBy = (arr, fn, obj={}) => ((arr.reverse().forEach(item => obj[typeof fn === 'function' ? fn(item) : item[fn]] = item)), Object.values(obj))
console.log(uniqBy([2.1, 2.3, 3.2], Math.floor))
console.log(uniqBy([{x:1}, {x:2}, {x:1}, {x:4}], 'x'))
```
Upvotes: 0
|
2018/03/16
| 2,991 | 7,828 |
<issue_start>username_0: I started to use Rcpp and be able to speed up R-code incredibly. However changing names of vector elements (like 'v.attr("names")=X' or 'v.names()=X') is very slow in my hand. Is there any solutions to improve? Plese see attached example.
sample of rcpp; test\_names.cpp
```
#include
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector test\_names(int N, bool name){
RNGScope scope;
NumericVector data = runif(N, 1, 100);
if(name)data.attr("names")=seq(1,N);
return data;
}
```
The result I got in R
```
> sourceCpp("./test_names.cpp")
> system.time(test_names(10000000, F))
user system elapsed
0.139 0.025 0.164
> system.time(test_names(10000000, T))
user system elapsed
5.181 0.117 5.296
```
Thank you.<issue_comment>username_1: I think creating that many strings is taking too much times and you can't do anything about it. See these comparisons:
```
> N <- 1e6
> system.time(test_names(N, FALSE))
user system elapsed
0.008 0.001 0.009
> system.time(test_names(N, TRUE))
user system elapsed
0.244 0.001 0.246
> system.time(setNames(test_names(N, FALSE), seq_len(N)))
user system elapsed
0.236 0.001 0.238
> system.time(seq_len(N))
user system elapsed
0.000 0.000 0.001
> system.time(as.character(seq_len(N)))
user system elapsed
0.228 0.000 0.229
```
It is really the conversion to strings which is slow.
I don't usually use names; why do you need them?
Upvotes: 1 <issue_comment>username_2: Naming an object from start to finish is going to take time as @F.Prive points out, converting a vector to characters is quite expensive. Generally speaking, naming an object is regarded more of as a convenience than
a necessity and when a "need for speed" user is faced with the option, they will gladly give up this convenience. This is why some developers give the option to return a named object.
Nevertheless, there are other options out there for naming objects, so let's see if any of them speed up the process.
**Option `Base R` :**
Sometimes, very basic functions in `base R`, such as `names`, can be very efficient.
```
// [[Rcpp::export]]
Rcpp::NumericVector test_namesBaseNameCpp(int N){
Rcpp::RNGScope scope;
return Rcpp::runif(N, 1, 100);
}
## in base R define the following:
test_namesBaseNameR <- function(n, named) {
v <- test_namesBaseNameCpp(N = n)
if (named)
names(v) <- 1:n
v
}
```
Here are the results:
```
library(microbenchmark)
microbenchmark(OP = test_names(10^5, T),
baseR = test_namesBaseNameR(10^5, T),
unit = "relative")
Unit: relative
expr min lq mean median uq max neval
OP 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 100
baseR 1.008021 1.001896 1.015566 1.001912 1.016359 1.101542 100
```
Virtually the same.
**Option Passing names as argument :**
Let's see if passing the names as an argument helps.
```
// [[Rcpp::export]]
Rcpp::NumericVector test_namesPassChar(int N, bool name,
Rcpp::CharacterVector RNames) {
Rcpp::RNGScope scope;
Rcpp::NumericVector data = Rcpp::runif(N, 1, 100);
if(name)data.attr("names")=RNames;
return data;
}
microbenchmark(OP = test_names(10^5, T),
passAndConvert = test_namesPassChar(10^5, T, 1:10^5),
passAndConvert2 = test_namesPassChar(10^5, T, as.character(1:10^5)),
unit = "relative")
Unit: relative
expr min lq mean median uq max neval
OP 0.9878606 1.0015865 0.9820272 1.000169 0.9471021 0.8645719 100
passAndConvert 1.0000000 1.0000000 1.0000000 1.000000 1.0000000 1.0000000 100
passAndConvert2 1.0085636 0.9998202 1.0332923 1.000702 1.0517044 1.0507859 100
```
No luck here either.
It seems that if we really want to speed things up, we are going to have to define a vector of names upfront and subset that vector as needed. For example, in your project if you know the maximum size of the named object you are wanting is `maxLength`, we can define `myNames <- as.character(1:maxLength)`. Now in practice when we pass `N`, we also pass `myNames[1:N]`.
**Option pre-made names :**
```
maxLength <- 10^7
myNames <- as.character(1:maxLength) ## this steps takes a while, but you only do it once
microbenchmark(OP = test_names(10^5, T),
passPreMade = test_namesPassChar(10^5, T, myNames[1:10^5]),
unit = "relative")
Unit: relative
expr min lq mean median uq max neval
OP 8.149265 6.321411 6.617447 6.097933 6.042956 31.8545 100
passPreMade 1.000000 1.000000 1.000000 1.000000 1.000000 1.0000 100
```
This is a nice improvement, but it still isn't that desirable because it isn't general.
Lastly, there is an option that I highly discourage, and I'm only mentioning it to show you why `Rcpp` is so nice. We turn to `C` and we exploit the structure of incrementing integers to get our gains. `SET_STRING_ELT` expects an array of `chars` and normally, we would convert each integer *i* to a string via `temp = std::to_string(i)`, then convert `temp` to a char using the `.c_str()` function like so `myChar = temp.c_str()`. This again, is just as slow as the first few methods because we are converting every integer from scratch to an array of `chars`. The good news in this scenario is that we don't need to this as we are simply naming our vector with the sequence `1:n`. So for 90% of our integers, only 1 digit is changing (i.e. the one's digit). Keeping this in mind, we can do something like this (N.B. this can definitely be improved as my C skills aren't strong):
**Option I don't recommend**
```
#include
#include "Rinternals.h"
// [[Rcpp::export]]
SEXP test\_namesSuperHard(int N, bool name) {
Rcpp::RNGScope scope;
Rcpp::NumericVector data = Rcpp::runif(N, 1, 100);
if (name) {
SEXP myNames = PROTECT(Rf\_allocVector(STRSXP, N));
int base = (int) log10(N) + 1;
char \*myChar;
myChar = (char \*) malloc(base \* sizeof(char));
int count = 1, index = base - 1;
for (std::size\_t i = 0; i < base; i++)
myChar[i] = '0';
for (std::size\_t i = 0; i < N; i++, count++) {
if ((count % 10) == 0) {
while (myChar[index] == '9') {
myChar[index] = '0';
index--;
}
count = 0;
myChar[index]++;
index = base - 1;
} else {
myChar[index] = count + '0';
}
SET\_STRING\_ELT(myNames, i, Rf\_mkChar(myChar));
}
Rf\_setAttrib(data, R\_NamesSymbol, myNames);
UNPROTECT(1);
}
return data;
}
```
Test the output:
```
test_namesSuperHard(20, TRUE)
01 02 03 04 05
13.417850 29.633416 35.221770 17.377710 97.139458
06 07 08 09 10
24.187230 60.962993 23.307580 61.151013 12.892655
11 12 13 14 15
48.303439 28.875226 37.264403 78.196955 29.705689
16 17 18 19 20
3.533349 86.505015 62.784809 95.785053 94.273097
```
And now we benchmark:
```
microbenchmark(OP = test_names(10^5, T),
dontRecommend = test_namesSuperHard(10^5, T),
unit = "relative")
Unit: relative
expr min lq mean median uq max neval
OP 3.753499 3.702676 3.885055 3.691977 3.504271 8.883482 100
dontRecommend 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 100
```
And we see an improvement of almost `4x` as fast. Not bad. However, this is a lot of work for something that is, as I said in the opening, a convenience. It also demonstrate the truly amazing work done by the `Rcpp` team (Dirk *et al.*) in making these *conveniences* effortless to implement.
Upvotes: 0
|
2018/03/16
| 981 | 3,043 |
<issue_start>username_0: I'm having a hard time understanding why the output for various metrics on my models differs when I use h2o.
For example, if I use 'h2o.grid' then the logloss measure is *different* when I look at the mean model$cross\_validation\_metrics\_summary. It is the same as model$cross\_validation\_metrics\_summary. What is the reasoning behind this difference? What one should I report on?
```
library(mlbench)
library(h2o)
data(Sonar)
h2o.init() Sonarhex <- as.h2o(Sonar) h2o.grid("gbm", grid_id = "gbm_grid_id0", x = c(1:50), y = 'Class',
training_frame = Sonarhex, hyper_params = list(ntrees = 50, learn_rate = c(.1, .2, .3)), nfolds = 5, seed=1234)
grid <- h2o.getGrid("gbm_grid_id0", sort_by = 'logloss')
first_model = h2o.getModel(grid@model_ids[[1]]) first_model@model$cross_validation_metrics_summary first_model@model$cross_validation_metrics
```<issue_comment>username_1: This inconsistency is an issue that has been documented and explained [here](https://0xdata.atlassian.net/browse/PUBDEV-4975) and will be resolved in a future release. The `model$cross_validation_metrics_summary` metrics are the correct CV metrics. The metrics that appear in the Grid table or by using the utility functions like `h2o.logloss(model, xval = TRUE)` are slightly different because they aggregate the CV predictions and then compute the loss (instead of computing the loss separately across K folds and then taking the average). This can lead to slight numerical differences.
Upvotes: 3 [selected_answer]<issue_comment>username_2: I suggest to use the following function
```
def sort_grid(grid,metric):
#input: grid and metric to order
if metric == 'accuracy':
id = 0
elif metric == 'auc':
id = 1
elif metric=='err':
id = 2
elif metric == 'err_count':
id=3
elif metric=='f0point5':
id=4
elif metric=='f1':
id=5
elif metric =='f2':
id=6
elif metric =='lift_top_group':
id=7
elif metric == 'logloss':
id=8
elif metric == 'max_per_class_error':
id=9
elif metric == 'mcc':
metric=9
elif metric =='mena_per_class_accuracy':
id=10
elif metric == 'mean_per_class_error':
id=11
elif metric == 'mse':
id =12
elif metric == 'pr_auc':
id=13
elif metric == 'precision':
id=14
elif metric == 'r2':
id=15
elif metric =='recall':
id=16
elif metric == 'rmse':
id = 17
elif metric == 'specificity':
id = 18
else:
return 0
model_ids = []
cross_val_values = []
number_of_models = len(grid.model_ids)
number_of_models
for i in range(number_of_models):
modelo_grid = grid[i]
mean = np.array(modelo_grid.cross_validation_metrics_summary()[[1]])
cross_val= mean[0][id]
model_id = grid.model_ids[i]
model_ids.append(model_id)
cross_val_values.append(cross_val)
df = pd.DataFrame(
{'Model_IDs': model_ids, metric: cross_val_values}
)
df = df.sort_values([metric], ascending=False)
best_model = h2o.get_model(df.iloc[0,0])
return df, best_model
#output ordered grid in pandas dataframe and best model
```
Upvotes: 0
|
2018/03/16
| 238 | 889 |
<issue_start>username_0: I have developed a custom skill, which is working well with Alexa test tool, but even after enabling the skill on Alexa app, it is not working with reverb.
PS:
* I'm running skill server locally on my computer with the help of reverse proxy.
* skill is not published yet.
* I've logged in with the same account on both reverb and Alexa app.
* Language is set to US English in both apps and in skill config.<issue_comment>username_1: Better use [echosim.io](https://echosim.io/) than reverb.
Upvotes: -1 <issue_comment>username_2: got it. had to say "ask ***skill-name*** to ***[do some operation]***" instead of "start ***skill-name***". reason unknown.
Upvotes: 1 [selected_answer]<issue_comment>username_3: You can invoke skill in two ways:
- Invoking a Skill with a Specific Request (Intent)
- Invoking a Skill with No Specific Request (No Intent)
Upvotes: 0
|
2018/03/16
| 321 | 1,188 |
<issue_start>username_0: Hi am a beginner in javascript and to programming.
i just made a live conversation using html,css and javascript.
I can't access the enter key in the button tag .
```
function typo(){
var currentText = document.getElementById("demo").innerHTML;
enterkey();
var x = '<p class=chatbox>' + document.getElementById("myText").value + '</p>';
document.getElementById("myText").value = "";
var y = document.getElementById("demo").innerHTML = currentText + x;
}
function enterkey() {
var input = document.getElementById("myText");
input.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("btn-chat").click();
}
});
}
Send
```<issue_comment>username_1: Better use [echosim.io](https://echosim.io/) than reverb.
Upvotes: -1 <issue_comment>username_2: got it. had to say "ask ***skill-name*** to ***[do some operation]***" instead of "start ***skill-name***". reason unknown.
Upvotes: 1 [selected_answer]<issue_comment>username_3: You can invoke skill in two ways:
- Invoking a Skill with a Specific Request (Intent)
- Invoking a Skill with No Specific Request (No Intent)
Upvotes: 0
|
2018/03/16
| 822 | 3,338 |
<issue_start>username_0: I want to get the value of all text-area boxes and store into database on click of submit button.
Multiple text-area's are appearing on click of add button.
I am using nodejs, express and mongodb.
I have one select field and two textarea's. i am able to post the first values of textarea's on submit.
But if i want to post multiple textarea values on submit (multiple textarea's will appear on click of respective add/plus button), I am unable to post it.
Also i am facing an issue while creating the same template of textarea box but with delete button. The textarea is appearing below submit button.
Can anyone help me out?
Here is my html code:
```
##### New updates/Notifications
Choose Module
Update area
*add\_circle*
Notification area
*add\_circle*
Submit
```
Here is my Javascript code:
```
$(document).ready(function() {
var getOptions = ajaxServices("/iotsupport/modules/getModules", "GET");
if (getOptions.status == 201) {
for (var i in getOptions.body) {
var option = getOptions.body[i].moduleName;
var optionDiv = document.createElement('option');
optionDiv = $(optionDiv).text(option);
$('.moduleSelect').append(optionDiv);
}
} else if (getOptions.status == 401) {
swal({
title: "",
text: "Error fetching the query options",
icon: "error",
button: "OK"
})
}
$('select').material_select();
$(".submitButton").on('click', function(e) {
var optionList = $("select[id='getOptionValue']").val();
console.log(optionList);
var updateFieldValue = $("textarea[name='updateTextarea']").val();
var notificationField = $("textarea[name='notificationTextarea']").val();
var sendObject = {
"moduleName": optionList,
"updateObject": updateFieldValue,
"notifyObject": notificationField
}
var responseObject = ajaxServices("/iotsupport/addUpdateNotify/postUpdateNotify", "POST", sendObject);
console.log(responseObject);
if (responseObject.status == 401) {
alert("some error occured")
} else if (responseObject.status == 201) {
alert("update/notification is done.");
location.reload();
}
});
$(".addButtonUpdate").on('click', function(e) {
var n = 8 // adjust it in some way
var inputArea = ['',
'',
'update area',
''
].join('')
$('.row').append(inputArea);
console.log(inputArea);
});
$(".addButtonNotify").on('click', function(e) {
var n = 8 // adjust it in some way
var inputArea = ['',
'',
'Notify area',
''
].join('')
$('.row').append(inputArea);
console.log(inputArea);
});
});
```
Please refer to this image<issue_comment>username_1: Better use [echosim.io](https://echosim.io/) than reverb.
Upvotes: -1 <issue_comment>username_2: got it. had to say "ask ***skill-name*** to ***[do some operation]***" instead of "start ***skill-name***". reason unknown.
Upvotes: 1 [selected_answer]<issue_comment>username_3: You can invoke skill in two ways:
- Invoking a Skill with a Specific Request (Intent)
- Invoking a Skill with No Specific Request (No Intent)
Upvotes: 0
|
2018/03/16
| 208 | 738 |
<issue_start>username_0: I'm sending a `HTML` form and `javascript` array using AJAX post method. But I can't get my data in the `PHP` file.
```
$.post("addOrder.php", {
"form": $("#placeOrderForm").serialize(),
"array": array
}, function(responce) {});
```<issue_comment>username_1: Better use [echosim.io](https://echosim.io/) than reverb.
Upvotes: -1 <issue_comment>username_2: got it. had to say "ask ***skill-name*** to ***[do some operation]***" instead of "start ***skill-name***". reason unknown.
Upvotes: 1 [selected_answer]<issue_comment>username_3: You can invoke skill in two ways:
- Invoking a Skill with a Specific Request (Intent)
- Invoking a Skill with No Specific Request (No Intent)
Upvotes: 0
|
2018/03/16
| 1,343 | 4,165 |
<issue_start>username_0: I'm building a website from `CSS` and `HTML`. I'm up to the point of adding a background image to my website. The trouble is, the image isn't showing up as the website's background.
My CSS code:
```css
.bg {
background: url('https://ak9.picdn.net/shutterstock/videos/12047219/thumb/10.jpg?i10c=img.resize(height:160)');
height: 50%;
/* Center and scale the image nicely */
background-position: center;
background-repeat: repeat-x;
background-size: cover;
}
```
Just ask me if you need any more code from my website.
>
> Edit: This is not a clone, I've tried every other solution that I've come across on here, and nothing works.
>
>
><issue_comment>username_1: **This works fine if you use `fixed height:`**
In the below case I have used `100px;`
```css
.bg {
background: url('https://ak9.picdn.net/shutterstock/videos/12047219/thumb/10.jpg?i10c=img.resize(height:160)');
height: 100px;
/* Center and scale the image nicely */
background-position: center;
background-repeat: repeat-x;
background-size: cover;
}
```
```html
```
But if you want it to be 100% of the screen you can always go with `100vh`
```css
.bg {
background: url('https://ak9.picdn.net/shutterstock/videos/12047219/thumb/10.jpg?i10c=img.resize(height:160)');
height: 100vh;
/* Center and scale the image nicely */
background-position: center;
background-repeat: repeat-x;
background-size: cover;
}
```
```html
```
*If you want to know more about `vh` visit this **[link](https://css-tricks.com/viewport-sized-typography/)***
Hope this was helpful for you.
Upvotes: 2 [selected_answer]<issue_comment>username_2: The background image for a page can be set like this:
```css
body {
background-image: url("paper.gif");
}
```
so maybe you can change your code become :
```css
.bg {
background-image: url('https://ak9.picdn.net/shutterstock/videos/12047219/thumb/10.jpg?i10c=img.resize(height:160)');
height: 100px;
/* Center and scale the image nicely */
background-position: center;
background-repeat: repeat-x;
background-size: cover;
}
```
Upvotes: 0 <issue_comment>username_3: If you want to add background image to whole HTML Page then use body tag.
```
body {
background-image: url("https://ak9.picdn.net/shutterstock/videos/12047219/thumb/10.jpg");
}
```
and if you want to add background to specific class then use this
```
.bg {
background-image: url('https://ak9.picdn.net/shutterstock/videos/12047219/thumb/10.jpg');
}
```
in that adjust your height accordingly. if you want to add to full class then use
height:100% else adjust it with your own condition.
Upvotes: 0 <issue_comment>username_4: The image that the OP refers to is a resized version of the original. This solution uses the original image along with CSS that uses a height of 100vh (as recommended by @weBBer) and auto for the width. The background position remains with a center value. It seems needless to repeat the image so the CSS uses no-repeat. This works with Google Chrome (version 49).
```css
.bg {
background-image: url(https://ak9.picdn.net/shutterstock/videos/12047219/thumb/10.jpg);
width:auto;
height:100vh;
background-position: center;
background-repeat: no-repeat;
background-size:cover;
}
```
The result is a centered image that fills the page due to background-size property being set to [cover](https://developer.mozilla.org/en-US/docs/Web/CSS/background-size) as well as the height property set to 100vh, i.e. 100% of the view port height; see more about this and other measurements [here](https://webdesign.tutsplus.com/articles/7-css-units-you-might-not-know-about--cms-22573).
If you only wanted to fill the portion within the dimensions of the DIV then you could alter the CSS and replace background-size property with object-fit, as follows:
```css
.bg {
background-image: url(https://ak9.picdn.net/shutterstock/videos/12047219/thumb/10.jpg);
height:480px;
margin-left:auto;width:100%;margin-right:auto;
background-position: center;
background-repeat: no-repeat;
object-fit:cover;
}
```
Upvotes: 0
|
2018/03/16
| 423 | 1,197 |
<issue_start>username_0: I am using `File` class for getting extention of image url.
```
File::extension($image_path)
```
But my image URL is `example.com/images/new.png?v=21212154`
It returns `png?v=21212154`
How to get the value `png` only?<issue_comment>username_1: You should try this way:
```
$url = 'example.com/images/new.png?v=21212154';
$data = explode('?',$test);
$data = explode('/',$data[0]);
$filename = $data[2];
$extention = File::extension($filename);
```
**OR Try with below code.**
```
$result = File::extension($image_path)
$url = strstr($result,"?");
echo str_replace($url,"",$result);
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: [`strstr`](http://php.net/strstr) will help you get values before some symbol:
```
$extension = 'png?v=21212154';
$real_extension = strstr($extension, '?', true);
// but if there's no '?' in `$extension`,
// `$real_extension` will be false
if ($real_extension) {
$extension = $real_extension;
}
```
Upvotes: 1 <issue_comment>username_3: Try to use pathinfo():
```
$extension = pathinfo($image_path, PATHINFO_EXTENSION);
```
or
```
$info = pathinfo(image_path);
$extension = $info['extension'];
```
Upvotes: 0
|
2018/03/16
| 424 | 1,268 |
<issue_start>username_0: I want to to add 2 Section Headers in Recycler View..
I want to develop Header inside a Header.
I dont want to use Expandable view.I need it in Scroll-able view.
I want to show Tour Name as 1st Header.
Under that i want to show Location as 2nd Header
<issue_comment>username_1: You should try this way:
```
$url = 'example.com/images/new.png?v=21212154';
$data = explode('?',$test);
$data = explode('/',$data[0]);
$filename = $data[2];
$extention = File::extension($filename);
```
**OR Try with below code.**
```
$result = File::extension($image_path)
$url = strstr($result,"?");
echo str_replace($url,"",$result);
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: [`strstr`](http://php.net/strstr) will help you get values before some symbol:
```
$extension = 'png?v=21212154';
$real_extension = strstr($extension, '?', true);
// but if there's no '?' in `$extension`,
// `$real_extension` will be false
if ($real_extension) {
$extension = $real_extension;
}
```
Upvotes: 1 <issue_comment>username_3: Try to use pathinfo():
```
$extension = pathinfo($image_path, PATHINFO_EXTENSION);
```
or
```
$info = pathinfo(image_path);
$extension = $info['extension'];
```
Upvotes: 0
|
2018/03/16
| 512 | 1,768 |
<issue_start>username_0: I have following data:
**Table**: PriceTable
```
Price Applicable1 Applicable2 Percentage
--------------------------------------------
100 Yes Yes 0.10
200 Yes No 0.50
300 No Yes 0.30
500 Yes Yes 0.40
```
I want to calculate the Percentage of price in last column and show in the table/matrix in the power bi report.
**Scenario**: If both column `Applicable1 and Applicable2` are equal to `Yes` then calculate the percentage of price in the final column.
**My try**: I have taken `New Column` and added following **DAX**:
```
Commission = IF( PriceTable[Applicable1] = "Yes" &&
PriceTable[Applicable2] = "Yes",
PriceTable[Price] * PriceTable[Percentage], 0)
```
**Question**:
>
> 1. Which one should I use `New Column` OR `Measure`?
> 2. If `Measure`, then how to calculate the same?
>
>
><issue_comment>username_1: Use new Column as you calculation is not dynamic it's row wise calculation so use NewColumn.
Even it's fast as It's precalculated If you use dynamic it calculates the value every time when you launch the report which slow down your report loading
Upvotes: 2 <issue_comment>username_2: <NAME> has an excellent blog post on "[When to Use Measures vs. Calc Columns](https://powerpivotpro.com/2013/02/when-to-use-measures-vs-calc-columns/)"
And <NAME> has another good post:
[Measure vs Calculated Column: The Mysterious Question? Not!](http://radacad.com/measure-vs-calculated-column-the-mysterious-question-not)
My favourite take-away from this is:
>
> If you want to put it on rows, columns, slicers, or report filters, it
> MUST be a column
>
>
>
Upvotes: 3 [selected_answer]
|
2018/03/16
| 374 | 1,385 |
<issue_start>username_0: I tried to build a image upload tool, every child component have there own upload button.
Is there the way to let the upload function control by parent component?
following the code:
Child Component
```
class Child extends Component{
constructor(props){
super(props)
this.state={
imageUrl: 'base64'
}
}
componentDidMount(){
this.setState({imageUrl: this.props.image})
}
handleUpload(){
axios.post(this.state.imageUrl);
}
render(){
return(

)
}
}
```
Parent Component
```
class Parent extends Component{
constructor(props){
super(props)
this.state={
imageFiles: [...image]
}
}
componentDidMount(){
}
render(){
return(
{
this.state.imageFiles.map(image=>{
return(
)
})
}
)
}
}
```
I know how to access the parent component function to child component by this way in the parent component.
Is there some method to let parent component functions can trigger all the child component?<issue_comment>username_1: Here is the same [question](https://stackoverflow.com/questions/37949981/call-child-method-from-parent)
Make a `ref` for a child component and then call it within parent's function.
Upvotes: 1 [selected_answer]<issue_comment>username_2: You could move handle function in the parent component, then pass it to the child component like:
```
```
Upvotes: 1
|
2018/03/16
| 3,629 | 8,463 |
<issue_start>username_0: Suppose I have a Pandas Series `s` whose values sum to `1` and whose values are also all greater than or equal to `0`. I need to subtract a constant from all values such that the sum of the new Series is equal to `0.6`. The catch is, when I subtract this constant, the values never end up less than zero.
In math formula, assume I have a series of `x`'s and I want to find `k`
[](https://i.stack.imgur.com/LphIb.png)
MCVE
====
```
import pandas as pd
import numpy as np
from string import ascii_uppercase
np.random.seed([3, 141592653])
s = np.power(
1000, pd.Series(
np.random.rand(10),
list(ascii_uppercase[:10])
)
).pipe(lambda s: s / s.sum())
s
A 0.001352
B 0.163135
C 0.088365
D 0.010904
E 0.007615
F 0.407947
G 0.005856
H 0.198381
I 0.027455
J 0.088989
dtype: float64
```
The sum is `1`
```
s.sum()
0.99999999999999989
```
What I've tried
---------------
I can use Newton's method (among others) found in Scipy's `optimize` module
```
from scipy.optimize import newton
def f(k):
return s.sub(k).clip(0).sum() - .6
```
Finding the root of this function will give me the `k` I need
```
initial_guess = .1
k = newton(f, x0=initial_guess)
```
Then subtract this from `s`
```
new_s = s.sub(k).clip(0)
new_s
A 0.000000
B 0.093772
C 0.019002
D 0.000000
E 0.000000
F 0.338583
G 0.000000
H 0.129017
I 0.000000
J 0.019626
dtype: float64
```
And the new sum is
```
new_s.sum()
0.60000000000000009
```
Question
========
Can we find `k` without resorting to using a solver?<issue_comment>username_1: Updated: Three different implementations - interestingly, the least sophisticated scales best.
```
import numpy as np
def f_sort(A, target=0.6):
B = np.sort(A)
C = np.cumsum(np.r_[B[0], np.diff(B)] * np.arange(N, 0, -1))
idx = np.searchsorted(C, 1 - target)
return B[idx] + (1 - target - C[idx]) / (N-idx)
def f_partition(A, target=0.6):
target, l = 1 - target, len(A)
while len(A) > 1:
m = len(A) // 2
A = np.partition(A, m-1)
ls = A[:m].sum()
if ls + A[m-1] * (l-m) > target:
A = A[:m]
else:
l -= m
target -= ls
A = A[m:]
return target / l
def f_direct(A, target=0.6):
target = 1 - target
while True:
gt = A > target / len(A)
if np.all(gt):
return target / len(A)
target -= A[~gt].sum()
A = A[gt]
N = 10
A = np.random.random(N)
A /= A.sum()
print(f_sort(A), np.clip(A-f_sort(A), 0, None).sum())
print(f_partition(A), np.clip(A-f_partition(A), 0, None).sum())
print(f_direct(A), np.clip(A-f_direct(A), 0, None).sum())
from timeit import timeit
kwds = dict(globals=globals(), number=1000)
N = 100000
A = np.random.random(N)
A /= A.sum()
print(timeit('f_sort(A)', **kwds))
print(timeit('f_partition(A)', **kwds))
print(timeit('f_direct(A)', **kwds))
```
Sample run:
```
0.04813686999999732 0.5999999999999999
0.048136869999997306 0.6000000000000001
0.048136869999997306 0.6000000000000001
8.38109541599988
2.1064437470049597
1.2743922089866828
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: An exact solution, requesting only a sort, then in O(n) (well, less: we only need as many loops as the number of values that will turn to zero):
we turn the smallest values to zero while possible, then share the remaining excess between the remaining ones:
```
l = [0.001352, 0.163135, 0.088365, 0.010904, 0.007615, 0.407947,
0.005856, 0.198381, 0.027455, 0.088989]
initial_sum = sum(l)
target_sum = 0.6
# number of values not yet turned to zero
non_zero = len(l)
# already substracted by substracting the constant where possible
substracted = 0
# what we want to substract to each value
constant = 0
for v in sorted(l):
if initial_sum - substracted - non_zero * (v - constant) >= target_sum:
substracted += non_zero * (v - constant)
constant = v
non_zero -= 1
else:
constant += (initial_sum - substracted - target_sum) / non_zero
break
l = [v - constant if v > constant else 0 for v in l]
print(l)
print(sum(l))
# [0, 0.09377160000000001, 0.019001600000000007, 0, 0, 0.3385836, 0, 0.1290176, 0, 0.019625600000000007]
# 0.6
```
Upvotes: 2 <issue_comment>username_3: I was not expecting `newton` to carry the day. But on large arrays, it does.
`numba.njit`
============
Inspire by [Thierry's](https://stackoverflow.com/users/550094/thierry-lathuille) [Answer](https://stackoverflow.com/a/49315398/2336654)
Using a loop on a sorted array with `numba`s `jit`
```
import numpy as np
from numba import njit
@njit
def find_k_numba(a, t):
a = np.sort(a)
m = len(a)
s = a.sum()
to_remove = s - t
if to_remove <= 0:
k = 0
else:
for i, x in enumerate(a):
k = to_remove / (m - i)
if k < x:
break
else:
to_remove -= x
return k
```
---
`numpy`
=======
Inspired by [Paul's](https://stackoverflow.com/users/7207392/paul-panzer) [Answer](https://stackoverflow.com/a/49314794/2336654)
Numpy carrying the heavy lifting.
```
import numpy as np
def find_k_numpy(a, t):
a = np.sort(a)
m = len(a)
s = a.sum()
to_remove = s - t
if to_remove <= 0:
k = 0
else:
c = a.cumsum()
n = np.arange(m)[::-1]
b = n * a + c
i = np.searchsorted(b, to_remove)
k = a[i] + (to_remove - b[i]) / (m - i)
return k
```
---
`scipy.optimize.newton`
=======================
My method via Newton
```
import numpy as np
from scipy.optimize import newton
def find_k_newton(a, t):
s = a.sum()
if s <= t:
k = 0
else:
def f(k_):
return np.clip(a - k_, 0, a.max()).sum() - t
k = newton(f, (s - t) / len(a))
return k
```
---
Time Trials
===========
```
import pandas as pd
from timeit import timeit
res = pd.DataFrame(
np.nan, [10, 30, 100, 300, 1000, 3000, 10000, 30000],
'find_k_newton find_k_numpy find_k_numba'.split()
)
for i in res.index:
a = np.random.rand(i)
t = a.sum() * .6
for j in res.columns:
stmt = f'{j}(a, t)'
setp = f'from __main__ import {j}, a, t'
res.at[i, j] = timeit(stmt, setp, number=200)
```
Results
=======
```
res.plot(loglog=True)
```
[](https://i.stack.imgur.com/OyBLG.png)
```
res.div(res.min(1), 0)
find_k_newton find_k_numpy find_k_numba
10 57.265421 17.552150 1.000000
30 29.221947 9.420263 1.000000
100 16.920463 5.294890 1.000000
300 10.761341 3.037060 1.000000
1000 1.455159 1.033066 1.000000
3000 1.000000 2.076484 2.550152
10000 1.000000 3.798906 4.421955
30000 1.000000 5.551422 6.784594
```
Upvotes: 3 <issue_comment>username_4: Just wanted to add an option to @username_3 's answer: `find_k_hybrd`
[](https://i.stack.imgur.com/cfmFW.png)
`find_k_hybrd` is a mixture of the "numba" and "newton" solutions. I use the `hybrd` root finding algorithm in [NumbaMinpack](https://github.com/Nicholaswogan/NumbaMinpack). `NumbaMinpack` is faster than `scipy` for problems like this, because it's root finding methods can be within jit-ed functions.
```py
import numpy as np
from NumbaMinpack import hybrd, minpack_sig
from numba import njit, cfunc
n = 10000
np.random.seed(0)
a = np.random.rand(n)
t = a.sum()*.6
@cfunc(minpack_sig)
def func(k_, fvec, args):
t = args[n]
amax = -np.inf
for i in range(n):
if args[i] > amax:
amax = args[i]
args1 = np.empty(n)
for i in range(n):
args1[i] = args[i] - k_[0]
if args1[i] < 0.0:
args1[i] = 0.0
elif args1[i] > amax:
args1[i] = amax
argsum = args1.sum()
fvec[0] = argsum - t
funcptr = func.address
@njit
def find_k_hybrd(a, t):
s = a.sum()
if s <= t:
k = 0.0
else:
k_init = np.array([(s - t) / len(a)])
args = np.append(a, np.array([t]))
sol = hybrd(funcptr, k_init, args)
k = sol[0][0]
return k
print(find_k_hybrd(a, t))
```
Upvotes: 1
|
2018/03/16
| 2,149 | 7,257 |
<issue_start>username_0: I'm using ui-bootstrap pagination, I use $index value to add a comment on every row it is working fine but on 2nd page and 3rd and so on $index value starts from 0 again. how to read index value on 2nd 3rd ... pages,
why it is taking from 0th index again in page 2 and so on. i'm passing index value in in textarea as well.
I have give code below.
```js
var myApp = angular.module('myApp', ['ui.bootstrap'])
.controller('employeeController', function ($scope) {
var employees = [{
"Name": "<NAME>",
"City": "Berlin",
"Country": "Germany"
}, {
"Name": "<NAME>",
"City": "Luleå",
"Country": "Sweden"
}, {
"Name": "<NAME>",
"City": "Mannheim",
"Country": "Germany"
}, {
"Name": "<NAME>",
"City": "Strasbourg",
"Country": "France"
}, {
"Name": "<NAME>",
"City": "Madrid",
"Country": "Spain"
}, {
"Name": "<NAME>'",
"City": "Marseille",
"Country": "France"
}, {
"Name": "<NAME>",
"City": "Tsawassen",
"Country": "Canada"
}, {
"Name": "<NAME>",
"City": "Buenos Aires",
"Country": "Argentina"
}, {
"Name": "<NAME>erc<NAME>",
"City": "México D.F.",
"Country": "Mexico"
}, {
"Name": "<NAME>",
"City": "Bern",
"Country": "Switzerland"
}, {
"Name": "<NAME>",
"City": "São Paulo",
"Country": "Brazil"
}];
$scope.employees=employees;
$scope.showHideAddNotes = function (vendorsId, $index) {
$scope.comments = vendorsId;
angular.forEach($scope.employees, function (vendr) {
if (vendr.VendID == $scope.comments) {
$scope.showComment = true;
}
})
}
$scope.pageSize = 10;
$scope.currentPage = 1;
$scope.itemsPerPage = $scope.pageSize;
$scope.maxSize = 5; //Number of pager buttons to show
$scope.totalItems = $scope.employees.length;
$scope.setPage = function (pageNo) {
$scope.currentPage = pageNo;
};
$scope.pageChanged = function () {
console.log('Page changed to: ' + $scope.currentPage);
};
$scope.setItemsPerPage = function (num) {
$scope.itemsPerPage = num;
$scope.currentPage = 1; //reset to first page
}
$scope.showHideAddNotes = function (index) {
alert(index);
$scope.employees[index].showComment = !$scope.employees[index].showComment;
}
$scope.addNote = function (vendkey, index) {
var notes = APService.SaveVendorComment($('#txtVendorNote' + index).val(), vendkey).responseJSON;
$scope.employees[index].showComment = !$scope.employees[index].showComment;
}
})
```
```css
.textarea-container {
position: relative;
}
.textarea-container textarea {
width: 100%;
height: 100%;
box-sizing: border-box;
}
```
```html
| Name | City | Country |
| --- | --- | --- |
| {{emp.Name}}
Save
| {{emp.City}} | {{emp.Country}} |
```<issue_comment>username_1: ```
var app = angular.module("myApp", ["ui.bootstrap"]);
app.controller("MainCtrl", function($scope) {
var allData =
[your data goes here];
$scope.totalItems = allData.length;
$scope.currentPage = 1;
$scope.itemsPerPage = 5;
$scope.$watch("currentPage", function() {
setPagingData($scope.currentPage);
});
function setPagingData(page) {
var pagedData = allData.slice(
(page - 1) * $scope.itemsPerPage,
page * $scope.itemsPerPage
);
$scope.aCandidates = pagedData;
}
});
```
---
```
document.write('<base href="' + document.location + '" />');
| Name |
| --- |
| {{person}} |
| --- |
```
Upvotes: 0 <issue_comment>username_2: The `$index` is actually the index of visible elements. You can get the real index like this.
```
index += ($scope.currentPage - 1) * $scope.itemsPerPage;
```
**Working Snippet:**
```js
var myApp = angular.module('myApp', ['ui.bootstrap'])
.controller('employeeController', function($scope) {
var employees = [{
"Name": "<NAME>",
"City": "Berlin",
"Country": "Germany"
}, {
"Name": "<NAME>",
"City": "Luleå",
"Country": "Sweden"
}, {
"Name": "<NAME>",
"City": "Mannheim",
"Country": "Germany"
}, {
"Name": "<NAME>",
"City": "Strasbourg",
"Country": "France"
}, {
"Name": "<NAME>",
"City": "Madrid",
"Country": "Spain"
}, {
"Name": "<NAME>'",
"City": "Marseille",
"Country": "France"
}, {
"Name": "<NAME>",
"City": "Tsawassen",
"Country": "Canada"
}, {
"Name": "<NAME>",
"City": "Buenos Aires",
"Country": "Argentina"
}, {
"Name": "Centro comercial Moctezuma",
"City": "México D.F.",
"Country": "Mexico"
}, {
"Name": "<NAME>",
"City": "Bern",
"Country": "Switzerland"
}, {
"Name": "<NAME>",
"City": "São Paulo",
"Country": "Brazil"
}];
$scope.employees = employees;
$scope.showHideAddNotes = function(vendorsId, $index) {
$scope.comments = vendorsId;
angular.forEach($scope.employees, function(vendr) {
if (vendr.VendID == $scope.comments) {
$scope.showComment = true;
}
})
}
$scope.pageSize = 10;
$scope.currentPage = 1;
$scope.itemsPerPage = $scope.pageSize;
$scope.maxSize = 5; //Number of pager buttons to show
$scope.totalItems = $scope.employees.length;
$scope.setPage = function(pageNo) {
$scope.currentPage = pageNo;
};
$scope.pageChanged = function() {
console.log('Page changed to: ' + $scope.currentPage);
};
$scope.setItemsPerPage = function(num) {
$scope.itemsPerPage = num;
$scope.currentPage = 1; //reset to first page
}
$scope.showHideAddNotes = function(index) {
index += ($scope.currentPage - 1) * $scope.itemsPerPage;
alert(index);
$scope.employees[index].showComment = !$scope.employees[index].showComment;
}
$scope.addNote = function(vendkey, index) {
var notes = APService.SaveVendorComment($('#txtVendorNote' + index).val(), vendkey).responseJSON;
$scope.employees[index].showComment = !$scope.employees[index].showComment;
}
})
```
```css
.textarea-container {
position: relative;
}
.textarea-container textarea {
width: 100%;
height: 100%;
box-sizing: border-box;
}
```
```html
| Name | City | Country |
| --- | --- | --- |
| {{emp.Name}}
Save
| {{emp.City}} | {{emp.Country}} |
```
Upvotes: 3 [selected_answer]
|
2018/03/16
| 1,494 | 4,936 |
<issue_start>username_0: Here is my object,
```
{'name': 'Lipika', 'monday': 1}
{'name': 'Ram', 'monday': 0}
{'name': 'Lipika', 'tuesday': 1}
{'name': 'Ram', 'tuesday': 0}
```
**Here is the two condition**
I want to check whether Lipika is present in the DB, If not present i should create his name in the User Collection and then insert in the Attendance Collection, If Already present then i should just insert the Attendance Collection.
**Here is what i have tried**
```
for (var key in row) {
checkUser(name,function(data) {
//Insert inside Attendence collection then..
});
}
function checkUser(name, callback){
dbModel.User.findOne({ name: name}, function (err, data) {
if(data){
callback('exist');
}else{
var User = new dbModel.User({name : name});
User.save(function (err) {
if (err) {
console.log('Err',err);
} else {
callback('not exist');
}
});
}
});
}
```
But it is creating Lipika and Ram two times as nodejs run async way. How can i wait the until the javascript checks and insert inside the user ?<issue_comment>username_1: ```
var app = angular.module("myApp", ["ui.bootstrap"]);
app.controller("MainCtrl", function($scope) {
var allData =
[your data goes here];
$scope.totalItems = allData.length;
$scope.currentPage = 1;
$scope.itemsPerPage = 5;
$scope.$watch("currentPage", function() {
setPagingData($scope.currentPage);
});
function setPagingData(page) {
var pagedData = allData.slice(
(page - 1) * $scope.itemsPerPage,
page * $scope.itemsPerPage
);
$scope.aCandidates = pagedData;
}
});
```
---
```
document.write('<base href="' + document.location + '" />');
| Name |
| --- |
| {{person}} |
| --- |
```
Upvotes: 0 <issue_comment>username_2: The `$index` is actually the index of visible elements. You can get the real index like this.
```
index += ($scope.currentPage - 1) * $scope.itemsPerPage;
```
**Working Snippet:**
```js
var myApp = angular.module('myApp', ['ui.bootstrap'])
.controller('employeeController', function($scope) {
var employees = [{
"Name": "<NAME>",
"City": "Berlin",
"Country": "Germany"
}, {
"Name": "<NAME>",
"City": "Luleå",
"Country": "Sweden"
}, {
"Name": "<NAME>",
"City": "Mannheim",
"Country": "Germany"
}, {
"Name": "<NAME>",
"City": "Strasbourg",
"Country": "France"
}, {
"Name": "<NAME>",
"City": "Madrid",
"Country": "Spain"
}, {
"Name": "<NAME>'",
"City": "Marseille",
"Country": "France"
}, {
"Name": "<NAME>",
"City": "Tsawassen",
"Country": "Canada"
}, {
"Name": "<NAME>",
"City": "Buenos Aires",
"Country": "Argentina"
}, {
"Name": "Centro comerc<NAME>",
"City": "México D.F.",
"Country": "Mexico"
}, {
"Name": "<NAME>",
"City": "Bern",
"Country": "Switzerland"
}, {
"Name": "<NAME>",
"City": "São Paulo",
"Country": "Brazil"
}];
$scope.employees = employees;
$scope.showHideAddNotes = function(vendorsId, $index) {
$scope.comments = vendorsId;
angular.forEach($scope.employees, function(vendr) {
if (vendr.VendID == $scope.comments) {
$scope.showComment = true;
}
})
}
$scope.pageSize = 10;
$scope.currentPage = 1;
$scope.itemsPerPage = $scope.pageSize;
$scope.maxSize = 5; //Number of pager buttons to show
$scope.totalItems = $scope.employees.length;
$scope.setPage = function(pageNo) {
$scope.currentPage = pageNo;
};
$scope.pageChanged = function() {
console.log('Page changed to: ' + $scope.currentPage);
};
$scope.setItemsPerPage = function(num) {
$scope.itemsPerPage = num;
$scope.currentPage = 1; //reset to first page
}
$scope.showHideAddNotes = function(index) {
index += ($scope.currentPage - 1) * $scope.itemsPerPage;
alert(index);
$scope.employees[index].showComment = !$scope.employees[index].showComment;
}
$scope.addNote = function(vendkey, index) {
var notes = APService.SaveVendorComment($('#txtVendorNote' + index).val(), vendkey).responseJSON;
$scope.employees[index].showComment = !$scope.employees[index].showComment;
}
})
```
```css
.textarea-container {
position: relative;
}
.textarea-container textarea {
width: 100%;
height: 100%;
box-sizing: border-box;
}
```
```html
| Name | City | Country |
| --- | --- | --- |
| {{emp.Name}}
Save
| {{emp.City}} | {{emp.Country}} |
```
Upvotes: 3 [selected_answer]
|
2018/03/16
| 1,777 | 6,911 |
<issue_start>username_0: I am getting error in my codeignitor application:
>
> Unable to load the requested file: helpers/files\_helper.php
>
>
>
Can you please elaborate where is the issue?
File: autoload.php
```
php
defined('BASEPATH') or exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| Instructions
| -------------------------------------------------------------------
|
| These are the things you can load automatically:
|
| 1. Packages
| 2. Libraries
| 3. Drivers
| 4. Helper files
| 5. Custom config files
| 6. Language files
| 7. Models
|
*/
/*
| -------------------------------------------------------------------
| Auto-load Packages
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['packages'] = array(APPPATH.'third_party', '/usr/local/shared');
|
*/
$autoload['packages'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Libraries
| -------------------------------------------------------------------
| These are the classes located in system/libraries/ or your
| application/libraries/ directory, with the addition of the
| 'database' library, which is somewhat of a special case.
|
| Prototype:
|
| $autoload['libraries'] = array('database', 'email', 'session');
|
| You can also supply an alternative library name to be assigned
| in the controller:
|
| $autoload['libraries'] = array('user_agent' = 'ua');
*/
$autoload['libraries'] = array( 'database', 'user_agent', 'image_lib', 'encryption', 'object_cache', 'email', 'app', 'gateways/app_gateway', 'sms' );
$CI = &get_instance();
$CI->load->helper('files');
$gateways = list_files(APPPATH.'/libraries/gateways');
foreach ($gateways as $gateway) {
$pathinfo = pathinfo($gateway);
// Check if file is .php and do not starts with .dot
// Offen happens Mac os user to have underscore prefixed files while unzipping the zip file.
if ($pathinfo['extension'] == 'php' && 0 !== strpos($gateway, '.') && $pathinfo['filename'] != 'App_gateway') {
array_push($autoload['libraries'], 'gateways/'.strtolower($pathinfo['filename']));
}
}
/*
| -------------------------------------------------------------------
| Auto-load Drivers
| -------------------------------------------------------------------
| These classes are located in system/libraries/ or in your
| application/libraries/ directory, but are also placed inside their
| own subdirectory and they extend the CI_Driver_Library class. They
| offer multiple interchangeable driver options.
|
| Prototype:
|
| $autoload['drivers'] = array('cache');
*/
$autoload['drivers'] = array('session');
/*
| -------------------------------------------------------------------
| Auto-load Helper Files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['helper'] = array('url', 'file');
*/
$autoload['helper'] = array(
'url',
'file',
'form',
'action_hooks',
'general',
'misc',
'func',
'datatables',
'custom_fields',
'defaults',
'merge_fields',
'app_html',
'email_templates',
'invoices',
'estimates',
'credit_notes',
'proposals',
'projects',
'tasks',
'fields',
'tickets',
'relation',
'tags',
'pdf',
'clients',
'database',
'upload',
'sales',
'themes',
'theme_style',
'pre_query_data_formatters',
'widgets',
'sms',
'deprecated',
);
if (file_exists(APPPATH.'helpers/system_messages_helper.php')) {
array_push($autoload['helper'], 'system_messages');
}
if (file_exists(APPPATH.'helpers/my_functions_helper.php')) {
array_push($autoload['helper'], 'my_functions');
}
/*
| -------------------------------------------------------------------
| Auto-load Config files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['config'] = array('config1', 'config2');
|
| NOTE: This item is intended for use ONLY if you have created custom
| config files. Otherwise, leave it blank.
|
*/
$autoload['config'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Language files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['language'] = array('lang1', 'lang2');
|
| NOTE: Do not include the "_lang" part of your file. For example
| "codeigniter_lang.php" would be referenced as array('codeigniter');
|
*/
$autoload['language'] = array('english');
/*
| -------------------------------------------------------------------
| Auto-load Models
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['model'] = array('first_model', 'second_model');
|
| You can also supply an alternative model name to be assigned
| in the controller:
|
| $autoload['model'] = array('first_model' => 'first');
*/
$autoload['model'] = array( 'misc_model' , 'roles_model' , 'clients_model' , 'tasks_model' );
if(file_exists(APPPATH.'config/my_autoload.php')){
include_once(APPPATH.'config/my_autoload.php');
}
```
The path in my codeigitor application of this file is application/config/autoload.php
I'm just trying to login from the base URL: <http://crm.thecoder.pw/>
And I'm getting this error: Unable to load the requested file: helpers/files\_helper.php<issue_comment>username_1: There is no helper call `files_helper`. Use [**`file`**](https://www.codeigniter.com/userguide3/helpers/file_helper.html)
```
$this->load->helper('file');
```
or in [**`/config/autoload.php`**](https://github.com/bcit-ci/CodeIgniter/blob/develop/application/config/autoload.php#L92)
```
$autoload['helper'] = array('file');
```
---
**EDIT 01**
If you're creating new helper check **[this answer as well](https://stackoverflow.com/questions/804399/codeigniter-create-new-helper)**
Upvotes: 2 <issue_comment>username_2: I think it's a simple mistake that you have made, Replace below line of your code
```
$CI->load->helper('files');
```
by
```
$CI->load->helper('file');
```
Upvotes: 0 <issue_comment>username_3: I think you have created helper in application/helpers folder.
You have to create helper in **system/helpers** folder instead of **application/helpers**.
Then load `$this->load->helper('files');`
Upvotes: 2 <issue_comment>username_4: My solution was to move my `custom_helper.php` from `application/helpers/custom_helper.php`
to `system/helpers/custom_helper.php` and in `application/config/autoload.php $autoload['helper'] = array('custom');`
Reload page and it work fine
Upvotes: 2 <issue_comment>username_5: There should not be an upper case latter in helpers name.
Upvotes: 2
|
2018/03/16
| 461 | 1,594 |
<issue_start>username_0: The question is very simple how to get Apple search ads popularity index for any given keyword?
It's possible since i see a lot of ASO tools provide such metric. But there are not any open API documentation how to get this data.<issue_comment>username_1: There is no helper call `files_helper`. Use [**`file`**](https://www.codeigniter.com/userguide3/helpers/file_helper.html)
```
$this->load->helper('file');
```
or in [**`/config/autoload.php`**](https://github.com/bcit-ci/CodeIgniter/blob/develop/application/config/autoload.php#L92)
```
$autoload['helper'] = array('file');
```
---
**EDIT 01**
If you're creating new helper check **[this answer as well](https://stackoverflow.com/questions/804399/codeigniter-create-new-helper)**
Upvotes: 2 <issue_comment>username_2: I think it's a simple mistake that you have made, Replace below line of your code
```
$CI->load->helper('files');
```
by
```
$CI->load->helper('file');
```
Upvotes: 0 <issue_comment>username_3: I think you have created helper in application/helpers folder.
You have to create helper in **system/helpers** folder instead of **application/helpers**.
Then load `$this->load->helper('files');`
Upvotes: 2 <issue_comment>username_4: My solution was to move my `custom_helper.php` from `application/helpers/custom_helper.php`
to `system/helpers/custom_helper.php` and in `application/config/autoload.php $autoload['helper'] = array('custom');`
Reload page and it work fine
Upvotes: 2 <issue_comment>username_5: There should not be an upper case latter in helpers name.
Upvotes: 2
|
2018/03/16
| 480 | 1,570 |
<issue_start>username_0: how do i add up all the strings together in a list into a big string?
For example:
```
alist = ["Hi","How are YOU","THANK YOU"]
```
How do i make it into:
```
alist = ["Hi,How are YOU, THANK YOU"]
```<issue_comment>username_1: There is no helper call `files_helper`. Use [**`file`**](https://www.codeigniter.com/userguide3/helpers/file_helper.html)
```
$this->load->helper('file');
```
or in [**`/config/autoload.php`**](https://github.com/bcit-ci/CodeIgniter/blob/develop/application/config/autoload.php#L92)
```
$autoload['helper'] = array('file');
```
---
**EDIT 01**
If you're creating new helper check **[this answer as well](https://stackoverflow.com/questions/804399/codeigniter-create-new-helper)**
Upvotes: 2 <issue_comment>username_2: I think it's a simple mistake that you have made, Replace below line of your code
```
$CI->load->helper('files');
```
by
```
$CI->load->helper('file');
```
Upvotes: 0 <issue_comment>username_3: I think you have created helper in application/helpers folder.
You have to create helper in **system/helpers** folder instead of **application/helpers**.
Then load `$this->load->helper('files');`
Upvotes: 2 <issue_comment>username_4: My solution was to move my `custom_helper.php` from `application/helpers/custom_helper.php`
to `system/helpers/custom_helper.php` and in `application/config/autoload.php $autoload['helper'] = array('custom');`
Reload page and it work fine
Upvotes: 2 <issue_comment>username_5: There should not be an upper case latter in helpers name.
Upvotes: 2
|
2018/03/16
| 2,294 | 6,164 |
<issue_start>username_0: I have a pandas dataframe as follow:
```
Names Cider Juice Subtotal (Cider) Subtotal (Juice) Total
Richard 13 9 $ 71.5 $ 40.5 $ 112.0
George 7 21 $ 38.5 $ 94.5 $ 133.0
Paul 0 23 $ 0.0 $ 103.5 $ 103.5
John 22 5 $ 121.0 $ 22.5 $ 143.5
Total 42 58 $ 231.0 $ 261.0 $ 492.0
Average 10.5 14.5 $ 57.75 $ 65.25 $ 123.0
```
I'd like to all float numbers to be '.2f' (2 digits float) numbers. `.applymap()` does not work since I have string type in "Names" column. Is there a work around using `.applymap()` or is there a better way to do this?
```
import pandas as pd
df = pd.DataFrame(columns=["Names", "Cider", "Juice", "Subtotal(Cider)", "Subtotal(Juice)", "Total"])
people_ordered = input('How many people ordered? ') # type str
# Create the 4x3 table from user input
for i in range(int(people_ordered)):
names = input("Enter the name of Person #{}: ".format(i+1)) # type str
cider_orderred = float(input("How many orders of cider did {} have? ".format(names))) # type str -> int
#cider_orderred = float("{:.2f}".format(cider_orderred))
juice_orderred = float(input("How many orders of juice did {} have? ".format(names))) # type str -> int
#juice_orderred = float("{:.2f}".format(juice_orderred))
# store the values of the subtotals from user inputs
cider_sub = 5.50 * cider_orderred # type float
cider_sub = float("{:.2f}".format(cider_sub))
juice_sub = 4.50 * juice_orderred # type float
juice_sub = float("{:.2f}".format(juice_sub))
total = cider_sub + juice_sub # type float
total = float("{:.2f}".format(total))
# create the 4x6 table
df1 = pd.DataFrame(
data=[[names, int(cider_orderred), int(juice_orderred), round(cider_sub, 2), round(juice_sub, 2), round(total, 2)]],
columns=["Names", "Cider", "Juice", "Subtotal(Cider)", "Subtotal(Juice)", "Total"])
# merge the the 4x3 into the 4x6 table
df = pd.concat([df, df1], axis=0)
# add rows of "Total" and "Average"
df.loc['Total'] = df.sum()
df.loc['Average'] = df[:int(people_ordered)].mean()
# Adding "$" to the prices
df['Subtotal(Cider)'] = '$ ' + df['Subtotal(Cider)'].astype(str)
df['Subtotal(Juice)'] = '$ ' + df['Subtotal(Juice)'].astype(str)
df['Total'] = '$ ' + df['Total'].astype(str)
# Set the row name to "Total" and "Average"
df.iloc[int(people_ordered),0] = 'Total'
df.iloc[int(people_ordered)+1,0] = 'Average'
# Set the index according to 'Names'
df.index = range(len(df.index))
df.set_index('Names', inplace=True)
print(df)
```
updated with my current solution as above.<issue_comment>username_1: Use:
* [`set_index`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html) for only numeric columns
* [`replace`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html) `$` with one or more whitespaces `\s+`
* convert to `float`s by [`astype`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.astype.html)
* convert to custom format by [`applymap`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.applymap.html)
---
```
df = (df.set_index('Names')
.replace('\$\s+','', regex=True)
.astype(float)
.applymap('{:,.2f}'.format))
print (df)
Cider Juice Subtotal (Cider) Subtotal (Juice) Total
Names
Richard 13.00 9.00 71.50 40.50 112.00
George 7.00 21.00 38.50 94.50 133.00
Paul 0.00 23.00 0.00 103.50 103.50
John 22.00 5.00 121.00 22.50 143.50
Total 42.00 58.00 231.00 261.00 492.00
Average 10.50 14.50 57.75 65.25 123.00
```
EDIT:
I try improve your solution:
```
people_ordered = input('How many people ordered? ')
Data = []
# Create the 4x3 table from user input
for i in range(int(people_ordered)):
names = input("Enter the name of Person #{}: ".format(i+1)) # type str
cider_orderred = int(input("How many orders of cider did {} have? ".format(names))) # type str -> int
juice_orderred = int(input("How many orders of juice did {} have? ".format(names))) # type str -> int
#create in loop tuple and append to list Data
Data.append((names, cider_orderred, juice_orderred))
#create DataFrame form list of tuples, create index by Names
df1 = pd.DataFrame(Data, columns=['Names','Cider','Juice']).set_index('Names')
#count all new columns, rows
df1['Subtotal(Cider)'] = df1['Cider'] * 5.5
df1['Subtotal(Juice)'] = df1['Juice'] * 4.5
df1['Total'] = df1['Subtotal(Cider)'] + df1['Subtotal(Juice)']
df1.loc['Total'] = df1.sum()
#remove row Total for correct mean
df1.loc['Average'] = df1.drop('Total').mean()
#get custom format of columns in list cols
cols = ['Subtotal(Cider)','Subtotal(Juice)','Total']
df1[cols] = df1[cols].applymap('$ {:,.2f}'.format)
#create column from index
df1 = df1.reset_index()
```
---
```
print(df1)
Names Cider Juice Subtotal(Cider) Subtotal(Juice) Total
0 r 13.0 9.0 $ 71.50 $ 40.50 $ 112.00
1 g 7.0 21.0 $ 38.50 $ 94.50 $ 133.00
2 p 0.0 23.0 $ 0.00 $ 103.50 $ 103.50
3 j 22.0 5.0 $ 121.00 $ 22.50 $ 143.50
4 Total 42.0 58.0 $ 231.00 $ 261.00 $ 492.00
5 Average 10.5 14.5 $ 57.75 $ 65.25 $ 123.00
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: **Just set all floats to 2 digits in general**
```
pd.options.display.float_format = "{:.2f}".format
```
Although: df['column'].sum() will not become 2 digits...?
Upvotes: 3 <issue_comment>username_3: if you want to apply to particular column you can try
```
col_name
123.1
456
df["col_name"] = df["col_name"].apply(lambda x: format(float(x),".2f"))
**after applying format**
col_name
123.10
456.00
```
Upvotes: 2
|
2018/03/16
| 1,988 | 5,633 |
<issue_start>username_0: I have a table with data. Above the table I have an add button and when clicking that button a form will display. But what I want is to display that form in a popup window to submit when clicking the add button.
How can I do that?
Below I have attached my screenshot.
My table view code:
```
#customers {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
}
#customers td, #customers th {
border: 1px solid #ddd;
padding: 3px;
}
#customers tr:nth-child(even){background-color: #f2f2f2;}
#customers tr:hover {background-color: #ddd;}
#customers th {
padding-top: 3px;
padding-bottom: 3px;
text-align: left;
background-color: #4CAF50;
color: white;
}
|
php
$doc = $display['hits']['hits'];
$html = '<table id = "customers"
| Id | First\_name | Last\_name | Email | Phone | Address | Password | Status | Createddate | Updateddate | File | Edit | Delete |
';
foreach($doc as $key => $value)
{
$html = $html."| ".$value['\_source']['Id']." | ".$value['\_source']['First\_name']." | ".$value['\_source']['Last\_name']." | ".$value['\_source']['Email']." | ".$value['\_source']['Phone']." | ".$value['\_source']['Address']." | ".$value['\_source']['Password']." | ".$value['\_source']['Status']." | ".$value['\_source']['Createddate']." | ".$value['\_source']['Updateddate']." | ".$value['\_source']['File']." | | |
";
}
$html = $html."";
echo $html;
?>
$(document).ready(function(){
$('.add\_class').click(function(){
$("#created").toggle();
});
});
$(document).ready(function(){
$(".add\_class").click(function(e) {
e.preventDefault();
$.ajax({
url : "Crud\_controller/Add",
data : '',
dataType: "HTML",
success: function(response) {
var result = $(response).find("body");
$("#created").html(response);
}
}).error(function() { alert("Something went wrong"); });
});
});
```
My form code:
```
Add Employee
label
{
display:inline-block;
width:100px;
margin-bottom:10px;
}
Add Employee
============
ID:
First Name:
Last Name:
Email:
Phone:
Address:
Password:
Status:
CreatedDate:
Updateddate:
FileUpload:
```
[enter image description here](https://i.stack.imgur.com/IHv2x.png)<issue_comment>username_1: Use:
* [`set_index`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html) for only numeric columns
* [`replace`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html) `$` with one or more whitespaces `\s+`
* convert to `float`s by [`astype`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.astype.html)
* convert to custom format by [`applymap`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.applymap.html)
---
```
df = (df.set_index('Names')
.replace('\$\s+','', regex=True)
.astype(float)
.applymap('{:,.2f}'.format))
print (df)
Cider Juice Subtotal (Cider) Subtotal (Juice) Total
Names
Richard 13.00 9.00 71.50 40.50 112.00
George 7.00 21.00 38.50 94.50 133.00
Paul 0.00 23.00 0.00 103.50 103.50
John 22.00 5.00 121.00 22.50 143.50
Total 42.00 58.00 231.00 261.00 492.00
Average 10.50 14.50 57.75 65.25 123.00
```
EDIT:
I try improve your solution:
```
people_ordered = input('How many people ordered? ')
Data = []
# Create the 4x3 table from user input
for i in range(int(people_ordered)):
names = input("Enter the name of Person #{}: ".format(i+1)) # type str
cider_orderred = int(input("How many orders of cider did {} have? ".format(names))) # type str -> int
juice_orderred = int(input("How many orders of juice did {} have? ".format(names))) # type str -> int
#create in loop tuple and append to list Data
Data.append((names, cider_orderred, juice_orderred))
#create DataFrame form list of tuples, create index by Names
df1 = pd.DataFrame(Data, columns=['Names','Cider','Juice']).set_index('Names')
#count all new columns, rows
df1['Subtotal(Cider)'] = df1['Cider'] * 5.5
df1['Subtotal(Juice)'] = df1['Juice'] * 4.5
df1['Total'] = df1['Subtotal(Cider)'] + df1['Subtotal(Juice)']
df1.loc['Total'] = df1.sum()
#remove row Total for correct mean
df1.loc['Average'] = df1.drop('Total').mean()
#get custom format of columns in list cols
cols = ['Subtotal(Cider)','Subtotal(Juice)','Total']
df1[cols] = df1[cols].applymap('$ {:,.2f}'.format)
#create column from index
df1 = df1.reset_index()
```
---
```
print(df1)
Names Cider Juice Subtotal(Cider) Subtotal(Juice) Total
0 r 13.0 9.0 $ 71.50 $ 40.50 $ 112.00
1 g 7.0 21.0 $ 38.50 $ 94.50 $ 133.00
2 p 0.0 23.0 $ 0.00 $ 103.50 $ 103.50
3 j 22.0 5.0 $ 121.00 $ 22.50 $ 143.50
4 Total 42.0 58.0 $ 231.00 $ 261.00 $ 492.00
5 Average 10.5 14.5 $ 57.75 $ 65.25 $ 123.00
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: **Just set all floats to 2 digits in general**
```
pd.options.display.float_format = "{:.2f}".format
```
Although: df['column'].sum() will not become 2 digits...?
Upvotes: 3 <issue_comment>username_3: if you want to apply to particular column you can try
```
col_name
123.1
456
df["col_name"] = df["col_name"].apply(lambda x: format(float(x),".2f"))
**after applying format**
col_name
123.10
456.00
```
Upvotes: 2
|
2018/03/16
| 463 | 1,768 |
<issue_start>username_0: I sent in a PR to a remote repo and discovered I had the commit from a previous PR included is it possible to delete this unwanted commit?<issue_comment>username_1: You can make a `revert` commit for unwanted commits. In this [answer](https://stackoverflow.com/questions/927358/how-to-undo-the-most-recent-commits-in-git) should be enough info.
Upvotes: 2 [selected_answer]<issue_comment>username_2: You may [close a pull request](https://help.github.com/articles/closing-a-pull-request/) from the GitHub website:
>
> You may choose to close a pull request without merging it into the upstream branch. This can be handy if the changes proposed in the branch are no longer needed, or if another solution has been proposed in another branch.
>
>
>
1. Under your repository name, click Pull requests.
2. In the "Pull Requests" list, click the pull request you'd like to close.
3. The close Pull Request buttonAt the bottom of the pull request, below the comment box, click Close pull request.
4. Optionally, delete the branch. This keeps the list of branches in your repository tidy.
Upvotes: 0 <issue_comment>username_3: You can rebase your branch and update your pull request. Take a look to this [**link**](https://ncona.com/2011/07/how-to-delete-a-commit-in-git-local-and-remote/) and it'll help to how to remove the commit
Upvotes: 0 <issue_comment>username_4: Under your repository name, click Pull requests.
In the "Pull Requests" list, click the pull request you'd like to close.
At the bottom of the pull request, below the comment box, click Close pull request.
Then to revert the last commit or revert to the SHA of the commit ,you can use the command
git revert HEAD~1 or
git revert (get the commit id from git log)
Upvotes: 1
|
2018/03/16
| 1,177 | 3,423 |
<issue_start>username_0: I have a structure as below, Similarly there could multiple structures with multiple fields.
```
struct A
{
int a;
int b;
char * c;
float d
};
```
Now if I want to print each field of the above struct I need to manually type,
```
cout << A.a << endl;
cout << A.b << endl;
cout << A.c << endl;
cout << A.d << endl;
```
As you can see the above stuff is manually and repeated task, Is there any way we can auto genearate the above things.
If anyone can provide code template for eclipse then that would be useful.<issue_comment>username_1: I think you can just create a method in the `struct A` that prints all the members. Call it wherever you need to print all the data using `A.PrintInternalData()`.
```
#include
struct A
{
int a;
int b;
char \* c;
float d
void PrintInternalData()
{
std::cout<
```
Upvotes: 1 [selected_answer]<issue_comment>username_2: C++ does not natively support reflection nor introspection. You cannot inspect a type and query it for what members or functions it contains. You are pretty much stuck doing it "manually" or using a library that adds reflection (like boost reflect or Qt which also provides a limited version for QObject derived classes).
Upvotes: 0 <issue_comment>username_3: There exists a way to enumerate and output all fields of any structure/class automatically, but it exists probably starting only from C++20 standard through unpacking operation (e.g. `auto [a, b] = obj;`). Next code solves your task for any structure, your structure is used as example, for usage example see `main()` function at the very end of code:
[Try it online!](https://godbolt.org/z/WY9bG4)
```
#include
#include
#include
template
struct any\_type {
template constexpr operator T &() const noexcept;
template constexpr operator T &&() const noexcept;
};
template
constexpr auto detect\_fields\_count(std::index\_sequence) noexcept {
if constexpr (requires { T{any\_type{}...}; })
return sizeof...(Is);
else
return detect\_fields\_count(std::make\_index\_sequence{});
}
template
constexpr auto fields\_count() noexcept {
return detect\_fields\_count(std::make\_index\_sequence{});
}
template
constexpr auto to\_tuple(S & s) noexcept {
constexpr auto count = fields\_count~~();
if constexpr (count == 8) {
auto & [f0, f1, f2, f3, f4, f5, f6, f7] = s;
return std::tie(f0, f1, f2, f3, f4, f5, f6, f7);
} else if constexpr (count == 7) {
auto & [f0, f1, f2, f3, f4, f5, f6] = s;
return std::tie(f0, f1, f2, f3, f4, f5, f6);
} else if constexpr (count == 6) {
auto & [f0, f1, f2, f3, f4, f5] = s;
return std::tie(f0, f1, f2, f3, f4, f5);
} else if constexpr (count == 5) {
auto & [f0, f1, f2, f3, f4] = s;
return std::tie(f0, f1, f2, f3, f4);
} else if constexpr (count == 4) {
auto & [f0, f1, f2, f3] = s;
return std::tie(f0, f1, f2, f3);
} else if constexpr (count == 3) {
auto & [f0, f1, f2] = s;
return std::tie(f0, f1, f2);
} else if constexpr (count == 2) {
auto & [f0, f1] = s;
return std::tie(f0, f1);
} else if constexpr (count == 1) {
auto & [f0] = s;
return std::tie(f0);
} else if constexpr (count == 0) {
return std::tie();
}
}
struct A {
int a;
int b;
char const \* c;
float d;
};
int main() {
A a{.a = 1, .b = 2, .c = "c", .d = 3.14};
std::apply([](auto const &... x) {
((std::cout << x << std::endl), ...); }, to\_tuple(a));
}~~
```
Output:
```
1
2
c
3.14
```
Upvotes: 1
|
2018/03/16
| 360 | 1,261 |
<issue_start>username_0: Hi in my reactJS application I use this
```
this.props.history.push("URL");
```
to redirect to another page or to the same page when I want to reload the page.
But I got this error:
```
Hash history cannot PUSH the same path; a new entry will not be added to the history stack
```
how can I solve this issue?
thanks in advance<issue_comment>username_1: You can use `replace` prop. When replace prop is true, clicking the link will replace the current entry in the history stack instead of adding a new one. To get current pathname use `props.location`.
```
{to}
```
You can create higher order function and wrap your in it. So you can use it as
```
```
**[Here is tutorial and example (my blog)](https://filipmolcik.com/react-router-warning-hash-history-cannot-push-the-same-path/)**
Upvotes: 0 <issue_comment>username_2: I think you are looking for this
```
this.props.history.push({
pathname: "URL"
})
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: You can use
```js
if (history.location.pathname !== somePath) history.push(somePath);
```
Here somePath could be any url.
In react-router-4, pathname can be accessed like
```js
this.props.history.location.pathname
```
Upvotes: 2
|
2018/03/16
| 317 | 1,084 |
<issue_start>username_0: After migration to QBS my QML debugging stopped working.
I made sure that:
1. I'm building a debug build, C++ debugging works
2. I've checked "Enable QML Debugging" in qt creator's Project tab
3. I've even tried to add qbs properties manually `Qt.declarative.qmlDebugging:true Qt.quick.qmlDebugging:true`
Still QtCreator says:
>
> Some breakpoints cannot be handled by the debugger languages currently active, and will be ignored.
>
>
>
QML debugging works with an old .pro
My system:
* Linux archlinux 4.15.7-1-ARCH
* QBS 1.10.1
* Qt 5.10.1<issue_comment>username_1: It's not so clear, but there are **TWO** checkboxes.
One at the build step, and another one in the run step.
So to get QML Debugging working you have to check both of them.
I missed the one under the "Projects->Run->Debugger settings->Enable QML"
Upvotes: 4 [selected_answer]<issue_comment>username_2: The upcoming 4.6 release of Qt Creator should be smarter about this and auto-enable the checkbox in the run settings if the one in the build settings gets enabled.
Upvotes: 0
|
2018/03/16
| 1,113 | 4,917 |
<issue_start>username_0: I am sitting with a situation where I need to provision EC2 instances with some packages on startup. There are a couple of (enterprise/corporate) constraints that exist:
* I need to provision on top of a specific AMI, which adds enterprisey stuff such as LDAP/AD access and so on
* These changes are intended to be used for all internal development machines
Because of mainly the second constraint, I was wondering where is the best place to place the provisioning. This is what I've come up with
**Provision in Terraform**
As it states, I simply provision in terraform for the necessary instances. If I package these resources into modules, then provisioning won't "leak out". The disadvantages
* I won't be able to add a different set of provisioning steps on top of the module?
* A change in the provisioning will probably result in instances being destroyed on apply?
* Provisioning takes a long time because of the packages it tries to install
**Provisioning in Packer**
This is based on the [assumption](https://www.packer.io/intro/getting-started/build-image.html) that Packer allows you to provision on top of AMIs so that AMIs can be "extended". Also, this will only be used in AWS so it won't use other builders necessarily. Provisioning in Packer makes the Terraform Code much simpler and terraform applies will become faster because it's just an AMI that you fire up.
**For me both of these methods have their place. But what I really want to know is when do you choose Packer Provisioning over Terraform Provisioning?**<issue_comment>username_1: Using Packer to create finished (or very nearly finished) images drastically shortens the time it takes to deploy new instances and also allows you to use autoscaling groups.
If you have Terraform run a provisioner such as Chef or Ansible on every EC2 instance creation you add a chunk of time for the provisioner to run at the time you need to deploy new instances. In my opinion it's much better to do the configuration up front and ahead of time using Packer to bake as much as possible into the AMI and then use user data scripts/tools like [Consul-Template](https://github.com/hashicorp/consul-template) to provide environment specific differences.
Packer certainly can build on top of images and in fact requires a [`source_ami`](https://www.packer.io/docs/builders/amazon-ebs.html#source_ami) to be specified. I'd strongly recommend tagging your AMIs in a way that allows you to use [`source_ami_filter`](https://www.packer.io/docs/builders/amazon-ebs.html#source_ami_filter) in Packer and Terraform's [`aws_ami` data source](https://www.terraform.io/docs/providers/aws/d/ami.html) so when you make changes to your AMIs Packer and Terraform will automatically pull those in to be built on top of or deployed at the next opportunity.
I personally bake a reasonably lightweight "Base" AMI that does some basic hardening and sets up monitoring and logging that I want for all instances that are deployed and also makes sure that Packer encrypts the root volume of the AMI. All other images are then built off the latest "Base" AMI and don't have to worry about making sure those things are installed/configured or worry about encrypting the root volume.
By baking your configuration into the AMI you are also able to move towards the immutable infrastructure model which has some major benefits in that you know that you can always throw away an instance that is having issues and very quickly replace it with a new one. Depending on your maturity level you could even remove access to the instances so that it's no longer possible to change anything on the instance once it has been deployed which, in my experience, is a major factor in operational issues.
Very occasionally you might come across something that makes it very difficult to bake an AMI for and in those cases you might choose to run your provisioning scripts in a Terraform provisioner when it is being created. Sometimes it's simply easier to move an existing process over to using provisioners with Terraform than baking the AMIs but I would push to move things over to Packer where possible.
Upvotes: 6 [selected_answer]<issue_comment>username_2: I have come across the same situation. As per my understanding
* If you bring up your EC2 instances very frequently say 2 to 3 times a
day then go with creating an customized AMI with packer and then call
the ami through terraform.
* If your base image ( AMI created by packer) change frequently based
on your requirements then its good to go with packer. But for me
running a packer scripts are very time consuming.
* You can do the same with packer as well. You can write your
requirements in a script and call it in terraform. By having everything
incorporated in a terraform script would reduce some time
Finally its your decision and your frequency of bringing up EC2 instances.
Upvotes: 2
|
2018/03/16
| 974 | 2,947 |
<issue_start>username_0: I'm generating a report in SQL. I had an error of divided by zero. To resolve this error, I used case in SQL query. Now I'm getting a syntax error at 'as'. Is there anyone who can help me to resolve this issue?
```
create procedure dbo.CompanyAverageSales @startdate as varchar(50),@enddate
as varchar(50)
As begin
select datename(year,SO_SalesOrder.InvoicedDate) as [Year],
datename(month,SO_SalesOrder.InvoicedDate) as [Month],
l.Name as [Store Name],
case when sum(convert(int,SO_SalesOrder.Custom1))>0 then sum(SO_SalesOrder_Line.SubTotal)/sum(convert(int,SO_SalesOrder.Custom1)) as [Average Sales]
From SO_SalesOrder
inner join BASE_Location l on SO_SalesOrder.LocationId = l.LocationId
inner join SO_SalesOrder_Line
on SO_SalesOrder.SalesOrderId = SO_SalesOrder_Line.SalesOrderId
inner join BASE_PaymentTerms
on BASE_PaymentTerms.PaymentTermsId = SO_SalesOrder.PaymentTermsId
where SO_SalesOrder.InvoicedDate >= @startdate and SO_SalesOrder.InvoicedDate <= @enddate
group by l.Name,
datename(year,SO_SalesOrder.InvoicedDate),
datename(month,SO_SalesOrder.InvoicedDate)
end
```<issue_comment>username_1: ```
case when sum(convert(int,SO_SalesOrder.Custom1))>0 then
sum(SO_SalesOrder_Line.SubTotal)/sum(convert(int,SO_SalesOrder.Custom1)) as
[Average Sales
```
Should be:
```
case when sum(convert(int,SO_SalesOrder.Custom1))>0 then
sum(SO_SalesOrder_Line.SubTotal)/sum(convert(int,SO_SalesOrder.Custom1))
ELSE 0 -- your logic here
END as [Average Sales
```
Upvotes: 2 <issue_comment>username_2: Add `END` before `AS`
```
case
when sum(convert(int,SO_SalesOrder.Custom1))>0
then
sum(SO_SalesOrder_Line.SubTotal)/sum(convert(int,SO_SalesOrder.Custom1))
Else
0
END as [Average Sales]
```
Upvotes: 4 [selected_answer]<issue_comment>username_3: A nice way to avoid division by zero in this case is to use `NULLIF`:
```
sum(SO_SalesOrder_Line.SubTotal)
/
NULLIF(sum(convert(int,SO_SalesOrder.Custom1)), 0)
```
This will return `NULL` if `sum(convert(int,SO_SalesOrder.Custom1)) = 0`
If you want to return `0` then you can wrap the expression in a `COALESCE`:
```
COALESCE(sum(SO_SalesOrder_Line.SubTotal)
/
NULLIF(sum(convert(int,SO_SalesOrder.Custom1)), 0), 0)
```
Upvotes: 2 <issue_comment>username_4: ```
select
sum(SO_SalesOrder_Line.SubTotal)/NULLIF(sum(convert(int,SO_SalesOrder.Custom1)),0)
FROM ...
```
This will returns Null for records with result with Devided by zero
Upvotes: 0 <issue_comment>username_5: This line generates error:
```
case when sum(convert(int,SO_SalesOrder.Custom1))>0 then sum(SO_SalesOrder_Line.SubTotal)/sum(convert(int,SO_SalesOrder.Custom1)) as [Average Sales]
```
You should close `case` statement with `end`:
```
case when sum(convert(int,SO_SalesOrder.Custom1))>0 then sum(SO_SalesOrder_Line.SubTotal)/sum(convert(int,SO_SalesOrder.Custom1)) end as [Average Sales]
```
Upvotes: 0
|
2018/03/16
| 1,709 | 6,517 |
<issue_start>username_0: I'm working on a third person controller and I'm trying to prevent movement when a raycast in front of the player hits something. Currently when the player collides with a block the blend tree is set to 0 so that it shows the Idle animation. In this case the player appears to be not moving, which it obviously isn't because it's colliding with something, but the input of the user is still there.
This is visible when the player presses the jump button, because the player moves in the direction the user was initially trying to move. In the player controller there is a part that prevents the user from moving after the jump button has been pressed during the length of the jump (Until the player is grounded again). What I'm trying to achieve is that when the user is moving against something and presses the jump button the player will just jump up and won't go in the direction the user was initially trying to go, even if there is no more collider or obstruction.
Something like if the raycast hits something the user won't be able to add movement in that direction, but is still able to turn the player away from the object and move in that direction as long as the raycast doesn't hit a collider.
I'm no c# wizard, so most of the code below comes from a tutorial. I can write a raycast myself, but have no clue how to write the rest of what I'm trying to achieve.
Edit: Current script
```
public RaycastHit _Hit;
public LayerMask _RaycastCollidableLayers; //Set this in inspector, makes you able to say which layers should be collided with and which not.
public float _CheckDistance = 5f;
void Update()
{
PushStates();
// Input
Vector2 input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
Vector2 inputDir = input.normalized;
bool running = Input.GetButton("Run");
if (IsNotBlocked())
{
Move(inputDir, running);
}
float animationSpeedPercent = ((running) ? currentSpeed / runSpeed : currentSpeed / walkSpeed * .5f);
anim.SetFloat("speedPercent", animationSpeedPercent, speedSmoothTime, Time.deltaTime);
anim.SetFloat("speedPercentPush", animationSpeedPercent, speedSmoothTime, Time.deltaTime);
// Check if walking or running
if (animationSpeedPercent < 0.51f)
{
if (ShortJumpRaycast())
{
if (Input.GetButtonDown("Jump") && Time.time > canJump)
{
ShortJump();
}
}
else
{
if (Input.GetButtonDown("Jump") && Time.time > canJump)
{
JumpWalk();
}
}
}
else
{
//Debug.Log("You are Running");
if (Input.GetButtonDown("Jump") && Time.time > canJump)
{
JumpRun();
}
}
JumpCheck();
}
void Move(Vector2 inputDir, bool running)
{
if (inputDir != Vector2.zero)
{
float targetRotation = Mathf.Atan2(inputDir.x, inputDir.y) * Mathf.Rad2Deg + cameraT.eulerAngles.y;
transform.eulerAngles = Vector3.up * Mathf.SmoothDampAngle(transform.eulerAngles.y, targetRotation, ref turnSmoothVelocity, GetModifiedSmoothTime(turnSmoothTime));
}
float targetSpeed = ((running) ? runSpeed : walkSpeed) * inputDir.magnitude;
currentSpeed = Mathf.SmoothDamp(currentSpeed, targetSpeed, ref speedSmoothVelocity, GetModifiedSmoothTime(speedSmoothTime));
velocityY += Time.deltaTime * gravity;
Vector3 velocity = transform.forward * currentSpeed + Vector3.up * velocityY;
controller.Move(velocity * Time.deltaTime);
currentSpeed = new Vector2(controller.velocity.x, controller.velocity.z).magnitude;
// Checks if player is not grounded and is falling
if (GroundCheck())
{
velocityY = 0;
anim.SetBool("onAir", false);
}
else
{
anim.SetBool("onAir", true);
}
}
bool IsNotBlocked()
{
Vector3 forward = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast(transform.position, forward, out _Hit, _CheckDistance + 0.1f, _RaycastCollidableLayers))
if (_Hit.collider == null)
{
Debug.Log("Raycast hit nothing");
return true;
}
GameObject go = _Hit.collider.gameObject;
if (go == null) //If no object hit, nothing is blocked.
return true;
else //An object was hit.
return false;
}
```<issue_comment>username_1: ```
case when sum(convert(int,SO_SalesOrder.Custom1))>0 then
sum(SO_SalesOrder_Line.SubTotal)/sum(convert(int,SO_SalesOrder.Custom1)) as
[Average Sales
```
Should be:
```
case when sum(convert(int,SO_SalesOrder.Custom1))>0 then
sum(SO_SalesOrder_Line.SubTotal)/sum(convert(int,SO_SalesOrder.Custom1))
ELSE 0 -- your logic here
END as [Average Sales
```
Upvotes: 2 <issue_comment>username_2: Add `END` before `AS`
```
case
when sum(convert(int,SO_SalesOrder.Custom1))>0
then
sum(SO_SalesOrder_Line.SubTotal)/sum(convert(int,SO_SalesOrder.Custom1))
Else
0
END as [Average Sales]
```
Upvotes: 4 [selected_answer]<issue_comment>username_3: A nice way to avoid division by zero in this case is to use `NULLIF`:
```
sum(SO_SalesOrder_Line.SubTotal)
/
NULLIF(sum(convert(int,SO_SalesOrder.Custom1)), 0)
```
This will return `NULL` if `sum(convert(int,SO_SalesOrder.Custom1)) = 0`
If you want to return `0` then you can wrap the expression in a `COALESCE`:
```
COALESCE(sum(SO_SalesOrder_Line.SubTotal)
/
NULLIF(sum(convert(int,SO_SalesOrder.Custom1)), 0), 0)
```
Upvotes: 2 <issue_comment>username_4: ```
select
sum(SO_SalesOrder_Line.SubTotal)/NULLIF(sum(convert(int,SO_SalesOrder.Custom1)),0)
FROM ...
```
This will returns Null for records with result with Devided by zero
Upvotes: 0 <issue_comment>username_5: This line generates error:
```
case when sum(convert(int,SO_SalesOrder.Custom1))>0 then sum(SO_SalesOrder_Line.SubTotal)/sum(convert(int,SO_SalesOrder.Custom1)) as [Average Sales]
```
You should close `case` statement with `end`:
```
case when sum(convert(int,SO_SalesOrder.Custom1))>0 then sum(SO_SalesOrder_Line.SubTotal)/sum(convert(int,SO_SalesOrder.Custom1)) end as [Average Sales]
```
Upvotes: 0
|
2018/03/16
| 1,270 | 4,658 |
<issue_start>username_0: I am using `react-chartjs-2` for visualizing data.
I want to make a nested doughnut chart.
<https://jsfiddle.net/moe2ggrd/152/> this link shows how I want to visualize two different datasets.
Above example shows that if I use `tooltip` to label each data, it creates nested doughnut chart with correct name. However, when I try to make it work in my project, it only shows one doughnut chart.
Below is my render function for rendering doughnut chart.
```
render() {
const data = {
datasets: [
{
data: [1, 2, 3],
labels: ["category1", "category2", "category3"],
backgroundColor: [
"#79CAF2",
"#80DEEA",
"#A5D6A7",
],
hoverBackgroundColor: [
"#31B2F2",
"#00BCD4",
"#4CAF50",
]
},
{
data: [1, 2, 3, 4, 5],
labels: ["sub1", "sub2", "sub3", "sub4", "sub5"],
backgroundColor: [
"#79CAF2",
"#80DEEA",
"#A5D6A7",
"#C5E1A5",
"#FFF59D",
],
hoverBackgroundColor: [
"#31B2F2",
"#00BCD4",
"#4CAF50",
"#8BC34A",
"#FFEB3B",
]
},
]
};
const options = {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var dataset = data.datasets[tooltipItem.datasetIndex];
var index = tooltipItem.index;
return dataset.labels[index] + ': ' + dataset.data[index];
},
}
}
}
return (
)
}
```
And this is screenshot of graph.
[](https://i.stack.imgur.com/Rq8tq.png)
Why doesn't it render two graphs? any suggestions ?
--- Edit
I also have tried not having `tooltips` at all. In this case, two doughnut chart are rendered correctly but each label for data becomes undefined.<issue_comment>username_1: You need to add a different label for each chart :
```
datasets: [
{
label: "chart1",
data: [1, 2, 3],
labels: ["category1", "category2", "category3"],
backgroundColor: [
"#79CAF2",
"#80DEEA",
"#A5D6A7",
],
hoverBackgroundColor: [
"#31B2F2",
"#00BCD4",
"#4CAF50",
]
},
{
label: "chart2",
data: [1, 2, 3, 4, 5],
labels: ["sub1", "sub2", "sub3", "sub4", "sub5"],
backgroundColor: [
"#79CAF2",
"#80DEEA",
"#A5D6A7",
"#C5E1A5",
"#FFF59D",
],
hoverBackgroundColor: [
"#31B2F2",
"#00BCD4",
"#4CAF50",
"#8BC34A",
"#FFEB3B",
]
},
]
```
Upvotes: 2 <issue_comment>username_2: The issue is with the first dataset being copied over the other dataset because the library cannot identify the difference between the two. And that is because there is no specification of unique keys (either **key** or **label**) for them.
While working with multiple datasets in the *react-chartjs-2* library, the library needs to track the changes in the dataset series at any event that triggers re-rendering of the chart (such as tooltips, updating charts on onClick events, etc.).
In such cases, you can do one of the following:
* Add the `label` property on each dataset (by default, the library treats this as the key to identify the datasets.). These labels should be unique for each dataset.
```
render() {
const data = {
datasets: [
{
label:"chart1",
data: [1, 2, 3],
...
},
{
label:"chart2",
data: [1, 2, 3, 4, 5],
...
},
]
};
...
return (
)
}
```
* (Recommended) Add the `key` property on each dataset that specifies a
unique string. Add `datasetKeyProvider` prop to the chart component.
Then pass a function to the `datasetKeyProvider` prop that returns the unique key of each dataset.
```
render() {
const data = {
datasets: [
{
key:"D1",
label:"chart1",
data: [1, 2, 3],
...
},
{
key:"D2",
label:"chart2",
data: [1, 2, 3, 4, 5],
...
},
]
};
...
getDatasetKey = (d) => {return d.key};
return (
)
}
```
Upvotes: 0
|
2018/03/16
| 608 | 2,279 |
<issue_start>username_0: I am using the `ref.on()` function to monitor the change in firebase nodes,
but there is a problem, `ref.on()` gives whole database record.
How can I get only those rows/nodes whose state is changed
```
function watch()
{
riderequests.once('value', function(snapshot)
{
alert("change");
var newrequest = snapshot.val();
}
}
```<issue_comment>username_1: To only get the specific row/node that changed, then inside your `ref()` you need to reference those nodes, example if you have this:
```
users
userid
name:peter
userid
name: john
```
then to only get the changed node, you can do this:
```
ref().child("user").child(userid); //this will only give you the change in the logged in userid node
```
Also, you can just use a query like:
```
orderByChild("userid").equalTo(username);
```
which will give you only that specific node.
`on`
>
> Listens for data changes at a particular location.
>
>
>
<https://firebase.google.com/docs/reference/js/firebase.database.Reference#on>
You can also access a specific node change by doing this when retrieving:
```
var newrequest = snapshot.val().name;
```
assuming `name` is a node in your firebase database.
Upvotes: 2 <issue_comment>username_2: Firebase provide events `child_added`, `child_changed`, `child_removed` for handling different events of adding, modifying and removing a child node from firebase. Read this [link](https://firebase.google.com/docs/database/admin/retrieve-data#child-changed).
According to Firebase docs:-
>
> The child\_changed event is triggered any time a child node is
> modified. This includes any modifications to descendants of the child
> node. It is typically used in conjunction with child\_added and
> child\_removed to respond to changes to a list of items. The snapshot
> passed to the event callback contains the updated data for the child.
>
>
>
For getting the details of changed nodes use `child_changed` event. Basically this events fires whenever a child node is changed. It will result the snapshot of changed node.
```
riderequests.on('child_changed', function(snapshot){
var newrequest = snapshot.val();
console.log(newrequest);
});
```
Upvotes: 1 [selected_answer]
|
2018/03/16
| 1,319 | 4,629 |
<issue_start>username_0: On this example, the promise that i created works ok.
But the promise from the google api don't work.
It says that the `this.youtube` is undefined
*index.html*
*app.component.html*
```
custom Promise
---
youtube Promise
```
*app.component.ts*
```
import { Component } from '@angular/core';
import { } from '@types/gapi.client.youtube';
import { } from '@types/gapi.auth2';
export class AppComponent {
name = 'Angular 5';
youtube = 'youtube';
egPromise(){
return new Promise((resolve, reject) => {
setTimeout(function(){
resolve();
}, 1000);
});
}
customPromise(){
this.egPromise().then( () => {
this.name = 'from .then angular 5'
});
}
customClick(){
this.customPromise();
}
/\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*/
youtubePromise(){
gapi.client.init({
apiKey: 'key',
clientId: 'id',
scope: "https://www.googleapis.com/auth/youtube.readonly",
discoveryDocs: [
"https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest"
]
}).then(() => {
this.youtube = 'from .then youtube'
});
}
youtubeClick(){
gapi.load('client:auth2', this.youtubePromise);
}
```
Edit: Solution/Explanation
--------------------------
With the help of @vivek-doshi
I found this post searching "bind this"
<https://www.sitepoint.com/bind-javascripts-this-keyword-react/>
And as the post explain
"it’s not always clear what this is going to refer to in your code, especially when dealing with callback functions, whose callsites you have no control over."
Since I'm working with the google API and i have no control over that code.
"This is because when the callback to the promise is called, the internal context of the function is changed and this references the wrong object."
And the function to load the library use a callback function, and don't even crossed my mind that the first callback was the problem.
So using the ES2015 Fat Arrows function, as the post says.
"they always use the value of this from the enclosing scope." ... "Regardless of how many levels of nesting you use, arrow functions will always have the correct context."
So instead of creating `binding` and `self` and `that` and `wherever`, I think that is more clean the use of `=>`
Other thing that it was confunsing me is that the google api aks for a callback with no argument.
So if you try to use
`const that = this;
gapi.load('client:auth2', this.start(that) );`
It will complain.
But using `gapi.load('client:auth2', () => this.start() );` I'm not passing an argument.
This things could be simple for a lot of people, but since I'm learning, I will try to make it simple for others that are learning too.
Thanks everyone.<issue_comment>username_1: To only get the specific row/node that changed, then inside your `ref()` you need to reference those nodes, example if you have this:
```
users
userid
name:peter
userid
name: john
```
then to only get the changed node, you can do this:
```
ref().child("user").child(userid); //this will only give you the change in the logged in userid node
```
Also, you can just use a query like:
```
orderByChild("userid").equalTo(username);
```
which will give you only that specific node.
`on`
>
> Listens for data changes at a particular location.
>
>
>
<https://firebase.google.com/docs/reference/js/firebase.database.Reference#on>
You can also access a specific node change by doing this when retrieving:
```
var newrequest = snapshot.val().name;
```
assuming `name` is a node in your firebase database.
Upvotes: 2 <issue_comment>username_2: Firebase provide events `child_added`, `child_changed`, `child_removed` for handling different events of adding, modifying and removing a child node from firebase. Read this [link](https://firebase.google.com/docs/database/admin/retrieve-data#child-changed).
According to Firebase docs:-
>
> The child\_changed event is triggered any time a child node is
> modified. This includes any modifications to descendants of the child
> node. It is typically used in conjunction with child\_added and
> child\_removed to respond to changes to a list of items. The snapshot
> passed to the event callback contains the updated data for the child.
>
>
>
For getting the details of changed nodes use `child_changed` event. Basically this events fires whenever a child node is changed. It will result the snapshot of changed node.
```
riderequests.on('child_changed', function(snapshot){
var newrequest = snapshot.val();
console.log(newrequest);
});
```
Upvotes: 1 [selected_answer]
|
2018/03/16
| 1,244 | 3,870 |
<issue_start>username_0: Using a bash script, I'm trying to iterate through a text file that only has around 700 words, line-by-line, and run a case-insensitive grep search in the current directory using that word on particular files. To break it down, I'm trying to output the following to a file:
>
> 1. Append a newline to a file, then the searched word, then another newline
> 2. Append the results of the grep command using that search
> 3. Repeat steps 1 and 2 until all words in the list are exhausted
>
>
>
So for example, if I had this list.txt:
```
search1
search2
```
I'd want the results.txt to be:
```
search1:
grep result here
search2:
grep result here
```
I've found some answers throughout the stack exchanges on how to do this and have come up with the following implementation:
```
#!/usr/bin/bash
while IFS = read -r line;
do
"\n$line:\n" >> "results.txt";
grep -i "$line" *.in >> "results.txt";
done < "list.txt"
```
For some reason, however, this (and the numerous variants I've tried) isn't working. Seems trivial, but I'd it's been frustrating me beyond belief. Any help is appreciated.<issue_comment>username_1: Possible problems:
1. bash path - use `/bin/bash` path instead of `/usr/bin/bash`
2. blank spaces - remove `' '` after `IFS`
3. echo - use `-e` option for handling escape characters (here: `'\n'`)
4. semicolons - not required at end of line
Try following script:
```
#!/bin/bash
while IFS= read -r line; do
echo -e "$line:\n" >> "results.txt"
grep -i "$line" *.in >> "results.txt"
done < "list.txt"
```
Upvotes: 0 <issue_comment>username_2: You do not even need to write a bash script for this purpose:
**INPUT FILES:**
```
$ more file?.in
::::::::::::::
file1.in
::::::::::::::
abc
search1
def
search3
::::::::::::::
file2.in
::::::::::::::
search2
search1
abc
def
::::::::::::::
file3.in
::::::::::::::
abc
search1
search2
def
search3
```
**PATTERN FILE:**
```
$ more patterns
search1
search2
search3
```
**CMD:**
```
$ grep -inf patterns file*.in | sort -t':' -k3 | awk -F':' 'BEGIN{OFS=FS}{if($3==buffer){print $1,$2}else{print $3; print $1,$2}buffer=$3}'
```
**OUTPUT:**
```
search1
file1.in:2
file2.in:2
file3.in:2
search2
file2.in:1
file3.in:3
search3
file1.in:4
file3.in:5
```
**EXPLANATIONS:**
* `grep -inf patterns file*.in` will grep all the file\*.in with all the patterns located in patterns file thanks to `-f` option, using `-i` forces insensitive case, `-n` will add the line numbers
* `sort -t':' -k3` you sort the output with the 3rd column to regroup patterns together
* `awk -F':' 'BEGIN{OFS=FS}{if($3==buffer){print $1,$2}else{print $3; print $1,$2}buffer=$3}'` then `awk` will print the display that you want by using `:` as Field Separator and Output Field Separator, you use a buffer variable to save the pattern (3rd field) and you print the pattern whenever it changes (`$3!=buffer`)
Upvotes: 0 <issue_comment>username_3: Your script would work if you changed it to:
```
while IFS= read -r line; do
printf '\n%s:\n' "$line"
grep -i "$line" *.in
done < list.txt > results.txt
```
but it'd be extremely slow. See <https://unix.stackexchange.com/questions/169716/why-is-using-a-shell-loop-to-process-text-considered-bad-practice> for why you should think long and hard before writing a shell loop just to manipulate text. The standard UNIX tool for manipulating text is awk:
```
awk '
NR==FNR { words2matches[$0]; next }
{
for (word in words2matches) {
if ( index(tolower($0),tolower(word)) ) {
words2matches[word] = words2matches[word] $0 ORS
}
}
}
END {
for (word in words2matches) {
print word ":" ORS words2matches[word]
}
}
' list.txt *.in > results.txt
```
The above is untested of course since you didn't provide sample input/output we could test against.
Upvotes: 2 [selected_answer]
|
2018/03/16
| 1,133 | 3,441 |
<issue_start>username_0: I have two lists, which are like following. I am looking for an output where every row of dat1 will match on complete column in dat, and on the basis of that, I will get the results
```
dat <- data.frame(v=c('apple', 'le123', 'app', 'being', 'aple',"beiling"))
dat1 <- data.frame(v1=c('app','123', 'be'))
```
I have tried following two alternatives but without success
```
test <- mapply(grepl, pattern=dat1$v1, x=dat$v)
str_detect(as.character(dat$v),dat1)
```
the output I am getting is
```
TRUE TRUE FALSE FALSE FALSE TRUE
```
but the desired output I am looking for is
```
TRUE TRUE TRUE TRUE FALSE TRUE
```
How can I go ahead with this, every help is important<issue_comment>username_1: Possible problems:
1. bash path - use `/bin/bash` path instead of `/usr/bin/bash`
2. blank spaces - remove `' '` after `IFS`
3. echo - use `-e` option for handling escape characters (here: `'\n'`)
4. semicolons - not required at end of line
Try following script:
```
#!/bin/bash
while IFS= read -r line; do
echo -e "$line:\n" >> "results.txt"
grep -i "$line" *.in >> "results.txt"
done < "list.txt"
```
Upvotes: 0 <issue_comment>username_2: You do not even need to write a bash script for this purpose:
**INPUT FILES:**
```
$ more file?.in
::::::::::::::
file1.in
::::::::::::::
abc
search1
def
search3
::::::::::::::
file2.in
::::::::::::::
search2
search1
abc
def
::::::::::::::
file3.in
::::::::::::::
abc
search1
search2
def
search3
```
**PATTERN FILE:**
```
$ more patterns
search1
search2
search3
```
**CMD:**
```
$ grep -inf patterns file*.in | sort -t':' -k3 | awk -F':' 'BEGIN{OFS=FS}{if($3==buffer){print $1,$2}else{print $3; print $1,$2}buffer=$3}'
```
**OUTPUT:**
```
search1
file1.in:2
file2.in:2
file3.in:2
search2
file2.in:1
file3.in:3
search3
file1.in:4
file3.in:5
```
**EXPLANATIONS:**
* `grep -inf patterns file*.in` will grep all the file\*.in with all the patterns located in patterns file thanks to `-f` option, using `-i` forces insensitive case, `-n` will add the line numbers
* `sort -t':' -k3` you sort the output with the 3rd column to regroup patterns together
* `awk -F':' 'BEGIN{OFS=FS}{if($3==buffer){print $1,$2}else{print $3; print $1,$2}buffer=$3}'` then `awk` will print the display that you want by using `:` as Field Separator and Output Field Separator, you use a buffer variable to save the pattern (3rd field) and you print the pattern whenever it changes (`$3!=buffer`)
Upvotes: 0 <issue_comment>username_3: Your script would work if you changed it to:
```
while IFS= read -r line; do
printf '\n%s:\n' "$line"
grep -i "$line" *.in
done < list.txt > results.txt
```
but it'd be extremely slow. See <https://unix.stackexchange.com/questions/169716/why-is-using-a-shell-loop-to-process-text-considered-bad-practice> for why you should think long and hard before writing a shell loop just to manipulate text. The standard UNIX tool for manipulating text is awk:
```
awk '
NR==FNR { words2matches[$0]; next }
{
for (word in words2matches) {
if ( index(tolower($0),tolower(word)) ) {
words2matches[word] = words2matches[word] $0 ORS
}
}
}
END {
for (word in words2matches) {
print word ":" ORS words2matches[word]
}
}
' list.txt *.in > results.txt
```
The above is untested of course since you didn't provide sample input/output we could test against.
Upvotes: 2 [selected_answer]
|
2018/03/16
| 1,905 | 5,369 |
<issue_start>username_0: I'm using ros kinetic and Ubuntu 16.04
I'm trying to do run [this project](https://github.com/erlerobot/gym-gazebo) but not running inside a Docker container.
After, I had done
```
user@user-HP-Pavilion-15-Notebook-PC:~/gym-gazebo/gym_gazebo/envs/installation/catkin_ws$ catkin_make
user@user-HP-Pavilion-15-Notebook-PC:~/gym-gazebo/gym_gazebo/envs/installation$ bash setup_kinetic.bash
user@user-HP-Pavilion-15-Notebook-PC:~/gym-gazebo/gym_gazebo/envs/installation$ bash turtlebot_setup.bash
user@user-HP-Pavilion-15-Notebook-PC:~/gym-gazebo/examples/turtlebot$ python circuit2_turtlebot_lidar_qlearn.py
```
Then, it comes out the following error:
```
... logging to /home/user/.ros/log/3ac6e572-28a3-11e8-9aba-142d27dccbb5/roslaunch-user-HP-Pavilion-15-Notebook-PC-6853.log
Checking log directory for disk usage. This may take awhile.
Press Ctrl-C to interrupt
Done checking log file disk usage. Usage is <1GB.
started roslaunch server http://user-HP-Pavilion-15-Notebook-PC:37855/
ros_comm version 1.12.12
SUMMARY
========
PARAMETERS
* /rosdistro: kinetic
* /rosversion: 1.12.12
NODES
auto-starting new master
process[master]: started with pid [6864]
ROS_MASTER_URI=http://user-HP-Pavilion-15-Notebook-PC:11311/
setting /run_id to 3ac6e572-28a3-11e8-9aba-142d27dccbb5
process[rosout-1]: started with pid [6884]
started core service [/rosout]
Roscore launched!
Gazebo launched!
... logging to /home/user/.ros/log/3ac6e572-28a3-11e8-9aba-142d27dccbb5/roslaunch-user-HP-Pavilion-15-Notebook-PC-6908.log
Checking log directory for disk usage. This may take awhile.
Press Ctrl-C to interrupt
Done checking log file disk usage. Usage is <1GB.
while processing /home/user/gym-gazebo/gym_gazebo/envs/installation/catkin_ws/src/turtlebot_simulator/turtlebot_gazebo/launch/includes/kobuki.launch.xml:
Invalid tag: Cannot load command parameter [robot_description]: command [/opt/ros/kinetic/lib/xacro/xacro --inorder '/home/user/gym-gazebo/gym_gazebo/envs/installation/catkin_ws/src/turtlebot/turtlebot_description/robots/kobuki_hexagons_asus_xtion_pro.urdf.xacro'] returned with code [2].
Param xml is
The traceback for the exception was written to the log file
```
And the kobuki.launch.xml :
```html
```
This is what I get after run `xacro --inorder /home/user/gym-gazebo/gym_gazebo/envs/installation/catkin_ws/src/turtlebot/turtlebot_description/robots/kobuki_hexagons_asus_xtion_pro.urdf.xacro`
```
option --inorder not recognized
Usage: xacro.py [-o ]
xacro.py --deps Prints dependencies
xacro.py --includes Only evalutes includes
```
I'm still new with ROS. Did I miss something?<issue_comment>username_1: Possible problems:
1. bash path - use `/bin/bash` path instead of `/usr/bin/bash`
2. blank spaces - remove `' '` after `IFS`
3. echo - use `-e` option for handling escape characters (here: `'\n'`)
4. semicolons - not required at end of line
Try following script:
```
#!/bin/bash
while IFS= read -r line; do
echo -e "$line:\n" >> "results.txt"
grep -i "$line" *.in >> "results.txt"
done < "list.txt"
```
Upvotes: 0 <issue_comment>username_2: You do not even need to write a bash script for this purpose:
**INPUT FILES:**
```
$ more file?.in
::::::::::::::
file1.in
::::::::::::::
abc
search1
def
search3
::::::::::::::
file2.in
::::::::::::::
search2
search1
abc
def
::::::::::::::
file3.in
::::::::::::::
abc
search1
search2
def
search3
```
**PATTERN FILE:**
```
$ more patterns
search1
search2
search3
```
**CMD:**
```
$ grep -inf patterns file*.in | sort -t':' -k3 | awk -F':' 'BEGIN{OFS=FS}{if($3==buffer){print $1,$2}else{print $3; print $1,$2}buffer=$3}'
```
**OUTPUT:**
```
search1
file1.in:2
file2.in:2
file3.in:2
search2
file2.in:1
file3.in:3
search3
file1.in:4
file3.in:5
```
**EXPLANATIONS:**
* `grep -inf patterns file*.in` will grep all the file\*.in with all the patterns located in patterns file thanks to `-f` option, using `-i` forces insensitive case, `-n` will add the line numbers
* `sort -t':' -k3` you sort the output with the 3rd column to regroup patterns together
* `awk -F':' 'BEGIN{OFS=FS}{if($3==buffer){print $1,$2}else{print $3; print $1,$2}buffer=$3}'` then `awk` will print the display that you want by using `:` as Field Separator and Output Field Separator, you use a buffer variable to save the pattern (3rd field) and you print the pattern whenever it changes (`$3!=buffer`)
Upvotes: 0 <issue_comment>username_3: Your script would work if you changed it to:
```
while IFS= read -r line; do
printf '\n%s:\n' "$line"
grep -i "$line" *.in
done < list.txt > results.txt
```
but it'd be extremely slow. See <https://unix.stackexchange.com/questions/169716/why-is-using-a-shell-loop-to-process-text-considered-bad-practice> for why you should think long and hard before writing a shell loop just to manipulate text. The standard UNIX tool for manipulating text is awk:
```
awk '
NR==FNR { words2matches[$0]; next }
{
for (word in words2matches) {
if ( index(tolower($0),tolower(word)) ) {
words2matches[word] = words2matches[word] $0 ORS
}
}
}
END {
for (word in words2matches) {
print word ":" ORS words2matches[word]
}
}
' list.txt *.in > results.txt
```
The above is untested of course since you didn't provide sample input/output we could test against.
Upvotes: 2 [selected_answer]
|
2018/03/16
| 1,012 | 3,148 |
<issue_start>username_0: I'm having an annoying problem with Bootstrap glyphicon icons. The icon has white rectangular background around the image and it looks very ugly when used on top of colored backgrounds. Example of problem:
[](https://i.stack.imgur.com/z4uHQ.png)
How exactly can I change this to be transparent with the red background?<issue_comment>username_1: Possible problems:
1. bash path - use `/bin/bash` path instead of `/usr/bin/bash`
2. blank spaces - remove `' '` after `IFS`
3. echo - use `-e` option for handling escape characters (here: `'\n'`)
4. semicolons - not required at end of line
Try following script:
```
#!/bin/bash
while IFS= read -r line; do
echo -e "$line:\n" >> "results.txt"
grep -i "$line" *.in >> "results.txt"
done < "list.txt"
```
Upvotes: 0 <issue_comment>username_2: You do not even need to write a bash script for this purpose:
**INPUT FILES:**
```
$ more file?.in
::::::::::::::
file1.in
::::::::::::::
abc
search1
def
search3
::::::::::::::
file2.in
::::::::::::::
search2
search1
abc
def
::::::::::::::
file3.in
::::::::::::::
abc
search1
search2
def
search3
```
**PATTERN FILE:**
```
$ more patterns
search1
search2
search3
```
**CMD:**
```
$ grep -inf patterns file*.in | sort -t':' -k3 | awk -F':' 'BEGIN{OFS=FS}{if($3==buffer){print $1,$2}else{print $3; print $1,$2}buffer=$3}'
```
**OUTPUT:**
```
search1
file1.in:2
file2.in:2
file3.in:2
search2
file2.in:1
file3.in:3
search3
file1.in:4
file3.in:5
```
**EXPLANATIONS:**
* `grep -inf patterns file*.in` will grep all the file\*.in with all the patterns located in patterns file thanks to `-f` option, using `-i` forces insensitive case, `-n` will add the line numbers
* `sort -t':' -k3` you sort the output with the 3rd column to regroup patterns together
* `awk -F':' 'BEGIN{OFS=FS}{if($3==buffer){print $1,$2}else{print $3; print $1,$2}buffer=$3}'` then `awk` will print the display that you want by using `:` as Field Separator and Output Field Separator, you use a buffer variable to save the pattern (3rd field) and you print the pattern whenever it changes (`$3!=buffer`)
Upvotes: 0 <issue_comment>username_3: Your script would work if you changed it to:
```
while IFS= read -r line; do
printf '\n%s:\n' "$line"
grep -i "$line" *.in
done < list.txt > results.txt
```
but it'd be extremely slow. See <https://unix.stackexchange.com/questions/169716/why-is-using-a-shell-loop-to-process-text-considered-bad-practice> for why you should think long and hard before writing a shell loop just to manipulate text. The standard UNIX tool for manipulating text is awk:
```
awk '
NR==FNR { words2matches[$0]; next }
{
for (word in words2matches) {
if ( index(tolower($0),tolower(word)) ) {
words2matches[word] = words2matches[word] $0 ORS
}
}
}
END {
for (word in words2matches) {
print word ":" ORS words2matches[word]
}
}
' list.txt *.in > results.txt
```
The above is untested of course since you didn't provide sample input/output we could test against.
Upvotes: 2 [selected_answer]
|
2018/03/16
| 728 | 1,939 |
<issue_start>username_0: I have the following code:
```
use strict;
use warnings;
my $find = "(.*\s+)(subject:)(.*)(_1)(\s+.*)";
my $replace = '"\nsubject: \t\t$3_2"';
my $var_1 = "Time: 1000-1200 subject: Physic_1 Class: Room A";
my $var_2 = "Time: 1000-1200 subject: Math_1 Class: Room A";
$var_1 =~ s/$find/$replace/ee;
$var_2 =~ s/$find/$replace/ee;
print $var_1."\n";
print $var_2."\n";
```
I expect the output only extract the subject and change \_1 to \_2 like:
```
Output:
subject: Physic_2
subject: Math_2
```
However, what I get is:
```
Output:
Unrecognized escape \s passed through at test.pl line 20.
Unrecognized escape \s passed through at test.pl line 20.
Time: 1000-1200 subject: Physic_1 Class: Room A
Time: 1000-1200 subject: Math_1 Class: Room A
```
How can I escape those \t, \s+, \n as on string variable as perl regex pattern?
UPDATE:
If I do something like this:
```
my $pattern = 's/(.*\s+)(subject:)(.*)(_1)(\s+.*)/\nsubject: \t\t$3_2/g';
my $var = "Time: 1000-1200 subject: Physic_1 Class: Room A";
$var =~ $pattern;
print $var."\n";
```
It give the output, seem like nothing change:
```
Time: 1000-1200 subject: Physic_1 Class: Room A
```<issue_comment>username_1: You can do that in the first line exactly as you did it in the second line:
```
my $find = '(.*\s+)(subject:)(.*)(_1)(\s+.*)';
```
Output:
```
subject: Physic_2
subject: Math_2
```
Upvotes: 0 <issue_comment>username_2: Double quotes interpolate backslashed characters. `\s` has a special meaning in a regex, but not in doublequotes - hence the warning. Use single quotes instead.
```
my $find = '(.*\s+)(subject:)(.*)(_1)(\s+.*)';
```
or, if you need double quotes for some other reasons, double the backslashes that should survive in the regex:
```
my $find = "(.*\\s+)(subject:)(.*)(_1)(\\s+.*)";
```
Upvotes: 2
|
2018/03/16
| 697 | 2,631 |
<issue_start>username_0: I'm making an Chrome Extension which interacts with Gmail API.
Basically it needs to extract email senders from emails that match some keyword.
Problem is that sometimes there are over 10K emails matching this keyword.
I utilize `gapi.client.gmail.users.messages.list` to fetch all emails that match entered keyword, but this only returns email and thread IDs, so I need to call `gapi.client.gmail.users.messages.get` for each email ID retrieved from `messages.list`.
So there are over 10K requests to Gmail API, and I run into `ERR_INSUFFICIENT_RESOURCES` error in Chrome. To prevent this error, I set some timeout between calls to `messages.get` but then it would take ages to complete...
Is there some recommended way to get this amount of emails from Gmail API?<issue_comment>username_1: This is unfortunately how the Gmail api works.
You are going to have to do a [messages.list](https://developers.google.com/gmail/api/v1/reference/users/messages/list) followed by a [message.get](https://developers.google.com/gmail/api/v1/reference/users/messages/get) if you want to get more details about the message.
There is a limit to how fast you can make requests against the api you just need to slow things down if you get the error. Flooding error messages are used to ensure that we all get to use the api and one person doesnt over load things by making to many requests.
Upvotes: 0 <issue_comment>username_2: According to [documentation](https://developers.google.com/gmail/api/guides/batch), one way to improve performance is by batching requests. Currently it has a limit of 100 requests per batch, but it is still 100 times fewer requests.
EDIT: Also you can use `fields` parameter in query to request the fields you want from the messages, since both [messages.list](https://developers.google.com/gmail/api/v1/reference/users/messages/list) and [messages.get](https://developers.google.com/gmail/api/v1/reference/users/messages/get) can return a whole [users.messages Resource](https://developers.google.com/gmail/api/v1/reference/users/messages#resource).
For example:
```
var xhr = new XMLHttpRequest;
xhr.onload = () => {
var resp = JSON.parse(xhr.response);
var wholeFirstMessage = atob(resp.messages[0].raw);
console.log(wholeFirstMessage);
};
xhr.open("GET", "https://www.googleapis.com/gmail/v1/users/userId/messages?fields=messages(id,threadId,raw)");
xhr.send();
```
NOTE: The code sample above ignores `pageToken` and `maxResults` from the XHR parameters for simplicity' sake. Those parameters would be needed for a long list of messages.
Upvotes: 2 [selected_answer]
|
2018/03/16
| 805 | 2,881 |
<issue_start>username_0: I have multiple element with the same class. When I use this method below, it does not work.
```
$(".tab-content")[index].addClass("active-content");
```
My code:
HTML:
```
* [Lodon](javascript:;)
* [Paris](javascript:;)
* [Tokyo](javascript:;)
### Lodon
London is the capital of England
### Paris
Paris is the capital of France
### Tokyo
Tokyo is the capital of Japan
```
And JS
```
$(".tag li").click(function () {
var index = $(this).index();
$(".tab-content")[index].addClass("active-content");
});
```
<https://codepen.io/WillyIsCoding/pen/KoMxMJ><issue_comment>username_1: A small change might help you
```
$(".tag li").click(function () {
var index = $(this).index();
$(".tab-content").eq(index).addClass("active-content");
});
```
Upvotes: 2 <issue_comment>username_2: Check out this one
```
$(".tag li").click(function () {
var index = $(this).index();
$(".tab-content").removeClass("active-content");
$($(".tab-content")[index]).addClass("active-content");
});
```
In addition to adding active class to your tab content, make sure we remove active class on the remaining.(again its based on our requirement)
Upvotes: 1 <issue_comment>username_3: That's because `.addClass()` is a jQuery-method, not a native JS-method.
And when you use `$(".tab-content")[index]`, you are selecting the true DOM-element within the jQuery-object. The same kind of element you get when you use `document.getElementById("id")`.
And just like when you would combine that with a jQuery-method:
`document.getElementById("id").addClass("class");`
this too will generate an error and not work:
`$(".tab-content")[index].addClass("class");`
In order to get this working, you have to stick with jQuery. Luckily, jQuery has a method to do just that: [**`.eq()`**](https://api.jquery.com/eq/). Just like `.addClass()`, this is a jQuery-method so you can use it in the same manner.
---
**SOLUTION:** `$(".tab-content").eq(index).addClass("active-content");`
This method will select the element at the given index of the complete set of matching elements, and only perform the action on that one element.
---
After a bit of fiddling around, I came up with this alternative implementation of your code.
I thought I'd put it on here, maybe someone will find it useful:
```js
$(".select").change(function() {
$(".tab.active").removeClass("active").addClass("hidden");
$(".tab").eq($(this).children("option:selected").index()).removeClass("hidden").addClass("active");
});
```
```css
.tab.hidden {display:none;}
```
```html
London
Paris
Tokyo
### London
London is the capital of England
### Paris
Paris is the capital of France
### Tokyo
Tokyo is the capital of Japan
```
*jsfiddle: <https://jsfiddle.net/jdea7mc8/>*
Upvotes: 5 [selected_answer]
|
2018/03/16
| 1,033 | 4,531 |
<issue_start>username_0: I have created an activity which is transparent. The background is click-able, anything can be performed on mobile with activity opened. Now I want to set click listeners on the `textview` that is inside the transparent activity. I have searched but didn't find anything.
Here is the code to my layout :
```
xml version="1.0" encoding="utf-8"?
```
Here is the `Java` code that i am using :
```
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.tv);
tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "clicked", Toast.LENGTH_SHORT).show();
}
});
}
```
[](https://i.stack.imgur.com/Uk0XZ.jpg)
I want the hello world to be click-able as well as other apps for example, Chrome, messaging, menu etc.<issue_comment>username_1: What you are trying to achieve is not possible with an activity. When you use activity it covers all of the screen and any touch done on screen will only accessible by that activity(If it transparent or not, this does not matter).
My suggestion is, try to use a widget instead of activity. It may fulfill your requirement. I suggest you to use any floating widget or permanently place that widget into center of the screen.
Below link may helpful for you.
[Chat Widget](http://myandroidtuts.blogspot.in/2013/05/facebook-chat-heads-feature.html)
[Floating widget](http://www.androhub.com/android-floating-widget-like-facebook-messenger-chat-head/)
Upvotes: 3 [selected_answer]<issue_comment>username_2: you don't have to use activity for this purpose. you just call it form service class.
```
windowManager2 = (WindowManager)getSystemService(WINDOW_SERVICE);
LayoutInflater layoutInflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view=layoutInflater.inflate(R.layout.popup_incoming, null);
params=new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity=Gravity.CENTER|Gravity.CENTER;
params.x=0;
params.y=0;
windowManager2.addView(view, params);
view.setOnTouchListener(new View.OnTouchListener() {
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;
@Override public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
initialX = params.x;
initialY = params.y;
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
return true;
case MotionEvent.ACTION_UP:
return true;
case MotionEvent.ACTION_MOVE:
params.x = initialX + (int) (event.getRawX() - initialTouchX);
params.y = initialY + (int) (event.getRawY() - initialTouchY);
windowManager2.updateViewLayout(view, params);
return true;
}
return false;
}
});
txtNameIncoming = (TextView)view.findViewById(R.id.NameIncoming);
txtIncomingnumber = (TextView)view.findViewById(R.id.txtIncomingnumber);
txtIncomingnumber.setText("You have Incoming Call from " + PhoneStateReceiver.savedNumber);
btnClose = (Button) view.findViewById(R.id.buttonClose);
btnClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
clearView(v.getContext());
}
});
```
xml will be:
```
xml version="1.0" encoding="utf-8"?
```
now modify it for yourself.
Upvotes: 1
|
2018/03/16
| 173 | 697 |
<issue_start>username_0: How can I troubleshoot an apk file which I created with react-native and Android Studio? It works to run in the expo dev environment. Then I ejected it into Android Studio and build an apk and build succeeded. But when I actually try and load the apk in my Samsung S8 phone it says that a problem occurred analysing the package. How can I proceed?<issue_comment>username_1: Just to double check, is the unknown sources / developer mode enabled on the S8?
<https://www.technipages.com/galaxy-note8-s8-install-apk-file>
Upvotes: 1 <issue_comment>username_2: The solution was to install it from "my files" instead of from the cache directly from the download link
Upvotes: 0
|
2018/03/16
| 409 | 2,047 |
<issue_start>username_0: This is just a simple way of registering new account credentials. My problem is that whenever I click the save button, the data will be saved twice in the database.
[Sample image of the double entry in the database.](https://i.stack.imgur.com/EgKxc.png)
```
using (SqlConnection con = new SqlConnection(conString))
{
try
{
string query = ("INSERT INTO Tbl_Staff (Name,pos,username,password) VALUES (@name,@pos,@username,@password)");
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("@name", textBox1.Text);
cmd.Parameters.AddWithValue("@pos", textBox4.Text);
cmd.Parameters.AddWithValue("@username", textBox2.Text);
cmd.Parameters.AddWithValue("@password", <PASSWORD>);
con.Open();
cmd.ExecuteNonQuery();
int result = cmd.ExecuteNonQuery();
//MessageBox.Show(result.ToString());
// Check Error
if (result > 0)
MessageBox.Show("Credentials has been successfully added.","" ,MessageBoxButtons.OK, MessageBoxIcon.Information);
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
```<issue_comment>username_1: Just to double check, is the unknown sources / developer mode enabled on the S8?
<https://www.technipages.com/galaxy-note8-s8-install-apk-file>
Upvotes: 1 <issue_comment>username_2: The solution was to install it from "my files" instead of from the cache directly from the download link
Upvotes: 0
|
2018/03/16
| 991 | 3,942 |
<issue_start>username_0: We are using kafka 0.10.2.1. The documentation specifies that a buffer is available to send even if it isn't full-
>
> By default a buffer is available to send immediately even if there is additional unused space in the buffer. However if you want to reduce the number of requests you can set linger.ms to something greater than 0.
>
>
>
However, it also says that the producer will attempt to batch requests even if linger time is set to 0ms-
>
> Note that records that arrive close together in time will generally batch together even with linger.ms=0 so under heavy load batching will occur regardless of the linger configuration; however setting this to something larger than 0 can lead to fewer, more efficient requests when not under maximal load at the cost of a small amount of latency.
>
>
>
Intuitively, it seems that any kind of batching would require some linger time, and the only way to achieve a linger time of 0 would be to make the broker call synchronised. Clearly, keeping the linger time at 0 doesn't appear to harm performance as much as blocking on the send call, but seems to have some impact on performance. Can someone clarify what the docs are saying above?<issue_comment>username_1: The docs are saying that even though you set linger time to 0, you might end up with a little bit of batching under load since records are getting added to be sent faster than the send thread can dispatch them. This setting is optimizing for minimal latency. If the measure of performance you really care about is throughput, you'd increase the linger time a bit to batch more and that's what the docs are getting at. Not so much to do with synchronous send in this case. [More in depth info](https://www.confluent.io/blog/optimizing-apache-kafka-deployment/)
Upvotes: 5 [selected_answer]<issue_comment>username_2: With `linger.ms=0` the record is sent as soon as possible and with many requests this may impact the performance. Forcing a little wait by increasing `linger.ms` on moderate/high load will optimize the use of the batch and increase throughput. This depends as well on the record size, the bigger the less can fit in the batch (`batch.size` default is 16Kb).
Basically it is a trade off between number of *number of requests and throughput* and it really depends on your scenario, however sending immediately does not take full advantage of batching and compression (if enabled) and I suggest to run some metrics with different values of `linger.ms` such as 0/5/10/50/200
In general I will suggest to set `linger.ms > 0`
References:
* [KIP-91](https://cwiki.apache.org/confluence/display/KAFKA/KIP-91+Provide+Intuitive+User+Timeouts+in+The+Producer)
* [Nice tutorial from cloudurable](http://cloudurable.com/blog/kafka-tutorial-kafka-producer-advanced-java-examples/index.html)
* [Official Docs v0.10.2](https://kafka.apache.org/0102/documentation.html)
Upvotes: 4 <issue_comment>username_3: I am by far no kafka expert, but these things should be explained easier, otherwise all the metrics read and not going to be understood.
First thing I want to notice is that a *Sender Thread*, which is not the thread you call `producer::send` under, sends *batches* of messages to the cluster. Now if your current batch has a single message inside it, it does not break the rule : it still sends batches, it just happens that there is one single in the current batch. There are metrics that allow you to see how full, on average, is a batch before it was sent.
If there are many batches that senders send that are more empty than full - it's not a good thing. The work it has to do to actually place messages is much more than expensive than the actual message sent and that's why batching exists to begin with.
In such cases, `linger.ms` might help, cause it will allow for a "batch" to stay a little bit more in the RecordAccumulator and thus more batching will happen.
Upvotes: 0
|
2018/03/16
| 1,132 | 4,025 |
<issue_start>username_0: I am trying to get an local asset image loaded into an ui.Image object. But the ui.Image is an abstract class. I basically have this :
```
import 'dart:ui' as ui;
class MyImage implements ui.Image{
int height;
int width;
MyImage(String file){
}
@override
void dispose() {
// TODO: implement dispose
super.dispose();
}
@override
String toString() {
// TODO: implement toString
return super.toString();
}
}
```
Using your code with the function definition Below. The error is at
' ui.Image image = await loadImage(img); ' await is underlined red and tool tip is 'Undefined name 'await' in function body not marked with async.'
```
class TrialApp extends StatefulWidget {
@override
_TrialAppState createState() => new _TrialAppState();
}
class _TrialAppState extends State {
NodeWithSize rootNode;
@override
void initState() {
// TODO: implement initState
super.initState();
rootNode = new NodeWithSize(new Size(400.0, 400.0));
}
@override
Widget build(BuildContext context) {
// define a function that converts the I.Image object into ui.Image
//object
Future loadImage(I.Image img) async {
final Completer imageCompleter = new Completer();
ui.decodeImageFromList(img.getBytes(), (ui.Image img) {
imageCompleter.complete(img);
});
return imageCompleter.future;
}
// Obtain a `I.Image` object from the image file
I.Image img = I.decodeImage(new io.File('images/tile.png').readAsBytesSync());
// Obtain the `ui.Image` from the `I.Image` object
ui.Image image = await loadImage(img);
Sprite myButton = new Sprite.fromImage(image);
rootNode.addChild(myButton);
return new SpriteWidget(rootNode);
}
}
```<issue_comment>username_1: First obtain the image from the assetbundle using [`rootBundle`](https://docs.flutter.io/flutter/services/rootBundle.html). The convert the obtained `ByteData` to `List`. Now you can obtain a `ui.Image` using the `decodeImageFromList` method.
Example:
```
// import statements
import 'dart:async';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:spritewidget/spritewidget.dart';
class TrialApp extends StatefulWidget {
@override
_TrialAppState createState() => new _TrialAppState();
}
class _TrialAppState extends State {
NodeWithSize rootNode = new NodeWithSize(new Size(400.0, 400.0));
@override
void initState() {
super.initState();
init();
}
Future init() async {
rootNode = new NodeWithSize(new Size(400.0, 400.0));
// Read file from assetbundle
final ByteData data = await rootBundle.load('images/tile.png');
// Convert the obtained ByteData into ui.Image
final ui.Image image = await loadImage(new Uint8List.view(data.buffer)); // Uint8List converts the ByteData into List
Sprite myButton = new Sprite.fromImage(image);
rootNode.addChild(myButton);
// notify to redraw with child
setState(() {
rootNode = rootNode;
});
}
// define a function that converts the List into ui.Image object
Future loadImage(List img) async {
final Completer imageCompleter = new Completer();
ui.decodeImageFromList(img, (ui.Image img) {
imageCompleter.complete(img);
});
return imageCompleter.future;
}
@override
Widget build(BuildContext context) {
return new Container(
color: Colors.white,
child: new SpriteWidget(rootNode),
);
}
}
```
Hope that helps!
Upvotes: 1 <issue_comment>username_2: If you are using SpriteWidget you can load images using the `ImageMap` class to save some code. From the SpriteWidget docuementation:
```
ImageMap images = new ImageMap(rootBundle);
// Load a single image
ui.Image image = await images.loadImage('assets/my_image.png');
// Load multiple images
await images.load([
'assets/image\_0.png',
'assets/image\_1.png',
'assets/image\_2.png',
]);
// Access a loaded image from the ImageMap
image = images['assets/image\_0.png'];
```
Upvotes: 1 [selected_answer]
|
2018/03/16
| 278 | 1,004 |
<issue_start>username_0: How to verify Keyboard is opened or not in the screen.That means if Keyboard opened i have to hide or else have to open keyboard.
Using Appium Version : 4.1.0
```
io.appium
java-client
4.1.0
```<issue_comment>username_1: Try below the snippet to identify that Soft Keyboard is opened or closed. Hope it helps!
```
InputMethodManager imm = (InputMethodManager) getActivity()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isAcceptingText()) {
Log("Soft_Keyboard displaying");
//write your requirement here to close SKeyBoard if required
} else {
Log("Soft_Keyboard is not displaying");
//write your requirement here to open SKeyBoard if required
}
```
Upvotes: 0 <issue_comment>username_2: I use the default function provided, "**isKeyboardShown**()"
For iOS
```
getIosDriver().isKeyboardShown();
```
returns true if the keyboarad is open, false otherwise.
<http://appium.io/docs/en/commands/device/keys/is-keyboard-shown/>
Upvotes: 1
|
2018/03/16
| 321 | 1,328 |
<issue_start>username_0: In hdfs sink connector, I need to configure key and value converter at topic level i.e. different topic using different converter . Is it possible ?<issue_comment>username_1: You just need to create different worker config files for the topics you'd like to use different key/value converters.
For example, if you'd like to parse a topic with Avro key then use
```
key.converter=io.confluent.connect.avro.AvroConverter
key.converter.schema.registry.url=http://localhost:8081
```
while for another (say in JSON format without schemas) you can use
```
key.converter=org.apache.kafka.connect.json.JsonConverter
key.converter.schemas.enable=false
```
Then, you can run these worker config files in [distributed mode](https://docs.confluent.io/3.1.0/connect/userguide.html#distributed-worker-configuration).
Upvotes: 0 <issue_comment>username_2: Converters are properties that can be overridden at the Connector level. This means that a Connector instance can override the values that are globally set for converters within the Connect worker's configuration.
Therefore, although a per-topic override is not possible, grouping the topics that use the same converter types, each in a single connector instance, could achieve something close to what you describe in a more practical way.
Upvotes: 1
|
2018/03/16
| 517 | 1,865 |
<issue_start>username_0: // Add Images
var aspect\_ratio = '';
var itemImagesHtml = '';
itemImagesHtml += ' 0) {
aspect\_ratio = images[0]['width'] / images[0]['height'];
itemImagesHtml += 1 / aspect\_ratio \* 100;
} else {
itemImagesHtml += 100;
}
itemImagesHtml += '%;">';
itemImagesHtml += '';
itemImagesHtml += '';
itemImagesHtml += '';
```
var image_size = bcSfFilterConfig.custom.max_height + 'x' + bcSfFilterConfig.custom.max_height;
var max_width = images.length > 0 ? bcSfFilterConfig.custom.max_height * aspect_ratio : 0;
itemImagesHtml += ' + ')';
itemHtml = itemHtml.replace(/{{itemImages}}/g, itemImagesHtml);
```<issue_comment>username_1: You just need to create different worker config files for the topics you'd like to use different key/value converters.
For example, if you'd like to parse a topic with Avro key then use
```
key.converter=io.confluent.connect.avro.AvroConverter
key.converter.schema.registry.url=http://localhost:8081
```
while for another (say in JSON format without schemas) you can use
```
key.converter=org.apache.kafka.connect.json.JsonConverter
key.converter.schemas.enable=false
```
Then, you can run these worker config files in [distributed mode](https://docs.confluent.io/3.1.0/connect/userguide.html#distributed-worker-configuration).
Upvotes: 0 <issue_comment>username_2: Converters are properties that can be overridden at the Connector level. This means that a Connector instance can override the values that are globally set for converters within the Connect worker's configuration.
Therefore, although a per-topic override is not possible, grouping the topics that use the same converter types, each in a single connector instance, could achieve something close to what you describe in a more practical way.
Upvotes: 1
|
2018/03/16
| 881 | 2,895 |
<issue_start>username_0: I am storing all of my items into lines in a text file like so, with the ID at the start
```
1/item name/content/etc
2/item name/content/etc
3/item name/content/etc
4/item name/content/etc
```
This method of storage is for a simple script we are using on a game that is editable by the different users so security really isn't a big deal, or else we would just use mysqli and the like.
I need to be able to print out variable information for a single entry, found by the id at the beginning, and also print say, 3 and 2, in numerical order. So far I am loading them into an array like so
```
$content = file('script/items.txt');
$items = array($content);
```
it throws the whole file into an array like this
```
array(1) {
[0]=> array(4) {
[0]=> string(23) "1/item name/content/etc"
[1]=> string(23) "2/item name/content/etc"
[2]=> string(23) "3/item name/content/etc"
[3]=> string(23) "4/item name/content/etc"
}
}
```
is there an easier way to pick one, or even multiple using just their id so i don't have to store the whole file into the array (it could get big in the future) or is the best way to store them all, loop through the entire array one line at a time, explode them for each /, and them compare is it's in the required items? Thanks.<issue_comment>username_1: You need to use `file()` flags `FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES`
Do like below:-
```
$content = file('script/items.txt',FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
print_r($content);
```
Note:-
Now loop over the array to get records one-by-one.
***Best approach to save data to database table with columns like `id`,`item_name`,`contents` and `extra`***
Upvotes: 2 [selected_answer]<issue_comment>username_2: You can try the below code to read file line by line.
```
$handle = fopen("script/items.txt", "r");
if ($handle) {
while (!feof($handle)) {
$line = fgets($handle)
// do your stuffs.
}
fclose($handle);
} else {
// error opening the file.
}
```
It will not load complete file in memory so you can use this for bigger files as well.
**feof($handle)** It will save you in case you have a line which contains a boolean **false**.
Upvotes: 0 <issue_comment>username_3: You could also use `array_reduce` to store the ID as key into the array.
```
$content = file('script/items.txt',FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$content = array_reduce($content, function ($result, $line) {
list($id, $data) = explode('/', $line, 2) ;
$result[$id] = $data;
return $result;
}, array());
print_r($content);
```
Outputs:
```
Array
(
[1] => item name/content/etc
[2] => item name/content/etc
[3] => item name/content/etc
[4] => item name/content/etc
)
```
So you can get elements using without using a loop:
```
$content[$wanted_id]
```
Upvotes: 0
|
2018/03/16
| 988 | 3,099 |
<issue_start>username_0: I'm trying select the results of a one-to-many relation and get the results in multiple columns. My tables look like:
Table users:
```
+----+----------+
| id | user |
+----+----------+
| 1 | jenny |
| 2 | chris |
| 3 | harry |
+----+----------+
```
Table locations:
```
+----+-------------+
| id | location |
+----+-------------+
| 1 | New York |
| 2 | Washington |
| 3 | Memphis |
| 4 | Dallas |
| 5 | Las Vegas |
+----+-------------+
```
Table user\_locations:
```
+----+---------+-------------+
| id | user_id | location_id |
+----+---------+-------------+
| 1 | 1 | 1 |
| 2 | 1 | 3 |
| 3 | 1 | 5 |
| 4 | 2 | 2 |
| 5 | 2 | 4 |
| 6 | 3 | 4 |
| 7 | 3 | 5 |
| 8 | 3 | 2 |
+----+---------+-------------+
```
The result I'm trying to get is:
```
+---------+-------+------------+------------+------------+
| user_id | user | location_1 | location_2 | location_3 |
+---------+-------+------------+------------+------------+
| 1 | jenny | New York | Memphis | Las Vegas |
| 2 | chris | Washington | Dallas | NULL |
| 3 | harry | Dallas | Las Vegas | Washington |
+---------+-------+------------+------------+------------+
```
I tried several queries with left join and group by but I seem to be getting the first location only.
Thanks in advance.<issue_comment>username_1: You need to use `file()` flags `FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES`
Do like below:-
```
$content = file('script/items.txt',FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
print_r($content);
```
Note:-
Now loop over the array to get records one-by-one.
***Best approach to save data to database table with columns like `id`,`item_name`,`contents` and `extra`***
Upvotes: 2 [selected_answer]<issue_comment>username_2: You can try the below code to read file line by line.
```
$handle = fopen("script/items.txt", "r");
if ($handle) {
while (!feof($handle)) {
$line = fgets($handle)
// do your stuffs.
}
fclose($handle);
} else {
// error opening the file.
}
```
It will not load complete file in memory so you can use this for bigger files as well.
**feof($handle)** It will save you in case you have a line which contains a boolean **false**.
Upvotes: 0 <issue_comment>username_3: You could also use `array_reduce` to store the ID as key into the array.
```
$content = file('script/items.txt',FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$content = array_reduce($content, function ($result, $line) {
list($id, $data) = explode('/', $line, 2) ;
$result[$id] = $data;
return $result;
}, array());
print_r($content);
```
Outputs:
```
Array
(
[1] => item name/content/etc
[2] => item name/content/etc
[3] => item name/content/etc
[4] => item name/content/etc
)
```
So you can get elements using without using a loop:
```
$content[$wanted_id]
```
Upvotes: 0
|
2018/03/16
| 574 | 1,832 |
<issue_start>username_0: ```
scope :created_after, ->(start_time,end_time) { where("start_time > ? and end_time ", start_time,end_time) }
</code
```
I want to add if condition if start time present then only `start_time` query run if `end_time` then its query run<issue_comment>username_1: You need to use `file()` flags `FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES`
Do like below:-
```
$content = file('script/items.txt',FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
print_r($content);
```
Note:-
Now loop over the array to get records one-by-one.
***Best approach to save data to database table with columns like `id`,`item_name`,`contents` and `extra`***
Upvotes: 2 [selected_answer]<issue_comment>username_2: You can try the below code to read file line by line.
```
$handle = fopen("script/items.txt", "r");
if ($handle) {
while (!feof($handle)) {
$line = fgets($handle)
// do your stuffs.
}
fclose($handle);
} else {
// error opening the file.
}
```
It will not load complete file in memory so you can use this for bigger files as well.
**feof($handle)** It will save you in case you have a line which contains a boolean **false**.
Upvotes: 0 <issue_comment>username_3: You could also use `array_reduce` to store the ID as key into the array.
```
$content = file('script/items.txt',FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$content = array_reduce($content, function ($result, $line) {
list($id, $data) = explode('/', $line, 2) ;
$result[$id] = $data;
return $result;
}, array());
print_r($content);
```
Outputs:
```
Array
(
[1] => item name/content/etc
[2] => item name/content/etc
[3] => item name/content/etc
[4] => item name/content/etc
)
```
So you can get elements using without using a loop:
```
$content[$wanted_id]
```
Upvotes: 0
|
2018/03/16
| 823 | 2,204 |
<issue_start>username_0: I have a list of dictionary items
```
[{'x': 0, 'y': 0}, {'x': 1, 'y': 0}, {'x': 2, 'y': 2}]
```
I want to have an array of "array of dictionaries" with all the maximum permutation order of the list for example for the above array it would be (3 factorial ways)
```
[[{'x': 0, 'y': 0}, {'x': 1, 'y': 0}, {'x': 2, 'y': 2}],
[{'x': 0, 'y': 0}, {'x': 2, 'y': 2}, {'x': 1, 'y': 0}],
[{'x': 1, 'y': 0}, {'x': 0, 'y': 0}, {'x': 2, 'y': 2}],
[{'x': 1, 'y': 0}, {'x': 2, 'y': 2}, {'x': 0, 'y': 0}],
[{'x': 2, 'y': 2}, {'x': 1, 'y': 0}, {'x': 0, 'y': 0}],
[{'x': 2, 'y': 2}, {'x': 0, 'y': 0}, {'x': 1, 'y': 0}]]
```<issue_comment>username_1: You need to use `file()` flags `FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES`
Do like below:-
```
$content = file('script/items.txt',FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
print_r($content);
```
Note:-
Now loop over the array to get records one-by-one.
***Best approach to save data to database table with columns like `id`,`item_name`,`contents` and `extra`***
Upvotes: 2 [selected_answer]<issue_comment>username_2: You can try the below code to read file line by line.
```
$handle = fopen("script/items.txt", "r");
if ($handle) {
while (!feof($handle)) {
$line = fgets($handle)
// do your stuffs.
}
fclose($handle);
} else {
// error opening the file.
}
```
It will not load complete file in memory so you can use this for bigger files as well.
**feof($handle)** It will save you in case you have a line which contains a boolean **false**.
Upvotes: 0 <issue_comment>username_3: You could also use `array_reduce` to store the ID as key into the array.
```
$content = file('script/items.txt',FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$content = array_reduce($content, function ($result, $line) {
list($id, $data) = explode('/', $line, 2) ;
$result[$id] = $data;
return $result;
}, array());
print_r($content);
```
Outputs:
```
Array
(
[1] => item name/content/etc
[2] => item name/content/etc
[3] => item name/content/etc
[4] => item name/content/etc
)
```
So you can get elements using without using a loop:
```
$content[$wanted_id]
```
Upvotes: 0
|
2018/03/16
| 768 | 2,495 |
<issue_start>username_0: I have setup my navigation menu from a ViewComposer (see laravel view composers: <https://laravel.com/docs/5.6/views#view-composers>) like this
```
View::composer('partials.nav', function ($view) {
$view->with('menu', Nav::all());
});
```
What I need is that from some controllers to setup which navigation item is active, ie "current section".
**Question**:
How do I send from some controllers a variable to "partials.nav" like `currentNavItem`?
Do I send it with the rest of the variables for returned view?
like
```
return view('page.blade.php",$viewVariables + $optionalVariablesForPartialsViews);
```
It looks spammy
**Side notes**:
* I use laravel 5.6
**Later edit**
It looks [Laravel 5.1 : Passing Data to View Composer](https://stackoverflow.com/questions/34153072/laravel-5-1-passing-data-to-view-composer?rq=1) might be an options. I will try and get back .<issue_comment>username_1: You need to use `file()` flags `FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES`
Do like below:-
```
$content = file('script/items.txt',FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
print_r($content);
```
Note:-
Now loop over the array to get records one-by-one.
***Best approach to save data to database table with columns like `id`,`item_name`,`contents` and `extra`***
Upvotes: 2 [selected_answer]<issue_comment>username_2: You can try the below code to read file line by line.
```
$handle = fopen("script/items.txt", "r");
if ($handle) {
while (!feof($handle)) {
$line = fgets($handle)
// do your stuffs.
}
fclose($handle);
} else {
// error opening the file.
}
```
It will not load complete file in memory so you can use this for bigger files as well.
**feof($handle)** It will save you in case you have a line which contains a boolean **false**.
Upvotes: 0 <issue_comment>username_3: You could also use `array_reduce` to store the ID as key into the array.
```
$content = file('script/items.txt',FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$content = array_reduce($content, function ($result, $line) {
list($id, $data) = explode('/', $line, 2) ;
$result[$id] = $data;
return $result;
}, array());
print_r($content);
```
Outputs:
```
Array
(
[1] => item name/content/etc
[2] => item name/content/etc
[3] => item name/content/etc
[4] => item name/content/etc
)
```
So you can get elements using without using a loop:
```
$content[$wanted_id]
```
Upvotes: 0
|
2018/03/16
| 402 | 1,326 |
<issue_start>username_0: i am trying to update a table column which same column from same table select.
Here is the code (updated)
```
public function UpdateStockIn($id, $subUnitValue) {
$query = "UPDATE BRAND_LIST SET CURRENT_STOCK_BOTTLE = (SELECT CURRENT_STOCK_BOTTLE FROM BRAND_LIST WHERE ID = ?) + '.$subUnitValue.' WHERE ID = ? ";
$success = 0;
try {
$stmt = $this->conn->prepare($query);
$stmt->bindParam(1, $id);
$stmt->bindParam(2, $id);
$stmt->execute();
$success = 1;
} catch (PDOException $ex) {
echo $ex->getMessage();
}
return $success;
}
```
it Show error like this
You can't specify target table 'BRAND\_LIST' for update in FROM clause<issue_comment>username_1: Use the below query
```
$query = "UPDATE BRAND_LIST SET CURRENT_STOCK_BOTTLE = CURRENT_STOCK_BOTTLE + ".$subUnitValue." WHERE ID = ?";
```
Upvotes: 1 [selected_answer]<issue_comment>username_2: **Try run these 2 sqls, The first one will store a value into mysql local variable then use into 2nd sql.**
```
SELECT @old_subUnitValue := GROUP_CONCAT(table1.CURRENT_STOCK_BOTTLE) FROM BRAND_LIST AS table1 WHERE table1.ID=2;
UPDATE BRAND_LIST AS table2 SET table2.CURRENT_STOCK_BOTTLE = @old_subUnitValue + '.$subUnitValue.' WHERE table2.ID=2;
```
Upvotes: 2
|
2018/03/16
| 334 | 963 |
<issue_start>username_0: Can any one please explian me the below bteq code.
Is this script valid?
```
exec 1> $CODE/edlr2/logs/AGP_MBR_BTEQ_CSA_MBR_STG_LOAD_$(date +"%Y%m%d_%H%M%S").log 2>&1`echo "script file =" $0 PARM_FILE=$1 echo "parm file= "$PARM_FILE.parm . $CODE/edlr2/scripts/$PARM_FILE.parm select name from customer;
```
Can anyone please explain this code<issue_comment>username_1: Use the below query
```
$query = "UPDATE BRAND_LIST SET CURRENT_STOCK_BOTTLE = CURRENT_STOCK_BOTTLE + ".$subUnitValue." WHERE ID = ?";
```
Upvotes: 1 [selected_answer]<issue_comment>username_2: **Try run these 2 sqls, The first one will store a value into mysql local variable then use into 2nd sql.**
```
SELECT @old_subUnitValue := GROUP_CONCAT(table1.CURRENT_STOCK_BOTTLE) FROM BRAND_LIST AS table1 WHERE table1.ID=2;
UPDATE BRAND_LIST AS table2 SET table2.CURRENT_STOCK_BOTTLE = @old_subUnitValue + '.$subUnitValue.' WHERE table2.ID=2;
```
Upvotes: 2
|
2018/03/16
| 1,011 | 4,463 |
<issue_start>username_0: I want to send multiple checkbox values to Firebase database. I took three Checkboxes in XML and a Button. I want to store selected checkbox text to Firebase when the Button is clicked and go to another Activity. This is my code, but it isn't working.
```
mFirstCheckBox = findViewById(R.id.firstCheckBox);
mSecondCheckBox = findViewById(R.id.secondCheckBox);
mThirdCheckBox = findViewById(R.id.thirdCheckBox);
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mAuth = FirebaseAuth.getInstance();
saveButton = findViewById(R.id.saveButton);
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.firstCheckBox:
if(mFirstCheckBox.isChecked()) {
String user_id = mAuth.getCurrentUser().getUid();
DatabaseReference current_user_db = mDatabase.child(user_id);
current_user_db.child("1").setValue("Compiler design");
}
break;
case R.id.secondCheckBox:
if(mSecondCheckBox.isChecked()) {
String user_id = mAuth.getCurrentUser().getUid();
DatabaseReference current_user_db = mDatabase.child(user_id);
current_user_db.child("2").setValue("Operating Systems");
}
break;
case R.id.thirdCheckBox:
if(mThirdCheckBox.isChecked()) {
String user_id = mAuth.getCurrentUser().getUid();
DatabaseReference current_user_db = mDatabase.child(user_id);
current_user_db.child("3").setValue("Software Engineering");
}
break;
}
Intent interestIntent = new Intent(HomeActivity.this, InterestsActivity.class);
interestIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(interestIntent);
}
});
```
This is what I want to achieve in Firebase database, but not getting. In between 'Users' and 'Values(1,2,3)' there must be user\_Id. it is missing in the diagram
because I have entered them in Firebase

Please Guide me, where I am getting wrong. Tell me any other alternative to get this done, if I am completely wrong.
Thanks in advance.<issue_comment>username_1: ```
CheckBoxes only have two states - checked and unchecked, i.e. true and false.
Therefore, you're correct in saying a String isn't a suitable datatype
for holding information given by a CheckBox.
What you want to use is a boolean.
Treat CheckBoxes as having boolean values (the isChecked()
method each CheckBox has will probably come in handy),
and save them .
```
Upvotes: 0 <issue_comment>username_2: First, when you are using this `view.getId()`, you are getting the id of the button that was clicked and not the id of your checkbox that was checked. Second, there is no need to use the following line of code in each case of your switch statement:
```
String user_id = mAuth.getCurrentUser().getUid();
```
It is enough to be used only once. In fact, there is no need to use a switch statement at all. Your code should look like this:
```
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String user_id = mAuth.getCurrentUser().getUid();
DatabaseReference current_user_db = mDatabase.child(user_id);
if(mFirstCheckBox.isChecked()) {
current_user_db.child("1").setValue("Compiler design");
}
if(mSecondCheckBox.isChecked()) {
current_user_db.child("2").setValue("Operating Systems");
}
if(mThirdCheckBox.isChecked()) {
current_user_db.child("3").setValue("Software Engineering");
}
Intent interestIntent = new Intent(HomeActivity.this, InterestsActivity.class);
interestIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(interestIntent);
}
});
```
Upvotes: 3 [selected_answer]
|
2018/03/16
| 578 | 1,964 |
<issue_start>username_0: I cant find this option in *Unity 2017.3*
[](https://i.stack.imgur.com/XSAtb.png)
[](https://i.stack.imgur.com/WzNlx.png)
[](https://i.stack.imgur.com/I1DRl.png)
[](https://i.stack.imgur.com/mqH8j.png)<issue_comment>username_1: The Lightmapping Window has been removed. Although, you can still access the *"Scale In Lightmap"* option in Unity.
Select the GameObject. Go the *MeshRender* ----> *Lightning* then check the *Lightmap Static* checkbox. *Lightmap Settings* menu will appear under it and you can find *"Scale In Lightmap"* under it too.
If still confused, check the animated image below:
[](https://i.stack.imgur.com/HtP3J.gif)
**EDIT:**
Everything mentioned above is still true in *Unity 2017.3*. There is only one more step to do. You **must** tick the `static` checkbox next to the name of the GameObject in order for the *MeshRenderer Lightmap* information to show in the MeshRenderer.
[](https://i.stack.imgur.com/mvV2r.png)
Upvotes: 1 <issue_comment>username_2: You must have installed TextMesh PRO, then you can delete the file called `"TMP_MeshRendererEditor.cs"` in your project. To restore all of them to their default state.
Upvotes: 0 <issue_comment>username_3: For those who are still not seeing the settings, make sure you've enabled Baked Global Illumination in the Lighting Setting tab (Window/Rendering/Lighting Settings). They only appeared for me after ticking it on and saving - easy to miss if you're using a different way to bake lightmaps than the built in baker.
(Unity 2019)
Upvotes: 0
|
2018/03/16
| 3,234 | 10,595 |
<issue_start>username_0: I am making a program to draw using 'x' but for each input, im going to have to copy out:
```
if input() == 'a0':
L0[1] = 'x'
print('\n')
all()
```
100 times, then even another 100 if I want to add a way to delete the 'x',
is there any way to shorten that process using the range function or anything?
```
Tl = ['/','a','b','c','d','e','f','g','h','i','j']
L0 = ['0','.','.','.','.','.','.','.','.','.','.']
L1 = ['1','.','.','.','.','.','.','.','.','.','.']
L2 = ['2','.','.','.','.','.','.','.','.','.','.']
L3 = ['3','.','.','.','.','.','.','.','.','.','.']
L4 = ['4','.','.','.','.','.','.','.','.','.','.']
L5 = ['5','.','.','.','.','.','.','.','.','.','.']
L6 = ['6','.','.','.','.','.','.','.','.','.','.']
L7 = ['7','.','.','.','.','.','.','.','.','.','.']
L8 = ['8','.','.','.','.','.','.','.','.','.','.']
L9 = ['9','.','.','.','.','.','.','.','.','.','.']
def all():
print(*Tl)
print(*L0)
print(*L1)
print(*L2)
print(*L3)
print(*L4)
print(*L5)
print(*L6)
print(*L7)
print(*L8)
print(*L9)
all()
print('\nenter coordinates to draw')
if input() == 'a0':
L0[1] = 'x'
print('\n')
all()
```
I have thought about this and searched, but I have no clue how I am going to do this, thanks<issue_comment>username_1: As suggested in the comments above, you should split printing information from data storage.
The first approach would be creating a `list` of `list`s.
```
def create_empty_table():
return [
['.','.','.','.','.','.','.','.','.','.'],
['.','.','.','.','.','.','.','.','.','.'],
['.','.','.','.','.','.','.','.','.','.'],
['.','.','.','.','.','.','.','.','.','.'],
['.','.','.','.','.','.','.','.','.','.'],
['.','.','.','.','.','.','.','.','.','.'],
['.','.','.','.','.','.','.','.','.','.'],
['.','.','.','.','.','.','.','.','.','.'],
['.','.','.','.','.','.','.','.','.','.'],
['.','.','.','.','.','.','.','.','.','.'],
]
def print_table(table):
print("/ a b c d e f g h i j")
for n, line in enumerate(table):
print(n, " ".join(line))
print()
if __name__ == '__main__':
table = create_empty_table()
# The following part should probably go inside a loop to let the users introduce several values and not just one
print_table(table)
user_value = input("Enter coordinates to draw: ") # Ask the user for the input
letter = user_value[0] # Extract the first char
number = user_value[1] # Extract the second char
col = ord(letter) - ord("a") # Transform the letter into an integer
row = int(number) # Transform the numbr into an int
table[row][col] = 'x'
print_table(table)
```
A numeric string can be converted to a int directly with `int('0')` but the letters are a bit more complex. The [builtin `ord` function](https://docs.python.org/3/library/functions.html#ord) returns the unicode point representation of a character. By substracting the unicode point representation of `'a'` (97) we get an index that we can use in our lists: `ord('a') - ord('a') == 0`, `ord('b') - ord('a') == 1`, `ord('c') - ord('a') == 2`, ...
There are several things that could be enhanced. EDITING ...
Accepting capital letters is quite easy. Check the [`str.lower` method](https://docs.python.org/3/library/stdtypes.html#str.lower) if you want to try it yourself or continue with next example as it use this approach.
Non-hardcoded size for the table would be another improvement. For now we will keep the maximum number of rows and columns at 10 and 26 respectively as there are 10 digits and 26 letters. Accepting higher upper bounds will be done later on.
Another important variation is handling user input. We are going to use exceptions for this.
```
def create_empty_table(rows=10, cols=10, *, fill_char='.'):
table = []
for i in range(rows): # Create the specified number of rows
table.append([fill_char] * cols) # and the specified number of cols
return table
def print_table(table):
if len(table) == 0: # If the table had no row and no column
return # we return to avoid errors
header = "/"
for i in range(ord("a"), ord("a") + len(table[0]): # len(table[0]) == number of cols
header += " " + chr(i)
print(header)
for n, line in enumerate(table):
print(n, " ".join(line))
print()
if __name__ == '__main__':
table = create_empty_table()
# The following part should probably go inside a loop to let the users introduce several values and not just one
print_table(table)
while True:
user_value = input("Enter coordinates to draw: ") # Ask the user for the input
try:
letter = user_value[0] # Extract the first char
number = user_value[1] # Extract the second char
except IndexError: # The user did not introduce two characters
print("ERRROR: use 'a0' notation to introduce the coordinates!")
continue # Go back to the beggining of the loop again
col = ord(letter.lower()) - ord("a") # Transform the letter into an integer
row = int(number) # Transform the numbr into an int
try:
table[row][col] = 'x'
except IndexError: # He introduced wrong values
print("ERROR: Wrong input!")
continue
break # Get out of the while True infinite loop if we have gotten this far
print_table(table)
```
The [builtin `chr` method](https://docs.python.org/3/library/functions.html#chr) is the opposite of `ord`, it returns the symbol from the point (integer).
Some further verification would be needed for a robust code such as detecting if the first character is not a letter or the second is not a digit, detecting if he introduced more than 2 characters, ...
Upvotes: 1 <issue_comment>username_2: You can simplify it by storing only the "painted" coords in a set - or go for a dictionary and also store whats paintet at that coord.
Essentially you store only where/which players/coords are occupied. If a coord is not occupied, draw an "empty" in your grid, else draw its content:
Example for Player-turn-taking field:
```
import os # clear console
def cls():
"""Clears the console."""
os.system('cls' if os.name=='nt' else 'clear')
# playground definitions
cols = [x for x in "abcdefghij"] # column headers
rows = [x for x in range(10)] # row "headers"
rowsString = [str(x) for x in rows] # convenience
# dictionary holding whats in what cell
field = {}
def printAll(d):
"""Clears the screen, prints d. Non-provided keys are printed as '.'"""
cls()
print(" ", ' '.join(cols)) # print column headers
for rowNum in rows:
print(f' {rowNum:d} ', end = " ") # print row header
for c in cols:
key = (c,rowNum) # check if in dict, print value else '.'
if key in d:
print(f'{d[key]}', end = " ")
else:
print(".", end = " ")
print()
player = ["X","O"]
turn = 0
while True:
printAll(field) # inital field printing
p = player[turn%2] # who is it this turn?
coord = ""
print("'q' quits, 'r' resets")
# repeat until valid input
while len(coord)!= 2 or coord[0] not in cols or coord[1] not in rowsString:
coord = input(f'Player {p} - enter coords: ')
if coord=="q":
exit()
elif coord =="r":
field = {}
printAll(field)
print("'q' quits, 'r' resets")
elif len(coord)== 2 and (coord[0],int(coord[1])) in field:
print("Already placed. Choose new coords.")
coord=""
# store coord with players symbol - if you only draw lines, simplify code w/o playrs
field[(coord[0],int(coord[1]))] = p
turn+=1
```
Output after some turns:
```
a b c d e f g h i j
0 . . . . . . . . . .
1 . . . . . . . . . .
2 . . . . . . . . . .
3 . O X . . O . . . .
4 X . . . . X . . . .
5 X . . . . O . . . .
6 . . . . . . . . . .
7 . . . . . . . . . .
8 . . . . . . . . X .
9 O . O . . . . . . .
'q' quits, 'r' resets
Player X - enter coords: c99
Player X - enter coords: b33
Player X - enter coords: abdc
Player X - enter coords: hallo
Player X - enter coords: 34
Player X - enter coords:
```
---
To just print Xs and remove them again change the main program to:
```
while True:
printAll(field) # inital field printing
coord = ""
print("'q' quits, 'r' resets")
while len(coord)!= 2 or coord[0] not in cols or coord[1] not in rowsString:
coord = input(f'Enter coords: ')
if coord=="q":
exit()
elif coord =="r":
field = {}
printAll(field)
print("'q' quits, 'r' resets")
# set or delete field depending on if it is already set or not:
if len(coord)== 2 and (coord[0],int(coord[1])) in field:
field.pop((coord[0],int(coord[1])))
else:
field[(coord[0],int(coord[1]))] = 'X'
```
Upvotes: 0 <issue_comment>username_3: EDIT: If you are already importing pandas somewhere in your code, you CAN leverage it to solve your current query.
If you are just starting a larger program which performs data crunching/analysis or deals with matrix, you MIGHT want to check panda's capabilities.
If your case is neither of above, then go with [username_1's answer](https://stackoverflow.com/a/49315925/9501564)
Using pandas we have created a dataframe which is like a modifiable matrix. We initially populate it with '.' & later change them to 'x' as usr input arrives.
I have written this program to accept multiple fields to be changed to 'x' as long as they are separated by whitespace.
you can further modify this program to modify this matrix by as many types of symbols you want.
```
import pandas as pd
canvas = pd.DataFrame()
for z in 'abcdefghij':
canvas = pd.concat([canvas,pd.DataFrame(['.','.','.','.','.','.','.','.','.','.'],columns=list(z))],axis=1)
print('\nenter coordinates to draw')
usr_input = input()
for i in usr_input.split():
c,r = list(i)
r = int(r)
canvas.at[r,c] = 'x'
print('\n')
print(canvas)
```
output:
```
enter coordinates to draw
a1 b2 c3
a b c d e f g h i j
0 . . . . . . . . . .
1 x . . . . . . . . .
2 . x . . . . . . . .
3 . . x . . . . . . .
4 . . . . . . . . . .
5 . . . . . . . . . .
6 . . . . . . . . . .
7 . . . . . . . . . .
8 . . . . . . . . . .
9 . . . . . . . . . .
```
Upvotes: 1
|
2018/03/16
| 716 | 2,816 |
<issue_start>username_0: I am very new to React and TypeScript. I am developing a web page in Visual Studio 2017 where I have a search component which I would like to use in my home component. But after importing search into my home component, I get a compile time error saying:
```
Type {} is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & Readonly<{ children?: ReactNode; }>
Type {} is not assignable to type Readonly
Property 'suggestionList' is missing in type {}
```
Search Component code:
```
export class Search extends React.Component { //SearchForm is a class with string and an object of another class as properties
constructor() {
super();
}
```
Home component code:
```
export class Home extends React.Component, {}>
{
return
< Search /> // <=Getting error at this line
}
```
If I remove `RouteComponentProps<{}>` from Home component, then I get an error in route.tsx file. I know, I must be doing something wrong or some silly mistake. I googled this but I am not getting any helpful answers. Can somebody tell me how do I solve this?<issue_comment>username_1: You are missing required properties of `Search` component, the error shows `suggestion List`. You need something like:
```
```
(and maybe not only `suggestionList` is missing)
React.Component definition is:
```
interface Component
```
where `P` defines components properties and `S` the state. You must pass to the component all requiered properties defined in `P`.
In your example, component properties type is `SearchForm`. Therefore you need to pass, at least, all required attributes of `SearchForm`.
Please refer to [Define Props and State Types](https://charleslbryant.gitbooks.io/hello-react-and-typescript/content/DefinePropsAndStateTypes.html) for a more complete explanation.
Upvotes: 2 [selected_answer]<issue_comment>username_2: As @username_1 said, you are missing the required properties of Search component.
Giving all props a value will fix it:
```
```
Upvotes: 2 <issue_comment>username_3: If you would like to create functional component you can use generics in order to get rid of this error. Consider this example.
```
interface SearchProps {
suggestionList: any
}
export const Search: React.FC = ({suggestionList}): JSX.Element => {
return ...
}
```
Upvotes: 2 <issue_comment>username_4: you have to spread the props object. to elaborate:
i have this component
```js
const Component: FunctionComponent =
(props) => {
//component code
}
```
and here where it is invoked; where we have the props object and the component
```js
const componentProps: ComponentProps= {
//properties
title:'title 1',
//etc...
}
```
to assign the props object as props to the component
you should spread the object in the component
```js
```
Upvotes: 0
|
2018/03/16
| 634 | 2,300 |
<issue_start>username_0: I saw answer "JavaScript's code gets executed before the DOM contains #annual element. Put the javascript after the div or use jQuery.ready()" But I don't know to put after what div?
this is script include?
[enter image description here](https://i.stack.imgur.com/TxWTE.png)
error:
```
Uncaught Error: Graph container element not found
at d [as constructor] (morris.min.js:6)
at d.c [as constructor] (morris.min.js:6)
at new d (morris.min.js:6)
at HTMLDocument. (dashboard.js:129)
at j (jquery.min.js:2)
at k (jquery.min.js:2)
```<issue_comment>username_1: You are missing required properties of `Search` component, the error shows `suggestion List`. You need something like:
```
```
(and maybe not only `suggestionList` is missing)
React.Component definition is:
```
interface Component
```
where `P` defines components properties and `S` the state. You must pass to the component all requiered properties defined in `P`.
In your example, component properties type is `SearchForm`. Therefore you need to pass, at least, all required attributes of `SearchForm`.
Please refer to [Define Props and State Types](https://charleslbryant.gitbooks.io/hello-react-and-typescript/content/DefinePropsAndStateTypes.html) for a more complete explanation.
Upvotes: 2 [selected_answer]<issue_comment>username_2: As @username_1 said, you are missing the required properties of Search component.
Giving all props a value will fix it:
```
```
Upvotes: 2 <issue_comment>username_3: If you would like to create functional component you can use generics in order to get rid of this error. Consider this example.
```
interface SearchProps {
suggestionList: any
}
export const Search: React.FC = ({suggestionList}): JSX.Element => {
return ...
}
```
Upvotes: 2 <issue_comment>username_4: you have to spread the props object. to elaborate:
i have this component
```js
const Component: FunctionComponent =
(props) => {
//component code
}
```
and here where it is invoked; where we have the props object and the component
```js
const componentProps: ComponentProps= {
//properties
title:'title 1',
//etc...
}
```
to assign the props object as props to the component
you should spread the object in the component
```js
```
Upvotes: 0
|
2018/03/16
| 653 | 2,254 |
<issue_start>username_0: I tried so many things to change the navbar colour such as
[Android lollipop change navigation bar color](https://stackoverflow.com/questions/27839105/android-lollipop-change-navigation-bar-color)
[android change navigation bar color](https://stackoverflow.com/questions/41303597/android-change-navigation-bar-color)
[How to change system navigation bar color](https://stackoverflow.com/questions/27348336/how-to-change-system-navigation-bar-color)
Nothing works
I added the item to `styles.xml` - using Android 8.1
```
@color/theme\_color
```
Anyone knows what is the best way to do this in Xamarin.Android
UPDATE: I tried the following code in my style file
```
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowNoTitle">true</item>
<item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
<item name="color">@color/red</item>
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
<item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
```<issue_comment>username_1: This works for me.
You need to create a new style for drawer toggle **like this**:
```
<item name="color">@color/white\_color</item>
```
And add this to your preferable style.
```
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/primary</item>
<item name="colorPrimaryDark">@color/primary\_dark</item>
<item name="colorAccent">@color/primary</item>
<item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
```
And finally use `NoActionbarTheme` theme in manifest file within your Activity.
Hope it will help you.
Upvotes: 0 <issue_comment>username_2: >
> While fixing another issue I had to change and minimum API level to
> Lollipop and noticed that
> `@color/theme\_color`
> started working when minimum API level is set to Lollipop.
>
>
>
So I think for some reason Xamarin requires to use use Minimum API version Lollipop for this to work
Upvotes: 2 [selected_answer]
|
2018/03/16
| 890 | 2,840 |
<issue_start>username_0: I want to ask someone to type in a letter, and when they do, check if that letter is a certain letter that I am asking them. If it is, my output will display a list of an array. My Code:
```
import java.util.Scanner;
Scanner input = new Scanner(System.in);
public static void main(String[] args) {
String[] rodent;
String[] dog;
String[] cat;
rodent = new String[] {"Rat", "Guinea Pig", "Mouse"};
dog = new String[] {"Rottweiler", "Basset Hound", "Weiner Dog"};
cat = new String[] {"Lion", "Tiger", "Mountain Lion"};
Scanner input = new Scanner(System.in);
System.out.print("Please Enter [R] for Rodent, [D] for Dogs, and"
+ " [C] for Cats: ");
char character = input.next().charAt(0);
if(character == 'R'); {
System.out.print(rodent[0]+", "+rodent[1]+", "+rodent[2]);
} // closes 'R' statement
if(character == 'D') {
System.out.print(dog[0]+", "+dog[1]+", "+dog[2]);
} //closes 'D' statement
if(character == 'C') {
System.out.print(cat[0]+", "+cat[1]+", "+cat[2]);
} //closes 'C' statement
}
```
If they enter R, it outputs correctly.
If they enter D, it outputs rodents, and dogs.
If they enter C, it outputs just rodents.
What would be the fix to this?<issue_comment>username_1: You have a typo in your code:
`if(character == 'R'); {`
Remove the `;` which terminates the `if` and it will work.
Upvotes: 1 <issue_comment>username_2: There is a wrong semicolon in your code:
```
if(character == 'R'); {
```
Delete it and your code will work!
The Semicolon says that your if statement is finished - so that the following part
```
{
System.out.print(rodent[0]+", "+rodent[1]+", "+rodent[2]);
} // closes 'R' statement
```
is not part of your first `if`.
So the above statement will always be printed.
Upvotes: 1 <issue_comment>username_3: It's indeed because of the unwanted semicolon BUT always try to use switch-case structure for these kinds of checks for the best practice.
```
Scanner input = new Scanner(System.in);
public static void main(String[] args) {
String[] rodent;
String[] dog;
String[] cat;
rodent = new String[] {"Rat", "Guinea Pig", "Mouse"};
dog = new String[] {"Rottweiler", "Basset Hound", "Weiner Dog"};
cat = new String[] {"Lion", "Tiger", "Mountain Lion"};
Scanner input = new Scanner(System.in);
System.out.print("Please Enter [R] for Rodent, [D] for Dogs, and"
+ " [C] for Cats: ");
char character = input.next().charAt(0);
switch (character){
case 'R': System.out.print(rodent[0]+", "+rodent[1]+", "+rodent[2]);break;
case 'D': System.out.print(dog[0]+", "+dog[1]+", "+dog[2]);break;
case 'C': System.out.print(cat[0]+", "+cat[1]+", "+cat[2]);break;
}
}
```
Upvotes: 2
|
2018/03/16
| 639 | 2,323 |
<issue_start>username_0: I implement TabbedPage with 3 tabs like the following picture.
[](https://i.stack.imgur.com/uOJcQ.png)
On top of these 3 tabs, I am trying to set a title, which will be common for all the 3 tabs. Tried title property of tabbedpage, but not worked.
MyTabbedpage.xaml
```
xml version="1.0" encoding="utf-8" ?
```
MyTabbedpage.xaml.cs
```
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Myapp
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MyTabbedPage : TabbedPage
{
public MyTabbedPage(bool value)
{
InitializeComponent();
Children.Add(new Topics());
Children.Add(new Group());
Children.Add(new Menu());
}
protected override bool OnBackButtonPressed()
{
return false;
}
}
}
```
[](https://i.stack.imgur.com/xP7lu.png)
Please suggest a solution.<issue_comment>username_1: ```
public class MainPageCS : TabbedPage
{
public MainPageCS ()
{
var navigationPage = new NavigationPage (new SchedulePageCS ());
navigationPage.Icon = "schedule.png";
navigationPage.Title = "Schedule";
Children.Add (new TodayPageCS ());
Children.Add (navigationPage);
}
}
```
This is the code snippet from the [official documentation](https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/navigation/tabbed-page). On line number 7 you can see how the title is set.
After you edited your question, it seems that you want to wrap your `TabbedPage` by a `NavigationPage` and set a `Title` for the `NavigationPage`. Example:
```
new NavigationPage(new MyTabbedPage()) { Title = "Common Title" };
```
Alternatively, one of your `TabbedPage` children can be a `NavigationPage` as well, depends on your needs.
Upvotes: 0 <issue_comment>username_2: I don't think you can do it without a custom renderer.
You may try this prebuilt form control - TabView - found at:
<https://github.com/gruan01/XFControls>
You can find it also on NuGet.
You can set image onto the tabs and other enhancements.
But I strongly recommend a custom renderer as a final solution.
Upvotes: 1
|
2018/03/16
| 417 | 1,507 |
<issue_start>username_0: Does anyone know how to convert this into mips 32? Please show the code and explain for me. Thank you so much
```
int service (int n) {
if (n <= 10)
return n;
else
return n + service(n+1) + service (n+2);
}
```<issue_comment>username_1: ```
public class MainPageCS : TabbedPage
{
public MainPageCS ()
{
var navigationPage = new NavigationPage (new SchedulePageCS ());
navigationPage.Icon = "schedule.png";
navigationPage.Title = "Schedule";
Children.Add (new TodayPageCS ());
Children.Add (navigationPage);
}
}
```
This is the code snippet from the [official documentation](https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/navigation/tabbed-page). On line number 7 you can see how the title is set.
After you edited your question, it seems that you want to wrap your `TabbedPage` by a `NavigationPage` and set a `Title` for the `NavigationPage`. Example:
```
new NavigationPage(new MyTabbedPage()) { Title = "Common Title" };
```
Alternatively, one of your `TabbedPage` children can be a `NavigationPage` as well, depends on your needs.
Upvotes: 0 <issue_comment>username_2: I don't think you can do it without a custom renderer.
You may try this prebuilt form control - TabView - found at:
<https://github.com/gruan01/XFControls>
You can find it also on NuGet.
You can set image onto the tabs and other enhancements.
But I strongly recommend a custom renderer as a final solution.
Upvotes: 1
|
2018/03/16
| 448 | 1,651 |
<issue_start>username_0: ```
InputTags = document.getElementsByTagName("input")
for (inputTag in InputTags) {
if (inputTag.name == 'username') inputTag.value = "abc"
else if (inputTag.name == 'password') {
inputTag.value = "<PASSWORD>"
}
}
```
In the above segment, DOM elements are manipulated by Javascript method "getElementsByTagName".Similarly how do I acheive this in languages like python?<issue_comment>username_1: ```
public class MainPageCS : TabbedPage
{
public MainPageCS ()
{
var navigationPage = new NavigationPage (new SchedulePageCS ());
navigationPage.Icon = "schedule.png";
navigationPage.Title = "Schedule";
Children.Add (new TodayPageCS ());
Children.Add (navigationPage);
}
}
```
This is the code snippet from the [official documentation](https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/navigation/tabbed-page). On line number 7 you can see how the title is set.
After you edited your question, it seems that you want to wrap your `TabbedPage` by a `NavigationPage` and set a `Title` for the `NavigationPage`. Example:
```
new NavigationPage(new MyTabbedPage()) { Title = "Common Title" };
```
Alternatively, one of your `TabbedPage` children can be a `NavigationPage` as well, depends on your needs.
Upvotes: 0 <issue_comment>username_2: I don't think you can do it without a custom renderer.
You may try this prebuilt form control - TabView - found at:
<https://github.com/gruan01/XFControls>
You can find it also on NuGet.
You can set image onto the tabs and other enhancements.
But I strongly recommend a custom renderer as a final solution.
Upvotes: 1
|
2018/03/16
| 621 | 1,288 |
<issue_start>username_0: I am trying to find all permutations of elements in a list and add it to a global dictionary
Code:
```
outp={}
k=0
def func(i,arr):
global outp
global k
arr=arr.copy()
for j in range(i,len(list)):
arr[i],arr[j] = arr[j],arr[i]
if i!=j or i==0:
k=k+1
print("\n\n",arr,k)
outp[k]=arr
print("\n",outp)
func(i+1,arr)
list = [1,2,3,8]
func(0,list)
```
Output below:
Till 4th element it updated correctly. During 5th element, it updated both 5th and 3rd element in the dictionary. I don't know why it is happening. Kindly help
```
[1, 2, 3, 8] 1
{1: [1, 2, 3, 8]}
[1, 2, 8, 3] 2
{1: [1, 2, 3, 8], 2: [1, 2, 8, 3]}
[1, 3, 2, 8] 3
{1: [1, 2, 3, 8], 2: [1, 2, 8, 3], 3: [1, 3, 2, 8]}
[1, 3, 8, 2] 4
{1: [1, 2, 3, 8], 2: [1, 2, 8, 3], 3: [1, 3, 2, 8], 4: [1, 3, 8, 2]}
[1, 8, 2, 3] 5
{1: [1, 2, 3, 8], 2: [1, 2, 8, 3], 3: [1, 8, 2, 3], 4: [1, 3, 8, 2], 5: [1, 8, 2, 3]}
```<issue_comment>username_1: You need to place a copy of the array in the dictionary:
```
outp[k] = arr.copy()
```
Upvotes: 1 <issue_comment>username_2: This would be a better way to copy list to a new list.
`arr=arr[:]` .
<https://repl.it/repls/BronzeYellowConversion>
Upvotes: 0
|
2018/03/16
| 516 | 1,630 |
<issue_start>username_0: So I am working with this code:
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Leap;
using Leap.Unity;
public class iliketomoveit : MonoBehaviour {
Controller controller;
float HandPalmPitch;
float HandPalmYam;
float HandPalmRoll;
float HandWristRot;
void Start () {
}
// Update is called once per frame
void Update () {
controller = new Controller();
Frame frame = controller.Frame();
List hands = frame.Hands;
if (frame.Hands.Count > 0)
{
Hand fristHand = hands[0];
}
HandPalmPitch = hands[0].PalmNormal.Pitch;
HandPalmRoll = hands[0].PalmNormal.Roll;
HandPalmYam = hands[0].PalmNormal.Yaw;
HandWristRot = hands[0].WristPosition.Pitch;
Debug.Log("Pitch :" + HandPalmPitch);
Debug.Log("Roll :" + HandPalmRoll);
Debug.Log("Yam :" + HandPalmYam);
if (HandPalmYam > -2f && HandPalmYam < 3.5f)
{
transform.Translate ( new Vector3(0, 0,1 \* Time.deltaTime));
}else if (HandPalmYam < -2.2f)
{
transform.Translate ( new Vector3(0, 0, -1 \* Time.deltaTime));
}
}
}
```
This is used for LeapMotion hands translation in Unity. But when I run this script I get the exception'Argument is out of Range' and the program does not work .I tried to add items into the list but haven't been able to do so .<issue_comment>username_1: You need to place a copy of the array in the dictionary:
```
outp[k] = arr.copy()
```
Upvotes: 1 <issue_comment>username_2: This would be a better way to copy list to a new list.
`arr=arr[:]` .
<https://repl.it/repls/BronzeYellowConversion>
Upvotes: 0
|
2018/03/16
| 226 | 1,018 |
<issue_start>username_0: I'm managing few iOS devices, so I want to create a app to add security feature like collecting the user information from the user like UserID to track which user is currently using the device .
**Desired output:**
So I want to trigger my app as soon as a user unlock the device and without giving the details the user should not able to access the home screen of the Device.
Is it possible to do it with any framework in iOS without Jailbreak ?<issue_comment>username_1: No its not possible. iOS does not allows application to manage device with it self. Application should work in the pre given area which is called Sandbox. So its not possible to handle the entire device and you can not check it that who is using the device.
Upvotes: 2 [selected_answer]<issue_comment>username_2: This is not possible, you should look to Mobile Device Management solutions and rather go that route. You could also look at [apple's business solutions](https://www.apple.com/business/dep/).
Upvotes: 0
|
2018/03/16
| 468 | 1,786 |
<issue_start>username_0: I created a folder in res folder and it named draw2 which i will use for specisific imageviews.I want to access the images inside this folder how to do it?<issue_comment>username_1: You cannot. Custom folders in res folder are not supported.
Upvotes: 2 <issue_comment>username_2: Just Put the images you trying to access into your (**drawable**) folder, because in android the **res** folder has specific folder names like (**values**,**mipmap**,**anim**,**drawable** ...) , and you can't create new folder name , it will not be recognized.
Upvotes: 0 <issue_comment>username_3: >
> I created a folder in res folder and it named draw2 which i will use for specisific imageviews.
>
>
>
Custom folders in res folder are not supported. Better To create [**`raw folder or asset folder`**](https://developer.android.com/guide/topics/resources/providing-resources.html)
for this purpose
**`raw/`**
>
> Arbitrary files to save in their raw form. To open these resources with a raw `InputStream`, call `Resources.openRawResource()` with the resource ID, which is `R.raw.filename`.
>
>
>
[How to create assets in android studio](https://stackoverflow.com/a/34315335/7666442)
[How to create raw in android studio](https://stackoverflow.com/questions/5777413/android-raw-folders-creation-and-reference)
for more information **[The Android Project View](https://developer.android.com/studio/projects/index.html#mipmap)**
```
module-name/
build/
libs/
src/
androidTest/
main/
AndroidManifest.xml
java/
jni/
gen/
res/
assets/
test/
build.gradle (module)
build.gradle (project)
```
Upvotes: 1 [selected_answer]
|
2018/03/16
| 709 | 2,454 |
<issue_start>username_0: I am linking my navigation bar list items to includes folder page with href Attribute
```
- [Brands](/opt/lampp/htdocs/FoundationFlex/admin/includes/brands.php)
```
I have tried copying full path
I have tried setting permission on htdocs to 777 but still not working.
[My code and folder structure](https://i.stack.imgur.com/06h3Z.jpg)
I am using new Ubuntu machine (16.04) with XAmp
This is my error :
>
> Object not found!
>
>
>
The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error.<issue_comment>username_1: You are trying to link using PATH on server, use URL instead and make sure this file is accessible from browser
```
- [Brands](http://example.com/FoundationFlex/admin/includes/brands.php)
```
Upvotes: 0 <issue_comment>username_2: You are using the full file system path of the file. But you must enter a relative path to your webservers root folder (htdocs).
So if you call your page with <http://localhost/> then in your case your webserver root folder seems to be /opt/lampp/htdocs/. Linking the file brands.php in a html link will look like this (relative):
```
[Brands](FoundationFlex/admin/includes/brands.php)
```
or absolute
```
[Brands](/FoundationFlex/admin/includes/brands.php)
```
or (but this one should have the same result ase the one above:
```
[Brands](http://localhost/FoundationFlex/admin/includes/brands.php)
```
These links can help you:
<https://www.coffeecup.com/help/articles/absolute-vs-relative-pathslinks/>
<https://www.w3schools.com/html/html_links.asp>
Upvotes: 0 <issue_comment>username_3: replace your code with this `- [Brands](http://localhost/FoundationFlex/admin/includes/brands.php)` or `- [Brands](FoundationFlex/admin/includes/brands.php)`
the problem in your href link is that you are giving a file path in browser, which correct but not executable nor a website url so it will always throw a 404 error which means the web page doesn't exits.
Upvotes: 1 [selected_answer]<issue_comment>username_4: If `/opt/lampp/htdocs/FoundationFlex` is your servers DocumentRoot you can just
```
[Brand](/admin/includes/brand.php)
```
Upvotes: 0 <issue_comment>username_5: You are putting wrong path
This is your site url
```
http://localhost/FoundationFlex/
```
and this is your file path
```
[Brand](/admin/includes/brand.php)
```
Upvotes: 1
|
2018/03/16
| 775 | 2,772 |
<issue_start>username_0: I am using contao 4.4 instance.I have a problem in google sitemap generation.
I have a newsletter page (page type = regular ) . In that page I have some newsletter articles (with teaser) . When I generate the sitemap, the url of these articles generated twice. When I checked the core I found a class which creates the page array for generating sitemap
>
> vendor/contao/core-bundle/src/Resources/contao/classes/Backend.php
>
> line no 662 - 680 .
>
>
>
Which append 'articles/' to the articles with teaser. So the sitemap generates url
1. with articles/
2. List item
without articles/
The first one is the correct url.Second Url generate 404. How I fix the issue ?
My siteconfiguration is as follows
->created a regular page with hidden in navigation and created articles with configuration show teaser
->created another page and created elements as 'teaser articles' and select articles from the above page<issue_comment>username_1: You are trying to link using PATH on server, use URL instead and make sure this file is accessible from browser
```
- [Brands](http://example.com/FoundationFlex/admin/includes/brands.php)
```
Upvotes: 0 <issue_comment>username_2: You are using the full file system path of the file. But you must enter a relative path to your webservers root folder (htdocs).
So if you call your page with <http://localhost/> then in your case your webserver root folder seems to be /opt/lampp/htdocs/. Linking the file brands.php in a html link will look like this (relative):
```
[Brands](FoundationFlex/admin/includes/brands.php)
```
or absolute
```
[Brands](/FoundationFlex/admin/includes/brands.php)
```
or (but this one should have the same result ase the one above:
```
[Brands](http://localhost/FoundationFlex/admin/includes/brands.php)
```
These links can help you:
<https://www.coffeecup.com/help/articles/absolute-vs-relative-pathslinks/>
<https://www.w3schools.com/html/html_links.asp>
Upvotes: 0 <issue_comment>username_3: replace your code with this `- [Brands](http://localhost/FoundationFlex/admin/includes/brands.php)` or `- [Brands](FoundationFlex/admin/includes/brands.php)`
the problem in your href link is that you are giving a file path in browser, which correct but not executable nor a website url so it will always throw a 404 error which means the web page doesn't exits.
Upvotes: 1 [selected_answer]<issue_comment>username_4: If `/opt/lampp/htdocs/FoundationFlex` is your servers DocumentRoot you can just
```
[Brand](/admin/includes/brand.php)
```
Upvotes: 0 <issue_comment>username_5: You are putting wrong path
This is your site url
```
http://localhost/FoundationFlex/
```
and this is your file path
```
[Brand](/admin/includes/brand.php)
```
Upvotes: 1
|
2018/03/16
| 244 | 800 |
<issue_start>username_0: I want to horizontally align center the div with the red border and vertically align middle the image. Vertically align middle is working but horizontally align center is not working. Here is my code:
```css
.vcenter {
display: table-cell;
vertical-align: middle;
}
```
```html
xyz
---
![Cinque Terre]()
```<issue_comment>username_1: ```css
.vcenter {
display: table-cell;
vertical-align: middle;
}
.text-center div{
display: flex;
}
```
```html
xyz
---
![Cinque Terre]()
```
Upvotes: 0 <issue_comment>username_2: ```css
.vcenter {
display: flex;
justify-content:center; //making content center;
align-items:center; //vertical align to middle of div
}
```
```html
xyz
---
![Cinque Terre]()
```
Upvotes: 3 [selected_answer]
|
2018/03/16
| 1,582 | 4,607 |
<issue_start>username_0: I have tried to make a simple snake game with Free Pascal, when I started the programme, it drew the map exactly what I want but after that, I pressed the button that I have set to control the snake and it exited with exit code 201.
I don't know much about that exit code, could you explain me the problems of the programme? This is the longest program I have ever made with Pascal.
Here is the code:
```
uses crt;
type
ran=record
x:byte;
y:byte;
end;
var
f:ran;
s:array[1..1000] of ran;
i,j:longint;
st,l:byte;
function getkey:integer;
var
k:integer;
begin
k:=ord(readkey);
if k=0 then k:=-ord(readkey);
getkey:=k;
end;
procedure fa;
begin
randomize;
f.x:=random(98)+1;
f.y:=random(23)+1;
gotoxy(f.x,f.y);
writeln('o');
end;
procedure draw;
begin
gotoxy(1,1);
st:=1;
for i:=1 to 25 do begin
for j:=1 to 100 do write('X');
writeln
end;
gotoxy(st+1,st+1);
for i:=1 to 23 do begin
for j:=1 to 98 do write(' ');
gotoxy(st+1,i+2);
end;
end;
procedure sts;
begin
s[1].x:=19;
s[1].y:=6;
gotoxy(s[1].x,s[1].y);
writeln('@');
end;
procedure fa1;
begin
f.x:=29;
f.y:=5;
gotoxy(f.x,f.y);
writeln('o');
end;
procedure eat;
begin
if (s[1].x=f.x) and (s[1].y=f.y) then begin
l:=l+1;
fa;
end;
end;
function die:boolean;
begin
die:=false;
if (s[1].x=1) or (s[1].x=100) or (s[1].y=1) or (s[1].y=25) then
die:=true;
if l>=5 then
for i:=5 to l do
if (s[1].x=s[i].x) and (s[1].y=s[i].y) then
die:=true;
end;
procedure up;
begin
for i:=l downto 2 do begin
s[i].y:=s[i-1].y;
gotoxy(s[i].x,s[i].y);
writeln('+');
end;
gotoxy(s[l].x,s[l].y+1);
writeln(' ');
s[1].y:=s[1].y-1;
gotoxy(s[1].x,s[1].y);
writeln('@');
end;
procedure down;
begin
for i:=l downto 2 do begin
s[i].y:=s[i-1].y;
gotoxy(s[i].x,s[i].y);
writeln('+');
end;
gotoxy(s[l].x,s[l].y-1);
writeln(' ');
s[1].y:=s[1].y+1;
gotoxy(s[1].x,s[1].y);
writeln('@');
end;
procedure left;
begin
for i:=l downto 2 do begin
s[i].x:=s[i-1].x;
gotoxy(s[i].x,s[i].y);
writeln('+');
end;
gotoxy(s[l].x+1,s[l].y);
writeln(' ');
s[1].x:=s[1].x-1;
gotoxy(s[1].x,s[1].y);
writeln('@');
end;
procedure right;
begin
for i:=l downto 2 do begin
s[i].x:=s[i-1].x;
gotoxy(s[i].x,s[i].y);
writeln('+');
end;
gotoxy(s[l].x-1,s[l].y);
writeln(' ');
s[1].x:=s[1].x+1;
gotoxy(s[1].x,s[1].y);
writeln('@');
end;
procedure auto(k:integer);
begin
case k of
-72:up;
-80:down;
-75:left;
-77:right;
119:up;
115:down;
97:left;
100:right;
end;
end;
procedure ingame(t:integer);
var
d,e:boolean;
begin
repeat
auto(t);
d:=die;
if d=true then exit;
eat;
until (keypressed);
if keypressed then t:=getkey;
case t of
-72:up;
-80:down;
-75:left;
-77:right;
119:up;
115:down;
97:left;
100:right;
end;
eat;
d:=die;
if d=true then exit;
end;
procedure first;
var
k:integer;
begin
draw;
fa1;
sts;
if keypressed then k:=getkey;
ingame(k);
end;
BEGIN
clrscr;
first;
readln
END.
```<issue_comment>username_1: The code 201 seems to be explained for example here: [Runtime Error 201 at fpc](https://stackoverflow.com/questions/20315852/runtime-error-201-at-fpc)
Exactly why this happens in your code, I don't know.
Upvotes: 0 <issue_comment>username_2: I googled this: `201 : range error`, so you probably go out of array bounds. The only array `s` in indexed by variables that depend on `l` value (weird name, BTW). But I see a single place where you do changing (increment) this variable and don't see any `l` initialization. So you are using **arbitrary** starting value (here perhaps zero because `l` is global).
Note that you could discover this bug (and perhaps others) with simple debugging.
Upvotes: 1
|
2018/03/16
| 300 | 1,059 |
<issue_start>username_0: I'm using ASP.NET Boilerplate, on ASP.NET Core.
I have some model classes.
```
public class AClass : FullAuditedEntity
{
}
```
and one interface like below.
```
public interface ISomeInterface where T : BaseFileEntity where TEntity : class, IEntity
{
}
```
Now If I add one extra model class like below.
```
public class BClass : FullAuditedEntity
{
}
```
I have to define another interface for this change like below.
```
public interface ISomeInterface where T : BaseFileEntity where TEntity : class, IEntity
{
}
```
So basically it's duplicate code. Is there any better way to do this?<issue_comment>username_1: You can Change the interface to:
```
public interface ISomeInterface where T : BaseFileEntity where TEntity : class, IEntity
{
}
```
Upvotes: 0 <issue_comment>username_2: Is it possible to declare your interface like the one below so you can pass the type to IEntity
```
public interface ISomeInterfaceB where T : BaseFileEntity where TEntity : class, IEntity {
}
```
Upvotes: 2 [selected_answer]
|
2018/03/16
| 401 | 1,494 |
<issue_start>username_0: I can do `const A& a = A()` and `A&& a = A()`, but why cannot I do `A& a = A()`?<issue_comment>username_1: By "initialising an lvalue reference" you refer to defining the lavalue which the reference is referring to from then on.
So the lvalue-reference will propagate any access to the rvalue "initialisation".
I.e. you would attempt to access an rvalue-expression like an lvalue.
It is not possible in all cases to access an rvalue like an lvalue.
That is why.
Upvotes: 0 <issue_comment>username_2: An rvalue is a temporary - it's going to die soon. Creating a lvalue reference to such an object would be a recipe for disaster since the reference would become a dangling reference to a dead object very quickly.
Upvotes: 0 <issue_comment>username_3: The rationale is that it rarely makes sense to mutate a temporary. Any attempt to do so is likely to be a programming error rather than a deliberate decision.
The prototypical example is as follows. Assume binding to non-const reference is allowed.
```
void foo(int& x, int& y); // sets x and y
int xx, yy;
foo(xx, yy); // xx and yy are set
// now make a small change...
void foo(long& x, long& y); // upgrade
int xx, yy; // forgot to change here
foo(xx, yy); // silently breaks
```
While one does sometimes want to mutate a temporary, it's often for an entirely different reason from that of mutating an lvalue. Rvalue references were invented to accommodate these cases.
Upvotes: 3 [selected_answer]
|
2018/03/16
| 281 | 838 |
<issue_start>username_0: I am also using socket.io. There is an HTML table, and when a user clicks a button, my code is supposed to replace that table with a new one, however it gives the error message in the title.
Here is my code:
HTML:
```
| | | |
| | | |
| | | |
```
JQuery script:
```
socket.on('resetGranted', function() {
$('table').replaceWith('
//says error is here
| | | |
| | | |
| | | |
');
})
```
How do I fix this?<issue_comment>username_1: Use backtick ``` for multiline string
```js
console.log(`
multi
line
string
here
`);
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: ```
socket.on('resetGranted', function() {
var htmlContent='
| | | |
| | | |
| | | |
';
$('table').replaceWith(htmlContent);
})
```
Upvotes: 0
|
2018/03/16
| 669 | 1,511 |
<issue_start>username_0: A data frame and I want to pick some it by the value in a column. In this case, rows of 'reports' between 10~31.
```
import pandas as pd
data = {'name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy', 'Daisy', 'River', 'Kate', 'David', 'Jack', 'Nancy'],
'month of entry': ["20171002", "20171206", "20171208", "20171018", "20090506", "20171128", "20101216", "20171230", "20171115", "20171030", "20171216"],
'reports': [14, 24, 31, 22, 34, 6, 47, 2, 14, 10, 8]}
df = pd.DataFrame(data)
df_4 = df[(df.reports >= 10) | (df.reports <= 31)]
df_5 = df.query('reports >= 10 | reports <= 31')
print df_4
print df_5
```
Above generated 2 sets of same wrong result (47 is there!):
```
month of entry name reports
0 20171002 Jason 14
1 20171206 Molly 24
2 20171208 Tina 31
3 20171018 Jake 22
4 20090506 Amy 34
5 20171128 Daisy 6
6 20101216 River 47
7 20171230 Kate 2
8 20171115 David 14
9 20171030 Jack 10
10 20171216 Nancy 8
```
What went wrong? Thank you.<issue_comment>username_1: Use backtick ``` for multiline string
```js
console.log(`
multi
line
string
here
`);
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: ```
socket.on('resetGranted', function() {
var htmlContent='
| | | |
| | | |
| | | |
';
$('table').replaceWith(htmlContent);
})
```
Upvotes: 0
|
2018/03/16
| 724 | 2,378 |
<issue_start>username_0: I'm trying to insert a move-only type into a map. I have the following piece of code:
```
#include
class Moveable
{
public:
Moveable() = default;
Moveable(const Moveable&) = delete;
Moveable(Moveable&&) = default;
Moveable& operator=(const Moveable&) = delete;
Moveable& operator=(Moveable&&) = default;
};
int main() {
std::map my\_map;
Moveable my\_moveable\_1, my\_moveable\_2, my\_moveable\_3;
my\_map.insert(std::pair{1, std::move(my\_moveable\_1)}); // (1)
my\_map.insert(std::make\_pair(2, std::move(my\_moveable\_2))); // (2)
my\_map.insert({3, std::move(my\_moveable\_3)}); // (3)
return 0;
}
```
What happens is that using VisualC++ lines 1,2 and 3 compile. In clang and gcc, only 1 and 2 compile and line 3 gives an error (use of deleted copy constructor).
Question: Which compiler is right and why?
Try it here: [rextester](http://rextester.com/XPDYU27100)<issue_comment>username_1: I've tested your code with with g++ 7.3 and it compiles without error!
With clang++ 5.0.1 it doesn't compile.
I think that you are using a feature of the c++20 so the support is not yet ready on all compilers.
Upvotes: 0 <issue_comment>username_2: `std::map::insert` has (among others) the following overloads:
```
// 1.
std::pair insert( const value\_type& value );
// 2. (since C++11)
template< class P >
std::pair insert( P&& value );
// 3. (since C++17)
std::pair insert( value\_type&& value );
```
The first overload obviously cannot be used with move-only types. But the second overload, while available in C++11, does not work with braces here because template argument deduction does not occur with braces (at least in C++11, not sure about later standards).
Both your first and second call to `insert` work in C++11 or later because the compiler knows the type, but the third fails.
C++17 adds another overload that works with braces and move-only types. Now as for why it works with certain compilers and not others, this is most likely due to diffences in the level of C++17 support, or compiler flags.
UPDATE: Just to make it painfully obvious: With using braces I mean using braces only (aggregate initialization or implicit constructor call), i.e. `insert({k,v})`, not `insert(pair{k,v})`. In the latter case, the type is known and the templated overload can be selected even in C++11.
Upvotes: 2 [selected_answer]
|
2018/03/16
| 697 | 2,619 |
<issue_start>username_0: So i'm following the Storm-Crawler-ElasticSearch tutorial and playing around with it.
When Kibana is used to search I've noticed that number of hits for index name 'status' is far greater than 'index'.
Example:
[](https://i.stack.imgur.com/bLO3w.png)
On the top left, you can see that there's **846 hits** **for 'status'** index I assume that means it has crawled through 846 pages.
[](https://i.stack.imgur.com/taK73.png)
Now with **'index' index**, it is shown that there are **only 31 hits**.
I understand that functionallyn index and status are different as status is just responsible for the link meta data. The problem is that it seem that StormCrawler is parsing through many pages and not indexing them.
So what I would like to have is the same amount of hits on 'index' too with the content displayed. Instead of just 31.<issue_comment>username_1: The 'status' index contains the information about all the URLs the crawler either fetched or discovered. This is roughly the equivalent of the crawldb in Nutch.The 'index' index contains the pages that have been fetched, parsed and, well, indexed.
Now if you look at the 'status' field within the status index, you'll find that there are different values indicating whether a URL has been DISCOVERED, FETCHED etc... See [WIKI about status stream](https://github.com/DigitalPebble/storm-crawler/wiki/statusStream).
The ones marked as DISCOVERED haven't yet been fetched and therefore can't be in the 'index' index. If you filter the content of the status index by status:FETCHED you should see a number comparable to the target index.
The Elasticsearch module in SC contains templates for kibana that allow you to see the breakdown of URLs per status. If you haven't done so already, I'd recommend that you look at the [video tutorials on Youtube](https://www.youtube.com/channel/UCUuzkdeQV-XEPUq53bH_b5A/videos).
>
> So what I would like to have is the same amount of hits on 'index' too with the content displayed. Instead of just 31.
>
>
>
It will eventually get there, you just need to give time to the crawler to do its job (and do so politely). Bear in mind that a crawler discovers URLs quicker than it fetches them. Before you ask about speed, please read the [FAQ](http://stormcrawler.net/faq/#howfast).
Upvotes: 3 [selected_answer]<issue_comment>username_2: Redirections and Fetch Errors are another possible reason for a difference. They exist in the status index but not in content index.
Upvotes: 0
|
2018/03/16
| 286 | 854 |
<issue_start>username_0: So, I query a database and I succeed with this query:
```
$sql = 'SELECT * FROM log WHERE dokumen_name LIKE "%A12345%" ORDER BY Id DESC LIMIT 1';
```
and the result is this:
[](https://i.stack.imgur.com/aAXNe.jpg)
Then I want to take from the red box to put it in here:
```
### di Posisi sekarang: php echo $row["lokasi"]; ?
```
but it did not show up, how do I do that?<issue_comment>username_1: ```
### di Posisi sekarang: php echo $row["Lokasi"]; ?
```
Don't forget capitals
Upvotes: 2 <issue_comment>username_2: My code is right, turn out i query after `### di Posisi sekarang: php echo $row["lokasi"]; ?` this code, so it will not work. so, i put the query before the di Posisi sekarang: `php echo $row["lokasi"]; ?` and it works. soory for my misconception.
Upvotes: 0
|
2018/03/16
| 672 | 2,045 |
<issue_start>username_0: I am trying to parse this json file but I cannot store it as an array in php. I have been having a problem with accessing the objects of the json file as i get an "Illegal string offset 'name' error.
My code is as follows:
This is my json:
```
"{\"Data\":[{\"id\":21,\"name\":\"<NAME>\",\"item_code\":\"PG4\"},{\"id\":22,\"name\":\"Dark Fentasy\",\"item_code\":\"DF\"}]}"
```
Here is where I am trying to read the file but I can't access the objects
```
php
// Read JSON file
$json = file_get_contents('results.json');
//Decode JSON
$json_data = json_decode($json);
//print_r($json_data);
echo $json_data[0]['name'];
?
```
Could anybody help me through this please?<issue_comment>username_1: You need to use:
```
$json_data = json_decode($json, true);
```
That will convert json to associative array
And then try:
```
echo $json_data['Data'][0]['name'];
```
Upvotes: 2 <issue_comment>username_2: If you want to use this as an Array you will have to cast it into it like:
```
$json_data = (array) json_decode($json);
```
This will get all Fields from JSON into an PHP Array:
```
Array ( [Data] => Array ( [0] => stdClass Object ( [id] => 21 [name] => <NAME> [item_code] => PG4 ) [1] => stdClass Object ( [id] => 22 [name] => Dark Fentasy [item_code] => DF ) ) )
```
Alternativ you can casting the data into an Object, so you will have to access fields like `$json_data->Data[0]->name`
```
$json_data = (object) json_decode($json);
```
Read more in the `json_decode` Documentation: <http://php.net/manual/en/function.json-decode.php>
Upvotes: -1 [selected_answer]<issue_comment>username_3: ```
php
// Read JSON file
$json = file_get_contents('http://192.168.1.100:8080/demo_phonegap/webservices/result.json');
//Decode JSON
$json_data = json_decode($json, true);
echo json_encode($json_data);
?
```
Here you need to set full path of the JSON file to read JSON File.
and use $json\_data = json\_decode($json, true); to decode the JSON File.
Hope this will help you.
Upvotes: 0
|
2018/03/16
| 1,894 | 8,681 |
<issue_start>username_0: I have two array one is list of hours array and second is my result array. I have to fill `$current_play` array with 24 hours elements.
For that first I search hours array value into second array with `$watch_hour` value. If value not match not value fill with zero value and add array elements with zero value.
first array:
```
$hoursArray=
['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23'];
```
Second Array:
```
$result = array(
array(
"code" => "BA",
"name" => "BARCA",
"current_play" => array(
array(
"whours" => "20",
"value" => "6"
),
array(
"whours" => "5",
"value" => "6"
),
array(
"whours" => "6",
"value" => "6"
),
array(
"whours" => "8",
"value" => "6"
),
array(
"whours" => "9",
"value" => "6"
)
)
)
);
```
I am trying below code but its not working;
```
for($i = 0; $i < count ( $hoursArray ); $i ++) {
foreach ($result as $t){
if($t['watch_hour'] == $hoursArray[$i]){
$result[$v['code']]['cplay'][] = array('whours'=> $hoursArray[$i],'value' => $v['value']);
} else{
$result[$v['code']]['cplay'][] = array('whours'=> $hoursArray[$i],'value' => "0");
}
}
}
```
required array will be:
```
Array
(
[0] => Array
(
[code] => BA
[name] => BARCA
[current_play] => Array
(
[0] => Array
(
[whour] => 0
[value] => 0
)
[1] => Array
(
[whour] => 1
[value] => 0
)
[2] => Array
(
[whour] => 2
[value] => 0
)
[3] => Array
(
[whour] => 3
[value] => 0
)
[4] => Array
(
[whour] => 4
[value] => 6
)
[5] => Array
(
[whour] => 5
[value] => 6
)
[6] => Array
(
[whour] => 6
[value] => 6
)
and so on for each hours element....
)
)
)
```<issue_comment>username_1: The way I've tried to solve it is to extract the hours played out into an indexed array using `array_column()`. Then for each hour check if there is a value and add it in if not found. Then take the result of this and put it back into the main array (sorted)...
```
$currentPlay = array_column($result[0]['current_play'], null, "watch_hour" );
foreach ( $hoursArray as $hour ) {
if ( isset($currentPlay[$hour]) === false ) {
$currentPlay[$hour] = array(
"watch_hour" => "$hour",
"value" => "0"
);
}
}
sort($currentPlay);
$result[0]['current_play'] = $currentPlay;
print_r($result);
```
The output is...
```
Array
(
[0] => Array
(
[code] => CA
[name] => Canada
[current_play] => Array
(
[0] => Array
(
[watch_hour] => 0
[value] => 0
)
[1] => Array
(
[watch_hour] => 1
[value] => 0
)
[2] => Array
(
[watch_hour] => 2
[value] => 0
)
[3] => Array
(
[watch_hour] => 3
[value] => 0
)
[4] => Array
(
[watch_hour] => 4
[value] => 0
)
[5] => Array
(
[watch_hour] => 5
[value] => 6
)
[6] => Array
(
[watch_hour] => 6
[value] => 6
)
[7] => Array
(
[watch_hour] => 7
[value] => 0
)
[8] => Array
(
[watch_hour] => 8
[value] => 6
)
[9] => Array
(
[watch_hour] => 9
[value] => 6
)
[10] => Array
(
[watch_hour] => 10
[value] => 0
)
[11] => Array
(
[watch_hour] => 11
[value] => 0
)
[12] => Array
(
[watch_hour] => 12
[value] => 0
)
[13] => Array
(
[watch_hour] => 13
[value] => 0
)
[14] => Array
(
[watch_hour] => 14
[value] => 0
)
[15] => Array
(
[watch_hour] => 15
[value] => 0
)
[16] => Array
(
[watch_hour] => 16
[value] => 0
)
[17] => Array
(
[watch_hour] => 17
[value] => 0
)
[18] => Array
(
[watch_hour] => 18
[value] => 0
)
[19] => Array
(
[watch_hour] => 19
[value] => 0
)
[20] => Array
(
[watch_hour] => 20
[value] => 6
)
[21] => Array
(
[watch_hour] => 21
[value] => 0
)
[22] => Array
(
[watch_hour] => 22
[value] => 0
)
[23] => Array
(
[watch_hour] => 23
[value] => 0
)
)
)
)
```
**Update:**
To do this for each country...
```
foreach ( $result as $key => $country ) {
// $currentPlay = array_column($country['current_play'], null, "watch_hour" );
$currentPlay = array();
foreach ( $country['current_play'] as $item ) {
$currentPlay[$item["watch_hour"]] = $item;
}
foreach ( $hoursArray as $hour ) {
if ( isset($currentPlay[$hour]) === false ) {
$currentPlay[$hour] = array(
"watch_hour" => "$hour",
"value" => "0"
);
}
}
sort($currentPlay);
$result[$key]['current_play'] = $currentPlay;
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Try this:
```
$currebt_hours = array_column($result[0]['current_play'], 'watch_hour');
$arrdiff = array_diff($hoursArray, $currebt_hours);
foreach ($arrdiff as $value) {
$entry = array();
$entry[watch_hour]=$value;
$entry[value]=0;
$result[0][current_play][]=$entry;
}
```
Upvotes: 0
|
2018/03/16
| 854 | 3,013 |
<issue_start>username_0: I have setup my .htaccess file to redirect <http://example.com> to <https://www.example.com>. But <http://www.example.com> does not redirect to https.
I have my AWS route 53 setup at site.com and an alias of www.example.com pointing to example.com.
Here is my .htaccess file. I cannot for the life of me figure out how to redirect all to <https://www.example.com>.
```
RewriteBase /
RewriteEngine on
#WARNING: NEEDED FOR ONLINE VERSION - always have www in url
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,l]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{HTTP:X-Forwarded-Proto} ^http$
RewriteRule (.*) https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
```<issue_comment>username_1: This will force to redirect to https, add this in the bottom
```
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?!localhost$|127\.0\.0\.1$)(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]
```
Remove
```
RewriteCond %{HTTP:X-Forwarded-Proto} ^http$
RewriteRule (.*) https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
```
Upvotes: 0 <issue_comment>username_2: Redirect HTTP to HTTPS on Apache Using .htaccess File
=====================================================
2. For CentOS/RHEL users, ensure that your have the following line in httpd.conf (mod\_rewrite support – enabled by default).
```
LoadModule rewrite_module modules/mod_rewrite.so
```
3. Now you just need to edit or create .htaccess file in your domain root directory and add these lines to redirect http to https.
```
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
```
Now, when a visitor types http://www.yourdomain.com the server will automatically redirect HTTP to HTTPS https://www.yourdomain.com.
Redirect HTTP to HTTPS on Apache Virtual Host
=============================================
6. Additionally, to force all web traffic to use HTTPS, you can also configure your virtual host file. Normally, there are two important sections of a virtual host configurations if an SSL certificate is enabled; the first contains configurations for the non-secure port 80.
The second is for the secure port 443. To redirect HTTP to HTTPS for all the pages of your website, first open the appropriate virtual host file. Then modify it by adding the configuration below.
```
NameVirtualHost *:80
ServerName www.yourdomain.com
Redirect / https://www.yourdomain.com
ServerName www.yourdomain.com
DocumentRoot /usr/local/apache2/htdocs
SSLEngine On
....
....
```
7. Save and close the file, then restart the HTTP sever like this.
```
$ sudo systemctl restart apache2 [Ubuntu/Debian]
$ sudo systemctl restart httpd [RHEL/CentOS]
```
**Note:** While the is the most recommended solution because it is simpler and safer.
Upvotes: 1
|
2018/03/16
| 400 | 1,329 |
<issue_start>username_0: I'm developing Delphi Firemonkey mobile application. I want to make a rounded button in Firemonkey. How can i do this without using 3rd party components?<issue_comment>username_1: There are a lot of ways to do rounded buttons in FMX. You can use some different components for making buttons like `TRectangle`.
Personally I use and suggest you to use `TRectangle` too.
* Put a `TRectangle` to your FMX Form.
* Set your **Rectangle1**'s `Height` and `Width` values to `70` *(for e.g.)*
* Change `XRadius` and `YRadius` values to `35` *(it depends on height-width values)*
>
> If you want to make more satisfying button, you should change `Fill`
> and `Stroke` properties.
>
>
>
*for e.g.*
* Set `Fill.Color` is `#FF0288D1` *(to use Hax color code, add 2 FF to first digit)*
* Set `Fill.Kind` is `Solid`
If you don't want to use `Stroke` (Border for Button) Set `Stroke.Kind` to `None`.
>
> Also you can add `TLabel` or `TImage` component into your Rectangle1
> component and be sure that you set `Align` property well.
>
>
>
Upvotes: 3 <issue_comment>username_2: Use TCornerButton.
This represents a button with customizable corners.
Use the Corners property to choose the corners to be customized and the CornerType, XRadius, and YRadius properties to customize the corners.
Upvotes: 3
|
2018/03/16
| 1,400 | 4,382 |
<issue_start>username_0: I want to create a docker file using alpine(as it creates a light weight image) with a cron (to execute a task periodically) , As a newbie I initially tried with ubuntu it worked perfect as i took the help from this link [UbuntuExample with CRON](https://www.ekito.fr/people/run-a-cron-job-with-docker/)
Now the problem is it create heavy docker image. I want to convert this same example for alpine but couldn't find the perfect help. Searched a lot of websites but didn't got anything fruitfull.
**MAIN TASK :-**
*My main task is to execute a java jar file through a docker and execute that jar file periodically*
What I have tried till now is created a simple docker file and a crontab file just to print the message periodically.
Main issue I am facing is install cron on alpine.
**DOCKERFILE (DockerFile)**
```
FROM ubuntu:latest
MAINTAINER <EMAIL>
# Add crontab file in the cron directory
ADD crontab /etc/cron.d/hello-cron
# Give execution rights on the cron job
RUN chmod 0644 /etc/cron.d/hello-cron
# Create the log file to be able to run tail
RUN touch /var/log/cron.log
#Install Cron
RUN apt-get update
RUN apt-get -y install cron
# Run the command on container startup
CMD cron && tail -f /var/log/cron.log
```
**CRONTAB (crontab)**
```
* * * * * root echo "Hello world" >> /var/log/cron.log 2>&1
# Don't remove the empty line at the end of this file. It is required to run the cron job
```
This worked perfect for ubuntu but how to achieve it for openjdk:8-jre-alpine<issue_comment>username_1: An example with openjdk:8-jre-alpine image base:
Dockerfile:
```
FROM openjdk:8-jre-alpine
MAINTAINER dperezcabrera
ADD java-version-cron /temp/java-version-cron
RUN cat /temp/java-version-cron >> /etc/crontabs/root
RUN rm /temp/java-version-cron
RUN touch /var/log/cron.log
CMD crond 2>&1 >/dev/null && tail -f /var/log/cron.log
```
Script `java-version-cron`:
```
* * * * * /usr/bin/java -version >>/var/log/cron.log 2>&1
```
Upvotes: 2 <issue_comment>username_2: Finally achieved my task for the executing java jar using cron. Posting the solution so that it could help other beginners.
**Dockerfile**
```
FROM openjdk:8-jre-alpine
MAINTAINER dperezcabrera
RUN apk update && apk add bash
ADD java-version-cron /temp/java-version-cron
RUN chmod 777 /etc/test/
ADD DockerTesting-0.0.1-SNAPSHOT.jar /etc/test
RUN cat /temp/java-version-cron >> /etc/crontabs/root
RUN rm /temp/java-version-cron
RUN touch /var/log/cron.log
CMD crond 2>&1 >/dev/null && tail -f /var/log/cron.log
```
**java-version-cron**
```
* * * * * java -jar /etc/test/DockerTesting-0.0.1-SNAPSHOT.jar >> /var/log/cron.log 2>&1
# Don't remove the empty line at the end of this file. It is required to run the cron job
```
Place your dockerfile , cron and the jar in the same folder or as according to your requirement.
Upvotes: 3 [selected_answer]<issue_comment>username_3: ```
# https://labs.play-with-docker.com/
# add this to dockerfile and execute below two docker commands
# docker build -t cron:test .
# docker run cron:test &
FROM openjdk:8-jdk-alpine
RUN mkdir /app
RUN mkdir /app/bin
RUN mkdir /app/lib
RUN mkdir /app/crontabs
RUN wget https://busybox.net/downloads/binaries/1.30.0-i686/busybox_CROND
RUN mv busybox_CROND /app/bin/crond
RUN wget https://busybox.net/downloads/binaries/1.30.0-i686/busybox_CRONTAB
RUN mv busybox_CRONTAB /app/bin/crontab
RUN chmod +x /app/bin/*
# create HelloWorld.java and compile on the fly, cannot upload files to docker labs
RUN echo 'public class HelloWorld { public static void main(String[]args){ System.out.println("Hello World ..." + new java.util.Date()); } }' > /app/lib/HelloWorld.java
RUN javac /app/lib/HelloWorld.java -d /app/lib
# create entry point script on the fly to avoid windows line ending issues
RUN touch /entrypoint.sh
RUN echo '#!/bin/sh' >> /entrypoint.sh
RUN echo 'echo "* * * * * java -cp /app/lib HelloWorld" | crontab -c /app/crontabs -' >> /entrypoint.sh
RUN echo 'crontab -c /app/crontabs -l' >> /entrypoint.sh
RUN echo 'echo "Executing crond ..."' >> /entrypoint.sh
# -f foreground flag is important, if this returns, docker exits
RUN echo 'crond -f -l 6 -c /app/crontabs' >> /entrypoint.sh
RUN echo 'echo "crond exited !!!"' >> /entrypoint.sh
RUN chmod +x /entrypoint.sh
ENTRYPOINT /entrypoint.sh
```
Upvotes: 0
|