问:
Regular exp file iteration
i have got  2 files ,one with some  keywords and other with plain text i.e myfile.txt , i need to open a myfile.txt and extract the specific text starting with each keyword (mentioned in keyword file) and ends with "!"
example:

keyword file :

vrf-a

vrf-b

myfile.txt:

hello

how are you

!

x vrf-a

number 1

!

hi

howa are you

!

x vrf-b

number 2

!

Output should be:

x vrf-a

number 1

!

x vrf-b

number 2

I tried the below code:

```<code>import re
crazy = open("keyword.txt","r+")
lines  = crazy.readlines()
for word in lines:
    #print(word)
    with open('mytext.txt', 'r') as fh:
        result = re.findall(r'word[^!]+', fh.read(), re.M)
        print(result)
fh.close()
crazy.close()
</code>```

output getting as :
[]
[]
means no match

答:
You need to use the word as a variable not a string. With a little help of link below:

How to use a variable inside a regular expression?

I have made a little change to our code and it works fine now. You just have to make sure your output is in a format you want:

```<code>import re
crazy = open("keyword.txt","r+")
lines  = crazy.readlines()
for word in lines:
    with open('mytext.txt', 'r') as fh:
        result = re.findall(re.escape(word) + r'[^!]+', fh.read(), re.M)
        print(''.join(result))
fh.close()
crazy.close()
</code>```

Best

Title: Regular exp file iteration

Body:
i have got  2 files ,one with some  keywords and other with plain text i.e myfile.txt , i need to open a myfile.txt and extract the specific text starting with each keyword (mentioned in keyword file) and ends with "!"
example:

keyword file :

vrf-a

vrf-b

myfile.txt:

hello

how are you

!

x vrf-a

number 1

!

hi

howa are you

!

x vrf-b

number 2

!

Output should be:

x vrf-a

number 1

!

x vrf-b

number 2

I tried the below code:

import re
crazy = open("keyword.txt","r+")
lines  = crazy.readlines()
for word in lines:
    #print(word)
    with open('mytext.txt', 'r') as fh:
        result = re.findall(r'word[^!]+', fh.read(), re.M)
        print(result)
fh.close()
crazy.close()

output getting as :
[]
[]
means no match

Body:
You need to use the word as a variable not a string. With a little help of link below:

How to use a variable inside a regular expression?

I have made a little change to our code and it works fine now. You just have to make sure your output is in a format you want:

import re
crazy = open("keyword.txt","r+")
lines  = crazy.readlines()
for word in lines:
    with open('mytext.txt', 'r') as fh:
        result = re.findall(re.escape(word) + r'[^!]+', fh.read(), re.M)
        print(''.join(result))
fh.close()
crazy.close()

Best


来源: stackexchange

问:
How do you test code without uploading to the web server?
(This is a high level software development question)

I'm running a web app.  In the past, to test new features, I have uploaded under a subdirectory such as test/.  This generally broke all the URLs, so I'd have to redo the URLs in the test code. Then I'd have to rename all the URLs when I pushed it to the main site.  I'm sure there's a better way but don't know what people usually do.

Do you install a web server on your laptop?  I could always buy a cheap computer and run it as a test web server, I suppose.

Eventually I'd like to have a version control system with a friend also coding, so maybe we'd both need to install Apache and MySQL on our laptops?  That way we don't interfere with each other when testing new code.

答:
Two answers:

Unit test!  Write tests for your code that aren't dependent on a web server.

Yes, you install a web server on your laptop.

This need not be a big deal at all, depending on your platform.  If you're developing Ruby on Rails apps, there's a web server built in, and others easily installable.  A local copy of Tomcat or Apache is no problem.  For IIS you need to be running the right version of Windows, I think, but I haven't worked in that sphere in a while.

in a pinch you could run a server environment inside a virtual machine.  This has the advantage of making it easier to replicate the precise environment of your actual server.  Occasionally you may run across an situation where something works fine on your own machine but doesn't work on the server, due to a permissions issue or an environment setting or some such.  These can be a pain to debug.  A VM that clones your server environment is one way to avoid these.

OwnerDisplayName: anon

ContentLicense: CC BY-SA 2.5


问:
PHP Error in my Server
Hey Guys I have this Java code in ANdroid studio:

```<code>private void loginUser(){
pd = ProgressDialog.show(LoginActivity.this, "", "Loading...");
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonResponse = new JSONObject(response);
                    boolean success = jsonResponse.getBoolean("success");
                    if (success) {
                        launchHomeScreen();
                        pd.dismiss();
                        Toast.makeText(LoginActivity.this,"Welcome back " + username,Toast.LENGTH_LONG).show();
                    }
                    else {
                        loginButton.setBackgroundColor(0x73000000);
                        Toast.makeText(LoginActivity.this,"Try again later!",Toast.LENGTH_LONG).show();
                        pd.dismiss();
                    }
                }
                catch (JSONException e) {
                    loginButton.setBackgroundColor(0x73000000);
                    e.printStackTrace();
                    Toast.makeText(LoginActivity.this,e.toString(),Toast.LENGTH_LONG).show();
                    pd.dismiss();
                }
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                loginButton.setBackgroundColor(0x73000000);
                Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                pd.dismiss();
            }
        }){
    @Override
    protected Map<String,String> getParams(){
        Map<String,String> params = new HashMap<>();
        params.put(KEY_USERNAME,username);
        params.put(KEY_PASSWORD,password);
        return params;
    }

};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
</code>```

}

And this at my Server as php code:

```<code><?php
$con = mysqli_connect("x", "x", "x", "x");

$username = $_POST["username"];
$password = $_POST["password"];

$statement = mysqli_prepare($con, "SELECT * FROM user WHERE username = ?");
mysqli_stmt_bind_param($statement, "s", $username);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $colUsername, $colPassword);

$response = array();
$response["success"] = false;

while(mysqli_stmt_fetch($statement)){
    if (password_verify($password, $colPassword)) {
        $response["success"] = true;
    }
}
header('Content-Type: application/json');
echo json_encode($response);
</code>```

?>

And that's the Error I get from my Server:

[29-Mar-2017 18:24:46 UTC] PHP Warning: mysqli_stmt_bind_result(): Number of bind variables doesn't match number of fields in prepared statement in /home/u371648055/public_html/login.php on line 11

SO I don't understand what's wrong in my Code. I know that the Javacode is correct....so....it's the phpcode..but what?

MY MySQL Database:

For the problem with the password = 0
Here is that what I send to Server:

```<code>private void registerUser(){
    pd = ProgressDialog.show(RegisterActivity.this, "", "Loading...");
    StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse = new JSONObject(response);
                        boolean success = jsonResponse.getBoolean("success");
                        if (success) {
                            launchHomeScreen();
                            pd.dismiss();
                        }
                        else {
                            Toast.makeText(RegisterActivity.this,"Try again later!",Toast.LENGTH_LONG).show();
                            pd.dismiss();
                            Intent loginActivity = new Intent (RegisterActivity.this,LoginActivity.class);
                            RegisterActivity.this.startActivity(loginActivity);
                            finish();
                        }
                    }
                    catch (JSONException e) {
                        e.printStackTrace();
                        pd.dismiss();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(RegisterActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                    pd.dismiss();
                }
            }){
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> params = new HashMap<>();
            params.put(KEY_USERNAME,username);
            params.put(KEY_PASSWORD,password);
            params.put(KEY_MOBILENUMBER,mobileNumber);
            params.put(KEY_EMAIL, email);
            return params;
        }

    };
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
</code>```

}
ANd that's the register php code:

```<code><?php
$connect = mysqli_connect("x", "x", "x", "x");

$username = $_POST["username"];
$password = $_POST["password"];
$mobilenumber = $_POST["mobilenumber"];
$email = $_POST["email"];

registerUser();

function registerUser() {
    global $connect, $username, $password, $mobilenumber, $email;
    $statement = mysqli_prepare($connect, "INSERT INTO user (username, password, mobilenumber, email) VALUES (?, ?, ?, ?)");
    mysqli_stmt_bind_param($statement, "siss", $username, $password, $mobilenumber, $email);
    mysqli_stmt_execute($statement);
    mysqli_stmt_close($statement);

}
</code>```

How I get the $password:

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

   public static final String KEY_PASSWORD = "password";
   private String password;

  //When clicking the Regsiter-Button:
   pwd = (EditText) findViewById(R.id.editText2);
   password = pwd.getText().toString().trim();
   registerUser();
}
</code>```

答:
Your query gets more columns than variables your are passing to the mysqli_stmt_bind_result() function. Change your select query to get only those columns you need (I'm guessing username and password):

```<code>$statement = mysqli_prepare($con, "SELECT username,password FROM user WHERE username = ?");
</code>```

ContentLicense: CC BY-SA 3.0

Title: PHP Error in my Server

Body:
Hey Guys I have this Java code in ANdroid studio:

private void loginUser(){
pd = ProgressDialog.show(LoginActivity.this, "", "Loading...");
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonResponse = new JSONObject(response);
                    boolean success = jsonResponse.getBoolean("success");
                    if (success) {
                        launchHomeScreen();
                        pd.dismiss();
                        Toast.makeText(LoginActivity.this,"Welcome back " + username,Toast.LENGTH_LONG).show();
                    }
                    else {
                        loginButton.setBackgroundColor(0x73000000);
                        Toast.makeText(LoginActivity.this,"Try again later!",Toast.LENGTH_LONG).show();
                        pd.dismiss();
                    }
                }
                catch (JSONException e) {
                    loginButton.setBackgroundColor(0x73000000);
                    e.printStackTrace();
                    Toast.makeText(LoginActivity.this,e.toString(),Toast.LENGTH_LONG).show();
                    pd.dismiss();
                }
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                loginButton.setBackgroundColor(0x73000000);
                Toast.makeText(LoginActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                pd.dismiss();
            }
        }){
    @Override
    protected Map<String,String> getParams(){
        Map<String,String> params = new HashMap<>();
        params.put(KEY_USERNAME,username);
        params.put(KEY_PASSWORD,password);
        return params;
    }

};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);

}

And this at my Server as php code:

<?php
$con = mysqli_connect("x", "x", "x", "x");

$username = $_POST["username"];
$password = $_POST["password"];

$statement = mysqli_prepare($con, "SELECT * FROM user WHERE username = ?");
mysqli_stmt_bind_param($statement, "s", $username);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $colUsername, $colPassword);

$response = array();
$response["success"] = false;

while(mysqli_stmt_fetch($statement)){
    if (password_verify($password, $colPassword)) {
        $response["success"] = true;
    }
}
header('Content-Type: application/json');
echo json_encode($response);

?>

And that's the Error I get from my Server:

[29-Mar-2017 18:24:46 UTC] PHP Warning: mysqli_stmt_bind_result(): Number of bind variables doesn't match number of fields in prepared statement in /home/u371648055/public_html/login.php on line 11

SO I don't understand what's wrong in my Code. I know that the Javacode is correct....so....it's the phpcode..but what?

MY MySQL Database:

For the problem with the password = 0
Here is that what I send to Server:

private void registerUser(){
    pd = ProgressDialog.show(RegisterActivity.this, "", "Loading...");
    StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse = new JSONObject(response);
                        boolean success = jsonResponse.getBoolean("success");
                        if (success) {
                            launchHomeScreen();
                            pd.dismiss();
                        }
                        else {
                            Toast.makeText(RegisterActivity.this,"Try again later!",Toast.LENGTH_LONG).show();
                            pd.dismiss();
                            Intent loginActivity = new Intent (RegisterActivity.this,LoginActivity.class);
                            RegisterActivity.this.startActivity(loginActivity);
                            finish();
                        }
                    }
                    catch (JSONException e) {
                        e.printStackTrace();
                        pd.dismiss();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(RegisterActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                    pd.dismiss();
                }
            }){
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> params = new HashMap<>();
            params.put(KEY_USERNAME,username);
            params.put(KEY_PASSWORD,password);
            params.put(KEY_MOBILENUMBER,mobileNumber);
            params.put(KEY_EMAIL, email);
            return params;
        }

    };
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);

}
ANd that's the register php code:

<?php
$connect = mysqli_connect("x", "x", "x", "x");

$username = $_POST["username"];
$password = $_POST["password"];
$mobilenumber = $_POST["mobilenumber"];
$email = $_POST["email"];

registerUser();

function registerUser() {
    global $connect, $username, $password, $mobilenumber, $email;
    $statement = mysqli_prepare($connect, "INSERT INTO user (username, password, mobilenumber, email) VALUES (?, ?, ?, ?)");
    mysqli_stmt_bind_param($statement, "siss", $username, $password, $mobilenumber, $email);
    mysqli_stmt_execute($statement);
    mysqli_stmt_close($statement);

}

How I get the $password:

public class RegisterActivity extends AppCompatActivity {

   public static final String KEY_PASSWORD = "password";
   private String password;

  //When clicking the Regsiter-Button:
   pwd = (EditText) findViewById(R.id.editText2);
   password = pwd.getText().toString().trim();
   registerUser();
}

Body:
Your query gets more columns than variables your are passing to the mysqli_stmt_bind_result() function. Change your select query to get only those columns you need (I'm guessing username and password):

$statement = mysqli_prepare($con, "SELECT username,password FROM user WHERE username = ?");


问:
Close Firefox tab programmatically?
I need to close firefox's current tab, either by javascript or any other method, if possible.

I had found somewhere the following solutions:

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

and

```<code> var myWin = window.open('','_self','');
  myWin.close();
</code>```

and both the codes are working in:

Chrome 56.0

Opera 44.0

Internet Explorer 11

Microsoft Edge 38

Safari 5.1

But not in Firefox, I want this working in Firefox.

I have Firefox 52.0, Please Suggest any method,...

Thankyou

答:
Try this

```<code>window.open(document.URL,'_self','resizable=no,top=-245,width=250,height=250,scrollbars=no');
window.close();
</code>```

This should work on chrome and firefox, collected from Close firefox tab from javascript

Title: Close Firefox tab programmatically?

Body:
I need to close firefox's current tab, either by javascript or any other method, if possible.

I had found somewhere the following solutions:

window.close();

and

 var myWin = window.open('','_self','');
  myWin.close();

and both the codes are working in:

Chrome 56.0

Opera 44.0

Internet Explorer 11

Microsoft Edge 38

Safari 5.1

But not in Firefox, I want this working in Firefox.

I have Firefox 52.0, Please Suggest any method,...

Thankyou

Body:
Try this

window.open(document.URL,'_self','resizable=no,top=-245,width=250,height=250,scrollbars=no');
window.close();

This should work on chrome and firefox, collected from Close firefox tab from javascript


问:
Passing multiple values. getting org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
I'm reading query from a text file and depend upon the filters from the UI, With the string buffer i'm appending the additional queries.. Passing multiple id's like above to get the data

I'm getting nested exception is javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
java.sql.SQLSyntaxErrorException: ORA-01722: invalid number.

I'm using q.setParameter which is Java persistance Query. So i don't have paramterList.Because of comma between the values i'm getting Invalid number. Can you please help me what i can do here to support multiple values and can get the data.

My code sample:

```<code>StringBuffer q = new StringBuffer();

 q.append(queryFromPropertiesFile);

if( model.getId()!=null && ! model.getId().isEmpty())
q.append(" and emp.id IN (:id)");

Query query = entity.createNativeQuery(q.toString());

query.setParameter("id", model.getId());
</code>```

答:
You need to pass a List object (i.e., split your string using , delimiter) and then pass that list of ids (List object) to the setParameter as shown below:

```<code>List<String> idsList = new ArrayList<>();
String[] ids = model.getId().split(",");
for(String id : ids) {
    idsList.add(id);
}

query.setParameterList("id", idsList);
</code>```

Body:
I'm reading query from a text file and depend upon the filters from the UI, With the string buffer i'm appending the additional queries.. Passing multiple id's like above to get the data

I'm getting nested exception is javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
java.sql.SQLSyntaxErrorException: ORA-01722: invalid number.

I'm using q.setParameter which is Java persistance Query. So i don't have paramterList.Because of comma between the values i'm getting Invalid number. Can you please help me what i can do here to support multiple values and can get the data.

My code sample:

StringBuffer q = new StringBuffer();

 q.append(queryFromPropertiesFile);

if( model.getId()!=null && ! model.getId().isEmpty())
q.append(" and emp.id IN (:id)");

Query query = entity.createNativeQuery(q.toString());

query.setParameter("id", model.getId());

Body:
You need to pass a List object (i.e., split your string using , delimiter) and then pass that list of ids (List object) to the setParameter as shown below:

List<String> idsList = new ArrayList<>();
String[] ids = model.getId().split(",");
for(String id : ids) {
    idsList.add(id);
}

query.setParameterList("id", idsList);


问:
How to add median value mysql
I'm trying a add median to this query below. I already have MAX.and MIN for the Sales_Total_Price Column with the results group by the Item_name.

Can anyone help me. I have seen a lot of posts about this but I am having a hard time attaching that data to my query. thanks!

```<code>SELECT item_master_list.Item_Name, item_master_list.NPC_Item_Price,
       item_master_list.NPC_Item_Value,
       MAX(public_vendor_sales_data.Sales_Total_Price),
       MIN(public_vendor_sales_data.Sales_Total_Price)
FROM item_master_list INNER JOIN
     public_vendor_sales_data
     ON  public_vendor_sales_data.Item_ID = item_master_list.Item_ID
GROUP BY Item_Name
</code>```

current results
results

答:
I would give up on the median; it is rather hard to calculate.  Instead, I recommend calculating the average:

```<code>SELECT iml.Item_Name, iml.NPC_Item_Price, iml.NPC_Item_Value,
       MAX(vs.Sales_Total_Price),
       MIN(vs.Sales_Total_Price),
       AVG(vs.Sales_Total_Price)
FROM item_master_list iml INNER JOIN
     public_vendor_sales_data vs
     ON vs.Item_ID = iml.Item_ID
GROUP BY Item_Name;
</code>```

Title: How to add median value mysql

Body:
I'm trying a add median to this query below. I already have MAX.and MIN for the Sales_Total_Price Column with the results group by the Item_name.

Can anyone help me. I have seen a lot of posts about this but I am having a hard time attaching that data to my query. thanks!

SELECT item_master_list.Item_Name, item_master_list.NPC_Item_Price,
       item_master_list.NPC_Item_Value,
       MAX(public_vendor_sales_data.Sales_Total_Price),
       MIN(public_vendor_sales_data.Sales_Total_Price)
FROM item_master_list INNER JOIN
     public_vendor_sales_data
     ON  public_vendor_sales_data.Item_ID = item_master_list.Item_ID
GROUP BY Item_Name

current results
results

Body:
I would give up on the median; it is rather hard to calculate.  Instead, I recommend calculating the average:

SELECT iml.Item_Name, iml.NPC_Item_Price, iml.NPC_Item_Value,
       MAX(vs.Sales_Total_Price),
       MIN(vs.Sales_Total_Price),
       AVG(vs.Sales_Total_Price)
FROM item_master_list iml INNER JOIN
     public_vendor_sales_data vs
     ON vs.Item_ID = iml.Item_ID
GROUP BY Item_Name;


答:
Use something like JUnit for java ..

Yes, install a local tomcat or whatever webserver you run in production environment,
with eclipse IDE it's pretty simple to even debug the code .. still talking java ..

Title: How do you test code without uploading to the web server?

Body:
(This is a high level software development question)

I'm running a web app.  In the past, to test new features, I have uploaded under a subdirectory such as test/.  This generally broke all the URLs, so I'd have to redo the URLs in the test code. Then I'd have to rename all the URLs when I pushed it to the main site.  I'm sure there's a better way but don't know what people usually do.

Do you install a web server on your laptop?  I could always buy a cheap computer and run it as a test web server, I suppose.

Eventually I'd like to have a version control system with a friend also coding, so maybe we'd both need to install Apache and MySQL on our laptops?  That way we don't interfere with each other when testing new code.


问:
React Photoswipe using removed babel 5 option
I am just starting to dabble in react and one of the first components I want is something to use photoswipe.js. (react photoswipe)  It looks like there is a pretty decent one on npm, but I am running into a problem.  When I run my storybook to start testing and building my component, I get an error from babel.  It says:

```<code>in ./~/react-photoswipe/lib/index.js
Module build failed: ReferenceError: [BABEL] C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\react-photoswipe\lib\index.js: Using removed Babel 5 option: C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\react-photoswipe\.babelrc.stage - Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets
    at Logger.error (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-core\lib\transformation\file\logger.js:41:11)
    at OptionManager.mergeOptions (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-core\lib\transformation\file\options\option-manager.js:220:20)
    at OptionManager.init (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-core\lib\transformation\file\options\option-manager.js:368:12)
    at File.initOptions (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-core\lib\transformation\file\index.js:212:65)
    at new File (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-core\lib\transformation\file\index.js:135:24)
    at Pipeline.transform (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-core\lib\transformation\pipeline.js:46:16)
    at transpile (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-loader\lib\index.js:46:20)
    at C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-loader\lib\fs-cache.js:79:18
    at ReadFileContext.callback (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-loader\lib\fs-cache.js:15:14)
    at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:365:13)
</code>```

So I did a bit of poking around and noticed that the babel rc file appears to be set to stage:0 which from my understanding seems like a really bad idea if you are producing a component that is supposed to be durable as the javascript spec updates and evolves.

I am still pretty new to using babel though so I am kind of having a hard time tracking down what I would need to update for this component to get it working in my environment with the newer babel.  Has anyone encountered this problem with this component before?  Does anyone have any advice or tips on how to troubleshoot the bable transpile and track down what I need to update?

答: Thanks Michael for getting me pointed in the right direction.  I am testing and building a component using a react storybook tool that has a whitelist configuration that tells it what node modules not to run through the full build.  I had to add react-photoswipe to that whitelist and it is now working... well starting to work, but this problem is taken care of.</p>

Body:
I am just starting to dabble in react and one of the first components I want is something to use photoswipe.js. (react photoswipe)  It looks like there is a pretty decent one on npm, but I am running into a problem.  When I run my storybook to start testing and building my component, I get an error from babel.  It says:

in ./~/react-photoswipe/lib/index.js
Module build failed: ReferenceError: [BABEL] C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\react-photoswipe\lib\index.js: Using removed Babel 5 option: C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\react-photoswipe\.babelrc.stage - Check out the corresponding stage-x presets http://babeljs.io/docs/plugins/#presets
    at Logger.error (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-core\lib\transformation\file\logger.js:41:11)
    at OptionManager.mergeOptions (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-core\lib\transformation\file\options\option-manager.js:220:20)
    at OptionManager.init (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-core\lib\transformation\file\options\option-manager.js:368:12)
    at File.initOptions (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-core\lib\transformation\file\index.js:212:65)
    at new File (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-core\lib\transformation\file\index.js:135:24)
    at Pipeline.transform (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-core\lib\transformation\pipeline.js:46:16)
    at transpile (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-loader\lib\index.js:46:20)
    at C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-loader\lib\fs-cache.js:79:18
    at ReadFileContext.callback (C:\Code\GIT\DanStatenReact\DanStatenUI\node_modules\babel-loader\lib\fs-cache.js:15:14)
    at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:365:13)

So I did a bit of poking around and noticed that the babel rc file appears to be set to stage:0 which from my understanding seems like a really bad idea if you are producing a component that is supposed to be durable as the javascript spec updates and evolves.

I am still pretty new to using babel though so I am kind of having a hard time tracking down what I would need to update for this component to get it working in my environment with the newer babel.  Has anyone encountered this problem with this component before?  Does anyone have any advice or tips on how to troubleshoot the bable transpile and track down what I need to update?


问:
Center text with images on the left and right
Im trying to create a small navigation using jquery and bootstrap. Im a bit stuck with aligning the images

i have 2 arrow images onto my left and right with the title in the center.

Below is my code

```<code><div class="row" style="text-align:center">
  <img src="https://cdn3.iconfinder.com/data/icons/google-material-design-icons/48/ic_keyboard_arrow_left_48px-128.png" style="float:left">
   <h2>Heading name or title</h2>
  <img src="https://cdn3.iconfinder.com/data/icons/google-material-design-icons/48/ic_keyboard_arrow_right_48px-128.png">
</div>
</code>```

i did manage to set some margins and paddings and get it working but when the title gets longer the layout breaks also it doesnt work property on responsive views.

Can someone please suggest me a proper way to do this?

Thanks

答:
Make the h2 an inline-block, apply vertical-align: middle; to the images and remove the float from the first image:

h2 {
display: inline-block;
}
img {
vertical-align: middle;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row" style="text-align:center;">
  <img src="https://cdn3.iconfinder.com/data/icons/google-material-design-icons/48/ic_keyboard_arrow_left_48px-128.png">
   <h2>Heading name or title</h2>
  <img src="https://cdn3.iconfinder.com/data/icons/google-material-design-icons/48/ic_keyboard_arrow_right_48px-128.png">
</div></code>```

Body:
Im trying to create a small navigation using jquery and bootstrap. Im a bit stuck with aligning the images

i have 2 arrow images onto my left and right with the title in the center.

Below is my code

Heading name or title

i did manage to set some margins and paddings and get it working but when the title gets longer the layout breaks also it doesnt work property on responsive views.

Can someone please suggest me a proper way to do this?

Thanks

Body:
Make the h2 an inline-block, apply vertical-align: middle; to the images and remove the float from the first image:

h2 {
display: inline-block;
}
img {
vertical-align: middle;
}

<div class="row" style="text-align:center;">
  <img src="https://cdn3.iconfinder.com/data/icons/google-material-design-icons/48/ic_keyboard_arrow_left_48px-128.png">
   <h2>Heading name or title</h2>
  <img src="https://cdn3.iconfinder.com/data/icons/google-material-design-icons/48/ic_keyboard_arrow_right_48px-128.png">
</div>


问:
Firebase Email Verification Android
I am trying having a little bit of a problem in my application which uses firebase to store usernames and send verification emails. I have gotten to the point where you can create an account and it will send a verification link. So, I was wondering since if someone registers with an email firebase automatically registers it, so can't a person that just type a random email, say for example test@test.com and then the real owner of test@test.com tries registering but can't because the email is already taken even though the imposter didn't/can't verify it the verification link. Is there any way to make it so that the email is only registered in the firebase auth once the verification link has successfully been clicked by the person that really owns that email?

Any help would be greatly appreciated! (Also I am very new to firebase)

Here is my Java class code:

https://pastebin.com/HP7Q15Gh

答:
When you send the email verification, it won't be verified until the link is clicked, so even if User A tries to verify UserB@example.com, it will send the link, but won't create the account until the email is verified. If User B tries to create an account, another email would be sent to UserB@example.com, which they could verify. The template very clearly says:

If you didn’t ask to verify this address, you can ignore this email.

This would allow the "real" user to create an account with their own address if the wanted to.

Title: Firebase Email Verification Android


问:
trying to avoid hard coding markup in react given but unsure if it is efficient
For example, to avoid hardcoding here:

```<code>photos.map((photo, i) => {
  return (
    <tr>
      {
        Object.keys(photo).map(j =>
          <td>
            {photo[j]}
          </td>
        )
      }
    </tr>
  );
});
</code>```

Obviously this is better than hard coding each column, but is this efficient?  Is there a better way to do this?

答:
I feel this is good. You can refactor your two maps into separate methods, but that depends.

Here is an example from React docs, they show how to use the map for dynamic items.

Tip: You will want to add keys to your
 and

I hope that helps!

Body:
For example, to avoid hardcoding here:

photos.map((photo, i) => {
  return (

      {
        Object.keys(photo).map(j =>

            {photo[j]}

        )
      }

  );
});

Obviously this is better than hard coding each column, but is this efficient?  Is there a better way to do this?

Body:
I feel this is good. You can refactor your two maps into separate methods, but that depends.

Here is an example from React docs, they show how to use the map for dynamic items.

Tip: You will want to add keys to your <tr> and <td>

I hope that helps!


问:
How to resolve error when initializing MobileServiceClient Xamarin.Forms?
This is my code:

```<code>MobileServiceClient a = new MobileServiceClient("http://appitalo.azurewebsites.net/");
</code>```

When I try to execute this code in my Xamarin.Forms android app, I get the following message

Does somebody have any idea how to fix this?

答:
platform specific assembly: Microsoft.WindowsAzure.Mobile.Ext

(Assuming you are talking at the deprecated Mobile Services vs. App Services)

Make sure that you have added the WindowsAzure.MobileServices Nuget package to each of your projects, including the application projects as there are platform-specific libraries that need to be included.

```<code>├── Xamarin.iOS10
│   ├── Microsoft.WindowsAzure.Mobile.Ext.dll
│   ├── Microsoft.WindowsAzure.Mobile.Ext.xml
│   ├── Microsoft.WindowsAzure.Mobile.dll
│   └── Microsoft.WindowsAzure.Mobile.xml
├── monoandroid
│   ├── Microsoft.WindowsAzure.Mobile.Ext.dll
│   ├── Microsoft.WindowsAzure.Mobile.Ext.xml
│   ├── Microsoft.WindowsAzure.Mobile.dll
│   └── Microsoft.WindowsAzure.Mobile.xml
├── monotouch
│   ├── Microsoft.WindowsAzure.Mobile.Ext.dll
│   ├── Microsoft.WindowsAzure.Mobile.Ext.xml
│   ├── Microsoft.WindowsAzure.Mobile.dll
│   └── Microsoft.WindowsAzure.Mobile.xml
├── net45
│   ├── Microsoft.WindowsAzure.Mobile.Ext.dll
│   ├── Microsoft.WindowsAzure.Mobile.dll
│   └── Microsoft.WindowsAzure.Mobile.xml
├── netcore45
│   ├── Microsoft.WindowsAzure.Mobile.Ext.dll
│   ├── Microsoft.WindowsAzure.Mobile.Ext.pri
│   ├── Microsoft.WindowsAzure.Mobile.Ext.xml
│   ├── Microsoft.WindowsAzure.Mobile.dll
│   └── Microsoft.WindowsAzure.Mobile.xml
├── portable-win+net45+wp8+wpa81+monotouch+monoandroid
│   ├── Microsoft.WindowsAzure.Mobile.dll
│   └── Microsoft.WindowsAzure.Mobile.xml
├── wp8
│   ├── Microsoft.WindowsAzure.Mobile.Ext.dll
│   ├── Microsoft.WindowsAzure.Mobile.Ext.xml
│   ├── Microsoft.WindowsAzure.Mobile.UI.dll
│   ├── Microsoft.WindowsAzure.Mobile.UI.xml
│   ├── Microsoft.WindowsAzure.Mobile.dll
│   └── Microsoft.WindowsAzure.Mobile.xml
└── wpa81
    ├── Microsoft.WindowsAzure.Mobile.Ext.dll
    ├── Microsoft.WindowsAzure.Mobile.Ext.xml
    ├── Microsoft.WindowsAzure.Mobile.dll
    └── Microsoft.WindowsAzure.Mobile.xml
</code>```

Body:
This is my code:

MobileServiceClient a = new MobileServiceClient("http://appitalo.azurewebsites.net/");

When I try to execute this code in my Xamarin.Forms android app, I get the following message

Does somebody have any idea how to fix this?

Body:
platform specific assembly: Microsoft.WindowsAzure.Mobile.Ext

(Assuming you are talking at the deprecated Mobile Services vs. App Services)

Make sure that you have added the WindowsAzure.MobileServices Nuget package to each of your projects, including the application projects as there are platform-specific libraries that need to be included.

├── Xamarin.iOS10
│   ├── Microsoft.WindowsAzure.Mobile.Ext.dll
│   ├── Microsoft.WindowsAzure.Mobile.Ext.xml
│   ├── Microsoft.WindowsAzure.Mobile.dll
│   └── Microsoft.WindowsAzure.Mobile.xml
├── monoandroid
│   ├── Microsoft.WindowsAzure.Mobile.Ext.dll
│   ├── Microsoft.WindowsAzure.Mobile.Ext.xml
│   ├── Microsoft.WindowsAzure.Mobile.dll
│   └── Microsoft.WindowsAzure.Mobile.xml
├── monotouch
│   ├── Microsoft.WindowsAzure.Mobile.Ext.dll
│   ├── Microsoft.WindowsAzure.Mobile.Ext.xml
│   ├── Microsoft.WindowsAzure.Mobile.dll
│   └── Microsoft.WindowsAzure.Mobile.xml
├── net45
│   ├── Microsoft.WindowsAzure.Mobile.Ext.dll
│   ├── Microsoft.WindowsAzure.Mobile.dll
│   └── Microsoft.WindowsAzure.Mobile.xml
├── netcore45
│   ├── Microsoft.WindowsAzure.Mobile.Ext.dll
│   ├── Microsoft.WindowsAzure.Mobile.Ext.pri
│   ├── Microsoft.WindowsAzure.Mobile.Ext.xml
│   ├── Microsoft.WindowsAzure.Mobile.dll
│   └── Microsoft.WindowsAzure.Mobile.xml
├── portable-win+net45+wp8+wpa81+monotouch+monoandroid
│   ├── Microsoft.WindowsAzure.Mobile.dll
│   └── Microsoft.WindowsAzure.Mobile.xml
├── wp8
│   ├── Microsoft.WindowsAzure.Mobile.Ext.dll
│   ├── Microsoft.WindowsAzure.Mobile.Ext.xml
│   ├── Microsoft.WindowsAzure.Mobile.UI.dll
│   ├── Microsoft.WindowsAzure.Mobile.UI.xml
│   ├── Microsoft.WindowsAzure.Mobile.dll
│   └── Microsoft.WindowsAzure.Mobile.xml
└── wpa81
    ├── Microsoft.WindowsAzure.Mobile.Ext.dll
    ├── Microsoft.WindowsAzure.Mobile.Ext.xml
    ├── Microsoft.WindowsAzure.Mobile.dll
    └── Microsoft.WindowsAzure.Mobile.xml


问:
C++: What are some general ways to make code more efficient for use with large numbers?
Please when answering this question try to be as general as possible to help the wider community, rather than just specifically helping my issue (although helping my issue would be great too ;) )

I seem to be encountering this problem time and time again with the simple problems on Project Euler. Most commonly are the problems that require a computation of the prime numbers - these without fail always fail to terminate for numbers greater than about 60,000.

My most recent issue is with Problem 12:

The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

Let us list the factors of the first seven triangle numbers:

1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.

What is the value of the first triangle number to have over five hundred divisors?

Here is my code:

```<code>#include <iostream>
#include <vector>
#include <cmath>

using namespace std;

int main() {

int numberOfDivisors = 500;

//I begin by looping from 1, with 1 being the 1st triangular number, 2 being the second, and so on.
for (long long int i = 1;; i++) {
    long long int triangularNumber = (pow(i, 2) + i)/2
    //Once I have the i-th triangular, I loop from 1 to itself, and add 1 to count each time I encounter a divisor, giving the total number of divisors for each triangular.
    int count = 0;
    for (long long int j = 1; j <= triangularNumber; j++) {
        if (triangularNumber%j == 0) {
            count++;
        }
    }
    //If the number of divisors is 500, print out the triangular and break the code.
    if (count == numberOfDivisors) {
        cout << triangularNumber << endl;
        break;
    }
}

}
</code>```

This code gives the correct answers for smaller numbers, and then either fails to terminate or takes an age to do so!

So firstly, what can I do with this specific problem to make my code more efficient?

Secondly, what are some general tips both for myself and other new C++ users for making code more efficient? (I.e. applying what we learn here in the future.)

Thanks!

答:
Tldr: 76576500.

About your Euler problem, some math:

Preliminary 1:

Let's call the n-th triangle number T(n).

T(n) = 1 + 2 + 3 + ... + n = (n^2 + n)/2 (sometimes attributed to Gauss, sometimes someone else). It's not hard to figure it out:

```<code>1+2+3+4+5+6+7+8+9+10 =
(1+10) + (2+9) + (3+8) + (4+7) + (5+6) =
11 + 11 + 11 + 11 + 11 =
55 =
110 / 2 =
(10*10 + 10)/2
</code>```

Because of its definition, it's trivial that T(n) + n + 1 = T(n+1), and that with a<b, T(a)<T(b) is true too.

Preliminary 2:

Let's call the divisor count D. D(1)=1, D(4)=3 (because 1 2 4).

For a n with c non-repeating prime factors (not just any divisors, but prime factors, eg. n = 42 = 2 * 3 * 7 has c = 3), D(n) is c^2: For each factor, there are two possibilites (use it or not). The 9 possibile divisors for the examples are: 1, 2, 3, 7, 6 (2*3), 14 (2*7), 21 (3*7), 42 (2*3*7).

More generally with repeating, the solution for D(n) is multiplying (Power+1) together. Example 126 = 2^1 * 3^2 * 7^1: Because it has two 3, the question is no "use 3 or not", but "use it 1 time, 2 times or not" (if one time, the "first" or "second" 3 doesn't change the result). With the powers 1 2 1, D(126) is 2*3*2=12.

Preliminary 3:

A number n and n+1 can't have any common prime factor x other than 1 (technically, 1 isn't a prime, but whatever). Because if both n/x and (n+1)/x are natural numbers, (n+1)/x - n/x has to be too, but that is 1/x.

Back to Gauss: If we know the prime factors for a certain n and n+1 (needed to calculate D(n) and D(n+1)), calculating D(T(n)) is easy. T(N) = (n^2 + n) / 2 = n * (n+1) / 2. As n and n+1 don't have common prime factors, just throwing together all factors and removing one 2 because of the "/2" is enough. Example: n is 7, factors 7 = 7^1, and n+1 = 8 = 2^3. Together it's 2^3 * 7^1, removing one 2 is 2^2 * 7^1. Powers are 2 1, D(T(7)) = 3*2 = 6. To check, T(7) = 28 = 2^2 * 7^1, the 6 possible divisors are 1 2 4 7 14 28.

What the program could do now: Loop through all n from 1 to something, always factorize n and n+1, use this to get the divisor count of the n-th triangle number, and check if it is >500.

There's just the tiny problem that there are no efficient algorithms for prime factorization. But for somewhat small numbers, todays computers are still fast enough, and keeping all found factorizations from 1 to n helps too for finding the next one (for n+1). Potential problem 2 are too large numbers for longlong, but again, this is no problem here (as can be found out with trying).

With the described process and the program below, I got

the 12375th triangle number is 76576500 and has 576 divisors

```<code>#include <iostream>
#include <vector>
#include <cstdint>

using namespace std;

const int limit = 500;

vector<uint64_t> knownPrimes; //2 3 5 7...

//eg. [14] is 1 0 0 1 ... because 14 = 2^1 * 3^0 * 5^0 * 7^1
vector<vector<uint32_t>> knownFactorizations;

void init()
{
    knownPrimes.push_back(2);
    knownFactorizations.push_back(vector<uint32_t>(1, 0)); //factors for 0 (dummy)
    knownFactorizations.push_back(vector<uint32_t>(1, 0)); //factors for 1 (dummy)
    knownFactorizations.push_back(vector<uint32_t>(1, 1)); //factors for 2
}

void addAnotherFactorization()
{
    uint64_t number = knownFactorizations.size();
    size_t len = knownPrimes.size();
    for(size_t i = 0; i < len; i++)
    {
        if(!(number % knownPrimes[i]))
        {
            //dividing with a prime gets a already factorized number
            knownFactorizations.push_back(knownFactorizations[number / knownPrimes[i]]);
            knownFactorizations[number][i]++;
            return;
        }
    }

    //if this failed, number is a newly found prime
    //because a) it has no known prime factors, so it must have others
    //and b) if it is not a prime itself, then it's factors should've been
    //found already (because they are smaller than the number itself)

    knownPrimes.push_back(number);

    len = knownFactorizations.size();
    for(size_t s = 0; s < len; s++)
    {
        knownFactorizations[s].push_back(0);
    }

    knownFactorizations.push_back(knownFactorizations[0]);
    knownFactorizations[number][knownPrimes.size() - 1]++;
}

uint64_t calculateDivisorCountOfN(uint64_t number)
{
    //factors for number must be known
    uint64_t res = 1;
    size_t len = knownFactorizations[number].size();
    for(size_t s = 0; s < len; s++)
    {
        if(knownFactorizations[number][s])
        {
            res *= (knownFactorizations[number][s] + 1);
        }
    }
    return res;
}

uint64_t calculateDivisorCountOfTN(uint64_t number)
{
    //factors for number and number+1 must be known
    uint64_t res = 1;
    size_t len = knownFactorizations[number].size();
    vector<uint32_t> tmp(len, 0);
    size_t s;
    for(s = 0; s < len; s++)
    {
        tmp[s] = knownFactorizations[number][s]
            + knownFactorizations[number+1][s];
    }
    //remove /2
    tmp[0]--;
    for(s = 0; s < len; s++)
    {
        if(tmp[s])
        {
            res *= (tmp[s] + 1);
        }
    }
    return res;
}

int main()
{
    init();
    uint64_t number = knownFactorizations.size() - 2;
    uint64_t DTn = 0;

    while(DTn <= limit)
    {
        number++;
        addAnotherFactorization();
        DTn = calculateDivisorCountOfTN(number);
    }

    uint64_t tn;
    if(number % 2) tn = ((number+1)/2)*number;
    else tn = (number/2)*(number+1);
    cout << "the " << number << "th triangle number is "
        << tn << " and has " << DTn << " divisors" << endl;
    return 0;
}
</code>```

About your general question about speed:

1) Algorithms.

How to know them? For (relatively) simple problems, either reading a book/Wikipedia/etc. or figuring it out if you can. For harder stuff, learning more basic things and gaining experience is necessary before it's even possible to understand them, eg. studying CS and/or maths ... number theory helps a lot for your Euler problem. (It will help less to understand how a MP3 file is compressed ... there are many areas, it's not possible to know everything.).

2a) Automated compiler optimizations of frequently used code parts / patterns

2b) Manual timing what program parts are the slowest, and (when not replacing it with another algorithm) changing it in a way that eg. requires less data send to slow devices (HDD, hetwork...), less RAM memory access, less CPU cycles, works better together with OS scheduler and memory management strategies, uses the CPU pipeline/caches better etc.etc. ... this is both education and experience (and a big topic).

And because long variables have a limited size, sometimes it is necessary to use custom types that use eg. a byte array to store a single digit in each byte. That way, it's possible to use the whole RAM for a single number if you want to, but the downside is you/someone has to reimplement stuff like addition and so on for this kind of number storage. (Of course, libs for that exist already, without writing everything from scratch).

Btw., pow is a floating point function and may get you inaccurate results. It's not appropriate to use it in this case.

Body:
Please when answering this question try to be as general as possible to help the wider community, rather than just specifically helping my issue (although helping my issue would be great too ;) )

I seem to be encountering this problem time and time again with the simple problems on Project Euler. Most commonly are the problems that require a computation of the prime numbers - these without fail always fail to terminate for numbers greater than about 60,000.

My most recent issue is with Problem 12:

The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

Let us list the factors of the first seven triangle numbers:

1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.

What is the value of the first triangle number to have over five hundred divisors?

Here is my code:

#include <iostream>
#include <vector>
#include <cmath>

using namespace std;

int main() {

int numberOfDivisors = 500;

//I begin by looping from 1, with 1 being the 1st triangular number, 2 being the second, and so on.
for (long long int i = 1;; i++) {
    long long int triangularNumber = (pow(i, 2) + i)/2
    //Once I have the i-th triangular, I loop from 1 to itself, and add 1 to count each time I encounter a divisor, giving the total number of divisors for each triangular.
    int count = 0;
    for (long long int j = 1; j <= triangularNumber; j++) {
        if (triangularNumber%j == 0) {
            count++;
        }
    }
    //If the number of divisors is 500, print out the triangular and break the code.
    if (count == numberOfDivisors) {
        cout << triangularNumber << endl;
        break;
    }
}

}

This code gives the correct answers for smaller numbers, and then either fails to terminate or takes an age to do so!

So firstly, what can I do with this specific problem to make my code more efficient?

Secondly, what are some general tips both for myself and other new C++ users for making code more efficient? (I.e. applying what we learn here in the future.)

Thanks!

Body:
Tldr: 76576500.

About your Euler problem, some math:

Preliminary 1:

Let's call the n-th triangle number T(n).

T(n) = 1 + 2 + 3 + ... + n = (n^2 + n)/2 (sometimes attributed to Gauss, sometimes someone else). It's not hard to figure it out:

1+2+3+4+5+6+7+8+9+10 =
(1+10) + (2+9) + (3+8) + (4+7) + (5+6) =
11 + 11 + 11 + 11 + 11 =
55 =
110 / 2 =
(10*10 + 10)/2

Because of its definition, it's trivial that T(n) + n + 1 = T(n+1), and that with a<b, T(a)<T(b) is true too.

Preliminary 2:

Let's call the divisor count D. D(1)=1, D(4)=3 (because 1 2 4).

For a n with c non-repeating prime factors (not just any divisors, but prime factors, eg. n = 42 = 2 * 3 * 7 has c = 3), D(n) is c^2: For each factor, there are two possibilites (use it or not). The 9 possibile divisors for the examples are: 1, 2, 3, 7, 6 (2*3), 14 (2*7), 21 (3*7), 42 (2*3*7).

More generally with repeating, the solution for D(n) is multiplying (Power+1) together. Example 126 = 2^1 * 3^2 * 7^1: Because it has two 3, the question is no "use 3 or not", but "use it 1 time, 2 times or not" (if one time, the "first" or "second" 3 doesn't change the result). With the powers 1 2 1, D(126) is 2*3*2=12.

Preliminary 3:

A number n and n+1 can't have any common prime factor x other than 1 (technically, 1 isn't a prime, but whatever). Because if both n/x and (n+1)/x are natural numbers, (n+1)/x - n/x has to be too, but that is 1/x.

Back to Gauss: If we know the prime factors for a certain n and n+1 (needed to calculate D(n) and D(n+1)), calculating D(T(n)) is easy. T(N) = (n^2 + n) / 2 = n * (n+1) / 2. As n and n+1 don't have common prime factors, just throwing together all factors and removing one 2 because of the "/2" is enough. Example: n is 7, factors 7 = 7^1, and n+1 = 8 = 2^3. Together it's 2^3 * 7^1, removing one 2 is 2^2 * 7^1. Powers are 2 1, D(T(7)) = 3*2 = 6. To check, T(7) = 28 = 2^2 * 7^1, the 6 possible divisors are 1 2 4 7 14 28.

What the program could do now: Loop through all n from 1 to something, always factorize n and n+1, use this to get the divisor count of the n-th triangle number, and check if it is >500.

There's just the tiny problem that there are no efficient algorithms for prime factorization. But for somewhat small numbers, todays computers are still fast enough, and keeping all found factorizations from 1 to n helps too for finding the next one (for n+1). Potential problem 2 are too large numbers for longlong, but again, this is no problem here (as can be found out with trying).

With the described process and the program below, I got

the 12375th triangle number is 76576500 and has 576 divisors

#include <iostream>
#include <vector>
#include <cstdint>

using namespace std;

const int limit = 500;

vector<uint64_t> knownPrimes; //2 3 5 7...

//eg. [14] is 1 0 0 1 ... because 14 = 2^1 * 3^0 * 5^0 * 7^1
vector<vector<uint32_t>> knownFactorizations;

void init()
{
    knownPrimes.push_back(2);
    knownFactorizations.push_back(vector<uint32_t>(1, 0)); //factors for 0 (dummy)
    knownFactorizations.push_back(vector<uint32_t>(1, 0)); //factors for 1 (dummy)
    knownFactorizations.push_back(vector<uint32_t>(1, 1)); //factors for 2
}

void addAnotherFactorization()
{
    uint64_t number = knownFactorizations.size();
    size_t len = knownPrimes.size();
    for(size_t i = 0; i < len; i++)
    {
        if(!(number % knownPrimes[i]))
        {
            //dividing with a prime gets a already factorized number
            knownFactorizations.push_back(knownFactorizations[number / knownPrimes[i]]);
            knownFactorizations[number][i]++;
            return;
        }
    }

    //if this failed, number is a newly found prime
    //because a) it has no known prime factors, so it must have others
    //and b) if it is not a prime itself, then it's factors should've been
    //found already (because they are smaller than the number itself)

    knownPrimes.push_back(number);

    len = knownFactorizations.size();
    for(size_t s = 0; s < len; s++)
    {
        knownFactorizations[s].push_back(0);
    }

    knownFactorizations.push_back(knownFactorizations[0]);
    knownFactorizations[number][knownPrimes.size() - 1]++;
}

uint64_t calculateDivisorCountOfN(uint64_t number)
{
    //factors for number must be known
    uint64_t res = 1;
    size_t len = knownFactorizations[number].size();
    for(size_t s = 0; s < len; s++)
    {
        if(knownFactorizations[number][s])
        {
            res *= (knownFactorizations[number][s] + 1);
        }
    }
    return res;
}

uint64_t calculateDivisorCountOfTN(uint64_t number)
{
    //factors for number and number+1 must be known
    uint64_t res = 1;
    size_t len = knownFactorizations[number].size();
    vector<uint32_t> tmp(len, 0);
    size_t s;
    for(s = 0; s < len; s++)
    {
        tmp[s] = knownFactorizations[number][s]
            + knownFactorizations[number+1][s];
    }
    //remove /2
    tmp[0]--;
    for(s = 0; s < len; s++)
    {
        if(tmp[s])
        {
            res *= (tmp[s] + 1);
        }
    }
    return res;
}

int main()
{
    init();
    uint64_t number = knownFactorizations.size() - 2;
    uint64_t DTn = 0;

    while(DTn <= limit)
    {
        number++;
        addAnotherFactorization();
        DTn = calculateDivisorCountOfTN(number);
    }

    uint64_t tn;
    if(number % 2) tn = ((number+1)/2)*number;
    else tn = (number/2)*(number+1);
    cout << "the " << number << "th triangle number is "
        << tn << " and has " << DTn << " divisors" << endl;
    return 0;
}

About your general question about speed:

1) Algorithms.

How to know them? For (relatively) simple problems, either reading a book/Wikipedia/etc. or figuring it out if you can. For harder stuff, learning more basic things and gaining experience is necessary before it's even possible to understand them, eg. studying CS and/or maths ... number theory helps a lot for your Euler problem. (It will help less to understand how a MP3 file is compressed ... there are many areas, it's not possible to know everything.).

2a) Automated compiler optimizations of frequently used code parts / patterns

2b) Manual timing what program parts are the slowest, and (when not replacing it with another algorithm) changing it in a way that eg. requires less data send to slow devices (HDD, hetwork...), less RAM memory access, less CPU cycles, works better together with OS scheduler and memory management strategies, uses the CPU pipeline/caches better etc.etc. ... this is both education and experience (and a big topic).

And because long variables have a limited size, sometimes it is necessary to use custom types that use eg. a byte array to store a single digit in each byte. That way, it's possible to use the whole RAM for a single number if you want to, but the downside is you/someone has to reimplement stuff like addition and so on for this kind of number storage. (Of course, libs for that exist already, without writing everything from scratch).

Btw., pow is a floating point function and may get you inaccurate results. It's not appropriate to use it in this case.


问:
Typescript definition files and extending external types
I'm trying to extend one of my own types from an external type.

Since I don't really know what I'm doing I am putting these in the global.d.ts file.

Previous to doing this I have been importing types into every typescript file in my project which seems wrong and messy (30 import lines on the top of every file).

global.d.ts file works when I just have my code in it

```<code>// successfully can use this anywhere
interface IPerson {
   name: string
}
</code>```

Where my understanding stops is what if I have a type that needs to extend one that's external.

(For example I'm going to try to extend the Redux action type).

```<code>/// <reference path="../node_modules/redux/index.d.ts" />

interface IPerson {
  name: string
}

// even with the reference typescript 'cannot find name Action'
interface PersonAction extends Action {
   person?: IPerson
}
</code>```

I can successfully get typescript to stop complaining that it can't find 'name Action' if I change the file to this

```<code>import * as Redux from 'redux';

interface IPerson {
  name: string
}

interface PersonAction extends Redux.Action {
  person?: IPerson
}
</code>```

Except now every file that uses IPerson can no longer find it.  I don't understand why.  Anytime I add an import to a declaration file it breaks everything else, but fixes the declaration file.

What am I doing wrong here?  I'm looking for a place I can put all my types, if there's a better way to get typescript to recognize my types I'm open to other options.

答:
I think you need to export the interface from your module:

```<code>import * as Redux from 'redux';

export interface IPerson {
  name: string
}

export interface PersonAction extends Redux.Action {
  person?: IPerson
}
</code>```

and then import the same at the place of usage:

```<code>import {IPerson, PersonAction} from 'your-module'
</code>```

P.S. Though it is not a problem, you might want to loose the 'I' from the name of interfaces.

Body:
I'm trying to extend one of my own types from an external type.

Since I don't really know what I'm doing I am putting these in the global.d.ts file.

Previous to doing this I have been importing types into every typescript file in my project which seems wrong and messy (30 import lines on the top of every file).

global.d.ts file works when I just have my code in it

// successfully can use this anywhere
interface IPerson {
   name: string
}

Where my understanding stops is what if I have a type that needs to extend one that's external.

(For example I'm going to try to extend the Redux action type).

/// <reference path="../node_modules/redux/index.d.ts" />

interface IPerson {
  name: string
}

// even with the reference typescript 'cannot find name Action'
interface PersonAction extends Action {
   person?: IPerson
}

I can successfully get typescript to stop complaining that it can't find 'name Action' if I change the file to this

import * as Redux from 'redux';

interface IPerson {
  name: string
}

interface PersonAction extends Redux.Action {
  person?: IPerson
}

Except now every file that uses IPerson can no longer find it.  I don't understand why.  Anytime I add an import to a declaration file it breaks everything else, but fixes the declaration file.

What am I doing wrong here?  I'm looking for a place I can put all my types, if there's a better way to get typescript to recognize my types I'm open to other options.

Body:
I think you need to export the interface from your module:

import * as Redux from 'redux';

export interface IPerson {
  name: string
}

export interface PersonAction extends Redux.Action {
  person?: IPerson
}

and then import the same at the place of usage:

import {IPerson, PersonAction} from 'your-module'

P.S. Though it is not a problem, you might want to loose the 'I' from the name of interfaces.


问:
Asynctask parallel execution
At application launch time I am making network call (resttemplate Get call) to fetch data.

Scenario is something like this,

1)Parent call which returns list of tokens(Id's)

2)Once I got list of tokens(Id's),I iterate through it make network call for   each token(Id) to get Data.

What I have done so for:

1)I have used Intent service to make parent network call to get list tokens(ID's).

2)Once I got list token(Id's) I started my AsyncTask executeOnExecutor,Passing list of tokens(ID's) to asynctask through constructor and starting AsyncTask executor.
Something like this,

```<code>MyAsyncExecutorTask executorTask = new MyAsyncExecutorTask(List<Integer> of tokens);
executorTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,(Void[]) null);
</code>```

And In MyAsyncExecutorTask this is what I am doing.

```<code> protected Void doInBackground(Void...params) {

    //Settimg max priority
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);

    for (int i = 0; i < scheduleList.size(); i++) {
       ScheduleImpl scheduleImpl = new ScheduleImpl();
        //Making network call to get data using token
        scheduleImpl.getData(scheduleList(i));
    }

 }
</code>```

Its working as it should be.

My doubts or Questions are:

1)Am I using Async executeOnExecuter() in right way(I want to make parallel  network calls).I don't see any huge performance improvement after switching from AsyncTask execute() to Async executeOnExecuter().

2)How to check how many number worker threads running.

答:
1)Am I using Async executeOnExecuter() in right way(I want to make parallel network calls).I don't see any huge performance improvement after switching from AsyncTask execute() to Async executeOnExecuter().

From Android Documentation

execute:

Executes the task with the specified parameters. The task returns itself (this) so that the caller can keep a reference to it.

Note: this function schedules the task on a queue for a single background thread or pool of threads depending on the platform version. When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting HONEYCOMB, tasks are back to being executed on a single thread to avoid common application errors caused by parallel execution

executeOnExecuter

Executes the task with the specified parameters. The task returns itself (this) so that the caller can keep a reference to it.

This method is typically used with THREAD_POOL_EXECUTOR to allow multiple tasks to run in parallel on a pool of threads managed by AsyncTask, however you can also use your own Executor for custom behavior.

Warning: Allowing multiple tasks to run in parallel from a thread pool is generally not what one wants, because the order of their operation is not defined. For example, if these tasks are used to modify any state in common (such as writing a file due to a button click), there are no guarantees on the order of the modifications. Without careful work it is possible in rare cases for the newer version of the data to be over-written by an older one, leading to obscure data loss and stability issues. Such changes are best executed in serial; to guarantee such work is serialized regardless of platform version you can use this function with SERIAL_EXECUTOR.

The question isn't about the performance improvement necessarily. When you run as executeOnExecuter, there is no guarantee that the calls will return in the order you made them. An execute method will schedule the task in a queue for a single background thread.

2)How to check how many number worker threads running.

You have the ability to define your own work queue, so if the question is how many threads can you run, then refer to this post Android AsyncTask threads limits?

I'm not sure if there is an easy way to check the count of current running. If there is I'm sure someone will be comment on that. But you can keep references to each task and check its status.

Title: Asynctask parallel execution

Body:
At application launch time I am making network call (resttemplate Get call) to fetch data.

Scenario is something like this,

1)Parent call which returns list of tokens(Id's)

2)Once I got list of tokens(Id's),I iterate through it make network call for   each token(Id) to get Data.

What I have done so for:

1)I have used Intent service to make parent network call to get list tokens(ID's).

2)Once I got list token(Id's) I started my AsyncTask executeOnExecutor,Passing list of tokens(ID's) to asynctask through constructor and starting AsyncTask executor.
Something like this,

MyAsyncExecutorTask executorTask = new MyAsyncExecutorTask(List<Integer> of tokens);
executorTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,(Void[]) null);

And In MyAsyncExecutorTask this is what I am doing.

 protected Void doInBackground(Void...params) {

    //Settimg max priority
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);

    for (int i = 0; i < scheduleList.size(); i++) {
       ScheduleImpl scheduleImpl = new ScheduleImpl();
        //Making network call to get data using token
        scheduleImpl.getData(scheduleList(i));
    }

 }

Its working as it should be.

My doubts or Questions are:

1)Am I using Async executeOnExecuter() in right way(I want to make parallel  network calls).I don't see any huge performance improvement after switching from AsyncTask execute() to Async executeOnExecuter().

2)How to check how many number worker threads running.


问:
Visual Studio 2015 or 2017 shows IntelliSense errors but solution compiles
We are currently evaluating the new Visual Studio 2015 and encountered a strange problem with IntelliSense. When I compiled our main solution with the new studio the build succeeds, but nevertheless 6 errors are shown.

I discovered that it's not a real error, but only an intellisense error. The code is definitely correct and everything compiled successfully. The code however is marked red and errors show up in the error list.

All 6 errors have the same origin. It's a simple constructor call. Strange enough, but there are also some occurrences of the exact same constructor without any errors.

The error message:

```<code>Code: CS1729
Message: '<the class>' does not contain a constructor that takes that many arguments.
Project: <the project name>
File: <the path to the file>
</code>```

The new studio was installed on a freshly installed Windows 7 without any legacy software (no VS13).

I've already tried to clear the caches, deleted the suo file, deleted bin and obj directories, cleaned and rebuilt the solution etc. But nothing worked.

Can anyone explain that behavior to me?

答:
Ran into similar issue in Visual Studio 2017 ASP.Net Core Project. Following steps did the trick for me

Perform Clean Solution

Close VS

Delete .suo file & Delete bin/obj directories

Reopen VS

ContentLicense: CC BY-SA 4.0

Body:
We are currently evaluating the new Visual Studio 2015 and encountered a strange problem with IntelliSense. When I compiled our main solution with the new studio the build succeeds, but nevertheless 6 errors are shown.

I discovered that it's not a real error, but only an intellisense error. The code is definitely correct and everything compiled successfully. The code however is marked red and errors show up in the error list.

All 6 errors have the same origin. It's a simple constructor call. Strange enough, but there are also some occurrences of the exact same constructor without any errors.

The error message:

Code: CS1729
Message: '<the class>' does not contain a constructor that takes that many arguments.
Project: <the project name>
File: <the path to the file>

The new studio was installed on a freshly installed Windows 7 without any legacy software (no VS13).

I've already tried to clear the caches, deleted the suo file, deleted bin and obj directories, cleaned and rebuilt the solution etc. But nothing worked.

Can anyone explain that behavior to me?


问:
Make a camel-case function using a for loop in Javascript
I am brand new to Javascript and trying to figure out how to camel-case any string by using a for loop. This is what I have so far.

```<code>function camelCase(str) {
 var splitStr = "";
 var result = "";

 splitStr = str.split(" ");
 for(var i = 0; i < splitStr.length; i++){
 result += splitStr[i][0].toUpperCase() +
   splitStr[i].slice(1);
  }
  return result;
 }

console.log(camelCase("hello there people"));
</code>```

it returns "HelloTherePeople" - How do you I make the very first index of splitStr (splitStr[0][0]) be excluded from toUpperCase, but still included in the beginning of the string?

答:
change return like this:</p>

```<code>return result[0].toLowerCase()+result.substr(1);
</code>```

Body:
I am brand new to Javascript and trying to figure out how to camel-case any string by using a for loop. This is what I have so far.

function camelCase(str) {
 var splitStr = "";
 var result = "";

 splitStr = str.split(" ");
 for(var i = 0; i < splitStr.length; i++){
 result += splitStr[i][0].toUpperCase() +
   splitStr[i].slice(1);
  }
  return result;
 }

console.log(camelCase("hello there people"));

it returns "HelloTherePeople" - How do you I make the very first index of splitStr (splitStr[0][0]) be excluded from toUpperCase, but still included in the beginning of the string?

Body:
change return like this:

return result[0].toLowerCase()+result.substr(1);


问:
How to subclass DefaultTableModel and change its dataVector
I want to extend the DefaultTableModel and change its dataVector.
I want to make the dataVector to show only specific fields of DataHolder in the column:

```<code> public class MyTableModel extends DefaultTableModel {

    /**
     * The data vector
     */
    private Vector<DataHolder>   dataVector_;

    //overridden method to add row in the table model
    public void addRow(DataHolder rowData) {
        insertRow(getRowCount(), rowData);
    }

    public void insertRow(int row, DataHolder rowData) {
            dataVector_.insertElementAt(rowData, row);
            fireTableRowsInserted(row, row);
        }

    ...} //end of MyTableModel

   class DataHolder{
     private int age;
     private int year;
     private int month;
     private int day;
    }
</code>```

How can i display specific DataHolder fields in my jtable? My table has 3 columns for month, day, and year.

答: Do you want to change this in the Table Model or the Table View? If you are using a JTable for the view, might I suggest working with the TableColumnModel which is accessible via the JTable.</p>

Body:
I want to extend the DefaultTableModel and change its dataVector.
I want to make the dataVector to show only specific fields of DataHolder in the column:

 public class MyTableModel extends DefaultTableModel {

    /**
     * The data vector
     */
    private Vector<DataHolder>   dataVector_;

    //overridden method to add row in the table model
    public void addRow(DataHolder rowData) {
        insertRow(getRowCount(), rowData);
    }

    public void insertRow(int row, DataHolder rowData) {
            dataVector_.insertElementAt(rowData, row);
            fireTableRowsInserted(row, row);
        }

    ...} //end of MyTableModel

   class DataHolder{
     private int age;
     private int year;
     private int month;
     private int day;
    }

How can i display specific DataHolder fields in my jtable? My table has 3 columns for month, day, and year.


问:
Longest Increasing Cyclic Subsequence
I have a code for finding the longest increasing subsequence, but I'd like to extend this to allow wrap arounds. For example for the sequence (4,5,6,1,2,3) the longest increasing cyclic subsequence is (1,2,3,4,5,6) since once we reach 3, we can go back to the beginning of the sequence (we can only do this once.) Is anyone able to help me?

Here is the code:

```<code>def longest_increasing_subsequence(X):

N = len(X)
P = [0] * N
M = [0] * (N+1)
L = 0
for i in range(N):
   lo = 1
   hi = L
   while lo <= hi:
       mid = (lo+hi)//2
       if (X[M[mid]] < X[i]):
           lo = mid+1
       else:
           hi = mid-1

   newL = lo
   P[i] = M[newL-1]
   M[newL] = i

   if (newL > L):
       L = newL

S = []
k = M[L]
for i in range(L-1, -1, -1):
    S.append(X[k])
    k = P[k]
return len(S[::-1])
</code>```

答: Concatenate the sequence to the end of itself, then run your algorithm on it. </p>

Title: Longest Increasing Cyclic Subsequence

Body:
I have a code for finding the longest increasing subsequence, but I'd like to extend this to allow wrap arounds. For example for the sequence (4,5,6,1,2,3) the longest increasing cyclic subsequence is (1,2,3,4,5,6) since once we reach 3, we can go back to the beginning of the sequence (we can only do this once.) Is anyone able to help me?

Here is the code:

def longest_increasing_subsequence(X):

N = len(X)
P = [0] * N
M = [0] * (N+1)
L = 0
for i in range(N):
   lo = 1
   hi = L
   while lo <= hi:
       mid = (lo+hi)//2
       if (X[M[mid]] < X[i]):
           lo = mid+1
       else:
           hi = mid-1

   newL = lo
   P[i] = M[newL-1]
   M[newL] = i

   if (newL > L):
       L = newL

S = []
k = M[L]
for i in range(L-1, -1, -1):
    S.append(X[k])
    k = P[k]
return len(S[::-1])


问:
method invocation may produce nullpointerexception
I'm trying to implement Graph using adjacency list, but when I try to add new pair into the list it gaves me an NullPointerException. Is there anyone know why it would happen and how to fix it?

Thanks in advance.

My Graph.java is like:

```<code>import javafx.util.Pair;
import java.util.*;

public class Graph{
    private final HashMap<String, List<Pair<String, Integer>>> adj;

    public Graph(String filePath) {
        adj = new HashMap<>();
        addEdge("a", "b", 30);
    }

    public void addEdge(String start, String end, int weight) {
        adj.get(start).add(new Pair<>(end, weight));
    }
}
</code>```

My Main.java is like:

```<code>public class Main {
    public static void main(String[] args) {
        Graph gr;

        try {
            gr = new Graph("test.txt");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
</code>```

答:
Just putting new Graph() in your second constructor doesn't initialize it. You just declare a default graph and don't store it anywhere. Now if you use the special function this, you'll get what you want.

```<code>public Graph(String filePath) {
    this();
    ...
</code>```

Body:
I'm trying to implement Graph using adjacency list, but when I try to add new pair into the list it gaves me an NullPointerException. Is there anyone know why it would happen and how to fix it?

Thanks in advance.

My Graph.java is like:

import javafx.util.Pair;
import java.util.*;

public class Graph{
    private final HashMap<String, List<Pair<String, Integer>>> adj;

    public Graph(String filePath) {
        adj = new HashMap<>();
        addEdge("a", "b", 30);
    }

    public void addEdge(String start, String end, int weight) {
        adj.get(start).add(new Pair<>(end, weight));
    }
}

My Main.java is like:

public class Main {
    public static void main(String[] args) {
        Graph gr;

        try {
            gr = new Graph("test.txt");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

Body:
Just putting new Graph() in your second constructor doesn't initialize it. You just declare a default graph and don't store it anywhere. Now if you use the special function this, you'll get what you want.

public Graph(String filePath) {
    this();
    ...


问:
How do you test code without uploading to the web server?
(This is a high level software development question)

I'm running a web app.  In the past, to test new features, I have uploaded under a subdirectory such as test/.  This generally broke all the URLs, so I'd have to redo the URLs in the test code. Then I'd have to rename all the URLs when I pushed it to the main site.  I'm sure there's a better way but don't know what people usually do.

Do you install a web server on your laptop?  I could always buy a cheap computer and run it as a test web server, I suppose.

Eventually I'd like to have a version control system with a friend also coding, so maybe we'd both need to install Apache and MySQL on our laptops?  That way we don't interfere with each other when testing new code.

答:
You should have a development version of the app running locally on your work computer.  Depending on your web framework, this can be easy or hard.  For example, grails has tools that allow you to easily run locally.  But no matter, you should definitely do this.  To much can go wrong pushing things to servers, especially servers that are used to production.  Invest the time and get set up properly.

And, as the other answers point out, unit test.


问:
How to parse a JSON Object within two JSON Array's?
I'm trying to get the item name, brand name and total carbohydrate value out of the following JSON Array but am having problems with accessing the the individual values within the "fields" section. Anyone with any pointers to retrieve this info?

```<code>{
</code>```

"total_hits": 49127,
  "max_score": 11.919899,
  "hits": [
    {

```<code>  "_index": "f762ef22-e660-434f-9071-a10ea6691c27",
  "_type": "item",
  "_id": "513fceb375b8dbbc21000022",
  "_score": 11.919899,
  "fields": {
    "item_id": "513fceb375b8dbbc21000022",
    "item_name": "Cheese, cheddar - 1 cup, diced",
    "brand_name": "USDA",
    "nf_total_carbohydrate": 4.08,
    "nf_serving_size_qty": 1,
    "nf_serving_size_unit": "serving"
  }
},
{
  "_index": "f762ef22-e660-434f-9071-a10ea6691c27",
  "_type": "item",
  "_id": "513fceb375b8dbbc21000021",
  "_score": 11.788424,
  "fields": {
    "item_id": "513fceb375b8dbbc21000021",
    "item_name": "Cheese, cheddar - 1 cup, melted",
    "brand_name": "USDA",
    "nf_total_carbohydrate": 7.54,
    "nf_serving_size_qty": 1,
    "nf_serving_size_unit": "serving"
  }
</code>```

/* sorry for some reason i can't get the formatting right but the "hits" is a parent of the whole highlighted code section*/

答:
Here is the fully working code. Try this:

```<code>// Your JSON string
String jsonStr = "{\n" +
            "  \"total_hits\": 49127,\n" +
            "  \"max_score\": 11.919899,\n" +
            "  \"hits\": [\n" +
            "    {\n" +
            "      \"_index\": \"f762ef22-e660-434f-9071-a10ea6691c27\",\n" +
            "      \"_type\": \"item\",\n" +
            "      \"_id\": \"513fceb375b8dbbc21000022\",\n" +
            "      \"_score\": 11.919899,\n" +
            "      \"fields\": {\n" +
            "        \"item_id\": \"513fceb375b8dbbc21000022\",\n" +
            "        \"item_name\": \"Cheese, cheddar - 1 cup, diced\",\n" +
            "        \"brand_name\": \"USDA\",\n" +
            "        \"nf_total_carbohydrate\": 4.08,\n" +
            "        \"nf_serving_size_qty\": 1,\n" +
            "        \"nf_serving_size_unit\": \"serving\"\n" +
            "      }\n" +
            "    },\n" +
            "    {\n" +
            "      \"_index\": \"f762ef22-e660-434f-9071-a10ea6691c27\",\n" +
            "      \"_type\": \"item\",\n" +
            "      \"_id\": \"513fceb375b8dbbc21000021\",\n" +
            "      \"_score\": 11.788424,\n" +
            "      \"fields\": {\n" +
            "        \"item_id\": \"513fceb375b8dbbc21000021\",\n" +
            "        \"item_name\": \"Cheese, cheddar - 1 cup, melted\",\n" +
            "        \"brand_name\": \"USDA\",\n" +
            "        \"nf_total_carbohydrate\": 7.54,\n" +
            "        \"nf_serving_size_qty\": 1,\n" +
            "        \"nf_serving_size_unit\": \"serving\"\n" +
            "      }\n" +
            "    }\n" +
            "  ]\n" +
            "}";

    try {
        JSONObject jsonObject = new JSONObject(jsonStr);
        JSONArray jsonArrayHits = jsonObject.getJSONArray("hits");

        // Get all jsonObject from jsonArray
        for (int i = 0; i < jsonArrayHits.length(); i++)
        {
            JSONObject jsonObjectFields = jsonArrayHits.getJSONObject(i).getJSONObject("fields");

            String itemName = null, brandName = null;
            double totalCarbohydrate = 0.0;

            // Item name
            if (jsonObjectFields.has("item_name") && !jsonObjectFields.isNull("item_name")) {
                itemName = jsonObjectFields.getString("item_name");
            }

            // Brand name
            if (jsonObjectFields.has("brand_name") && !jsonObjectFields.isNull("brand_name")) {
                brandName = jsonObjectFields.getString("brand_name");
            }

            // Total carbohydrate
            if (jsonObjectFields.has("nf_total_carbohydrate") && !jsonObjectFields.isNull("nf_total_carbohydrate")) {
                totalCarbohydrate = jsonObjectFields.getDouble("nf_total_carbohydrate");
            }

            Log.d("SUCCESS", "JSON Object: " + "\nItem Name: " + itemName
                    + "\nBrand Name: " + brandName
                    + "\nTotal carbohydrate: " + totalCarbohydrate);
        }
    } catch (JSONException e) {
        Log.e("FAILED", "Json parsing error: " + e.getMessage());
    }
</code>```

OUTPUT LOG:

```<code>D/SUCCESS: JSON Object:
           Item Name: Cheese, cheddar - 1 cup, diced
           Brand Name: USDA
           Total carbohydrate: 4.08

D/SUCCESS: JSON Object:
           Item Name: Cheese, cheddar - 1 cup, melted
           Brand Name: USDA
           Total carbohydrate: 7.54
</code>```

Hope this will help~

Body:
I'm trying to get the item name, brand name and total carbohydrate value out of the following JSON Array but am having problems with accessing the the individual values within the "fields" section. Anyone with any pointers to retrieve this info?

{

"total_hits": 49127,
  "max_score": 11.919899,
  "hits": [
    {

  "_index": "f762ef22-e660-434f-9071-a10ea6691c27",
  "_type": "item",
  "_id": "513fceb375b8dbbc21000022",
  "_score": 11.919899,
  "fields": {
    "item_id": "513fceb375b8dbbc21000022",
    "item_name": "Cheese, cheddar - 1 cup, diced",
    "brand_name": "USDA",
    "nf_total_carbohydrate": 4.08,
    "nf_serving_size_qty": 1,
    "nf_serving_size_unit": "serving"
  }
},
{
  "_index": "f762ef22-e660-434f-9071-a10ea6691c27",
  "_type": "item",
  "_id": "513fceb375b8dbbc21000021",
  "_score": 11.788424,
  "fields": {
    "item_id": "513fceb375b8dbbc21000021",
    "item_name": "Cheese, cheddar - 1 cup, melted",
    "brand_name": "USDA",
    "nf_total_carbohydrate": 7.54,
    "nf_serving_size_qty": 1,
    "nf_serving_size_unit": "serving"
  }

/* sorry for some reason i can't get the formatting right but the "hits" is a parent of the whole highlighted code section*/

Body:
Here is the fully working code. Try this:

// Your JSON string
String jsonStr = "{\n" +
            "  \"total_hits\": 49127,\n" +
            "  \"max_score\": 11.919899,\n" +
            "  \"hits\": [\n" +
            "    {\n" +
            "      \"_index\": \"f762ef22-e660-434f-9071-a10ea6691c27\",\n" +
            "      \"_type\": \"item\",\n" +
            "      \"_id\": \"513fceb375b8dbbc21000022\",\n" +
            "      \"_score\": 11.919899,\n" +
            "      \"fields\": {\n" +
            "        \"item_id\": \"513fceb375b8dbbc21000022\",\n" +
            "        \"item_name\": \"Cheese, cheddar - 1 cup, diced\",\n" +
            "        \"brand_name\": \"USDA\",\n" +
            "        \"nf_total_carbohydrate\": 4.08,\n" +
            "        \"nf_serving_size_qty\": 1,\n" +
            "        \"nf_serving_size_unit\": \"serving\"\n" +
            "      }\n" +
            "    },\n" +
            "    {\n" +
            "      \"_index\": \"f762ef22-e660-434f-9071-a10ea6691c27\",\n" +
            "      \"_type\": \"item\",\n" +
            "      \"_id\": \"513fceb375b8dbbc21000021\",\n" +
            "      \"_score\": 11.788424,\n" +
            "      \"fields\": {\n" +
            "        \"item_id\": \"513fceb375b8dbbc21000021\",\n" +
            "        \"item_name\": \"Cheese, cheddar - 1 cup, melted\",\n" +
            "        \"brand_name\": \"USDA\",\n" +
            "        \"nf_total_carbohydrate\": 7.54,\n" +
            "        \"nf_serving_size_qty\": 1,\n" +
            "        \"nf_serving_size_unit\": \"serving\"\n" +
            "      }\n" +
            "    }\n" +
            "  ]\n" +
            "}";

    try {
        JSONObject jsonObject = new JSONObject(jsonStr);
        JSONArray jsonArrayHits = jsonObject.getJSONArray("hits");

        // Get all jsonObject from jsonArray
        for (int i = 0; i < jsonArrayHits.length(); i++)
        {
            JSONObject jsonObjectFields = jsonArrayHits.getJSONObject(i).getJSONObject("fields");

            String itemName = null, brandName = null;
            double totalCarbohydrate = 0.0;

            // Item name
            if (jsonObjectFields.has("item_name") && !jsonObjectFields.isNull("item_name")) {
                itemName = jsonObjectFields.getString("item_name");
            }

            // Brand name
            if (jsonObjectFields.has("brand_name") && !jsonObjectFields.isNull("brand_name")) {
                brandName = jsonObjectFields.getString("brand_name");
            }

            // Total carbohydrate
            if (jsonObjectFields.has("nf_total_carbohydrate") && !jsonObjectFields.isNull("nf_total_carbohydrate")) {
                totalCarbohydrate = jsonObjectFields.getDouble("nf_total_carbohydrate");
            }

            Log.d("SUCCESS", "JSON Object: " + "\nItem Name: " + itemName
                    + "\nBrand Name: " + brandName
                    + "\nTotal carbohydrate: " + totalCarbohydrate);
        }
    } catch (JSONException e) {
        Log.e("FAILED", "Json parsing error: " + e.getMessage());
    }

OUTPUT LOG:

D/SUCCESS: JSON Object:
           Item Name: Cheese, cheddar - 1 cup, diced
           Brand Name: USDA
           Total carbohydrate: 4.08

D/SUCCESS: JSON Object:
           Item Name: Cheese, cheddar - 1 cup, melted
           Brand Name: USDA
           Total carbohydrate: 7.54

Hope this will help~


问:
STM32F4 USB CDC, can't use Data with pyserial
I have a problem with the combination of STM32F4 USB CDC and pyserial. If my Code in the STM32 wants to work with the received Data in the main.c I can't open the Port. If not, I can send and receive with no problem, the information is stored successfully in the UserRxBufferFS.

I get following error:

```<code>>>> ser.open() Traceback (most recent call last):   File "<stdin>", line 1, in <module>   File "C:\Program Files\Anaconda2\lib\site-packages\serial\serialwin32.py", line 78, in open
    self._reconfigure_port()   File "C:\Program Files\Anaconda2\lib\site-packages\serial\serialwin32.py", line 222, in
_reconfigure_port
    'Original message: {!r}'.format(ctypes.WinError())) serial.serialutil.SerialException: Cannot configure port, something went wrong. Original message: WindowsError(87, 'Falscher Parameter.')
</code>```

I tried to store the Data in a global variable that I declared in the usbd_cdc_if.h:

usbd_cdc_if.h: extern int my_buf[8];

usbd_cdc_if.c: my_buf[0]=UserRxBufferFS[0];

--> error

Tried to call a function in the callback that brings the information to my main.c --> error

Tried a global pointer that points to the buffer --> error

All of this is working when I use a windows terminal.
But I need to use pyserial. When I don't work with the data I can connect, send and receive everything with no problem.

Has anyone an idea of the problem and a way to solve it?

答:
WindowsError(87, 'Falscher Parameter.')

I suppose you know that means 'wrong parameter'. Did you send an invalid parameter to the routine?

Note that, very probably, UserRxBufferFS will be defined as something like an unsigned char (1 byte long) because the communication is byte by byte. You are defining your buffer as int, which probably is either 2 or 4 bytes long.

Maybe you as passing int to the transmission or initializing routine, where that routine expects bytes? (or unsigned chars)

```<code>my_buf[0]=UserRxBufferFS[0];
</code>```

transfers the first element from UserRxBufferFS to my_buf, which probably copies an unsigned char into an int, which can also give unexpected results.

Body:
I have a problem with the combination of STM32F4 USB CDC and pyserial. If my Code in the STM32 wants to work with the received Data in the main.c I can't open the Port. If not, I can send and receive with no problem, the information is stored successfully in the UserRxBufferFS.

I get following error:

>>> ser.open() Traceback (most recent call last):   File "<stdin>", line 1, in <module>   File "C:\Program Files\Anaconda2\lib\site-packages\serial\serialwin32.py", line 78, in open
    self._reconfigure_port()   File "C:\Program Files\Anaconda2\lib\site-packages\serial\serialwin32.py", line 222, in
_reconfigure_port
    'Original message: {!r}'.format(ctypes.WinError())) serial.serialutil.SerialException: Cannot configure port, something went wrong. Original message: WindowsError(87, 'Falscher Parameter.')

I tried to store the Data in a global variable that I declared in the usbd_cdc_if.h:

usbd_cdc_if.h: extern int my_buf[8];

usbd_cdc_if.c: my_buf[0]=UserRxBufferFS[0];

--> error

Tried to call a function in the callback that brings the information to my main.c --> error

Tried a global pointer that points to the buffer --> error

All of this is working when I use a windows terminal.
But I need to use pyserial. When I don't work with the data I can connect, send and receive everything with no problem.

Has anyone an idea of the problem and a way to solve it?

Body:
WindowsError(87, 'Falscher Parameter.')

I suppose you know that means 'wrong parameter'. Did you send an invalid parameter to the routine?

Note that, very probably, UserRxBufferFS will be defined as something like an unsigned char (1 byte long) because the communication is byte by byte. You are defining your buffer as int, which probably is either 2 or 4 bytes long.

Maybe you as passing int to the transmission or initializing routine, where that routine expects bytes? (or unsigned chars)

my_buf[0]=UserRxBufferFS[0];

transfers the first element from UserRxBufferFS to my_buf, which probably copies an unsigned char into an int, which can also give unexpected results.


问:
Pandas: How can I convert 'timestamp' values in my dataframe column from object/str to timestamp?
My timestamp looks like below in the dataframe of my column but it is in 'object'. I want to convert this into 'timestamp'. How can I convert all values such in my dataframe column into timestamp?

```<code>0    01/Jul/1995:00:00:01
1    01/Jul/1995:00:00:06
2    01/Jul/1995:00:00:09
3    01/Jul/1995:00:00:09
4    01/Jul/1995:00:00:09
Name: timestamp, dtype: object
</code>```

I tried below code referring this stackoverflow post but it gives me error:

```<code>pd.to_datetime(df['timestamp'], format='%d/%b/%Y:%H:%M:%S.%f')
</code>```

Below is the error:

```<code>ValueError: time data '01/Jul/1995:00:00:01' does not match format '%d/%b/%Y:%H:%M:%S.%f' (match)
</code>```

答:
Try the follwing format:</p>

```<code>ourdates = pd.to_datetime(df['timestamp'], format='%d/%b/%Y:%H:%M:%S')
</code>```

Body:
My timestamp looks like below in the dataframe of my column but it is in 'object'. I want to convert this into 'timestamp'. How can I convert all values such in my dataframe column into timestamp?

0    01/Jul/1995:00:00:01
1    01/Jul/1995:00:00:06
2    01/Jul/1995:00:00:09
3    01/Jul/1995:00:00:09
4    01/Jul/1995:00:00:09
Name: timestamp, dtype: object

I tried below code referring this stackoverflow post but it gives me error:

pd.to_datetime(df['timestamp'], format='%d/%b/%Y:%H:%M:%S.%f')

Below is the error:

ValueError: time data '01/Jul/1995:00:00:01' does not match format '%d/%b/%Y:%H:%M:%S.%f' (match)

Body:
Try the follwing format:

ourdates = pd.to_datetime(df['timestamp'], format='%d/%b/%Y:%H:%M:%S')


问:
Tools for a lone developer setup?
I'm a lone developer who would like to get some structure to my projects. My hardware setup is a laptop running windows XP and a desktop running Ubuntu that acts as a storage server.

I currently use Mercurial as my source control system with my working copy of the repository stored on my laptop and clone the repository to the Ubuntu machine every couple of days as a backup.

What other tools would you recommend for a lone developer to do things such as bug tracking, project planning, etc? I'm looking for something simple that either has to run on windows or as a web app on Apache.

答: Try Mylyn or Tasktop for accessing your bug tracker and managing your issues/tasks. If you've set up a compatible bug/issue tracker, you can access it on your desktop via Tasktop to streamline your workflow. If you haven't set up an issue tracker, you can use local tasks to track your work. </p>

OwnerDisplayName: Jared

Title: Tools for a lone developer setup?

LastEditorDisplayName: Peter Hilton

OwnerDisplayName: wesleycoelho