问:
Pandas quirk using sets as data type
I'm trying to augment an existing data frame with a set data type column. I'm iterating over the rows of the data frame and adding to each set, however the update is being applied to every row, i.e.,

```<code>>>> df = pd.DataFrame()
>>> df['foo'] = [set()] * 2
>>> df
  foo
0  {}
1  {}

>>> df.ix[0, 'foo'].update([1, 2, 3])
>>> df
         foo
0  {1, 2, 3}
1  {1, 2, 3}
</code>```

Does anyone know why this may be happening and/or an alternative mechanism for using sets?

答:
I think you can use loc:

```<code>df = pd.DataFrame()
df['foo'] = [set()] * 2
df.loc[0, 'foo'] = set([1, 2, 3])
print (df)
         foo
0  {1, 2, 3}
1         {}
</code>```

Also it works with ix, but deprecated in next version of pandas:

```<code>df.ix[0, 'foo'] = set([1, 2, 3])
print (df)
         foo
0  {1, 2, 3}
1         {}
</code>```

Warning: non-scalar entries aren't really supported by pandas and so you're going to be at risk of unexpected bugs. Sometimes it's useful despite this, but I've actually been bitten by some in the past.

Title: Pandas quirk using sets as data type

Body:
I'm trying to augment an existing data frame with a set data type column. I'm iterating over the rows of the data frame and adding to each set, however the update is being applied to every row, i.e.,

>>> df = pd.DataFrame()
>>> df['foo'] = [set()] * 2
>>> df
  foo
0  {}
1  {}

>>> df.ix[0, 'foo'].update([1, 2, 3])
>>> df
         foo
0  {1, 2, 3}
1  {1, 2, 3}

Does anyone know why this may be happening and/or an alternative mechanism for using sets?

Body:
I think you can use loc:

df = pd.DataFrame()
df['foo'] = [set()] * 2
df.loc[0, 'foo'] = set([1, 2, 3])
print (df)
         foo
0  {1, 2, 3}
1         {}

Also it works with ix, but deprecated in next version of pandas:

df.ix[0, 'foo'] = set([1, 2, 3])
print (df)
         foo
0  {1, 2, 3}
1         {}

Warning: non-scalar entries aren't really supported by pandas and so you're going to be at risk of unexpected bugs. Sometimes it's useful despite this, but I've actually been bitten by some in the past.


来源: stackexchange

问:
Selenium script fails with TestNG annotation
Steps:
1. In eclipse I've created a new project named 'ForSe'.

Under 'src' folder → 'default package' I created a class named Login.java.

My code inside this class is like this:

```<code>public class Login_Valid {
    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver","*my path*");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("*URL of prject ForSe*");
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.findElement(By.xpath("//*@id='email_address']")).sendKeys("*email address*");
        driver.findElement(By.xpath("//*[@id='password']")).sendKeys("*Password*");
        driver.findElement(By.xpath("//*[@id='login-form']/div[4]/button")).click();
    }
}
</code>```

The scripts run very well when I run with run as java application.
But when I use the same script with TestNG, it skips/fails my test.

Steps taken to create TestNG script is as follows:

Installed TestNG and under same src creates a new package named ForSe_TestCases.java

My TestNG scripts is as follows:

```<code>public class ForSe_TestCases
{
    WebDriver driver;
    String url = "*project's URL*";

    @Test (priority = 0)
    public void IO_login(WebDriver driver)
    {

        //ForSe test environment URL
        driver.navigate().to(url);

        //this is official email address of IO
        driver.findElement(By.xpath("//*[@id='email_address']")).sendKeys("*email address*");

        //this is password
        driver.findElement(By.xpath("//*[@id='password']")).sendKeys("*Password*");

        //click on submit button to login
        driver.findElement(By.xpath("//*[@id='login-form']/div[4]/button")).click();
        System.out.println("Login button pressed");
    }

    @BeforeTest
    public void setup()
    {
        // Set property for Chrome
        System.setProperty("webdriver.chrome.driver","*my path*");
        WebDriver driver = new ChromeDriver();

        //apply implicit wait
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        //maximize window
        driver.manage().window().maximize();
    }
}
</code>```

I'm unable to understand at which step I'm going wrong. This the error message I get on running my test by Run as TestNG

```<code>    [Utils] [ERROR] [Error] org.testng.TestNGException:
    Cannot inject @Test annotated Method [IO_login] with [interface org.openqa.selenium.WebDriver].

    ===============================================
    Default test
        Tests run: 1, Failures: 1, Skips: 0
    ===============================================
    ===============================================
    Default suite
    Total tests run: 1, Failures: 1, Skips: 0
    ===============================================
</code>```

答:
Change below line of your code.

from public void IO_login(WebDriver driver) to public void IO_login()

Then try to run your code, it will surely work for you. For more details on this refer this below code.

```<code>public class ForSe_TestCases {

    WebDriver driver;
    String url = "http://google.com";

  @Test (priority = 0)
  public void IO_login()
  {
       driver.navigate().to(url);
       System.out.println("Login Method");
  }

  @BeforeTest
  public void setup()
  {
      System.setProperty("webdriver.chrome.driver", "C:\\Drivers\\chromedriver.exe");
      driver = new ChromeDriver();
      driver.manage().window().maximize();
      driver.manage().timeouts().implicitlyWait(25, TimeUnit.SECONDS);
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Steps:
1. In eclipse I've created a new project named 'ForSe'.

Under 'src' folder → 'default package' I created a class named Login.java.

My code inside this class is like this:

public class Login_Valid {
    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver","*my path*");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("*URL of prject ForSe*");
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.findElement(By.xpath("//*@id='email_address']")).sendKeys("*email address*");
        driver.findElement(By.xpath("//*[@id='password']")).sendKeys("*Password*");
        driver.findElement(By.xpath("//*[@id='login-form']/div[4]/button")).click();
    }
}

The scripts run very well when I run with run as java application.
But when I use the same script with TestNG, it skips/fails my test.

Steps taken to create TestNG script is as follows:

Installed TestNG and under same src creates a new package named ForSe_TestCases.java

My TestNG scripts is as follows:

public class ForSe_TestCases
{
    WebDriver driver;
    String url = "*project's URL*";

    @Test (priority = 0)
    public void IO_login(WebDriver driver)
    {

        //ForSe test environment URL
        driver.navigate().to(url);

        //this is official email address of IO
        driver.findElement(By.xpath("//*[@id='email_address']")).sendKeys("*email address*");

        //this is password
        driver.findElement(By.xpath("//*[@id='password']")).sendKeys("*Password*");

        //click on submit button to login
        driver.findElement(By.xpath("//*[@id='login-form']/div[4]/button")).click();
        System.out.println("Login button pressed");
    }

    @BeforeTest
    public void setup()
    {
        // Set property for Chrome
        System.setProperty("webdriver.chrome.driver","*my path*");
        WebDriver driver = new ChromeDriver();

        //apply implicit wait
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

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

I'm unable to understand at which step I'm going wrong. This the error message I get on running my test by Run as TestNG

    [Utils] [ERROR] [Error] org.testng.TestNGException:
    Cannot inject @Test annotated Method [IO_login] with [interface org.openqa.selenium.WebDriver].

    ===============================================
    Default test
        Tests run: 1, Failures: 1, Skips: 0
    ===============================================
    ===============================================
    Default suite
    Total tests run: 1, Failures: 1, Skips: 0
    ===============================================

Body:
Change below line of your code.

from public void IO_login(WebDriver driver) to public void IO_login()

Then try to run your code, it will surely work for you. For more details on this refer this below code.

public class ForSe_TestCases {

    WebDriver driver;
    String url = "http://google.com";

  @Test (priority = 0)
  public void IO_login()
  {
       driver.navigate().to(url);
       System.out.println("Login Method");
  }

  @BeforeTest
  public void setup()
  {
      System.setProperty("webdriver.chrome.driver", "C:\\Drivers\\chromedriver.exe");
      driver = new ChromeDriver();
      driver.manage().window().maximize();
      driver.manage().timeouts().implicitlyWait(25, TimeUnit.SECONDS);
  }
}


问:
Broadcast receiver for checking internet connection in android app
I am developing an android broadcast receiver for checking internet connection.

The problem is that my broadcast receiver is being called two times. I want it to get called only when the network is available. If it is unavailable, I don't want notified.

This is the broadcast receiver

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

    @Override
    public void onReceive(final Context context, final Intent intent) {
        final ConnectivityManager connMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        final android.net.NetworkInfo wifi = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        final android.net.NetworkInfo mobile = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        if (wifi.isAvailable() || mobile.isAvailable()) {
            // Do something

            Log.d("Network Available ", "Flag No 1");
        }
    }
}
</code>```

This is the manifest.xml

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.broadcastreceiverforinternetconnection"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <receiver android:name=".NetworkChangeReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>
    </application>

</manifest>
</code>```

答:
just for someone else who wanna register a broadcast dynamicly:</p>

```<code>BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (checkWifiConnect()) {
            Log.d(TAG, "wifi has connected");
            // TODO
        }
    }
};

private void registerWifiReceiver() {
    IntentFilter filter = new IntentFilter();
    filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
    filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
    filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    mContext.registerReceiver(mWifiReceiver, filter);
}

private void unregisterWifiReceiver() {
    mContext.unregisterReceiver(mWifiReceiver);
}

private boolean checkWifiConnect() {
    ConnectivityManager manager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = manager.getActiveNetworkInfo();
    if (networkInfo != null
            && networkInfo.getType() == ConnectivityManager.TYPE_WIFI
            && networkInfo.isConnected()) {
        return true;
    }
    return false;
}
</code>```

Body:
I am developing an android broadcast receiver for checking internet connection.

The problem is that my broadcast receiver is being called two times. I want it to get called only when the network is available. If it is unavailable, I don't want notified.

This is the broadcast receiver

public class NetworkChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, final Intent intent) {
        final ConnectivityManager connMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        final android.net.NetworkInfo wifi = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        final android.net.NetworkInfo mobile = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        if (wifi.isAvailable() || mobile.isAvailable()) {
            // Do something

            Log.d("Network Available ", "Flag No 1");
        }
    }
}

This is the manifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.broadcastreceiverforinternetconnection"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <receiver android:name=".NetworkChangeReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>
    </application>

</manifest>

Body:
just for someone else who wanna register a broadcast dynamicly:

BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (checkWifiConnect()) {
            Log.d(TAG, "wifi has connected");
            // TODO
        }
    }
};

private void registerWifiReceiver() {
    IntentFilter filter = new IntentFilter();
    filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
    filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
    filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    mContext.registerReceiver(mWifiReceiver, filter);
}

private void unregisterWifiReceiver() {
    mContext.unregisterReceiver(mWifiReceiver);
}

private boolean checkWifiConnect() {
    ConnectivityManager manager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = manager.getActiveNetworkInfo();
    if (networkInfo != null
            && networkInfo.getType() == ConnectivityManager.TYPE_WIFI
            && networkInfo.isConnected()) {
        return true;
    }
    return false;
}


问:
How to handle file downloads with JWT based authentication?
I'm writing a webapp in Angular where authentication is handled by a JWT token, meaning that every request has an "Authentication" header with all the necessary information.

This works nicely for REST calls, but I don't understand how I should handle download links for files hosted on the backend (the files reside on the same server where the webservices are hosted).

I can't use regular href='...'/> links since they won't carry any header and the authentication will fail. Same for the various incantations of window.open(...).

Some solutions I thought of:

Generate a temporary unsecured download link on the server

Pass the authentication information as an url parameter and manually handle the case

Get the data through XHR and save the file client side.

All of the above are less than satisfactory.

1 is the solution I am using right now. I don't like it for two reasons: first it is not ideal security-wise, second it works but it requires quite a lot of work especially on the server: to download something I need to call a service that generates a new "random" url, stores it somewhere (possibly on the DB) for a some time, and returns it to the client. The client gets the url, and use window.open or similar with it. When requested, the new url should check if it is still valid, and then return the data.

2 seems at least as much work.

3 seems a lot of work, even using available libraries, and lot of potential issues. (I would need to provide my own download status bar, load the whole file in memory and then ask the user to save the file locally).

The task seems a pretty basic one though, so I'm wondering if there is anything much simpler that I can use.

I'm not necessarily looking for a solution "the Angular way". Regular Javascript would be fine.

答:
Here's a way to download it on the client using the download attribute, the fetch API, and URL.createObjectURL. You would fetch the file using your JWT, convert the payload into a blob, put the blob into an objectURL, set the source of an anchor tag to that objectURL, and click that objectURL in javascript.

```<code>let anchor = document.createElement("a");
document.body.appendChild(anchor);
let file = 'https://www.example.com/some-file.pdf';

let headers = new Headers();
headers.append('Authorization', 'Bearer MY-TOKEN');

fetch(file, { headers })
    .then(response => response.blob())
    .then(blobby => {
        let objectUrl = window.URL.createObjectURL(blobby);

        anchor.href = objectUrl;
        anchor.download = 'some-file.pdf';
        anchor.click();

        window.URL.revokeObjectURL(objectUrl);
    });
</code>```

The value of the download attribute will be the eventual file name. If desired, you can mine an intended filename out of the content disposition response header as described in other answers.

Body:
I'm writing a webapp in Angular where authentication is handled by a JWT token, meaning that every request has an "Authentication" header with all the necessary information.

This works nicely for REST calls, but I don't understand how I should handle download links for files hosted on the backend (the files reside on the same server where the webservices are hosted).

I can't use regular  links since they won't carry any header and the authentication will fail. Same for the various incantations of window.open(...).

Some solutions I thought of:

Generate a temporary unsecured download link on the server

Pass the authentication information as an url parameter and manually handle the case

Get the data through XHR and save the file client side.

All of the above are less than satisfactory.

1 is the solution I am using right now. I don't like it for two reasons: first it is not ideal security-wise, second it works but it requires quite a lot of work especially on the server: to download something I need to call a service that generates a new "random" url, stores it somewhere (possibly on the DB) for a some time, and returns it to the client. The client gets the url, and use window.open or similar with it. When requested, the new url should check if it is still valid, and then return the data.

2 seems at least as much work.

3 seems a lot of work, even using available libraries, and lot of potential issues. (I would need to provide my own download status bar, load the whole file in memory and then ask the user to save the file locally).

The task seems a pretty basic one though, so I'm wondering if there is anything much simpler that I can use.

I'm not necessarily looking for a solution "the Angular way". Regular Javascript would be fine.

Body:
Here's a way to download it on the client using the download attribute, the fetch API, and URL.createObjectURL. You would fetch the file using your JWT, convert the payload into a blob, put the blob into an objectURL, set the source of an anchor tag to that objectURL, and click that objectURL in javascript.

let anchor = document.createElement("a");
document.body.appendChild(anchor);
let file = 'https://www.example.com/some-file.pdf';

let headers = new Headers();
headers.append('Authorization', 'Bearer MY-TOKEN');

fetch(file, { headers })
    .then(response => response.blob())
    .then(blobby => {
        let objectUrl = window.URL.createObjectURL(blobby);

        anchor.href = objectUrl;
        anchor.download = 'some-file.pdf';
        anchor.click();

        window.URL.revokeObjectURL(objectUrl);
    });

The value of the download attribute will be the eventual file name. If desired, you can mine an intended filename out of the content disposition response header as described in other answers.

ContentLicense: CC BY-SA 4.0


问:
How to grab json data and store in a database
I am trying to get data from a json and i want to save it in a database.
I got errors, kindly put me through. Below is me code.

```<code><?php

//My connection was ok

//read the json file contents
$url = ('http://api.football-data.org/v1/teams/61/players/');
$jsondata = file_get_contents($url);

//convert json object to php associative array
$data = json_decode($jsondata, true);
//print_r($data);

//get the employee details
foreach ($data['_links']['players'] as $myp) {
    $name = $myp['name'];
    $posi = $myp['position'];
    $nation = $myp['nationality'];
    $market = $myp['marketValue'];
}

//    //insert into mysql table
mysql_select_db($db, $conn); //database and connection

$date = date('Y-m-d H:m:s'); //date stamp formatting
//sql query that insert the user info into the database
$sql = "INSERT INTO player ( Name, Position, Nationality, Market, Created)
        VALUES( ?,?,?,?,?)";
// bind variables to insert query params
    mysqli_stmt_bind_param($sql, 'sss', $name, $posi, $nation, $market, $date);
//if the connection is sucessful, display regards message
if (mysql_query($sql, $conn)) {
    echo "Thank you <br/>";
} else {   //if the connection is not established
    die('Error: ' . mysql_error());
}

mysql_close($conn); //close of process or connection
?>
</code>```

I have tried to first print the values/datas that I want so that am sure the foreach loop is working but I also got errors:

Notice: Undefined index: players in C:\xampp\htdocs\lab4\apitest.php on line 22

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\lab4\apitest.php on line 22

Warning: mysql_select_db() expects parameter 2 to be resource, object given in C:\xampp\htdocs\lab4\apitest.php on line 31

Warning: mysqli_stmt_bind_param() expects parameter 1 to be mysqli_stmt, string given in C:\xampp\htdocs\lab4\apitest.php on line 38

Warning: mysql_query() expects parameter 2 to be resource, object given in C:\xampp\htdocs\lab4\apitest.php on line 40
Error:

Here is my json:

```<code>{

    "_links": {
        "self": {
            "href": "http://api.football-data.org/v1/teams/61/players"
        },
        "team": {
            "href": "http://api.football-data.org/v1/teams/61"
        }
    },
    "count": 25,
    "players": [
        {
            "name": "Marcos Alonso",
            "position": "Left-Back",
            "jerseyNumber": 3,
            "dateOfBirth": "1990-12-28",
            "nationality": "Spain",
            "contractUntil": "2021-06-30",
            "marketValue": "9,000,000 €"
        },
        {
            "name": "Marco van Ginkel",
            "position": "Central Midfield",
            "jerseyNumber": null,
            "dateOfBirth": "1992-12-01",
            "nationality": "Netherlands",
            "contractUntil": "2018-06-30",
            "marketValue": "7,000,000 €"
        },
</code>```

Kindly help me on how to read the wanted data and store in a database successfully.

Many thanks!

答:
try </p>

```<code>foreach ($data['players'] as $myp) {
    $name = $myp['name'];
    $posi = $myp['position'];
    $nation = $myp['nationality'];
    $market = $myp['marketValue'];
}
</code>```

Body:
I am trying to get data from a json and i want to save it in a database.
I got errors, kindly put me through. Below is me code.

<?php

//My connection was ok

//read the json file contents
$url = ('http://api.football-data.org/v1/teams/61/players/');
$jsondata = file_get_contents($url);

//convert json object to php associative array
$data = json_decode($jsondata, true);
//print_r($data);

//get the employee details
foreach ($data['_links']['players'] as $myp) {
    $name = $myp['name'];
    $posi = $myp['position'];
    $nation = $myp['nationality'];
    $market = $myp['marketValue'];
}

//    //insert into mysql table
mysql_select_db($db, $conn); //database and connection

$date = date('Y-m-d H:m:s'); //date stamp formatting
//sql query that insert the user info into the database
$sql = "INSERT INTO player ( Name, Position, Nationality, Market, Created)
        VALUES( ?,?,?,?,?)";
// bind variables to insert query params
    mysqli_stmt_bind_param($sql, 'sss', $name, $posi, $nation, $market, $date);
//if the connection is sucessful, display regards message
if (mysql_query($sql, $conn)) {
    echo "Thank you
";
} else {   //if the connection is not established
    die('Error: ' . mysql_error());
}

mysql_close($conn); //close of process or connection
?>

I have tried to first print the values/datas that I want so that am sure the foreach loop is working but I also got errors:

Notice: Undefined index: players in C:\xampp\htdocs\lab4\apitest.php on line 22

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\lab4\apitest.php on line 22

Warning: mysql_select_db() expects parameter 2 to be resource, object given in C:\xampp\htdocs\lab4\apitest.php on line 31

Warning: mysqli_stmt_bind_param() expects parameter 1 to be mysqli_stmt, string given in C:\xampp\htdocs\lab4\apitest.php on line 38

Warning: mysql_query() expects parameter 2 to be resource, object given in C:\xampp\htdocs\lab4\apitest.php on line 40
Error:

Here is my json:

{

    "_links": {
        "self": {
            "href": "http://api.football-data.org/v1/teams/61/players"
        },
        "team": {
            "href": "http://api.football-data.org/v1/teams/61"
        }
    },
    "count": 25,
    "players": [
        {
            "name": "Marcos Alonso",
            "position": "Left-Back",
            "jerseyNumber": 3,
            "dateOfBirth": "1990-12-28",
            "nationality": "Spain",
            "contractUntil": "2021-06-30",
            "marketValue": "9,000,000 €"
        },
        {
            "name": "Marco van Ginkel",
            "position": "Central Midfield",
            "jerseyNumber": null,
            "dateOfBirth": "1992-12-01",
            "nationality": "Netherlands",
            "contractUntil": "2018-06-30",
            "marketValue": "7,000,000 €"
        },

Kindly help me on how to read the wanted data and store in a database successfully.

Many thanks!

Body:
try

foreach ($data['players'] as $myp) {
    $name = $myp['name'];
    $posi = $myp['position'];
    $nation = $myp['nationality'];
    $market = $myp['marketValue'];
}


问:
IE8: "The system cannot find the path specified" error when acessing window.localStorage
I have some javascript code which accesses window.localStorage, and it's working fine on most machines, but in one of them (IE8 compat view, Windows 7 64) I get the error "The system cannot find the path specified" whenever I try to read window.localStorage. I've tried to find some discussions about it at SO and Google (no cigar) and didn't find any suspicious setting at the browser's options. Has anyone encountered this error, and a solution for it? I could put a try/catch around window.localStorage but I'd rather understand what is going on.</p>

答:
Why do you expect the local storage to work in IE8? IIUC, not even IE9 will support local storage API.

We are talking about HTML5 local storage, right?

ContentLicense: CC BY-SA 2.5


问:
Connected device [OFFLINE] - Session 'app': Error Installing APKs - existing connection was forcibly closed
When I trying to:

RUN > Select Deployment target > Select my Real Android device.

I after build my device disconnect automatically and Device status [OFFLINE]

EVENT LOG HERE:

```<code>2:40 PM Executing tasks: [:app:assembleDebug]

2:41 PM Gradle build finished with 1 warnings(s) in 7s 577ms

2:41 PM An existing connection was forcibly closed by the remote host
                java.io.IOException: An existing connection was forcibly closed by the remote host
                at sun.nio.ch.SocketDispatcher.write0(Native Method)
                at sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:51)
                at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:93)
                at sun.nio.ch.IOUtil.write(IOUtil.java:65)
                at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:471)
                at com.android.ddmlib.AdbHelper.executeRemoteCommand(AdbHelper.java:471)
                at com.android.ddmlib.SplitApkInstaller.uploadApk(SplitApkInstaller.java:152)
                at com.android.ddmlib.SplitApkInstaller.install(SplitApkInstaller.java:78)
                at com.android.ddmlib.Device.installPackages(Device.java:904)
                at com.android.tools.idea.run.tasks.SplitApkDeployTask$SplitApkInstaller.installApp(SplitApkDeployTask.java:117)
                at com.android.tools.idea.run.RetryingInstaller.install(RetryingInstaller.java:86)
                at com.android.tools.idea.run.tasks.SplitApkDeployTask.perform(... (show balloon)

2:41 PM Session 'app': Error Installing APKs
</code>```

And also sometime I found event log like this in Android Studio 2.3:

```<code>2:27 PM IllegalStateException
                Android Studio could not interpret the results of the Gradle build correctly.
                You may be able to recover from this issue by pressing 'Run' or 'Debug' again.
                Please file a bug at b.android.com including this message and your idea.log (Help | Show Log in ..).

    Session 'app': Error Launching activity .
</code>```

Already Tried.

Disable Instant Run feature from settings.

Perform a clean build and run again.

Terminal window = start and stop adb server using this command "adb kill-server" and "adb start-server".

Enable and Disable USB Debugging.

-

Note: If I restart my device and Windows PC then it works but I can't restart every time so any one have better solutions for 'app': Error Installing APKs issues.

答:
Please try with this - ADB Android Device Unauthorized.

This will work for you. if not then let me inform.

Body:
When I trying to:

RUN > Select Deployment target > Select my Real Android device.

I after build my device disconnect automatically and Device status [OFFLINE]

EVENT LOG HERE:

2:40 PM Executing tasks: [:app:assembleDebug]

2:41 PM Gradle build finished with 1 warnings(s) in 7s 577ms

2:41 PM An existing connection was forcibly closed by the remote host
                java.io.IOException: An existing connection was forcibly closed by the remote host
                at sun.nio.ch.SocketDispatcher.write0(Native Method)
                at sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:51)
                at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:93)
                at sun.nio.ch.IOUtil.write(IOUtil.java:65)
                at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:471)
                at com.android.ddmlib.AdbHelper.executeRemoteCommand(AdbHelper.java:471)
                at com.android.ddmlib.SplitApkInstaller.uploadApk(SplitApkInstaller.java:152)
                at com.android.ddmlib.SplitApkInstaller.install(SplitApkInstaller.java:78)
                at com.android.ddmlib.Device.installPackages(Device.java:904)
                at com.android.tools.idea.run.tasks.SplitApkDeployTask$SplitApkInstaller.installApp(SplitApkDeployTask.java:117)
                at com.android.tools.idea.run.RetryingInstaller.install(RetryingInstaller.java:86)
                at com.android.tools.idea.run.tasks.SplitApkDeployTask.perform(... (show balloon)

2:41 PM Session 'app': Error Installing APKs

And also sometime I found event log like this in Android Studio 2.3:

2:27 PM IllegalStateException
                Android Studio could not interpret the results of the Gradle build correctly.
                You may be able to recover from this issue by pressing 'Run' or 'Debug' again.
                Please file a bug at b.android.com including this message and your idea.log (Help | Show Log in ..).

    Session 'app': Error Launching activity .

Already Tried.

Disable Instant Run feature from settings.

Perform a clean build and run again.

Terminal window = start and stop adb server using this command "adb kill-server" and "adb start-server".

Enable and Disable USB Debugging.

-

Note: If I restart my device and Windows PC then it works but I can't restart every time so any one have better solutions for 'app': Error Installing APKs issues.


问:
Use both $ and jquery as variable
In my project every page loads a cdn jquery script. some use $ and some use jquery. and now I have to use my new script file 'myNewScript.js' in every page.

If I write my function like $(function (){}) it gives error on some pages like

$ is not function

and if I write function like this jquery(function (){}) then it also give error on other page like

jquery is not a function.

I want to know can we use both $ and jquery as variable . like in same script file say 'myNewScript.js' I want to write $(function (){}) and jquery(function (){}).

Every thing is dependent on each other so I can't reverse the loading of the script. I can't think of any solution...

答:
Define jQuery locally for yourself by looking for both variables.</p>

```<code>var myJquery = jquery || $;
</code>```

Title: Use both $ and jquery as variable

Body:
Define jQuery locally for yourself by looking for both variables.

var myJquery = jquery || $;


问:
How can I create a table as displayed in the below screen shot
Please help me on how can I create a table as mentioned in the below screen shot

https://i.stack.imgur.com/zgf2Z.png

Thank you in advance!!

    Duration
    Topic

    10 min
     Recap of FY17 CSP Incentives

     20 min
     Partner Incentive Experience Onboarding

     15 min
     Updating Banking Details/Partner Requirements

     10 min
     Understanding MPN IDs

     5 min
     Q&A and Closing Session Survey

```

答:
If you are unfamiliar with HTML, I would recommend you to use this website to generate HTML tables:

http://www.tablesgenerator.com/html_tables


答:
The reason this is happening is because you are using the same copy of set instance at both index:

```<code>df['foo'] = [set()] * 2
</code>```

So, when you try to update, the values are added in both the sets.

Instead, create a different instance:

```<code>df['foo'] = [set() for _ in range(2)]
</code>```

Title: Pandas quirk using sets as data type

Body:
The reason this is happening is because you are using the same copy of set instance at both index:

df['foo'] = [set()] * 2

So, when you try to update, the values are added in both the sets.

Instead, create a different instance:

df['foo'] = [set() for _ in range(2)]


问:
My UIActionSheet isn't clickable, and now I can't do anything
I open a UIActionSheet with [actionSheet openInView:view] ... and it opens in the iPhone simulator.  And you can't click on it.

Any ideas?

答:
You should also check if your view (from which you are showing the actionsheet) is touchable or not means if the view's userinteraction is not disabled. If this is alright then check for Mike Weller's answer.

Hope this helps,
Thanks,

Madhup


问:
tableviewcontroller not working when called from other viewcontroller
I have two tableViewControllers created in storyboard:
categories and stores.
When I select a category, it's supposed to show all stores that are in that category.
(I'm getting stores data from server, but I set a fixed category in the url so it should fetch the same two stores no matter what.)

The weird thing is that when I choose a category, storesController shows up empty,
but if I set it as initial controller, it works.

StoreTableViewController_as_initial.png

StoreTableViewController_from_categories.png

this is how I setup the cells in storeController.

```<code>   - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
StoresCell *cell = [tableView dequeueReusableCellWithIdentifier:@"storetile"];
if(cell == nil){
    cell = [[StoresCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"storetile"];
}

cell.storelabel.text = [[_results objectAtIndex:[indexPath row]]objectForKey:@"name"];
[cell.storelabel sizeToFit];
cell.subtitleOneLabel.text=[[_results objectAtIndex:[indexPath row]]objectForKey:@"neighborhood"];
cell.subtitleTwoLabel.text = [[_results objectAtIndex:[indexPath row]]objectForKey:@"city"];
NSString *distance = [NSString stringWithFormat:@"~%@ km",[[_results objectAtIndex:[indexPath row]]objectForKey:@"distance"]];
cell.distanceLabel.text = distance;
NSString *imgPath = [[_results objectAtIndex:[indexPath row]]objectForKey:@"imgUrl"];
UIImage *thumb = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://andrafterdevelopment.com.br/apps/buscaabc/img/%@",imgPath]]]];

[cell.thumbImage setImage:thumb];
return cell;
}
</code>```

I break at the return, the method is always called but when it's from categoriesController all labels in my cell are nil.

this is how I call storeController from categoriesController

```<code>-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:
    (NSIndexPath *)indexPath{

NSDictionary *item = [_results objectAtIndex:[indexPath row]];
BOOL hasSub = [[item objectForKey:@"hasSub"] boolValue];

    StoreTableViewController *storesTableViewController = [[StoreTableViewController alloc]init];

    //storesTableViewController.title = [item valueForKey:@"name"];
    //storesTableViewController.category = (int)[item valueForKey:@"id"];
    [storesTableViewController.tableView registerClass:[StoresCell class] forCellReuseIdentifier:@"storetile"];
    [self.navigationController pushViewController:storesTableViewController animated:YES];
}
</code>```

I'm guessing this has to do with custom cell or maybe I'm doing it wrong by calling it this way.

答:
I am guessing you have declared _results as a property in StoreTableViewController right?
If so, change your categoriesController method to:

```<code>-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:
    (NSIndexPath *)indexPath{

NSDictionary *item = [_results objectAtIndex:[indexPath row]];
BOOL hasSub = [[item objectForKey:@"hasSub"] boolValue];

    StoreTableViewController *storesTableViewController = [[StoreTableViewController alloc]init];
    storesTableViewController.title = [item valueForKey:@"name"];
    storesTableViewController.category = (int)[item valueForKey:@"id"];

    [self.navigationController pushViewController:storesTableViewController animated:YES];
}
</code>```

And register cell in viewDidLoad.

Body:
I have two tableViewControllers created in storyboard:
categories and stores.
When I select a category, it's supposed to show all stores that are in that category.
(I'm getting stores data from server, but I set a fixed category in the url so it should fetch the same two stores no matter what.)

The weird thing is that when I choose a category, storesController shows up empty,
but if I set it as initial controller, it works.

StoreTableViewController_as_initial.png

StoreTableViewController_from_categories.png

this is how I setup the cells in storeController.

   - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
StoresCell *cell = [tableView dequeueReusableCellWithIdentifier:@"storetile"];
if(cell == nil){
    cell = [[StoresCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"storetile"];
}

cell.storelabel.text = [[_results objectAtIndex:[indexPath row]]objectForKey:@"name"];
[cell.storelabel sizeToFit];
cell.subtitleOneLabel.text=[[_results objectAtIndex:[indexPath row]]objectForKey:@"neighborhood"];
cell.subtitleTwoLabel.text = [[_results objectAtIndex:[indexPath row]]objectForKey:@"city"];
NSString *distance = [NSString stringWithFormat:@"~%@ km",[[_results objectAtIndex:[indexPath row]]objectForKey:@"distance"]];
cell.distanceLabel.text = distance;
NSString *imgPath = [[_results objectAtIndex:[indexPath row]]objectForKey:@"imgUrl"];
UIImage *thumb = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://andrafterdevelopment.com.br/apps/buscaabc/img/%@",imgPath]]]];

[cell.thumbImage setImage:thumb];
return cell;
}

I break at the return, the method is always called but when it's from categoriesController all labels in my cell are nil.

this is how I call storeController from categoriesController

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:
    (NSIndexPath *)indexPath{

NSDictionary *item = [_results objectAtIndex:[indexPath row]];
BOOL hasSub = [[item objectForKey:@"hasSub"] boolValue];

    StoreTableViewController *storesTableViewController = [[StoreTableViewController alloc]init];

    //storesTableViewController.title = [item valueForKey:@"name"];
    //storesTableViewController.category = (int)[item valueForKey:@"id"];
    [storesTableViewController.tableView registerClass:[StoresCell class] forCellReuseIdentifier:@"storetile"];
    [self.navigationController pushViewController:storesTableViewController animated:YES];
}

I'm guessing this has to do with custom cell or maybe I'm doing it wrong by calling it this way.

Body:
I am guessing you have declared _results as a property in StoreTableViewController right?
If so, change your categoriesController method to:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:
    (NSIndexPath *)indexPath{

NSDictionary *item = [_results objectAtIndex:[indexPath row]];
BOOL hasSub = [[item objectForKey:@"hasSub"] boolValue];

    StoreTableViewController *storesTableViewController = [[StoreTableViewController alloc]init];
    storesTableViewController.title = [item valueForKey:@"name"];
    storesTableViewController.category = (int)[item valueForKey:@"id"];

    [self.navigationController pushViewController:storesTableViewController animated:YES];
}

And register cell in viewDidLoad.


问:
Disable & enable Google Play system apps or 3rd Party apps in android
As we known,
On devices running Android 4.0 and higher, you can disable pre-installed Google Play system apps through your device Settings. After a system app has been disabled, it will be hidden on your device.

steps for Disable & enable Google Play system apps

Disable pre-installed system apps

1. Go to your device's Settings menu.

2. Select Apps.

3. Touch the system app you’d like to disable.

4. Select Disable.

Re-enable pre-installed system apps

If you’ve disabled an app and would like to enable it, you can find and re-enable the app using the following steps:

1. Go to Settings on your device.

2. Swipe to view the list of All apps.

3. Scroll to the bottom of the list to view disabled system apps.

4. Touch the system app from the list that you’d like to enable.

5. Select Enable.

Once a system app has been re-enabled, it can be viewed and opened from your main apps screen.

but i want to Disable & enable Google Play system apps & 3rd Party apps in android programmetically.

I have rooted android device .

I want to do this for only rooted device not for non-rooted device.

how I disable  & enable system ? if you have any idea then please tell me.

thanks.

答:
Disable app:

```<code>PackageManager pm = context.getPackageManager();
pm.setApplicationEnabledSetting("disableapp.package", PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 0);
</code>```

Enable app:

```<code>PackageManager pm = context.getPackageManager();
pm.setApplicationEnabledSetting("enableapp.package", PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 0);
</code>```

Of course it need system privilege to do this.

Body:
Disable app:

PackageManager pm = context.getPackageManager();
pm.setApplicationEnabledSetting("disableapp.package", PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 0);

Enable app:

PackageManager pm = context.getPackageManager();
pm.setApplicationEnabledSetting("enableapp.package", PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 0);

Of course it need system privilege to do this.


问:
Hibernate mapping for varchar primary key
I have set primary key as varchar in table. But when I am trying to map this in hibernate I get error as below:

```<code>Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)
</code>```

Hibernate mapping :

```<code>@Id
@Column(name="LOGIN_ID",columnDefinition="VARCHAR")
private String id;
</code>```

How can I map varchar primary key in hibernate?

答:
can you try using

```<code>@Id
@Column(name = "LOGIN_ID", nullable = false, columnDefinition="VARCHAR(64)")
</code>```

also add a constructor to initialize the above instance variable along with a default constructor.

Body:
I have set primary key as varchar in table. But when I am trying to map this in hibernate I get error as below:

Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)

Hibernate mapping :

@Id
@Column(name="LOGIN_ID",columnDefinition="VARCHAR")
private String id;

How can I map varchar primary key in hibernate?

Body:
can you try using

@Id
@Column(name = "LOGIN_ID", nullable = false, columnDefinition="VARCHAR(64)")

also add a constructor to initialize the above instance variable along with a default constructor.


问:
Prevent a build step from failing the build
Is there a way to prevent a build step from failing the overall build?

I have one (sbt) build step that if the tests fail I would like to fail the build, and then another that might exit with a non zero status code, and should only run if the first step was successful, but should not have an impact on the overall build status. Is that at possible?

答: No, TeamCity developers still nto introduced editable conditions for build steps. You can use PowerShell script to run and outbounding status control for you step.</p>


问:
alert controller not displaying in iphone using swift2
in my app i want to use alert controller so am using the following code:

```<code>import UIKit
import CoreLocation
class GPSTrackingManager: NSObject,CLLocationManagerDelegate {
  var locationManager: CLLocationManager!
var seenError : Bool = false

func startTracking() {

    locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()
    locationManager.startUpdatingLocation()
}

func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
    locationManager.stopUpdatingLocation()
    print("error occured:\(error)")

}

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    //println("locations = \(locationManager)")
    let latValue = locationManager.location!.coordinate.latitude
    let lonValue = locationManager.location!.coordinate.longitude

    print(latValue)
    print(lonValue)
    GoogleLat = latValue
    GoogleLong = lonValue
    CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in

        if (error != nil)
        {
            print("Reverse geocoder failed with error" + error!.localizedDescription)
            return
        }

        if placemarks!.count > 0
        {
            let pm = placemarks![0] as CLPlacemark
            self.displayLocationInfo(pm)
        }
        else
        {
            print("Problem with the data received from geocoder")
        }
    })

}
func displayLocationInfo(placemark: CLPlacemark?)
{
    if let containsPlacemark = placemark
    {
            locationManager.stopUpdatingLocation()
            let fourthcity = (containsPlacemark.subAdministrativeArea != nil) ? containsPlacemark.subAdministrativeArea : ""
            let fourthState = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.administrativeArea : ""
            let fourthCountry = (containsPlacemark.country != nil) ? containsPlacemark.country : ""
            print("my Real City = \(fourthcity)")
            let fullName = fourthcity
            let fullNameArr = fullName!.characters.split{$0 == " "}.map(String.init)
            fullNameArr[0]
            print(fullNameArr[0])
            print("myState = \(fourthState)")
            print("myCountry = \(fourthCountry)")
            appDelCityname = fullNameArr[0]
            appDelStateName = fourthState
            appDelCountryName = fourthCountry
            print("AppDelegate City Name = \(appDelCityname)")

    }

}

func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
    switch status {
    case .NotDetermined:
        // If status has not yet been determied, ask for authorization
        manager.requestWhenInUseAuthorization()
        break
    case .AuthorizedWhenInUse:
        // If authorized when in use
        print("AuthorizedWhenInUse")
        manager.startUpdatingLocation()
        break
    case .AuthorizedAlways:
        // If always authorized
        print("AuthorizedAlways")
        manager.startUpdatingLocation()
        break
    case .Denied:
        // If user denied your app access to Location Services, but can grant access from Settings.app
        print("user denied to allow")
          dispatch_async(dispatch_get_main_queue(), {
       NSTimer.scheduledTimerWithTimeInterval(3.0,target: self, selector: #selector(self.DisplayalertToturnonLocation), userInfo: nil, repeats: false)
            })
        break
    default:
        print("user cant allow location service")
        break
    }
}

func DisplayalertToturnonLocation(){

    let alertController = UIAlertController(title: "GPRS is Required", message: "This app requires your location,please turn on your location service or set your address", preferredStyle: .Alert)

    let saveAction = UIAlertAction(title: "Set Address", style: UIAlertActionStyle.Default, handler: {
        alert -> Void in
        self.alertTogetAdrressFromUser()

    })
    alertController.addAction(saveAction)
    let cancelAction = UIAlertAction(title: "Settings", style: UIAlertActionStyle.Default, handler: {
        (action : UIAlertAction!) -> Void in
        UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)

    })
    alertController.addAction(cancelAction)

    let keyWindow = UIApplication.sharedApplication().keyWindow
    let mainController = keyWindow!.rootViewController!
    mainController.presentViewController(alertController, animated: true, completion: nil)

}
}
</code>```

I am calling this function in AppDelegate which executes well in iPad but not in iPhone also it not shows any error or warning and  am feeling too difficult to find what am doing wrong here so any one help me to display alert controller in iPhone.

in AppDelegate:

```<code>var tracking = GPSTrackingManager()

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
 tracking.startTracking()
}
</code>```

答:
in here you need to follow two things . 1. your code is fine you need to show ur alertcontroller using main thread, else find the root wihch one is most top presnt your alert, else check once your current window is visible or not

present  your UIAlertcontroller in Main thread, for e.g

Swift3

```<code> DispatchQueue.main.async {
  self.tracking.DisplayalertToturnonLocation()
    }
</code>```

swift2

```<code>  dispatch_async(dispatch_get_main_queue()) {
    self.tracking.DisplayalertToturnonLocation()
}
</code>```

you get the output as

full code

```<code>class GPSTrackingManager: NSObject {

func DisplayalertToturnonLocation(){

    let alertController = UIAlertController(title: "GPRS is Required", message: "This app requires your location,please turn on your location service or set your address", preferredStyle: .alert)

    let saveAction = UIAlertAction(title: "Set Address", style: UIAlertActionStyle.default, handler: {
        alert -> Void in
      //  self.alertTogetAdrressFromUser()

    })
    alertController.addAction(saveAction)
    let cancelAction = UIAlertAction(title: "Settings", style: UIAlertActionStyle.default, handler: {
        (action : UIAlertAction!) -> Void in
      //  UIApplication.shared.openURL(NSURL(string: UIApplicationOpenSettingsURLString)! as URL)

    })
    alertController.addAction(cancelAction)

    UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true, completion: nil)

}
}
</code>```

Body:
in my app i want to use alert controller so am using the following code:

import UIKit
import CoreLocation
class GPSTrackingManager: NSObject,CLLocationManagerDelegate {
  var locationManager: CLLocationManager!
var seenError : Bool = false

func startTracking() {

    locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()
    locationManager.startUpdatingLocation()
}

func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
    locationManager.stopUpdatingLocation()
    print("error occured:\(error)")

}

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    //println("locations = \(locationManager)")
    let latValue = locationManager.location!.coordinate.latitude
    let lonValue = locationManager.location!.coordinate.longitude

    print(latValue)
    print(lonValue)
    GoogleLat = latValue
    GoogleLong = lonValue
    CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in

        if (error != nil)
        {
            print("Reverse geocoder failed with error" + error!.localizedDescription)
            return
        }

        if placemarks!.count > 0
        {
            let pm = placemarks![0] as CLPlacemark
            self.displayLocationInfo(pm)
        }
        else
        {
            print("Problem with the data received from geocoder")
        }
    })

}
func displayLocationInfo(placemark: CLPlacemark?)
{
    if let containsPlacemark = placemark
    {
            locationManager.stopUpdatingLocation()
            let fourthcity = (containsPlacemark.subAdministrativeArea != nil) ? containsPlacemark.subAdministrativeArea : ""
            let fourthState = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.administrativeArea : ""
            let fourthCountry = (containsPlacemark.country != nil) ? containsPlacemark.country : ""
            print("my Real City = \(fourthcity)")
            let fullName = fourthcity
            let fullNameArr = fullName!.characters.split{$0 == " "}.map(String.init)
            fullNameArr[0]
            print(fullNameArr[0])
            print("myState = \(fourthState)")
            print("myCountry = \(fourthCountry)")
            appDelCityname = fullNameArr[0]
            appDelStateName = fourthState
            appDelCountryName = fourthCountry
            print("AppDelegate City Name = \(appDelCityname)")

    }

}

func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
    switch status {
    case .NotDetermined:
        // If status has not yet been determied, ask for authorization
        manager.requestWhenInUseAuthorization()
        break
    case .AuthorizedWhenInUse:
        // If authorized when in use
        print("AuthorizedWhenInUse")
        manager.startUpdatingLocation()
        break
    case .AuthorizedAlways:
        // If always authorized
        print("AuthorizedAlways")
        manager.startUpdatingLocation()
        break
    case .Denied:
        // If user denied your app access to Location Services, but can grant access from Settings.app
        print("user denied to allow")
          dispatch_async(dispatch_get_main_queue(), {
       NSTimer.scheduledTimerWithTimeInterval(3.0,target: self, selector: #selector(self.DisplayalertToturnonLocation), userInfo: nil, repeats: false)
            })
        break
    default:
        print("user cant allow location service")
        break
    }
}

func DisplayalertToturnonLocation(){

    let alertController = UIAlertController(title: "GPRS is Required", message: "This app requires your location,please turn on your location service or set your address", preferredStyle: .Alert)

    let saveAction = UIAlertAction(title: "Set Address", style: UIAlertActionStyle.Default, handler: {
        alert -> Void in
        self.alertTogetAdrressFromUser()

    })
    alertController.addAction(saveAction)
    let cancelAction = UIAlertAction(title: "Settings", style: UIAlertActionStyle.Default, handler: {
        (action : UIAlertAction!) -> Void in
        UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)

    })
    alertController.addAction(cancelAction)

    let keyWindow = UIApplication.sharedApplication().keyWindow
    let mainController = keyWindow!.rootViewController!
    mainController.presentViewController(alertController, animated: true, completion: nil)

}
}

I am calling this function in AppDelegate which executes well in iPad but not in iPhone also it not shows any error or warning and  am feeling too difficult to find what am doing wrong here so any one help me to display alert controller in iPhone.

in AppDelegate:

var tracking = GPSTrackingManager()

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
 tracking.startTracking()
}

Body:
in here you need to follow two things . 1. your code is fine you need to show ur alertcontroller using main thread, else find the root wihch one is most top presnt your alert, else check once your current window is visible or not

present  your UIAlertcontroller in Main thread, for e.g

Swift3

 DispatchQueue.main.async {
  self.tracking.DisplayalertToturnonLocation()
    }

swift2

  dispatch_async(dispatch_get_main_queue()) {
    self.tracking.DisplayalertToturnonLocation()
}

you get the output as

full code

class GPSTrackingManager: NSObject {

func DisplayalertToturnonLocation(){

    let alertController = UIAlertController(title: "GPRS is Required", message: "This app requires your location,please turn on your location service or set your address", preferredStyle: .alert)

    let saveAction = UIAlertAction(title: "Set Address", style: UIAlertActionStyle.default, handler: {
        alert -> Void in
      //  self.alertTogetAdrressFromUser()

    })
    alertController.addAction(saveAction)
    let cancelAction = UIAlertAction(title: "Settings", style: UIAlertActionStyle.default, handler: {
        (action : UIAlertAction!) -> Void in
      //  UIApplication.shared.openURL(NSURL(string: UIApplicationOpenSettingsURLString)! as URL)

    })
    alertController.addAction(cancelAction)

    UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true, completion: nil)

}
}


问:
Could not connect to MySQL in PHP
I have newly purchased server, on that server database connections are not working.

```<code><?php
    error_reporting(E_ALL);
    $server   = "server name";
    $user     = "username";
    $password = "password";
    $db       = "test";
    echo "Before";
    $con = mysql_connect($server, $user, $password);
    echo "After";
    if (!$con){
        die('Could not connect:' . mysql_error());
    }
    mysql_select_db($db, $con);
?>
</code>```

When run this file its print Before text but not print After text.

答:
Currently you can use the following code:

```<code>ini_set("error_reporting", E_ALL & ~E_DEPRECATED);
</code>```

Using this you can get either deprecated or not.

FYI: The mysql_* functions have been removed in PHP7.x. There are two modules you can use.

The first is MySQLi, just use the code as follows:

```<code><?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
?>
</code>```

You can also use PDO using code :

```<code><?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
    $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }
?>
</code>```

Title: Could not connect to MySQL in PHP

Body:
I have newly purchased server, on that server database connections are not working.

<?php
    error_reporting(E_ALL);
    $server   = "server name";
    $user     = "username";
    $password = "password";
    $db       = "test";
    echo "Before";
    $con = mysql_connect($server, $user, $password);
    echo "After";
    if (!$con){
        die('Could not connect:' . mysql_error());
    }
    mysql_select_db($db, $con);
?>

When run this file its print Before text but not print After text.

Body:
Currently you can use the following code:

ini_set("error_reporting", E_ALL & ~E_DEPRECATED);

Using this you can get either deprecated or not.

FYI: The mysql_* functions have been removed in PHP7.x. There are two modules you can use.

The first is MySQLi, just use the code as follows:

<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
?>

You can also use PDO using code :

<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
    $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }
?>


问:
Prestashop Geoip module - missing country
No matter how I try I can't find Germany under GeoIP module list in Prestashop 1.6.1.7.
Country is turned on in Localization-> Countries.
I have uploaded newest GeoLiteCity.dat but that hasn't solved the problem.
Any ideas where to look?</p>

答:
You may have deleted 'Germany' from the countries list on your PrestaShop, you can add it manually under Localization -> Countries in the back office.

Click on 'Add new country' button in the top right corner to open the add new country form and use data in the attached image to fill the form.


答:
By Using Colspan property you can do this</p>

```<code><table>
  <tr>
    <th colspan="2">COlumn</th>
  </tr>
  <tr>
    <td>Column A</td>
    <td>Column B</td>
  </tr>
</table>
</code>```

Title: How can I create a table as displayed in the below screen shot

Body:
Please help me on how can I create a table as mentioned in the below screen shot

https://i.stack.imgur.com/zgf2Z.png

Thank you in advance!!

    Duration
    Topic

    10 min
     Recap of FY17 CSP Incentives

     20 min
     Partner Incentive Experience Onboarding

     15 min
     Updating Banking Details/Partner Requirements

     10 min
     Understanding MPN IDs

     5 min
     Q&A and Closing Session Survey

Body:
By Using Colspan property you can do this

<table>
  <tr>
    <th colspan="2">COlumn</th>
  </tr>
  <tr>
    <td>Column A</td>
    <td>Column B</td>
  </tr>
</table>


问:
Difference between 'related_name' and 'related_query_name' attributes in Django?
Can you explain the difference between related_name and related_query_name attributes for the Field object in Django ? When I use them, How to use them? Thanks!

答:
related_name will be the attribute of the related object that allows you to go 'backwards' to the model with the foreign key on it. For example, if ModelA has a field like: model_b = ForeignKeyField(ModelB, related_name='model_as'), this would enable you to access the ModelA instances that are related to your ModelB instance by going model_b_instance.model_as.all(). Note that this is generally written with a plural for a Foreign Key, because a foreign key is a one to many relationship, and the many side of that equation is the model with the Foreign Key field declared on it.

The further explanation linked to in the docs is helpful. https://docs.djangoproject.com/en/dev/topics/db/queries/#backwards-related-objects

related_query_name is for use in Django querysets. It allows you to filter on the reverse relationship of a foreign key related field. To continue our example - having a field on Model A like:
model_b = ForeignKeyField(ModelB, related_query_name='model_a') would enable you to use model_a as a lookup parameter in a queryset, like: ModelB.objects.filter(model_a=whatever). It is more common to use a singular form for the related_query_name. As the docs say, it isn't necessary to specify both (or either of) related_name and related_query_name. Django has sensible defaults.


问:
What does csr_matrix.sort_indices do?
I make a csr_matrix in the following way:

```<code>>>> A = sparse.csr_matrix([[0, 1, 0],
                           [1, 0, 1],
                           [0, 1, 0]])
>>> A[2,:] = np.array([-1, -2, -3])

>>> A.indptr
Out[12]: array([0, 1, 3, 6], dtype=int32)
>>> A.indices
Out[13]: array([1, 0, 2, 0, 2, 1], dtype=int32)
>>> A.data
Out[14]: array([ 1,  1,  1, -1, -3, -2], dtype=int64)
</code>```

Now I want to interchange the last two elements in the indices and data arrays, so I try:

```<code>>>> A.sort_indices()
</code>```

This does not do anything to my matrix however. The manual for this function only states that it sorts the indices.

What does this function do? In which condition can you see a difference?

How can I sort the indices and data arrays, such that for each row the indices are sorted?

答:
As stated in the document, A.sort_indices() sorts the indices in-place. But there is a cache: if A.has_sorted_indices is True, it won't do anything (the cache was introduced at 0.7.0).

So, in order to see a difference, you need to manually set A.has_sorted_indices to False.

```<code>>>> A.has_sorted_indices, A.indices
(True, array([1, 0, 2, 0, 2, 1], dtype=int32))
>>> A.sort_indices()
>>> A.has_sorted_indices, A.indices
(True, array([1, 0, 2, 0, 2, 1], dtype=int32))
>>> A.has_sorted_indices = False
>>> A.sort_indices()
>>> A.has_sorted_indices, A.indices
(True, array([1, 0, 2, 0, 1, 2], dtype=int32))
</code>```

Note that, unlike what OP has indicated, as of SciPy 0.19.0 running A[2, :] = [-1, -2, -3] no longer produces an out-of-order index (this should have been fixed in 0.14.0). On the other hand, this operation produces a warning:

SparseEfficiencyWarning: Changing the sparsity structure of a csr_matrix is expensive. lil_matrix is more efficient.

Anyway, we could easily produce out-of-order index in other ways, e.g. by matrix multiplication:

```<code>>>> B = scipy.sparse.csr_matrix([[0, 1, 0], [1, 0, 1], [0, 1, 0]])
>>> C = B*B
>>> C.has_sorted_indices, C.indices
(0, array([2, 0, 1, 2, 0], dtype=int32))
>>> C.sort_indices()
>>> C.has_sorted_indices, C.indices
(True, array([0, 2, 1, 0, 2], dtype=int32))
</code>```

Title: What does csr_matrix.sort_indices do?

Body:
I make a csr_matrix in the following way:

>>> A = sparse.csr_matrix([[0, 1, 0],
                           [1, 0, 1],
                           [0, 1, 0]])
>>> A[2,:] = np.array([-1, -2, -3])

>>> A.indptr
Out[12]: array([0, 1, 3, 6], dtype=int32)
>>> A.indices
Out[13]: array([1, 0, 2, 0, 2, 1], dtype=int32)
>>> A.data
Out[14]: array([ 1,  1,  1, -1, -3, -2], dtype=int64)

Now I want to interchange the last two elements in the indices and data arrays, so I try:

>>> A.sort_indices()

This does not do anything to my matrix however. The manual for this function only states that it sorts the indices.

What does this function do? In which condition can you see a difference?

How can I sort the indices and data arrays, such that for each row the indices are sorted?

Body:
As stated in the document, A.sort_indices() sorts the indices in-place. But there is a cache: if A.has_sorted_indices is True, it won't do anything (the cache was introduced at 0.7.0).

So, in order to see a difference, you need to manually set A.has_sorted_indices to False.

>>> A.has_sorted_indices, A.indices
(True, array([1, 0, 2, 0, 2, 1], dtype=int32))
>>> A.sort_indices()
>>> A.has_sorted_indices, A.indices
(True, array([1, 0, 2, 0, 2, 1], dtype=int32))
>>> A.has_sorted_indices = False
>>> A.sort_indices()
>>> A.has_sorted_indices, A.indices
(True, array([1, 0, 2, 0, 1, 2], dtype=int32))

Note that, unlike what OP has indicated, as of SciPy 0.19.0 running A[2, :] = [-1, -2, -3] no longer produces an out-of-order index (this should have been fixed in 0.14.0). On the other hand, this operation produces a warning:

SparseEfficiencyWarning: Changing the sparsity structure of a csr_matrix is expensive. lil_matrix is more efficient.

Anyway, we could easily produce out-of-order index in other ways, e.g. by matrix multiplication:

>>> B = scipy.sparse.csr_matrix([[0, 1, 0], [1, 0, 1], [0, 1, 0]])
>>> C = B*B
>>> C.has_sorted_indices, C.indices
(0, array([2, 0, 1, 2, 0], dtype=int32))
>>> C.sort_indices()
>>> C.has_sorted_indices, C.indices
(True, array([0, 2, 1, 0, 2], dtype=int32))


问:
how to show multidimentional array result using foreach loop in php
```<code>Array
(
    [result] => Array
        (
            [0] => stdClass Object
                (
                    [uniq_id] => 00fdc23c151ad0044d60
                )

            [1] => stdClass Object
                (
                    [uniq_id] => 590dde424e
                )

            [2] => stdClass Object
                (
                    [uniq_id] => 6f0eb3bb34
                )

            [3] => stdClass Object
                (
                    [uniq_id] => eeb6c63929
                )

            [4] => stdClass Object
                (
                    [uniq_id] => a72034387e
                )
                     }
}
</code>```

But I want only   multiple uniq_id  one by one in foreach loop

like

```<code>00fdc23c151ad0044d60

590dde424e

6f0eb3bb34

eeb6c63929

a72034387e
</code>```

答:
Its a stdClass Object array, so try this:

```<code>foreach($yourArray['result'] as $data)
{
    echo $date->uniq_id.'<br>';
}
</code>```

Note: stdClass Object properties can be accessed using ->

Body:
Array
(
    [result] => Array
        (
            [0] => stdClass Object
                (
                    [uniq_id] => 00fdc23c151ad0044d60
                )

            [1] => stdClass Object
                (
                    [uniq_id] => 590dde424e
                )

            [2] => stdClass Object
                (
                    [uniq_id] => 6f0eb3bb34
                )

            [3] => stdClass Object
                (
                    [uniq_id] => eeb6c63929
                )

            [4] => stdClass Object
                (
                    [uniq_id] => a72034387e
                )
                     }
}

But I want only   multiple uniq_id  one by one in foreach loop

like

00fdc23c151ad0044d60

590dde424e

6f0eb3bb34

eeb6c63929

a72034387e

Body:
Its a stdClass Object array, so try this:

foreach($yourArray['result'] as $data)
{
    echo $date->uniq_id.'<br>';
}

Note: stdClass Object properties can be accessed using ->


问:
Position of a point in a circle
Hello again first part is working like a charm, thank you everyone.

But I've another question...

As I've no interface, is there a way to do the same thing with out not knowing the radius of the circle?

Should have refresh the page CodeMonkey solution is exactly what I was looking for...

Thank you again.

============================

First I'm not a developer, I'm a simple woodworker that left school far too early...

I'm trying to make one of my tool to work with an autonomous robot.
I made them communicate by reading a lot of tutorials.

But I have one problem I cant figure out.

Robot expect position of the tool as (X,Y) but tool's output is (A,B,C)
A is the distance from tool to north
B distance to east
C distance at 120 degree clockwise from east axe

the border is a circle, radius may change, and may or may not be something I know.

I've been on that for 1 month, and I can't find a way to transform those value into the position.

I made a test with 3 nails on a circle I draw on wood, and if I have the distance there is only one position possible, so I guess its possible.
But how?

Also, if someone as an answer I'd love pseudo code not code so I can practice.

If there is a tool to make a drawing I can use to make it clearer can you point it out to me?

Thank you.

hope it helps :

X, Y are coordinate from center, Da,Db, Dc are known.

Trying to make it more clear (sorry its so clear in my head).

X,Y are the coordinate of the point where is the tool (P).
Center is at 0,0

A is the point where vertical line cut the circle from P, with Da distance P to A;

B is the point where horizontal line cuts the circle fom P, with Db distance P to B.

C is the point where the line at 120 clockwise from horizontal cuts the circle from P, with Dc distance P to C.

Output from tool is an array of int (unit mm): A=123, B=114, C=89
Those are the only informations I have

thanks for all the ideas I'll try them at home later,
Hope it works :)

答:
Basic geometry.  I decided to give up having the circle at the origin.  We don't know the center of the circle yet.  What you do have, is three points on that circle.  Let's try having the tool's position, given as P, as the new (0,0).  This thus resolves to finding a circle given three points: (0, Da); (Db,0), and back off at 120° at Dc distance.

Pseudocode:

Calculate a line from A to B: we'll call it AB.  Find AB's halfway point.  Calculate a line perpendicular to AB, through that midpoint (e.g. the cross product of AB and a unit Z axis finds the perpendicular vector).

Calculate a line from B to C (or C to A works just as well): we'll call it BC.  Find BC's halfway point.  Calculate a line perpendicular to BC, through that midpoint.

Calculate where these two lines cross.  This will be the origin of your circle.

Since P is at (0,0), the negative of your circle's origin will be your tool's coordinates relative to the circle's origin.  You should be able to calculate anything you need relative to that, now.

Midpoint between two points: X=(X1+X2)/2.  Y=(Y1+Y2)/2.

The circle's radius can be calculated using, e.g. point A and the circle's origin: R=sqrt(sqr((Ax-CirX)+sqr(Ay-CirY))

Distance from the edge: circle's radius - tool's distance from the circle's center via Pythagorean Theorem again.

Title: Position of a point in a circle


问:
purrr::discard How to delete elements in a vector containing one or more specific strings
I would like to remove the elements containing '_1' and '_3' in the vector using the discard function from purrr. Here the example:

```<code>library(purrr)
x <- c("ABAC_13", "ZDRF73", "UYDS_12", "FGSH41", "GFSC_35" , "JHSC_29")
</code>```

答:
As this is specific to tidyverse, we can use the syntax specific to it

```<code>library(tidyverse)
str_detect(x, "_[13]") %>%
                  discard(x, .)
#[1] "ZDRF73"  "FGSH41"  "JHSC_29"
</code>```

If we need to remove the elements

```<code>grep("_\\d+", x, invert = TRUE, value = TRUE)
#[1] "ZDRF73" "FGSH41"
</code>```

or if it is specific to 1, 3

```<code>grep("_[13]", x, invert = TRUE, value = TRUE)
#[1] "ZDRF73"  "FGSH41"  "JHSC_29"
</code>```

If we need to remove the substring part,

```<code>sub("_\\d+", '', x)
</code>```

Body:
I would like to remove the elements containing '_1' and '_3' in the vector using the discard function from purrr. Here the example:

library(purrr)
x <- c("ABAC_13", "ZDRF73", "UYDS_12", "FGSH41", "GFSC_35" , "JHSC_29")

Body:
As this is specific to tidyverse, we can use the syntax specific to it

library(tidyverse)
str_detect(x, "_[13]") %>%
                  discard(x, .)
#[1] "ZDRF73"  "FGSH41"  "JHSC_29"

If we need to remove the elements

grep("_\\d+", x, invert = TRUE, value = TRUE)
#[1] "ZDRF73" "FGSH41"

or if it is specific to 1, 3

grep("_[13]", x, invert = TRUE, value = TRUE)
#[1] "ZDRF73"  "FGSH41"  "JHSC_29"

If we need to remove the substring part,

sub("_\\d+", '', x)


问:
React-native get stuck at Dependency Graph
I try to start with react-native, I've installed everything and got to phase where I have RSoD on my phone which is telling me to run server.
When i run react-native start lot of things runs, but then it gets stuck at <END>   Building Dependency Graph and I have no idea what to do with it. So, how can I make it continue?

答: After the command react-native run-android worked for me. I just waited library installings, after that it worked.


问:
In React, is it a good practise to return null if props is empty
Given my code:

```<code>class Example extends Components {
  constructor(props) {
     super(props)
  }

  componentDidMount() {
     //fetch data
  }

  render() {
     const {obj} = this.props;
     if(R.isEmpty(obj)) {
        return null;
     }

     return (<div>{obj.name}</div>)
  }
}
</code>```

the obj is retrieved from server. so for the initial render, obj is empty. If I don't return null, obj.name would report error

so is it a good practise to return null before I get response from server? thanks

答:
Yes, that is the proper way. If don't want to render anything return null.

One more thing if you want to wait for response and hold the rendering until that, you can return this also:

```<code>if(R.isEmpty(obj)) {
    return <div>Loading...</div>
}
</code>```

By this way user will come to know that something is going on, some kind of data is being fetch from server, this is more intuitive i think.

Body:
Given my code:

class Example extends Components {
  constructor(props) {
     super(props)
  }

  componentDidMount() {
     //fetch data
  }

  render() {
     const {obj} = this.props;
     if(R.isEmpty(obj)) {
        return null;
     }

     return (
{obj.name}
)
  }
}

the obj is retrieved from server. so for the initial render, obj is empty. If I don't return null, obj.name would report error

so is it a good practise to return null before I get response from server? thanks

Body:
Yes, that is the proper way. If don't want to render anything return null.

One more thing if you want to wait for response and hold the rendering until that, you can return this also:

if(R.isEmpty(obj)) {
    return <div>Loading...</div>
}

By this way user will come to know that something is going on, some kind of data is being fetch from server, this is more intuitive i think.


问:
error when i import android eclipse project in Android Studio
Hello guys i'm gald to be here, please i have that error, can you help me?

```<code>Error:Execution failed for task ':app:processDebugManifest'.
</code>```

Manifest merger failed : uses-sdk:minSdkVersion 9 cannot be smaller than version 14 declared in library [com.google.android.gms:play-services:10.2.1] C:\Users\Khalil\StudioProjects\Android eBook Template\app\build\intermediates\exploded-aar\com.google.android.gms\play-services\10.2.1\AndroidManifest.xml
      Suggestion: use tools:overrideLibrary="com.google.android.gms.play_services" to force usage

what i can do?

答:
First Remove the google play library(in this case com.google.android.gms.play_services), then open manifests --> AndroidManifest.xml
and change min sdk version to 14

This Line:- android:minSdkVersion="14"

Also Change it in your build.gradle of app..
under the  defaultConfig

Hope it helps!!

Body:
Hello guys i'm gald to be here, please i have that error, can you help me?

Error:Execution failed for task ':app:processDebugManifest'.

Manifest merger failed : uses-sdk:minSdkVersion 9 cannot be smaller than version 14 declared in library [com.google.android.gms:play-services:10.2.1] C:\Users\Khalil\StudioProjects\Android eBook Template\app\build\intermediates\exploded-aar\com.google.android.gms\play-services\10.2.1\AndroidManifest.xml
      Suggestion: use tools:overrideLibrary="com.google.android.gms.play_services" to force usage

what i can do?


问:
Pickle with cucumber, machinist and Mongoid
I'm using pickle 0.3.0 with rails, cucumber and mongoid. I do found that pickle0.3.0 automatically finds the ORM. But while I wrote a cucumber scenario and tested it, It didn't find any pickle steps.

Here is the sample:

```
Scenario: logging in user
  Given the following users exists
  |name|
  |John|
  |white|
```

But didn't find pickle step

```
# create models from a table
Given(/^the following #{capture_plural_factory} exists?:?$/) do |plural_factory, table|
  create_models_from_table(plural_factory, table)
end
```

and generates this error

```
You can implement step definitions for undefined steps with these snippets:

Given /^the following users should exists$/ do |table|
  # table is a Cucumber::Ast::Table
  pending # express the regexp above with the code you wish you had
end

```

Any Ideas?

答: After using pickle 0.4. Error was solved.</p>

Body:
I'm using pickle 0.3.0 with rails, cucumber and mongoid. I do found that pickle0.3.0 automatically finds the ORM. But while I wrote a cucumber scenario and tested it, It didn't find any pickle steps.

Here is the sample:

Scenario: logging in user
  Given the following users exists
  |name|
  |John|
  |white|

But didn't find pickle step

# create models from a table
Given(/^the following #{capture_plural_factory} exists?:?$/) do |plural_factory, table|
  create_models_from_table(plural_factory, table)
end

and generates this error

You can implement step definitions for undefined steps with these snippets:

Given /^the following users should exists$/ do |table|
  # table is a Cucumber::Ast::Table
  pending # express the regexp above with the code you wish you had
end

Any Ideas?


问:
Error: The current thread must be in Single Thread Apartment
I have this error whenever i try to open the Openfiledialog :

The current thread must be in Single Thread Apartment (STA) mode before OLE calls can be made. Make sure your Main function is marked as STAThreadAttribute. This exception is triggered only if a debugger is attached to the process.

My code :

```<code>    Dim ofg As New OpenFileDialog
    Dim lvp As New ListViewItem

    ofg.Multiselect = True
    ofg.Filter = "All Files|*.*"
    Statue.Text = "Loading..."

    If ofg.ShowDialog = Windows.Forms.DialogResult.OK Then
        For Each File As String In ofg.SafeFileNames

            Dim hInst As IntPtr = Marshal.GetHINSTANCE([Assembly].GetExecutingAssembly.GetModules()(0))
            Dim iIcon As Int32 = 0
            Dim hIcon As IntPtr

            hIcon = ExtractAssociatedIcon(hInst, File, iIcon)
            ico = Icon.FromHandle(hIcon)
            icondufile = ico.ToBitmap
            Img.Images.Add(icondufile)
            Dim C_File As New IO.FileInfo(File)

            Dim ItemFile As ListViewItem = New ListViewItem(C_File.Name)
            lvp = Files_List.Items.Add(ItemFile)
            lvp.SubItems.Add(MD5Checksum(File))
            lvp.SubItems.Add(hash_generator("sha1", File))
            lvp.SubItems.Add(hash_generator("sha256", File))
            lvp.SubItems.Add(GetCRC32(File))
            lvp.SubItems.Add(hash_generator("sha384", File))
            lvp.SubItems.Add(hash_generator("sha512", File))
            lvp.SubItems.Add(C_File.FullName)
            lvp.SubItems.Add(C_File.Extension)
            lvp.StateImageIndex = lvp.Index

            ItemFile = Nothing

        Next

  Private Sub AddFilesToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AddFilesToolStripMenuItem.Click
    trd = New Threading.Thread(AddressOf AddFiles)
    trd.IsBackground = True
    trd.Start()
    Timer_AddFiles.Start()
End Sub
</code>```

答:
You can use Form Invoke method or set Thread Apartment as :</p>

```<code>Dim ItemFile As ListViewItem
Private Function Init()
 trd = New Threading.Thread(AddressOf AddFiles)
 trd.IsBackground = True
 trd.SetApartmentState(Threading.ApartmentState.STA) ''You can set MTA or STA
 trd.Start(ItemFile)
End Function
Private Sub DoFormUiBased()
    '' Add your code here
End Sub
Private Function AddFiles(ByVal Argument As Object)
    Me.Invoke(New MethodInvoker(AddressOf DoFormUiBased))
End Function
</code>```

Body:
I have this error whenever i try to open the Openfiledialog :

The current thread must be in Single Thread Apartment (STA) mode before OLE calls can be made. Make sure your Main function is marked as STAThreadAttribute. This exception is triggered only if a debugger is attached to the process.

My code :

    Dim ofg As New OpenFileDialog
    Dim lvp As New ListViewItem

    ofg.Multiselect = True
    ofg.Filter = "All Files|*.*"
    Statue.Text = "Loading..."

    If ofg.ShowDialog = Windows.Forms.DialogResult.OK Then
        For Each File As String In ofg.SafeFileNames

            Dim hInst As IntPtr = Marshal.GetHINSTANCE([Assembly].GetExecutingAssembly.GetModules()(0))
            Dim iIcon As Int32 = 0
            Dim hIcon As IntPtr

            hIcon = ExtractAssociatedIcon(hInst, File, iIcon)
            ico = Icon.FromHandle(hIcon)
            icondufile = ico.ToBitmap
            Img.Images.Add(icondufile)
            Dim C_File As New IO.FileInfo(File)

            Dim ItemFile As ListViewItem = New ListViewItem(C_File.Name)
            lvp = Files_List.Items.Add(ItemFile)
            lvp.SubItems.Add(MD5Checksum(File))
            lvp.SubItems.Add(hash_generator("sha1", File))
            lvp.SubItems.Add(hash_generator("sha256", File))
            lvp.SubItems.Add(GetCRC32(File))
            lvp.SubItems.Add(hash_generator("sha384", File))
            lvp.SubItems.Add(hash_generator("sha512", File))
            lvp.SubItems.Add(C_File.FullName)
            lvp.SubItems.Add(C_File.Extension)
            lvp.StateImageIndex = lvp.Index

            ItemFile = Nothing

        Next

  Private Sub AddFilesToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AddFilesToolStripMenuItem.Click
    trd = New Threading.Thread(AddressOf AddFiles)
    trd.IsBackground = True
    trd.Start()
    Timer_AddFiles.Start()
End Sub

Body:
You can use Form Invoke method or set Thread Apartment as :

Dim ItemFile As ListViewItem
Private Function Init()
 trd = New Threading.Thread(AddressOf AddFiles)
 trd.IsBackground = True
 trd.SetApartmentState(Threading.ApartmentState.STA) ''You can set MTA or STA
 trd.Start(ItemFile)
End Function
Private Sub DoFormUiBased()
    '' Add your code here
End Sub
Private Function AddFiles(ByVal Argument As Object)
    Me.Invoke(New MethodInvoker(AddressOf DoFormUiBased))
End Function


问:
Python Scrapy grabbing table not working in the way it should
Following the help I have designed the scraper as follows:

import scrapy

from lankatable.items import LankatableItem

class TableScraper(scrapy.Spider):
    """docstring for TableScraper."""
    name = "table"
    allowed_domains = ["lankabd.com"]
    start_urls = [
        "http://lankabd.com/dse/stock-market/GSPFINANCE/gsp-finance-company-(bangladesh)-limited-/financial-statements?companyId=300&stockId=287",
    ]

    def parse(self,response):
        Item = LankatableItem()
        Item['industry'] = response.css('.portalTitleL2 ::text').extract_first().split(' - ')[-2]
        Item['ticker']   = response.css('.portalTitle.companyTitle ::text').extract_first().split(' (')[-1].strip(')')
        Item['yearEnd']  = response.css('.note>font::text').extract_first()
        # text in a row-cell
        Item['summery'] = {}
        for tr in response.xpath(".//*[@id='summery']/table/tbody/tr"):
            Item['summery']['title'] = tr.xpath('/td[1]/text()').extract_first().strip()
            Item['summery']['y2011'] = tr.xpath('/td[2]/span/text()').extract_first().strip()
            print Item
        print "Hello World!"
```

<p>With the items as :</p>

<pre class="lang-py prettyprint-override"><code># -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html

import scrapy

class LankatableItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    ticker   = scrapy.Field()
    industry = scrapy.Field()
    yearEnd  = scrapy.Field()
    summery  = scrapy.Field()   # should hold 'summery' table from the page
    balance  = scrapy.Field()   # should hold 'Balance-sheet' table from the page
    income   = scrapy.Field()   # should hold 'income-statemnt' table from the page
    cash     = scrapy.Field()   # should hold 'cash-flow' table from the page
</code>```

But it is not grabbing anything. Don't understand what is missing in my code! Any help is highly appreciated. Since response includes the Xpath internally I'm not using the HtmlXpathSelector in my code.

And I ran it with scrapy crawl table in the root folder.

答:
The reason of why your xpath doesn't work is becuase of tbody. You have to remove it and check if you get that result that you want.

You can read this in scrapy documentation: http://doc.scrapy.org/en/0.14/topics/firefox.html

Firefox, in particular, is known for adding
 elements to
  tables. Scrapy, on the other hand, does not modify the original page
  HTML, so you won’t be able to extract any data if you use
 in
  your XPath expressions.

Body:
Following the help I have designed the scraper as follows:

import scrapy

from lankatable.items import LankatableItem

class TableScraper(scrapy.Spider):
    """docstring for TableScraper."""
    name = "table"
    allowed_domains = ["lankabd.com"]
    start_urls = [
        "http://lankabd.com/dse/stock-market/GSPFINANCE/gsp-finance-company-(bangladesh)-limited-/financial-statements?companyId=300&stockId=287",
    ]

    def parse(self,response):
        Item = LankatableItem()
        Item['industry'] = response.css('.portalTitleL2 ::text').extract_first().split(' - ')[-2]
        Item['ticker']   = response.css('.portalTitle.companyTitle ::text').extract_first().split(' (')[-1].strip(')')
        Item['yearEnd']  = response.css('.note>font::text').extract_first()
        # text in a row-cell
        Item['summery'] = {}
        for tr in response.xpath(".//*[@id='summery']/table/tbody/tr"):
            Item['summery']['title'] = tr.xpath('/td[1]/text()').extract_first().strip()
            Item['summery']['y2011'] = tr.xpath('/td[2]/span/text()').extract_first().strip()
            print Item
        print "Hello World!"

With the items as :

# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html

import scrapy

class LankatableItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    ticker   = scrapy.Field()
    industry = scrapy.Field()
    yearEnd  = scrapy.Field()
    summery  = scrapy.Field()   # should hold 'summery' table from the page
    balance  = scrapy.Field()   # should hold 'Balance-sheet' table from the page
    income   = scrapy.Field()   # should hold 'income-statemnt' table from the page
    cash     = scrapy.Field()   # should hold 'cash-flow' table from the page

But it is not grabbing anything. Don't understand what is missing in my code! Any help is highly appreciated. Since response includes the Xpath internally I'm not using the HtmlXpathSelector in my code.

And I ran it with scrapy crawl table in the root folder.

Body:
The reason of why your xpath doesn't work is becuase of tbody. You have to remove it and check if you get that result that you want.

You can read this in scrapy documentation: http://doc.scrapy.org/en/0.14/topics/firefox.html

Firefox, in particular, is known for adding <tbody> elements to
  tables. Scrapy, on the other hand, does not modify the original page
  HTML, so you won’t be able to extract any data if you use <tbody> in
  your XPath expressions.


问:
CAShapeLayer dashed line clipping at end of view
Okay so I'm trying to draw a dashed line inside of a view, which should be fairly simple but no matter what I've tried I keep getting the dashes at both ends clipping and I would like to have the dash not have any clipped segments. Here's the extension I made (the purple background color is just there so I can see the frame)

```<code>extension UIView {
public func addDashedLineToView(_ color : UIColor) {
    self.backgroundColor = UIColor.purple
    let cgColor = color.cgColor

    let shapeLayer: CAShapeLayer = CAShapeLayer()
    let frameSize = self.frame.size
    let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height)

    shapeLayer.bounds = shapeRect
    shapeLayer.position = CGPoint(x: frameSize.width / 2, y: frameSize.height)
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.strokeColor = cgColor
    shapeLayer.lineWidth = 6
    shapeLayer.lineCap = kCALineCapRound
    shapeLayer.lineJoin = kCALineJoinRound
    shapeLayer.lineDashPattern = [8, 10]

    let path: CGMutablePath = CGMutablePath()
    path.move(to: .zero)
    path.addLine(to: CGPoint(x: self.frame.width, y: 0))
    shapeLayer.path = path

    self.layer.addSublayer(shapeLayer)
    self.layer.masksToBounds = true
}
</code>```

and here's a screenshot of what it ends up looking like.

not sure where I'm messing up here, but I know that I must be doing something wrong since it shouldn't be this hard to draw a dashed line in swift (I hope).

答:
You can adjust the start position of the pattern with lineDashPhase. Try

```<code>shapeLayer.lineDashPhase = -4
</code>```

Body:
Okay so I'm trying to draw a dashed line inside of a view, which should be fairly simple but no matter what I've tried I keep getting the dashes at both ends clipping and I would like to have the dash not have any clipped segments. Here's the extension I made (the purple background color is just there so I can see the frame)

extension UIView {
public func addDashedLineToView(_ color : UIColor) {
    self.backgroundColor = UIColor.purple
    let cgColor = color.cgColor

    let shapeLayer: CAShapeLayer = CAShapeLayer()
    let frameSize = self.frame.size
    let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height)

    shapeLayer.bounds = shapeRect
    shapeLayer.position = CGPoint(x: frameSize.width / 2, y: frameSize.height)
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.strokeColor = cgColor
    shapeLayer.lineWidth = 6
    shapeLayer.lineCap = kCALineCapRound
    shapeLayer.lineJoin = kCALineJoinRound
    shapeLayer.lineDashPattern = [8, 10]

    let path: CGMutablePath = CGMutablePath()
    path.move(to: .zero)
    path.addLine(to: CGPoint(x: self.frame.width, y: 0))
    shapeLayer.path = path

    self.layer.addSublayer(shapeLayer)
    self.layer.masksToBounds = true
}

and here's a screenshot of what it ends up looking like.

not sure where I'm messing up here, but I know that I must be doing something wrong since it shouldn't be this hard to draw a dashed line in swift (I hope).

Body:
You can adjust the start position of the pattern with lineDashPhase. Try

shapeLayer.lineDashPhase = -4


问:
Return back to App after clicking on Accessibility Service
Please Please read the question complete before marking it as duplicate or vague

On clicking of a button I want to redirect the user to accessibility settings of the android mobile. Where user can click on the accessibility settings of the application. Here is the code that I am using for the same:

```<code>Intent dummyIntent = new Intent(android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS);
startActivityForResult(dummyIntent, 1);
</code>```

Problem: When user clicks on, I want that it should redirect back to my application and should not remain on the accessibility screen itself.

答:
try this :</p>

```<code> Intent dummyIntent = new Intent(android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS);
 ActivityContext.startActivityForResult(dummyIntent, 1);
</code>```

Body:
Please Please read the question complete before marking it as duplicate or vague

On clicking of a button I want to redirect the user to accessibility settings of the android mobile. Where user can click on the accessibility settings of the application. Here is the code that I am using for the same:

Intent dummyIntent = new Intent(android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS);
startActivityForResult(dummyIntent, 1);

Problem: When user clicks on, I want that it should redirect back to my application and should not remain on the accessibility screen itself.

Body:
try this :

 Intent dummyIntent = new Intent(android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS);
 ActivityContext.startActivityForResult(dummyIntent, 1);