问:
python ax window content being automatically refreshed
Known bugs are when plots the window's plt.pause while the thread is multithreaded, and the other thread needs windows to draw points, causing the reaction to get stuck.

Is there any way to get the effect of plotting points in my window
displayed dynamically, that is, the point is drawn step by step.Or
other ways  allowing ax window content being automatically refreshed.

I think the main problem is caused by the command "plt.pause"

```<code>  #-*-coding:utf-8-*-
    from matplotlib.patches import Circle
    import matplotlib.pyplot as plt
    import xlrd
    import numpy as np
    from matplotlib.animation import FuncAnimation
    import matplotlib.ticker as mticker
    import cartopy.crs as ccrs
    from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
    import time
    from matplotlib.offsetbox import AnnotationBbox,OffsetImage
    from PIL import Image
    import random
    from time import ctime,sleep
    import threading
     #地图可视化
    fig=plt.figure(figsize=(20,10))
    ax = plt.axes(projection=ccrs.PlateCarree())
    ax.coastlines()
    ax.stock_img()
    gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
                      linewidth=2, color='gray', alpha=15, linestyle='--')
    gl.xlabels_top = False
    gl.ylabels_left = False
    gl.xlines = False
    gl.xlocator = mticker.FixedLocator([-180, -45, 0, 45, 180])
    gl.xformatter = LONGITUDE_FORMATTER
    gl.yformatter = LATITUDE_FORMATTER
    gl.xlabel_style = {'size': 15, 'color': 'gray'}
    gl.xlabel_style = {'color': 'red', 'weight': 'bold'}
    img=Image.open(r'E:\python_file\untitled\p.png')
    imagebox=OffsetImage(img,zoom=0.05)
    imagebox.image.axes=ax
    ab=AnnotationBbox(imagebox,[55,10],pad=0,frameon=False)
    ax.add_artist(ab)
    ac=AnnotationBbox(imagebox,[63,0],pad=0,frameon=False)
    ax.add_artist(ac)
    ad=AnnotationBbox(imagebox,[70,-10],pad=0,frameon=False)
    ax.add_artist(ad)
    #============================================#攻击
    tolerance=1
    x_m1,y_m1=random.randint(-180,180),random.randint(-90,90)
    v_m1=170
    x_m2,y_m2=random.randint(-180,180),random.randint(-90,90)
    v_m2=v_m1
    x_m3,y_m3=random.randint(-180,180),random.randint(-90,90)
    v_m3=v_m1
    x_m4,y_m4=55,10
    x_m5,y_m5=63,0
    x_m6,y_m6=70,-10

    class target():
        """docstring for target"""
        def __init__(self, x, y):

            self.x = x
            self.y = y
    target1=target(x_m4,y_m4)
    target2=target(x_m5,y_m5)
    target3=target(x_m6,y_m6)
    v=v_m1

    class missile(threading.Thread):

        """docstring for missile"""

        def __init__(self, x, y,name):
            super(missile,self).__init__()
            self.x = x
            self.y = y
            self.name=name
        def forward(self, v, target1):
            """docstring for forward"""
            if self.x < target1.x:
                alpha = np.arctan((target1.y - self.y) / (target1.x - self.x))
            elif self.x > target1.x:
                alpha = np.pi + np.arctan((target1.y - self.y) / (target1.x - self.x))
            elif self.x == target1.x and self.y < target1.y:
                alpha = np.pi / 2
            else:
                alpha = -np.pi / 2
            self.x = self.x + v * 0.01 * np.cos(alpha)
            self.y = self.y + v * 0.01 * np.sin(alpha)
            return self.x, self.y
        def distance(self, target1):
            """docstring for distance"""
            return np.sqrt((self.x - target1.x) ** 2 + (self.y - target1.y) ** 2)

        def run(self):

            while True:

                if self.distance(target1)<self.distance(target2) and self.distance(target1)<self.distance(target3):
                    if self.distance(target1)<tolerance:
                            print ("collision")

                            break
                    else:
                          self.x,self.y=self.forward(v,target1)

                if self.distance(target2)<self.distance(target1) and self.distance(target2)<self.distance(target3):
                    if self.distance(target2)<tolerance:
                            print ("collision")
                            break
                    else:
                          self.x,self.y=self.forward(v,target2)

                if self.distance(target3)<self.distance(target2) and self.distance(target3)<self.distance(target1):

                    if self.distance(target3)<tolerance:
                            print ("collision")

                            break
                    else:
                          self.x,self.y=self.forward(v,target3)
                print "qian jin"

                plt.plot(self.x, self.y, 'bx')
                print "ok2"
                plt.pause(0.1)#the commond
    m2=missile(x_m2,y_m2,'mm')
    m1=missile(x_m1,y_m1,'mn')
    m3=missile(x_m3,y_m3,'md')
    m1.start()
    m2.start()
    m3.start()
    plt.show()
</code>```

these are the all codes

答:
you could try </p>

```<code>fig.canvas.flush_events()
</code>```

<p>The reason for the plt.pause() is because when matplotlib plots it first generates the structure needed for the plot and then updates the screen. But if it continuously gets new data to plot it never updates the screen (to busy plotting). Therefore, pausing just a fraction of a second gives matplotlib time to update the screen. The flush_events function of the figure forces matplotlib to update the screen without the pause. </p>

Body:
Known bugs are when plots the window's plt.pause while the thread is multithreaded, and the other thread needs windows to draw points, causing the reaction to get stuck.

Is there any way to get the effect of plotting points in my window
displayed dynamically, that is, the point is drawn step by step.Or
other ways  allowing ax window content being automatically refreshed.

I think the main problem is caused by the command "plt.pause"

  #-*-coding:utf-8-*-
    from matplotlib.patches import Circle
    import matplotlib.pyplot as plt
    import xlrd
    import numpy as np
    from matplotlib.animation import FuncAnimation
    import matplotlib.ticker as mticker
    import cartopy.crs as ccrs
    from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
    import time
    from matplotlib.offsetbox import AnnotationBbox,OffsetImage
    from PIL import Image
    import random
    from time import ctime,sleep
    import threading
     #地图可视化
    fig=plt.figure(figsize=(20,10))
    ax = plt.axes(projection=ccrs.PlateCarree())
    ax.coastlines()
    ax.stock_img()
    gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True,
                      linewidth=2, color='gray', alpha=15, linestyle='--')
    gl.xlabels_top = False
    gl.ylabels_left = False
    gl.xlines = False
    gl.xlocator = mticker.FixedLocator([-180, -45, 0, 45, 180])
    gl.xformatter = LONGITUDE_FORMATTER
    gl.yformatter = LATITUDE_FORMATTER
    gl.xlabel_style = {'size': 15, 'color': 'gray'}
    gl.xlabel_style = {'color': 'red', 'weight': 'bold'}
    img=Image.open(r'E:\python_file\untitled\p.png')
    imagebox=OffsetImage(img,zoom=0.05)
    imagebox.image.axes=ax
    ab=AnnotationBbox(imagebox,[55,10],pad=0,frameon=False)
    ax.add_artist(ab)
    ac=AnnotationBbox(imagebox,[63,0],pad=0,frameon=False)
    ax.add_artist(ac)
    ad=AnnotationBbox(imagebox,[70,-10],pad=0,frameon=False)
    ax.add_artist(ad)
    #============================================#攻击
    tolerance=1
    x_m1,y_m1=random.randint(-180,180),random.randint(-90,90)
    v_m1=170
    x_m2,y_m2=random.randint(-180,180),random.randint(-90,90)
    v_m2=v_m1
    x_m3,y_m3=random.randint(-180,180),random.randint(-90,90)
    v_m3=v_m1
    x_m4,y_m4=55,10
    x_m5,y_m5=63,0
    x_m6,y_m6=70,-10

    class target():
        """docstring for target"""
        def __init__(self, x, y):

            self.x = x
            self.y = y
    target1=target(x_m4,y_m4)
    target2=target(x_m5,y_m5)
    target3=target(x_m6,y_m6)
    v=v_m1

    class missile(threading.Thread):

        """docstring for missile"""

        def __init__(self, x, y,name):
            super(missile,self).__init__()
            self.x = x
            self.y = y
            self.name=name
        def forward(self, v, target1):
            """docstring for forward"""
            if self.x < target1.x:
                alpha = np.arctan((target1.y - self.y) / (target1.x - self.x))
            elif self.x > target1.x:
                alpha = np.pi + np.arctan((target1.y - self.y) / (target1.x - self.x))
            elif self.x == target1.x and self.y < target1.y:
                alpha = np.pi / 2
            else:
                alpha = -np.pi / 2
            self.x = self.x + v * 0.01 * np.cos(alpha)
            self.y = self.y + v * 0.01 * np.sin(alpha)
            return self.x, self.y
        def distance(self, target1):
            """docstring for distance"""
            return np.sqrt((self.x - target1.x) ** 2 + (self.y - target1.y) ** 2)

        def run(self):

            while True:

                if self.distance(target1)<self.distance(target2) and self.distance(target1)<self.distance(target3):
                    if self.distance(target1)<tolerance:
                            print ("collision")

                            break
                    else:
                          self.x,self.y=self.forward(v,target1)

                if self.distance(target2)<self.distance(target1) and self.distance(target2)<self.distance(target3):
                    if self.distance(target2)<tolerance:
                            print ("collision")
                            break
                    else:
                          self.x,self.y=self.forward(v,target2)

                if self.distance(target3)<self.distance(target2) and self.distance(target3)<self.distance(target1):

                    if self.distance(target3)<tolerance:
                            print ("collision")

                            break
                    else:
                          self.x,self.y=self.forward(v,target3)
                print "qian jin"

                plt.plot(self.x, self.y, 'bx')
                print "ok2"
                plt.pause(0.1)#the commond
    m2=missile(x_m2,y_m2,'mm')
    m1=missile(x_m1,y_m1,'mn')
    m3=missile(x_m3,y_m3,'md')
    m1.start()
    m2.start()
    m3.start()
    plt.show()

these are the all codes

Body:
you could try

fig.canvas.flush_events()

The reason for the plt.pause() is because when matplotlib plots it first generates the structure needed for the plot and then updates the screen. But if it continuously gets new data to plot it never updates the screen (to busy plotting). Therefore, pausing just a fraction of a second gives matplotlib time to update the screen. The flush_events function of the figure forces matplotlib to update the screen without the pause.


来源: stackexchange

问:
Help with a SQL query
I have been trying different sql queries that do the following:

For all the table entries which have a field that has a field_value in clumn_a of table_1 which equals any field value in column_b of table_2 insert the id of the field in table_2 in id_of_the_other_entry_column of table_1.

However I can only use SQL and not use anything else than a SQL command for that. Is this even possible without the help of another programming language? If so.. any tips?

EDIT:
An example:

```<code>TableOwner
id  name
1   SomeCompany
2   SomeOtherCompany

TableContracts
Name               ownerid
NewCompany       Null --> Should remain null after the query
SomeCompany     Null -->Should change to 1 after the query
SomeCompany        Null -->Should change to 1 after the query
SomeOtherCompany   Null -->Should change to 2 after the query
</code>```

thanks

答:
```<code>UPDATE
    table_2
SET
    id_of_the_other_entry_column = t1.ID
FROM
    table_2 t2
INNER JOIN
    table_1 t1
ON
    t1.column_a = t2.column_b
</code>```

EDIT:

Just tried this with MySQL, without success.
With MySQL use:

```<code>UPDATE
    table_2 as t2
SET
    id_of_the_other_entry_column = (SELECT
                                        t1.ID
                                    FROM
                                        table_1 as t1
                                    WHERE
                                        t1.col_a = t2.col_b
                                    )</code>```

Importent:
If table_1 contains more then one row with table_1.col_a equal to table_2.col_b the command will abort.

ContentLicense: CC BY-SA 2.5

Title: Help with a SQL query

Body:
I have been trying different sql queries that do the following:

For all the table entries which have a field that has a field_value in clumn_a of table_1 which equals any field value in column_b of table_2 insert the id of the field in table_2 in id_of_the_other_entry_column of table_1.

However I can only use SQL and not use anything else than a SQL command for that. Is this even possible without the help of another programming language? If so.. any tips?

EDIT:
An example:

TableOwner
id  name
1   SomeCompany
2   SomeOtherCompany

TableContracts
Name               ownerid
NewCompany       Null --> Should remain null after the query
SomeCompany     Null -->Should change to 1 after the query
SomeCompany        Null -->Should change to 1 after the query
SomeOtherCompany   Null -->Should change to 2 after the query

thanks

Body:
UPDATE
    table_2
SET
    id_of_the_other_entry_column = t1.ID
FROM
    table_2 t2
INNER JOIN
    table_1 t1
ON
    t1.column_a = t2.column_b

EDIT:

Just tried this with MySQL, without success.
With MySQL use:

UPDATE
    table_2 as t2
SET
    id_of_the_other_entry_column = (SELECT
                                        t1.ID
                                    FROM
                                        table_1 as t1
                                    WHERE
                                        t1.col_a = t2.col_b
                                    )

Importent:
If table_1 contains more then one row with table_1.col_a equal to table_2.col_b the command will abort.


问:
DocumentDB querying child elements in a document
In the DocumentDB document below, what's the correct way to query on the DevicePin? ie WHERE DevicePin = '1234'
I'm using Node.js and have the basic query working, I can query on things like Email and Name, just can't get the syntax for the DevicePin correct</p>

```<code>{
    "id": "2ca572d0-858d-4376-8537-c228a8379638",
    "Email": "dave@test.com",
    "Name": "dave",
    "OrgRoles": null,
    "DeviceIDs": [
        {
            "DeviceID": "12121212",
            "DevicePin": "1234"
        }
    ],
    "UpdatedDate": "2017-11-10T13:18:32.0110724Z",
    "CreatedDate": "2017-11-10T13:18:27.220764Z",
    "IsDeleted": true,
    "_rid": "kIddAMqgTQBFAAAAAAAAAA==",
    "_self": "dbs/kIddAA==/colls/kIddAMqgTQA=/docs/kIddAMqgTQBFAAAAAAAAAA==/",
    "_etag": "\"02007530-0000-0000-0000-5a0d685b0000\"",
    "_attachments": "attachments/",
    "_ts": 1510828123
}
</code>```

答:
Got it, in case anyone else is looking to do this:</p>

```<code>SELECT *
FROM c.DeviceIDs[0] d
WHERE (d.DevicePin = "1234")
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In the DocumentDB document below, what's the correct way to query on the DevicePin? ie WHERE DevicePin = '1234'
I'm using Node.js and have the basic query working, I can query on things like Email and Name, just can't get the syntax for the DevicePin correct

{
    "id": "2ca572d0-858d-4376-8537-c228a8379638",
    "Email": "dave@test.com",
    "Name": "dave",
    "OrgRoles": null,
    "DeviceIDs": [
        {
            "DeviceID": "12121212",
            "DevicePin": "1234"
        }
    ],
    "UpdatedDate": "2017-11-10T13:18:32.0110724Z",
    "CreatedDate": "2017-11-10T13:18:27.220764Z",
    "IsDeleted": true,
    "_rid": "kIddAMqgTQBFAAAAAAAAAA==",
    "_self": "dbs/kIddAA==/colls/kIddAMqgTQA=/docs/kIddAMqgTQBFAAAAAAAAAA==/",
    "_etag": "\"02007530-0000-0000-0000-5a0d685b0000\"",
    "_attachments": "attachments/",
    "_ts": 1510828123
}

Body:
Got it, in case anyone else is looking to do this:

SELECT *
FROM c.DeviceIDs[0] d
WHERE (d.DevicePin = "1234")


问:
Change cipher suite in Elastic Beanstalk tomcat7
I need to enable one of both:

TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384

TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384

When I call a third party API I receive handshake exception.
In localhost I resolved it adding the JCE Package for Java 7 to enable newer cipher suites, but, in elastic beanstalk environment it didn't work and I received the same error.

Beanstalk configuration:
64bit Amazon Linux 2015.03 v1.4.3 running Tomcat 7 Java 7

I thought in change the server.xml and set Connector configs, but in localhost I didn't make this and work's fine.

Anybody have an ideia?

PS: Java 7 inside elastic beanstalk environment is open-jdk

答:
At first: in my opinion elastic beanstalk it's a sucks.
- have not a lot of support in foruns and community
- it's hard to understand lifecycles and hooks
- isn't immutable, persist files among deploys

I couldn't solve this problem in AWS.

I fixed this updating java 7 to java 8.


问:
Python: Storing Values in __return__ System Variable?
I was given a task to do in python, and have to "store an expression to the system variable __return__", then later return the value of __return__ in another function.

I understand what __return__ is, however, I am not sure of how one would "store" something to it for later use?

Should I ask for further clarification on the topic, or is there a way to do this?

答:
A system variable is a global variable that is accessible anywhere from your system.

In Windows, for example, you can see your system variables by pressing Winkey and then searching for Edit the system environment variables, and then clicking on the environment variables... button.
(Note: In Windows you can have separate variables for user and for the whole system).

In Linux, printenv in a terminal will print your environment variables.

Back to Python:
You can store said expression to the relevant system variable by using

```<code>import os
os.environ['__return__'] = some_expression
</code>```

And get the expression back by using

```<code>def foo():
    return os.environ['__return__']
</code>```

Body:
A system variable is a global variable that is accessible anywhere from your system.

In Windows, for example, you can see your system variables by pressing Winkey and then searching for Edit the system environment variables, and then clicking on the environment variables... button.
(Note: In Windows you can have separate variables for user and for the whole system).

In Linux, printenv in a terminal will print your environment variables.

Back to Python:
You can store said expression to the relevant system variable by using

import os
os.environ['__return__'] = some_expression

And get the expression back by using

def foo():
    return os.environ['__return__']


问:
How to add multiple strings with jQuery in HTML
First of all, I apologize if the question is too primal for this Q&A site. I am learning jQuery, and I need to create a countdown sort of display in which, instead of numbers, there will be strings. Like providing an array in jQuery and setting a div's innerHTML to the string, and changing its class.

答:
Do you need like the below code.

$(function () {
  count = 0;
  wordsArray = ["Hi", "How are you", "do you like this", "sample"];
  setInterval(function () {
    count++;
    $("#word").fadeOut(400, function () {
      $(this).text(wordsArray[count % wordsArray.length]).fadeIn(400);
    });
  }, 2000);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="word">Hello</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
Do you need like the below code.

$(function () {
  count = 0;
  wordsArray = ["Hi", "How are you", "do you like this", "sample"];
  setInterval(function () {
    count++;
    $("#word").fadeOut(400, function () {
      $(this).text(wordsArray[count % wordsArray.length]).fadeIn(400);
    });
  }, 2000);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="word">Hello</div>


问:
Verilog - re-using register value on always posedge
Consider the following code:

```<code>Module Test  (B, A, CLK)

Input A, CLK;
Output B;

Reg RA;

Always @(Posedge CLK)

Begin

RA=A;
B=RA;

End
EndModule
</code>```

Would that work properly to move the input to the register and then to the output on every positive edge? Can it be created with circuits?

答:
It depends what you are trying to do...

If you just want a single flip-flop, the simplest way is to declare reg B; then you can write always @(posedge CLK) B <= A;. There is no need for another signal.

If (for some style reason) you want to separate the flip-flop from the output, you can wire them together with a continuous assignment assign B = RA;. The circuit would be the same.

If you want two flip-flops (2-stage pipeline), your code is almost correct but remember to declare reg B; and use <= for both updates (they can be written in either order).

If RA is some sort of temporary variable for describing your intentions to the tools, then Yes; you can write to it with = and use its value in the same process (do not try to access it from any other process). This is occasionally useful for e.g. accumulating things in loops, but here it would just be confusing and error-prone!

To synthesize real hardware you would typically also have a reset signal and would need to use it in the proper way for each flip-flop.

Body:
Consider the following code:

Module Test  (B, A, CLK)

Input A, CLK;
Output B;

Reg RA;

Always @(Posedge CLK)

Begin

RA=A;
B=RA;

End
EndModule

Would that work properly to move the input to the register and then to the output on every positive edge? Can it be created with circuits?


问:
esp8266 on wifi serial board and Arduino Uno board
I bought esp8266 with serial wifi wifi card
I connect RX to TX; TX to RX; VCC to VCC; GRD to GRD;
I cant communicate with the board not if program mode and not in UART mode; the reset do nothing.

the red led on the board is on.

I connected the wifi serial to Arduino uno board.
try to upload sketch i got the following error:

```<code>warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
</code>```

Any help or guides will help me to solve the issue.

答: I had (too many/wrong) COM port(s). Find the right one and I't fine.</p>

Body:
I bought esp8266 with serial wifi wifi card
I connect RX to TX; TX to RX; VCC to VCC; GRD to GRD;
I cant communicate with the board not if program mode and not in UART mode; the reset do nothing.

the red led on the board is on.

I connected the wifi serial to Arduino uno board.
try to upload sketch i got the following error:

warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed

Any help or guides will help me to solve the issue.


问:
Nodejs server with Express not sending responses to HTTP requests from javascript file, but is receiving the requests and processing them
So I have a node-js server and an apache server on the same machine, and one of the javascript files is sending an HTTP request to the node-js server. The node-js server receives the file, reads the data, puts it in the database, as it should, but it isn't sending back any status codes or data.

Here is the XHTMLRequest send code snippet,

```<code>// creates a new http request to be sent to the nodejs server
function createNewUser(username, password, email) {

    // The url is the URL of our local nodejs server
    var userCreateRequest = new XMLHttpRequest();
    userCreateRequest.open( "POST", "http://<machine's IP>:8080/api/users" );

    // Create json object for user data
    var user = "name="+username+"&password="+password+"&email="+email;
    alert(user);

    // set content type for http request
    userCreateRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    // Event listern for server response
    // userCreateRequest.addEventListener("readystatechange", processRequest, false);

    // Call process request whenever state changes
    userCreateRequest.onreadystatechange = function() {
            alert(this.readyState + ", " + this.status);
            if (this.readyState == 4 && this.status == 200) {

                    var response = this.response;
                    alert(response.name);

            }

    }

    // Send user data to server
    userCreateRequest.send(user);

}
</code>```

And here is the code for the node-js server (with express)

```<code>router.route('/users')

    .post(function(req, res) { //create a new user

            var user = new User();

            user.name = req.body.name;
            user.password = req.body.password;
            user.email = req.body.email;

            user.save(function(err) { //add user object to database

                    if(err)
                            res.send(err);

                    res.status(200).json(user);

            });

    });
</code>```

As I said above, the code works fine in terms of putting the body of the request in the database and what-not, but the server is not sending back the 200 OK response (or I'm failing to receive it for some reason). The only times I get an alert from onreadystatechange is when it's state 2, status 0, and state 4, status 0.

答:
Try below code snippet.</p>

```<code>user.save(function(err, user) {

                if(err)
                        res.send(err);

                res.status(200).json(user);

        });
</code>```

Body:
So I have a node-js server and an apache server on the same machine, and one of the javascript files is sending an HTTP request to the node-js server. The node-js server receives the file, reads the data, puts it in the database, as it should, but it isn't sending back any status codes or data.

Here is the XHTMLRequest send code snippet,

// creates a new http request to be sent to the nodejs server
function createNewUser(username, password, email) {

    // The url is the URL of our local nodejs server
    var userCreateRequest = new XMLHttpRequest();
    userCreateRequest.open( "POST", "http://<machine's IP>:8080/api/users" );

    // Create json object for user data
    var user = "name="+username+"&password="+password+"&email="+email;
    alert(user);

    // set content type for http request
    userCreateRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    // Event listern for server response
    // userCreateRequest.addEventListener("readystatechange", processRequest, false);

    // Call process request whenever state changes
    userCreateRequest.onreadystatechange = function() {
            alert(this.readyState + ", " + this.status);
            if (this.readyState == 4 && this.status == 200) {

                    var response = this.response;
                    alert(response.name);

            }

    }

    // Send user data to server
    userCreateRequest.send(user);

}

And here is the code for the node-js server (with express)

router.route('/users')

    .post(function(req, res) { //create a new user

            var user = new User();

            user.name = req.body.name;
            user.password = req.body.password;
            user.email = req.body.email;

            user.save(function(err) { //add user object to database

                    if(err)
                            res.send(err);

                    res.status(200).json(user);

            });

    });

As I said above, the code works fine in terms of putting the body of the request in the database and what-not, but the server is not sending back the 200 OK response (or I'm failing to receive it for some reason). The only times I get an alert from onreadystatechange is when it's state 2, status 0, and state 4, status 0.

Body:
Try below code snippet.

user.save(function(err, user) {

                if(err)
                        res.send(err);

                res.status(200).json(user);

        });


问:
Firestore Paginating data + Snapshot listener
I am working with Firestore right now and have a little bit of a problem with pagination.

Basically, I have a collection (assume 10 items) where each item has some data and a timestamp.

Now, I am fetching the first 3 items like this:

```<code>Firestore.firestore()
    .collection("collectionPath")
    .order(by: "timestamp", descending: true)
    .limit(to: 3)
    .addSnapshotListener(snapshotListener())
</code>```

Inside my snapshot listener, I save the last document from the snapshot, in order to use that as a starting point for my next page.

So, at some time I will request the next page of items like this:

```<code>Firestore.firestore()
    .collection("collectionPath")
    .order(by: "timestamp", descending: true)
    .start(afterDocument: lastDocument)
    .limit(to: 3)
    .addSnapshotListener(snapshotListener2()) // Note that this is a new snapshot listener, I don't know how I could reuse the first one
</code>```

Now I have the items from index 0 to index 5 (in total 6) in my frontend. Neat!

If the document at index 4 now updates its timestamp to the newest timestamp of the whole collection, things start to go down.

Remember that the timestamp determines its position on account of the order clause!

What I expected to happen was, that after the changes are applied, I still show 6 items (and still ordered by their timestamps)

What happened was, that after the changes are applied, I have only 5 items remaining, since the item that got pushed out of the first snapshot is not added to the second snapshot automatically.

Am I missing something about Pagination with Firestore?

EDIT: As requested, I post some more code here:

This is my function to return a snapshot listener. Well, and the two methods I use to request the first page and then the second page I posted already above

```<code>private func snapshotListener() -> FIRQuerySnapshotBlock {
    let index = self.index
    return { querySnapshot, error in
        guard let snap = querySnapshot, error == nil else {
            log.error(error)
            return
        }

        // Save the last doc, so we can later use pagination to retrieve further chats
        if snap.count == self.limit {
            self.lastDoc = snap.documents.last
        } else {
            self.lastDoc = nil
        }

        let offset = index * self.limit

        snap.documentChanges.forEach() { diff in
            switch diff.type {
            case .added:
                log.debug("added chat at index: \(diff.newIndex), offset: \(offset)")
                self.tVHandler.dataManager.insert(item: Chat(dictionary: diff.document.data() as NSDictionary), at: IndexPath(row: Int(diff.newIndex) + offset, section: 0), in: nil)

            case .removed:
                log.debug("deleted chat at index: \(diff.oldIndex), offset: \(offset)")
                self.tVHandler.dataManager.remove(itemAt: IndexPath(row: Int(diff.oldIndex) + offset, section: 0), in: nil)

            case .modified:
                if diff.oldIndex == diff.newIndex {
                    log.debug("updated chat at index: \(diff.oldIndex), offset: \(offset)")
                    self.tVHandler.dataManager.update(item: Chat(dictionary: diff.document.data() as NSDictionary), at: IndexPath(row: Int(diff.oldIndex) + offset, section: 0), in: nil)
                } else {
                    log.debug("moved chat at index: \(diff.oldIndex), offset: \(offset) to index: \(diff.newIndex), offset: \(offset)")
                    self.tVHandler.dataManager.move(item: Chat(dictionary: diff.document.data() as NSDictionary), from: IndexPath(row: Int(diff.oldIndex) + offset, section: 0), to: IndexPath(row: Int(diff.newIndex) + offset, section: 0), in: nil)
                }
            }
        }
        self.tableView?.reloadData()
    }
}
</code>```

So again, I am asking if I can have one snapshot listener that listens for changes in more than one page I requested from Firestore

答:
Well, I contacted the guys over at Firebase Google Group for help, and they were able to tell me that my use case is not yet supported.

Thanks to Kato Richardson for attending to my problem!

For anyone interested in the details, see this thread

Body:
I am working with Firestore right now and have a little bit of a problem with pagination.

Basically, I have a collection (assume 10 items) where each item has some data and a timestamp.

Now, I am fetching the first 3 items like this:

Firestore.firestore()
    .collection("collectionPath")
    .order(by: "timestamp", descending: true)
    .limit(to: 3)
    .addSnapshotListener(snapshotListener())

Inside my snapshot listener, I save the last document from the snapshot, in order to use that as a starting point for my next page.

So, at some time I will request the next page of items like this:

Firestore.firestore()
    .collection("collectionPath")
    .order(by: "timestamp", descending: true)
    .start(afterDocument: lastDocument)
    .limit(to: 3)
    .addSnapshotListener(snapshotListener2()) // Note that this is a new snapshot listener, I don't know how I could reuse the first one

Now I have the items from index 0 to index 5 (in total 6) in my frontend. Neat!

If the document at index 4 now updates its timestamp to the newest timestamp of the whole collection, things start to go down.

Remember that the timestamp determines its position on account of the order clause!

What I expected to happen was, that after the changes are applied, I still show 6 items (and still ordered by their timestamps)

What happened was, that after the changes are applied, I have only 5 items remaining, since the item that got pushed out of the first snapshot is not added to the second snapshot automatically.

Am I missing something about Pagination with Firestore?

EDIT: As requested, I post some more code here:

This is my function to return a snapshot listener. Well, and the two methods I use to request the first page and then the second page I posted already above

private func snapshotListener() -> FIRQuerySnapshotBlock {
    let index = self.index
    return { querySnapshot, error in
        guard let snap = querySnapshot, error == nil else {
            log.error(error)
            return
        }

        // Save the last doc, so we can later use pagination to retrieve further chats
        if snap.count == self.limit {
            self.lastDoc = snap.documents.last
        } else {
            self.lastDoc = nil
        }

        let offset = index * self.limit

        snap.documentChanges.forEach() { diff in
            switch diff.type {
            case .added:
                log.debug("added chat at index: \(diff.newIndex), offset: \(offset)")
                self.tVHandler.dataManager.insert(item: Chat(dictionary: diff.document.data() as NSDictionary), at: IndexPath(row: Int(diff.newIndex) + offset, section: 0), in: nil)

            case .removed:
                log.debug("deleted chat at index: \(diff.oldIndex), offset: \(offset)")
                self.tVHandler.dataManager.remove(itemAt: IndexPath(row: Int(diff.oldIndex) + offset, section: 0), in: nil)

            case .modified:
                if diff.oldIndex == diff.newIndex {
                    log.debug("updated chat at index: \(diff.oldIndex), offset: \(offset)")
                    self.tVHandler.dataManager.update(item: Chat(dictionary: diff.document.data() as NSDictionary), at: IndexPath(row: Int(diff.oldIndex) + offset, section: 0), in: nil)
                } else {
                    log.debug("moved chat at index: \(diff.oldIndex), offset: \(offset) to index: \(diff.newIndex), offset: \(offset)")
                    self.tVHandler.dataManager.move(item: Chat(dictionary: diff.document.data() as NSDictionary), from: IndexPath(row: Int(diff.oldIndex) + offset, section: 0), to: IndexPath(row: Int(diff.newIndex) + offset, section: 0), in: nil)
                }
            }
        }
        self.tableView?.reloadData()
    }
}

So again, I am asking if I can have one snapshot listener that listens for changes in more than one page I requested from Firestore


问:
Android Studio 2.2 giving error while creating new project
I just updated my android studio to

Android Studio 2.2
Build #AI-145.3276617, built on September 15, 2016
JRE: 1.8.0_76-release-b03 x86_64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o

Now when I create a new project I am getting build error.

```<code>Error:Failed to resolve: javax.inject:javax.inject:1 <a href="open.dependency.in.project.structure">Show in Project Structure dialog</a>
</code>```

答:
this worked for me add the following code to the build.gradle:

```<code>repositories {
        maven { url "http://jcenter.bintray.com"}
        jcenter()
    }
</code>```

Body:
I just updated my android studio to

Android Studio 2.2
Build #AI-145.3276617, built on September 15, 2016
JRE: 1.8.0_76-release-b03 x86_64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o

Now when I create a new project I am getting build error.

Error:Failed to resolve: javax.inject:javax.inject:1 Show in Project Structure dialog

Body:
this worked for me add the following code to the build.gradle:

repositories {
        maven { url "http://jcenter.bintray.com"}
        jcenter()
    }


问:
Yii2 disable field
In yii2 I have two fields (Text1 and Text2). I want to disable the second field (Text2) if the first field (Text1) is not null.
I think this can be done with javascript but I dont't really know.
Can anybody help me?</p>

答:
```<code><script>

var textbox1 = document.getElementById("id1");
    textbox1.onkeyup = function(){
    value = document.getElementById("id1").value;
    if(value.length != 0){
     document.getElementById("id2").disabled = true;
    }
    else {
      document.getElementById("id2").disabled = false;
    }
 };

<script>
</code>```

Title: Yii2 disable field


问:
Unexpected namespace prefix "app" found for tag TextView when I try to set fontFamily attribute
I set app:fontFamily="@font/montserrat_bold" on TextView and i get error: Unexpected namespace prefix "app" found for tag TextView. I use Android Studio 3.0. Is there any solution?

答:
this is working for me

```<code><TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fontFamily="cursive"
        android:textSize="50sp"
        android:text="hhellloSDFSDF"/>
</code>```

Body:
this is working for me

<TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fontFamily="cursive"
        android:textSize="50sp"
        android:text="hhellloSDFSDF"/>


问:
asp.net Core mvc hide and exclude Web Api Controller Method
I know there is the ApiExplorerSettings attribute

```<code>[ApiExplorerSettings(IgnoreApi = true)]
public async Task<IActionResult> MyMethod(int id)
</code>```

But that does not stop a client of the api to call the endpoint method.

I need to know if there is an attribute that disables the endpoint and does not allow requests. I want to avoid doing it by modifying the routing mechanism.

答:
The simplest MVC approach might be to use the NonAction attribute, like so:

```<code>[ApiExplorerSettings(IgnoreApi = true)]
[NonAction]
public async Task<IActionResult> MyMethod(int id)
</code>```

Another option is to just change the method's access modifier from public to e.g. private for the same effect.

If you'd like to exclude an entire controller, there's the NonController attribute:

```<code>[NonController]
public class MyController : ControllerBase
</code>```

Body:
I know there is the ApiExplorerSettings attribute

[ApiExplorerSettings(IgnoreApi = true)]
public async Task<IActionResult> MyMethod(int id)

But that does not stop a client of the api to call the endpoint method.

I need to know if there is an attribute that disables the endpoint and does not allow requests. I want to avoid doing it by modifying the routing mechanism.

Body:
The simplest MVC approach might be to use the NonAction attribute, like so:

[ApiExplorerSettings(IgnoreApi = true)]
[NonAction]
public async Task<IActionResult> MyMethod(int id)

Another option is to just change the method's access modifier from public to e.g. private for the same effect.

If you'd like to exclude an entire controller, there's the NonController attribute:

[NonController]
public class MyController : ControllerBase


问:
ASP.net Core Web Application Template is missing
I am trying to follow this tutorial:  https://learn.microsoft.com/en-us/aspnet/core/tutorials/razor-pages/razor-pages-start

However, when I get to the Create a Razor Web App section, there is no template in my install of VS2017.

I have both the .net core and asp.net and web dev workloads installed.  Where have I gone wrong?

答:
Have you got the latest update for your Visual Studio installation?

Head to Add or Remove Programs

find Visual Studio

Click Modify

Allow the installer to update

Install any updates that are missing

On top of that, do you have the latest version of the .NET Core SDK?


问:
Average performance measurements for local IPC
We are now assessing different IPC (or rather RPC) methods for our current project, which is in its very early stages. Performance is a big deal, and so we are making some measurements to aid our choice. Our processes that will be communicating will reside on the same machine.

A separate valid option is to avoid IPC altogether (by encapsulating the features of one of the processes in a .NET DLL and having the other one use it), but this is an option we would really like to avoid, as these two pieces of software are developed by two separate companies and we find it very important to maintain good "fences", which make good neighbors.

Our tests consisted of passing messages (which contain variously sized BLOBs) across process boundaries using each method. These are the figures we get (performance range correlates with message size range):

Web Service (SOAP over HTTP):

25-30 MB/s when binary data is encoded as Base64 (default)

70-100 MB/s when MTOM is utilized

.NET Remoting (BinaryFormatter over TCP): 100-115 MB/s

Control group - DLL method call + mem copy: 800-1000 MB/s

Now, we've been looking all over the place for some average performance figures for these (and other) IPC methods, including performance of raw TCP loopback sockets, but couldn't find any. Do these figures look sane? Why is the performance of these local IPC methods at least 10 times slower than copying memory? I couldn't get better results even when I used raw sockets - is the overhead of TCP that big?

答:
Several parts of our system have been redesigned so that we don't have to pass 30MB messages around, but rather 3MB. This allowed us to choose .NET Remoting with BinaryFormatter over named pipes (IpcChannel), which gives satisfactory results.

Our contingency plan (in case we ever do need to pass 30MB messages around) is to pass protobuf-serialized messages over named pipes manually. We have determined that this also provides satisfactory results.


问:
Select random row(s) in SQLite
In MySQL, you can select X random rows with the following statement:

```<code>SELECT * FROM table ORDER BY RAND() LIMIT X
</code>```

This does not, however, work in SQLite. Is there an equivalent?

答:
All answers here are based on ORDER BY. This is very inefficient (i.e. unusable) for large sets because you will evaluate RANDOM() for each record, and then ORDER BY which is a resource expensive operation.

An other approach is to place abs(CAST(random() AS REAL))/9223372036854775808 < 0.5 in the WHERE clause to get in this case for example 0.5 hit chance.

```<code>SELECT *
FROM table
WHERE abs(CAST(random() AS REAL))/9223372036854775808 < 0.5
</code>```

The large number is the maximum absolute number that random() can produce. The abs() is because it is signed. Result is a uniformly distributed random variable between 0 and 1.

This has its drawbacks. You can not guarantee a result and if the threshold is large compared to the table, the selected data will be skewed towards the start of the table. But in some carefully designed situations, it can be a feasible option.

Title: Select random row(s) in SQLite

Body:
In MySQL, you can select X random rows with the following statement:

SELECT * FROM table ORDER BY RAND() LIMIT X

This does not, however, work in SQLite. Is there an equivalent?

Body:
All answers here are based on ORDER BY. This is very inefficient (i.e. unusable) for large sets because you will evaluate RANDOM() for each record, and then ORDER BY which is a resource expensive operation.

An other approach is to place abs(CAST(random() AS REAL))/9223372036854775808 < 0.5 in the WHERE clause to get in this case for example 0.5 hit chance.

SELECT *
FROM table
WHERE abs(CAST(random() AS REAL))/9223372036854775808 < 0.5

The large number is the maximum absolute number that random() can produce. The abs() is because it is signed. Result is a uniformly distributed random variable between 0 and 1.

This has its drawbacks. You can not guarantee a result and if the threshold is large compared to the table, the selected data will be skewed towards the start of the table. But in some carefully designed situations, it can be a feasible option.


问:
What are the NSURLErrorDomain error code descriptions?
This is my first experience of developing an iOS app. I am trying to POST some data using the Facebook graph API. I am constantly getting the following error:

The operation couldn’t be completed. (NSURLErrorDomain error 400.)

I cannot find the description of NSURLErrorDomain error codes. What do the 400 error code mean?

答:
IN SWIFT 3.
Here are the NSURLErrorDomain error codes description in a Swift 3 enum:
(copied from answer above and converted what i can).

```<code>enum NSURLError: Int {
    case unknown = -1
    case cancelled = -999
    case badURL = -1000
    case timedOut = -1001
    case unsupportedURL = -1002
    case cannotFindHost = -1003
    case cannotConnectToHost = -1004
    case connectionLost = -1005
    case lookupFailed = -1006
    case HTTPTooManyRedirects = -1007
    case resourceUnavailable = -1008
    case notConnectedToInternet = -1009
    case redirectToNonExistentLocation = -1010
    case badServerResponse = -1011
    case userCancelledAuthentication = -1012
    case userAuthenticationRequired = -1013
    case zeroByteResource = -1014
    case cannotDecodeRawData = -1015
    case cannotDecodeContentData = -1016
    case cannotParseResponse = -1017
    //case NSURLErrorAppTransportSecurityRequiresSecureConnection NS_ENUM_AVAILABLE(10_11, 9_0) = -1022
    case fileDoesNotExist = -1100
    case fileIsDirectory = -1101
    case noPermissionsToReadFile = -1102
    //case NSURLErrorDataLengthExceedsMaximum NS_ENUM_AVAILABLE(10_5, 2_0) =   -1103

    // SSL errors
    case secureConnectionFailed = -1200
    case serverCertificateHasBadDate = -1201
    case serverCertificateUntrusted = -1202
    case serverCertificateHasUnknownRoot = -1203
    case serverCertificateNotYetValid = -1204
    case clientCertificateRejected = -1205
    case clientCertificateRequired = -1206
    case cannotLoadFromNetwork = -2000

    // Download and file I/O errors
    case cannotCreateFile = -3000
    case cannotOpenFile = -3001
    case cannotCloseFile = -3002
    case cannotWriteToFile = -3003
    case cannotRemoveFile = -3004
    case cannotMoveFile = -3005
    case downloadDecodingFailedMidStream = -3006
    case downloadDecodingFailedToComplete = -3007

    /*
     case NSURLErrorInternationalRoamingOff NS_ENUM_AVAILABLE(10_7, 3_0) =         -1018
     case NSURLErrorCallIsActive NS_ENUM_AVAILABLE(10_7, 3_0) =                    -1019
     case NSURLErrorDataNotAllowed NS_ENUM_AVAILABLE(10_7, 3_0) =                  -1020
     case NSURLErrorRequestBodyStreamExhausted NS_ENUM_AVAILABLE(10_7, 3_0) =      -1021

     case NSURLErrorBackgroundSessionRequiresSharedContainer NS_ENUM_AVAILABLE(10_10, 8_0) = -995
     case NSURLErrorBackgroundSessionInUseByAnotherProcess NS_ENUM_AVAILABLE(10_10, 8_0) = -996
     case NSURLErrorBackgroundSessionWasDisconnected NS_ENUM_AVAILABLE(10_10, 8_0)= -997
     */
}
</code>```

Direct link to URLError.Code in the Swift github repository, which contains the up to date list of error codes being used (github link).

Body:
IN SWIFT 3.
Here are the NSURLErrorDomain error codes description in a Swift 3 enum:
(copied from answer above and converted what i can).

enum NSURLError: Int {
    case unknown = -1
    case cancelled = -999
    case badURL = -1000
    case timedOut = -1001
    case unsupportedURL = -1002
    case cannotFindHost = -1003
    case cannotConnectToHost = -1004
    case connectionLost = -1005
    case lookupFailed = -1006
    case HTTPTooManyRedirects = -1007
    case resourceUnavailable = -1008
    case notConnectedToInternet = -1009
    case redirectToNonExistentLocation = -1010
    case badServerResponse = -1011
    case userCancelledAuthentication = -1012
    case userAuthenticationRequired = -1013
    case zeroByteResource = -1014
    case cannotDecodeRawData = -1015
    case cannotDecodeContentData = -1016
    case cannotParseResponse = -1017
    //case NSURLErrorAppTransportSecurityRequiresSecureConnection NS_ENUM_AVAILABLE(10_11, 9_0) = -1022
    case fileDoesNotExist = -1100
    case fileIsDirectory = -1101
    case noPermissionsToReadFile = -1102
    //case NSURLErrorDataLengthExceedsMaximum NS_ENUM_AVAILABLE(10_5, 2_0) =   -1103

    // SSL errors
    case secureConnectionFailed = -1200
    case serverCertificateHasBadDate = -1201
    case serverCertificateUntrusted = -1202
    case serverCertificateHasUnknownRoot = -1203
    case serverCertificateNotYetValid = -1204
    case clientCertificateRejected = -1205
    case clientCertificateRequired = -1206
    case cannotLoadFromNetwork = -2000

    // Download and file I/O errors
    case cannotCreateFile = -3000
    case cannotOpenFile = -3001
    case cannotCloseFile = -3002
    case cannotWriteToFile = -3003
    case cannotRemoveFile = -3004
    case cannotMoveFile = -3005
    case downloadDecodingFailedMidStream = -3006
    case downloadDecodingFailedToComplete = -3007

    /*
     case NSURLErrorInternationalRoamingOff NS_ENUM_AVAILABLE(10_7, 3_0) =         -1018
     case NSURLErrorCallIsActive NS_ENUM_AVAILABLE(10_7, 3_0) =                    -1019
     case NSURLErrorDataNotAllowed NS_ENUM_AVAILABLE(10_7, 3_0) =                  -1020
     case NSURLErrorRequestBodyStreamExhausted NS_ENUM_AVAILABLE(10_7, 3_0) =      -1021

     case NSURLErrorBackgroundSessionRequiresSharedContainer NS_ENUM_AVAILABLE(10_10, 8_0) = -995
     case NSURLErrorBackgroundSessionInUseByAnotherProcess NS_ENUM_AVAILABLE(10_10, 8_0) = -996
     case NSURLErrorBackgroundSessionWasDisconnected NS_ENUM_AVAILABLE(10_10, 8_0)= -997
     */
}

Direct link to URLError.Code in the Swift github repository, which contains the up to date list of error codes being used (github link).


问:
Use from "php - $_GET[]" and "RewriteRule" in "htaccess" for "d.com" and "d.com/p/1"

Mode 1 :

URL: domain.com/?sv=g

.htaccess: RewriteRule ^page/([0-9]+)/$ fa/?page=$1

When I use from $_GET['sv'] return to me g.

Mode 2 :

URL: domain.com/page/1/?sv=g

.htaccess:  RewriteRule ^page/([0-9]+)/$ fa/?page=$1

When I use from $_GET['sv'] return to me null.

答:
.htaccess :

```<code>RewriteEngine On
RewriteRule ^page/([0-9]+)/$ fa/?page=$1 [QSA]
RewriteRule ^page/([0-9]+)$ fa/?page=$1 [QSA]
</code>```

Read this : https://httpd.apache.org/docs/2.4/rewrite/flags.html#flag_qsa

Body:
.htaccess :

RewriteEngine On
RewriteRule ^page/([0-9]+)/$ fa/?page=$1 [QSA]
RewriteRule ^page/([0-9]+)$ fa/?page=$1 [QSA]

Read this : https://httpd.apache.org/docs/2.4/rewrite/flags.html#flag_qsa


问:
Android Nougat 7.1.1 broadcastReceiver don't receive the action WifiManager.SCAN_RESULTS_AVAILABLE_ACTION
i am working on Nexus 5X android Nougat 7.1.1 on BroadCastReceiver with action WifiManager.SCAN_RESULTS_AVAILABLE_ACTION defined in AndroidManifests.xml, but is don't work properly, is works only when i opened the wifi settings page.

Note: Since i have updated the device version from 7.0.0 to 7.1.1 this happening with me , before that, everything was working properly.

WiifiBroadcastReceiver.java

```<code>public class WifiBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();

        if(action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
            List<ScanResult> wifiScanResult = new ArrayList<>();
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            if (wifiManager.isWifiEnabled()) {
               wifiScanResult = wifiManager.getScanResults();
            }
        }
    }
}
</code>```

AndroidManifests.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android.TestApp">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".LauncherActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".WifiBroadcastReceiver">
            <intent-filter>
                <action android:name="android.net.wifi.SCAN_RESULTS" />
            </intent-filter>
        </receiver>

    </application>

</manifest>
</code>```

答: You need to activate the GPS on your device.Then it will work.</p>

Body:
i am working on Nexus 5X android Nougat 7.1.1 on BroadCastReceiver with action WifiManager.SCAN_RESULTS_AVAILABLE_ACTION defined in AndroidManifests.xml, but is don't work properly, is works only when i opened the wifi settings page.

Note: Since i have updated the device version from 7.0.0 to 7.1.1 this happening with me , before that, everything was working properly.

WiifiBroadcastReceiver.java

public class WifiBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();

        if(action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
            List<ScanResult> wifiScanResult = new ArrayList<>();
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            if (wifiManager.isWifiEnabled()) {
               wifiScanResult = wifiManager.getScanResults();
            }
        }
    }
}

AndroidManifests.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android.TestApp">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".LauncherActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".WifiBroadcastReceiver">
            <intent-filter>
                <action android:name="android.net.wifi.SCAN_RESULTS" />
            </intent-filter>
        </receiver>

    </application>

</manifest>


问:
webpack-dev-server in Docker
I lifted docker file from

https://medium.com/@andyccs/webpack-and-docker-for-development-and-deployment-ae0e73243db4

```<code># Dockerfile (tag: v3)
FROM node:4.7

RUN npm install webpack -g

WORKDIR /webCode/
COPY package.json .
RUN npm config set registry http://registry.npmjs.org/ && npm install

WORKDIR /usr/src/app
COPY . /usr/src/app/
RUN cp -a /webCode/node_modules /usr/src/app/
RUN webpack

CMD npm run start
EXPOSE 8080
</code>```

I have "start": "webpack-dev-server --host 0.0.0.0" in my package.json file.

In the terminal it runs okay. However, when I use browser to connect to the localhost:8080 it shows refused to connect error.

Here is the what I got from docker run -t container

```<code>npm info it worked if it ends with ok
npm info using npm@2.15.11
npm info using node@v4.7.3
npm info prestart reactWeb@1.0.0
npm info start reactWeb@1.0.0

> reactWeb@1.0.0 start /usr/src/app
> webpack-dev-server --host 0.0.0.0

Project is running at http://0.0.0.0:8080/
webpack output is served from /
Hash: ecb5b52795042a7c522b
Version: webpack 2.7.0
Time: 10569ms
    Asset     Size  Chunks                    Chunk Names
bundle.js  5.12 MB       0  [emitted]  [big]  main
chunk    {0} bundle.js (main) 1.74 MB [entry] [rendered]
    [1] ./~/react/react.js 56 bytes {0} [built]
   [19] ./~/react-dom/index.js 59 bytes {0} [built]
   [49] ./~/react-redux/es/index.js 230 bytes {0} [built]
  [102] ./~/redux/es/index.js 1.08 kB {0} [built]
  [252] (webpack)-dev-server/client/overlay.js 3.73 kB {0} [built]
  [253] (webpack)-dev-server/client/socket.js 897 bytes {0} [built]
  [269] (webpack)-dev-server/~/strip-ansi/index.js 161 bytes {0} [built]
  [270] (webpack)/hot/emitter.js 77 bytes {0} [built]
  [271] (webpack)/~/node-libs-browser/~/url/url.js 23.3 kB {0} [built]
  [272] ./src/index.js 717 bytes {0} [built]
  [273] (webpack)-dev-server/client?http://0.0.0.0:8080 5.68 kB {0} [built]
  [274] (webpack)-dev-server/client?http://0.0.0.0:8080/ 5.68 kB {0} [built]
  [276] ./src/components/App.js 1.25 kB {0} [built]
  [285] ./src/reducer/index.js 927 bytes {0} [built]
  [621] multi (webpack)-dev-server/client?http://0.0.0.0:8080 webpack-dev-server/client?http://0.0.0.0:8080/ ./src 52 bytes {0} [built]
     + 607 hidden modules
webpack: Compiled successfully.
</code>```

In terminal when I run webpack-dev-server --host 0.0.0.0 it works fine.
I wonder why couldn't I view the homepage by run docker command.

答:
You forgot to map your port? Try</p>

```<code>docker run -p 8080:8080 your_image
</code>```

Title: webpack-dev-server in Docker

Body:
I lifted docker file from

https://medium.com/@andyccs/webpack-and-docker-for-development-and-deployment-ae0e73243db4

# Dockerfile (tag: v3)
FROM node:4.7

RUN npm install webpack -g

WORKDIR /webCode/
COPY package.json .
RUN npm config set registry http://registry.npmjs.org/ && npm install

WORKDIR /usr/src/app
COPY . /usr/src/app/
RUN cp -a /webCode/node_modules /usr/src/app/
RUN webpack

CMD npm run start
EXPOSE 8080

I have "start": "webpack-dev-server --host 0.0.0.0" in my package.json file.

In the terminal it runs okay. However, when I use browser to connect to the localhost:8080 it shows refused to connect error.

Here is the what I got from docker run -t container

npm info it worked if it ends with ok
npm info using npm@2.15.11
npm info using node@v4.7.3
npm info prestart reactWeb@1.0.0
npm info start reactWeb@1.0.0

> reactWeb@1.0.0 start /usr/src/app
> webpack-dev-server --host 0.0.0.0

Project is running at http://0.0.0.0:8080/
webpack output is served from /
Hash: ecb5b52795042a7c522b
Version: webpack 2.7.0
Time: 10569ms
    Asset     Size  Chunks                    Chunk Names
bundle.js  5.12 MB       0  [emitted]  [big]  main
chunk    {0} bundle.js (main) 1.74 MB [entry] [rendered]
    [1] ./~/react/react.js 56 bytes {0} [built]
   [19] ./~/react-dom/index.js 59 bytes {0} [built]
   [49] ./~/react-redux/es/index.js 230 bytes {0} [built]
  [102] ./~/redux/es/index.js 1.08 kB {0} [built]
  [252] (webpack)-dev-server/client/overlay.js 3.73 kB {0} [built]
  [253] (webpack)-dev-server/client/socket.js 897 bytes {0} [built]
  [269] (webpack)-dev-server/~/strip-ansi/index.js 161 bytes {0} [built]
  [270] (webpack)/hot/emitter.js 77 bytes {0} [built]
  [271] (webpack)/~/node-libs-browser/~/url/url.js 23.3 kB {0} [built]
  [272] ./src/index.js 717 bytes {0} [built]
  [273] (webpack)-dev-server/client?http://0.0.0.0:8080 5.68 kB {0} [built]
  [274] (webpack)-dev-server/client?http://0.0.0.0:8080/ 5.68 kB {0} [built]
  [276] ./src/components/App.js 1.25 kB {0} [built]
  [285] ./src/reducer/index.js 927 bytes {0} [built]
  [621] multi (webpack)-dev-server/client?http://0.0.0.0:8080 webpack-dev-server/client?http://0.0.0.0:8080/ ./src 52 bytes {0} [built]
     + 607 hidden modules
webpack: Compiled successfully.

In terminal when I run webpack-dev-server --host 0.0.0.0 it works fine.
I wonder why couldn't I view the homepage by run docker command.

Body:
You forgot to map your port? Try

docker run -p 8080:8080 your_image


问:
NSNotification addObserver:someOtherClass
I need to pass a message up to a controlling class (which creates an instance of the class which will be sending the message) So, I cannot directly reference the class name in my file, without either making it a Global (which is ridiculous to do if "NSNotification" advertises to be able to pass all kinds of messages, regardless of where / what class they are.

So without further ado...

(calling from Say ClassB)

ClassA creates instance of ClassB

Now in ClassB, I need to pass messages regarding button presses back up to ClassA

```<code>(insdie ClassB)
- (void)viewDidLoad
{
  [[NSNotificationCenter defaultCenter] addObserver:ClassA
                                        selector:@selector(doLoginAction)
                                        name:@"SomeButton"
                                        object:nil];
  [super viewDidLoad];
}
</code>```

This will NOT compile, even when I include, sorry, "#import "ClassA.h"
Now if I do something stupid like,

```<code>ClassA *classa = [[ClassA alloc]init];
</code>```

and then use this Newly created instance of classa in addObserver:classa it will compile, but as I thought, will do absolutely nothing... (I knew that, but surprisingly this kind of code is prevalent in Iphone programming books...) So I tried it anyway.

But if I put this function in ClassA and use addObserver:ClassB
it will get called, but will cause a stack dump unrecognized selector sent to instance
or use addObserver:self.

I am tempted to delete Xcode and go back to vim and use a good old "C" callback...

答:
I see a couple of problems here.

First you need to stop trying to use classes and instances interchangeably. Until you have a reasonable mental model of what your classes and instances represent and what they are responsible for you're going to have all sorts of confusion around when to use which one and OOP in general.

NSNotificationCenter allows you to register a specific instance of a class, a single object, as an observer of particular notifications. You need to be aware of, and have a reference to, the observing object in order to register it as an observer.

Secondly you need to consider what each of your classes, and therefor their instantiated objects are responsible for. What they should know, what they do not need to know, and how they can communicate.

Let's assume you create ObjectA as an instance of ClassA and it creates ObjectB which is an instance of ClassB. Now ObjectA is aware of ObjectB, after all A just created B so it is easy for A to have a reference to B. ObjectB is not yet aware of ObjectA; B was created but it need not know by which object or even what class that object was an instance of. If you want ObjectB to be able to communicate with ObjectA you have a couple of options.

Delegation: ObjectA sets a property on ObjectB to point back to ObjectA, now B can send messages to A directly. Now your two objects are coupled together which can be both useful and problematic.

Notifications: ObjectB can post notifications, ObjectA can observe notifications. B does not need to know that A is observing those notifications and A does not need to know that the notifications originated with B (though it could). These objects are very loosely coupled and you could change many things about your application without them ever being aware of it.

Importantly, if ObjectA is to listen for notifications then it is A's responsibility to add itself as an observer. Since B is not aware of A there's no way B can make A an observer. A's creator could since that object would have a reference to A but A's children cannot unless they were given some reference to A.

Looks like Alex chimed in with an excellent answer so hopefully this will all be useful.

Body:
I need to pass a message up to a controlling class (which creates an instance of the class which will be sending the message) So, I cannot directly reference the class name in my file, without either making it a Global (which is ridiculous to do if "NSNotification" advertises to be able to pass all kinds of messages, regardless of where / what class they are.

So without further ado...

(calling from Say ClassB)

ClassA creates instance of ClassB

Now in ClassB, I need to pass messages regarding button presses back up to ClassA

(insdie ClassB)
- (void)viewDidLoad
{
  [[NSNotificationCenter defaultCenter] addObserver:ClassA
                                        selector:@selector(doLoginAction)
                                        name:@"SomeButton"
                                        object:nil];
  [super viewDidLoad];
}

This will NOT compile, even when I include, sorry, "#import "ClassA.h"
Now if I do something stupid like,

ClassA *classa = [[ClassA alloc]init];

and then use this Newly created instance of classa in addObserver:classa it will compile, but as I thought, will do absolutely nothing... (I knew that, but surprisingly this kind of code is prevalent in Iphone programming books...) So I tried it anyway.

But if I put this function in ClassA and use addObserver:ClassB
it will get called, but will cause a stack dump unrecognized selector sent to instance
or use addObserver:self.

I am tempted to delete Xcode and go back to vim and use a good old "C" callback...


问:
python update a list of dictionaries using another list of the same length
I am trying to update a list a of dictionaries using another list b of the same length that each dict should add a key which corresponds to a value in b at the same position,

```<code>for x in range(len(a)):
    a[x]['val'] = b[x]
</code>```

I am wondering is there a more efficient/concise way to do it

答:
Could try using zip():

```<code>for ai, bi in zip(a, b):
    ai["val"] = bi
</code>```

Body:
I am trying to update a list a of dictionaries using another list b of the same length that each dict should add a key which corresponds to a value in b at the same position,

for x in range(len(a)):
    a[x]['val'] = b[x]

I am wondering is there a more efficient/concise way to do it

Body:
Could try using zip():

for ai, bi in zip(a, b):
    ai["val"] = bi


问:
Response code 500 in JMeter when running with threads
Getting the following error in JMeter while running the list of APIs (with no of threads:1-140 with ramp up period-1).

```<code>Response code:500
Response message: Internal Server Error
</code>```

How should I overcome this Error Response code in order to get the accurate response?
What should do to decrease amount of response with this response code?

答:
The general advice in JMeter is Ramp-up = number of threads, in your case 140

Start with Ramp-up = number of threads and adjust up or down as needed.

Currently you are sending every 1/140 seconds new thread which is almost simultaneously, the reason to the change is:

Ramp-up needs to be long enough to avoid too large a work-load at the start of a test

Body:
Getting the following error in JMeter while running the list of APIs (with no of threads:1-140 with ramp up period-1).

Response code:500
Response message: Internal Server Error

How should I overcome this Error Response code in order to get the accurate response?
What should do to decrease amount of response with this response code?


问:
React Native Get battery status / level Using Native Modules
I am writing a react native app to get IOS and Android Battery status. I search through the net and found few libraries which can get battery level of the phone.

https://github.com/robinpowered/react-native-device-battery

https://github.com/remobile/react-native-battery-status

https://github.com/oojr/react-native-battery

Every library has issues when I try that and not much support for the developer when ask a question on git hub.

Can any one provide me better solution or library to get Battery status of IOS and Android.

Thanks in advance

答:
I wrote my own IOS and Android classes to get the Battery Status. Here are the steps if any one interested on that,

For IOS,

Open the iOS project in XCode

Create 2 new files call BatteryStatus.h and BatteryStatus.m

BatteryStatus.h file should contain following code

```<code>#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>

@interface BatteryStatus : RCTEventEmitter <RCTBridgeModule>
@end
</code>```

BatteryStatus.m file should

```<code>#import "BatteryStatus.h"

@implementation BatteryStatus
RCT_EXPORT_MODULE(BatteryStatus)

- (instancetype)init
{
 if ((self = [super init])) {

   [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];

 }
 return self;
}

RCT_EXPORT_METHOD(hide) {
}

RCT_EXPORT_METHOD(updateBatteryLevel:(RCTResponseSenderBlock)callback)
{
 callback(@[[self getBatteryStatus]]);
}

 //manually get battery status by calling following method

-(NSDictionary*)getBatteryStatus
{

 float batteryLevel = [UIDevice currentDevice].batteryLevel;

 NSObject* currentLevel = nil;

 currentLevel = [NSNumber numberWithFloat:(batteryLevel * 100)];

 NSMutableDictionary* batteryData = [NSMutableDictionary dictionaryWithCapacity:2];

 [batteryData setObject:currentLevel forKey:@"level"];
 return batteryData;

  }

@end
</code>```

Inside your react native app, inside your js file add following code

```<code>import { NativeModules } from 'react-native';

constructor(props) {
 super(props);
 this.state = {
 batteryLevel: null,
 };
}

componentDidMount() {
  NativeModules.BatteryStatus.updateBatteryLevel((info) => {
  //console.log(info.level)
  const level = Math.ceil(info.level);
  this.setState({ batteryLevel: level});
  });
}
</code>```

For IOS above code is working for me to get the battery level

For Android,

Open the Android project in Android Studio

Create a group call BatteryStatus and include 2 Files named , BatteryStatusModule.java and BatteryStatusPackage.java

BatteryStatusModule.java Should contain following code

```<code>package com.yourproject.BatteryStatus;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;

import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

public class BatteryStatusModule extends ReactContextBaseJavaModule  {
     public BatteryStatusModule(ReactApplicationContext reactContext) {

         super(reactContext);
     }

     @Override
     public String getName() {
    return "BatteryStatus";
}

@ReactMethod
public void getBatteryStatus(Callback successCallback) {
    Intent batteryIntent = getCurrentActivity().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

    if(level == -1 || scale == -1) {
        level = 0;
    }
    //System.out.print("battery level");
    //System.out.print(level);
    successCallback.invoke(null ,((float)level / (float)scale) * 100.0f);
    }
 }
</code>```

BatteryStatusPackage.java should contain following code

```<code> package com.yourproject.BatteryStatus;

 import com.facebook.react.ReactPackage;
 import com.facebook.react.bridge.JavaScriptModule;
 import com.facebook.react.bridge.NativeModule;
 import com.facebook.react.bridge.ReactApplicationContext;
 import com.facebook.react.uimanager.ViewManager;

 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;

 public class BatteryStatusPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
    List<NativeModule> modules = new ArrayList<>();

    modules.add(new BatteryStatusModule(reactContext));

    return modules;
}

@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
    return Collections.emptyList();
}

@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
    return Collections.emptyList();
}
}
</code>```

Inside MainApplication.java include following code

```<code>@Override
protected List<ReactPackage> getPackages() {
  return Arrays.<ReactPackage>asList(
      new MainReactPackage(),
        new MapsPackage(),
        new BatteryStatusPackage()
  );
}
</code>```

Inside your react native app, inside your js file add following code

```<code> import { NativeModules } from 'react-native';

 constructor(props) {
 super(props);

 this.state = {
   batteryLevel: null
 };
}

getBatteryLevel = (callback) => {
   NativeModules.BatteryStatus.getBatteryStatus(callback);
}
</code>```

6.Call it something like this:

```<code>componentDidMount() {
 this.getBatteryLevel((batteryLevel) => {
   console.log(batteryLevel);
 });
}
</code>```

For Android above code is working for me to get the battery level

Hope this will help some one to get battery level for IOS and ANDROID

Body:
I wrote my own IOS and Android classes to get the Battery Status. Here are the steps if any one interested on that,

For IOS,

Open the iOS project in XCode

Create 2 new files call BatteryStatus.h and BatteryStatus.m

BatteryStatus.h file should contain following code

#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTEventEmitter.h>

@interface BatteryStatus : RCTEventEmitter <RCTBridgeModule>
@end

BatteryStatus.m file should

#import "BatteryStatus.h"

@implementation BatteryStatus
RCT_EXPORT_MODULE(BatteryStatus)

- (instancetype)init
{
 if ((self = [super init])) {

   [[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];

 }
 return self;
}

RCT_EXPORT_METHOD(hide) {
}

RCT_EXPORT_METHOD(updateBatteryLevel:(RCTResponseSenderBlock)callback)
{
 callback(@[[self getBatteryStatus]]);
}

 //manually get battery status by calling following method

-(NSDictionary*)getBatteryStatus
{

 float batteryLevel = [UIDevice currentDevice].batteryLevel;

 NSObject* currentLevel = nil;

 currentLevel = [NSNumber numberWithFloat:(batteryLevel * 100)];

 NSMutableDictionary* batteryData = [NSMutableDictionary dictionaryWithCapacity:2];

 [batteryData setObject:currentLevel forKey:@"level"];
 return batteryData;

  }

@end

Inside your react native app, inside your js file add following code

import { NativeModules } from 'react-native';

constructor(props) {
 super(props);
 this.state = {
 batteryLevel: null,
 };
}

componentDidMount() {
  NativeModules.BatteryStatus.updateBatteryLevel((info) => {
  //console.log(info.level)
  const level = Math.ceil(info.level);
  this.setState({ batteryLevel: level});
  });
}

For IOS above code is working for me to get the battery level

For Android,

Open the Android project in Android Studio

Create a group call BatteryStatus and include 2 Files named , BatteryStatusModule.java and BatteryStatusPackage.java

BatteryStatusModule.java Should contain following code

package com.yourproject.BatteryStatus;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;

import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

public class BatteryStatusModule extends ReactContextBaseJavaModule  {
     public BatteryStatusModule(ReactApplicationContext reactContext) {

         super(reactContext);
     }

     @Override
     public String getName() {
    return "BatteryStatus";
}

@ReactMethod
public void getBatteryStatus(Callback successCallback) {
    Intent batteryIntent = getCurrentActivity().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

    if(level == -1 || scale == -1) {
        level = 0;
    }
    //System.out.print("battery level");
    //System.out.print(level);
    successCallback.invoke(null ,((float)level / (float)scale) * 100.0f);
    }
 }

BatteryStatusPackage.java should contain following code

 package com.yourproject.BatteryStatus;

 import com.facebook.react.ReactPackage;
 import com.facebook.react.bridge.JavaScriptModule;
 import com.facebook.react.bridge.NativeModule;
 import com.facebook.react.bridge.ReactApplicationContext;
 import com.facebook.react.uimanager.ViewManager;

 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;

 public class BatteryStatusPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
    List<NativeModule> modules = new ArrayList<>();

    modules.add(new BatteryStatusModule(reactContext));

    return modules;
}

@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
    return Collections.emptyList();
}

@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
    return Collections.emptyList();
}
}

Inside MainApplication.java include following code

@Override
protected List<ReactPackage> getPackages() {
  return Arrays.<ReactPackage>asList(
      new MainReactPackage(),
        new MapsPackage(),
        new BatteryStatusPackage()
  );
}

Inside your react native app, inside your js file add following code

 import { NativeModules } from 'react-native';

 constructor(props) {
 super(props);

 this.state = {
   batteryLevel: null
 };
}

getBatteryLevel = (callback) => {
   NativeModules.BatteryStatus.getBatteryStatus(callback);
}

6.Call it something like this:

componentDidMount() {
 this.getBatteryLevel((batteryLevel) => {
   console.log(batteryLevel);
 });
}

For Android above code is working for me to get the battery level

Hope this will help some one to get battery level for IOS and ANDROID


问:
Is a signal sent with kill to a parent thread guaranteed to be processed before the next statement?
Okay, so if I'm running in a child thread on linux (using pthreads if that matters), and I run the following command

```<code>kill(getpid(), someSignal);
</code>```

it will send the given signal to the parent of the current thread.

My question: Is it guaranteed that the parent will then immediately get the CPU and process the signal (killing the app if it's a SIGKILL or doing whatever else if it's some other signal) before the statement following kill() is run? Or is it possible - even probable - that whatever command follows kill() will run before the signal is processed by the parent thread?

答:
Signals sent to a process (thread group) may generally get delivered to any thread, and you generally have no guarantee that the handler will have finished before the kill call returns.

If you run

```<code>kill(getpid(), someSignal);
</code>```

in a multithreaded process then you can only be sure that your sighandler will run before kill returns in a very specific scenario, where
all but the calling threads have someSignal blocked (in which case, the sig handler will run from the thread calling kill).

See
http://pubs.opengroup.org/onlinepubs/009695399/functions/kill.html :

If the value of pid causes sig to be generated for the sending
  process, and if sig is not blocked for the calling thread and if no
  other thread has sig unblocked or is waiting in a sigwait() function
  for sig, either sig or at least one pending unblocked signal shall be
  delivered to the sending thread before kill() returns.

Body:
Okay, so if I'm running in a child thread on linux (using pthreads if that matters), and I run the following command

kill(getpid(), someSignal);

it will send the given signal to the parent of the current thread.

My question: Is it guaranteed that the parent will then immediately get the CPU and process the signal (killing the app if it's a SIGKILL or doing whatever else if it's some other signal) before the statement following kill() is run? Or is it possible - even probable - that whatever command follows kill() will run before the signal is processed by the parent thread?

Body:
Signals sent to a process (thread group) may generally get delivered to any thread, and you generally have no guarantee that the handler will have finished before the kill call returns.

If you run

kill(getpid(), someSignal);

in a multithreaded process then you can only be sure that your sighandler will run before kill returns in a very specific scenario, where
all but the calling threads have someSignal blocked (in which case, the sig handler will run from the thread calling kill).

See
http://pubs.opengroup.org/onlinepubs/009695399/functions/kill.html :

If the value of pid causes sig to be generated for the sending
  process, and if sig is not blocked for the calling thread and if no
  other thread has sig unblocked or is waiting in a sigwait() function
  for sig, either sig or at least one pending unblocked signal shall be
  delivered to the sending thread before kill() returns.


问:
Multiple Languages for your app?
I am using the ionic framework with Ionic Creator.

Is it possible to have all my text referenced to any String file. And this file can be different for each language so that i can change my displayed language dynamically?

Thanks

答:
This is my working Example clone from github.
Github Repo</p>

Title: Multiple Languages for your app?


问:
dotnet publish with gitlab-ci for dummies
I am trying to setup ci with gitlab-ci. And I have a few questions about it.

It looks like there is no rollback mechanism on gitlab-ci. So should i care about rolling back if deploy stage fails?

I'am planning to use "dotnet publish Solution.sln -c release" script. But I have multiple projects in this solution. It has one classlib and 2 api. (like AdminApi and UserApi). And these 2 apis are hosted different sites in IIS. In this case, how can i configure dotnet publish script with params?

Should i use something like xcopy for moving publish output to iis folder?

答:
I've put an app_offile.htm_for each web sites in iis with "We'll back soon message" in html.

And I've solved my problem with this gitlab-ci.yml

```<code>stages:
    - build
    - test
    - deploy
build:
    stage: build
    script:
        - echo "Building the app"
        - "dotnet publish MySolution.sln -c release"
    artifacts:
        untracked: true
    only:
        - dev
test:
    stage: test
    script: echo "Running tests"
    artifacts:
        untracked: true
    dependencies:
        - build
    only:
        - dev
deploy_staging:
    stage: deploy
    script:
        - echo "Deployintg to staging server Admin"
        - ren c:\\inetpub\\vhosts\\xxx\\admin\\app_offline.htm_ app_offline.htm
        - dotnet publish PathToAdmin.csproj -c release -o c:\\inetpub\\vhosts\\xxx\\admin
        - ren c:\\inetpub\\vhosts\\xxx\\admin\\app_offline.htm app_offline.htm_
        - echo "Deployintg to staging server User"
        - ren c:\\inetpub\\vhosts\\xxx\\user\\app_offline.htm_ app_offline.htm
        - dotnet publish PathToUser.csproj -c release -o c:\\inetpub\\vhosts\\xxx\\user
        - ren c:\\inetpub\\vhosts\\xxx\\user\\app_offline.htm app_offline.htm_
    dependencies:
        - build
    only:
        - dev
</code>```

Body:
I've put an app_offile.htm_for each web sites in iis with "We'll back soon message" in html.

And I've solved my problem with this gitlab-ci.yml

stages:
    - build
    - test
    - deploy
build:
    stage: build
    script:
        - echo "Building the app"
        - "dotnet publish MySolution.sln -c release"
    artifacts:
        untracked: true
    only:
        - dev
test:
    stage: test
    script: echo "Running tests"
    artifacts:
        untracked: true
    dependencies:
        - build
    only:
        - dev
deploy_staging:
    stage: deploy
    script:
        - echo "Deployintg to staging server Admin"
        - ren c:\\inetpub\\vhosts\\xxx\\admin\\app_offline.htm_ app_offline.htm
        - dotnet publish PathToAdmin.csproj -c release -o c:\\inetpub\\vhosts\\xxx\\admin
        - ren c:\\inetpub\\vhosts\\xxx\\admin\\app_offline.htm app_offline.htm_
        - echo "Deployintg to staging server User"
        - ren c:\\inetpub\\vhosts\\xxx\\user\\app_offline.htm_ app_offline.htm
        - dotnet publish PathToUser.csproj -c release -o c:\\inetpub\\vhosts\\xxx\\user
        - ren c:\\inetpub\\vhosts\\xxx\\user\\app_offline.htm app_offline.htm_
    dependencies:
        - build
    only:
        - dev


问:
compare two arrays for common Items and return another array with the common items
So the problem is I have two array and have to check them for common items.Usual stuff, very easy.But the tricky thing for me is that I have to return another array with the elements that have been found to be common.I cannot not use any Collections.Thanks in advance.This is my code so far!</p>

```<code>public class checkArrayItems {
    static int[] array1 = { 4, 5, 6, 7, 8 };
    static int[] array2 = { 1, 2, 3, 4, 5 };

    public static void main(String[] args) {
        checkArrayItems obj = new checkArrayItems();
        System.out.println(obj.checkArr(array1, array2));

    }

    int[] checkArr(int[] arr1, int[] arr2) {
        int[] arr = new int[array1.length];
        for (int i = 0; i < arr1.length; i++) {
            for (int j = 0; j < arr2.length; j++) {
                if (arr1[i] == arr2[j]) {
                    arr[i] = arr1[i];
                }

            }
        }
        return arr;

    }

}
</code>```

答:
Declare an index before the two for loops

```<code>int index = 0;
</code>```

that will hold the current position of the arr array. Then:

```<code>arr[index++] = arr1[i];
</code>```

And also, since you initialize arr with arr1.lenght your array will be filled with 0s at the end of the not colision.

Body:
So the problem is I have two array and have to check them for common items.Usual stuff, very easy.But the tricky thing for me is that I have to return another array with the elements that have been found to be common.I cannot not use any Collections.Thanks in advance.This is my code so far!

public class checkArrayItems {
    static int[] array1 = { 4, 5, 6, 7, 8 };
    static int[] array2 = { 1, 2, 3, 4, 5 };

    public static void main(String[] args) {
        checkArrayItems obj = new checkArrayItems();
        System.out.println(obj.checkArr(array1, array2));

    }

    int[] checkArr(int[] arr1, int[] arr2) {
        int[] arr = new int[array1.length];
        for (int i = 0; i < arr1.length; i++) {
            for (int j = 0; j < arr2.length; j++) {
                if (arr1[i] == arr2[j]) {
                    arr[i] = arr1[i];
                }

            }
        }
        return arr;

    }

}

Body:
Declare an index before the two for loops

int index = 0;

that will hold the current position of the arr array. Then:

arr[index++] = arr1[i];

And also, since you initialize arr with arr1.lenght your array will be filled with 0s at the end of the not colision.


问:
Sub Folder is affected by root web.config
It should be an easy question ,

I am building a site under IIS ,
For one part of it inside a subdirectory like \blog
I turned it to a vitual directory .

the root folder has its own web.config
and the blog sub Folder has its own .

in the root's web.config I used :

```<code><pages theme="DefaultTheme">
</code>```

and the sub folder seems to be affected by that ,
it causes an error telling I don't have this theme .

What is the solution ?

答:
Web.Config's can be nested, and so the pages element will affect all other applications below it in scope (for example, there is a web.config that sets up various defaults in the framework's config folder).

If you don't want the theme on the pages in your blog folder, have you tried setting the theme to an empty string in the sub web.config? This is a valid value for the attribute, and should override the one set in the parent.

Theming works by looking in the Themes folder under the application root - in this case, under the /blogs folder, and if it can't find one in there, it will throw this exception.

OwnerDisplayName: Sypress

Body:
It should be an easy question ,

I am building a site under IIS ,
For one part of it inside a subdirectory like \blog
I turned it to a vitual directory .

the root folder has its own web.config
and the blog sub Folder has its own .

in the root's web.config I used :

<pages theme="DefaultTheme">

and the sub folder seems to be affected by that ,
it causes an error telling I don't have this theme .

What is the solution ?

OwnerDisplayName: Zhaph - Ben Duguid


问:
What is "it" in EntityDataSource's select property?
For example :

```<code><asp:EntityDataSource ID="EntityDataSource2" runat="server"
            ConnectionString="name=AdventureWorksEntities"
            DefaultContainerName="AdventureWorksEntities"
            EnableUpdate="True" EntitySetName="Employee"
            Select="" Where="it.EmployeeID = @selEmpID">
            <WhereParameters>
            <asp:ControlParameter ControlID="GridView1" Name="selEmpID" Type="Int32" PropertyName="SelectedValue" />
            </WhereParameters>
</asp:EntityDataSource>
</code>```

Is the "it" generate by EntityDataSource?
The "it" is the entity alias of Employee, but how can i define that?

For exmaple, if i include other entity by property below :

```<code>Include="Users,Permissions"
</code>```

How to define different alias to different entity
e.g.:

emp = Employee usr = Users perm =
  Permissions

答:
"it" is the "Control Variable."  You can change it using ObjectQuery's Name property.

ObjectQuery is what you get, for example out of your ObjectContext class, such as context.Products or context.Customers.

```<code>var query = context.Products;
query.Name = "products";  // changes "it" to "products"
</code>```

Body:
For example :

<asp:EntityDataSource ID="EntityDataSource2" runat="server"
            ConnectionString="name=AdventureWorksEntities"
            DefaultContainerName="AdventureWorksEntities"
            EnableUpdate="True" EntitySetName="Employee"
            Select="" Where="it.EmployeeID = @selEmpID">
            <WhereParameters>
            <asp:ControlParameter ControlID="GridView1" Name="selEmpID" Type="Int32" PropertyName="SelectedValue" />
            </WhereParameters>
</asp:EntityDataSource>

Is the "it" generate by EntityDataSource?
The "it" is the entity alias of Employee, but how can i define that?

For exmaple, if i include other entity by property below :

Include="Users,Permissions"

How to define different alias to different entity
e.g.:

emp = Employee usr = Users perm =
  Permissions

Body:
"it" is the "Control Variable."  You can change it using ObjectQuery's Name property.

ObjectQuery is what you get, for example out of your ObjectContext class, such as context.Products or context.Customers.

var query = context.Products;
query.Name = "products";  // changes "it" to "products"


问:
How to handle Authentication header in Selenium?
I am new to selenium and trying to handle authentication header which had been put up on web end for security reason. I am trying to access the site and send data using url using selenium but as authentication is required, I am unable to do so.
I've tried below mentioned code but couldn't succeed.

```<code>//Selenium-WebDriver Java Code for entering Username & Password as below:
    driver.findElement(By.id("userID")).sendKeys("username");
    driver.findElement(By.id("password")).sendKeys("pass");
    driver.switchTo().alert().accept();
    driver.switchTo().defaultContent();*/
        //self.headers = { "Authorization": "Basic xyz=" };
  /*        driver.switchTo().window("Authentication Required");
        driver.findElement(By.id("userID")).sendKeys("username");
        driver.findElement(By.id("password")).sendKeys("pass");*/

        //selenium.start("addCustomRequestHeader=true");
        //selenium.windowMaximize();
        //selenium.addCustomRequestHeader( "Authorization","Basic "+"xyx=" );
</code>```

Any help or suggestion would do great. Thanks in advance.

答:
This is my Java code:

```<code>public class LoginPage {

private WebDriver driver;

public LoginPage(WebDriver driver) {
    this.driver = driver;
}

public void login(){
    driver.get("http://localhost:8080/projectLogin/");

    WebElement username = driver.findElement(By.name("iDElementHtmlUser"));
    WebElement pass = driver.findElement(By.name("iDElementHtmlPassword"));

    username.sendKeys("rivanMota");
    pass.sendKeys("1234");
    username.submit();

    boolean logged = driver.getPageSource()
            .contains("idLogged"); // some id that only exists on logged page.
    assertTrue(logged); // True if login success
}
}
</code>```

And HTML:

```<code><input id="iDElementHtmlUser" type="text" name="username" />
<input id="iDElementHtmlPassword" type="password" name="password" />
</code>```

That is all folks!

Body:
I am new to selenium and trying to handle authentication header which had been put up on web end for security reason. I am trying to access the site and send data using url using selenium but as authentication is required, I am unable to do so.
I've tried below mentioned code but couldn't succeed.

//Selenium-WebDriver Java Code for entering Username & Password as below:
    driver.findElement(By.id("userID")).sendKeys("username");
    driver.findElement(By.id("password")).sendKeys("pass");
    driver.switchTo().alert().accept();
    driver.switchTo().defaultContent();*/
        //self.headers = { "Authorization": "Basic xyz=" };
  /*        driver.switchTo().window("Authentication Required");
        driver.findElement(By.id("userID")).sendKeys("username");
        driver.findElement(By.id("password")).sendKeys("pass");*/

        //selenium.start("addCustomRequestHeader=true");
        //selenium.windowMaximize();
        //selenium.addCustomRequestHeader( "Authorization","Basic "+"xyx=" );

Any help or suggestion would do great. Thanks in advance.

Body:
This is my Java code:

public class LoginPage {

private WebDriver driver;

public LoginPage(WebDriver driver) {
    this.driver = driver;
}

public void login(){
    driver.get("http://localhost:8080/projectLogin/");

    WebElement username = driver.findElement(By.name("iDElementHtmlUser"));
    WebElement pass = driver.findElement(By.name("iDElementHtmlPassword"));

    username.sendKeys("rivanMota");
    pass.sendKeys("1234");
    username.submit();

    boolean logged = driver.getPageSource()
            .contains("idLogged"); // some id that only exists on logged page.
    assertTrue(logged); // True if login success
}
}

And HTML:

<input id="iDElementHtmlUser" type="text" name="username" />
<input id="iDElementHtmlPassword" type="password" name="password" />

That is all folks!