问:
How McCarthy 91 function works
I have following function based on McCarthy 91 principle:

```<code>mc91 :: Integer -> Integer
mc91 n
    | n > 100 = n - 10
    | otherwise = mc91 (mc91 (n + 11))
</code>```

when I type in the prelude mc91 85 I've got 91.

I could not configure it out, how it is expanded and why do I've got 91.

答:
Let's first analyze the function. There are two cases:

in the case n > 100, then we return n-10; and

in the case n <= 100, then we calculate n+11, and we do two additional steps.

There are thus two possible "steps": one where we decrement with 10, and one where we increment with 11. We can visualize this with a graph, like:

The edges of the first case are denoted in black, the edges of the latter case are denoted in red.

What we notice is that there is a loop here: 92 -> 103 -> 93 -> 104 -> 94 -> 105 -> 95 -> 106 -> 96 -> 107 -> 97 -> 108 -> 98 -> 109 -> 99 -> 110 -> 100 -> 111 -> 101 -> 91 -> ...

Let's assume for now that - regardless of the original value - we will always end up in that loop. Now the loop always interleaves a black edge, and a red edge, except for the 111 -> 101 -> 91 part, which consists out of two black edges.

Since a red edge introduces two additional recursive calls, that means that, if we take a red hop, we get the next black and red hop for free. The next red hop will again add two recursive calls to the "todo list". So as a result, if we start in the loop, and we first take a red hop, we will keep running through the loop. This holds as long as we do not take the 111 -> 101 -> 91 part of the loop. Since those are two black edges, we can get out of recursive calls to perform and thus stop at 91 (since we always get two additional hops per red hop).

As a result if we start at a certain node in the loop and we immediately take a red hop, regardless of the number of recursive calls we still need to do, we will eventually stop in 91: each time we do a complete loop, we "lose" one recursive call, so eventually we will run out of remaining recursive calls and stop in 91. So now we know that if we start, for instance at 94 with an arbitrary number of recursive calls, we will stop at 91.

Now we still need to show that - given the number is less than 100 - we will end up in the loop, and that the first node we encounter in the loop is a node from which a red edge begins. We know that all numbers in the range of 91..100 are in the loop. Any number that is smaller than 91, will result in a red hop and will be incremented with 11. Therefore - as is partly shown in the graph - all numbers less than 91 will end up in the range of [91..100] eventually by always using red edges.

Based on the above reasoning, a more efficient version of the function would be:

```<code>mc91' n | n > 100 = n-10
        | otherwise = 91
</code>```

Now for your given sample input (85), we see that the program will evaluate to:

```<code>   mc91 85
-> mc91 (mc91 96) -- we are in the loop now
-> mc91 (mc91 (mc91 107))
-> mc91 (mc91 97)
-> mc91 (mc91 (mc91 108))
-> mc91 (mc91 98)
-> mc91 (mc91 (mc91 109))
-> mc91 (mc91 99)
-> mc91 (mc91 (mc91 110))
-> mc91 (mc91 100)
-> mc91 (mc91 (mc91 111))
-> mc91 (mc91 101)
-> mc91 91 -- we reached 91, and thus removed one recursive call
-> mc91 (mc91 102)
-> mc91 92
-> mc91 (mc91 103)
-> mc91 93
-> mc91 (mc91 104)
-> mc91 94
-> mc91 (mc91 105)
-> mc91 95
-> mc91 (mc91 106)
-> mc91 96
-> mc91 (mc91 107)
-> mc91 97
-> mc91 (mc91 108)
-> mc91 98
-> mc91 (mc91 109)
-> mc91 99
-> mc91 (mc91 110)
-> mc91 100
-> mc91 (mc91 111)
-> mc91 101
-> 91 -- we hit 91 a second time, and now the last recursive call is gone
</code>```

Title: How McCarthy 91 function works

Body:
I have following function based on McCarthy 91 principle:

mc91 :: Integer -> Integer
mc91 n
    | n > 100 = n - 10
    | otherwise = mc91 (mc91 (n + 11))

when I type in the prelude mc91 85 I've got 91.

I could not configure it out, how it is expanded and why do I've got 91.

Body:
Let's first analyze the function. There are two cases:

in the case n > 100, then we return n-10; and

in the case n <= 100, then we calculate n+11, and we do two additional steps.

There are thus two possible "steps": one where we decrement with 10, and one where we increment with 11. We can visualize this with a graph, like:

The edges of the first case are denoted in black, the edges of the latter case are denoted in red.

What we notice is that there is a loop here: 92 -> 103 -> 93 -> 104 -> 94 -> 105 -> 95 -> 106 -> 96 -> 107 -> 97 -> 108 -> 98 -> 109 -> 99 -> 110 -> 100 -> 111 -> 101 -> 91 -> ...

Let's assume for now that - regardless of the original value - we will always end up in that loop. Now the loop always interleaves a black edge, and a red edge, except for the 111 -> 101 -> 91 part, which consists out of two black edges.

Since a red edge introduces two additional recursive calls, that means that, if we take a red hop, we get the next black and red hop for free. The next red hop will again add two recursive calls to the "todo list". So as a result, if we start in the loop, and we first take a red hop, we will keep running through the loop. This holds as long as we do not take the 111 -> 101 -> 91 part of the loop. Since those are two black edges, we can get out of recursive calls to perform and thus stop at 91 (since we always get two additional hops per red hop).

As a result if we start at a certain node in the loop and we immediately take a red hop, regardless of the number of recursive calls we still need to do, we will eventually stop in 91: each time we do a complete loop, we "lose" one recursive call, so eventually we will run out of remaining recursive calls and stop in 91. So now we know that if we start, for instance at 94 with an arbitrary number of recursive calls, we will stop at 91.

Now we still need to show that - given the number is less than 100 - we will end up in the loop, and that the first node we encounter in the loop is a node from which a red edge begins. We know that all numbers in the range of 91..100 are in the loop. Any number that is smaller than 91, will result in a red hop and will be incremented with 11. Therefore - as is partly shown in the graph - all numbers less than 91 will end up in the range of [91..100] eventually by always using red edges.

Based on the above reasoning, a more efficient version of the function would be:

mc91' n | n > 100 = n-10
        | otherwise = 91

Now for your given sample input (85), we see that the program will evaluate to:

   mc91 85
-> mc91 (mc91 96) -- we are in the loop now
-> mc91 (mc91 (mc91 107))
-> mc91 (mc91 97)
-> mc91 (mc91 (mc91 108))
-> mc91 (mc91 98)
-> mc91 (mc91 (mc91 109))
-> mc91 (mc91 99)
-> mc91 (mc91 (mc91 110))
-> mc91 (mc91 100)
-> mc91 (mc91 (mc91 111))
-> mc91 (mc91 101)
-> mc91 91 -- we reached 91, and thus removed one recursive call
-> mc91 (mc91 102)
-> mc91 92
-> mc91 (mc91 103)
-> mc91 93
-> mc91 (mc91 104)
-> mc91 94
-> mc91 (mc91 105)
-> mc91 95
-> mc91 (mc91 106)
-> mc91 96
-> mc91 (mc91 107)
-> mc91 97
-> mc91 (mc91 108)
-> mc91 98
-> mc91 (mc91 109)
-> mc91 99
-> mc91 (mc91 110)
-> mc91 100
-> mc91 (mc91 111)
-> mc91 101
-> 91 -- we hit 91 a second time, and now the last recursive call is gone


来源: stackexchange

问:
interpolate string with variable name in angularjs
How to interpolate value inside interpolate?

I am using a file where I have written message string and using {{ vm.variable }}  but I am unable to display the string with variable value on HTML.

input string ( in JS ): "Welcome {{name}} to the World."

desired output string (in HTML ): "Welcome John Smith to the world."

look my code below

(function() {

    'use strict';

    angular
        .module('app', [])
        .value('_MSG_', {
                "signup": "Welcome {{name}} to the World.",
                "login": "last login from {{location}}"
        }).controller('MessageController', function($scope, $parse, $interpolate, _MSG_){
            var vm = this;
            vm.name = "John Smith";
            vm.location = "India";
            vm.welcomeMessage = _MSG_.signup;
            //========trial 1 =======
            // vm.finalString = $interpolate(vm.welcomeMessage);
            // nothing happens but
            //=====trial 2=====
            // set {{vm.name}} in _MSG_.signup and do below
            // vm.finalString = $parse(_MSG_).assign($scope, vm.name);
            // ERROR [$parse:syntax] Syntax Error: Token '{' is an unexpected token at column 9 of the expression [Weclome {{vm.name}}.] starting at [{{vm.name}}.].
        });
})();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-controller="MessageController as vm ">
    {{ vm.welcomeMessage }} ==> Welcome John Smith to the world

    // trial 1

    {{ vm.finalString }}
</body>
</html></code>```

答:
You need to bind $interpolate to this\vm

Like: $interpolate(vm.welcomeMessage)(this);

DEMO:

angular
  .module('app', [])
  .value('MSG', {
    "signup": "Welcome {{name}} to the World.",
    "login": "last login from {{location}}"
  }).controller('MessageController', function($scope, $parse, $interpolate, MSG) {
    var vm = this;
    vm.name = "John Smith";
    vm.location = "India";
    vm.welcomeMessage = MSG.signup;
    vm.finalString = $interpolate(vm.welcomeMessage)(this);
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-controller="MessageController as vm ">
    {{ vm.welcomeMessage }} ==> Welcome John Smith

    <br>// trial 1<br>
    {{ vm.finalString }}
</body>
</html></code>```

ContentLicense: CC BY-SA 3.0

Body:
How to interpolate value inside interpolate?

I am using a file where I have written message string and using {{ vm.variable }}  but I am unable to display the string with variable value on HTML.

input string ( in JS ): "Welcome {{name}} to the World."

desired output string (in HTML ): "Welcome John Smith to the world."

look my code below

(function() {

    'use strict';

    angular
        .module('app', [])
        .value('_MSG_', {
                "signup": "Welcome {{name}} to the World.",
                "login": "last login from {{location}}"
        }).controller('MessageController', function($scope, $parse, $interpolate, _MSG_){
            var vm = this;
            vm.name = "John Smith";
            vm.location = "India";
            vm.welcomeMessage = _MSG_.signup;
            //========trial 1 =======
            // vm.finalString = $interpolate(vm.welcomeMessage);
            // nothing happens but
            //=====trial 2=====
            // set {{vm.name}} in _MSG_.signup and do below
            // vm.finalString = $parse(_MSG_).assign($scope, vm.name);
            // ERROR [$parse:syntax] Syntax Error: Token '{' is an unexpected token at column 9 of the expression [Weclome {{vm.name}}.] starting at [{{vm.name}}.].
        });
})();

    {{ vm.welcomeMessage }} ==> Welcome John Smith to the world

    // trial 1

    {{ vm.finalString }}

Body:
You need to bind $interpolate to this\vm

Like: $interpolate(vm.welcomeMessage)(this);

DEMO:

angular
  .module('app', [])
  .value('MSG', {
    "signup": "Welcome {{name}} to the World.",
    "login": "last login from {{location}}"
  }).controller('MessageController', function($scope, $parse, $interpolate, MSG) {
    var vm = this;
    vm.name = "John Smith";
    vm.location = "India";
    vm.welcomeMessage = MSG.signup;
    vm.finalString = $interpolate(vm.welcomeMessage)(this);
  });

<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-controller="MessageController as vm ">
    {{ vm.welcomeMessage }} ==> Welcome John Smith

    <br>// trial 1<br>
    {{ vm.finalString }}
</body>
</html>


问:
Unable to click the element. Error: no such element: Unable to locate element:
I am practicing on flipkart.com. i am unable to click the product after the search result. The xpath is correct. I tried using scroll function,visible, find by partial linktext, wait, sleep still i am unable to do. Please find the below code.</p>

```<code>package Flipkart;

import org.openqa.selenium.By; import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class TC2
{
    public static void main(String[] args) throws InterruptedException
    {
        System.setProperty("webdriver.chrome.driver","C:\\Chrome\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.flipkart.com/");
        driver.findElement(By.name("q")).sendKeys("Bag");
        driver.findElement(By.xpath("html/body/div[1]/div/header/div[1]/div[2]/div/div/div[2]/form/div/div[2]/button")).click();
        driver.findElement(By.xpath(".//*[@id='container']/div/div[2]/div[2]/div/div[2]/div/div[3]/div[1]/div[1]/div[1]/div/a[2]")).click();
    }
}

  Error:
    Starting ChromeDriver 2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed) on port 17575
    Only local connections are allowed.
    Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":".//*[@id='container']/div/div[2]/div[2]/div/div[2]/div/div[3]/div[1]/div[1]/div[1]/div/a[2]"}
      (Session info: chrome=58.0.3029.81)
      (Driver info: chromedriver=2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed),platform=Windows NT 10.0.14393 x86_64) (WARNING: The server did not provide any stacktrace information)
    Command duration or timeout: 76 milliseconds
    For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
    Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
    System info: host: 'D90T0CQ1', ip: '192.168.162.83', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_102'
    Driver info: org.openqa.selenium.chrome.ChromeDriver
    Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed), userDataDir=C:\Users\SALUNK~1\AppData\Local\Temp\scoped_dir12552_16506}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=58.0.3029.81, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
    Session ID: a8c3432c9b1e8cce3365db9407fc310f
    *** Element info: {Using=xpath, value=.//*[@id='container']/div/div[2]/div[2]/div/div[2]/div/div[3]/div[1]/div[1]/div[1]/div/a[2]}
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
        at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
        at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363)
        at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:500)
        at org.openqa.selenium.By$ByXPath.findElement(By.java:361)
        at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:355)
        at Flipkart.TC2.main(TC2.java:15)
</code>```

答:
Here is the Answer to your Question:

I don't see any such errors/issues in your code. A few words about the solution:

Chrome browser sometimes doesn't opens maximized so you need to maximize the Chrome browser using ChromeOptions class.

If the browser is not maximized certain elements doesn't appers within the Viewport and and may throw NoSuchElementException

Add the argument to disable the infobars through ChromeOptions class.

Your xpath looks vulnerable to me, try to construct logical xpath for the elements on the HTML DOM.

Your own code works at my end with some simple tweaks which opens the Chrome
Browser, navigates to the URL https://www.flipkart.com/, searches for Bag, clicks on Skybags Pixel Plus 03 30 L Backpack and Skybags Pixel Plus 03 30 L Backpack  (Grey) is opened in a new tab.

Here is the modified code block:

```<code>System.setProperty("webdriver.chrome.driver","C:\\your_directory\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
options.addArguments("disable-infobars");
WebDriver driver = new ChromeDriver(options);
driver.get("https://www.flipkart.com/");
driver.findElement(By.name("q")).sendKeys("Bag");
driver.findElement(By.xpath("html/body/div[1]/div/header/div[1]/div[2]/div/div/div[2]/form/div/div[2]/button")).click();
driver.findElement(By.xpath(".//*[@id='container']/div/div[2]/div[2]/div/div[2]/div/div[3]/div[1]/div[1]/div[1]/div/a[2]")).click();
</code>```

Let me know if this Answers your Question.

Body:
I am practicing on flipkart.com. i am unable to click the product after the search result. The xpath is correct. I tried using scroll function,visible, find by partial linktext, wait, sleep still i am unable to do. Please find the below code.

package Flipkart;

import org.openqa.selenium.By; import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class TC2
{
    public static void main(String[] args) throws InterruptedException
    {
        System.setProperty("webdriver.chrome.driver","C:\\Chrome\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.flipkart.com/");
        driver.findElement(By.name("q")).sendKeys("Bag");
        driver.findElement(By.xpath("html/body/div[1]/div/header/div[1]/div[2]/div/div/div[2]/form/div/div[2]/button")).click();
        driver.findElement(By.xpath(".//*[@id='container']/div/div[2]/div[2]/div/div[2]/div/div[3]/div[1]/div[1]/div[1]/div/a[2]")).click();
    }
}

  Error:
    Starting ChromeDriver 2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed) on port 17575
    Only local connections are allowed.
    Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":".//*[@id='container']/div/div[2]/div[2]/div/div[2]/div/div[3]/div[1]/div[1]/div[1]/div/a[2]"}
      (Session info: chrome=58.0.3029.81)
      (Driver info: chromedriver=2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed),platform=Windows NT 10.0.14393 x86_64) (WARNING: The server did not provide any stacktrace information)
    Command duration or timeout: 76 milliseconds
    For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
    Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
    System info: host: 'D90T0CQ1', ip: '192.168.162.83', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_102'
    Driver info: org.openqa.selenium.chrome.ChromeDriver
    Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed), userDataDir=C:\Users\SALUNK~1\AppData\Local\Temp\scoped_dir12552_16506}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=58.0.3029.81, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
    Session ID: a8c3432c9b1e8cce3365db9407fc310f
    *** Element info: {Using=xpath, value=.//*[@id='container']/div/div[2]/div[2]/div/div[2]/div/div[3]/div[1]/div[1]/div[1]/div/a[2]}
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
        at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
        at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:363)
        at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:500)
        at org.openqa.selenium.By$ByXPath.findElement(By.java:361)
        at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:355)
        at Flipkart.TC2.main(TC2.java:15)

Body:
Here is the Answer to your Question:

I don't see any such errors/issues in your code. A few words about the solution:

Chrome browser sometimes doesn't opens maximized so you need to maximize the Chrome browser using ChromeOptions class.

If the browser is not maximized certain elements doesn't appers within the Viewport and and may throw NoSuchElementException

Add the argument to disable the infobars through ChromeOptions class.

Your xpath looks vulnerable to me, try to construct logical xpath for the elements on the HTML DOM.

Your own code works at my end with some simple tweaks which opens the Chrome
Browser, navigates to the URL https://www.flipkart.com/, searches for Bag, clicks on Skybags Pixel Plus 03 30 L Backpack and Skybags Pixel Plus 03 30 L Backpack  (Grey) is opened in a new tab.

Here is the modified code block:

System.setProperty("webdriver.chrome.driver","C:\\your_directory\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
options.addArguments("disable-infobars");
WebDriver driver = new ChromeDriver(options);
driver.get("https://www.flipkart.com/");
driver.findElement(By.name("q")).sendKeys("Bag");
driver.findElement(By.xpath("html/body/div[1]/div/header/div[1]/div[2]/div/div/div[2]/form/div/div[2]/button")).click();
driver.findElement(By.xpath(".//*[@id='container']/div/div[2]/div[2]/div/div[2]/div/div[3]/div[1]/div[1]/div[1]/div/a[2]")).click();

Let me know if this Answers your Question.


问:
Controlling Video with Gestures
I have a video playing a camera rotating around a 3D model. I want to be able to sweep left to right to play the video forwards and right to left to play the video backwards.

Can this be done on iOS 4 and how?

Cheers

答: just add a new transparent view on top of your video and catch touch actions in that layer</p>

ContentLicense: CC BY-SA 2.5

Title: Controlling Video with Gestures


问:
Materialize Icons working on localhost but not live
I have materialize icons working on my local machine.  I can view them in both Chrome and FF.

I am calling the CDN at:

<link href="https://fonts.googleapis.com/icon?family=Material+Icons"rel="stylesheet">

In my html I am using:

menu  (I've changed the colour)

However when looking at the site live on either desktop or mobile, I just see the 'text' relating to the icon.  I see that many others have had this problem and most say to simply add the CDN stylesheet in the  which I of course have.

The site is hosted on Heroku.

答:
Did you check CDN url correctly?

I accidently put "http" instead of "https" and pushed it to Heroku, same thing happens as you.
After changing protocol to "https", it works fine.</p>


问:
How to use shared preference to checkbox - Android Studio
I created a login page that connects to a mysql database.
In the activity_user_login.xml I entered 2 editText for email and password and a login Botton, I added a checkbox for the saved data.
I would like to save email and password.

However, I can not add the sharedPreference.
Below the full code.. You can help me? Thank you

activity_user_login.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_user_login"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.myapp.UserLoginActivity"
    android:background="#FF5722"
    android:padding="20dp">

    <TextView
        android:text="User Login Form"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:id="@+id/textView"
        android:gravity="center"
        android:textSize="20dp"
        android:textColor="#fff"/>

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:background="#fbfefd"
        android:inputType="textPersonName"
        android:ems="10"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:id="@+id/email"
        android:hint="Enter Your Email Here"
        android:gravity="center"
        />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:background="#fbfefd"
        android:inputType="textPassword"
        android:ems="10"
        android:layout_below="@+id/email"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:id="@+id/password"
        android:hint="Enter Your Password Here"
        android:gravity="center"/>

    <Button
        android:text="Log In Here"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/password"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:id="@+id/Login" />

    <CheckBox
        android:id="@+id/saveLoginCheckBox"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/editTextPassword"
        android:text="Save Login?"
        android:textColor="#FFF" />

</RelativeLayout>
</code>```

UserLoginActivity.java

```<code>package com.myapp.myappcode;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.HashMap;

public class UserLoginActivity extends AppCompatActivity {

    EditText Email, Password;
    Button LogIn ;
    String PasswordHolder, EmailHolder;
    String finalResult ;
    String HttpURL = "http://mysite/User/UserLogin.php";
    Boolean CheckEditText ;
    ProgressDialog progressDialog;
    HashMap<String,String> hashMap = new HashMap<>();
    HttpParse httpParse = new HttpParse();
    public static final String UserEmail = "";

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

        Email = (EditText)findViewById(R.id.email);
        Password = (EditText)findViewById(R.id.password);
        LogIn = (Button)findViewById(R.id.Login);

        LogIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                CheckEditTextIsEmptyOrNot();

                if(CheckEditText){

                    UserLoginFunction(EmailHolder, PasswordHolder);

                }
                else {

                    Toast.makeText(UserLoginActivity.this, "Please fill all form fields.", Toast.LENGTH_LONG).show();

                }

            }
        });
    }
    public void CheckEditTextIsEmptyOrNot(){

        EmailHolder = Email.getText().toString();
        PasswordHolder = Password.getText().toString();

        if(TextUtils.isEmpty(EmailHolder) || TextUtils.isEmpty(PasswordHolder))
        {
            CheckEditText = false;
        }
        else {

            CheckEditText = true ;
        }
    }

    public void UserLoginFunction(final String email, final String password){

        class UserLoginClass extends AsyncTask<String,Void,String> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();

                progressDialog = ProgressDialog.show(UserLoginActivity.this,"Loading Data",null,true,true);
            }

            @Override
            protected void onPostExecute(String httpResponseMsg) {

                super.onPostExecute(httpResponseMsg);

                progressDialog.dismiss();

                if(httpResponseMsg.equalsIgnoreCase("Data Matched")){

                    finish();

                    Intent intent = new Intent(UserLoginActivity.this, DashboardActivity.class);

                    intent.putExtra(UserEmail,email);

                    startActivity(intent);

                }
                else{

                    Toast.makeText(UserLoginActivity.this,httpResponseMsg,Toast.LENGTH_LONG).show();
                }

            }

            @Override
            protected String doInBackground(String... params) {

                hashMap.put("email",params[0]);

                hashMap.put("password",params[1]);

                finalResult = httpParse.postRequest(hashMap, HttpURL);

                return finalResult;
            }
        }

        UserLoginClass userLoginClass = new UserLoginClass();

        userLoginClass.execute(email,password);
    }

}
</code>```

答:
checkbox is checked then put values to the Shared preference

Put the values to Shared Preference

```<code>SharedPreferences pref=getSharedPreferences("values",Context.MODE_PRIVATE);
pref.edit().putString("email", Email.getText().toString());
pref.edit().putString("pass", Password.getText().toString());
pref.apply();
</code>```

get the values from Shared Preference

```<code>SharedPreferences pref=getSharedPreferences("values", Context.MODE_PRIVATE);
String useremail=pref.getString("email","def_val");
String password=pref.getString("pass","def_val");
</code>```

def_val replace with empty or anything

Body:
I created a login page that connects to a mysql database.
In the activity_user_login.xml I entered 2 editText for email and password and a login Botton, I added a checkbox for the saved data.
I would like to save email and password.

However, I can not add the sharedPreference.
Below the full code.. You can help me? Thank you

activity_user_login.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_user_login"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.myapp.UserLoginActivity"
    android:background="#FF5722"
    android:padding="20dp">

    <TextView
        android:text="User Login Form"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:id="@+id/textView"
        android:gravity="center"
        android:textSize="20dp"
        android:textColor="#fff"/>

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:background="#fbfefd"
        android:inputType="textPersonName"
        android:ems="10"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:id="@+id/email"
        android:hint="Enter Your Email Here"
        android:gravity="center"
        />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:background="#fbfefd"
        android:inputType="textPassword"
        android:ems="10"
        android:layout_below="@+id/email"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:id="@+id/password"
        android:hint="Enter Your Password Here"
        android:gravity="center"/>

    <Button
        android:text="Log In Here"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/password"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:id="@+id/Login" />

    <CheckBox
        android:id="@+id/saveLoginCheckBox"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/editTextPassword"
        android:text="Save Login?"
        android:textColor="#FFF" />

</RelativeLayout>

UserLoginActivity.java

package com.myapp.myappcode;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.HashMap;

public class UserLoginActivity extends AppCompatActivity {

    EditText Email, Password;
    Button LogIn ;
    String PasswordHolder, EmailHolder;
    String finalResult ;
    String HttpURL = "http://mysite/User/UserLogin.php";
    Boolean CheckEditText ;
    ProgressDialog progressDialog;
    HashMap<String,String> hashMap = new HashMap<>();
    HttpParse httpParse = new HttpParse();
    public static final String UserEmail = "";

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

        Email = (EditText)findViewById(R.id.email);
        Password = (EditText)findViewById(R.id.password);
        LogIn = (Button)findViewById(R.id.Login);

        LogIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                CheckEditTextIsEmptyOrNot();

                if(CheckEditText){

                    UserLoginFunction(EmailHolder, PasswordHolder);

                }
                else {

                    Toast.makeText(UserLoginActivity.this, "Please fill all form fields.", Toast.LENGTH_LONG).show();

                }

            }
        });
    }
    public void CheckEditTextIsEmptyOrNot(){

        EmailHolder = Email.getText().toString();
        PasswordHolder = Password.getText().toString();

        if(TextUtils.isEmpty(EmailHolder) || TextUtils.isEmpty(PasswordHolder))
        {
            CheckEditText = false;
        }
        else {

            CheckEditText = true ;
        }
    }

    public void UserLoginFunction(final String email, final String password){

        class UserLoginClass extends AsyncTask<String,Void,String> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();

                progressDialog = ProgressDialog.show(UserLoginActivity.this,"Loading Data",null,true,true);
            }

            @Override
            protected void onPostExecute(String httpResponseMsg) {

                super.onPostExecute(httpResponseMsg);

                progressDialog.dismiss();

                if(httpResponseMsg.equalsIgnoreCase("Data Matched")){

                    finish();

                    Intent intent = new Intent(UserLoginActivity.this, DashboardActivity.class);

                    intent.putExtra(UserEmail,email);

                    startActivity(intent);

                }
                else{

                    Toast.makeText(UserLoginActivity.this,httpResponseMsg,Toast.LENGTH_LONG).show();
                }

            }

            @Override
            protected String doInBackground(String... params) {

                hashMap.put("email",params[0]);

                hashMap.put("password",params[1]);

                finalResult = httpParse.postRequest(hashMap, HttpURL);

                return finalResult;
            }
        }

        UserLoginClass userLoginClass = new UserLoginClass();

        userLoginClass.execute(email,password);
    }

}

Body:
checkbox is checked then put values to the Shared preference

Put the values to Shared Preference

SharedPreferences pref=getSharedPreferences("values",Context.MODE_PRIVATE);
pref.edit().putString("email", Email.getText().toString());
pref.edit().putString("pass", Password.getText().toString());
pref.apply();

get the values from Shared Preference

SharedPreferences pref=getSharedPreferences("values", Context.MODE_PRIVATE);
String useremail=pref.getString("email","def_val");
String password=pref.getString("pass","def_val");

def_val replace with empty or anything


问:
Expanding menu not responding
I'm trying to fix a mobile menu in a WordPress child theme (from Twentyseventeen) that is no longer expanding when 'menu' is clicked. Basically I've had to tear the header apart to move things around and now the aria expanded menu isn't recognised. Instead I'm trying to use javascript to change the display property of the ul from none to block, but this isn't working either - mostly because I don't know the first thing about js and I've just tried making something from bits and pieces of code.

The demo of the site is live at http://www.histeve.co.uk/testing/triangledrivertraining/

The javascript I'm trying to use is as follows:

```<code><script>
var element = document.getElementById("topMenu");
document.getElementById("navBtn").addEventListener("click", toggleNav);

function toggleNav() {
if( element.style.display == 'none' ) {
function show() {('#topMenu').css ('display:block');}
} else {
function hide() {('#topMenu').css ('display:none'); }}
}
</script>
</code>```

This is no longer kicking out errors, but it's not doing anything at all.

If anyone has any ideas, your help is greatly appreciated!

Thanks
Steve

答:
You should fix your both selector which should start with $ (since it is wordpress you might have to user jquery instead of $) as well as your css function as follows.

```<code><script>
var element = document.getElementById("topMenu");
document.getElementById("navBtn").addEventListener("click", toggleNav);

function toggleNav() {
if( element.style.display == 'none' ) {
function show() {$('#topMenu').css ('display','block');}
} else {
function hide() {$('#topMenu').css ('display','none'); }}
}
</script>
</code>```

Alternative

Instead of using css you can toggle class which is much easier

```<code>function toggleNav() {
  $('#topMenu').toggleClass('active');
}
</code>```

then in css

```<code>#topMenu{display: none;}

#topMenu.active{display: block;}
</code>```

Title: Expanding menu not responding

Body:
I'm trying to fix a mobile menu in a WordPress child theme (from Twentyseventeen) that is no longer expanding when 'menu' is clicked. Basically I've had to tear the header apart to move things around and now the aria expanded menu isn't recognised. Instead I'm trying to use javascript to change the display property of the ul from none to block, but this isn't working either - mostly because I don't know the first thing about js and I've just tried making something from bits and pieces of code.

The demo of the site is live at http://www.histeve.co.uk/testing/triangledrivertraining/

The javascript I'm trying to use is as follows:

This is no longer kicking out errors, but it's not doing anything at all.

If anyone has any ideas, your help is greatly appreciated!

Thanks
Steve

Body:
You should fix your both selector which should start with $ (since it is wordpress you might have to user jquery instead of $) as well as your css function as follows.

<script>
var element = document.getElementById("topMenu");
document.getElementById("navBtn").addEventListener("click", toggleNav);

function toggleNav() {
if( element.style.display == 'none' ) {
function show() {$('#topMenu').css ('display','block');}
} else {
function hide() {$('#topMenu').css ('display','none'); }}
}
</script>

Alternative

Instead of using css you can toggle class which is much easier

function toggleNav() {
  $('#topMenu').toggleClass('active');
}

then in css

#topMenu{display: none;}

#topMenu.active{display: block;}


问:
httpd direct based on HTTP header
I have some existing config to redirect traffic to a different service depending on the URL path, and if no path matches defaults to a "main" load balanced service

```<code><Proxy balancer://main>

        BalancerMember http://main-service01:8080
        BalancerMember http://main-service02:8080
</Proxy>

ProxyPreserveHost on

ProxyPassMatch "/server.txt" !

ProxyPassMatch "^/register/(.*)$"  http://register_service/$1
ProxyPassMatch "^/login/(.*)$"  http://login_service/$1
ProxyPassMatch "^/lookup/(.*)$"  http://lookup_service/$1

ProxyPassMatch ".*" balancer://main-service nofailover=Off maxattempts=3 timeout=5
</code>```

This works!
Now I wish to extend the functionality so if the request contains HTTP header environment = dev, the request should be directed to the dev server instead of the main server in the event the path does not match one of the other conditions

I tried adding this just above the ".*" case but did not work

```<code>RewriteCond %{HTTP:environment} dev
RewriteRule (.*) http://dev:8080/$1 [P]
</code>```

答:
The above config does work but you have to remember to turn the RewriteEngine on</p>

```<code>RewriteEngine on
</code>```

Title: httpd direct based on HTTP header

Body:
I have some existing config to redirect traffic to a different service depending on the URL path, and if no path matches defaults to a "main" load balanced service

<Proxy balancer://main>

        BalancerMember http://main-service01:8080
        BalancerMember http://main-service02:8080
</Proxy>

ProxyPreserveHost on

ProxyPassMatch "/server.txt" !

ProxyPassMatch "^/register/(.*)$"  http://register_service/$1
ProxyPassMatch "^/login/(.*)$"  http://login_service/$1
ProxyPassMatch "^/lookup/(.*)$"  http://lookup_service/$1

ProxyPassMatch ".*" balancer://main-service nofailover=Off maxattempts=3 timeout=5

This works!
Now I wish to extend the functionality so if the request contains HTTP header environment = dev, the request should be directed to the dev server instead of the main server in the event the path does not match one of the other conditions

I tried adding this just above the ".*" case but did not work

RewriteCond %{HTTP:environment} dev
RewriteRule (.*) http://dev:8080/$1 [P]

Body:
The above config does work but you have to remember to turn the RewriteEngine on

RewriteEngine on


问:
Python not found in the Open WRT MenuConfig --> Languages
I am trying to include python in openwrt. It's not showing up in the open wrt menuconfig. I can see only Lua and nothing else under language options. While checking it shows me python ... OK , perl ... OK. Am I missing any steps?</p>

答:
```<code>$ cd (to/openwrt/path)
$ scripts/feeds update
$ scripts/feeds install python
$ make menuconfig
</code>```


问:
How to check if element contains specific class attribute
How can I check if a selenium web element contains a specific css class.

I have this html li element

```<code><li class="list-group-item ng-scope active" ng-repeat="report in lineageController.reports" ng-click="lineageController.activate(report)" ng-class="{active : lineageController.active == report}">
</code>```

As you can see inside class attribute there is an active class.

My problem is that I have this element and I want to do a check based on if the class attribute has that "active" value among the others, being more elegant solution then using xpath.

How can I do this?

答:
Try using contains();</p>

```<code>String classes = divPubli.getAttribute("class");
assertTrue("The element does not contain .maClass class .publi",classes.contains("maClass"));
</code>```

Body:
How can I check if a selenium web element contains a specific css class.

I have this html li element

As you can see inside class attribute there is an active class.

My problem is that I have this element and I want to do a check based on if the class attribute has that "active" value among the others, being more elegant solution then using xpath.

How can I do this?

Body:
Try using contains();

String classes = divPubli.getAttribute("class");
assertTrue("The element does not contain .maClass class .publi",classes.contains("maClass"));


问:
Is there a barcode recognition framework for Cocoa (OS X)?
Is there a framework or other sample code for doing barcode recognition (create and scan) on cocoa [OS X]?</p>

答:
Since macOS 10.10 you can use a CIFilter to read QRCodes without the need for any third-party framework:

Here's the link to the official docs, and to a blog post that shows how to use it.


问:
A regex to match the smallest nested part first
I am quite new to RegEx. I have not much experience. I already searched the internet and tried many things on regex101.com. Nothing seems to work.

This is the pattern:
\\((.*?)\\)

I use it in combination with Java 's replaceAll to add a ?: to each (...) provided in a string (the user input).

The user input is used as regular expression as well. But currently I am treating it as a normal String.

Imagine this user input: (Welcome, (StackOverflow|World)|Hello, Dad)

What I want as the result is: (?:Welcome, (?:StackOverflow|World)|Hello, Dad)

But I only get the first ?: : (?:Welcome, (StackOverflow|World)|Hello, Dad)

I think, I understand the problem. I guess, RegEx scans from right to left and is trying to get the smallest match (see .*? ). It searches for ( till the next ) . And this is (Welcome, (StackOverflow|World) .

What could I do to match these nested matches first? I cannot let the user modify their input. I have to find a better regex pattern to match from the smallest possible match to the greatest possible match, and not from the left to the right.

答:
I suggest searching for any unescaped ( (so as not to add ?: after literal () that is not followed with ? (to avoid matching lookarounds/non-capturing groups/etc,):

```<code>(?<!\\)((?:\\{2})*)\((?!\?)
</code>```

and replace with $1(?:. See the regex demo.

Java declaration:

```<code>String pat = "(?<!\\\\)((?:\\\\{2})*)\\((?!\\?)";
</code>```

Details:

(?<!\\) - no backslash immediately to the left of the current location

((?:\\{2})*) - Group 1: zero or more even number of backslashes

\(- a literal (...

(?!\?) - that is not immediately followed with a literal ?.

Body:
I suggest searching for any unescaped ( (so as not to add ?: after literal () that is not followed with ? (to avoid matching lookarounds/non-capturing groups/etc,):

(?<!\\)((?:\\{2})*)\((?!\?)

and replace with $1(?:. See the regex demo.

Java declaration:

String pat = "(?<!\\\\)((?:\\\\{2})*)\\((?!\\?)";

Details:

(?<!\\) - no backslash immediately to the left of the current location

((?:\\{2})*) - Group 1: zero or more even number of backslashes

\(- a literal (...

(?!\?) - that is not immediately followed with a literal ?.


问:
MYSQL Next Previous Record
I need to be able to find the next and previous record going from a non auto incremental id.

The correct sort order from the database uses this order by statement:

The below works only to list all results from a search.
ORDER BY length(general.blockid), general.blockid, length(general.plotid), general.plotid

The page that needs to know the next and previous record, holds the unique id/varchar in the URL as simply ?id=100_1A

In the url variable example above,

100_1A is in the db as blockplot

100 is the in the db as blockid

1A is in the datbase as plotid

When I am on the record 100_1A the next record should be 100_1B.
The previous record to 100_1a should be 99_6C

My problem is that how do i query the database for the next record when I dont know the order until it is sorted?

The sort order I typed is a working sort for the search results page.

When a user clicks to go into a specific record, the id is passed to the ur on the detail-view.php?id=100_1a

From the view page i need to take 100_1A and use the same sort to see what record is after and before 100_1A

答:
You can try this

```<code>set @row:=0;
select * from
(
  select *, (@row:=@row+1) as row_number from your_tables
  order by
    length(general.blockid), general.blockid,
    length(general.plotid), general.plotid
) as rowset
WHERE id='100_A';
</code>```

the above will give you the position of 100_A with the refer to the column row_number, and you can use that column to determine the next/prev row like,

```<code>set @row:=0;
select * from
(
  select *, (@row:=@row+1) as row_number from your_tables
  order by
    length(general.blockid), general.blockid,
    length(general.plotid), general.plotid
) as rowset
where
  row_number in(first_query_row+1, first_query_row-1);
</code>```

Please note that the query cost might very expensive if table is big,

and you can consider to create a view summary table to store the row_number and uniqid

Example of creating summary table

```<code>create table ordering_table
(
  row_number int(10) unsigned not null default 0,
  blockid varchar(255),
); /* no index, define yourself later */

 set @row:=0
 insert into ordering_table
   select @row:=@row+1, blockid from your_tables
   order by ...
</code>```

Title: MYSQL Next Previous Record

Body:
You can try this

set @row:=0;
select * from
(
  select *, (@row:=@row+1) as row_number from your_tables
  order by
    length(general.blockid), general.blockid,
    length(general.plotid), general.plotid
) as rowset
WHERE id='100_A';

the above will give you the position of 100_A with the refer to the column row_number, and you can use that column to determine the next/prev row like,

set @row:=0;
select * from
(
  select *, (@row:=@row+1) as row_number from your_tables
  order by
    length(general.blockid), general.blockid,
    length(general.plotid), general.plotid
) as rowset
where
  row_number in(first_query_row+1, first_query_row-1);

Please note that the query cost might very expensive if table is big,

and you can consider to create a view summary table to store the row_number and uniqid

Example of creating summary table

create table ordering_table
(
  row_number int(10) unsigned not null default 0,
  blockid varchar(255),
); /* no index, define yourself later */

 set @row:=0
 insert into ordering_table
   select @row:=@row+1, blockid from your_tables
   order by ...


问:
How to provide a datasource for Select2 with October CMS via the built in Ajax Framework
October CMS provides an extensive AJAX framework, that I'm looking to use to populate a Select2 box with.

According to Select2, using a remote dataset happens as follows:

```<code>$(".js-data-example-ajax").select2({
  ajax: {
    url: "https://api.github.com/search/repositories",
    dataType: 'json',
    delay: 250,
    data: function (params) {
      return {
        q: params.term, // search term
        page: params.page
      };
    },
    processResults: function (data, params) {
      params.page = params.page || 1;
      return {
        results: data.items,
        pagination: {
          more: (params.page * 30) < data.total_count
        }
      };
    },
    cache: true
  },
  escapeMarkup: function (markup) { return markup; },
  minimumInputLength: 1,
  templateResult: formatRepo,
  templateSelection: formatRepoSelection
});
</code>```

But from the October CMS docs, I cannot figure out how to pass the data to the server manually.

Questions are: which URL to use, and which parameters do I need to pass along so that October knows which function I want to access. Also, how can I capture the result without a partial being loaded?

This might be a trivial question; I might be looking in the wrong direction. Maybe the AJAX framework should not be used at all. Any insights on the correct way to proceed?

** EDIT FOLLOWING CORRECT ANSWER BY SAMUEL **

To make Select2 work with a remote dataset in combination with October CMS,
please take into account the following pitfalls. Below is my working code:

```<code>// SELECT 2
$('select').select2({
    /*placeholder: "Your placeholder", // Remove this, this causes issues*/
    ajax: {
        // Use transport function instead of URL as suggested by Samuel
        transport: function(params, success, failure) {
            var $request = $.request('onSelect', {
                data: params.data
            });
            $request.done(success);
            $request.fail(failure);
            return $request
        },
        dataType: 'json',
        delay: 250,
        data: function (params) {
            console.log(params);
            return {
                q: params.term, // search term
                page: params.page
            };
        },
        processResults: function (data,params) {
            console.log(data);
            return {
                // The JSON needs to be parsed before Select2 knows what to do with it.
                results: JSON.parse(data.result)
            };
        },
        cache: true
    },
    minimumInputLength: 1
});
</code>```

Below is the example output I used in combination with this Select2 example:

```<code>[
   {
      "id":1,
      "text":"Henry Kissinger"
   },
   {
      "id":2,
      "text":"Ricardo Montalban"
   }
]
</code>```

Above JSON was generated by my VisitorForm.php file:

```<code><?php namespace XXX\VisitorRegistration\Components;

use Cms\Classes\ComponentBase;
use XXX\VisitorRegistration\Models\Visitor;
use October\Rain\Auth\Models\User;

class VisitorForm extends ComponentBase {
    public function componentDetails()
    {
        return [
            'name' => 'Visitor Form',
            'description' => 'Description of the component'
        ];
    }

    // The function that returns the JSON, needs to be made dynamic
    public function onSelect() {
        return json_encode(array(array('id'=>1,'text'=>'Henry Kissinger'), array('id'=>2,'text'=>'Ricardo Montalban')));
    }
}
</code>```

Voilà, hope this can be useful.

答:
Pass the transport option instead of url. Here is an example:

```<code>$(".js-data-example-ajax").select2({
    ajax: {
        transport: function(params, success, failure) {

            /*
             * This is where the AJAX framework is used
             */
            var $request = $.request('onGetSomething', {
                data: params.data
            })

            $request.done(success)
            $request.fail(failure)

            return $request
        },

        dataType: 'json'
    },
    // ...
});
</code>```

Body:
October CMS provides an extensive AJAX framework, that I'm looking to use to populate a Select2 box with.

According to Select2, using a remote dataset happens as follows:

$(".js-data-example-ajax").select2({
  ajax: {
    url: "https://api.github.com/search/repositories",
    dataType: 'json',
    delay: 250,
    data: function (params) {
      return {
        q: params.term, // search term
        page: params.page
      };
    },
    processResults: function (data, params) {
      params.page = params.page || 1;
      return {
        results: data.items,
        pagination: {
          more: (params.page * 30) < data.total_count
        }
      };
    },
    cache: true
  },
  escapeMarkup: function (markup) { return markup; },
  minimumInputLength: 1,
  templateResult: formatRepo,
  templateSelection: formatRepoSelection
});

But from the October CMS docs, I cannot figure out how to pass the data to the server manually.

Questions are: which URL to use, and which parameters do I need to pass along so that October knows which function I want to access. Also, how can I capture the result without a partial being loaded?

This might be a trivial question; I might be looking in the wrong direction. Maybe the AJAX framework should not be used at all. Any insights on the correct way to proceed?

** EDIT FOLLOWING CORRECT ANSWER BY SAMUEL **

To make Select2 work with a remote dataset in combination with October CMS,
please take into account the following pitfalls. Below is my working code:

// SELECT 2
$('select').select2({
    /*placeholder: "Your placeholder", // Remove this, this causes issues*/
    ajax: {
        // Use transport function instead of URL as suggested by Samuel
        transport: function(params, success, failure) {
            var $request = $.request('onSelect', {
                data: params.data
            });
            $request.done(success);
            $request.fail(failure);
            return $request
        },
        dataType: 'json',
        delay: 250,
        data: function (params) {
            console.log(params);
            return {
                q: params.term, // search term
                page: params.page
            };
        },
        processResults: function (data,params) {
            console.log(data);
            return {
                // The JSON needs to be parsed before Select2 knows what to do with it.
                results: JSON.parse(data.result)
            };
        },
        cache: true
    },
    minimumInputLength: 1
});

Below is the example output I used in combination with this Select2 example:

[
   {
      "id":1,
      "text":"Henry Kissinger"
   },
   {
      "id":2,
      "text":"Ricardo Montalban"
   }
]

Above JSON was generated by my VisitorForm.php file:

<?php namespace XXX\VisitorRegistration\Components;

use Cms\Classes\ComponentBase;
use XXX\VisitorRegistration\Models\Visitor;
use October\Rain\Auth\Models\User;

class VisitorForm extends ComponentBase {
    public function componentDetails()
    {
        return [
            'name' => 'Visitor Form',
            'description' => 'Description of the component'
        ];
    }

    // The function that returns the JSON, needs to be made dynamic
    public function onSelect() {
        return json_encode(array(array('id'=>1,'text'=>'Henry Kissinger'), array('id'=>2,'text'=>'Ricardo Montalban')));
    }
}

Voilà, hope this can be useful.

Body:
Pass the transport option instead of url. Here is an example:

$(".js-data-example-ajax").select2({
    ajax: {
        transport: function(params, success, failure) {

            /*
             * This is where the AJAX framework is used
             */
            var $request = $.request('onGetSomething', {
                data: params.data
            })

            $request.done(success)
            $request.fail(failure)

            return $request
        },

        dataType: 'json'
    },
    // ...
});


问:
First launch take long time (ClassLoader referenced unknown path)
After updating my Android studio to 2.0 and gradle to 2.0.0 and SDK-Platform to 23.0.3 When I want to launch application it take too much time (about 2-3 second) and following warning appears in Android Monitor :

```<code>W/System: ClassLoader referenced unknown path: /data/app/net.hadifar.test-1/lib/arm
W/System: ClassLoader referenced unknown path: /data/app/net.hadifar.test-1/lib/arm
 W/art: Suspending all threads took: 5.439ms
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
W/art: Suspending all threads took: 6.808ms
</code>```

But second time I launch application it's run as usual. Can any body knows what's the issue ?

答: no need to disable instant run ,but follow my step ,use gradle plugin v2.3.2 and use gradle v3.5 can solve it , enjoy , anyway I solve the problem on my project.</p>

Body:
After updating my Android studio to 2.0 and gradle to 2.0.0 and SDK-Platform to 23.0.3 When I want to launch application it take too much time (about 2-3 second) and following warning appears in Android Monitor :

W/System: ClassLoader referenced unknown path: /data/app/net.hadifar.test-1/lib/arm
W/System: ClassLoader referenced unknown path: /data/app/net.hadifar.test-1/lib/arm
 W/art: Suspending all threads took: 5.439ms
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
W/art: Suspending all threads took: 6.808ms

But second time I launch application it's run as usual. Can any body knows what's the issue ?


问:
Selenium WebElement times out on most commands
I've run into a problem that has baffled me while attempting to use Selenium 3.4 on jre 1.8 in JUnit. After successfully grabbing a WebElement, attempting to perform the click(), isDisplayed(), sendKeys(), and clear() functions all cause the driver connection to timeout before they can complete. I've wound up creating the following code:

```<code>@Test
public void canLogIn(){
    WebDriver driver = new HtmlUnitDriver();
    driver.get("http://"+ip+"/login/loginpage.html");
    WebElement username = driver.findElement(By.id("username_div"));
    System.out.println("Username to string: "+username.toString());

    /*Thread.sleep(6000);*/

    if(!username.isEnabled()) fail();

    if(!username.isDisplayed()) fail();

    username.click();
    username.clear();
    username.sendKeys("manager");
</code>```

...

So far, the code has timed out on username.isDisplayed(), username.click(), username.clear(), and username.sendKeys() when all the other elements were commented out. However, username.toString() works, and shows the correct element, and the code has yet to hang on username.isEnabled(). Thread.sleep() was used to test whether allowing the page to load would eliminate the issue, but to no avail. I have tried executing these commands using Selenium's JavascriptExecutor, also to no avail. I am well and truly stumped at this point, and any assistance you could give me would be greatly appreciated.

答:
Is the username element visible? Perhaps you can try adding this after opening the page:

```<code>WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until( ExpectedConditions.visibilityOfElementLocated("username_div"));
</code>```

What exception are you getting if any?

Body:
I've run into a problem that has baffled me while attempting to use Selenium 3.4 on jre 1.8 in JUnit. After successfully grabbing a WebElement, attempting to perform the click(), isDisplayed(), sendKeys(), and clear() functions all cause the driver connection to timeout before they can complete. I've wound up creating the following code:

@Test
public void canLogIn(){
    WebDriver driver = new HtmlUnitDriver();
    driver.get("http://"+ip+"/login/loginpage.html");
    WebElement username = driver.findElement(By.id("username_div"));
    System.out.println("Username to string: "+username.toString());

    /*Thread.sleep(6000);*/

    if(!username.isEnabled()) fail();

    if(!username.isDisplayed()) fail();

    username.click();
    username.clear();
    username.sendKeys("manager");

...

So far, the code has timed out on username.isDisplayed(), username.click(), username.clear(), and username.sendKeys() when all the other elements were commented out. However, username.toString() works, and shows the correct element, and the code has yet to hang on username.isEnabled(). Thread.sleep() was used to test whether allowing the page to load would eliminate the issue, but to no avail. I have tried executing these commands using Selenium's JavascriptExecutor, also to no avail. I am well and truly stumped at this point, and any assistance you could give me would be greatly appreciated.

Body:
Is the username element visible? Perhaps you can try adding this after opening the page:

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until( ExpectedConditions.visibilityOfElementLocated("username_div"));

What exception are you getting if any?


问:
EncryptedXml DecryptDocument method error after .Net framework update
I have an old function written in 2013 that decrypt xml that was encrypted by another program.

The code is realy simple

```<code>        public static void Decrypt(XmlDocument Doc)
    {
        // Check the arguments.
        if (Doc == null)
            throw new ArgumentNullException("Doc");

        // Create a new EncryptedXml object.
        EncryptedXml exml = new EncryptedXml(Doc);

        // Decrypt the XML document.
        exml.DecryptDocument();

    }
</code>```

It worked like a charm until recently that some of our clients started to upgrade their framework to 4.6.2, so the method DecryptDocument() stopped working. Now it throws an exception "The algorithm group '' is invalid". If I remove .net framework 4.6.2 it works again.

The sample code in this link will reproduce the error, it will encrypt successfully then fail to decrypt.

I'm using A3 certificates, pendrive token. Anyone have faced this problem? there is any work around in .net 4.6.2?

Edit 1:

Stacktrace:

at System.Security.Cryptography.CngAlgorithmGroup..ctor(String algorithmGroup)
 at System.Security.Cryptography.CngKey.get_AlgorithmGroup()
 at System.Security.Cryptography.RSACng..ctor(CngKey key)
 at System.Security.Cryptography.X509Certificates.RSACertificateExtensions.GetRSAPrivateKey(X509Certificate2 certificate)
 at System.Security.Cryptography.CngLightup.GetRSAPrivateKey(X509Certificate2 cert)
 at System.Security.Cryptography.Xml.EncryptedXml.DecryptEncryptedKey(EncryptedKey encryptedKey)
 at System.Security.Cryptography.Xml.EncryptedXml.GetDecryptionKey(EncryptedData encryptedData, String symmetricAlgorithmUri)
 at System.Security.Cryptography.Xml.EncryptedXml.DecryptDocument()
 at Criptografar.Program.Decrypt(XmlDocument Doc) in C:\Users\leoka\Documents\Visual Studio 2017\Projects\ConsoleApp4\Criptografar\Program.cs:line 152
 at Criptografar.Program.Main(String[] args) in C:\Users\leoka\Documents\Visual Studio 2017\Projects\ConsoleApp4\Criptografar\Program.cs:line 83

答:
I cannot reproduce the problem myself - I don't have the "pendrive token" which I suspect is the problem - so this is guesswork.
There are two generations of cryptographic APIs in Windows - the "old" one and the "new generation" one, known as CNG.
Now, if you look at the source code for the CngLightup type that appears midway through your stack trace, specifically the DetectRsaCngSupport method, you'll see that .NET framework tries to use the new generation API if possible. My guess is that the "pendrive token" device does not support the new API. You can verify this by forcing the use of the old API. Unfortunately, there does not seem to be a public configuration flag that controls this, so you must resort to reflection-based hacks. For example, you can put something like this at the beginning of your program, so that it runs once, before you try the decrypting operation:

```<code>    var cngLightupType = typeof(EncryptedXml).Assembly.GetType("System.Security.Cryptography.CngLightup");
    var preferRsaCngField = cngLightupType.GetField("s_preferRsaCng", BindingFlags.Static | BindingFlags.NonPublic);
    var getRsaPublicKeyField = cngLightupType.GetField("s_getRsaPublicKey", BindingFlags.Static | BindingFlags.NonPublic);
    var getRsaPrivateKeyField = cngLightupType.GetField("s_getRsaPrivateKey", BindingFlags.Static | BindingFlags.NonPublic);
    preferRsaCngField.SetValue(null, new Lazy<bool>(() => false));
    getRsaPublicKeyField.SetValue(null, null);
    getRsaPrivateKeyField.SetValue(null, null);
</code>```

Do note that it is extremely hacky, not thread-safe, error handling is omitted etc. If you verify that the CNG usage is the problem, you can then ask the "pendrive token" supplier to provide drivers that work with CNG. Or you can live with the hack above, rewritten for more safety.

Body:
I have an old function written in 2013 that decrypt xml that was encrypted by another program.

The code is realy simple

        public static void Decrypt(XmlDocument Doc)
    {
        // Check the arguments.
        if (Doc == null)
            throw new ArgumentNullException("Doc");

        // Create a new EncryptedXml object.
        EncryptedXml exml = new EncryptedXml(Doc);

        // Decrypt the XML document.
        exml.DecryptDocument();

    }

It worked like a charm until recently that some of our clients started to upgrade their framework to 4.6.2, so the method DecryptDocument() stopped working. Now it throws an exception "The algorithm group '' is invalid". If I remove .net framework 4.6.2 it works again.

The sample code in this link will reproduce the error, it will encrypt successfully then fail to decrypt.

I'm using A3 certificates, pendrive token. Anyone have faced this problem? there is any work around in .net 4.6.2?

Edit 1:

Stacktrace:

at System.Security.Cryptography.CngAlgorithmGroup..ctor(String algorithmGroup)
 at System.Security.Cryptography.CngKey.get_AlgorithmGroup()
 at System.Security.Cryptography.RSACng..ctor(CngKey key)
 at System.Security.Cryptography.X509Certificates.RSACertificateExtensions.GetRSAPrivateKey(X509Certificate2 certificate)
 at System.Security.Cryptography.CngLightup.GetRSAPrivateKey(X509Certificate2 cert)
 at System.Security.Cryptography.Xml.EncryptedXml.DecryptEncryptedKey(EncryptedKey encryptedKey)
 at System.Security.Cryptography.Xml.EncryptedXml.GetDecryptionKey(EncryptedData encryptedData, String symmetricAlgorithmUri)
 at System.Security.Cryptography.Xml.EncryptedXml.DecryptDocument()
 at Criptografar.Program.Decrypt(XmlDocument Doc) in C:\Users\leoka\Documents\Visual Studio 2017\Projects\ConsoleApp4\Criptografar\Program.cs:line 152
 at Criptografar.Program.Main(String[] args) in C:\Users\leoka\Documents\Visual Studio 2017\Projects\ConsoleApp4\Criptografar\Program.cs:line 83

Body:
I cannot reproduce the problem myself - I don't have the "pendrive token" which I suspect is the problem - so this is guesswork.
There are two generations of cryptographic APIs in Windows - the "old" one and the "new generation" one, known as CNG.
Now, if you look at the source code for the CngLightup type that appears midway through your stack trace, specifically the DetectRsaCngSupport method, you'll see that .NET framework tries to use the new generation API if possible. My guess is that the "pendrive token" device does not support the new API. You can verify this by forcing the use of the old API. Unfortunately, there does not seem to be a public configuration flag that controls this, so you must resort to reflection-based hacks. For example, you can put something like this at the beginning of your program, so that it runs once, before you try the decrypting operation:

    var cngLightupType = typeof(EncryptedXml).Assembly.GetType("System.Security.Cryptography.CngLightup");
    var preferRsaCngField = cngLightupType.GetField("s_preferRsaCng", BindingFlags.Static | BindingFlags.NonPublic);
    var getRsaPublicKeyField = cngLightupType.GetField("s_getRsaPublicKey", BindingFlags.Static | BindingFlags.NonPublic);
    var getRsaPrivateKeyField = cngLightupType.GetField("s_getRsaPrivateKey", BindingFlags.Static | BindingFlags.NonPublic);
    preferRsaCngField.SetValue(null, new Lazy<bool>(() => false));
    getRsaPublicKeyField.SetValue(null, null);
    getRsaPrivateKeyField.SetValue(null, null);

Do note that it is extremely hacky, not thread-safe, error handling is omitted etc. If you verify that the CNG usage is the problem, you can then ask the "pendrive token" supplier to provide drivers that work with CNG. Or you can live with the hack above, rewritten for more safety.


问:
What's the difference between traveling salesman and chinese traveling?
What's the difference between travelling salesman problem (TSP) and Chinese postman problem (CPP)?

For me, both wants go to a destination, and then back.

答:
Chinese postman

Travelling salesman

From a brief read of the two articles (and I never took a course in graph theory, so I could be talking through my hat), it appears that the "CPP" involves visiting all edges, and the "TSP" involves visiting all nodes.

ContentLicense: CC BY-SA 4.0


问:
Group array of javascript objects based on value into there own sub array of objects
I have an array of Javascript objects like below.

```<code>        [{

            "email": "alex@test.com",
            "fn": "Alex",
            "sn": "McPherson",
            "phone": "01233xxxxx",
            "hours": "40",
            "rate": "20",
            "amount": "200",
            "vat": "60",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        },
        {

            "email": "mike@test.com",
            "fn": "Mike",
            "sn": "Mann",
            "phone": "01233xxxxx",
            "hours": "50",
            "rate": "70",
            "amount": "500",
            "vat": "90",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        },
        {

            "email": "fred@test.com",
            "fn": "Fred",
            "sn": "Frogg",
            "phone": "01233xxxxx",
            "hours": "80",
            "rate": "90",
            "amount": "800",
            "vat": "100",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        },
        {

            "email": "alex@test.com",
            "fn": "Alex",
            "sn": "McPherson",
            "phone": "01233xxxxx",
            "hours": "90",
            "rate": "30",
            "amount": "900",
            "vat": "120",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        }]
</code>```

What I ideally want is to group those of the same value (email) into there own sub array of objects i.e if you look at the array above you will see I have 2 entries for the same person Alex McPherson. What I want to do is the below if possible move and combine into a sub array and the same for any other value that exists more than once.

```<code>    [[{

        "email": "alex@test.com",
        "fn": "Alex",
        "sn": "McPherson",
        "phone": "01233xxxxx",
        "hours": "40",
        "rate": "20",
        "amount": "200",
        "vat": "60",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    },{

        "email": "alex@test.com",
        "fn": "Alex",
        "sn": "McPherson",
        "phone": "01233xxxxx",
        "hours": "90",
        "rate": "30",
        "amount": "900",
        "vat": "120",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    }],
    [{

        "email": "mike@test.com",
        "fn": "Mike",
        "sn": "Mann",
        "phone": "01233xxxxx",
        "hours": "50",
        "rate": "70",
        "amount": "500",
        "vat": "90",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    }],
    [{

        "email": "fred@test.com",
        "fn": "Fred",
        "sn": "Frogg",
        "phone": "01233xxxxx",
        "hours": "80",
        "rate": "90",
        "amount": "800",
        "vat": "100",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    }]]
</code>```

I can't seem to get my head around resorting the array.

答:
You could use an ES6 map to collect the data per email and then extract the resulting values from that map (assuming data is input):

```<code>Array.from(
    data.reduce(
        (acc, o) => (acc.get(o.email).push(o), acc),
        new Map(data.map( o => [o.email, []] ))
    ), ([key, value]) => value
)
</code>```

var data = [{
    "email": "alex@test.com",
    "fn": "Alex",
    "sn": "McPherson",
    "phone": "01233xxxxx",
    "hours": "40",
    "rate": "20",
    "amount": "200",
    "vat": "60",
    "agency": "test",
    "start": "08/06/2017",
    "end": "10/06/2017"
}, {
    "email": "mike@test.com",
    "fn": "Mike",
    "sn": "Mann",
    "phone": "01233xxxxx",
    "hours": "50",
    "rate": "70",
    "amount": "500",
    "vat": "90",
    "agency": "test",
    "start": "08/06/2017",
    "end": "10/06/2017"
}, {
    "email": "fred@test.com",
    "fn": "Fred",
    "sn": "Frogg",
    "phone": "01233xxxxx",
    "hours": "80",
    "rate": "90",
    "amount": "800",
    "vat": "100",
    "agency": "test",
    "start": "08/06/2017",
    "end": "10/06/2017"
}, {
    "email": "alex@test.com",
    "fn": "Alex",
    "sn": "McPherson",
    "phone": "01233xxxxx",
    "hours": "90",
    "rate": "30",
    "amount": "900",
    "vat": "120",
    "agency": "test",
    "start": "08/06/2017",
    "end": "10/06/2017"
}];

var result = Array.from(
    data.reduce(
        (acc, o) => (acc.get(o.email).push(o), acc),
        new Map(data.map( o => [o.email, []] ))
    ), ([key, value]) => value
);

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have an array of Javascript objects like below.

        [{

            "email": "alex@test.com",
            "fn": "Alex",
            "sn": "McPherson",
            "phone": "01233xxxxx",
            "hours": "40",
            "rate": "20",
            "amount": "200",
            "vat": "60",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        },
        {

            "email": "mike@test.com",
            "fn": "Mike",
            "sn": "Mann",
            "phone": "01233xxxxx",
            "hours": "50",
            "rate": "70",
            "amount": "500",
            "vat": "90",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        },
        {

            "email": "fred@test.com",
            "fn": "Fred",
            "sn": "Frogg",
            "phone": "01233xxxxx",
            "hours": "80",
            "rate": "90",
            "amount": "800",
            "vat": "100",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        },
        {

            "email": "alex@test.com",
            "fn": "Alex",
            "sn": "McPherson",
            "phone": "01233xxxxx",
            "hours": "90",
            "rate": "30",
            "amount": "900",
            "vat": "120",
            "agency": "test",
            "start": "08/06/2017",
            "end": "10/06/2017"
        }]

What I ideally want is to group those of the same value (email) into there own sub array of objects i.e if you look at the array above you will see I have 2 entries for the same person Alex McPherson. What I want to do is the below if possible move and combine into a sub array and the same for any other value that exists more than once.

    [[{

        "email": "alex@test.com",
        "fn": "Alex",
        "sn": "McPherson",
        "phone": "01233xxxxx",
        "hours": "40",
        "rate": "20",
        "amount": "200",
        "vat": "60",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    },{

        "email": "alex@test.com",
        "fn": "Alex",
        "sn": "McPherson",
        "phone": "01233xxxxx",
        "hours": "90",
        "rate": "30",
        "amount": "900",
        "vat": "120",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    }],
    [{

        "email": "mike@test.com",
        "fn": "Mike",
        "sn": "Mann",
        "phone": "01233xxxxx",
        "hours": "50",
        "rate": "70",
        "amount": "500",
        "vat": "90",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    }],
    [{

        "email": "fred@test.com",
        "fn": "Fred",
        "sn": "Frogg",
        "phone": "01233xxxxx",
        "hours": "80",
        "rate": "90",
        "amount": "800",
        "vat": "100",
        "agency": "test",
        "start": "08/06/2017",
        "end": "10/06/2017"
    }]]

I can't seem to get my head around resorting the array.

Body:
You could use an ES6 map to collect the data per email and then extract the resulting values from that map (assuming data is input):

Array.from(
    data.reduce(
        (acc, o) => (acc.get(o.email).push(o), acc),
        new Map(data.map( o => [o.email, []] ))
    ), ([key, value]) => value
)

var data = [{
    "email": "alex@test.com",
    "fn": "Alex",
    "sn": "McPherson",
    "phone": "01233xxxxx",
    "hours": "40",
    "rate": "20",
    "amount": "200",
    "vat": "60",
    "agency": "test",
    "start": "08/06/2017",
    "end": "10/06/2017"
}, {
    "email": "mike@test.com",
    "fn": "Mike",
    "sn": "Mann",
    "phone": "01233xxxxx",
    "hours": "50",
    "rate": "70",
    "amount": "500",
    "vat": "90",
    "agency": "test",
    "start": "08/06/2017",
    "end": "10/06/2017"
}, {
    "email": "fred@test.com",
    "fn": "Fred",
    "sn": "Frogg",
    "phone": "01233xxxxx",
    "hours": "80",
    "rate": "90",
    "amount": "800",
    "vat": "100",
    "agency": "test",
    "start": "08/06/2017",
    "end": "10/06/2017"
}, {
    "email": "alex@test.com",
    "fn": "Alex",
    "sn": "McPherson",
    "phone": "01233xxxxx",
    "hours": "90",
    "rate": "30",
    "amount": "900",
    "vat": "120",
    "agency": "test",
    "start": "08/06/2017",
    "end": "10/06/2017"
}];

var result = Array.from(
    data.reduce(
        (acc, o) => (acc.get(o.email).push(o), acc),
        new Map(data.map( o => [o.email, []] ))
    ), ([key, value]) => value
);

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
IntelliJ System.out.println() - Cannot resolve method println(java.lang.String)
I am using IntelliJ IDEA, learning Java. All went well until yesterday, when the mentioned error occurred.

I didn't make any changes. I was looking for the solution the following ways:

reboot the pc

restart IntelliJ.

delete the project directory and use another one (both on desktop)

nothing helps. buy running simple hello world method. It keeps showing this error:

Is there someone able to help me?

答:
In my case my project was set up to Java 6th and I had installed jre1.8.0_131 which I assume was causing the problem. After changing Java to level 8 problem have been solved.

Press Ctrl+Alt+Shift+s or go to File -> Project Structure -> Project, and set Project Language Level to yours.


问:
Ignore the first row when running the macro
I have the below macro to transfer data from one sheet to another. However I need the first row to be the date (date modified) so I need the macro to ignore the top row. I've looked online but can't seem to find the solution?

```<code>Sub HistoricMD()

    ActiveSheet.Range("K7:K15").Copy
    Sheets("Historic MD").Range("IV1").End(xlToLeft).Offset(1, 1).PasteSpecial xlValues
    Application.CutCopyMode = False

End Sub
</code>```

On another note I've just added

```<code>=IF(B2 >0,NOW(),"")
</code>```

to get the date modified, any other better solutions would be good!

Thank you :)

答:
Alter as follows: We will paste in row 2 (as you did already, using offset), and manually put the date in row 1:</p>

```<code>Sub HistoricMD()

    ActiveSheet.Range("K7:K15").Copy
    Sheets("Historic MD").Range("IV1").End(xlToLeft).Offset(1, 1).PasteSpecial xlValues
    Sheets("Historic MD").Range("IV1").End(xlToLeft).Offset(0, 1).value = Date
    Application.CutCopyMode = False

End Sub
</code>```

Body:
I have the below macro to transfer data from one sheet to another. However I need the first row to be the date (date modified) so I need the macro to ignore the top row. I've looked online but can't seem to find the solution?

Sub HistoricMD()

    ActiveSheet.Range("K7:K15").Copy
    Sheets("Historic MD").Range("IV1").End(xlToLeft).Offset(1, 1).PasteSpecial xlValues
    Application.CutCopyMode = False

End Sub

On another note I've just added

=IF(B2 >0,NOW(),"")

to get the date modified, any other better solutions would be good!

Thank you :)

Body:
Alter as follows: We will paste in row 2 (as you did already, using offset), and manually put the date in row 1:

Sub HistoricMD()

    ActiveSheet.Range("K7:K15").Copy
    Sheets("Historic MD").Range("IV1").End(xlToLeft).Offset(1, 1).PasteSpecial xlValues
    Sheets("Historic MD").Range("IV1").End(xlToLeft).Offset(0, 1).value = Date
    Application.CutCopyMode = False

End Sub


问:
What is the purpose of tf.global_variables_initializer?
I would like to understand what tf.global_variables_initializer does in a bit more detail.
A sparse description is given here:

Returns an Op that initializes global variables.

But that doesn't really help me. I know that the op is necessary to initialize the graph, but what does that actually mean? Is this the step where the graph is complied?

答:
A more complete description is given here.

Only after running tf.global_variables_initializer() in a session will your variables hold the values you told them to hold when you declare them (tf.Variable(tf.zeros(...)), tf.Variable(tf.random_normal(...)),...).

From the TF doc :

Calling tf.Variable() adds several ops to the graph:

A variable op that holds the variable value.

An initializer op that sets the variable to its initial value. This is actually a tf.assign op.

The ops for the initial value, such as the zeros op for the biases variable in the example are also added to the graph.

And also:

Variable initializers must be run explicitly before other ops in your
  model can be run. The easiest way to do that is to add an op that runs
  all the variable initializers, and run that op before using the model.


问:
c# hosting a usercontrol in IE
Our web page is only available internally in our company and we am very intrested in being able to offer  interactive .net usercontrols on our departments website in the .Net 2.0 enviorment. I have been successful with embeding the object as so:

```<code><object id="Object1" classid="http:EmbedTest1.dll#EmbedTest1.UserControl1"
        width="400" height="400">
    <param name="TestStr" value="Test Param String" />
</object>
</code>```

The control worked just fine and the value was passed to the control without issue.
But I had a problem with passing  subsequent values back to the embedded control

 attempt to Recieve event from control:

attempt to update control:

```<code><script type="text/javascript">
   function UpdateStr()
   {
      Object1.Text = "update string";
   }
</script>
</code>```

Reference:

http://www.15seconds.com/issue/030610.htm

http://windowsclient.net/articles/iesourcing.aspx

Questions:

Is this technology outdated? - if so is there a replacement

Should I just work with action script instead of trying this?

I have got this to partially work and I was attempting to connect to a webservice that I have running and I got many security exceptions...I didn't get the same exceptions when I used action scipt2 in the same manner?

(side note : - how do i paste html script examples?)

Thanks.

Brad

答:
1, 2) Yes it is outdated. If you want to work in .NET (and you're bent on having a control rather than an ASP.NET-style page/site), give Silverlight a try instead.

3) .NET code running in the browser is subject to very strict security controls (can't call back to a web site it didn't come from, for example).

OwnerDisplayName: Brad

Title: c# hosting a usercontrol in IE

Body:
Our web page is only available internally in our company and we am very intrested in being able to offer  interactive .net usercontrols on our departments website in the .Net 2.0 enviorment. I have been successful with embeding the object as so:

<object id="Object1" classid="http:EmbedTest1.dll#EmbedTest1.UserControl1"
        width="400" height="400">
    <param name="TestStr" value="Test Param String" />
</object>

The control worked just fine and the value was passed to the control without issue.
But I had a problem with passing  subsequent values back to the embedded control

 attempt to Recieve event from control:

attempt to update control:

Reference:

http://www.15seconds.com/issue/030610.htm

http://windowsclient.net/articles/iesourcing.aspx

Questions:

Is this technology outdated? - if so is there a replacement

Should I just work with action script instead of trying this?

I have got this to partially work and I was attempting to connect to a webservice that I have running and I got many security exceptions...I didn't get the same exceptions when I used action scipt2 in the same manner?

(side note : - how do i paste html script examples?)

Thanks.

Brad

LastEditorDisplayName: Benoit

OwnerDisplayName: DannySmurf


问:
macro that will insert a space between words in an array
I need to write a macro that will insert a space between each word in the final array. How could I achieve this and where must I initialize and call it.

Desired output: "Say Cheese Okay".

Output so far: "SayCheeseOkay"

My code so far:

```<code>INCLUDE Irvine32.inc

.data
seq1 byte 'Sequence1 : ', 0
seq2 byte 'Sequence2 : ', 0
seq3 byte 'Sequence3 : ', 0
fin_seq byte 'Final Sequence : ', 0
s1 byte 'Say', 0
s2 byte 'Cheese', 0
s3 byte 'Okay', 0
s4 byte 30 dup(?)

.code
main PROC
    cld
    mov edx, offset seq1
    call WriteString
    mov edx, offset s1
    call WriteString
    call Crlf

    mov edx, offset seq2
    call WriteString
    mov edx, offset s2
    call WriteString
    call Crlf

    mov edx, offset seq3
    call WriteString
    mov edx, offset s3
    call WriteString
    call Crlf

    mov ecx, LENGTHOF s1
    mov esi, offset s1
    mov edi, offset s4

copy1 : movsb
    loop copy1

    mov ecx, LENGTHOF s2
    mov esi, offset s2
    mov edi, offset s4
    add edi, LENGTHOF s1
    sub edi, 1

copy2: movsb
    loop copy2
    mov ecx, LENGTHOF s3
    mov esi, offset s3
    mov edi, offset s4
    add edi, LENGTHOF s1
    add edi, LENGTHOF s2
    sub edi, 2

copy3: movsb
    loop copy3
    mov edi, offset s4
    mov ecx, lengthof s4
    mov al, ' '
    cld

c1:
    scasb
    je c2
    cmp ecx, 0
    jz quit
    loop c1

c2:
    cld
    sub edi, 1
    stosb
    jmp c1

quit:
    mov ecx, LENGTHOF s4
    mov esi, OFFSET s4
    mov ebx, 0

cycle:
    mov al, [esi]
    jmp exl

exl:
    movsb
    loop cycle
    mov edx, offset fin_seq
    call WriteString
    mov edx, offset s4
    call WriteString

    call Crlf
    call ReadKey
    call ReadChar

exit
main ENDP
END main
</code>```

答:
The funny thing is, that with the way you defined s1,s2,s3 in memory, you can "concatenate" the strings into single one just by this (this is not solution to your assignment, as it effectively takes all the work out of it, it's just demonstration how things in assembly can be fast, if the programmer carefully reasons about what has to be done and comes up with optimal algorithm first ... also it demonstrates somewhat more meaningful way of using a macro, although in my own code I would rather use procedure, unless some special performance reasons would made macro needed):

```<code>INCLUDE Irvine32.inc

.data
seq1 byte 'Sequence1 : ', 0
seq2 byte 'Sequence2 : ', 0
seq3 byte 'Sequence3 : ', 0
fin_seq byte 'Final Sequence : ', 0
s1 byte 'Say', 0
s2 byte 'Cheese', 0
s3 byte 'Okay', 0

.code

DisplayLabelValueEol MACRO labelStrPtr:REQ, valueStrPtr:REQ
    mov     edx,labelStrPtr
    call    WriteString
    mov     edx,valueStrPtr
    call    WriteString
    call    Crlf
    ENDM

main PROC
    DisplayLabelValueEol OFFSET seq1, OFFSET s1
    DisplayLabelValueEol OFFSET seq2, OFFSET s2
    DisplayLabelValueEol OFFSET seq3, OFFSET s3
    ; modify s1-s2-s3 memory to work as single concatenated string
    mov     al,' '
    mov     [s2-1],al       ; replace the original s1 zero terminator
    mov     [s3-1],al       ; replace the original s2 zero terminator
    ; display result
    DisplayLabelValueEol OFFSET fin_seq, OFFSET s1

    call ReadKey
    call ReadChar
    exit
main ENDP

END main
</code>```

(unfortunately I don't have MASM + Irvine32 anywhere, so I didn't actually test it, let me know if this does not work).

Body:
I need to write a macro that will insert a space between each word in the final array. How could I achieve this and where must I initialize and call it.

Desired output: "Say Cheese Okay".

Output so far: "SayCheeseOkay"

My code so far:

INCLUDE Irvine32.inc

.data
seq1 byte 'Sequence1 : ', 0
seq2 byte 'Sequence2 : ', 0
seq3 byte 'Sequence3 : ', 0
fin_seq byte 'Final Sequence : ', 0
s1 byte 'Say', 0
s2 byte 'Cheese', 0
s3 byte 'Okay', 0
s4 byte 30 dup(?)

.code
main PROC
    cld
    mov edx, offset seq1
    call WriteString
    mov edx, offset s1
    call WriteString
    call Crlf

    mov edx, offset seq2
    call WriteString
    mov edx, offset s2
    call WriteString
    call Crlf

    mov edx, offset seq3
    call WriteString
    mov edx, offset s3
    call WriteString
    call Crlf

    mov ecx, LENGTHOF s1
    mov esi, offset s1
    mov edi, offset s4

copy1 : movsb
    loop copy1

    mov ecx, LENGTHOF s2
    mov esi, offset s2
    mov edi, offset s4
    add edi, LENGTHOF s1
    sub edi, 1

copy2: movsb
    loop copy2
    mov ecx, LENGTHOF s3
    mov esi, offset s3
    mov edi, offset s4
    add edi, LENGTHOF s1
    add edi, LENGTHOF s2
    sub edi, 2

copy3: movsb
    loop copy3
    mov edi, offset s4
    mov ecx, lengthof s4
    mov al, ' '
    cld

c1:
    scasb
    je c2
    cmp ecx, 0
    jz quit
    loop c1

c2:
    cld
    sub edi, 1
    stosb
    jmp c1

quit:
    mov ecx, LENGTHOF s4
    mov esi, OFFSET s4
    mov ebx, 0

cycle:
    mov al, [esi]
    jmp exl

exl:
    movsb
    loop cycle
    mov edx, offset fin_seq
    call WriteString
    mov edx, offset s4
    call WriteString

    call Crlf
    call ReadKey
    call ReadChar

exit
main ENDP
END main

Body:
The funny thing is, that with the way you defined s1,s2,s3 in memory, you can "concatenate" the strings into single one just by this (this is not solution to your assignment, as it effectively takes all the work out of it, it's just demonstration how things in assembly can be fast, if the programmer carefully reasons about what has to be done and comes up with optimal algorithm first ... also it demonstrates somewhat more meaningful way of using a macro, although in my own code I would rather use procedure, unless some special performance reasons would made macro needed):

INCLUDE Irvine32.inc

.data
seq1 byte 'Sequence1 : ', 0
seq2 byte 'Sequence2 : ', 0
seq3 byte 'Sequence3 : ', 0
fin_seq byte 'Final Sequence : ', 0
s1 byte 'Say', 0
s2 byte 'Cheese', 0
s3 byte 'Okay', 0

.code

DisplayLabelValueEol MACRO labelStrPtr:REQ, valueStrPtr:REQ
    mov     edx,labelStrPtr
    call    WriteString
    mov     edx,valueStrPtr
    call    WriteString
    call    Crlf
    ENDM

main PROC
    DisplayLabelValueEol OFFSET seq1, OFFSET s1
    DisplayLabelValueEol OFFSET seq2, OFFSET s2
    DisplayLabelValueEol OFFSET seq3, OFFSET s3
    ; modify s1-s2-s3 memory to work as single concatenated string
    mov     al,' '
    mov     [s2-1],al       ; replace the original s1 zero terminator
    mov     [s3-1],al       ; replace the original s2 zero terminator
    ; display result
    DisplayLabelValueEol OFFSET fin_seq, OFFSET s1

    call ReadKey
    call ReadChar
    exit
main ENDP

END main

(unfortunately I don't have MASM + Irvine32 anywhere, so I didn't actually test it, let me know if this does not work).


问:
Failed to decode downloaded font
This is an error I am getting in Chrome and unfortunately searching for it hasn't given me much results. The font itself is appearing correctly. However I still get this error/warning. More specifically, this is the full warning:

"Failed to decode downloaded font:
  http://localhost:8000/app/fonts/Lato/"

My CSS are these:

```<code>@font-face {
    font-family:"Lato";
    src: url("../fonts/Lato/");
}

html, body {
    font-family:'Lato';
}
</code>```

I just do not understand. The font is applied correctly, but the warning is always there. Trying to use Sans-Serif makes the font revert to the normal browser font, so that may be it, but I am not sure, and even after searching I have found nothing. Thanks!

EDIT

There are various font files, all from the same family. I am trying to load them all. The font files are .ttf. I am loading them from a local folder, and there are various font-files, like Lato-Black.ttf, Lato-Bold.ttf, Lato-Italic.ttf etc.

答:
For me, the mistake was forgetting to put FTP into binary mode before uploading the font files.

Edit

You can test for this by uploading other types of binary data like images. If they also fail to display, then this may be your issue.

Title: Failed to decode downloaded font

Body:
This is an error I am getting in Chrome and unfortunately searching for it hasn't given me much results. The font itself is appearing correctly. However I still get this error/warning. More specifically, this is the full warning:

"Failed to decode downloaded font:
  http://localhost:8000/app/fonts/Lato/"

My CSS are these:

@font-face {
    font-family:"Lato";
    src: url("../fonts/Lato/");
}

html, body {
    font-family:'Lato';
}

I just do not understand. The font is applied correctly, but the warning is always there. Trying to use Sans-Serif makes the font revert to the normal browser font, so that may be it, but I am not sure, and even after searching I have found nothing. Thanks!

EDIT

There are various font files, all from the same family. I am trying to load them all. The font files are .ttf. I am loading them from a local folder, and there are various font-files, like Lato-Black.ttf, Lato-Bold.ttf, Lato-Italic.ttf etc.