问:
Julia: Minimise a function with multiple arguments (BFGS)
I am trying to minimise a function with multiple arguments with the Optim.jl library, using a BFGS algorithm.

In the GitHub website of the Optim library, I found the following working example:

```<code>using Optim
rosenbrock(x) = (1.0 - x[1])^2 + 100.0 * (x[2] - x[1]^2)^2
result        = optimize(rosenbrock, zeros(2), BFGS())
</code>```

Let's say that my objective function is:

```<code>fmin(x, a) = (1.0 - x[1])^a + 100.0 * (x[2] - x[1]^2)^(1-a)
</code>```

How can I pass the additional - constant - argument a using optimize?

答:
The simplest way is to pass an anonymous function of one variable which calls your original function with the parameters set.  For example, using a variant of your fmin:

```<code>julia> fmin(x, a) = (1.0 - x[1])^a + 100.0 * (x[2] - x[1]^2)^(a)
fmin (generic function with 1 method)

julia> r = optimize(x->fmin(x, 2), zeros(2), BFGS());

julia> r.minimizer, r.minimum
([1.0,1.0],5.471432684244042e-17)
</code>```

Alternatively you can make a separate named function of one variable which closes over whatever parameters you like.  There's no equivalent to the args in scipy.optimize.minimize in Python where you pass the non-varying arguments separately as a tuple, AFAIK.

Body:
I am trying to minimise a function with multiple arguments with the Optim.jl library, using a BFGS algorithm.

In the GitHub website of the Optim library, I found the following working example:

using Optim
rosenbrock(x) = (1.0 - x[1])^2 + 100.0 * (x[2] - x[1]^2)^2
result        = optimize(rosenbrock, zeros(2), BFGS())

Let's say that my objective function is:

fmin(x, a) = (1.0 - x[1])^a + 100.0 * (x[2] - x[1]^2)^(1-a)

How can I pass the additional - constant - argument a using optimize?

Body:
The simplest way is to pass an anonymous function of one variable which calls your original function with the parameters set.  For example, using a variant of your fmin:

julia> fmin(x, a) = (1.0 - x[1])^a + 100.0 * (x[2] - x[1]^2)^(a)
fmin (generic function with 1 method)

julia> r = optimize(x->fmin(x, 2), zeros(2), BFGS());

julia> r.minimizer, r.minimum
([1.0,1.0],5.471432684244042e-17)

Alternatively you can make a separate named function of one variable which closes over whatever parameters you like.  There's no equivalent to the args in scipy.optimize.minimize in Python where you pass the non-varying arguments separately as a tuple, AFAIK.


来源: stackexchange

问:
Get the position of clicked word in textbox (Javascript)
I have a textbox with multiple sentences, and when I click on a word, I need to get the position of the word in this textbox.

The code actually just get the whole text from the textarea and writes it in another text area. I am struggling to get specific position of the character (or word) I clicked on.

What it should do is to copy just the text before clicked word/character.

 var themaintextarea = document.getElementById('textarea');
 themaintextarea.addEventListener('click', replace_sentence);
 function replace_sentence(e){
  var themaintext = document.getElementById("textarea").innerHTML;
    //alert(thereplace);
    document.getElementById("curent_sentence").value = themaintext;
    theselection = window.getSelection();
    var therange = theselection.getRangeAt(0);
    var sometext = therange.toString().trim();
    alert(sometext);

 } ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea id="curent_sentence"></textarea>

<div id="textarea" contenteditable>I <span>like</span> apples. I <span>like</span> apples.
<br>
I <span>like</span> apples.</div></code>```

答:
EDITED : Heres the fiddle to select the word before the word clicked on. Note: no spans are used in this. https://jsfiddle.net/Lnkav5ca/5/

I think i understood what you're looking for. https://jsfiddle.net/Lnkav5ca/1/ I put all the clickable words in a class and add event listeners to that class. So when the word is clicked on it gets inserted into the text box.

```<code>var themaintextarea = document.getElementsByClassName('clickable');
for (var i = 0; i < themaintextarea.length; i++) {
themaintextarea[i].addEventListener('click', replace_sentence);
}
function replace_sentence(e){
console.log(e);
    var themaintext = e.target.innerHTML
//alert(thereplace);
document.getElementById("curent_sentence").value = themaintext;
theselection = window.getSelection();
var therange = theselection.getRangeAt(0);
var sometext = therange.toString().trim();
//alert(sometext);

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a textbox with multiple sentences, and when I click on a word, I need to get the position of the word in this textbox.

The code actually just get the whole text from the textarea and writes it in another text area. I am struggling to get specific position of the character (or word) I clicked on.

What it should do is to copy just the text before clicked word/character.

 var themaintextarea = document.getElementById('textarea');
 themaintextarea.addEventListener('click', replace_sentence);
 function replace_sentence(e){
  var themaintext = document.getElementById("textarea").innerHTML;
    //alert(thereplace);
    document.getElementById("curent_sentence").value = themaintext;
    theselection = window.getSelection();
    var therange = theselection.getRangeAt(0);
    var sometext = therange.toString().trim();
    alert(sometext);

 }

<textarea id="curent_sentence"></textarea>

I like apples. I like apples.

I like apples.

Body:
EDITED : Heres the fiddle to select the word before the word clicked on. Note: no spans are used in this. https://jsfiddle.net/Lnkav5ca/5/

I think i understood what you're looking for. https://jsfiddle.net/Lnkav5ca/1/ I put all the clickable words in a class and add event listeners to that class. So when the word is clicked on it gets inserted into the text box.

var themaintextarea = document.getElementsByClassName('clickable');
for (var i = 0; i < themaintextarea.length; i++) {
themaintextarea[i].addEventListener('click', replace_sentence);
}
function replace_sentence(e){
console.log(e);
    var themaintext = e.target.innerHTML
//alert(thereplace);
document.getElementById("curent_sentence").value = themaintext;
theselection = window.getSelection();
var therange = theselection.getRangeAt(0);
var sometext = therange.toString().trim();
//alert(sometext);

}


问:
Fill array list with database in java
i create function he return a array list
and after fill jfxtreetableview with this array list

```<code>public ArrayList afficher_user() throws SQLException{

    List<String> table =  new ArrayList<String>();
        Connection conn=null;

      try {
            Class.forName(Driver);
            conn = DriverManager.getConnection(URL,"root","");
            String sql ="select * from utilisateur";
            PreparedStatement Stmt = conn.prepareStatement(sql);
            ResultSet rs = Stmt.executeQuery(sql);

            while(rs.next()){
            setId(rs.getInt("id"));
            setNom(rs.getString("nom"));
            setPrenom(rs.getString("prenom"));
            setCin(rs.getString("cin"));
            setAdresse(rs.getString("adresse"));
            setTel(rs.getString("tel"));
            setDn(rs.getString("dn"));
            }
            rs.close();
            conn.close();

      } catch (ClassNotFoundException ex) {
            System.err.println(ex.getMessage());
      }

  return table;
}
</code>```

how i can put this result to array list

答:
Assuming you need to return the list of User objects, you need to create an object inside the while loop and add it into the list, e.g.:

```<code>List<User> data =  new ArrayList<String>();
    Connection conn=null;

  try {
        Class.forName(Driver);
        conn = DriverManager.getConnection(URL,"root","");
        String sql ="select * from utilisateur";
        PreparedStatement Stmt = conn.prepareStatement(sql);
        ResultSet rs = Stmt.executeQuery(sql);

        while(rs.next()){
        User user = new User();
        user.setId(rs.getInt("id"));
        user.setNom(rs.getString("nom"));
        user.setPrenom(rs.getString("prenom"));
        user.setCin(rs.getString("cin"));
        user.setAdresse(rs.getString("adresse"));
        user.setTel(rs.getString("tel"));
        user.setDn(rs.getString("dn"));
        data.add(user);
        }
        rs.close();
        conn.close();

  } catch (ClassNotFoundException ex) {
        System.err.println(ex.getMessage());
  }

  return data;
</code>```

Title: Fill array list with database in java

Body:
i create function he return a array list
and after fill jfxtreetableview with this array list

public ArrayList afficher_user() throws SQLException{

    List<String> table =  new ArrayList<String>();
        Connection conn=null;

      try {
            Class.forName(Driver);
            conn = DriverManager.getConnection(URL,"root","");
            String sql ="select * from utilisateur";
            PreparedStatement Stmt = conn.prepareStatement(sql);
            ResultSet rs = Stmt.executeQuery(sql);

            while(rs.next()){
            setId(rs.getInt("id"));
            setNom(rs.getString("nom"));
            setPrenom(rs.getString("prenom"));
            setCin(rs.getString("cin"));
            setAdresse(rs.getString("adresse"));
            setTel(rs.getString("tel"));
            setDn(rs.getString("dn"));
            }
            rs.close();
            conn.close();

      } catch (ClassNotFoundException ex) {
            System.err.println(ex.getMessage());
      }

  return table;
}

how i can put this result to array list

Body:
Assuming you need to return the list of User objects, you need to create an object inside the while loop and add it into the list, e.g.:

List<User> data =  new ArrayList<String>();
    Connection conn=null;

  try {
        Class.forName(Driver);
        conn = DriverManager.getConnection(URL,"root","");
        String sql ="select * from utilisateur";
        PreparedStatement Stmt = conn.prepareStatement(sql);
        ResultSet rs = Stmt.executeQuery(sql);

        while(rs.next()){
        User user = new User();
        user.setId(rs.getInt("id"));
        user.setNom(rs.getString("nom"));
        user.setPrenom(rs.getString("prenom"));
        user.setCin(rs.getString("cin"));
        user.setAdresse(rs.getString("adresse"));
        user.setTel(rs.getString("tel"));
        user.setDn(rs.getString("dn"));
        data.add(user);
        }
        rs.close();
        conn.close();

  } catch (ClassNotFoundException ex) {
        System.err.println(ex.getMessage());
  }

  return data;


问:
stopping Android Accessibility UI Component on softKey "HOME" Button pressed
Created  "AccessibilityService" and am able to show Hints based on the Text Entered.The Problem is i want to stop the activity service when the Host application Home Pressed.
I have tried Adding

```<code><accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
                  android:accessibilityEventTypes="typeAllMask|typeViewClicked|typeViewFocused"
                      android:canRequestFilterKeyEvents="true"
                    android:accessibilityFlags="flagRequestFilterKeyEvents"
                     android:description="@string/accessibility_service_description" />
</code>```

With this am able to solve issue with phones which has Physical Button For "HOME".
How to Stop the Accessibility service When "HOME" event for Soft Buttons Like Nexus 5.

答:
ANSWER TO ORIGINAL QUESTION: "Detecting when the software 'Home' button is pressed?"

As per Android documentation, Soft keyboards are not required to send hardware keyboard events and in fact the Android samples don't, so pretty much every software keyboard on the app store does not. You can only rely on the events from external Bluetooth and hardware keyboards.

Simply put, you can't reliably do what you want, the APIs don't support it.

ANSWER TO QUESTION EDIT:

Let me reiterate, THERE IS NO "RELIABLE" WAY TO DO THIS.

What you could do is listen for Screen change related events, and detect when the screen content matches the Home screen.  Now, this is still going to be a very fragile solution.  There is no consistent way to detect the Launcher Activity, vs any other Activity, and also no way to determine if perhaps the matcher you set up might match something that's not a Launcher Activity.  But, here is what I think to be the most reasonable approach.

```<code>public void onAccessibilityEvent(AccessibilityEvent e) {

    switch (e.getEventType()) {
        case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED:
        case AccessibilityEvent.TYPE_VIEW_SCROLLED:
        case AccessibilityEvent.TYPE_WINDOWS_CHANGED:
        case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED: {
            if (detectHomeScreen(getRootInActiveWindow()) {
                //We are now at the "home" screen, do what you want here.
            }
        }
    }
}
//A List of package names you know to be associated with "launcher" activities.  Populate this list in your classes static initialization block.
private static ArrayList<String> LAUNCHER_PACKAGE_NAMES;

private static boolean detectHomeScreen(AccessibilityNodeInfo rootNodeInfo) {
    return LAUNCHER_PACKAGE_NAMES.contains(rootNodeInfo.getPackageName().toString())
}
</code>```

XML Configuration

```<code><?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
    android:description="@string/accessibility_service_description"
    android:accessibilityEventTypes="typeAllMask"
    android:accessibilityFlags="flagIncludeNotImportantViews|flagReportViewIds"
    android:canRetrieveWindowContent="true"
    android:notificationTimeout="100"
    android:settingsActivity="com.example.SettingsActivity"
    />
</code>```

The last one is cool.  It allows you to set an Activity that will open up via the "Settings" button in the top right corner of the Accessibility Service configuration screen.

Body:
Created  "AccessibilityService" and am able to show Hints based on the Text Entered.The Problem is i want to stop the activity service when the Host application Home Pressed.
I have tried Adding

<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
                  android:accessibilityEventTypes="typeAllMask|typeViewClicked|typeViewFocused"
                      android:canRequestFilterKeyEvents="true"
                    android:accessibilityFlags="flagRequestFilterKeyEvents"
                     android:description="@string/accessibility_service_description" />

With this am able to solve issue with phones which has Physical Button For "HOME".
How to Stop the Accessibility service When "HOME" event for Soft Buttons Like Nexus 5.

Body:
ANSWER TO ORIGINAL QUESTION: "Detecting when the software 'Home' button is pressed?"

As per Android documentation, Soft keyboards are not required to send hardware keyboard events and in fact the Android samples don't, so pretty much every software keyboard on the app store does not. You can only rely on the events from external Bluetooth and hardware keyboards.

Simply put, you can't reliably do what you want, the APIs don't support it.

ANSWER TO QUESTION EDIT:

Let me reiterate, THERE IS NO "RELIABLE" WAY TO DO THIS.

What you could do is listen for Screen change related events, and detect when the screen content matches the Home screen.  Now, this is still going to be a very fragile solution.  There is no consistent way to detect the Launcher Activity, vs any other Activity, and also no way to determine if perhaps the matcher you set up might match something that's not a Launcher Activity.  But, here is what I think to be the most reasonable approach.

public void onAccessibilityEvent(AccessibilityEvent e) {

    switch (e.getEventType()) {
        case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED:
        case AccessibilityEvent.TYPE_VIEW_SCROLLED:
        case AccessibilityEvent.TYPE_WINDOWS_CHANGED:
        case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED: {
            if (detectHomeScreen(getRootInActiveWindow()) {
                //We are now at the "home" screen, do what you want here.
            }
        }
    }
}
//A List of package names you know to be associated with "launcher" activities.  Populate this list in your classes static initialization block.
private static ArrayList<String> LAUNCHER_PACKAGE_NAMES;

private static boolean detectHomeScreen(AccessibilityNodeInfo rootNodeInfo) {
    return LAUNCHER_PACKAGE_NAMES.contains(rootNodeInfo.getPackageName().toString())
}

XML Configuration

<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
    android:description="@string/accessibility_service_description"
    android:accessibilityEventTypes="typeAllMask"
    android:accessibilityFlags="flagIncludeNotImportantViews|flagReportViewIds"
    android:canRetrieveWindowContent="true"
    android:notificationTimeout="100"
    android:settingsActivity="com.example.SettingsActivity"
    />

The last one is cool.  It allows you to set an Activity that will open up via the "Settings" button in the top right corner of the Accessibility Service configuration screen.


问:
Strange character appearing at start of string
I am taking different transistor data from a file. The program stores that in a structure. It then prompts for an input from the user. User enters 5 different values, eg 12 0.03 100 320 65 and then the program takes these values and compares it to the data from the file and sees if any transistors would be suitable for the parameters you have entered.
The program then prompts the user again, and this repeats until the letter q is entered, which ends the program.

The problem I'm having - and I've been trawling the internet for hours trying to find a solution but none of them have worked - is that any input after the first set isn't accepted. So it looks like this.

Please input: Voltage Current Power Frequency Gain

15 0.1 200 100 80

15 0.1 200 100 80

ALL RELEVANT TRANSISTORS

Please input: Voltage Current Power Frequency Gain

20 0.3 100 150 40

?1 2 3 4 5

The question mark is always a strange character. In the past few hours it has been a ? in a diamond, the letter P, and a small square with 0010 in it. Everything I have found on the internet says this should work. What am I missing?

Here's my input function

```<code>#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define MAX 15
struct input{
    int volt, power, freq, gain;
    float amp;
};
struct input inputs[MAX_IN];

int CHK =1, number=0;

int input_function1()
{
    const char check[3] = {'\0'};
    int i;
    const char inp[30] = {'\0'};

    printf("Please input: Voltage Current Power Frequency Gain\n");

    fgets(inp, 30, stdin);
    puts(inp); //Prints out the string to see if the input has been correctly accepted
    ungetc(inp, stdin);

    sscanf(inp, "%s", &check);
    if(check[0]!='q' && check[1]!='q' && check[2]!='q')
    {

    sscanf(inp, "%d %f %d %d %d", &inputs[number].volt, &inputs[number].amp,
    &inputs[number].power, &inputs[number].freq, &inputs[number].gain);

    }

}
</code>```

Below is how I am calling the function. check_function is the function which checks the input transistor against the database.

```<code>while(CHK==1)
{
    input_function1();

    check_function();
    ++number;

}
</code>```

答:
Here's a little example which fixes some stuff of your current snippet:

```<code>#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <conio.h>

#define MAX 15

struct input {
    int volt, power, freq, gain;
    float amp;
};
struct input inputs[MAX];

int fill_input(int index) {
    char check[4];
    char inp[30];

    printf("Please input: Voltage Current Power Frequency Gain\n");

    fgets(inp, 30, stdin);
    puts(inp);
    sscanf(inp, "%s", &check);

    if (strcmp(check, "qqq") == 0) {
        return 0;
    }

    sscanf(inp, "%d %f %d %d %d", &inputs[index].volt, &inputs[index].amp,
           &inputs[index].power, &inputs[index].freq, &inputs[index].gain);

    return 1;
}

int main(int argc, char *argv[]) {
    int index = 0;

    while (1 && index < MAX) {
        if (!fill_input(index)) break;
        index++;
    }

    printf("End");
    getch();
}
</code>```

The goal of the above snippet is to help you to move on.

Few notes for you to consider though:

Try to avoid global variables as much as possible

The current provided version is far away from being optimal, think why is that and don't just copy paste other's code, try to figure out what a good function is all about. The most important lesson for you here should be how to code proper functions

The errors in your snippet are related to arguments not matching properly the datatypes, for instance, take a look to the fgets docs, you can see the first argument is char*, you were using const char*, datatypes should match

Try to refactor the function till is good one and learn as much as possible from each refactoring

Have fun coding! <--- most important one

ContentLicense: CC BY-SA 4.0

Body:
I am taking different transistor data from a file. The program stores that in a structure. It then prompts for an input from the user. User enters 5 different values, eg 12 0.03 100 320 65 and then the program takes these values and compares it to the data from the file and sees if any transistors would be suitable for the parameters you have entered.
The program then prompts the user again, and this repeats until the letter q is entered, which ends the program.

The problem I'm having - and I've been trawling the internet for hours trying to find a solution but none of them have worked - is that any input after the first set isn't accepted. So it looks like this.

Please input: Voltage Current Power Frequency Gain

15 0.1 200 100 80

15 0.1 200 100 80

ALL RELEVANT TRANSISTORS

Please input: Voltage Current Power Frequency Gain

20 0.3 100 150 40

?1 2 3 4 5

The question mark is always a strange character. In the past few hours it has been a ? in a diamond, the letter P, and a small square with 0010 in it. Everything I have found on the internet says this should work. What am I missing?

Here's my input function

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define MAX 15
struct input{
    int volt, power, freq, gain;
    float amp;
};
struct input inputs[MAX_IN];

int CHK =1, number=0;

int input_function1()
{
    const char check[3] = {'\0'};
    int i;
    const char inp[30] = {'\0'};

    printf("Please input: Voltage Current Power Frequency Gain\n");

    fgets(inp, 30, stdin);
    puts(inp); //Prints out the string to see if the input has been correctly accepted
    ungetc(inp, stdin);

    sscanf(inp, "%s", &check);
    if(check[0]!='q' && check[1]!='q' && check[2]!='q')
    {

    sscanf(inp, "%d %f %d %d %d", &inputs[number].volt, &inputs[number].amp,
    &inputs[number].power, &inputs[number].freq, &inputs[number].gain);

    }

}

Below is how I am calling the function. check_function is the function which checks the input transistor against the database.

while(CHK==1)
{
    input_function1();

    check_function();
    ++number;

}

Body:
Here's a little example which fixes some stuff of your current snippet:

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <conio.h>

#define MAX 15

struct input {
    int volt, power, freq, gain;
    float amp;
};
struct input inputs[MAX];

int fill_input(int index) {
    char check[4];
    char inp[30];

    printf("Please input: Voltage Current Power Frequency Gain\n");

    fgets(inp, 30, stdin);
    puts(inp);
    sscanf(inp, "%s", &check);

    if (strcmp(check, "qqq") == 0) {
        return 0;
    }

    sscanf(inp, "%d %f %d %d %d", &inputs[index].volt, &inputs[index].amp,
           &inputs[index].power, &inputs[index].freq, &inputs[index].gain);

    return 1;
}

int main(int argc, char *argv[]) {
    int index = 0;

    while (1 && index < MAX) {
        if (!fill_input(index)) break;
        index++;
    }

    printf("End");
    getch();
}

The goal of the above snippet is to help you to move on.

Few notes for you to consider though:

Try to avoid global variables as much as possible

The current provided version is far away from being optimal, think why is that and don't just copy paste other's code, try to figure out what a good function is all about. The most important lesson for you here should be how to code proper functions

The errors in your snippet are related to arguments not matching properly the datatypes, for instance, take a look to the fgets docs, you can see the first argument is char*, you were using const char*, datatypes should match

Try to refactor the function till is good one and learn as much as possible from each refactoring

Have fun coding! <--- most important one


问:
Qt - splitting a QString by several types of whitespaces without RegExp
everyone. I need to split a QString by any type of whitespaces as fast as possible. Now I am using QRegExp, but this method takes a lot of time. Is there a faster option to do that?</p>

```<code>QString l = "one two  three   four    five";
lst = l.split(QRegExp("\\s+"), QString::SkipEmptyParts);
</code>```

答:
The only other way I could know is by using the simplified() method:

```<code>QString l = "one two  three   four    five";
QStringList lst = l.simplified().split(" ");
</code>```

I have no idea how it compares in performance against regexp though.

Body:
everyone. I need to split a QString by any type of whitespaces as fast as possible. Now I am using QRegExp, but this method takes a lot of time. Is there a faster option to do that?

QString l = "one two  three   four    five";
lst = l.split(QRegExp("\\s+"), QString::SkipEmptyParts);

Body:
The only other way I could know is by using the simplified() method:

QString l = "one two  three   four    five";
QStringList lst = l.simplified().split(" ");

I have no idea how it compares in performance against regexp though.


问:
How to Root an Android Emulator?
I know there are quite a few question like this around but none of them really seems to work for me.

I am writing a program that automatically updates and installs itself, however to install the update it requires user confirmation but I do not want this as the device I will deploy on will never be physically used by anyone. So to try work around this I want to root the device and use a runtime command in the code to get it to just install.

To test this out I want to try it on the (AVD) emulator first however it (obviously) needs to be rooted. So how would i go about this?

I have tried commands in the adb shell (and out of it with the adb shell) like:

```<code>mount -o rw,remount -t yaffs2 /dev/block/mtdblock03 /system
push su /system/xbin/su
chmod 06755 /system
chmod 06755 /system/xbin/su
</code>```

and a few others I can't find again at this moment but they will always give me errors such as cannot stat 'su' and stuff like that (will edit if i can find the commands and recreate again) or they just don't say anything and it doesn't appear to work.

If it helps i'm using xamarin in visual studio.

答:
When working with android emulators, just do:

adb.exe root - restart adbd with root permissions

adb.exe unroot - restart adbd without root permissions

You can find adb.exe at: android_sdk\platform-tools\

You can confirm if the device is rooted by doing:

```<code>adb.exe shell
</code>```

Inside the shell type: whoami. Then type exit to exit the shell

Example

```<code>P:\Android\sdk\platform-tools>adb.exe shell
generic_x86:/ $ whoami
shell
generic_x86:/ $ exit

P:\Android\sdk\platform-tools>adb.exe root

P:\Android\sdk\platform-tools>adb.exe shell
generic_x86:/ # whoami
root
generic_x86:/ # exit

P:\Android\sdk\platform-tools>adb.exe unroot

P:\Android\sdk\platform-tools>adb.exe shell
generic_x86:/ $ whoami
shell
generic_x86:/ $ exit
</code>```

Title: How to Root an Android Emulator?

Body:
I know there are quite a few question like this around but none of them really seems to work for me.

I am writing a program that automatically updates and installs itself, however to install the update it requires user confirmation but I do not want this as the device I will deploy on will never be physically used by anyone. So to try work around this I want to root the device and use a runtime command in the code to get it to just install.

To test this out I want to try it on the (AVD) emulator first however it (obviously) needs to be rooted. So how would i go about this?

I have tried commands in the adb shell (and out of it with the adb shell) like:

mount -o rw,remount -t yaffs2 /dev/block/mtdblock03 /system
push su /system/xbin/su
chmod 06755 /system
chmod 06755 /system/xbin/su

and a few others I can't find again at this moment but they will always give me errors such as cannot stat 'su' and stuff like that (will edit if i can find the commands and recreate again) or they just don't say anything and it doesn't appear to work.

If it helps i'm using xamarin in visual studio.

Body:
When working with android emulators, just do:

adb.exe root - restart adbd with root permissions

adb.exe unroot - restart adbd without root permissions

You can find adb.exe at: android_sdk\platform-tools\

You can confirm if the device is rooted by doing:

adb.exe shell

Inside the shell type: whoami. Then type exit to exit the shell

Example

P:\Android\sdk\platform-tools>adb.exe shell
generic_x86:/ $ whoami
shell
generic_x86:/ $ exit

P:\Android\sdk\platform-tools>adb.exe root

P:\Android\sdk\platform-tools>adb.exe shell
generic_x86:/ # whoami
root
generic_x86:/ # exit

P:\Android\sdk\platform-tools>adb.exe unroot

P:\Android\sdk\platform-tools>adb.exe shell
generic_x86:/ $ whoami
shell
generic_x86:/ $ exit


问:
How can iterate rows of dataframe using index?
I am looking to apply a loop over indices of dataframe in python.

My loop is like:

```<code>for index in DataFrame:
 if index <= 10
    index= index+1
 return rows(index)
</code>```

答:
Try this:

```<code>for index, row in df.iterrows():
    if index <=10:
        print row
</code>```

This is going to print the first 10 rows

Body:
I am looking to apply a loop over indices of dataframe in python.

My loop is like:

for index in DataFrame:
 if index <= 10
    index= index+1
 return rows(index)

Body:
Try this:

for index, row in df.iterrows():
    if index <=10:
        print row

This is going to print the first 10 rows


问:
How to remove nested JSON.stringify() properties
I'm trying to modify a string with Typescript. The string is created by the JSON.stringify() method.

I want to remove the properties "id", "lightStatus" and the "value" attributes of "inputPort" and "outputPort". (I only need their attribute "id".)

```<code>console.log(JSON.stringify(this.light));
// Results in -> {"id":1,"name":"Light Switch","lightStatus":true,"inputPort":{"id":2,"value":0},"outputPort":{"id":2,"value":false},"resistance":100}
</code>```

I tried to do it the following way but it doesn't recognize "inputPort.id" and "outputPort.id". This is what I tried and what it resulted in.

```<code>var savedLight = JSON.stringify(this.light, ["name", "inputPort.id", "outputPort.id", "resistance"]);
// Results in -> {"name":"Light Switch","resistance":100}
</code>```

The result should include the properties "name", "inputPort id", "outputPort id" and "resistance". Like this:

```<code>{"name":"Light Switch","inputPort": 2, "outputPort": 2, "resistance":100}
</code>```

Can anyone help me how I can get rid of the unnecessary properties?

答:
You can pass a "replacer" function that returns the exact value you want.

var data = {"id":1,"name":"Light Switch","lightStatus":true,"inputPort":{"id":2,"value":0},"outputPort":{"id":2,"value":false},"resistance":100};

var result = JSON.stringify(data, function(k, v) {
    switch (k) {
    case "": case "name": case "resistance":
     return v
    case "inputPort": case "outputPort":
     return v.id
    default:
     return undefined;
  }
}, 2)

document.querySelector("pre").textContent = result```
<pre class="snippet-code-html lang-html prettyprint-override"><code>``````</code>```

The "" represents the top level object. For that, "name", and "resistance", it simply returns the original value.

For "inputPort" and "outputPort" it returns the id property.

Anything else gets undefined, which means it gets omitted from the result.

Body:
I'm trying to modify a string with Typescript. The string is created by the JSON.stringify() method.

I want to remove the properties "id", "lightStatus" and the "value" attributes of "inputPort" and "outputPort". (I only need their attribute "id".)

console.log(JSON.stringify(this.light));
// Results in -> {"id":1,"name":"Light Switch","lightStatus":true,"inputPort":{"id":2,"value":0},"outputPort":{"id":2,"value":false},"resistance":100}

I tried to do it the following way but it doesn't recognize "inputPort.id" and "outputPort.id". This is what I tried and what it resulted in.

var savedLight = JSON.stringify(this.light, ["name", "inputPort.id", "outputPort.id", "resistance"]);
// Results in -> {"name":"Light Switch","resistance":100}

The result should include the properties "name", "inputPort id", "outputPort id" and "resistance". Like this:

{"name":"Light Switch","inputPort": 2, "outputPort": 2, "resistance":100}

Can anyone help me how I can get rid of the unnecessary properties?

Body:
You can pass a "replacer" function that returns the exact value you want.

var data = {"id":1,"name":"Light Switch","lightStatus":true,"inputPort":{"id":2,"value":0},"outputPort":{"id":2,"value":false},"resistance":100};

var result = JSON.stringify(data, function(k, v) {
    switch (k) {
    case "": case "name": case "resistance":
     return v
    case "inputPort": case "outputPort":
     return v.id
    default:
     return undefined;
  }
}, 2)

document.querySelector("pre").textContent = result

<pre></pre>

The "" represents the top level object. For that, "name", and "resistance", it simply returns the original value.

For "inputPort" and "outputPort" it returns the id property.

Anything else gets undefined, which means it gets omitted from the result.


问:
Can I have entity as one of the value in DTO
I need to pass few data between layers of my application and within layer.I have defined DTO to do this. My question is can I have my domain entity is one of Value in my DTO.Is it good design?

In below code UserEntity is JPA entity.

UserDTO.java

private UserEntity userEntity;

private String empNo;

private String place;

答:
Ideally, no.

DTO, Data Transfer Object, should ideally be decoupled from Database entities. That way, if you change anything in the latter, that information doesn't automatically flow into the former. This helps in preventing unnecessary data leaks.


问:
Can i query ejabberd database for online users
i have ejabberd 16.03, i would like to query the database to get online users that are showed in admin panel.

Can someone help me? wich table i have to query?

I think i can do something like:

```<code>SELECT * FROM lasts WHERE
</code>```

I need this to make a join with another table of external database. thanks for the help!

答:
You can use

select * from sm

for odbc as backend

Body:
i have ejabberd 16.03, i would like to query the database to get online users that are showed in admin panel.

Can someone help me? wich table i have to query?

I think i can do something like:

SELECT * FROM lasts WHERE

I need this to make a join with another table of external database. thanks for the help!


问:
Models load() usage
Can someone enligthen me ,what is the real usage of load method if setting post params can  be directly set to models attributes? Thanks

$model->load(Yii::$app->request->post());

vs

$model->attributes = Yii::$app->request->post();

答: not sure if you have gone through this or not .. .but it's pretty much clear here : www.yiiframework.com/doc-2.0/yii-base-model.html#load()-detail</p>

Title: Models load() usage


问:
How to extract portion of a line in ruby?
I have a line say

line = "start running at Sat April 1 07:30:37 2017"

and I want to extract

"Sat April 1 07:30:37 2017"

I tried this...

```<code>line = "start running at Sat April 1 07:30:37 2017"
if (line =~ /start running at/)
   line.split("start running at ").last
end
</code>```

... but is there any other way of doing this?

答:
The standard way to do this with regular expressions would be:

```<code>if md = line.match(/start running at (.*)/)
  md[1]
end
</code>```

But you don't need regular expressions, you can do regular string operations:

```<code>prefix = 'start running at '
if line.start_with?(prefix)
  line[prefix.size..-1]
end
</code>```

Body:
I have a line say

line = "start running at Sat April 1 07:30:37 2017"

and I want to extract

"Sat April 1 07:30:37 2017"

I tried this...

line = "start running at Sat April 1 07:30:37 2017"
if (line =~ /start running at/)
   line.split("start running at ").last
end

... but is there any other way of doing this?

Body:
The standard way to do this with regular expressions would be:

if md = line.match(/start running at (.*)/)
  md[1]
end

But you don't need regular expressions, you can do regular string operations:

prefix = 'start running at '
if line.start_with?(prefix)
  line[prefix.size..-1]
end


问:
Should I perform input validation on the forms or in the class set method?
Say I have a database which stores information on customers, and there is an application with various forms to register customers, edit customers, delete customers, etc...

Should input validation (for example, checking the customer's post code is in the correct format) be placed in the Customer class or be done on the form?  Currently I have it in the class and I am throwing a custom exception if the value is not of the correct format.

答:
There are two cases of validations:

Required

Almost Required

Required

The validations which you are doing in the class/backend are the validation which you cannot ignore. If you do,this can leave your data in heywired state. So must do this!

Almost Required

The validation in the UI is not essential, but almost always a part of a quality app. We build an app for users, therefore UX(user experience) is of paramount importance. Validation in the UI gives the user immediate feedback and keep the correction cycle short. This is of more importance as the form grows.

Hope that helps.


问:
ASP.net: Display PDF in a asp.net web page
User click on a link button and it will direct them to a url that is dynmaically generated which a pdf file. The browser will prompt the user to either save or open it.

I want to know if it is possible to downlaod the pdf file to the server then show the pdf file in the asp.net web page. When i google on this question, 99% of top link are some third party component. Is it a way to do this without purchase any 3rd party component?

thank

答:
I use itextsharp, its a free open source c# port of the java itext library.

Makes generating dynamic pdfs in asp.net a breeze and there is lots of documentation/examples floating around.

OwnerDisplayName: Jack

ContentLicense: CC BY-SA 2.5


问:
How to use fscanf to reads any character into a string until a tab is reached?
How to use fscanf to reads any character into a string until a tab is reached?

My data file have only 1 row:

```<code>123'\t'(Tab)345'\t'Le Duc Huy'\t'567
</code>```

and i use fscanf like this:

```<code>fscanf(fin,"%d %d %d %[^\t]%s %d",&m,&n,&k,s,&q);
</code>```

it return q with wrong value. Anybody can tell me what made it failed?

答:
Note, this is not safe!
```
char foo[100];
scanf("%s\t", foo);
</code>```

You have no way of keeping the user from overflowing the buffer

Body:
How to use fscanf to reads any character into a string until a tab is reached?

My data file have only 1 row:

123'\t'(Tab)345'\t'Le Duc Huy'\t'567

and i use fscanf like this:

fscanf(fin,"%d %d %d %[^\t]%s %d",&m,&n,&k,s,&q);

it return q with wrong value. Anybody can tell me what made it failed?

Body:
Note, this is not safe!

char foo[100];
scanf("%s\t", foo);

You have no way of keeping the user from overflowing the buffer


答: I don't know which framework you are using but it would make sense to put form validation in the class which Handels your tables. Thats the framework im  currently using https://book.cakephp.org/2.0/en/models/data-validation.html. It would probably be helpful.</p>

Title: Should I perform input validation on the forms or in the class set method?

Body:
Say I have a database which stores information on customers, and there is an application with various forms to register customers, edit customers, delete customers, etc...

Should input validation (for example, checking the customer's post code is in the correct format) be placed in the Customer class or be done on the form?  Currently I have it in the class and I am throwing a custom exception if the value is not of the correct format.


问:
Rails displaying validation messages on form
I am trying to validate a data model that belongs_to a project model. The validation works as data does not get saved if it fails the validation.

However, I can't get the data validation to display the correct error message from the validation on the new form.

How do I display the correct error validation messages on the data form?

Form URL
http://localhost:9080/projects/7/data/new

Data Model:

```<code>class Datum < ApplicationRecord
  belongs_to :project
  validates :supplier, :item, :presence => true #need this to display error message on data form
end
</code>```

Project Model:

```<code>class Project < ApplicationRecord
  belongs_to :user
  validates :name,:presence => true #works perfectly, displays error message on project form
  has_many :data, dependent: :destroy
  accepts_nested_attributes_for :data
end
</code>```

Data Controller

```<code>def create
  @datum = Datum.new(datum_params)
  @datum.project_id = params[:project_id]

  respond_to do |format|
    if @datum.save
      format.html { redirect_to project_data_path, notice: 'Created.' }
    else
      format.html {#do I need something here to redisplay the form with the errors }
    end
  end
end
</code>```

Data Form:

```<code><%= bootstrap_form_for([@project, @project.data.build]) do |f| %>
  <div class="field">
    <%= f.text_field :supplier %>
  </div>

  <div class="field">
    <%= f.text_field :item %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
</code>```

EDIT
The closest I got to a solution is if the object doesn't save:

```<code>format.html { redirect_to new_project_datum_path, alert: @datum.errors }
</code>```

But this isn't exactly what I need. Because it just returns the error msg, and the empty fields so the user has to fill out all fields again.
For some reason the redirect works, but the render 'new' does not work.

答:
You should render the 'new' action if the saving fails:

```<code>def create
  @project = Project.find(params[:project_id])
  @datum = @project.build(datum_params)

  respond_to do |format|
    if @datum.save
      format.html { redirect_to project_data_path, notice: 'Created.' }
    else
      format.html { render action: 'new' }
    end
  end
end
</code>```

Also you should change your form to use the @datum instance variable instead building it in the form:

```<code><%= bootstrap_form_for([@project, @datum]) do |f| %>
</code>```

and the controller:

```<code>def new
  @project = Project.find(params[:project_id])
  @datum = @project.data.build
end
</code>```

The basic idea is that if the user arrives to the new page you create a new empty datum instance variable. The user fills out the form and posts it to the create action. If the saving fails in the create action, you keep your filled-out @datum object and render that back to the form. The @datum object will have the errors ( you can check by @datum.errors ) which you can display to the user.

Body:
I am trying to validate a data model that belongs_to a project model. The validation works as data does not get saved if it fails the validation.

However, I can't get the data validation to display the correct error message from the validation on the new form.

How do I display the correct error validation messages on the data form?

Form URL
http://localhost:9080/projects/7/data/new

Data Model:

class Datum < ApplicationRecord
  belongs_to :project
  validates :supplier, :item, :presence => true #need this to display error message on data form
end

Project Model:

class Project < ApplicationRecord
  belongs_to :user
  validates :name,:presence => true #works perfectly, displays error message on project form
  has_many :data, dependent: :destroy
  accepts_nested_attributes_for :data
end

Data Controller

def create
  @datum = Datum.new(datum_params)
  @datum.project_id = params[:project_id]

  respond_to do |format|
    if @datum.save
      format.html { redirect_to project_data_path, notice: 'Created.' }
    else
      format.html {#do I need something here to redisplay the form with the errors }
    end
  end
end

Data Form:

<%= bootstrap_form_for([@project, @project.data.build]) do |f| %>

    <%= f.text_field :supplier %>

    <%= f.text_field :item %>

    <%= f.submit %>

<% end %>

EDIT
The closest I got to a solution is if the object doesn't save:

format.html { redirect_to new_project_datum_path, alert: @datum.errors }

But this isn't exactly what I need. Because it just returns the error msg, and the empty fields so the user has to fill out all fields again.
For some reason the redirect works, but the render 'new' does not work.

Body:
You should render the 'new' action if the saving fails:

def create
  @project = Project.find(params[:project_id])
  @datum = @project.build(datum_params)

  respond_to do |format|
    if @datum.save
      format.html { redirect_to project_data_path, notice: 'Created.' }
    else
      format.html { render action: 'new' }
    end
  end
end

Also you should change your form to use the @datum instance variable instead building it in the form:

<%= bootstrap_form_for([@project, @datum]) do |f| %>

and the controller:

def new
  @project = Project.find(params[:project_id])
  @datum = @project.data.build
end

The basic idea is that if the user arrives to the new page you create a new empty datum instance variable. The user fills out the form and posts it to the create action. If the saving fails in the create action, you keep your filled-out @datum object and render that back to the form. The @datum object will have the errors ( you can check by @datum.errors ) which you can display to the user.


答:
You can use a replacer function for this.

var obj = {
  "id": 1,
  "name": "Light Switch",
  "lightStatus": true,
  "inputPort": {
    "id": 2,
    "value": 0
  },
  "outputPort": {
    "id": 2,
    "value": false
  },
  "resistance": 100
};

var stringified = JSON.stringify(obj, function(key, val) {
  if (key === 'id' || key === 'lightStatus') {
    return void(0);
  }
  if (key === 'inputPort' || key === 'outputPort') {
    return val.id;
  }
  return val;
});

console.log(stringified);```

Title: How to remove nested JSON.stringify() properties


问:
SQL export to ListView using C#
I have a query that selects 3 columns from a SQL table, I need to export the resulting query into a listview.  I don't need any help with the SQL setup, just how to format it into the listview.  There is where I am stuck.  Any help is appreciated.  Thanks!

```<code>string sql = "select distinct pro,ds,date from dbo.Sge where date IN (select max(date) from dbo.Storage) order by project";
SqlConnection con = new SqlConnection("Data Source= ;Initial Catalog= ;Integrated Security= SSPI");
con.Open();
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(sql,con);
adapter.Fill(ds);
foreach (DataRow row in ds.Tables[0].Rows)
{
    for(int i=0; i< ds.Tables[0].Columns.Count; i++))
}
</code>```

Edit: Sorry guys, i mentioned ListBox originally and i meant ListView. My ListView is detailed and had a column for each of my columns in my select, i just simply need the SQL export to go to the right column.

This is what I have come up with, but it doesn't add to each column, just to the first column

```<code>foreach (DataRow row in poplb6ds.Tables[0].Rows)
{
    listView1.Items.Add(row["Pro"].ToString());
    listView1.Items.Add(row["size"].ToString());
    listView1.Items.Add(row["Date"].ToString());
}
</code>```

答:
Use using blocks:

```<code>using (SqlConnection con = new SqlConnection("Data Source=;Initial Catalog= ;Integrated Security= SSPI"))
{
    con.Open();
    using (DataSet ds = new DataSet())
    {
        using (SqlDataAdapter adapter = new SqlDataAdapter(sql, con))
        {
            adapter.Fill(ds);
        }
    }
}
</code>```

Fill single table:

```<code>DataTable dt = new DataTable(); // new DataTable("Sge"); name it if will be required
adapter.Fill(dt);
</code>```

Your loop has makes no sense because columns are the same for each row in the table:

```<code>foreach (DataColumn column in dt.Columns)
{
}
</code>```

Or you want to iterate thru each row and each column?

```<code>foreach (DataColumn column in dt.Columns)
{
    foreach (DataRow row in dt)
    {
        object value = row[column];
    }
}
</code>```

Title: SQL export to ListView using C#

Body:
I have a query that selects 3 columns from a SQL table, I need to export the resulting query into a listview.  I don't need any help with the SQL setup, just how to format it into the listview.  There is where I am stuck.  Any help is appreciated.  Thanks!

string sql = "select distinct pro,ds,date from dbo.Sge where date IN (select max(date) from dbo.Storage) order by project";
SqlConnection con = new SqlConnection("Data Source= ;Initial Catalog= ;Integrated Security= SSPI");
con.Open();
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(sql,con);
adapter.Fill(ds);
foreach (DataRow row in ds.Tables[0].Rows)
{
    for(int i=0; i< ds.Tables[0].Columns.Count; i++))
}

Edit: Sorry guys, i mentioned ListBox originally and i meant ListView. My ListView is detailed and had a column for each of my columns in my select, i just simply need the SQL export to go to the right column.

This is what I have come up with, but it doesn't add to each column, just to the first column

foreach (DataRow row in poplb6ds.Tables[0].Rows)
{
    listView1.Items.Add(row["Pro"].ToString());
    listView1.Items.Add(row["size"].ToString());
    listView1.Items.Add(row["Date"].ToString());
}

Body:
Use using blocks:

using (SqlConnection con = new SqlConnection("Data Source=;Initial Catalog= ;Integrated Security= SSPI"))
{
    con.Open();
    using (DataSet ds = new DataSet())
    {
        using (SqlDataAdapter adapter = new SqlDataAdapter(sql, con))
        {
            adapter.Fill(ds);
        }
    }
}

Fill single table:

DataTable dt = new DataTable(); // new DataTable("Sge"); name it if will be required
adapter.Fill(dt);

Your loop has makes no sense because columns are the same for each row in the table:

foreach (DataColumn column in dt.Columns)
{
}

Or you want to iterate thru each row and each column?

foreach (DataColumn column in dt.Columns)
{
    foreach (DataRow row in dt)
    {
        object value = row[column];
    }
}


问:
Pointer getter to a reference
I have a class with a reference and want a getter that returns a pointer.

```<code>class X {
    std::string& text;
public:
    auto GetText() -> decltype(text) * { return &text); // doesn't work
    X(std::string& text): text(text) {}
};
</code>```

The easy way is to pass a pointer to this class. But if I pass a reference, can I get a pointer with a getter?

Edit: here is the error message

```<code>error: cannot declare pointer to 'std::__cxx11::string& {aka class std::__cxx11::basic_string<char>&}'
auto GetText() -> decltype(text) * { return &text);
                                 ^
</code>```

答:
Firstly,

```<code>auto GetText() -> decltype(text) * { return &text); // doesn't work
</code>```

is a positively abominable way to declare this signature. Prefer

```<code>std::string* GetText(){ return &text);
</code>```

or even just

```<code>auto GetText(){ return &text);
</code>```

But this isn't code review.

The problem here is that you're asking for a pointer to the declared type of the text member variable which is a string reference (std::string&). From the comment section, it seems you were unaware that decltype respects the 'reference'ness, 'const'ness, and 'volatile'ness of its argument.

You cannot have a pointer to a reference in C++, e.g. std::string&* is malformed. Calling to std::remove_reference_t should resolve that issue, e.g.

```<code>auto GetText() -> std::remove_reference_t<decltype(text)> * { return &text);
</code>```

However, in this case, auto would have correctly deduced your type anyway, so your explicit declaration is unnecessary.

Title: Pointer getter to a reference

Body:
I have a class with a reference and want a getter that returns a pointer.

class X {
    std::string& text;
public:
    auto GetText() -> decltype(text) * { return &text); // doesn't work
    X(std::string& text): text(text) {}
};

The easy way is to pass a pointer to this class. But if I pass a reference, can I get a pointer with a getter?

Edit: here is the error message

error: cannot declare pointer to 'std::__cxx11::string& {aka class std::__cxx11::basic_string<char>&}'
auto GetText() -> decltype(text) * { return &text);
                                 ^

Body:
Firstly,

auto GetText() -> decltype(text) * { return &text); // doesn't work

is a positively abominable way to declare this signature. Prefer

std::string* GetText(){ return &text);

or even just

auto GetText(){ return &text);

But this isn't code review.

The problem here is that you're asking for a pointer to the declared type of the text member variable which is a string reference (std::string&). From the comment section, it seems you were unaware that decltype respects the 'reference'ness, 'const'ness, and 'volatile'ness of its argument.

You cannot have a pointer to a reference in C++, e.g. std::string&* is malformed. Calling to std::remove_reference_t should resolve that issue, e.g.

auto GetText() -> std::remove_reference_t<decltype(text)> * { return &text);

However, in this case, auto would have correctly deduced your type anyway, so your explicit declaration is unnecessary.


问:
How to pass a variable content to the client side?
I'm working with express js. I want to pass the content of the variable "resultat" to the client side and put it into a javascript variable to be used in a ejs page.
this code is in app.js

```<code>var fs = require('fs');// File System Module
var xml2js = require('xml2js'); // XML2JS Module
var parser = new xml2js.Parser(); // Creating XML to JSON parser object
// Reading and Parsing the file
fs.readFile( 'views/xmlfile.xml', function(err, data) {
    parser.parseString(data, function (err, resultat) {
        console.log(resultat);
        console.log('Done');
    });
});
</code>```

the content of the variable "resultat" is shown in the console

答:
You could use this (client-side):

```<code><script>
  var myVar = <%- JSON.stringify(myVar) %>;
</script>
</code>```

You could also get EJS to render a .js file

In router file you will get res object.

```<code>fs.readFile( 'views/xmlfile.xml', function(err, data) {
parser.parseString(data, function (err, resultat) {
    console.log(resultat);
    console.log('Done');
    res.set('Content-Type', 'application/javascript');
   res.render('testPage', { myVar : resultat : ... });
    });
});
</code>```

Body:
I'm working with express js. I want to pass the content of the variable "resultat" to the client side and put it into a javascript variable to be used in a ejs page.
this code is in app.js

var fs = require('fs');// File System Module
var xml2js = require('xml2js'); // XML2JS Module
var parser = new xml2js.Parser(); // Creating XML to JSON parser object
// Reading and Parsing the file
fs.readFile( 'views/xmlfile.xml', function(err, data) {
    parser.parseString(data, function (err, resultat) {
        console.log(resultat);
        console.log('Done');
    });
});

the content of the variable "resultat" is shown in the console

Body:
You could use this (client-side):

<script>
  var myVar = <%- JSON.stringify(myVar) %>;
</script>

You could also get EJS to render a .js file

In router file you will get res object.

fs.readFile( 'views/xmlfile.xml', function(err, data) {
parser.parseString(data, function (err, resultat) {
    console.log(resultat);
    console.log('Done');
    res.set('Content-Type', 'application/javascript');
   res.render('testPage', { myVar : resultat : ... });
    });
});


问:
How does one get widget values with a button in ipython
I have a function createWidgets whose purpose is to take a list of strings and create a list of containers for each string -> 1 container = a textbox and checkbox.  Each container is then put into a large container.

What I am trying to do is append a button to the container that on_click takes all the "True"s and puts all the modified strings and puts them in a dataframe

```<code>    widgelist = e.options
    txtBox_type = 'text_widget' # Define if Area box o regular txtbox
    bigContainer = createWidgets(widgelist, txtBox_type)

    Function
    def createWidgets(widgelist, txtBox_type):

        #containerList = []
        i = 0

        for k in widgelist:
        ## Build Container widgets

           chBox_Widget = widgets.CheckboxWidget(description = str(i),value = False,)
           if txtBox_type == 'textA_widget': # Check wether txtBox should be an area txt box or not.
               txt_Widget = widgets.TextareaWidget( description = str(i), value = k)
           else:
               txt_Widget = widgets.TextWidget( description = str(i), value = k)

        container = widgets.ContainerWidget()
        container.children = [chBox_Widget, txt_Widget]
        containerList.append(container)

        i+= 1

        button = widgets.ButtonWidget(description = 'Add')
        bigContainer = widgets.ContainerWidget()
        bigContainer.children = containerList

        return  bigContainer
</code>```

I have gone to many websites and spent many days on this help is very much appreciated

答:
This is updated version for Ipython3 on jupyternotebooks 4

Just rename:

widgets.ContainerWidget ->widgets.Box

widgets.CheckboxWidget -> widgets.Checkbox

widgets.TextWidget     -> widgets.Text

Reference: [https://ipython.org/ipython-doc/3/whatsnew/version3_widget_migration.html]

Body:
I have a function createWidgets whose purpose is to take a list of strings and create a list of containers for each string -> 1 container = a textbox and checkbox.  Each container is then put into a large container.

What I am trying to do is append a button to the container that on_click takes all the "True"s and puts all the modified strings and puts them in a dataframe

    widgelist = e.options
    txtBox_type = 'text_widget' # Define if Area box o regular txtbox
    bigContainer = createWidgets(widgelist, txtBox_type)

    Function
    def createWidgets(widgelist, txtBox_type):

        #containerList = []
        i = 0

        for k in widgelist:
        ## Build Container widgets

           chBox_Widget = widgets.CheckboxWidget(description = str(i),value = False,)
           if txtBox_type == 'textA_widget': # Check wether txtBox should be an area txt box or not.
               txt_Widget = widgets.TextareaWidget( description = str(i), value = k)
           else:
               txt_Widget = widgets.TextWidget( description = str(i), value = k)

        container = widgets.ContainerWidget()
        container.children = [chBox_Widget, txt_Widget]
        containerList.append(container)

        i+= 1

        button = widgets.ButtonWidget(description = 'Add')
        bigContainer = widgets.ContainerWidget()
        bigContainer.children = containerList

        return  bigContainer

I have gone to many websites and spent many days on this help is very much appreciated


问:
How can I simplify this code? (Chess game obstruction testing)
I'm making a chess game in Java, and testing to make sure there are no pieces blocking the path of the piece being moved. The piece moves from (srcX,srcY) to (dstX,dstY).

I've written this code which checks if there are any obstructions for a rook:

```<code>    if(dstY == srcY) {

            // No change on Y axis, so moving east or west

            if(dstX > srcX) {
                // Moving east
                // Test every cell the piece will pass over
                for(int x = srcX+1; x < dstX; x++) {
                    // Is the cell set?
                    if(isPiece(x, srcY)) {
                        return true;
                    }
                }
            } else {
                // Must be moving west
                // Test every cell the piece will pass over
                for(int x = srcX-1; x > dstX; x--) {
                    // Is the cell set?
                    if(isPiece(x, srcY)) {
                        return true;
                    }
                }
            }

        } else if(dstX == srcX) {

            // No change on X axis, so moving north or south

            if(dstY > srcY) {
                // Moving north
                // Test every cell the piece will pass over
                for(int y = srcY+1; y < dstY; y++) {
                    // Is the cell set?
                    if(isPiece(srcX, y)) {
                        return true;
                    }
                }
            } else {
                // Must be moving south
                // Test every cell the piece will pass over
                for(int y = srcY-1; y > dstY; y--) {
                    // Is the cell set?
                    if(isPiece(srcX, y)) {
                        return true;
                    }
                }
            }
        }
</code>```

but it's a bit big and I'm sure it can be simplied.. any ideas?

ps, this is ONLY obstruction testing. I've already validated everything else.

答:
You could do something along these lines (untested as I don't have a compiler to hand):</p>

```
int dx = 0;
int dy = 0;
if (dstX != srcX) {
  dx = (dstX > srcX) ? 1 : -1;
} else if (dstY != srcY) {
  dy = (dstY > srcY) ? 1 : -1;
}
int x = srcX + dx;
int y = srcY + dy;
while (x != dstX || y != dstY) {
  if (isPiece(x, y)) return true;
  x += dx;
  y += dy;
}
```

Body:
I'm making a chess game in Java, and testing to make sure there are no pieces blocking the path of the piece being moved. The piece moves from (srcX,srcY) to (dstX,dstY).

I've written this code which checks if there are any obstructions for a rook:

    if(dstY == srcY) {

            // No change on Y axis, so moving east or west

            if(dstX > srcX) {
                // Moving east
                // Test every cell the piece will pass over
                for(int x = srcX+1; x < dstX; x++) {
                    // Is the cell set?
                    if(isPiece(x, srcY)) {
                        return true;
                    }
                }
            } else {
                // Must be moving west
                // Test every cell the piece will pass over
                for(int x = srcX-1; x > dstX; x--) {
                    // Is the cell set?
                    if(isPiece(x, srcY)) {
                        return true;
                    }
                }
            }

        } else if(dstX == srcX) {

            // No change on X axis, so moving north or south

            if(dstY > srcY) {
                // Moving north
                // Test every cell the piece will pass over
                for(int y = srcY+1; y < dstY; y++) {
                    // Is the cell set?
                    if(isPiece(srcX, y)) {
                        return true;
                    }
                }
            } else {
                // Must be moving south
                // Test every cell the piece will pass over
                for(int y = srcY-1; y > dstY; y--) {
                    // Is the cell set?
                    if(isPiece(srcX, y)) {
                        return true;
                    }
                }
            }
        }

but it's a bit big and I'm sure it can be simplied.. any ideas?

ps, this is ONLY obstruction testing. I've already validated everything else.

Body:
You could do something along these lines (untested as I don't have a compiler to hand):

int dx = 0;
int dy = 0;
if (dstX != srcX) {
  dx = (dstX > srcX) ? 1 : -1;
} else if (dstY != srcY) {
  dy = (dstY > srcY) ? 1 : -1;
}
int x = srcX + dx;
int y = srcY + dy;
while (x != dstX || y != dstY) {
  if (isPiece(x, y)) return true;
  x += dx;
  y += dy;
}


问:
How to adjust the divs?
I need to move the paragraph div over to the left with it expanding all the way to the image. The top-div should display on two lines and break after the word festival. Both paragraphs should be to the left of the image. How do I get the div's to display correctly?

body {
  width: 8.5in;
}

.container {
  display: flex;
  background: red;
}

.top-div {
  display: table;
  background: rgb(204, 255, 102);
  text-align: center;
  font-size: 1.75em;
  font-weight: bold;
  color: rgb(35, 66, 113);
}

.top-div>p {
  margin: 10px;
}

.paragraph {
  align-self: flex-end;
  background: blue;
}

.flower-img {
  display: table;
  float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="top-div">
    <p lang="zh">Qingming Festival<br>qīng míng jié</p>
  </div>
  <div class="paragraph">
    <p>The Qingming or Ching Ming Festival, also known as Tomb-Sweeping Day in English, is a traditional Chinese festival on the first day of the fifth solar term of the traditional Chinese lunisolar calendar. This makes it the 15th day after the Spring
      Equinox, either 4 or 5 April in a given year. Other common translations include Chinese Memorial Day and Ancestors' Day.</p>
    <p>It is also a time for people to go outside to enjoy the spring such as having a picnic or flying a kite. In 2017 Qingming Festival falls on April 4. The three-day public holiday in China is April 3–5, 2017.</p>
  </div>
  <div>
    <img src="//dummyimage.com/300x450" alt="flower" width="300" class="flower-img">
  </div>
</div></code>```

This what I would like it to look like

答:
Make the width property of the p element equal to 100%. This will render it across the entire screen. If that doesn't work, set the width of the div that contains the p element equal to 100% as well. Not sure what you want to do with the 'top-div'. If you're trying to center it, you can just do this:</p>

```<code>       p {
             text-align: center;
          }
</code>```

Title: How to adjust the divs?

Body:
I need to move the paragraph div over to the left with it expanding all the way to the image. The top-div should display on two lines and break after the word festival. Both paragraphs should be to the left of the image. How do I get the div's to display correctly?

body {
  width: 8.5in;
}

.container {
  display: flex;
  background: red;
}

.top-div {
  display: table;
  background: rgb(204, 255, 102);
  text-align: center;
  font-size: 1.75em;
  font-weight: bold;
  color: rgb(35, 66, 113);
}

.top-div>p {
  margin: 10px;
}

.paragraph {
  align-self: flex-end;
  background: blue;
}

.flower-img {
  display: table;
  float: left;
}

Qingming Festival
qīng míng jié

The Qingming or Ching Ming Festival, also known as Tomb-Sweeping Day in English, is a traditional Chinese festival on the first day of the fifth solar term of the traditional Chinese lunisolar calendar. This makes it the 15th day after the Spring
      Equinox, either 4 or 5 April in a given year. Other common translations include Chinese Memorial Day and Ancestors' Day.

It is also a time for people to go outside to enjoy the spring such as having a picnic or flying a kite. In 2017 Qingming Festival falls on April 4. The three-day public holiday in China is April 3–5, 2017.

This what I would like it to look like

Body:
Make the width property of the p element equal to 100%. This will render it across the entire screen. If that doesn't work, set the width of the div that contains the p element equal to 100% as well. Not sure what you want to do with the 'top-div'. If you're trying to center it, you can just do this:

       p {
             text-align: center;
          }


答:
You can apply Replacer function  of JSON.stringify

```<code>var data='{"id":1,"name":"Light Switch","lightStatus":true,"inputPort":{"id":2,"value":0},"outputPort":{"id":2,"value":false},"resistance":100}';
var json=JSON.parse(data);

function replacer(i, val) {
  switch (i) {
    case "": case "name": case "resistance":
        return val
    case "inputPort": case "outputPort":
        return val.id
    default:
        return undefined;
  }

}

console.log(JSON.stringify(json,replacer));
</code>```

Body:
I'm trying to modify a string with Typescript. The string is created by the JSON.stringify() method.

I want to remove the properties "id", "lightStatus" and the "value" attributes of "inputPort" and "outputPort". (I only need their attribute "id".)

console.log(JSON.stringify(this.light));
// Results in -> {"id":1,"name":"Light Switch","lightStatus":true,"inputPort":{"id":2,"value":0},"outputPort":{"id":2,"value":false},"resistance":100}

I tried to do it the following way but it doesn't recognize "inputPort.id" and "outputPort.id". This is what I tried and what it resulted in.

var savedLight = JSON.stringify(this.light, ["name", "inputPort.id", "outputPort.id", "resistance"]);
// Results in -> {"name":"Light Switch","resistance":100}

The result should include the properties "name", "inputPort id", "outputPort id" and "resistance". Like this:

{"name":"Light Switch","inputPort": 2, "outputPort": 2, "resistance":100}

Can anyone help me how I can get rid of the unnecessary properties?

Body:
You can apply Replacer function  of JSON.stringify

var data='{"id":1,"name":"Light Switch","lightStatus":true,"inputPort":{"id":2,"value":0},"outputPort":{"id":2,"value":false},"resistance":100}';
var json=JSON.parse(data);

function replacer(i, val) {
  switch (i) {
    case "": case "name": case "resistance":
        return val
    case "inputPort": case "outputPort":
        return val.id
    default:
        return undefined;
  }

}

console.log(JSON.stringify(json,replacer));


问:
How to POST using HTTPclient content type = application/x-www-form-urlencoded
I am currently developing a wp8.1 application C#, i have managed to perform a POST method in json to my api by creating a json object (bm) from textbox.texts.
here is my code below. How do i take the same textbox.text and POST them as a content type = application/x-www-form-urlencoded. whats the code for that?

```<code>Profile bm = new Profile();
bm.first_name = Names.Text;
bm.surname = surname.Text;

string json = JsonConvert.SerializeObject(bm);

MessageDialog messageDialog = new MessageDialog(json);//Text should not be empty
await messageDialog.ShowAsync();

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");

byte[] messageBytes = Encoding.UTF8.GetBytes(json);
var content = new ByteArrayContent(messageBytes);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = client.PostAsync("myapiurl", content).Result;
</code>```

答:
```<code>var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("Input1", "TEST2"));
nvc.Add(new KeyValuePair<string, string>("Input2", "TEST2"));
var client = new HttpClient();
var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(nvc) };
var res = await client.SendAsync(req);
</code>```

Or

```<code>var dict = new Dictionary<string, string>();
dict.Add("Input1", "TEST2");
dict.Add("Input2", "TEST2");
var client = new HttpClient();
var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(dict) };
var res = await client.SendAsync(req);
</code>```

Body:
I am currently developing a wp8.1 application C#, i have managed to perform a POST method in json to my api by creating a json object (bm) from textbox.texts.
here is my code below. How do i take the same textbox.text and POST them as a content type = application/x-www-form-urlencoded. whats the code for that?

Profile bm = new Profile();
bm.first_name = Names.Text;
bm.surname = surname.Text;

string json = JsonConvert.SerializeObject(bm);

MessageDialog messageDialog = new MessageDialog(json);//Text should not be empty
await messageDialog.ShowAsync();

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");

byte[] messageBytes = Encoding.UTF8.GetBytes(json);
var content = new ByteArrayContent(messageBytes);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = client.PostAsync("myapiurl", content).Result;

Body:
var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("Input1", "TEST2"));
nvc.Add(new KeyValuePair<string, string>("Input2", "TEST2"));
var client = new HttpClient();
var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(nvc) };
var res = await client.SendAsync(req);

Or

var dict = new Dictionary<string, string>();
dict.Add("Input1", "TEST2");
dict.Add("Input2", "TEST2");
var client = new HttpClient();
var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(dict) };
var res = await client.SendAsync(req);


问:
Calculations in childs using pipes
My task is

a. A parent and two childs

b. Parent take data from the user

c. Send to a child for addition and subtraction.

d. Again take input from user and send to another child for multiplication and division.

e. First child process creates another child C3.

f. Both the childs send result to the child process C3 to show output.

g. Parent process after completion of each child process task kill the process.

I've write the following code but i don't know where I'm doing wrong, I tried to debug it but I do not know what is wrong with it, it not showing the multiplication and division result.

Here is my code:

```<code>#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include<string.h>
#include <stdlib.h>

int main()
{
    int status = 0;
    int pfds[2];
    int pfds2[2];
    int pfds3[2];
    int pfds4[2];
    int val = 0;
    int val2 = 0;
    pipe(pfds);
    pipe(pfds2);
    pipe(pfds3);
    pipe(pfds4);
    printf("Enter FIRST Number:  ");
    scanf("%i", &val);
    printf("Enter SECOND Number:  ");
    scanf("%i", &val2);
    if (fork() == 0)
    {
//Child
        printf("I'm Child 1 and I'm Calculating Sum AND Differnece Of Numbers\n");
        read(pfds[0], &val, sizeof(val));
        read(pfds2[0], &val2, sizeof(val));
        int sum = val + val2;
        int sub = val - val2;
        write(pfds3[1], &sum, sizeof(val));
        write(pfds4[1], &sub, sizeof(val));
        if (fork() == 0)
        {
            read(pfds3[0], &val, sizeof(val));
            printf("Sum Of Numbers Is : %i\n", val);
            read(pfds4[0], &val, sizeof(val));
            printf("Sub Of Numbers Is : %i\n", val);
            read(pfds[0], &val, sizeof(val));
            printf("Mul Of Numbers Is : %i\n", val);
            read(pfds2[0], &val, sizeof(val));
            printf("Div Of Numbers Is : %i\n", val);
            exit(1);
        }
        else
        {
            wait(&status);
        }
        exit(1);
    }
    else
    {
        if (fork() == 0)
        {
//Child2
            printf("I'm Child 2 and I'm Calculating Multiplication and Division Of Number\n");
            read(pfds[0], &val, sizeof(val));
            read(pfds2[0], &val2, sizeof(val));
            int mul = val * val2;
            int div = val / val2;
            write(pfds[1], &mul, sizeof(val));
            write(pfds2[1], &div, sizeof(val));
            exit(0);
        }
        else
        {
//wait(&status);
            write(pfds[1], &val, sizeof(val));
            write(pfds2[1], &val2, sizeof(val));
            wait(&status);
        } //else1
    } //else2
} //main
</code>```

It's giving me the following output:

```<code>Enter FIRST Number:  4
Enter SECOND Number:  2
I'm Child 1 and I'm Calculating Sum AND Differnece Of Numbers
I'm Child 2 and I'm Calculating Multiplication and Division Of Number
Sum Of Numbers Is : 6
Sub Of Numbers Is : 2
</code>```

If someone can help thankyou very much.

答:
Here is what you can do:

```<code>#include <stdio.h>
#include <unistd.h>
#include<stdlib.h>
int main()
{
int status = 0;
int fd1[2], fd2[2], fd3[2], fd4[2], a, b;
pipe(fd1); pipe(fd2);
pipe(fd3); pipe(fd4);
printf("Input two numbers for + and - ");
scanf("%d,", &a); scanf("%d,", &b);
write(fd1[1], &a, sizeof(int));
write(fd2[1], &b, sizeof(int));
printf("Input two numbers for multiplication and division\n");
scanf("%d,", &a); scanf("%d,", &b);
write(fd3[1], &a, sizeof(int));
write(fd4[1], &b, sizeof(int));
pid_t child1 = fork();
if (child1 == 0)
{
    int status = 0, a, b, c;
    read(fd1[0], &a, sizeof(int));
    read(fd2[0], &b, sizeof(int));
    printf("I'm 1st child and calculating + and -\n");
    c = a + b;
    a = a - b;
    write(fd1[1], &c, sizeof(int));
    write(fd2[1], &a, sizeof(int));
    pid_t c3 = fork();
    if (c3 == 0)
    {
        int sum, sub, mul, div;
        read(fd1[0], &sum, sizeof(int));
        read(fd2[0], &sub, sizeof(int));
        read(fd3[0], &mul, sizeof(int));
        read(fd4[0], &div, sizeof(int));
        printf("SUM = %d\n", sum);
        printf("SUB = %d\n", sub);
        printf("MUL = %d\n", mul);
        printf("DIV = %d\n", div);
    }
}
else
{
    pid_t child2 = fork();
    if (child2 == 0) {
        int status = 0, a, b, c;
        read(fd3[0], &a, sizeof(int));
        read(fd4[0], &b, sizeof(int));
        printf("I'm 2nd child and calculating multiplication and division");
        c = a*b;
        a = a / b;
        write(fd3[1], &c, sizeof(int));
        write(fd4[1], &a, sizeof(int));
    }
}
return 0;
}
</code>```

Hope this will help you :)

Title: Calculations in childs using pipes

Body:
My task is

a. A parent and two childs

b. Parent take data from the user

c. Send to a child for addition and subtraction.

d. Again take input from user and send to another child for multiplication and division.

e. First child process creates another child C3.

f. Both the childs send result to the child process C3 to show output.

g. Parent process after completion of each child process task kill the process.

I've write the following code but i don't know where I'm doing wrong, I tried to debug it but I do not know what is wrong with it, it not showing the multiplication and division result.

Here is my code:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include<string.h>
#include <stdlib.h>

int main()
{
    int status = 0;
    int pfds[2];
    int pfds2[2];
    int pfds3[2];
    int pfds4[2];
    int val = 0;
    int val2 = 0;
    pipe(pfds);
    pipe(pfds2);
    pipe(pfds3);
    pipe(pfds4);
    printf("Enter FIRST Number:  ");
    scanf("%i", &val);
    printf("Enter SECOND Number:  ");
    scanf("%i", &val2);
    if (fork() == 0)
    {
//Child
        printf("I'm Child 1 and I'm Calculating Sum AND Differnece Of Numbers\n");
        read(pfds[0], &val, sizeof(val));
        read(pfds2[0], &val2, sizeof(val));
        int sum = val + val2;
        int sub = val - val2;
        write(pfds3[1], &sum, sizeof(val));
        write(pfds4[1], &sub, sizeof(val));
        if (fork() == 0)
        {
            read(pfds3[0], &val, sizeof(val));
            printf("Sum Of Numbers Is : %i\n", val);
            read(pfds4[0], &val, sizeof(val));
            printf("Sub Of Numbers Is : %i\n", val);
            read(pfds[0], &val, sizeof(val));
            printf("Mul Of Numbers Is : %i\n", val);
            read(pfds2[0], &val, sizeof(val));
            printf("Div Of Numbers Is : %i\n", val);
            exit(1);
        }
        else
        {
            wait(&status);
        }
        exit(1);
    }
    else
    {
        if (fork() == 0)
        {
//Child2
            printf("I'm Child 2 and I'm Calculating Multiplication and Division Of Number\n");
            read(pfds[0], &val, sizeof(val));
            read(pfds2[0], &val2, sizeof(val));
            int mul = val * val2;
            int div = val / val2;
            write(pfds[1], &mul, sizeof(val));
            write(pfds2[1], &div, sizeof(val));
            exit(0);
        }
        else
        {
//wait(&status);
            write(pfds[1], &val, sizeof(val));
            write(pfds2[1], &val2, sizeof(val));
            wait(&status);
        } //else1
    } //else2
} //main

It's giving me the following output:

Enter FIRST Number:  4
Enter SECOND Number:  2
I'm Child 1 and I'm Calculating Sum AND Differnece Of Numbers
I'm Child 2 and I'm Calculating Multiplication and Division Of Number
Sum Of Numbers Is : 6
Sub Of Numbers Is : 2

If someone can help thankyou very much.

Body:
Here is what you can do:

#include <stdio.h>
#include <unistd.h>
#include<stdlib.h>
int main()
{
int status = 0;
int fd1[2], fd2[2], fd3[2], fd4[2], a, b;
pipe(fd1); pipe(fd2);
pipe(fd3); pipe(fd4);
printf("Input two numbers for + and - ");
scanf("%d,", &a); scanf("%d,", &b);
write(fd1[1], &a, sizeof(int));
write(fd2[1], &b, sizeof(int));
printf("Input two numbers for multiplication and division\n");
scanf("%d,", &a); scanf("%d,", &b);
write(fd3[1], &a, sizeof(int));
write(fd4[1], &b, sizeof(int));
pid_t child1 = fork();
if (child1 == 0)
{
    int status = 0, a, b, c;
    read(fd1[0], &a, sizeof(int));
    read(fd2[0], &b, sizeof(int));
    printf("I'm 1st child and calculating + and -\n");
    c = a + b;
    a = a - b;
    write(fd1[1], &c, sizeof(int));
    write(fd2[1], &a, sizeof(int));
    pid_t c3 = fork();
    if (c3 == 0)
    {
        int sum, sub, mul, div;
        read(fd1[0], &sum, sizeof(int));
        read(fd2[0], &sub, sizeof(int));
        read(fd3[0], &mul, sizeof(int));
        read(fd4[0], &div, sizeof(int));
        printf("SUM = %d\n", sum);
        printf("SUB = %d\n", sub);
        printf("MUL = %d\n", mul);
        printf("DIV = %d\n", div);
    }
}
else
{
    pid_t child2 = fork();
    if (child2 == 0) {
        int status = 0, a, b, c;
        read(fd3[0], &a, sizeof(int));
        read(fd4[0], &b, sizeof(int));
        printf("I'm 2nd child and calculating multiplication and division");
        c = a*b;
        a = a / b;
        write(fd3[1], &c, sizeof(int));
        write(fd4[1], &a, sizeof(int));
    }
}
return 0;
}

Hope this will help you :)


问:
Libgdx Error in Importing chartboost. sdk
I am trying to add chartboost ads, I had added the jar file to my libs but when I am trying to import the chartboost sdk it gives me error and the whole lines of:

```<code>import com.chartboost.sdk.Chartboost;
import com.chartboost.sdk.CBLocation;
import com.chartboost.sdk.ChartboostDelegate;
</code>```

was red
but when I added this code to the gradle

```<code> compile files('libs/chartboost.jar')
</code>```

only Chartboost , CBLocation, ChartboostDelegate, is red
and gives me

```<code>Error:(19, 26) error: package com.chartboost.sdk does not exist
</code>```

here is the code of the build gradle (Project):

```<code>buildscript {
    repositories {
        mavenCentral()
        maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
        jcenter()
    }
    dependencies {
        classpath 'de.richsource.gradle.plugins:gwt-gradle-plugin:0.6'
        classpath 'com.android.tools.build:gradle:1.5.0'
        classpath 'org.robovm:robovm-gradle-plugin:1.12.0'
    }
}

allprojects {
    apply plugin: "eclipse"
    apply plugin: "idea"

    version = '1.0'
    ext {
        appName = "FlappyBird"
        gdxVersion = '1.7.2'
        roboVMVersion = '1.12.0'
        box2DLightsVersion = '1.4'
        ashleyVersion = '1.7.0'
        aiVersion = '1.7.0'
    }

    repositories {
        mavenCentral()
        maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
        maven { url "https://oss.sonatype.org/content/repositories/releases/" }
    }
}

project(":desktop") {
    apply plugin: "java"

    dependencies {
        compile project(":core")
        compile "com.badlogicgames.gdx:gdx-backend-lwjgl:$gdxVersion"
        compile "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-desktop"
        compile "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-desktop"
    }
}

project(":android") {
    apply plugin: "android"

    configurations { natives }

    dependencies {
        compile project(":core")

        compile "com.badlogicgames.gdx:gdx-backend-android:$gdxVersion"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi-v7a"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-x86"
        compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi-v7a"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-x86"
        compile 'com.google.android.gms:play-services-ads:9.2.1'
        compile files('libs/chartboost.jar')

    }
}

project(":ios") {
    apply plugin: "java"
    apply plugin: "robovm"

    dependencies {
        compile project(":core")
        compile "org.robovm:robovm-rt:$roboVMVersion"
        compile "org.robovm:robovm-cocoatouch:$roboVMVersion"
        compile "com.badlogicgames.gdx:gdx-backend-robovm:$gdxVersion"
        compile "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-ios"
        compile "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-ios"
    }
}

project(":html") {
    apply plugin: "gwt"
    apply plugin: "war"

    dependencies {
        compile project(":core")
        compile "com.badlogicgames.gdx:gdx-backend-gwt:$gdxVersion"
        compile "com.badlogicgames.gdx:gdx:$gdxVersion:sources"
        compile "com.badlogicgames.gdx:gdx-backend-gwt:$gdxVersion:sources"
        compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion:sources"
        compile "com.badlogicgames.gdx:gdx-box2d-gwt:$gdxVersion:sources"
    }
}

project(":core") {
    apply plugin: "java"

    dependencies {
        compile "com.badlogicgames.gdx:gdx:$gdxVersion"
        compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion"
    }
}

tasks.eclipse.doLast {
    delete ".project"
}
</code>```

and here the code of build gradle ( module: android):

```<code>android {
    buildToolsVersion "23.0.3"
    compileSdkVersion 24
    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
            jniLibs.srcDirs = ['libs']
        }

        instrumentTest.setRoot('tests')
    }
    defaultConfig {
        applicationId "com.myflappybird.game"
        minSdkVersion 9
        targetSdkVersion 24
    }
}

// called every time gradle gets executed, takes the native dependencies of
// the natives configuration, and extracts them to the proper libs/ folders
// so they get packed with the APK.
task copyAndroidNatives() {
    file("libs/armeabi/").mkdirs();
    file("libs/armeabi-v7a/").mkdirs();
    file("libs/x86/").mkdirs();

    configurations.natives.files.each { jar ->
        def outputDir = null
        if(jar.name.endsWith("natives-armeabi-v7a.jar")) outputDir = file("libs/armeabi-v7a")
        if(jar.name.endsWith("natives-armeabi.jar")) outputDir = file("libs/armeabi")
        if(jar.name.endsWith("natives-x86.jar")) outputDir = file("libs/x86")
        if(outputDir != null) {
            copy {
                from zipTree(jar)
                into outputDir
                include "*.so"
            }
        }
    }
}

task run(type: Exec) {
    def path
    def localProperties = project.file("../local.properties")
    if (localProperties.exists()) {
        Properties properties = new Properties()
        localProperties.withInputStream { instr ->
            properties.load(instr)
        }
        def sdkDir = properties.getProperty('sdk.dir')
        if (sdkDir) {
            path = sdkDir
        } else {
            path = "$System.env.ANDROID_HOME"
        }
    } else {
        path = "$System.env.ANDROID_HOME"
    }

    def adb = path + "/platform-tools/adb"
    commandLine "$adb", 'shell', 'am', 'start', '-n', 'com.myflappybird.game/com.myflappybird.game.AndroidLauncher'
}

// sets up the Android Eclipse project, using the old Ant based build.
eclipse {
    // need to specify Java source sets explicitely, SpringSource Gradle Eclipse plugin
    // ignores any nodes added in classpath.file.withXml
    sourceSets {
        main {
            java.srcDirs "src", 'gen'
        }
    }

    jdt {
        sourceCompatibility = 1.6
        targetCompatibility = 1.6
    }

    classpath {
        plusConfigurations += [ project.configurations.compile ]
        containers 'com.android.ide.eclipse.adt.ANDROID_FRAMEWORK', 'com.android.ide.eclipse.adt.LIBRARIES'
    }

    project {
        name = appName + "-android"
        natures 'com.android.ide.eclipse.adt.AndroidNature'
        buildCommands.clear();
        buildCommand "com.android.ide.eclipse.adt.ResourceManagerBuilder"
        buildCommand "com.android.ide.eclipse.adt.PreCompilerBuilder"
        buildCommand "org.eclipse.jdt.core.javabuilder"
        buildCommand "com.android.ide.eclipse.adt.ApkBuilder"
    }
}

// sets up the Android Idea project, using the old Ant based build.
idea {
    module {
        sourceDirs += file("src");
        scopes = [ COMPILE: [plus:[project.configurations.compile]]]

        iml {
            withXml {
                def node = it.asNode()
                def builder = NodeBuilder.newInstance();
                builder.current = node;
                builder.component(name: "FacetManager") {
                    facet(type: "android", name: "Android") {
                        configuration {
                            option(name: "UPDATE_PROPERTY_FILES", value:"true")
                        }
                    }
                }
            }
        }
    }
}
</code>```

答:
With much pain...  It seems that the chartboost.jar doesn't like to just be in the libs folder directly.  At least when using the LibGDX framework.

So, I created a subfolder in libs called "chartboost" and added this line to the gradle

compile fileTree(dir: 'libs/chartboost', include: ['*.jar'])

Seems to have gotten me past my compile problems.

Body:
I am trying to add chartboost ads, I had added the jar file to my libs but when I am trying to import the chartboost sdk it gives me error and the whole lines of:

import com.chartboost.sdk.Chartboost;
import com.chartboost.sdk.CBLocation;
import com.chartboost.sdk.ChartboostDelegate;

was red
but when I added this code to the gradle

 compile files('libs/chartboost.jar')

only Chartboost , CBLocation, ChartboostDelegate, is red
and gives me

Error:(19, 26) error: package com.chartboost.sdk does not exist

here is the code of the build gradle (Project):

buildscript {
    repositories {
        mavenCentral()
        maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
        jcenter()
    }
    dependencies {
        classpath 'de.richsource.gradle.plugins:gwt-gradle-plugin:0.6'
        classpath 'com.android.tools.build:gradle:1.5.0'
        classpath 'org.robovm:robovm-gradle-plugin:1.12.0'
    }
}

allprojects {
    apply plugin: "eclipse"
    apply plugin: "idea"

    version = '1.0'
    ext {
        appName = "FlappyBird"
        gdxVersion = '1.7.2'
        roboVMVersion = '1.12.0'
        box2DLightsVersion = '1.4'
        ashleyVersion = '1.7.0'
        aiVersion = '1.7.0'
    }

    repositories {
        mavenCentral()
        maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
        maven { url "https://oss.sonatype.org/content/repositories/releases/" }
    }
}

project(":desktop") {
    apply plugin: "java"

    dependencies {
        compile project(":core")
        compile "com.badlogicgames.gdx:gdx-backend-lwjgl:$gdxVersion"
        compile "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-desktop"
        compile "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-desktop"
    }
}

project(":android") {
    apply plugin: "android"

    configurations { natives }

    dependencies {
        compile project(":core")

        compile "com.badlogicgames.gdx:gdx-backend-android:$gdxVersion"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi-v7a"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-x86"
        compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi-v7a"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-x86"
        compile 'com.google.android.gms:play-services-ads:9.2.1'
        compile files('libs/chartboost.jar')

    }
}

project(":ios") {
    apply plugin: "java"
    apply plugin: "robovm"

    dependencies {
        compile project(":core")
        compile "org.robovm:robovm-rt:$roboVMVersion"
        compile "org.robovm:robovm-cocoatouch:$roboVMVersion"
        compile "com.badlogicgames.gdx:gdx-backend-robovm:$gdxVersion"
        compile "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-ios"
        compile "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-ios"
    }
}

project(":html") {
    apply plugin: "gwt"
    apply plugin: "war"

    dependencies {
        compile project(":core")
        compile "com.badlogicgames.gdx:gdx-backend-gwt:$gdxVersion"
        compile "com.badlogicgames.gdx:gdx:$gdxVersion:sources"
        compile "com.badlogicgames.gdx:gdx-backend-gwt:$gdxVersion:sources"
        compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion:sources"
        compile "com.badlogicgames.gdx:gdx-box2d-gwt:$gdxVersion:sources"
    }
}

project(":core") {
    apply plugin: "java"

    dependencies {
        compile "com.badlogicgames.gdx:gdx:$gdxVersion"
        compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion"
    }
}

tasks.eclipse.doLast {
    delete ".project"
}

and here the code of build gradle ( module: android):

android {
    buildToolsVersion "23.0.3"
    compileSdkVersion 24
    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
            jniLibs.srcDirs = ['libs']
        }

        instrumentTest.setRoot('tests')
    }
    defaultConfig {
        applicationId "com.myflappybird.game"
        minSdkVersion 9
        targetSdkVersion 24
    }
}

// called every time gradle gets executed, takes the native dependencies of
// the natives configuration, and extracts them to the proper libs/ folders
// so they get packed with the APK.
task copyAndroidNatives() {
    file("libs/armeabi/").mkdirs();
    file("libs/armeabi-v7a/").mkdirs();
    file("libs/x86/").mkdirs();

    configurations.natives.files.each { jar ->
        def outputDir = null
        if(jar.name.endsWith("natives-armeabi-v7a.jar")) outputDir = file("libs/armeabi-v7a")
        if(jar.name.endsWith("natives-armeabi.jar")) outputDir = file("libs/armeabi")
        if(jar.name.endsWith("natives-x86.jar")) outputDir = file("libs/x86")
        if(outputDir != null) {
            copy {
                from zipTree(jar)
                into outputDir
                include "*.so"
            }
        }
    }
}

task run(type: Exec) {
    def path
    def localProperties = project.file("../local.properties")
    if (localProperties.exists()) {
        Properties properties = new Properties()
        localProperties.withInputStream { instr ->
            properties.load(instr)
        }
        def sdkDir = properties.getProperty('sdk.dir')
        if (sdkDir) {
            path = sdkDir
        } else {
            path = "$System.env.ANDROID_HOME"
        }
    } else {
        path = "$System.env.ANDROID_HOME"
    }

    def adb = path + "/platform-tools/adb"
    commandLine "$adb", 'shell', 'am', 'start', '-n', 'com.myflappybird.game/com.myflappybird.game.AndroidLauncher'
}

// sets up the Android Eclipse project, using the old Ant based build.
eclipse {
    // need to specify Java source sets explicitely, SpringSource Gradle Eclipse plugin
    // ignores any nodes added in classpath.file.withXml
    sourceSets {
        main {
            java.srcDirs "src", 'gen'
        }
    }

    jdt {
        sourceCompatibility = 1.6
        targetCompatibility = 1.6
    }

    classpath {
        plusConfigurations += [ project.configurations.compile ]
        containers 'com.android.ide.eclipse.adt.ANDROID_FRAMEWORK', 'com.android.ide.eclipse.adt.LIBRARIES'
    }

    project {
        name = appName + "-android"
        natures 'com.android.ide.eclipse.adt.AndroidNature'
        buildCommands.clear();
        buildCommand "com.android.ide.eclipse.adt.ResourceManagerBuilder"
        buildCommand "com.android.ide.eclipse.adt.PreCompilerBuilder"
        buildCommand "org.eclipse.jdt.core.javabuilder"
        buildCommand "com.android.ide.eclipse.adt.ApkBuilder"
    }
}

// sets up the Android Idea project, using the old Ant based build.
idea {
    module {
        sourceDirs += file("src");
        scopes = [ COMPILE: [plus:[project.configurations.compile]]]

        iml {
            withXml {
                def node = it.asNode()
                def builder = NodeBuilder.newInstance();
                builder.current = node;
                builder.component(name: "FacetManager") {
                    facet(type: "android", name: "Android") {
                        configuration {
                            option(name: "UPDATE_PROPERTY_FILES", value:"true")
                        }
                    }
                }
            }
        }
    }
}