问:
How to create 10 UIButtons in round shape in a for loop
How to create a 10 rounded UIButtons in round shape with number text using for loop</p>

```<code> for(i=0;i<=10;i++) {
    j=j+10;

    UIButton *bt = [[UIButton alloc]initWithFrame:CGRectMake(10, j+10, 50, 50)];
    bt.backgroundColor = [UIColor redColor];

    bt.layer.cornerRadius = 0.5 * bt.frame.size.width;
    [bt setTitle:@"click" forState:UIControlStateNormal];
    [bt addTarget:nil action:@selector(clicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:bt];

}
</code>```

答:
You are seeing only "one" button that is elongated vertically, which makes you think you are only creating one button instead of 11?

The reason is the offset that you apply within your code:

```<code> j = j + 10;
</code>```

With the above, you are seeing 11 UIButtons overlapping each other, hence the illusion that there were only one button that is elongated vertically.

Try changing the amount of offset:

```<code>j = j + 50;
</code>```

You would see, then, 11 UIButtons on the screen vertically.

As an aside, if you meant to only create 10 buttons instead of 11, the condition should be changed to:

```<code>for(int i = 0; i < 10; i++) //instead of using <=
</code>```

And, don't forget to initialize j; or else you would see nothing:

```<code>int j = 0; //do this before you enter the loop
</code>```

You should have received a warning, too, had you not done so.

Result of having 10 UIButtons with the aforementioned modifications:

Body:
How to create a 10 rounded UIButtons in round shape with number text using for loop

 for(i=0;i<=10;i++) {
    j=j+10;

    UIButton *bt = [[UIButton alloc]initWithFrame:CGRectMake(10, j+10, 50, 50)];
    bt.backgroundColor = [UIColor redColor];

    bt.layer.cornerRadius = 0.5 * bt.frame.size.width;
    [bt setTitle:@"click" forState:UIControlStateNormal];
    [bt addTarget:nil action:@selector(clicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:bt];

}

Body:
You are seeing only "one" button that is elongated vertically, which makes you think you are only creating one button instead of 11?

The reason is the offset that you apply within your code:

 j = j + 10;

With the above, you are seeing 11 UIButtons overlapping each other, hence the illusion that there were only one button that is elongated vertically.

Try changing the amount of offset:

j = j + 50;

You would see, then, 11 UIButtons on the screen vertically.

As an aside, if you meant to only create 10 buttons instead of 11, the condition should be changed to:

for(int i = 0; i < 10; i++) //instead of using <=

And, don't forget to initialize j; or else you would see nothing:

int j = 0; //do this before you enter the loop

You should have received a warning, too, had you not done so.

Result of having 10 UIButtons with the aforementioned modifications:


来源: stackexchange

问:
Adding figures with gridspec
I am trying to create a plot similar to the one from
this question.

Why am I only getting two pannels, i.e. just gs2:

```<code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

def main():
   fig = plt.figure()
   gs1 = gridspec.GridSpec(1,4)
   gs2 = gridspec.GridSpec(2,4)

   for n in range(4):
      ax00 = plt.subplot(gs1[0,n])
      ax10 = plt.subplot(gs2[0,n])
      ax11 = plt.subplot(gs2[1,n])

      ax00.plot([0,0],[0,1*n],color='r')
      ax10.plot([0,1],[0,2*n],color='b')
      ax11.plot([0,1],[0,3*n],color='g')
   plt.show()

main()
</code>```

which gives me this:

In the end I'd like to have a figure like:

which I obtained using the the code at the end of the questions. However I'd like to have the movability of the plots, which gs2.update(hspace=0) gives (the reason why i tried using gridspec). I.e. I'd like to remove the space between the last and second row.

```<code>def whatIwant():
    f, axarr = plt.subplots(3,4)

    for i in range(4):
        axarr[0][i].plot([0,0],[0,1*i],color='r')
        axarr[1][i].plot([0,1],[0,2*i],color='b') #remove the space between those and be able to move the plots where I want
        axarr[2][i].plot([0,1],[0,3*i],color='g')
    plt.show()
</code>```

答:
This would indeed be one of the cases, where it makes sense to use a GridSpecFromSubplotSpec. That is, you'd create an overall GridSpec with one column and 2 rows (and a 1 to 2 height ratio). In the first row you'd put a GridSpecFromSubplotSpec with one row and 4 columns. In the second row you'd put one with two rows and 4 columns, additionally specifying an hspace=0.0 such that the two bottom rows do not have any spacing between them.

```<code>import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure()

gs = gridspec.GridSpec(2, 1, height_ratios=[1,2])
gs0 = gridspec.GridSpecFromSubplotSpec(1, 4, subplot_spec=gs[0], wspace=0.4)
gs1 = gridspec.GridSpecFromSubplotSpec(2, 4, subplot_spec=gs[1], hspace=0.0, wspace=0.4)

for n in range(4):
    ax00 = plt.subplot(gs0[0,n])
    ax10 = plt.subplot(gs1[0,n])
    ax11 = plt.subplot(gs1[1,n], sharex=ax10)
    plt.setp(ax10.get_xticklabels(), visible=False)
    ax00.plot([0,0],[0,1*n],color='r')
    ax10.plot([0,1],[0,2*n],color='b')
    ax11.plot([0,1],[0,3*n],color='g')
plt.show()
</code>```

The advantage of this solution as opposed to the one in the linked question's answer is that you do not overlapping GridSpecs and thus do not need to think about how they relate to each other.

In case you're still interested in why the code from the question did not work:

You would need to use two different GridSpecs with each having the total amount of rows (in this case 3); but then only populating the first row of the first GridSpec and the second two rows of the second GridSpec:

```<code>import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

def main():
    fig = plt.figure()
    gs1 = gridspec.GridSpec(3,4)
    gs2 = gridspec.GridSpec(3,4, hspace=0.0)

    for n in range(4):
        ax00 = plt.subplot(gs1[0,n])
        ax10 = plt.subplot(gs2[1,n])
        ax11 = plt.subplot(gs2[2,n])

        ax00.plot([0,0],[0,1*n],color='r')
        ax10.plot([0,1],[0,2*n],color='b')
        ax11.plot([0,1],[0,3*n],color='g')
    plt.show()

main()
</code>```

ContentLicense: CC BY-SA 3.0

Title: Adding figures with gridspec

Body:
I am trying to create a plot similar to the one from
this question.

Why am I only getting two pannels, i.e. just gs2:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

def main():
   fig = plt.figure()
   gs1 = gridspec.GridSpec(1,4)
   gs2 = gridspec.GridSpec(2,4)

   for n in range(4):
      ax00 = plt.subplot(gs1[0,n])
      ax10 = plt.subplot(gs2[0,n])
      ax11 = plt.subplot(gs2[1,n])

      ax00.plot([0,0],[0,1*n],color='r')
      ax10.plot([0,1],[0,2*n],color='b')
      ax11.plot([0,1],[0,3*n],color='g')
   plt.show()

main()

which gives me this:

In the end I'd like to have a figure like:

which I obtained using the the code at the end of the questions. However I'd like to have the movability of the plots, which gs2.update(hspace=0) gives (the reason why i tried using gridspec). I.e. I'd like to remove the space between the last and second row.

def whatIwant():
    f, axarr = plt.subplots(3,4)

    for i in range(4):
        axarr[0][i].plot([0,0],[0,1*i],color='r')
        axarr[1][i].plot([0,1],[0,2*i],color='b') #remove the space between those and be able to move the plots where I want
        axarr[2][i].plot([0,1],[0,3*i],color='g')
    plt.show()

Body:
This would indeed be one of the cases, where it makes sense to use a GridSpecFromSubplotSpec. That is, you'd create an overall GridSpec with one column and 2 rows (and a 1 to 2 height ratio). In the first row you'd put a GridSpecFromSubplotSpec with one row and 4 columns. In the second row you'd put one with two rows and 4 columns, additionally specifying an hspace=0.0 such that the two bottom rows do not have any spacing between them.

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure()

gs = gridspec.GridSpec(2, 1, height_ratios=[1,2])
gs0 = gridspec.GridSpecFromSubplotSpec(1, 4, subplot_spec=gs[0], wspace=0.4)
gs1 = gridspec.GridSpecFromSubplotSpec(2, 4, subplot_spec=gs[1], hspace=0.0, wspace=0.4)

for n in range(4):
    ax00 = plt.subplot(gs0[0,n])
    ax10 = plt.subplot(gs1[0,n])
    ax11 = plt.subplot(gs1[1,n], sharex=ax10)
    plt.setp(ax10.get_xticklabels(), visible=False)
    ax00.plot([0,0],[0,1*n],color='r')
    ax10.plot([0,1],[0,2*n],color='b')
    ax11.plot([0,1],[0,3*n],color='g')
plt.show()

The advantage of this solution as opposed to the one in the linked question's answer is that you do not overlapping GridSpecs and thus do not need to think about how they relate to each other.

In case you're still interested in why the code from the question did not work:

You would need to use two different GridSpecs with each having the total amount of rows (in this case 3); but then only populating the first row of the first GridSpec and the second two rows of the second GridSpec:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

def main():
    fig = plt.figure()
    gs1 = gridspec.GridSpec(3,4)
    gs2 = gridspec.GridSpec(3,4, hspace=0.0)

    for n in range(4):
        ax00 = plt.subplot(gs1[0,n])
        ax10 = plt.subplot(gs2[1,n])
        ax11 = plt.subplot(gs2[2,n])

        ax00.plot([0,0],[0,1*n],color='r')
        ax10.plot([0,1],[0,2*n],color='b')
        ax11.plot([0,1],[0,3*n],color='g')
    plt.show()

main()


问:
Accessing fields of JSON string in C#
I'm trying to access specific fields of a json string returned when I authenticate to an API. When I attempt to print or manipulate the string I receive

System.NullReferenceException: 'Object reference not set to an instance of an object.'

```<code>var response = client.GetAsync(fullUri).Result;
string content = await response.Content.ReadAsStringAsync();
Console.WriteLine("StatusCode : " + (int)response.StatusCode + " " + response.StatusCode.ToString());

var jo = JObject.Parse(content);
var token = jo["Result"]["Token"].ToString(); //error mentioned above received here
Console.WriteLine(token.ToString());          //error mentioned above also recieved here
Console.WriteLine(content);                   //error mentioned above received here too
</code>```

the string "content" holds the json looking like this:

```<code>{
    "Result":{
        "TenantId":"1",
        "Token":"38255507",
        "UserName":"kadmin",
        "RoleId":2,
        "ScopeId":"2",
        "AdminId":16596942,
        "MachineId":null,
        "MachineGroupName":null,
        "CultureInfo":"en-US",
        "TimePref":"Browser",
        "OffSetInMinutes":420,
        "Attributes":null
    },
    "ResponseCode":0,
    "Status":"OK",
    "Error":"None"
}
</code>```

I've tried applying many examples I've seen on stackoverflow but none seem to work

答:
The line should read </p>

```<code>var token = jo["Result"]["Token"].ToString();
</code>```

Title: Accessing fields of JSON string in C#

Body:
I'm trying to access specific fields of a json string returned when I authenticate to an API. When I attempt to print or manipulate the string I receive

System.NullReferenceException: 'Object reference not set to an instance of an object.'

var response = client.GetAsync(fullUri).Result;
string content = await response.Content.ReadAsStringAsync();
Console.WriteLine("StatusCode : " + (int)response.StatusCode + " " + response.StatusCode.ToString());

var jo = JObject.Parse(content);
var token = jo["Result"]["Token"].ToString(); //error mentioned above received here
Console.WriteLine(token.ToString());          //error mentioned above also recieved here
Console.WriteLine(content);                   //error mentioned above received here too

the string "content" holds the json looking like this:

{
    "Result":{
        "TenantId":"1",
        "Token":"38255507",
        "UserName":"kadmin",
        "RoleId":2,
        "ScopeId":"2",
        "AdminId":16596942,
        "MachineId":null,
        "MachineGroupName":null,
        "CultureInfo":"en-US",
        "TimePref":"Browser",
        "OffSetInMinutes":420,
        "Attributes":null
    },
    "ResponseCode":0,
    "Status":"OK",
    "Error":"None"
}

I've tried applying many examples I've seen on stackoverflow but none seem to work

Body:
The line should read

var token = jo["Result"]["Token"].ToString();


问:
how to 3-way outer product in numpy?
About the numpy.outer [link] .

Given two vectors, a = [a0, a1, ..., aM] and b = [b0, b1, ..., bN], the outer product will be M*N matrix.

But how to implement a 3-array outer product, which means : given
third vector c = [c0, c1, ..., cP], how to get the outer product
between the 3 numpy arrays.

and how to get n-way outer product for n-array in numpy, for the method of einsum, how to change 'i,j,k->ijk'  to process "n" .

答:
You can use numpy.ix_; it adds axes to its operands such that they form an open grid. Below the shapes of A,B,C are (2, 1, 1), (1, 3, 1) and (1, 1, 4), so just multiplying them together results in the outer product.

```<code>a = np.arange(1, 3)
b = np.arange(1, 4)
c = np.arange(1, 5)
A,B,C = np.ix_(a,b,c)
A*B*C
# array([[[ 1,  2,  3,  4],
#         [ 2,  4,  6,  8],
#         [ 3,  6,  9, 12]],
#
#        [[ 2,  4,  6,  8],
#         [ 4,  8, 12, 16],
#         [ 6, 12, 18, 24]]])
</code>```

Title: how to 3-way outer product in numpy?

Body:
You can use numpy.ix_; it adds axes to its operands such that they form an open grid. Below the shapes of A,B,C are (2, 1, 1), (1, 3, 1) and (1, 1, 4), so just multiplying them together results in the outer product.

a = np.arange(1, 3)
b = np.arange(1, 4)
c = np.arange(1, 5)
A,B,C = np.ix_(a,b,c)
A*B*C
# array([[[ 1,  2,  3,  4],
#         [ 2,  4,  6,  8],
#         [ 3,  6,  9, 12]],
#
#        [[ 2,  4,  6,  8],
#         [ 4,  8, 12, 16],
#         [ 6, 12, 18, 24]]])


问:
Manipulating random number arrays
The question: Given integer values of x and y generate 20 random values within [x, y] interval and put them in an array. Print the array. Determine the index of the largest even negative number in it (ranging from 0 to 19). Account for the possibility that there might be no such number in the array. Calculate the sum of all positive odd numbers. You are only allowed to go through the
array values once. You should define separate functions for generating random numbers and checking even and odd numbers.

What I have written:

```<code>    #include <stdio.h>

int random(int min, int max, int arr[]){
    int i, j = 1;
    for(i = 0; i<20; i++){
        arr[i] = min + rand() % (max+1 - min);}
    for(i = 0; i<20; i++){
        printf("%d. %d\n", j, arr[i]);
        j++;}
    return arr[20];}

int evenodd(int arr[], int size){
    int i, holder, sum, index = 1;
    holder = arr[i];
    for(i = 0; i<20; i++){
        if (holder>0){
            if (holder%2 == 0){
                sum = sum;}
            else{
                sum += i;}}
        else{
            sum = sum;}}
    printf("\nThe sum of all odd positive numbers is %d.", sum);
    for(i = 1; i<20; i++){
        int top = arr[0];
        if (arr[i]<0){
            if(arr[i]<top){
                top = arr[i];
                index = i;}
            else{
                top = top;}}
        else{
            top = top;}}
    printf("\nThe index of the largest negative number is %d", index);}

int main()
{
    int min, max;
    printf("Please input the minimum desired random number: ");
    scanf("%d", &min);
    printf("\nPlease input the maximum desired random number: ");
    scanf("%d", &max);
    int a[20];
    random(min, max, a);
    evenodd(a, 20);
}
</code>```

It prints out fine, but the sum of positive odd number is wrong, as well as the index of the largest negative number.

答:
Four things
1) You did not initialize your sum to zero for odd positive numbers. So you should do that.
2) In calculating the sum you should do sum+=sum[i] and not sum+=i;

3) You initialized your index to 1 and not 0 for index of the largest  negative number. If the first element is your smallest negative your answer should be zero. Right now for both first and second element you will give answer as 1. If you want a range from 1 to 20 you can output i+1 in the prints. I think you also have to do if(arr[i]>top) to find the largest negative integer assuming -10 is larger than -20 which is usually the case

4) Your implementation in three still wont account for the fact that no such number exists. What I recommend doing is initialize your top to largest negative integer. Range of values in C Int and Long 32 - 64 bits . And you can set your index to -1. Compare this to the entire array and if your index is -1 in the end. Then you print that no such element exists. You also have to check if the integer you are comparing is even. You can do the summing and the even negative integer in one loop as the two things are independent of each other

Title: Manipulating random number arrays

Body:
The question: Given integer values of x and y generate 20 random values within [x, y] interval and put them in an array. Print the array. Determine the index of the largest even negative number in it (ranging from 0 to 19). Account for the possibility that there might be no such number in the array. Calculate the sum of all positive odd numbers. You are only allowed to go through the
array values once. You should define separate functions for generating random numbers and checking even and odd numbers.

What I have written:

    #include <stdio.h>

int random(int min, int max, int arr[]){
    int i, j = 1;
    for(i = 0; i<20; i++){
        arr[i] = min + rand() % (max+1 - min);}
    for(i = 0; i<20; i++){
        printf("%d. %d\n", j, arr[i]);
        j++;}
    return arr[20];}

int evenodd(int arr[], int size){
    int i, holder, sum, index = 1;
    holder = arr[i];
    for(i = 0; i<20; i++){
        if (holder>0){
            if (holder%2 == 0){
                sum = sum;}
            else{
                sum += i;}}
        else{
            sum = sum;}}
    printf("\nThe sum of all odd positive numbers is %d.", sum);
    for(i = 1; i<20; i++){
        int top = arr[0];
        if (arr[i]<0){
            if(arr[i]<top){
                top = arr[i];
                index = i;}
            else{
                top = top;}}
        else{
            top = top;}}
    printf("\nThe index of the largest negative number is %d", index);}

int main()
{
    int min, max;
    printf("Please input the minimum desired random number: ");
    scanf("%d", &min);
    printf("\nPlease input the maximum desired random number: ");
    scanf("%d", &max);
    int a[20];
    random(min, max, a);
    evenodd(a, 20);
}

It prints out fine, but the sum of positive odd number is wrong, as well as the index of the largest negative number.


问:
How to remove line breaks and make single line text?
I have a log file where events are in multiple lines. In order to make event into single line, first I have to separate lines that contain date and lines from those that are without date. Now I am trying to write a logic to check a line and if it doesn't have date, merge it with prevLine.

How can I combine multiples lines into one using regular expression or any other module that helps to achieve this task?

ctrl.js

```<code>var regex = /\[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\w+\]/;
var prevLine;
var readStream = fs.createReadStream(dir + '/' + logFile,'utf8');
        readStream.pipe(split()).on('data', function (line) {
            if (regex.test(line)) {
                    console.log('Line with date:', line);
                    parseLog(line,prevLine);
                } else {
                    console.log('Line without date:', line);
                    line = prevLine + line;
                }
                function parseLog(line, prev) {
                    if (line.indexOf('|') === -1) line = prev + line;
                 }
          });
</code>```

fileData

```<code>[2017-03-23T18:13:16Z]|verbose|bmid: n/a|infra.topicWorkers|topology changed, emitting topology event { newTopology:
   [ '-0000001337',
     '-0000001338',
     '-0000001339',
     '-0000001340',
     '-0000001341',
     '-0000001342' ],
  oldTopology:
   [ '-0000001337',
     '-0000001338',
     '-0000001339',
     '-0000001340',
     '-0000001341' ],
  workerId: 6,
  pid: 30488 }
[2017-03-23T18:13:16Z]|verbose|bmid: n/a|infra.topicWorkers|topology changed, emitting topology event { newTopology:
   [ '-0000001337',
     '-0000001338',
     '-0000001339',
     '-0000001340',
     '-0000001341',
     '-0000001342' ],
  oldTopology: [],
  workerId: 4,
  pid: 30481 }
</code>```

答:
You can do something like this:

```<code>const split = require('split');
const regex = /\[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\w+\]/;
let items = [];
let item = [];
fs.createReadtStream(path.join(dir, logFile), 'utf8')
  .pipe(split()).on('data', (line) => {
    if (regex.test(line)) {
        item = [];
        items.push(item);
    }
    item.push(line);
});
let lines = items.map(item => item.join(' '));
lines.forEach(line => console.log(line));
</code>```

You can add a new line to an array every time there is a new line, but when there is a line with a date then you can put that array into another array and create a new array for those single lines. Then you can combine the elements within the inner arrays by joining them and you will have a large array of combined lines - the array called lines in that example.

Body:
I have a log file where events are in multiple lines. In order to make event into single line, first I have to separate lines that contain date and lines from those that are without date. Now I am trying to write a logic to check a line and if it doesn't have date, merge it with prevLine.

How can I combine multiples lines into one using regular expression or any other module that helps to achieve this task?

ctrl.js

var regex = /\[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\w+\]/;
var prevLine;
var readStream = fs.createReadStream(dir + '/' + logFile,'utf8');
        readStream.pipe(split()).on('data', function (line) {
            if (regex.test(line)) {
                    console.log('Line with date:', line);
                    parseLog(line,prevLine);
                } else {
                    console.log('Line without date:', line);
                    line = prevLine + line;
                }
                function parseLog(line, prev) {
                    if (line.indexOf('|') === -1) line = prev + line;
                 }
          });

fileData

[2017-03-23T18:13:16Z]|verbose|bmid: n/a|infra.topicWorkers|topology changed, emitting topology event { newTopology:
   [ '-0000001337',
     '-0000001338',
     '-0000001339',
     '-0000001340',
     '-0000001341',
     '-0000001342' ],
  oldTopology:
   [ '-0000001337',
     '-0000001338',
     '-0000001339',
     '-0000001340',
     '-0000001341' ],
  workerId: 6,
  pid: 30488 }
[2017-03-23T18:13:16Z]|verbose|bmid: n/a|infra.topicWorkers|topology changed, emitting topology event { newTopology:
   [ '-0000001337',
     '-0000001338',
     '-0000001339',
     '-0000001340',
     '-0000001341',
     '-0000001342' ],
  oldTopology: [],
  workerId: 4,
  pid: 30481 }

Body:
You can do something like this:

const split = require('split');
const regex = /\[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\w+\]/;
let items = [];
let item = [];
fs.createReadtStream(path.join(dir, logFile), 'utf8')
  .pipe(split()).on('data', (line) => {
    if (regex.test(line)) {
        item = [];
        items.push(item);
    }
    item.push(line);
});
let lines = items.map(item => item.join(' '));
lines.forEach(line => console.log(line));

You can add a new line to an array every time there is a new line, but when there is a line with a date then you can put that array into another array and create a new array for those single lines. Then you can combine the elements within the inner arrays by joining them and you will have a large array of combined lines - the array called lines in that example.


问:
How to Return last occurrence of value in Array using VB6
Hi need to return the index of the last occurrence of a value in an array.
I tried this but it won't work. What am I doing wrong?

NOT THE LAST INDEX.. I am looking for the last index of a specific value contained within an array. in this case, it should return 3 which would be the last index of the value "this"

in a zero based array this should return 3

```<code>  Dim ary() As Variant
  Dim  stg as string
  stg = "this,one,is,this,going,to,be,fun"
  ary = Split(stg, ",")

  MsgBox (ary.LastIndexOf(ary, "this"))
</code>```

答:
You can try this. I changed from Variant array to string, and made a FindLast function.</p>

```<code>Sub test()

  Dim ary() As String
  Dim stg As String
  Dim i As Integer

  stg = "this,one,is,this,going,to,be,fun"
  ary = Split(stg, ",")

  MsgBox FindLast(ary, "this")

End Sub

Private Function FindLast(ary() As String, value As String) As Integer

  For i = UBound(ary) To 0 Step -1
    If ary(i) = value Then
        FindLast = i
        Exit For
    End If
  Next

End Function
</code>```

Body:
Hi need to return the index of the last occurrence of a value in an array.
I tried this but it won't work. What am I doing wrong?

NOT THE LAST INDEX.. I am looking for the last index of a specific value contained within an array. in this case, it should return 3 which would be the last index of the value "this"

in a zero based array this should return 3

  Dim ary() As Variant
  Dim  stg as string
  stg = "this,one,is,this,going,to,be,fun"
  ary = Split(stg, ",")

  MsgBox (ary.LastIndexOf(ary, "this"))

Body:
You can try this. I changed from Variant array to string, and made a FindLast function.

Sub test()

  Dim ary() As String
  Dim stg As String
  Dim i As Integer

  stg = "this,one,is,this,going,to,be,fun"
  ary = Split(stg, ",")

  MsgBox FindLast(ary, "this")

End Sub

Private Function FindLast(ary() As String, value As String) As Integer

  For i = UBound(ary) To 0 Step -1
    If ary(i) = value Then
        FindLast = i
        Exit For
    End If
  Next

End Function


问:
NodeJS file shown as non-existent while path is correct
I am checking if file exists using the following:

```<code>var fs = require("fs");
console.log(process.cwd());

var file="C:\\Users\\Usr1\\Documents\\Node\\Test1\\input.txt";

if(!fs.existsSync(file)) {
    console.log("File not found");
}
</code>```

The path is correct and file does exist. If I output file, it also shows the correct path. I am new to NodeJS and can't figure out what is going on. Can anyone help?

答:
First.  From the fs.existsSync() man pages :

Using fs.exists() to check for the existence of a file before calling fs.open(), fs.readFile() or fs.writeFile() is not recommended. Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file does not exist.

So, if you were too rewrite your logic, taking the recommendation into account, and adding a bit of the path module logic that @Hogan suggested:

```<code>var fs = require("fs");
var path = require('path');

console.log(process.cwd()); // C:\Users\Usr1\Documents\Node\Test1

var file="C:\\Users\\Usr1\\Documents\\Node\\Test1\\input.txt";

fs.open(path.normalize(file), 'rx', function(err, fd){
   if (err) console.log(err); // consoling the actual error may help in troubleshooting what the issue is...

   // do something now...
});
</code>```

Body:
I am checking if file exists using the following:

var fs = require("fs");
console.log(process.cwd());

var file="C:\\Users\\Usr1\\Documents\\Node\\Test1\\input.txt";

if(!fs.existsSync(file)) {
    console.log("File not found");
}

The path is correct and file does exist. If I output file, it also shows the correct path. I am new to NodeJS and can't figure out what is going on. Can anyone help?

Body:
First.  From the fs.existsSync() man pages :

Using fs.exists() to check for the existence of a file before calling fs.open(), fs.readFile() or fs.writeFile() is not recommended. Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file does not exist.

So, if you were too rewrite your logic, taking the recommendation into account, and adding a bit of the path module logic that @Hogan suggested:

var fs = require("fs");
var path = require('path');

console.log(process.cwd()); // C:\Users\Usr1\Documents\Node\Test1

var file="C:\\Users\\Usr1\\Documents\\Node\\Test1\\input.txt";

fs.open(path.normalize(file), 'rx', function(err, fd){
   if (err) console.log(err); // consoling the actual error may help in troubleshooting what the issue is...

   // do something now...
});


问:
Wordpress - Only show tags under the current Category
Looking into showing tags on the Archieve.php file in Wordpress to only show tags that are under the current Category.

At the moment all I have been able to do is show all the tags instead of pick the ones under just the current category with the code below:

```<code><ul id="blog-tags">
<?php
$tags = get_tags();
if ( $tags ) {
foreach ( $tags as $tag ) {
    echo '<li>';

    if ( (int) $tag->term_id === get_queried_object_id() )
        echo "<b>$tag->name</b>";
    else
        printf(
            '<a href="%1$s">%2$s</a>',
            get_tag_link( $tag->term_id ),
            $tag->name
        );

    echo '</li>';
}
}
?>
</ul>
</code>```

Is it possible to manipulate my code above to do what I want? Or have I got to take a completely different approach.

答:
Not exactly sure this is what you want but basically just need to loop through all posts by category, then grab the tags for those posts.

You could try something like this to get all the tags for the current category. You would need to manipulate it a bit to spit it out formatted the way you want with certain HTML .

```<code><?php
$custom_query = new WP_Query(
array(
    'cat' => get_query_var('cat')
  )
);
if ($custom_query->have_posts()) :
while ($custom_query->have_posts()) : $custom_query->the_post();
    $posttags = get_the_tags();
    if ($posttags) {
        foreach($posttags as $tag) {
            $all_tags[] = $tag->term_id;
        }
    }
endwhile;
endif;

$tags_arr = array_unique($all_tags);
$tags_str = implode(",", $tags_arr);

$args = array(
'smallest'  => 12,
'largest'   => 12,
'unit'      => 'px',
'number'    => 0,
'format'    => 'list',
'include'   => $tags_str
);
wp_tag_cloud($args);
// or use  <?php $my_tags = wp_tag_cloud( 'format=array' ); ?> to have them in an array that you can format after
?>
</code>```

Body:
Looking into showing tags on the Archieve.php file in Wordpress to only show tags that are under the current Category.

At the moment all I have been able to do is show all the tags instead of pick the ones under just the current category with the code below:

<?php
$tags = get_tags();
if ( $tags ) {
foreach ( $tags as $tag ) {
    echo '
';

    if ( (int) $tag->term_id === get_queried_object_id() )
        echo "$tag->name";
    else
        printf(
            '%2$s',
            get_tag_link( $tag->term_id ),
            $tag->name
        );

    echo '
';
}
}
?>

Is it possible to manipulate my code above to do what I want? Or have I got to take a completely different approach.

Body:
Not exactly sure this is what you want but basically just need to loop through all posts by category, then grab the tags for those posts.

You could try something like this to get all the tags for the current category. You would need to manipulate it a bit to spit it out formatted the way you want with certain HTML .

<?php
$custom_query = new WP_Query(
array(
    'cat' => get_query_var('cat')
  )
);
if ($custom_query->have_posts()) :
while ($custom_query->have_posts()) : $custom_query->the_post();
    $posttags = get_the_tags();
    if ($posttags) {
        foreach($posttags as $tag) {
            $all_tags[] = $tag->term_id;
        }
    }
endwhile;
endif;

$tags_arr = array_unique($all_tags);
$tags_str = implode(",", $tags_arr);

$args = array(
'smallest'  => 12,
'largest'   => 12,
'unit'      => 'px',
'number'    => 0,
'format'    => 'list',
'include'   => $tags_str
);
wp_tag_cloud($args);
// or use  <?php $my_tags = wp_tag_cloud( 'format=array' ); ?> to have them in an array that you can format after
?>


问:
How do you set a active tag in wordpress that matches the post your on
I'm trying to set an active class on a tag list with the below code:

```<code>    <?php
        $categories = get_the_category();
        $category_id = $categories[0]->cat_ID;
        $args = array( 'category' => $category_id, 'post_type' =>  'post' );
        $postslist = get_posts($args);  ?>
        <div class="archieve__list">
            <ul class="row" data-equalizer data-equalize-on="medium">
                <?php foreach ($postslist as $post) :  setup_postdata($post); ?>
                    <?php the_tags( '
                            <li class="column small-12 medium-4 text-center float-left archieve__item"><span class="archieve__link" data-equalizer-watch>', '</span></li>
                    '); ?>
                <?php endforeach; ?>
            </ul>
        </div>
</code>```

I've looked into using get_tags() however this pulls back all of the tags where I only want it to pull back the tags of the current category. This code below does what I want, setting an active state on the tag in use but I again need it to just output the tags of that category:

```<code><ul id="blog-tags">
<?php
$tags = get_tags();
if ( $tags ) {
foreach ( $tags as $tag ) {
    echo '<li>';

    if ( (int) $tag->term_id === get_queried_object_id() )
        echo "<b>$tag->name</b>";
    else
        printf(
            '<a href="%1$s">%2$s</a>',
            get_tag_link( $tag->term_id ),
            $tag->name
        );

    echo '</li>';
}
}
?>
</ul>
</code>```

I really would like the latter option to work as it feels a lot cleaner than the first option.

答: I'm not sure if you actually mean "Tags of the current category" as Categories and Tags are both taxonomies. But if you want to pull the tags of the current post you can use wp_get_post_tags()</p>

Body:
I'm trying to set an active class on a tag list with the below code:

    <?php
        $categories = get_the_category();
        $category_id = $categories[0]->cat_ID;
        $args = array( 'category' => $category_id, 'post_type' =>  'post' );
        $postslist = get_posts($args);  ?>

                <?php foreach ($postslist as $post) :  setup_postdata($post); ?>
                    <?php the_tags( '

', '

                    '); ?>
                <?php endforeach; ?>

I've looked into using get_tags() however this pulls back all of the tags where I only want it to pull back the tags of the current category. This code below does what I want, setting an active state on the tag in use but I again need it to just output the tags of that category:

<?php
$tags = get_tags();
if ( $tags ) {
foreach ( $tags as $tag ) {
    echo '
';

    if ( (int) $tag->term_id === get_queried_object_id() )
        echo "$tag->name";
    else
        printf(
            '%2$s',
            get_tag_link( $tag->term_id ),
            $tag->name
        );

    echo '
';
}
}
?>

I really would like the latter option to work as it feels a lot cleaner than the first option.


问:
Seam Logger inside a Servlet?
Is there a way to use a Seam Logger inside of a standard Java Servlet?  I have one servlet that I use to serve up content, while the rest of my application is developed using Seam.  I'd like to be able to make use of Seam's built-in Log functionality in my servlet, the same way I do with the rest of my Seam-based classes.  In my Servlet constructor, I tried calling

```<code>Log logger = (Log)Component.getInstance(Log.class);
</code>```

...but I'm getting an exception.  Is there a better way to "inject" a Logger into the servlet?  Something I'm missing?  Thanks!!

答:
I didn't tested it, but you could try this :

```<code>Log mylog = Logging.getLogger(MyClass.class);
</code>```

That's what i use in my tests.

ContentLicense: CC BY-SA 2.5

Title: Seam Logger inside a Servlet?

Body:
Is there a way to use a Seam Logger inside of a standard Java Servlet?  I have one servlet that I use to serve up content, while the rest of my application is developed using Seam.  I'd like to be able to make use of Seam's built-in Log functionality in my servlet, the same way I do with the rest of my Seam-based classes.  In my Servlet constructor, I tried calling

Log logger = (Log)Component.getInstance(Log.class);

...but I'm getting an exception.  Is there a better way to "inject" a Logger into the servlet?  Something I'm missing?  Thanks!!

Body:
I didn't tested it, but you could try this :

Log mylog = Logging.getLogger(MyClass.class);

That's what i use in my tests.


问:
python string splitting with multiple splitting points
Ok so ill get straight to the point here is my code

```<code>def digestfragmentwithenzyme(seqs, enzymes):

fragment = []
for seq in seqs:
    for enzyme in enzymes:
        results = []
        prog = re.compile(enzyme[0])
        for dingen in prog.finditer(seq):
           results.append(dingen.start() + enzyme[1])
        results.reverse()
        #result = 0
        for result in results:
            fragment.append(seq[result:])
            seq = seq[:result]
        fragment.append(seq[:result])
fragment.reverse()
return fragment
</code>```

Input for this function is a list of multiple strings (seq) e.g. :

```<code>List = ["AATTCCGGTCGGGGCTCGGGGG","AAAGCAAAATCAAAAAAGCAAAAAATC"]
</code>```

And enzymes as input:

```<code>[["TC", 1],["GC",1]]
</code>```

(note: there can be multiple given but most of them are in this matter of letters with ATCG)

The function should return a list that, in this example, contain 2 lists:

```<code>Outputlist = [["AATT","CCGGT","CGGGG","CT","CGGGGG"],["AAAG","CAAAAT","CAAAAAAG","CAAAAAAT","C"]]
</code>```

Right now i am having troubles with splitting it twice and getting the right output.

Little bit more information about the function. It looks through the string (seq) for the recognizion point. in this case TC or GC and splits it on the 2nd index of enzymes. it should do that for both strings in the list with both enzymes.

答:
Throwing my hat in the ring here.

Using dict for patterns rather than list of lists.

Joining pattern as others have done to avoid fancy regexes.

.

```<code>import re

sequences = ["AATTCCGGTCGGGGCTCGGGGG","AAAGCAAAATCAAAAAAGCAAAAAATC"]
patterns = { 'TC': 1, 'GC': 1 }

def intervals(patterns, text):
  pattern = '|'.join(patterns.keys())
  start = 0
  for match in re.finditer(pattern, text):
    index = match.start() + patterns.get(match.group())
    yield text[start:index]
    start = index
  yield text[index:len(text)]

print [list(intervals(patterns, s)) for s in sequences]

# [['AATT', 'CCGGT', 'CGGGG', 'CT', 'CGGGGG'], ['AAAG', 'CAAAAT', 'CAAAAAAG', 'CAAAAAAT', 'C']]
</code>```

Body:
Ok so ill get straight to the point here is my code

def digestfragmentwithenzyme(seqs, enzymes):

fragment = []
for seq in seqs:
    for enzyme in enzymes:
        results = []
        prog = re.compile(enzyme[0])
        for dingen in prog.finditer(seq):
           results.append(dingen.start() + enzyme[1])
        results.reverse()
        #result = 0
        for result in results:
            fragment.append(seq[result:])
            seq = seq[:result]
        fragment.append(seq[:result])
fragment.reverse()
return fragment

Input for this function is a list of multiple strings (seq) e.g. :

List = ["AATTCCGGTCGGGGCTCGGGGG","AAAGCAAAATCAAAAAAGCAAAAAATC"]

And enzymes as input:

[["TC", 1],["GC",1]]

(note: there can be multiple given but most of them are in this matter of letters with ATCG)

The function should return a list that, in this example, contain 2 lists:

Outputlist = [["AATT","CCGGT","CGGGG","CT","CGGGGG"],["AAAG","CAAAAT","CAAAAAAG","CAAAAAAT","C"]]

Right now i am having troubles with splitting it twice and getting the right output.

Little bit more information about the function. It looks through the string (seq) for the recognizion point. in this case TC or GC and splits it on the 2nd index of enzymes. it should do that for both strings in the list with both enzymes.

Body:
Throwing my hat in the ring here.

Using dict for patterns rather than list of lists.

Joining pattern as others have done to avoid fancy regexes.

.

import re

sequences = ["AATTCCGGTCGGGGCTCGGGGG","AAAGCAAAATCAAAAAAGCAAAAAATC"]
patterns = { 'TC': 1, 'GC': 1 }

def intervals(patterns, text):
  pattern = '|'.join(patterns.keys())
  start = 0
  for match in re.finditer(pattern, text):
    index = match.start() + patterns.get(match.group())
    yield text[start:index]
    start = index
  yield text[index:len(text)]

print [list(intervals(patterns, s)) for s in sequences]

# [['AATT', 'CCGGT', 'CGGGG', 'CT', 'CGGGGG'], ['AAAG', 'CAAAAT', 'CAAAAAAG', 'CAAAAAAT', 'C']]


问:
Find out what is taking my memory in torch7
I have written a rather complex torch application and it works quite well, that is if it doesn't run out of memory. Now I have tried to see what sort of inputs or situations cause it too seemingly randomly run out of memory but so far I have had little to no success. So now I'm looking for a way to check which variables take how much (v)ram.

I can with a simple statement switch between running my code on caffe:cuda or caffe:cl which changes whatever or not my program runs in RAM or on the GPU, I imagine that such a switch will make validating my memory usage a lot easier.

I have already tried to use print(collectgarbage("count")*1024) to check how much memory is in usage at a given point in time however this does not clearly show me where the memory is being used, perhaps because the program is relatively complex (although there are a few variables which I suspect are hugging a lot of memory, neural networks, large matrices and such).

I already know that once I have identified who is hogging my memory I can assign a nill value to it and call the garbage collector too free it.

So in short is there a program or a tool that allows me to run a torch program and then list each variable and it's memory usage?

答:
I don't know if you tried google :)
But here you are:

Torch7-profiling

Neural Model profiler script

"How to Profile a Lua Script using Pepperfish"

Easy Lua Profiling

tbo, I've never had memory issues with Torch7 so it might be your implementation which is just not optimal. It might be a loop without collectgarbage call somewhere where it should be, e.g. in a training loop or between the epochs.


问:
connect to SQL hosted on a local machine from my laptop (using an IP)
I set up an SQL server on my Windows 7 PC.

I have a laptop, from which I want to connect to the SQL server (using visual studio 2010).
I need to fill in a "server name" when creating a database connection.

I tried "My.IP.Address/SQLEXPRESS,custom-port", but that doesn't work. All examples talk about using server names which are formatted like so "TOM-PC/SQLEXPRESS", but I have an important requirement:

I want to be able to connect from anywhere (not only when in the same local network), therefore I'm trying to use the IP address (the port isn't simply 1433 since my ISP blocks it).

The custom port is open, and reachable in tests.

I've been Googling this all day long, but can't find a solution. Please help!

Thank you,

Tom

答: should it not be My.IP.Address:custom-port/SQLEXPRESS ?</p>


问:
how can I loop and perform operations on columns of a pandas dataframe?
I've imported the fitter package which plots the top 5 plots for a distribution of a series

```<code>f=Fitter(df.distance)
f.fit()
f.summary()
</code>```

distance is one of the columns of my dataframe. how can I apply the fitter function to plot the graphs of each series?

答:
If I'm understanding correctly you want to apply Fitter to multiple columns in your df in a loop:

```<code>for col in df.columns:
    f=Fitter(df[col])
    f.fit()
    f.summary()
</code>```

Body:
I've imported the fitter package which plots the top 5 plots for a distribution of a series

f=Fitter(df.distance)
f.fit()
f.summary()

distance is one of the columns of my dataframe. how can I apply the fitter function to plot the graphs of each series?

Body:
If I'm understanding correctly you want to apply Fitter to multiple columns in your df in a loop:

for col in df.columns:
    f=Fitter(df[col])
    f.fit()
    f.summary()


问:
How do you deploy a basic HTML file to the root directory of an Azure Bot function app?
I created a Bot App Service in Azure from the LUIS template and configured continuous integration. The Bot Service is a function app, and works locally and within the web-windows in Azure and on dev.botframework.com.

My goal is to deploy a basic HTML page to the root directory BOT_NAME.azurewebsites.net of my app service.

Current attempts to solve:

I have configured Web Chat and have an I-Frame as such:

<iframe src='https://webchat.botframework.com/embed/<BOT_NAME>?s=<SECRET>'>

I have attempted to modify the run.csx file with the following:

```<code>var response = req.CreateResponse(HttpStatusCode.OK);
var stream = new FileStream(@"index.html", FileMode.Open);
response.Content = new StreamContent(stream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
return req.CreateResponse(HttpStatusCode.Accepted);
</code>```

This correctly displays index.html at localhost:3979/api/messages. When deployed to Azure, I attempted to fully qualify index.html as d:\home\site\wwwroot\index.html, yet <BOT_NAME>.azurewebsites.com/api/messages returns the following:

The HTTP 'GET' method is not supported by the 'GenericJsonWebHookReceiver' WebHook receiver

I have created a new function app (not bot app) in an effort to launch the base HTML file and utilize Azure's web-proxy feature to map the URL \wwwroot\index.html to \. This works, but it isolates the app into two repositories, and thus feels out of practice.

I have also attempted to modify function.json to include "authLevel": "anonymous" to no avail.

Please help! I would really appreciate it, as I'm unaware of the best practice to implement such a solution. Within Azure, all out-of-the-box Bot templates are function apps now, hence anyone wishing to launch an HTML bot page will likely need details. Thank you!

The example solution contains the following:

答:
You are right, the Bot Services UI does not expose the Azure Function Proxies section. However, you can still use it as Bot Service is still a Function App.

Here's what you can do.

Enable Function Proxies

To enable function proxies, Add the following to the App Settings of the Function App.

```<code>ROUTING_EXTENSION_VERSION ~0.2
</code>```

You can access the tab by Bot Service > Settings > Application settings > App settings

Add Index.html

Add the index.html with the iframe for the bot at the wwwroot/index.html

Add a New Function to expose index.html

Create a new HTTP Trigger function that reads index.html and returns it as a http response.
Directory structure

Function.json

```<code>{
 "bindings": [
    {
      "authLevel": "anonymous",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in"
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    }
  ],
  "disabled": false
}
</code>```

run.csx

```<code>using System.Net;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.IO;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    var response = new HttpResponseMessage(HttpStatusCode.OK);
    var stream = new FileStream(@"d:\home\site\wwwroot\index.html", FileMode.Open);
    response.Content = new StreamContent(stream);
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
    return response;
}
</code>```

Add proxies.json

Finally add a proxy to have the root of the function app point to the new function.

```<code>{
    "proxies":{
        "home":{
            "matchCondition": {
                "route": "/"
            },
            "backendUri": "https://<<FUNCTION_APP_NAME>>.azurewebsites.net/api/home"
        }
    }
}
</code>```

Note that I used App Service Editor to add the function app and proxies files. You can find it at Bot Service > Settings > Advanced Settings > Development Tools > App Service Editor.

Body:
I created a Bot App Service in Azure from the LUIS template and configured continuous integration. The Bot Service is a function app, and works locally and within the web-windows in Azure and on dev.botframework.com.

My goal is to deploy a basic HTML page to the root directory BOT_NAME.azurewebsites.net of my app service.

Current attempts to solve:

I have configured Web Chat and have an I-Frame as such:

<iframe src='https://webchat.botframework.com/embed/<BOT_NAME>?s=<SECRET>'>

I have attempted to modify the run.csx file with the following:

var response = req.CreateResponse(HttpStatusCode.OK);
var stream = new FileStream(@"index.html", FileMode.Open);
response.Content = new StreamContent(stream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
return req.CreateResponse(HttpStatusCode.Accepted);

This correctly displays index.html at localhost:3979/api/messages. When deployed to Azure, I attempted to fully qualify index.html as d:\home\site\wwwroot\index.html, yet <BOT_NAME>.azurewebsites.com/api/messages returns the following:

The HTTP 'GET' method is not supported by the 'GenericJsonWebHookReceiver' WebHook receiver

I have created a new function app (not bot app) in an effort to launch the base HTML file and utilize Azure's web-proxy feature to map the URL \wwwroot\index.html to \. This works, but it isolates the app into two repositories, and thus feels out of practice.

I have also attempted to modify function.json to include "authLevel": "anonymous" to no avail.

Please help! I would really appreciate it, as I'm unaware of the best practice to implement such a solution. Within Azure, all out-of-the-box Bot templates are function apps now, hence anyone wishing to launch an HTML bot page will likely need details. Thank you!

The example solution contains the following:

Body:
You are right, the Bot Services UI does not expose the Azure Function Proxies section. However, you can still use it as Bot Service is still a Function App.

Here's what you can do.

Enable Function Proxies

To enable function proxies, Add the following to the App Settings of the Function App.

ROUTING_EXTENSION_VERSION ~0.2

You can access the tab by Bot Service > Settings > Application settings > App settings

Add Index.html

Add the index.html with the iframe for the bot at the wwwroot/index.html

Add a New Function to expose index.html

Create a new HTTP Trigger function that reads index.html and returns it as a http response.
Directory structure

Function.json

{
 "bindings": [
    {
      "authLevel": "anonymous",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in"
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    }
  ],
  "disabled": false
}

run.csx

using System.Net;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.IO;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    var response = new HttpResponseMessage(HttpStatusCode.OK);
    var stream = new FileStream(@"d:\home\site\wwwroot\index.html", FileMode.Open);
    response.Content = new StreamContent(stream);
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
    return response;
}

Add proxies.json

Finally add a proxy to have the root of the function app point to the new function.

{
    "proxies":{
        "home":{
            "matchCondition": {
                "route": "/"
            },
            "backendUri": "https://<<FUNCTION_APP_NAME>>.azurewebsites.net/api/home"
        }
    }
}

Note that I used App Service Editor to add the function app and proxies files. You can find it at Bot Service > Settings > Advanced Settings > Development Tools > App Service Editor.


问:
Enable zooming/pinch on UIWebView
I have an UIWebView with a pdf-file. It works fine. But how can i enable zooming on the pdf-file? </p>

答:
If you want do by programmatically then use

```<code>webView.scalesPageToFit = true;
</code>```

If you are using storyboard then you have to tick check box "Scaling" scales Page to fit

Title: Enable zooming/pinch on UIWebView

Body:
If you want do by programmatically then use

webView.scalesPageToFit = true;

If you are using storyboard then you have to tick check box "Scaling" scales Page to fit


问:
Where is the chink in Google Chrome's armor?
While browsing with Chrome, I noticed that it responds extremely fast (in comparison with IE and Firefox on my laptop) in terms of rendering pages, including JavaScript heavy sites like gmail.

This is what googlebook on Chrome has to say

tabs are hosted in process rather than thread.

compile javascript using V8 engine as opposed to interpreting.

Introduce new virtual machine to support javascript heavy apps

introduce "hidden class transitions" and apply dynamic optimization to speed up things.

Replace inefficient "Conservative garbage colllection" scheme with more precise garbage  collection scheme.

Introduce their own task scheduler and memory manager to manage the browser environment.

All this sounds so familiar, and Microsoft has been doing such things for long time.. Windows os, C++, C# etc compilers, CLR, and so on.

So why isn't Microsoft or any other browser vendor taking Chrome's approach? Is there a flaw in Chrome's approach? If not, is the rest of browser vendor community caught unaware  with Google's approach?

答:
@pix0r but they added a little thing in the bottom right corner so you can expand the text box any direction you want, which I love because I use a wide display and prefer to type in a wider screen.

I also wanted to point out that Google completely built Chrome from the ground up, with the exception of using webkit, so they have some of the advantages of not having to not deal with old-code.  And of course there is the INSANLELY cool/smart developers.

OwnerDisplayName: kudlur

LastEditorDisplayName: Greg Hurlman

OwnerDisplayName: Unkwntech


问:
Approximating nonparametric cubic Bezier
What is the best way to approximate a cubic Bezier curve?  Ideally I would want a function y(x) which would give the exact y value for any given x, but this would involve solving a cubic equation for every x value, which is too slow for my needs, and there may be numerical stability issues as well with this approach.

Would this be a good solution?

答:
Just solve the cubic.

If you're talking about Bezier plane curves, where x(t) and y(t) are cubic polynomials, then y(x) might be undefined or have multiple values.  An extreme degenerate case would be the line x= 1.0, which can be expressed as a cubic Bezier (control point 2 is the same as end point 1; control point 3 is the same as end point 4).  In that case, y(x) has no solutions for x != 1.0, and infinite solutions for x == 1.0.

A method of recursive subdivision will work, but I would expect it to be much slower than just solving the cubic.  (Unless you're working with some sort of embedded processor with unusually poor floating-point capacity.)

You should have no trouble finding code that solves a cubic that has already been thoroughly tested and debuged.  If you implement your own solution using recursive subdivision, you won't have that advantage.

Finally, yes, there may be numerical stablility problems, like when the point you want is near a tangent, but a subdivision method won't make those go away.  It will just make them less obvious.

EDIT:  responding to your comment, but I need more than 300 characters.

I'm only dealing with bezier curves where y(x) has only one (real) root. Regarding numerical stability, using the formula from http://en.wikipedia.org/wiki/Cubic_equation#Summary, it would appear that there might be problems if u is very small. – jtxx000

The wackypedia article is math with no code.  I suspect you can find some cookbook code that's more ready-to-use somewhere.  Maybe Numerical Recipies or ACM collected algorithms link text.

To your specific question, and using the same notation as the article, u is only zero or near zero when p is also zero or near zero.  They're related by the equation:

    u^^6 + q u^^3 == p^^3 /27

Near zero, you can use the approximation:

    q u^^3 == p^^3 /27

or  p / 3u == cube root of q

So the computation of x from u should contain something like:

```<code>(fabs(u) >= somesmallvalue) ?  (p / u / 3.0) : cuberoot (q)
</code>```

How "near" zero is near?  Depends on how much accuracy you need.  You could spend some quality time with Maple or Matlab looking at how much error is introduced for what magnitudes of u.  Of course, only you know how much accuracy you need.

The article gives 3 formulas for u for the 3 roots of the cubic.  Given the three u values, you can get the 3 corresponding x values.  The 3 values for u and x are all complex numbers with an imaginary component.  If you're sure that there has to be only one real solution, then you expect one of the roots to have a zero imaginary component, and the other two to be complex conjugates.  It looks like you have to compute all three and then pick the real one.  (Note that a complex u can correspond to a real x!)  However, there's another numerical stability problem there:  floating-point arithmetic being what it is, the imaginary component of the real solution will not be exactly zero, and the imaginary components of the non-real roots can be arbitrarily close to zero.  So numeric round-off can result in you picking the wrong root.  It would be helpfull if there's some sanity check from your application that you could apply there.

If you do pick the right root, one or more iterations of Newton-Raphson can improve it's accuracy a lot.

Body:
Just solve the cubic.

If you're talking about Bezier plane curves, where x(t) and y(t) are cubic polynomials, then y(x) might be undefined or have multiple values.  An extreme degenerate case would be the line x= 1.0, which can be expressed as a cubic Bezier (control point 2 is the same as end point 1; control point 3 is the same as end point 4).  In that case, y(x) has no solutions for x != 1.0, and infinite solutions for x == 1.0.

A method of recursive subdivision will work, but I would expect it to be much slower than just solving the cubic.  (Unless you're working with some sort of embedded processor with unusually poor floating-point capacity.)

You should have no trouble finding code that solves a cubic that has already been thoroughly tested and debuged.  If you implement your own solution using recursive subdivision, you won't have that advantage.

Finally, yes, there may be numerical stablility problems, like when the point you want is near a tangent, but a subdivision method won't make those go away.  It will just make them less obvious.

EDIT:  responding to your comment, but I need more than 300 characters.

I'm only dealing with bezier curves where y(x) has only one (real) root. Regarding numerical stability, using the formula from http://en.wikipedia.org/wiki/Cubic_equation#Summary, it would appear that there might be problems if u is very small. – jtxx000

The wackypedia article is math with no code.  I suspect you can find some cookbook code that's more ready-to-use somewhere.  Maybe Numerical Recipies or ACM collected algorithms link text.

To your specific question, and using the same notation as the article, u is only zero or near zero when p is also zero or near zero.  They're related by the equation:

    u^^6 + q u^^3 == p^^3 /27

Near zero, you can use the approximation:

    q u^^3 == p^^3 /27

or  p / 3u == cube root of q

So the computation of x from u should contain something like:

(fabs(u) >= somesmallvalue) ?  (p / u / 3.0) : cuberoot (q)

How "near" zero is near?  Depends on how much accuracy you need.  You could spend some quality time with Maple or Matlab looking at how much error is introduced for what magnitudes of u.  Of course, only you know how much accuracy you need.

The article gives 3 formulas for u for the 3 roots of the cubic.  Given the three u values, you can get the 3 corresponding x values.  The 3 values for u and x are all complex numbers with an imaginary component.  If you're sure that there has to be only one real solution, then you expect one of the roots to have a zero imaginary component, and the other two to be complex conjugates.  It looks like you have to compute all three and then pick the real one.  (Note that a complex u can correspond to a real x!)  However, there's another numerical stability problem there:  floating-point arithmetic being what it is, the imaginary component of the real solution will not be exactly zero, and the imaginary components of the non-real roots can be arbitrarily close to zero.  So numeric round-off can result in you picking the wrong root.  It would be helpfull if there's some sanity check from your application that you could apply there.

If you do pick the right root, one or more iterations of Newton-Raphson can improve it's accuracy a lot.

OwnerDisplayName: Die in Sente

LastEditorDisplayName: Die in Sente


问:
Capturing a repeated group vs repeating a capturing group in the middle of a complex regex
First: I know this question has been beaten to death.

Second: I've looked at every resource (online editors, RexEgg, regular-expressions.info etc...) I can think of over the past few years and I still cannot grasp this part of regex. It never seems to work for me no matter what RegEx I use.

Now that the house-keeping is out of the way:

I have a large amount of text that I need to extract some data from that I think Regex is well-suited for.

The text looks like this:

2017-03-31 09:41:18 EDT [12708-4] parameters: $1 = '0', $2 = 'ON', $3 = 'ON'

Fairly obviously, I want the values for $1, $2 and $3. This particular example has 3 variables but it's generally between 1 and 15.

I want a regex that will capture the following:

$1

'0'

$2

'ON'

$3

'ON'

This is my regex, which matches the first group:

\d{4}.+\[[\d-]*\].+?parameters:\s((\$\d+)\s?=\s?(['\d+\w+]+))

but no combination of pluses, parentheses and commas produces anything near what I want. Even if I remove the commas from the string and just jam them together I can't get it to capture.

This guy captures everything, but the groups don't make sense:

\d{4}.+\[[\d-]*\].+?parameters:\s(((\$\d+)\s?=\s?(['\d+\w+]+),?\s?)+)

Can someone end my misery here and explain to me how to capture repeated text in a regex if the text is separated by characters that I don't care about?

答:
I would suggest you use come regex to extract each value set like this (\$\d) = '(.+?)' example

Then you can loop through all the matches. Group 1 will be the label (ie. $1) and Group 2 will be the value (ie. 0)

Just a small warning I think is worth mentioning: "A repeated capturing group will only capture the last iteration. Put a capturing group around the repeated group to capture all iterations or use a non-capturing group instead if you're not interested in the data" (as noted on regex101)


答:
I see several issues with your code (especially with respect to your problem statement), but the summation procedure is not working because you are initializing variable "holder" only once, that too, before the for loop. Also, you are using an uninitialized varaible "i" as an index for the array arr. A lot can go wrong here!

By the way, Please use proper indentation to make your code more readable.

Title: Manipulating random number arrays

Body:
The question: Given integer values of x and y generate 20 random values within [x, y] interval and put them in an array. Print the array. Determine the index of the largest even negative number in it (ranging from 0 to 19). Account for the possibility that there might be no such number in the array. Calculate the sum of all positive odd numbers. You are only allowed to go through the
array values once. You should define separate functions for generating random numbers and checking even and odd numbers.

What I have written:

    #include <stdio.h>

int random(int min, int max, int arr[]){
    int i, j = 1;
    for(i = 0; i<20; i++){
        arr[i] = min + rand() % (max+1 - min);}
    for(i = 0; i<20; i++){
        printf("%d. %d\n", j, arr[i]);
        j++;}
    return arr[20];}

int evenodd(int arr[], int size){
    int i, holder, sum, index = 1;
    holder = arr[i];
    for(i = 0; i<20; i++){
        if (holder>0){
            if (holder%2 == 0){
                sum = sum;}
            else{
                sum += i;}}
        else{
            sum = sum;}}
    printf("\nThe sum of all odd positive numbers is %d.", sum);
    for(i = 1; i<20; i++){
        int top = arr[0];
        if (arr[i]<0){
            if(arr[i]<top){
                top = arr[i];
                index = i;}
            else{
                top = top;}}
        else{
            top = top;}}
    printf("\nThe index of the largest negative number is %d", index);}

int main()
{
    int min, max;
    printf("Please input the minimum desired random number: ");
    scanf("%d", &min);
    printf("\nPlease input the maximum desired random number: ");
    scanf("%d", &max);
    int a[20];
    random(min, max, a);
    evenodd(a, 20);
}

It prints out fine, but the sum of positive odd number is wrong, as well as the index of the largest negative number.


问:
Python math range error
I'm getting an error when trying to calculate a very large number in Python. Here is my code:

```<code># Where fourthNumber = 2790
# and dee = 413
emm = math.pow(fourthNumber, dee)
</code>```

An my error is:

```<code>line 44, in <module>
    emm = math.pow(fourthNumber, dee)
OverflowError: math range error
</code>```

Is there a way around this error? I thought Python could handle arbitrarily large numbers? Or am I wrong? Any help is appreciated. Thanks!

答:
The builtin pow works with integer arithmetic:

```<code>>>> pow.__module__
'__builtin__'
>>> pow is math.pow
False
>>> pow(2790, 413)
108276934...
</code>```

Title: Python math range error

Body:
I'm getting an error when trying to calculate a very large number in Python. Here is my code:

# Where fourthNumber = 2790
# and dee = 413
emm = math.pow(fourthNumber, dee)

An my error is:

line 44, in <module>
    emm = math.pow(fourthNumber, dee)
OverflowError: math range error

Is there a way around this error? I thought Python could handle arbitrarily large numbers? Or am I wrong? Any help is appreciated. Thanks!

Body:
The builtin pow works with integer arithmetic:

>>> pow.__module__
'__builtin__'
>>> pow is math.pow
False
>>> pow(2790, 413)
108276934...


问:
Java User Input array is only capturing 3 integers instead of five
This code is supposed to capture 5 user integers, print them out, then print them in reverse. It is capturing the first int only, and printing it 3 times, then printing the first integer again 5 more times without reversing. Test ends with "Process finished with exit code 0"  which I think is says the program finished without errors -- which of course is not correct. I assume the issue is in how the user input array is stored. I have it assigning as userNum[i] with a limited array of 5, and int i =0 to begin array storage at userNum[0], so I'm not clear on why all the inputs are not captured up to userNum[4].
Thank you for any insight you can provide. I am very new to java and this is prework for my java class.</p>

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

public class ArrayReverse {

    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in); // scanner for input
        final int NUM_VALS = 5; // number on int user able to enter
        int[] userNum = new int[NUM_VALS]; // user integers storage
        int j = 0;
        int i = 0;

        System.out.println("Enter integer values: ");
        userNum[i] = scnr.nextInt(); // capture user input int

        for (j = 0; j < NUM_VALS; j++) {
            System.out.print("You entered: ");
            System.out.println(userNum[i]);
            ++j;
        }
        System.out.print("\nNumbers in reverse: "); // statement to Print reversed array
        for (j = NUM_VALS - 1; j >= 0; j--) {
            System.out.print(userNum[i] + " ");
        }
    }
}
</code>```

答:
Here is a solution using the collections framework:</p>

```<code>import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class ArrayReverse {

  public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in); // scanner for input
    final List<Integer> numbers = new ArrayList<>();
    System.out.println("Enter any number of integers. (whitespace delimited. enter a non-integer to quit.): ");
    while (scnr.hasNextBigInteger()) {
      final int n = scnr.nextInt();
      System.out.println("Parsed: " + n);
      numbers.add(n);
    }
    System.out.println("Done reading user input.");
    System.out.println("Your input: " + numbers);
    Collections.reverse(numbers);
    System.out.println("Your input reversed: " + numbers);
  }
}
</code>```

Body:
This code is supposed to capture 5 user integers, print them out, then print them in reverse. It is capturing the first int only, and printing it 3 times, then printing the first integer again 5 more times without reversing. Test ends with "Process finished with exit code 0"  which I think is says the program finished without errors -- which of course is not correct. I assume the issue is in how the user input array is stored. I have it assigning as userNum[i] with a limited array of 5, and int i =0 to begin array storage at userNum[0], so I'm not clear on why all the inputs are not captured up to userNum[4].
Thank you for any insight you can provide. I am very new to java and this is prework for my java class.

import java.util.Scanner;

public class ArrayReverse {

    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in); // scanner for input
        final int NUM_VALS = 5; // number on int user able to enter
        int[] userNum = new int[NUM_VALS]; // user integers storage
        int j = 0;
        int i = 0;

        System.out.println("Enter integer values: ");
        userNum[i] = scnr.nextInt(); // capture user input int

        for (j = 0; j < NUM_VALS; j++) {
            System.out.print("You entered: ");
            System.out.println(userNum[i]);
            ++j;
        }
        System.out.print("\nNumbers in reverse: "); // statement to Print reversed array
        for (j = NUM_VALS - 1; j >= 0; j--) {
            System.out.print(userNum[i] + " ");
        }
    }
}

Body:
Here is a solution using the collections framework:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class ArrayReverse {

  public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in); // scanner for input
    final List<Integer> numbers = new ArrayList<>();
    System.out.println("Enter any number of integers. (whitespace delimited. enter a non-integer to quit.): ");
    while (scnr.hasNextBigInteger()) {
      final int n = scnr.nextInt();
      System.out.println("Parsed: " + n);
      numbers.add(n);
    }
    System.out.println("Done reading user input.");
    System.out.println("Your input: " + numbers);
    Collections.reverse(numbers);
    System.out.println("Your input reversed: " + numbers);
  }
}


Title: Python math range error

Body:
The problem is that math.pow(..) works on floating point numbers. In Python floating point numbers are not arbitrary large. Only ints are (in python-3.x, and longs in python-2.x).

You can however use the ** operator which does integer power (given of course the arguments are integers) if the two numbers are integers:

>>> 2790**413
10827693458027068918752254513689369927451498632867702850871449492721716762882046359646654407147290095143376244612860740505063304616869045757879636651922242895944635094287526023557872050108996014618928707382416906723717536207944990935946477343103732942220495426003253324856391048675505527041527544249845903325107575822015010197006079682477544271998209608154757421132764034059289159228295810448568286783859864141487725512980856505994152145510660350938086763233208252511256291934375881870590480237727775536326670654123168787472077359939510018827829233028430183558108518520524567765780717109616748933630364200317687291046055118737587697510939517252245710306646155772831436013971724481443654932630319085588147436112198934867224850036968074130558127066188475740553149587714112808551835880666012903651859580234129805580074844684526620091506655345299434455806896837926335229779632528684030400890708579038639280240022309690038032176604539091205540422068492362106868171343650410145963283813864374487990607671475570427243900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

If you however cast it to a float, you get:

>>> float(2790**413)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: int too large to convert to float

So the error clearly shows that python cannot handle this large numbers as floats.