问:
pyspark dataframe filtering on multiple columns
I have a pyspark dataframe which looks like below

df

```<code>num11   num21
10     10
20     30
5      25
</code>```

I am filtering above dataframe on all columns present, and selecting rows with number greater than 10 [no of columns can be more than two]

```<code>from pyspark.sql.functions import col
col_list = df.schema.names
df_fltered = df.where(col(c) >= 10 for c in col_list)
</code>```

desired output is :

```<code>num11    num21
10       10
20       30
</code>```

How can we achieve filtering on multiple columns using iteration on column list as above. [all efforts are appriciated]

[error i reveive is : condition should be string or column]

答:
You can use functools.reduce to combine the column conditions, to simulate an all condition, for instance, you can use reduce(lambda x, y: x & y, ...):

import pyspark.sql.functions as F
from functools import reduce

df.where(reduce(lambda x, y: x & y,  (F.col(x) >= 10 for x in df.columns))).show()
+-----+-----+
|num11|num21|
+-----+-----+
|   10|   10|
|   20|   30|
+-----+-----+
```

Body:
I have a pyspark dataframe which looks like below

df

num11   num21
10     10
20     30
5      25

I am filtering above dataframe on all columns present, and selecting rows with number greater than 10 [no of columns can be more than two]

from pyspark.sql.functions import col
col_list = df.schema.names
df_fltered = df.where(col(c) >= 10 for c in col_list)

desired output is :

num11    num21
10       10
20       30

How can we achieve filtering on multiple columns using iteration on column list as above. [all efforts are appriciated]

[error i reveive is : condition should be string or column]


来源: stackexchange

问:
Change background color but always get error that App has stopped
```<code>Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RelativeLayout.setBackgroundColor(int)' on a null object reference.
</code>```

This is what I get when I run the program and I don't know what to do.
I read the others post but still don't know what the problem is.I replaced the "v" in "public void onClick(View v)" with "findViewById" but still no working.

```<code>package com.example.gia.applumini;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RelativeLayout bgElement = (RelativeLayout) findViewById(R.layout.activity_main);
        bgElement.setBackgroundColor(Color.RED);
        myButtonListenerMethod();
    }

    public void myButtonListenerMethod() {
        Button button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RelativeLayout bgElement = (RelativeLayout) findViewById(R.layout.activity_main);
                int color = ((ColorDrawable) bgElement.getBackground()).getColor();
                if (color == Color.RED) {
                    bgElement.setBackgroundColor(Color.BLUE);
                }
                else {
                    bgElement.setBackgroundColor(Color.RED);
                }
            }
        });
    }
}
</code>```

答:
Replace

 RelativeLayout bgElement   =(RelativeLayout)findViewById(R.layout.activity_main);
by
  RelativeLayout bgElement = (RelativeLayout) findViewById(R.id.activity_main);

and also make sure that the id of the Relative layout is activity_main

ContentLicense: CC BY-SA 3.0

Body:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RelativeLayout.setBackgroundColor(int)' on a null object reference.

This is what I get when I run the program and I don't know what to do.
I read the others post but still don't know what the problem is.I replaced the "v" in "public void onClick(View v)" with "findViewById" but still no working.

package com.example.gia.applumini;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RelativeLayout bgElement = (RelativeLayout) findViewById(R.layout.activity_main);
        bgElement.setBackgroundColor(Color.RED);
        myButtonListenerMethod();
    }

    public void myButtonListenerMethod() {
        Button button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RelativeLayout bgElement = (RelativeLayout) findViewById(R.layout.activity_main);
                int color = ((ColorDrawable) bgElement.getBackground()).getColor();
                if (color == Color.RED) {
                    bgElement.setBackgroundColor(Color.BLUE);
                }
                else {
                    bgElement.setBackgroundColor(Color.RED);
                }
            }
        });
    }
}


问:
Cannot get my own JS file to work with Wordpress (4.9).
I am in a bit of a pickle, lol.

Here is my function:

```<code>  function start_group_escapes_4_less() {

    wp_enqueue_style( 'style', get_stylesheet_uri() . '/style.css');
    wp_enqueue_script( 'ge4l', get_stylesheet_uri() . '/js/ge4l.js', array('jquery'), null, true);

  }

  add_action( 'wp_enqueue_scripts', 'start_group_escapes_4_less' );
</code>```

Everywhere I checked, the syntax is right. Or is it?
Help :(

答:
The function get_stylesheet_uri() return the url of the theme style.css file.

You need to use get_stylesheet_directory_uri()

```<code>function start_group_escapes_4_less() {
    wp_enqueue_style( 'style', get_stylesheet_directory_uri() . '/style.css');
    wp_enqueue_script( 'ge4l', get_stylesheet_directory_uri() . '/js/ge4l.js', array('jquery'), null, true);
}
add_action( 'wp_enqueue_scripts', 'start_group_escapes_4_less' );
</code>```

Body:
I am in a bit of a pickle, lol.

Here is my function:

  function start_group_escapes_4_less() {

    wp_enqueue_style( 'style', get_stylesheet_uri() . '/style.css');
    wp_enqueue_script( 'ge4l', get_stylesheet_uri() . '/js/ge4l.js', array('jquery'), null, true);

  }

  add_action( 'wp_enqueue_scripts', 'start_group_escapes_4_less' );

Everywhere I checked, the syntax is right. Or is it?
Help :(

Body:
The function get_stylesheet_uri() return the url of the theme style.css file.

You need to use get_stylesheet_directory_uri()

function start_group_escapes_4_less() {
    wp_enqueue_style( 'style', get_stylesheet_directory_uri() . '/style.css');
    wp_enqueue_script( 'ge4l', get_stylesheet_directory_uri() . '/js/ge4l.js', array('jquery'), null, true);
}
add_action( 'wp_enqueue_scripts', 'start_group_escapes_4_less' );


问:
Google Calendar Scope for OAuth GoogleSignInOptions in Android
I am using Google Sign in to authenticate the user and add an event to user's Google Calendar. The event is added at the server side. GoogleSignInOptions objects is created as follows:

```<code>GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestScopes(new Scope(**WHAT SCOPE**))
            .requestIdToken(Server_Client_ID)
            .requestServerAuthCode(Server_Client_ID)
            .requestEmail()
            .build();
</code>```

But when setting scope the scope for Calendar is not found in the list. There is EMAIL, PLUS_ME and a set of FITNESS_ACTIVITY scopes etc. But what should be the scope for Calendar?

答:
Ok. I figured it out. Strings can also be passed as parameter to the method for creating scope object. For managing calendar, is it 'https://www.googleapis.com/auth/admin.directory.resource.calendar'. All the scopes can be found here</p>

```<code>GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestScopes(new Scope('https://www.googleapis.com/auth/admin.directory.resource.calendar'))
        .requestIdToken(Server_Client_ID)
        .requestServerAuthCode(Server_Client_ID)
        .requestEmail()
        .build();
</code>```

Body:
I am using Google Sign in to authenticate the user and add an event to user's Google Calendar. The event is added at the server side. GoogleSignInOptions objects is created as follows:

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestScopes(new Scope(**WHAT SCOPE**))
            .requestIdToken(Server_Client_ID)
            .requestServerAuthCode(Server_Client_ID)
            .requestEmail()
            .build();

But when setting scope the scope for Calendar is not found in the list. There is EMAIL, PLUS_ME and a set of FITNESS_ACTIVITY scopes etc. But what should be the scope for Calendar?

Body:
Ok. I figured it out. Strings can also be passed as parameter to the method for creating scope object. For managing calendar, is it 'https://www.googleapis.com/auth/admin.directory.resource.calendar'. All the scopes can be found here

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestScopes(new Scope('https://www.googleapis.com/auth/admin.directory.resource.calendar'))
        .requestIdToken(Server_Client_ID)
        .requestServerAuthCode(Server_Client_ID)
        .requestEmail()
        .build();


答:
I had the same issue. I found in a post that you have to change:

MODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_08'

To:

MODEL_NAME = 'ssd_mobilenet_v1_coco_11_06_2017'

and it worked fine.

Original answer: https://stackoverflow.com/a/47332228/8954260

Title: Tensorflow Object Detection Jupyter Notebook no detection

Body:
I tried to run the Jupyter Notebook example for the object detection of tensorflow (tutorial) but there are no detections. I printed the scores and it's seems to work but the results are very bad. Does anyone have an idea what I might have done wrong.

print(scores[0]):

[ 0.03587309  0.02224856  0.01864638  0.01096715  0.0100315

  0.0065446
    0.00633551  0.00534311  0.00495995  0.00410238  0.00362363  0.00339175
    0.00308251  0.0030337   0.00293387  0.00277085  0.00269581  0.00266825
    0.00263924  0.00263331  0.00258721  0.00240822  0.00225823  0.00186966
    0.00184308  0.00180467  0.00177474  0.00173643  0.0017281   0.00171935
    0.00171891  0.00170284  0.00163754  0.00162967  0.00160267  0.00156545
    0.00153614  0.00140936  0.00132406  0.00131524  0.00131041  0.00129431
    0.00125819  0.0012553   0.00122365  0.00119179  0.00115673  0.00115186
    0.00112368  0.00107096  0.00105803  0.00104337  0.00102719  0.00102337
    0.00100349  0.00097767  0.0009685   0.00092741  0.00088506  0.00087696
    0.0008734   0.00084825  0.00084135  0.00083512  0.00083396  0.00082068
    0.00080583  0.00078979  0.00078059  0.00077475  0.00075449  0.00074426
    0.00074421  0.00070195  0.00068741  0.00068138  0.00067261  0.00067125
    0.00067032  0.00066041  0.0006473   0.00064205  0.00061964  0.00061793
    0.00060834  0.00060468  0.00059547  0.00059478  0.00059461  0.00059436
    0.00059426  0.00059411  0.00059406  0.00059392  0.00059365  0.00059351
    0.00059191  0.00058798  0.00058682  0.00058148]

[ 0.01044157  0.00982138  0.00942336  0.00846517  0.00613665  0.00398568
    0.00357755  0.00300539  0.00255862  0.00236576  0.00232631  0.00220291
    0.00185227  0.00163544  0.00159791  0.00145071  0.0014366   0.0014137
    0.00122685  0.00118978  0.00108457  0.00104252  0.00099215  0.00096401
    0.0008708   0.00084774  0.00080484  0.00078507  0.00078379  0.00076875
    0.00072774  0.00071732  0.00071343  0.00070812  0.00069253  0.0006762
    0.00067269  0.00059905  0.00059367  0.000588    0.00056114  0.0005504
    0.00051472  0.00051055  0.00050973  0.00048484  0.00047297  0.00046204
    0.00044787  0.00043259  0.00042987  0.00042673  0.00041978  0.00040494
    0.00040087  0.00039576  0.00039059  0.00037274  0.00036828  0.00036417
    0.0003612   0.00034645  0.00034479  0.00034078  0.00033771  0.00033605
    0.0003333   0.0003304   0.0003294   0.00032325  0.00031787  0.00031773
    0.00031748  0.00031741  0.00031732  0.00031729  0.00031724  0.00031722
    0.00031717  0.00031708  0.00031702  0.00031579  0.00030416  0.00030222
    0.00029739  0.00029726  0.00028289  0.00026527  0.00026325  0.00024584
    0.00024221  0.00024156  0.0002391   0.00023335  0.00021617  0.0002001
    0.00019127  0.00018342  0.00017271  0.00015507]

I'm running the example with tensorflow 1.4, python 3.5 and I tested the installation as suggested.


问:
Cookies not showing up in global.asax
I'm using cookies to pass user information for authentication as seen in this question. Everything was working fine, until our team upgraded our computers and are now on windows 10. Now my cookie is not found in global.asax.cs's Application_PostAuthenticateRequest.

Here's my code trying to send the cookie:

```<code>private void AddUserDataToCookies(User user)
    {
        var serializeModel = new WebUserSerializeModel
        {
            FirstName = user.Person.FirstName,
            MiddleName = user.Person.MiddleName,
            LastName = user.Person.LastName,
            CredentialNumber = user.CredentialNumber,
            Roles = user.Roles.Select(role => role.Name).ToList(),
            Permissions = user.Permissions.Select(perm => perm.PrimaryKey).ToList()
        };

        var userData = new JavaScriptSerializer().Serialize(serializeModel);
        var authTicket = new FormsAuthenticationTicket(1, user.CredentialNumber, DateTime.Now, DateTime.Now.AddMinutes(15), false, userData);
        var encryptedTicket = FormsAuthentication.Encrypt(authTicket);

        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
        {
            Secure = true,
            HttpOnly = true
        };

        Response.Cookies.Add(cookie);

        var requestCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
    }
</code>```

The cookie shows up in request cookie. But when I try in my global.asax, it doesn't. My global asax code is below.

```<code>protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
    {
        var cookie = Request.Cookies[FormsAuthentication.FormsCookieName];

        if (cookie != null)
        {
            try
            {
                var authTicket = FormsAuthentication.Decrypt(cookie.Value);

                if (authTicket != null)
                {
                    var serializer = new JavaScriptSerializer();
                    var serializeModel = serializer.Deserialize<WebUserSerializeModel>(authTicket.UserData);

                    var user = new WebUser(serializeModel.FirstName, serializeModel.LastName)
                    {
                        MiddleName = serializeModel.MiddleName,
                        CredentialNumber = serializeModel.CredentialNumber,
                        Roles = serializeModel.Roles,
                        Permissions = serializeModel.Permissions
                    };

                    HttpContext.Current.User = user;
                }
            }
            catch (CryptographicException ex)
            {
                Logger.Error("Error while decrypting cookie post authentication.", ex);
                FormsAuthentication.SignOut();
                HttpContext.Current.User = null;
            }
        }
    }
</code>```

Does anyone have any ideas why changing to Windows 10 may have causes this issue? I'm somewhat new to ASP.NET and web development in general.

EDIT - by removing Secure = true when creating my cookie I was able to get it to work. I'm investigating why this is the case before I add an answer and I welcome any insights.

答:
As mentioned in my edit, the problem was that Secure was set to true when creating my cookie but I did not have SSL enabled when running locally, unlike, I guess, on my old workstation. The code in my controller currently looks like:

```<code>private void AddUserDataToCookies(User user)
    {
        var serializeModel = new WebUserSerializeModel
        {
            FirstName = user.FirstName,
            MiddleName = user.MiddleName,
            LastName = user.LastName,
            CredentialNumber = user.CredentialNumber,
            Roles = user.Roles,
            Permissions = user.Permissions
        };

        var userData = new JavaScriptSerializer().Serialize(serializeModel);
        var authTicket = new FormsAuthenticationTicket(1, user.CredentialNumber, DateTime.Now, DateTime.Now.AddMinutes(FormsAuthentication.Timeout.Minutes), false, userData, FormsAuthentication.FormsCookiePath);
        var encryptedTicket = FormsAuthentication.Encrypt(authTicket);

        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
        {
            HttpOnly = true,
            Secure = true
        };

        if (Request.IsLocal)
        {
            cookie.Secure = false;
        }

        Response.Cookies.Add(cookie);
    }
</code>```

Leaving Request.IsLocal is a bit ugly but it's good enough for now until we decide if we want to implement SSL for everyone locally.

At least it was an easy fix.

Title: Cookies not showing up in global.asax

Body:
I'm using cookies to pass user information for authentication as seen in this question. Everything was working fine, until our team upgraded our computers and are now on windows 10. Now my cookie is not found in global.asax.cs's Application_PostAuthenticateRequest.

Here's my code trying to send the cookie:

private void AddUserDataToCookies(User user)
    {
        var serializeModel = new WebUserSerializeModel
        {
            FirstName = user.Person.FirstName,
            MiddleName = user.Person.MiddleName,
            LastName = user.Person.LastName,
            CredentialNumber = user.CredentialNumber,
            Roles = user.Roles.Select(role => role.Name).ToList(),
            Permissions = user.Permissions.Select(perm => perm.PrimaryKey).ToList()
        };

        var userData = new JavaScriptSerializer().Serialize(serializeModel);
        var authTicket = new FormsAuthenticationTicket(1, user.CredentialNumber, DateTime.Now, DateTime.Now.AddMinutes(15), false, userData);
        var encryptedTicket = FormsAuthentication.Encrypt(authTicket);

        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
        {
            Secure = true,
            HttpOnly = true
        };

        Response.Cookies.Add(cookie);

        var requestCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
    }

The cookie shows up in request cookie. But when I try in my global.asax, it doesn't. My global asax code is below.

protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
    {
        var cookie = Request.Cookies[FormsAuthentication.FormsCookieName];

        if (cookie != null)
        {
            try
            {
                var authTicket = FormsAuthentication.Decrypt(cookie.Value);

                if (authTicket != null)
                {
                    var serializer = new JavaScriptSerializer();
                    var serializeModel = serializer.Deserialize<WebUserSerializeModel>(authTicket.UserData);

                    var user = new WebUser(serializeModel.FirstName, serializeModel.LastName)
                    {
                        MiddleName = serializeModel.MiddleName,
                        CredentialNumber = serializeModel.CredentialNumber,
                        Roles = serializeModel.Roles,
                        Permissions = serializeModel.Permissions
                    };

                    HttpContext.Current.User = user;
                }
            }
            catch (CryptographicException ex)
            {
                Logger.Error("Error while decrypting cookie post authentication.", ex);
                FormsAuthentication.SignOut();
                HttpContext.Current.User = null;
            }
        }
    }

Does anyone have any ideas why changing to Windows 10 may have causes this issue? I'm somewhat new to ASP.NET and web development in general.

EDIT - by removing Secure = true when creating my cookie I was able to get it to work. I'm investigating why this is the case before I add an answer and I welcome any insights.

Body:
As mentioned in my edit, the problem was that Secure was set to true when creating my cookie but I did not have SSL enabled when running locally, unlike, I guess, on my old workstation. The code in my controller currently looks like:

private void AddUserDataToCookies(User user)
    {
        var serializeModel = new WebUserSerializeModel
        {
            FirstName = user.FirstName,
            MiddleName = user.MiddleName,
            LastName = user.LastName,
            CredentialNumber = user.CredentialNumber,
            Roles = user.Roles,
            Permissions = user.Permissions
        };

        var userData = new JavaScriptSerializer().Serialize(serializeModel);
        var authTicket = new FormsAuthenticationTicket(1, user.CredentialNumber, DateTime.Now, DateTime.Now.AddMinutes(FormsAuthentication.Timeout.Minutes), false, userData, FormsAuthentication.FormsCookiePath);
        var encryptedTicket = FormsAuthentication.Encrypt(authTicket);

        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
        {
            HttpOnly = true,
            Secure = true
        };

        if (Request.IsLocal)
        {
            cookie.Secure = false;
        }

        Response.Cookies.Add(cookie);
    }

Leaving Request.IsLocal is a bit ugly but it's good enough for now until we decide if we want to implement SSL for everyone locally.

At least it was an easy fix.


问:
Android studio 3 Unable to resolve dependency
I update android studio to version 3.0.0 and installed gradle 4.
i create new project but Unable to resolve dependency.

i test this method but not working:
 - invalidate and restart
 - delete .gradle folder and build
 - clean and rebuild
 - deactive offline mode

how to fix?

details screenshots:

答:
use compile instead of implementation

and testCompile instead of androidTestimplementation


问:
Don't understand IndexError from for loop
So I've got this code for a school project (which explains the variable names) but when I get to the for loop at the bottom it says the list index is out of range. It is supposed to input a username and then check it before asking for a password. I've tried to figure out what is wrong but nothing works.</p>

```<code>def passwordSystem():
    #TASK ONE
    username_array = []
    password_array = []
    for i in range (1, 30):
        username_to_be_entered = str(input("Enter a username"))
        acceptable_password = False
        while not acceptable_password:
            password_to_be_entered = str(input("Enter a password between 6 and 12 characters"))
            if len(password_to_be_entered) > 12 or len(password_to_be_entered) < 6:
                print ("Your password was not between 6 and 12 characters")
            else:
                acceptable_password = True
                print ("Password accepted")
        print ("Your username is:" ,username_to_be_entered)
        print ("Your password is:" ,password_to_be_entered)
    #TASK TWO
    username_accepted = False
    while not username_accepted:
        username_to_be_checked = str(input("Please enter your username"))
        for i in range (1, 30):
            if username_array[i] == username_to_be_checked:
                print ("Username accepted")
                username_accepted = True
</code>```

答:
Your lists remain empty forever. In this code block you need to append the username and password to their respective lists.

```<code>while not acceptable_password:
    password_to_be_entered = str(input("Enter a password between 6 and 12 characters"))
    if len(password_to_be_entered) > 12 or len(password_to_be_entered) < 6:
        print ("Your password was not between 6 and 12 characters")
    else:
        acceptable_password = True
        username_array.append(username_to_be_entered)
        password_array.append(password_to_be_entered)
        print ("Password accepted")
</code>```

Then, to check the username, you should just use the in keyword instead of manually iterating over the whole list.

```<code>#TASK TWO
username_accepted = False
while not username_accepted:
    username_to_be_checked = str(input("Please enter your username"))
    if username_to_be_checked in username_array:
        print ("Username accepted")
        username_accepted = True
</code>```

Body:
So I've got this code for a school project (which explains the variable names) but when I get to the for loop at the bottom it says the list index is out of range. It is supposed to input a username and then check it before asking for a password. I've tried to figure out what is wrong but nothing works.

def passwordSystem():
    #TASK ONE
    username_array = []
    password_array = []
    for i in range (1, 30):
        username_to_be_entered = str(input("Enter a username"))
        acceptable_password = False
        while not acceptable_password:
            password_to_be_entered = str(input("Enter a password between 6 and 12 characters"))
            if len(password_to_be_entered) > 12 or len(password_to_be_entered) < 6:
                print ("Your password was not between 6 and 12 characters")
            else:
                acceptable_password = True
                print ("Password accepted")
        print ("Your username is:" ,username_to_be_entered)
        print ("Your password is:" ,password_to_be_entered)
    #TASK TWO
    username_accepted = False
    while not username_accepted:
        username_to_be_checked = str(input("Please enter your username"))
        for i in range (1, 30):
            if username_array[i] == username_to_be_checked:
                print ("Username accepted")
                username_accepted = True

Body:
Your lists remain empty forever. In this code block you need to append the username and password to their respective lists.

while not acceptable_password:
    password_to_be_entered = str(input("Enter a password between 6 and 12 characters"))
    if len(password_to_be_entered) > 12 or len(password_to_be_entered) < 6:
        print ("Your password was not between 6 and 12 characters")
    else:
        acceptable_password = True
        username_array.append(username_to_be_entered)
        password_array.append(password_to_be_entered)
        print ("Password accepted")

Then, to check the username, you should just use the in keyword instead of manually iterating over the whole list.

#TASK TWO
username_accepted = False
while not username_accepted:
    username_to_be_checked = str(input("Please enter your username"))
    if username_to_be_checked in username_array:
        print ("Username accepted")
        username_accepted = True


问:
Why does Chrome open a connection but not send anything
I'm building a web server from scratch for fun and I am noticing some strange behaviors from Chrome. The request I get from Chrome for a GET request to / looks like this:

```<code>GET / HTTP/1.1
Host: localhost:8000
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
DNT: 1
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
</code>```

Nothing special, but it also make another request to my server and it doesn't send anything, which results in my server waiting for an incoming message forever.

This behavior is not found with Safari. I have set the server to respond with 403 to every single request, but the persistent connection remains. What is the purpose of this connection and how should I handle it? Am I missing something from the HTTP protocol?

答:
HTTP/1.1 browsers tend to open multiple TCP connections. If your server can only act upon one connection at a time, you might end up in a deadlock. You should either use threads or nonblocking IO (select) to handle each connection when it has a request ready.

Chrome is probably opening an additional socket so that it's ready if the first one closes, but I'm not sure. HTTP/1.1 has no way to cancel a request/response, other than closing the socket, and it's also possible that the server would send Connection: close after finishing the response, so the browser is preparing itself for the future requests.

Body:
I'm building a web server from scratch for fun and I am noticing some strange behaviors from Chrome. The request I get from Chrome for a GET request to / looks like this:

GET / HTTP/1.1
Host: localhost:8000
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
DNT: 1
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9

Nothing special, but it also make another request to my server and it doesn't send anything, which results in my server waiting for an incoming message forever.

This behavior is not found with Safari. I have set the server to respond with 403 to every single request, but the persistent connection remains. What is the purpose of this connection and how should I handle it? Am I missing something from the HTTP protocol?


问:
How to bind event for dynamically created elements in JQuery
i have created some dynamic elements using jquery and add a dropdownlist using ajax inside dynamic elements ,The problem is when i select a option from a dropdownlist,then upcoming ajax data are override the all other dynamic elements data.

now i want to bind data every dynamic elements data separately in jquery.

  $(document).ready(function() {
  var html = $("#dsp > .row:first").first().html();
  var maxrows = 5;
  var x = 1;
  $("#addrow").click(function() {
    if (x <= maxrows) {
      $('#dsp').append(html);
      x++;
    }
  });

  $("#rmvrow").click(function() {
    $('#dsp').children().last().remove();
  });

    $('#dsp').on('change','.p_name',function(){
      var pid=$(this).val();
      var parent=$('#dsp');

      //alert(pid);
      $.ajax({
        url:"{{route('getinfo')}}",
        method:'post',
        data:{id:pid,'_token':"{{csrf_token()}}"},
        success:function(response) {
            console.log(parent.find('.p_code').val(response.code));

        }
      });

    });
});

  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code>           <div id="dsp">
  <div class="row">
    <div class="col-md-2">
      <select name="p_name[]" class="form-control p_name">
      <option value="">-Select Product-</option>
      @foreach($products as $product)
      <option value="{{$product->product_id}}">{{$product->name}}</option>
      @endforeach
    </select>
    </div>
    <div class="col-md-2">
      <input type="text" name="p_code[]" class="form-control p_code">
    </div>
    <div class="col-md-2">
      <input type="text" name="unit_pctn[]" class="form-control unit_pctn" readonly="">
    </div>
    <div class="col-md-2">
      <input type="text" name="u_price[]" class="form-control u_price" readonly="">
    </div>
    <div class="col-md-1">
      <input type="text" name="ctn[]" class="form-control ctn">
    </div>
    <div class="col-md-1">
      <input type="text" name="pcs[]" class="form-control pcs">
    </div>
    <div class="col-md-2">
      <input type="text" name="t_amt[]" class="form-control t_amt">
    </div>

  </div><br>
</div></code>```

答:
Your code for delegating event binding is fine. The problem is that your second success function doesn't put the response in the current row, it fills in all .u_price fields. Change that to:

```<code>parent.find(".u_price").val(response.client_price);
</code>```

When you add a new row, it needs to be inside its own
, so that $(this).closest(".row") will select the correct row. You currently just have one class="row" and it's the #dsp DIV that contains all the rows. Each row needs to be a child of #dsp.

$(document).ready(function() {
  var html = $("#dsp > row:first").first().html();
  var maxrows = 5;
  var x = 1;
  $("#addrow").click(function() {
    if (x <= maxrows) {
      $('#dsp').append(html);
      x++;
    }
  });

  $("#rmvrow").click(function() {
    $('#dsp').children().last().remove();
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="dsp">
  <div class="row">
    <div class="col-md-2">
      <select name="p_name[]" class="form-control p_name">
      <option value="">-Select Product-</option>
      @foreach($products as $product)
      <option value="{{$product->product_id}}">{{$product->name}}</option>
      @endforeach
    </select>
    </div>
    <div class="col-md-2">
      <input type="text" name="p_code[]" class="form-control p_code">
    </div>
    <div class="col-md-2">
      <input type="text" name="unit_pctn[]" class="form-control unit_pctn" readonly="">
    </div>
    <div class="col-md-2">
      <input type="text" name="u_price[]" class="form-control u_price" readonly="">
    </div>
    <div class="col-md-1">
      <input type="text" name="ctn[]" class="form-control ctn">
    </div>
    <div class="col-md-1">
      <input type="text" name="pcs[]" class="form-control pcs">
    </div>
    <div class="col-md-2">
      <input type="text" name="t_amt[]" class="form-control t_amt">
    </div>

  </div>
</div></code>```

Body:
i have created some dynamic elements using jquery and add a dropdownlist using ajax inside dynamic elements ,The problem is when i select a option from a dropdownlist,then upcoming ajax data are override the all other dynamic elements data.

now i want to bind data every dynamic elements data separately in jquery.

  $(document).ready(function() {
  var html = $("#dsp > .row:first").first().html();
  var maxrows = 5;
  var x = 1;
  $("#addrow").click(function() {
    if (x <= maxrows) {
      $('#dsp').append(html);
      x++;
    }
  });

  $("#rmvrow").click(function() {
    $('#dsp').children().last().remove();
  });

    $('#dsp').on('change','.p_name',function(){
      var pid=$(this).val();
      var parent=$('#dsp');

      //alert(pid);
      $.ajax({
        url:"{{route('getinfo')}}",
        method:'post',
        data:{id:pid,'_token':"{{csrf_token()}}"},
        success:function(response) {
            console.log(parent.find('.p_code').val(response.code));

        }
      });

    });
});

      <select name="p_name[]" class="form-control p_name">
      <option value="">-Select Product-</option>
      @foreach($products as $product)
      <option value="{{$product->product_id}}">{{$product->name}}</option>
      @endforeach
    </select>

      <input type="text" name="p_code[]" class="form-control p_code">

      <input type="text" name="unit_pctn[]" class="form-control unit_pctn" readonly="">

      <input type="text" name="u_price[]" class="form-control u_price" readonly="">

      <input type="text" name="ctn[]" class="form-control ctn">

      <input type="text" name="pcs[]" class="form-control pcs">

      <input type="text" name="t_amt[]" class="form-control t_amt">

Body:
Your code for delegating event binding is fine. The problem is that your second success function doesn't put the response in the current row, it fills in all .u_price fields. Change that to:

parent.find(".u_price").val(response.client_price);

When you add a new row, it needs to be inside its own <div class="row">, so that $(this).closest(".row") will select the correct row. You currently just have one class="row" and it's the #dsp DIV that contains all the rows. Each row needs to be a child of #dsp.

$(document).ready(function() {
  var html = $("#dsp > row:first").first().html();
  var maxrows = 5;
  var x = 1;
  $("#addrow").click(function() {
    if (x <= maxrows) {
      $('#dsp').append(html);
      x++;
    }
  });

  $("#rmvrow").click(function() {
    $('#dsp').children().last().remove();
  });
});

<div id="dsp">
  <div class="row">
    <div class="col-md-2">
      <select name="p_name[]" class="form-control p_name">
      <option value="">-Select Product-</option>
      @foreach($products as $product)
      <option value="{{$product->product_id}}">{{$product->name}}</option>
      @endforeach
    </select>
    </div>
    <div class="col-md-2">
      <input type="text" name="p_code[]" class="form-control p_code">
    </div>
    <div class="col-md-2">
      <input type="text" name="unit_pctn[]" class="form-control unit_pctn" readonly="">
    </div>
    <div class="col-md-2">
      <input type="text" name="u_price[]" class="form-control u_price" readonly="">
    </div>
    <div class="col-md-1">
      <input type="text" name="ctn[]" class="form-control ctn">
    </div>
    <div class="col-md-1">
      <input type="text" name="pcs[]" class="form-control pcs">
    </div>
    <div class="col-md-2">
      <input type="text" name="t_amt[]" class="form-control t_amt">
    </div>

  </div>
</div>


问:
write the result into input field
I have problem with my javascript. I'm not able to display the results in the input field. Please can anyone help me?? And if it possible it will be better to calculate the result without clicking on the button!! Thanks.

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span style="font-size:20px;">Your bid:</span> <input type="number"    name="bid" class="form-control" style="max-width:250px; margin-top:10px;"> <br>
        <input type="button" onClick="cal();">
        <span style="font-size:20px;" >Our Fee (10%):</span><input type="number" name="fee" readonly class="form-control" style="max-width:250px; margin-top:10px;"><br>
        <span style="font-size:20px;">You'll paid:</span> <input type="number"  name="get" readonly class="form-control" style="max-width:250px; margin-top:10px;"></code>```

答:
try it :

```<code> function cal(){

            var bid = document.querySelector("input[name=bid]");
            var result1= bid * 0.1;
            var result2= bid - result1;
            document.querySelector("input[name=fee]").value = result1;
            document.querySelector("input[name=get]").value = result2;

        }
</code>```

or

```<code>function cal(){

        var bid = document.getElementsByName("bid")[0].value;
        var result1= bid * 0.1;
        var result2= bid - result1;
        document.getElementsByName("fee")[0].value = result1;
        document.getElementsByName("get")[0].value = result2;

    }
</code>```

Or you can set id to all inputs and use documment.getElementById
For use function after change you can use next code:

```<code>var bid = document.getElementsByName("bid")[0];
bid.addEventListener('change',function(){
  cal();
});
</code>```

Title: write the result into input field

Body:
I have problem with my javascript. I'm not able to display the results in the input field. Please can anyone help me?? And if it possible it will be better to calculate the result without clicking on the button!! Thanks.

Your bid: <input type="number"    name="bid" class="form-control" style="max-width:250px; margin-top:10px;">

        <input type="button" onClick="cal();">
        Our Fee (10%):<input type="number" name="fee" readonly class="form-control" style="max-width:250px; margin-top:10px;">

        You'll paid: <input type="number"  name="get" readonly class="form-control" style="max-width:250px; margin-top:10px;">

Body:
try it :

 function cal(){

            var bid = document.querySelector("input[name=bid]");
            var result1= bid * 0.1;
            var result2= bid - result1;
            document.querySelector("input[name=fee]").value = result1;
            document.querySelector("input[name=get]").value = result2;

        }

or

function cal(){

        var bid = document.getElementsByName("bid")[0].value;
        var result1= bid * 0.1;
        var result2= bid - result1;
        document.getElementsByName("fee")[0].value = result1;
        document.getElementsByName("get")[0].value = result2;

    }

Or you can set id to all inputs and use documment.getElementById
For use function after change you can use next code:

var bid = document.getElementsByName("bid")[0];
bid.addEventListener('change',function(){
  cal();
});


问:
Navigate to root screen from nested stack navigator
i am new to react and trying to learn it by myself , i am facing problem in navigating user back to root screen from nested stck navigator screen .

Here is some of my classes :-

index.android.js :-

```<code>import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  StatusBar,
  View
} from 'react-native';
import {LoginStack} from './login/loginregisterrouter';
import {StackNavigator } from 'react-navigation';
class reactNavigationSample extends Component {
  render(){
    return (
   <LoginStack/>
    );
  }
}
AppRegistry.registerComponent('MssReactDemo', () => reactNavigationSample);
</code>```

loginregisterrouter :-

```<code>import React from 'react';
import {StackNavigator } from 'react-navigation';
import LoginScreen from './LoginScreen';
import RegisterScreen from './RegisterScreen';
import NavigationContainer from './navigationContainer';
export const LoginStack = StackNavigator({
  LoginScreen: {
    screen: LoginScreen,
    navigationOptions: {
      title: 'LoginScreen',
    }
  },
  RegisterScreen: {
    screen: RegisterScreen,
    navigationOptions: ({ navigation }) => ({
      title: 'RegisterScreen',
    }),
  },NavigationContainer: {
        screen: NavigationContainer,
        navigationOptions: ({ navigation }) => ({
          title: 'NavigationContainer', header: null,
        }),
      },
});
</code>```

Navigationcontainer.js :-

```<code>import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  StatusBar,
  View
} from 'react-native';
import {EasyRNRoute,} from '../parent';
import {StackNavigator } from 'react-navigation';
export default class NavigationContainer extends Component {
  render(){
    return (
   <EasyRNRoute/>
    );
  }
}
</code>```

parent.js :-

```<code>import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  StatusBar,
  View
} from 'react-native';
import App from './app';
import DrawerMenu from './Drawer/drawer-toolbar-android';
import BookmarkView from './Pages/bookmark';
import ClientView from './Pages/client';
import InfoView from './Pages/info';
import SettingsView from './Pages/setting';
import { DrawerNavigator, StackNavigator } from 'react-navigation';

export const stackNavigator = StackNavigator({
  Info: { screen: InfoView },
  Settings: {screen: SettingsView },
  Bookmark: {screen: BookmarkView },
  Connections: {screen: ClientView},
}, {
  headerMode: 'none'
});

export const EasyRNRoute = DrawerNavigator({
  Home: {
    screen: App,
  },
  Stack: {
    screen: stackNavigator
  }
}, {
  contentComponent: DrawerMenu,
  contentOptions: {
    activeTintColor: '#e91e63',
    style: {
      flex: 1,
      paddingTop: 15,
    }
  }
});
</code>```

Drawer-toolbar-android.js :-

```<code>import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    StatusBar,
    View
} from 'react-native';
import { NavigationActions } from 'react-navigation'
import { COLOR, ThemeProvider, Toolbar, Drawer, Avatar } from 'react-native-material-ui';
import Container from '../Container';
import LoginScreen from '../login/LoginScreen';

const uiTheme = {
    palette: {
        primaryColor: COLOR.green500,
        accentColor: COLOR.pink500,
      },
    toolbar: {
        container: {
            height: 70,
            paddingTop: 20,
          },
      },
      avatar: {
          container: {
              backgroundColor: '#333'
          }
      }
  };

export default class DrawerMenu extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
        active: 'people',
      };
  }
handleLogoutPress = () => {
//    AsyncStorage.setItem('SignedUpuser', '');
this.props
               .navigation
               .dispatch(NavigationActions.reset(
                 {
                    index: 0,
                    actions: [
                      NavigationActions.navigate({ routeName: 'LoginScreen'})
                    ]
                  }));
//     this.props.navigation.dispatch(NavigationActions.back());
  };
  _setInfoActive() {
    this.setState({ active: 'info' });
  }

  render() {
    return (
        <ThemeProvider uiTheme={uiTheme}>
                <Container>
                    <StatusBar backgroundColor="rgba(0, 0, 0, 0.2)" translucent />
                    <Toolbar
                    leftElement="arrow-back"
                    onLeftElementPress={() => this.props.navigation.navigate('DrawerClose')}
                    centerElement="Menu"
                />
                    <View style={styles.container}>
                        <Drawer>
                            <Drawer.Header >
                                <Drawer.Header.Account
                                style={{
                                    container: { backgroundColor: '#fafafa' },
                                }}
                                avatar={<Avatar text={'S'} />}
//                                accounts={[
//                                    { avatar: <Avatar text="H" /> },
//                                    { avatar: <Avatar text="L" /> },
//                                ]}
                                footer={{
                                    dense: true,
                                    centerElement: {
                                        primaryText: 'Siddharth',
                                        secondaryText: 'I am DONE now',
                                    },

                                  }}
                            />
                            </Drawer.Header>
                            <Drawer.Section
                            style={{
                                label: {color: '#0000ff'}
                            }}
                            divider
                            items={[
                                {
                                    icon: 'bookmark-border', value: 'Bookmarks',
                                    active: this.state.active == 'bookmark',
                                    onPress: () => {
                                        this.setState({ active: 'bookmark' });
                                        this.props.navigation.navigate('Bookmark');
                                      },
                                  },
                                {
                                    icon: 'people', value: 'Connections',
                                    active: this.state.active == 'Connection',
                                    onPress: () => {
                                        this.setState({ active: 'Connection' });
                                        this.props.navigation.navigate('Connections');
                                      },
                                  },
                            ]}
                        />
                            <Drawer.Section
                            title="Personal"
                            items={[
                                {
                                    icon: 'info', value: 'Info',
                                    active: this.state.active == 'info',
                                    onPress: () => {
                                        this.setState({ active: 'info' });
                                        //this.props.navigation.navigate('DrawerClose');
                                        this.props.navigation.navigate('Info');
                                      },
                                  },
                                {
                                    icon: 'settings', value: 'Settings',
                                    active: this.state.active == 'settings',
                                    onPress: () => {
                                        this.setState({ active: 'settings' });
                                        this.props.navigation.navigate('Settings');
                                      },
                                  },
                                   {
                                    icon: 'logout', value: 'Logout',
                                    active: this.state.active == 'logout',
                                    onPress: () => {
                                    this.handleLogoutPress();
                                     },
                                      },
                            ]}
                        />
                        </Drawer>
                    </View>
                </Container>
            </ThemeProvider>
    );
  }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F5FCFF',
      },
    header: {
        backgroundColor: '#455A64',
      },
    welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
      },
    instructions: {
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5,
      },
  });
</code>```

The above is the stack architecture i am using inside my application and as you can see that my Main screen is LOGIN screen and i do have option for LOGOUT from application in my Drawer(side menu). What i eaxtly want is that when user click on logout he/she should get redirected to LOGIN screen . i have googled about this and got to know about two ways of doing it , but both the ways are not working for me , may be i am using them in wrong way. so i am here to seek your help .

The two methods are :-

1)

```<code>this.props
               .navigation
               .dispatch(NavigationActions.reset(
                 {
                    index: 0,
                    actions: [
                      NavigationActions.navigate({ routeName: 'LoginScreen'})
                    ]
                  }));
</code>```

2) this.props.navigation.dispatch(NavigationActions.back());

this question may seems silly to you but i am really stuck at this point and just want to know how can i  figure this out.Any help would be greatly Appreciated!!!!
Thanks in advance.

答:
Modal StackNavigator containing a Dismissable StackNavigator

Requires: react-navigation version: 1.0.0

Goal: Navigate from App TabNavigator to Screen 1 to Screen 2 to Screen N and then directly back to App TabNavigator.

Navigation hierarchy:

RootNavigator StackNavigator {mode: 'modal'}

App TabNavigator

TabA Screen

TabB Screen

TabC Screen

ModalScreen Screen

ModalStack DismissableStackNavigator

Screen 1 ModalStackScreen

Screen 2 ModalStackScreen

Screen N ModalStackScreen

Demo

package.json

{
  "name": "HelloWorld",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "react": "16.0.0-alpha.6",
    "react-native": "0.44.0",
    "react-navigation": "^1.0.0"
  },
  "devDependencies": {
    "babel-jest": "20.0.3",
    "babel-preset-react-native": "1.9.2",
    "jest": "20.0.3",
    "react-test-renderer": "16.0.0-alpha.6"
  },
  "jest": {
    "preset": "react-native"
  }
}
```

<h2><code>index.ios.js</code> (or <code>index.android.js</code>)</h2>

<pre class="lang-js prettyprint-override"><code>import React from 'react'
import {
  AppRegistry,
  Button,
  Text,
  View
} from 'react-native'
import {
  StackNavigator,
  TabNavigator
} from 'react-navigation'

class TabA extends React.Component {
  state = {
    startScreen: 'none',
    returnScreen: 'none'
  }
  render () {
    return (
      <View style={{ padding: 40, paddingTop: 64 }}>
        <Text style={{ fontSize: 20 }}>{this.constructor.name}</Text>
        <Text>startScreen: {this.state.startScreen}</Text>
        <Text>returnScreen: {this.state.returnScreen}</Text>
        <Button
          title="Open ModalScreen"
          onPress={() => this.props.navigation.navigate('ModalScreen', {
            startScreen: this.constructor.name,
            setParentState: (state) => this.setState(state)
          })}
        />
        <Button
          title="Open ModalStack"
          onPress={() => this.props.navigation.navigate('ModalStack', {
            startScreen: this.constructor.name,
            setParentState: (state) => this.setState(state)
          })}
        />
      </View>
    )
  }
}

class TabB extends TabA {}
class TabC extends TabA {}

class ModalScreen extends React.Component {
  render () {
    const {
      startScreen,
      setParentState
    } = this.props.navigation.state.params
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text style={{ fontSize: 20 }}>{this.constructor.name}</Text>
        <Button
          title="Close"
          onPress={() => {
            setParentState({
              startScreen,
              returnScreen: this.constructor.name
            })
            this.props.navigation.goBack()
          }}
        />
      </View>
    )
  }
}

const DismissableStackNavigator = (routes, options) => {
  const StackNav = StackNavigator(routes, options)

  return class DismissableStackNav extends React.Component {
    static router = StackNav.router

    render () {
      const { state, goBack } = this.props.navigation
      const screenProps = {
        ...this.props.screenProps,
        dismissStackNav: () => goBack(state.key)
      }
      return (
        <StackNav
          screenProps={screenProps}
          navigation={this.props.navigation}
        />
      )
    }
  }
}

class ModalStackScreen extends React.Component {
  render () {
    const screenNumber = this.props.navigation.state.params && this.props.navigation.state.params.screenNumber || 0
    const {
      startScreen,
      setParentState
    } = this.props.navigation.state.params
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text style={{ fontSize: 20 }}>{this.constructor.name + screenNumber}</Text>
        <View style={{
          flexDirection: 'row',
          justifyContent: 'space-between'
        }}>
          <Button
            title={screenNumber === 0 ? "Close" : "Back"}
            onPress={() => this.props.navigation.goBack(null)}
          />
          <Button
            title="Save"
            onPress={() => {
              setParentState({
                startScreen,
                returnScreen: this.constructor.name + screenNumber
              })
              this.props.screenProps.dismissStackNav()
            }}
          />
          <Button
            title="Next"
            onPress={() => this.props.navigation.navigate('ModalStackScreen', {
              screenNumber: screenNumber + 1,
              startScreen,
              setParentState
            })}
          />
        </View>
      </View>
    )
  }
}

const TabNav = TabNavigator(
  {
    TabA: {
      screen: TabA
    },
    TabB: {
      screen: TabB
    },
    TabC: {
      screen: TabC
    }
  }
)

const ModalStack = DismissableStackNavigator(
  {
    ModalStackScreen: {
      screen: ModalStackScreen
    }
  },
  {
    headerMode: 'none'
  }
)

const RootStack = StackNavigator(
  {
    Main: {
      screen: TabNav,
    },
    ModalScreen: {
      screen: ModalScreen,
    },
    ModalStack: {
      screen: ModalStack
    }
  },
  {
    mode: 'modal',
    headerMode: 'none'
  }
)

class App extends React.Component {
  render () {
    return <RootStack />
  }
}

AppRegistry.registerComponent('HelloWorld', () => App)
</code>```

Previous Answer

This solution is a sledgehammer. It causes the screen of the default tab in the TabNavigator to unmount and then mount again. If the Screen a tab launching the Modal with the StackNavigator passes some callbacks to update it's state, these callbacks will be called when the Screen is unmounted.

The solution was to add key: null to the reset object:

this.props.navigation.dispatch(NavigationActions.reset({
  index: 0,
  key: null,
  actions: [
    NavigationActions.navigate({ routeName: 'App'})
  ]
}))
```

I was tipped off by this comment.

(FYI - I got here via your comment asking for help.)

Body:
i am new to react and trying to learn it by myself , i am facing problem in navigating user back to root screen from nested stck navigator screen .

Here is some of my classes :-

index.android.js :-

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  StatusBar,
  View
} from 'react-native';
import {LoginStack} from './login/loginregisterrouter';
import {StackNavigator } from 'react-navigation';
class reactNavigationSample extends Component {
  render(){
    return (
   <LoginStack/>
    );
  }
}
AppRegistry.registerComponent('MssReactDemo', () => reactNavigationSample);

loginregisterrouter :-

import React from 'react';
import {StackNavigator } from 'react-navigation';
import LoginScreen from './LoginScreen';
import RegisterScreen from './RegisterScreen';
import NavigationContainer from './navigationContainer';
export const LoginStack = StackNavigator({
  LoginScreen: {
    screen: LoginScreen,
    navigationOptions: {
      title: 'LoginScreen',
    }
  },
  RegisterScreen: {
    screen: RegisterScreen,
    navigationOptions: ({ navigation }) => ({
      title: 'RegisterScreen',
    }),
  },NavigationContainer: {
        screen: NavigationContainer,
        navigationOptions: ({ navigation }) => ({
          title: 'NavigationContainer', header: null,
        }),
      },
});

Navigationcontainer.js :-

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  StatusBar,
  View
} from 'react-native';
import {EasyRNRoute,} from '../parent';
import {StackNavigator } from 'react-navigation';
export default class NavigationContainer extends Component {
  render(){
    return (
   <EasyRNRoute/>
    );
  }
}

parent.js :-

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  StatusBar,
  View
} from 'react-native';
import App from './app';
import DrawerMenu from './Drawer/drawer-toolbar-android';
import BookmarkView from './Pages/bookmark';
import ClientView from './Pages/client';
import InfoView from './Pages/info';
import SettingsView from './Pages/setting';
import { DrawerNavigator, StackNavigator } from 'react-navigation';

export const stackNavigator = StackNavigator({
  Info: { screen: InfoView },
  Settings: {screen: SettingsView },
  Bookmark: {screen: BookmarkView },
  Connections: {screen: ClientView},
}, {
  headerMode: 'none'
});

export const EasyRNRoute = DrawerNavigator({
  Home: {
    screen: App,
  },
  Stack: {
    screen: stackNavigator
  }
}, {
  contentComponent: DrawerMenu,
  contentOptions: {
    activeTintColor: '#e91e63',
    style: {
      flex: 1,
      paddingTop: 15,
    }
  }
});

Drawer-toolbar-android.js :-

import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    StatusBar,
    View
} from 'react-native';
import { NavigationActions } from 'react-navigation'
import { COLOR, ThemeProvider, Toolbar, Drawer, Avatar } from 'react-native-material-ui';
import Container from '../Container';
import LoginScreen from '../login/LoginScreen';

const uiTheme = {
    palette: {
        primaryColor: COLOR.green500,
        accentColor: COLOR.pink500,
      },
    toolbar: {
        container: {
            height: 70,
            paddingTop: 20,
          },
      },
      avatar: {
          container: {
              backgroundColor: '#333'
          }
      }
  };

export default class DrawerMenu extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
        active: 'people',
      };
  }
handleLogoutPress = () => {
//    AsyncStorage.setItem('SignedUpuser', '');
this.props
               .navigation
               .dispatch(NavigationActions.reset(
                 {
                    index: 0,
                    actions: [
                      NavigationActions.navigate({ routeName: 'LoginScreen'})
                    ]
                  }));
//     this.props.navigation.dispatch(NavigationActions.back());
  };
  _setInfoActive() {
    this.setState({ active: 'info' });
  }

  render() {
    return (
        <ThemeProvider uiTheme={uiTheme}>
                <Container>
                    <StatusBar backgroundColor="rgba(0, 0, 0, 0.2)" translucent />
                    <Toolbar
                    leftElement="arrow-back"
                    onLeftElementPress={() => this.props.navigation.navigate('DrawerClose')}
                    centerElement="Menu"
                />
                    <View style={styles.container}>
                        <Drawer>
                            <Drawer.Header >
                                <Drawer.Header.Account
                                style={{
                                    container: { backgroundColor: '#fafafa' },
                                }}
                                avatar={<Avatar text={'S'} />}
//                                accounts={[
//                                    { avatar: <Avatar text="H" /> },
//                                    { avatar: <Avatar text="L" /> },
//                                ]}
                                footer={{
                                    dense: true,
                                    centerElement: {
                                        primaryText: 'Siddharth',
                                        secondaryText: 'I am DONE now',
                                    },

                                  }}
                            />
                            </Drawer.Header>
                            <Drawer.Section
                            style={{
                                label: {color: '#0000ff'}
                            }}
                            divider
                            items={[
                                {
                                    icon: 'bookmark-border', value: 'Bookmarks',
                                    active: this.state.active == 'bookmark',
                                    onPress: () => {
                                        this.setState({ active: 'bookmark' });
                                        this.props.navigation.navigate('Bookmark');
                                      },
                                  },
                                {
                                    icon: 'people', value: 'Connections',
                                    active: this.state.active == 'Connection',
                                    onPress: () => {
                                        this.setState({ active: 'Connection' });
                                        this.props.navigation.navigate('Connections');
                                      },
                                  },
                            ]}
                        />
                            <Drawer.Section
                            title="Personal"
                            items={[
                                {
                                    icon: 'info', value: 'Info',
                                    active: this.state.active == 'info',
                                    onPress: () => {
                                        this.setState({ active: 'info' });
                                        //this.props.navigation.navigate('DrawerClose');
                                        this.props.navigation.navigate('Info');
                                      },
                                  },
                                {
                                    icon: 'settings', value: 'Settings',
                                    active: this.state.active == 'settings',
                                    onPress: () => {
                                        this.setState({ active: 'settings' });
                                        this.props.navigation.navigate('Settings');
                                      },
                                  },
                                   {
                                    icon: 'logout', value: 'Logout',
                                    active: this.state.active == 'logout',
                                    onPress: () => {
                                    this.handleLogoutPress();
                                     },
                                      },
                            ]}
                        />
                        </Drawer>
                    </View>
                </Container>
            </ThemeProvider>
    );
  }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F5FCFF',
      },
    header: {
        backgroundColor: '#455A64',
      },
    welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
      },
    instructions: {
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5,
      },
  });

The above is the stack architecture i am using inside my application and as you can see that my Main screen is LOGIN screen and i do have option for LOGOUT from application in my Drawer(side menu). What i eaxtly want is that when user click on logout he/she should get redirected to LOGIN screen . i have googled about this and got to know about two ways of doing it , but both the ways are not working for me , may be i am using them in wrong way. so i am here to seek your help .

The two methods are :-

1)

this.props
               .navigation
               .dispatch(NavigationActions.reset(
                 {
                    index: 0,
                    actions: [
                      NavigationActions.navigate({ routeName: 'LoginScreen'})
                    ]
                  }));

2) this.props.navigation.dispatch(NavigationActions.back());

this question may seems silly to you but i am really stuck at this point and just want to know how can i  figure this out.Any help would be greatly Appreciated!!!!
Thanks in advance.

Body:
Modal StackNavigator containing a Dismissable StackNavigator

Requires: react-navigation version: 1.0.0

Goal: Navigate from App TabNavigator to Screen 1 to Screen 2 to Screen N and then directly back to App TabNavigator.

Navigation hierarchy:

RootNavigator StackNavigator {mode: 'modal'}

App TabNavigator

TabA Screen

TabB Screen

TabC Screen

ModalScreen Screen

ModalStack DismissableStackNavigator

Screen 1 ModalStackScreen

Screen 2 ModalStackScreen

Screen N ModalStackScreen

Demo

package.json

{
  "name": "HelloWorld",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "react": "16.0.0-alpha.6",
    "react-native": "0.44.0",
    "react-navigation": "^1.0.0"
  },
  "devDependencies": {
    "babel-jest": "20.0.3",
    "babel-preset-react-native": "1.9.2",
    "jest": "20.0.3",
    "react-test-renderer": "16.0.0-alpha.6"
  },
  "jest": {
    "preset": "react-native"
  }
}

index.ios.js (or index.android.js)

import React from 'react'
import {
  AppRegistry,
  Button,
  Text,
  View
} from 'react-native'
import {
  StackNavigator,
  TabNavigator
} from 'react-navigation'

class TabA extends React.Component {
  state = {
    startScreen: 'none',
    returnScreen: 'none'
  }
  render () {
    return (
      <View style={{ padding: 40, paddingTop: 64 }}>
        <Text style={{ fontSize: 20 }}>{this.constructor.name}</Text>
        <Text>startScreen: {this.state.startScreen}</Text>
        <Text>returnScreen: {this.state.returnScreen}</Text>
        <Button
          title="Open ModalScreen"
          onPress={() => this.props.navigation.navigate('ModalScreen', {
            startScreen: this.constructor.name,
            setParentState: (state) => this.setState(state)
          })}
        />
        <Button
          title="Open ModalStack"
          onPress={() => this.props.navigation.navigate('ModalStack', {
            startScreen: this.constructor.name,
            setParentState: (state) => this.setState(state)
          })}
        />
      </View>
    )
  }
}

class TabB extends TabA {}
class TabC extends TabA {}

class ModalScreen extends React.Component {
  render () {
    const {
      startScreen,
      setParentState
    } = this.props.navigation.state.params
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text style={{ fontSize: 20 }}>{this.constructor.name}</Text>
        <Button
          title="Close"
          onPress={() => {
            setParentState({
              startScreen,
              returnScreen: this.constructor.name
            })
            this.props.navigation.goBack()
          }}
        />
      </View>
    )
  }
}

const DismissableStackNavigator = (routes, options) => {
  const StackNav = StackNavigator(routes, options)

  return class DismissableStackNav extends React.Component {
    static router = StackNav.router

    render () {
      const { state, goBack } = this.props.navigation
      const screenProps = {
        ...this.props.screenProps,
        dismissStackNav: () => goBack(state.key)
      }
      return (
        <StackNav
          screenProps={screenProps}
          navigation={this.props.navigation}
        />
      )
    }
  }
}

class ModalStackScreen extends React.Component {
  render () {
    const screenNumber = this.props.navigation.state.params && this.props.navigation.state.params.screenNumber || 0
    const {
      startScreen,
      setParentState
    } = this.props.navigation.state.params
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text style={{ fontSize: 20 }}>{this.constructor.name + screenNumber}</Text>
        <View style={{
          flexDirection: 'row',
          justifyContent: 'space-between'
        }}>
          <Button
            title={screenNumber === 0 ? "Close" : "Back"}
            onPress={() => this.props.navigation.goBack(null)}
          />
          <Button
            title="Save"
            onPress={() => {
              setParentState({
                startScreen,
                returnScreen: this.constructor.name + screenNumber
              })
              this.props.screenProps.dismissStackNav()
            }}
          />
          <Button
            title="Next"
            onPress={() => this.props.navigation.navigate('ModalStackScreen', {
              screenNumber: screenNumber + 1,
              startScreen,
              setParentState
            })}
          />
        </View>
      </View>
    )
  }
}

const TabNav = TabNavigator(
  {
    TabA: {
      screen: TabA
    },
    TabB: {
      screen: TabB
    },
    TabC: {
      screen: TabC
    }
  }
)

const ModalStack = DismissableStackNavigator(
  {
    ModalStackScreen: {
      screen: ModalStackScreen
    }
  },
  {
    headerMode: 'none'
  }
)

const RootStack = StackNavigator(
  {
    Main: {
      screen: TabNav,
    },
    ModalScreen: {
      screen: ModalScreen,
    },
    ModalStack: {
      screen: ModalStack
    }
  },
  {
    mode: 'modal',
    headerMode: 'none'
  }
)

class App extends React.Component {
  render () {
    return <RootStack />
  }
}

AppRegistry.registerComponent('HelloWorld', () => App)

Previous Answer

This solution is a sledgehammer. It causes the screen of the default tab in the TabNavigator to unmount and then mount again. If the Screen a tab launching the Modal with the StackNavigator passes some callbacks to update it's state, these callbacks will be called when the Screen is unmounted.

The solution was to add key: null to the reset object:

this.props.navigation.dispatch(NavigationActions.reset({
  index: 0,
  key: null,
  actions: [
    NavigationActions.navigate({ routeName: 'App'})
  ]
}))

I was tipped off by this comment.

(FYI - I got here via your comment asking for help.)


问:
Generalization vs Specialization of DB table
When I want to design database tables that model a finite parent-child relationship, for e.g., computer as parent, and the components inside as the child; or a simple organizational hierarchy, I am usually torn at which approach to use -

A 'specialized table' approach, in which I create a table for each of the possible entity. In the computer component example, I would have a Computer table and a Component table, with the ComputerID as FK in the Component table referencing back to Computer.ComputerID.
or

A 'generalized table approach, in which I have one table table called Component, with ComponentID as PK, and a ParentComponentID as FK referencing to its parent's ComponentID.

答:
The reason I choose option 1 over 2 most of the time is because it is easier to pull my parent rows out of the database.  Otherwise, you have to write the sql statement such that you get the rows from the table that have children rows, but only those.  It gets messy quick.

If you're using any of the common relational databases, then use them the way they're designed to be used.

OwnerDisplayName: Nick DeVore

ContentLicense: CC BY-SA 2.5


问:
.NET project build automation
I'm very green when it comes to build automation under windows and capability of that OS.
So I'll explain what I would like to achieve bringing up Debian scenario from my previous work. So I had 2 pc, local & remote. On my local PC I launched script which:

downloaded latest version from source control

did some build stuff, renaming files according to build params etc

created zipped bundle

copied zipped bundle to remote live host

amended application entrypoint config file on live host (PHP application) so that application is in "offline" mode

started to unzip bundle

when package is unzipped, script revert changes in some files and application is back in "online" mode

I  guess that some of that actions will reqiure only FTP server. But what about performing unzip/rename , on linux I had remote access to command line. How is that with Windows. What tools / apps / services will I require to perform above stuff?

Thanks, Pawel

答:
Script wise you have several choices on Windows:
 1. Native batch files (.BAT) - can run everything you can run from a command line
 2. Visual Basic Script (.VBS) - gives you some more freedom, people have done some really nice things with it, personally I really dislike it though.

Files can be zipped and unzipped using the "gzip" utility.

The problems start when you want some user interaction, this can be done but gets cumbersome (looks like you don't need that anyway). Or when you want to do something on a remote machine. The second problem is much more serious and personally I haven't found a build in way to run something on a remote machine without connecting to it.

Luckily, the choices for external tools are plenty.
You can install Perl,Ruby, Python.. etc. interpretors on one or both machines to keep the environment familiar. You will probably want to take a look at http://www.cygwin.com/ too, in addition to scripting capabilities it can also be used to open an SSH connection from a remote machine.

Title: .NET project build automation


问:
IoC (Ninject) and Factories
If I have the following code:

```<code>public class RobotNavigationService : IRobotNavigationService {
  public RobotNavigationService(IRobotFactory robotFactory) {
    //...
  }
}
public class RobotFactory : IRobotFactory {
  public IRobot Create(string nameOfRobot) {
    if (name == "Maximilian") {
      return new KillerRobot();
    } else {
      return new StandardRobot();
    }
  }
}
</code>```

My question is what is the proper way to do Inversion of Control here? I don't want to add the KillerRobot and StandardRobot concretes to the Factory class do I? And I don't want to bring them in via a IoC.Get<> right? bc that would be Service Location not true IoC right? Is there a better way to approach the problem of switching the concrete at runtime?

答:
I was looking for a way to clean up a massive switch statement that returned a C# class to do some work (code smell here).

I didn't want to explicitly map each interface to its concrete implementation in the ninject module (essentially a mimic of lengthy switch case, but in a diff file) so I setup the module to bind all the interfaces automatically:

```<code>public class FactoryModule: NinjectModule
{
    public override void Load()
    {
        Kernel.Bind(x => x.FromThisAssembly()
                            .IncludingNonPublicTypes()
                            .SelectAllClasses()
                            .InNamespaceOf<FactoryModule>()
                            .BindAllInterfaces()
                            .Configure(b => b.InSingletonScope()));
    }
}
</code>```

Then create the factory class, implementing the StandardKernal which will Get the specified interfaces and their implementations via a singleton instance using an IKernal:

```<code>    public class CarFactoryKernel : StandardKernel, ICarFactoryKernel{
    public static readonly ICarFactoryKernel _instance = new CarFactoryKernel();

    public static ICarFactoryKernel Instance { get => _instance; }

    private CarFactoryKernel()
    {
        var carFactoryModeule = new List<INinjectModule> { new FactoryModule() };

        Load(carFactoryModeule);
    }

    public ICar GetCarFromFactory(string name)
    {
        var cars = this.GetAll<ICar>();
        foreach (var car in cars)
        {
            if (car.CarModel == name)
            {
                return car;
            }
        }

        return null;
    }
}

public interface ICarFactoryKernel : IKernel
{
    ICar GetCarFromFactory(string name);
}
</code>```

Then your StandardKernel implementation can get at any interface by the identifier of you choice on the interface decorating your class.

e.g.:

```<code>    public interface ICar
{
    string CarModel { get; }
    string Drive { get; }
    string Reverse { get; }
}

public class Lamborghini : ICar
{
    private string _carmodel;
    public string CarModel { get => _carmodel; }
    public string Drive => "Drive the Lamborghini forward!";
    public string Reverse => "Drive the Lamborghini backward!";

    public Lamborghini()
    {
        _carmodel = "Lamborghini";
    }
}
</code>```

Usage:

```<code>        [Test]
    public void TestDependencyInjection()
    {
        var ferrari = CarFactoryKernel.Instance.GetCarFromFactory("Ferrari");
        Assert.That(ferrari, Is.Not.Null);
        Assert.That(ferrari, Is.Not.Null.And.InstanceOf(typeof(Ferrari)));

        Assert.AreEqual("Drive the Ferrari forward!", ferrari.Drive);
        Assert.AreEqual("Drive the Ferrari backward!", ferrari.Reverse);

        var lambo = CarFactoryKernel.Instance.GetCarFromFactory("Lamborghini");
        Assert.That(lambo, Is.Not.Null);
        Assert.That(lambo, Is.Not.Null.And.InstanceOf(typeof(Lamborghini)));

        Assert.AreEqual("Drive the Lamborghini forward!", lambo.Drive);
        Assert.AreEqual("Drive the Lamborghini backward!", lambo.Reverse);
    }
</code>```

Title: IoC (Ninject) and Factories

Body:
If I have the following code:

public class RobotNavigationService : IRobotNavigationService {
  public RobotNavigationService(IRobotFactory robotFactory) {
    //...
  }
}
public class RobotFactory : IRobotFactory {
  public IRobot Create(string nameOfRobot) {
    if (name == "Maximilian") {
      return new KillerRobot();
    } else {
      return new StandardRobot();
    }
  }
}

My question is what is the proper way to do Inversion of Control here? I don't want to add the KillerRobot and StandardRobot concretes to the Factory class do I? And I don't want to bring them in via a IoC.Get<> right? bc that would be Service Location not true IoC right? Is there a better way to approach the problem of switching the concrete at runtime?

Body:
I was looking for a way to clean up a massive switch statement that returned a C# class to do some work (code smell here).

I didn't want to explicitly map each interface to its concrete implementation in the ninject module (essentially a mimic of lengthy switch case, but in a diff file) so I setup the module to bind all the interfaces automatically:

public class FactoryModule: NinjectModule
{
    public override void Load()
    {
        Kernel.Bind(x => x.FromThisAssembly()
                            .IncludingNonPublicTypes()
                            .SelectAllClasses()
                            .InNamespaceOf<FactoryModule>()
                            .BindAllInterfaces()
                            .Configure(b => b.InSingletonScope()));
    }
}

Then create the factory class, implementing the StandardKernal which will Get the specified interfaces and their implementations via a singleton instance using an IKernal:

    public class CarFactoryKernel : StandardKernel, ICarFactoryKernel{
    public static readonly ICarFactoryKernel _instance = new CarFactoryKernel();

    public static ICarFactoryKernel Instance { get => _instance; }

    private CarFactoryKernel()
    {
        var carFactoryModeule = new List<INinjectModule> { new FactoryModule() };

        Load(carFactoryModeule);
    }

    public ICar GetCarFromFactory(string name)
    {
        var cars = this.GetAll<ICar>();
        foreach (var car in cars)
        {
            if (car.CarModel == name)
            {
                return car;
            }
        }

        return null;
    }
}

public interface ICarFactoryKernel : IKernel
{
    ICar GetCarFromFactory(string name);
}

Then your StandardKernel implementation can get at any interface by the identifier of you choice on the interface decorating your class.

e.g.:

    public interface ICar
{
    string CarModel { get; }
    string Drive { get; }
    string Reverse { get; }
}

public class Lamborghini : ICar
{
    private string _carmodel;
    public string CarModel { get => _carmodel; }
    public string Drive => "Drive the Lamborghini forward!";
    public string Reverse => "Drive the Lamborghini backward!";

    public Lamborghini()
    {
        _carmodel = "Lamborghini";
    }
}

Usage:

        [Test]
    public void TestDependencyInjection()
    {
        var ferrari = CarFactoryKernel.Instance.GetCarFromFactory("Ferrari");
        Assert.That(ferrari, Is.Not.Null);
        Assert.That(ferrari, Is.Not.Null.And.InstanceOf(typeof(Ferrari)));

        Assert.AreEqual("Drive the Ferrari forward!", ferrari.Drive);
        Assert.AreEqual("Drive the Ferrari backward!", ferrari.Reverse);

        var lambo = CarFactoryKernel.Instance.GetCarFromFactory("Lamborghini");
        Assert.That(lambo, Is.Not.Null);
        Assert.That(lambo, Is.Not.Null.And.InstanceOf(typeof(Lamborghini)));

        Assert.AreEqual("Drive the Lamborghini forward!", lambo.Drive);
        Assert.AreEqual("Drive the Lamborghini backward!", lambo.Reverse);
    }


答: Make sure the directory of the files style.css and ge4l.js are correct and appropriate to the wp-admin file. Or try puting ~ sign at the directory shown in your code.

Title: Cannot get my own JS file to work with Wordpress (4.9).

Body:
I am in a bit of a pickle, lol.

Here is my function:

  function start_group_escapes_4_less() {

    wp_enqueue_style( 'style', get_stylesheet_uri() . '/style.css');
    wp_enqueue_script( 'ge4l', get_stylesheet_uri() . '/js/ge4l.js', array('jquery'), null, true);

  }

  add_action( 'wp_enqueue_scripts', 'start_group_escapes_4_less' );

Everywhere I checked, the syntax is right. Or is it?
Help :(


问:
How to set the icon and title on Android TV home screen for the currently running task
I have enabled picture-in-picture mode for an Android TV app based on this guide: https://developer.android.com/guide/topics/ui/picture-in-picture.html

When I enter PiP mode, and navigate to the home screen of the Android home screen, it shown at the top the currently running task (PiP window) with an icon an title and options to Open and Close.

I could not find any documentation on how to set the the title and the icon (but most importantly the title). I have tried setting the ActivityManager.TaskDescription but without any luck. Also note that I do have an app title set in the Manifest, but that is not being shown here. Also note that in the task switcher, the app title and icon is shown correctly.

Any ideas how to set the (No title program) from the screenshot?

Tested on Android TV API 26, 27, as Picture-in-Picture is only available since Oreo.

答:
If you implement MediaSession, the title will appear. The system evaluates the MediaSession similar to how notifications with MediaSession work on phones.

There is an activity that demonstrates how MediaSession can affect PIP actions in the android-PictureInPicture sample. This is a bug in the sample, thank you for logging it.

To get the title to appear, you will need to update the meta data on the media session.

```<code>MediaMetadataCompat metadata = new MediaMetadataCompat.Builder()
            .putString(
                 MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE,
                "Big Buck Bunny")
            ...
            .build();
mSession.setMetadata(metadata);
</code>```

Body:
If you implement MediaSession, the title will appear. The system evaluates the MediaSession similar to how notifications with MediaSession work on phones.

There is an activity that demonstrates how MediaSession can affect PIP actions in the android-PictureInPicture sample. This is a bug in the sample, thank you for logging it.

To get the title to appear, you will need to update the meta data on the media session.

MediaMetadataCompat metadata = new MediaMetadataCompat.Builder()
            .putString(
                 MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE,
                "Big Buck Bunny")
            ...
            .build();
mSession.setMetadata(metadata);


问:
Elasticsearch query for OR and AND functions
I'm new to elasticsearch and am doing a bit of query basics.

I have to retrieve count of those documents that:
Either contain netflow.src_port ['10','11','12'] OR netflow.dst_port ['20','21','22']
AND timestamp being within the last 15 minutes.

I have a basic query as below:

```<code>    body: {
    "query": {
      "bool":{
        "should": [
          {"terms": { "netflow.src_port": ["10","11","12"] }},
          {"terms": { "netflow.dst_port": ["20","21","22"] }}
        ],
        "must": [
          {"range" : {
            "@timestamp" : {
              "gt" : "now-15m"
            }
          }}
        ]
      }
    }
  }
</code>```

Going by the official documentation, should is used to note that: a document need not contain src_port or dst_port in that range, but if it does, then calculate cost accordingly.

What I actually need is an or condition for them.

If my explaination is not clear, the below might convey what I'm trying to achieve:

```<code>if( (netflow.src_port contains [10 or 11 or 12] || netflow.dst_port contains [20 or 21 or 22]) && timestamp is within the last 15m.
</code>```

What exactly do I need to do to get the desired result?

答:
Try changing the should section of your query to include a minimum_should_match attribute. e.g.

```<code>{
  "bool":{
    "should": [
      {"terms": { "netflow.src_port": ["10","11","12"] }},
      {"terms": { "netflow.dst_port": ["20","21","22"] }}
    ],
    "must": [
      {"range" : {
        "@timestamp" : {
          "gt" : "now-15m"
        }
      }}
    ],
    "minimum_should_match": 1
  }
}
</code>```

Body:
I'm new to elasticsearch and am doing a bit of query basics.

I have to retrieve count of those documents that:
Either contain netflow.src_port ['10','11','12'] OR netflow.dst_port ['20','21','22']
AND timestamp being within the last 15 minutes.

I have a basic query as below:

    body: {
    "query": {
      "bool":{
        "should": [
          {"terms": { "netflow.src_port": ["10","11","12"] }},
          {"terms": { "netflow.dst_port": ["20","21","22"] }}
        ],
        "must": [
          {"range" : {
            "@timestamp" : {
              "gt" : "now-15m"
            }
          }}
        ]
      }
    }
  }

Going by the official documentation, should is used to note that: a document need not contain src_port or dst_port in that range, but if it does, then calculate cost accordingly.

What I actually need is an or condition for them.

If my explaination is not clear, the below might convey what I'm trying to achieve:

if( (netflow.src_port contains [10 or 11 or 12] || netflow.dst_port contains [20 or 21 or 22]) && timestamp is within the last 15m.

What exactly do I need to do to get the desired result?

Body:
Try changing the should section of your query to include a minimum_should_match attribute. e.g.

{
  "bool":{
    "should": [
      {"terms": { "netflow.src_port": ["10","11","12"] }},
      {"terms": { "netflow.dst_port": ["20","21","22"] }}
    ],
    "must": [
      {"range" : {
        "@timestamp" : {
          "gt" : "now-15m"
        }
      }}
    ],
    "minimum_should_match": 1
  }
}


问:
Scala worksheet not getting evaluated on changing scala compiler version
I have just started with scala and I am using Scala IDE to run my scripts.

I created some basic scala worksheets which compiles and shows the output on the right side in the IDE.

The default scala version that came built-in with Scala IDE is 2.12.2

I decided to move to scala version 2.11.8(which also came built in with the IDE) after facing some dependency issues.

I changed the Scala Installation to "Fixed Scala Installation: 2.11.8(built-in)" by right-clicking project->Properties->Scala Compiler

As soon as I changed the installation my all worksheets stopped working. They are not getting evaluated. They are also not getting saved. I saved the scripts multiple times but the files are still showing unsaved changes(*). I also restarted Scala IDE, but the problem didn't solve.

Is there any thing else that I need to change? What wrong am I doing?
Also the project name does not contain any SPACE(suggest as a possible cause for this problem in this answer)

The problem is occurring only when I change Scala version

答:
I have the same problem. It seems the worksheet only works with default Scala version in Scala IDE. I have tried uninstall the default Scala version and install a different Scala version, say 2.11.8. I can do that, but I won't be able to uninstall the Scala Worksheet and reinstall another version. The IDE will nevertheless stick with the original scala IDE build version and don't think you can install a version earlier than that. So I am stuck. The uninstall and install is done by clicking Help -> Install New Software...

Since i need to install different Scala version in Eclipse anyway, I just go download and install a bare-bones version Eclipse and install the Scala version and the Scala Worksheet version I want. The repository I use is Scala IDE - http://download.scala-ide.org/sdk/lithium/e46/scala211/stable/site for Scala version 2.11.8.


问:
PHP Coding Style Function vs Passing Variables
A bit new to the whole PHP thing.

Just wanna ask, which is better in regards to performance and security. I know both has its pros and cons, but just cant seem to come to a conclusion on which could be better for overall performance and security.

Use a PHP file with loads of functions. So every page I have will "include" the function php file, thus functions can be called in any given page.

OR

Have a PHP file that accept parameter input(not sure if that is what you call it). For example function.PHP?id=100

Any comments?

Thanks everyone :)

答:
Welcome Tak4evr

I would use Object Orientated design practices over this method. Procedural code, based on many functions is hard to follow and therefore expensive to maintain.

But given the choices I would go with your first option:

Use a PHP file with loads of functions. So every page I have will "include" the function php file, thus functions can be called in any given page.

You would include this file and rather than using function.php?id=100 as you suggested you should use something more descriptive which then uses your functions.

For example use clients.php?id=100 then use clients.php to get the id, and pass that id to one of your functions.

Hope that helps.