问:
C# client-Java Server data reading is slow?
Yesterday I tried to create an Android app and a windows app.

Android app - Sends couple of char[] to the windows app using WIFI.

Windows app - C# server app, listens for clients data

However both programs works well, but the data reads from the server is kinda very slow.

I'm sending a data like this 00000000. I have an gamepad connected to my phone via otg, and when I pressed Button A data becomes like this 10000000. I even tried putting a textview in my android app, it works without any delay and when I press a button I can see the changed data set in my textview.

So I assumed the problem is between the server and the client. Is it impossible to solve this, as they are 2 different platforms? I have tried this kind of thing with Xamarin, it worked well. but I don't want to use Xamarin at this point for some specific reasons.

Let's say I press buttons A,B,C,D so the data is like this 11110000, I clearly can see it in the android apps TextView, of course I will see this data in my server program, but only after a big delay, about 10-30 seconds.

My phone is Nexus 5. Is it a consequence of using 2 different platforms?

Server Code:

```<code>private void startBtn_Click(object sender, EventArgs e)
        {
            Thread thread = new Thread(new ThreadStart(StartServer));
            thread.Start();
        }

        void StartServer()
        {
            Log("Running");
            TcpClient client = new TcpClient();
            TcpListener server = new TcpListener(IPAddress.Any, 8888);
            server.Start();
            client = server.AcceptTcpClient();
            Log("Client connected");

            byte[] byteArray = new byte[8];
            NetworkStream inOpt = client.GetStream();
            while (true)
            {
                inOpt.Read(byteArray, 0, 8);
                Log(ASCIIEncoding.);
            }
        }

        void Log(string msg)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(Log), new object[] {msg});
                return;
            }
            logBox.Text = "";
            logBox.Text += msg + Environment.NewLine;
        }
</code>```

Android Client Code:

```<code>char[] keys = {'0', '0', '0', '0', '0', '0', '0', '0'};
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ArrayList gameControllerDeviceIds = new ArrayList();
        int[] deviceIds = InputDevice.getDeviceIds();
        for (int deviceId : deviceIds) {
            InputDevice dev = InputDevice.getDevice(deviceId);

            int sources = dev.getSources();

            // Verify that the device has gamepad buttons, control sticks, or both.
            if (((sources & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD)
                    || ((sources & InputDevice.SOURCE_JOYSTICK)
                    == InputDevice.SOURCE_JOYSTICK)) {
                // This device is a game controller. Store its device ID.
                if (!gameControllerDeviceIds.contains(deviceId)) {
                    gameControllerDeviceIds.add(deviceId);
                    Log.d("yolol", String.valueOf(deviceId));

                }
            }
        }

        //Log.d("yolol", InputDevice.getDevice(7).getName());
        new CheckUsageStartup().execute();
        Log.d("sss", Arrays.toString(keys));

        textView = (TextView) findViewById(R.id.textView);
    }

    byte[] toByteArray(String[] strong){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);
        for(int i = 0; i < strong.length; i++)
        {
            try{
                dos.writeUTF(strong[i]);
            }
            catch (IOException e){

            }
        }

        return baos.toByteArray();
    }

    class CheckUsageStartup extends AsyncTask<Void, Integer, String> {
        String TAG = getClass().getSimpleName();

        protected void onPreExecute() {
            Log.d(TAG + " PreExceute", "On pre Exceute......");

        }

        protected String doInBackground(Void... arg0) {
            Log.d(TAG + " DoINBackGround", "On doInBackground...");

            try {
                Socket socket = new Socket("192.168.1.8", 8888);
                OutputStream out = socket.getOutputStream();
                Writer writer = new OutputStreamWriter(out, "UTF-8");

                while(true){
                    writer.write(keys, 0, 8);
                    writer.flush();
                }

            } catch (IOException e) {
                System.out.println(e.getMessage());
                return "Instant";
            }
        }

        protected void onProgressUpdate(Integer... a) {
            Log.d(TAG + " onProgressUpdate", "You are in progress update ... " + a[0]);
        }

        protected void onPostExecute(String result) {
            Log.d(TAG + " onPostExecute", "" + result);

        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        int deviceId = event.getDeviceId();
        if (deviceId != -1) {
            switch(keyCode){
                case KeyEvent.KEYCODE_BUTTON_1:
                    keys[0] = '1';
                    Log.d("u", "po");
                    break;
                case KeyEvent.KEYCODE_BUTTON_2:
                    keys[1] = '1';
                    break;
                case KeyEvent.KEYCODE_BUTTON_3:
                    keys[2] = '1';
                    break;
                case KeyEvent.KEYCODE_BUTTON_4:
                    keys[3] = '1';
                    break;

                case KeyEvent.KEYCODE_DPAD_UP:
                    keys[4] = '1';
                    break;
                case KeyEvent.KEYCODE_DPAD_DOWN:
                    keys[5] = '1';
                    break;
                case KeyEvent.KEYCODE_DPAD_LEFT:
                    keys[6] = '1';
                    break;
                case KeyEvent.KEYCODE_DPAD_RIGHT:
                    keys[7] = '1';
                    break;
            }
            textView.setText(Arrays.toString(keys));
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        int deviceId = event.getDeviceId();
        if (deviceId != -1) {
            switch(keyCode){
                case KeyEvent.KEYCODE_BUTTON_1:
                    keys[0] = '0';
                    break;
                case KeyEvent.KEYCODE_BUTTON_2:
                    keys[1] = '0';
                    break;
                case KeyEvent.KEYCODE_BUTTON_3:
                    keys[2] = '0';
                    break;
                case KeyEvent.KEYCODE_BUTTON_4:
                    keys[3] = '0';
                    break;

                case KeyEvent.KEYCODE_DPAD_UP:
                    keys[4] = '0';
                    break;
                case KeyEvent.KEYCODE_DPAD_DOWN:
                    keys[5] = '0';
                    break;
                case KeyEvent.KEYCODE_DPAD_LEFT:
                    keys[6] = '0';
                    break;
                case KeyEvent.KEYCODE_DPAD_RIGHT:
                    keys[7] = '0';
                    break;
            }
            textView.setText(Arrays.toString(keys));
            return true;
        }

        return super.onKeyUp(keyCode, event);
    }
</code>```

Here's the code. Please tell me possible solutions. Is it encoding do this much delay, perhaps?

答:
I figured it out.

This is code that was updating the textbox from earlier,

```<code>void Log(string msg)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(Log), new object[] {msg});
                return;
            }
            logBox.Text = "";
            logBox.Text += msg + Environment.NewLine;
        }
</code>```

I don't know what causes the problem, but after updating the textbox from the below code, it works well now.

```<code>Invoke((MethodInvoker)delegate {
                    logBox.Text = ASCIIEncoding.UTF8.GetString(byteArray, 0, 8);
                });
</code>```

It seems using the first method gives some unwanted delay.

Body:
Yesterday I tried to create an Android app and a windows app.

Android app - Sends couple of char[] to the windows app using WIFI.

Windows app - C# server app, listens for clients data

However both programs works well, but the data reads from the server is kinda very slow.

I'm sending a data like this 00000000. I have an gamepad connected to my phone via otg, and when I pressed Button A data becomes like this 10000000. I even tried putting a textview in my android app, it works without any delay and when I press a button I can see the changed data set in my textview.

So I assumed the problem is between the server and the client. Is it impossible to solve this, as they are 2 different platforms? I have tried this kind of thing with Xamarin, it worked well. but I don't want to use Xamarin at this point for some specific reasons.

Let's say I press buttons A,B,C,D so the data is like this 11110000, I clearly can see it in the android apps TextView, of course I will see this data in my server program, but only after a big delay, about 10-30 seconds.

My phone is Nexus 5. Is it a consequence of using 2 different platforms?

Server Code:

private void startBtn_Click(object sender, EventArgs e)
        {
            Thread thread = new Thread(new ThreadStart(StartServer));
            thread.Start();
        }

        void StartServer()
        {
            Log("Running");
            TcpClient client = new TcpClient();
            TcpListener server = new TcpListener(IPAddress.Any, 8888);
            server.Start();
            client = server.AcceptTcpClient();
            Log("Client connected");

            byte[] byteArray = new byte[8];
            NetworkStream inOpt = client.GetStream();
            while (true)
            {
                inOpt.Read(byteArray, 0, 8);
                Log(ASCIIEncoding.);
            }
        }

        void Log(string msg)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(Log), new object[] {msg});
                return;
            }
            logBox.Text = "";
            logBox.Text += msg + Environment.NewLine;
        }

Android Client Code:

char[] keys = {'0', '0', '0', '0', '0', '0', '0', '0'};
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ArrayList gameControllerDeviceIds = new ArrayList();
        int[] deviceIds = InputDevice.getDeviceIds();
        for (int deviceId : deviceIds) {
            InputDevice dev = InputDevice.getDevice(deviceId);

            int sources = dev.getSources();

            // Verify that the device has gamepad buttons, control sticks, or both.
            if (((sources & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD)
                    || ((sources & InputDevice.SOURCE_JOYSTICK)
                    == InputDevice.SOURCE_JOYSTICK)) {
                // This device is a game controller. Store its device ID.
                if (!gameControllerDeviceIds.contains(deviceId)) {
                    gameControllerDeviceIds.add(deviceId);
                    Log.d("yolol", String.valueOf(deviceId));

                }
            }
        }

        //Log.d("yolol", InputDevice.getDevice(7).getName());
        new CheckUsageStartup().execute();
        Log.d("sss", Arrays.toString(keys));

        textView = (TextView) findViewById(R.id.textView);
    }

    byte[] toByteArray(String[] strong){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);
        for(int i = 0; i < strong.length; i++)
        {
            try{
                dos.writeUTF(strong[i]);
            }
            catch (IOException e){

            }
        }

        return baos.toByteArray();
    }

    class CheckUsageStartup extends AsyncTask<Void, Integer, String> {
        String TAG = getClass().getSimpleName();

        protected void onPreExecute() {
            Log.d(TAG + " PreExceute", "On pre Exceute......");

        }

        protected String doInBackground(Void... arg0) {
            Log.d(TAG + " DoINBackGround", "On doInBackground...");

            try {
                Socket socket = new Socket("192.168.1.8", 8888);
                OutputStream out = socket.getOutputStream();
                Writer writer = new OutputStreamWriter(out, "UTF-8");

                while(true){
                    writer.write(keys, 0, 8);
                    writer.flush();
                }

            } catch (IOException e) {
                System.out.println(e.getMessage());
                return "Instant";
            }
        }

        protected void onProgressUpdate(Integer... a) {
            Log.d(TAG + " onProgressUpdate", "You are in progress update ... " + a[0]);
        }

        protected void onPostExecute(String result) {
            Log.d(TAG + " onPostExecute", "" + result);

        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        int deviceId = event.getDeviceId();
        if (deviceId != -1) {
            switch(keyCode){
                case KeyEvent.KEYCODE_BUTTON_1:
                    keys[0] = '1';
                    Log.d("u", "po");
                    break;
                case KeyEvent.KEYCODE_BUTTON_2:
                    keys[1] = '1';
                    break;
                case KeyEvent.KEYCODE_BUTTON_3:
                    keys[2] = '1';
                    break;
                case KeyEvent.KEYCODE_BUTTON_4:
                    keys[3] = '1';
                    break;

                case KeyEvent.KEYCODE_DPAD_UP:
                    keys[4] = '1';
                    break;
                case KeyEvent.KEYCODE_DPAD_DOWN:
                    keys[5] = '1';
                    break;
                case KeyEvent.KEYCODE_DPAD_LEFT:
                    keys[6] = '1';
                    break;
                case KeyEvent.KEYCODE_DPAD_RIGHT:
                    keys[7] = '1';
                    break;
            }
            textView.setText(Arrays.toString(keys));
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        int deviceId = event.getDeviceId();
        if (deviceId != -1) {
            switch(keyCode){
                case KeyEvent.KEYCODE_BUTTON_1:
                    keys[0] = '0';
                    break;
                case KeyEvent.KEYCODE_BUTTON_2:
                    keys[1] = '0';
                    break;
                case KeyEvent.KEYCODE_BUTTON_3:
                    keys[2] = '0';
                    break;
                case KeyEvent.KEYCODE_BUTTON_4:
                    keys[3] = '0';
                    break;

                case KeyEvent.KEYCODE_DPAD_UP:
                    keys[4] = '0';
                    break;
                case KeyEvent.KEYCODE_DPAD_DOWN:
                    keys[5] = '0';
                    break;
                case KeyEvent.KEYCODE_DPAD_LEFT:
                    keys[6] = '0';
                    break;
                case KeyEvent.KEYCODE_DPAD_RIGHT:
                    keys[7] = '0';
                    break;
            }
            textView.setText(Arrays.toString(keys));
            return true;
        }

        return super.onKeyUp(keyCode, event);
    }

Here's the code. Please tell me possible solutions. Is it encoding do this much delay, perhaps?

Body:
I figured it out.

This is code that was updating the textbox from earlier,

void Log(string msg)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action<string>(Log), new object[] {msg});
                return;
            }
            logBox.Text = "";
            logBox.Text += msg + Environment.NewLine;
        }

I don't know what causes the problem, but after updating the textbox from the below code, it works well now.

Invoke((MethodInvoker)delegate {
                    logBox.Text = ASCIIEncoding.UTF8.GetString(byteArray, 0, 8);
                });

It seems using the first method gives some unwanted delay.


来源: stackexchange

问:
DIY Google home using PC and BT speaker with mic
I have this BT speaker , with in built mic , http://www.intex.in/speakers/bluetooth-speakers/it-11s-bt
i want to build something like google home with it , using python .Please guide me.</p>

答:
I've read a couple articles and comments that suggest the reason why bluetooth is not an ideal setup is because BT and WIFI both use the same 2.4 Ghz band and slow each other down / disconnect when used simultaneously. My advice would be to do what I did: run a usb mic with an extension cable from inside a cabinet or entertainment unit and connect it to your audio system or run a 3.5 mm headphone jack extension too.

I've been writing a tutorial that is for beginners and is super easy to follow. All the steps to get it up and running (step 3) and monitor-free (step 4) are there.

I'll be working on it throughout the summer, adding the LED support, similar to G Home. Best of luck!

ContentLicense: CC BY-SA 3.0


问:
How can I fix this file name expression?
I'm using Ext.js for filemanager. I'm trying to allow saving only .c and .cpp files. But I cant get both file extensions to work.

```<code>Ext.ns('Editor.FileCombo');

Editor.VTypes = Ext.form.field.VTypes;
Ext.apply(Ext.form.field.VTypes, {Expression
    fileNameExp: /^(?!main\.c$)([a-zA-z]+[\w-]*\.c)$/i, // Expression
    fileName: function(val,field){      // Test
        return this.fileNameExp.test(val);
    },
    fileNameText: 'The filename ist not in a valid format!<br />Filename has to end with \'.c\' Or \'.cpp\,<br />Allowed: a-z,A-Z,0-9,_,- <br />Filename <i>main.c</i> is reserved for the compiler.',      // Error QTIP Text
    fileNameMask: /[\w\d-\.]/i          // valid character Mask
});
</code>```

Tried to modify fileNameExp to this:

```<code>fileNameExp: /^(?!main\.c$)([a-zA-z]+[\w-]*\.c)$([a-zA-z]+[\w-]*\.cpp)/i
</code>```

But thats not working.. .I look around the Stackoverflow about this topic, but couldn't understand how to archive this. I would be very much appreciated if someone can fix this expression code!

答:
I believe this is the RegEx you are looking for: /(?:^(?!main\.)[^\\/]+\.)(?:c|cpp)$/

You can always use this website to test JS RegEx: https://regex101.com/

Remember to select Javascript on the left hand side.

Body:
I'm using Ext.js for filemanager. I'm trying to allow saving only .c and .cpp files. But I cant get both file extensions to work.

Ext.ns('Editor.FileCombo');

Editor.VTypes = Ext.form.field.VTypes;
Ext.apply(Ext.form.field.VTypes, {Expression
    fileNameExp: /^(?!main\.c$)([a-zA-z]+[\w-]*\.c)$/i, // Expression
    fileName: function(val,field){      // Test
        return this.fileNameExp.test(val);
    },
    fileNameText: 'The filename ist not in a valid format!
Filename has to end with \'.c\' Or \'.cpp\,
Allowed: a-z,A-Z,0-9,_,-
Filename main.c is reserved for the compiler.',      // Error QTIP Text
    fileNameMask: /[\w\d-\.]/i          // valid character Mask
});

Tried to modify fileNameExp to this:

fileNameExp: /^(?!main\.c$)([a-zA-z]+[\w-]*\.c)$([a-zA-z]+[\w-]*\.cpp)/i

But thats not working.. .I look around the Stackoverflow about this topic, but couldn't understand how to archive this. I would be very much appreciated if someone can fix this expression code!


问:
How to correct hibernate test
Can someone explain the following. I have the code:

```<code>@Entity
public class Model {

    @Id
    @GeneratedValue(strategy = AUTO)
    @Column
    private long id;

    @Column(length = 200, nullable = false)
    private String field0;

    @Column(length = 200, nullable = false)
    private String field1;

    @Column(length = 200, nullable = false)
    private String field2;

    @Column(length = 200, nullable = false)
    private String field3;

    @Column(length = 200, nullable = false)
    private String field4;

    @Column(length = 200, nullable = false)
    private String field5;

    @Column(length = 200, nullable = false)
    private String field6;

    @Column(length = 200, nullable = false)
    private String field7;

    @Column(length = 200, nullable = false)
    private String field8;

    @Column(length = 200, nullable = false)
    private String field9;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getField0() {
        return field0;
    }

    public void setField0(String field0) {
        this.field0 = field0;
    }

    public String getField1() {
        return field1;
    }

    public void setField1(String field1) {
        this.field1 = field1;
    }

    public String getField2() {
        return field2;
    }

    public void setField2(String field2) {
        this.field2 = field2;
    }

    public String getField3() {
        return field3;
    }

    public void setField3(String field3) {
        this.field3 = field3;
    }

    public String getField4() {
        return field4;
    }

    public void setField4(String field4) {
        this.field4 = field4;
    }

    public String getField5() {
        return field5;
    }

    public void setField5(String field5) {
        this.field5 = field5;
    }

    public String getField6() {
        return field6;
    }

    public void setField6(String field6) {
        this.field6 = field6;
    }

    public String getField7() {
        return field7;
    }

    public void setField7(String field7) {
        this.field7 = field7;
    }

    public String getField8() {
        return field8;
    }

    public void setField8(String field8) {
        this.field8 = field8;
    }

    public String getField9() {
        return field9;
    }

    public void setField9(String field9) {
        this.field9 = field9;
    }

    @Override
    public String toString() {
        return "Model{" + "id=" + id + ", field0='" + field0 + '\''
                + ", field1='" + field1 + '\'' + ", field2='" + field2 + '\''
                + ", field3='" + field3 + '\'' + ", field4='" + field4 + '\''
                + ", field5='" + field5 + '\'' + ", field6='" + field6 + '\''
                + ", field7='" + field7 + '\'' + ", field8='" + field8 + '\''
                + ", field9='" + field9 + '\'' + '}';
    }
}

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/testContext.xml")
public class MainTest {

    @Autowired
    private SessionFactory sessionFactory;
    private Session session;
    private Transaction tx;

    @Before
    public void before() {
        session = sessionFactory.openSession();
        tx = session.beginTransaction();
        session.setFlushMode(FlushMode.COMMIT);
    }

    @After
    public void after() {
        tx.commit();
        session.close();
    }

    @Test
    public void shouldFindModelByField() {
        Model model = createRandomModel();
        session.save(model);

        model.setField0("TEST1");
        session.save(model);

        assertTrue(null != session.createSQLQuery(
                "select id from model where field0 = '" + model.getField0()
                        + "'").uniqueResult());
    }

    private Model createRandomModel() {
        Model ret = new Model();
        ret.setField0(RandomStringUtils.randomAlphanumeric(10));
        ret.setField1(RandomStringUtils.randomAlphanumeric(10));
        ret.setField2(RandomStringUtils.randomAlphanumeric(10));
        ret.setField3(RandomStringUtils.randomAlphanumeric(10));
        ret.setField4(RandomStringUtils.randomAlphanumeric(10));
        ret.setField5(RandomStringUtils.randomAlphanumeric(10));
        ret.setField6(RandomStringUtils.randomAlphanumeric(10));
        ret.setField7(RandomStringUtils.randomAlphanumeric(10));
        ret.setField8(RandomStringUtils.randomAlphanumeric(10));
        ret.setField9(RandomStringUtils.randomAlphanumeric(10));
        return ret;
    }
}
</code>```

If I run the test as is, the test fails and I get an error java.lang.AssertionError.

I have three varints to change @Test method to run the test successfully:

1)

```<code>@Test
public void shouldFindModelByField() {
    Model model = createRandomModel();
    session.save(model);

    session.evict(model);

    model.setField0("TEST1");
    session.save(model);

    assertTrue(null != session.createSQLQuery(
            "select id from model where field0 = '" + model.getField0()
                    + "'").uniqueResult());
}
</code>```

2)

```<code>@Test
public void shouldFindModelByField() {
    Model model = createRandomModel();
    session.save(model);

    model.setField0("TEST1");
    session.save(model);

    tx.commit();
    tx = session.beginTransaction();

    assertTrue(null != session.createSQLQuery(
            "select id from model where field0 = '" + model.getField0()
                    + "'").uniqueResult());
}
</code>```

3)

```<code>@Test
public void shouldFindModelByField() {
    Model model = createRandomModel();
    session.save(model);

    model.setField0("TEST1");
    session.save(model);

    session.flush();

    assertTrue(null != session.createSQLQuery(
            "select id from model where field0 = '" + model.getField0()
                    + "'").uniqueResult());
}
</code>```

Questions:
1) Why test fails if I run it as is?
2) What variant is correct?
3) If none of them, how to correct the code?

答:
When Hibernate executes SQL

FlushMode dictates when Hibernate generates the actual SQL statements. The default (auto) is pretty sensible and it tries to delay the statements as much as possible. But it will flush before each SELECT statement (otherwise you won't find the records you just persisted).

Hibernate must generate an ID for the entity when you save it (the result of the save() is a PERSISTED entity which must have an ID). Thus no matter which FlushMode you choose ORM will issue INSERT statement if that's what's needed for ID to be generated. If you were to use Sequence generator - INSERT could be postponed, but you use Identity - this one cannot be postponed as the ID is generated by the DB during the INSERT.

Why original code doesn't work

You set FlushMode to COMMIT which means Hibernate executes SQL right before the transaction commit. Thus when you update your entity the UPDATE statement is not invoked. It would've been invoked only at the end when you commit the transaction (which you never do).

Why Fix #1 "works"

Your original INSERT statement for the new entity still executes even with FlushMode COMMIT - the ID has to be generated.

After you evict() entity Hibernate doesn't know about it anymore, but it has an ID, so next time you save() Hibernate knows that it's a DETACHED entity. Every time a detached entity is saved() an UPDATE is invoked.

Why Fix #2 works

Well, you actually commit the transaction so Hibernate flushes all the SQLs including UPDATE statements. Your FlushMode=COMMIT works as expected.

Why Fix #3 works

In this case you manually flush() the changes - it will execute SQL statements no matter which Flush Mode you chose.

How to write Hibernate tests

First of all SpringJUnit4ClassRunner supports @Transactional annotations on tests. So instead of handling transactions manually in @Before & @After you can use the annotation.

Second, to be sure that the test actually works you need to flush and clear 1st level cache manually. Otherwise you risk to work with cached entities instead of the real DB. So your test can look like this:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/testContext.xml")
@Transactional
public class MainTest {
    ...
    @Test public void canUpdateAllTheFields() {
        Model original = createRandomModel();
        session.save(original);
        session.flush();
        session.clear();

        Model updates = createRandomModel();
        model.setId(original.getId());
        session.update(updates);
        session.flush();
        session.clear();

        assertReflectionEquals(updates, session.get(Model.class, original.getId()));
    }
}
</code>```

Notes:

You can combine flush() and clear() in a separate method so that it doesn't take that much space.

assertReflectionEquals() comes from Unitils lib.

You can find an example of such tests here (TestNG) and here (Spock).

Title: How to correct hibernate test

Body:
Can someone explain the following. I have the code:

@Entity
public class Model {

    @Id
    @GeneratedValue(strategy = AUTO)
    @Column
    private long id;

    @Column(length = 200, nullable = false)
    private String field0;

    @Column(length = 200, nullable = false)
    private String field1;

    @Column(length = 200, nullable = false)
    private String field2;

    @Column(length = 200, nullable = false)
    private String field3;

    @Column(length = 200, nullable = false)
    private String field4;

    @Column(length = 200, nullable = false)
    private String field5;

    @Column(length = 200, nullable = false)
    private String field6;

    @Column(length = 200, nullable = false)
    private String field7;

    @Column(length = 200, nullable = false)
    private String field8;

    @Column(length = 200, nullable = false)
    private String field9;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getField0() {
        return field0;
    }

    public void setField0(String field0) {
        this.field0 = field0;
    }

    public String getField1() {
        return field1;
    }

    public void setField1(String field1) {
        this.field1 = field1;
    }

    public String getField2() {
        return field2;
    }

    public void setField2(String field2) {
        this.field2 = field2;
    }

    public String getField3() {
        return field3;
    }

    public void setField3(String field3) {
        this.field3 = field3;
    }

    public String getField4() {
        return field4;
    }

    public void setField4(String field4) {
        this.field4 = field4;
    }

    public String getField5() {
        return field5;
    }

    public void setField5(String field5) {
        this.field5 = field5;
    }

    public String getField6() {
        return field6;
    }

    public void setField6(String field6) {
        this.field6 = field6;
    }

    public String getField7() {
        return field7;
    }

    public void setField7(String field7) {
        this.field7 = field7;
    }

    public String getField8() {
        return field8;
    }

    public void setField8(String field8) {
        this.field8 = field8;
    }

    public String getField9() {
        return field9;
    }

    public void setField9(String field9) {
        this.field9 = field9;
    }

    @Override
    public String toString() {
        return "Model{" + "id=" + id + ", field0='" + field0 + '\''
                + ", field1='" + field1 + '\'' + ", field2='" + field2 + '\''
                + ", field3='" + field3 + '\'' + ", field4='" + field4 + '\''
                + ", field5='" + field5 + '\'' + ", field6='" + field6 + '\''
                + ", field7='" + field7 + '\'' + ", field8='" + field8 + '\''
                + ", field9='" + field9 + '\'' + '}';
    }
}

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/testContext.xml")
public class MainTest {

    @Autowired
    private SessionFactory sessionFactory;
    private Session session;
    private Transaction tx;

    @Before
    public void before() {
        session = sessionFactory.openSession();
        tx = session.beginTransaction();
        session.setFlushMode(FlushMode.COMMIT);
    }

    @After
    public void after() {
        tx.commit();
        session.close();
    }

    @Test
    public void shouldFindModelByField() {
        Model model = createRandomModel();
        session.save(model);

        model.setField0("TEST1");
        session.save(model);

        assertTrue(null != session.createSQLQuery(
                "select id from model where field0 = '" + model.getField0()
                        + "'").uniqueResult());
    }

    private Model createRandomModel() {
        Model ret = new Model();
        ret.setField0(RandomStringUtils.randomAlphanumeric(10));
        ret.setField1(RandomStringUtils.randomAlphanumeric(10));
        ret.setField2(RandomStringUtils.randomAlphanumeric(10));
        ret.setField3(RandomStringUtils.randomAlphanumeric(10));
        ret.setField4(RandomStringUtils.randomAlphanumeric(10));
        ret.setField5(RandomStringUtils.randomAlphanumeric(10));
        ret.setField6(RandomStringUtils.randomAlphanumeric(10));
        ret.setField7(RandomStringUtils.randomAlphanumeric(10));
        ret.setField8(RandomStringUtils.randomAlphanumeric(10));
        ret.setField9(RandomStringUtils.randomAlphanumeric(10));
        return ret;
    }
}

If I run the test as is, the test fails and I get an error java.lang.AssertionError.

I have three varints to change @Test method to run the test successfully:

1)

@Test
public void shouldFindModelByField() {
    Model model = createRandomModel();
    session.save(model);

    session.evict(model);

    model.setField0("TEST1");
    session.save(model);

    assertTrue(null != session.createSQLQuery(
            "select id from model where field0 = '" + model.getField0()
                    + "'").uniqueResult());
}

2)

@Test
public void shouldFindModelByField() {
    Model model = createRandomModel();
    session.save(model);

    model.setField0("TEST1");
    session.save(model);

    tx.commit();
    tx = session.beginTransaction();

    assertTrue(null != session.createSQLQuery(
            "select id from model where field0 = '" + model.getField0()
                    + "'").uniqueResult());
}

3)

@Test
public void shouldFindModelByField() {
    Model model = createRandomModel();
    session.save(model);

    model.setField0("TEST1");
    session.save(model);

    session.flush();

    assertTrue(null != session.createSQLQuery(
            "select id from model where field0 = '" + model.getField0()
                    + "'").uniqueResult());
}

Questions:
1) Why test fails if I run it as is?
2) What variant is correct?
3) If none of them, how to correct the code?

Body:
When Hibernate executes SQL

FlushMode dictates when Hibernate generates the actual SQL statements. The default (auto) is pretty sensible and it tries to delay the statements as much as possible. But it will flush before each SELECT statement (otherwise you won't find the records you just persisted).

Hibernate must generate an ID for the entity when you save it (the result of the save() is a PERSISTED entity which must have an ID). Thus no matter which FlushMode you choose ORM will issue INSERT statement if that's what's needed for ID to be generated. If you were to use Sequence generator - INSERT could be postponed, but you use Identity - this one cannot be postponed as the ID is generated by the DB during the INSERT.

Why original code doesn't work

You set FlushMode to COMMIT which means Hibernate executes SQL right before the transaction commit. Thus when you update your entity the UPDATE statement is not invoked. It would've been invoked only at the end when you commit the transaction (which you never do).

Why Fix #1 "works"

Your original INSERT statement for the new entity still executes even with FlushMode COMMIT - the ID has to be generated.

After you evict() entity Hibernate doesn't know about it anymore, but it has an ID, so next time you save() Hibernate knows that it's a DETACHED entity. Every time a detached entity is saved() an UPDATE is invoked.

Why Fix #2 works

Well, you actually commit the transaction so Hibernate flushes all the SQLs including UPDATE statements. Your FlushMode=COMMIT works as expected.

Why Fix #3 works

In this case you manually flush() the changes - it will execute SQL statements no matter which Flush Mode you chose.

How to write Hibernate tests

First of all SpringJUnit4ClassRunner supports @Transactional annotations on tests. So instead of handling transactions manually in @Before & @After you can use the annotation.

Second, to be sure that the test actually works you need to flush and clear 1st level cache manually. Otherwise you risk to work with cached entities instead of the real DB. So your test can look like this:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/testContext.xml")
@Transactional
public class MainTest {
    ...
    @Test public void canUpdateAllTheFields() {
        Model original = createRandomModel();
        session.save(original);
        session.flush();
        session.clear();

        Model updates = createRandomModel();
        model.setId(original.getId());
        session.update(updates);
        session.flush();
        session.clear();

        assertReflectionEquals(updates, session.get(Model.class, original.getId()));
    }
}

Notes:

You can combine flush() and clear() in a separate method so that it doesn't take that much space.

assertReflectionEquals() comes from Unitils lib.

You can find an example of such tests here (TestNG) and here (Spock).

ContentLicense: CC BY-SA 4.0


问:
Sails project - mysql connection 'Error: Consistency violation'
I have created a new sails project and installed sails-permission. First it worked fine. After creating connection to Mysql and did sails lift it throws an error as

```<code>error: Error: Consistency violation: A model (`passport`) references a
</code>```

datastore which cannot be found ('mysql').  If this model definition has an explicit connection property, check that it is spelled correctly.  If not, check your default connection (usually located in config/models.js).

The Model passport.js is located in node_modules/sails-permission/api/models.

config/connections.js

```<code> mysql: {
    module    : 'sails-mysql',
    host      : '127.0.0.1',
    port      :  3306,
    user      : 'review',
    password  : 'review',
    database  : 'reviews'
  },
</code>```

config/models.js

```<code>module.exports.models = {
  connection: 'mysql',
  migrate: 'alter'
};
</code>```

node_modules/sails-permission/api/models

```<code>var bcrypt = require('bcryptjs');

function hashPassword (passport, next) {
  var config = sails.config.auth.bcrypt;
  var salt = config.salt || config.rounds;
  if (passport.password) {
    bcrypt.hash(passport.password, salt, function (err, hash) {
      if (err) {
        delete passport.password;
        sails.log.error(err);
        throw err;
      }
      passport.password = hash;
      next(null, passport);
    });
  }
  else {
    next(null, passport);
  }
}

  var Passport = {
  attributes: {

    password: { type: 'string', minLength: 8 },
    provider   : { type: 'alphanumericdashed' },
    identifier : { type: 'string' },
    tokens     : { type: 'json' },
    user: { model: 'User', required: true },

    validatePassword: function (password, next) {
      bcrypt.compare(password, this.password, next);
    }

  },
  beforeCreate: function (passport, next) {
    hashPassword(passport, next);
  },
  beforeUpdate: function (passport, next) {
    hashPassword(passport, next);
  }
};

module.exports = Passport;
</code>```

答:
It beacause of sails-mysql update. [https://github.com/balderdashy/sails-mysql/pull/328/files].

Change module as adapter in

```<code>config/connection.js

mysql: {
    adapter    : 'sails-mysql',
    host      : '127.0.0.1',
    port      :  3306,
    user      : 'review',
    password  : 'review',
    database  : 'reviews'
  },
</code>```

Body:
I have created a new sails project and installed sails-permission. First it worked fine. After creating connection to Mysql and did sails lift it throws an error as

error: Error: Consistency violation: A model (`passport`) references a

datastore which cannot be found ('mysql').  If this model definition has an explicit connection property, check that it is spelled correctly.  If not, check your default connection (usually located in config/models.js).

The Model passport.js is located in node_modules/sails-permission/api/models.

config/connections.js

 mysql: {
    module    : 'sails-mysql',
    host      : '127.0.0.1',
    port      :  3306,
    user      : 'review',
    password  : 'review',
    database  : 'reviews'
  },

config/models.js

module.exports.models = {
  connection: 'mysql',
  migrate: 'alter'
};

node_modules/sails-permission/api/models

var bcrypt = require('bcryptjs');

function hashPassword (passport, next) {
  var config = sails.config.auth.bcrypt;
  var salt = config.salt || config.rounds;
  if (passport.password) {
    bcrypt.hash(passport.password, salt, function (err, hash) {
      if (err) {
        delete passport.password;
        sails.log.error(err);
        throw err;
      }
      passport.password = hash;
      next(null, passport);
    });
  }
  else {
    next(null, passport);
  }
}

  var Passport = {
  attributes: {

    password: { type: 'string', minLength: 8 },
    provider   : { type: 'alphanumericdashed' },
    identifier : { type: 'string' },
    tokens     : { type: 'json' },
    user: { model: 'User', required: true },

    validatePassword: function (password, next) {
      bcrypt.compare(password, this.password, next);
    }

  },
  beforeCreate: function (passport, next) {
    hashPassword(passport, next);
  },
  beforeUpdate: function (passport, next) {
    hashPassword(passport, next);
  }
};

module.exports = Passport;

Body:
It beacause of sails-mysql update. [https://github.com/balderdashy/sails-mysql/pull/328/files].

Change module as adapter in

config/connection.js

mysql: {
    adapter    : 'sails-mysql',
    host      : '127.0.0.1',
    port      :  3306,
    user      : 'review',
    password  : 'review',
    database  : 'reviews'
  },


问:
Saving data from android app to remote server
I am just a beginner in android app development and that's why I have many doubts. I am building one application where the user enters some data in editText. Now I want to save that data in my database. My database is running on my laptop. How would my app connect to the database? Do I need a web server in between? If yes then which web server is used for Android apps? Basically, i want to know the flow of data from app to the database.</p>

答: You can use REST Service when it comes to web Service on Android like this. You can either pass the values as parameters or an Object depending on your requirement. All the best</p>


问:
How to groupby by a column and return the values of other columns as lists in pandas?
I am facing trouble clubbing the values of a column together and retaining the respective values of other columns. I would like to do something similar to this: grouping rows in list in pandas groupby

But instead, I want the list/dictionary (preferably latter) to contain values of multiple columns.
Example for this dataframe:

df:

```<code>Col1   Col2   Col3
A      xyz     1
A      pqr     2
B      xyz     2
B      pqr     3
B      lmn     1
C      pqr     2
</code>```

I want something like-

```<code>A {'xyz':1, 'pqr': 2}
B {'xyz':2, 'pqr': 3, 'lmn': 1}
C {'pqr':2}
</code>```

I tried doing

```<code>df.groupby('Col1')[['Col2', 'Col3']].apply(list)
</code>```

which is a variant of the solution mentioned in the linked post, but isn't giving me the result I need.

From that point on, I would also like to transform it into a dataframe of the form:

```<code>  xyz  pqr  lmn
A  1    2    NaN
B  2    3    1
C  NaN  2    NaN
</code>```

答:
Neither one of these are pandas only solutions.  I provided them because I find exploring alternatives fun.  The bincount base solution is very fast but less transparent.

Creative Solution 1

collections.defaultdict and dictionary comprehension

```<code>from collections import defaultdict

d = defaultdict(dict)
[d[c2].setdefault(c1, c3) for i, c1, c2, c3 in df.itertuples()];
pd.DataFrame(d)

   lmn  pqr  xyz
A  NaN    2  1.0
B  1.0    3  2.0
C  NaN    2  NaN
</code>```

Creative Solution 2

pd.factorize and np.bincount

```<code>f1, u1 = pd.factorize(df.Col1.values)
f2, u2 = pd.factorize(df.Col2.values)
w = df.Col3.values

n, m = u1.size, u2.size

v = np.bincount(f1 * n + f2, w, n * m).reshape(n, m)
pd.DataFrame(np.ma.array(v, mask=v == 0), u1, u2)

   lmn  pqr  xyz
A  NaN    2  1.0
B  1.0    3  2.0
C  NaN    2  NaN
</code>```

Timing

```<code>%timeit df.pivot(index='Col1',columns='Col2',values='Col3')
%timeit df.set_index(['Col1','Col2'])['Col3'].unstack()
%timeit df.groupby(['Col1','Col2'])['Col3'].mean().unstack()
%timeit df.pivot_table(index='Col1',columns='Col2',values='Col3')

%%timeit
d = defaultdict(dict)
[d[c2].setdefault(c1, c3) for i, c1, c2, c3 in df.itertuples()];
pd.DataFrame(d)

%%timeit
f1, u1 = pd.factorize(df.Col1.values)
f2, u2 = pd.factorize(df.Col2.values)
w = df.Col3.values

n, m = u1.size, u2.size

v = np.bincount(f1 * n + f2, w, n * m).reshape(n, m)
pd.DataFrame(np.ma.array(v, mask=v == 0), u1, u2)
</code>```

small data

```<code>1000 loops, best of 3: 1.11 ms per loop
1000 loops, best of 3: 1.67 ms per loop
1000 loops, best of 3: 1.51 ms per loop
100 loops, best of 3: 4.17 ms per loop

1000 loops, best of 3: 1.18 ms per loop

1000 loops, best of 3: 420 µs per loop
</code>```

medium data

```<code>from string import ascii_letters
l = list(ascii_letters)
df = pd.DataFrame(dict(
        Col1=np.random.choice(l, 10000),
        Col2=np.random.choice(l, 10000),
        Col3=np.random.randint(10, size=10000)
    )).drop_duplicates(['Col1', 'Col2'])

1000 loops, best of 3: 1.75 ms per loop
100 loops, best of 3: 2.17 ms per loop
100 loops, best of 3: 2.2 ms per loop
100 loops, best of 3: 4.89 ms per loop

100 loops, best of 3: 5.6 ms per loop

1000 loops, best of 3: 549 µs per loop
</code>```

Body:
I am facing trouble clubbing the values of a column together and retaining the respective values of other columns. I would like to do something similar to this: grouping rows in list in pandas groupby

But instead, I want the list/dictionary (preferably latter) to contain values of multiple columns.
Example for this dataframe:

df:

Col1   Col2   Col3
A      xyz     1
A      pqr     2
B      xyz     2
B      pqr     3
B      lmn     1
C      pqr     2

I want something like-

A {'xyz':1, 'pqr': 2}
B {'xyz':2, 'pqr': 3, 'lmn': 1}
C {'pqr':2}

I tried doing

df.groupby('Col1')[['Col2', 'Col3']].apply(list)

which is a variant of the solution mentioned in the linked post, but isn't giving me the result I need.

From that point on, I would also like to transform it into a dataframe of the form:

  xyz  pqr  lmn
A  1    2    NaN
B  2    3    1
C  NaN  2    NaN

Body:
Neither one of these are pandas only solutions.  I provided them because I find exploring alternatives fun.  The bincount base solution is very fast but less transparent.

Creative Solution 1

collections.defaultdict and dictionary comprehension

from collections import defaultdict

d = defaultdict(dict)
[d[c2].setdefault(c1, c3) for i, c1, c2, c3 in df.itertuples()];
pd.DataFrame(d)

   lmn  pqr  xyz
A  NaN    2  1.0
B  1.0    3  2.0
C  NaN    2  NaN

Creative Solution 2

pd.factorize and np.bincount

f1, u1 = pd.factorize(df.Col1.values)
f2, u2 = pd.factorize(df.Col2.values)
w = df.Col3.values

n, m = u1.size, u2.size

v = np.bincount(f1 * n + f2, w, n * m).reshape(n, m)
pd.DataFrame(np.ma.array(v, mask=v == 0), u1, u2)

   lmn  pqr  xyz
A  NaN    2  1.0
B  1.0    3  2.0
C  NaN    2  NaN

Timing

%timeit df.pivot(index='Col1',columns='Col2',values='Col3')
%timeit df.set_index(['Col1','Col2'])['Col3'].unstack()
%timeit df.groupby(['Col1','Col2'])['Col3'].mean().unstack()
%timeit df.pivot_table(index='Col1',columns='Col2',values='Col3')

%%timeit
d = defaultdict(dict)
[d[c2].setdefault(c1, c3) for i, c1, c2, c3 in df.itertuples()];
pd.DataFrame(d)

%%timeit
f1, u1 = pd.factorize(df.Col1.values)
f2, u2 = pd.factorize(df.Col2.values)
w = df.Col3.values

n, m = u1.size, u2.size

v = np.bincount(f1 * n + f2, w, n * m).reshape(n, m)
pd.DataFrame(np.ma.array(v, mask=v == 0), u1, u2)

small data

1000 loops, best of 3: 1.11 ms per loop
1000 loops, best of 3: 1.67 ms per loop
1000 loops, best of 3: 1.51 ms per loop
100 loops, best of 3: 4.17 ms per loop

1000 loops, best of 3: 1.18 ms per loop

1000 loops, best of 3: 420 µs per loop

medium data

from string import ascii_letters
l = list(ascii_letters)
df = pd.DataFrame(dict(
        Col1=np.random.choice(l, 10000),
        Col2=np.random.choice(l, 10000),
        Col3=np.random.randint(10, size=10000)
    )).drop_duplicates(['Col1', 'Col2'])

1000 loops, best of 3: 1.75 ms per loop
100 loops, best of 3: 2.17 ms per loop
100 loops, best of 3: 2.2 ms per loop
100 loops, best of 3: 4.89 ms per loop

100 loops, best of 3: 5.6 ms per loop

1000 loops, best of 3: 549 µs per loop


问:
How to check address (category city:mtm) and get particular user details from json using typescript in my .ts file?
I have give below my json.

I need to check the address category type city. but i am able to get
  the output. I have given below is my json object.

```<code>[
  {
    "username": "ramu",
    "user_id": "222",
    "profileImage": "ramu.jpg",
    "status": "15",
    "address": [
      {
        "type": "permanent",
        "city": "mtm",
        "pin": "654654",
        "personal": [
          {
            "age": "26",
            "color": "white"
          }
        ]
      },
      {
        "type": "residential",
        "city": "chennai",
        "pin": "76755624",
        "personal": [
          {
            "age": "26",
            "color": "green"
          }
        ]
      }
    ]
  },
  {
    "username": "raju",
    "user_id": "222",
    "profileImage": "ramu.jpg",
    "status": "15",
    "address": [
      {
        "type": "permanent",
        "city": "mtm",
        "pin": "521001",
        "personal": [
          {
            "age": "26",
            "color": "red"
          }
        ]
      },
      {
        "type": "residential",
        "city": "chennai",
        "pin": "600024",
        "personal": [
          {
            "age": "26",
            "color": "blue"
          }
        ]
      }
    ]
  }
]
</code>```

Any body help me to check(address category city:mtm) and get particular user details only?

答:
```<code>class AddressLookUp{
    lookup:{ [index:string]: any};
    userArray:Array<Object>;
    constructor(users:Array<Object>){
        this.userArray = users;
        this.lookup={};
        this._buildLookUp()
    }
     private _buildLookUp():void{
        this.userArray.forEach((currentU:Object,_indexU:number)=>{
            (<any>currentU).address.forEach((currentA:Object,_indexA:number)=>{
                if((<any>currentA).city in this.lookup){
                    this.lookup[(<any>currentA).city].push(_indexU)
                }else{
                    this.lookup[(<any>currentA).city]=new Array(_indexU)
                }
            })
        })
    }
    findByAddress(address:string):Array<Object>{
        return  this.userArray.filter((c,i)=>{
            return i in this.lookup[address]
        })
    }
}
</code>```

<p>then use it </p>

```<code>let lookup = new AddressLookUp(userArray)
console.log(JSON.stringify(lookup.findByAddress("mtm")))
</code>```

Body:
I have give below my json.

I need to check the address category type city. but i am able to get
  the output. I have given below is my json object.

[
  {
    "username": "ramu",
    "user_id": "222",
    "profileImage": "ramu.jpg",
    "status": "15",
    "address": [
      {
        "type": "permanent",
        "city": "mtm",
        "pin": "654654",
        "personal": [
          {
            "age": "26",
            "color": "white"
          }
        ]
      },
      {
        "type": "residential",
        "city": "chennai",
        "pin": "76755624",
        "personal": [
          {
            "age": "26",
            "color": "green"
          }
        ]
      }
    ]
  },
  {
    "username": "raju",
    "user_id": "222",
    "profileImage": "ramu.jpg",
    "status": "15",
    "address": [
      {
        "type": "permanent",
        "city": "mtm",
        "pin": "521001",
        "personal": [
          {
            "age": "26",
            "color": "red"
          }
        ]
      },
      {
        "type": "residential",
        "city": "chennai",
        "pin": "600024",
        "personal": [
          {
            "age": "26",
            "color": "blue"
          }
        ]
      }
    ]
  }
]

Any body help me to check(address category city:mtm) and get particular user details only?

Body:
class AddressLookUp{
    lookup:{ [index:string]: any};
    userArray:Array<Object>;
    constructor(users:Array<Object>){
        this.userArray = users;
        this.lookup={};
        this._buildLookUp()
    }
     private _buildLookUp():void{
        this.userArray.forEach((currentU:Object,_indexU:number)=>{
            (<any>currentU).address.forEach((currentA:Object,_indexA:number)=>{
                if((<any>currentA).city in this.lookup){
                    this.lookup[(<any>currentA).city].push(_indexU)
                }else{
                    this.lookup[(<any>currentA).city]=new Array(_indexU)
                }
            })
        })
    }
    findByAddress(address:string):Array<Object>{
        return  this.userArray.filter((c,i)=>{
            return i in this.lookup[address]
        })
    }
}

then use it

let lookup = new AddressLookUp(userArray)
console.log(JSON.stringify(lookup.findByAddress("mtm")))


问:
Get app icon URL in Qt on Linux
I am trying to get the icon of an app (doesn't matter which one). I noticed Qt doesn't have something like GDesktopAppInfo and therefore I tried getting it through QSettings from /usr/share/applications/appname.desktop. That's already a problem, because the desktop file might not be there. Anyway, going further to extract the Icon key. Now I dunno how to find the url (notice that I need the url, sure I could make a QIcon, but I need to export it to QML, which would mean another QQuickImageProvider class, anyway, I don't wanna go that way). Is it possible, or is the aforementioned QQuickImageProvider my only solution?

答: You can use QIcon::fromTheme(QString iconName) to find the icon. It works most of the time but it's not as reliable as gtk</p>

Title: Get app icon URL in Qt on Linux


问:
G-WAN: adding .jar application to CLASSPATH: "try catch not catching exception"
I'm trying to use to G-WAN webserver. So I added a ".jar" application to CLASSPATH in order to call it from java servlet.
The code is running, but it is unable to catch the exception, and the application crashes.
Below you can find the output:</p>

```<code>'import site' failed; use -v for traceback
ptrace: Operation not permitted.
No frame selected.

Signal        : 11:Address not mapped to object
Signal src    : 1:.
errno         : 0
Thread        : 2
Code   Pointer: 7f22eda66ac7 module:libjvm.so function:Arena::set_size_in_bytes(unsigned long) line:0
Access Address: 000000000020
</code>```

答:
Can you confirm if G-WAN Java examples were running fine in the first place (even with exception handling)?

If so, your loaded .jar is the place to start with - or maybe the way the JVM loaded it from G-WAN's servlet.

That's clearly a JVM class loader issue but investigating it would require using your exact same .jar and settings, and digging into JVM internals.

Body:
I'm trying to use to G-WAN webserver. So I added a ".jar" application to CLASSPATH in order to call it from java servlet.
The code is running, but it is unable to catch the exception, and the application crashes.
Below you can find the output:

'import site' failed; use -v for traceback
ptrace: Operation not permitted.
No frame selected.

Signal        : 11:Address not mapped to object
Signal src    : 1:.
errno         : 0
Thread        : 2
Code   Pointer: 7f22eda66ac7 module:libjvm.so function:Arena::set_size_in_bytes(unsigned long) line:0
Access Address: 000000000020


问:
HTML to WordPress
I've never used WordPress.org before. I'm wondering if I can convert this html website that I have to wordpress exactly the same?

https://reporting.pacificamerican.org/pas/

And if this website is a wordpress site, does it means that I don't have to go into the codes if I want to update my content? Because right now with html site it takes more time to update all the contents.

Thank you.

答:
Sure, you could replicate the layouts.

Sure, your content would be editable with just a form.

It would take a lot of effort, but certainly doable.

Title: HTML to WordPress


答:
Wamp server is best option to play with server related utilities.You can use it even if you are offline. and it provides various option for data storage. It Mainly uses MySql and PHP scripts for fast performance.
For More details Click Here

Title: Saving data from android app to remote server

Body: I am just a beginner in android app development and that's why I have many doubts. I am building one application where the user enters some data in editText. Now I want to save that data in my database. My database is running on my laptop. How would my app connect to the database? Do I need a web server in between? If yes then which web server is used for Android apps? Basically, i want to know the flow of data from app to the database.


问:
Clicking one button then activate another button
I want to click 1st button then activate 2nd button. After 2nd button is activated, 1st button will be disabled. I wrote the code below but it is not working. Where is the problem?</p>

```<code><!DOCTYPE html>
<html>
<head>
<title>Edit Page</title>
</head>
<body>
<input type="submit" name="submit" value="button1" id="bt1">
<input type="button" name="button" value="button2" id="bt2" disabled="disabled">
</body>
<script>
$(function(){
        $("#bt1").click(function(){
            $(this).attr("disabled", "disabled");
            $("#bt2").removeAttr("disabled");
        });

        $("#bt2").click(function(){
            $(this).attr("disabled", "disabled");
            $("#bt1").removeAttr("disabled");
        });
    });
</script>

</html>
</code>```

答:
You code is perfect,just add jQuery library and it will start working

Check here:-

$(function(){
  $("#bt1").click(function(){
    $(this).attr("disabled", "disabled");
    $("#bt2").removeAttr("disabled");
  });

  $("#bt2").click(function(){
    $(this).attr("disabled", "disabled");
    $("#bt1").removeAttr("disabled");
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
  <head>
    <title>Edit Page</title>
  </head>
  <body>
    <input type="submit" name="submit" value="button1" id="bt1">
    <input type="button" name="button" value="button2" id="bt2" disabled="disabled">
  </body>
</html></code>```

Body:
I want to click 1st button then activate 2nd button. After 2nd button is activated, 1st button will be disabled. I wrote the code below but it is not working. Where is the problem?

<!DOCTYPE html>

<title>Edit Page</title>

<input type="submit" name="submit" value="button1" id="bt1">
<input type="button" name="button" value="button2" id="bt2" disabled="disabled">

Body:
You code is perfect,just add jQuery library and it will start working

Check here:-

$(function(){
  $("#bt1").click(function(){
    $(this).attr("disabled", "disabled");
    $("#bt2").removeAttr("disabled");
  });

  $("#bt2").click(function(){
    $(this).attr("disabled", "disabled");
    $("#bt1").removeAttr("disabled");
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
  <head>
    <title>Edit Page</title>
  </head>
  <body>
    <input type="submit" name="submit" value="button1" id="bt1">
    <input type="button" name="button" value="button2" id="bt2" disabled="disabled">
  </body>
</html>


问:
How to fetch particular data from Firebase in Android
I have integrated Google sign-in in my app and i am pushing some data in to fire base including user U-id.I had researched a lot and didn't get anything the problem i am facing that i want to fetch Particular data for eg If User A sign-in and push 5 data and Then User B sign-in and push 3 data.I want a query like if User A sing-in Again it will get his 5 data only and not the data which is pushed by User B.Thanks in Advance :)

By using this it fetch all the data from firebase:

```<code> databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot data : dataSnapshot.getChildren()) {
                FirebaseModel firebasemodel =
      data.getValue(FirebaseModel.class);
                firebasemodels.add(firebasemodel);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
</code>```

I have tried all that .child .orderby and .equalTo but did'nt work

My Structure is Like:

My FireBase Structure

答:
To Fetch Particular values from the firebase,try this code</p>

```<code>   FirebaseDatabase database;
   database.getReference().child("notepad-secure").orderByChild("id").equalTo(user).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.getValue() != null) {
                for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {

                    User userdet =childSnapshot.getValue(yourclass.class);
                    String note=userdet.note;
                   //Here you will get the string values what you want to fetch
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
</code>```

Body:
I have integrated Google sign-in in my app and i am pushing some data in to fire base including user U-id.I had researched a lot and didn't get anything the problem i am facing that i want to fetch Particular data for eg If User A sign-in and push 5 data and Then User B sign-in and push 3 data.I want a query like if User A sing-in Again it will get his 5 data only and not the data which is pushed by User B.Thanks in Advance :)

By using this it fetch all the data from firebase:

 databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot data : dataSnapshot.getChildren()) {
                FirebaseModel firebasemodel =
      data.getValue(FirebaseModel.class);
                firebasemodels.add(firebasemodel);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

I have tried all that .child .orderby and .equalTo but did'nt work

My Structure is Like:

My FireBase Structure

Body:
To Fetch Particular values from the firebase,try this code

   FirebaseDatabase database;
   database.getReference().child("notepad-secure").orderByChild("id").equalTo(user).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.getValue() != null) {
                for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {

                    User userdet =childSnapshot.getValue(yourclass.class);
                    String note=userdet.note;
                   //Here you will get the string values what you want to fetch
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });


问:
How to redirect http to https in codeigniter
Point #1
If I type:

```<code>www.myurl.com/somepage
http://www.myurl.com/somepage
http://myurl.com/somepage
https://myurl.com/somepage
</code>```

have it redirect to

```<code>https://www.myurl.com/somepage
</code>```

Point #2

```<code>When I type in something like www.myurl.com it is redirecting to https://www.myurl.com/index.php.
Make it so the index.php is not displaying. It should just display https://www.myurl.com
</code>```

From Comment htaccess

```<code>RewriteEngine On
RewriteCond %{HTTP_HOST} ^myhost\.com$ [NC]
RewriteRule ^(.*)$ myhost.com/$1 [R=301,L]
RewriteCond %{THE_REQUEST} ^[A-Z]+\ /index\.php(/[^\ ]*)?\ HTTP/
RewriteRule ^index\.php(/(.*))?$ myhost.com/$2 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</code>```

答:
If you find the error "No Input file specified" then add "?"
in the last line

RewriteRule ^(.*)$ index.php/?$1 [L]

in the answer from @asiya khan

Body:
Point #1
If I type:

www.myurl.com/somepage
http://www.myurl.com/somepage
http://myurl.com/somepage
https://myurl.com/somepage

have it redirect to

https://www.myurl.com/somepage

Point #2

When I type in something like www.myurl.com it is redirecting to https://www.myurl.com/index.php.
Make it so the index.php is not displaying. It should just display https://www.myurl.com

From Comment htaccess

RewriteEngine On
RewriteCond %{HTTP_HOST} ^myhost\.com$ [NC]
RewriteRule ^(.*)$ myhost.com/$1 [R=301,L]
RewriteCond %{THE_REQUEST} ^[A-Z]+\ /index\.php(/[^\ ]*)?\ HTTP/
RewriteRule ^index\.php(/(.*))?$ myhost.com/$2 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]


问:
how to display images in php from database using MYSQLi queries?
Below is the code from where my page jumps to the "prac_image_display" to display images:-

```<code><?php
    session_start();
    include("database.php");
    $sql = mysqli_query($con,"select * from mst_subject");
    echo "<h2><table cellpadding=5>";
    while($row = mysqli_fetch_array($sql)){
        echo "<tr>";
        echo "<td><img height='50' width='50' src='prac_img_display.php? id=".$row['sub_id']."'></td><td><a href=showtest.php?subid={$row['sub_id']}>".$row['sub_name']."</td>";
        echo "<tr>";
        //$_SESSION['subid']=$row['sub_id'];
    }
    echo "</table></h2>";
?>
</code>```

And now below is the code written in prac_image_display.php file:-

```<code>        <?php

       if(isset($_GET['id']))
       {
        include("database.php");
        $sql = "SELECT image FROM mst_subject WHERE
       sub_id=".$_GET['id'].";";
       //$sql = "SELECT image FROM mst_subject WHERE sub_id=8";
        $result=mysqli_query($con,"$sql");
        header("Content-type: image/jpeg");
        echo mysqli_result($result,0);
        mysqli_close($con);
     }
     else
     {
           echo 'Please use a real id number';
     }
    ?>
</code>```

Below is the code written in "database.php" file :-

```<code>    <?php
    $con=mysqli_connect("localhost","root","","test") or die("could not
                         connect ");
    //mysql_select_db("test",$con)  or die("Could connect to Database");
    ?>
</code>```

The images are stored in the database in BLOB.
The problem is when I use MYSQL in both .php files as shown above it runs fine and all the images get displayed on localhost perfectly but when I replace MYSQL functions with MYSQLi functions the images do not get displayed. please, tell me what changes can I do here.

答:
You can follow below steps to DEBUG and find out where is the actual problem.

Step 1 : Update your Image src

```<code>src='prac_img_display.php? id=".$row['sub_id']."'
/*TO*/
src='prac_img_display.php?id=".$row['sub_id']."'
</code>```

Note : Because, there is a Blank space.

Step 2 : Browse your Image URL in Browser, like

```<code>example.com/prac_img_display.php?id=8
</code>```

Note : Check, If the image Display properly In your browser window.

IF, Not displaying Image properly

Step 3 : Check header("Content-type: image/jpeg"); is correct.

Suppose, If you uploaded PNG image, This will not work.

For PNG image you should use header("Content-type: image/png");

Note : Also don't forget to DEBUG SQL Result.

Body:
Below is the code from where my page jumps to the "prac_image_display" to display images:-

<?php
    session_start();
    include("database.php");
    $sql = mysqli_query($con,"select * from mst_subject");
    echo "

";
    while($row = mysqli_fetch_array($sql)){
        echo "
";
        echo "	".$row['sub_name']."	";
        echo "
";
        //$_SESSION['subid']=$row['sub_id'];
    }
    echo "

";
?>

And now below is the code written in prac_image_display.php file:-

        <?php

       if(isset($_GET['id']))
       {
        include("database.php");
        $sql = "SELECT image FROM mst_subject WHERE
       sub_id=".$_GET['id'].";";
       //$sql = "SELECT image FROM mst_subject WHERE sub_id=8";
        $result=mysqli_query($con,"$sql");
        header("Content-type: image/jpeg");
        echo mysqli_result($result,0);
        mysqli_close($con);
     }
     else
     {
           echo 'Please use a real id number';
     }
    ?>

Below is the code written in "database.php" file :-

    <?php
    $con=mysqli_connect("localhost","root","","test") or die("could not
                         connect ");
    //mysql_select_db("test",$con)  or die("Could connect to Database");
    ?>

The images are stored in the database in BLOB.
The problem is when I use MYSQL in both .php files as shown above it runs fine and all the images get displayed on localhost perfectly but when I replace MYSQL functions with MYSQLi functions the images do not get displayed. please, tell me what changes can I do here.

Body:
You can follow below steps to DEBUG and find out where is the actual problem.

Step 1 : Update your Image src

src='prac_img_display.php? id=".$row['sub_id']."'
/*TO*/
src='prac_img_display.php?id=".$row['sub_id']."'

Note : Because, there is a Blank space.

Step 2 : Browse your Image URL in Browser, like

example.com/prac_img_display.php?id=8

Note : Check, If the image Display properly In your browser window.

IF, Not displaying Image properly

Step 3 : Check header("Content-type: image/jpeg"); is correct.

Suppose, If you uploaded PNG image, This will not work.

For PNG image you should use header("Content-type: image/png");

Note : Also don't forget to DEBUG SQL Result.


答:
Firstly add a user_id key in your child data, it will look like below :

```<code>id:"",
note:"",
title:"",
user:""
user_id:"{id from which user have you uploaded data}"
</code>```

And than you can call below function with specific user data like
       below Note : "user_id" = id from which user have you uploaded data

```<code>DatabaseReference reference = FirebaseDatabase.getInstance().getReference();

Query query = reference.child("notepad").orderByChild("id").equalTo("user_id");
query.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
            // dataSnapshot is the "notepad" node with all children with id
            for (DataSnapshot notepad: dataSnapshot.getChildren()) {
                // do something with the individual "notepad_data"
            }
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});
</code>```

Title: How to fetch particular data from Firebase in Android

Body:
Firstly add a user_id key in your child data, it will look like below :

id:"",
note:"",
title:"",
user:""
user_id:"{id from which user have you uploaded data}"

And than you can call below function with specific user data like
       below Note : "user_id" = id from which user have you uploaded data

DatabaseReference reference = FirebaseDatabase.getInstance().getReference();

Query query = reference.child("notepad").orderByChild("id").equalTo("user_id");
query.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
            // dataSnapshot is the "notepad" node with all children with id
            for (DataSnapshot notepad: dataSnapshot.getChildren()) {
                // do something with the individual "notepad_data"
            }
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});


问:
How to destroy session within 1 minute?
I try atmost but I failed to destroy session within in 1 minute. I am using PHP destroy code which is given below but it is not working.</p>

```<code><?php
    session_start();
    $_SESSION['start'] = "start session";
    if(isset($_POST['destroy'])){
        session_cache_expire(1);
    }
?>
</code>```

答:
```<code>        <?php
        define("DURATION",'1'); // define duration constant in minutes
        session_start();
        $duration = (DURATION * 60); // duration in seconds

        if(isset($_SESSION['started'])) //check whether session is set or not
        {
            $time = ($duration - (time() - $_SESSION['started']));
            if($time <= 0)
            {
                session_destroy();
                echo "Session has been expired. You were logged in for one minute";
            }
        }
       else
        {
            $_SESSION['started'] = time();
        }
        ?>
</code>```

Title: How to destroy session within 1 minute?

Body:
I try atmost but I failed to destroy session within in 1 minute. I am using PHP destroy code which is given below but it is not working.

<?php
    session_start();
    $_SESSION['start'] = "start session";
    if(isset($_POST['destroy'])){
        session_cache_expire(1);
    }
?>


问:
store data to 2 tables with foreign key in MySql php
I have two table in MySql, which are table 1 and table 2. As I want to link table 1 to 2 via userID. However, the funciton I have come out is not working.

MySQl tables are below:

In my case, userId will be the foreign key to link these 2 tables.
However, my functions are not working.
This is my function below:

```<code>function insert() {
    function adduserdetails($con, $accountId, $name, $contact) {

        $query = "insert into userdetails(accountId,name,contact)
            values('$accountId','$name','$contact')";
        //echo "{$sqlString}";

        $insertResult = mysqli_query($con, $query);

        if ($insertResult) {
            echo " Applicant Detail Added !<br />";
            echo "<a href='index.php'>Back to Home</a>";
        } else {
            echo " Error !";
            echo "{$query}";
            //header('Location: post.php');
        }
    }

}

if ($con->query($query) === TRUE) {
    $last_id = $con->insert_id;
    echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
    echo "Error: " . $query . "<br>" . $con->error;
}

function adduseremployment($con,$last_id,$occupationMain,$comapny){

    $query1 = "insert into useremployment(userId,Occupation,company)
            values('$last_id',$occupationMain','$comapny')";
                 //echo "{$sqlString}";

                 $insertResult = mysqli_query($con, $query1);

                 if($insertResult){
                     echo " Applicant Detail Added !<br />";
                     echo "<a href='index.php'>Back to Home</a>";
                 }
                 else {
                     echo " Error !";
                     echo "{$query1}";
                     //header('Location: post.php');
                 }

}
</code>```

答:
In second insert you are using wrong column name  (userID and not accountID)

```<code>   $query1 = "insert into useremployment(userID,Occupation,company)
                                         ^^^^^^ here
          values('$last_id',$occupationMain','$comapny')";
</code>```

and in function signature and body you have comapny (could be you want company)

Body:
I have two table in MySql, which are table 1 and table 2. As I want to link table 1 to 2 via userID. However, the funciton I have come out is not working.

MySQl tables are below:

In my case, userId will be the foreign key to link these 2 tables.
However, my functions are not working.
This is my function below:

function insert() {
    function adduserdetails($con, $accountId, $name, $contact) {

        $query = "insert into userdetails(accountId,name,contact)
            values('$accountId','$name','$contact')";
        //echo "{$sqlString}";

        $insertResult = mysqli_query($con, $query);

        if ($insertResult) {
            echo " Applicant Detail Added !
";
            echo "Back to Home";
        } else {
            echo " Error !";
            echo "{$query}";
            //header('Location: post.php');
        }
    }

}

if ($con->query($query) === TRUE) {
    $last_id = $con->insert_id;
    echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
    echo "Error: " . $query . "
" . $con->error;
}

function adduseremployment($con,$last_id,$occupationMain,$comapny){

    $query1 = "insert into useremployment(userId,Occupation,company)
            values('$last_id',$occupationMain','$comapny')";
                 //echo "{$sqlString}";

                 $insertResult = mysqli_query($con, $query1);

                 if($insertResult){
                     echo " Applicant Detail Added !
";
                     echo "Back to Home";
                 }
                 else {
                     echo " Error !";
                     echo "{$query1}";
                     //header('Location: post.php');
                 }

}

Body:
In second insert you are using wrong column name  (userID and not accountID)

   $query1 = "insert into useremployment(userID,Occupation,company)
                                         ^^^^^^ here
          values('$last_id',$occupationMain','$comapny')";

and in function signature and body you have comapny (could be you want company)


问:
Run dbus-daemon inside Docker container
I am trying to create a Docker container with a custom D-Bus bus running inside.

I configured my Dockerfile as follow:

```<code>FROM ubuntu:16.04
COPY myCustomDbus.conf /etc/dbus-1/
RUN apt-get update && apt-get install -y dbus
RUN dbus-daemon --config-file=/etc/dbus-1/myCustomDbus.conf
</code>```

After building, the socket is created but it is flagged as "file", not as "socket", and I can not use it as a bus...

```<code>-rwxrwxrwx  1 root root    0 Mar 20 07:25 myCustomDbus.sock
</code>```

If I remove this file and run the dbus-daemon command again in a terminal, the socket is successfully created :

```<code>srwxrwxrwx  1 root root    0 Mar 20 07:35 myCustomDbus.sock
</code>```

I am not sure if it is a D-Bus problem or a docker one.

答: You should use a startup script. The "run" command is executed only when the container is created and then stopped.</p>

Title: Run dbus-daemon inside Docker container

Body:
I am trying to create a Docker container with a custom D-Bus bus running inside.

I configured my Dockerfile as follow:

FROM ubuntu:16.04
COPY myCustomDbus.conf /etc/dbus-1/
RUN apt-get update && apt-get install -y dbus
RUN dbus-daemon --config-file=/etc/dbus-1/myCustomDbus.conf

After building, the socket is created but it is flagged as "file", not as "socket", and I can not use it as a bus...

-rwxrwxrwx  1 root root    0 Mar 20 07:25 myCustomDbus.sock

If I remove this file and run the dbus-daemon command again in a terminal, the socket is successfully created :

srwxrwxrwx  1 root root    0 Mar 20 07:35 myCustomDbus.sock

I am not sure if it is a D-Bus problem or a docker one.


问:
How to put Cookie session id into volley request?
So, i have this code to make a POST request with volley:

```<code>public class MainActivity extends AppCompatActivity {

 Button btnSearch;
 ProgressDialog loadingDialog;
 ListView lvResult;
 String session_id;
 RequestQueue queue;
 MyCookieManager myCookieManager;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  btnSearch = (Button) findViewById(R.id.btnSearch);
  lvResult = (ListView) findViewById(R.id.lvResult);
  loadingDialog = new ProgressDialog(MainActivity.this);
  loadingDialog.setMessage("Wait.\nLoading...");
  loadingDialog.setCancelable(false);
  myCookieManager = new MyCookieManager();

  requestCookie(); //FIRST CALL TO GET SESSION ID

  btnSearch.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
    showLoading();
    requestWithSomeHttpHeaders(); //CALL TO MAKE THE REQUEST WITH VALID SESSION ID
   }
  });

 }

 public void requestCookie() {
  queue = Volley.newRequestQueue(this);
  String url = "http://myurl.com/json/";

  StringRequest postRequest = new StringRequest(Request.Method.POST, url,
   new Response.Listener < String > () {
    @Override
    public void onResponse(String response) {
     //
     String x = myCookieManager.getCookieValue();
    }
   },
   new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
     Log.d("ERROR", "Error => " + error.toString());
     hideLoading();
    }
   }
  ) {
   @Override
   public byte[] getBody() throws AuthFailureError {
    String httpPostBody = "param1=XPTO&param2=XPTO";
    return httpPostBody.getBytes();
   }

   @Override
   public Map < String, String > getHeaders() throws AuthFailureError {
    Map <String, String> params = new HashMap < String, String > ();
    params.put("User-Agent", "Mozilla/5.0");
    params.put("Accept", "application/json, text/javascript, */*; q=0.01");
    params.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    //params.put("Set-Cookie", session_id);// + " _ga=GA1.3.1300076726.1496455105; _gid=GA1.3.1624400465.1496455105; _gat=1; _gali=AguardeButton");
    //"PHPSESSID=ra0nbm0l22gsnl6s4jo0qkqci1");
    return params;
   }

   protected Response <String> parseNetworkResponse(NetworkResponse response) {
    try {
     String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
     String header_response = String.valueOf(response.headers.values());
     int index1 = header_response.indexOf("PHPSESSID=");
     int index2 = header_response.indexOf("; path");
     //Log.e(Utils.tag, "error is : " + index1 + "::" + index2);
     session_id = header_response.substring(index1, index2);

     return Response.success(jsonString, HttpHeaderParser.parseCacheHeaders(response));
    } catch (UnsupportedEncodingException e) {
     return Response.error(new ParseError(e));
    }
   }
  };

  queue.add(postRequest);
 }

 public void requestWithSomeHttpHeaders() {
  queue = Volley.newRequestQueue(this);
  String url = "http://myurl.com/json/";

  StringRequest postRequest = new StringRequest(Request.Method.POST, url,
   new Response.Listener <String> () {
    @Override
    public void onResponse(String response) {
     Log.d("Response", response);
     String x = myCookieManager.getCookieValue();
     String status = "";

     try {
      JSONObject resultObject = new JSONObject(response);
      Log.d("JSON RESULT =>", resultObject.toString());
     } catch (JSONException e) {
      Toast.makeText(MainActivity.this, "Request Error", Toast.LENGTH_SHORT).show();
      e.printStackTrace();
     }

     hideLoading();
    }
   },
   new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
     Log.d("ERROR", "Error => " + error.toString());
     hideLoading();
    }
   }
  ) {
   @Override
   public byte[] getBody() throws AuthFailureError {
    String httpPostBody = "param1=XPTO&param2=XPTO";
    return httpPostBody.getBytes();
   }

   @Override
   public Map <String, String> getHeaders() throws AuthFailureError {
    Map <String, String> params = new HashMap <String, String> ();
    params.put("User-Agent", "Mozilla/5.0");
    params.put("Accept", "application/json, text/javascript, */*; q=0.01");
    params.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    params.put("Cookie", /*myCookieManager.getCookieValue()*/ session_id + "; _ga=GA1.3.1300076726.1496455105; _gid=GA1.3.1624400465.1496455105; _gat=1; _gali=AguardeButton");
    return params;
   }
  };

  queue.add(postRequest);
 }

 private void showLoading() {
  runOnUiThread(new Runnable() {
   @Override
   public void run() {
    if (!loadingDialog.isShowing())
     loadingDialog.show();
   }
  });
 }

 private void hideLoading() {
  runOnUiThread(new Runnable() {
   @Override
   public void run() {
    if (loadingDialog.isShowing())
     loadingDialog.dismiss();
   }
  });
 }
}
</code>```

If I send a valid cookie ID this return a valid JSON object else a empty object.

I tried (unsuccessfully) to set default cookie handles like

CookieManager manager = new CookieManager();
 CookieHandler.setDefault(manager);

but I get a empty object.

How to put a valid cookie session ID to post request?

答:
You getting cookie (Session id) in Login response, Save cookie in sharedpreference or other db, and use that to send in request.

for getting cookie from login request

```<code> CustomStringRequest stringRequest = new CustomStringRequest(Request.Method.POST, SIGN_IN_URL,
                    new Response.Listener<CustomStringRequest.ResponseM>() {
                        @Override
                        public void onResponse(CustomStringRequest.ResponseM result) {

                            CookieManager cookieManage = new CookieManager();
                            CookieHandler.setDefault(cookieManage);

                            progressDialog.hide();
                            try {
                                //From here you will get headers
                                String sessionId = result.headers.get("Set-Cookie");
                                String responseString = result.response;

                                Log.e("session", sessionId);
                                Log.e("responseString", responseString);

                                JSONObject object = new JSONObject(responseString);
</code>```

CustomStringRequest class

```<code>public class CustomStringRequest extends Request<CustomStringRequest.ResponseM> {

    private Response.Listener<CustomStringRequest.ResponseM> mListener;

    public CustomStringRequest(int method, String url, Response.Listener<CustomStringRequest.ResponseM> responseListener, Response.ErrorListener listener) {
        super(method, url, listener);
        this.mListener = responseListener;
    }

    @Override
    protected void deliverResponse(ResponseM response) {
        this.mListener.onResponse(response);
    }

    @Override
    protected Response<ResponseM> parseNetworkResponse(NetworkResponse response) {
        String parsed;
        try {
            parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        } catch (UnsupportedEncodingException e) {
            parsed = new String(response.data);
        }

        ResponseM responseM = new ResponseM();
        responseM.headers = response.headers;
        responseM.response = parsed;

        return Response.success(responseM, HttpHeaderParser.parseCacheHeaders(response));
    }

    public static class ResponseM {
        public Map<String, String> headers;
        public String response;
    }

}
</code>```

set cookie when add request to server..

```<code>                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> headers = new HashMap<String, String>();

                    String session=sharedPreferences.getString("sessionId","");
                    headers.put("Cookie",session);
                    return headers;
                }
</code>```

Body:
So, i have this code to make a POST request with volley:

public class MainActivity extends AppCompatActivity {

 Button btnSearch;
 ProgressDialog loadingDialog;
 ListView lvResult;
 String session_id;
 RequestQueue queue;
 MyCookieManager myCookieManager;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  btnSearch = (Button) findViewById(R.id.btnSearch);
  lvResult = (ListView) findViewById(R.id.lvResult);
  loadingDialog = new ProgressDialog(MainActivity.this);
  loadingDialog.setMessage("Wait.\nLoading...");
  loadingDialog.setCancelable(false);
  myCookieManager = new MyCookieManager();

  requestCookie(); //FIRST CALL TO GET SESSION ID

  btnSearch.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
    showLoading();
    requestWithSomeHttpHeaders(); //CALL TO MAKE THE REQUEST WITH VALID SESSION ID
   }
  });

 }

 public void requestCookie() {
  queue = Volley.newRequestQueue(this);
  String url = "http://myurl.com/json/";

  StringRequest postRequest = new StringRequest(Request.Method.POST, url,
   new Response.Listener < String > () {
    @Override
    public void onResponse(String response) {
     //
     String x = myCookieManager.getCookieValue();
    }
   },
   new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
     Log.d("ERROR", "Error => " + error.toString());
     hideLoading();
    }
   }
  ) {
   @Override
   public byte[] getBody() throws AuthFailureError {
    String httpPostBody = "param1=XPTO&param2=XPTO";
    return httpPostBody.getBytes();
   }

   @Override
   public Map < String, String > getHeaders() throws AuthFailureError {
    Map <String, String> params = new HashMap < String, String > ();
    params.put("User-Agent", "Mozilla/5.0");
    params.put("Accept", "application/json, text/javascript, */*; q=0.01");
    params.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    //params.put("Set-Cookie", session_id);// + " _ga=GA1.3.1300076726.1496455105; _gid=GA1.3.1624400465.1496455105; _gat=1; _gali=AguardeButton");
    //"PHPSESSID=ra0nbm0l22gsnl6s4jo0qkqci1");
    return params;
   }

   protected Response <String> parseNetworkResponse(NetworkResponse response) {
    try {
     String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
     String header_response = String.valueOf(response.headers.values());
     int index1 = header_response.indexOf("PHPSESSID=");
     int index2 = header_response.indexOf("; path");
     //Log.e(Utils.tag, "error is : " + index1 + "::" + index2);
     session_id = header_response.substring(index1, index2);

     return Response.success(jsonString, HttpHeaderParser.parseCacheHeaders(response));
    } catch (UnsupportedEncodingException e) {
     return Response.error(new ParseError(e));
    }
   }
  };

  queue.add(postRequest);
 }

 public void requestWithSomeHttpHeaders() {
  queue = Volley.newRequestQueue(this);
  String url = "http://myurl.com/json/";

  StringRequest postRequest = new StringRequest(Request.Method.POST, url,
   new Response.Listener <String> () {
    @Override
    public void onResponse(String response) {
     Log.d("Response", response);
     String x = myCookieManager.getCookieValue();
     String status = "";

     try {
      JSONObject resultObject = new JSONObject(response);
      Log.d("JSON RESULT =>", resultObject.toString());
     } catch (JSONException e) {
      Toast.makeText(MainActivity.this, "Request Error", Toast.LENGTH_SHORT).show();
      e.printStackTrace();
     }

     hideLoading();
    }
   },
   new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
     Log.d("ERROR", "Error => " + error.toString());
     hideLoading();
    }
   }
  ) {
   @Override
   public byte[] getBody() throws AuthFailureError {
    String httpPostBody = "param1=XPTO&param2=XPTO";
    return httpPostBody.getBytes();
   }

   @Override
   public Map <String, String> getHeaders() throws AuthFailureError {
    Map <String, String> params = new HashMap <String, String> ();
    params.put("User-Agent", "Mozilla/5.0");
    params.put("Accept", "application/json, text/javascript, */*; q=0.01");
    params.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    params.put("Cookie", /*myCookieManager.getCookieValue()*/ session_id + "; _ga=GA1.3.1300076726.1496455105; _gid=GA1.3.1624400465.1496455105; _gat=1; _gali=AguardeButton");
    return params;
   }
  };

  queue.add(postRequest);
 }

 private void showLoading() {
  runOnUiThread(new Runnable() {
   @Override
   public void run() {
    if (!loadingDialog.isShowing())
     loadingDialog.show();
   }
  });
 }

 private void hideLoading() {
  runOnUiThread(new Runnable() {
   @Override
   public void run() {
    if (loadingDialog.isShowing())
     loadingDialog.dismiss();
   }
  });
 }
}

If I send a valid cookie ID this return a valid JSON object else a empty object.

I tried (unsuccessfully) to set default cookie handles like

CookieManager manager = new CookieManager();
 CookieHandler.setDefault(manager);

but I get a empty object.

How to put a valid cookie session ID to post request?

Body:
You getting cookie (Session id) in Login response, Save cookie in sharedpreference or other db, and use that to send in request.

for getting cookie from login request

 CustomStringRequest stringRequest = new CustomStringRequest(Request.Method.POST, SIGN_IN_URL,
                    new Response.Listener<CustomStringRequest.ResponseM>() {
                        @Override
                        public void onResponse(CustomStringRequest.ResponseM result) {

                            CookieManager cookieManage = new CookieManager();
                            CookieHandler.setDefault(cookieManage);

                            progressDialog.hide();
                            try {
                                //From here you will get headers
                                String sessionId = result.headers.get("Set-Cookie");
                                String responseString = result.response;

                                Log.e("session", sessionId);
                                Log.e("responseString", responseString);

                                JSONObject object = new JSONObject(responseString);

CustomStringRequest class

public class CustomStringRequest extends Request<CustomStringRequest.ResponseM> {

    private Response.Listener<CustomStringRequest.ResponseM> mListener;

    public CustomStringRequest(int method, String url, Response.Listener<CustomStringRequest.ResponseM> responseListener, Response.ErrorListener listener) {
        super(method, url, listener);
        this.mListener = responseListener;
    }

    @Override
    protected void deliverResponse(ResponseM response) {
        this.mListener.onResponse(response);
    }

    @Override
    protected Response<ResponseM> parseNetworkResponse(NetworkResponse response) {
        String parsed;
        try {
            parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        } catch (UnsupportedEncodingException e) {
            parsed = new String(response.data);
        }

        ResponseM responseM = new ResponseM();
        responseM.headers = response.headers;
        responseM.response = parsed;

        return Response.success(responseM, HttpHeaderParser.parseCacheHeaders(response));
    }

    public static class ResponseM {
        public Map<String, String> headers;
        public String response;
    }

}

set cookie when add request to server..

                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> headers = new HashMap<String, String>();

                    String session=sharedPreferences.getString("sessionId","");
                    headers.put("Cookie",session);
                    return headers;
                }