问:
Is there a way I can center edittext input and floating label in TextInputLayout?
I want to apply white background to my EditText along TextInputLayout. However, when I do that, edittext input/hint seems to be at the bottom and I can understand that is because of the reserved space of floating label. However, I want my EditText to be in the center and when floating label comes, they both come to the center. Is there a way I can achieve this?</p>

答:
Try this:

```<code>public static void addTextInputLayoutWatcher(TextInputLayout inputLayout) {

    EditText editText = inputLayout.getEditText();
    if (editText == null)
        return;

    float offset = inputLayout.getResources().getDimensionPixelOffset(R.dimen.inputlayout_focus_offset);

    editText.setOnFocusChangeListener((v, hasFocus) -> {

        float absY = initTag(inputLayout);

        if (hasFocus || editText.getText().length() > 0) {
            inputLayout.setY(absY + offset);
        } else {
            inputLayout.setY(absY);
        }
    });
}

private static float initTag(TextInputLayout inputLayout) {

    float absY;
    Object tag = inputLayout.getTag();

    if (tag == null) {
        // Setting for the first time
        absY = inputLayout.getY();
        inputLayout.setTag(absY);
    } else {
        absY = (float) tag;
    }

    return absY;
}
</code>```

So, whenever the TextInputLayout has focus or is filled-in, give it that offset; otherwise reset it to the original position (which is saved in the view tag in the beginning).

You can set inputlayout_focus_offset to a value that is based on the height of the component, or it can be calculated in a more scaleable way. Either way, there's room for improvement there, but hopefully, this solution will set you off in the right direction.

Body:
Try this:

public static void addTextInputLayoutWatcher(TextInputLayout inputLayout) {

    EditText editText = inputLayout.getEditText();
    if (editText == null)
        return;

    float offset = inputLayout.getResources().getDimensionPixelOffset(R.dimen.inputlayout_focus_offset);

    editText.setOnFocusChangeListener((v, hasFocus) -> {

        float absY = initTag(inputLayout);

        if (hasFocus || editText.getText().length() > 0) {
            inputLayout.setY(absY + offset);
        } else {
            inputLayout.setY(absY);
        }
    });
}

private static float initTag(TextInputLayout inputLayout) {

    float absY;
    Object tag = inputLayout.getTag();

    if (tag == null) {
        // Setting for the first time
        absY = inputLayout.getY();
        inputLayout.setTag(absY);
    } else {
        absY = (float) tag;
    }

    return absY;
}

So, whenever the TextInputLayout has focus or is filled-in, give it that offset; otherwise reset it to the original position (which is saved in the view tag in the beginning).

You can set inputlayout_focus_offset to a value that is based on the height of the component, or it can be calculated in a more scaleable way. Either way, there's room for improvement there, but hopefully, this solution will set you off in the right direction.


来源: stackexchange

问:
g++ crashed when I tried to compile a program with ONE LINE
My program is this:

```<code>#include <iostream>
</code>```

That's it. That's the entire program, just one line.

I tried to compile it with this:

```<code>g++ CVB--OpenPic--00.cpp -o cv
</code>```

and I got this:

```<code>/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 0 has invalid symbol index 11
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 1 has invalid symbol index 12
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 2 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 3 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 4 has invalid symbol index 11
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 5 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 6 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 7 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 8 has invalid symbol index 12
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 9 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 10 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 11 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 12 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 13 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 14 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 15 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 16 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 17 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 18 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 19 has invalid symbol index 21
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_line): relocation 0 has invalid symbol index 2
/usr/lib/gcc/x86_64-linux-gnu/4.8/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status
</code>```

I've compiled dozens of other .cpp files over the past few weeks, and many, many other programs. What exactly is happening here?

答:
Your g++ did not crash. It has just and rightfully emitted some error message, then it completed successfully (with a failure exit code). Actually the error message is given by the linker ld (which  g++ has run after running the cc1plus compiler proper).

Your code does not has any main function (which is the function that starts execution, after construction of static variables, in C++), so you cannot compile it into an executable.

BTW, you should always compile your code with all warnings & debug info, so use

```<code>g++ -Wall -g CVB--OpenPic--00.cpp -o cv
</code>```

Once you did debug your program (using the gdb debugger) you might want to benchmark it. Then ask the compiler to optimize (e.g. by adding -O2 option to g++).

Notice that order of arguments to g++ matters a big lot.

Once your program becomes larger and made of several translation units (e.g. several .cpp files, probably all #include-ing your header file[s]), you'll want to use a build automation tool (like make). Learn also to use a version control system like git and a memory leak detector like valgrind.

ContentLicense: CC BY-SA 3.0

Body:
My program is this:

#include <iostream>

That's it. That's the entire program, just one line.

I tried to compile it with this:

g++ CVB--OpenPic--00.cpp -o cv

and I got this:

/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 0 has invalid symbol index 11
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 1 has invalid symbol index 12
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 2 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 3 has invalid symbol index 2
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 4 has invalid symbol index 11
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 5 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 6 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 7 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 8 has invalid symbol index 12
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 9 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 10 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 11 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 12 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 13 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 14 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 15 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 16 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 17 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 18 has invalid symbol index 13
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 19 has invalid symbol index 21
/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_line): relocation 0 has invalid symbol index 2
/usr/lib/gcc/x86_64-linux-gnu/4.8/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status

I've compiled dozens of other .cpp files over the past few weeks, and many, many other programs. What exactly is happening here?

Body:
Your g++ did not crash. It has just and rightfully emitted some error message, then it completed successfully (with a failure exit code). Actually the error message is given by the linker ld (which  g++ has run after running the cc1plus compiler proper).

Your code does not has any main function (which is the function that starts execution, after construction of static variables, in C++), so you cannot compile it into an executable.

BTW, you should always compile your code with all warnings & debug info, so use

g++ -Wall -g CVB--OpenPic--00.cpp -o cv

Once you did debug your program (using the gdb debugger) you might want to benchmark it. Then ask the compiler to optimize (e.g. by adding -O2 option to g++).

Notice that order of arguments to g++ matters a big lot.

Once your program becomes larger and made of several translation units (e.g. several .cpp files, probably all #include-ing your header file[s]), you'll want to use a build automation tool (like make). Learn also to use a version control system like git and a memory leak detector like valgrind.


问:
click on TableViewCell to open profile view of current user
I am using firebase database and have a table view showing name, age, location, and image of user at index path.row. How would I go about showing another view when the cell is clicked to the users profile with more information and photos of the user. here is the code for my tableView.

```<code> override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return userList.count

}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "prefCell", for: indexPath) as! SFPTableViewCell

      let user = userList[indexPath.row]

    cell.name.text = userList[indexPath.row].name
    cell.location.text = userList[indexPath.row].location

    if let imageURL = user.image {

        cell.imageOne.loadImageUsingCacheWithUrlString(urlString: imageURL)
    }
          return cell
}

    }
</code>```

答:
Using Code use didSelectRowAtIndexPath.

or

Using Storyboard:

step 1: select tableview cell.

step 2: Control + click mouse and drag in destination view.

step 3: Give Any of segue.

step 4: Done.

Body:
I am using firebase database and have a table view showing name, age, location, and image of user at index path.row. How would I go about showing another view when the cell is clicked to the users profile with more information and photos of the user. here is the code for my tableView.

 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return userList.count

}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "prefCell", for: indexPath) as! SFPTableViewCell

      let user = userList[indexPath.row]

    cell.name.text = userList[indexPath.row].name
    cell.location.text = userList[indexPath.row].location

    if let imageURL = user.image {

        cell.imageOne.loadImageUsingCacheWithUrlString(urlString: imageURL)
    }
          return cell
}

    }


问:
Spark Did not find registered driver with class com.mysql.jdbc.Driver
I'm using CDH 5.7.0 and PySpark.  When I run the action such as RDD.count() ,It show errors :Did not find registered driver with class com.mysql.jdbc.Driver

Following is the step

pyspark --driver-class-path /usr/share/java/mysql-connector-java.jar
(the /usr/share/java/mysql-connector-java.jar on every node)

```<code>>>>url ="jdbc:mysql://host/spark?user=root&password=test"
>>> stock_data=sqlContext.read.format("jdbc").option("url",url).option("dbtable","StockPrices").load()
>>> stock_data.printSchema()
root
 |-- date: string (nullable = true)
 |-- open: double (nullable = true)
 |-- high: double (nullable = true)
 |-- low: double (nullable = true)
 |-- close: double (nullable = true)
 |-- volume: long (nullable = true)
 |-- adjclose: double (nullable = true)
>>> stock_data.count()
......
    at java.lang.reflect.Method.invoke(Method.java:606)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:231)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:381)
    at py4j.Gateway.invoke(Gateway.java:259)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:133)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:209)
    at java.lang.Thread.run(Thread.java:745)
**Caused by: java.lang.IllegalStateException: Did not find registered driver with class com.mysql.jdbc.Driver**
    at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$2$$anonfun$3.apply(JdbcUtils.scala:58)
    at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$2$$anonfun$3.apply(JdbcUtils.scala:58)
    at scala.Option.getOrElse(Option.scala:120)
    at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$2.apply(JdbcUtils.scala:57)
    at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$2.apply(JdbcUtils.scala:52)
    at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD$$anon$1.<init>(JDBCRDD.scala:347)
    at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD.compute(JDBCRDD.scala:339)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:306)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:270)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
</code>```

答:
That's failure when I use the link like:

```<code>--driver-class-path /usr/share/java/mysql-connector-java.jar
</code>```

But that's ok when I use the full file path like:

```<code>--driver-class-path /usr/share/java/mysql-connector-java-5.1.28.jar
</code>```

Body:
I'm using CDH 5.7.0 and PySpark.  When I run the action such as RDD.count() ,It show errors :Did not find registered driver with class com.mysql.jdbc.Driver

Following is the step

pyspark --driver-class-path /usr/share/java/mysql-connector-java.jar
(the /usr/share/java/mysql-connector-java.jar on every node)

>>>url ="jdbc:mysql://host/spark?user=root&password=test"
>>> stock_data=sqlContext.read.format("jdbc").option("url",url).option("dbtable","StockPrices").load()
>>> stock_data.printSchema()
root
 |-- date: string (nullable = true)
 |-- open: double (nullable = true)
 |-- high: double (nullable = true)
 |-- low: double (nullable = true)
 |-- close: double (nullable = true)
 |-- volume: long (nullable = true)
 |-- adjclose: double (nullable = true)
>>> stock_data.count()
......
    at java.lang.reflect.Method.invoke(Method.java:606)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:231)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:381)
    at py4j.Gateway.invoke(Gateway.java:259)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:133)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:209)
    at java.lang.Thread.run(Thread.java:745)
**Caused by: java.lang.IllegalStateException: Did not find registered driver with class com.mysql.jdbc.Driver**
    at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$2$$anonfun$3.apply(JdbcUtils.scala:58)
    at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$2$$anonfun$3.apply(JdbcUtils.scala:58)
    at scala.Option.getOrElse(Option.scala:120)
    at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$2.apply(JdbcUtils.scala:57)
    at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$2.apply(JdbcUtils.scala:52)
    at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD$$anon$1.<init>(JDBCRDD.scala:347)
    at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD.compute(JDBCRDD.scala:339)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:306)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:270)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)

Body:
That's failure when I use the link like:

--driver-class-path /usr/share/java/mysql-connector-java.jar

But that's ok when I use the full file path like:

--driver-class-path /usr/share/java/mysql-connector-java-5.1.28.jar


问:
Parsley.js: Multiple group validation
I am currently using Parsley.js 2.2.0. I had group validation working when there was one group, but I added another group, but it still tries to validate the old group.

eventinfo group example.

```<code><input maxlength="45" value="" type="text" name="address" id="Address" class="form-control floatlabel" placeholder="Address" tabindex="75" title="Address" data-parsley-required data-parsley-group="eventinfo">
</code>```

call to validate eventinfo group

```<code>if (elEventForm.parsley().validate('eventinfo') === false) { return }
</code>```

quoteinfo group example.

```<code><input data-parsley-required data-parsley-group="quoteinfo" maxlength="75" value="" type="email" name="email" id="Email" class="form-control floatlabel" placeholder="Email" tabindex="45" title="Email">
</code>```

call to validate quoteinfo group

```<code>if (elEventForm.parsley().validate('quoteinfo') === false) {
      return
   }
</code>```

答:
There have been 20 releases since 2.2.0.

Current API is ...validate({group: 'eventinfo'})

Title: Parsley.js: Multiple group validation

Body:
I am currently using Parsley.js 2.2.0. I had group validation working when there was one group, but I added another group, but it still tries to validate the old group.

eventinfo group example.

<input maxlength="45" value="" type="text" name="address" id="Address" class="form-control floatlabel" placeholder="Address" tabindex="75" title="Address" data-parsley-required data-parsley-group="eventinfo">

call to validate eventinfo group

if (elEventForm.parsley().validate('eventinfo') === false) { return }

quoteinfo group example.

<input data-parsley-required data-parsley-group="quoteinfo" maxlength="75" value="" type="email" name="email" id="Email" class="form-control floatlabel" placeholder="Email" tabindex="45" title="Email">

call to validate quoteinfo group

if (elEventForm.parsley().validate('quoteinfo') === false) {
      return
   }


问:
Space concatenated with an expression is sometimes dropped
JSFiddle contains:

```<code>var d = " " + true ? "am" : "pm";
var e = " " + "am";
alert("|" + d + "|");
alert("|" + e + "|");
</code>```

Why does d not contain the leading space?

答:
You are trying to do same like
var d = (" " +  true) ? "am" : "pm"
In your case the condition is " " +  true.
Correct condition is var d = (true ? "am" : "pm")

```<code>var d = " " + true ? "am" : "pm";   //output    |am|
var d = (" " + true) ? "am" : "pm";   //output  |am|
var d = " " + (true ? "am" : "pm");   //output  | am|
</code>```

Body:
JSFiddle contains:

var d = " " + true ? "am" : "pm";
var e = " " + "am";
alert("|" + d + "|");
alert("|" + e + "|");

Why does d not contain the leading space?

Body:
You are trying to do same like
var d = (" " +  true) ? "am" : "pm"
In your case the condition is " " +  true.
Correct condition is var d = (true ? "am" : "pm")

var d = " " + true ? "am" : "pm";   //output    |am|
var d = (" " + true) ? "am" : "pm";   //output  |am|
var d = " " + (true ? "am" : "pm");   //output  | am|


问:
Android Sending Email
I Wrote This Code To Send An Email But Give Me " No App Can Perform This action " Error ?!! Can Any One Help Me .!

```<code>public class MainActivity extends Activity {
Button startBtn;
Intent chooser = null , emailIntent = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);

    startBtn = (Button) findViewById(R.id.sendEmail);
    startBtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            sendEmail();
        }
    });
}
</code>```

protected void sendEmail()

```<code>    {
        String[] TO = {"a.gadelkareem94@gmail.com"};
        emailIntent = new Intent(Intent.ACTION_SEND);
        emailIntent.setData(Uri.parse("mailto:"));
        emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
        emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Hello");
        emailIntent.putExtra(Intent.EXTRA_TEXT, "Thanks For Your Job");
        emailIntent.setType("message/rfc822");
        emailIntent.setPackage("com.Gmail");
        chooser = Intent.createChooser(emailIntent, "Send Email");
        startActivity(chooser);
    }
</code>```

}

but no emails Send

答:
There are a couple of issues with your snippet.

The one that's responsible for the "No app can perform this action" is emailIntent.setPackage("com.Gmail"). This will only consider apps with the application ID "com.Gmail" as target for the intent. However, "com.Gmail" is not the application ID of the Gmail app. You shouldn't limit the selection anyway. So let's just drop this line.

ACTION_SEND is the generic Share action. This will work with email apps, but there's a better way: use ACTION_SENDTO. With ACTION_SENDTO the only input is a mailto URI. One that includes the recipient, subject and text from your example looks like this: mailto:a.gadelkareem94@gmail.com?subject=Hello&body=Thanks%20For%20Your%20Job

Users tend to use only one email app and set that one as default. By using Intent.createChooser() you make them have to manually choose their email app every time (assuming there's more than one installed).

Considering all this we end up with:

```<code>Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData(Uri.parse("mailto:a.gadelkareem94@gmail.com?subject=Hello&body=Thanks%20For%20Your%20Job"));
try {
    startActivity(emailIntent);
} catch (ActivityNotFoundException e) {
    //TODO: Display message that no email app was found
}
</code>```

To make all this less painful I wrote the library EmailIntentBuilder. You can use it like this:

```<code>EmailIntentBuilder.from(context)
        .to("a.gadelkareem94@gmail.com")
        .subject("Hello")
        .body("Thanks For Your Job")
        .start();
</code>```

I also wrote a blog post explaining all of this in more detail: Sending Email using Intents.

Title: Android Sending Email

Body:
I Wrote This Code To Send An Email But Give Me " No App Can Perform This action " Error ?!! Can Any One Help Me .!

public class MainActivity extends Activity {
Button startBtn;
Intent chooser = null , emailIntent = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);

    startBtn = (Button) findViewById(R.id.sendEmail);
    startBtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            sendEmail();
        }
    });
}

protected void sendEmail()

    {
        String[] TO = {"a.gadelkareem94@gmail.com"};
        emailIntent = new Intent(Intent.ACTION_SEND);
        emailIntent.setData(Uri.parse("mailto:"));
        emailIntent.putExtra(Intent.EXTRA_EMAIL, TO);
        emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Hello");
        emailIntent.putExtra(Intent.EXTRA_TEXT, "Thanks For Your Job");
        emailIntent.setType("message/rfc822");
        emailIntent.setPackage("com.Gmail");
        chooser = Intent.createChooser(emailIntent, "Send Email");
        startActivity(chooser);
    }

}

but no emails Send

Body:
There are a couple of issues with your snippet.

The one that's responsible for the "No app can perform this action" is emailIntent.setPackage("com.Gmail"). This will only consider apps with the application ID "com.Gmail" as target for the intent. However, "com.Gmail" is not the application ID of the Gmail app. You shouldn't limit the selection anyway. So let's just drop this line.

ACTION_SEND is the generic Share action. This will work with email apps, but there's a better way: use ACTION_SENDTO. With ACTION_SENDTO the only input is a mailto URI. One that includes the recipient, subject and text from your example looks like this: mailto:a.gadelkareem94@gmail.com?subject=Hello&body=Thanks%20For%20Your%20Job

Users tend to use only one email app and set that one as default. By using Intent.createChooser() you make them have to manually choose their email app every time (assuming there's more than one installed).

Considering all this we end up with:

Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData(Uri.parse("mailto:a.gadelkareem94@gmail.com?subject=Hello&body=Thanks%20For%20Your%20Job"));
try {
    startActivity(emailIntent);
} catch (ActivityNotFoundException e) {
    //TODO: Display message that no email app was found
}

To make all this less painful I wrote the library EmailIntentBuilder. You can use it like this:

EmailIntentBuilder.from(context)
        .to("a.gadelkareem94@gmail.com")
        .subject("Hello")
        .body("Thanks For Your Job")
        .start();

I also wrote a blog post explaining all of this in more detail: Sending Email using Intents.


问:
How to return two different View inside onCreateView method of fragment depending on results of asyn background call to server in Android?
i have a fragment in which we have to return  the view depending on result of Background thread. but currently i get null pointer Exception.

this is our Fragment class:

```<code>public class ProductFragment extends Fragment {

String ss = null;
GridView gridView;
ArrayList<ProductParameterBO> productlist;
GridViewCustomAdapter gridViewCustomAdapter;
ArrayList<View> viewList;
public int itemSelected = 0;
private static boolean isFirstTime = false;
RequestObject requestObject;
JSONObject jsonObject1;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String responseString = "{\"rqBody\" :" + "{"+ "}}" ;
    try {
        requestObject = new RequestObject();
        requestObject.setJsonSend(responseString);
        requestObject.setUrl(NetworkUrl.GETPRODUCTINFO_URL);

        new GetProductInfo().execute(requestObject);
    }
    catch (Exception e){
        e.printStackTrace();
    }

}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    if (jsonObject1.length()==0){
        View rootView =  inflater.inflate(R.layout.empty_catalog_item,null);

        TextView configure = (TextView)rootView.findViewById(R.id.text_conf);

        configure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(getActivity(),SplitViewActivity.class);
                intent.putExtra("firstTab","1stTabs");
                startActivity(intent);

            }
        });

        TextView text_here = (TextView)rootView.findViewById(R.id.text_here);
        text_here.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        FloatingActionButton fab = (FloatingActionButton)rootView.findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(getActivity(), EditUploadActivity.class);
                startActivity(intent);

            }
        });

      return rootView;
    }else {

        View rootView =  inflater.inflate(R.layout.fragment_product,null);

        gridView =(GridView)rootView.findViewById(R.id.gridView);

        viewList = new ArrayList<View>();

        productlist = new ArrayList<ProductParameterBO>();

        productlist.add(new ProductParameterBO("Type","Numeric","yes","yes"));
        productlist.add(new ProductParameterBO("Typess","Numericss","yesss","yesss"));
        productlist.add(new ProductParameterBO("Typess","Numericss","yesss","yesss"));
        productlist.add(new ProductParameterBO("Typess","Numericss","yesss","yesss"));
        gridViewCustomAdapter = new GridViewCustomAdapter(getActivity(),productlist);
        gridView.setAdapter(gridViewCustomAdapter);
        gridViewCustomAdapter.notifyDataSetChanged();

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {

                if (isFirstTime) {
                    viewList.get(itemSelected).setVisibility(View.GONE);
                    Log.d("Inside", "Selected");
                }

                RelativeLayout relativeLayout = (RelativeLayout) v.findViewById(R.id.grid_img_ovrly);
                viewList.add(relativeLayout);
                relativeLayout.setVisibility(View.VISIBLE);
                itemSelected = position;
                isFirstTime = true;

                Log.d("outside", "Selected");

            }
        });

        FloatingActionButton fab = (FloatingActionButton)rootView.findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(getActivity(), EditUploadActivity.class);
                startActivity(intent);

            }
        });

        return rootView;
    }

   // return inflater.inflate(R.layout.fragment_product,null);
}

private class GetProductInfo extends AsyncTask<RequestObject, Void, JSONObject> {
    private ProgressDialog pDialog;
    private Context context;

    @Override
    protected JSONObject doInBackground(RequestObject... arg0) {
        // Creating service handler class instance
        ServiceCallHandler sh = new ServiceCallHandler();
        // RequestObject requestObject = new RequestObject();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(arg0[0], ServiceCallHandler.POST);

        Log.d("Response: ", "> " + jsonStr);

        String status=null;
        JSONObject jsonObject = new JSONObject();

        if (jsonStr != null) {

            try {
                JSONObject jsonObj = new JSONObject(jsonStr);
                jsonObject = jsonObj.getJSONObject("rsBody");
               /* if (jsonObject.has("name")){
                    status = jsonObject.getString("status");

                }*/

            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return jsonObject;
    }

    @Override
    protected void onPostExecute(JSONObject result) {
        super.onPostExecute(result);

        jsonObject1 = new JSONObject();
        jsonObject1 = result;

    }

}
</code>```

}

i want that depending on JsonObject1 we return view inside oncreate method,but we get nullpointer exception. i think oncreate method called before background thread.How can i call my server call first and depending on their results we show the view.

Any help would be appreciated in advance....

答:
```<code>@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View view=inflater.inflate(R.layout.activity_notification_fragment,container,false); //first layout

    View view1=inflater.inflate(R.layout.activity_offline,container,false);             //second layout

    //On back press for view....

    view.setFocusableInTouchMode(true);
    view.requestFocus();
    view.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (event.getAction() == KeyEvent.ACTION_DOWN) {

                mFragmentManager = getActivity().getSupportFragmentManager();
                mFragmentTransaction = mFragmentManager.beginTransaction();

                mFragmentTransaction.addToBackStack("home");
                mFragmentTransaction.replace(R.id.containerView, new HomeFragment()).commit();
                return true;
            }

            return false;
        }
    });

    //On back press for view1....

    view1.setFocusableInTouchMode(true);
    view1.requestFocus();
    view1.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (event.getAction() == KeyEvent.ACTION_DOWN) {

                mFragmentManager = getActivity().getSupportFragmentManager();
                mFragmentTransaction = mFragmentManager.beginTransaction();

                mFragmentTransaction.addToBackStack("home");
                mFragmentTransaction.replace(R.id.containerView, new HomeFragment()).commit();
                return true;
            }

            return false;
        }
    });

    /* Depending on the condition....returning the views...*/
    if(notificationsList.size() == 0){
        return view1;
    }else{
        return view;
    }

}
</code>```

Body:
i have a fragment in which we have to return  the view depending on result of Background thread. but currently i get null pointer Exception.

this is our Fragment class:

public class ProductFragment extends Fragment {

String ss = null;
GridView gridView;
ArrayList<ProductParameterBO> productlist;
GridViewCustomAdapter gridViewCustomAdapter;
ArrayList<View> viewList;
public int itemSelected = 0;
private static boolean isFirstTime = false;
RequestObject requestObject;
JSONObject jsonObject1;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String responseString = "{\"rqBody\" :" + "{"+ "}}" ;
    try {
        requestObject = new RequestObject();
        requestObject.setJsonSend(responseString);
        requestObject.setUrl(NetworkUrl.GETPRODUCTINFO_URL);

        new GetProductInfo().execute(requestObject);
    }
    catch (Exception e){
        e.printStackTrace();
    }

}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    if (jsonObject1.length()==0){
        View rootView =  inflater.inflate(R.layout.empty_catalog_item,null);

        TextView configure = (TextView)rootView.findViewById(R.id.text_conf);

        configure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(getActivity(),SplitViewActivity.class);
                intent.putExtra("firstTab","1stTabs");
                startActivity(intent);

            }
        });

        TextView text_here = (TextView)rootView.findViewById(R.id.text_here);
        text_here.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        FloatingActionButton fab = (FloatingActionButton)rootView.findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(getActivity(), EditUploadActivity.class);
                startActivity(intent);

            }
        });

      return rootView;
    }else {

        View rootView =  inflater.inflate(R.layout.fragment_product,null);

        gridView =(GridView)rootView.findViewById(R.id.gridView);

        viewList = new ArrayList<View>();

        productlist = new ArrayList<ProductParameterBO>();

        productlist.add(new ProductParameterBO("Type","Numeric","yes","yes"));
        productlist.add(new ProductParameterBO("Typess","Numericss","yesss","yesss"));
        productlist.add(new ProductParameterBO("Typess","Numericss","yesss","yesss"));
        productlist.add(new ProductParameterBO("Typess","Numericss","yesss","yesss"));
        gridViewCustomAdapter = new GridViewCustomAdapter(getActivity(),productlist);
        gridView.setAdapter(gridViewCustomAdapter);
        gridViewCustomAdapter.notifyDataSetChanged();

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {

                if (isFirstTime) {
                    viewList.get(itemSelected).setVisibility(View.GONE);
                    Log.d("Inside", "Selected");
                }

                RelativeLayout relativeLayout = (RelativeLayout) v.findViewById(R.id.grid_img_ovrly);
                viewList.add(relativeLayout);
                relativeLayout.setVisibility(View.VISIBLE);
                itemSelected = position;
                isFirstTime = true;

                Log.d("outside", "Selected");

            }
        });

        FloatingActionButton fab = (FloatingActionButton)rootView.findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(getActivity(), EditUploadActivity.class);
                startActivity(intent);

            }
        });

        return rootView;
    }

   // return inflater.inflate(R.layout.fragment_product,null);
}

private class GetProductInfo extends AsyncTask<RequestObject, Void, JSONObject> {
    private ProgressDialog pDialog;
    private Context context;

    @Override
    protected JSONObject doInBackground(RequestObject... arg0) {
        // Creating service handler class instance
        ServiceCallHandler sh = new ServiceCallHandler();
        // RequestObject requestObject = new RequestObject();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(arg0[0], ServiceCallHandler.POST);

        Log.d("Response: ", "> " + jsonStr);

        String status=null;
        JSONObject jsonObject = new JSONObject();

        if (jsonStr != null) {

            try {
                JSONObject jsonObj = new JSONObject(jsonStr);
                jsonObject = jsonObj.getJSONObject("rsBody");
               /* if (jsonObject.has("name")){
                    status = jsonObject.getString("status");

                }*/

            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return jsonObject;
    }

    @Override
    protected void onPostExecute(JSONObject result) {
        super.onPostExecute(result);

        jsonObject1 = new JSONObject();
        jsonObject1 = result;

    }

}

}

i want that depending on JsonObject1 we return view inside oncreate method,but we get nullpointer exception. i think oncreate method called before background thread.How can i call my server call first and depending on their results we show the view.

Any help would be appreciated in advance....


问:
Spring Integration expression to verify string contains another string with equals ignore case
I am using spring integration in my project. I need to verify if one of the nodes value in my response contains a string by ignoring case sensitivity.
I have to see if the databaseName value contains DB2 by ignoring case sensitivity.

I am using the following expression to verify, but it's not working.

```<code>expression="T(java.util.regex.Pattern).compile(T(java.util.regex.Pattern).quote('DB2'), T(java.util.regex.Pattern).CASE_INSENSITIVE).matcher(#xpath(payload, '//databaseName')).find()"
</code>```

I referred the following links before framing my expression:

https://docs.spring.io/spring/docs/current/spring-framework-reference/html/expressions.html

How to call a method of a class from expression in spring Integration

How to check if a String contains another String in a case insensitive manner in Java?

Am I missing anything in the expression?

答:
As per Gary Russell's suggestion, The following expression worked for me.

```<code>#xpath(payload, '//databaseName').toLowerCase().contains('db2')
</code>```

Body:
I am using spring integration in my project. I need to verify if one of the nodes value in my response contains a string by ignoring case sensitivity.
I have to see if the databaseName value contains DB2 by ignoring case sensitivity.

I am using the following expression to verify, but it's not working.

expression="T(java.util.regex.Pattern).compile(T(java.util.regex.Pattern).quote('DB2'), T(java.util.regex.Pattern).CASE_INSENSITIVE).matcher(#xpath(payload, '//databaseName')).find()"

I referred the following links before framing my expression:

https://docs.spring.io/spring/docs/current/spring-framework-reference/html/expressions.html

How to call a method of a class from expression in spring Integration

How to check if a String contains another String in a case insensitive manner in Java?

Am I missing anything in the expression?

Body:
As per Gary Russell's suggestion, The following expression worked for me.

#xpath(payload, '//databaseName').toLowerCase().contains('db2')


问:
Show div class one by one
In blade.php file in Laravel I create a class name flip, when I click on it a class named panel is showed. Here $post_list contains some data which is collected from database table in previous controller. Using @for I can create many flip and slide class, but problem is when I click any of the flip class all slide class is showed. How can I click on one flip class and show the respective slide class?

Here is code for creating flip and panel class

```<code>@foreach($post_list as $post_list)
<div class="flip">Click to slide the panel down or up</div>
<div class="panel">
<ul>
<li>
<input type="checkbox" name="selected[]">
<label>
<img src="{{ URL::asset($post_list-->image)}}" />
<p>{{$post_list->id->name}}</p>
</label>
</li>
</ul>
</div>
@endforeach
</code>```

And here is my javascript code -

```<code><script>
$(document).ready(function(){
$(".flip").click(function(){
    $(".panel").slideToggle("slow");
});
});
</script>
</code>```

答:
You are toggling all .panel divs. You need to take only the required .panel in context.

```<code><script>
    $(document).ready(function(){
        $(".flip").click(function(){
            $(this).next('.panel').slideToggle("slow");
        });
    });
</script>
</code>```

Title: Show div class one by one

Body:
In blade.php file in Laravel I create a class name flip, when I click on it a class named panel is showed. Here $post_list contains some data which is collected from database table in previous controller. Using @for I can create many flip and slide class, but problem is when I click any of the flip class all slide class is showed. How can I click on one flip class and show the respective slide class?

Here is code for creating flip and panel class

@foreach($post_list as $post_list)

Click to slide the panel down or up

<input type="checkbox" name="selected[]">

image)}}" />

{{$post_list->id->name}}

@endforeach

And here is my javascript code -

Body:
You are toggling all .panel divs. You need to take only the required .panel in context.

<script>
    $(document).ready(function(){
        $(".flip").click(function(){
            $(this).next('.panel').slideToggle("slow");
        });
    });
</script>


问:
difference size of list make Dataframe in pandas and how to make dummies
```<code>  index            0          1         2         3         4        5  \
0         0       Action  Adventure   Fantasy    Sci-Fi       NaN      NaN
1         1       Action  Adventure   Fantasy       NaN       NaN      NaN
2         2       Action  Adventure  Thriller       NaN       NaN      NaN
3         3       Action   Thriller       NaN       NaN       NaN      NaN
4         4  Documentary        NaN       NaN       NaN       NaN      NaN
5         5       Action  Adventure    Sci-Fi       NaN       NaN      NaN
6         6       Action  Adventure   Romance       NaN       NaN      NaN
7         7    Adventure  Animation    Comedy    Family   Fantasy  Musical
8         8       Action  Adventure    Sci-Fi       NaN       NaN      NaN
9         9    Adventure     Family   Fantasy   Mystery       NaN      NaN
</code>```

i have data like this...

but i have no idea to make dummies with difference size of data frame data in pandas python....

```<code>Action  Adventure   Fantasy Sci-Fi  Thriller    Ducumentary Romance Animation   Comedy  family  Fantasy Musical Mystery
0   1   1   1   1   0   0   0   0   0   0   0   0   0
1   1   1   1   0   0   0   0   0   0   0   0   0   0
2   1   1   0   0   1   0   0   0   0   0   0   0   0
3   1   0   0   0   1   0   0   0   0   0   0   0   0
4   0   0   0   0   0   1   0   0   0   0   0   0   0
5   1   1   0   1   0   0   0   0   0   0   0   0   0
6   1   1   0   0   0   0   1   0   0   0   0   0   0
7   0   1   0   0   0   0   0   1   1   1   1   1   0
8   1   1   0   1   0   0   0   0   0   0   0   0   0
9   0   1   0   0   0   0   0   0   0   1   1   0   1
</code>```

like this....

答:
I think you can use get_dummies, but first need remove first column by drop or iloc, then create Series by stack.

Output have duplicated index, so need groupby by index and aggregate max:

```<code>df = pd.get_dummies(df.drop('index', axis=1).stack()).groupby(level=0).max()
#alternative solution
#df = pd.get_dummies(df.iloc[:, 1:].stack()).groupby(level=0).max()
print (df)
   Action  Adventure  Animation  Comedy  Documentary  Family  Fantasy  \
0       1          1          0       0            0       0        1
1       1          1          0       0            0       0        1
2       1          1          0       0            0       0        0
3       1          0          0       0            0       0        0
4       0          0          0       0            1       0        0
5       1          1          0       0            0       0        0
6       1          1          0       0            0       0        0
7       0          1          1       1            0       1        1
8       1          1          0       0            0       0        0
9       0          1          0       0            0       1        1

   Musical  Mystery  Romance  Sci-Fi  Thriller
0        0        0        0       1         0
1        0        0        0       0         0
2        0        0        0       0         1
3        0        0        0       0         1
4        0        0        0       0         0
5        0        0        0       1         0
6        0        0        1       0         0
7        1        0        0       0         0
8        0        0        0       1         0
9        0        1        0       0         0
</code>```

Body:
  index            0          1         2         3         4        5  \
0         0       Action  Adventure   Fantasy    Sci-Fi       NaN      NaN
1         1       Action  Adventure   Fantasy       NaN       NaN      NaN
2         2       Action  Adventure  Thriller       NaN       NaN      NaN
3         3       Action   Thriller       NaN       NaN       NaN      NaN
4         4  Documentary        NaN       NaN       NaN       NaN      NaN
5         5       Action  Adventure    Sci-Fi       NaN       NaN      NaN
6         6       Action  Adventure   Romance       NaN       NaN      NaN
7         7    Adventure  Animation    Comedy    Family   Fantasy  Musical
8         8       Action  Adventure    Sci-Fi       NaN       NaN      NaN
9         9    Adventure     Family   Fantasy   Mystery       NaN      NaN

i have data like this...

but i have no idea to make dummies with difference size of data frame data in pandas python....

Action  Adventure   Fantasy Sci-Fi  Thriller    Ducumentary Romance Animation   Comedy  family  Fantasy Musical Mystery
0   1   1   1   1   0   0   0   0   0   0   0   0   0
1   1   1   1   0   0   0   0   0   0   0   0   0   0
2   1   1   0   0   1   0   0   0   0   0   0   0   0
3   1   0   0   0   1   0   0   0   0   0   0   0   0
4   0   0   0   0   0   1   0   0   0   0   0   0   0
5   1   1   0   1   0   0   0   0   0   0   0   0   0
6   1   1   0   0   0   0   1   0   0   0   0   0   0
7   0   1   0   0   0   0   0   1   1   1   1   1   0
8   1   1   0   1   0   0   0   0   0   0   0   0   0
9   0   1   0   0   0   0   0   0   0   1   1   0   1

like this....

Body:
I think you can use get_dummies, but first need remove first column by drop or iloc, then create Series by stack.

Output have duplicated index, so need groupby by index and aggregate max:

df = pd.get_dummies(df.drop('index', axis=1).stack()).groupby(level=0).max()
#alternative solution
#df = pd.get_dummies(df.iloc[:, 1:].stack()).groupby(level=0).max()
print (df)
   Action  Adventure  Animation  Comedy  Documentary  Family  Fantasy  \
0       1          1          0       0            0       0        1
1       1          1          0       0            0       0        1
2       1          1          0       0            0       0        0
3       1          0          0       0            0       0        0
4       0          0          0       0            1       0        0
5       1          1          0       0            0       0        0
6       1          1          0       0            0       0        0
7       0          1          1       1            0       1        1
8       1          1          0       0            0       0        0
9       0          1          0       0            0       1        1

   Musical  Mystery  Romance  Sci-Fi  Thriller
0        0        0        0       1         0
1        0        0        0       0         0
2        0        0        0       0         1
3        0        0        0       0         1
4        0        0        0       0         0
5        0        0        0       1         0
6        0        0        1       0         0
7        1        0        0       0         0
8        0        0        0       1         0
9        0        1        0       0         0


问:
Why Java process hang?
There are many threads in my Java server.
It hangs when one thread recursive invoke a method infinitely.
After the method is invoked 54 times, the process hang, and there is no any log like "StackOverFlow" or "OutOfMemory".

However, as I know, only the thread with the problem will crash, other threads can work normally.

environment:

Linux version 2.6.31-20-server
  (buildd@crested) (gcc version 4.4.1
  (Ubuntu 4.4.1-4ubuntu8) ) java version
  "1.6.0_18" Java(TM) SE Runtime
  Environment (build 1.6.0_18-b07) Java
  HotSpot(TM) 64-Bit Server VM (build
  16.0-b13, mixed mode)

答:
All threads require stack space. Every time you invoke a method recursively the stack expands - eventually you're gonna run out.

The number of iterations you manage depends on the exact code being run.

ContentLicense: CC BY-SA 2.5

Title: Why Java process hang?


问:
OS: Does the following algorithm comply with the conditions to have processes adequately progressing?
"Given the following algorithm for two processes, 0 and 1:

```<code>Process (i)
REPEAT WHILE Interest [j] = 1 DO;
START
     Interest [i]:=1;
     Critical Section;
     Interest [i]:=0;
     Non-critical Section;
END
</code>```

where i=0,1; j=1-i;, and Interest is a vector of shared variables of size 2 and initialized at 0.

Check if the mutual exclusion requirements are met. Does the algorithm comply with the conditions to have processes adequately progressing?"

Can you help me reasoning this problem from my OS class?

答:
The algorithm does guarantee progress, but does not guarantee mutual exclusion. Its very clear that when both the process simultaneously try to enter the critical section, they both will succeed in entering the critical section, and the reason is:

both Interest [0] := 0  and Interest [1] := 0, therefore both the processes would come out of the while loop.

Body:
"Given the following algorithm for two processes, 0 and 1:

Process (i)
REPEAT WHILE Interest [j] = 1 DO;
START
     Interest [i]:=1;
     Critical Section;
     Interest [i]:=0;
     Non-critical Section;
END

where i=0,1; j=1-i;, and Interest is a vector of shared variables of size 2 and initialized at 0.

Check if the mutual exclusion requirements are met. Does the algorithm comply with the conditions to have processes adequately progressing?"

Can you help me reasoning this problem from my OS class?


问:
Pretty URL Conditional Rewrite
Our site allows for a pretty url 'etest.me/1234' where '1234' is a client id. As you can see below it redirects to our route.php file where we do our redirect. The problem is when a client uses 'etest.me' without the '/1234' they get the apache 'The requested URL /go/ was not found on this server.' message. I would like the url to go to another page when the '/1234' is missing.

Note that we have the domain and path forwarded to the non-existing '/go' directory so the rules below will catch it. The following is in our .htaccess file in the root directory.

```<code>RewriteEngine On
#restrict rewriting URLs ONLY to paths that DO NOT exist
RewriteCond %{SCRIPT_FILENAME} !-d
# commented out to speed up looking since we are not processig file names anyway
#RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^go/([a-zA-Z0-9/]+)$ ./route\.php?go=$1
</code>```

答:
I accepted the answer by Sahil and posted the entire logic below for others to use:

```<code>Domain: etest.me
Pretty URL: etest.me/1234 (where '1234' is a client id)
Forwarded to: etesting.io/go (with forward path option selected so the '/1234' will be include in the forward)
</code>```

Note: There is no '/go' directory on the server, '/go' is used to trigger the redirect.

Wanted 'etest.me' (without client id) to go to index file in root directory.

Here is the rewrite rules in .htaccess:

```<code>RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^go/([a-zA-Z0-9/]*)$ ./route\.php?go=$1
</code>```

Here is the route.php code:

```<code><?php

if($_GET['go']){
    $a = explode('/', $_GET['go']);
    $c = count($a);
    if($c == 1 || $c == 2){
        header('location: ../../index.php?aid=' . $a[0] . '&tid=' . $a[1]);
        exit;
    }
    else{
        die('Invalid URL');
    }
}
else{
    header('location: ../index.php');
    exit;
}
</code>```

And finally the index.php file:

```<code>if($_GET['aid'] && $_GET['tid']){
    header('location: test/register.php?aid=' . $_GET['aid'] . '&tid=' . $_GET['tid']);
    exit;
}
elseif($_GET['aid']){
    header('location: test/index.php?aid=' . $_GET['aid']);
    exit;
}
else{
    header('location: account/index.php?' . $_SERVER['QUERY_STRING']);
    exit;
}
</code>```

Hope this helps somebody in the future.

I would like a more elegant solution but it's behind me for now...

Title: Pretty URL Conditional Rewrite

Body:
Our site allows for a pretty url 'etest.me/1234' where '1234' is a client id. As you can see below it redirects to our route.php file where we do our redirect. The problem is when a client uses 'etest.me' without the '/1234' they get the apache 'The requested URL /go/ was not found on this server.' message. I would like the url to go to another page when the '/1234' is missing.

Note that we have the domain and path forwarded to the non-existing '/go' directory so the rules below will catch it. The following is in our .htaccess file in the root directory.

RewriteEngine On
#restrict rewriting URLs ONLY to paths that DO NOT exist
RewriteCond %{SCRIPT_FILENAME} !-d
# commented out to speed up looking since we are not processig file names anyway
#RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^go/([a-zA-Z0-9/]+)$ ./route\.php?go=$1

Body:
I accepted the answer by Sahil and posted the entire logic below for others to use:

Domain: etest.me
Pretty URL: etest.me/1234 (where '1234' is a client id)
Forwarded to: etesting.io/go (with forward path option selected so the '/1234' will be include in the forward)

Note: There is no '/go' directory on the server, '/go' is used to trigger the redirect.

Wanted 'etest.me' (without client id) to go to index file in root directory.

Here is the rewrite rules in .htaccess:

RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^go/([a-zA-Z0-9/]*)$ ./route\.php?go=$1

Here is the route.php code:

<?php

if($_GET['go']){
    $a = explode('/', $_GET['go']);
    $c = count($a);
    if($c == 1 || $c == 2){
        header('location: ../../index.php?aid=' . $a[0] . '&tid=' . $a[1]);
        exit;
    }
    else{
        die('Invalid URL');
    }
}
else{
    header('location: ../index.php');
    exit;
}

And finally the index.php file:

if($_GET['aid'] && $_GET['tid']){
    header('location: test/register.php?aid=' . $_GET['aid'] . '&tid=' . $_GET['tid']);
    exit;
}
elseif($_GET['aid']){
    header('location: test/index.php?aid=' . $_GET['aid']);
    exit;
}
else{
    header('location: account/index.php?' . $_SERVER['QUERY_STRING']);
    exit;
}

Hope this helps somebody in the future.

I would like a more elegant solution but it's behind me for now...


问:
How to tackle this session problem in ASP.NET,VB.NET?
How to tackle this session problem in ASP.NET,VB.NET?

The following requirement are there:

When the authorized user logs into the system that user is not allowed to login from another computer or in different browser other than that user is using right at this time.

The remedy we applied was: We have kept "Is_Loggedin" as a column with data type "bit" in a mst_vendor as a table name. When a user logs in we set the flag, Is_Loggedin, to "1" and each time when someone tries to log in using this account, the system is showing the error "The user is already logged in.".

When the user logs out it turns to "0" as the logout procedure calls as soon as the user clicks the log out button.

Problem scenario:

When the user closes the browser the flag remains the same, that is, "1".

When power gets off, it remains the same as "1".

If the session timeouts after a predefined value it remains the same.

There may be different scenarios other than this.

Is there any way so that we can store this internal flagging for the user's login status using the application object?

It may improve efficiency of the system and also eliminates the above problematic scenarios.

答:
You could keep a pulse going in script, and when the pulse times out, consider the user finished with that session.

The benefit to this is that you can tell the difference between the user sitting idle on the site and the user leaving the site.


问:
Update column using the same column from another table and gruoping by another and make sum equal
There are 2 tables - DepoSevkDetay и SatisDetay. Both have columns - Miktar and UrunID. I need to make sum of Miktar in DepoSevkDetay for each UrunID equal to sum of Miktar in SatisDetay. Query I ve written cant handle it.    What am I doing wrong? Considering that count of records in two tables is not equal

        ```</p>

<code>UPDATE
    Table_A
SET
    Table_A.[Miktar] = (((Table_B.Miktar)/Table_C.c) +
(case when ((Table_B.Miktar) % Table_C.c  < Table_C.r) then 1
                                                        else 0 end ))
FROM
    [Retail].[dbo].[tb_DepoSevkDetay] AS Table_A
    INNER JOIN (
                SELECT SUM(Miktar)as Miktar, UrunID
                FROM tb_SatisDetay
                GROUP BY UrunID ) AS Table_B
        ON Table_A.[UrunID] = Table_B.[UrunID]
    INNER JOIN (
                SELECT COUNT([UrunID]) AS c, ROW_NUMBER() OVER (ORDER BY UrunID) r, UrunID as UrunID
                FROM tb_DepoSevkDetay
                GROUP BY UrunID ) AS Table_C
        ON Table_B.[UrunID] = Table_C.[UrunID]
</code>```

答:
I would do it like this. First, I would make Miktar=0:

```<code>UPDATE [Retail].[dbo].[tb_DepoSevkDetay]
SET [Miktar] = 0
</code>```

Then I would update all records but first with the Miktar equal to sum(Miktar)/(Count(*))

```<code>; with Table_A as (
 SELECT *,
 ROW_NUMBER() OVER (PARTITION BY UrunID ORDER BY UrunID) as rn,
 COUNT(*) OVER (PARTITION BY UrunID) as c
 [Retail].[dbo].[tb_DepoSevkDetay])
UPDATE
    Table_A
SET
    Table_A.[Miktar] = Table_B.Miktar/(Table_A.c)
FROM
    Table_A
    INNER JOIN (
                SELECT SUM(Miktar)as Miktar, UrunID
                FROM tb_SatisDetay
                GROUP BY UrunID ) AS Table_B
        ON Table_A.[UrunID] = Table_B.[UrunID]
WHERE Table_A.c > 0 and Table_A.rn > 1
</code>```

And then I would update the remaining [Miktar]'s, like this:

```<code>UPDATE
    Table_A
SET
    Table_A.[Miktar] = Table_B.Miktar - Table_C.Miktar
FROM
    [Retail].[dbo].[tb_DepoSevkDetay] AS Table_A
    INNER JOIN (
                SELECT SUM(Miktar)as Miktar, UrunID
                FROM tb_SatisDetay
                GROUP BY UrunID ) AS Table_B
        ON Table_A.[UrunID] = Table_B.[UrunID]
    INNER JOIN (
                SELECT SUM(Miktar)as Miktar, UrunID
                FROM [Retail].[dbo].[tb_DepoSevkDetay]
                GROUP BY UrunID ) AS Table_C
        ON Table_A.[UrunID] = Table_C.[UrunID]
WHERE Table_A.[Miktar] = 0
</code>```

Hopefully, it makes sense

Body:
There are 2 tables - DepoSevkDetay и SatisDetay. Both have columns - Miktar and UrunID. I need to make sum of Miktar in DepoSevkDetay for each UrunID equal to sum of Miktar in SatisDetay. Query I ve written cant handle it.    What am I doing wrong? Considering that count of records in two tables is not equal

UPDATE
    Table_A
SET
    Table_A.[Miktar] = (((Table_B.Miktar)/Table_C.c) +
(case when ((Table_B.Miktar) % Table_C.c  < Table_C.r) then 1
                                                        else 0 end ))
FROM
    [Retail].[dbo].[tb_DepoSevkDetay] AS Table_A
    INNER JOIN (
                SELECT SUM(Miktar)as Miktar, UrunID
                FROM tb_SatisDetay
                GROUP BY UrunID ) AS Table_B
        ON Table_A.[UrunID] = Table_B.[UrunID]
    INNER JOIN (
                SELECT COUNT([UrunID]) AS c, ROW_NUMBER() OVER (ORDER BY UrunID) r, UrunID as UrunID
                FROM tb_DepoSevkDetay
                GROUP BY UrunID ) AS Table_C
        ON Table_B.[UrunID] = Table_C.[UrunID]

Body:
I would do it like this. First, I would make Miktar=0:

UPDATE [Retail].[dbo].[tb_DepoSevkDetay]
SET [Miktar] = 0

Then I would update all records but first with the Miktar equal to sum(Miktar)/(Count(*))

; with Table_A as (
 SELECT *,
 ROW_NUMBER() OVER (PARTITION BY UrunID ORDER BY UrunID) as rn,
 COUNT(*) OVER (PARTITION BY UrunID) as c
 [Retail].[dbo].[tb_DepoSevkDetay])
UPDATE
    Table_A
SET
    Table_A.[Miktar] = Table_B.Miktar/(Table_A.c)
FROM
    Table_A
    INNER JOIN (
                SELECT SUM(Miktar)as Miktar, UrunID
                FROM tb_SatisDetay
                GROUP BY UrunID ) AS Table_B
        ON Table_A.[UrunID] = Table_B.[UrunID]
WHERE Table_A.c > 0 and Table_A.rn > 1

And then I would update the remaining [Miktar]'s, like this:

UPDATE
    Table_A
SET
    Table_A.[Miktar] = Table_B.Miktar - Table_C.Miktar
FROM
    [Retail].[dbo].[tb_DepoSevkDetay] AS Table_A
    INNER JOIN (
                SELECT SUM(Miktar)as Miktar, UrunID
                FROM tb_SatisDetay
                GROUP BY UrunID ) AS Table_B
        ON Table_A.[UrunID] = Table_B.[UrunID]
    INNER JOIN (
                SELECT SUM(Miktar)as Miktar, UrunID
                FROM [Retail].[dbo].[tb_DepoSevkDetay]
                GROUP BY UrunID ) AS Table_C
        ON Table_A.[UrunID] = Table_C.[UrunID]
WHERE Table_A.[Miktar] = 0

Hopefully, it makes sense


问:
C fgets function not working when ran on linux
So the problem I'm having is that I believe fgets is getting skipped over but I'm not sure. The code I'm working with looks like this:

```<code>void createAccount()
{
ignore = fseek(stdin,0,SEEK_END);
printf("Creating A New Account:\n");
FILE *input;
input = fopen("accounts.txt", "a");
if (input == NULL)
{
    printf("Error opening accounts.txt file!\n");
    exit(1);
}
char username[USERNAME_LENGTH];
char password[PASSWORD_LENGTH];
char type[CHOICE_LENGTH];
char age[10];
printf("Username:");
a = fgets(username,USERNAME_LENGTH,stdin);
char *fileOpener = malloc(strlen(username));
if (fileOpener!=NULL) {
    strcpy(fileOpener, username);
}
const size_t end = strlen(fileOpener) - 1;
if (fileOpener[end] == '\n')
    fileOpener[end] = '\0';
ignore = fseek(stdin,0,SEEK_END);
printf("age:");
a = fgets(age,10,stdin);
ignore = fseek(stdin,0,SEEK_END);
printf("Password:");
a = fgets(password,PASSWORD_LENGTH,stdin);
ignore = fseek(stdin,0,SEEK_END);
printf("Account Type:");
a = fgets(type,CHOICE_LENGTH,stdin);
ignore = fseek(stdin,0,SEEK_END);
ignore = fputs(username,input);
ignore = fputs(password,input);
ignore = fputs(type,input);
fclose(input);
FILE *newFile = fopen(fileOpener,"ab+");
char *newAge = malloc(strlen("AGE: " + strlen(age)));
if (newAge!=NULL) {
    strcpy(newAge,"AGE: ");
    strcat(newAge,age);
}
char *newName =malloc(strlen("NAME: " + strlen(username)));
if (newName!=NULL) {
    strcpy(newName,"NAME: ");
    strcat(newName,username);
}
ignore = fputs(newName,newFile);
ignore = fputs(newAge,newFile);
ignore = fputs("MEDICATIONS: ",newFile);
ignore = fputs("\nVITALS: ",newFile);
ignore = fputs("\nHISTORY: ",newFile);
ignore = fputs("\nALLERGIES: ",newFile);
fclose(newFile);
printf("Account made.");
}
</code>```

It scans user input and puts it inside a file. The problem is that it never prompts for the user name, and instead prompts straight for the age, that output looks like this:

```<code>Creating A New Account:
Username:age:(user input)
Password: (user input)
Account Type: (user input)
</code>```

when it should look like this:

```<code>Creating A New Account:
Username:(user input)
age:(user input)
Password:(user input)
Account Type:(user input)
</code>```

so it looks like the fgets for the username is just being ignored? And it just goes straight to age, printing it on the same line. This code works fine when I run it on a mac, but I only have this problem on linux. Please help.

答:
```<code>void createAccount()
{
fseek(stdin,0,SEEK_END);
printf("Creating A New Account:\n");
FILE *input = fopen("accounts.txt", "a");
if (input == NULL)
{
    printf("Error opening accounts.txt file!\n");
    exit(1);
}
char username[USERNAME_LENGTH];
char password[PASSWORD_LENGTH];
char type[CHOICE_LENGTH];
char age[10];
printf("Username:");
fgets(username,USERNAME_LENGTH,stdin);
char *fileOpener = malloc(strlen(username));
 if (fileOpener == NULL)
{
    printf("cannot allocating the space in malloc!\n");
    exit(1);
}
    strcpy(fileOpener, username);
const size_t end = strlen(fileOpener) - 1;
if (fileOpener[end] == '\n')
    fileOpener[end] = '\0';
fseek(stdin,0,SEEK_END);
printf("age:");
fgets(age,10,stdin);
fseek(stdin,0,SEEK_END);
printf("Password:");
fgets(password,PASSWORD_LENGTH,stdin);
fseek(stdin,0,SEEK_END);
printf("Account Type:");
fgets(type,CHOICE_LENGTH,stdin);
fseek(stdin,0,SEEK_END);
fputs(username,input);
fputs(password,input);
fputs(type,input);
fclose(input);
FILE *newFile = fopen(fileOpener,"ab+");
char *newAge = malloc(strlen("AGE: ") + strlen(age));
if (newAge == NULL) {
   printf("cannot allocating the space in malloc!\n");
    exit(1);
}
 strcpy(newAge,"AGE: ");
    strcat(newAge,age);
char *newName =malloc(strlen("NAME: ") + strlen(username));
if (newName == NULL) {
   printf("cannot allocating the space in malloc!\n");
    exit(1);
}
strcpy(newName,"NAME: ");
    strcat(newName,username);
fputs(newName,newFile);
fputs(newAge,newFile);
fputs("MEDICATIONS: ",newFile);
fputs("\nVITALS: ",newFile);
fputs("\nHISTORY: ",newFile);
fputs("\nALLERGIES: ",newFile);
fclose(newFile);
printf("Account made.");
}
</code>```

you had some problems in your code.

1: you don't need to write a = or ignore = if you don't realy use them.

2: change malloc(strlen("things" + strlen(things))) to `malloc(strlen("things: ") + strlen(things))

check fore more...

Body:
So the problem I'm having is that I believe fgets is getting skipped over but I'm not sure. The code I'm working with looks like this:

void createAccount()
{
ignore = fseek(stdin,0,SEEK_END);
printf("Creating A New Account:\n");
FILE *input;
input = fopen("accounts.txt", "a");
if (input == NULL)
{
    printf("Error opening accounts.txt file!\n");
    exit(1);
}
char username[USERNAME_LENGTH];
char password[PASSWORD_LENGTH];
char type[CHOICE_LENGTH];
char age[10];
printf("Username:");
a = fgets(username,USERNAME_LENGTH,stdin);
char *fileOpener = malloc(strlen(username));
if (fileOpener!=NULL) {
    strcpy(fileOpener, username);
}
const size_t end = strlen(fileOpener) - 1;
if (fileOpener[end] == '\n')
    fileOpener[end] = '\0';
ignore = fseek(stdin,0,SEEK_END);
printf("age:");
a = fgets(age,10,stdin);
ignore = fseek(stdin,0,SEEK_END);
printf("Password:");
a = fgets(password,PASSWORD_LENGTH,stdin);
ignore = fseek(stdin,0,SEEK_END);
printf("Account Type:");
a = fgets(type,CHOICE_LENGTH,stdin);
ignore = fseek(stdin,0,SEEK_END);
ignore = fputs(username,input);
ignore = fputs(password,input);
ignore = fputs(type,input);
fclose(input);
FILE *newFile = fopen(fileOpener,"ab+");
char *newAge = malloc(strlen("AGE: " + strlen(age)));
if (newAge!=NULL) {
    strcpy(newAge,"AGE: ");
    strcat(newAge,age);
}
char *newName =malloc(strlen("NAME: " + strlen(username)));
if (newName!=NULL) {
    strcpy(newName,"NAME: ");
    strcat(newName,username);
}
ignore = fputs(newName,newFile);
ignore = fputs(newAge,newFile);
ignore = fputs("MEDICATIONS: ",newFile);
ignore = fputs("\nVITALS: ",newFile);
ignore = fputs("\nHISTORY: ",newFile);
ignore = fputs("\nALLERGIES: ",newFile);
fclose(newFile);
printf("Account made.");
}

It scans user input and puts it inside a file. The problem is that it never prompts for the user name, and instead prompts straight for the age, that output looks like this:

Creating A New Account:
Username:age:(user input)
Password: (user input)
Account Type: (user input)

when it should look like this:

Creating A New Account:
Username:(user input)
age:(user input)
Password:(user input)
Account Type:(user input)

so it looks like the fgets for the username is just being ignored? And it just goes straight to age, printing it on the same line. This code works fine when I run it on a mac, but I only have this problem on linux. Please help.

Body:
void createAccount()
{
fseek(stdin,0,SEEK_END);
printf("Creating A New Account:\n");
FILE *input = fopen("accounts.txt", "a");
if (input == NULL)
{
    printf("Error opening accounts.txt file!\n");
    exit(1);
}
char username[USERNAME_LENGTH];
char password[PASSWORD_LENGTH];
char type[CHOICE_LENGTH];
char age[10];
printf("Username:");
fgets(username,USERNAME_LENGTH,stdin);
char *fileOpener = malloc(strlen(username));
 if (fileOpener == NULL)
{
    printf("cannot allocating the space in malloc!\n");
    exit(1);
}
    strcpy(fileOpener, username);
const size_t end = strlen(fileOpener) - 1;
if (fileOpener[end] == '\n')
    fileOpener[end] = '\0';
fseek(stdin,0,SEEK_END);
printf("age:");
fgets(age,10,stdin);
fseek(stdin,0,SEEK_END);
printf("Password:");
fgets(password,PASSWORD_LENGTH,stdin);
fseek(stdin,0,SEEK_END);
printf("Account Type:");
fgets(type,CHOICE_LENGTH,stdin);
fseek(stdin,0,SEEK_END);
fputs(username,input);
fputs(password,input);
fputs(type,input);
fclose(input);
FILE *newFile = fopen(fileOpener,"ab+");
char *newAge = malloc(strlen("AGE: ") + strlen(age));
if (newAge == NULL) {
   printf("cannot allocating the space in malloc!\n");
    exit(1);
}
 strcpy(newAge,"AGE: ");
    strcat(newAge,age);
char *newName =malloc(strlen("NAME: ") + strlen(username));
if (newName == NULL) {
   printf("cannot allocating the space in malloc!\n");
    exit(1);
}
strcpy(newName,"NAME: ");
    strcat(newName,username);
fputs(newName,newFile);
fputs(newAge,newFile);
fputs("MEDICATIONS: ",newFile);
fputs("\nVITALS: ",newFile);
fputs("\nHISTORY: ",newFile);
fputs("\nALLERGIES: ",newFile);
fclose(newFile);
printf("Account made.");
}

you had some problems in your code.

1: you don't need to write a = or ignore = if you don't realy use them.

2: change malloc(strlen("things" + strlen(things))) to `malloc(strlen("things: ") + strlen(things))

check fore more...


问:
VBScript writing to file error
I've coded a script that has the basic function of creating a .txt file and then writing some text into it. But whenever I run it I get;

Script: F\Known.vbs
    Line: 17
    Char:1
    Error: Permission denied
    Code: 800A0046
    Source: Microsoft VBScript runtime error

My code goes as such;

Option Explicit
    Dim objFSO, objFSOText, objFolder, r, objFile
    Dim strDirectory, strFile
    Dim objNetwork
    do
    randomize
    r = int(rnd*91372183) + 1
    strDirectory = "C:\Users\" & CreateObject("Wscript.Network").UserName & "\Desktop"
    strFile = "\" & r & ".txt"
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
    Const ReadOnly = 1
    Set objFile = objFSO.GetFile(strDirectory & strFile)
    objFile.Attributes = objFile.Attributes XOR ReadOnly
    Const ForWriting = 2
    Set objNetwork = CreateObject("Wscript.Network")
    Set objFile = objFSO.OpenTextFile(strDirectory & strFile, ForWriting)
    objFile.Write "f672f7fd12d6wf6df26df6f26dfs6f6qf67wqqf6dfw6f16fw76df61f62fd"
    objFile.WriteBlankLines(1)
    loop

I have looked at other questions of a similar nature, trying to add read-write attributes, etc. but none have worked.

答:
You have to run your script with administrative privileges .
To do so open command prompt as administrator and navigate to the directory where the script is contained in and then run the following command

```<code>>cscript {Your script name}
</code>```

Title: VBScript writing to file error

Body:
You have to run your script with administrative privileges .
To do so open command prompt as administrator and navigate to the directory where the script is contained in and then run the following command

>cscript {Your script name}


问:
Regex - Match multiple lines that don't end with character
I have been racking my brain with a particular regex problem I currently have.

I want to match values that that could span multiple lines.
If the data spans multiple lines it will end with as space than an underscore " _" but there may be valid text in the line that will have a space and underscore before it "This _is".

See the below text sample:

```<code>This is d_ata 1
_This is _
data 2
This _is data 3a
This _
is _
data 4
</code>```

Results would be the following

Match 1

```<code>This is d_ata 1
</code>```

Match 2

```<code>_This is _
data 2
</code>```

Match 3

```<code>This _is data 3a
</code>```

Match 4

```<code>This _
is _
data 4
</code>```

I don't care about the content matching, just ensuring I get the correct end of line matches.

Edit:
See Robby's negative look behind solution below.

Had tried it with some additional logic earlier which turned out to be to complicated for my regex provider to handle, simplified it and it worked a treat.

答:
This PCRE expression should deliver the required result:

```<code>/^.*?(?<! _)$/gms
</code>```

This is using the negative lookbehind (?<! _) in combination with the multiline flag (m) to match up to a line end that is not preceded by _. The single-line flag (s) ensures that the dot also matches newlines.

Here's a regex101 example.

Body:
I have been racking my brain with a particular regex problem I currently have.

I want to match values that that could span multiple lines.
If the data spans multiple lines it will end with as space than an underscore " _" but there may be valid text in the line that will have a space and underscore before it "This _is".

See the below text sample:

This is d_ata 1
_This is _
data 2
This _is data 3a
This _
is _
data 4

Results would be the following

Match 1

This is d_ata 1

Match 2

_This is _
data 2

Match 3

This _is data 3a

Match 4

This _
is _
data 4

I don't care about the content matching, just ensuring I get the correct end of line matches.

Edit:
See Robby's negative look behind solution below.

Had tried it with some additional logic earlier which turned out to be to complicated for my regex provider to handle, simplified it and it worked a treat.

Body:
This PCRE expression should deliver the required result:

/^.*?(?<! _)$/gms

This is using the negative lookbehind (?<! _) in combination with the multiline flag (m) to match up to a line end that is not preceded by _. The single-line flag (s) ensures that the dot also matches newlines.

Here's a regex101 example.


问:
Extra height pixels in simple div with img
I am having difficulty determining where the extra pixels of height are coming from for the div in this simple layout. My expectation would be that the image would determine the height of the div but instead it appears to be a few pixels larger. The pixels I am trying to get rid of are shown in blue. Any ideas?

Oh, I have added a button to explicitly set the height of the image parent div properly using javascript - my question is really where is it getting that extra height from in the first place, or how can I do this without javascript?

function change() {
  var image = document.getElementById('image1ID');
  var width = image.naturalWidth;
  var height = image.naturalHeight;
  var imageDIV = document.getElementById('image1DIV');

  imageDIV.style.height = (100 * height / width) + "px";

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="image1DIV" style="background-color:#00f;">
  <img id="image1ID" style="width:100px;" src="http://www.imageno.com/thumbs/20170330/73dlz3sr4pfy.jpg">
</div>

<button onclick="change()">change height of parent div</button></code>```

答:
Add vertical-align:middle to your img tag. It removes extra space.

function change() {
  var image = document.getElementById('image1ID');
  var width = image.naturalWidth;
  var height = image.naturalHeight;
  var imageDIV = document.getElementById('image1DIV');

  imageDIV.style.height = (100 * height / width) + "px";

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#image1ID {
  vertical-align: middle;
}</code>```

<button onclick="change()">change height of parent div</button>```

Body:
I am having difficulty determining where the extra pixels of height are coming from for the div in this simple layout. My expectation would be that the image would determine the height of the div but instead it appears to be a few pixels larger. The pixels I am trying to get rid of are shown in blue. Any ideas?

Oh, I have added a button to explicitly set the height of the image parent div properly using javascript - my question is really where is it getting that extra height from in the first place, or how can I do this without javascript?

function change() {
  var image = document.getElementById('image1ID');
  var width = image.naturalWidth;
  var height = image.naturalHeight;
  var imageDIV = document.getElementById('image1DIV');

  imageDIV.style.height = (100 * height / width) + "px";

}

<button onclick="change()">change height of parent div</button>

Body:
Add vertical-align:middle to your img tag. It removes extra space.

function change() {
  var image = document.getElementById('image1ID');
  var width = image.naturalWidth;
  var height = image.naturalHeight;
  var imageDIV = document.getElementById('image1DIV');

  imageDIV.style.height = (100 * height / width) + "px";

}

#image1ID {
  vertical-align: middle;
}

<div id="image1DIV" style="background-color:#00f;">
  <img id="image1ID" style="width:100px;" src="http://www.imageno.com/thumbs/20170330/73dlz3sr4pfy.jpg">
</div>

<button onclick="change()">change height of parent div</button>


问:
Generate a random even number inside a range?
Here's the format I'm following:

```<code> int randomNum = rand.nextInt((max - min) + 1) + min;
</code>```

So here's my code. I'm trying to get a random even number between 1 and 100:

```<code> Random rand = new Random();
 int randomNum = rand.nextInt((100 - 2) + 1) + 2;
</code>```

I saw one solution is to multiply the number by 2, but that breaches the intended range.

I thought of doing a bunch of if statements to solve this, but it seems overly complex. Is there a relatively simple solution?

答:
In Java 1.7 or later, I would use ThreadLocalRandom:

```<code>import java.util.concurrent.ThreadLocalRandom;

// Get even random number within range [min, max]
// Start with an even minimum and add random even number from the remaining range
public static int randEvenInt(int min, int max) {
    if (min % 2 != 0) ++min;
    return min + 2*ThreadLocalRandom.current().nextInt((max-min)/2+1);
}

// Get odd random number within range [min, max]
// Start with an odd minimum and add random even number from the remaining range
public static int randOddInt(int min, int max) {
    if (min % 2 == 0) ++min;
    return min + 2*ThreadLocalRandom.current().nextInt((max-min)/2+1);
}
</code>```

The reason to use ThreadLocalRandom is explained here. Also note, that the reason we +1 to the input to ThreadLocalRandom.nextInt() is to make sure the max is included in the range.

Body:
Here's the format I'm following:

 int randomNum = rand.nextInt((max - min) + 1) + min;

So here's my code. I'm trying to get a random even number between 1 and 100:

 Random rand = new Random();
 int randomNum = rand.nextInt((100 - 2) + 1) + 2;

I saw one solution is to multiply the number by 2, but that breaches the intended range.

I thought of doing a bunch of if statements to solve this, but it seems overly complex. Is there a relatively simple solution?

Body:
In Java 1.7 or later, I would use ThreadLocalRandom:

import java.util.concurrent.ThreadLocalRandom;

// Get even random number within range [min, max]
// Start with an even minimum and add random even number from the remaining range
public static int randEvenInt(int min, int max) {
    if (min % 2 != 0) ++min;
    return min + 2*ThreadLocalRandom.current().nextInt((max-min)/2+1);
}

// Get odd random number within range [min, max]
// Start with an odd minimum and add random even number from the remaining range
public static int randOddInt(int min, int max) {
    if (min % 2 == 0) ++min;
    return min + 2*ThreadLocalRandom.current().nextInt((max-min)/2+1);
}

The reason to use ThreadLocalRandom is explained here. Also note, that the reason we +1 to the input to ThreadLocalRandom.nextInt() is to make sure the max is included in the range.


问:
How to make buttons in python/pygame?
I'm making a game in pygame and on the first screen I want there to be buttons that you can press to (i) start the game, (ii) load a new screen with instructions, and (iii) exit the program.

I've found this code online for button making, but I don't really understand it (I'm not that good at object oriented programming). If I could get some explanation as to what it's doing that would be great. Also, when I use it and try to open a file on my computer using the file path, I get the error sh: filepath :Permission denied, which I don't know how to solve.

```<code>#load_image is used in most pygame programs for loading images
def load_image(name, colorkey=None):
    fullname = os.path.join('data', name)
    try:
        image = pygame.image.load(fullname)
    except pygame.error, message:
        print 'Cannot load image:', fullname
        raise SystemExit, message
    image = image.convert()
    if colorkey is not None:
        if colorkey is -1:
            colorkey = image.get_at((0,0))
        image.set_colorkey(colorkey, RLEACCEL)
    return image, image.get_rect()
class Button(pygame.sprite.Sprite):
    """Class used to create a button, use setCords to set
        position of topleft corner. Method pressed() returns
        a boolean and should be called inside the input loop."""
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image, self.rect = load_image('button.png', -1)

    def setCords(self,x,y):
        self.rect.topleft = x,y

    def pressed(self,mouse):
        if mouse[0] > self.rect.topleft[0]:
            if mouse[1] > self.rect.topleft[1]:
                if mouse[0] < self.rect.bottomright[0]:
                    if mouse[1] < self.rect.bottomright[1]:
                        return True
                    else: return False
                else: return False
            else: return False
        else: return False
def main():
    button = Button() #Button class is created
    button.setCords(200,200) #Button is displayed at 200,200
    while 1:
        for event in pygame.event.get():
            if event.type == MOUSEBUTTONDOWN:
                mouse = pygame.mouse.get_pos()
                if button.pressed(mouse):   #Button's pressed method is called
                    print ('button hit')
if __name__ == '__main__': main()
</code>```

Thank you to anyone who can help me.

答:
The 'code' you have found online is not that good. All you need to make a button is this. Put this near the beginning of your code:

```<code>def Buttonify(Picture, coords, surface):
    image = pygame.image.load(Picture)
    imagerect = image.get_rect()
    imagerect.topright = coords
    surface.blit(image,imagerect)
    return (image,imagerect)
</code>```

Put the following in your game loop. Also somewhere in your game loop:

```<code>Image = Buttonify('YOUR_PICTURE.png',THE_COORDS_OF_THE_BUTTONS_TOP_RIGHT_CORNER, THE_NAME_OF_THE_SURFACE)
</code>```

Also put this in your game loop wherever you have done for event in pygame.event.get

```<code>if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
     mouse = pygame.mouse.get_pos
     if Image[1].collidepoint(mouse):
        #code if button is pressed goes here
</code>```

So, buttonify loads the image that will be on the button. This image must be a .jpg file or any other PICTURE file in the same directory as the code. Picture is its name. The name must have .jpg or anything else after it and the name must be in quotation marks. The coords parameter in Buttonify is the top-right coordinate on your screen or window that opens from pygame. The surface is this thing:

```<code>blahblahblah = pygame.surface.set_mode((WindowSize))
 /|\
  |
  Surface's Name
</code>```

So it the function makes something called 'image' which is a pygame surface, it puts a rectangle around it called 'imagerect' (to set it at a location and for the second parameter when blitting,) and then it sets it's location, and blits it on the second to last last line.

The next bit of code makes 'Image' a tuple of both 'image' and 'imagerect.'

The last code has if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: which basically means if the left mouse button is pressed. This code MUST be in for event in pygame.event.get. The next line makes mouse a tuple of the mouses position. The last line checks if the mouse cursor is inside the area of Image[1], which as we know is 'imagerect.' The code follows that.

Tell me if I need to explain further.

Title: How to make buttons in python/pygame?

Body:
I'm making a game in pygame and on the first screen I want there to be buttons that you can press to (i) start the game, (ii) load a new screen with instructions, and (iii) exit the program.

I've found this code online for button making, but I don't really understand it (I'm not that good at object oriented programming). If I could get some explanation as to what it's doing that would be great. Also, when I use it and try to open a file on my computer using the file path, I get the error sh: filepath :Permission denied, which I don't know how to solve.

#load_image is used in most pygame programs for loading images
def load_image(name, colorkey=None):
    fullname = os.path.join('data', name)
    try:
        image = pygame.image.load(fullname)
    except pygame.error, message:
        print 'Cannot load image:', fullname
        raise SystemExit, message
    image = image.convert()
    if colorkey is not None:
        if colorkey is -1:
            colorkey = image.get_at((0,0))
        image.set_colorkey(colorkey, RLEACCEL)
    return image, image.get_rect()
class Button(pygame.sprite.Sprite):
    """Class used to create a button, use setCords to set
        position of topleft corner. Method pressed() returns
        a boolean and should be called inside the input loop."""
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image, self.rect = load_image('button.png', -1)

    def setCords(self,x,y):
        self.rect.topleft = x,y

    def pressed(self,mouse):
        if mouse[0] > self.rect.topleft[0]:
            if mouse[1] > self.rect.topleft[1]:
                if mouse[0] < self.rect.bottomright[0]:
                    if mouse[1] < self.rect.bottomright[1]:
                        return True
                    else: return False
                else: return False
            else: return False
        else: return False
def main():
    button = Button() #Button class is created
    button.setCords(200,200) #Button is displayed at 200,200
    while 1:
        for event in pygame.event.get():
            if event.type == MOUSEBUTTONDOWN:
                mouse = pygame.mouse.get_pos()
                if button.pressed(mouse):   #Button's pressed method is called
                    print ('button hit')
if __name__ == '__main__': main()

Thank you to anyone who can help me.

Body:
The 'code' you have found online is not that good. All you need to make a button is this. Put this near the beginning of your code:

def Buttonify(Picture, coords, surface):
    image = pygame.image.load(Picture)
    imagerect = image.get_rect()
    imagerect.topright = coords
    surface.blit(image,imagerect)
    return (image,imagerect)

Put the following in your game loop. Also somewhere in your game loop:

Image = Buttonify('YOUR_PICTURE.png',THE_COORDS_OF_THE_BUTTONS_TOP_RIGHT_CORNER, THE_NAME_OF_THE_SURFACE)

Also put this in your game loop wherever you have done for event in pygame.event.get

if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
     mouse = pygame.mouse.get_pos
     if Image[1].collidepoint(mouse):
        #code if button is pressed goes here

So, buttonify loads the image that will be on the button. This image must be a .jpg file or any other PICTURE file in the same directory as the code. Picture is its name. The name must have .jpg or anything else after it and the name must be in quotation marks. The coords parameter in Buttonify is the top-right coordinate on your screen or window that opens from pygame. The surface is this thing:

blahblahblah = pygame.surface.set_mode((WindowSize))
 /|\
  |
  Surface's Name

So it the function makes something called 'image' which is a pygame surface, it puts a rectangle around it called 'imagerect' (to set it at a location and for the second parameter when blitting,) and then it sets it's location, and blits it on the second to last last line.

The next bit of code makes 'Image' a tuple of both 'image' and 'imagerect.'

The last code has if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: which basically means if the left mouse button is pressed. This code MUST be in for event in pygame.event.get. The next line makes mouse a tuple of the mouses position. The last line checks if the mouse cursor is inside the area of Image[1], which as we know is 'imagerect.' The code follows that.

Tell me if I need to explain further.

ContentLicense: CC BY-SA 4.0


问:
How can I sync data between a Android app , Webserver and Web app?
I have an app that runs on SQL database. I'm making a similar website now that is
going to use the same data. I already connected the basics like email and username both from Android app and Web app to server. Im using PDO at the server side. This may be answered many times before but some questions are as old as from 2012.

Android app and web app is going to be dependent on the same data

I want to make sure Im doing everything right from the start.

What ways are there to connect from Android to server read/write data (Now Im only using HttpURLConnection to write data)?

Could I bulk the data and send it for example one time after session ended or should I update the database after every transaction from Android side?

答:
1) Yes HttpURLConnection will the best way to connect server.

2) You have to update database in every android transaction so when ever you will refresh your web page, it will show you latest data in both side(Android app & web).