问:
How can we get the objects in reverse order from list object?
in my List object(of generic type of pojo class objects) i am getting that list by calling service method, as per my requirement i have to place those object values in reverse order, for example

```<code>List<MyPojo> listData = serviceObj.getTableDate();//gets the total content of table
if(listData.size()>0){
  int i=0;
  while(i>=listData.size()){
    listData.get(i).getPojoId();
    listData.get(i).getPojoName();
  }
}
</code>```

Note: please dont tell to me use iterator or to use ListIterator, because i am showing the data in Grid(JQuery) some logic will fail while using iterator, the code what written was just sample of few lines only.

答: Would Collections.reverse(list) work?

Body:
in my List object(of generic type of pojo class objects) i am getting that list by calling service method, as per my requirement i have to place those object values in reverse order, for example

List<MyPojo> listData = serviceObj.getTableDate();//gets the total content of table
if(listData.size()>0){
  int i=0;
  while(i>=listData.size()){
    listData.get(i).getPojoId();
    listData.get(i).getPojoName();
  }
}

Note: please dont tell to me use iterator or to use ListIterator, because i am showing the data in Grid(JQuery) some logic will fail while using iterator, the code what written was just sample of few lines only.

Body: Would Collections.reverse(list) work?


来源: stackexchange

问:
How to get the key value from the AppSettings.Config file?
I'm trying to get my key value set in the appsettings.Config file but seems not working.

This is what i wrote for that. The code is called from the constructor of an MDI file and its returning only null value. Anybody know why?

```<code>     var getValue = ConfigurationSettings.AppSettings["ShowQueryTextbox"];
</code>```

I also tried with ConfigurationManager.AppSettings . That too didnt work.

My AppSettings Code is as follows.

```<code><configuration>
  <appSettings>
    <add key="ShowQueryTextbox" value="true"/>
  </appSettings>
</configuration>
</code>```

答:
I am able to get like this:</p>

```<code>System.Configuration.ConfigurationManager.AppSettings.Get("KEY").ToString();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to get my key value set in the appsettings.Config file but seems not working.

This is what i wrote for that. The code is called from the constructor of an MDI file and its returning only null value. Anybody know why?

     var getValue = ConfigurationSettings.AppSettings["ShowQueryTextbox"];

I also tried with ConfigurationManager.AppSettings . That too didnt work.

My AppSettings Code is as follows.

<configuration>
  <appSettings>
    <add key="ShowQueryTextbox" value="true"/>
  </appSettings>
</configuration>

Body:
I am able to get like this:

System.Configuration.ConfigurationManager.AppSettings.Get("KEY").ToString();


问:
Check if an object is equal to array
I would like to check if an object has a child object array

for example

```<code>{
   "parent_category_id": "ABC",
   "parent_category_name": "ABC COMPANY",
   "place_id": 733,
   "industry": {
       "@nil": "true"
   }
   "street_id": 733
}
</code>```

How would you check if the "Industry" object would have a child array.
Like if "Industry" has a child array value of "@nil: true". Then alert Has Child

答:
You can check with the instanceof operator.

For example:

```<code>var t = {
    "parent_category_id": "ABC",
    "parent_category_name": "ABC COMPANY",
    "place_id": 733,
    "industry": {
        "@nil": "true"
    },
    "street_id": 733
};
</code>```

After it, you can use:

```<code>t.industry instanceof Object // result is: true
t.industry instanceof Array  // result is: false
</code>```

Title: Check if an object is equal to array

Body:
I would like to check if an object has a child object array

for example

{
   "parent_category_id": "ABC",
   "parent_category_name": "ABC COMPANY",
   "place_id": 733,
   "industry": {
       "@nil": "true"
   }
   "street_id": 733
}

How would you check if the "Industry" object would have a child array.
Like if "Industry" has a child array value of "@nil: true". Then alert Has Child

Body:
You can check with the instanceof operator.

For example:

var t = {
    "parent_category_id": "ABC",
    "parent_category_name": "ABC COMPANY",
    "place_id": 733,
    "industry": {
        "@nil": "true"
    },
    "street_id": 733
};

After it, you can use:

t.industry instanceof Object // result is: true
t.industry instanceof Array  // result is: false


问:
PowerShell: How to source a function like source a file?
In my main script, I will first call an init function to initiate many variables which I expected to be used in the script. One way is to use variables whose name are like $script:var1 which are script level variable. But that's kind of ugly and I'd like to use normal variable name, so I need a mechanism to source a function just like source a file.

When source a file, all the variables in that file are available in the calling script.

答:
Use the same syntax that uses dot-operator, just like for sourcing files:</p>

```<code>. My-Function
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Use the same syntax that uses dot-operator, just like for sourcing files:

. My-Function


问:
How to trigger barcode scan key in android using appium?
enter image description hereI have an android device with scanning enabled. Normally we do scanning by pressing a hardware button. How can I automate this process using appium ?</p>

答:
You need to install Appium desktop, run emulator or real device, setup capabilities in appium desktop like:

```<code>platformName: 'Android',
deviceName: 'Android Emulator',
appWaitActivity: <activity to be launched on app start>,
appWaitPackage: <your app package>,
app: <path to apk>
</code>```

and start new session.

Here how inspector will look like

Search for your buttons to get unique locators (better to use resource-id) and later in test you can click it:

```<code>driver.findElement(By.id(<button resource_id>)).click()
</code>```

Body:
You need to install Appium desktop, run emulator or real device, setup capabilities in appium desktop like:

platformName: 'Android',
deviceName: 'Android Emulator',
appWaitActivity: <activity to be launched on app start>,
appWaitPackage: <your app package>,
app: <path to apk>

and start new session.

Here how inspector will look like

Search for your buttons to get unique locators (better to use resource-id) and later in test you can click it:

driver.findElement(By.id(<button resource_id>)).click()


问:
Matching text to keywords in Swift
Let's say I'm parsing a document and am trying to find Test©/Testing© Keyword Finder by taking some keywords and matching them to the aforementioned string.

If I were using a document where each block of text is separate and clearly defined so that there wouldn't be any confusion as to what words were connected in a sentence/title, is there a way in Swift to compare such a block of words with keywords to find a match?

答:
The Levenshtein distance, aka edit distance, is a metric for measuring the difference between two strings. The implementation of it is here:

```<code>func levenshteinDist(test: String, key: String) -> Int {
    let empty = Array<Int>(repeating:0, count: key.count)
    var last = [Int](0...key.count)

    for (i, testLetter) in test.enumerated() {
        var cur = [i + 1] + empty
        for (j, keyLetter) in key.enumerated() {
            cur[j + 1] = testLetter == keyLetter ? last[j] : min(last[j], last[j + 1], cur[j]) + 1
        }
        last = cur
    }
    return last.last!
}
</code>```

You can use it as follows:

```<code>let test1 = "Test©/Testing© Keyword Finder"
let test2 = "Test© Word Finder"
let test3 = "Number Categorizer"
let test4 = "Alphabet in Order"

let key = "Test Testing Keyword"

print(levenshteinDist(test: test1, key: key)) // 10
print(levenshteinDist(test: test2, key: key)) // 14
print(levenshteinDist(test: test3, key: key)) // 18
print(levenshteinDist(test: test4, key: key)) // 15
print(levenshteinDist(test: key, key: key)) // 0
</code>```

As you can see, levensthlindist(test: key, key: key) outputs 0, since the strings are same. Also, the minimum output is 10 and it corresponds to the expected test string.

Title: Matching text to keywords in Swift

Body:
The Levenshtein distance, aka edit distance, is a metric for measuring the difference between two strings. The implementation of it is here:

func levenshteinDist(test: String, key: String) -> Int {
    let empty = Array<Int>(repeating:0, count: key.count)
    var last = [Int](0...key.count)

    for (i, testLetter) in test.enumerated() {
        var cur = [i + 1] + empty
        for (j, keyLetter) in key.enumerated() {
            cur[j + 1] = testLetter == keyLetter ? last[j] : min(last[j], last[j + 1], cur[j]) + 1
        }
        last = cur
    }
    return last.last!
}

You can use it as follows:

let test1 = "Test©/Testing© Keyword Finder"
let test2 = "Test© Word Finder"
let test3 = "Number Categorizer"
let test4 = "Alphabet in Order"

let key = "Test Testing Keyword"

print(levenshteinDist(test: test1, key: key)) // 10
print(levenshteinDist(test: test2, key: key)) // 14
print(levenshteinDist(test: test3, key: key)) // 18
print(levenshteinDist(test: test4, key: key)) // 15
print(levenshteinDist(test: key, key: key)) // 0

As you can see, levensthlindist(test: key, key: key) outputs 0, since the strings are same. Also, the minimum output is 10 and it corresponds to the expected test string.


问:
(Gridbag Layout) Graphic component is clipping into another grid, not sure why
This is the intended design of my JFrame:

It looks easy enough to implement, has some buttons, textfields, lables, and a selection list.

It also has that yellow box in the upper left called a "graphic". I'm not too familiar on how to use though.

In order to make something similar to above, I wanted to use a gridbag layout.

This is what I was able to produce before running into issues:

The label red:, the textbox and the -/+ buttons are all on col 1 (gridy = 1;).

When I added my graphic on row 0 col 0 (with gridwidth = 4), I expected it to go above those elements (because 0 is less than 1). Sadly thats not what I got, and its frustrating because I dont know why its doing this.

My result:

Like I said earlier, I don't have that much experience with JFrames. I would really appreciate someone's experience and help with fixing this and an explanation on why.

Here is my source code:

(1/2):

```<code>package colorSamplerApp;

import java.awt.*;
import javax.swing.*;

public class WindowApplication extends JFrame {
    final static boolean shouldFill = true;
    final static boolean shouldWeightX = true;
    final static boolean RIGHT_TO_LEFT = false;

    protected static JLabel redLabel;
    protected static JLabel greenLabel;
    protected static JLabel blueLabel;

    protected static JTextField redTextField;
    protected static JTextField greenTextField;
    protected static JTextField blueTextField;

    protected static JButton redButtonM;
    protected static JButton greenButtonM;
    protected static JButton blueButtonM;

    protected static JButton redButtonP;
    protected static JButton greenButtonP;
    protected static JButton blueButtonP;

    protected static JButton saveButton;
    protected static JButton resetButton;

    protected static JList listColors;

    protected static DrawingTester drawTest;

    public static void addComponentsToPane(Container pane)
    {
        if (RIGHT_TO_LEFT) {
            pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        }

        pane.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        if (shouldFill) {
        //natural height, maximum width
        c.fill = GridBagConstraints.HORIZONTAL;
        }

        /**
         * Setup the RGB Labels
         *
         * R <0,1>
         * G <0,2>
         * B <0,3>
         *
         */

        c.insets = new Insets(0,10,0,5);

        c.gridwidth = 1;
        redLabel = new JLabel("Red:");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 1;
        pane.add(redLabel, c);

        greenLabel = new JLabel("Green:");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 2;
        pane.add(greenLabel, c);

        blueLabel = new JLabel("Blue:");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 3;
        pane.add(blueLabel, c);

        /**
         * Setup the RGB Text Fields
         *
         * R<1,1>
         * G<1,2>
         * B<1,3>
         *
         */

        c.insets.set(0, 0, 0, 5);

        redTextField = new JTextField("255");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 1;
        c.gridy = 1;
        pane.add(redTextField, c);

        greenTextField = new JTextField("0");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 1;
        c.gridy = 2;
        pane.add(greenTextField, c);

        blueTextField = new JTextField("0");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 1;
        c.gridy = 3;
        pane.add(blueTextField, c);

        /**
         * Setup the RGB (-) Button Fields
         *
         * R<2,1>
         * G<2,2>
         * B<2,3>
         *
         */

        c.insets.set(5,5,0,10);

        redButtonM = new JButton("-");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 2;
        c.gridy = 1;
        pane.add(redButtonM, c);

        greenButtonM = new JButton("-");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 2;
        c.gridy = 2;
        pane.add(greenButtonM, c);

        blueButtonM = new JButton("-");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 2;
        c.gridy = 3;
        pane.add(blueButtonM, c);

        /**
         * Setup the RGB (+) Button Fields
         *
         * R<3,1>
         * G<3,2>
         * B<3,3>
         *
         */

        c.insets.set(5,0,0,10);

        redButtonP = new JButton("+");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 3;
        c.gridy = 1;
        pane.add(redButtonP, c);

        greenButtonP = new JButton("+");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 3;
        c.gridy = 2;
        pane.add(greenButtonP, c);

        blueButtonP = new JButton("+");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 3;
        c.gridy = 3;
        pane.add(blueButtonP, c);

        /**
         * Setup the Save/Reset Buttons
         *
         * save <0,4>
         * reset<1,4>
         *
         */

        c.insets.set(10,10,10,5);

        saveButton = new JButton("Save");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 10;      //make this component tall
        c.ipadx = 10;
        //c.weightx = 0.0;
        c.gridwidth = 2;
        c.gridx = 0;
        c.gridy = 4;
        pane.add(saveButton, c);

        c.insets.set(10,5,10,10);

        resetButton = new JButton("Reset");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 10;
        c.ipadx = 10;
        //c.weighty = 1.0;   //request any extra vertical space
        //c.anchor = GridBagConstraints.PAGE_END; //bottom of space
        c.gridx = 2;       //aligned with button 2
        c.gridwidth = 2;   //2 columns wide
        c.gridy = 4;       //third row
        pane.add(resetButton, c);

        /**
         * Setup the Color Selection List
         *
         * <4,0>
         *
         */

        c.insets.set(10,0,10,10);

        listColors = new JList();
        /**
            File reading shenanigans to fill up the list
        */
        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 150;
        c.ipadx = 100;
        //c.weighty = 1.0;   //request any extra vertical space
        //c.anchor = GridBagConstraints.PAGE_END; //bottom of space
        c.gridx = 4;       //aligned with button 2
        c.gridheight = 5;   //2 columns wide
        c.gridy = 1;       //third row
        pane.add(listColors, c);

        /**
         * Setup the Graphics
         *
         * <0,0>
         *
         */

        drawTest = new DrawingTester();
        c.insets.set(0,0,0,0);
        c.gridx = 0;       //top leftw
        c.gridy = 0;       //bottom
        c.gridwidth = 0 ;
        pane.add(drawTest,c);
    }

    public static void main (String argv[])
    {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI("Color Sampler");
            }
        });
    }

    public static void createAndShowGUI(String title)
    {
        // Create and setup the window
        JFrame frame = new JFrame (title);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Setup the content pane
        addComponentsToPane(frame.getContentPane());

        // Display the window
        frame.pack();
        frame.setVisible(true);

    }

}
</code>```

(2/2)

```<code>package colorSamplerApp;

import java.awt.*;
import javax.swing.*;

import javax.swing.JComponent;

public class DrawingTester extends JComponent {

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.setColor(Color.red);
        g.fillRect(0,0, 170, 70);
    }
}
</code>```

答:
The problem you're facing is related to reusing the same GridBagConstraints object. Pretty common one and is one of the pains of dealing with this layout.

First of all, I've commented out all the calls that changed the insets.

Then, I've made sure that the gridx and gridy were being set correctly. Also, think of gridheight and gridwidth as the number of cells in the grid your component is going to take, don't think in terms of the actual width and height of the internal component that you're placing in the cell.

In DrawingTester, I've also made sure that we were painting the whole thing.

Check out the code and the result:

```<code>import java.awt.*;
import javax.swing.*;

public class WindowApplication extends JFrame {
    final static boolean shouldFill = true;
    final static boolean shouldWeightX = true;
    final static boolean RIGHT_TO_LEFT = false;

    protected static JLabel redLabel;
    protected static JLabel greenLabel;
    protected static JLabel blueLabel;

    protected static JTextField redTextField;
    protected static JTextField greenTextField;
    protected static JTextField blueTextField;

    protected static JButton redButtonM;
    protected static JButton greenButtonM;
    protected static JButton blueButtonM;

    protected static JButton redButtonP;
    protected static JButton greenButtonP;
    protected static JButton blueButtonP;

    protected static JButton saveButton;
    protected static JButton resetButton;

    protected static JList listColors;

    protected static DrawingTester drawTest;

    public static void addComponentsToPane(Container pane)
    {
        if (RIGHT_TO_LEFT) {
            pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        }

        pane.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        if (shouldFill) {
        //natural height, maximum width
        c.fill = GridBagConstraints.HORIZONTAL;
        }

        /**
         * Setup the RGB Labels
         *
         * R <0,1>
         * G <0,2>
         * B <0,3>
         *
         */

//        c.insets = new Insets(0,10,0,5);

        c.gridwidth = 1;
        redLabel = new JLabel("Red:");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 1;
        pane.add(redLabel, c);

        greenLabel = new JLabel("Green:");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 2;
        pane.add(greenLabel, c);

        blueLabel = new JLabel("Blue:");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 3;
        pane.add(blueLabel, c);

        /**
         * Setup the RGB Text Fields
         *
         * R<1,1>
         * G<1,2>
         * B<1,3>
         *
         */

//        c.insets.set(0, 0, 0, 5);

        redTextField = new JTextField("255");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 1;
        c.gridy = 1;
        pane.add(redTextField, c);

        greenTextField = new JTextField("0");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 1;
        c.gridy = 2;
        pane.add(greenTextField, c);

        blueTextField = new JTextField("0");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 1;
        c.gridy = 3;
        pane.add(blueTextField, c);

        /**
         * Setup the RGB (-) Button Fields
         *
         * R<2,1>
         * G<2,2>
         * B<2,3>
         *
         */

//        c.insets.set(5,5,0,10);

        redButtonM = new JButton("-");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 2;
        c.gridy = 1;
        pane.add(redButtonM, c);

        greenButtonM = new JButton("-");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 2;
        c.gridy = 2;
        pane.add(greenButtonM, c);

        blueButtonM = new JButton("-");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 2;
        c.gridy = 3;
        pane.add(blueButtonM, c);

        /**
         * Setup the RGB (+) Button Fields
         *
         * R<3,1>
         * G<3,2>
         * B<3,3>
         *
         */

//        c.insets.set(5,0,0,10);

        redButtonP = new JButton("+");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 3;
        c.gridy = 1;
        pane.add(redButtonP, c);

        greenButtonP = new JButton("+");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 3;
        c.gridy = 2;
        pane.add(greenButtonP, c);

        blueButtonP = new JButton("+");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 3;
        c.gridy = 3;
        pane.add(blueButtonP, c);

        /**
         * Setup the Save/Reset Buttons
         *
         * save <0,4>
         * reset<1,4>
         *
         */

        saveButton = new JButton("Save");
        c.insets.set(10,10,10,5);
        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 10;      //make this component tall
        c.ipadx = 10;
        //c.weightx = 0.0;
        c.gridwidth = 2;
        c.gridx = 0;
        c.gridy = 4;
        pane.add(saveButton, c);

        resetButton = new JButton("Reset");
        c.insets.set(10,5,10,10);
        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 10;
        c.ipadx = 10;
        //c.weighty = 1.0;   //request any extra vertical space
        //c.anchor = GridBagConstraints.PAGE_END; //bottom of space
        c.gridx = 2;       //aligned with button 2
        c.gridwidth = 2;   //2 columns wide
        c.gridy = 4;       //third row
        pane.add(resetButton, c);

        /**
         * Setup the Color Selection List
         *
         * <4,0>
         *
         */

        c.insets.set(5,5,5,5);

        listColors = new JList(new Object[] {"Test 1", "Test 2", "Test 3"});
        /**
            File reading shenanigans to fill up the list
        */
        c.fill = GridBagConstraints.BOTH;
        c.gridy = 0;
        c.gridx = 4;
        c.gridheight = 5;
        c.gridwidth = 1;

        pane.add(listColors, c);

        /**
         * Setup the Graphics
         *
         * <0,0>
         *
         */

        drawTest = new DrawingTester();
        c.insets = new Insets(5,5,5,5);
        c.fill = GridBagConstraints.BOTH;
        c.gridx = 0;       //top leftw
        c.gridy = 0;       //bottom
        c.gridheight = 1;
        c.gridwidth = 4;
        pane.add(drawTest,c);
    }

    public static void main (String argv[])
    {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI("Color Sampler");
            }
        });
    }

    public static void createAndShowGUI(String title)
    {
        // Create and setup the window
        JFrame frame = new JFrame (title);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Setup the content pane
        addComponentsToPane(frame.getContentPane());

        // Display the window
        frame.pack();
        frame.setVisible(true);

    }

}

class DrawingTester extends JComponent {

  public void paintComponent(Graphics g){
      super.paintComponent(g);
      g.setColor(Color.red);
      g.fillRect(0,0, g.getClipBounds().width, g.getClipBounds().height);
  }
}
</code>```

Check out the result:

From that point on you should be able to continue altering it to suit your needs, like getting back all the insets and changing the height and width of the components. Keep in mind that you're reusing the GridBagConstraints, so you have to be careful. If you're unsure, just instantiate a new one and test your code.

Body:
This is the intended design of my JFrame:

It looks easy enough to implement, has some buttons, textfields, lables, and a selection list.

It also has that yellow box in the upper left called a "graphic". I'm not too familiar on how to use though.

In order to make something similar to above, I wanted to use a gridbag layout.

This is what I was able to produce before running into issues:

The label red:, the textbox and the -/+ buttons are all on col 1 (gridy = 1;).

When I added my graphic on row 0 col 0 (with gridwidth = 4), I expected it to go above those elements (because 0 is less than 1). Sadly thats not what I got, and its frustrating because I dont know why its doing this.

My result:

Like I said earlier, I don't have that much experience with JFrames. I would really appreciate someone's experience and help with fixing this and an explanation on why.

Here is my source code:

(1/2):

package colorSamplerApp;

import java.awt.*;
import javax.swing.*;

public class WindowApplication extends JFrame {
    final static boolean shouldFill = true;
    final static boolean shouldWeightX = true;
    final static boolean RIGHT_TO_LEFT = false;

    protected static JLabel redLabel;
    protected static JLabel greenLabel;
    protected static JLabel blueLabel;

    protected static JTextField redTextField;
    protected static JTextField greenTextField;
    protected static JTextField blueTextField;

    protected static JButton redButtonM;
    protected static JButton greenButtonM;
    protected static JButton blueButtonM;

    protected static JButton redButtonP;
    protected static JButton greenButtonP;
    protected static JButton blueButtonP;

    protected static JButton saveButton;
    protected static JButton resetButton;

    protected static JList listColors;

    protected static DrawingTester drawTest;

    public static void addComponentsToPane(Container pane)
    {
        if (RIGHT_TO_LEFT) {
            pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        }

        pane.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        if (shouldFill) {
        //natural height, maximum width
        c.fill = GridBagConstraints.HORIZONTAL;
        }

        /**
         * Setup the RGB Labels
         *
         * R <0,1>
         * G <0,2>
         * B <0,3>
         *
         */

        c.insets = new Insets(0,10,0,5);

        c.gridwidth = 1;
        redLabel = new JLabel("Red:");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 1;
        pane.add(redLabel, c);

        greenLabel = new JLabel("Green:");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 2;
        pane.add(greenLabel, c);

        blueLabel = new JLabel("Blue:");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 3;
        pane.add(blueLabel, c);

        /**
         * Setup the RGB Text Fields
         *
         * R<1,1>
         * G<1,2>
         * B<1,3>
         *
         */

        c.insets.set(0, 0, 0, 5);

        redTextField = new JTextField("255");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 1;
        c.gridy = 1;
        pane.add(redTextField, c);

        greenTextField = new JTextField("0");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 1;
        c.gridy = 2;
        pane.add(greenTextField, c);

        blueTextField = new JTextField("0");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 1;
        c.gridy = 3;
        pane.add(blueTextField, c);

        /**
         * Setup the RGB (-) Button Fields
         *
         * R<2,1>
         * G<2,2>
         * B<2,3>
         *
         */

        c.insets.set(5,5,0,10);

        redButtonM = new JButton("-");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 2;
        c.gridy = 1;
        pane.add(redButtonM, c);

        greenButtonM = new JButton("-");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 2;
        c.gridy = 2;
        pane.add(greenButtonM, c);

        blueButtonM = new JButton("-");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 2;
        c.gridy = 3;
        pane.add(blueButtonM, c);

        /**
         * Setup the RGB (+) Button Fields
         *
         * R<3,1>
         * G<3,2>
         * B<3,3>
         *
         */

        c.insets.set(5,0,0,10);

        redButtonP = new JButton("+");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 3;
        c.gridy = 1;
        pane.add(redButtonP, c);

        greenButtonP = new JButton("+");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 3;
        c.gridy = 2;
        pane.add(greenButtonP, c);

        blueButtonP = new JButton("+");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 3;
        c.gridy = 3;
        pane.add(blueButtonP, c);

        /**
         * Setup the Save/Reset Buttons
         *
         * save <0,4>
         * reset<1,4>
         *
         */

        c.insets.set(10,10,10,5);

        saveButton = new JButton("Save");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 10;      //make this component tall
        c.ipadx = 10;
        //c.weightx = 0.0;
        c.gridwidth = 2;
        c.gridx = 0;
        c.gridy = 4;
        pane.add(saveButton, c);

        c.insets.set(10,5,10,10);

        resetButton = new JButton("Reset");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 10;
        c.ipadx = 10;
        //c.weighty = 1.0;   //request any extra vertical space
        //c.anchor = GridBagConstraints.PAGE_END; //bottom of space
        c.gridx = 2;       //aligned with button 2
        c.gridwidth = 2;   //2 columns wide
        c.gridy = 4;       //third row
        pane.add(resetButton, c);

        /**
         * Setup the Color Selection List
         *
         * <4,0>
         *
         */

        c.insets.set(10,0,10,10);

        listColors = new JList();
        /**
            File reading shenanigans to fill up the list
        */
        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 150;
        c.ipadx = 100;
        //c.weighty = 1.0;   //request any extra vertical space
        //c.anchor = GridBagConstraints.PAGE_END; //bottom of space
        c.gridx = 4;       //aligned with button 2
        c.gridheight = 5;   //2 columns wide
        c.gridy = 1;       //third row
        pane.add(listColors, c);

        /**
         * Setup the Graphics
         *
         * <0,0>
         *
         */

        drawTest = new DrawingTester();
        c.insets.set(0,0,0,0);
        c.gridx = 0;       //top leftw
        c.gridy = 0;       //bottom
        c.gridwidth = 0 ;
        pane.add(drawTest,c);
    }

    public static void main (String argv[])
    {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI("Color Sampler");
            }
        });
    }

    public static void createAndShowGUI(String title)
    {
        // Create and setup the window
        JFrame frame = new JFrame (title);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Setup the content pane
        addComponentsToPane(frame.getContentPane());

        // Display the window
        frame.pack();
        frame.setVisible(true);

    }

}

(2/2)

package colorSamplerApp;

import java.awt.*;
import javax.swing.*;

import javax.swing.JComponent;

public class DrawingTester extends JComponent {

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.setColor(Color.red);
        g.fillRect(0,0, 170, 70);
    }
}

Body:
The problem you're facing is related to reusing the same GridBagConstraints object. Pretty common one and is one of the pains of dealing with this layout.

First of all, I've commented out all the calls that changed the insets.

Then, I've made sure that the gridx and gridy were being set correctly. Also, think of gridheight and gridwidth as the number of cells in the grid your component is going to take, don't think in terms of the actual width and height of the internal component that you're placing in the cell.

In DrawingTester, I've also made sure that we were painting the whole thing.

Check out the code and the result:

import java.awt.*;
import javax.swing.*;

public class WindowApplication extends JFrame {
    final static boolean shouldFill = true;
    final static boolean shouldWeightX = true;
    final static boolean RIGHT_TO_LEFT = false;

    protected static JLabel redLabel;
    protected static JLabel greenLabel;
    protected static JLabel blueLabel;

    protected static JTextField redTextField;
    protected static JTextField greenTextField;
    protected static JTextField blueTextField;

    protected static JButton redButtonM;
    protected static JButton greenButtonM;
    protected static JButton blueButtonM;

    protected static JButton redButtonP;
    protected static JButton greenButtonP;
    protected static JButton blueButtonP;

    protected static JButton saveButton;
    protected static JButton resetButton;

    protected static JList listColors;

    protected static DrawingTester drawTest;

    public static void addComponentsToPane(Container pane)
    {
        if (RIGHT_TO_LEFT) {
            pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        }

        pane.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        if (shouldFill) {
        //natural height, maximum width
        c.fill = GridBagConstraints.HORIZONTAL;
        }

        /**
         * Setup the RGB Labels
         *
         * R <0,1>
         * G <0,2>
         * B <0,3>
         *
         */

//        c.insets = new Insets(0,10,0,5);

        c.gridwidth = 1;
        redLabel = new JLabel("Red:");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 1;
        pane.add(redLabel, c);

        greenLabel = new JLabel("Green:");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 2;
        pane.add(greenLabel, c);

        blueLabel = new JLabel("Blue:");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 3;
        pane.add(blueLabel, c);

        /**
         * Setup the RGB Text Fields
         *
         * R<1,1>
         * G<1,2>
         * B<1,3>
         *
         */

//        c.insets.set(0, 0, 0, 5);

        redTextField = new JTextField("255");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 1;
        c.gridy = 1;
        pane.add(redTextField, c);

        greenTextField = new JTextField("0");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 1;
        c.gridy = 2;
        pane.add(greenTextField, c);

        blueTextField = new JTextField("0");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 1;
        c.gridy = 3;
        pane.add(blueTextField, c);

        /**
         * Setup the RGB (-) Button Fields
         *
         * R<2,1>
         * G<2,2>
         * B<2,3>
         *
         */

//        c.insets.set(5,5,0,10);

        redButtonM = new JButton("-");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 2;
        c.gridy = 1;
        pane.add(redButtonM, c);

        greenButtonM = new JButton("-");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 2;
        c.gridy = 2;
        pane.add(greenButtonM, c);

        blueButtonM = new JButton("-");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 2;
        c.gridy = 3;
        pane.add(blueButtonM, c);

        /**
         * Setup the RGB (+) Button Fields
         *
         * R<3,1>
         * G<3,2>
         * B<3,3>
         *
         */

//        c.insets.set(5,0,0,10);

        redButtonP = new JButton("+");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 3;
        c.gridy = 1;
        pane.add(redButtonP, c);

        greenButtonP = new JButton("+");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 3;
        c.gridy = 2;
        pane.add(greenButtonP, c);

        blueButtonP = new JButton("+");
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 3;
        c.gridy = 3;
        pane.add(blueButtonP, c);

        /**
         * Setup the Save/Reset Buttons
         *
         * save <0,4>
         * reset<1,4>
         *
         */

        saveButton = new JButton("Save");
        c.insets.set(10,10,10,5);
        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 10;      //make this component tall
        c.ipadx = 10;
        //c.weightx = 0.0;
        c.gridwidth = 2;
        c.gridx = 0;
        c.gridy = 4;
        pane.add(saveButton, c);

        resetButton = new JButton("Reset");
        c.insets.set(10,5,10,10);
        c.fill = GridBagConstraints.HORIZONTAL;
        c.ipady = 10;
        c.ipadx = 10;
        //c.weighty = 1.0;   //request any extra vertical space
        //c.anchor = GridBagConstraints.PAGE_END; //bottom of space
        c.gridx = 2;       //aligned with button 2
        c.gridwidth = 2;   //2 columns wide
        c.gridy = 4;       //third row
        pane.add(resetButton, c);

        /**
         * Setup the Color Selection List
         *
         * <4,0>
         *
         */

        c.insets.set(5,5,5,5);

        listColors = new JList(new Object[] {"Test 1", "Test 2", "Test 3"});
        /**
            File reading shenanigans to fill up the list
        */
        c.fill = GridBagConstraints.BOTH;
        c.gridy = 0;
        c.gridx = 4;
        c.gridheight = 5;
        c.gridwidth = 1;

        pane.add(listColors, c);

        /**
         * Setup the Graphics
         *
         * <0,0>
         *
         */

        drawTest = new DrawingTester();
        c.insets = new Insets(5,5,5,5);
        c.fill = GridBagConstraints.BOTH;
        c.gridx = 0;       //top leftw
        c.gridy = 0;       //bottom
        c.gridheight = 1;
        c.gridwidth = 4;
        pane.add(drawTest,c);
    }

    public static void main (String argv[])
    {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI("Color Sampler");
            }
        });
    }

    public static void createAndShowGUI(String title)
    {
        // Create and setup the window
        JFrame frame = new JFrame (title);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Setup the content pane
        addComponentsToPane(frame.getContentPane());

        // Display the window
        frame.pack();
        frame.setVisible(true);

    }

}

class DrawingTester extends JComponent {

  public void paintComponent(Graphics g){
      super.paintComponent(g);
      g.setColor(Color.red);
      g.fillRect(0,0, g.getClipBounds().width, g.getClipBounds().height);
  }
}

Check out the result:

From that point on you should be able to continue altering it to suit your needs, like getting back all the insets and changing the height and width of the components. Keep in mind that you're reusing the GridBagConstraints, so you have to be careful. If you're unsure, just instantiate a new one and test your code.


问:
'xx' is not a registered namespace in django
there is a question about django url reversing...
'appA' and 'appB' are two apps in django,and both have been registered in root
'urls.py':

```<code>include(r'appA/',include('mysite.appA',namespace='appA')),
</code>```

but in most of my templates,{% url appA:app_view_one %} would work, and in few pages,it doesn't work for {% url appA:app_view_two %}

i don't think it is because of app_view_two being wrong ,it works in other template.
and it may not because the django url syntax {% load url from future %} ,I've tried but still not work...

could someone help me or ever see similar question?

thanks!

答:
Check urls.py in your Project's root directory.

Take notice of what before string 'url',"tab" or "space".

Consider using any one of them.

Body:
there is a question about django url reversing...
'appA' and 'appB' are two apps in django,and both have been registered in root
'urls.py':

include(r'appA/',include('mysite.appA',namespace='appA')),

but in most of my templates,{% url appA:app_view_one %} would work, and in few pages,it doesn't work for {% url appA:app_view_two %}

i don't think it is because of app_view_two being wrong ,it works in other template.
and it may not because the django url syntax {% load url from future %} ,I've tried but still not work...

could someone help me or ever see similar question?

thanks!


问:
How to pass a string from C to swift?
I am using OpenSSL as a library in swift. Since it's in C, I need to pass some data from C language back to swift. The data was an array, but after some research I have learned that I cannot pass an array from C to swift. One way I can think of it is to change the array into a string, an then pass the string back to swift.
In C I wrote:

```<code>char teststring()
{
    char c[]={"H","E","L","L","O"};
    printf(c);
    return c;
}
</code>```

In Swift I wrote:

```<code>teststring()
</code>```

The result is that it only prints H.
What did I do wrong with it? It there a easier way to pass an array from C back to Swift?

答:
there's a couple things...

First, it'd be a lot easier to format your string this way:

```<code>char* c="HELLO";
</code>```

But, if you want to do it your way still, you need to null-terminate your string, otherwise the computer will not know where the string ends and new memory begins:

```<code>char c[]={"H","E","L","L","O"};
</code>```

becomes:

```<code>char c[]={'H','E','L','L','O',0};
</code>```

See the single quotes vs the double quotes?  The double quotes indicate a whole string (null terminated with zero)... the single quotes indicate a single char.

So when you did it with double quotes, in characters in memory for the whole thing looked something like this:

H0E0L0L0O0

With single quotes, the characters in memory looks like this:

HELLO0

The printf function will print until it hits a zero and then quit.  That's why you were getting just the 'H' printing out.

Title: How to pass a string from C to swift?

Body:
I am using OpenSSL as a library in swift. Since it's in C, I need to pass some data from C language back to swift. The data was an array, but after some research I have learned that I cannot pass an array from C to swift. One way I can think of it is to change the array into a string, an then pass the string back to swift.
In C I wrote:

char teststring()
{
    char c[]={"H","E","L","L","O"};
    printf(c);
    return c;
}

In Swift I wrote:

teststring()

The result is that it only prints H.
What did I do wrong with it? It there a easier way to pass an array from C back to Swift?

Body:
there's a couple things...

First, it'd be a lot easier to format your string this way:

char* c="HELLO";

But, if you want to do it your way still, you need to null-terminate your string, otherwise the computer will not know where the string ends and new memory begins:

char c[]={"H","E","L","L","O"};

becomes:

char c[]={'H','E','L','L','O',0};

See the single quotes vs the double quotes?  The double quotes indicate a whole string (null terminated with zero)... the single quotes indicate a single char.

So when you did it with double quotes, in characters in memory for the whole thing looked something like this:

H0E0L0L0O0

With single quotes, the characters in memory looks like this:

HELLO0

The printf function will print until it hits a zero and then quit.  That's why you were getting just the 'H' printing out.


问:
Asp.Net WebApi 2: Add role claim to WindowsIdentity
I want to add a role claim to an already authenticated windows user. My naive first approach was to add the role claim inside of a custom owin middleware which runs before WebApi. Like this:

```<code>public class IdentityMiddleware : OwinMiddleware
{
    public IdentityMiddleware(OwinMiddleware next) : base(next)
    {
    }

    public async override Task Invoke(IOwinContext context)
    {
        var user = context.Request.User as WindowsPrincipal;
        var identity = user.Identity as ClaimsIdentity;
        identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));

        await Next.Invoke(context);
    }
}
</code>```

However when providing the Authorize attribute in the controller like this.

```<code>public class TestController : ApiController
{
    [Authorize(Roles = "Admin")]
    public string Get()
    {
        return User.Identity.Name;
    }
}
</code>```

..I will get a 401.

I noticed that the issuer of the new claim is "Local Authority" instead of "AD Authority" could this be the reason?

答:
This works for me:</p>

```<code>var сlaimsIdentity = user.Identity as ClaimsIdentity;
сlaimsIdentity?.AddClaim(new Claim(сlaimsIdentity.RoleClaimType, "Admin"));
if (user.IsInRole("Admin")) ... // always true
</code>```

Body:
I want to add a role claim to an already authenticated windows user. My naive first approach was to add the role claim inside of a custom owin middleware which runs before WebApi. Like this:

public class IdentityMiddleware : OwinMiddleware
{
    public IdentityMiddleware(OwinMiddleware next) : base(next)
    {
    }

    public async override Task Invoke(IOwinContext context)
    {
        var user = context.Request.User as WindowsPrincipal;
        var identity = user.Identity as ClaimsIdentity;
        identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));

        await Next.Invoke(context);
    }
}

However when providing the Authorize attribute in the controller like this.

public class TestController : ApiController
{
    [Authorize(Roles = "Admin")]
    public string Get()
    {
        return User.Identity.Name;
    }
}

..I will get a 401.

I noticed that the issuer of the new claim is "Local Authority" instead of "AD Authority" could this be the reason?

Body:
This works for me:

var сlaimsIdentity = user.Identity as ClaimsIdentity;
сlaimsIdentity?.AddClaim(new Claim(сlaimsIdentity.RoleClaimType, "Admin"));
if (user.IsInRole("Admin")) ... // always true


问:
How can I rewrite a code for php server to a code for Apache?
Is it possible that a code written for php server could be rewritten for apache server? Is it even a legal question in the first place? I have very little experience on server-side technologies.
THanks</p>

答:
You are comparing apples and oranges.

Apache is an HTTP server (well, a generic TCP/IP server with a strong focus on HTTP).
PHP is a programming language.

Software written in PHP can run on a variety of servers, so long as they support PHP. Apache can run software written in PHP via mod_php, mod_cgi, and a few other modules.

Apache can run software written in other programming languages.


问:
Having trouble finding the start of a sentence inside string array
I have a text file from which I read the text in lines. Also from all that text I need to find the longest sentence and find in which line it begins. I have no trouble finding the longest sentence but the problem arises when I need to find where it begins.

The contents of the text file is:

V. M. Putinas

  Margi sakalai

  Lydėdami gęstančią žarą vėlai

  Pakilo į dangų;;, margi sakalai.

  Paniekinę žemės vylingus sapnus,

  Padangėje ištiesė,,; savo sparnus.

  Ir tarė margieji: negrįšim į žemę,

  Kol josios kalnai ir pakalnės aptemę.

My code:

```<code>static void Sakiniai (string fv, string skyrikliai)
{
    char[] skyrikliaiSak = { '.', '!', '?' };
    string naujas = "";
    string[] lines = File.ReadAllLines(fv, Encoding.GetEncoding(1257));

    foreach (string line in lines)
    {
        // Add lines into a string so I can separate them into sentences
        naujas += line;
    }

    // Separating into sentences
    string[] sakiniai = naujas.Split(skyrikliaiSak);

    // This method finds the longest sentence
    string ilgiausiasSak = RastiIlgiausiaSakini(sakiniai);
}
</code>```

From the text file the longest sentence is: "Margi sakalai Lydėdami gęstančią žarą vėlai Pakilo į dangų;;, margi sakalai"

How can I find the exact line where the sentence begins?

答:
How about

identify the lines in the text

split the text into sentences

split the sentences into sections based on the line breaks (could work also with splitting on words as well if needed)

verify the sections of the sentence are on consecutive rows

In the end certain sections of the sentence might occur on multiple lines forming other sentences so you need to correctly identify the sentences spreading consecutive rows

```<code>// define separators for various contexts
var separator = new
{
    Lines = new[] { '\n' },
    Sentences = new[] { '.', '!', '?' },
    Sections = new[] { '\n' },
};

// isolate the lines and their corresponding number
var lines = paragraph
    .Split(separator.Lines, StringSplitOptions.RemoveEmptyEntries)
    .Select((text, number) => new
    {
        Number = number += 1,
        Text = text,
    })
    .ToList();
</code>```

```<code>// isolate the sentences with corresponding sections and line numbers
var sentences = paragraph
    .Split(separator.Sentences, StringSplitOptions.RemoveEmptyEntries)
    .Select(sentence => sentence.Trim())
    .Select(sentence => new
    {
        Text = sentence,
        Length = sentence.Length,
        Sections = sentence
               .Split(separator.Sections)
               .Select((section, index) => new
               {
                   Index = index,
                   Text = section,
                   Lines = lines
                        .Where(line => line.Text.Contains(section))
                        .Select(line => line.Number)
               })
               .OrderBy(section => section.Index)
    })
    .OrderByDescending(p => p.Length)
    .ToList();
</code>```

```<code>// build the possible combinations of sections within a sentence
// and filter only those that are on consecutive lines
var results = from sentence in sentences
            let occurences = sentence.Sections
                .Select(p => p.Lines)
                .Cartesian()
                .Where(p => p.Consecutive())
                .SelectMany(p => p)
            select new
            {
                Text = sentence.Text,
                Length = sentence.Length,
                Lines = occurences,
            };
</code>```

and the end results would look like this

where .Cartesian and .Consecutive are just some helper extension methods over enumerable (see associated gist for the entire source code in linqpad ready format)

```<code>public static IEnumerable<T> Yield<T>(this T instance)
{
    yield return instance;
}

public static IEnumerable<IEnumerable<T>> Cartesian<T>(this IEnumerable<IEnumerable<T>> instance)
{
    var seed = Enumerable.Empty<T>().Yield();

    return instance.Aggregate(seed, (accumulator, sequence) =>
    {
        var results = from vector in accumulator
                      from item in sequence
                      select vector.Concat(new[]
                      {
                          item
                      });

        return results;
    });
}

public static bool Consecutive(this IEnumerable<int> instance)
{
    var distinct = instance.Distinct().ToList();
    return distinct
        .Zip(distinct.Skip(1), (a, b) => a + 1 == b)
        .All(p => p);
}
</code>```

Body:
I have a text file from which I read the text in lines. Also from all that text I need to find the longest sentence and find in which line it begins. I have no trouble finding the longest sentence but the problem arises when I need to find where it begins.

The contents of the text file is:

V. M. Putinas

  Margi sakalai

  Lydėdami gęstančią žarą vėlai

  Pakilo į dangų;;, margi sakalai.

  Paniekinę žemės vylingus sapnus,

  Padangėje ištiesė,,; savo sparnus.

  Ir tarė margieji: negrįšim į žemę,

  Kol josios kalnai ir pakalnės aptemę.

My code:

static void Sakiniai (string fv, string skyrikliai)
{
    char[] skyrikliaiSak = { '.', '!', '?' };
    string naujas = "";
    string[] lines = File.ReadAllLines(fv, Encoding.GetEncoding(1257));

    foreach (string line in lines)
    {
        // Add lines into a string so I can separate them into sentences
        naujas += line;
    }

    // Separating into sentences
    string[] sakiniai = naujas.Split(skyrikliaiSak);

    // This method finds the longest sentence
    string ilgiausiasSak = RastiIlgiausiaSakini(sakiniai);
}

From the text file the longest sentence is: "Margi sakalai Lydėdami gęstančią žarą vėlai Pakilo į dangų;;, margi sakalai"

How can I find the exact line where the sentence begins?

Body:
How about

identify the lines in the text

split the text into sentences

split the sentences into sections based on the line breaks (could work also with splitting on words as well if needed)

verify the sections of the sentence are on consecutive rows

In the end certain sections of the sentence might occur on multiple lines forming other sentences so you need to correctly identify the sentences spreading consecutive rows

// define separators for various contexts
var separator = new
{
    Lines = new[] { '\n' },
    Sentences = new[] { '.', '!', '?' },
    Sections = new[] { '\n' },
};

// isolate the lines and their corresponding number
var lines = paragraph
    .Split(separator.Lines, StringSplitOptions.RemoveEmptyEntries)
    .Select((text, number) => new
    {
        Number = number += 1,
        Text = text,
    })
    .ToList();

// isolate the sentences with corresponding sections and line numbers
var sentences = paragraph
    .Split(separator.Sentences, StringSplitOptions.RemoveEmptyEntries)
    .Select(sentence => sentence.Trim())
    .Select(sentence => new
    {
        Text = sentence,
        Length = sentence.Length,
        Sections = sentence
               .Split(separator.Sections)
               .Select((section, index) => new
               {
                   Index = index,
                   Text = section,
                   Lines = lines
                        .Where(line => line.Text.Contains(section))
                        .Select(line => line.Number)
               })
               .OrderBy(section => section.Index)
    })
    .OrderByDescending(p => p.Length)
    .ToList();

// build the possible combinations of sections within a sentence
// and filter only those that are on consecutive lines
var results = from sentence in sentences
            let occurences = sentence.Sections
                .Select(p => p.Lines)
                .Cartesian()
                .Where(p => p.Consecutive())
                .SelectMany(p => p)
            select new
            {
                Text = sentence.Text,
                Length = sentence.Length,
                Lines = occurences,
            };

and the end results would look like this

where .Cartesian and .Consecutive are just some helper extension methods over enumerable (see associated gist for the entire source code in linqpad ready format)

public static IEnumerable<T> Yield<T>(this T instance)
{
    yield return instance;
}

public static IEnumerable<IEnumerable<T>> Cartesian<T>(this IEnumerable<IEnumerable<T>> instance)
{
    var seed = Enumerable.Empty<T>().Yield();

    return instance.Aggregate(seed, (accumulator, sequence) =>
    {
        var results = from vector in accumulator
                      from item in sequence
                      select vector.Concat(new[]
                      {
                          item
                      });

        return results;
    });
}

public static bool Consecutive(this IEnumerable<int> instance)
{
    var distinct = instance.Distinct().ToList();
    return distinct
        .Zip(distinct.Skip(1), (a, b) => a + 1 == b)
        .All(p => p);
}


问:
How are instance variables of a Class implemented in Crystal?
If I have an instance of A, are the instance variables implemented as pointers? In other words, are instance variables accessed by reference, even when using Structs?

```<code>class A
  @title = "the title"
  @my_val = MyStruct.new
end
</code>```

答:
@my_val is a reference to the instance of MyStruct on the stack. Checkout this example and notice the difference:

```<code>struct MyStruct
  property x

  def initialize(@x : Int32)
  end
end

class A
  getter my_val = MyStruct.new(10)
end

# mutates a struct (passed by reference)
def method(a : A)
  a.my_val.x = 20
end

# does not mutate a struct (passed by value)
def method(s : MyStruct)
  s.x = 30
end

a = A.new
p a.my_val.x       #=> 10

a.method(a)
p a.my_val.x       #=> 20

a.method(a.my_val)
p a.my_val.x       #=> 20 (not 30)
</code>```

Body:
If I have an instance of A, are the instance variables implemented as pointers? In other words, are instance variables accessed by reference, even when using Structs?

class A
  @title = "the title"
  @my_val = MyStruct.new
end

Body:
@my_val is a reference to the instance of MyStruct on the stack. Checkout this example and notice the difference:

struct MyStruct
  property x

  def initialize(@x : Int32)
  end
end

class A
  getter my_val = MyStruct.new(10)
end

# mutates a struct (passed by reference)
def method(a : A)
  a.my_val.x = 20
end

# does not mutate a struct (passed by value)
def method(s : MyStruct)
  s.x = 30
end

a = A.new
p a.my_val.x       #=> 10

a.method(a)
p a.my_val.x       #=> 20

a.method(a.my_val)
p a.my_val.x       #=> 20 (not 30)


答:
Yes you have to declare array of chars.

So the it will be

Case-1

```<code>char c[]={'H','E','L','L','O','\0');
</code>```

Here you have created something like array of array of chars. Coorect way of doing it would be.

Case-2

```<code>char c[][2]={"H","E","L","L","O"};
</code>```

But in this case you have to pass c[0] or c[1] in printf.

Also note that the first thing can alternatively done using

Case-3

```<code>   char c[]="HELLO";
</code>```

This is an array of 6 characters, \0 included.

And once again you could have also done

Case-4

```<code>   char *c[]={"H","E","L","L","O"};
</code>```

Here you have to pass the c[0] or c[1] which will print the string "H" or "E".

Also note that

```<code>char c[]={'H','E','L','L','O'};
</code>```

is a valid initialization but this is not null terminated. So you can't pass it where a null terminated char array is expected. (like strlen() etc).

Now the case-2, here the strings are modifiable. So you can change the character in them where as the strings in case-4 are not. Those are string literals which are non-modifiable.

Simply put if you wanted to have a string which contains those as
characters then Case-1 and case-3 are the way for you.

Title: How to pass a string from C to swift?

Body:
Yes you have to declare array of chars.

So the it will be

Case-1

char c[]={'H','E','L','L','O','\0');

Here you have created something like array of array of chars. Coorect way of doing it would be.

Case-2

char c[][2]={"H","E","L","L","O"};

But in this case you have to pass c[0] or c[1] in printf.

Also note that the first thing can alternatively done using

Case-3

   char c[]="HELLO";

This is an array of 6 characters, \0 included.

And once again you could have also done

Case-4

   char *c[]={"H","E","L","L","O"};

Here you have to pass the c[0] or c[1] which will print the string "H" or "E".

Also note that

char c[]={'H','E','L','L','O'};

is a valid initialization but this is not null terminated. So you can't pass it where a null terminated char array is expected. (like strlen() etc).

Now the case-2, here the strings are modifiable. So you can change the character in them where as the strings in case-4 are not. Those are string literals which are non-modifiable.

Simply put if you wanted to have a string which contains those as
characters then Case-1 and case-3 are the way for you.


问:
Hardcode arguments to the PowerShell Script in VSTS Release definition
I have PowerShell scripts to deploy csv files into Azure tables storage.Now,I want to configure these scripts in VSTS at the release definition after the WebApp deployment is done.So once the web app deploy is done,I will execute these scripts using VSTS PowerShell task.So I have 6 environments ,My PowerShell script will have to be deployed into different azure storage accounts(Environments).So I need to pass the storage account name,storage account key,resource group separately for different environments but my PowerShell script will be the same.So I can pass these arguments using argument field of PowerShell task in VSTS.But I don't want to pass using that field option.So,Is there any best way to pass those arguments at the release definition of VSTS. Please help me on this.</p>

答:
The simple way is using environment variable:

Add variables with the same name (different value) for each environment, such as storageAccountName

Using environment variables in PowerShell task, Arguments - storageAccountName $(storageAccountName)


问:
How to fix Warning: map service token not specified
I'm working on an app in Xamarin that uses a map.
The map seems to work fine because it does show my location, but it keeps showing me "warning map service token not specified" underneath the map.

The Api key type is basic/UWP and it's enabled.
I put the Api key in MainPage.xaml.cs

```<code>public MainPage()
    {
        Xamarin.FormsMaps.Init("myApiKey");
        this.InitializeComponent();
        LoadApplication(new BarApp.App());
    }
</code>```

And I also checked "Location" in Package.appxmanifest

I get no other errors, and everything else seems to work fine, so i'm really confused what the problem could be :/

Thanks in advance! (:

-Jeroen

Explanation I used: https://developer.xamarin.com/guides/xamarin-forms/user-interface/map/

答:
The map seems to work fine because it does show my location, but it keeps showing me "warning map service token not specified"

The native MapControl is BingMap in UWP platform. According to Request a maps authentication key, Your Universal Windows app must be authenticated before it can use the MapControl and map services in the Windows.Services.Maps namespace. The authentication key in Xamarin official  code sample was expired. You could request a new maps authentication key from the Bing Maps Developer Center and add it to your app.

Body:
I'm working on an app in Xamarin that uses a map.
The map seems to work fine because it does show my location, but it keeps showing me "warning map service token not specified" underneath the map.

The Api key type is basic/UWP and it's enabled.
I put the Api key in MainPage.xaml.cs

public MainPage()
    {
        Xamarin.FormsMaps.Init("myApiKey");
        this.InitializeComponent();
        LoadApplication(new BarApp.App());
    }

And I also checked "Location" in Package.appxmanifest

I get no other errors, and everything else seems to work fine, so i'm really confused what the problem could be :/

Thanks in advance! (:

-Jeroen

Explanation I used: https://developer.xamarin.com/guides/xamarin-forms/user-interface/map/


问:
R: Using function arguments to update elements in a data frame
I want the elements referenced in my data frame to be replaced with the argument I put into the function, however at the moment it is just replacing the elements with the argument I used to initially define the function (I'm finding it hard to explain - hopefully my code and pictures will clarify this a bit!)

```<code>Project_assign <- function(prjct) {
  Truth_vector <- is.element((giraffe[,1]),(prjct[,1]))
  giraffe[which(Truth_vector),5] <- 'prjct'
  assign('giraffe' , giraffe , envir= .GlobalEnv)
}
Project_assign(spine_hlfs)
</code>```

This mostly works however the elements get replaced with prjct instead of spine_hlfs
 https://i.stack.imgur.com/uuPnv.png

If I can get this to work as intended, then I will next create a vector with all the project names and use lapply with this function saving me a lot of manual work every few months. I am relatively new to R so any explanations are well appreciated.

答:
As far as I have understood OP's intentions from the many comments, he wants to update the giraffe data frame with the name of many other data frames where runkey matches.

This can be achieved by combining the other data frames into one data.table object treating the data frame names as data and finally updating giraffe in a join.

Sample Data

According to the OP, giraffe consists of 500 rows and 5 columns including runkey and project. project is initialized here as character column for the subsequent join with the data frame names.

```<code>set.seed(123L) # required for reproducible data
giraffe <- data.frame(runkey = 1:500,
                      X2 = sample.int(99L, 500L, TRUE),
                      X3 = sample.int(99L, 500L, TRUE),
                      X4 = sample.int(99L, 500L, TRUE),
                      project = "",
                      stringsAsFactors = FALSE)
</code>```

Then there are a number of data frames which contain only one column runkey. According to the OP, runkey is disjunct, i.e., the combined set of all runkey does not contain any duplicates.

```<code>spine_hlfs <- data.frame(runkey = c(1L, 498L, 5L))
ir_dia     <- data.frame(runkey = c(3L, 499L, 47L, 327L))
</code>```

Proposed solution

```<code># specify names of data frames
df_names <- c("spine_hlfs", "ir_dia")
# create named list of data frames
df_list <- mget(df_names)
# update on join
library(data.table)
setDT(giraffe)[rbindlist(df_list, idcol = "df.name"), on = "runkey", project := df.name][]
</code>```

```<code>     runkey X2 X3 X4    project
  1:      1  2 44 63 spine_hlfs
  2:      2 73 99 77
  3:      3 43 20 18     ir_dia
  4:      4 73 12 40
  5:      5  2 25 96 spine_hlfs
 ---
496:    496 75 45 84
497:    497 24 63 43
498:    498 33 53 81 spine_hlfs
499:    499  1 33 16     ir_dia
500:    500 99 77 41
</code>```

Explanation

setDT() coerces giraffe to data.table.  rbindlist(df_list, idcol = "df.name") creates a combined data.table from the list of data frames, thereby filling the df.name column with the names of the list elements:

```<code>      df.name runkey
1: spine_hlfs      1
2: spine_hlfs    498
3: spine_hlfs      5
4:     ir_dia      3
5:     ir_dia    499
6:     ir_dia     47
7:     ir_dia    327
</code>```

This intermediate result is joined on runkey with giraffe. The project column is updated with the contents of df.name only for matching rows.

Alternative solution

This is looping over df_names and performs repeated joins which update giraffe in place:

```<code>setDT(giraffe)
for (x in df_names) giraffe[get(x), on = "runkey", project := x]
giraffe[]
</code>```

Body:
I want the elements referenced in my data frame to be replaced with the argument I put into the function, however at the moment it is just replacing the elements with the argument I used to initially define the function (I'm finding it hard to explain - hopefully my code and pictures will clarify this a bit!)

Project_assign <- function(prjct) {
  Truth_vector <- is.element((giraffe[,1]),(prjct[,1]))
  giraffe[which(Truth_vector),5] <- 'prjct'
  assign('giraffe' , giraffe , envir= .GlobalEnv)
}
Project_assign(spine_hlfs)

This mostly works however the elements get replaced with prjct instead of spine_hlfs
 https://i.stack.imgur.com/uuPnv.png

If I can get this to work as intended, then I will next create a vector with all the project names and use lapply with this function saving me a lot of manual work every few months. I am relatively new to R so any explanations are well appreciated.

Body:
As far as I have understood OP's intentions from the many comments, he wants to update the giraffe data frame with the name of many other data frames where runkey matches.

This can be achieved by combining the other data frames into one data.table object treating the data frame names as data and finally updating giraffe in a join.

Sample Data

According to the OP, giraffe consists of 500 rows and 5 columns including runkey and project. project is initialized here as character column for the subsequent join with the data frame names.

set.seed(123L) # required for reproducible data
giraffe <- data.frame(runkey = 1:500,
                      X2 = sample.int(99L, 500L, TRUE),
                      X3 = sample.int(99L, 500L, TRUE),
                      X4 = sample.int(99L, 500L, TRUE),
                      project = "",
                      stringsAsFactors = FALSE)

Then there are a number of data frames which contain only one column runkey. According to the OP, runkey is disjunct, i.e., the combined set of all runkey does not contain any duplicates.

spine_hlfs <- data.frame(runkey = c(1L, 498L, 5L))
ir_dia     <- data.frame(runkey = c(3L, 499L, 47L, 327L))

Proposed solution

# specify names of data frames
df_names <- c("spine_hlfs", "ir_dia")
# create named list of data frames
df_list <- mget(df_names)
# update on join
library(data.table)
setDT(giraffe)[rbindlist(df_list, idcol = "df.name"), on = "runkey", project := df.name][]

     runkey X2 X3 X4    project
  1:      1  2 44 63 spine_hlfs
  2:      2 73 99 77
  3:      3 43 20 18     ir_dia
  4:      4 73 12 40
  5:      5  2 25 96 spine_hlfs
 ---
496:    496 75 45 84
497:    497 24 63 43
498:    498 33 53 81 spine_hlfs
499:    499  1 33 16     ir_dia
500:    500 99 77 41

Explanation

setDT() coerces giraffe to data.table.  rbindlist(df_list, idcol = "df.name") creates a combined data.table from the list of data frames, thereby filling the df.name column with the names of the list elements:

      df.name runkey
1: spine_hlfs      1
2: spine_hlfs    498
3: spine_hlfs      5
4:     ir_dia      3
5:     ir_dia    499
6:     ir_dia     47
7:     ir_dia    327

This intermediate result is joined on runkey with giraffe. The project column is updated with the contents of df.name only for matching rows.

Alternative solution

This is looping over df_names and performs repeated joins which update giraffe in place:

setDT(giraffe)
for (x in df_names) giraffe[get(x), on = "runkey", project := x]
giraffe[]


问:
convert tensorflow .pb to .dlc fail with snpe
I save the graph to a .pb file. I get an error when I convert the .pb to .dlc. Anyone know why?

My code to build the model:

```<code>import tensorflow as tf
from tensorflow.python.framework.graph_util import convert_variables_to_constants
from tensorflow.python.ops import variable_scope

X = tf.placeholder(tf.float32, shape=[None, 1], name="input");

with variable_scope.variable_scope("input"):
    a = tf.Variable([[1]], name="a", dtype=tf.float32);
    g = X * a

with variable_scope.variable_scope("output"):
    b = tf.Variable([[0]], name="b", dtype=tf.float32);
    ss = tf.add(g, b, name="output")

sess = tf.Session();
sess.run(tf.global_variables_initializer());

graph = convert_variables_to_constants(sess, sess.graph_def, ["output/output"])
tf.train.write_graph(graph, './linear/', 'graph.pb', as_text=False)

sess.close();
</code>```

convert cmd:

```<code>snpe-tensorflow-to-dlc --graph graph_sc.pb -i input 1 --out_node output/output --allow_unconsumed_nodes
</code>```

error message:

2017-10-26 01:55:15,919 - 390 - INFO - INFO_ALL_BUILDING_LAYER_W_NODES: Building layer (ElementWiseMul) with nodes: [u'input_1/mul']

~/snpe-sdk/snpe-1.6.0/lib/python/converters/tensorflow/layers/eltwise.py:108: RuntimeWarning: error_code=1002; error_message=Layer paramter value is invalid. Layer input_1/mul: at least two inputs required, have 1; error_component=Model Validation; line_no=732; thread_id=140514161018688
  output_name)

2017-10-26 01:55:15,920 - 390 - INFO - INFO_ALL_BUILDING_LAYER_W_NODES: Building layer (ElementWiseSum) with nodes: [u'output/output']

~/snpe-sdk/snpe-1.6.0/lib/python/converters/tensorflow/layers/eltwise.py:84: RuntimeWarning: error_code=1002; error_message=Layer paramter value is invalid. Layer output/output: at least two inputs required, have 1; error_component=Model Validation; line_no=732; thread_id=140514161018688
  output_name)
```

答: SNPE requires a 3D tensor as input. Try to update your command -i input 1 to -i input 1,1,1

ContentLicense: CC BY-SA 4.0

Body:
I save the graph to a .pb file. I get an error when I convert the .pb to .dlc. Anyone know why?

My code to build the model:

import tensorflow as tf
from tensorflow.python.framework.graph_util import convert_variables_to_constants
from tensorflow.python.ops import variable_scope

X = tf.placeholder(tf.float32, shape=[None, 1], name="input");

with variable_scope.variable_scope("input"):
    a = tf.Variable([[1]], name="a", dtype=tf.float32);
    g = X * a

with variable_scope.variable_scope("output"):
    b = tf.Variable([[0]], name="b", dtype=tf.float32);
    ss = tf.add(g, b, name="output")

sess = tf.Session();
sess.run(tf.global_variables_initializer());

graph = convert_variables_to_constants(sess, sess.graph_def, ["output/output"])
tf.train.write_graph(graph, './linear/', 'graph.pb', as_text=False)

sess.close();

convert cmd:

snpe-tensorflow-to-dlc --graph graph_sc.pb -i input 1 --out_node output/output --allow_unconsumed_nodes

error message:

2017-10-26 01:55:15,919 - 390 - INFO - INFO_ALL_BUILDING_LAYER_W_NODES: Building layer (ElementWiseMul) with nodes: [u'input_1/mul']

~/snpe-sdk/snpe-1.6.0/lib/python/converters/tensorflow/layers/eltwise.py:108: RuntimeWarning: error_code=1002; error_message=Layer paramter value is invalid. Layer input_1/mul: at least two inputs required, have 1; error_component=Model Validation; line_no=732; thread_id=140514161018688
  output_name)

2017-10-26 01:55:15,920 - 390 - INFO - INFO_ALL_BUILDING_LAYER_W_NODES: Building layer (ElementWiseSum) with nodes: [u'output/output']

~/snpe-sdk/snpe-1.6.0/lib/python/converters/tensorflow/layers/eltwise.py:84: RuntimeWarning: error_code=1002; error_message=Layer paramter value is invalid. Layer output/output: at least two inputs required, have 1; error_component=Model Validation; line_no=732; thread_id=140514161018688
  output_name)


问:
Deserializing complex JSON
I am trying to deserialize this JSON:

```<code>{
  "request": {
    "Target": "Affiliate",
    "Format": "json",
    "Service": "HasOffers",
    "Version": "2",
    "NetworkToken": "NETVTxpCN4QxoWuE6D6SCdh67itLvG",
    "Method": "getSignupAnswers",
    "id": "9820",
    "__lc_visitor_id_1040387": "S1501672650.ef9130f70a",
    "optimizelyEndUserId": "oeu1504526823197r0.9821082007049919",
    "optimizelySegments": "{\"3005961667\":\"campaign\",\"3007971800\":\"gc\",\"3016921538\":\"false\"}",
    "optimizelyBuckets": "{\"8910731217\":\"8900223657\"}",
    "_mkto_trk": "id:210-BFY-977&token:_mch-hasoffers.com-1504526823819-68924",
    "__gaTune": "GA1.2.1953499689.1501744456",
    "_hp2_id_1318563364": "{\"userId\":null,\"pageviewId\":\"5080006815314464\",\"sessionId\":\"3328773167767995\",\"identity\":\"23255-2\",\"trackerVersion\":\"3.0\"}",
    "intercom-session-zrjutp6m": "QXAxQTdza0JnNmVPLzNxZDFXSmFjbUQxRnVxQjArcmNmQWxMZzM4NWpSbWt3VXNzemFydG5oVjZYempaUlg3bS0tR0VrYWcwTGpSY3I4cDdsMFB3TndlUT09--5c9d563a96f41049f2703a3121484e9a299b4148",
    "intercom-lou-zrjutp6m": "1"
  },
  "response": {
    "status": 1,
    "httpStatus": 200,
    "data": {
      "140768": {
        "SignupAnswer": {
          "id": "140768",
          "question_id": "1",
          "responder_type": "affiliate",
          "answer": "Individual \r\n",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Affiliate Type",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140770": {
        "SignupAnswer": {
          "id": "140770",
          "question_id": "3",
          "responder_type": "affiliate",
          "answer": "Rugved Agro",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Organisation Name",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140772": {
        "SignupAnswer": {
          "id": "140772",
          "question_id": "5",
          "responder_type": "affiliate",
          "answer": "9822288117",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Contact Number ",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140774": {
        "SignupAnswer": {
          "id": "140774",
          "question_id": "7",
          "responder_type": "affiliate",
          "answer": "7972274145",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Secondary Contact Number",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140776": {
        "SignupAnswer": {
          "id": "140776",
          "question_id": "9",
          "responder_type": "affiliate",
          "answer": "",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Secondary E-mail Adress",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140778": {
        "SignupAnswer": {
          "id": "140778",
          "question_id": "11",
          "responder_type": "affiliate",
          "answer": "SACHIN RAMLAL AGALE",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Payee Name",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140780": {
        "SignupAnswer": {
          "id": "140780",
          "question_id": "13",
          "responder_type": "affiliate",
          "answer": "Electronic Fund Transfer \r\n",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Payment Mode",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140782": {
        "SignupAnswer": {
          "id": "140782",
          "question_id": "15",
          "responder_type": "affiliate",
          "answer": "0480104000105996",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Bank Account Number",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140784": {
        "SignupAnswer": {
          "id": "140784",
          "question_id": "17",
          "responder_type": "affiliate",
          "answer": "IDBI BANK ",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Bank Name",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140786": {
        "SignupAnswer": {
          "id": "140786",
          "question_id": "19",
          "responder_type": "affiliate",
          "answer": "IBKL0000480",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "IFSC Code",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140788": {
        "SignupAnswer": {
          "id": "140788",
          "question_id": "21",
          "responder_type": "affiliate",
          "answer": "431259006",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "MICR Code",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140790": {
        "SignupAnswer": {
          "id": "140790",
          "question_id": "23",
          "responder_type": "affiliate",
          "answer": "Aurangabad ",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Bank City",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140792": {
        "SignupAnswer": {
          "id": "140792",
          "question_id": "25",
          "responder_type": "affiliate",
          "answer": "",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "UPLOAD DOCUMENTS\u00a0(If required For Receiving Payments)",
          "type": "affiliate",
          "status": "deleted"
        }
      },
      "140794": {
        "SignupAnswer": {
          "id": "140794",
          "question_id": "27",
          "responder_type": "affiliate",
          "answer": "rugvedagro.blogspot.in",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:24",
          "question": "Website URL",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140796": {
        "SignupAnswer": {
          "id": "140796",
          "question_id": "29",
          "responder_type": "affiliate",
          "answer": "Blog\r\n",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:24",
          "question": "Website Type",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140798": {
        "SignupAnswer": {
          "id": "140798",
          "question_id": "31",
          "responder_type": "affiliate",
          "answer": "Btw 1000-10000\r\n",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:24",
          "question": "Monthly Visits",
          "type": "affiliate",
          "status": "active"
        }
      }
    },
    "errors": [

    ],
    "errorMessage": null
  }
}
</code>```

The classes I have are as follows:

```<code>public class Request
{
    public string Target { get; set; }
    public string Format { get; set; }
    public string Service { get; set; }
    public string Version { get; set; }
    public string NetworkToken { get; set; }
    public string Method { get; set; }
    public string id { get; set; }
    public string __lc_visitor_id_1040387 { get; set; }
    public string optimizelyEndUserId { get; set; }
    public string optimizelySegments { get; set; }
    public string optimizelyBuckets { get; set; }
    public string _mkto_trk { get; set; }
    public string __gaTune { get; set; }
    public string _hp2_id_1318563364 { get; set; }
    [JsonProperty(PropertyName = "intercom-session-zrjutp6m")]
    public string __invalid_name__intercom_session_zrjutp6m { get; set; }
    [JsonProperty(PropertyName = "intercom-lou-zrjutp6m")]
    public string __invalid_name__intercom_lou_zrjutp6m { get; set; }
}
public class SignupAnswer
{
    public string id { get; set; }
    public string question_id { get; set; }
    public string responder_type { get; set; }
    public string answer { get; set; }
    public object responder_user_id { get; set; }
    public object ref_id { get; set; }
    public string responder_id { get; set; }
    public string modified { get; set; }
    public string question { get; set; }
    public string type { get; set; }
    public string status { get; set; }
}

public class Data
{
    /* I can't code this class */

}

public class Response
{
    public int status { get; set; }
    public int httpStatus { get; set; }
    public Data data { get; set; } //I can't code this class
    public List<object> errors { get; set; }
    public object errorMessage { get; set; }
}

public class RootObject
{
    public Request request { get; set; }
    public Response response { get; set; }
}
</code>```

I have already tried it json2csharp. The problem here is the data under node response -> data is dynamic. So I cannot have a fixed class name

答:
The Data Property of the Response Class should be a Dictionary:

```<code>public class Response
{
    public int status { get; set; }
    public int httpStatus { get; set; }
    public Dictionary<string,Data> data { get; set; }
    public object[] errors { get; set; }
    public object errorMessage { get; set; }
}
</code>```

probably you need another wrapper around signupanswer like this:

```<code>public class Data
{
    public Signupanswer Signupanswer { get;set; }
}
</code>```

Title: Deserializing complex JSON

Body:
I am trying to deserialize this JSON:

{
  "request": {
    "Target": "Affiliate",
    "Format": "json",
    "Service": "HasOffers",
    "Version": "2",
    "NetworkToken": "NETVTxpCN4QxoWuE6D6SCdh67itLvG",
    "Method": "getSignupAnswers",
    "id": "9820",
    "__lc_visitor_id_1040387": "S1501672650.ef9130f70a",
    "optimizelyEndUserId": "oeu1504526823197r0.9821082007049919",
    "optimizelySegments": "{\"3005961667\":\"campaign\",\"3007971800\":\"gc\",\"3016921538\":\"false\"}",
    "optimizelyBuckets": "{\"8910731217\":\"8900223657\"}",
    "_mkto_trk": "id:210-BFY-977&token:_mch-hasoffers.com-1504526823819-68924",
    "__gaTune": "GA1.2.1953499689.1501744456",
    "_hp2_id_1318563364": "{\"userId\":null,\"pageviewId\":\"5080006815314464\",\"sessionId\":\"3328773167767995\",\"identity\":\"23255-2\",\"trackerVersion\":\"3.0\"}",
    "intercom-session-zrjutp6m": "QXAxQTdza0JnNmVPLzNxZDFXSmFjbUQxRnVxQjArcmNmQWxMZzM4NWpSbWt3VXNzemFydG5oVjZYempaUlg3bS0tR0VrYWcwTGpSY3I4cDdsMFB3TndlUT09--5c9d563a96f41049f2703a3121484e9a299b4148",
    "intercom-lou-zrjutp6m": "1"
  },
  "response": {
    "status": 1,
    "httpStatus": 200,
    "data": {
      "140768": {
        "SignupAnswer": {
          "id": "140768",
          "question_id": "1",
          "responder_type": "affiliate",
          "answer": "Individual \r\n",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Affiliate Type",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140770": {
        "SignupAnswer": {
          "id": "140770",
          "question_id": "3",
          "responder_type": "affiliate",
          "answer": "Rugved Agro",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Organisation Name",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140772": {
        "SignupAnswer": {
          "id": "140772",
          "question_id": "5",
          "responder_type": "affiliate",
          "answer": "9822288117",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Contact Number ",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140774": {
        "SignupAnswer": {
          "id": "140774",
          "question_id": "7",
          "responder_type": "affiliate",
          "answer": "7972274145",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Secondary Contact Number",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140776": {
        "SignupAnswer": {
          "id": "140776",
          "question_id": "9",
          "responder_type": "affiliate",
          "answer": "",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Secondary E-mail Adress",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140778": {
        "SignupAnswer": {
          "id": "140778",
          "question_id": "11",
          "responder_type": "affiliate",
          "answer": "SACHIN RAMLAL AGALE",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Payee Name",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140780": {
        "SignupAnswer": {
          "id": "140780",
          "question_id": "13",
          "responder_type": "affiliate",
          "answer": "Electronic Fund Transfer \r\n",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Payment Mode",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140782": {
        "SignupAnswer": {
          "id": "140782",
          "question_id": "15",
          "responder_type": "affiliate",
          "answer": "0480104000105996",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Bank Account Number",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140784": {
        "SignupAnswer": {
          "id": "140784",
          "question_id": "17",
          "responder_type": "affiliate",
          "answer": "IDBI BANK ",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Bank Name",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140786": {
        "SignupAnswer": {
          "id": "140786",
          "question_id": "19",
          "responder_type": "affiliate",
          "answer": "IBKL0000480",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "IFSC Code",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140788": {
        "SignupAnswer": {
          "id": "140788",
          "question_id": "21",
          "responder_type": "affiliate",
          "answer": "431259006",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "MICR Code",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140790": {
        "SignupAnswer": {
          "id": "140790",
          "question_id": "23",
          "responder_type": "affiliate",
          "answer": "Aurangabad ",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "Bank City",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140792": {
        "SignupAnswer": {
          "id": "140792",
          "question_id": "25",
          "responder_type": "affiliate",
          "answer": "",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:23",
          "question": "UPLOAD DOCUMENTS\u00a0(If required For Receiving Payments)",
          "type": "affiliate",
          "status": "deleted"
        }
      },
      "140794": {
        "SignupAnswer": {
          "id": "140794",
          "question_id": "27",
          "responder_type": "affiliate",
          "answer": "rugvedagro.blogspot.in",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:24",
          "question": "Website URL",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140796": {
        "SignupAnswer": {
          "id": "140796",
          "question_id": "29",
          "responder_type": "affiliate",
          "answer": "Blog\r\n",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:24",
          "question": "Website Type",
          "type": "affiliate",
          "status": "active"
        }
      },
      "140798": {
        "SignupAnswer": {
          "id": "140798",
          "question_id": "31",
          "responder_type": "affiliate",
          "answer": "Btw 1000-10000\r\n",
          "responder_user_id": null,
          "ref_id": null,
          "responder_id": "9820",
          "modified": "2017-07-04 02:55:24",
          "question": "Monthly Visits",
          "type": "affiliate",
          "status": "active"
        }
      }
    },
    "errors": [

    ],
    "errorMessage": null
  }
}

The classes I have are as follows:

public class Request
{
    public string Target { get; set; }
    public string Format { get; set; }
    public string Service { get; set; }
    public string Version { get; set; }
    public string NetworkToken { get; set; }
    public string Method { get; set; }
    public string id { get; set; }
    public string __lc_visitor_id_1040387 { get; set; }
    public string optimizelyEndUserId { get; set; }
    public string optimizelySegments { get; set; }
    public string optimizelyBuckets { get; set; }
    public string _mkto_trk { get; set; }
    public string __gaTune { get; set; }
    public string _hp2_id_1318563364 { get; set; }
    [JsonProperty(PropertyName = "intercom-session-zrjutp6m")]
    public string __invalid_name__intercom_session_zrjutp6m { get; set; }
    [JsonProperty(PropertyName = "intercom-lou-zrjutp6m")]
    public string __invalid_name__intercom_lou_zrjutp6m { get; set; }
}
public class SignupAnswer
{
    public string id { get; set; }
    public string question_id { get; set; }
    public string responder_type { get; set; }
    public string answer { get; set; }
    public object responder_user_id { get; set; }
    public object ref_id { get; set; }
    public string responder_id { get; set; }
    public string modified { get; set; }
    public string question { get; set; }
    public string type { get; set; }
    public string status { get; set; }
}

public class Data
{
    /* I can't code this class */

}

public class Response
{
    public int status { get; set; }
    public int httpStatus { get; set; }
    public Data data { get; set; } //I can't code this class
    public List<object> errors { get; set; }
    public object errorMessage { get; set; }
}

public class RootObject
{
    public Request request { get; set; }
    public Response response { get; set; }
}

I have already tried it json2csharp. The problem here is the data under node response -> data is dynamic. So I cannot have a fixed class name

Body:
The Data Property of the Response Class should be a Dictionary:

public class Response
{
    public int status { get; set; }
    public int httpStatus { get; set; }
    public Dictionary<string,Data> data { get; set; }
    public object[] errors { get; set; }
    public object errorMessage { get; set; }
}

probably you need another wrapper around signupanswer like this:

public class Data
{
    public Signupanswer Signupanswer { get;set; }
}