问:
MySQL Performance Degrades during Concurrent Stored Proc Execution
Machine Specs : macOS Sierra, Version 10.12.5, Memory 8 GB

MySQL Version:  MySQL Enterprise Server - Advanced Edition (Commercial)3
innodb_version : 5.7.18

Problem :  When same stored procedure is called concurrently by different sessions, the response time gets delayed a lot.

The below SQL is the one which takes 0.12s per execution. For simulating the issue, I am running the below SQL in a while loop which iterates for 30 times thereby taking an average of 3 seconds per Stored procedure execution.

However, when I run the same stored proc CONCURRENTLY from a different terminal/session, both the stored procs take nearly 50 seconds.

The tables are created in innodb and the buffer size and read/write io's are set with normal values.

Query

```<code> SELECT MIN(BEGIN_date) , MAX(END_date)
   FROM employee e, department d
  WHERE e.employee_ID = d.employee_ID
    AND d.Department_ID = 72641 ;
</code>```

Explain Extended Plan is below ( Indexes are perfectly used)

```<code>----+-------------+-------+------------+------+------------------+----------    --------+---------+-------------------------------+------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys    | key               | key_len | ref                           | rows | filtered | Extra       |
+----+-------------+-------+------------+------+------------------+------------------+---------+-------------------------------+------+----------+-------------+
|  1 | SIMPLE      | d     | NULL       | ref  | deptmnt_dept_idx | deptmnt_dept_idx | 4       | const                         |  808 |   100.00 | NULL        |
|  1 | SIMPLE      | e     | NULL       | ref  | Emp_Name_Dt _idx | Emp_Name_Dt _idx | 4       | radar_bridge_db.d.Employee_ID |  156 |   100.00 | Using index |
+----+-------------+-------+------------+------+------------------+------------------+---------+-------------------------------+------+----------+-------------+
</code>```

Stored Proc:

```<code>CREATE PROCEDURE `fetchEmployeeDetails`()
BEGIN

DECLARE l_StartDate DATE DEFAULT CURRENT_DATE()-INTERVAL 7 DAY;
DECLARE l_EndDate DATE DEFAULT CURRENT_DATE();

DECLARE I_Range INT DEFAULT 0;

WHILE I_Range < 30 DO

    SELECT MIN(BEGIN_date) , MAX(END_date)
      INTO l_StartDate,  l_EndDate  FROM employee e, department d
     WHERE e.employee_ID = d.employee_ID AND d.Department_ID = 72641 ;

    SET I_Range = I_Range + 1;

 END WHILE;

END;
</code>```

The same SP when called CONCURRENTLY from a different terminal/session, both the SPs take nearly 50 seconds.

The sample is run on both MySQL Community Version and also on Enterprise edition ( with thread pool ON) on the same Mac Machine, but the issue persists.
Please let me know if you have any ways to resolve this performance issue.

```<code>CREATE TABLE `employee` (
  `COMPANY_ID` int(11) NOT NULL,
  `COMPANY_NAME` varchar(255) CHARACTER SET utf8 NOT NULL,
  `EMPLOYEE_ID` int(11) NOT NULL,
  `BEGIN_DATE` timestamp NULL DEFAULT NULL,
  `END_DATE` timestamp NULL DEFAULT NULL,
  KEY `Emp_Name_Dt_idx` (`EMPLOYEE_ID`,`BEGIN_DATE`,`END_DATE`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

CREATE TABLE `department` (
  `Employee_ID` int(11) NOT NULL,
  `Department_ID` int(11) NOT NULL,
  KEY `deptmnt_dept_idx` (`Department_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
</code>```

答:
Please re-think the schema.

A table named employee should talk about one person.  What you have seems to have multiple rows if the person was employed multiple times.  Perhaps it should be called tenure, and be separate from employee.

department should be a department.  What you have is a many:many mapping between employees and departments.  But, can an employee belong to multiple departments?  If not, then it is a 1:many mapping, and the table is not needed.  Instead have department_id in the employee table.

And, you need a PRIMARY KEY on each table:

```<code>PRIMARY KEY(employee_id) -- on employee
PRIMARY KEY(employee_id, start_date, end_date) -- on tenure
PRIMARY KEY(department_id) -- on department
PRIMARY KEY(department_id, employee_id) -- on many:many mapping
INDEX(department_id) -- on employee, if 1:many
INDEX(employee_id, department_id) -- if many:many
</code>```

More discussion on many:many .

After all of that, we can continue the discussion of your timing anomaly, if it still exists.

Body:
Machine Specs : macOS Sierra, Version 10.12.5, Memory 8 GB

MySQL Version:  MySQL Enterprise Server - Advanced Edition (Commercial)3
innodb_version : 5.7.18

Problem :  When same stored procedure is called concurrently by different sessions, the response time gets delayed a lot.

The below SQL is the one which takes 0.12s per execution. For simulating the issue, I am running the below SQL in a while loop which iterates for 30 times thereby taking an average of 3 seconds per Stored procedure execution.

However, when I run the same stored proc CONCURRENTLY from a different terminal/session, both the stored procs take nearly 50 seconds.

The tables are created in innodb and the buffer size and read/write io's are set with normal values.

Query

 SELECT MIN(BEGIN_date) , MAX(END_date)
   FROM employee e, department d
  WHERE e.employee_ID = d.employee_ID
    AND d.Department_ID = 72641 ;

Explain Extended Plan is below ( Indexes are perfectly used)

----+-------------+-------+------------+------+------------------+----------    --------+---------+-------------------------------+------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys    | key               | key_len | ref                           | rows | filtered | Extra       |
+----+-------------+-------+------------+------+------------------+------------------+---------+-------------------------------+------+----------+-------------+
|  1 | SIMPLE      | d     | NULL       | ref  | deptmnt_dept_idx | deptmnt_dept_idx | 4       | const                         |  808 |   100.00 | NULL        |
|  1 | SIMPLE      | e     | NULL       | ref  | Emp_Name_Dt _idx | Emp_Name_Dt _idx | 4       | radar_bridge_db.d.Employee_ID |  156 |   100.00 | Using index |
+----+-------------+-------+------------+------+------------------+------------------+---------+-------------------------------+------+----------+-------------+

Stored Proc:

CREATE PROCEDURE `fetchEmployeeDetails`()
BEGIN

DECLARE l_StartDate DATE DEFAULT CURRENT_DATE()-INTERVAL 7 DAY;
DECLARE l_EndDate DATE DEFAULT CURRENT_DATE();

DECLARE I_Range INT DEFAULT 0;

WHILE I_Range < 30 DO

    SELECT MIN(BEGIN_date) , MAX(END_date)
      INTO l_StartDate,  l_EndDate  FROM employee e, department d
     WHERE e.employee_ID = d.employee_ID AND d.Department_ID = 72641 ;

    SET I_Range = I_Range + 1;

 END WHILE;

END;

The same SP when called CONCURRENTLY from a different terminal/session, both the SPs take nearly 50 seconds.

The sample is run on both MySQL Community Version and also on Enterprise edition ( with thread pool ON) on the same Mac Machine, but the issue persists.
Please let me know if you have any ways to resolve this performance issue.

CREATE TABLE `employee` (
  `COMPANY_ID` int(11) NOT NULL,
  `COMPANY_NAME` varchar(255) CHARACTER SET utf8 NOT NULL,
  `EMPLOYEE_ID` int(11) NOT NULL,
  `BEGIN_DATE` timestamp NULL DEFAULT NULL,
  `END_DATE` timestamp NULL DEFAULT NULL,
  KEY `Emp_Name_Dt_idx` (`EMPLOYEE_ID`,`BEGIN_DATE`,`END_DATE`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

CREATE TABLE `department` (
  `Employee_ID` int(11) NOT NULL,
  `Department_ID` int(11) NOT NULL,
  KEY `deptmnt_dept_idx` (`Department_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

Body:
Please re-think the schema.

A table named employee should talk about one person.  What you have seems to have multiple rows if the person was employed multiple times.  Perhaps it should be called tenure, and be separate from employee.

department should be a department.  What you have is a many:many mapping between employees and departments.  But, can an employee belong to multiple departments?  If not, then it is a 1:many mapping, and the table is not needed.  Instead have department_id in the employee table.

And, you need a PRIMARY KEY on each table:

PRIMARY KEY(employee_id) -- on employee
PRIMARY KEY(employee_id, start_date, end_date) -- on tenure
PRIMARY KEY(department_id) -- on department
PRIMARY KEY(department_id, employee_id) -- on many:many mapping
INDEX(department_id) -- on employee, if 1:many
INDEX(employee_id, department_id) -- if many:many

More discussion on many:many .

After all of that, we can continue the discussion of your timing anomaly, if it still exists.


来源: stackexchange

问:
Python3 Pandas - How to create all combinations of 4 columns and write them in rows in a CSV?
I have 4 CSV files with one column. Each column represents a part of a name (4 parts):

CSV 1:

```<code>first_name
michael
madonna
steve
albert
</code>```

CSV 2:

```<code>second_name
luke
han
kurt
</code>```

CSV 3:

```<code>first_last_name
jackson
jobs
skywalker
</code>```

CSV 4:

```<code>second_last_name
solo
cobain
einstein
</code>```

The end result I want is to get all the possible combinations between all the 4 columns (4 CSVs):

```<code>first_name,second_name,first_last_name,second_last_name
michael,luke,jackson,solo
michael,luke,jackson,cobain
michael,luke,jackson,einstein
michael,luke,jobs,solo
michael,luke,jobs,cobain
michael,luke,jobs,einstein
michael,luke,skywalker,solo
michael,luke,skywalker,cobain
michael,luke,skywalker,einstein
...
</code>```

With pandas I converted each CSV into a dataframe but I have no idea of how to combine all four. How can I achieve this?

答:
Use itertools.product for the heavy lifting.

```<code>import pandas as pd
from itertools import product

lists = [list(pd.read_csv('data{}.csv'.format(i), header=0).iloc[:,0]) for i in range(1,5)]
combined = list(','.join(items) for items in product(*lists))
pd.DataFrame(combined).to_csv('combined.csv', index=0)
</code>```

If you just want the list form, use combined. It looks like:

```<code>['michael,luke,jackson,solo',
 'michael,luke,jackson,cobain',
 'michael,luke,jackson,einstein',
 'michael,luke,jobs,solo',
 'michael,luke,jobs,cobain',
 'michael,luke,jobs,einstein',
 'michael,luke,skywalker,solo',
 'michael,luke,skywalker,cobain',
 'michael,luke,skywalker,einstein',
 ...
</code>```

Or the final line writes the combined values out to a CSV.

ContentLicense: CC BY-SA 3.0

Body:
I have 4 CSV files with one column. Each column represents a part of a name (4 parts):

CSV 1:

first_name
michael
madonna
steve
albert

CSV 2:

second_name
luke
han
kurt

CSV 3:

first_last_name
jackson
jobs
skywalker

CSV 4:

second_last_name
solo
cobain
einstein

The end result I want is to get all the possible combinations between all the 4 columns (4 CSVs):

first_name,second_name,first_last_name,second_last_name
michael,luke,jackson,solo
michael,luke,jackson,cobain
michael,luke,jackson,einstein
michael,luke,jobs,solo
michael,luke,jobs,cobain
michael,luke,jobs,einstein
michael,luke,skywalker,solo
michael,luke,skywalker,cobain
michael,luke,skywalker,einstein
...

With pandas I converted each CSV into a dataframe but I have no idea of how to combine all four. How can I achieve this?

Body:
Use itertools.product for the heavy lifting.

import pandas as pd
from itertools import product

lists = [list(pd.read_csv('data{}.csv'.format(i), header=0).iloc[:,0]) for i in range(1,5)]
combined = list(','.join(items) for items in product(*lists))
pd.DataFrame(combined).to_csv('combined.csv', index=0)

If you just want the list form, use combined. It looks like:

['michael,luke,jackson,solo',
 'michael,luke,jackson,cobain',
 'michael,luke,jackson,einstein',
 'michael,luke,jobs,solo',
 'michael,luke,jobs,cobain',
 'michael,luke,jobs,einstein',
 'michael,luke,skywalker,solo',
 'michael,luke,skywalker,cobain',
 'michael,luke,skywalker,einstein',
 ...

Or the final line writes the combined values out to a CSV.


问:
Is it advisable to upload files as parameter of Parse Cloud Code function?
I want to upload videos to parse server. Instead of saving the video file with the Parse iOS SDK's PFFile I upload the video to Parse Cloud Code as parameter:

```<code>PFCloud.callFunction(inBackground: "uploadVideo", withParameters: ["videoData": videoData]]) { (response, error) in
    ...
}
</code>```

On the server side I save the file:

```<code>Parse.Cloud.define("uploadVideo", function(request, response) {

    var videoData = request.params.videoData;
    var videoFile = new Parse.File("video.mov", videoData, "video/mov");

    videoFile.save(null, {useMasterKey: true})
    .then(
        function() {
            response.success();
        },
        function(error) {
            response.error(error.message);
        }
    );
});
</code>```

Is that good practice or are there any risks involved?
E.g. what is the maximum data object size to be passed as Cloud Code parameter?

答: I had some data issues with this, since my app may be used while trying to upload pictures in remote areas with poor service and no wifi. I changed the implementation to instead safe the Parse File object, and pass the URL if necessary, rather than sending a file. That way an unsuccessful file upload didn't interfere with the rest of the functionality. </p>

Body:
I want to upload videos to parse server. Instead of saving the video file with the Parse iOS SDK's PFFile I upload the video to Parse Cloud Code as parameter:

PFCloud.callFunction(inBackground: "uploadVideo", withParameters: ["videoData": videoData]]) { (response, error) in
    ...
}

On the server side I save the file:

Parse.Cloud.define("uploadVideo", function(request, response) {

    var videoData = request.params.videoData;
    var videoFile = new Parse.File("video.mov", videoData, "video/mov");

    videoFile.save(null, {useMasterKey: true})
    .then(
        function() {
            response.success();
        },
        function(error) {
            response.error(error.message);
        }
    );
});

Is that good practice or are there any risks involved?
E.g. what is the maximum data object size to be passed as Cloud Code parameter?


问:
How to disable keyboard appearing when hitting on a text field , iOS?
I have a text field , and i need when the user presses it to show a custom picker.

The picker is shown fine , but the problem is that the keyboard appears on the bottom and i dont want that.

This is an iPad project which i am trying to convert from my iphone one. On the iPhone , this works well and the keyboard is always hidden.

What could i be missing/forgetting to do here ?

EDIT

For future reference what actually happened here , was that in fact both times (iphone & ipad) the keyboard was not hidden. I just thought that it was hidden in the iphone because my picker , which was popping from the bottom was hiding the keyboard as it was on top of it. But on ipad this wasnt the case.

Anyway i fixed it , using the delegate method suggested below.

Caution , i accepted this answer cause it was the one answering specifically what i wanted. The rest of the answers are correct and my considered better for other implementations.

答:
swift 3.0 version

First set the delegate for the text field

```<code>self.textfield.delegate = self
</code>```

Then in an extension

```<code>extension ViewController: UITextFieldDelegate {
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        return false
    }
}
</code>```

Body:
swift 3.0 version

First set the delegate for the text field

self.textfield.delegate = self

Then in an extension

extension ViewController: UITextFieldDelegate {
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        return false
    }
}


答:
```<code>import numpy as np
import pandas as pd
import itertools
import functools

def cartesian(df1, df2):
    rows = itertools.product(df1.iterrows(), df2.iterrows())
    df = pd.DataFrame(left.append(right) for (_, left), (_, right) in rows)
    return df.reset_index(drop=True)

df1 = pd.read_csv('first_name.csv')
df2 = pd.read_csv('second_name.csv')
df3 = pd.read_csv('first_last_name.csv')
df4 = pd.read_csv('second_last_name.csv')

combined = functools.reduce(cartesian, [df1, df2, df3, df4])
combined.to_csv('combined.csv')
</code>```

Title: Python3 Pandas - How to create all combinations of 4 columns and write them in rows in a CSV?


问:
Java:how to group similar strings (items) to respective array (group)?
I have the following string "0#Aitem, 0#Aitem2, 0#Aitem3, 1#Bitem, 1#Bitem2, 2#Citem, Nitem, Nitem2".

the 0# shows group number. so Aitem, Aitem2, Aitem3 will belong to group 0. Bitem, Bitem2 in group 1. Citem in group 2. If there is no group number, they will all be place in separate group. So Nitem, Nitem2 will be placed in group 3.

I would like to create an array for each group, and place the "items" in respective group(array). So I would end up with something like

```<code>[array("Aitem,Aitem2,Aitem3"), array("Bitem, Bitem2"), array("Citem"), array("Nitem, Nitem2")]
</code>```

I am guessing I need an arrayList to hold all the groups (arrays) which respectively has appropriate elements (items).

This is what I started with but I don't know if this is the best approach. The string is dynamic, so there can be any number of groups and has to follow the criteria above.

```<code>String[] x = Pattern.compile(",").split("0#item, 0#item2, 0#item3, 1#item, 1#item2, 2#item, item");
   for (int ii=0; ii<x.length; ii++) {
       System.out.println(i + " \"" + x[ii] + "\"");
   }
</code>```

答:
Another solution based on Maps.</p>

```<code>    System.out.println("###Parsing results and populating map");
    String[] x = Pattern.compile("\\s*,\\s*").split(
            "0#item, 0#item2, 0#item3, 1#item, 1#item2, 2#item, item");

    Map<String, List<String>> result = new TreeMap<String, List<String>>();

    for (int i = 0; i < x.length; i++) {
        String y[] = x[i].split("#");

        if (y.length > 1) {
        System.out.println("group: '" + y[0] + "' item: '" + y[1] + "'");
            List<String> l = result.get(y[0]);
            if(l==null){
                l = new ArrayList<String>();
                result.put(y[0], l);
            }
            l.add(y[1]);
        }
    }

    System.out.println("###Returning values stored in map, as separate arrays");
    for(Entry<String,List<String>> entry: result.entrySet()){
        System.out.println("Group:" + entry.getKey());
        //System.out.println("Items:");
        List <String> l = entry.getValue();
        // This is where the final array is
        String[] finalArray = l.toArray(new String[1]);
        for (int i = 0; i < finalArray.length; i++) {
            System.out.println(finalArray[i]);
        }

    }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have the following string "0#Aitem, 0#Aitem2, 0#Aitem3, 1#Bitem, 1#Bitem2, 2#Citem, Nitem, Nitem2".

the 0# shows group number. so Aitem, Aitem2, Aitem3 will belong to group 0. Bitem, Bitem2 in group 1. Citem in group 2. If there is no group number, they will all be place in separate group. So Nitem, Nitem2 will be placed in group 3.

I would like to create an array for each group, and place the "items" in respective group(array). So I would end up with something like

[array("Aitem,Aitem2,Aitem3"), array("Bitem, Bitem2"), array("Citem"), array("Nitem, Nitem2")]

I am guessing I need an arrayList to hold all the groups (arrays) which respectively has appropriate elements (items).

This is what I started with but I don't know if this is the best approach. The string is dynamic, so there can be any number of groups and has to follow the criteria above.

String[] x = Pattern.compile(",").split("0#item, 0#item2, 0#item3, 1#item, 1#item2, 2#item, item");
   for (int ii=0; ii<x.length; ii++) {
       System.out.println(i + " \"" + x[ii] + "\"");
   }

Body:
Another solution based on Maps.

    System.out.println("###Parsing results and populating map");
    String[] x = Pattern.compile("\\s*,\\s*").split(
            "0#item, 0#item2, 0#item3, 1#item, 1#item2, 2#item, item");

    Map<String, List<String>> result = new TreeMap<String, List<String>>();

    for (int i = 0; i < x.length; i++) {
        String y[] = x[i].split("#");

        if (y.length > 1) {
        System.out.println("group: '" + y[0] + "' item: '" + y[1] + "'");
            List<String> l = result.get(y[0]);
            if(l==null){
                l = new ArrayList<String>();
                result.put(y[0], l);
            }
            l.add(y[1]);
        }
    }

    System.out.println("###Returning values stored in map, as separate arrays");
    for(Entry<String,List<String>> entry: result.entrySet()){
        System.out.println("Group:" + entry.getKey());
        //System.out.println("Items:");
        List <String> l = entry.getValue();
        // This is where the final array is
        String[] finalArray = l.toArray(new String[1]);
        for (int i = 0; i < finalArray.length; i++) {
            System.out.println(finalArray[i]);
        }

    }


问:
For each through List<string> returned from AJAX GET in JavaScript
The problem is as the title describes... I'm trying to loop through the values in a list of strings and alert them on the page.  Unfortunately, I keep getting an error of...

"Uncaught TypeError: response.forEach is not a function"

I've read a few other places on SO about for loops in javascript, but it seems that it works with arrays.  I'll state that I'm a novice when it comes to JavaScript... so is there an equivalent .ToArray() method in JavaScript?  I've written a simple application to show what it is I'm trying to accomplish.

Note: I'm unable to change the return type of the controller method "GetStringList". In the larger application, the method must return a list of strings.

Controller Method (C#)

```<code>    public List<string> GetStringList(){
        List<string> listOfStrings = new List<string>();

        SqlConnection sqlConn = new SqlConnection(connection_String);

        sqlConn.Open();

        string sqlStr = "SELECT * FROM dbo.[SampleOrders] WHERE Active = 1";
        SqlCommand sqlCmd = new SqlCommand(sqlStr, sqlConn);
        SqlDataReader sqlDR = sqlCmd.ExecuteReader();

        if (sqlDR.HasRows) {
            while (sqlDR.Read()) {
                listOfStrings.Add((string)sqlDR["SalesOrder"]);
            }
        }

        sqlDR.Close();
        sqlCmd.Dispose();
        sqlConn.Close();

        return listOfStrings;
    }
</code>```

View / JavaScript Function

```<code>    <script>
        $(document).ready(function () {
            $('#demoBtn').click(function () {
                $.ajax({
                    type: 'GET',
                    url: '/Home/GetStringList',
                    success: function (response) {
                        response.forEach(function (item) {
                            alert(item);
                        });
                    }
                });
            });
        });
    </script>
</code>```

Please let me know if any clarifications need made -- thanks!

答:
You can't just return listOfStrings as it would just print something like System.Collections.Generic.List 1[System.String]

So you should change your code to something like:

```<code>return string.Join(",",listOfStrings);
</code>```

But, since you want to traverse it using Javascript, I suggest returning it as a JSON, doing this:

```<code>using Newtonsoft.Json;
...
return JsonConvert.SerializeObject(listOfStrings);
</code>```

This way, you'll end up with an string similar to:

```<code>["string1","string2","string3"]
</code>```

Now, you may change your jQuery so it expects a JSON:

```<code>$.ajax({
  type: 'GET',
  dataType: 'json', //So your response will be parsed and ready to use as a Javascript object
  url: '/Home/GetStringList',
  success: function (response) {
    response.forEach(function (item) {
      alert(item);
    });
  }
});
</code>```

If you absolutely don't want to change the return statement of the function, you have two options:

Use an optional parameter so you can tell when you need a JSON

```<code>public List<string> GetStringList(bool json = False){
  ...
  if(json){
    return JsonConvert.SerializeObject(listOfStrings);
  }
  return listOfStrings;
}
</code>```

Create another method to wrap the return, like so:

```<code>public string GetStringListAsJSON(){
  return JsonConvert.SerializeObject(GetStringList());
}
</code>```

Body:
The problem is as the title describes... I'm trying to loop through the values in a list of strings and alert them on the page.  Unfortunately, I keep getting an error of...

"Uncaught TypeError: response.forEach is not a function"

I've read a few other places on SO about for loops in javascript, but it seems that it works with arrays.  I'll state that I'm a novice when it comes to JavaScript... so is there an equivalent .ToArray() method in JavaScript?  I've written a simple application to show what it is I'm trying to accomplish.

Note: I'm unable to change the return type of the controller method "GetStringList". In the larger application, the method must return a list of strings.

Controller Method (C#)

    public List<string> GetStringList(){
        List<string> listOfStrings = new List<string>();

        SqlConnection sqlConn = new SqlConnection(connection_String);

        sqlConn.Open();

        string sqlStr = "SELECT * FROM dbo.[SampleOrders] WHERE Active = 1";
        SqlCommand sqlCmd = new SqlCommand(sqlStr, sqlConn);
        SqlDataReader sqlDR = sqlCmd.ExecuteReader();

        if (sqlDR.HasRows) {
            while (sqlDR.Read()) {
                listOfStrings.Add((string)sqlDR["SalesOrder"]);
            }
        }

        sqlDR.Close();
        sqlCmd.Dispose();
        sqlConn.Close();

        return listOfStrings;
    }

View / JavaScript Function

Please let me know if any clarifications need made -- thanks!

Body:
You can't just return listOfStrings as it would just print something like System.Collections.Generic.List 1[System.String]

So you should change your code to something like:

return string.Join(",",listOfStrings);

But, since you want to traverse it using Javascript, I suggest returning it as a JSON, doing this:

using Newtonsoft.Json;
...
return JsonConvert.SerializeObject(listOfStrings);

This way, you'll end up with an string similar to:

["string1","string2","string3"]

Now, you may change your jQuery so it expects a JSON:

$.ajax({
  type: 'GET',
  dataType: 'json', //So your response will be parsed and ready to use as a Javascript object
  url: '/Home/GetStringList',
  success: function (response) {
    response.forEach(function (item) {
      alert(item);
    });
  }
});

If you absolutely don't want to change the return statement of the function, you have two options:

Use an optional parameter so you can tell when you need a JSON

public List<string> GetStringList(bool json = False){
  ...
  if(json){
    return JsonConvert.SerializeObject(listOfStrings);
  }
  return listOfStrings;
}

Create another method to wrap the return, like so:

public string GetStringListAsJSON(){
  return JsonConvert.SerializeObject(GetStringList());
}


问:
How do I get a feed of the 10th page on realbusiness.co.uk?
I'm  trying to pull the 10th page from realbusuiness.co.uk rss feed. I have tried several variations of the url but I can't find the correct one like so:

http://realbusiness.co.uk/feed/page10

http://realbusiness.co.uk/feed/paged10

http://realbusiness.co.uk/feed/?page10

http://realbusiness.co.uk/feed/?paged10

http://realbusiness.co.uk/feed?page10

http://realbusiness.co.uk/feed?paged10

Any idea on what the correct url would be?

Thanks in advance!

答: I think you missing = on url. Because the wordpress feed page url is at http://realbusiness.co.uk/feed/?paged=number of page in your case maybe http://realbusiness.co.uk/feed/?paged=10


问:
Not show Correct Scores java
in my code , i have 2 array name and score and length of both is 2

```<code>import java.util.Scanner;

public class Test {

    private static Scanner key = new Scanner (System.in);

    public static void main (String [] args){

        String [] name = new String [2];
        int [] score = new int [2];

        readInfo(name, score);
        showInfo(name, score);

    }

    public static void readInfo (String [] name, int [] score){

        for (int i = 0; i < name.length; i++){

            System.out.print("Name no."+(i + 1)+": ");
            name [i] = key.next();

            for (int j = 0; j < score.length; j++){

                System.out.print("Score no."+(j + 1)+": ");
                score [j] = key.nextInt();

            }

            System.out.println("");

        }

    }

    public static void showInfo (String [] name, int [] score){

        System.out.println("Name\tScores\n");

        for (int i = 0; i < name.length; i++){

            System.out.print(name [i]);

            for (int j = 0; j < score.length; j++ )
                System.out.println("\t"+score [j]+"\t");

            System.out.println("");
        }

    }

}
</code>```

when i input names and scores, in output only show second scores for both names.

```<code>Name no.1: john
Score no.1: 17
Score no.2: 19

Name no.2: jack
Score no.1: 12
Score no.2: 18

Name    Scores

john    12
        18

jack    12
        18
</code>```

this is my problem how can i fix it?

答:
You can fix it like this:

```<code>public class Test{

private static Scanner key = new Scanner (System.in);

public static void main (String [] args){

    String [] name = new String [2];
    int [] score = new int [name.length*2];

    readInfo(name, score);
    showInfo(name, score);

}

public static void readInfo (String [] name, int [] score){

    for (int i = 0; i < name.length; i++){

        System.out.print("Name no."+(i + 1)+": ");
        name [i] = key.next();

        for (int j = i*2; j < name.length+i*2; j++){

            System.out.print("Score no."+(j + 1)+": ");
            score [j] = key.nextInt();

        }

        System.out.println("");

    }

}

public static void showInfo (String [] name, int [] score){

    System.out.println("Name\tScores\n");

    for (int i = 0; i < name.length; i++){

        System.out.print(name [i]);

        for (int j = i*2; j < name.length +i*2; j++ )
            System.out.println("\t"+score [j]+"\t");

        System.out.println("");
    }

}
}
</code>```

what's happening here is that you have an array of names length 2, and you want 2 scores for each. That means your scores array needs to have a length of names*2:

```<code>int [] score = new int [name.length*2];
</code>```

Then, when inputting the scores, score index 0 and 1 needs to be for person 1, and index 2 and 3 needs to be for person 2, hence:

```<code>for (int j = i*2; j < name.length+i*2; j++){

        System.out.print("Score no."+(j + 1)+": ");
        score [j] = key.nextInt();

    }
</code>```

Then, the same thing needs to be done for read

Title: Not show Correct Scores java

Body:
in my code , i have 2 array name and score and length of both is 2

import java.util.Scanner;

public class Test {

    private static Scanner key = new Scanner (System.in);

    public static void main (String [] args){

        String [] name = new String [2];
        int [] score = new int [2];

        readInfo(name, score);
        showInfo(name, score);

    }

    public static void readInfo (String [] name, int [] score){

        for (int i = 0; i < name.length; i++){

            System.out.print("Name no."+(i + 1)+": ");
            name [i] = key.next();

            for (int j = 0; j < score.length; j++){

                System.out.print("Score no."+(j + 1)+": ");
                score [j] = key.nextInt();

            }

            System.out.println("");

        }

    }

    public static void showInfo (String [] name, int [] score){

        System.out.println("Name\tScores\n");

        for (int i = 0; i < name.length; i++){

            System.out.print(name [i]);

            for (int j = 0; j < score.length; j++ )
                System.out.println("\t"+score [j]+"\t");

            System.out.println("");
        }

    }

}

when i input names and scores, in output only show second scores for both names.

Name no.1: john
Score no.1: 17
Score no.2: 19

Name no.2: jack
Score no.1: 12
Score no.2: 18

Name    Scores

john    12
        18

jack    12
        18

this is my problem how can i fix it?

Body:
You can fix it like this:

public class Test{

private static Scanner key = new Scanner (System.in);

public static void main (String [] args){

    String [] name = new String [2];
    int [] score = new int [name.length*2];

    readInfo(name, score);
    showInfo(name, score);

}

public static void readInfo (String [] name, int [] score){

    for (int i = 0; i < name.length; i++){

        System.out.print("Name no."+(i + 1)+": ");
        name [i] = key.next();

        for (int j = i*2; j < name.length+i*2; j++){

            System.out.print("Score no."+(j + 1)+": ");
            score [j] = key.nextInt();

        }

        System.out.println("");

    }

}

public static void showInfo (String [] name, int [] score){

    System.out.println("Name\tScores\n");

    for (int i = 0; i < name.length; i++){

        System.out.print(name [i]);

        for (int j = i*2; j < name.length +i*2; j++ )
            System.out.println("\t"+score [j]+"\t");

        System.out.println("");
    }

}
}

what's happening here is that you have an array of names length 2, and you want 2 scores for each. That means your scores array needs to have a length of names*2:

int [] score = new int [name.length*2];

Then, when inputting the scores, score index 0 and 1 needs to be for person 1, and index 2 and 3 needs to be for person 2, hence:

for (int j = i*2; j < name.length+i*2; j++){

        System.out.print("Score no."+(j + 1)+": ");
        score [j] = key.nextInt();

    }

Then, the same thing needs to be done for read


问:
Dropdown navigation submenu renders behind other elements
The submenus in my navigation bar are rendering behind the main content. More specifically, I have a navigation component which is right above another component containing an h1 element. The submenus in the navigation bar are visibly behind the h1 element in the main body component (because there is no background). It is also being hidden by the footer.

In the main app component, the template looks like this:

```<code><nova-header></nova-header>
<nova-navigation [categories]="categories"></nova-navigation>
<router-outlet></router-outlet>
<nova-footer [categories]="categories"></nova-footer>
</code>```

What's strange is that I copy-pasted my code into JSFiddle, which you can see where I've separated the nova-navigation template HTML and the main body component HTML in the fiddle, however the problem is gone and the submenus render correctly. I'm new to Angular, so I assume I'm missing something with how Angular works.

Here's a link to said JSFiddle: https://jsfiddle.net/jonnylin13/nwxyd8j8/

I've tried z-index and overflow already

EDIT ** the problem must be with my local environment as I created a plnkr and the problem is not there. http://plnkr.co/edit/Pzzt6C4C9OrAvil50yqT?p=preview

答:
As I can't comment, I will help you with answering.
I can suggest you the z-index.
But you have to remember that z-index need the property position to work.

I hope this will help you, let me know!

Body:
The submenus in my navigation bar are rendering behind the main content. More specifically, I have a navigation component which is right above another component containing an h1 element. The submenus in the navigation bar are visibly behind the h1 element in the main body component (because there is no background). It is also being hidden by the footer.

In the main app component, the template looks like this:

<nova-header></nova-header>
<nova-navigation [categories]="categories"></nova-navigation>
<router-outlet></router-outlet>
<nova-footer [categories]="categories"></nova-footer>

What's strange is that I copy-pasted my code into JSFiddle, which you can see where I've separated the nova-navigation template HTML and the main body component HTML in the fiddle, however the problem is gone and the submenus render correctly. I'm new to Angular, so I assume I'm missing something with how Angular works.

Here's a link to said JSFiddle: https://jsfiddle.net/jonnylin13/nwxyd8j8/

I've tried z-index and overflow already

EDIT ** the problem must be with my local environment as I created a plnkr and the problem is not there. http://plnkr.co/edit/Pzzt6C4C9OrAvil50yqT?p=preview


问:
Doing many iterations of curve_fit in one go for piecewise function
I'm trying to perform what are many iterations of Scipy's curve_fit at once in order to avoid loops and therefore increase speed.

This is very similar to this problem, which was solved. However, the fact that the functions are piece-wise (discontinuous) makes so that that solution isn't applicable here.

Consider this example:

```<code>import numpy as np
from numpy import random as rng
from scipy.optimize import curve_fit
rng.seed(0)
N=20
X=np.logspace(-1,1,N)
Y = np.zeros((4, N))
for i in range(0,4):
    b = i+1
    a = b
    print(a,b)
    Y[i] = (X/b)**(-a) #+ 0.01 * rng.randn(6)
    Y[i, X>b] = 1
</code>```

This yields these arrays:

Which as you can see are discontinuous at X==b. I can retrieve the original values of a and b by using curve_fit iteratively:

```<code>def plaw(r, a, b):
    """ Theoretical power law for the shape of the normalized conditional density """
    import numpy as np
    return np.piecewise(r, [r < b, r >= b], [lambda x: (x/b)**-a, lambda x: 1])

coeffs=[]
for ix in range(Y.shape[0]):
    print(ix)
    c0, pcov = curve_fit(plaw, X, Y[ix])
    coeffs.append(c0)
</code>```

But this process can be very slow depending of the size of X, Y and the loop, so I'm trying to speed things up by trying to get coeffs without the need for a loop. So far I haven't had any luck.

Things that might be important:

X and Y only contain positive values

a and b are always positive

Although the data to fit in this example is smooth (for the sake of simplicity), the real data has noise

EDIT

This is as far as I've gotten:

```<code>y=np.ma.masked_where(Y<1.01, Y)

lX = np.log(X)
lY = np.log(y)
A = np.vstack([lX, np.ones(len(lX))]).T
m,c=np.linalg.lstsq(A, lY.T)[0]

print('a=',-m)
print('b=',np.exp(-c/m))
</code>```

But even without any noise the output is:

```<code>a= [0.18978965578339158 1.1353633705997466 2.220234483915197 3.3324502660995714]
b= [339.4090881838179 7.95073481873057 6.296592007396107 6.402567167503574]
</code>```

Which is way worse than I was hoping to get.

答:
Two suggestions:

Use numpy.where (and possibly argmin) to find the X value at which the Y data becomes 1, or perhaps just slightly larger than 1, and truncate the data to that point -- effectively ignoring the data where Y=1.

That might be something like:

```<code>index_max = numpy.where(y < 1.2)[0][0]
x = y[:index_max]
y = y[:index_max]
</code>```

Use the hint shown in your log-log plot that the power law is now linear in log-log.  You don't need curve_fit, but can use scipy.stats.linregress on log(Y) vs log(Y).  For your real work, that will at the very least give good starting values for a subsequent fit.

Following up on this and trying to follow your question, you might try something like:

```<code>import numpy as np
from scipy.stats import linregress

np.random.seed(0)
npts = 51
x = np.logspace(-2, 2, npts)
YTHRESH = 1.02

for i in range(5):
    b = i + 1.0 + np.random.normal(scale=0.1)
    a = b + np.random.random()
    y = (x/b)**(-a) + np.random.normal(scale=0.0030, size=npts)
    y[x>b] = 1.0

    # to model exponential decay, first remove the values
    # where y ~= 1 where the data is known to not decay...
    imax = np.where(y < YTHRESH)[0][0]

    # take log of this truncated x and y
    _x = np.log(x[:imax])
    _y = np.log(y[:imax])

    # use linear regression on the log-log data:
    out = linregress(_x, _y)

    # map slope/intercept to scale, exponent
    afit = -out.slope
    bfit = np.exp(out.intercept/afit)

    print(""" === Fit Example {i:3d}
          a  expected {a:4f}, got {afit:4f}
          b  expected {b:4f}, got {bfit:4f}
          """.format(i=i+1, a=a, b=b, afit=afit, bfit=bfit))
</code>```

Hopefully that's enough to get you going.

Body:
I'm trying to perform what are many iterations of Scipy's curve_fit at once in order to avoid loops and therefore increase speed.

This is very similar to this problem, which was solved. However, the fact that the functions are piece-wise (discontinuous) makes so that that solution isn't applicable here.

Consider this example:

import numpy as np
from numpy import random as rng
from scipy.optimize import curve_fit
rng.seed(0)
N=20
X=np.logspace(-1,1,N)
Y = np.zeros((4, N))
for i in range(0,4):
    b = i+1
    a = b
    print(a,b)
    Y[i] = (X/b)**(-a) #+ 0.01 * rng.randn(6)
    Y[i, X>b] = 1

This yields these arrays:

Which as you can see are discontinuous at X==b. I can retrieve the original values of a and b by using curve_fit iteratively:

def plaw(r, a, b):
    """ Theoretical power law for the shape of the normalized conditional density """
    import numpy as np
    return np.piecewise(r, [r = b], [lambda x: (x/b)**-a, lambda x: 1])

coeffs=[]
for ix in range(Y.shape[0]):
    print(ix)
    c0, pcov = curve_fit(plaw, X, Y[ix])
    coeffs.append(c0)

But this process can be very slow depending of the size of X, Y and the loop, so I'm trying to speed things up by trying to get coeffs without the need for a loop. So far I haven't had any luck.

Things that might be important:

X and Y only contain positive values

a and b are always positive

Although the data to fit in this example is smooth (for the sake of simplicity), the real data has noise

EDIT

This is as far as I've gotten:

y=np.ma.masked_where(Y<1.01, Y)

lX = np.log(X)
lY = np.log(y)
A = np.vstack([lX, np.ones(len(lX))]).T
m,c=np.linalg.lstsq(A, lY.T)[0]

print('a=',-m)
print('b=',np.exp(-c/m))

But even without any noise the output is:

a= [0.18978965578339158 1.1353633705997466 2.220234483915197 3.3324502660995714]
b= [339.4090881838179 7.95073481873057 6.296592007396107 6.402567167503574]

Which is way worse than I was hoping to get.

Body:
Two suggestions:

Use numpy.where (and possibly argmin) to find the X value at which the Y data becomes 1, or perhaps just slightly larger than 1, and truncate the data to that point -- effectively ignoring the data where Y=1.

That might be something like:

index_max = numpy.where(y < 1.2)[0][0]
x = y[:index_max]
y = y[:index_max]

Use the hint shown in your log-log plot that the power law is now linear in log-log.  You don't need curve_fit, but can use scipy.stats.linregress on log(Y) vs log(Y).  For your real work, that will at the very least give good starting values for a subsequent fit.

Following up on this and trying to follow your question, you might try something like:

import numpy as np
from scipy.stats import linregress

np.random.seed(0)
npts = 51
x = np.logspace(-2, 2, npts)
YTHRESH = 1.02

for i in range(5):
    b = i + 1.0 + np.random.normal(scale=0.1)
    a = b + np.random.random()
    y = (x/b)**(-a) + np.random.normal(scale=0.0030, size=npts)
    y[x>b] = 1.0

    # to model exponential decay, first remove the values
    # where y ~= 1 where the data is known to not decay...
    imax = np.where(y < YTHRESH)[0][0]

    # take log of this truncated x and y
    _x = np.log(x[:imax])
    _y = np.log(y[:imax])

    # use linear regression on the log-log data:
    out = linregress(_x, _y)

    # map slope/intercept to scale, exponent
    afit = -out.slope
    bfit = np.exp(out.intercept/afit)

    print(""" === Fit Example {i:3d}
          a  expected {a:4f}, got {afit:4f}
          b  expected {b:4f}, got {bfit:4f}
          """.format(i=i+1, a=a, b=b, afit=afit, bfit=bfit))

Hopefully that's enough to get you going.


问:
Live call transfer by using asterisk
i want to transfer a call from first executive to second executive when customer call to first executive by mistake? How first executive can map customer to second executive by pressing a key by using asterisk technology? </p>

答:
The question is a bit vague, but since you put freepbx on the tags, I suppose you are using freepbx generated dialplan.

If I understand well, when a certain inbound context calls executive1 you want

1) them to be automagically redirected on executive2 before executive1 answers

or

2) executive1 answers, realizes that call is wrong and blind-transfers call to executive2 pressing a single button (= DTMF).

CASE 1 - Automatic redirection

Edit your /etc/asterisk/extension_custom.conf

```<code>[your inbound context]
exten => <executive 1 number>,Goto(your inbound context, executive2 number, 1)
</code>```

You can find the name of your inbound context in the freepbx automatic generated dialplan, or in the freepbx GUI

CASE2 - In call transfer

Refer to this post to define a new feature code for in-call transfer. Unfortunately your feature code will be likely some #digit
Associate the application

```<code>Goto(your inbound context, executive2 number, 1)
</code>```

to the feature code

Hope this will help.

Title: Live call transfer by using asterisk

Body:
The question is a bit vague, but since you put freepbx on the tags, I suppose you are using freepbx generated dialplan.

If I understand well, when a certain inbound context calls executive1 you want

1) them to be automagically redirected on executive2 before executive1 answers

or

2) executive1 answers, realizes that call is wrong and blind-transfers call to executive2 pressing a single button (= DTMF).

CASE 1 - Automatic redirection

Edit your /etc/asterisk/extension_custom.conf

[your inbound context]
exten => <executive 1 number>,Goto(your inbound context, executive2 number, 1)

You can find the name of your inbound context in the freepbx automatic generated dialplan, or in the freepbx GUI

CASE2 - In call transfer

Refer to this post to define a new feature code for in-call transfer. Unfortunately your feature code will be likely some #digit
Associate the application

Goto(your inbound context, executive2 number, 1)

to the feature code

Hope this will help.


问:
A new Catalog entry is not visible in Catalogs
I am trying to add a new Catalog entry as "Beauty Products" in addition to Service Catalog and Technical Catalog which is not visible in Catalogs when I login as a user. I have added a category and catalog item as well. Attaching the settings as an image.

答:
To clarify, you are under Service Catalog > Catalogs?

If so, you need to add the new catalog by clicking the plus button on the top right.

Then select your Beauty Products catalog from the window, then click Add here


问:
Beautiful Soup - Blank screen for a long time without any output
I am quite new to python and am working on a scraping based project- where I am supposed to extract all the contents from links containing a particular search term and place them in a csv file. As a first step, I wrote this code to extract all the links from a website based on a search term entered. I only get a blank screen as output and I am unable to find my mistake.</p>

```<code>import urllib
import mechanize
from bs4 import BeautifulSoup
import datetime

def searchAP(searchterm):
    newlinks = []
    browser = mechanize.Browser()
    browser.set_handle_robots(False)
    browser.addheaders = [('User-agent', 'Firefox')]
    text = ""
    start = 0

    while "There were no matches for your search" not in text:
        url = "http://www.marketing-interactive.com/"+"?s="+searchterm
        text = urllib.urlopen(url).read()
        soup = BeautifulSoup(text, "lxml")
        results = soup.findAll('a')
        for r in results:
            if "rel=bookmark" in r['href'] :
                newlinks.append("http://www.marketing-interactive.com"+ str(r["href"]))
        start +=10
                return newlinks
       print searchAP("digital marketing")
</code>```

答:
The following script extracts all the links from the web page based on given search key. But it does not explore beyond the first page. Although the following code can easily be modified to get all results from multiple pages by manipulating page-number in the URL (as described by Rutger de Knijf in the other answer.).

```<code>from pprint import pprint
import requests
from BeautifulSoup import BeautifulSoup

def get_url_for_search_key(search_key):
    base_url = 'http://www.marketing-interactive.com/'
    response = requests.get(base_url + '?s=' + search_key)
    soup = BeautifulSoup(response.content)

    return [url['href'] for url in soup.findAll('a', {'rel': 'bookmark'})]
</code>```

Usage:

```<code>pprint(get_url_for_search_key('digital marketing'))
</code>```

Output:

```<code>[u'http://www.marketing-interactive.com/astro-launches-digital-marketing-arm-blaze-digital/',
 u'http://www.marketing-interactive.com/singapore-polytechnic-on-the-hunt-for-digital-marketing-agency/',
 u'http://www.marketing-interactive.com/how-to-get-your-bosses-on-board-your-digital-marketing-plan/',
 u'http://www.marketing-interactive.com/digital-marketing-institute-launches-brand-refresh/',
 u'http://www.marketing-interactive.com/entropia-highlights-the-7-original-sins-of-digital-marketing/',
 u'http://www.marketing-interactive.com/features/futurist-right-mindset-digital-marketing/',
 u'http://www.marketing-interactive.com/lenovo-brings-board-new-digital-marketing-head/',
 u'http://www.marketing-interactive.com/video/discussing-digital-marketing-indonesia-video/',
 u'http://www.marketing-interactive.com/ubs-melvin-kwek-joins-credit-suisse-as-apac-digital-marketing-lead/',
 u'http://www.marketing-interactive.com/linkedins-top-10-digital-marketing-predictions-2017/']
</code>```

Hope this is what you wanted as the first step for your project.

Body:
I am quite new to python and am working on a scraping based project- where I am supposed to extract all the contents from links containing a particular search term and place them in a csv file. As a first step, I wrote this code to extract all the links from a website based on a search term entered. I only get a blank screen as output and I am unable to find my mistake.

import urllib
import mechanize
from bs4 import BeautifulSoup
import datetime

def searchAP(searchterm):
    newlinks = []
    browser = mechanize.Browser()
    browser.set_handle_robots(False)
    browser.addheaders = [('User-agent', 'Firefox')]
    text = ""
    start = 0

    while "There were no matches for your search" not in text:
        url = "http://www.marketing-interactive.com/"+"?s="+searchterm
        text = urllib.urlopen(url).read()
        soup = BeautifulSoup(text, "lxml")
        results = soup.findAll('a')
        for r in results:
            if "rel=bookmark" in r['href'] :
                newlinks.append("http://www.marketing-interactive.com"+ str(r["href"]))
        start +=10
                return newlinks
       print searchAP("digital marketing")

Body:
The following script extracts all the links from the web page based on given search key. But it does not explore beyond the first page. Although the following code can easily be modified to get all results from multiple pages by manipulating page-number in the URL (as described by Rutger de Knijf in the other answer.).

from pprint import pprint
import requests
from BeautifulSoup import BeautifulSoup

def get_url_for_search_key(search_key):
    base_url = 'http://www.marketing-interactive.com/'
    response = requests.get(base_url + '?s=' + search_key)
    soup = BeautifulSoup(response.content)

    return [url['href'] for url in soup.findAll('a', {'rel': 'bookmark'})]

Usage:

pprint(get_url_for_search_key('digital marketing'))

Output:

[u'http://www.marketing-interactive.com/astro-launches-digital-marketing-arm-blaze-digital/',
 u'http://www.marketing-interactive.com/singapore-polytechnic-on-the-hunt-for-digital-marketing-agency/',
 u'http://www.marketing-interactive.com/how-to-get-your-bosses-on-board-your-digital-marketing-plan/',
 u'http://www.marketing-interactive.com/digital-marketing-institute-launches-brand-refresh/',
 u'http://www.marketing-interactive.com/entropia-highlights-the-7-original-sins-of-digital-marketing/',
 u'http://www.marketing-interactive.com/features/futurist-right-mindset-digital-marketing/',
 u'http://www.marketing-interactive.com/lenovo-brings-board-new-digital-marketing-head/',
 u'http://www.marketing-interactive.com/video/discussing-digital-marketing-indonesia-video/',
 u'http://www.marketing-interactive.com/ubs-melvin-kwek-joins-credit-suisse-as-apac-digital-marketing-lead/',
 u'http://www.marketing-interactive.com/linkedins-top-10-digital-marketing-predictions-2017/']

Hope this is what you wanted as the first step for your project.


问:
What problems can arise when the program ends before fclose()
I understand that not closing a file is irresponsible, but under the following two conditions, what issues can arise if fclose() was not be called?

1) In the event that fclose() was not called when a program ends, does the OS communicate with the file descriptor to let it know that the file is not longer needed and closes it?

```<code>#include <stdio.h>
int main(){
    FILE* f = open("sample.txt","r");
    return 0;
};
</code>```

In the event of a explicit exit e.g. exit(1) does it differ in any way as to just returning in the previous example?

```<code>#include <stdio.h>
int main(){
    FILE* f = fopen("sample.txt","r");
    exit(1);
    return 0;
}
</code>```

2) A potential segmentation fault occurs before fclose() could be called?

```<code>#include <stdio.h>
int main(){
    FILE* f = fopen("sample.txt","r");
    int *ptr = NULL;
    *ptr = 1; //seg-fault
    fclose(f);
    return 0;
};
</code>```

答:
If you use exist, in  C Language, the exit function calls all functions registered with atexit and terminates the program. File buffers are flushed, streams are closed, and temporary files are deleted.

And even you don't the OS should release all the program resources once it terminates. Though not cleaning up is a bad habit that can lead to serious issues.

Body:
I understand that not closing a file is irresponsible, but under the following two conditions, what issues can arise if fclose() was not be called?

1) In the event that fclose() was not called when a program ends, does the OS communicate with the file descriptor to let it know that the file is not longer needed and closes it?

#include <stdio.h>
int main(){
    FILE* f = open("sample.txt","r");
    return 0;
};

In the event of a explicit exit e.g. exit(1) does it differ in any way as to just returning in the previous example?

#include <stdio.h>
int main(){
    FILE* f = fopen("sample.txt","r");
    exit(1);
    return 0;
}

2) A potential segmentation fault occurs before fclose() could be called?

#include <stdio.h>
int main(){
    FILE* f = fopen("sample.txt","r");
    int *ptr = NULL;
    *ptr = 1; //seg-fault
    fclose(f);
    return 0;
};


问:
Using Beautiful Soup to Find Links Before a Certain Letter
I have a BeautifulSoup problem that hopefully you can help me out with.

Currently, I have a website with a lot of links on it. The links lead to pages that contain the data of that item that is linked. If you want to check it out, it's this one: http://ogle.astrouw.edu.pl/ogle4/ews/ews.html. What I ultimately want to accomplish is to print out the links of the data that are labeled with an 'N'. It may not be apparent at first, but if you look closely on the website, some of the data have 'N' after their Star No, and others do not. Afterwards, I use that link to download a file containing the information I need on that data. The website is very convenient because the download URLs only change a bit from data to data, so I only need to change a part of the URL, as you'll see in the code below.

I currently have accomplished the data downloading part. However, this is where you come in. Currently, I need to put in the identification number of the BLG event that I desire. (This will become apparent after you view the code below.) However, the website is consistently updating over time, and having to manually search for 'N' events takes up unnecessary time. I want the Python code to be able to do it for me. My original thoughts on the subject were that I could have BeautifulSoup search through the text for all N's, but I ran into some issues on accomplishing that. I feel like I am not familiar enough with BeautifulSoup to get done what I wish to get done. Some help would be appreciated.

The code I have currently is below. I have put in a range of BLG events that have the 'N' label as an example.

```<code>#Retrieve .gz files from URLs

from urllib.request import urlopen
import urllib.request
from bs4 import BeautifulSoup

#Access website
URL = 'http://ogle.astrouw.edu.pl/ogle4/ews/ews.html'
soup = BeautifulSoup(urlopen(URL))

#Select the desired data numbers
numbers = list(range(974,998))
x=0
for i in numbers:
    numbers[x] = str(i)
    x += 1
print(numbers)

#Get all links and put into list
allLinks = []
for link in soup.find_all('a'):
    list_links = link.get('href')
    allLinks.append(list_links)

#Remove None datatypes from link list
while None in allLinks:
    allLinks.remove(None)
#print(allLinks)

#Remove all links but links to data pages and gets rid of the '.html'
list_Bindices = [i for i, s in enumerate(allLinks) if 'b' in s]
print(list_Bindices)
bLinks = []
for x in list_Bindices:
    bLinks.append(allLinks[x])
bLinks = [s.replace('.html', '') for s in bLinks]
#print(bLinks)

#Create a list of indices for accessing those pages
list_Nindices = []
for x in numbers:
    list_Nindices.append([i for i, s in enumerate(bLinks) if x in s])
#print(type(list_Nindices))
#print(list_Nindices)

nindices_corrected = []
place = 0
while place < (len(list_Nindices)):
    a = list_Nindices[place]
    nindices_corrected.append(a[0])
    place = place + 1
#print(nindices_corrected)

#Get the page names (without the .html) from the indices
nLinks = []
for x in nindices_corrected:
    nLinks.append(bLinks[x])
#print(nLinks)

#Form the URLs for those pages
final_URLs = []
for x in nLinks:
    y = "ftp://ftp.astrouw.edu.pl/ogle/ogle4/ews/2017/"+ x + "/phot.dat"
    final_URLs.append(y)
#print(final_URLs)
#Retrieve the data from the URLs
z = 0
for x in final_URLs:
    name = nLinks[z] + ".dat"
    #print(name)
    urllib.request.urlretrieve(x, name)
    z += 1
#hrm = urllib.request.urlretrieve("ftp://ftp.astrouw.edu.pl/ogle/ogle4/ews/2017/blg-0974.tar.gz", "practice.gz")
</code>```

This piece of code has taken me quite some time to write, as I am not a professional programmer, nor an expert in BeautifulSoup or URL manipulation in any way. In fact, I use MATLAB more than Python. As such, I tend to think in terms of MATLAB, which translates into less efficient Python code. However, efficiency is not what I am searching for in this problem. I can wait the extra five minutes for my code to finish if it means that I understand what is going on and can accomplish what I need to accomplish. Thank you for any help you can offer! I realize this is a fairly muti-faceted problem.

答:
This should do it:

```<code>from urllib.request import urlopen
import urllib.request
from bs4 import BeautifulSoup

#Access website
URL = 'http://ogle.astrouw.edu.pl/ogle4/ews/ews.html'
soup = BeautifulSoup(urlopen(URL), 'html5lib')
</code>```

Here, I'm using the html5lib to parse the url content.

Next, we'll look through the table, extracting links if the star names have a 'N' in them:

```<code>table = soup.find('table')

links = []
for tr in table.find_all('tr', {'class' : 'trow'}):
    td = tr.findChildren()
    if 'N' in td[4].text:
        links.append('http://ogle.astrouw.edu.pl/ogle4/ews/' + td[1].a['href'])

print(links)
</code>```

Output:

```<code>['http://ogle.astrouw.edu.pl/ogle4/ews/blg-0974.html', 'http://ogle.astrouw.edu.pl/ogle4/ews/blg-0975.html', 'http://ogle.astrouw.edu.pl/ogle4/ews/blg-0976.html', 'http://ogle.astrouw.edu.pl/ogle4/ews/blg-0977.html', 'http://ogle.astrouw.edu.pl/ogle4/ews/blg-0978.html',
...
]
</code>```

Body:
I have a BeautifulSoup problem that hopefully you can help me out with.

Currently, I have a website with a lot of links on it. The links lead to pages that contain the data of that item that is linked. If you want to check it out, it's this one: http://ogle.astrouw.edu.pl/ogle4/ews/ews.html. What I ultimately want to accomplish is to print out the links of the data that are labeled with an 'N'. It may not be apparent at first, but if you look closely on the website, some of the data have 'N' after their Star No, and others do not. Afterwards, I use that link to download a file containing the information I need on that data. The website is very convenient because the download URLs only change a bit from data to data, so I only need to change a part of the URL, as you'll see in the code below.

I currently have accomplished the data downloading part. However, this is where you come in. Currently, I need to put in the identification number of the BLG event that I desire. (This will become apparent after you view the code below.) However, the website is consistently updating over time, and having to manually search for 'N' events takes up unnecessary time. I want the Python code to be able to do it for me. My original thoughts on the subject were that I could have BeautifulSoup search through the text for all N's, but I ran into some issues on accomplishing that. I feel like I am not familiar enough with BeautifulSoup to get done what I wish to get done. Some help would be appreciated.

The code I have currently is below. I have put in a range of BLG events that have the 'N' label as an example.

#Retrieve .gz files from URLs

from urllib.request import urlopen
import urllib.request
from bs4 import BeautifulSoup

#Access website
URL = 'http://ogle.astrouw.edu.pl/ogle4/ews/ews.html'
soup = BeautifulSoup(urlopen(URL))

#Select the desired data numbers
numbers = list(range(974,998))
x=0
for i in numbers:
    numbers[x] = str(i)
    x += 1
print(numbers)

#Get all links and put into list
allLinks = []
for link in soup.find_all('a'):
    list_links = link.get('href')
    allLinks.append(list_links)

#Remove None datatypes from link list
while None in allLinks:
    allLinks.remove(None)
#print(allLinks)

#Remove all links but links to data pages and gets rid of the '.html'
list_Bindices = [i for i, s in enumerate(allLinks) if 'b' in s]
print(list_Bindices)
bLinks = []
for x in list_Bindices:
    bLinks.append(allLinks[x])
bLinks = [s.replace('.html', '') for s in bLinks]
#print(bLinks)

#Create a list of indices for accessing those pages
list_Nindices = []
for x in numbers:
    list_Nindices.append([i for i, s in enumerate(bLinks) if x in s])
#print(type(list_Nindices))
#print(list_Nindices)

nindices_corrected = []
place = 0
while place < (len(list_Nindices)):
    a = list_Nindices[place]
    nindices_corrected.append(a[0])
    place = place + 1
#print(nindices_corrected)

#Get the page names (without the .html) from the indices
nLinks = []
for x in nindices_corrected:
    nLinks.append(bLinks[x])
#print(nLinks)

#Form the URLs for those pages
final_URLs = []
for x in nLinks:
    y = "ftp://ftp.astrouw.edu.pl/ogle/ogle4/ews/2017/"+ x + "/phot.dat"
    final_URLs.append(y)
#print(final_URLs)
#Retrieve the data from the URLs
z = 0
for x in final_URLs:
    name = nLinks[z] + ".dat"
    #print(name)
    urllib.request.urlretrieve(x, name)
    z += 1
#hrm = urllib.request.urlretrieve("ftp://ftp.astrouw.edu.pl/ogle/ogle4/ews/2017/blg-0974.tar.gz", "practice.gz")

This piece of code has taken me quite some time to write, as I am not a professional programmer, nor an expert in BeautifulSoup or URL manipulation in any way. In fact, I use MATLAB more than Python. As such, I tend to think in terms of MATLAB, which translates into less efficient Python code. However, efficiency is not what I am searching for in this problem. I can wait the extra five minutes for my code to finish if it means that I understand what is going on and can accomplish what I need to accomplish. Thank you for any help you can offer! I realize this is a fairly muti-faceted problem.

Body:
This should do it:

from urllib.request import urlopen
import urllib.request
from bs4 import BeautifulSoup

#Access website
URL = 'http://ogle.astrouw.edu.pl/ogle4/ews/ews.html'
soup = BeautifulSoup(urlopen(URL), 'html5lib')

Here, I'm using the html5lib to parse the url content.

Next, we'll look through the table, extracting links if the star names have a 'N' in them:

table = soup.find('table')

links = []
for tr in table.find_all('tr', {'class' : 'trow'}):
    td = tr.findChildren()
    if 'N' in td[4].text:
        links.append('http://ogle.astrouw.edu.pl/ogle4/ews/' + td[1].a['href'])

print(links)

Output:

['http://ogle.astrouw.edu.pl/ogle4/ews/blg-0974.html', 'http://ogle.astrouw.edu.pl/ogle4/ews/blg-0975.html', 'http://ogle.astrouw.edu.pl/ogle4/ews/blg-0976.html', 'http://ogle.astrouw.edu.pl/ogle4/ews/blg-0977.html', 'http://ogle.astrouw.edu.pl/ogle4/ews/blg-0978.html',
...
]


问:
Solr: getting error on url field while updating
I am trying to update url fields of my Solr documents but i am getting below error

HTTP Error 400: Bad Request

I think it is because of a url field

```<code>image_new_path = https://aaa.com/bbb/posts/post_fta6cueqq1497926075564.jpeg
req = urllib2.Request(url=solrPath + '/update/json?commit=true', data='[{"id":"' + docs['id'] + '","image":{"set":'+image_new_path+'}}]')
</code>```

Is there are some special character which i have to change? If yes which one and how?

Solr error:

```<code>RequestHandlerBase

org.apache.solr.common.SolrException: Cannot parse provided JSON: Expected ',' or '}': char=:,position=41 BEFORE='[{"id":"189","image":{"set":https:' AFTER='//aaa.com/bbb/user'
</code>```

答:
The problem is ":" i have to add '\' before ':' to make it work. So now image path becomes </p>

```<code>https\://aaa/bbb
</code>```

Body:
I am trying to update url fields of my Solr documents but i am getting below error

HTTP Error 400: Bad Request

I think it is because of a url field

image_new_path = https://aaa.com/bbb/posts/post_fta6cueqq1497926075564.jpeg
req = urllib2.Request(url=solrPath + '/update/json?commit=true', data='[{"id":"' + docs['id'] + '","image":{"set":'+image_new_path+'}}]')

Is there are some special character which i have to change? If yes which one and how?

Solr error:

RequestHandlerBase

org.apache.solr.common.SolrException: Cannot parse provided JSON: Expected ',' or '}': char=:,position=41 BEFORE='[{"id":"189","image":{"set":https:' AFTER='//aaa.com/bbb/user'

Body:
The problem is ":" i have to add '\' before ':' to make it work. So now image path becomes

https\://aaa/bbb


问:
How to prevent absolutely positioned child to being cropped by overflow hidden div?
I want to be able to show all the contents of the divBox, but it has to be inside divBtoConteudo1_2, as I have to make a reference to its position, in order to determine the right placement. The problem is the top layer, which is set to overflow: hidden, and it's not allowing to display the content.

      Box images.

```

I've researched a bit for this solution, but couldn't find anything that would work. And in some posts, it said even that it couldn't be done.

Is there any solution for this, even if I have to use some jQuery? It would be great if I only had to do some changes on the divBox, in order for it to work.

答: do you try setting the style to style="visibility:hidden" or to style="display:none"</p>

Body:
I want to be able to show all the contents of the divBox, but it has to be inside divBtoConteudo1_2, as I have to make a reference to its position, in order to determine the right placement. The problem is the top layer, which is set to overflow: hidden, and it's not allowing to display the content.

      Box images.

I've researched a bit for this solution, but couldn't find anything that would work. And in some posts, it said even that it couldn't be done.

Is there any solution for this, even if I have to use some jQuery? It would be great if I only had to do some changes on the divBox, in order for it to work.


问:
Manipulate values in pandas DataFrame columns based on matching IDs from another DataFrame
I have two dataframes like the following examples:

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame({'a': ['20', '50', '100'], 'b': [1, np.nan, 1],
                 'c': [np.nan, 1, 1]})
df_id = pd.DataFrame({'b': ['50', '4954', '93920', '20'],
                      'c': ['123', '100', '6', np.nan]})

print(df)
     a    b    c
0   20  1.0  NaN
1   50  NaN  1.0
2  100  1.0  1.0

print(df_id)
       b    c
0     50  123
1   4954  100
2  93920    6
3     20  NaN
</code>```

For each identifier in df['a'], I want to null the value in df['b'] if there is no matching identifier in any row in df_id['b']. I want to do the same for column df['c'].

My desired result is as follows:

```<code>result = pd.DataFrame({'a': ['20', '50', '100'], 'b': [1, np.nan, np.nan],
                 'c': [np.nan, np.nan, 1]})
print(result)
     a    b    c
0   20  1.0  NaN
1   50  NaN  NaN    # df_id['c'] did not contain '50'
2  100  NaN  1.0    # df_id['b'] did not contain '100'
</code>```

My attempt to do this is here:

```<code>for i, letter in enumerate(['b','c']):
    df[letter] = (df.apply(lambda x: x[letter] if x['a']
                   .isin(df_id[letter].tolist()) else np.nan, axis = 1))
</code>```

The error I get:

```<code>AttributeError: ("'str' object has no attribute 'isin'", 'occurred at index 0')
</code>```

This is in Python 3.5.2, Pandas version 20.1

答:
If you have a bigger Dataframe and performance is important to you, you can first build a mask df and then apply it to your dataframe.
First create the mask:

```<code>mask = df_id.apply(lambda x: df['a'].isin(x))
       b      c
0   True  False
1   True  False
2  False   True
</code>```

This can be applied to the original dataframe:

```<code>df.iloc[:,1:] = df.iloc[:,1:].mask(~mask, np.nan)
     a    b    c
0   20  1.0  NaN
1   50  NaN  NaN
2  100  NaN  1.0
</code>```

Body:
I have two dataframes like the following examples:

import pandas as pd
import numpy as np

df = pd.DataFrame({'a': ['20', '50', '100'], 'b': [1, np.nan, 1],
                 'c': [np.nan, 1, 1]})
df_id = pd.DataFrame({'b': ['50', '4954', '93920', '20'],
                      'c': ['123', '100', '6', np.nan]})

print(df)
     a    b    c
0   20  1.0  NaN
1   50  NaN  1.0
2  100  1.0  1.0

print(df_id)
       b    c
0     50  123
1   4954  100
2  93920    6
3     20  NaN

For each identifier in df['a'], I want to null the value in df['b'] if there is no matching identifier in any row in df_id['b']. I want to do the same for column df['c'].

My desired result is as follows:

result = pd.DataFrame({'a': ['20', '50', '100'], 'b': [1, np.nan, np.nan],
                 'c': [np.nan, np.nan, 1]})
print(result)
     a    b    c
0   20  1.0  NaN
1   50  NaN  NaN    # df_id['c'] did not contain '50'
2  100  NaN  1.0    # df_id['b'] did not contain '100'

My attempt to do this is here:

for i, letter in enumerate(['b','c']):
    df[letter] = (df.apply(lambda x: x[letter] if x['a']
                   .isin(df_id[letter].tolist()) else np.nan, axis = 1))

The error I get:

AttributeError: ("'str' object has no attribute 'isin'", 'occurred at index 0')

This is in Python 3.5.2, Pandas version 20.1

Body:
If you have a bigger Dataframe and performance is important to you, you can first build a mask df and then apply it to your dataframe.
First create the mask:

mask = df_id.apply(lambda x: df['a'].isin(x))
       b      c
0   True  False
1   True  False
2  False   True

This can be applied to the original dataframe:

df.iloc[:,1:] = df.iloc[:,1:].mask(~mask, np.nan)
     a    b    c
0   20  1.0  NaN
1   50  NaN  NaN
2  100  NaN  1.0


问:
tqdm variations in different python enviroments
I'm working with tqdm package that presents progress bar in python.

tqdm has also a widget for Jupyter notebooks (tqdm_notebook()), allowing a pretty "web-ish" progress bar.

My problem that I have a tqdm progress bar inside a code.py file, that I import into jupyter notebook.

While running the code.py from regular python eviroment (i.e. Ipython, IDLE, shell) I want tqdm to run in normal form:

```<code>from tqdm import tqdm
a = 0
for i in tqdm(range(2000)):
   a+=i
</code>```

but when I import code.py into Jupyter, I want it to use tqdm_notebook():

```<code>from tqdm import tqdm_notebook as tqdm
a = 0
for i in tqdm(range(2000)):
   a+=i
</code>```

How can I make python distinguish between the environments?

I found this post that suggest to check get_ipython().__class__.__name__ or 'ipykernel' in sys.modules
 but it doesn't distinguish between the notebook and other Ipython shells (such as in Spyder or IDLE).

答:
Apparently, using sys.argv can help here.

```<code>import sys
print sys.argv
</code>```

Running this code in Jupyter will have this arguments:

```<code>['C:\\Users\\...\\lib\\site-packages\\ipykernel\\__main__.py',
 '-f',
 'C:\\Users\\...\\jupyter\\runtime\\kernel-###.json']
</code>```

While of course running from shell/IDLE won't have the jupyter line.

Therefore the import statement in code.py should be:

```<code>if any('jupyter' in arg for arg in sys.argv):
    from tqdm import tqdm_notebook as tqdm
else:
   from tqdm import tqdm
</code>```

Body:
I'm working with tqdm package that presents progress bar in python.

tqdm has also a widget for Jupyter notebooks (tqdm_notebook()), allowing a pretty "web-ish" progress bar.

My problem that I have a tqdm progress bar inside a code.py file, that I import into jupyter notebook.

While running the code.py from regular python eviroment (i.e. Ipython, IDLE, shell) I want tqdm to run in normal form:

from tqdm import tqdm
a = 0
for i in tqdm(range(2000)):
   a+=i

but when I import code.py into Jupyter, I want it to use tqdm_notebook():

from tqdm import tqdm_notebook as tqdm
a = 0
for i in tqdm(range(2000)):
   a+=i

How can I make python distinguish between the environments?

I found this post that suggest to check get_ipython().__class__.__name__ or 'ipykernel' in sys.modules
 but it doesn't distinguish between the notebook and other Ipython shells (such as in Spyder or IDLE).

Body:
Apparently, using sys.argv can help here.

import sys
print sys.argv

Running this code in Jupyter will have this arguments:

['C:\\Users\\...\\lib\\site-packages\\ipykernel\\__main__.py',
 '-f',
 'C:\\Users\\...\\jupyter\\runtime\\kernel-###.json']

While of course running from shell/IDLE won't have the jupyter line.

Therefore the import statement in code.py should be:

if any('jupyter' in arg for arg in sys.argv):
    from tqdm import tqdm_notebook as tqdm
else:
   from tqdm import tqdm


问:
open new tab(not link in new tab) in Chrome and focus on it Selenium java
I have the following problem: When I run my code I want to open new tab(not link in new tab) but after I open it I can't focus on it. The focus is still on the old one.
Here is my code:

```<code>    WebDriver driver = new ChromeDriver();

    driver.get("url for the initial tab");

    driver.manage().window().maximize();

    WebDriverWait wait = new WebDriverWait(driver, 15);

    // Open tab for email generation
    String url = "url for tab 2";

    ((JavascriptExecutor) driver).executeScript("window.open(arguments[0])", url);

    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

    String site = driver.getCurrentUrl();

    if(driver.findElements(By.xpath("xpath here")).size() != 0){
        System.out.println("Element is Present");
        }else{
        System.out.println("Element is Absent");
        }
    System.out.println("Current URL:" + site); //I get the initial url.
</code>```

Also after I focus on the new tab how to switch to the old one?
Thanks

答:
Here is the Answer to your Question:

I have used your own code and rewritten it with a few tweaks to work with the WindowHandles using Set from java.util. Now your code opens https://google.com first, prints the Page Title, then opens the URL https://www.facebook.com/ in a new tab shifts its focus to the new tab with the URL https://www.facebook.com/, prints the Page Title and the current URL:

```<code>    import java.util.Iterator;
    import java.util.Set;
    import java.util.concurrent.TimeUnit;
    import org.openqa.selenium.JavascriptExecutor;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;

    public class Q44970997_newTabURL
    {

        public static void main(String[] args)
        {

            String site = null;
            System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
            WebDriver driver = new ChromeDriver();
            driver.get("https://google.com");
            driver.manage().window().maximize();
            System.out.println(driver.getTitle());
            String first_tab = driver.getWindowHandle();
            String url = "https://www.facebook.com/";
            ((JavascriptExecutor) driver).executeScript("window.open(arguments[0])", url);
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            site = driver.getCurrentUrl();
            Set<String> tab_handles = driver.getWindowHandles();
            Iterator<String> itr = tab_handles.iterator();
            while(itr.hasNext())
            {
            String next_tab = itr.next();
            if(!first_tab.equalsIgnoreCase(next_tab))
                {
                    driver.switchTo().window(next_tab);
                    System.out.println(driver.getTitle());
                    site = driver.getCurrentUrl();
                    System.out.println("Current URL:" + site); //You get the new url.
                }
            }

        }

    }
</code>```

Let me know if this Answers your Question.

Body:
I have the following problem: When I run my code I want to open new tab(not link in new tab) but after I open it I can't focus on it. The focus is still on the old one.
Here is my code:

    WebDriver driver = new ChromeDriver();

    driver.get("url for the initial tab");

    driver.manage().window().maximize();

    WebDriverWait wait = new WebDriverWait(driver, 15);

    // Open tab for email generation
    String url = "url for tab 2";

    ((JavascriptExecutor) driver).executeScript("window.open(arguments[0])", url);

    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

    String site = driver.getCurrentUrl();

    if(driver.findElements(By.xpath("xpath here")).size() != 0){
        System.out.println("Element is Present");
        }else{
        System.out.println("Element is Absent");
        }
    System.out.println("Current URL:" + site); //I get the initial url.

Also after I focus on the new tab how to switch to the old one?
Thanks

Body:
Here is the Answer to your Question:

I have used your own code and rewritten it with a few tweaks to work with the WindowHandles using Set from java.util. Now your code opens https://google.com first, prints the Page Title, then opens the URL https://www.facebook.com/ in a new tab shifts its focus to the new tab with the URL https://www.facebook.com/, prints the Page Title and the current URL:

    import java.util.Iterator;
    import java.util.Set;
    import java.util.concurrent.TimeUnit;
    import org.openqa.selenium.JavascriptExecutor;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;

    public class Q44970997_newTabURL
    {

        public static void main(String[] args)
        {

            String site = null;
            System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
            WebDriver driver = new ChromeDriver();
            driver.get("https://google.com");
            driver.manage().window().maximize();
            System.out.println(driver.getTitle());
            String first_tab = driver.getWindowHandle();
            String url = "https://www.facebook.com/";
            ((JavascriptExecutor) driver).executeScript("window.open(arguments[0])", url);
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            site = driver.getCurrentUrl();
            Set<String> tab_handles = driver.getWindowHandles();
            Iterator<String> itr = tab_handles.iterator();
            while(itr.hasNext())
            {
            String next_tab = itr.next();
            if(!first_tab.equalsIgnoreCase(next_tab))
                {
                    driver.switchTo().window(next_tab);
                    System.out.println(driver.getTitle());
                    site = driver.getCurrentUrl();
                    System.out.println("Current URL:" + site); //You get the new url.
                }
            }

        }

    }

Let me know if this Answers your Question.


问:
AsyncTask and SOAP webservices
I'm new to SOAP webservices and AsyncTask, I'm developing an app which is using SOAP webservices for login.
I tried to do all work in onCreate method but I got android.os.NetworkOnMainThreadException.

So i tried to use AsyncTask,
but I'm not able to get reference to emailText and passwordText in RetrieveFeedTask class.

Here is my code:

```<code>public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private static String SOAP_ACTION = "intentionally hided";
    private static String NAMESPACE = "intentionally hided";
    private static String METHOD_NAME = "intentionally hided";
    private static String URL = "intentionally hided";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        final EditText emailText = (EditText) findViewById(R.id.emailText);
        final EditText passwordText = (EditText) findViewById(R.id.passwordText);
        Button loginButton = (Button) findViewById(R.id.button_login);

        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new RetrieveFeedTask().execute();

            }
        });
    }

    class RetrieveFeedTask extends AsyncTask<String, String, String> {

        protected String doInBackground(String... urls) {

            SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

            request.addProperty("userName", emailText.getText().toString());
            request.addProperty("userPassword", passwordText.getText().toString());

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

            envelope.setOutputSoapObject(request);
            envelope.dotNet = true;

            try {
                HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

                androidHttpTransport.call(SOAP_ACTION, envelope);

                SoapObject result = (SoapObject) envelope.bodyIn;
                if (result != null) {
                    Toast.makeText(getApplicationContext(), "Login Successful!", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(), "Login Failed!", Toast.LENGTH_LONG).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
</code>```

答:
You could pass the text value of the views into the constructor of the async task and access them via the inner reference.

```<code>class RetrieveFeedTask extends AsyncTask<String, String, String> {

    private String emailText, passwordText;

    RetrieveFeedTask(String emailText, String passwordText) {
        this.emailText = emailText;
        this.passwordText = passwordText;
    }

    protected String doInBackground(String... urls) {
        ...
    }
}
</code>```

You would then call it like so:

```<code> new RetrieveFeedTask(
        emailText.getText().toString(),
        passwordText.getText().toString()
 ).execute();
</code>```

Alternatively, you could pass parameters directly to doInBackground() as an array.

```<code>protected Void doInBackground(String... urls) {
    String email = urls[0];
    String password = urls[1];
    ....
}
</code>```

And then call it like so:

```<code>String[] urls = {
    emailText.getText().toString(),
    passwordText.getText().toString()
};

new RetrieveFeedTask().execute(urls);
</code>```

Title: AsyncTask and SOAP webservices

Body:
I'm new to SOAP webservices and AsyncTask, I'm developing an app which is using SOAP webservices for login.
I tried to do all work in onCreate method but I got android.os.NetworkOnMainThreadException.

So i tried to use AsyncTask,
but I'm not able to get reference to emailText and passwordText in RetrieveFeedTask class.

Here is my code:

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private static String SOAP_ACTION = "intentionally hided";
    private static String NAMESPACE = "intentionally hided";
    private static String METHOD_NAME = "intentionally hided";
    private static String URL = "intentionally hided";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        final EditText emailText = (EditText) findViewById(R.id.emailText);
        final EditText passwordText = (EditText) findViewById(R.id.passwordText);
        Button loginButton = (Button) findViewById(R.id.button_login);

        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new RetrieveFeedTask().execute();

            }
        });
    }

    class RetrieveFeedTask extends AsyncTask<String, String, String> {

        protected String doInBackground(String... urls) {

            SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

            request.addProperty("userName", emailText.getText().toString());
            request.addProperty("userPassword", passwordText.getText().toString());

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

            envelope.setOutputSoapObject(request);
            envelope.dotNet = true;

            try {
                HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

                androidHttpTransport.call(SOAP_ACTION, envelope);

                SoapObject result = (SoapObject) envelope.bodyIn;
                if (result != null) {
                    Toast.makeText(getApplicationContext(), "Login Successful!", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(), "Login Failed!", Toast.LENGTH_LONG).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

Body:
You could pass the text value of the views into the constructor of the async task and access them via the inner reference.

class RetrieveFeedTask extends AsyncTask<String, String, String> {

    private String emailText, passwordText;

    RetrieveFeedTask(String emailText, String passwordText) {
        this.emailText = emailText;
        this.passwordText = passwordText;
    }

    protected String doInBackground(String... urls) {
        ...
    }
}

You would then call it like so:

 new RetrieveFeedTask(
        emailText.getText().toString(),
        passwordText.getText().toString()
 ).execute();

Alternatively, you could pass parameters directly to doInBackground() as an array.

protected Void doInBackground(String... urls) {
    String email = urls[0];
    String password = urls[1];
    ....
}

And then call it like so:

String[] urls = {
    emailText.getText().toString(),
    passwordText.getText().toString()
};

new RetrieveFeedTask().execute(urls);


问:
1004 error for range argument
I have another simple syntax question that I can't quite figure out. I want to change all the cells in a column so they have a bottom border and have a variable to figure out the last night with data on it.

My code is below and I believe the error is how I am trying to define the last cell.

```<code>wsSheet.Range("F11:wsSheet.Cells(LastRowForSig, 6)").Borders(xlEdgeBottom).LineStyle = xlContinuous
</code>```

答:
You should accept E. Trauger's answer, but here is a slight variation</p>

```<code>With wsSheet
    .Range("F11", .Cells(LastRowForSig, 6)).Borders(xlEdgeBottom).LineStyle = xlContinuous
End With
</code>```

Title: 1004 error for range argument

Body:
I have another simple syntax question that I can't quite figure out. I want to change all the cells in a column so they have a bottom border and have a variable to figure out the last night with data on it.

My code is below and I believe the error is how I am trying to define the last cell.

wsSheet.Range("F11:wsSheet.Cells(LastRowForSig, 6)").Borders(xlEdgeBottom).LineStyle = xlContinuous

Body:
You should accept E. Trauger's answer, but here is a slight variation

With wsSheet
    .Range("F11", .Cells(LastRowForSig, 6)).Borders(xlEdgeBottom).LineStyle = xlContinuous
End With


问:
Chrome Custom Tabs not working
I am using the tutorial from CodeLabs and in an attempt to test my authorization at Step 8, I get a log info 06-13 14:15:42.053 3089-3089/com.google.codelabs.appauth I/AppAuth: Unable to bind custom tabs service and as such I am unable to see if this works. Any help to understand why this is happening and how to solve it will be appreciated. Thank you.

答: If Chrome (or any other browser that supports the custom tab service) is not installed on the device, then this error will be displayed. However, this should not prevent authorization from working - AppAuth will fall back to using the system browser if no custom tab provider is available.</p>

Title: Chrome Custom Tabs not working


问:
How Do We Identify the Owner of a Window?
Suppose we have an Android device, and on that device are 1+ apps capable of creating their own floating windows (e.g., hold the SYSTEM_ALERT_WINDOW permission). Plus, of course, there can be other windows that are not necessarily independently floating (Spinner, Dialog, etc. all create their own windows via WindowManager, just for display over an existing activity).

Given that I know from developer tools a pixel coordinate inside a window, how can I determine the process or app that created the window containing that pixel? IOW, how can I find out who to blame for the existence of a given window?

I thought that perhaps adb shell dumpsys window would have that information, but if it does, I'm not seeing it.

Note that I am happy to settle for a solution involving development tools. I would hope that determining this information at runtime would be difficult or impossible without special privileges.

答:
I would hope that determining this information at runtime would be
  difficult or impossible without special privileges

The most recent Android release is heavily locked down to prevent malware spoofing "trusted" applications such as online banking applications.

Even knowing what other processes are running via the /proc filesystem is now restricted, so it seems unlikely you will be able to know pixel ownership without rooting the platform (that would be a back-door to get the same information as /proc would expose about the current foreground process).


问:
C# "Load" an object's property with text from a file during compilation
I want to load text from a file into a property on a class during compilation.

Example -

I have a file called banana.txt, the contents of which I'd like to put into a Banana class during compilation.

```<code>public class Banana
{
     public string Text { get; set; }  //contents of banana.txt goes in here
}
</code>```

How can this be done?

The purpose of this is so every time a Banana object's Text is needed, the file does not have to be read, the text from the file will only have to be read once during compile time.

(NOTE: I must read from the file, not copy the contents into a variable, or resource file. And I realize every Banana object will have the same text.)

答:
If it's alright to load the file content just once at runtime, you may consider using the following code:</p>

```<code>public class Banana
{
    public string Text
    {
        get
        {
            return fileContent;
        }
    }

    private static string fileContent;

    static Banana()
    {
        using (var reader = File.OpenText("banana.txt"))
        {
            fileContent = reader.ReadToEnd();
        }
    }
}
</code>```

Body:
I want to load text from a file into a property on a class during compilation.

Example -

I have a file called banana.txt, the contents of which I'd like to put into a Banana class during compilation.

public class Banana
{
     public string Text { get; set; }  //contents of banana.txt goes in here
}

How can this be done?

The purpose of this is so every time a Banana object's Text is needed, the file does not have to be read, the text from the file will only have to be read once during compile time.

(NOTE: I must read from the file, not copy the contents into a variable, or resource file. And I realize every Banana object will have the same text.)

Body:
If it's alright to load the file content just once at runtime, you may consider using the following code:

public class Banana
{
    public string Text
    {
        get
        {
            return fileContent;
        }
    }

    private static string fileContent;

    static Banana()
    {
        using (var reader = File.OpenText("banana.txt"))
        {
            fileContent = reader.ReadToEnd();
        }
    }
}


问:
Unable to bind 'this' when passing a function as props in React
My Letter component needs to be reused multiple times, with minor changes in what happens in its constructor. My idea was to pass a function as props to Letter, so I can call it in the constructor. However, I'm having a problem with this.

In the code below, when I invoke this.props.setMessage.call(this), this refers to Container and not Letter, and so the state of Letter remains unchanged. I can see that this refers to Container by inserting console.log(this) in the body of the setMessage function in Container.

How do I bind this such that the state of Letter will change when I run this code?

Source:

```<code>export class Container extends React.component {

    ...

    setMessage = () => {
        this.state.message = 'hello';
    }

    render () {
        return (
            <div>
                <Letter setMessage={this.setMessage} />
            </div>
    }
}

export class Letter extends React.component {
    constructor (props) {
        super(props);
        this.props.setMessage.call(this); // doesn't work, 'this' should refer to Letter but refers to Container
    }

    render () {
        ...
    }
}
</code>```

答:
Try    </p>

```<code>export class Container extends React.component {

    ...

    setMessage() {
        this.setState({
            message: 'hello'
        });
    }

    render () {
        return (
            <div>
                <Letter setMessage={this.setMessage} />
            </div>
    }
}

export class Letter extends React.component {
    constructor (props) {
        super(props);
    }

    setMessage() {
        this.props.setMessage();
    }

    render () {
        ...
    }
}
</code>```

<p>"this" binds to the immediate scope when used in arrow functions
Also, prefer to use this.setState over this.state. = ... </p>

Body:
My Letter component needs to be reused multiple times, with minor changes in what happens in its constructor. My idea was to pass a function as props to Letter, so I can call it in the constructor. However, I'm having a problem with this.

In the code below, when I invoke this.props.setMessage.call(this), this refers to Container and not Letter, and so the state of Letter remains unchanged. I can see that this refers to Container by inserting console.log(this) in the body of the setMessage function in Container.

How do I bind this such that the state of Letter will change when I run this code?

Source:

export class Container extends React.component {

    ...

    setMessage = () => {
        this.state.message = 'hello';
    }

    render () {
        return (

                <Letter setMessage={this.setMessage} />

    }
}

export class Letter extends React.component {
    constructor (props) {
        super(props);
        this.props.setMessage.call(this); // doesn't work, 'this' should refer to Letter but refers to Container
    }

    render () {
        ...
    }
}

Body:
Try

export class Container extends React.component {

    ...

    setMessage() {
        this.setState({
            message: 'hello'
        });
    }

    render () {
        return (
            <div>
                <Letter setMessage={this.setMessage} />
            </div>
    }
}

export class Letter extends React.component {
    constructor (props) {
        super(props);
    }

    setMessage() {
        this.props.setMessage();
    }

    render () {
        ...
    }
}

"this" binds to the immediate scope when used in arrow functions
Also, prefer to use this.setState over this.state. = ...