问:
how to count a 0 modulus in a list
I have created a list and an iteration loop for this list. I am trying to count all the even numbers using the modulus operator.  I have initialised the count variable and used the count increment and an if statement to catch all the even numbers in a nested loop. However all I get is the number one. count equals 1, is this because of using modulus incorrectly, and item = 10 , is this because of the iteration loop reaching its end of the list?

I don't know what to change, the code structure all looks ok to me.  I tried indenting the print function. This showed me that the modulus is catching the even numbers but the count is not totalling these.

```<code>list = [1,2,3,4,5,6,7,8,9,10]
for item in list:
    count = 0
    if (item % 2 == 0):
        count = count + 1
print(count)
print(item)
print(list)
</code>```

I expect the number 5 as the result of the program as there are 5 even numbers in the list

答:
Put the count=0 outside the for loop. Right now, you reinitialize count to 0 during each iteration of the for loop.

Also, don't name your variable as built-in function names: In your case, don't use list as a variable name. Below, I am using lst for example.

Minor other modifications: You can just use count += 1 instead of count = count + 1. The former is a concise way of writing. Also, you don't need to enclose the single condition in parentheses () in your case.

```<code>lst = [1,2,3,4,5,6,7,8,9,10]
count = 0

for item in lst:
    if item % 2 == 0:
        count += 1 # equivalent to count = count + 1
print(count)
print(item)
print(lst)

# 5
# 10
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
</code>```

Title: how to count a 0 modulus in a list

Body:
I have created a list and an iteration loop for this list. I am trying to count all the even numbers using the modulus operator.  I have initialised the count variable and used the count increment and an if statement to catch all the even numbers in a nested loop. However all I get is the number one. count equals 1, is this because of using modulus incorrectly, and item = 10 , is this because of the iteration loop reaching its end of the list?

I don't know what to change, the code structure all looks ok to me.  I tried indenting the print function. This showed me that the modulus is catching the even numbers but the count is not totalling these.

list = [1,2,3,4,5,6,7,8,9,10]
for item in list:
    count = 0
    if (item % 2 == 0):
        count = count + 1
print(count)
print(item)
print(list)

I expect the number 5 as the result of the program as there are 5 even numbers in the list

Body:
Put the count=0 outside the for loop. Right now, you reinitialize count to 0 during each iteration of the for loop.

Also, don't name your variable as built-in function names: In your case, don't use list as a variable name. Below, I am using lst for example.

Minor other modifications: You can just use count += 1 instead of count = count + 1. The former is a concise way of writing. Also, you don't need to enclose the single condition in parentheses () in your case.

lst = [1,2,3,4,5,6,7,8,9,10]
count = 0

for item in lst:
    if item % 2 == 0:
        count += 1 # equivalent to count = count + 1
print(count)
print(item)
print(lst)

# 5
# 10
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


来源: stackexchange

问:
React Native - How to localize app name?
I am using React Native 0.45.1.

For localization, I am using the 'react-native-i18n' package (version 2.0.2).

I want to know how I can localize my displayed app name in iOS and Android.

答:
This article contains a thorough explanation of how this works for ios:
https://hackernoon.com/localize-an-application-name-in-react-native-c36c4b2be7c3

As for Android, it's just about creating a file under
android/app/src/main/res/
copy the file under values/strings.xml
put it under ur language-region specification
ex. values-en-rUS/strings.xml
and then change the app name in there

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
How to find the list of pairs in an array using ruby?
Input:

```<code>a = [4, 5, 5, 5, 6, 6, 4, 1, 4, 4, 3, 6, 6, 3, 6, 1, 4, 5, 5, 5]
</code>```

How to list out no of pairs in an array.

Output:

9

Description

```<code>#no 1(1 pair)
#no 3(1 pair)
#no 4(2 pairs)
#no 5(3 pairs)
#no 6(2 pairs)
#so total 9 pairs
</code>```

答:
I have done like this, It works</p>

```<code>  b = []
  a.uniq.each { |i| b.push(a.count(i)/2)}
  b.sum
</code>```

Body:
Input:

a = [4, 5, 5, 5, 6, 6, 4, 1, 4, 4, 3, 6, 6, 3, 6, 1, 4, 5, 5, 5]

How to list out no of pairs in an array.

Output:

9

Description

#no 1(1 pair)
#no 3(1 pair)
#no 4(2 pairs)
#no 5(3 pairs)
#no 6(2 pairs)
#so total 9 pairs

Body:
I have done like this, It works

  b = []
  a.uniq.each { |i| b.push(a.count(i)/2)}
  b.sum


问:
Invalid Chai property: setEncoding on nock
I was using nock 9.1.6 to mock nylas API with chai 3.5.0. It was working perfectly with the code:

```<code>it('fails when no state is given and provider fails', () => {
  const user = fixture.elements.user1;
  const connector = new NylasConnector('nylas', 'connect', user);

  nock(NYLAS_API)
        .post(`/a/${DN_NYLAS_APP_ID}/accounts/${user.nylas.account_id}/downgrade`)
        .reply(500, (uri, body) => expect(body).to.eql(''));

  sinon.stub(Nylas, 'urlForAuthentication').callsFake(params => {
    expect(params).to.eql({
      redirectURI: `${DN_AUTH_SERVICE_URL}/oauth2/nylas/callback`,
      trial: false,
      state: JSON.stringify({})
    });
    return chance.url() + '?' + objectToQuery(params);
  });

  return expect(connector.getAuthenticationUrl()).to.be.rejectedWith(ProviderError)
    .then(() => User.findById(user._id))
    .then(user => {
       expect(user.nylas).not.null;
       expect(user.nylasToken).not.null;
       expect(user.nylasCursor).not.null;
     });
  })
</code>```

I tried to upgrade nock to 10.0.6 and chai to 4.2.0 and now the following error appears:

```<code>"Error: Invalid Chai property: setEncoding",
    "    at Object.proxyGetter [as get] (/home/jeremy/datananas/datananas/packages/api/node_modules/chai/lib/chai/utils/proxify.js:78:17)",
    "    at Object.isStream (/home/jeremy/datananas/datananas/packages/api/node_modules/nock/lib/common.js:382:24)",
    "    at continueWithResponseBody (/home/jeremy/datananas/datananas/packages/api/node_modules/nock/lib/request_overrider.js:435:20)",
    "    at end (/home/jeremy/datananas/datananas/packages/api/node_modules/nock/lib/request_overrider.js:385:12)",
    "    at /home/jeremy/datananas/datananas/packages/api/node_modules/nock/lib/request_overrider.js:160:9",
    "    at OverriddenClientRequest.RequestOverrider.req.write (/home/jeremy/datananas/datananas/packages/api/node_modules/nock/lib/request_overrider.js:139:9)",
    "    at OverriddenClientRequest.RequestOverrider.req.end (/home/jeremy/datananas/datananas/packages/api/node_modules/nock/lib/request_overrider.js:156:11)",
    "    at Request.end (/home/jeremy/datananas/datananas/packages/api/node_modules/request/request.js:1514:14)",
    "    at end (/home/jeremy/datananas/datananas/packages/api/node_modules/request/request.js:564:14)",
    "    at Immediate.<anonymous> (/home/jeremy/datananas/datananas/packages/api/node_modules/request/request.js:578:7)",
    "    at runCallback (timers.js:705:18)",
    "    at tryOnImmediate (timers.js:676:5)",
    "    at processImmediate (timers.js:658:5)"
</code>```

The error appears on connector.getAuthenticationUrl() as it's the function who called the mocked function. In this function, their is a call to nylasRequest and the error appears when the line with the new Promise() is reached:

```<code>function nylasRequest(uri, token, body) {
  const params = {
    uri: `https://api.nylas.com${uri}`,
    method: 'POST',
    json: body
  };

  if (token)
    params.auth = { user: token };

  console.log('This line appears. All params are valid.')
  return new Promise((resolve, reject) => request(params, (error, res, body) =>  {
    console.log('This line never shows up');
    // some code
  }));
}
</code>```

I use request 2.88.0 and I did not change the version I use.

答:
I'm assuming your issue is with this line:

```<code>.reply(500, (uri, body) => expect(body).to.eql(''))
</code>```

Nock is going to use the returned value from that function as the body of the fake response. Returning a chai expectation from the function seems to confuse nock when it tries to figure out if the response body is streamable.

I would change it to something like this:

```<code>nock(NYLAS_API)
  .post(`/a/${DN_NYLAS_APP_ID}/accounts/${user.nylas.account_id}/downgrade`)
  .reply(500, (uri, body) => {
    expect(body).to.eql('')
    return ''
  });
</code>```

Body:
I was using nock 9.1.6 to mock nylas API with chai 3.5.0. It was working perfectly with the code:

it('fails when no state is given and provider fails', () => {
  const user = fixture.elements.user1;
  const connector = new NylasConnector('nylas', 'connect', user);

  nock(NYLAS_API)
        .post(`/a/${DN_NYLAS_APP_ID}/accounts/${user.nylas.account_id}/downgrade`)
        .reply(500, (uri, body) => expect(body).to.eql(''));

  sinon.stub(Nylas, 'urlForAuthentication').callsFake(params => {
    expect(params).to.eql({
      redirectURI: `${DN_AUTH_SERVICE_URL}/oauth2/nylas/callback`,
      trial: false,
      state: JSON.stringify({})
    });
    return chance.url() + '?' + objectToQuery(params);
  });

  return expect(connector.getAuthenticationUrl()).to.be.rejectedWith(ProviderError)
    .then(() => User.findById(user._id))
    .then(user => {
       expect(user.nylas).not.null;
       expect(user.nylasToken).not.null;
       expect(user.nylasCursor).not.null;
     });
  })

I tried to upgrade nock to 10.0.6 and chai to 4.2.0 and now the following error appears:

"Error: Invalid Chai property: setEncoding",
    "    at Object.proxyGetter [as get] (/home/jeremy/datananas/datananas/packages/api/node_modules/chai/lib/chai/utils/proxify.js:78:17)",
    "    at Object.isStream (/home/jeremy/datananas/datananas/packages/api/node_modules/nock/lib/common.js:382:24)",
    "    at continueWithResponseBody (/home/jeremy/datananas/datananas/packages/api/node_modules/nock/lib/request_overrider.js:435:20)",
    "    at end (/home/jeremy/datananas/datananas/packages/api/node_modules/nock/lib/request_overrider.js:385:12)",
    "    at /home/jeremy/datananas/datananas/packages/api/node_modules/nock/lib/request_overrider.js:160:9",
    "    at OverriddenClientRequest.RequestOverrider.req.write (/home/jeremy/datananas/datananas/packages/api/node_modules/nock/lib/request_overrider.js:139:9)",
    "    at OverriddenClientRequest.RequestOverrider.req.end (/home/jeremy/datananas/datananas/packages/api/node_modules/nock/lib/request_overrider.js:156:11)",
    "    at Request.end (/home/jeremy/datananas/datananas/packages/api/node_modules/request/request.js:1514:14)",
    "    at end (/home/jeremy/datananas/datananas/packages/api/node_modules/request/request.js:564:14)",
    "    at Immediate.<anonymous> (/home/jeremy/datananas/datananas/packages/api/node_modules/request/request.js:578:7)",
    "    at runCallback (timers.js:705:18)",
    "    at tryOnImmediate (timers.js:676:5)",
    "    at processImmediate (timers.js:658:5)"

The error appears on connector.getAuthenticationUrl() as it's the function who called the mocked function. In this function, their is a call to nylasRequest and the error appears when the line with the new Promise() is reached:

function nylasRequest(uri, token, body) {
  const params = {
    uri: `https://api.nylas.com${uri}`,
    method: 'POST',
    json: body
  };

  if (token)
    params.auth = { user: token };

  console.log('This line appears. All params are valid.')
  return new Promise((resolve, reject) => request(params, (error, res, body) =>  {
    console.log('This line never shows up');
    // some code
  }));
}

I use request 2.88.0 and I did not change the version I use.

Body:
I'm assuming your issue is with this line:

.reply(500, (uri, body) => expect(body).to.eql(''))

Nock is going to use the returned value from that function as the body of the fake response. Returning a chai expectation from the function seems to confuse nock when it tries to figure out if the response body is streamable.

I would change it to something like this:

nock(NYLAS_API)
  .post(`/a/${DN_NYLAS_APP_ID}/accounts/${user.nylas.account_id}/downgrade`)
  .reply(500, (uri, body) => {
    expect(body).to.eql('')
    return ''
  });


问:
Hackerrank: Climbing the Leaderboard
i have a deal with a hackerrank algorithm problem.

It works at all cases, except 6-7-8-9. It gives timeout error. I had spent so much time at this level. Someone saw where is problem?

```<code>static long[] climbingLeaderboard(long[] scores, long[] alice)
{
    //long[] ranks = new long[scores.Length];
    long[] aliceRanks = new long[alice.Length]; // same length with alice length
    long lastPoint = 0;
    long lastRank;
    for (long i = 0; i < alice.Length; i++)
    {
        lastPoint = scores[0];
        lastRank = 1;
        bool isIn = false; // if never drop in if statement
        for (long j = 0; j < scores.Length; j++)
        {
            if (lastPoint != scores[j])  //if score is not same, raise the variable
            {
                lastPoint = scores[j];
                lastRank++;
            }

            if (alice[i] >= scores[j])
            {
                aliceRanks[i] = lastRank;
                isIn = true;
                break;
            }
            aliceRanks[i] = !isIn & j + 1 == scores.Length ? ++lastRank : aliceRanks[i]; //drop in here
        }
    }
    return aliceRanks;
}
</code>```

答:
Based on the given constraint brute-force solution will not be efficient for the problem.
you have to optimize your code and the key part here is to look up for exact place which can be effectively done by using binary search.

Here is the solution using binary search:-

```<code>static int[] climbingLeaderboard(int[] scores, int[] alice) {
        int n = scores.length;
        int m = alice.length;

        int res[] = new int[m];
        int[] rank = new int[n];

        rank[0] = 1;

        for (int i = 1; i < n; i++) {
            if (scores[i] == scores[i - 1]) {
                rank[i] = rank[i - 1];
            } else {
                rank[i] = rank[i - 1] + 1;
            }
        }

        for (int i = 0; i < m; i++) {
            int aliceScore = alice[i];
            if (aliceScore > scores[0]) {
                res[i] = 1;
            } else if (aliceScore < scores[n - 1]) {
                res[i] = rank[n - 1] + 1;
            } else {
                int index = binarySearch(scores, aliceScore);
                res[i] = rank[index];

            }
        }
        return res;

    }

    private static int binarySearch(int[] a, int key) {

        int lo = 0;
        int hi = a.length - 1;

        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (a[mid] == key) {
                return mid;
            } else if (a[mid] < key && key < a[mid - 1]) {
                return mid;
            } else if (a[mid] > key && key >= a[mid + 1]) {
                return mid + 1;
            } else if (a[mid] < key) {
                hi = mid - 1;
            } else if (a[mid] > key) {
                lo = mid + 1;
            }
        }
        return -1;
    }
</code>```

You can refer to this link for a more detailed video explanation.

Title: Hackerrank: Climbing the Leaderboard

Body:
i have a deal with a hackerrank algorithm problem.

It works at all cases, except 6-7-8-9. It gives timeout error. I had spent so much time at this level. Someone saw where is problem?

static long[] climbingLeaderboard(long[] scores, long[] alice)
{
    //long[] ranks = new long[scores.Length];
    long[] aliceRanks = new long[alice.Length]; // same length with alice length
    long lastPoint = 0;
    long lastRank;
    for (long i = 0; i < alice.Length; i++)
    {
        lastPoint = scores[0];
        lastRank = 1;
        bool isIn = false; // if never drop in if statement
        for (long j = 0; j < scores.Length; j++)
        {
            if (lastPoint != scores[j])  //if score is not same, raise the variable
            {
                lastPoint = scores[j];
                lastRank++;
            }

            if (alice[i] >= scores[j])
            {
                aliceRanks[i] = lastRank;
                isIn = true;
                break;
            }
            aliceRanks[i] = !isIn & j + 1 == scores.Length ? ++lastRank : aliceRanks[i]; //drop in here
        }
    }
    return aliceRanks;
}

Body:
Based on the given constraint brute-force solution will not be efficient for the problem.
you have to optimize your code and the key part here is to look up for exact place which can be effectively done by using binary search.

Here is the solution using binary search:-

static int[] climbingLeaderboard(int[] scores, int[] alice) {
        int n = scores.length;
        int m = alice.length;

        int res[] = new int[m];
        int[] rank = new int[n];

        rank[0] = 1;

        for (int i = 1; i < n; i++) {
            if (scores[i] == scores[i - 1]) {
                rank[i] = rank[i - 1];
            } else {
                rank[i] = rank[i - 1] + 1;
            }
        }

        for (int i = 0; i < m; i++) {
            int aliceScore = alice[i];
            if (aliceScore > scores[0]) {
                res[i] = 1;
            } else if (aliceScore < scores[n - 1]) {
                res[i] = rank[n - 1] + 1;
            } else {
                int index = binarySearch(scores, aliceScore);
                res[i] = rank[index];

            }
        }
        return res;

    }

    private static int binarySearch(int[] a, int key) {

        int lo = 0;
        int hi = a.length - 1;

        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (a[mid] == key) {
                return mid;
            } else if (a[mid] < key && key < a[mid - 1]) {
                return mid;
            } else if (a[mid] > key && key >= a[mid + 1]) {
                return mid + 1;
            } else if (a[mid] < key) {
                hi = mid - 1;
            } else if (a[mid] > key) {
                lo = mid + 1;
            }
        }
        return -1;
    }

You can refer to this link for a more detailed video explanation.


问:
How to take specific users from JSON file?
I have a JSON file from where i am taking users data and performing operations.how to get the specific users from JSON file?

Here is the JSON file:

```<code>    "users" : {
            "ABC": {
                "ip": "10.50.10.XXXX:5555",
                "username": "user1@gmail.com",
                "password": "xyz123",
                "displayname": "user 1",
                "Mode": "Personal",
                "phonenumber": "14084xxxx",
                "pstndisplay": "+1 408-xxx-xxx"
            }
            "EFG": {
                "ip": "10.50.10.XXXX:5555",
                "username": "user2@gmail.com",
                "password": "xyz123",
                "displayname": "user 2",
                "Mode": "Personal",
                "phonenumber": "14084xxxx",
                "pstndisplay": "+1 408-xxx-xxx"
            }

             "XYZ": {
                "ip": "10.50.10.XXXX:5555",
                "username": "user3@gmail.com",
                "password": "xyz123",
                "displayname": "user 3",
                "Mode": "Personal",
                "phonenumber": "14084xxxx",
                "pstndisplay": "+1 408-xxx-xxx"
            }
</code>```

here how i am parsing the JSON data:

```<code>  ${the file as string}=    Get File    ${users_json_path}
      ${parsed}=    Evaluate  json.loads("""${the file as string}""", object_pairs_hook=collections.OrderedDict)     json, collections
      ${properties}=  Set Variable  ${parsed["users"]}
      Log  ${properties}
      :FOR    ${key}    IN    @{properties}
      \  ${sub dict}=    Get From Dictionary    ${properties}    ${key}
      \  Log  ${sub dict}
      \  Signin  ${sub dict}[ip]   ${sub dict}[username]   ${sub dict}[password]  ${sub dict}[Mode]
      \  Log  ${key} is successfully signed in.
</code>```

here is the test case:

```<code>Given Number of users signs in to their respective devices  ${ABC}
      Then ABC sees that Sign in is successful
      And No action is taken for 30 seconds
      When ABC signs out from the device
      Then ABC sees that sign out was successful
</code>```

i am expecting when i wanted to perform sign in by using particular user like ABC, it will perform sign in operation with ABC only, but it's performing sign in operation using all the users by taking the data from users.how to perform sign in operation by taking particular user from JSON?

答:
Add into start of loop:

```<code>Continue For Loop If    $key != 'ABC'
</code>```

This will skip "Signin" if user is not ABC.

Body:
I have a JSON file from where i am taking users data and performing operations.how to get the specific users from JSON file?

Here is the JSON file:

    "users" : {
            "ABC": {
                "ip": "10.50.10.XXXX:5555",
                "username": "user1@gmail.com",
                "password": "xyz123",
                "displayname": "user 1",
                "Mode": "Personal",
                "phonenumber": "14084xxxx",
                "pstndisplay": "+1 408-xxx-xxx"
            }
            "EFG": {
                "ip": "10.50.10.XXXX:5555",
                "username": "user2@gmail.com",
                "password": "xyz123",
                "displayname": "user 2",
                "Mode": "Personal",
                "phonenumber": "14084xxxx",
                "pstndisplay": "+1 408-xxx-xxx"
            }

             "XYZ": {
                "ip": "10.50.10.XXXX:5555",
                "username": "user3@gmail.com",
                "password": "xyz123",
                "displayname": "user 3",
                "Mode": "Personal",
                "phonenumber": "14084xxxx",
                "pstndisplay": "+1 408-xxx-xxx"
            }

here how i am parsing the JSON data:

  ${the file as string}=    Get File    ${users_json_path}
      ${parsed}=    Evaluate  json.loads("""${the file as string}""", object_pairs_hook=collections.OrderedDict)     json, collections
      ${properties}=  Set Variable  ${parsed["users"]}
      Log  ${properties}
      :FOR    ${key}    IN    @{properties}
      \  ${sub dict}=    Get From Dictionary    ${properties}    ${key}
      \  Log  ${sub dict}
      \  Signin  ${sub dict}[ip]   ${sub dict}[username]   ${sub dict}[password]  ${sub dict}[Mode]
      \  Log  ${key} is successfully signed in.

here is the test case:

Given Number of users signs in to their respective devices  ${ABC}
      Then ABC sees that Sign in is successful
      And No action is taken for 30 seconds
      When ABC signs out from the device
      Then ABC sees that sign out was successful

i am expecting when i wanted to perform sign in by using particular user like ABC, it will perform sign in operation with ABC only, but it's performing sign in operation using all the users by taking the data from users.how to perform sign in operation by taking particular user from JSON?

Body:
Add into start of loop:

Continue For Loop If    $key != 'ABC'

This will skip "Signin" if user is not ABC.


问:
Remove tag from image
I have an image (in AWS ECR) with 2 tags and I would like to remove one tag only.

I can easily remove from my local environment using:
docker rmi <REPOSITORY>:<TAG>

I would like to remove it from ECR. Any help would be appreciated.

答:
You can delete a tag using the following command:

```<code>aws ecr batch-delete-image --repository-name <REPO NAME> --image-ids imageTag=<TAG NAME>
</code>```

If you have only one tag and execute this command, it will remove the image. If you have multiple tags for the same image, specify one, and only the tag is removed.

Title: Remove tag from image

Body:
You can delete a tag using the following command:

aws ecr batch-delete-image --repository-name <REPO NAME> --image-ids imageTag=<TAG NAME>

If you have only one tag and execute this command, it will remove the image. If you have multiple tags for the same image, specify one, and only the tag is removed.


问:
flutter CocoaPods err (running pod install)
When I run flutter run,   CocoaPods' errr , Error running pod install

flutter stable,
updata pod, CocoaPods

```<code>CocoaPods' output:
↳
      Preparing
    Analyzing dependencies
    Inspecting targets to integrate
      Using `ARCHS` setting to build architectures of target `Pods-Runner`: (``)
    Fetching external sources
    -> Fetching podspec for `Flutter` from `.symlinks/flutter/ios`
    -> Fetching podspec for `barcode_scan` from `.symlinks/plugins/barcode_scan/ios`
    -> Fetching podspec for `flutter_full_pdf_viewer` from `.symlinks/plugins/flutter_full_pdf_viewer/ios`
    -> Fetching podspec for `flutter_record` from `.symlinks/plugins/flutter_record/ios`
    -> Fetching podspec for `flutter_vedio_compress` from `.symlinks/plugins/flutter_vedio_compress/ios`
    [!] No podspec found for `flutter_vedio_compress` in `.symlinks/plugins/flutter_vedio_compress/ios`
    /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.6.1/lib/cocoapods/external_sources/path_source.rb:14:in `block in fetch'
    /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.6.1/lib/cocoapods/user_interface.rb:86:in `titled_section'
    /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.6.1/lib/cocoapods/external_sources/path_source.rb:11:in `fetch'
    /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.6.1/lib/cocoapods/installer/analyzer.rb:825:in `fetch_external_source'
    /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.6.1/lib/cocoapods/installer/analyzer.rb:804:in `block (2 levels) in fetch_external_sources'
    /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.6.1/lib/cocoapods/installer/analyzer.rb:803:in `each'
    /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.6.1/lib/cocoapods/installer/analyzer.rb:803:in `block in fetch_external_sources'

</code>```

答:
I had a similar issue, I have stopped receiving the error while executing pod install, when I altered some of the dependencies in pubspec.yaml. What I have done was referring to the dependency's git link instead of its version number.

To make it more clear instead of:

```<code>barcode_scan: ^1.0.0
</code>```

I have written:

```<code>barcode_scan:
  git: git://github.com/apptreesoftware/flutter_barcode_reader.git
</code>```

Body:
When I run flutter run,   CocoaPods' errr , Error running pod install

flutter stable,
updata pod, CocoaPods

CocoaPods' output:
↳
      Preparing
    Analyzing dependencies
    Inspecting targets to integrate
      Using `ARCHS` setting to build architectures of target `Pods-Runner`: (``)
    Fetching external sources
    -> Fetching podspec for `Flutter` from `.symlinks/flutter/ios`
    -> Fetching podspec for `barcode_scan` from `.symlinks/plugins/barcode_scan/ios`
    -> Fetching podspec for `flutter_full_pdf_viewer` from `.symlinks/plugins/flutter_full_pdf_viewer/ios`
    -> Fetching podspec for `flutter_record` from `.symlinks/plugins/flutter_record/ios`
    -> Fetching podspec for `flutter_vedio_compress` from `.symlinks/plugins/flutter_vedio_compress/ios`
    [!] No podspec found for `flutter_vedio_compress` in `.symlinks/plugins/flutter_vedio_compress/ios`
    /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.6.1/lib/cocoapods/external_sources/path_source.rb:14:in `block in fetch'
    /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.6.1/lib/cocoapods/user_interface.rb:86:in `titled_section'
    /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.6.1/lib/cocoapods/external_sources/path_source.rb:11:in `fetch'
    /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.6.1/lib/cocoapods/installer/analyzer.rb:825:in `fetch_external_source'
    /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.6.1/lib/cocoapods/installer/analyzer.rb:804:in `block (2 levels) in fetch_external_sources'
    /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.6.1/lib/cocoapods/installer/analyzer.rb:803:in `each'
    /Library/Ruby/Gems/2.3.0/gems/cocoapods-1.6.1/lib/cocoapods/installer/analyzer.rb:803:in `block in fetch_external_sources'

Body:
I had a similar issue, I have stopped receiving the error while executing pod install, when I altered some of the dependencies in pubspec.yaml. What I have done was referring to the dependency's git link instead of its version number.

To make it more clear instead of:

barcode_scan: ^1.0.0

I have written:

barcode_scan:
  git: git://github.com/apptreesoftware/flutter_barcode_reader.git


问:
Multiple householdId's among units controllable from one Sonos mobile app?
I have 3 Sonos units controllable from my Sonos Android app: A, B, and C.
A and B return one householdId from http://<ip>:1400/info, but C returns a different householdId.

From the Sonos Android app (slightly abridged):

```<code>About My Sonos System

Controller
Version: 10.2 (build 50165071)

Sonos A
Play:1
Version: 10.2 (build 50165071)
Hardware Version: 1.20.1.601
Series Id: A200

Sonos B
Play:1
Version: 10.2 (build 50165071)
Hardware Version: 1.20.1.601
Series Id: A200

Sonos C
Play:1
Version: 10.2 (build 50165071)
Hardware Version: 1.20.1.601
Series Id: A200
</code>```

Below are the two household IDs I observed.  Of note, the strings only differ after the '.'

Sonos_K9Coj5AnNdwkpeGiArYtMHF4ug.6M_0OEa8aOhO-j2oZUMF
Sonos_K9Coj5AnNdwkpeGiArYtMHF4ug.WOnnBPGSlfiyINzEybJL

```<code>$ curl http://192.168.5.33:1400/info && echo && curl http://192.168.9.42:1400/info && echo && curl http://192.168.5.71:1400/info && echo
{"websocketUrl":"wss:\/\/192.168.5.33:1443\/websocket\/api","playerId":"RINCON_7828CA92D6B201400","householdId":"Sonos_K9Coj5AnNdwkpeGiArYtMHF4ug.6M_0OEa8aOhO-j2oZUMF","groupId":"RINCON_7828CA92D6B201400:2486844229","apiVersion":"1.12.2","minApiVersion":"1.1.0"}
{"websocketUrl":"wss:\/\/192.168.9.42:1443\/websocket\/api","playerId":"RINCON_949F3E8AE0D601400","householdId":"Sonos_K9Coj5AnNdwkpeGiArYtMHF4ug.WOnnBPGSlfiyINzEybJL","groupId":"RINCON_949F3E8AE0D601400:1922741597","apiVersion":"1.12.2","minApiVersion":"1.1.0"}
{"websocketUrl":"wss:\/\/192.168.5.71:1443\/websocket\/api","playerId":"RINCON_7828CA92D67801400","householdId":"Sonos_K9Coj5AnNdwkpeGiArYtMHF4ug.WOnnBPGSlfiyINzEybJL","groupId":"RINCON_7828CA92D67801400:3241438112","apiVersion":"1.12.2","minApiVersion":"1.1.0"}
</code>```

I expect all of these units to be in the same household, and thus have the same household ID, since they are all controllable from my Sonos Android app.

答:
Looks like they all have the same household id at the Player level (which is the part before the period), but the Cloud API thinks you have two households.

Sadly Sonos don't offer any kind of account-admin page that lets you see which apps are registered for their API, as then you could delete your account there and re-add it.

Something else to try: create a new API secret/key and login to that one with the same Sonos account, to see if the duplicate data occurs then.

Body:
I have 3 Sonos units controllable from my Sonos Android app: A, B, and C.
A and B return one householdId from http://<ip>:1400/info, but C returns a different householdId.

From the Sonos Android app (slightly abridged):

About My Sonos System

Controller
Version: 10.2 (build 50165071)

Sonos A
Play:1
Version: 10.2 (build 50165071)
Hardware Version: 1.20.1.601
Series Id: A200

Sonos B
Play:1
Version: 10.2 (build 50165071)
Hardware Version: 1.20.1.601
Series Id: A200

Sonos C
Play:1
Version: 10.2 (build 50165071)
Hardware Version: 1.20.1.601
Series Id: A200

Below are the two household IDs I observed.  Of note, the strings only differ after the '.'

Sonos_K9Coj5AnNdwkpeGiArYtMHF4ug.6M_0OEa8aOhO-j2oZUMF
Sonos_K9Coj5AnNdwkpeGiArYtMHF4ug.WOnnBPGSlfiyINzEybJL

$ curl http://192.168.5.33:1400/info && echo && curl http://192.168.9.42:1400/info && echo && curl http://192.168.5.71:1400/info && echo
{"websocketUrl":"wss:\/\/192.168.5.33:1443\/websocket\/api","playerId":"RINCON_7828CA92D6B201400","householdId":"Sonos_K9Coj5AnNdwkpeGiArYtMHF4ug.6M_0OEa8aOhO-j2oZUMF","groupId":"RINCON_7828CA92D6B201400:2486844229","apiVersion":"1.12.2","minApiVersion":"1.1.0"}
{"websocketUrl":"wss:\/\/192.168.9.42:1443\/websocket\/api","playerId":"RINCON_949F3E8AE0D601400","householdId":"Sonos_K9Coj5AnNdwkpeGiArYtMHF4ug.WOnnBPGSlfiyINzEybJL","groupId":"RINCON_949F3E8AE0D601400:1922741597","apiVersion":"1.12.2","minApiVersion":"1.1.0"}
{"websocketUrl":"wss:\/\/192.168.5.71:1443\/websocket\/api","playerId":"RINCON_7828CA92D67801400","householdId":"Sonos_K9Coj5AnNdwkpeGiArYtMHF4ug.WOnnBPGSlfiyINzEybJL","groupId":"RINCON_7828CA92D67801400:3241438112","apiVersion":"1.12.2","minApiVersion":"1.1.0"}

I expect all of these units to be in the same household, and thus have the same household ID, since they are all controllable from my Sonos Android app.


问:
Splitting date and time then transfer them to their new respective columns
I have a website which have a date and time combined in the start of meeting and end of meeting.

Meeting_start
2019-04-26 11:39:15

I already created new columns for date and time. How can I split the existing date and time then transfer them to their new respective columns?

Ps. I'm looking for SQL codes.

答:
```<code><?php

$subject = 'Meeting_start 2019-04-26 11:39:15';

$pattern = '/(\d\d\d\d\-\d\d\-\d\d).*(\d\d\:\d\d\:\d\d)/U';

preg_match_all($pattern,$subject,$matches);

$date = $matches[1][0];
$time = $matches[2][0];

echo $date . '<br>' . PHP_EOL;
echo $time . '<br>' . PHP_EOL;
</code>```

gives result

```<code>2019-04-26<br>
11:39:15<br>
</code>```

Body:
<?php

$subject = 'Meeting_start 2019-04-26 11:39:15';

$pattern = '/(\d\d\d\d\-\d\d\-\d\d).*(\d\d\:\d\d\:\d\d)/U';

preg_match_all($pattern,$subject,$matches);

$date = $matches[1][0];
$time = $matches[2][0];

echo $date . '<br>' . PHP_EOL;
echo $time . '<br>' . PHP_EOL;

gives result

2019-04-26<br>
11:39:15<br>


问:
powershell select-string output for loop foreach
I'm traditional bash user therefore i don't understand how to work foreach in powershell.

Powershell

I need output

```<code>Vasya
http://192.168.10.61:8085/data.json
Misha
http://192.168.10.82:8085/data.json
</code>```

but I receive another output

```<code>Vasya
Misha
http://192.168.10.61:8085/data.json
http://192.168.10.82:8085/data.json
</code>```

Script

$pspath="E:\monitor.ps1"
$txtpath="E:\temp.txt"
$user1="Vasya"
$user2="Misha"
$ip1="http://192.168.10.61:8085/data.json"
$ip2="http://192.168.10.82:8085/data.json"

$list = @"
${user1}-${ip1}
${user2}-${ip2}
"@

foreach ($zab in $list)
{
    $regex_url = 'http://\d+.\d+.\d+.\d+:\d+/data.json'
    $regex_name = "([A-Z]|[a-z])\w+"
    $name =  echo $zab |%{$_.split('-')} |sls -pattern $regex_name -AllMatches |%{$_.Matches -notmatch 'http|json|data'} |%{$_.Value}
    $url = echo $zab |%{$_.split('-')} |sls -pattern $regex_url -AllMatches |%{$_.Matches} |%{$_.Value}
    echo $name
    echo $url
}
```

<h3>Bash</h3>

<p>In bash work's perfect.</p>

<ul>
<li>Script</li>
</ul>

<pre class="lang-perl prettyprint-override"><code>
#!/bin/bash
users="Vasya-http://192.168.10.61:8085/data.json Misha-http://192.168.10.82:8085/data.json"

for zab in $users; do
    name=$(echo $zab |cut -f 1 -d -)
    url=$(echo $zab |cut -f 2 -d -)
    echo $name
    echo $url

done
exit 0
</code>```

Help guys my hands are tied.

答:
Your PowerShell script is quite different from the bash script.

I don't know if you need the greater complexity with the Select-String for other reasons,

but in PowerShell it could also be as easy as:

```<code>$users="Vasya-http://192.168.10.61:8085/data.json Misha-http://192.168.10.82:8085/data.json"

foreach($zab in ($users -split ' ')){
    $name,$url = $zab -split '-',2
    [PSCustomObject]@{
        Name = $name
        Url  = $url
    }
}
</code>```

for this sample object oriented output:

```<code>Name  Url
----  ---
Vasya http://192.168.10.61:8085/data.json
Misha http://192.168.10.82:8085/data.json
</code>```

Body:
I'm traditional bash user therefore i don't understand how to work foreach in powershell.

Powershell

I need output

Vasya
http://192.168.10.61:8085/data.json
Misha
http://192.168.10.82:8085/data.json

but I receive another output

Vasya
Misha
http://192.168.10.61:8085/data.json
http://192.168.10.82:8085/data.json

Script

$pspath="E:\monitor.ps1"
$txtpath="E:\temp.txt"
$user1="Vasya"
$user2="Misha"
$ip1="http://192.168.10.61:8085/data.json"
$ip2="http://192.168.10.82:8085/data.json"

$list = @"
${user1}-${ip1}
${user2}-${ip2}
"@

foreach ($zab in $list)
{
    $regex_url = 'http://\d+.\d+.\d+.\d+:\d+/data.json'
    $regex_name = "([A-Z]|[a-z])\w+"
    $name =  echo $zab |%{$_.split('-')} |sls -pattern $regex_name -AllMatches |%{$_.Matches -notmatch 'http|json|data'} |%{$_.Value}
    $url = echo $zab |%{$_.split('-')} |sls -pattern $regex_url -AllMatches |%{$_.Matches} |%{$_.Value}
    echo $name
    echo $url
}

Bash

In bash work's perfect.

Script

#!/bin/bash
users="Vasya-http://192.168.10.61:8085/data.json Misha-http://192.168.10.82:8085/data.json"

for zab in $users; do
    name=$(echo $zab |cut -f 1 -d -)
    url=$(echo $zab |cut -f 2 -d -)
    echo $name
    echo $url

done
exit 0

Help guys my hands are tied.

Body:
Your PowerShell script is quite different from the bash script.

I don't know if you need the greater complexity with the Select-String for other reasons,

but in PowerShell it could also be as easy as:

$users="Vasya-http://192.168.10.61:8085/data.json Misha-http://192.168.10.82:8085/data.json"

foreach($zab in ($users -split ' ')){
    $name,$url = $zab -split '-',2
    [PSCustomObject]@{
        Name = $name
        Url  = $url
    }
}

for this sample object oriented output:

Name  Url
----  ---
Vasya http://192.168.10.61:8085/data.json
Misha http://192.168.10.82:8085/data.json


问:
Filtering data based on input D3
I'm trying to filter down data to one value based on input. If the user enters a value, I want it to be able to display only that value on the graph. However, it's not working. I believe the code is in all the right places, just the logic isn't there.

If I remove the functionallity that attempts this, everything is fine - meaning that if I click on A, only data with type A is returned, and the same with B. But this doesn't work when I implement my code that tries to fitler down to one value.

Question:

How can I filter down to one value along the x axis based on user input, but still retain the funcationality that allows the user to switch between data types.

$(document).ready(function() {
  $("#input").attr("value", 0);
});

const margin = {
    top: 10,
    right: 30,
    bottom: 70,
    left: 65
  },
  width = 520,
  height = 480;

function SVGmaker(target) {
  const svg = d3.selectAll(target)
    .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")

  svg.append("rect")
    .attr("x", 0)
    .attr("y", 0)
    .attr("height", height)
    .attr("width", width)
    .attr("fill", "white")

  return svg;
}

const svgOne = SVGmaker("#svg");

const data = [{
    x: "1",
    y: "5",
    type: "A"
  },
  {
    x: "2",
    y: "4",
    type: "B"
  },
  {
    x: "3",
    y: "3",
    type: "B"
  },
  {
    x: "4",
    y: "2",
    type: "A"
  },
  {
    x: "5",
    y: "1",
    type: "A"
  }
]

let x = d3.scaleLinear()
  .domain([1, 5])
  .range([0, width]);

// DC SVG Settings
const xAxis = d3.axisBottom(x);

svgOne.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis)

const yAxis = d3.scaleLinear()
  .domain([0, 6])
  .range([height, 0])
svgOne.append("g")
  .call(d3.axisLeft(yAxis));

const colors = d3.scaleOrdinal()
  .domain(["A", "B"])
  .range(["red", "blue"]);

function updateData(data, type, theSVG, xAxis, yAxis, colors, value) {

  // Filters through the data
  const changeData = data.filter(function(d) {
    if (type === "A") {
      return d.type === "A"
    } else if (type === "B") {
      return d.type === "B"
    } else {
      return true;
    }
  });

  var min = d3.min(data, function(d) {
    return d.x;
  });

  const gra = theSVG
    .selectAll("circle")
    .data(changeData);

  gra.enter()
    .append("circle")
    .filter(function(d) {
      if (value <= min) {
        return d.x
      } else {
        return d.x >= value && d.x <= value
      }
    })
    .attr("cx", function(d) {
      return xAxis(d.x);
    })
    .attr("cy", function(d) {
      return yAxis(d.y);
    })
    .style("fill", function(d) {
      return colors(d.type)
    })
    .merge(gra)
    .attr("r", 11)
    .filter(function(d) {
      if (value <= min) {
        return d.x
      } else {
        return d.x >= value && d.x <= value
      }
    })
    .attr("cx", function(d) {
      return xAxis(d.x);
    })
    .attr("cy", function(d) {
      return yAxis(d.y);
    })
    .style("fill", function(d) {
      return colors(d.type)
    })

  gra.exit()
    .remove();

}

updateData(data, "", svgOne, x, yAxis, colors, 0);

let value;

function getMessage() {
  value = document.getElementById("#input").value;
}

d3.select("#a")
  .on("click", function() {
    updateData(data, "A", svgOne, x, yAxis, colors, value);
  });

d3.select("#b")
  .on("click", function() {
    updateData(data, "B", svgOne, x, yAxis, colors, value);
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<!DOCTYPE html>

<div id="svg"></div>
<button id="a">a</button>
<button id="b">b</button>
<input type="number" id="input" value=0>
<button id="submit">submit</button>

<script type="text/javascript" src="scripts.js"></script></code>```

答:
I was a bit guessing what you want to do, but really the problem was that you never set'value' variable, and thus you were always passing undefined.

When you call getElementById, do not include the #.

Generally if you're not generating the tag/element with d3 or js, I'd personally attach the click listener with onclick attribute straight inside html instead of d3.on.

$(document).ready(function() {
  $("#input").attr("value", 0);
});

const margin = {
    top: 10,
    right: 30,
    bottom: 70,
    left: 65
  },
  width = 520,
  height = 480;

function SVGmaker(target) {
  const svg = d3.selectAll(target)
    .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")

  svg.append("rect")
    .attr("x", 0)
    .attr("y", 0)
    .attr("height", height)
    .attr("width", width)
    .attr("fill", "white")

  return svg;
}

const svgOne = SVGmaker("#svg");

const data = [{
    x: "1",
    y: "5",
    type: "A"
  },
  {
    x: "2",
    y: "4",
    type: "B"
  },
  {
    x: "3",
    y: "3",
    type: "B"
  },
  {
    x: "4",
    y: "2",
    type: "A"
  },
  {
    x: "5",
    y: "1",
    type: "A"
  }
]

let x = d3.scaleLinear()
  .domain([1, 5])
  .range([0, width]);

// DC SVG Settings
const xAxis = d3.axisBottom(x);

svgOne.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis)

const yAxis = d3.scaleLinear()
  .domain([0, 6])
  .range([height, 0])
svgOne.append("g")
  .call(d3.axisLeft(yAxis));

const colors = d3.scaleOrdinal()
  .domain(["A", "B"])
  .range(["red", "blue"]);

function updateData(data, type, theSVG, xAxis, yAxis, colors, value) {

  // Filters through the data

  var min = d3.min(data, function(d) {
    return d.x;
  });

  const changeData = data
    .filter(function(d) {
      if (value >= min) {
        return d.x == value;
      } else {
        return true;
      }
    })
    .filter(function(d) {
      if (type === "A") {
        return d.type === "A"
      } else if (type === "B") {
        return d.type === "B"
      } else {
        return true;
      }
    });
  const gra = theSVG
    .selectAll("circle")
    .data(changeData);

  gra.enter()
    .append("circle")
    .attr("r", 11)
    .style("fill", function(d) {
      return colors(d.type)
    })
    .merge(gra)
    .attr("cx", function(d) {
      return xAxis(d.x);
    })
    .attr("cy", function(d) {
      return yAxis(d.y);
    })
    .style("fill", function(d) {
      return colors(d.type)
    })

  gra.exit()
    .remove();

}

updateData(data, "", svgOne, x, yAxis, colors, 0);

d3.select("#submit")
  .on("click", function() {
    var value = document.getElementById("input").value;
    updateData(data, "", svgOne, x, yAxis, colors, value);
   });

d3.select("#a")
  .on("click", function() {
    updateData(data, "A", svgOne, x, yAxis, colors, 0);
  });

d3.select("#b")
  .on("click", function() {
    updateData(data, "B", svgOne, x, yAxis, colors, 0);
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<!DOCTYPE html>

<div id="svg"></div>
<button id="a">a</button>
<button id="b">b</button>
<input type="number" id="input" value=0>
<button id="submit">submit</button>

<script type="text/javascript" src="scripts.js"></script></code>```

Title: Filtering data based on input D3

Body:
I'm trying to filter down data to one value based on input. If the user enters a value, I want it to be able to display only that value on the graph. However, it's not working. I believe the code is in all the right places, just the logic isn't there.

If I remove the functionallity that attempts this, everything is fine - meaning that if I click on A, only data with type A is returned, and the same with B. But this doesn't work when I implement my code that tries to fitler down to one value.

Question:

How can I filter down to one value along the x axis based on user input, but still retain the funcationality that allows the user to switch between data types.

$(document).ready(function() {
  $("#input").attr("value", 0);
});

const margin = {
    top: 10,
    right: 30,
    bottom: 70,
    left: 65
  },
  width = 520,
  height = 480;

function SVGmaker(target) {
  const svg = d3.selectAll(target)
    .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")

  svg.append("rect")
    .attr("x", 0)
    .attr("y", 0)
    .attr("height", height)
    .attr("width", width)
    .attr("fill", "white")

  return svg;
}

const svgOne = SVGmaker("#svg");

const data = [{
    x: "1",
    y: "5",
    type: "A"
  },
  {
    x: "2",
    y: "4",
    type: "B"
  },
  {
    x: "3",
    y: "3",
    type: "B"
  },
  {
    x: "4",
    y: "2",
    type: "A"
  },
  {
    x: "5",
    y: "1",
    type: "A"
  }
]

let x = d3.scaleLinear()
  .domain([1, 5])
  .range([0, width]);

// DC SVG Settings
const xAxis = d3.axisBottom(x);

svgOne.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis)

const yAxis = d3.scaleLinear()
  .domain([0, 6])
  .range([height, 0])
svgOne.append("g")
  .call(d3.axisLeft(yAxis));

const colors = d3.scaleOrdinal()
  .domain(["A", "B"])
  .range(["red", "blue"]);

function updateData(data, type, theSVG, xAxis, yAxis, colors, value) {

  // Filters through the data
  const changeData = data.filter(function(d) {
    if (type === "A") {
      return d.type === "A"
    } else if (type === "B") {
      return d.type === "B"
    } else {
      return true;
    }
  });

  var min = d3.min(data, function(d) {
    return d.x;
  });

  const gra = theSVG
    .selectAll("circle")
    .data(changeData);

  gra.enter()
    .append("circle")
    .filter(function(d) {
      if (value <= min) {
        return d.x
      } else {
        return d.x >= value && d.x <= value
      }
    })
    .attr("cx", function(d) {
      return xAxis(d.x);
    })
    .attr("cy", function(d) {
      return yAxis(d.y);
    })
    .style("fill", function(d) {
      return colors(d.type)
    })
    .merge(gra)
    .attr("r", 11)
    .filter(function(d) {
      if (value <= min) {
        return d.x
      } else {
        return d.x >= value && d.x <= value
      }
    })
    .attr("cx", function(d) {
      return xAxis(d.x);
    })
    .attr("cy", function(d) {
      return yAxis(d.y);
    })
    .style("fill", function(d) {
      return colors(d.type)
    })

  gra.exit()
    .remove();

}

updateData(data, "", svgOne, x, yAxis, colors, 0);

let value;

function getMessage() {
  value = document.getElementById("#input").value;
}

d3.select("#a")
  .on("click", function() {
    updateData(data, "A", svgOne, x, yAxis, colors, value);
  });

d3.select("#b")
  .on("click", function() {
    updateData(data, "B", svgOne, x, yAxis, colors, value);
  });

<!DOCTYPE html>

<button id="a">a</button>
<button id="b">b</button>
<input type="number" id="input" value=0>
<button id="submit">submit</button>

Body:
I was a bit guessing what you want to do, but really the problem was that you never set'value' variable, and thus you were always passing undefined.

When you call getElementById, do not include the #.

Generally if you're not generating the tag/element with d3 or js, I'd personally attach the click listener with onclick attribute straight inside html instead of d3.on.

$(document).ready(function() {
  $("#input").attr("value", 0);
});

const margin = {
    top: 10,
    right: 30,
    bottom: 70,
    left: 65
  },
  width = 520,
  height = 480;

function SVGmaker(target) {
  const svg = d3.selectAll(target)
    .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")

  svg.append("rect")
    .attr("x", 0)
    .attr("y", 0)
    .attr("height", height)
    .attr("width", width)
    .attr("fill", "white")

  return svg;
}

const svgOne = SVGmaker("#svg");

const data = [{
    x: "1",
    y: "5",
    type: "A"
  },
  {
    x: "2",
    y: "4",
    type: "B"
  },
  {
    x: "3",
    y: "3",
    type: "B"
  },
  {
    x: "4",
    y: "2",
    type: "A"
  },
  {
    x: "5",
    y: "1",
    type: "A"
  }
]

let x = d3.scaleLinear()
  .domain([1, 5])
  .range([0, width]);

// DC SVG Settings
const xAxis = d3.axisBottom(x);

svgOne.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis)

const yAxis = d3.scaleLinear()
  .domain([0, 6])
  .range([height, 0])
svgOne.append("g")
  .call(d3.axisLeft(yAxis));

const colors = d3.scaleOrdinal()
  .domain(["A", "B"])
  .range(["red", "blue"]);

function updateData(data, type, theSVG, xAxis, yAxis, colors, value) {

  // Filters through the data

  var min = d3.min(data, function(d) {
    return d.x;
  });

  const changeData = data
    .filter(function(d) {
      if (value >= min) {
        return d.x == value;
      } else {
        return true;
      }
    })
    .filter(function(d) {
      if (type === "A") {
        return d.type === "A"
      } else if (type === "B") {
        return d.type === "B"
      } else {
        return true;
      }
    });
  const gra = theSVG
    .selectAll("circle")
    .data(changeData);

  gra.enter()
    .append("circle")
    .attr("r", 11)
    .style("fill", function(d) {
      return colors(d.type)
    })
    .merge(gra)
    .attr("cx", function(d) {
      return xAxis(d.x);
    })
    .attr("cy", function(d) {
      return yAxis(d.y);
    })
    .style("fill", function(d) {
      return colors(d.type)
    })

  gra.exit()
    .remove();

}

updateData(data, "", svgOne, x, yAxis, colors, 0);

d3.select("#submit")
  .on("click", function() {
    var value = document.getElementById("input").value;
    updateData(data, "", svgOne, x, yAxis, colors, value);
   });

d3.select("#a")
  .on("click", function() {
    updateData(data, "A", svgOne, x, yAxis, colors, 0);
  });

d3.select("#b")
  .on("click", function() {
    updateData(data, "B", svgOne, x, yAxis, colors, 0);
  });

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<!DOCTYPE html>

<div id="svg"></div>
<button id="a">a</button>
<button id="b">b</button>
<input type="number" id="input" value=0>
<button id="submit">submit</button>

<script type="text/javascript" src="scripts.js"></script>


问:
Can I import data from On-Premises SQL Server Database to Azure Machine Learning virtual machine?
On the limited Azure Machine Learning Studio, one can import data from an On-Premises SQL Server Database.
What about the ability to do the exact same thing on a python jupyter notebook on a virtual machine from the Azure Machine Learning Services workspace ?

It does not seem possible from what I've found in the documentation.
Data sources would be limited in Azure ML Services : "Currently, the list of supported Azure storage services that can be registered as datastores are Azure Blob Container, Azure File Share, Azure Data Lake, Azure Data Lake Gen2, Azure SQL Database, Azure PostgreSQL, and Databricks File System"

Thank you in advance for your assistance

答: You can always push the data to a supported source using a data movement/orchestration service.  Remember that all Azure services are not going to have every source option like Power BI, Logic Apps or Data Factory...this is why data orchestration/movement services exist.</p>


问:
Why do I get error 'iCloud Keychain is disabled'?
I implement Firebase Auth in Xcode , when I try app and register
error message has been shown "iCloud Keychain is disabled"

how I can solve it please ?

2019-05-27 13:22:01.286422+0300 OPTION 1[1629:161800] [AutoFill]
  Cannot show Automatic Strong Passwords for app bundleID:
  com.qaysi.OPTION1 due to error: iCloud Keychain is disabled

答:
Try this:

Enable iCloud Keychain on iPhone and iPad:

Launch the Settings app on your iPhone or iPad.

Tap your Apple ID banner.

Tap iCloud.

Scroll down and tap Keychain.

Toggle the iCloud Keychain switch on.

Enter your Apple ID password if prompted.

Now in your project, enable Keychain sharing for the target that you are working on. In your Xcode:

Open project setting.

Open capabilities tab.

Enable keychain sharing.


问:
How to convert words into numbers in java using icu4j
I want to parse words into numbers and have an error when the string doesn't fully express a real number, for example:

```<code>"Twenty two" => 22
"One hundred forty four" => 144
"Twenty bla bla" => error
"One hundred forty thousand one" => error
</code>```

I tried to use com.ibm.icu.text.RuleBasedNumberFormat but the parse() method is parsing only the beginning and not the full string.
This is mentioned in their javadoc:
 Parses text from the beginning of the given string to produce a number. The method might not use the entire text of the given string

In their javadoc it is mentioned that a special rule set can be used, in combination with RuleBasedCollator for changing the lenient parsing, but I'm struggling to achieve this.

```<code>public class NumFormatter {
    public static int numberFromString(String number, Locale locale) {
        RuleBasedNumberFormat numberFormat = new RuleBasedNumberFormat(locale, RuleBasedNumberFormat.SPELLOUT);

        try {
            return numberFormat.parse(number).intValue();
        } catch (ParseException e) {
            return -1;
        }
    }
}

public class NumFormatterTest
    @Test
    public void formatNumber_fromString() {
        Locale locale =  new Locale("en");
        assertEquals(numberFromString("twenty two", locale), 22);
        assertEquals(numberFromString("three blablabla ", locale), -1); // not ok. It return 3 and not -1.
    }
}

pom.xml
<dependency>
    <groupId>com.ibm.icu</groupId>
    <artifactId>icu4j</artifactId>
    <version>60.2</version>
</dependency>
</code>```

Did anyone had to deal with this before?
Thank you in advance.

Links

http://icu-project.org/apiref/icu4j/com/ibm/icu/text/RuleBasedNumberFormat.html

How to convert number to words in java

Using StringTokenizer in Coverting words to number

答:
The content of the document is as follows:

```<code>To see how these rules actually work in practice, consider the following example: Formatting 25,430 with this rule set would work like this:

<< thousand >>  [the rule whose base value is 1,000 is applicable to 25,340]
twenty->> thousand >>   [25,340 over 1,000 is 25. The rule for 20 applies.]
twenty-five thousand >> [25 mod 10 is 5. The rule for 5 is "five."
twenty-five thousand << hundred >>  [25,340 mod 1,000 is 340. The rule for 100 applies.]
twenty-five thousand three hundred >>   [340 over 100 is 3. The rule for 3 is "three."]
twenty-five thousand three hundred forty    [340 mod 100 is 40. The rule for 40 applies. Since 40 divides evenly by 10, the hyphen and substitution in the brackets are omitted.]

</code>```

public class NumberFormat {

    public static void main(String[] args) {
        Locale locale = new Locale("en");
        int twenty = numberFromString("twenty-two", locale);
        System.out.println(twenty);
    }

    public static int numberFromString(String number, Locale locale) {
        RuleBasedNumberFormat numberFormat = new RuleBasedNumberFormat(locale, RuleBasedNumberFormat.SPELLOUT);

        try {
            return numberFormat.parse(number).intValue();
        } catch (ParseException e) {
            return -1;
        }
    }
}
```

You need to replace the Spaces with -

Body:
I want to parse words into numbers and have an error when the string doesn't fully express a real number, for example:

"Twenty two" => 22
"One hundred forty four" => 144
"Twenty bla bla" => error
"One hundred forty thousand one" => error

I tried to use com.ibm.icu.text.RuleBasedNumberFormat but the parse() method is parsing only the beginning and not the full string.
This is mentioned in their javadoc:
 Parses text from the beginning of the given string to produce a number. The method might not use the entire text of the given string

In their javadoc it is mentioned that a special rule set can be used, in combination with RuleBasedCollator for changing the lenient parsing, but I'm struggling to achieve this.

public class NumFormatter {
    public static int numberFromString(String number, Locale locale) {
        RuleBasedNumberFormat numberFormat = new RuleBasedNumberFormat(locale, RuleBasedNumberFormat.SPELLOUT);

        try {
            return numberFormat.parse(number).intValue();
        } catch (ParseException e) {
            return -1;
        }
    }
}

public class NumFormatterTest
    @Test
    public void formatNumber_fromString() {
        Locale locale =  new Locale("en");
        assertEquals(numberFromString("twenty two", locale), 22);
        assertEquals(numberFromString("three blablabla ", locale), -1); // not ok. It return 3 and not -1.
    }
}

pom.xml
<dependency>
    <groupId>com.ibm.icu</groupId>
    <artifactId>icu4j</artifactId>
    <version>60.2</version>
</dependency>

Did anyone had to deal with this before?
Thank you in advance.

Links

http://icu-project.org/apiref/icu4j/com/ibm/icu/text/RuleBasedNumberFormat.html

How to convert number to words in java

Using StringTokenizer in Coverting words to number

Body:
The content of the document is as follows:

To see how these rules actually work in practice, consider the following example: Formatting 25,430 with this rule set would work like this:

<< thousand >>  [the rule whose base value is 1,000 is applicable to 25,340]
twenty->> thousand >>   [25,340 over 1,000 is 25. The rule for 20 applies.]
twenty-five thousand >> [25 mod 10 is 5. The rule for 5 is "five."
twenty-five thousand << hundred >>  [25,340 mod 1,000 is 340. The rule for 100 applies.]
twenty-five thousand three hundred >>   [340 over 100 is 3. The rule for 3 is "three."]
twenty-five thousand three hundred forty    [340 mod 100 is 40. The rule for 40 applies. Since 40 divides evenly by 10, the hyphen and substitution in the brackets are omitted.]

public class NumberFormat {

    public static void main(String[] args) {
        Locale locale = new Locale("en");
        int twenty = numberFromString("twenty-two", locale);
        System.out.println(twenty);
    }

    public static int numberFromString(String number, Locale locale) {
        RuleBasedNumberFormat numberFormat = new RuleBasedNumberFormat(locale, RuleBasedNumberFormat.SPELLOUT);

        try {
            return numberFormat.parse(number).intValue();
        } catch (ParseException e) {
            return -1;
        }
    }
}

You need to replace the Spaces with -


问:
JAVA AES ECB Encryption to Golang migration
I try to port a Java implementation of AES decryption to Golang. I need to decrypt data that is previously encrypted by the JAVA code using Golang. But so far I have no luck decrypting it.

The Java code is:

```<code>private static byte[] pad(final String password) {
    String key;
    for (key = password; key.length() < 16; key = String.valueOf(key) + key) {}
    return key.substring(0, 16).getBytes();
}

public static String encrypt(String password, String message) throws Exception
{
  SecretKeySpec skeySpec = new SecretKeySpec(pad(password), "AES");
  Cipher cipher = Cipher.getInstance("AES");
  cipher.init(1, skeySpec);

  byte[] encrypted = cipher.doFinal(message.getBytes());
  return Hex.encodeHexString(encrypted);
}

public static String decrypt(String password, String message)
throws Exception {

  SecretKeySpec skeySpec = new SecretKeySpec(pad(password), "AES");

  Cipher cipher = Cipher.getInstance("AES");
  cipher.init(1, skeySpec);

  cipher.init(2, skeySpec);
  byte[] original = cipher.doFinal(Hex.decodeHex(message.toCharArray()));
  return new String(original);
}
</code>```

I tried implementations like Cryptography GIST or

```<code>func decrypt(passphrase, data []byte) []byte {
  cipher, err := aes.NewCipher([]byte(passphrase))
  if err != nil {
    panic(err)
  }
  decrypted := make([]byte, len(data))
  size := 16

  for bs, be := 0, size; bs < len(data); bs, be = bs+size, be+size {
    cipher.Decrypt(decrypted[bs:be], data[bs:be])
  }

  return decrypted
}
hx, _ := hex.DecodeString(hexString)
res := decrypt([]byte(password), hx)
</code>```

No error is thrown, and a string is returned. But this string is not anywhere close to the encrypted data. Any help is very much appreciated! Thanks!

答:
Java adds a padding by default with the PKCS5 algorithm. In your Go code, you have to remove that padding with something like this (before returning the decrypted value):</p>

```<code>func pkcs5UnPadding(src []byte) []byte {
    length := len(src)
    if length%64 == 0 {
        return src
    }
    unpadding := int(src[length-1])
    return src[:(length - unpadding)]
}
</code>```

Body:
I try to port a Java implementation of AES decryption to Golang. I need to decrypt data that is previously encrypted by the JAVA code using Golang. But so far I have no luck decrypting it.

The Java code is:

private static byte[] pad(final String password) {
    String key;
    for (key = password; key.length() < 16; key = String.valueOf(key) + key) {}
    return key.substring(0, 16).getBytes();
}

public static String encrypt(String password, String message) throws Exception
{
  SecretKeySpec skeySpec = new SecretKeySpec(pad(password), "AES");
  Cipher cipher = Cipher.getInstance("AES");
  cipher.init(1, skeySpec);

  byte[] encrypted = cipher.doFinal(message.getBytes());
  return Hex.encodeHexString(encrypted);
}

public static String decrypt(String password, String message)
throws Exception {

  SecretKeySpec skeySpec = new SecretKeySpec(pad(password), "AES");

  Cipher cipher = Cipher.getInstance("AES");
  cipher.init(1, skeySpec);

  cipher.init(2, skeySpec);
  byte[] original = cipher.doFinal(Hex.decodeHex(message.toCharArray()));
  return new String(original);
}

I tried implementations like Cryptography GIST or

func decrypt(passphrase, data []byte) []byte {
  cipher, err := aes.NewCipher([]byte(passphrase))
  if err != nil {
    panic(err)
  }
  decrypted := make([]byte, len(data))
  size := 16

  for bs, be := 0, size; bs < len(data); bs, be = bs+size, be+size {
    cipher.Decrypt(decrypted[bs:be], data[bs:be])
  }

  return decrypted
}
hx, _ := hex.DecodeString(hexString)
res := decrypt([]byte(password), hx)

No error is thrown, and a string is returned. But this string is not anywhere close to the encrypted data. Any help is very much appreciated! Thanks!

Body:
Java adds a padding by default with the PKCS5 algorithm. In your Go code, you have to remove that padding with something like this (before returning the decrypted value):

func pkcs5UnPadding(src []byte) []byte {
    length := len(src)
    if length%64 == 0 {
        return src
    }
    unpadding := int(src[length-1])
    return src[:(length - unpadding)]
}


答:
You can use DateTime::format method

```<code>$date = new DateTime('2019-04-26 11:39:15');
$timeString = $date->format('H:i:s');
$dateString = $date->format('Y-m-d');
</code>```

Title: Splitting date and time then transfer them to their new respective columns

Body:
I have a website which have a date and time combined in the start of meeting and end of meeting.

Meeting_start
2019-04-26 11:39:15

I already created new columns for date and time. How can I split the existing date and time then transfer them to their new respective columns?

Ps. I'm looking for SQL codes.

Body:
You can use DateTime::format method

$date = new DateTime('2019-04-26 11:39:15');
$timeString = $date->format('H:i:s');
$dateString = $date->format('Y-m-d');


问:
SuiteScript 2.0 file.load method does not accept relative path of a .xml file
I have developed a Suitlet script that, in particular, loads an .xml file for further processing using the file.load method with an absolute path. I want to use a relative path, but when I do so, it won't work.

Basically, I'm providing the file.load method with the absolute path of an .xml file.

I expect the same behavior with a relative path provided instead, but it throws an error.

Both my Suitlet and .xml are in the same folder next to each other.

Forks fine:

```<code>var xmlTemplateFile = file.load({ id: 'SuiteScripts/printXml/template.xml' });
</code>```

Doesn't work:

```<code>var xmlTemplateFile = file.load({ id: 'template.xml' });
</code>```

Error message:

{"type":"error.SuiteScriptError","name":"RCRD_DSNT_EXIST","message":"That
  record does not exist. path: template.xml

I expect file.load, provided with a relative path, to load my .xml file seamlessly.

答: file.load() does not accept paths relative to the current file. Not much you can do about it other than submit a feature request to NetSuite.

Body:
I have developed a Suitlet script that, in particular, loads an .xml file for further processing using the file.load method with an absolute path. I want to use a relative path, but when I do so, it won't work.

Basically, I'm providing the file.load method with the absolute path of an .xml file.

I expect the same behavior with a relative path provided instead, but it throws an error.

Both my Suitlet and .xml are in the same folder next to each other.

Forks fine:

var xmlTemplateFile = file.load({ id: 'SuiteScripts/printXml/template.xml' });

Doesn't work:

var xmlTemplateFile = file.load({ id: 'template.xml' });

Error message:

{"type":"error.SuiteScriptError","name":"RCRD_DSNT_EXIST","message":"That
  record does not exist. path: template.xml

I expect file.load, provided with a relative path, to load my .xml file seamlessly.


问:
How do you detect where two line segments intersect?
How do I determine whether or not two lines intersect, and if they do, at what x,y point?</p>

答:
The problem reduces to this question: Do two lines from A to B and from C to D intersect?  Then you can ask it four times (between the line and each of the four sides of the rectangle).

Here's the vector math for doing it.  I'm assuming the line from A to B is the line in question and the line from C to D is one of the rectangle lines.  My notation is that Ax is the "x-coordinate of A" and Cy is the "y-coordinate of C."  And "*" means dot-product, so e.g. A*B = Ax*Bx + Ay*By.

```<code>E = B-A = ( Bx-Ax, By-Ay )
F = D-C = ( Dx-Cx, Dy-Cy )
P = ( -Ey, Ex )
h = ( (A-C) * P ) / ( F * P )
</code>```

This h number is the key.  If h is between 0 and 1, the lines intersect, otherwise they don't.  If F*P is zero, of course you cannot make the calculation, but in this case the lines are parallel and therefore only intersect in the obvious cases.

The exact point of intersection is C + F*h.

More Fun:

If h is exactly 0 or 1 the lines touch at an end-point.  You can consider this an "intersection" or not as you see fit.

Specifically, h is how much you have to multiply the length of the line in order to exactly touch the other line.

Therefore, If h<0, it means the rectangle line is "behind" the given line (with "direction" being "from A to B"), and if h>1 the rectangle line is "in front" of the given line.

Derivation:

A and C are vectors that point to the start of the line; E and F are the vectors from the ends of A and C that form the line.

For any two non-parallel lines in the plane, there must be exactly one pair of scalar g and h such that this equation holds:

```<code>A + E*g = C + F*h
</code>```

Why?  Because two non-parallel lines must intersect, which means you can scale both lines by some amount each and touch each other.

(At first this looks like a single equation with two unknowns!  But it isn't when you consider that this is a 2D vector equation, which means this is really a pair of equations in x and y.)

We have to eliminate one of these variables.  An easy way is to make the E term zero.  To do that, take the dot-product of both sides of the equation using a vector that will dot to zero with E.  That vector I called P above, and I did the obvious transformation of E.

You now have:

```<code>A*P = C*P + F*P*h
(A-C)*P = (F*P)*h
( (A-C)*P ) / (F*P) = h
</code>```

OwnerDisplayName: KingNestor

Body:
The problem reduces to this question: Do two lines from A to B and from C to D intersect?  Then you can ask it four times (between the line and each of the four sides of the rectangle).

Here's the vector math for doing it.  I'm assuming the line from A to B is the line in question and the line from C to D is one of the rectangle lines.  My notation is that Ax is the "x-coordinate of A" and Cy is the "y-coordinate of C."  And "*" means dot-product, so e.g. A*B = Ax*Bx + Ay*By.

E = B-A = ( Bx-Ax, By-Ay )
F = D-C = ( Dx-Cx, Dy-Cy )
P = ( -Ey, Ex )
h = ( (A-C) * P ) / ( F * P )

This h number is the key.  If h is between 0 and 1, the lines intersect, otherwise they don't.  If F*P is zero, of course you cannot make the calculation, but in this case the lines are parallel and therefore only intersect in the obvious cases.

The exact point of intersection is C + F*h.

More Fun:

If h is exactly 0 or 1 the lines touch at an end-point.  You can consider this an "intersection" or not as you see fit.

Specifically, h is how much you have to multiply the length of the line in order to exactly touch the other line.

Therefore, If h<0, it means the rectangle line is "behind" the given line (with "direction" being "from A to B"), and if h>1 the rectangle line is "in front" of the given line.

Derivation:

A and C are vectors that point to the start of the line; E and F are the vectors from the ends of A and C that form the line.

For any two non-parallel lines in the plane, there must be exactly one pair of scalar g and h such that this equation holds:

A + E*g = C + F*h

Why?  Because two non-parallel lines must intersect, which means you can scale both lines by some amount each and touch each other.

(At first this looks like a single equation with two unknowns!  But it isn't when you consider that this is a 2D vector equation, which means this is really a pair of equations in x and y.)

We have to eliminate one of these variables.  An easy way is to make the E term zero.  To do that, take the dot-product of both sides of the equation using a vector that will dot to zero with E.  That vector I called P above, and I did the obvious transformation of E.

You now have:

A*P = C*P + F*P*h
(A-C)*P = (F*P)*h
( (A-C)*P ) / (F*P) = h

OwnerDisplayName: Jason Cohen

LastEditorDisplayName: Jason Cohen


问:
window.open(url, name, features) under IE
This is regarding JavaScript method window.open(url, name, features).
If the url is relative or under the same domain of the current page, the parameter features will be ignored by IE.

Example: http://statcomp.ats.ucla.edu/WebTools/JavaTools/popup.htm.

This happens in IE8/9 at least.
Why? Is there any workaround?

Thanks a lot, Xiao

答:
In your second example, the browser does respect the size, but the other properties are ignored as they don't have any value.

Use a value of 1, 0, yes or no for the properties:

```<code>width=480,height=200,scrollbars=1,dependent=1,resizable=1
</code>```

Body:
In your second example, the browser does respect the size, but the other properties are ignored as they don't have any value.

Use a value of 1, 0, yes or no for the properties:

width=480,height=200,scrollbars=1,dependent=1,resizable=1


问:
method newInstance required: int,String[],String[],int found: int,String[],int
I am getting compiler error for my fragment newInstance, can anyone tell me what is wrong with my code?

When i remove the second array String everything works as expected, but passing another String Array is giving the error:

error: method newInstance in class LightFragment cannot be applied to given types;
required: int,String[],String[],int
found: int,String[],int
reason: actual and formal argument lists differ in length

Calling Fragment:

```<code>`return LightFragment.newInstance(position+1,devicesMacArray,devicesTypeArray, deviceCounter);`
</code>```

and in my Fragment class:

```<code>`public static LightFragment newInstance(int pageNumber, String[] deviceMac,String[] deviceType, int numOfDevices) {
    LightFragment fragment = new LightFragment();
    Bundle args = new Bundle();
    args.putInt("PageNumber", pageNumber);
    args.putInt("numberOfDevices", numOfDevices);
    args.putStringArray("deviceMacArray",deviceMac);
    //args.putStringArray("deviceTypeArray",deviceType);
    fragment.setArguments(args);
    return fragment;
}`
</code>```

I am passing two String Arrays, one has saved Mac addresses and the other the Type of the device.

later to use them within the fragment.

I am able to pass only one String array for some reason, the moment i add the second the compiler provide the error mentioned above.

答:
I found the reason,

Apparently i had a none used class that calls the same fragment but pass different arguments.

weirdly the android studio did not show an error on that class until i opened it.

Body:
I am getting compiler error for my fragment newInstance, can anyone tell me what is wrong with my code?

When i remove the second array String everything works as expected, but passing another String Array is giving the error:

error: method newInstance in class LightFragment cannot be applied to given types;
required: int,String[],String[],int
found: int,String[],int
reason: actual and formal argument lists differ in length

Calling Fragment:

`return LightFragment.newInstance(position+1,devicesMacArray,devicesTypeArray, deviceCounter);`

and in my Fragment class:

`public static LightFragment newInstance(int pageNumber, String[] deviceMac,String[] deviceType, int numOfDevices) {
    LightFragment fragment = new LightFragment();
    Bundle args = new Bundle();
    args.putInt("PageNumber", pageNumber);
    args.putInt("numberOfDevices", numOfDevices);
    args.putStringArray("deviceMacArray",deviceMac);
    //args.putStringArray("deviceTypeArray",deviceType);
    fragment.setArguments(args);
    return fragment;
}`

I am passing two String Arrays, one has saved Mac addresses and the other the Type of the device.

later to use them within the fragment.

I am able to pass only one String array for some reason, the moment i add the second the compiler provide the error mentioned above.


问:
WPF: Usercontrol datacontext binding does not reflect changes to ViewModel
I have a collection bound to Combobox and it's SelectedItem is bound to my viewmodel property SelectedItem.

```<code><ComboBox ItemsSource="{Binding itemSource}"
          SelectedItem="{Binding SelectedItem}"/>
</code>```

The class of SelectedItem is as follows:

```<code>public class SelectedItem
{
   public AnotherViewModel anotherViewModel {get;set;}
}
</code>```

I have used an Usercontrol like below:

```<code><local:usercontrol DataContext="{Binding SelectedItem.anotherViewModel}"/>
</code>```

I am trying to change the content of usercontrol on selection change of combobox in main view.

The changes to properties of anotherViewModel reflects to the view only first time.
On debugging the code, I found that properties of anotherViewModel contains new values but it doesn't reflect to view.

Any help would be appreciated.

Edit

```<code>Public class MainViewModel
{
   public string property1 {get;set;} //has propertychanged implemented
   public ObservableCollection<Item> Items {get;set;} //combobox itemsource
   public Item SelectedItem {get;set;}//combobox selecteditem
}

public class Item
{
  public AnotherViewModel anotherViewModel {get;set;}//has propertychanged implemented
}

public class AnotherViewModel
{
  public string property1 {get;set;} //has propertychanged implemented
  public string property2 {get;set;} //has propertychanged implemented
  public ObservableCollection<string> items {get;set;} //has propertychanged implemented
}

<Window>
  <Textbox Text="{Binding property1}"/>
   <ComboBox ItemsSource="{Binding Items}"
          SelectedItem="{Binding SelectedItem}"/>
  <local:usercontrol DataContext="{Binding SelectedItem.anotherViewModel}"/>
<Window>

<UserControl>
   <ListView ItemsSource="{Binding items}"/>
</UserControl>
</code>```

答:
You should not do a class SelectedItem encapsulating your AnotherViewModel class.

Rather, in the viewmodel that is the datacontext of your window you should have :

```<code>private AnotherViewModel _selectedItem;
public AnotherViewModel SelectedItem
    {
        get { return _selectedItem; }
        set { _selectedItem = value; OnPropertyChanged(nameof(SelectedItem)); }
    }
</code>```

After that, you edit your xaml so that your usercontrol binds to your viewmodel property SelectedItem :

```<code><local:usercontrol DataContext="{Binding SelectedItem}"/>
</code>```

EDIT:

The standard structure would be :

The file MainView.xaml having your <Combobox> and a xaml element <local:usercontrol>.

The MainViewModel.cs having multiple properties, but especially the property SelectedItem of type AnotherViewModel and raising PropertyChangedEvent in its setter.

The AnotherViewModel.cs being anything you want. The goal is of course that your usercontrol inner xaml is binding to the properties you defined in  AnotherViewModel class.

The usercontrol.xaml which is basically another view in which xaml elements are bound to AnotherViewModel properties.

And then you bind the Datacontext of your <local:usercontrol> to your MainViewModel SelectedItem property (as you did in your question).

Body:
I have a collection bound to Combobox and it's SelectedItem is bound to my viewmodel property SelectedItem.

<ComboBox ItemsSource="{Binding itemSource}"
          SelectedItem="{Binding SelectedItem}"/>

The class of SelectedItem is as follows:

public class SelectedItem
{
   public AnotherViewModel anotherViewModel {get;set;}
}

I have used an Usercontrol like below:

<local:usercontrol DataContext="{Binding SelectedItem.anotherViewModel}"/>

I am trying to change the content of usercontrol on selection change of combobox in main view.

The changes to properties of anotherViewModel reflects to the view only first time.
On debugging the code, I found that properties of anotherViewModel contains new values but it doesn't reflect to view.

Any help would be appreciated.

Edit

Public class MainViewModel
{
   public string property1 {get;set;} //has propertychanged implemented
   public ObservableCollection<Item> Items {get;set;} //combobox itemsource
   public Item SelectedItem {get;set;}//combobox selecteditem
}

public class Item
{
  public AnotherViewModel anotherViewModel {get;set;}//has propertychanged implemented
}

public class AnotherViewModel
{
  public string property1 {get;set;} //has propertychanged implemented
  public string property2 {get;set;} //has propertychanged implemented
  public ObservableCollection<string> items {get;set;} //has propertychanged implemented
}

<Window>
  <Textbox Text="{Binding property1}"/>
   <ComboBox ItemsSource="{Binding Items}"
          SelectedItem="{Binding SelectedItem}"/>
  <local:usercontrol DataContext="{Binding SelectedItem.anotherViewModel}"/>
<Window>

<UserControl>
   <ListView ItemsSource="{Binding items}"/>
</UserControl>

Body:
You should not do a class SelectedItem encapsulating your AnotherViewModel class.

Rather, in the viewmodel that is the datacontext of your window you should have :

private AnotherViewModel _selectedItem;
public AnotherViewModel SelectedItem
    {
        get { return _selectedItem; }
        set { _selectedItem = value; OnPropertyChanged(nameof(SelectedItem)); }
    }

After that, you edit your xaml so that your usercontrol binds to your viewmodel property SelectedItem :

<local:usercontrol DataContext="{Binding SelectedItem}"/>

EDIT:

The standard structure would be :

The file MainView.xaml having your <Combobox> and a xaml element <local:usercontrol>.

The MainViewModel.cs having multiple properties, but especially the property SelectedItem of type AnotherViewModel and raising PropertyChangedEvent in its setter.

The AnotherViewModel.cs being anything you want. The goal is of course that your usercontrol inner xaml is binding to the properties you defined in  AnotherViewModel class.

The usercontrol.xaml which is basically another view in which xaml elements are bound to AnotherViewModel properties.

And then you bind the Datacontext of your <local:usercontrol> to your MainViewModel SelectedItem property (as you did in your question).


问:
Message notifications produce "This content can't be displayed"
I'm sending messages into Slack via a web hook.  Message notifications using a single "text" JSON element produce the correct notification text with the Slack app for OS X and iOS.  The message text is also correct in the channel.  However, when using the new "blocks" method, the notification text becomes "This content can't be displayed".  The message does correctly show up in the channel.  It's just the notification that is not working.

According to https://api.slack.com/messaging/composing/layouts the text in the first block is used for the notification:

When you're using blocks in your message payload, the text field becomes a fallback message displayed in notifications.

Without using the blocks style, this works:

```<code>curl -s -k -X POST https://hooks.slack.com/services/${webhook} -H 'Content-type: application/json' --data @- << EOF
{
  "text": "${message}"
}
EOF
</code>```

If you generate a simple blocks style equivalent using the block builder app at https://api.slack.com/tools/block-kit-builder by clearing out any existing code and then adding a Section block you will have something like this:

```<code>[
    {
        "type": "section",
        "text": {
            "type": "plain_text",
            "text": "This is a plain text section block.",
            "emoji": true
        }
    }
]
</code>```

Now at the bottom of the page, enter your channel and click "Send to Slack".  The result is that the text arrives in the channel correctly, however the notification that pops up contains the text "This content can't be displayed".

At first I thought that my own block style code was incorrect, however, this code that is generated by the block kit builder app does not work either which leads me to believe there is a problem/bug with Slack itself.

Or is there something that I have overlooked?

Thank you

答:
There are multiple "text"properties in the message structure. I believe the doc is referring to the top-level one outside all blocks definitions.

Example:

```<code>{
  "channel": "C1H9RESGL",
  "text": "Text here for notifications",
  "blocks": [
    {
      "type": "section",
      "text": {
        "type": "mrkdwn",
        "text": "Danny Torrence left the following review for your property:"
      }
    }
  ]
}
</code>```

Body:
I'm sending messages into Slack via a web hook.  Message notifications using a single "text" JSON element produce the correct notification text with the Slack app for OS X and iOS.  The message text is also correct in the channel.  However, when using the new "blocks" method, the notification text becomes "This content can't be displayed".  The message does correctly show up in the channel.  It's just the notification that is not working.

According to https://api.slack.com/messaging/composing/layouts the text in the first block is used for the notification:

When you're using blocks in your message payload, the text field becomes a fallback message displayed in notifications.

Without using the blocks style, this works:

curl -s -k -X POST https://hooks.slack.com/services/${webhook} -H 'Content-type: application/json' --data @- << EOF
{
  "text": "${message}"
}
EOF

If you generate a simple blocks style equivalent using the block builder app at https://api.slack.com/tools/block-kit-builder by clearing out any existing code and then adding a Section block you will have something like this:

[
    {
        "type": "section",
        "text": {
            "type": "plain_text",
            "text": "This is a plain text section block.",
            "emoji": true
        }
    }
]

Now at the bottom of the page, enter your channel and click "Send to Slack".  The result is that the text arrives in the channel correctly, however the notification that pops up contains the text "This content can't be displayed".

At first I thought that my own block style code was incorrect, however, this code that is generated by the block kit builder app does not work either which leads me to believe there is a problem/bug with Slack itself.

Or is there something that I have overlooked?

Thank you

Body:
There are multiple "text"properties in the message structure. I believe the doc is referring to the top-level one outside all blocks definitions.

Example:

{
  "channel": "C1H9RESGL",
  "text": "Text here for notifications",
  "blocks": [
    {
      "type": "section",
      "text": {
        "type": "mrkdwn",
        "text": "Danny Torrence left the following review for your property:"
      }
    }
  ]
}


问:
Android problem with ArrayList of objects in SAX-parser
I'm trying to parse an XML page which is build like this: http://pastebin.com/t9cXdnGs.
I've implemented a basic SAX parser, following this tutorial: Anddev SAX tutorial.

It worked pretty well, except I'm only getting the values of the last tag. To solve this, I've implemented an ArrayList to add each object that's made per XML node. But now I'm getting some weird output. For each node he passes in the loop, he adds the same value again. So for node 1, I get the value once, for node 2, I get the value twice and so on... (example: value1, value2value2, value3value3value3)

I can't seem to figure out what's wrong...

Here's my full source code of the page: http://pastebin.com/bkyz0g1U

答:
You are re-using the same object over and over again, so you only ever add one object into your ArrayList.  Replace this line:

```<code>private Vacature vacature = new Vacature();
</code>```

with

```<code>private Vacature vacature;
</code>```

and add this line:

```<code>vacature = new Vacature();
</code>```

right after your declaration of the characters() method:

```<code>public void characters(char ch[], int start, int length) {
</code>```

I also suspect that getVacatures() should return the ArrayList arrayVaca.

Body:
You are re-using the same object over and over again, so you only ever add one object into your ArrayList.  Replace this line:

private Vacature vacature = new Vacature();

with

private Vacature vacature;

and add this line:

vacature = new Vacature();

right after your declaration of the characters() method:

public void characters(char ch[], int start, int length) {

I also suspect that getVacatures() should return the ArrayList arrayVaca.


问:
Display settings for TFS build agent session
We have some of our automated functional tests that require a particular screen resolution setting.

What is currently in place is that automatically, a script connects to the test server machine (running Windows Server 2008 R2 Standard 64 bit, in case it matters) via remote desktop, using the particular settings we need from an .rdp settings file.

Then the tests which are running automatically on a scheduled time on the machine seem to use these settings and everything works well.
(It seems Windows is using the display settings from the last successful remote connection session?)

Now we want to migrate the test schedule to an automated TFS 2018 build definition.

So a TFS test agent is installed on the server and run via TFS build.
But we dont get the right results because of wrong display settings.

Even if i manually connect to the server using rdp with right display settings, and then starting the TFS build, it doesn't work.

Somehow the TFS agent is running in a session that doesn't have (inherit?) the right display settings from the last rdp connection.

The user account is the same in every case.

How can I fix this?
How can I force a TFS agent to use specific display settings?

答:
From Microsoft Docs about Automated Testings in TFS/Azure DevOps:

Before running UI tests you mat need to adjust the screen resolution
  so that apps render correctly. For this, a screen resolution utility
  task is available from Marketplace. Use this task in your pipeline
  to set the test screen resolution to a value that is supported by the
  agent machine. By default, this utility sets the resolution to the
  optimal value supported by the agent machine.

If you encounter failures using the screen resolution task, ensure
  that the agent is configured to run with auto-logon enabled and that
  all remote desktop sessions are safely disconnected using the tscon
  command.

So download the task from the link above, and add the task to your pipeline before the UI tests task.


问:
How to capture multiline regex between two tags that are into different steps/array/place
I Use TCPDF for generate some complex PDF so the problem is inside a PDF not into a standard web page

I'm trying to get text between 2 tags including the two tags that are: [#SCHANGE#] and [#ECHANGE#].

I'm using this regex:

preg_match('/(?:\[#SCHANGE#\]((?:.*?\r?\n?)*)\[#ECHANGE#\])+/m', $textV, $StartEndChange);
```

<p><code>$textV</code> is a dynamic value that came from a foreach loop like:</p>

<pre class="lang-php prettyprint-override"><code>foreach($text as $textV){

    //some code here..

}
</code>```

and inside there can be different situations such as:

$text = array (
    "0" => "[#SCHANGE#] same text [#ECHANGE#]" //This is okay, regex works in this case
) ;
```

<p>But this regex is not working when in <code>$text</code> there is only one tag then i have this situation :</p>

<pre class="lang-php prettyprint-override"><code>$text = array (
    "0" => "[#SCHANGE#]same text",
    "1" => "some text",
    "2" => "some text",
    "3" => "some text",
    "4" => "some text",
    "5" => "some text",
    "6" => "some text",
    "7" => "some text [#ECHANGE#]"
) ;
</code>```

So: how i can get the text between 2 tags including the two tags if the tags are not in the same text?

I can't explode the array bacause all the text inside $text is formatted and can be print differently from the previous or next one

答:
Try this:

```<code>$re = '/(\[#SCHANGE#\](.+?)\[#ECHANGE#\])|(\[#SCHANGE#\](.+?$))|(^(.+?)\[#ECHANGE#\])/m';

$str = '[#SCHANGE#]same text
some text [#ECHANGE#]
[#SCHANGE#] same text [#ECHANGE#]';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

// Print the entire match result
var_dump($matches);
</code>```

RegEx

If this expression wasn't desired, it can be modified or changed in regex101.com.

Body:
I Use TCPDF for generate some complex PDF so the problem is inside a PDF not into a standard web page

I'm trying to get text between 2 tags including the two tags that are: [#SCHANGE#] and [#ECHANGE#].

I'm using this regex:

preg_match('/(?:\[#SCHANGE#\]((?:.*?\r?\n?)*)\[#ECHANGE#\])+/m', $textV, $StartEndChange);

$textV is a dynamic value that came from a foreach loop like:

foreach($text as $textV){

    //some code here..

}

and inside there can be different situations such as:

$text = array (
    "0" => "[#SCHANGE#] same text [#ECHANGE#]" //This is okay, regex works in this case
) ;

But this regex is not working when in $text there is only one tag then i have this situation :

$text = array (
    "0" => "[#SCHANGE#]same text",
    "1" => "some text",
    "2" => "some text",
    "3" => "some text",
    "4" => "some text",
    "5" => "some text",
    "6" => "some text",
    "7" => "some text [#ECHANGE#]"
) ;

So: how i can get the text between 2 tags including the two tags if the tags are not in the same text?

I can't explode the array bacause all the text inside $text is formatted and can be print differently from the previous or next one

Body:
Try this:

$re = '/(\[#SCHANGE#\](.+?)\[#ECHANGE#\])|(\[#SCHANGE#\](.+?$))|(^(.+?)\[#ECHANGE#\])/m';

$str = '[#SCHANGE#]same text
some text [#ECHANGE#]
[#SCHANGE#] same text [#ECHANGE#]';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

// Print the entire match result
var_dump($matches);

RegEx

If this expression wasn't desired, it can be modified or changed in regex101.com.


问:
FileWriter not writing to file with protocol in URL
I am using the code below to write to file.

```<code>FileWriter writer = new FileWriter(outputPath);
writer.append(prettyJson);
writer.flush();
writer.close();
</code>```

I notice that the content is not written to the file path starts with "file://". Any specific reason for this ?

答:
Simple. You have to stick to the documentation. And the documentation clearly specifies:
https://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter(java.io.File)

```<code>fileName - String The system-dependent filename.
</code>```

System-dependent means:

/path/to/file on Linux / Mac

C:\path\to\file on Windows

file:// is not a filename, but a URL, and most commonly used in browsers.

Body:
I am using the code below to write to file.

FileWriter writer = new FileWriter(outputPath);
writer.append(prettyJson);
writer.flush();
writer.close();

I notice that the content is not written to the file path starts with "file://". Any specific reason for this ?

Body:
Simple. You have to stick to the documentation. And the documentation clearly specifies:
https://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter(java.io.File)

fileName - String The system-dependent filename.

System-dependent means:

/path/to/file on Linux / Mac

C:\path\to\file on Windows

file:// is not a filename, but a URL, and most commonly used in browsers.


问:
jQuery show and enter div on hover
There are answers to the question how to show a div when hovering over another div, but in my example I need to hover over an anchor tag which shows a list of menu bar items and after that to go with the mouse over that list of menu bar items. After that, when I mouseout the entered list, the list should hide. The problem is when I hover out of the menu bar list, it does not disappear.

I tried to do it when hovering over js-expand to show js-am-content and when mouseout over menu-bar-item to hide the content if menu-bar-item is not hovered on, but the content does not hide.

This is my simplified HTML

```<code><div>
  <a class="expand js-expand fa fa-bars"></a>
  <div class="action-menu-content js-am-content">
    <a class="menu-bar-item"> SHOW </a>
    <a class="menu-bar-item"> EDIT </a>
    <a class="menu-bar-item"> COLLECTIVE </a>
    <a class="menu-bar-item"> PER ORDER </a>
    <a class="menu-bar-item"> CUSTOMS </a>
    <a class="menu-bar-item"> HISTORY </a>
  </div>
</div>
</code>```

and jQuery (coffee script)

```<code>$(document).on 'mouseover', '.js-expand', (event) =>
  $parent = $(event.currentTarget).parent()
  $parent.children(".js-am-content").slideToggle('fast')

$(document).on 'mouseout', '.menu-bar-item', (event) =>
  if !$('.menu-bar-item:hover')
    $('.js-am-content').fadeOut('fast')
</code>```

答:
If it's possible to add the event handler to the parent
 then try this.

```<code>$(".parentdiv").hover(
    function(event) {
      $(event.currentTarget).children(".js-am-content").fadeIn("fast");
    }, function(event) {
      $(event.currentTarget).children(".js-am-content").fadeOut("fast");
    }
  );
</code>```

If u can't add the handler to the parent let me know and I'll try something else.

PS: Sorry that this isn't coffee script.

Title: jQuery show and enter div on hover

Body:
There are answers to the question how to show a div when hovering over another div, but in my example I need to hover over an anchor tag which shows a list of menu bar items and after that to go with the mouse over that list of menu bar items. After that, when I mouseout the entered list, the list should hide. The problem is when I hover out of the menu bar list, it does not disappear.

I tried to do it when hovering over js-expand to show js-am-content and when mouseout over menu-bar-item to hide the content if menu-bar-item is not hovered on, but the content does not hide.

This is my simplified HTML

     SHOW
     EDIT
     COLLECTIVE
     PER ORDER
     CUSTOMS
     HISTORY

and jQuery (coffee script)

$(document).on 'mouseover', '.js-expand', (event) =>
  $parent = $(event.currentTarget).parent()
  $parent.children(".js-am-content").slideToggle('fast')

$(document).on 'mouseout', '.menu-bar-item', (event) =>
  if !$('.menu-bar-item:hover')
    $('.js-am-content').fadeOut('fast')

Body:
If it's possible to add the event handler to the parent <div> then try this.

$(".parentdiv").hover(
    function(event) {
      $(event.currentTarget).children(".js-am-content").fadeIn("fast");
    }, function(event) {
      $(event.currentTarget).children(".js-am-content").fadeOut("fast");
    }
  );

If u can't add the handler to the parent let me know and I'll try something else.

PS: Sorry that this isn't coffee script.