问:
Getting Cognito Credentials on Android
I need to authenticate a user using AWS's Cognito in Android and get a token to use on my future requests. Some information is provided to me by the backend but I still haven't managed to use it in the appropriate way, and Cognito's documentation did not help me on this. I have this fixed info:

Pool Region: us-east-1
   Pool ID: us-east-1:xxxxx-xxxxx-xxxxx-xxxx-xxxxxxxx

And after authenticating the user on the login endpoint I get this info:

```<code>{
   "cognitoId": "us-east-1:yyyy-yyyy-yyyy-yyyy-yyyyyyy",
   "cognitoToken": "hH1Q8bCLh9-pamP6DCrC0-KY4rNtZ115xDedE224CeEanex-CCWh4tWUtJjPc_tU3d6eJ_7Uk23ceTNhCFYT1qnAL_7kAH_lHod4a1GQo29FuTLQSqx4lOFv2Ev3RvYcCzjyLEAA1-EIKBtfSm_YN9y6DHBOzDJ8owLJTxB0JEWvsWfATjug4P8hxCI97RVB2cetrmq4JvZr__bCziUb-7AifPvy4VMW3xLjJ7uyDvogwcx5gJ1rF8Z38_z7kREB1R_CYPRVQuoHzag0j9RoOTNeAYFGO42qgCewTl3Lvm5PUbTIGhCIp6y1RVWAPLEdMWmQ3LVpqJcZKLQRhMmEzOGMyTUiXSwiaXNzIjoiaHR0cHM6Ly9jb2duaXRvLWlkZW50aXR5LmFtYXpvbmF3cy5jb20iLCJleHAiOjE1MTE2NDEzMDksImlhdCI6MTUxMTYyNjkwOX0.QFWGxh_"
}
</code>```

The IDs were omitted and the token was altered in order to preserve the information. It is important to note that the Pool ID (constant in the app) and the cognitoId (returned by the backend) are different.

I have a static Credentials Provider initialized like this:

```<code>credentialsProvider = new CognitoCachingCredentialsProvider(
               getApplicationContext(),    /* get the context for the application */
               IDENTITY_POOL_ID,    /* Identity Pool ID */
               Regions.US_EAST_1           /* Region for your identity pool--US_EAST_1 or EU_WEST_1*/
       );
</code>```

This is the task that does the work of trying to get the Cognito auth:

```<code>private static final class CognitoAuthTask extends AsyncTask<String, Void, String> {
           @Override
           protected String doInBackground(String... strings) {
               String userId = strings[0];
               String token = strings[1];
               String sessionToken = null;
               try {
                   Map<String, String> logins = new HashMap<String, String>();
                   logins.put(userId, token);
                   credentialsProvider.setLogins(logins);
                   AWSSessionCredentials credentials = credentialsProvider.getCredentials();
                   sessionToken = credentials.getSessionToken();
               } catch (Exception e) {
                   if (BuildConfig.DEBUG) {
                       e.printStackTrace();
                   }
               } finally {
                   return sessionToken;
               }
           }

           @Override
           protected void onPostExecute(String authToken) {
               super.onPostExecute(authToken);
               cognitoAuthToken = authToken;
               if (BuildConfig.DEBUG) {
                   Log.d("Cognito Token", cognitoAuthToken == null ? "null" : cognitoAuthToken);
               }
           }
       }
</code>```

And this is where I call it when I have the information from my login endpoint (as I showed above):

```<code>public void authenticateCognito(String userId, String token) {
       new CognitoAuthTask().execute(userId, token);
   }
</code>```

The problem is that this is not working, I get this error here:

Invalid login token. Can't pass in a Cognito token. (Service:
  AmazonCognitoIdentity; Status Code: 400; Error Code:
  NotAuthorizedException; Request ID: zzzzzz-zzzz-zzzz-zzzz-zzzzzzzzzz)

The error happens on the task, on this line of code here:

```<code>credentialsProvider.getCredentials();
</code>```

The backend team mentioned that I would need to use the GetCredentialsForIdentity method, but I can't find anything like that on the Cognito Android SDK.

Any help is appreciated.

答: The class you should be using is AmazonCognitoIdentityClient, that is the class implementing the GetCredentialsForIdentity API.

Title: Getting Cognito Credentials on Android

Body:
I need to authenticate a user using AWS's Cognito in Android and get a token to use on my future requests. Some information is provided to me by the backend but I still haven't managed to use it in the appropriate way, and Cognito's documentation did not help me on this. I have this fixed info:

Pool Region: us-east-1
   Pool ID: us-east-1:xxxxx-xxxxx-xxxxx-xxxx-xxxxxxxx

And after authenticating the user on the login endpoint I get this info:

{
   "cognitoId": "us-east-1:yyyy-yyyy-yyyy-yyyy-yyyyyyy",
   "cognitoToken": "hH1Q8bCLh9-pamP6DCrC0-KY4rNtZ115xDedE224CeEanex-CCWh4tWUtJjPc_tU3d6eJ_7Uk23ceTNhCFYT1qnAL_7kAH_lHod4a1GQo29FuTLQSqx4lOFv2Ev3RvYcCzjyLEAA1-EIKBtfSm_YN9y6DHBOzDJ8owLJTxB0JEWvsWfATjug4P8hxCI97RVB2cetrmq4JvZr__bCziUb-7AifPvy4VMW3xLjJ7uyDvogwcx5gJ1rF8Z38_z7kREB1R_CYPRVQuoHzag0j9RoOTNeAYFGO42qgCewTl3Lvm5PUbTIGhCIp6y1RVWAPLEdMWmQ3LVpqJcZKLQRhMmEzOGMyTUiXSwiaXNzIjoiaHR0cHM6Ly9jb2duaXRvLWlkZW50aXR5LmFtYXpvbmF3cy5jb20iLCJleHAiOjE1MTE2NDEzMDksImlhdCI6MTUxMTYyNjkwOX0.QFWGxh_"
}

The IDs were omitted and the token was altered in order to preserve the information. It is important to note that the Pool ID (constant in the app) and the cognitoId (returned by the backend) are different.

I have a static Credentials Provider initialized like this:

credentialsProvider = new CognitoCachingCredentialsProvider(
               getApplicationContext(),    /* get the context for the application */
               IDENTITY_POOL_ID,    /* Identity Pool ID */
               Regions.US_EAST_1           /* Region for your identity pool--US_EAST_1 or EU_WEST_1*/
       );

This is the task that does the work of trying to get the Cognito auth:

private static final class CognitoAuthTask extends AsyncTask<String, Void, String> {
           @Override
           protected String doInBackground(String... strings) {
               String userId = strings[0];
               String token = strings[1];
               String sessionToken = null;
               try {
                   Map<String, String> logins = new HashMap<String, String>();
                   logins.put(userId, token);
                   credentialsProvider.setLogins(logins);
                   AWSSessionCredentials credentials = credentialsProvider.getCredentials();
                   sessionToken = credentials.getSessionToken();
               } catch (Exception e) {
                   if (BuildConfig.DEBUG) {
                       e.printStackTrace();
                   }
               } finally {
                   return sessionToken;
               }
           }

           @Override
           protected void onPostExecute(String authToken) {
               super.onPostExecute(authToken);
               cognitoAuthToken = authToken;
               if (BuildConfig.DEBUG) {
                   Log.d("Cognito Token", cognitoAuthToken == null ? "null" : cognitoAuthToken);
               }
           }
       }

And this is where I call it when I have the information from my login endpoint (as I showed above):

public void authenticateCognito(String userId, String token) {
       new CognitoAuthTask().execute(userId, token);
   }

The problem is that this is not working, I get this error here:

Invalid login token. Can't pass in a Cognito token. (Service:
  AmazonCognitoIdentity; Status Code: 400; Error Code:
  NotAuthorizedException; Request ID: zzzzzz-zzzz-zzzz-zzzz-zzzzzzzzzz)

The error happens on the task, on this line of code here:

credentialsProvider.getCredentials();

The backend team mentioned that I would need to use the GetCredentialsForIdentity method, but I can't find anything like that on the Cognito Android SDK.

Any help is appreciated.


来源: stackexchange

问:
Open Kendo Prompt Customized dialog on button click
I have tried to piece together bits of info from google searches, but I can't find a clear answer to why the Kendo Prompt only works once when a page is refreshed.  Here is a simple script which is based on one of the samples provided by Telerik, but I modified it to allow the prompt to be triggered by  a button click.  It appears that after the click, the prompt div is no longer accessible, but I don't understand why. Anybody know the answer?</p>

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Kendo UI Snippet</title>
    <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.common.min.css"/>
    <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.rtl.min.css"/>
    <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.silver.min.css"/>
    <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.mobile.all.min.css"/>

    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <script src="https://kendo.cdn.telerik.com/2017.3.1026/js/kendo.all.min.js"></script>
</head>
<body>

<div id="prompt"></div>
<div><button class="k-button" onclick="onClk()">Click Here</button></div>
<script>
  function onClk() {
      $("#prompt").kendoPrompt({
      content: "Prompt text",
     value: "Default input text",
    messages:{
      okText: "OK"
    }
    }).data("kendoPrompt").result.done(function(data){
        console.log("User accepted with text: " + data);
    })
    .fail(function(data){
        console.log("User rejected with text: " + data);
    });
   }
</script>
</body>
</html>
</code>```

答:
That is because you are using customized prompts targetted to a container rather than normal alert and prompt dialogs, and after opening it for the first time, once you click on ok or cancel the container div #prompt is removed from the document along with the dialog, and when you click the button again to open it, it simply does not find the element to bind kendopromptso it throws the error at the point when it calls .data(). ideally, if you want to use it in this way you should create the container div before calling the function inside your javascript and append it to the body, change your code to match the below code in the demo. just match your javascript and try to use meaningful names for the functions.

Hope it helps

function myPrompt() {
  $("#prompt").kendoPrompt({
      content: "Prompt text",
      value: "Default input text",
      messages: {
        okText: "OK"
      }
    }).data("kendoPrompt").result.done(function(data) {
      console.log("User accepted with text: " + data);
    })
    .fail(function(data) {
      console.log("User rejected with text: " + data);
    });
}

$(document).ready(function() {
  $(".k-button").on('click', function() {
    if ($("#prompt").length < 1) {
      var div = document.createElement('div');
      div.setAttribute('id', 'prompt');
      $('body').append(div);
    }
    myPrompt();
  });
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.common.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.rtl.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.silver.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.mobile.all.min.css" />

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.3.1026/js/kendo.all.min.js"></script>
</head>

<body>

  <div id="prompt"></div>
  <div>
    <button class="k-button">Click Here</button>
  </div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I have tried to piece together bits of info from google searches, but I can't find a clear answer to why the Kendo Prompt only works once when a page is refreshed.  Here is a simple script which is based on one of the samples provided by Telerik, but I modified it to allow the prompt to be triggered by  a button click.  It appears that after the click, the prompt div is no longer accessible, but I don't understand why. Anybody know the answer?

<!DOCTYPE html>

    <meta charset="utf-8"/>
    <title>Kendo UI Snippet</title>
    <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.common.min.css"/>
    <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.rtl.min.css"/>
    <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.silver.min.css"/>
    <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.mobile.all.min.css"/>

<button class="k-button" onclick="onClk()">Click Here</button>

Body:
That is because you are using customized prompts targetted to a container rather than normal alert and prompt dialogs, and after opening it for the first time, once you click on ok or cancel the container div #prompt is removed from the document along with the dialog, and when you click the button again to open it, it simply does not find the element to bind kendopromptso it throws the error at the point when it calls .data(). ideally, if you want to use it in this way you should create the container div before calling the function inside your javascript and append it to the body, change your code to match the below code in the demo. just match your javascript and try to use meaningful names for the functions.

Hope it helps

function myPrompt() {
  $("#prompt").kendoPrompt({
      content: "Prompt text",
      value: "Default input text",
      messages: {
        okText: "OK"
      }
    }).data("kendoPrompt").result.done(function(data) {
      console.log("User accepted with text: " + data);
    })
    .fail(function(data) {
      console.log("User rejected with text: " + data);
    });
}

$(document).ready(function() {
  $(".k-button").on('click', function() {
    if ($("#prompt").length < 1) {
      var div = document.createElement('div');
      div.setAttribute('id', 'prompt');
      $('body').append(div);
    }
    myPrompt();
  });
})

<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.common.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.rtl.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.silver.min.css" />
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.1026/styles/kendo.mobile.all.min.css" />

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.3.1026/js/kendo.all.min.js"></script>
</head>

<body>

  <div id="prompt"></div>
  <div>
    <button class="k-button">Click Here</button>
  </div>


问:
HTML text as POST toggle (kinda like a radio button)?
I have this on my site:

I want to be able to sort the servers by pressing on players, maps etc.
So to explain it better; If I press once one players I want the list to be ordered in descending order and if I press again I want it to be in ascending order. I already have a script for this and it works with radio buttons, however, that doesn't fit my design. Also, I don't want to need to press another button after the text is clicked on, I want it to change the sorting instantly.

My code for this is:
PHP:

```<code>        if(isset($_POST['sort']))
    {
        if($_POST['sort'] == 'Players Descending')
        {
              uasort($serverArray, function($a, $b) {
                return $b['Players'] <=> $a['Players'];
                });
        }
        if($_POST['sort'] == 'Players Ascending')
        {
              uasort($serverArray, function($a, $b) {
                return $a['Players'] <=> $b['Players'];
                });
        }
    }
</code>```

and the HTML/PHP

```<code>    <form method="post">
    </select>
        Sort by:
        <input type="radio" name="sort" value="Players Descending">Players Descending
        <input type="radio" name="sort" value="Players Ascending">Players Ascending
    <input type="submit" name="submit" value="Filter"/>
    </form>
</code>```

Do anyone have any tips on how to do this the way I want it? Thanks!

答:
If your data is stored into a table, which is what i'm sopposing looking at
the photo you posted, check this js code:

```<code>function sortTable() {
 var table, rows, switching, i, x, y, shouldSwitch;
  table = document.getElementById("myTable");
 switching = true;
 /* Make a loop that will continue until
 no switching has been done: */
 while (switching) {
   // Start by saying: no switching is done:
   switching = false;
   rows = table.getElementsByTagName("TR");
   /* Loop through all table rows (except the
   first, which contains table headers): */
   for (i = 1; i < (rows.length - 1); i++) {
  // Start by saying there should be no switching:
     shouldSwitch = false;
  /* Get the two elements you want to compare,
  one from current row and one from the next: */
  x = rows[i].getElementsByTagName("TD")[0];
  y = rows[i + 1].getElementsByTagName("TD")[0];
  // Check if the two rows should switch place:
  if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
    // I so, mark as a switch and break the loop:
    shouldSwitch= true;
    break;
  }
}
if (shouldSwitch) {
  /* If a switch has been marked, make the switch
  and mark that a switch has been done: */
  rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
  switching = true;
   }
 }
  }
</code>```

 Now edit the "mytable" name with your table name, this should work when you click on the column name (the th tag). Cheers!

Body:
I have this on my site:

I want to be able to sort the servers by pressing on players, maps etc.
So to explain it better; If I press once one players I want the list to be ordered in descending order and if I press again I want it to be in ascending order. I already have a script for this and it works with radio buttons, however, that doesn't fit my design. Also, I don't want to need to press another button after the text is clicked on, I want it to change the sorting instantly.

My code for this is:
PHP:

        if(isset($_POST['sort']))
    {
        if($_POST['sort'] == 'Players Descending')
        {
              uasort($serverArray, function($a, $b) {
                return $b['Players'] <=> $a['Players'];
                });
        }
        if($_POST['sort'] == 'Players Ascending')
        {
              uasort($serverArray, function($a, $b) {
                return $a['Players'] <=> $b['Players'];
                });
        }
    }

and the HTML/PHP

    <form method="post">
    </select>
        Sort by:
        <input type="radio" name="sort" value="Players Descending">Players Descending
        <input type="radio" name="sort" value="Players Ascending">Players Ascending
    <input type="submit" name="submit" value="Filter"/>
    </form>

Do anyone have any tips on how to do this the way I want it? Thanks!

Body:
If your data is stored into a table, which is what i'm sopposing looking at
the photo you posted, check this js code:

function sortTable() {
 var table, rows, switching, i, x, y, shouldSwitch;
  table = document.getElementById("myTable");
 switching = true;
 /* Make a loop that will continue until
 no switching has been done: */
 while (switching) {
   // Start by saying: no switching is done:
   switching = false;
   rows = table.getElementsByTagName("TR");
   /* Loop through all table rows (except the
   first, which contains table headers): */
   for (i = 1; i < (rows.length - 1); i++) {
  // Start by saying there should be no switching:
     shouldSwitch = false;
  /* Get the two elements you want to compare,
  one from current row and one from the next: */
  x = rows[i].getElementsByTagName("TD")[0];
  y = rows[i + 1].getElementsByTagName("TD")[0];
  // Check if the two rows should switch place:
  if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
    // I so, mark as a switch and break the loop:
    shouldSwitch= true;
    break;
  }
}
if (shouldSwitch) {
  /* If a switch has been marked, make the switch
  and mark that a switch has been done: */
  rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
  switching = true;
   }
 }
  }

 Now edit the "mytable" name with your table name, this should work when you click on the column name (the th tag). Cheers!


问:
How to create an empty array in Swift?
I'm really confused with regards to how we create an empty array in Swift. Could you please show me the different ways we have to create an empty array with some detail?</p>

答:
Initiating an array with a predefined count:

Array(repeating: 0, count: 10)

I often use this for mapping statements where I need a specified number of mock objects. For example,

let myObjects: [MyObject] = Array(repeating: 0, count: 10).map { _ in return MyObject() }

ContentLicense: CC BY-SA 4.0

Title: How to create an empty array in Swift?


问:
Spark ML: Taking square root of feature columns
Hi I am using a custom UDF to take square root of each value in each column.

```<code>square_root_UDF = udf(lambda x: math.sqrt(x), DoubleType())

for x in features:
  dataTraining = dataTraining.withColumn(x, square_root_UDF(x))
</code>```

Is there any faster way to get it done ? Polynomial expansion function is not suitable in this case.

答:
In order to speed-up your calculation in this case

put your data into a DataFrame (not RDD)

use vectorized operations (not lambda-operations with UDF) as suggested by @user7757642

this is an example if you dataTraining is an RDD then

```<code>from pyspark.sql import SparkSession
from pyspark.sql.functions import sqrt

spark = SparkSession.builder.appName("SessionName") \
      .config("spark.some.config.option", "some_value") \
      .getOrCreate()

df = spark.createDataFrame(dataTraining)

for x in features:
    df = df.withColumn(x, sqrt(x))
</code>```

Body:
Hi I am using a custom UDF to take square root of each value in each column.

square_root_UDF = udf(lambda x: math.sqrt(x), DoubleType())

for x in features:
  dataTraining = dataTraining.withColumn(x, square_root_UDF(x))

Is there any faster way to get it done ? Polynomial expansion function is not suitable in this case.

Body:
In order to speed-up your calculation in this case

put your data into a DataFrame (not RDD)

use vectorized operations (not lambda-operations with UDF) as suggested by @user7757642

this is an example if you dataTraining is an RDD then

from pyspark.sql import SparkSession
from pyspark.sql.functions import sqrt

spark = SparkSession.builder.appName("SessionName") \
      .config("spark.some.config.option", "some_value") \
      .getOrCreate()

df = spark.createDataFrame(dataTraining)

for x in features:
    df = df.withColumn(x, sqrt(x))


问:
Is std::ifstream significantly slower than FILE?
I've been informed that my library is slower than it should be, on the order of 30+ times too slow parsing a particular file (text file, size 326 kb). The user suggested that it may be that I'm using std::ifstream (presumably instead of FILE).

I'd rather not blindly rewrite, so I thought I'd check here first, since my guess would be the bottleneck is elsewhere. I'm reading character by character, so the only functions I'm using are get(), peek(), and tellg()/seekg().

Update:

I profiled, and got confusing output - gprof didn't appear to think that it took so long. I rewrote the program to read the entire file into a buffer first, and it sped up by about 100x. I think the problem may have been the tellg()/seekg() that took a long time, but gprof may have been unable to see that for some reason. In any case, ifstream does not appear to buffer the entire file, even for this size.

答: It should be slightly slower, but like what you said, it might not be the bottleneck. Why don't you profile your program and see if that's the case? </p>

OwnerDisplayName: Jesse Beder

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Jesse Beder

OwnerDisplayName: PolyThinker


问:
set /p not taking environment variables
I am trying to match a batch script to do this tutorial automatically, for any system.

```<code>@echo off
for /f "tokens=4* delims= " %%A in ('reg query "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" /v "My Pictures"') do (set loc=%%A %%B)
set loc=%loc%\Spotlight
set /p loc=Location for images (default - "%loc%") [use %%loc%% for default]?:
start robocopy "%localappdata%\Packages\Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy\LocalState\Assets" "%temp%\spotlight"
ren %temp%\spotlight\*.* *.jpg
robocopy "%temp%\spotlight" "%loc%"
start %SystemRoot%\explorer.exe %loc%
</code>```

However, if I try typing %loc%\Spotlight2, it places it in the Desktop\%loc%\spotlight2 (desktop is the current working directory).

Is there a way to make set /p take environment variables?

答:
SET /P is basically just an input routine.  There is no documented way to have it do further evaluation, and I doubt one exists.

One could try to get CMD to evaluate the contents of a variable to expand any variables in the contents -- I have seem kludges to do this.  However, I don't think that is a good way to do what you want.

I think you would be better off using something easier to type, and testing for that explicitly.  For example:

```<code>set loc=%loc%\Spotlight
echo Enter location for images, or just press [ENTER] to use the default.
echo Default location: %loc%
set userloc=*
set /p userloc=Location?
if not "%userloc%"=="*" set loc=%userloc%
</code>```

Title: set /p not taking environment variables

Body:
I am trying to match a batch script to do this tutorial automatically, for any system.

@echo off
for /f "tokens=4* delims= " %%A in ('reg query "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" /v "My Pictures"') do (set loc=%%A %%B)
set loc=%loc%\Spotlight
set /p loc=Location for images (default - "%loc%") [use %%loc%% for default]?:
start robocopy "%localappdata%\Packages\Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy\LocalState\Assets" "%temp%\spotlight"
ren %temp%\spotlight\*.* *.jpg
robocopy "%temp%\spotlight" "%loc%"
start %SystemRoot%\explorer.exe %loc%

However, if I try typing %loc%\Spotlight2, it places it in the Desktop\%loc%\spotlight2 (desktop is the current working directory).

Is there a way to make set /p take environment variables?

Body:
SET /P is basically just an input routine.  There is no documented way to have it do further evaluation, and I doubt one exists.

One could try to get CMD to evaluate the contents of a variable to expand any variables in the contents -- I have seem kludges to do this.  However, I don't think that is a good way to do what you want.

I think you would be better off using something easier to type, and testing for that explicitly.  For example:

set loc=%loc%\Spotlight
echo Enter location for images, or just press [ENTER] to use the default.
echo Default location: %loc%
set userloc=*
set /p userloc=Location?
if not "%userloc%"=="*" set loc=%userloc%


问:
CSS page width issue
I am trying to eliminate the horizontal scroll bar on our Intranet. There is nothing but background to the right of the page and I have been struggling with this for several hours now. We have CSS and HTML for the homepage, but use JavaScript to navigate multiple pages. All of the pages pull their settings from the CSS and all of the pages have this issue leading me to believe it is with the CSS. Below is my CSS, please let me know if and where I may need to make changes.

html, body {
    position: absolute;
    height: 100%;
    background-color: #FFEBD6;
    color: #665E56;
}
header {
    text-align:center;
    width: 600px;
}
nav {
    line-height:20px;
    width:180px;
    float:left;
    padding:5px;
    height: 40%;
}
section {
    position: Absolute;
    top: 260px;
    left: 10px;
    background-color:#fff3e5;
    padding:10px;
    border:1px solid #665E56;
    min-height:350px;
}
footer {
    clear:both;
    text-align:center;
    padding:7px;
}
table {
    text-align:center;
    border:1;
}
th, td {
    padding:10px;
}
.indent80 {
    margin-left: 80px;
}
.indented {
    margin-left: 80px;
}
.indent40 {
    margin-left: 40px;
}
.wrapper {
    position:absolute;
    min-height: 100%;
    height: 100%;
    width:500px;
}

/*.push-footer, .push { */
/*    height: 50px; /* .push must be the same height as .footer */
/*} */
#quicklinks {
    padding-left:5px;
    position: absolute;
    left:181px;
    float:left;
    text-align:center;
    border:3px raised;
    padding:10px;
    width:90%;
}
```

答: In your html, body section add width: 100%;

Title: CSS page width issue


问:
PhotoSwipe and Masonry Navigation Arrows Missing
I'm working on a portfolio website using both Masonry and PhotoSwipe. The navigation arrows do not  show and gallery is not navigable via gestures.
Can PhotoSwipe be used with Masonry?

Here's a bit of my code:

```<code><div class="main-container">
<div class="main clear fix">
<div id="content">
<!-- Portfolio Rendering -->
<div class="grid">
div class="grid-sizer">
<div class="grid-item">
<a href="portfolio/01.jpg" data-size="900x1200" data-med="portfolio/600/01.jpg" data-med-size="600x800" data-author="">
<img src="portfolio/600/01.jpg" alt="" />
</a>
</div>
<div class="grid-item">
<a href="portfolio/02.jpg" data-size="900x1200" data-med="portfolio/600/02.jpg" data-med-size="600x900" data-author=""><img src="portfolio/600/02.jpg" alt="" />
</a>
</div>
<div class="grid-item"><a href="portfolio/03.jpg" data-size="900x1200" data-med="portfolio/600/03.jpg" data-med-size="600x800" data-author="">            <img src="portfolio/600/03.jpg" alt="" />
</a>
</div></div></div>
</div></div></div>

<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
<div class="pswp__bg"></div>
<div class="pswp__scroll-wrap">
<div class="pswp__container">
<div class="pswp__item"></div>
<div class="pswp__item"></div>
<div class="pswp__item"></div>
</div>
<div class="pswp__ui pswp__ui--hidden">
<div class="pswp__top-bar">
<button class="pswp__button pswp__button--close" title="Close (Esc)"></button>                  <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>                                           <div class="pswp__preloader">
<div class="pswp__preloader__icn">
<div class="pswp__preloader__cut">
<div class="pswp__preloader__donut"></div>
</div></div></div></div>
<!-- <div class="pswp__loading-indicator">
<div class="pswp__loading-indicator__line">
</div></div> -->
<button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)"></button>
<button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)"></button>
</div></div></div>
</code>```

答:
I know that it's a bit late, but I was searching for a fix with no luck, until eventually I figured it out. My HTML, though, was a bit different, based on the suggestion on the official documentation of PhotoSwipe:

```<code> <div class="my-gallery" itemscope itemtype="http://schema.org/ImageGallery">
    <div class="grid-sizer"></div>
    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
        <a href="large-image.jpg" itemprop="contentUrl" data-size="600x400">
            <img src="small-image.jpg" itemprop="thumbnail" alt="Image description" />
        </a>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
        <a href="large-image.jpg" itemprop="contentUrl" data-size="600x400">
            <img src="small-image.jpg" itemprop="thumbnail" alt="Image description" />
        </a>
    </figure>
</div>
</code>```

When I wrapped the
 tag in a div, masonry was working, but PhotoSwipe navigation didn't. If I removed the div, PhotoSwipe navigation was OK but the layout got messed up. Eventually, I removed the .grid-sizer div and, instead, added the class .grid-sizer on the first  element of the gallery, which fixed the issue. So, the working markup in my case was something like that (notice the extra class on the first
 element):

```<code> <div class="my-gallery" itemscope itemtype="http://schema.org/ImageGallery">
    <figure class="grid-sizer" itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
        <a href="large-image.jpg" itemprop="contentUrl" data-size="600x400">
            <img src="small-image.jpg" itemprop="thumbnail" alt="Image description" />
        </a>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
        <a href="large-image.jpg" itemprop="contentUrl" data-size="600x400">
            <img src="small-image.jpg" itemprop="thumbnail" alt="Image description" />
        </a>
    </figure>
</div>
</code>```

That way, Masonry used the first item to calculate the responsive layout and PhotoSwipe was happy with the markup.

Body:
I'm working on a portfolio website using both Masonry and PhotoSwipe. The navigation arrows do not  show and gallery is not navigable via gestures.
Can PhotoSwipe be used with Masonry?

Here's a bit of my code:

div class="grid-sizer">

<button class="pswp__button pswp__button--close" title="Close (Esc)"></button>                  <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

<button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)"></button>
<button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)"></button>

Body:
I know that it's a bit late, but I was searching for a fix with no luck, until eventually I figured it out. My HTML, though, was a bit different, based on the suggestion on the official documentation of PhotoSwipe:

 <div class="my-gallery" itemscope itemtype="http://schema.org/ImageGallery">
    <div class="grid-sizer"></div>
    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
        <a href="large-image.jpg" itemprop="contentUrl" data-size="600x400">
            <img src="small-image.jpg" itemprop="thumbnail" alt="Image description" />
        </a>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
        <a href="large-image.jpg" itemprop="contentUrl" data-size="600x400">
            <img src="small-image.jpg" itemprop="thumbnail" alt="Image description" />
        </a>
    </figure>
</div>

When I wrapped the <figure> tag in a div, masonry was working, but PhotoSwipe navigation didn't. If I removed the div, PhotoSwipe navigation was OK but the layout got messed up. Eventually, I removed the .grid-sizer div and, instead, added the class .grid-sizer on the first  element of the gallery, which fixed the issue. So, the working markup in my case was something like that (notice the extra class on the first <figure> element):

 <div class="my-gallery" itemscope itemtype="http://schema.org/ImageGallery">
    <figure class="grid-sizer" itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
        <a href="large-image.jpg" itemprop="contentUrl" data-size="600x400">
            <img src="small-image.jpg" itemprop="thumbnail" alt="Image description" />
        </a>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
        <a href="large-image.jpg" itemprop="contentUrl" data-size="600x400">
            <img src="small-image.jpg" itemprop="thumbnail" alt="Image description" />
        </a>
    </figure>
</div>

That way, Masonry used the first item to calculate the responsive layout and PhotoSwipe was happy with the markup.


问:
How do I extract the particular row from .csv file and write out in to another file
I have .csv file something like this:

```<code>x,   y,   z
1,  10,   45
2,   0,   34
4,  15,   34
5,  99,   38
6,  13,   23
5,  99,   38
6,  13,   23
.    .     .
1000, 234, 678
</code>```

now I would like to write out the rows of column x, which can be advisable by 5 form this .csv file.

Here is the more detail about the file:

```<code>x,                  y
0.0000123219872323, 1.213
.                     .
4.991414887967266,  8.123
4.996324047550014,  2.323
5.000581861276573,  6.234
5.006295444400881,  9.234
5.029657671211434,  1.219
5.034806828096650,  1.123
.                   .
9.997414351064347,  1.345
10.00211537343025,  1.232
10.00675672507283,  2.234
10.01201110041457,  1.003
.                   .
</code>```

Here is the real file that I want to process. I have to extract the rows from this .csv file. In particular, rows of the column values which can be dividable by 5.

My output should look like this:

```<code>5.000581861276573,  6.234
10.00211537343025,  1.232
</code>```

Not twice the values of 5, 10 and so on. Once one 5 value is extracted,
it should go to next divisible by 5, in this case it should be 10.

答:
Your answer is very broad and needs more explanation. It is also likely that it has been answered in other posts on StackOverflow.

A very basic answer to your question:

```<code>to_print = [1, 5, 10, 1000]

with open('input_file.csv', 'r') as fr:
    with open('write_here.csv', 'w') as fw:
        for i, row in enumerate(fr):
            if i in to_print:
                 fw.write(row)
</code>```

This simply writes every line that you specify in to_print to another csv file.

If you want to print every fifth line between 0 and 1000, you can consider setting to_print = range(0, 1000, 5) or, if you don't know the number of lines of your file:

```<code>with open('input_file.csv', 'r') as fr:
    with open('write_here.csv', 'w') as fw:
        for i, row in enumerate(fr):
            if i % 5 == 0:
                 fw.write(row)
</code>```

Body:
I have .csv file something like this:

x,   y,   z
1,  10,   45
2,   0,   34
4,  15,   34
5,  99,   38
6,  13,   23
5,  99,   38
6,  13,   23
.    .     .
1000, 234, 678

now I would like to write out the rows of column x, which can be advisable by 5 form this .csv file.

Here is the more detail about the file:

x,                  y
0.0000123219872323, 1.213
.                     .
4.991414887967266,  8.123
4.996324047550014,  2.323
5.000581861276573,  6.234
5.006295444400881,  9.234
5.029657671211434,  1.219
5.034806828096650,  1.123
.                   .
9.997414351064347,  1.345
10.00211537343025,  1.232
10.00675672507283,  2.234
10.01201110041457,  1.003
.                   .

Here is the real file that I want to process. I have to extract the rows from this .csv file. In particular, rows of the column values which can be dividable by 5.

My output should look like this:

5.000581861276573,  6.234
10.00211537343025,  1.232

Not twice the values of 5, 10 and so on. Once one 5 value is extracted,
it should go to next divisible by 5, in this case it should be 10.

Body:
Your answer is very broad and needs more explanation. It is also likely that it has been answered in other posts on StackOverflow.

A very basic answer to your question:

to_print = [1, 5, 10, 1000]

with open('input_file.csv', 'r') as fr:
    with open('write_here.csv', 'w') as fw:
        for i, row in enumerate(fr):
            if i in to_print:
                 fw.write(row)

This simply writes every line that you specify in to_print to another csv file.

If you want to print every fifth line between 0 and 1000, you can consider setting to_print = range(0, 1000, 5) or, if you don't know the number of lines of your file:

with open('input_file.csv', 'r') as fr:
    with open('write_here.csv', 'w') as fw:
        for i, row in enumerate(fr):
            if i % 5 == 0:
                 fw.write(row)


问:
How do i access this Json with PHP
am having issues trying to get contents of this json, am using php.

```<code>{"song":{"returncode":"200","returnmsg":"OK","title":"Despacito Ft. Justin Bieber","artist":"Luis Fonsi, Daddy Yankee","album":"","size":"9193600","url":"http://sami-server.info/Bita6/04.96/Billboard%20Hot%20100%20Singles/Billboard%20Hot%20100%20Singles/01.%20Luis%20Fonsi%2C%20Daddy%20Yankee%20-%20Despacito%20ft.%20Justin%20Bieber.mp3","time":"1499079781","date":"Jul 3, 2017","source":"","active":"1","albumart":"https://images-na.ssl-images-amazon.com/images/I/5150NxehQtL._AC_US160_.jpg","speed":"21","counter":"850850"}
</code>```

this is my function, that returns the json

```<code>public function getSong($id) {
        $song_url = 'http://databrainz.com/api/data_api_new.cgi?jsoncallback=&id='.$id.'&r=mpl&format=json&_=';
        $api = Api::getSpotOn($song_url);
        $song = $api->{'song'};
         return $song;
    }
</code>```

I want to get all it content.

Thanks!

答:
try the following:</p>

```<code>$result = json_decode(
'{
    "song": {
        "returncode": "200",
        "returnmsg": "OK",
        "title": "Despacito Ft. Justin Bieber",
        "artist": "Luis Fonsi, Daddy Yankee",
        "album": "",
        "size": "9193600",
        "url": "http://sami-server.info/Bita6/04.96/Billboard%20Hot%20100%20Singles/Billboard%20Hot%20100%20Singles/01.%20Luis%20Fonsi%2C%20Daddy%20Yankee%20-%20Despacito%20ft.%20Justin%20Bieber.mp3",
        "time": "1499079781",
        "date": "Jul 3, 2017",
        "source": "",
        "active": "1",
        "albumart": "https://images-na.ssl-images-amazon.com/images/I/5150NxehQtL._AC_US160_.jpg",
        "speed": "21",
        "counter": "850850"
    }
}'
);

var_dump($result);

echo $result->song->title;
</code>```

Title: How do i access this Json with PHP

Body:
am having issues trying to get contents of this json, am using php.

{"song":{"returncode":"200","returnmsg":"OK","title":"Despacito Ft. Justin Bieber","artist":"Luis Fonsi, Daddy Yankee","album":"","size":"9193600","url":"http://sami-server.info/Bita6/04.96/Billboard%20Hot%20100%20Singles/Billboard%20Hot%20100%20Singles/01.%20Luis%20Fonsi%2C%20Daddy%20Yankee%20-%20Despacito%20ft.%20Justin%20Bieber.mp3","time":"1499079781","date":"Jul 3, 2017","source":"","active":"1","albumart":"https://images-na.ssl-images-amazon.com/images/I/5150NxehQtL._AC_US160_.jpg","speed":"21","counter":"850850"}

this is my function, that returns the json

public function getSong($id) {
        $song_url = 'http://databrainz.com/api/data_api_new.cgi?jsoncallback=&id='.$id.'&r=mpl&format=json&_=';
        $api = Api::getSpotOn($song_url);
        $song = $api->{'song'};
         return $song;
    }

I want to get all it content.

Thanks!

Body:
try the following:

$result = json_decode(
'{
    "song": {
        "returncode": "200",
        "returnmsg": "OK",
        "title": "Despacito Ft. Justin Bieber",
        "artist": "Luis Fonsi, Daddy Yankee",
        "album": "",
        "size": "9193600",
        "url": "http://sami-server.info/Bita6/04.96/Billboard%20Hot%20100%20Singles/Billboard%20Hot%20100%20Singles/01.%20Luis%20Fonsi%2C%20Daddy%20Yankee%20-%20Despacito%20ft.%20Justin%20Bieber.mp3",
        "time": "1499079781",
        "date": "Jul 3, 2017",
        "source": "",
        "active": "1",
        "albumart": "https://images-na.ssl-images-amazon.com/images/I/5150NxehQtL._AC_US160_.jpg",
        "speed": "21",
        "counter": "850850"
    }
}'
);

var_dump($result);

echo $result->song->title;


问:
Nudging geom_segments where x|xend = -Inf and segments are color-coded by group
I have data for 16 analytes (the facet variable) for three groundwater monitoring wells (well = factor basis for color-coding), each screened at different intervals. For each analyte (facet), the intent is to overlay the data for each well and show corresponding screen intervals along the y-axis. Some screens overlap so aren't easily distinguished. The goal is to have them align along the y-axis with equidistant spacing in this fashion: |||. Problem is the levels of my facetting variable have very different scales. Below is a rough example using the diamonds data set.

```<code>require(dplyr)
require(ggplot2)

# Create mock dataframe, where facet variable ("mockvar") has different x-axis scales
mockdf <- filter(diamonds, cut=="Fair"|cut=="Good"|cut=="Ideal") %>%
droplevels() %>% mutate(mockvar=ifelse(clarity=="SI2", 10*table,
              ifelse(clarity=="SI1", 100*table,
              ifelse(clarity=="VS2", 1000*table, table))))

#Plot Code
ggplot(mockdf, aes(mockvar, depth, color=cut)) + scale_y_reverse() +
geom_point() + facet_wrap(~clarity, scales="free") +
geom_segment(data=mockdf[mockdf$cut=="Fair",], aes(x=-Inf, xend=-Inf, y=55, yend=65)) +
geom_segment(data=mockdf[mockdf$cut=="Good",], aes(x=-Inf, xend=-Inf, y=60, yend=70)) +
geom_segment(data=mockdf[mockdf$cut=="Ideal",], aes(x=-Inf, xend=-Inf, y=65, yend=75))

#calls to position = position_dodge(width = #.#)) ...didn't work
</code>```

How do I juggle the segments given the different scaling? An alternate long-winded solution would be to subset further on each facet level, for example:

```<code>ggplot(mockdf, aes(mockvar, depth, color=cut)) + scale_y_reverse() +
geom_point() + facet_wrap(~clarity, scales="free") +
geom_segment(data=mockdf[mockdf$cut=="Fair"& mockdf$clarity=="I1",], aes(x=49, xend=49, y=55, yend=65)) +
geom_segment(data=mockdf[mockdf$cut=="Good"& mockdf$clarity=="I1",], aes(x=49.5, xend=49.5, y=60, yend=70)) +
geom_segment(data=mockdf[mockdf$cut=="Ideal"& mockdf$clarity=="I1",], aes(x=50, xend=50, y=65, yend=75))
#and so on for all remaining facet levels....
</code>```

But that's a lot of code and a crude 'jerry-rig' at best. Any suggestions for keeping the initial x|xend=-Inf for the first group, then nudging the next 2 segments relative to -Inf with consistent spacing globally across facets?

答:
You'll have to switch off automatic axis expansion and then you can draw the segments where you want them.

```<code>require(dplyr)
require(ggplot2)

# Create mock dataframe, where facet variable ("mockvar") has different x-axis scales
mockdf <- filter(diamonds, cut=="Fair"|cut=="Good"|cut=="Ideal") %>%
  droplevels() %>% mutate(mockvar=ifelse(clarity=="SI2", 10*table,
                                         ifelse(clarity=="SI1", 100*table,
                                                ifelse(clarity=="VS2", 1000*table, table))))

# variables to control axis range and segment spacing
s1 = 0.9 # controls distance to minimum point
s2 = 0.03 # controls distance between segment lines

# add min and range variables
mockdf <- group_by(mockdf, clarity) %>%
  mutate(min = s1*min(mockvar),
         range = (2-s1)*max(mockvar) - s1*min(mockvar))

ggplot(mockdf, aes(mockvar, depth, color=cut)) + scale_y_reverse() +
  # switch off automatic axis expansion
  scale_x_continuous(expand = c(0, 0)) +
  geom_point() + facet_wrap(~clarity, scales="free") +
  geom_segment(data=mockdf[mockdf$cut=="Fair",],
               aes(x=min, xend=min, y=55, yend=65)) +
  geom_segment(data=mockdf[mockdf$cut=="Good",],
               aes(x=min + s2*range, xend=min + s2*range, y=60, yend=70)) +
  geom_segment(data=mockdf[mockdf$cut=="Ideal",],
               aes(x=min + 2*s2*range, xend=min + 2*s2*range, y=65, yend=75)) +
  # draw invisible segment to set end of x axis range
  geom_segment(data=mockdf[mockdf$cut=="Fair",],
               aes(x=min + range, xend=min + range, y=60, yend=70), color = NA)
</code>```

Body:
I have data for 16 analytes (the facet variable) for three groundwater monitoring wells (well = factor basis for color-coding), each screened at different intervals. For each analyte (facet), the intent is to overlay the data for each well and show corresponding screen intervals along the y-axis. Some screens overlap so aren't easily distinguished. The goal is to have them align along the y-axis with equidistant spacing in this fashion: |||. Problem is the levels of my facetting variable have very different scales. Below is a rough example using the diamonds data set.

require(dplyr)
require(ggplot2)

# Create mock dataframe, where facet variable ("mockvar") has different x-axis scales
mockdf <- filter(diamonds, cut=="Fair"|cut=="Good"|cut=="Ideal") %>%
droplevels() %>% mutate(mockvar=ifelse(clarity=="SI2", 10*table,
              ifelse(clarity=="SI1", 100*table,
              ifelse(clarity=="VS2", 1000*table, table))))

#Plot Code
ggplot(mockdf, aes(mockvar, depth, color=cut)) + scale_y_reverse() +
geom_point() + facet_wrap(~clarity, scales="free") +
geom_segment(data=mockdf[mockdf$cut=="Fair",], aes(x=-Inf, xend=-Inf, y=55, yend=65)) +
geom_segment(data=mockdf[mockdf$cut=="Good",], aes(x=-Inf, xend=-Inf, y=60, yend=70)) +
geom_segment(data=mockdf[mockdf$cut=="Ideal",], aes(x=-Inf, xend=-Inf, y=65, yend=75))

#calls to position = position_dodge(width = #.#)) ...didn't work

How do I juggle the segments given the different scaling? An alternate long-winded solution would be to subset further on each facet level, for example:

ggplot(mockdf, aes(mockvar, depth, color=cut)) + scale_y_reverse() +
geom_point() + facet_wrap(~clarity, scales="free") +
geom_segment(data=mockdf[mockdf$cut=="Fair"& mockdf$clarity=="I1",], aes(x=49, xend=49, y=55, yend=65)) +
geom_segment(data=mockdf[mockdf$cut=="Good"& mockdf$clarity=="I1",], aes(x=49.5, xend=49.5, y=60, yend=70)) +
geom_segment(data=mockdf[mockdf$cut=="Ideal"& mockdf$clarity=="I1",], aes(x=50, xend=50, y=65, yend=75))
#and so on for all remaining facet levels....

But that's a lot of code and a crude 'jerry-rig' at best. Any suggestions for keeping the initial x|xend=-Inf for the first group, then nudging the next 2 segments relative to -Inf with consistent spacing globally across facets?

Body:
You'll have to switch off automatic axis expansion and then you can draw the segments where you want them.

require(dplyr)
require(ggplot2)

# Create mock dataframe, where facet variable ("mockvar") has different x-axis scales
mockdf <- filter(diamonds, cut=="Fair"|cut=="Good"|cut=="Ideal") %>%
  droplevels() %>% mutate(mockvar=ifelse(clarity=="SI2", 10*table,
                                         ifelse(clarity=="SI1", 100*table,
                                                ifelse(clarity=="VS2", 1000*table, table))))

# variables to control axis range and segment spacing
s1 = 0.9 # controls distance to minimum point
s2 = 0.03 # controls distance between segment lines

# add min and range variables
mockdf <- group_by(mockdf, clarity) %>%
  mutate(min = s1*min(mockvar),
         range = (2-s1)*max(mockvar) - s1*min(mockvar))

ggplot(mockdf, aes(mockvar, depth, color=cut)) + scale_y_reverse() +
  # switch off automatic axis expansion
  scale_x_continuous(expand = c(0, 0)) +
  geom_point() + facet_wrap(~clarity, scales="free") +
  geom_segment(data=mockdf[mockdf$cut=="Fair",],
               aes(x=min, xend=min, y=55, yend=65)) +
  geom_segment(data=mockdf[mockdf$cut=="Good",],
               aes(x=min + s2*range, xend=min + s2*range, y=60, yend=70)) +
  geom_segment(data=mockdf[mockdf$cut=="Ideal",],
               aes(x=min + 2*s2*range, xend=min + 2*s2*range, y=65, yend=75)) +
  # draw invisible segment to set end of x axis range
  geom_segment(data=mockdf[mockdf$cut=="Fair",],
               aes(x=min + range, xend=min + range, y=60, yend=70), color = NA)


问:
Euclidean greatest common divisor for more than two numbers
Can someone give an example for finding greatest common divisor algorithm for more than two numbers?

I believe programming language doesn't matter.

答:
For golang, using remainder</p>

```<code>func GetGCD(a, b int) int {
    for b != 0 {
        a, b = b, a%b
    }
    return a
}
func GetGCDFromList(numbers []int) int {
    var gdc = numbers[0]
    for i := 1; i < len(numbers); i++ {
        number := numbers[i]
        gdc  = GetGCD(gdc, number)
    }
    return gdc
}
</code>```

Body:
For golang, using remainder

func GetGCD(a, b int) int {
    for b != 0 {
        a, b = b, a%b
    }
    return a
}
func GetGCDFromList(numbers []int) int {
    var gdc = numbers[0]
    for i := 1; i < len(numbers); i++ {
        number := numbers[i]
        gdc  = GetGCD(gdc, number)
    }
    return gdc
}


问:
Removing arrow in ui-select box
In my AngularJS app I want to remove the default arrow from the ui-select box.

```<code>      <ui-select
        class="ui-select-no-arrow"
        ng-model="$ctrl.workoutHours"
        ng-change="$ctrl.updateHours($ctrl.workoutHours)"
        input-type="number"
        style="width: 3.5em"
        theme="bootstrap">
        <ui-select-match>{{ $ctrl.workoutHours }}</ui-select-match>
        <ui-select-choices
          repeat="hour in $ctrl.getHours($select.search) | filter: $select.search">
          {{ hour }}
        </ui-select-choices>
      </ui-select>
</code>```

Based on answers to similar question on Stack Overflow, I have attempted the following:

```<code>.ui-select-no-arrow {
  -webkit-appearance: none;
  -moz-appearance: none;
  text-indent: 1px;
  text-overflow: '';
}
</code>```

along with updating the class on the ui-select elements.  That has done nothing at all but if I change the  to  and do the following CSS:

```<code>select {
  -webkit-appearance: none;
  -moz-appearance: none;
  text-indent: 1px;
  text-overflow: '';
}
</code>```

that does indeed get rid of the arrow.  At least in Chrome and Firefox, anyway.

What do I need to do to get rid of the arrow in  as opposed to just ?

答:
Dead simple :)</p>

```<code>.caret {
  display: none;
}
</code>```

Title: Removing arrow in ui-select box

Body:
In my AngularJS app I want to remove the default arrow from the ui-select box.

      <ui-select
        class="ui-select-no-arrow"
        ng-model="$ctrl.workoutHours"
        ng-change="$ctrl.updateHours($ctrl.workoutHours)"
        input-type="number"
        style="width: 3.5em"
        theme="bootstrap">
        <ui-select-match>{{ $ctrl.workoutHours }}</ui-select-match>
        <ui-select-choices
          repeat="hour in $ctrl.getHours($select.search) | filter: $select.search">
          {{ hour }}
        </ui-select-choices>
      </ui-select>

Based on answers to similar question on Stack Overflow, I have attempted the following:

.ui-select-no-arrow {
  -webkit-appearance: none;
  -moz-appearance: none;
  text-indent: 1px;
  text-overflow: '';
}

along with updating the class on the ui-select elements.  That has done nothing at all but if I change the  to  and do the following CSS:

select {
  -webkit-appearance: none;
  -moz-appearance: none;
  text-indent: 1px;
  text-overflow: '';
}

that does indeed get rid of the arrow.  At least in Chrome and Firefox, anyway.

What do I need to do to get rid of the arrow in  as opposed to just ?

Body:
Dead simple :)

.caret {
  display: none;
}


问:
spark_sklearn GridSearchCV __init__ failed with parameter error
I am trying to use spark_sklearn.GridSearchCV, but got init parameter error.

```<code>TypeError: __init__() takes at least 4 arguments (4 given)
</code>```

This is the code:

```<code>from spark_sklearn import GridSearchCV

gsearch2 = GridSearchCV(estimator=ensemble.GradientBoostingRegressor(**params), param_grid=param_test2, n_jobs=1)
</code>```

If I give more parameters to GridSearchCV, such as add cv=5, then the error become

```<code>TypeError: __init__() takes at least 4 arguments (5 given)
</code>```

Any suggestion?

Thanks.

答:
GridSearchCV.__init__ takes 3 obligatory arguments:

sc - SparkContext.

estimator

param_grid.

You forgot the SparkContext:

```<code>GridSearchCV(
    sc=SparkContext.getOrCreate(),
    estimator=ensemble.GradientBoostingRegressor(**params),
    param_grid=param_test2, n_jobs=1)
</code>```

Body:
I am trying to use spark_sklearn.GridSearchCV, but got init parameter error.

TypeError: __init__() takes at least 4 arguments (4 given)

This is the code:

from spark_sklearn import GridSearchCV

gsearch2 = GridSearchCV(estimator=ensemble.GradientBoostingRegressor(**params), param_grid=param_test2, n_jobs=1)

If I give more parameters to GridSearchCV, such as add cv=5, then the error become

TypeError: __init__() takes at least 4 arguments (5 given)

Any suggestion?

Thanks.

Body:
GridSearchCV.__init__ takes 3 obligatory arguments:

sc - SparkContext.

estimator

param_grid.

You forgot the SparkContext:

GridSearchCV(
    sc=SparkContext.getOrCreate(),
    estimator=ensemble.GradientBoostingRegressor(**params),
    param_grid=param_test2, n_jobs=1)


问:
Laravel 5 composer wont update class not found
Whenever I do composer update or artisan cache:clear and I get the following error:

```<code>[Symfony\Component\Debug\Exception\FatalThrowableError]
Fatal error: Class 'Aws\Laravel\AwsServiceProvider' not found
</code>```

My app.php config file doesn't contain the AWS in the providers and or aliases. I've tried adding 'Aws\Laravel\AwsServiceProvider::class,' under providers and 'AWS => Aws\Laravel\AwsFacade::class,' under aliases but still the same issue. I think something is caching weird and doesn't recognize the updates I'm doing on app.php config file.

答:
delete the files (not the directory) in bootstrap/cache

run composer dump-autoload

remove config/aws.php if it exists

run composer install

Body:
Whenever I do composer update or artisan cache:clear and I get the following error:

[Symfony\Component\Debug\Exception\FatalThrowableError]
Fatal error: Class 'Aws\Laravel\AwsServiceProvider' not found

My app.php config file doesn't contain the AWS in the providers and or aliases. I've tried adding 'Aws\Laravel\AwsServiceProvider::class,' under providers and 'AWS => Aws\Laravel\AwsFacade::class,' under aliases but still the same issue. I think something is caching weird and doesn't recognize the updates I'm doing on app.php config file.


问:
I'm not sure what I am doing wrong in this try catch block
```<code>int memberChoice;
    boolean accountLoop = true;
    while (accountLoop) {
        try {
            System.out.println("Would you like to be a... \n1.Basic Member or \n2.Premium member");
            memberChoice = input.nextInt();
            if (memberChoice == 1 || memberChoice == 2) {
                accountLoop = false;
            }
            if (memberChoice < 1 || memberChoice > 2) {
                System.out.println("Please choose either 1 or 2");
            }
            System.out.println();
        } catch (InputMismatchException e) {
            System.out.println("Invalid input");
        }
    }
</code>```

Whenever I type a string it should say invalid input go back to the beginning of the loop and direct me to input a number again. Instead it gives me an infinite loop. I feel like its something really small but I've been at this for 5 hours and can't figure it out. Any suggestions?

答:
Add input = new Scanner(System.in); to the catch block as I assume you are reading from standard input with a Scanner...

This will re-initialise the scanner when something went wrong.

When putting in a "string" the scanner will try to read this as a nextInt() and that just will keep on failing unless you initialise it again...

Body:
int memberChoice;
    boolean accountLoop = true;
    while (accountLoop) {
        try {
            System.out.println("Would you like to be a... \n1.Basic Member or \n2.Premium member");
            memberChoice = input.nextInt();
            if (memberChoice == 1 || memberChoice == 2) {
                accountLoop = false;
            }
            if (memberChoice < 1 || memberChoice > 2) {
                System.out.println("Please choose either 1 or 2");
            }
            System.out.println();
        } catch (InputMismatchException e) {
            System.out.println("Invalid input");
        }
    }

Whenever I type a string it should say invalid input go back to the beginning of the loop and direct me to input a number again. Instead it gives me an infinite loop. I feel like its something really small but I've been at this for 5 hours and can't figure it out. Any suggestions?


问:
How to make spring social facebook work on localhost using ngrok tunneling
I want to send a message to my facebook page using my user credentials and using ngrok to make a localhost tunnel so that facebook can reach my machine. However I am still getting a bad request (500) telling me I havn't registered any domains or supdomains.

On developers.facebook.com I have something like this in my App domains: 04cda25e.ngrok.io

and I have this in my site Url https://04cda25e.ngrok.io/

This is my code:

```<code>//https://stackoverflow.com/questions/13376710/facebook-app-domain-name-when-using-localhost Ik krijg badrequest omdat ik geen appdomain opgegeven heb
    public void postToFacebook(){
        FacebookConnectionFactory connectionFactory =
                new FacebookConnectionFactory("1783242201976620", "******");

        OAuth2Operations oauthOperations = connectionFactory.getOAuthOperations();
        OAuth2Parameters params = new OAuth2Parameters();
        params.setRedirectUri("https://04cda25e.ngrok.io/1234");

//appid:1783242201976620 <<<<< not really an appid
//apptoken:Ycics4TEiCAs9JZXyHD4I489D6M <<<< this is like a mock apptoken. Totally not a real one that's for sure...

        params.setScope("public_profile,email,user_birthday");

// upon receiving the callback from the provider: http://massapi.com/method/an/andExpect.html
        AccessGrant accessGrant = oauthOperations.exchangeCredentialsForAccess("*****", "****",params);
        Connection<Facebook> connection = connectionFactory.createConnection(accessGrant);
        Facebook facebook = connection.getApi();
        //facebook.pageOperations().
         facebook.feedOperations().updateStatus("I'm trying out Spring Social!");

    }
</code>```

It throws the 500 error at the point where I'm trying to get the accessgrant.

Can someone please help?

EDIT: Heres a screenshot taken from my facebook settings: https://pasteboard.co/GXjfojs.png

Anyone have a clue on what I should change?

答:
Well I haven't found a solution to my problem, but I have found a workaround that enables accessing a facebookpage without using Spring social to get an access grant. It goes like this:

1) login to facebookdeveloper

2) go to Tools & Support

3)Select Graph API explorer, with this you can request an access token manually.

4) press the get Token button and select the type you want

5) select the permissions you would like your app to have for that page and click 'Get Access Token

6)Facebook produces a String which is the Access token. Use this to instantiate an AccessGrant object in java by including this string in the AccessGrant constructor.

7) use this AccessGrant to create a connection and voila!

Hope this helps anyone..

Body:
I want to send a message to my facebook page using my user credentials and using ngrok to make a localhost tunnel so that facebook can reach my machine. However I am still getting a bad request (500) telling me I havn't registered any domains or supdomains.

On developers.facebook.com I have something like this in my App domains: 04cda25e.ngrok.io

and I have this in my site Url https://04cda25e.ngrok.io/

This is my code:

//https://stackoverflow.com/questions/13376710/facebook-app-domain-name-when-using-localhost Ik krijg badrequest omdat ik geen appdomain opgegeven heb
    public void postToFacebook(){
        FacebookConnectionFactory connectionFactory =
                new FacebookConnectionFactory("1783242201976620", "******");

        OAuth2Operations oauthOperations = connectionFactory.getOAuthOperations();
        OAuth2Parameters params = new OAuth2Parameters();
        params.setRedirectUri("https://04cda25e.ngrok.io/1234");

//appid:1783242201976620 <<<<< not really an appid
//apptoken:Ycics4TEiCAs9JZXyHD4I489D6M <<<< this is like a mock apptoken. Totally not a real one that's for sure...

        params.setScope("public_profile,email,user_birthday");

// upon receiving the callback from the provider: http://massapi.com/method/an/andExpect.html
        AccessGrant accessGrant = oauthOperations.exchangeCredentialsForAccess("*****", "****",params);
        Connection<Facebook> connection = connectionFactory.createConnection(accessGrant);
        Facebook facebook = connection.getApi();
        //facebook.pageOperations().
         facebook.feedOperations().updateStatus("I'm trying out Spring Social!");

    }

It throws the 500 error at the point where I'm trying to get the accessgrant.

Can someone please help?

EDIT: Heres a screenshot taken from my facebook settings: https://pasteboard.co/GXjfojs.png

Anyone have a clue on what I should change?


问:
Removing \r from lines read from file
I am having a weird problem. I read a text file then I split it using \n as a delimiter. I noticed that the split lines contain '\r' at the end. So I am trying to remove it, I tried doing so using String.Replace but without luck. Here is my code:

```<code>    string fileOutput = File.ReadAllText(location);
    SettingsManager.proxies.Clear();
    foreach (string line in fileOutput.Split('\n'))
    {
        string cleanLine = line;
        if (cleanLine.Contains("\r")) cleanLine.Replace("\r", "");
        SettingsManager.proxies.Add(cleanLine);
    }
</code>```

EDIT: After staring at the code for 1 min, I found that I didn't assign the replaced value to the original string.

```<code>cleanLine.Replace("\r",""); //assigns a value to nothing
</code>```

I should have assigned cleanLine to cleanLine.Replace();

```<code>cleanLine = cleanLine.Replace("\r","");
</code>```

答:
If you call:

```<code>string[] lines = File.ReadAllLines(location);
</code>```

it will remove both the '\r' and '\n' from each line for you.

Title: Removing \r from lines read from file

Body:
I am having a weird problem. I read a text file then I split it using \n as a delimiter. I noticed that the split lines contain '\r' at the end. So I am trying to remove it, I tried doing so using String.Replace but without luck. Here is my code:

    string fileOutput = File.ReadAllText(location);
    SettingsManager.proxies.Clear();
    foreach (string line in fileOutput.Split('\n'))
    {
        string cleanLine = line;
        if (cleanLine.Contains("\r")) cleanLine.Replace("\r", "");
        SettingsManager.proxies.Add(cleanLine);
    }

EDIT: After staring at the code for 1 min, I found that I didn't assign the replaced value to the original string.

cleanLine.Replace("\r",""); //assigns a value to nothing

I should have assigned cleanLine to cleanLine.Replace();

cleanLine = cleanLine.Replace("\r","");

Body:
If you call:

string[] lines = File.ReadAllLines(location);

it will remove both the '\r' and '\n' from each line for you.


问:
how to upload at new name and section
I have a problem that made me lose my temper really I have the following code
OK ?

```<code>$sections = array("Other","Romance","Horror","Sucid","Dance","Comedy");

$vedioname = $_POST['vedionamet'];

$path = $_POST['selectsection'];

$finalpath =realpath(dirname(__FILE__)."/Uploads/".$path);

$vedname= $_FILES['vedio']['name'];

$temp=$_FILES['vedio']['tmp_name'];

$type = $_FILES["vedio"]['type'];

$size = $_FILES['vedio']['size'];

$errors = $_FILES['vedio']['error'];

if($_POST['uploadsub']){

move_uploaded_file($temp,$finalpath.$vedioname);

echo "Done Uploaded".$type;

}else
{
 echo "$error";
}
</code>```

The first problem is supposed to be the process of uploading the file to file uploads
The file is not even uploaded to the same file as the page
Second, the goal is to write the name of the file uploaded within the text, but what is happening in reverse exactly that
So how to make the upload process successful
Inside the uploads / value received from the form section
And the new name of the received value of the form

```<code>    <form action="<?php echo $PHP_SELF; ?>" method="post" enctype="multipart/form-data">
    <div id="inputs">
    <label class="labels" for="name">Vedio Name: </label>
        <input id="name" type="text" name="vedionamet" value="vedio"> </br>
        <label class="labels" for="selectsection">Select Section :</label>
        <select name="selectsection" id="section" >

            <?php
            foreach($sections as $pathat){
                echo "<option value='$pathat'>" . "$pathat" . "</option>";

            };
            ?>
        </select></br>
        <label class="labels" for="upup">Select Vedio : </label>
        <input id="upload" type="file" name="vedio"></br>
        <input id="subb" type="submit" name="uploadsub" value="Upload">
        </
</code>```

答:
For the HTML part, you may change the action to "#" if you want to use a same page to handle the upload request.

For the PHP part, you may try the following codes, it works on my computer. Please also make sure that you have already established these sub video folders in Uploads folder

```<code><?php
$sections = array("Other","Romance","Horror","Sucid","Dance","Comedy");
//add one condition to avoid warning when the page first loads
if(isset($_POST["selectsection"])){

    $vedioname = $_POST['vedionamet'];

    $path = $_POST['selectsection'];

    //Use this to get the path
    $finalpath = realpath(dirname(getcwd())) . '\\Uploads\\' . $path. '\\';

    $vedname= $_FILES['vedio']['name'];

    $temp=$_FILES['vedio']['tmp_name'];

    //Use this to get the extension of file name
    $type = pathinfo($vedname, PATHINFO_EXTENSION);

    $size = $_FILES['vedio']['size'];

    $errors = $_FILES['vedio']['error'];

    if($_POST['uploadsub']){

    move_uploaded_file($temp,$finalpath.$vedioname.".".$type);

    echo "Done Uploaded".$type;

    }else
    {
    echo "$error";
    }
}

?>
</code>```

Title: how to upload at new name and section

Body:
I have a problem that made me lose my temper really I have the following code
OK ?

$sections = array("Other","Romance","Horror","Sucid","Dance","Comedy");

$vedioname = $_POST['vedionamet'];

$path = $_POST['selectsection'];

$finalpath =realpath(dirname(__FILE__)."/Uploads/".$path);

$vedname= $_FILES['vedio']['name'];

$temp=$_FILES['vedio']['tmp_name'];

$type = $_FILES["vedio"]['type'];

$size = $_FILES['vedio']['size'];

$errors = $_FILES['vedio']['error'];

if($_POST['uploadsub']){

move_uploaded_file($temp,$finalpath.$vedioname);

echo "Done Uploaded".$type;

}else
{
 echo "$error";
}

The first problem is supposed to be the process of uploading the file to file uploads
The file is not even uploaded to the same file as the page
Second, the goal is to write the name of the file uploaded within the text, but what is happening in reverse exactly that
So how to make the upload process successful
Inside the uploads / value received from the form section
And the new name of the received value of the form

    <form action="<?php echo $PHP_SELF; ?>" method="post" enctype="multipart/form-data">

    Vedio Name:
        <input id="name" type="text" name="vedionamet" value="vedio">

        Select Section :
        <select name="selectsection" id="section" >

            <?php
            foreach($sections as $pathat){
                echo "<option value='$pathat'>" . "$pathat" . "</option>";

            };
            ?>
        </select>

        Select Vedio :
        <input id="upload" type="file" name="vedio">

        <input id="subb" type="submit" name="uploadsub" value="Upload">
        </

Body:
For the HTML part, you may change the action to "#" if you want to use a same page to handle the upload request.

For the PHP part, you may try the following codes, it works on my computer. Please also make sure that you have already established these sub video folders in Uploads folder

<?php
$sections = array("Other","Romance","Horror","Sucid","Dance","Comedy");
//add one condition to avoid warning when the page first loads
if(isset($_POST["selectsection"])){

    $vedioname = $_POST['vedionamet'];

    $path = $_POST['selectsection'];

    //Use this to get the path
    $finalpath = realpath(dirname(getcwd())) . '\\Uploads\\' . $path. '\\';

    $vedname= $_FILES['vedio']['name'];

    $temp=$_FILES['vedio']['tmp_name'];

    //Use this to get the extension of file name
    $type = pathinfo($vedname, PATHINFO_EXTENSION);

    $size = $_FILES['vedio']['size'];

    $errors = $_FILES['vedio']['error'];

    if($_POST['uploadsub']){

    move_uploaded_file($temp,$finalpath.$vedioname.".".$type);

    echo "Done Uploaded".$type;

    }else
    {
    echo "$error";
    }
}

?>


问:
Manipulating window.history affects favicon on IE11
Here's the scenario:
The site has a favicon already cached (/favicon.ico file) and I want to change it. It can be easily achieved (by adding a querystring to favicon's path: favicon.ico?v2). But, any state change (by calling window.history.pushState() or window.history.replaceState()) changes the favicon to the old one.

It looks like IE11 is taking favicon.ico from BASE directory which is unfortunately cached (favicon.ico?v2 is treated as a different entity in IE11's cache).

It's worth mentioning that the problem is not occurring when manipulating location.hash.
So changing state from:

```<code>http://x.com
</code>```

to:

```<code>http://x.com/#id=5
</code>```

has no affect on the favicon. But changing state to:

```<code>http://x.com/?id=5
</code>```

switches the favicon to the old one (if it's cached) or default from IE11.
As soon as I do a browser refresh the new favicon is shown.

This was already reported as a bug on IE11, but Microsoft decided to leave it. I found two related questions:
using history.pushState in Firefox make my favicon disappear &
history.pushState in Chrome make favicon request
but none provides a solution to my problem.

I've also tried to update the favicon's reference after changing the state (by updating link href attribute) - it helped on Edge but not on IE11. the browser is actually sending a new favicon request, but it still shows the old one.

I'm looking for a way of keeping the favicon after changing the state.
The alternative solution can be to programmatically forcing IE11 to reload favicon.ico file (let's assume that Expires header was not set).

答:
There is a solution, but it's quite hacky.

The Problem is, that IE caches the favicons seperately and they will only be loaded, if the entire page is. The pushState just checks the existing cache and will only show favicons of pages that have been loaded before. If pushState has not been used you can change the favicon with JavaScript, afterwards, you can't.

The favicon cache however is updated live, so you can do the following:

Set up a hidden iframe on your page.

Before calling pushState, load the page you need with an additional hash (e.g #onlyFavicon) in the iframe (make sure to use replace otherwise the ifarem will interfere with your history).

Have your server - or a javaScript - check for your hash on pageload and serve an empty page with just the favicon.

Once the iframe has loaded, your favicon cache is updated with the new favicon (add an onLoad eventlistener to the iframe to know when) No Need to wait, the favicon gets updated automtically once the iframe has loaded.

If you call pushState now, the favicon will be displayed correctly

I know it's hacky and late, but i hope it helps anyone who stumbles over this problem as well.

Body:
Here's the scenario:
The site has a favicon already cached (/favicon.ico file) and I want to change it. It can be easily achieved (by adding a querystring to favicon's path: favicon.ico?v2). But, any state change (by calling window.history.pushState() or window.history.replaceState()) changes the favicon to the old one.

It looks like IE11 is taking favicon.ico from BASE directory which is unfortunately cached (favicon.ico?v2 is treated as a different entity in IE11's cache).

It's worth mentioning that the problem is not occurring when manipulating location.hash.
So changing state from:

http://x.com

to:

http://x.com/#id=5

has no affect on the favicon. But changing state to:

http://x.com/?id=5

switches the favicon to the old one (if it's cached) or default from IE11.
As soon as I do a browser refresh the new favicon is shown.

This was already reported as a bug on IE11, but Microsoft decided to leave it. I found two related questions:
using history.pushState in Firefox make my favicon disappear &
history.pushState in Chrome make favicon request
but none provides a solution to my problem.

I've also tried to update the favicon's reference after changing the state (by updating link href attribute) - it helped on Edge but not on IE11. the browser is actually sending a new favicon request, but it still shows the old one.

I'm looking for a way of keeping the favicon after changing the state.
The alternative solution can be to programmatically forcing IE11 to reload favicon.ico file (let's assume that Expires header was not set).


问:
ImageView selectableItemBackgroundBorderless does not render outside of view bounds
I am using selectableItemBackgroundBorderless to add a ripple to an ImageView.
My expected behaviour would be to have a circular ripple, extending the views size. Unfortunately the ripple gets cropped by the view bounds.
How can this issue be solved?

Default state:

Pressed state:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/nav_instruction_container"
    android:layout_width="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_height="wrap_content"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="@drawable/nav_gradient_bg"
    android:padding="20dp">
    <ImageView
        android:id="@+id/nav_sign"
        android:layout_width="wrap_content"
        android:layout_height="46dp"
        android:layout_centerVertical="true"
        android:scaleType="centerInside"
        android:adjustViewBounds="true"
        />

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/nav_sign"
        android:layout_marginLeft="24dp"
        android:layout_marginStart="24dp"
        android:layout_marginRight="24dp"
        android:layout_marginEnd="24dp"
        android:textColor="@color/white"
        android:textSize="24sp"
        android:textStyle="bold"
        android:maxLines="2"
        tools:text="A644 Shudehill asdfkjasdf asdfasdf asdfsss"
        android:ellipsize="marquee"
        />

    <TextView
        android:id="@+id/subTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/title"
        android:layout_toRightOf="@+id/nav_sign"
        android:layout_marginLeft="24dp"
        android:layout_marginStart="24dp"
        android:layout_marginRight="24dp"
        android:layout_marginEnd="24dp"
        android:textColor="@color/white"
        android:textSize="17sp"
        tools:text="via Church St"
        />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        app:srcCompat="@drawable/ic_nav_queue_sheet_icon_light"
        android:id="@+id/nav_queue"
        android:scaleType="centerInside"
        android:foreground="?attr/selectableItemBackgroundBorderless"
        android:adjustViewBounds="true"/>
</RelativeLayout>
</code>```

答:
Define ripple_effect_circle.xml in drawable

```<code><?xml version="1.0" encoding="utf-8"?> <ripple xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:color="#BDBDBD"
    >

    <item android:id="@android:id/mask">
        <shape android:shape="oval">
            <size
                android:width="60dp"
                android:height="60dp"/>
            <solid android:color="#BDBDBD" />
        </shape>
    </item>

</ripple>
</code>```

Define ImageView in layout

```<code>    <ImageView
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_margin="60dp"
            android:src="@drawable/ripple_effect_circle"
            android:background="@drawable/your_round_image"
            />
</code>```

Body:
I am using selectableItemBackgroundBorderless to add a ripple to an ImageView.
My expected behaviour would be to have a circular ripple, extending the views size. Unfortunately the ripple gets cropped by the view bounds.
How can this issue be solved?

Default state:

Pressed state:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/nav_instruction_container"
    android:layout_width="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_height="wrap_content"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="@drawable/nav_gradient_bg"
    android:padding="20dp">
    <ImageView
        android:id="@+id/nav_sign"
        android:layout_width="wrap_content"
        android:layout_height="46dp"
        android:layout_centerVertical="true"
        android:scaleType="centerInside"
        android:adjustViewBounds="true"
        />

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/nav_sign"
        android:layout_marginLeft="24dp"
        android:layout_marginStart="24dp"
        android:layout_marginRight="24dp"
        android:layout_marginEnd="24dp"
        android:textColor="@color/white"
        android:textSize="24sp"
        android:textStyle="bold"
        android:maxLines="2"
        tools:text="A644 Shudehill asdfkjasdf asdfasdf asdfsss"
        android:ellipsize="marquee"
        />

    <TextView
        android:id="@+id/subTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/title"
        android:layout_toRightOf="@+id/nav_sign"
        android:layout_marginLeft="24dp"
        android:layout_marginStart="24dp"
        android:layout_marginRight="24dp"
        android:layout_marginEnd="24dp"
        android:textColor="@color/white"
        android:textSize="17sp"
        tools:text="via Church St"
        />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        app:srcCompat="@drawable/ic_nav_queue_sheet_icon_light"
        android:id="@+id/nav_queue"
        android:scaleType="centerInside"
        android:foreground="?attr/selectableItemBackgroundBorderless"
        android:adjustViewBounds="true"/>
</RelativeLayout>

Body:
Define ripple_effect_circle.xml in drawable

<?xml version="1.0" encoding="utf-8"?> <ripple xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:color="#BDBDBD"
    >

    <item android:id="@android:id/mask">
        <shape android:shape="oval">
            <size
                android:width="60dp"
                android:height="60dp"/>
            <solid android:color="#BDBDBD" />
        </shape>
    </item>

</ripple>

Define ImageView in layout

    <ImageView
            android:layout_width="60dp"
            android:layout_height="60dp"
            android:layout_margin="60dp"
            android:src="@drawable/ripple_effect_circle"
            android:background="@drawable/your_round_image"
            />


问:
Xcode View Debugger: How can I reveal in the hierarchy the selection in the 3-D inspector?
In the Xcode 9 view debugger, I'd like to select a view in the 3-D exploded diagram of views, and then reveal that view in the hierarchy on the left. I know I can "focus" on that view by double-clicking it or selecting "Focus on UIView" from the contextual menu. I know I can also filter by some part of the type of view I want to find, but I actually just want to view I have selected in the context of the complete hierarchy in a single step. I haven't found a way of doing this-- am I missing something?</p>

答:
You can use the Xcode menu item "Navigate / Reveal in Debug Navigator" to reveal the selected item in the outline view.

Or the convenient keyboard shortcut ⌘ + Shift + D.


问:
Trouble with elementary equation using variables in Java
new programmer here

I am currently trying to to have a little fun of Friday night and whip up a quick calculator to  show fantasy football scores and it won't work

```<code>import java.util.Scanner;
public class Players {

    public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    // Prompt user to enter how many catches
    System.out.print("How many catches did the player have? ");
    int catches = input.nextInt();

    //Prompts user to enter how many receiving yards
    System.out.print("How many yards receiving did the player have? ");
    int recYards = input.nextInt();

    //Prompts user to enter how many rushing yards
    System.out.print("How many yards rushing did the player have? ");
    int rushYards = input.nextInt();

    //Prompts user to enter how many touchdowns
    System.out.print("How many touchdowns did the player have? ");
    int touchDowns = input.nextInt();

    **//Calculates score
    int points = (catches + (recYards % 10) + (rushYards % 10) + (touchDowns * 6));**

    // Shows score
    System.out.print("Your score is " + points );

    }

}
</code>```

I have bolded the problem section in question.

For instance, it gives me scores like this

How many catches did the player have? 10 (This should be 10 points)
How many yards receiving did the player have? 100 (This should be 10 points)
How many yards rushing did the player have? 50 (This should be 5 points)
How many touchdowns did the player have? 2 (This should be 12 points)
Your score is 22.0 (This should be 37 points)

Could somebody help explain what's going wrong here?

答: I think you mixed modulus % with divide / up. Modulus gives you the remaining portion of the division. So, for example, 12 mod 10 equals 2.

Body:
new programmer here

I am currently trying to to have a little fun of Friday night and whip up a quick calculator to  show fantasy football scores and it won't work

import java.util.Scanner;
public class Players {

    public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    // Prompt user to enter how many catches
    System.out.print("How many catches did the player have? ");
    int catches = input.nextInt();

    //Prompts user to enter how many receiving yards
    System.out.print("How many yards receiving did the player have? ");
    int recYards = input.nextInt();

    //Prompts user to enter how many rushing yards
    System.out.print("How many yards rushing did the player have? ");
    int rushYards = input.nextInt();

    //Prompts user to enter how many touchdowns
    System.out.print("How many touchdowns did the player have? ");
    int touchDowns = input.nextInt();

    **//Calculates score
    int points = (catches + (recYards % 10) + (rushYards % 10) + (touchDowns * 6));**

    // Shows score
    System.out.print("Your score is " + points );

    }

}

I have bolded the problem section in question.

For instance, it gives me scores like this

How many catches did the player have? 10 (This should be 10 points)
How many yards receiving did the player have? 100 (This should be 10 points)
How many yards rushing did the player have? 50 (This should be 5 points)
How many touchdowns did the player have? 2 (This should be 12 points)
Your score is 22.0 (This should be 37 points)

Could somebody help explain what's going wrong here?


问:
Move an image to the left every time I press enter
The image moves to the left once correctly, but afterwards I press enter again it doesn't move. I'm looking for it to move left 10 more pixels everytime I press enter. Thanks</p>

```<code>    document.body.addEventListener("keydown", function (event) {
        if (event.keyCode === 13)  {

       document.getElementById("wagon").style.left=-10 + "px";
   }
  });
</code>```

答:
It was because you just assigned -10px to the element every time you did keydown, so left would always be -10px. You need to extract the number from left and subtract 10 and do some modification.

This will do the job.

```<code>var leftStr = document.getElementById("wagon").style.left;
var indexOfpx = leftStr.indexOf("px");
var num = leftStr.substring(0, indexOfpx); // extract the number part
var leftPx = Number(num) - 10 + "px";
document.getElementById("wagon").style.left = leftPx;
</code>```

Body:
The image moves to the left once correctly, but afterwards I press enter again it doesn't move. I'm looking for it to move left 10 more pixels everytime I press enter. Thanks

    document.body.addEventListener("keydown", function (event) {
        if (event.keyCode === 13)  {

       document.getElementById("wagon").style.left=-10 + "px";
   }
  });

Body:
It was because you just assigned -10px to the element every time you did keydown, so left would always be -10px. You need to extract the number from left and subtract 10 and do some modification.

This will do the job.

var leftStr = document.getElementById("wagon").style.left;
var indexOfpx = leftStr.indexOf("px");
var num = leftStr.substring(0, indexOfpx); // extract the number part
var leftPx = Number(num) - 10 + "px";
document.getElementById("wagon").style.left = leftPx;


问:
PHP Regular expression tag matching
Been beating my head against a wall trying to get this to work - help from any regex gurus would be greatly appreciated!

The text that has to be matched

```<code>[template option="whatever"]

<p>any amount of html would go here</p>

[/template]
</code>```

I need to pull the 'option' value (i.e. 'whatever') and the html between the template tags.

So far I have:

```<code>> /\[template\s*option=["\']([^"\']+)["\']\]((?!\[\/template\]))/
</code>```

Which gets me everything except the html between the template tags.

Any ideas?

Thanks, Chris

答:
Chris,

I see you've already accepted an answer. Great!

However, I don't think use of regular expressions is the right solution here. I think you can get the same effect by using string manipulations (substrings, etc)

Here is some code that may help you. If not now, maybe later in your coding endeavors.

```<code><?php

    $string = '[template option="whatever"]<p>any amount of html would go here</p>[/template]';

    $extractoptionline = strstr($string, 'option=');
    $chopoff = substr($extractoptionline,8);
    $option = substr($chopoff, 0, strpos($chopoff, '"]'));

    echo "option: $option<br \>\n";

    $extracthtmlpart = strstr($string, '"]');
    $chopoffneedle = substr($extracthtmlpart,2);
    $html = substr($chopoffneedle, 0, strpos($chopoffneedle, '[/'));

    echo "html: $html<br \>\n";

?>
</code>```

Hope this helps anyone looking for a similar answer with a different flavor.

Title: PHP Regular expression tag matching

Body:
Been beating my head against a wall trying to get this to work - help from any regex gurus would be greatly appreciated!

The text that has to be matched

[template option="whatever"]

any amount of html would go here

[/template]

I need to pull the 'option' value (i.e. 'whatever') and the html between the template tags.

So far I have:

> /\[template\s*option=["\']([^"\']+)["\']\]((?!\[\/template\]))/

Which gets me everything except the html between the template tags.

Any ideas?

Thanks, Chris

Body:
Chris,

I see you've already accepted an answer. Great!

However, I don't think use of regular expressions is the right solution here. I think you can get the same effect by using string manipulations (substrings, etc)

Here is some code that may help you. If not now, maybe later in your coding endeavors.

<?php

    $string = '[template option="whatever"]<p>any amount of html would go here</p>[/template]';

    $extractoptionline = strstr($string, 'option=');
    $chopoff = substr($extractoptionline,8);
    $option = substr($chopoff, 0, strpos($chopoff, '"]'));

    echo "option: $option<br \>\n";

    $extracthtmlpart = strstr($string, '"]');
    $chopoffneedle = substr($extracthtmlpart,2);
    $html = substr($chopoffneedle, 0, strpos($chopoffneedle, '[/'));

    echo "html: $html<br \>\n";

?>

Hope this helps anyone looking for a similar answer with a different flavor.


问:
Get data from Datagridview and put in dictionary c#
I have a datagridview contains 2 columns. "Email" and "Amount".
I just want to get data from these two columns and put in data-dictionary, EMAIL as Key and the AMOUNT as Value.
How could i get this? </p>

答:
```<code>Dictionary<String, Int32> myDic = new Dictionary<String, Int32>();

foreach (DataGridViewRow row in myDGV.Rows)
{
    String mail = row.Cells["Mail"].Value;
    Int32 amount = row.Cells["Amount"].Value;

    if (myDict.ContainsKey(mail))
        myDic[mail] += amount;
    else
        myDic.Add(mail, amount);
}
</code>```

You can also use an indexed approach where 0 is the index of your Mail column and 1 is the index of your Amount column:

```<code>foreach (DataGridViewRow row in myDGV.Rows)
{
    String mail = row.Cells[0].Value;
    Int32 amount = row.Cells[1].Value;

    if (myDict.ContainsKey(mail))
        myDic[mail] += amount;
    else
        myDic.Add(mail, amount);
}
</code>```

If your DataGridView contains rows with the same mail, my code handles this case by incrementing the respective Dictionary value.

Body:
Dictionary<String, Int32> myDic = new Dictionary<String, Int32>();

foreach (DataGridViewRow row in myDGV.Rows)
{
    String mail = row.Cells["Mail"].Value;
    Int32 amount = row.Cells["Amount"].Value;

    if (myDict.ContainsKey(mail))
        myDic[mail] += amount;
    else
        myDic.Add(mail, amount);
}

You can also use an indexed approach where 0 is the index of your Mail column and 1 is the index of your Amount column:

foreach (DataGridViewRow row in myDGV.Rows)
{
    String mail = row.Cells[0].Value;
    Int32 amount = row.Cells[1].Value;

    if (myDict.ContainsKey(mail))
        myDic[mail] += amount;
    else
        myDic.Add(mail, amount);
}

If your DataGridView contains rows with the same mail, my code handles this case by incrementing the respective Dictionary value.


问:
Example CrossEntropyLoss for 3D semantic segmentation in pytorch
I have a network performing 3D convolutions on a 5D input tensor. The output of my network if of size (1, 12, 60, 36, 60) corresponding to ( BatchSize, NumClasses, x-dim, y-dim, z-dim). I need to compute a voxel-wise cross entropy loss. However I keep on getting errors.

When trying to compute cross entropy loss using torch.nn.CrossEntropyLoss(), I keep on getting the following error message:

```<code>RuntimeError: multi-target not supported at .../src/THCUNN/generic/ClassNLLCriterion.cu:16
</code>```

here is the extract of my code:

```<code>import torch
import torch.nn as nn
from torch.autograd import Variable
criterion = torch.nn.CrossEntropyLoss()
images = Variable(torch.randn(1, 12, 60, 36, 60)).cuda()
labels = Variable(torch.zeros(1, 12, 60, 36, 60).random_(2)).long().cuda()
loss = criterion(images.view(1,-1), labels.view(1,-1))
</code>```

Same happens when I create a one-hot tensor for the labels:

```<code>nclasses = 12
labels = (np.random.randint(0,12,(1,60,36,60))) # Random labels with values between [0..11]
labels = (np.arange(nclasses) == labels[..., None] - 1).astype(int) # Converts labels to one_hot_tensor
a = np.transpose(labels,(0,4,3,2,1)) #  Reorder dimensions to match shape of "images" ([1, 12, 60, 36, 60])
b = Variable(torch.from_numpy(a)).cuda()
loss = criterion(images.view(1,-1), b.view(1,-1))
</code>```

Any idea what I'm doing wrong?
Can someone provide an example of computing cross entropy on a 5D output tensor?

答:
The docs explain this behavior (bottom line, it looks like it's actually computing the sparse Cross Entropy Loss, thereby not requiring targets for all dimensions of the output, but only the index of the required one) ... they specifically state:

```<code>Input: (N,C), where C = number of classes
Target: (N), where each value is 0 <= targets[i] <= C-1
Output: scalar. If reduce is False, then (N) instead.
</code>```

I'm not sure about your use-case, but you might want to use the KL Divergence or the Binary Cross Entropy Loss instead. Both are defined over inputs and targets of equal size.

Body:
I have a network performing 3D convolutions on a 5D input tensor. The output of my network if of size (1, 12, 60, 36, 60) corresponding to ( BatchSize, NumClasses, x-dim, y-dim, z-dim). I need to compute a voxel-wise cross entropy loss. However I keep on getting errors.

When trying to compute cross entropy loss using torch.nn.CrossEntropyLoss(), I keep on getting the following error message:

RuntimeError: multi-target not supported at .../src/THCUNN/generic/ClassNLLCriterion.cu:16

here is the extract of my code:

import torch
import torch.nn as nn
from torch.autograd import Variable
criterion = torch.nn.CrossEntropyLoss()
images = Variable(torch.randn(1, 12, 60, 36, 60)).cuda()
labels = Variable(torch.zeros(1, 12, 60, 36, 60).random_(2)).long().cuda()
loss = criterion(images.view(1,-1), labels.view(1,-1))

Same happens when I create a one-hot tensor for the labels:

nclasses = 12
labels = (np.random.randint(0,12,(1,60,36,60))) # Random labels with values between [0..11]
labels = (np.arange(nclasses) == labels[..., None] - 1).astype(int) # Converts labels to one_hot_tensor
a = np.transpose(labels,(0,4,3,2,1)) #  Reorder dimensions to match shape of "images" ([1, 12, 60, 36, 60])
b = Variable(torch.from_numpy(a)).cuda()
loss = criterion(images.view(1,-1), b.view(1,-1))

Any idea what I'm doing wrong?
Can someone provide an example of computing cross entropy on a 5D output tensor?

Body:
The docs explain this behavior (bottom line, it looks like it's actually computing the sparse Cross Entropy Loss, thereby not requiring targets for all dimensions of the output, but only the index of the required one) ... they specifically state:

Input: (N,C), where C = number of classes
Target: (N), where each value is 0 <= targets[i] <= C-1
Output: scalar. If reduce is False, then (N) instead.

I'm not sure about your use-case, but you might want to use the KL Divergence or the Binary Cross Entropy Loss instead. Both are defined over inputs and targets of equal size.