问:
How to mathematically evaluate a string like "2-1" to produce "1"?
I was just wondering if PHP has a function that can take a string like 2-1 and produce the arithmetic result of it?

Or will I have to do this manually with explode() to get the values left and right of the arithmetic operator?

答:
Here is a somewhat verbose bit of code I rolled for another SO question.  It does conform to <s>BO</s>MDAS without eval(), but is not equipped to do complex/higher-order/parenthetical expressions.  This library-free approach pulls the expression apart and systematically reduces the array of components until all of the operators are removed.  It certainly works for your sample expression: 2-1 ;)

preg_match() checks that each operator has a numeric substring on each side.

preg_split() divides the string into an array of alternating numbers and operators.

array_search() finds the index of the targeted operator, while it exists in the array.

array_splice() replaces the operator element and the elements on either side of it with a new element that contains the mathematical result of the three elements removed.

** updated to allow negative numbers **

Code: (Demo)

```<code>$expression = "-11+3*1*4/-6-12";
if (!preg_match('~^-?\d*\.?\d+([*/+-]-?\d*\.?\d+)*$~', $expression)) {
    echo "invalid expression";
} else {
    $components = preg_split('~(?<=\d)([*/+-])~', $expression, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
    var_export($components);  // ['-11','+','3','*','1','*','4','/','-6','-','12']
    while (($index = array_search('*',$components)) !== false) {
        array_splice($components, $index - 1, 3, $components[$index - 1] * $components[$index + 1]);
        var_export($components);
        // ['-11','+','3','*','4','/','-6','-','12']
        // ['-11','+','12','/','-6','-','12']
    }
    while (($index = array_search('/', $components)) !== false) {
        array_splice($components, $index - 1, 3, $components[$index - 1] / $components[$index + 1]);
        var_export($components);  // [-'11','+','-2','-','12']
    }
    while (($index = array_search('+', $components)) !== false) {
        array_splice($components, $index - 1, 3, $components[$index - 1] + $components[$index + 1]);
        var_export($components);  // ['-13','-','12']
    }
    while (($index = array_search('-', $components)) !== false) {
        array_splice($components, $index - 1, 3, $components[$index - 1] - $components[$index + 1]);
        var_export($components); // [-25]
    }
    echo current($components);  // -25
}
</code>```

Here is a demo of the <s>B</s>OMDAS version that uses php's pow() when ^ is encountered between two numbers (positive or negative).

I don't think I'll ever bother writing a version that handles parenthetical expressions ... but we'll see how bored I get.

Body:
Here is a somewhat verbose bit of code I rolled for another SO question.  It does conform to <s>BO</s>MDAS without eval(), but is not equipped to do complex/higher-order/parenthetical expressions.  This library-free approach pulls the expression apart and systematically reduces the array of components until all of the operators are removed.  It certainly works for your sample expression: 2-1 ;)

preg_match() checks that each operator has a numeric substring on each side.

preg_split() divides the string into an array of alternating numbers and operators.

array_search() finds the index of the targeted operator, while it exists in the array.

array_splice() replaces the operator element and the elements on either side of it with a new element that contains the mathematical result of the three elements removed.

** updated to allow negative numbers **

Code: (Demo)

$expression = "-11+3*1*4/-6-12";
if (!preg_match('~^-?\d*\.?\d+([*/+-]-?\d*\.?\d+)*$~', $expression)) {
    echo "invalid expression";
} else {
    $components = preg_split('~(?<=\d)([*/+-])~', $expression, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
    var_export($components);  // ['-11','+','3','*','1','*','4','/','-6','-','12']
    while (($index = array_search('*',$components)) !== false) {
        array_splice($components, $index - 1, 3, $components[$index - 1] * $components[$index + 1]);
        var_export($components);
        // ['-11','+','3','*','4','/','-6','-','12']
        // ['-11','+','12','/','-6','-','12']
    }
    while (($index = array_search('/', $components)) !== false) {
        array_splice($components, $index - 1, 3, $components[$index - 1] / $components[$index + 1]);
        var_export($components);  // [-'11','+','-2','-','12']
    }
    while (($index = array_search('+', $components)) !== false) {
        array_splice($components, $index - 1, 3, $components[$index - 1] + $components[$index + 1]);
        var_export($components);  // ['-13','-','12']
    }
    while (($index = array_search('-', $components)) !== false) {
        array_splice($components, $index - 1, 3, $components[$index - 1] - $components[$index + 1]);
        var_export($components); // [-25]
    }
    echo current($components);  // -25
}

Here is a demo of the <s>B</s>OMDAS version that uses php's pow() when ^ is encountered between two numbers (positive or negative).

I don't think I'll ever bother writing a version that handles parenthetical expressions ... but we'll see how bored I get.


来源: stackexchange

问:
How can I return null or bool from a function
I have this function:

```<code>public bool GetBoolSetting(Settings setting)
{
    return int.Parse(GetStringSetting(setting)) == 0 ? false : true;
}
</code>```

There is a problem in that GetStringSetting(setting) can return null, "0" or "1".  When it returns a null I get an exception.

Is it possible for me to make the GetBoolSetting function return a null if this happens?

答:
You get the exception because int.Parse can't handle the null input. You have to check it before.

If you want to return null if GetStringSetting returns null, you need to change the return type to a Nullable<bool> (short by appending a question mark: bool?), e.g.:

```<code>public bool? GetBoolSetting(Settings setting)
{
  var strSetting = GetStringSetting(setting);
  if (string.IsNullOrEmpty(strSetting))
    return null;
  return int.Parse(strSetting) == 0 ? false : true;
}
</code>```

When using the return value, you have to check whether it has a value so that it is more complicated to handle:

```<code>var boolSetting = GetBoolSetting(...);
if (boolSetting.HasValue)
{
    // Check boolSetting.Value
}
else
{
     // Handle null value
}
</code>```

For an overview of nullable data types, see this link.

ContentLicense: CC BY-SA 3.0

Body:
I have this function:

public bool GetBoolSetting(Settings setting)
{
    return int.Parse(GetStringSetting(setting)) == 0 ? false : true;
}

There is a problem in that GetStringSetting(setting) can return null, "0" or "1".  When it returns a null I get an exception.

Is it possible for me to make the GetBoolSetting function return a null if this happens?

Body:
You get the exception because int.Parse can't handle the null input. You have to check it before.

If you want to return null if GetStringSetting returns null, you need to change the return type to a Nullable<bool> (short by appending a question mark: bool?), e.g.:

public bool? GetBoolSetting(Settings setting)
{
  var strSetting = GetStringSetting(setting);
  if (string.IsNullOrEmpty(strSetting))
    return null;
  return int.Parse(strSetting) == 0 ? false : true;
}

When using the return value, you have to check whether it has a value so that it is more complicated to handle:

var boolSetting = GetBoolSetting(...);
if (boolSetting.HasValue)
{
    // Check boolSetting.Value
}
else
{
     // Handle null value
}

For an overview of nullable data types, see this link.


问:
Copying a Laravel's .env file into a Docker container
Setup

I'm running Docker on my Ubuntu server and I'm trying create a Laravel container to run my website with artisan. The Laravel project is inside a GitHub Repository and I clone the project to the docker container with a dockerfile.

Problem

Laravel projects are dependent on the .env (environment files) which are not included in the repo project, for security reasons. So when I clone the repo to the docker container it doesn't include the .env file and thereby doesn't run the website properly. I have an .env file locally on my Ubuntu that I'm trying to COPY to the docker container Laravel project folder, ofcourse it doesn't work. This is because it's looking for the directory in the docker container's file structure.

Error

```<code>Step 6/11 : COPY /containers/.env .env

lstat containers/.env: no such file or directory
</code>```

Question

How can I copy the .env file from the ubuntu server to the docker container with the COPY command?

file structure (Ubuntu) source from:

```<code>root/
  containers/
    - docker-compose
    - .env
</code>```

file structure (docker container) source to:

```<code>root/
  var/www/
</code>```

dockerfile

```<code>FROM hitalos/laravel

RUN git config --system http.sslverify false

RUN git clone repo /var/www

RUN git checkout test

COPY /containers/.env .env

# Run Compser Install
RUN composer install -d /var/www
RUN php /var/www/artisan key:generate

WORKDIR /var/www

CMD php /var/www/artisan serve --port=80 --host=0.0.0.0
EXPOSE 80
</code>```

答:
Simply copying the .env file is not going to work since you also have to run a source command on the file and then an export command to add each environment variable to your path.

Since you are using docker-compose then you can use the env_file like so in your docker-compose.yml:

env_file:
    -.env

This should automatically set the values required by Laravel from your .env file when you build your conainer.

Body:
Setup

I'm running Docker on my Ubuntu server and I'm trying create a Laravel container to run my website with artisan. The Laravel project is inside a GitHub Repository and I clone the project to the docker container with a dockerfile.

Problem

Laravel projects are dependent on the .env (environment files) which are not included in the repo project, for security reasons. So when I clone the repo to the docker container it doesn't include the .env file and thereby doesn't run the website properly. I have an .env file locally on my Ubuntu that I'm trying to COPY to the docker container Laravel project folder, ofcourse it doesn't work. This is because it's looking for the directory in the docker container's file structure.

Error

Step 6/11 : COPY /containers/.env .env

lstat containers/.env: no such file or directory

Question

How can I copy the .env file from the ubuntu server to the docker container with the COPY command?

file structure (Ubuntu) source from:

root/
  containers/
    - docker-compose
    - .env

file structure (docker container) source to:

root/
  var/www/

dockerfile

FROM hitalos/laravel

RUN git config --system http.sslverify false

RUN git clone repo /var/www

RUN git checkout test

COPY /containers/.env .env

# Run Compser Install
RUN composer install -d /var/www
RUN php /var/www/artisan key:generate

WORKDIR /var/www

CMD php /var/www/artisan serve --port=80 --host=0.0.0.0
EXPOSE 80


问:
smack 4.2 . app always crashing if i build the connection
I alrdy read tons of resolutions here in stack but i cant resolve this problem.

I give my App Internet premissions

i use asynctask

my problem is the same. My app is always crashing if i start to build

I tried to do it with try catch . i also tried to do it with the expected thrown but nothing helps. I hope for an smack specialist who can help me out of this hell. Without the Builder the App is running fine without problems

MainActivity.class

```<code>import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        connectXmpp con= new connectXmpp();
        con.execute();
    }
}
</code>```

connectXmpp.class

```<code>import android.os.AsyncTask;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;

/**
 * Created by saddam on 08.07.2017.
 */

public class connectXmpp extends AsyncTask <Void,Void,Void>{
    public static XMPPTCPConnection connection;
    @Override
    protected Void doInBackground(Void... voids) {

        XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration
                .builder();
        config.setUsernameAndPassword("username","pw");
        config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
        config.setHost("dismail.de");
        config.setPort(5222);
        config.setDebuggerEnabled(true);
        XMPPTCPConnection.setUseStreamManagementDefault(true);
        connection = new XMPPTCPConnection(config.build());

        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
    }

}
</code>```

答:
okay seems like smack 4.2 has a bug. My problem resolve with using this dependencies:</p>

```<code>compile 'org.igniterealtime.smack:smack-android:4.1.1'
   compile 'org.igniterealtime.smack:smack-android-extensions:4.1.1'
   compile 'org.igniterealtime.smack:smack-core:4.1.1'
   compile 'org.igniterealtime.smack:smack-tcp:4.1.1'
   compile 'org.igniterealtime.smack:smack-extensions:4.1.1'
   compile 'org.igniterealtime.smack:smack-experimental:4.1.1'
   compile 'org.igniterealtime.smack:smack-resolver-minidns:4.1.1'
   compile 'org.igniterealtime.smack:smack-sasl-provided:4.1.1'
   compile 'org.igniterealtime.smack:smack-im:4.1.1'
   compile 'org.jxmpp:jxmpp-core:0.4.2-beta1'
   compile 'org.jxmpp:jxmpp-util-cache:0.4.2-beta1'
   compile 'de.measite.minidns:minidns:0.1.1'
</code>```

Body:
I alrdy read tons of resolutions here in stack but i cant resolve this problem.

I give my App Internet premissions

i use asynctask

my problem is the same. My app is always crashing if i start to build

I tried to do it with try catch . i also tried to do it with the expected thrown but nothing helps. I hope for an smack specialist who can help me out of this hell. Without the Builder the App is running fine without problems

MainActivity.class

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        connectXmpp con= new connectXmpp();
        con.execute();
    }
}

connectXmpp.class

import android.os.AsyncTask;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;

/**
 * Created by saddam on 08.07.2017.
 */

public class connectXmpp extends AsyncTask <Void,Void,Void>{
    public static XMPPTCPConnection connection;
    @Override
    protected Void doInBackground(Void... voids) {

        XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration
                .builder();
        config.setUsernameAndPassword("username","pw");
        config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
        config.setHost("dismail.de");
        config.setPort(5222);
        config.setDebuggerEnabled(true);
        XMPPTCPConnection.setUseStreamManagementDefault(true);
        connection = new XMPPTCPConnection(config.build());

        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
    }

}

Body:
okay seems like smack 4.2 has a bug. My problem resolve with using this dependencies:

compile 'org.igniterealtime.smack:smack-android:4.1.1'
   compile 'org.igniterealtime.smack:smack-android-extensions:4.1.1'
   compile 'org.igniterealtime.smack:smack-core:4.1.1'
   compile 'org.igniterealtime.smack:smack-tcp:4.1.1'
   compile 'org.igniterealtime.smack:smack-extensions:4.1.1'
   compile 'org.igniterealtime.smack:smack-experimental:4.1.1'
   compile 'org.igniterealtime.smack:smack-resolver-minidns:4.1.1'
   compile 'org.igniterealtime.smack:smack-sasl-provided:4.1.1'
   compile 'org.igniterealtime.smack:smack-im:4.1.1'
   compile 'org.jxmpp:jxmpp-core:0.4.2-beta1'
   compile 'org.jxmpp:jxmpp-util-cache:0.4.2-beta1'
   compile 'de.measite.minidns:minidns:0.1.1'


问:
php search help
following are my posted variables from search form:

```<code>$city = $_REQUEST['city'];
$location = $_REQUEST['location'];
$bedrooms = $_REQUEST['noofbedrooms'];
$addeddate = $_REQUEST['addeddate'];
$minprice = $_REQUEST['pricefrom'];
$maxprice = $_REQUEST['priceto'];
$minarea = $_REQUEST['areafrom'];
$maxarea = $_REQUEST['areato'];
$propertytype = $_REQUEST['proptype'];
</code>```

so far so good. Now i need some good suggestions for the following scenario.
Almost every element in my field are optional. That means i can get empty values in above variables.

What should be my scenario to create the mysql query for the above variables. On case can be that i use conditions for each and every scenario. eg

```<code>if($city=="")
  $query="";
elseif($location=="")
  $query="";
and so on....
</code>```

i need some professional approach for this.

答:
If all the query parts are built in the same way: WHERE fieldname='fieldvalue', you could use a lazy, loop-based approach:

```<code>$conditions = array();

foreach (array("city", "location", "noofbedrooms") as $field)
           // ^ add all fields as needed
 {
   // Check whether parameter was passed at all
   if (!array_key_exists($field, $_POST)) continue;

   // Check whether parameter is empty
   if (!empty($_POST[$field]))
    $conditions[]="`$field` = ".mysql_real_escape_string($_POST[$field]);
                                // ^ or whatever your database library
                                //   does for escaping

 }

 $query = "SELECT * from table where ".implode(" AND ", $conditions);
</code>```

ContentLicense: CC BY-SA 2.5

Title: php search help

Body:
following are my posted variables from search form:

$city = $_REQUEST['city'];
$location = $_REQUEST['location'];
$bedrooms = $_REQUEST['noofbedrooms'];
$addeddate = $_REQUEST['addeddate'];
$minprice = $_REQUEST['pricefrom'];
$maxprice = $_REQUEST['priceto'];
$minarea = $_REQUEST['areafrom'];
$maxarea = $_REQUEST['areato'];
$propertytype = $_REQUEST['proptype'];

so far so good. Now i need some good suggestions for the following scenario.
Almost every element in my field are optional. That means i can get empty values in above variables.

What should be my scenario to create the mysql query for the above variables. On case can be that i use conditions for each and every scenario. eg

if($city=="")
  $query="";
elseif($location=="")
  $query="";
and so on....

i need some professional approach for this.

Body:
If all the query parts are built in the same way: WHERE fieldname='fieldvalue', you could use a lazy, loop-based approach:

$conditions = array();

foreach (array("city", "location", "noofbedrooms") as $field)
           // ^ add all fields as needed
 {
   // Check whether parameter was passed at all
   if (!array_key_exists($field, $_POST)) continue;

   // Check whether parameter is empty
   if (!empty($_POST[$field]))
    $conditions[]="`$field` = ".mysql_real_escape_string($_POST[$field]);
                                // ^ or whatever your database library
                                //   does for escaping

 }

 $query = "SELECT * from table where ".implode(" AND ", $conditions);


问:
ms-access/database - How to handle deprecated items which are still needed
I am wondering how to handle entrys in a database which should not exist anymore but are still necessary for dependent tables.

Example: I have one table for parking spots, one for cars, and one for the time when a car parked in a specifiv spot. I want to keep track when wich car was on which slot. Lets assume one day one of the parking slots will get removed.

What now? If I delete the spot in the table and I make use of referential integrety all entrys from the past associated with this slot will vanish, thats not acceptable. But if I remove the referential integrity and only delete the slot I will have a lot of orphaned entrys in the table which stores the entrys when which car was parked in a spot.

I am pretty sure there must be a simple answer to handle this problem but unfortunately I was not able to specify the problem good enough to find a solution on stackoverflow/google. Therefore I have to ask.

答:
Normally, you would just put a flag on in the "parking space" table that says whether it is active or not.  Well, actually, perhaps not just a flag, but a date when it is first available and a date when it is no longer available.

Incorporating this into a data model is a bit trickier.  In MS Access, I would recommend that you do the date check when attempting to insert references to the space.  This can be handled with a trigger.


问:
Android start activity when app started
This android project is about Webview.
It start the activity when it click some button called goURL.
but is it possible to start some activity when the app started?(not activity from the button).
my guess is put something on onCreate

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

}

public void goURL(View view){
    TextView tvURL = (TextView)findViewById(R.id.txtURL);
    String url = tvURL.getText().toString();
    Log.i("URL", "Opening URL with WebView :" + url);

    final long startTime = System.currentTimeMillis();
    WebView webView = (WebView)findViewById(R.id.webView);

//webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

webView.loadUrl(url);
</code>```

My guess is that to create intent about view.
but not sure how to do it

答:
Of course, just load your webView reference and webView.loadUrl("http://..") in your onCreate section.

Make sure you've added the permission request in your manifest

A good tutorial - https://www.mkyong.com/android/android-webview-example/

Title: Android start activity when app started

Body:
This android project is about Webview.
It start the activity when it click some button called goURL.
but is it possible to start some activity when the app started?(not activity from the button).
my guess is put something on onCreate

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

}

public void goURL(View view){
    TextView tvURL = (TextView)findViewById(R.id.txtURL);
    String url = tvURL.getText().toString();
    Log.i("URL", "Opening URL with WebView :" + url);

    final long startTime = System.currentTimeMillis();
    WebView webView = (WebView)findViewById(R.id.webView);

//webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

webView.loadUrl(url);

My guess is that to create intent about view.
but not sure how to do it


问:
Retrofit Doesnt show nested arraylists
I am trying to download data from the url ( JSON ) =
https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json

for the networking i have used retrofit, and these are my classes, whenever i try to access the nested classes or lists, it throws a fatal error.

MainActivity

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

ArrayList<Recipe> mRecipies = new ArrayList<>();
public TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    text = (TextView)findViewById(R.id.text);
    IRecipe iRecipe = RetrofitBuilder.Retrieve();
    Call<ArrayList<Recipe>> recipe = iRecipe.getRecipe();

    recipe.enqueue(new Callback<ArrayList<Recipe>>() {
        @Override
        public void onResponse(Call<ArrayList<Recipe>> call, Response<ArrayList<Recipe>> response) {
            mRecipies = response.body();
            text.setText(mRecipies.get(3).getIngredients().size());
        }

        @Override
        public void onFailure(Call<ArrayList<Recipe>> call, Throwable t) {

        }
    });
</code>```

MyRecipe class

```<code>public class Recipe {

private String id;
private String name;
private List<Ingredients> ingredients = new ArrayList<>();
private List<Steps> steps = new ArrayList<>();
private String servings;

public Recipe(String id, String name,  String servings, List<Ingredients> ingredients, List<Steps> steps) {
    this.id = id;
    this.name = name;
    this.ingredients = ingredients;
    this.steps = steps;
    this.servings = servings;
}

public Recipe(){

}

public String getId() {
    return id;
}

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

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public List<Ingredients> getIngredients() {
    return ingredients;
}

public void setIngredients(List<Ingredients> ingredients) {
    this.ingredients = ingredients;
}

public List<Steps> getSteps() {
    return steps;
}

public void setSteps(List<Steps> steps) {
    this.steps = steps;
}

public String getServings() {
    return servings;
}

public void setServings(String servings) {
    this.servings = servings;
}
</code>```

}

My ingredients class

```<code>public class Ingredients  {

private String quantity;
private String measure;
private String ingredient;

public Ingredients(String quantity, String measure, String ingredient) {
    this.quantity = quantity;
    this.measure = measure;
    this.ingredient = ingredient;
}

public Ingredients(){

}

public String getQuantity() {
    return quantity;
}

public void setQuantity(String quantity) {
    this.quantity = quantity;
}

public String getMeasure() {
    return measure;
}

public void setMeasure(String measure) {
    this.measure = measure;
}

public String getIngredient() {
    return ingredient;
}

public void setIngredient(String ingredient) {
    this.ingredient = ingredient;
}
</code>```

}

Retrofit classes

Builder

```<code>        public final class RetrofitBuilder {
        static IRecipe iRecipe;

        public static IRecipe Retrieve() {

            Gson gson = new GsonBuilder().create();

            OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();

            iRecipe = new Retrofit.Builder()
                    .baseUrl("https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/")
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .callFactory(httpClientBuilder.build())
                    .build().create(IRecipe.class);

            return iRecipe;
        }
    }

Interface

    public interface IRecipe {
    @GET("baking.json")
    Call<ArrayList<Recipe>> getRecipe();
}
</code>```

Stack Trace

```<code> FATAL EXCEPTION: main
                                                                              Process: com.example.vamshi.retrofittrial, PID: 20350
                                                                              android.content.res.Resources$NotFoundException: String resource ID #0x9
                                                                                at android.content.res.Resources.getText(Resources.java:328)
                                                                                at android.content.res.MiuiResources.getText(MiuiResources.java:123)
                                                                                at android.widget.TextView.setText(TextView.java:4432)
                                                                                at com.example.vamshi.retrofittrial.MainActivity$1.onResponse(MainActivity.java:34)
                                                                                at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
                                                                                at android.os.Handler.handleCallback(Handler.java:742)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5527)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
</code>```

07-08 19:07:00.145 20350-20350/com.example.vamshi.retrofittrial E/MQSEventManagerDelegate: failed to get MQSService.

答:
Well, setText doesnt allow integers.

So instead of

```<code>text.setText(mRecipies.get(3).getIngredients().size());
</code>```

use

```<code>text.setText(String.valueof(mRecipies.get(3).getIngredients().size()));
</code>```

Title: Retrofit Doesnt show nested arraylists

Body:
I am trying to download data from the url ( JSON ) =
https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json

for the networking i have used retrofit, and these are my classes, whenever i try to access the nested classes or lists, it throws a fatal error.

MainActivity

public class MainActivity extends AppCompatActivity {

ArrayList<Recipe> mRecipies = new ArrayList<>();
public TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    text = (TextView)findViewById(R.id.text);
    IRecipe iRecipe = RetrofitBuilder.Retrieve();
    Call<ArrayList<Recipe>> recipe = iRecipe.getRecipe();

    recipe.enqueue(new Callback<ArrayList<Recipe>>() {
        @Override
        public void onResponse(Call<ArrayList<Recipe>> call, Response<ArrayList<Recipe>> response) {
            mRecipies = response.body();
            text.setText(mRecipies.get(3).getIngredients().size());
        }

        @Override
        public void onFailure(Call<ArrayList<Recipe>> call, Throwable t) {

        }
    });

MyRecipe class

public class Recipe {

private String id;
private String name;
private List<Ingredients> ingredients = new ArrayList<>();
private List<Steps> steps = new ArrayList<>();
private String servings;

public Recipe(String id, String name,  String servings, List<Ingredients> ingredients, List<Steps> steps) {
    this.id = id;
    this.name = name;
    this.ingredients = ingredients;
    this.steps = steps;
    this.servings = servings;
}

public Recipe(){

}

public String getId() {
    return id;
}

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

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public List<Ingredients> getIngredients() {
    return ingredients;
}

public void setIngredients(List<Ingredients> ingredients) {
    this.ingredients = ingredients;
}

public List<Steps> getSteps() {
    return steps;
}

public void setSteps(List<Steps> steps) {
    this.steps = steps;
}

public String getServings() {
    return servings;
}

public void setServings(String servings) {
    this.servings = servings;
}

}

My ingredients class

public class Ingredients  {

private String quantity;
private String measure;
private String ingredient;

public Ingredients(String quantity, String measure, String ingredient) {
    this.quantity = quantity;
    this.measure = measure;
    this.ingredient = ingredient;
}

public Ingredients(){

}

public String getQuantity() {
    return quantity;
}

public void setQuantity(String quantity) {
    this.quantity = quantity;
}

public String getMeasure() {
    return measure;
}

public void setMeasure(String measure) {
    this.measure = measure;
}

public String getIngredient() {
    return ingredient;
}

public void setIngredient(String ingredient) {
    this.ingredient = ingredient;
}

}

Retrofit classes

Builder

        public final class RetrofitBuilder {
        static IRecipe iRecipe;

        public static IRecipe Retrieve() {

            Gson gson = new GsonBuilder().create();

            OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();

            iRecipe = new Retrofit.Builder()
                    .baseUrl("https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/")
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .callFactory(httpClientBuilder.build())
                    .build().create(IRecipe.class);

            return iRecipe;
        }
    }

Interface

    public interface IRecipe {
    @GET("baking.json")
    Call<ArrayList<Recipe>> getRecipe();
}

Stack Trace

 FATAL EXCEPTION: main
                                                                              Process: com.example.vamshi.retrofittrial, PID: 20350
                                                                              android.content.res.Resources$NotFoundException: String resource ID #0x9
                                                                                at android.content.res.Resources.getText(Resources.java:328)
                                                                                at android.content.res.MiuiResources.getText(MiuiResources.java:123)
                                                                                at android.widget.TextView.setText(TextView.java:4432)
                                                                                at com.example.vamshi.retrofittrial.MainActivity$1.onResponse(MainActivity.java:34)
                                                                                at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
                                                                                at android.os.Handler.handleCallback(Handler.java:742)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5527)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)

07-08 19:07:00.145 20350-20350/com.example.vamshi.retrofittrial E/MQSEventManagerDelegate: failed to get MQSService.

Body:
Well, setText doesnt allow integers.

So instead of

text.setText(mRecipies.get(3).getIngredients().size());

use

text.setText(String.valueof(mRecipies.get(3).getIngredients().size()));


问:
WPF Binding - StringFormat - Not Formatting
I have a ToolTip with a value set as:

```<code>Value="{Binding Path=DataItem.EquitySold, StringFormat=Reserved (Equity Share: \{0\}%)}"
</code>```

The toolip is displaying as:

72

But I expect it to be:

Reserved (Equity Share: 72%)

What is wrong with my binding?

答:
Have you tried:</p>

```<code><ToolTip>
    <TextBlock Text="{Binding Path=DataItem.EquitySold, StringFormat=Reserved (Equity Share: \{0\}%)}" />
</ToolTip>
</code>```

Body:
I have a ToolTip with a value set as:

Value="{Binding Path=DataItem.EquitySold, StringFormat=Reserved (Equity Share: \{0\}%)}"

The toolip is displaying as:

72

But I expect it to be:

Reserved (Equity Share: 72%)

What is wrong with my binding?

Body:
Have you tried:

<ToolTip>
    <TextBlock Text="{Binding Path=DataItem.EquitySold, StringFormat=Reserved (Equity Share: \{0\}%)}" />
</ToolTip>


问:
Automapper mapping list becomes 0
I'm mapping a list to another list with Automapper, but it seems that my items are not copied.

Here is my code:

```<code>var roles = userRepo.GetRoles(null).ToList();
Mapper.CreateMap < List<Domain.Role>, List<Role>>();
var mappedRole = Mapper.Map<List<Domain.Role>, List<Role>>(roles); //the count is 0, list empty :(
Mapper.AssertConfigurationIsValid();
</code>```

No exceptions were thrown.

All properties has the same names.

Domain.Role

```<code>public class Role
{
    public int RoleId { get; set; }
    public string RoleName { get; set; }
    public List<User> Users { get; set; }
}
</code>```

Role

```<code>public class Role
{
    public int RoleId { get; set; }
    public string RoleName { get; set; }
}
</code>```

答:
In my case, I had the (parent) type mapping configured correctly but I didn't add the mappings for the child records, so for this:

```<code>class FieldGroup
{
    string GroupName { get; set; }
    ...
    List<Field> fields { get; set; }
}
</code>```

I had to add the second mapping:

```<code>cfg.CreateMap<FieldGroup, FieldGroupDTO>();
cfg.CreateMap<Field, FieldDTO>(); << was missing
</code>```

Title: Automapper mapping list becomes 0

Body:
I'm mapping a list to another list with Automapper, but it seems that my items are not copied.

Here is my code:

var roles = userRepo.GetRoles(null).ToList();
Mapper.CreateMap < List<Domain.Role>, List<Role>>();
var mappedRole = Mapper.Map<List<Domain.Role>, List<Role>>(roles); //the count is 0, list empty :(
Mapper.AssertConfigurationIsValid();

No exceptions were thrown.

All properties has the same names.

Domain.Role

public class Role
{
    public int RoleId { get; set; }
    public string RoleName { get; set; }
    public List<User> Users { get; set; }
}

Role

public class Role
{
    public int RoleId { get; set; }
    public string RoleName { get; set; }
}

Body:
In my case, I had the (parent) type mapping configured correctly but I didn't add the mappings for the child records, so for this:

class FieldGroup
{
    string GroupName { get; set; }
    ...
    List<Field> fields { get; set; }
}

I had to add the second mapping:

cfg.CreateMap<FieldGroup, FieldGroupDTO>();
cfg.CreateMap<Field, FieldDTO>(); << was missing


问:
Calculate inverse CDF from a sample of data
If i got a random sample data: </p>

```<code>X=np.random.random(100)*100
</code>```

<p>and I need to get the value X_i with CDF = 34% or whatever. The only way that I am able to think right now is with inverse CDF. I thought that percentile would be equivalent but someone told me it is near but not exact. </p>

答:
This should give you the index of X where the cdf is 0.34:

```<code>X=np.random.random(100)*100
cdf_frac_to_find = 0.34
cdf = np.cumsum(X)/np.sum(X) #take the cumulative sum of x and normalize so that it's max value is 1
X_index = np.argmin(np.abs(cdf-cdf_pct_to_find))
X_index
#out: 32 -- note that this will likely change because you're generating random numbers for X.
</code>```

Body:
If i got a random sample data:

X=np.random.random(100)*100

and I need to get the value X_i with CDF = 34% or whatever. The only way that I am able to think right now is with inverse CDF. I thought that percentile would be equivalent but someone told me it is near but not exact.

Body:
This should give you the index of X where the cdf is 0.34:

X=np.random.random(100)*100
cdf_frac_to_find = 0.34
cdf = np.cumsum(X)/np.sum(X) #take the cumulative sum of x and normalize so that it's max value is 1
X_index = np.argmin(np.abs(cdf-cdf_pct_to_find))
X_index
#out: 32 -- note that this will likely change because you're generating random numbers for X.


问:
How do I sort a std::vector by the values of a different std::vector?
I have several std::vector, all of the same length. I want to sort one of these vectors, and apply the same transformation to all of the other vectors.  Is there a neat way of doing this? (preferably using the STL or Boost)?  Some of the vectors hold ints and some of them std::strings.

Pseudo code:

```<code>std::vector<int> Index = { 3, 1, 2 };
std::vector<std::string> Values = { "Third", "First", "Second" };

Transformation = sort(Index);
Index is now { 1, 2, 3};

... magic happens as Transformation is applied to Values ...
Values are now { "First", "Second", "Third" };
</code>```

答:
```<code>**// C++ program to demonstrate sorting in vector
// of pair according to 2nd element of pair
#include <iostream>
#include<string>
#include<vector>
#include <algorithm>

using namespace std;

// Driver function to sort the vector elements
// by second element of pairs
bool sortbysec(const pair<char,char> &a,
              const pair<int,int> &b)
{
    return (a.second < b.second);
}

int main()
{
    // declaring vector of pairs
    vector< pair <char, int> > vect;

    // Initialising 1st and 2nd element of pairs
    // with array values
    //int arr[] = {10, 20, 5, 40 };
    //int arr1[] = {30, 60, 20, 50};
    char arr[] = { ' a', 'b', 'c' };
    int arr1[] = { 4, 7, 1 };

    int n = sizeof(arr)/sizeof(arr[0]);

    // Entering values in vector of pairs
    for (int i=0; i<n; i++)
        vect.push_back( make_pair(arr[i],arr1[i]) );

    // Printing the original vector(before sort())
    cout << "The vector before sort operation is:\n" ;
    for (int i=0; i<n; i++)
    {
        // "first" and "second" are used to access
        // 1st and 2nd element of pair respectively
        cout << vect[i].first << " "
             << vect[i].second << endl;

    }

    // Using sort() function to sort by 2nd element
    // of pair
    sort(vect.begin(), vect.end(), sortbysec);

    // Printing the sorted vector(after using sort())
    cout << "The vector after sort operation is:\n" ;
    for (int i=0; i<n; i++)
    {
        // "first" and "second" are used to access
        // 1st and 2nd element of pair respectively
        cout << vect[i].first << " "
             << vect[i].second << endl;
    }
    getchar();
    return 0;`enter code here`
}**
</code>```

OwnerDisplayName: therefromhere

Body:
I have several std::vector, all of the same length. I want to sort one of these vectors, and apply the same transformation to all of the other vectors.  Is there a neat way of doing this? (preferably using the STL or Boost)?  Some of the vectors hold ints and some of them std::strings.

Pseudo code:

std::vector<int> Index = { 3, 1, 2 };
std::vector<std::string> Values = { "Third", "First", "Second" };

Transformation = sort(Index);
Index is now { 1, 2, 3};

... magic happens as Transformation is applied to Values ...
Values are now { "First", "Second", "Third" };


问:
NodeJs script with child_process spawn on Windows, why I need 'shell: true' for ENOENT error?
I'm using this code:

```<code>const {
  spawn
} = require('child_process');

let info = spawn('npm', ["-v"]);

info.on('close', () => {
  console.log('closed');
}
</code>```

But I have this error:

```<code>events.js:182
      throw er; // Unhandled 'error' event
      ^

Error: spawn npm ENOENT
    at exports._errnoException (util.js:1022:11)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:189:19)
    at onErrorNT (internal/child_process.js:366:16)
    at _combinedTickCallback (internal/process/next_tick.js:102:11)
    at process._tickCallback (internal/process/next_tick.js:161:9)
    at Function.Module.runMain (module.js:607:11)
    at startup (bootstrap_node.js:158:16)
    at bootstrap_node.js:575:3
</code>```

If I use instead:

```<code>let info = spawn('npm', ["-v"], {shell: true});
</code>```

it works!

But why I need shell: true? I need also to see the stdout of that spawn, so I'm also using this:

```<code>let info = spawn('npm', ["-v"], {shell: true, stdio: 'inherit'});
</code>```

It's correct?

答:
While calling spawn itself, there is no npm command under spawn. Thus you got that error message. Instead of using spawn itself, while adding shell: true, spawn will use shell of your system to run that command. Since your system has npm, it works.

let info = spawn('npm', ["-v"], {shell: true, stdio: 'inherit'}); It's correct?

The code is fine if your parameters of spawn are controllable. But generally, I suggest use pure spawn without using shell. The risk will reduce without touching shell directly.

Since you need the stream return from spawn. I have checked other solution here. Without shell: true, You can use the code:

```<code>const {
  spawn
} = require('child_process');

let projectPath = ''//the path of your project
let info = spawn('npm', ['-v'], { cwd: projectPath });

let result = '';
info.stdout.on('data', function(data) {
  result += data.toString();
  console.log(result);
}
</code>```

Body:
I'm using this code:

const {
  spawn
} = require('child_process');

let info = spawn('npm', ["-v"]);

info.on('close', () => {
  console.log('closed');
}

But I have this error:

events.js:182
      throw er; // Unhandled 'error' event
      ^

Error: spawn npm ENOENT
    at exports._errnoException (util.js:1022:11)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:189:19)
    at onErrorNT (internal/child_process.js:366:16)
    at _combinedTickCallback (internal/process/next_tick.js:102:11)
    at process._tickCallback (internal/process/next_tick.js:161:9)
    at Function.Module.runMain (module.js:607:11)
    at startup (bootstrap_node.js:158:16)
    at bootstrap_node.js:575:3

If I use instead:

let info = spawn('npm', ["-v"], {shell: true});

it works!

But why I need shell: true? I need also to see the stdout of that spawn, so I'm also using this:

let info = spawn('npm', ["-v"], {shell: true, stdio: 'inherit'});

It's correct?

Body:
While calling spawn itself, there is no npm command under spawn. Thus you got that error message. Instead of using spawn itself, while adding shell: true, spawn will use shell of your system to run that command. Since your system has npm, it works.

let info = spawn('npm', ["-v"], {shell: true, stdio: 'inherit'}); It's correct?

The code is fine if your parameters of spawn are controllable. But generally, I suggest use pure spawn without using shell. The risk will reduce without touching shell directly.

Since you need the stream return from spawn. I have checked other solution here. Without shell: true, You can use the code:

const {
  spawn
} = require('child_process');

let projectPath = ''//the path of your project
let info = spawn('npm', ['-v'], { cwd: projectPath });

let result = '';
info.stdout.on('data', function(data) {
  result += data.toString();
  console.log(result);
}


问:
Use C++ with Android ndk/jni
All the ndk samples only make use of basic C functions declared as extern in the header and defined in the cpp file. Then after including the header file in the C file containing the jni callback, everything works fine.

Is it possible to use C++ classes with the android ndk? My application is not going to be a native activity, it will still have an important java part but it will call native C code for CPU-intensive computation (already written in C++, with classes and other C++ stuff).

Here is my hello-world like strcuture for now:

File "first.h"

```<code>#ifndef FIRST_H
#define FIRST_H

class Test
{};

#endif /* FIRST_H */
</code>```

File "second.cpp"

```<code>#include <jni.h>
#include "first.h"

#ifdef __cplusplus
extern "C" {
#endif

jint Java_com_example_twolibs_TwoLibs_add( JNIEnv*  env,
                                      jobject  this,
                                      jint     x,
                                      jint     y )
{
    Test t;
    return 0;
}

#ifdef __cplusplus
}
#endif
</code>```

And finally Android.mk

```<code>LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := libtwolib-second
LOCAL_SRC_FILES := second.cpp

include $(BUILD_SHARED_LIBRARY)
</code>```

Pretty basic but that does not compile. Turning second.cpp in a .c file raises an error when including the header file, I guess this is because it is not a C++ file.

```<code>error: expected '=', ',', ';', 'asm' or '__attribute__' before 'Test'
</code>```

Making it .cpp raises the following error:

```<code>make: *** No rule to make target `/cygdrive/c/android-ndk-r5c/samples/twolibs/jni/second.c', needed by `/cygdrive/c/android-ndk-r5c/samples/two-libs/obj/local/armeabi/objs/twolib-second/second.o'.  Stop.
</code>```

Any idea how I can make that thing compile?

Thanks

答:
Edit Android.mk

Modify the instances of LOCAL_SRC_FILES and remove the ./ from the begginning of each line.

Title: Use C++ with Android ndk/jni

Body:
All the ndk samples only make use of basic C functions declared as extern in the header and defined in the cpp file. Then after including the header file in the C file containing the jni callback, everything works fine.

Is it possible to use C++ classes with the android ndk? My application is not going to be a native activity, it will still have an important java part but it will call native C code for CPU-intensive computation (already written in C++, with classes and other C++ stuff).

Here is my hello-world like strcuture for now:

File "first.h"

#ifndef FIRST_H
#define FIRST_H

class Test
{};

#endif /* FIRST_H */

File "second.cpp"

#include <jni.h>
#include "first.h"

#ifdef __cplusplus
extern "C" {
#endif

jint Java_com_example_twolibs_TwoLibs_add( JNIEnv*  env,
                                      jobject  this,
                                      jint     x,
                                      jint     y )
{
    Test t;
    return 0;
}

#ifdef __cplusplus
}
#endif

And finally Android.mk

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := libtwolib-second
LOCAL_SRC_FILES := second.cpp

include $(BUILD_SHARED_LIBRARY)

Pretty basic but that does not compile. Turning second.cpp in a .c file raises an error when including the header file, I guess this is because it is not a C++ file.

error: expected '=', ',', ';', 'asm' or '__attribute__' before 'Test'

Making it .cpp raises the following error:

make: *** No rule to make target `/cygdrive/c/android-ndk-r5c/samples/twolibs/jni/second.c', needed by `/cygdrive/c/android-ndk-r5c/samples/two-libs/obj/local/armeabi/objs/twolib-second/second.o'.  Stop.

Any idea how I can make that thing compile?

Thanks


问:
How to fix the image to a div when it's height is greater than its width?
In Facebook, when we post any size images, it shows perfectly on the timeline. How do they do this?

I have tried following.

Setting the image as background of the div.

CSS - width: 100%; height:auto;

Both did not work, All over the stack overflow there is no option for this,finally decided to add this.

答:
I think you are asking for the scaling technique.You should try to take the image and have it re-scaled i.e. change it's height and width using JavaScript DOM or CSS and re-uploading it to the page.

Your 1st solution did not work because images are not shown as the background of  rather shown with the .


问:
how can i use the same number for all the calculations
```<code>import java.util.Scanner;
public class Calculator
{
    public static void main(String args[])
    {
        System.out.println("Enter the numbers only ");
        Scanner num =new Scanner(System.in);
        System.out.println("Enter the number of times you want to run loop ");
        Scanner loop =new Scanner(System.in);
        int n =loop.nextInt();
        while(n!=0)
        {
            System.out.println("Enter the Cases  1 for addition,2 for Subtraction,3 for Division 4 for multipication and 5 for reaminder  ");
            Scanner cas =new Scanner(System.in);
            int c = cas.nextInt();
            double calc,first,second;
            switch (c)
            {
            case 1:
                System.out.println("addition of two number is ");
                first = num.nextDouble();
                second=num.nextDouble();
                calc = first + second;
                System.out.println(calc);
                break;
            case 2:
                System.out.println("subtraction of two number is ");
                first = num.nextDouble();
                second = num.nextDouble();
                calc = first - second;
                System.out.println(calc);
                break;
            case 3:
                System.out.println("division of two number is ");
                first = num.nextDouble();
                second = num.nextDouble();
                calc = first / second;
                System.out.println(calc);
                break;
            case 4:
                System.out.println("multipication of two number is ");
                first = num.nextDouble();
                second = num.nextDouble();
                calc = first * second;
                System.out.println(calc);
                break;
            case 5:
                System.out.println("remainder of two number is ");
                first = num.nextDouble();
                second = num.nextDouble();
                calc = first % second;
                System.out.println(calc);
                break;
            default:
                System.out.println("you did not enter 1,2,3,4,5 you entered something else ");
            }
        n--;
        }
        System.out.println("the program has end, THANK YOU!!");
    }
}
</code>```

<p>This the java code for calculation by asking user for input. How can i use the same number for all the calculations in this code?it ask user every time for the new number but i want this code to do all the calculation by only one input. </p>

答:
If you remove

break;

from every case it will do every case starting from the one the user chose

Is this what you wanted ?

Body:
import java.util.Scanner;
public class Calculator
{
    public static void main(String args[])
    {
        System.out.println("Enter the numbers only ");
        Scanner num =new Scanner(System.in);
        System.out.println("Enter the number of times you want to run loop ");
        Scanner loop =new Scanner(System.in);
        int n =loop.nextInt();
        while(n!=0)
        {
            System.out.println("Enter the Cases  1 for addition,2 for Subtraction,3 for Division 4 for multipication and 5 for reaminder  ");
            Scanner cas =new Scanner(System.in);
            int c = cas.nextInt();
            double calc,first,second;
            switch (c)
            {
            case 1:
                System.out.println("addition of two number is ");
                first = num.nextDouble();
                second=num.nextDouble();
                calc = first + second;
                System.out.println(calc);
                break;
            case 2:
                System.out.println("subtraction of two number is ");
                first = num.nextDouble();
                second = num.nextDouble();
                calc = first - second;
                System.out.println(calc);
                break;
            case 3:
                System.out.println("division of two number is ");
                first = num.nextDouble();
                second = num.nextDouble();
                calc = first / second;
                System.out.println(calc);
                break;
            case 4:
                System.out.println("multipication of two number is ");
                first = num.nextDouble();
                second = num.nextDouble();
                calc = first * second;
                System.out.println(calc);
                break;
            case 5:
                System.out.println("remainder of two number is ");
                first = num.nextDouble();
                second = num.nextDouble();
                calc = first % second;
                System.out.println(calc);
                break;
            default:
                System.out.println("you did not enter 1,2,3,4,5 you entered something else ");
            }
        n--;
        }
        System.out.println("the program has end, THANK YOU!!");
    }
}

This the java code for calculation by asking user for input. How can i use the same number for all the calculations in this code?it ask user every time for the new number but i want this code to do all the calculation by only one input.


问:
raspberry connect wifi by python
How can I configure WiFi using Python on Raspberry Pi3 (raspbian)?

I tried python's subprocess:

```<code>os.popen("sudo iwconfig wlan0 essid my_ssid key s:pass")
</code>```

But this command disables my WiFi interface (wlan0) so I have a no wifi interfaces found in the Raspbian top panel.
I also tried to use a module named wifi but I get the same result of wlan0 interface being disabled.

Any ideas?

答:
Try this:</p>

```<code>"""
Name             : Python Connect to Wifi for Linux
Created By       : Agus Makmun (Summon Agus)
Blog             : bloggersmart.net - python.web.id
License          : GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007
Documentation    : https://github.com/agusmakmun/Some-Examples-of-Simple-Python-Script/
Powered          : Ubuntu 14.04, Python 2.7
"""

import os, sys

print "[+] Enter this some Option"
print " 1. Active Wifi (up)\n 2. Down Wifi (down)\n 3. Exit"
inp_up_down = raw_input("[+] Enter choice number: ")
if inp_up_down == '1':
    os.system("ifconfig wlan0 up")
    print " Are you want connect to wifi?"
    print " 1. Yes, Conncet\n 2. No, Exit"
    inp_connect = raw_input("[+] Enter your choice: ")
    if inp_connect == '1':
        os.system("iwlist wlan0 scan | grep ESSID")
        masuk = raw_input("Enter name of wifi (ex: @wifi.id): ")
        os.system("iwconfig wlan0 essid "+masuk)
        os.system("dhclient wlan0")
    elif inp_connect == '2':
    print "Thankyou.."
        sys.exit()
elif inp_up_down == '2':
    os.system("ifconfig wlan0 down")
elif inp_up_down == '3':
    sys.exit()
else:
    print "Sorry, Wrong Input!!"
</code>```

Title: raspberry connect wifi by python

Body:
How can I configure WiFi using Python on Raspberry Pi3 (raspbian)?

I tried python's subprocess:

os.popen("sudo iwconfig wlan0 essid my_ssid key s:pass")

But this command disables my WiFi interface (wlan0) so I have a no wifi interfaces found in the Raspbian top panel.
I also tried to use a module named wifi but I get the same result of wlan0 interface being disabled.

Any ideas?

Body:
Try this:

"""
Name             : Python Connect to Wifi for Linux
Created By       : Agus Makmun (Summon Agus)
Blog             : bloggersmart.net - python.web.id
License          : GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007
Documentation    : https://github.com/agusmakmun/Some-Examples-of-Simple-Python-Script/
Powered          : Ubuntu 14.04, Python 2.7
"""

import os, sys

print "[+] Enter this some Option"
print " 1. Active Wifi (up)\n 2. Down Wifi (down)\n 3. Exit"
inp_up_down = raw_input("[+] Enter choice number: ")
if inp_up_down == '1':
    os.system("ifconfig wlan0 up")
    print " Are you want connect to wifi?"
    print " 1. Yes, Conncet\n 2. No, Exit"
    inp_connect = raw_input("[+] Enter your choice: ")
    if inp_connect == '1':
        os.system("iwlist wlan0 scan | grep ESSID")
        masuk = raw_input("Enter name of wifi (ex: @wifi.id): ")
        os.system("iwconfig wlan0 essid "+masuk)
        os.system("dhclient wlan0")
    elif inp_connect == '2':
    print "Thankyou.."
        sys.exit()
elif inp_up_down == '2':
    os.system("ifconfig wlan0 down")
elif inp_up_down == '3':
    sys.exit()
else:
    print "Sorry, Wrong Input!!"


问:
d3 horizontal bar chart with background and max value of 100%
I have this single horizontal bar chart and I want to make the following adjustments:

Show the tick value to the right of the bar chart, instead of by the axis.

Show a background for the bar chart scale instead of left and bottom axis.

Current version:

What I'd like to get to:

JS

```<code>var data = [
      {"yAxis":"score", "xAxis":"72"}
    ];
    // set the dimensions and margins of the graph
    var margin = {top: 20, right: 20, bottom: 30, left: 80},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;
    // set the ranges
    var y = d3.scaleBand()
    .range([height, 0])
    .padding(0.4);
    var x = d3.scaleLinear()
    .range([0, width]);
    var svg = d3.select(".barChartContainer").append("svg")
    .attr("preserveAspectRatio", "xMinYMin meet")
    .attr("viewBox", "0 0 960 500")
    .append("g")
    .attr("transform",
    "translate(" + margin.left + "," + margin.top + ")");
    // Scale the range of the data in the domains
    x.domain([0, d3.max(data, function(d){ return d.xAxis; })])
    y.domain(data.map(function(d) { return d.yAxis; }));
    //y.domain([0, d3.max(data, function(d) { return d.prereqs; })]);
    // append the rectangles for the bar chart
    svg.selectAll(".bar")
    .data(data)
    .enter().append("rect")
    .attr("class", "bar")
    .attr("y", function(d) { return y(d.yAxis); })
    .attr("height", y.bandwidth())
    .transition()
    .duration(1000)
    .delay(function(d, i) {
    return i * 100
    })
    .attr("width", function(d) {return x(d.xAxis); } );
    // add the x Axis
    svg.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x).tickValues(d3.range(x.domain()[0], x.domain()[1] + 1, 1))
    .tickFormat(d3.format("d"))
    );
    svg.append("g")
    .attr("class", "yAxis")
    .call(d3.axisLeft(y));
</code>```

I got this code from a codepen and I've been trying to adapt it, but it has been breaking so I stopped and was hoping you could help.

Thanks.

答:
For showing the background for the bars, just copy your selection and chose a value of 100% for the rectangles, in a light gray fill:

```<code>var backgroundBar = svg.selectAll(null)
    .data(data)
    .enter()
    .append("rect")
    //etc...
    .attr("width", function(d) {
        return x(100);
    });
</code>```

Of course, you'll have to change the domain of the x scale:

```<code>var x = d3.scaleLinear()
    .domain([0, 100]);
</code>```

Then, drop both axis and print the labels using a text selection.

Finally, use another text selection for the values:

```<code>var values = svg.selectAll(null)
    .data(data)
    .enter()
    .append("text")
    //etc...
    .text(function(d) {
        return +d.xAxis
    })
</code>```

If you want, you can tween the text:

```<code>.attrTween("text", function(d) {
    var self = this
    var i = d3.interpolateNumber(0, +d.xAxis);
    return function(t) {
        return d3.select(self).text(~~i(t));
    }
});
</code>```

This is the result:

var data = [{
  "yAxis": "score",
  "xAxis": "72"
}];

var margin = {
    top: 20,
    right: 20,
    bottom: 30,
    left: 80
  },
  width = 500 - margin.left - margin.right,
  height = 200 - margin.top - margin.bottom;

var y = d3.scaleBand()
  .range([height, 0])
  .padding(0.4);

var x = d3.scaleLinear()
  .range([0, width])
  .domain([0, 100]);

var svg = d3.select("body").append("svg")
  .attr("width", 500)
  .attr("height", 200)
  .append("g")
  .attr("transform",
    "translate(" + margin.left + "," + margin.top + ")");

y.domain(data.map(function(d) {
  return d.yAxis;
}));

var backgroundBar = svg.selectAll(null)
  .data(data)
  .enter()
  .append("rect")
  .attr("fill", "lightgray")
  .attr("y", function(d) {
    return y(d.yAxis);
  })
  .attr("height", y.bandwidth())
  .attr("width", function(d) {
    return x(100);
  });

var bar = svg.selectAll(null)
  .data(data)
  .enter()
  .append("rect")
  .attr("class", "bar")
  .attr("y", function(d) {
    return y(d.yAxis);
  })
  .attr("height", y.bandwidth())
  .transition()
  .duration(2000)
  .delay(function(d, i) {
    return i * 100
  })
  .attr("width", function(d) {
    return x(d.xAxis);
  });

var labels = svg.selectAll(null)
  .data(data)
  .enter()
  .append("text")
  .attr("y", function(d) {
    return y(d.yAxis) + y.bandwidth() / 2;
  })
  .attr("x", -10)
  .attr("text-anchor", "end")
  .text(function(d) {
    return d.yAxis
  });

var values = svg.selectAll(null)
  .data(data)
  .enter()
  .append("text")
  .attr("y", function(d) {
    return y(d.yAxis) + y.bandwidth() / 2;
  })
  .attr("x", 10)
  .text(function(d) {
    return +d.xAxis
  })
  .transition()
  .duration(2000)
  .delay(function(d, i) {
    return i * 100
  })
  .attr("x", function(d) {
    return x(d.xAxis) + 10;
  })
  .attrTween("text", function(d) {
    var self = this
    var i = d3.interpolateNumber(0, +d.xAxis);
    return function(t) {
      return d3.select(self).text(~~i(t));
    }
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script></code>```

Body:
I have this single horizontal bar chart and I want to make the following adjustments:

Show the tick value to the right of the bar chart, instead of by the axis.

Show a background for the bar chart scale instead of left and bottom axis.

Current version:

What I'd like to get to:

JS

var data = [
      {"yAxis":"score", "xAxis":"72"}
    ];
    // set the dimensions and margins of the graph
    var margin = {top: 20, right: 20, bottom: 30, left: 80},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;
    // set the ranges
    var y = d3.scaleBand()
    .range([height, 0])
    .padding(0.4);
    var x = d3.scaleLinear()
    .range([0, width]);
    var svg = d3.select(".barChartContainer").append("svg")
    .attr("preserveAspectRatio", "xMinYMin meet")
    .attr("viewBox", "0 0 960 500")
    .append("g")
    .attr("transform",
    "translate(" + margin.left + "," + margin.top + ")");
    // Scale the range of the data in the domains
    x.domain([0, d3.max(data, function(d){ return d.xAxis; })])
    y.domain(data.map(function(d) { return d.yAxis; }));
    //y.domain([0, d3.max(data, function(d) { return d.prereqs; })]);
    // append the rectangles for the bar chart
    svg.selectAll(".bar")
    .data(data)
    .enter().append("rect")
    .attr("class", "bar")
    .attr("y", function(d) { return y(d.yAxis); })
    .attr("height", y.bandwidth())
    .transition()
    .duration(1000)
    .delay(function(d, i) {
    return i * 100
    })
    .attr("width", function(d) {return x(d.xAxis); } );
    // add the x Axis
    svg.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x).tickValues(d3.range(x.domain()[0], x.domain()[1] + 1, 1))
    .tickFormat(d3.format("d"))
    );
    svg.append("g")
    .attr("class", "yAxis")
    .call(d3.axisLeft(y));

I got this code from a codepen and I've been trying to adapt it, but it has been breaking so I stopped and was hoping you could help.

Thanks.

Body:
For showing the background for the bars, just copy your selection and chose a value of 100% for the rectangles, in a light gray fill:

var backgroundBar = svg.selectAll(null)
    .data(data)
    .enter()
    .append("rect")
    //etc...
    .attr("width", function(d) {
        return x(100);
    });

Of course, you'll have to change the domain of the x scale:

var x = d3.scaleLinear()
    .domain([0, 100]);

Then, drop both axis and print the labels using a text selection.

Finally, use another text selection for the values:

var values = svg.selectAll(null)
    .data(data)
    .enter()
    .append("text")
    //etc...
    .text(function(d) {
        return +d.xAxis
    })

If you want, you can tween the text:

.attrTween("text", function(d) {
    var self = this
    var i = d3.interpolateNumber(0, +d.xAxis);
    return function(t) {
        return d3.select(self).text(~~i(t));
    }
});

This is the result:

var data = [{
  "yAxis": "score",
  "xAxis": "72"
}];

var margin = {
    top: 20,
    right: 20,
    bottom: 30,
    left: 80
  },
  width = 500 - margin.left - margin.right,
  height = 200 - margin.top - margin.bottom;

var y = d3.scaleBand()
  .range([height, 0])
  .padding(0.4);

var x = d3.scaleLinear()
  .range([0, width])
  .domain([0, 100]);

var svg = d3.select("body").append("svg")
  .attr("width", 500)
  .attr("height", 200)
  .append("g")
  .attr("transform",
    "translate(" + margin.left + "," + margin.top + ")");

y.domain(data.map(function(d) {
  return d.yAxis;
}));

var backgroundBar = svg.selectAll(null)
  .data(data)
  .enter()
  .append("rect")
  .attr("fill", "lightgray")
  .attr("y", function(d) {
    return y(d.yAxis);
  })
  .attr("height", y.bandwidth())
  .attr("width", function(d) {
    return x(100);
  });

var bar = svg.selectAll(null)
  .data(data)
  .enter()
  .append("rect")
  .attr("class", "bar")
  .attr("y", function(d) {
    return y(d.yAxis);
  })
  .attr("height", y.bandwidth())
  .transition()
  .duration(2000)
  .delay(function(d, i) {
    return i * 100
  })
  .attr("width", function(d) {
    return x(d.xAxis);
  });

var labels = svg.selectAll(null)
  .data(data)
  .enter()
  .append("text")
  .attr("y", function(d) {
    return y(d.yAxis) + y.bandwidth() / 2;
  })
  .attr("x", -10)
  .attr("text-anchor", "end")
  .text(function(d) {
    return d.yAxis
  });

var values = svg.selectAll(null)
  .data(data)
  .enter()
  .append("text")
  .attr("y", function(d) {
    return y(d.yAxis) + y.bandwidth() / 2;
  })
  .attr("x", 10)
  .text(function(d) {
    return +d.xAxis
  })
  .transition()
  .duration(2000)
  .delay(function(d, i) {
    return i * 100
  })
  .attr("x", function(d) {
    return x(d.xAxis) + 10;
  })
  .attrTween("text", function(d) {
    var self = this
    var i = d3.interpolateNumber(0, +d.xAxis);
    return function(t) {
      return d3.select(self).text(~~i(t));
    }
  });

<script src="https://d3js.org/d3.v4.min.js"></script>


问:
UTF-16 encoding spring mvc and mysql
```<code>  <filter>
    <filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
</code>```

1)How can i enable UTF-16 encoding in spring filter
I need to take UTF-16 or UCS2 character from a text box in JSP to Spring Controller and insert into Mysql.

2)How can I insert UTF-16 data into mysql

I am configuring JDBC URL like

```<code>"?useUnicode=yes&characterEncoding=UTF-8"
</code>```

my column schema is

```<code>`utf16` varchar(150) CHARACTER SET utf16 COLLATE utf16_unicode_ci NOT NULL,
</code>```

答:
I see no reason to use CHARACTER SET utf16 or ucs2.  What is your rationale for such?

CHARACTER SET utf8mb4 is the standard going forward.  It corresponds to the UTF-8 outside MySQL, as mentioned in "?useUnicode=yes&characterEncoding=UTF-8"

If you really need CHARACTER SET utf16 in the table, then it should work as presented.  MySQL converts from the specified client encoding to the specified column charset.  Yes, utf16 and utf8 are different encodings.

Title: UTF-16 encoding spring mvc and mysql

Body:
  <filter>
    <filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>

1)How can i enable UTF-16 encoding in spring filter
I need to take UTF-16 or UCS2 character from a text box in JSP to Spring Controller and insert into Mysql.

2)How can I insert UTF-16 data into mysql

I am configuring JDBC URL like

"?useUnicode=yes&characterEncoding=UTF-8"

my column schema is

`utf16` varchar(150) CHARACTER SET utf16 COLLATE utf16_unicode_ci NOT NULL,


答:
to start activity call this in onCreate

```<code>Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
</code>```

and set activity in manifest application

```<code><activity android:name=".SecondActivity" />
</code>```

Title: Android start activity when app started

Body:
This android project is about Webview.
It start the activity when it click some button called goURL.
but is it possible to start some activity when the app started?(not activity from the button).
my guess is put something on onCreate

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

}

public void goURL(View view){
    TextView tvURL = (TextView)findViewById(R.id.txtURL);
    String url = tvURL.getText().toString();
    Log.i("URL", "Opening URL with WebView :" + url);

    final long startTime = System.currentTimeMillis();
    WebView webView = (WebView)findViewById(R.id.webView);

//webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

webView.loadUrl(url);

My guess is that to create intent about view.
but not sure how to do it

Body:
to start activity call this in onCreate

Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);

and set activity in manifest application

<activity android:name=".SecondActivity" />


问:
How to check mouseover operation changes the UI colour in selenium
I want to verify whether stars are lit up or not when I hover mouse on top of it.(Attached a Screenshot for better understanding). How can I verify whether it is lit up or not?

HTML structure of the element is as given below:

```<code><span class="wh-rating rating_4_5" style="display: inline-block;">
Rating:
<span data-s13732055i-ir="this" itemprop="ratingValue">4.5</span>
</span>
<div class="wh-rating-choices" style="display: none;">
<div class="wh-rating-choices-holder">
 <a class="hover" href="#">1</a>
 <a class="hover" href="#">2</a>
 <a class="hover" href="#">3</a>
 <a class="hover" href="#">4</a>
 <a class="hover" href="#">5</a>
 </div>
 </div>
</code>```

答: This question is answered here , at a similar project like yours check this out it can be done with pure css : Change star rating on hover</p>

Body:
I want to verify whether stars are lit up or not when I hover mouse on top of it.(Attached a Screenshot for better understanding). How can I verify whether it is lit up or not?

HTML structure of the element is as given below:

Rating:
4.5

 1
 2
 3
 4
 5


问:
Can I redirect from a view in cakephp
I have a button on my home page which leads to a signup/login page. The signup/login page is just a page in views/pages/signup.ctp and as such doesn't have an action associated with it.

I want it so if a user is already logged in when they're on the homepage and they click my signup/login button, instead of taking them to the signup/login page it redirects them to another action. But since the signip/login page doesn't have an action I don't know where to do the check and redirect. Is there a way of checking if a persons logged in in the signup.ctp view? and redirect them from there?

Thats probably miles away from reality but I'm very confused. Any help appreciated. Cheers :)

答:
Do this in your ExampleController for the specific view like "example.ctp"

```<code>public function example(){
   if ($session.read('Auth.User')) {
       this->redirect(['action' => 'exampleview']);
   }
}
</code>```

Hope that it will solve your purpose.

Title: Can I redirect from a view in cakephp

Body:
Do this in your ExampleController for the specific view like "example.ctp"

public function example(){
   if ($session.read('Auth.User')) {
       this->redirect(['action' => 'exampleview']);
   }
}

Hope that it will solve your purpose.


问:
Generate valid Authorization:Basic
I'm trying to generate correct string for Authorization:Basic [string] but i fail because i'm not really sure what info should i encode.
First request that client sends is sign_up request which doesn't include Authorization.Response for that request looks like this:

```<code>{
"user": {
    "name": "Genome",
    "id": 2417370297
},
"identifier": "OFpDN0VJU3UxM1B1dTZTWDNMS1hqYWNwbmFjM3Zib0lBaTJYbTdUUWVWRkhTUUdYVWJyK0FobnppY1pkZEFwTG1OQkpoQjBGOVY5RmVtN0RtQ1BsUEE9PTpZaTc1SFZBeDFsWGxZaUZNeDZxTTZRPT0="
}
</code>```

After that,the next request client should send is sign_in which includes Authroization:Basic.This is how Authorization looks:

```<code>Authorization: Basic WWk3NUhWQXgxbFhsWWlGTXg2cU02UT09OjhaQzdFSVN1MTNQdXU2U1gzTEtYamFjcG5hYzN2Ym9JQWkyWG03VFFlVkZIU1FHWFVicitBaG56aWNaZGRBcExtTkJKaEIwRjlWOUZlbTdEbUNQbFBBPT0=
</code>```

Problem is i don't know how to generate that string after "Basic" .If you need any info ask here

答: Basic authentication is name:password encoded in Base64. </p>

Title: Generate valid Authorization:Basic

Body:
I'm trying to generate correct string for Authorization:Basic [string] but i fail because i'm not really sure what info should i encode.
First request that client sends is sign_up request which doesn't include Authorization.Response for that request looks like this:

{
"user": {
    "name": "Genome",
    "id": 2417370297
},
"identifier": "OFpDN0VJU3UxM1B1dTZTWDNMS1hqYWNwbmFjM3Zib0lBaTJYbTdUUWVWRkhTUUdYVWJyK0FobnppY1pkZEFwTG1OQkpoQjBGOVY5RmVtN0RtQ1BsUEE9PTpZaTc1SFZBeDFsWGxZaUZNeDZxTTZRPT0="
}

After that,the next request client should send is sign_in which includes Authroization:Basic.This is how Authorization looks:

Authorization: Basic WWk3NUhWQXgxbFhsWWlGTXg2cU02UT09OjhaQzdFSVN1MTNQdXU2U1gzTEtYamFjcG5hYzN2Ym9JQWkyWG03VFFlVkZIU1FHWFVicitBaG56aWNaZGRBcExtTkJKaEIwRjlWOUZlbTdEbUNQbFBBPT0=

Problem is i don't know how to generate that string after "Basic" .If you need any info ask here


问:
Testing if some value is not produced by an iterator
I would like to test whether a certain value belongs to a sequence of numbers, which is produced using an iterator. Of course when the value does belong to the sequence, one can stop as soon as the value is met. But when it does not, I guess that's when problems show up.

However one can use additional information (e.g., the sequence is increasing).

Consider the Fibonacci example:

```<code>class FibonacciIterator(object):
    def __init__(self):
        self.mem = [0, 1]
    def __next__(self):
        curr = self.mem[0]
        new = self.mem[0]+self.mem[1]
        self.mem[0] = self.mem[1]
        self.mem[1] = new
        return curr

class Fibonacci(object):
    def __iter__(self):
       return FibonacciIterator()
</code>```

If one tests whether 8 belongs to the sequence then everything is fine:

```<code>>>> fib = Fibonacci()
>>> 8 in fib
True
</code>```

If, however, one tests 10 (which doesn't belong to the sequence) then

```<code>>>> 10 in fib
...
</code>```

never terminates. But one could easily determine that 10 is not in the sequence by observing that after 8 comes 13, and since the sequence is increasing then necessarily not 10 in fib.

Is there a nice way in Python to implement such behavior of in, so that 10 in fib terminates?

答:
The trivial solution would be to implement a __contains__ method that just iterates over a copy of the iterator:

```<code>class FibonacciIterator(object):
    def __init__(self):
        self.mem = [0, 1]

    def __iter__(self):
        return self

    def __contains__(self, value):
        testit = FibonacciIterator()
        testit.mem = list(self.mem)  # copy
        for item in testit:
            if item == value:
                return True
            if item > value:
                return False

    def __next__(self):
        curr = self.mem[0]
        self.mem = self.mem[1], sum(self.mem)
        return curr

class Fibonacci(object):
    def __iter__(self):
        return FibonacciIterator()

    def __contains__(self, value):
        return value in iter(self)
</code>```

However there is another way to determine if a number is a Fibonacci number: If either (5*n**2 + 4) or (5*n**2 – 4) or both are perfect squares (square of an integer).

I'll use the approach from this answer to implement the is_square function:

```<code>def is_square(apositiveint):
    # Source: https://stackoverflow.com/a/2489519/5393381
    # Credit: Alex Martelli

    x = apositiveint // 2
    seen = {x}
    while x * x != apositiveint:
        x = (x + (apositiveint // x)) // 2
        if x in seen:
            return False
        seen.add(x)
    return True

class FibonacciIterator(object):
    def __init__(self):
        self.mem = [0, 1]

    def __iter__(self):
        return self

    def __contains__(self, value):
        if value < self.mem[0]:
            return False
        else:
            # Just check if at least one of both is a perfect square
            value_squared_times_five = 5*value**2
            return is_square(value_squared_times_five + 4) or is_square(value_squared_times_five - 4)

    def __next__(self):
        curr = self.mem[0]
        self.mem = self.mem[1], sum(self.mem)
        return curr

class Fibonacci(object):
    def __iter__(self):
        return FibonacciIterator()

    def __contains__(self, value):
        return value in iter(self)
</code>```

Body:
I would like to test whether a certain value belongs to a sequence of numbers, which is produced using an iterator. Of course when the value does belong to the sequence, one can stop as soon as the value is met. But when it does not, I guess that's when problems show up.

However one can use additional information (e.g., the sequence is increasing).

Consider the Fibonacci example:

class FibonacciIterator(object):
    def __init__(self):
        self.mem = [0, 1]
    def __next__(self):
        curr = self.mem[0]
        new = self.mem[0]+self.mem[1]
        self.mem[0] = self.mem[1]
        self.mem[1] = new
        return curr

class Fibonacci(object):
    def __iter__(self):
       return FibonacciIterator()

If one tests whether 8 belongs to the sequence then everything is fine:

>>> fib = Fibonacci()
>>> 8 in fib
True

If, however, one tests 10 (which doesn't belong to the sequence) then

>>> 10 in fib
...

never terminates. But one could easily determine that 10 is not in the sequence by observing that after 8 comes 13, and since the sequence is increasing then necessarily not 10 in fib.

Is there a nice way in Python to implement such behavior of in, so that 10 in fib terminates?

Body:
The trivial solution would be to implement a __contains__ method that just iterates over a copy of the iterator:

class FibonacciIterator(object):
    def __init__(self):
        self.mem = [0, 1]

    def __iter__(self):
        return self

    def __contains__(self, value):
        testit = FibonacciIterator()
        testit.mem = list(self.mem)  # copy
        for item in testit:
            if item == value:
                return True
            if item > value:
                return False

    def __next__(self):
        curr = self.mem[0]
        self.mem = self.mem[1], sum(self.mem)
        return curr

class Fibonacci(object):
    def __iter__(self):
        return FibonacciIterator()

    def __contains__(self, value):
        return value in iter(self)

However there is another way to determine if a number is a Fibonacci number: If either (5*n**2 + 4) or (5*n**2 – 4) or both are perfect squares (square of an integer).

I'll use the approach from this answer to implement the is_square function:

def is_square(apositiveint):
    # Source: https://stackoverflow.com/a/2489519/5393381
    # Credit: Alex Martelli

    x = apositiveint // 2
    seen = {x}
    while x * x != apositiveint:
        x = (x + (apositiveint // x)) // 2
        if x in seen:
            return False
        seen.add(x)
    return True

class FibonacciIterator(object):
    def __init__(self):
        self.mem = [0, 1]

    def __iter__(self):
        return self

    def __contains__(self, value):
        if value < self.mem[0]:
            return False
        else:
            # Just check if at least one of both is a perfect square
            value_squared_times_five = 5*value**2
            return is_square(value_squared_times_five + 4) or is_square(value_squared_times_five - 4)

    def __next__(self):
        curr = self.mem[0]
        self.mem = self.mem[1], sum(self.mem)
        return curr

class Fibonacci(object):
    def __iter__(self):
        return FibonacciIterator()

    def __contains__(self, value):
        return value in iter(self)


问:
how to communicate between labview and DM software
Hello，I need to use DM software to analyse a txt file and get numbers.Each number was send to a Labview software which controls the moving stage. Then Labview tells it's done then DM will take picture and save the files. So how can this be done？I found few samples with the DM script.Please give a direction.Thanks</p>

答: If speed is no issue, you could make Labview save an empty .txt. Your dm software could check if the file exists and take a picture as soon as it does. Ofcourse better, faster/safer methods exist, but I dont know how versitile your dm software is. A virtual com-port for example, ActiveX, there are many options to make software communicate with eachother. </p>


问:
Angular 2 Material Design
I am learning Angular 2 and I have so many problems with that whose one I can't find anything on that on internet. So, I tried easy thing to start : create a sign in form in my app, so I am using Material Design but my input are bad and nothing like in the Material Design Doc. Here so picture :
enter image description here

So as you can see my input are not display and the placeholder is under it.

Here the code :

<form >
    <md-input-container>
      <input mdInput type="email" placeholder="Email" >
    </md-input-container>
    <md-input-container>
      <input mdInput type="password" placeholder="Mot de passe" >
    </md-input-container>

    <button md-button type="submit" >Se connecter</button>
  </form>```

What I missed ? Thank you so much.

Elisa

答:
Make sure getting started steps are followed and

@NgModule({
  ...
  imports: [MdInputModule],
  ...
})
is added in angular module

Let me know if you need any help .

Title: Angular 2 Material Design

Body:
I am learning Angular 2 and I have so many problems with that whose one I can't find anything on that on internet. So, I tried easy thing to start : create a sign in form in my app, so I am using Material Design but my input are bad and nothing like in the Material Design Doc. Here so picture :
enter image description here

So as you can see my input are not display and the placeholder is under it.

Here the code :

<form >
    <md-input-container>
      <input mdInput type="email" placeholder="Email" >
    </md-input-container>
    <md-input-container>
      <input mdInput type="password" placeholder="Mot de passe" >
    </md-input-container>

    <button md-button type="submit" >Se connecter</button>
  </form>

What I missed ? Thank you so much.

Elisa


问:
How to filter multiple conditions in same column pyspark sql
I have a column like below:

```<code>+-------+------------------+-------+
|   name|             value|user_id|
+-------+------------------+-------+

| user 1|             view |      1|
| user 1|         processed|      1|
| user 2|             view |      3|
| user 3|             view |      4|
+-------+------------------+-------+
</code>```

I want to get column like below.

```<code>+-------+------------------+-------+
|   name|             value|user_id|
+-------+------------------+-------+
| user 2|             view |      3|
| user 3|             view |      4|
+-------+------------------+-------+
</code>```

simply, eliminate ids which done both action.

currently, I have two data frame like below

```<code>df1 = df.where(value=="processed").select("id").distinct()
df2 = df.where(value=="view").select("id").distinct()
</code>```

now, how to get only ids which only have view not processed.Or is there any better way to do it?

答:
One option could be a "leftanti" self join to eliminate all name's that contain "processed":

```<code>result = df.join(df.where(df.value=="processed") \
                   .select("name") \
                   .distinct(),
                 "name", "leftanti")
result.show()
+------+-----+-------+
|  name|value|user_id|
+------+-----+-------+
|user 3| view|      4|
|user 2| view|      3|
+------+-----+-------+
</code>```

Body:
I have a column like below:

+-------+------------------+-------+
|   name|             value|user_id|
+-------+------------------+-------+

| user 1|             view |      1|
| user 1|         processed|      1|
| user 2|             view |      3|
| user 3|             view |      4|
+-------+------------------+-------+

I want to get column like below.

+-------+------------------+-------+
|   name|             value|user_id|
+-------+------------------+-------+
| user 2|             view |      3|
| user 3|             view |      4|
+-------+------------------+-------+

simply, eliminate ids which done both action.

currently, I have two data frame like below

df1 = df.where(value=="processed").select("id").distinct()
df2 = df.where(value=="view").select("id").distinct()

now, how to get only ids which only have view not processed.Or is there any better way to do it?

Body:
One option could be a "leftanti" self join to eliminate all name's that contain "processed":

result = df.join(df.where(df.value=="processed") \
                   .select("name") \
                   .distinct(),
                 "name", "leftanti")
result.show()
+------+-----+-------+
|  name|value|user_id|
+------+-----+-------+
|user 3| view|      4|
|user 2| view|      3|
+------+-----+-------+


问:
How to load Data given in textboxes of html page in the below table of html page?
data given in surname,postcode,textboxes must be loaded in below table when create customer link is clicked</p>

答:
You can try my code as your requirement:

```<code><table>
<tr>
    <td>
        <select name="choice_type">
        <option>select</option>
        <option value="part_type">part_type</option>
        <option value="category">category</option>
        <option value="names">names</option>
        </select>
    </td>
</tr>
<tr>
    <th>VAL</th>
    <th>VAL DESC</th>
</tr>
<tr>
    <td> <input type="text" name="val"  id="val" size="15" /></td>
    <td> <input type="text" name="val_desc"  id="val_desc" size="15" /></td>
</tr>
</code>```

The getData() function is as follows:

```<code>function getData(){
xmlHttp=GetXmlHttpObject()
var id=document.getElementById("choice_type").value;
var url="choice_retrieval.jsp";//The code for this file is defined below
url=url+"?choice_type="+id;
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null);
}

function stateChanged(){
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
var showdata = xmlHttp.responseText;
var strar = showdata.split(":");
if(strar.length>1){
var strname = strar[1];
document.getElementById("val").value= strar[1];
document.getElementById("val_desc").value= strar[2];
}
}
</code>```

The Code snippet for choice_retrieval.jsp is as follows:

```<code><%
String ch = request.getParameter("choice_type").toString();
System.out.println(ch);
String data ="";
try{
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://", "", "");
    Statement st=con.createStatement();
    ResultSet rs=st.executeQuery("select * from master_panel where
   choice_type='"+ch+"'");
    while(rs.next())
    {
        data = ":" + rs.getString("val") + ": " + rs.getString("val_desc");
    }
    out.println(data);
    System.out.println(data);
}
catch(Exception e) {
    System.out.println(e);
}
%>
</code>```

i think it can help you , All The Best..

Body:
You can try my code as your requirement:

<table>
<tr>
    <td>
        <select name="choice_type">
        <option>select</option>
        <option value="part_type">part_type</option>
        <option value="category">category</option>
        <option value="names">names</option>
        </select>
    </td>
</tr>
<tr>
    <th>VAL</th>
    <th>VAL DESC</th>
</tr>
<tr>
    <td> <input type="text" name="val"  id="val" size="15" /></td>
    <td> <input type="text" name="val_desc"  id="val_desc" size="15" /></td>
</tr>

The getData() function is as follows:

function getData(){
xmlHttp=GetXmlHttpObject()
var id=document.getElementById("choice_type").value;
var url="choice_retrieval.jsp";//The code for this file is defined below
url=url+"?choice_type="+id;
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null);
}

function stateChanged(){
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
var showdata = xmlHttp.responseText;
var strar = showdata.split(":");
if(strar.length>1){
var strname = strar[1];
document.getElementById("val").value= strar[1];
document.getElementById("val_desc").value= strar[2];
}
}

The Code snippet for choice_retrieval.jsp is as follows:

<%
String ch = request.getParameter("choice_type").toString();
System.out.println(ch);
String data ="";
try{
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://", "", "");
    Statement st=con.createStatement();
    ResultSet rs=st.executeQuery("select * from master_panel where
   choice_type='"+ch+"'");
    while(rs.next())
    {
        data = ":" + rs.getString("val") + ": " + rs.getString("val_desc");
    }
    out.println(data);
    System.out.println(data);
}
catch(Exception e) {
    System.out.println(e);
}
%>

i think it can help you , All The Best..


问:
I wanna develop a real time graph app but It doesn't work
this is the code It runs on emulator but it doesn't give real time values

```<code> protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    GraphView graph1 = (GraphView)findViewById(R.id.main_graph1);

    Series = new LineGraphSeries<DataPoint>();
    graph1.addSeries(Series);
</code>```

Here I go to simulate real time with thread that append data:

```<code> protected void onResume(){
    super.onResume();

    new Thread(new Runnable() {

        public void run() {

            for(int i = 0; i<100; i++);
            runOnUiThread(new Runnable() {

                public void run() {
                    addEntry();
                }
            });

            try {
                Thread.sleep(600);
            } catch (InterruptedException e) {

                e.printStackTrace();
            }

        }

    });
}
</code>```

I think it seems to be wrong please help

答:
Issues :

1.) A thread will only be executed when you invoke start function on your thread object (which is missing)

2.) for(int i = 0; i<100; i++); this loop won't do anything due to terminated body by ; at the end

so solution would be

```<code>new Thread(new Runnable() {
    public void run() {
        for(int i = 0; i<100; i++) // ; removed
        runOnUiThread(new Runnable() {

            public void run() {
                addEntry();
            }
        });
        try {
            Thread.sleep(600);
        } catch (InterruptedException e) {

            e.printStackTrace();
        }
    }
}).start(); // invoke start for execution
</code>```

Body:
this is the code It runs on emulator but it doesn't give real time values

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

    GraphView graph1 = (GraphView)findViewById(R.id.main_graph1);

    Series = new LineGraphSeries<DataPoint>();
    graph1.addSeries(Series);

Here I go to simulate real time with thread that append data:

 protected void onResume(){
    super.onResume();

    new Thread(new Runnable() {

        public void run() {

            for(int i = 0; i<100; i++);
            runOnUiThread(new Runnable() {

                public void run() {
                    addEntry();
                }
            });

            try {
                Thread.sleep(600);
            } catch (InterruptedException e) {

                e.printStackTrace();
            }

        }

    });
}

I think it seems to be wrong please help

Body:
Issues :

1.) A thread will only be executed when you invoke start function on your thread object (which is missing)

2.) for(int i = 0; i<100; i++); this loop won't do anything due to terminated body by ; at the end

so solution would be

new Thread(new Runnable() {
    public void run() {
        for(int i = 0; i<100; i++) // ; removed
        runOnUiThread(new Runnable() {

            public void run() {
                addEntry();
            }
        });
        try {
            Thread.sleep(600);
        } catch (InterruptedException e) {

            e.printStackTrace();
        }
    }
}).start(); // invoke start for execution