问:
bash script for creating multiple files using forloop
I am brand new at bash script. I want to write a script using forloop which will give me the following line and execute also these lines.

```<code>gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 1000 -e 10000 -skip 10 -o 1.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 2000 -e 20000 -skip 10 -o 2.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 3000 -e 30000 -skip 10 -o 3.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 4000 -e 40000 -skip 10 -o 4.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 5000 -e 50000 -skip 10 -o 5.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 6000 -e 60000 -skip 10 -o 6.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 7000 -e 70000 -skip 10 -o 7.out
</code>```

....

答:
You can use a C-style loop as well, e.g.

```<code>for ((i = 1; i < 8; i++)); do
    echo "gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b $((i * 1000)) -e $((i * 10000)) -skip 10 -o $i.out"
done
</code>```

Example Use/Output

```<code>$ for ((i = 1; i < 8; i++)); do
>     echo "gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b $((i * 1000)) -e $((i * 10000)) -skip 10 -o $i.out"
> done
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 1000 -e 10000 -skip 10 -o 1.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 2000 -e 20000 -skip 10 -o 2.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 3000 -e 30000 -skip 10 -o 3.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 4000 -e 40000 -skip 10 -o 4.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 5000 -e 50000 -skip 10 -o 5.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 6000 -e 60000 -skip 10 -o 6.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 7000 -e 70000 -skip 10 -o 7.out
</code>```

Body:
I am brand new at bash script. I want to write a script using forloop which will give me the following line and execute also these lines.

gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 1000 -e 10000 -skip 10 -o 1.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 2000 -e 20000 -skip 10 -o 2.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 3000 -e 30000 -skip 10 -o 3.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 4000 -e 40000 -skip 10 -o 4.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 5000 -e 50000 -skip 10 -o 5.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 6000 -e 60000 -skip 10 -o 6.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 7000 -e 70000 -skip 10 -o 7.out

....

Body:
You can use a C-style loop as well, e.g.

for ((i = 1; i < 8; i++)); do
    echo "gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b $((i * 1000)) -e $((i * 10000)) -skip 10 -o $i.out"
done

Example Use/Output

$ for ((i = 1; i < 8; i++)); do
>     echo "gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b $((i * 1000)) -e $((i * 10000)) -skip 10 -o $i.out"
> done
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 1000 -e 10000 -skip 10 -o 1.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 2000 -e 20000 -skip 10 -o 2.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 3000 -e 30000 -skip 10 -o 3.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 4000 -e 40000 -skip 10 -o 4.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 5000 -e 50000 -skip 10 -o 5.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 6000 -e 60000 -skip 10 -o 6.out
gmx trjconv -f md_0_1.xtc -s md_0_1.tpr -b 7000 -e 70000 -skip 10 -o 7.out


来源: stackexchange

问:
Getting good mixing with many input datafiles in tensorflow
I'm working with tensorflow hoping to train a deep CNN to do move prediction for the game Go. The dataset I created consists of 100,000 binary data files, where each datafile corresponds to a recorded game and contains roughly 200 training samples (one for each move in the game). I believe it will be very important to get good mixing when using SGD. I'd like my batches to contain samples from different games AND samples from different stages of the games. So for example simply reading one sample from the start of 100 files and shuffling isn't good b/c those 100 samples will all be the first move of each game.

I have read the tutorial on feeding data from files but I'm not sure if their provided libraries do what I need. If I were to hard code it myself I would basically initialize a bunch of file pointers to random locations within each file and then pull samples from random files, incrementing the file pointers accordingly.

So, my question is does tensorflow provide this sort of functionality or would it be easier to write my own code for creating batches?

答:
In your case it is not a problem to do some preprocessing and create one file out of all the files you have. For this type of games, where the history is not important and the position determines everything your dataset can consist just from position -> next_move.

For a more broad case TF provides everything to allow the shuffling you want. There are two types shuffling which serve different purposes and shuffle different things:

tf.train.string_input_producer shuffle: Boolean. If true, the strings are randomly shuffled within each epoch.. So if you have a few files ['file1', 'file2', ..., 'filen'] this randomly selects a file from this list. If case of false, the files follow one after each other.

tf.train.shuffle_batch Creates batches by randomly shuffling tensors. So it takes batch_size tensors from your queue (you will need to create a queue with tf.train.start_queue_runners ) and shuffles them.

ContentLicense: CC BY-SA 3.0


问:
301 Redirects on Products in DNN
I am a novice when it comes to developing and coding. I am stronger at design and HTML/CSS but I have a question regarding 301 redirects on a eCommerce site that I am getting ready to launch.

The site has over 500 products and the URLs for these products are now different. I need a way to create a redirect map so that I don't have to redirect 500+ products manually.

The old URLs look like this: domainofstore.com/Animated-Waving-Santa.html

The new URLs look like this: domainofstore.com/Product/animated-waving-santa

The new site is built in DNN 9 with RevIndex StoreFront.

Now there are some static pages that need to be redirected as well and I have no problem creating those manually. There URL structure is below:

Old URL: domainofstore.com/About-The-Holiday-Light-Store.html

New URL: domainofstore.com/About-Us

So how do I go about creating the 500+ product URL rewrites without having to add them manually?

答:
We had the same situation with an ecommerce re-platform to DNN where we needed to programmatically redirect the old style product page Urls to the new Urls in DNN.  I ended up writing a custom Url Extension Provider in DNN to accomplish this. </p>

<p>I do have a step-by-step tutorial on DNNHero.com, but it does require a subscription.  Is is called: Building a URL Extension Provider for DNN. </p>

Title: 301 Redirects on Products in DNN

Body:
We had the same situation with an ecommerce re-platform to DNN where we needed to programmatically redirect the old style product page Urls to the new Urls in DNN.  I ended up writing a custom Url Extension Provider in DNN to accomplish this.

I do have a step-by-step tutorial on DNNHero.com, but it does require a subscription.  Is is called: Building a URL Extension Provider for DNN.


问:
Number of Triangles in a Vertex in C
I'm having some difficulties to develop a fuction to count the number of triangles in each vertex of a Graph. This graph is an adjacency list. I did
the Is_Edge function that returns 1 if there is an edge between V1 and V2, this might help.Any hint? The structs are below:</p>

```<code>struct AdjListNode
{
    int dest;
    int TrianglesNumber;
    int weight;
    struct AdjListNode* next;
};

struct AdjList
{
    struct AdjListNode *head;
};

struct Graph
{
    int V;
    struct AdjList* array;
};

int Is_Edge(struct Graph *Graph,int V1,int V2){
    int find=0;
    if(V1 > Graph->V || V2 > Graph->V)
        return 0;
    else{
        struct AdjListNode *aux = Graph->array[V1].head;
        while((aux!=NULL)&&(!find)){
                if(aux->dest == V2)
                    find = 1;
                else
                    aux = aux->prox;
        }
        return(find);
    }
}
</code>```

答:
Do not write code until you know what logic or algorithm you want the code to implement.

If you know which vertices are connected by an edge, say you have a function Connected(i, j), and the total number of vertices N, then you can count the number of triangles sharing vertex k using (pseudocode)

```<code>Function triangles_at_vertex(k):
    Count = 0
    For i = 1 to N:
        If i != k AND Connected(i, k):
            For j = 1 to N:
                If j != i AND j != k AND Connected(i, j):
                    Count = Count + 1
                End if
            End For
        End If
    End For
    Return Count
End Function
</code>```

However, the above function does not use adjacency lists at all.

Let's say you do have the adjacency list for vertex k, as well as for all vertices adjacent to k. One way to count the triangles is to count the number of unique pairs of connected vertices also connected to vertex k:

```<code>Function triangles_at_vertex(k):
    pairs = Empty
    kList = Adjacency_list(k)
    For i in kList:
       iList = Adjacency_list(i)
       For j in iList:
           If (j in kList):
               If ((Pair(i,j) NOT in pairs) AND
                  ((Pair(j,i) NOT in pairs):
                   Add Pair(i, j) to pairs
               End If
           End If
       End For
    End For
    Return Count(pairs)
End Function
</code>```

The pairs above can be a list, ordered set (array of pairs), or an unordered set. Note that it cannot have as many members as the adjacency list for vertex k, because all vertices in all triangles we are looking for must be in the adjacency list for k.

We can avoid the pairs set/list, if we assume that all adjacency lists are complete -- in the sense that if k is listed in i's adjacency list, then i is listed in k's adjacency list too. Often, only one half of the adjacency is stored, for smaller memory use.

Then, we know that we count each pair exactly twice, because we count both i,j and j,i:

```<code>Function triangles_at_vertex(k):
    Count = 0
    kList = Adjacency_list(k)
    For i in kList:
       iList = Adjacency_list(i)
       For j in iList:
           If (j in kList):
               Count = Count + 1
           End If
       End For
    End For
    Return Count / 2
End Function
</code>```

Pick your algorithm first, and then start coding.

Title: Number of Triangles in a Vertex in C

Body:
I'm having some difficulties to develop a fuction to count the number of triangles in each vertex of a Graph. This graph is an adjacency list. I did
the Is_Edge function that returns 1 if there is an edge between V1 and V2, this might help.Any hint? The structs are below:

struct AdjListNode
{
    int dest;
    int TrianglesNumber;
    int weight;
    struct AdjListNode* next;
};

struct AdjList
{
    struct AdjListNode *head;
};

struct Graph
{
    int V;
    struct AdjList* array;
};

int Is_Edge(struct Graph *Graph,int V1,int V2){
    int find=0;
    if(V1 > Graph->V || V2 > Graph->V)
        return 0;
    else{
        struct AdjListNode *aux = Graph->array[V1].head;
        while((aux!=NULL)&&(!find)){
                if(aux->dest == V2)
                    find = 1;
                else
                    aux = aux->prox;
        }
        return(find);
    }
}

Body:
Do not write code until you know what logic or algorithm you want the code to implement.

If you know which vertices are connected by an edge, say you have a function Connected(i, j), and the total number of vertices N, then you can count the number of triangles sharing vertex k using (pseudocode)

Function triangles_at_vertex(k):
    Count = 0
    For i = 1 to N:
        If i != k AND Connected(i, k):
            For j = 1 to N:
                If j != i AND j != k AND Connected(i, j):
                    Count = Count + 1
                End if
            End For
        End If
    End For
    Return Count
End Function

However, the above function does not use adjacency lists at all.

Let's say you do have the adjacency list for vertex k, as well as for all vertices adjacent to k. One way to count the triangles is to count the number of unique pairs of connected vertices also connected to vertex k:

Function triangles_at_vertex(k):
    pairs = Empty
    kList = Adjacency_list(k)
    For i in kList:
       iList = Adjacency_list(i)
       For j in iList:
           If (j in kList):
               If ((Pair(i,j) NOT in pairs) AND
                  ((Pair(j,i) NOT in pairs):
                   Add Pair(i, j) to pairs
               End If
           End If
       End For
    End For
    Return Count(pairs)
End Function

The pairs above can be a list, ordered set (array of pairs), or an unordered set. Note that it cannot have as many members as the adjacency list for vertex k, because all vertices in all triangles we are looking for must be in the adjacency list for k.

We can avoid the pairs set/list, if we assume that all adjacency lists are complete -- in the sense that if k is listed in i's adjacency list, then i is listed in k's adjacency list too. Often, only one half of the adjacency is stored, for smaller memory use.

Then, we know that we count each pair exactly twice, because we count both i,j and j,i:

Function triangles_at_vertex(k):
    Count = 0
    kList = Adjacency_list(k)
    For i in kList:
       iList = Adjacency_list(i)
       For j in iList:
           If (j in kList):
               Count = Count + 1
           End If
       End For
    End For
    Return Count / 2
End Function

Pick your algorithm first, and then start coding.


问:
Python. Homework: Not working due to efficiency with large inputs
Homework: return the maximal sum of k consecutive elements in a list. I have tried the following 3, which work for 6 of the 7 tests by which the solution is verified. The 7th test is a very long input with a very large k value. I cannot put the input list in because the shown list is truncated due to its length. Here are the 3 methods I tried. Reiterating, each timed out, while the last one also gave me a SyntaxError.
Method 1: [verbose]

```<code>def arrayMaxConsecutiveSum(inputArray, k):
    sum_array = []
    for i in range(len(inputArray)-(k+1)):
        sum_array.append(sum(inputArray[i:i+k]))

    return max(sum_array)
</code>```

Method 2: [one line = efficiency??]

```<code>def arrayMaxConsecutiveSum(inputArray, k):

    return max([sum(inputArray[i:i+k]) for i in range(len(inputArray)-(k+1))])
</code>```

Method 3: Lambda call

```<code>def arrayMaxConsecutiveSum(inputArray, k):
    f = lambda data, n: [data[i:i+n] for i in range(len(data) - n + 1)]

    sum_array = [sum(val) for val in f(inputArray,k)]

    return max(sum_array)
</code>```

Some examples of inputs and (correct) outputs:

IN:[2, 3, 5, 1, 6]
k: 2 OUT: 8

IN:[2, 4, 10, 1]
k: 2 OUT: 14

IN: [1, 3, 4, 2, 4, 2, 4]
k: 4 OUT: 13

Again, I would like to mention that I passed the other tests (6 was very long with a large k value as well[k was an order of magnitude smaller than 7's, however]) and just need to identify a method or a revision that would be more efficient/make these more efficient. Lastly, I would like to add that I attempted both 6 and 7 with the (truncated) inputs on IDLE3 and each produced a ValueError:

```<code>Traceback (most recent call last):
  File "/Users/ryanflynn/arrmaxconsecsum.py", line 15, in <module>
    962, 244, 390, 854, 406, 457, 160, 612, 693, 896, 800, 670, 776, 65, 81, 336, 305, 262, 877, 217, 50, 835, 307, 865, 774, 163, 556, 186, 734, 404, 610, 621, 538, 370, 153, 105, 816, 172, 149, 404, 634, 105, 74, 303, 304, 145, 592, 472, 778, 301, 480, 693, 954, 628, 355, 400, 327, 916, 458, 599, 157, 424, 957, 340, 51, 60, 688, 325, 456, 148, 189, 365, 358, 618, 462, 125, 863, 530, 942, 978, 898, 858, 671, 527, 877, 614, 826, 163, 380, 442, 68, 825, 978, 965, 562, 724, 553, 18, 554, 516, 694, 802, 650, 434, 520, 685, 581, 445, 441, 711, 757, 167, 594, 686, 993, 543, 694, 950, 812, 765, 483, 474, 961, 566, 224, 879, 403, 649, 27, 205, 841, 35, 35, 816, 723, 276, 984, 869, 502, 248, 695, 273, 689, 885, 157, 246, 684, 642, 172, 313, 683, 968, 29, 52, 915, 800, 608, 974, 266, 5, 252, 6, 15, 725, 788, 137, 200, 107, 173, 245, 753, 594, 47, 795, 477, 37, 904, 4, 781, 804, 352, 460, 244, 119, 410, 333, 187, 231, 48, 560, 771, 921, 595, 794, 925, 35, 312, 561, 173, 233, 669, 300, 73, 977, 977, 591, 322, 187, 199, 817, 386, 806, 625, 500, 1, 294, 40, 271, 306, 724, 713, 600, 126, 263, 591, 855, 976, 515, 850, 219, 118, 921, 522, 587, 498, 420, 724, 716],6886)
  File "/Users/ryanflynn/arrmaxconsecsum.py", line 6, in arrayMaxConsecutiveSum
    return max(sum_array)
ValueError: max() arg is an empty sequence
</code>```

(Note: this used method 3) I checked with print statements both the value for f(inputArray,k) and sum_array: [] Any help would be appreciated :)

答:
Try:

```<code>def arrayMaxConsecutiveSum(inputArray, k):
    S = sum(inputArray[:k])
    M = S
    for i in range(len(inputArray) - k):
        S += ( inputArray[i+k] - inputArray[i])
        if M < S:
            M = S
    return M
</code>```

S stands for sum and M stands for max.

This solution have a complexity of O(n), when your's have O(n*k)

You are summing k numbers n-k times, when I am summing 3 numbers n times.

Body:
Homework: return the maximal sum of k consecutive elements in a list. I have tried the following 3, which work for 6 of the 7 tests by which the solution is verified. The 7th test is a very long input with a very large k value. I cannot put the input list in because the shown list is truncated due to its length. Here are the 3 methods I tried. Reiterating, each timed out, while the last one also gave me a SyntaxError.
Method 1: [verbose]

def arrayMaxConsecutiveSum(inputArray, k):
    sum_array = []
    for i in range(len(inputArray)-(k+1)):
        sum_array.append(sum(inputArray[i:i+k]))

    return max(sum_array)

Method 2: [one line = efficiency??]

def arrayMaxConsecutiveSum(inputArray, k):

    return max([sum(inputArray[i:i+k]) for i in range(len(inputArray)-(k+1))])

Method 3: Lambda call

def arrayMaxConsecutiveSum(inputArray, k):
    f = lambda data, n: [data[i:i+n] for i in range(len(data) - n + 1)]

    sum_array = [sum(val) for val in f(inputArray,k)]

    return max(sum_array)

Some examples of inputs and (correct) outputs:

IN:[2, 3, 5, 1, 6]
k: 2 OUT: 8

IN:[2, 4, 10, 1]
k: 2 OUT: 14

IN: [1, 3, 4, 2, 4, 2, 4]
k: 4 OUT: 13

Again, I would like to mention that I passed the other tests (6 was very long with a large k value as well[k was an order of magnitude smaller than 7's, however]) and just need to identify a method or a revision that would be more efficient/make these more efficient. Lastly, I would like to add that I attempted both 6 and 7 with the (truncated) inputs on IDLE3 and each produced a ValueError:

Traceback (most recent call last):
  File "/Users/ryanflynn/arrmaxconsecsum.py", line 15, in <module>
    962, 244, 390, 854, 406, 457, 160, 612, 693, 896, 800, 670, 776, 65, 81, 336, 305, 262, 877, 217, 50, 835, 307, 865, 774, 163, 556, 186, 734, 404, 610, 621, 538, 370, 153, 105, 816, 172, 149, 404, 634, 105, 74, 303, 304, 145, 592, 472, 778, 301, 480, 693, 954, 628, 355, 400, 327, 916, 458, 599, 157, 424, 957, 340, 51, 60, 688, 325, 456, 148, 189, 365, 358, 618, 462, 125, 863, 530, 942, 978, 898, 858, 671, 527, 877, 614, 826, 163, 380, 442, 68, 825, 978, 965, 562, 724, 553, 18, 554, 516, 694, 802, 650, 434, 520, 685, 581, 445, 441, 711, 757, 167, 594, 686, 993, 543, 694, 950, 812, 765, 483, 474, 961, 566, 224, 879, 403, 649, 27, 205, 841, 35, 35, 816, 723, 276, 984, 869, 502, 248, 695, 273, 689, 885, 157, 246, 684, 642, 172, 313, 683, 968, 29, 52, 915, 800, 608, 974, 266, 5, 252, 6, 15, 725, 788, 137, 200, 107, 173, 245, 753, 594, 47, 795, 477, 37, 904, 4, 781, 804, 352, 460, 244, 119, 410, 333, 187, 231, 48, 560, 771, 921, 595, 794, 925, 35, 312, 561, 173, 233, 669, 300, 73, 977, 977, 591, 322, 187, 199, 817, 386, 806, 625, 500, 1, 294, 40, 271, 306, 724, 713, 600, 126, 263, 591, 855, 976, 515, 850, 219, 118, 921, 522, 587, 498, 420, 724, 716],6886)
  File "/Users/ryanflynn/arrmaxconsecsum.py", line 6, in arrayMaxConsecutiveSum
    return max(sum_array)
ValueError: max() arg is an empty sequence

(Note: this used method 3) I checked with print statements both the value for f(inputArray,k) and sum_array: [] Any help would be appreciated :)

Body:
Try:

def arrayMaxConsecutiveSum(inputArray, k):
    S = sum(inputArray[:k])
    M = S
    for i in range(len(inputArray) - k):
        S += ( inputArray[i+k] - inputArray[i])
        if M < S:
            M = S
    return M

S stands for sum and M stands for max.

This solution have a complexity of O(n), when your's have O(n*k)

You are summing k numbers n-k times, when I am summing 3 numbers n times.


问:
How to AddConstraint to a button relative to parent view's margin so that it appears 30 from top margin and 30 from right margin
This is the code I'm trying out:

```<code>    @IBOutlet weak var btnInfo: UIButton!

override func viewWillAppear(_ animated: Bool) {
    self.view.addConstraint(NSLayoutConstraint(item: self.view,
                                             attribute: .topMargin,
                                             relatedBy: .equal,
                                             toItem: btnInfo,
                                             attribute: .notAnAttribute,
                                             multiplier: 1,
                                             constant: 20))
    self.view.addConstraint(NSLayoutConstraint(item: self.view,
                                             attribute: .rightMargin,
                                             relatedBy: .equal,
                                             toItem: btnInfo,
                                             attribute: .notAnAttribute,
                                             multiplier: 1,
                                             constant: 30))
}
</code>```

Trying to add .topMargin and .rightMargin constraints to get the btnInfo to appear 30 points from top and 30 from right margin. Please help.

答:
If interface builder is an option, interface builder works great for this type of functionality.  Select the object you are wanting to add your margins to and set constant margins on the top and the right.

Here is a screen capture.

Body:
This is the code I'm trying out:

    @IBOutlet weak var btnInfo: UIButton!

override func viewWillAppear(_ animated: Bool) {
    self.view.addConstraint(NSLayoutConstraint(item: self.view,
                                             attribute: .topMargin,
                                             relatedBy: .equal,
                                             toItem: btnInfo,
                                             attribute: .notAnAttribute,
                                             multiplier: 1,
                                             constant: 20))
    self.view.addConstraint(NSLayoutConstraint(item: self.view,
                                             attribute: .rightMargin,
                                             relatedBy: .equal,
                                             toItem: btnInfo,
                                             attribute: .notAnAttribute,
                                             multiplier: 1,
                                             constant: 30))
}

Trying to add .topMargin and .rightMargin constraints to get the btnInfo to appear 30 points from top and 30 from right margin. Please help.


问:
Jquery selecting all table data in my tables
I'm new to Jquery FYI. I'm trying to get all the table data in my table to display in my console but its not working. I selected all table rows iterate through each to find all table data and for that console log it but its not working. Some explanation would be helpful !

$(document).ready(function() {
   $('#divTable td').each(function(){
        var tableData = $(this);
        console.log($(tableData).val());

    });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myContent">
  <p>My Jquery enabled page</p>
</div>
<br>
<div id="divTable">
  <table>
    <tr>
      <!--table heading-->
      <th>Company</th>
      <th>Contact</th>
      <th>Country</th>
    </tr>
    <tr>
      <td>Alfreds Futterkiste</td>
      <td>Maria Anders</td>
      <td>Germany</td>
    </tr>
    <tr>
      <td>Centro comercial Moctezuma</td>
      <td>Francisco Chang</td>
      <td>Mexico</td>
    </tr>
    <tr>
      <td>Ernst Handel</td>
      <td>Roland Mendel</td>
      <td>Austria</td>
    </tr>
    <tr>
      <td>Island Trading</td>
      <td>Helen Bennett</td>
      <td>UK</td>
    </tr>
    <tr>
      <td>Laughing Bacchus Winecellars</td>
      <td>Yoshi Tannamuri</td>
      <td>Canada</td>
    </tr>
    <tr>
      <td>Magazzini Alimentari Riuniti</td>
      <td>Giovanni Rovelli</td>
      <td>Italy</td>
    </tr>
  </table>
</div></code>```

答:
If you're trying to iterate through
 elements, it should be done the same was as you did through the  elements - that is, without the :.

That being said, looping through the
 elements isn't really necessary, as the  elements will always be within
 tags. The outer each() can simply be removed.

Last thing I'd change: You're logging each  as a jQuery element, when I'd assume you want the text inside the cell, rather than the cell object itself. I've added a .text() in my example to demonstrate.

$(document).ready(function() {
    $(this).find('td').each(function() {
      var tableData = $(this).text();
      console.log(tableData);
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myContent">
  <p>My Jquery enabled page</p>
</div>
<br>
<div id="divTable">
  <table>
    <tr>
      <!--table heading-->
      <th>Company</th>
      <th>Contact</th>
      <th>Country</th>
    </tr>
    <tr>
      <td>Alfreds Futterkiste</td>
      <td>Maria Anders</td>
      <td>Germany</td>
    </tr>
    <tr>
      <td>Centro comercial Moctezuma</td>
      <td>Francisco Chang</td>
      <td>Mexico</td>
    </tr>
    <tr>
      <td>Ernst Handel</td>
      <td>Roland Mendel</td>
      <td>Austria</td>
    </tr>
    <tr>
      <td>Island Trading</td>
      <td>Helen Bennett</td>
      <td>UK</td>
    </tr>
    <tr>
      <td>Laughing Bacchus Winecellars</td>
      <td>Yoshi Tannamuri</td>
      <td>Canada</td>
    </tr>
    <tr>
      <td>Magazzini Alimentari Riuniti</td>
      <td>Giovanni Rovelli</td>
      <td>Italy</td>
    </tr>
  </table>
</div></code>```

Body:
I'm new to Jquery FYI. I'm trying to get all the table data in my table to display in my console but its not working. I selected all table rows iterate through each to find all table data and for that console log it but its not working. Some explanation would be helpful !

$(document).ready(function() {
   $('#divTable td').each(function(){
        var tableData = $(this);
        console.log($(tableData).val());

    });

});

My Jquery enabled page

      Company
      Contact
      Country

      Alfreds Futterkiste
      Maria Anders
      Germany

      Centro comercial Moctezuma
      Francisco Chang
      Mexico

      Ernst Handel
      Roland Mendel
      Austria

      Island Trading
      Helen Bennett
      UK

      Laughing Bacchus Winecellars
      Yoshi Tannamuri
      Canada

      Magazzini Alimentari Riuniti
      Giovanni Rovelli
      Italy

Body:
If you're trying to iterate through <tr> elements, it should be done the same was as you did through the <td> elements - that is, without the :.

That being said, looping through the <tr> elements isn't really necessary, as the <td> elements will always be within <tr> tags. The outer each() can simply be removed.

Last thing I'd change: You're logging each <td> as a jQuery element, when I'd assume you want the text inside the cell, rather than the cell object itself. I've added a .text() in my example to demonstrate.

$(document).ready(function() {
    $(this).find('td').each(function() {
      var tableData = $(this).text();
      console.log(tableData);
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myContent">
  <p>My Jquery enabled page</p>
</div>
<br>
<div id="divTable">
  <table>
    <tr>
      <!--table heading-->
      <th>Company</th>
      <th>Contact</th>
      <th>Country</th>
    </tr>
    <tr>
      <td>Alfreds Futterkiste</td>
      <td>Maria Anders</td>
      <td>Germany</td>
    </tr>
    <tr>
      <td>Centro comercial Moctezuma</td>
      <td>Francisco Chang</td>
      <td>Mexico</td>
    </tr>
    <tr>
      <td>Ernst Handel</td>
      <td>Roland Mendel</td>
      <td>Austria</td>
    </tr>
    <tr>
      <td>Island Trading</td>
      <td>Helen Bennett</td>
      <td>UK</td>
    </tr>
    <tr>
      <td>Laughing Bacchus Winecellars</td>
      <td>Yoshi Tannamuri</td>
      <td>Canada</td>
    </tr>
    <tr>
      <td>Magazzini Alimentari Riuniti</td>
      <td>Giovanni Rovelli</td>
      <td>Italy</td>
    </tr>
  </table>
</div>


问:
DynamicResource Cannot be resolved
I have been trying to learn about resources and styles, I want to create a chromeless window.

I have an example that acheives what I want via the following simple extracts of xaml.

I have a Resource set in Themes/Generic.xaml

```<code><Style x:Key="BorderlessWindowStyle" TargetType="{x:Type Window}">
    <Setter Property="AllowsTransparency" Value="true" />
    <Setter Property="WindowStyle" Value="None" />
    <Setter Property="ResizeMode" Value="CanResizeWithGrip" />
    <Setter Property="Background" Value="Transparent" />
</Style>
</code>```

I have a main window:

```<code><Window x:Class="Project1.Shell"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Project1"
    x:Name="Window"
    Title="Shell" Height="576" Width="1024" Style="{DynamicResource BorderlessWindowStyle}">
<Grid></Grid>
</code>```

But the style is not being applied and VS designer states it cannot resolve the resource.

The example I have been looking at does things this way and I cannot discover the difference between what I have seen done and what I am trying to do.

I thought that Genric.xaml was a 'special' resource dictionary that should be discoverable by my Window control - and I am guessing this assumption is my error.

What do I need to do to make this work? (Now I understand I can set these properties in the Window xaml directly, and I have done so and get the effect I want. BUT I really want to undersatnd using the Generic.xaml resource dictionary way as I have presented here)

best regards

John.

答:
Thought I would add the following example in case it helps some others out.  To add a resource dictionary to your app.xaml file you can add the following xaml code to the app.xaml file.

```<code><Application x:Class="ProjectX.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:local="clr-namespace:ProjectX"
         StartupUri="MainWindow.xaml">
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <!-- Use the Black skin by default -->
            <ResourceDictionary Source="Resources\ResourceFile.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>
</code>```

Where 'Resources' coudl be a folder in your project that contains the Resource Dictionary file (ResourceFile.xaml).

The you can add code to your resource dictionary like such:

```<code><ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:local="clr-namespace:ProjectX.Resources">

<!-- The Background Brush is used as the background for the Main Window -->
<SolidColorBrush x:Key="MainBackgroundBrush" Color="#FF202020" />

</ResourceDictionary>
</code>```

And then finally, dynamically bind to your resource dictionary doing something like:

```<code><Window
  x:Class="ProjectX.MainWindow"
  Title="Family.Show" Height="728" Width="960"
  Background="{DynamicResource MainBackgroundBrush}"
  ResizeMode="CanResizeWithGrip">
</Window>
</code>```

Title: DynamicResource Cannot be resolved

Body:
I have been trying to learn about resources and styles, I want to create a chromeless window.

I have an example that acheives what I want via the following simple extracts of xaml.

I have a Resource set in Themes/Generic.xaml

I have a main window:

<Window x:Class="Project1.Shell"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Project1"
    x:Name="Window"
    Title="Shell" Height="576" Width="1024" Style="{DynamicResource BorderlessWindowStyle}">
<Grid></Grid>

But the style is not being applied and VS designer states it cannot resolve the resource.

The example I have been looking at does things this way and I cannot discover the difference between what I have seen done and what I am trying to do.

I thought that Genric.xaml was a 'special' resource dictionary that should be discoverable by my Window control - and I am guessing this assumption is my error.

What do I need to do to make this work? (Now I understand I can set these properties in the Window xaml directly, and I have done so and get the effect I want. BUT I really want to undersatnd using the Generic.xaml resource dictionary way as I have presented here)

best regards

John.

Body:
Thought I would add the following example in case it helps some others out.  To add a resource dictionary to your app.xaml file you can add the following xaml code to the app.xaml file.

<Application x:Class="ProjectX.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:local="clr-namespace:ProjectX"
         StartupUri="MainWindow.xaml">
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <!-- Use the Black skin by default -->
            <ResourceDictionary Source="Resources\ResourceFile.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

Where 'Resources' coudl be a folder in your project that contains the Resource Dictionary file (ResourceFile.xaml).

The you can add code to your resource dictionary like such:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:local="clr-namespace:ProjectX.Resources">

<!-- The Background Brush is used as the background for the Main Window -->
<SolidColorBrush x:Key="MainBackgroundBrush" Color="#FF202020" />

</ResourceDictionary>

And then finally, dynamically bind to your resource dictionary doing something like:

<Window
  x:Class="ProjectX.MainWindow"
  Title="Family.Show" Height="728" Width="960"
  Background="{DynamicResource MainBackgroundBrush}"
  ResizeMode="CanResizeWithGrip">
</Window>


问:
What is the specific reason for the runtime error I'm getting here?
```<code>#include<stdio.h>
#include<string.h>
void main()
{
    char a,b,c;
    printf("Enter alien names:\n");
    scanf("%s\n%s\n%s\n",a,b,c);
    printf("The alien names are %s, %s and %s. A meteor hit %s's spaceship. A star scratched %s\'s spaceship. But %s fixed %s and %s\'s spaceships. The three became friends and are from the planet BYG (which means BLUE YELLOW GREEN)",a,b,c,a,b,c,a,b);
}
</code>```

What is the specific reason for the runtime error I'm getting here?

答:
The posted code has undefined behavior, because the variables a, b, and c are of type char, while the %s conversion specifier in the call to scanf() is expecting a pointer to the first element of a character array that can hold the input string. Mismatched conversion specifers and arguments in a scanf() call lead to undefined behavior, and attempting to write too many characters into the receiving array causes undefined behavior.

The first problem can be fixed by declaring a, b, and c as arrays large enough to hold expected input:

```<code>char a[100], b[100], c[100];
...
scanf("%s\n%s\n%s\n", a, b, c);
</code>```

Note that arrays decay to pointers to their first elements in most expressions, including function calls, so here a is a pointer to the first element of the character array a[]; this is equivalent to &a[0].

There is still a possibility for undefined behavior if the user enters too many characters. To avoid this, always specify a maximum width when using scanf() to read user input into a string. Note here that the specified width is the maximum number of characters that will be read for that input item, not including the null terminator, \0, which will be automatically added by scanf(), so the maximum width must be at least one less than the size of the receiving array:

```<code>scanf("%99s\n%99s\n%99s\n", a, b, c);
</code>```

But if you compile and run this code, you will find that it does not behave as expected. After the third name is entered, the program will continue waiting for more input. This is because the \n character is a whitespace character, and when scanf() encounters a whitespace character in a format string, it reads and discards zero or more whitespace characters in the input until a nonwhitespace character is encountered, or until no more characters can be read. The %s directive tells scanf() to read characters until a whitespace character is encountered. So when the user presses Enter after the final name, scanf() completes matching input characters for the final name and returns the \n character to the input stream; then the \n is reached in the above format string, and scanf() matches the aforementioned \n character in the input stream, and any further whitespace characters that are encountered. This will end if the user enters another nonwhitespace character, or signals end-of-file from the keyboard (e.g., with Ctrl-D or Ctrl-Z).

To avoid this complication, remember that it is almost never correct to end a scanf() format string with a whitespace character. Also, there is no need to use \n rather than a space character, since both are simply interpreted as whitespace directives by scanf():

```<code>scanf("%99s %99s %99s", a, b, c);
</code>```

It would further improve the posted code if the return value from the call to scanf() were checked before attempting to use the input. Since scanf() returns the number of successful assignments made, this value should be 3:

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

int main(void)
{
    char a[100], b[100], c[100];

    printf("Enter alien names:\n");
    int ret_val = scanf("%99s %99s %99s", a, b, c);

    if (ret_val == 3) {
        printf("The alien names are %s, %s and %s. A meteor hit %s's "
               "spaceship. A star scratched %s\'s spaceship. But %s "
               "fixed %s and %s\'s spaceships. The three became friends "
               "and are from the planet BYG (which means BLUE YELLOW GREEN)\n",
               a, b, c, a, b, c, a, b);
    } else {
        puts("Input error");
    }
}
</code>```

Body:
#include<stdio.h>
#include<string.h>
void main()
{
    char a,b,c;
    printf("Enter alien names:\n");
    scanf("%s\n%s\n%s\n",a,b,c);
    printf("The alien names are %s, %s and %s. A meteor hit %s's spaceship. A star scratched %s\'s spaceship. But %s fixed %s and %s\'s spaceships. The three became friends and are from the planet BYG (which means BLUE YELLOW GREEN)",a,b,c,a,b,c,a,b);
}

What is the specific reason for the runtime error I'm getting here?

Body:
The posted code has undefined behavior, because the variables a, b, and c are of type char, while the %s conversion specifier in the call to scanf() is expecting a pointer to the first element of a character array that can hold the input string. Mismatched conversion specifers and arguments in a scanf() call lead to undefined behavior, and attempting to write too many characters into the receiving array causes undefined behavior.

The first problem can be fixed by declaring a, b, and c as arrays large enough to hold expected input:

char a[100], b[100], c[100];
...
scanf("%s\n%s\n%s\n", a, b, c);

Note that arrays decay to pointers to their first elements in most expressions, including function calls, so here a is a pointer to the first element of the character array a[]; this is equivalent to &a[0].

There is still a possibility for undefined behavior if the user enters too many characters. To avoid this, always specify a maximum width when using scanf() to read user input into a string. Note here that the specified width is the maximum number of characters that will be read for that input item, not including the null terminator, \0, which will be automatically added by scanf(), so the maximum width must be at least one less than the size of the receiving array:

scanf("%99s\n%99s\n%99s\n", a, b, c);

But if you compile and run this code, you will find that it does not behave as expected. After the third name is entered, the program will continue waiting for more input. This is because the \n character is a whitespace character, and when scanf() encounters a whitespace character in a format string, it reads and discards zero or more whitespace characters in the input until a nonwhitespace character is encountered, or until no more characters can be read. The %s directive tells scanf() to read characters until a whitespace character is encountered. So when the user presses Enter after the final name, scanf() completes matching input characters for the final name and returns the \n character to the input stream; then the \n is reached in the above format string, and scanf() matches the aforementioned \n character in the input stream, and any further whitespace characters that are encountered. This will end if the user enters another nonwhitespace character, or signals end-of-file from the keyboard (e.g., with Ctrl-D or Ctrl-Z).

To avoid this complication, remember that it is almost never correct to end a scanf() format string with a whitespace character. Also, there is no need to use \n rather than a space character, since both are simply interpreted as whitespace directives by scanf():

scanf("%99s %99s %99s", a, b, c);

It would further improve the posted code if the return value from the call to scanf() were checked before attempting to use the input. Since scanf() returns the number of successful assignments made, this value should be 3:

#include <stdio.h>
#include <string.h>

int main(void)
{
    char a[100], b[100], c[100];

    printf("Enter alien names:\n");
    int ret_val = scanf("%99s %99s %99s", a, b, c);

    if (ret_val == 3) {
        printf("The alien names are %s, %s and %s. A meteor hit %s's "
               "spaceship. A star scratched %s\'s spaceship. But %s "
               "fixed %s and %s\'s spaceships. The three became friends "
               "and are from the planet BYG (which means BLUE YELLOW GREEN)\n",
               a, b, c, a, b, c, a, b);
    } else {
        puts("Input error");
    }
}


问:
Adding conditions to "when" from VS-code extension?
The code editor I've been using for the past 20 years (codewright) allows you to set a "select mode". When that is set, all keyboard cursor movements extend the selection. In VS Code, you can extend the selection by holding down the shift key (for example, Shift down-arrow), but I am looking for a way to do that without the shift key.

I have written an extension that mostly does it, but I would have had to do far less work if I could have created a new condition for the "when" clause in keybindings.json. For example, I would have liked to change

{ "key": "shift+down",    "command": "cursorDownSelect",
                          "when": "editorTextFocus" },
```

<p>to something like</p>

<pre class="lang-json prettyprint-override"><code>{ "key": "down",    "command": "cursorDownSelect",
                    "when": "editorTextFocus || extensionSelectionMode" },
{ "key": "down",    "command": "cursorDown",
                    "when": "editorTextFocus" },
</code>```

Is there a way to do add a such a condition from an extension?

答:
Try using the setContext command in your extension:

vscode.commands.executeCommand('setContext', 'extensionSelectionMode', true)
```

See VSCode vim for an example of this in action

We are tracking a better API for setting contexts here: https://github.com/Microsoft/vscode/issues/10471

ContentLicense: CC BY-SA 4.0

Body:
The code editor I've been using for the past 20 years (codewright) allows you to set a "select mode". When that is set, all keyboard cursor movements extend the selection. In VS Code, you can extend the selection by holding down the shift key (for example, Shift down-arrow), but I am looking for a way to do that without the shift key.

I have written an extension that mostly does it, but I would have had to do far less work if I could have created a new condition for the "when" clause in keybindings.json. For example, I would have liked to change

{ "key": "shift+down",    "command": "cursorDownSelect",
                          "when": "editorTextFocus" },

to something like

{ "key": "down",    "command": "cursorDownSelect",
                    "when": "editorTextFocus || extensionSelectionMode" },
{ "key": "down",    "command": "cursorDown",
                    "when": "editorTextFocus" },

Is there a way to do add a such a condition from an extension?

Body:
Try using the setContext command in your extension:

vscode.commands.executeCommand('setContext', 'extensionSelectionMode', true)

See VSCode vim for an example of this in action

We are tracking a better API for setting contexts here: https://github.com/Microsoft/vscode/issues/10471


问:
Writing multiple json objects to a json file
I have a list of json objects that I would like to write to a json file. Example of my data is as follows:

```<code>    {
    "_id": "abc",
    "resolved": false,
    "timestamp": "2017-04-18T04:57:41 366000",
    "timestamp_utc": {
        "$date": 1492509461366
    },
    "sessionID": "abc",
    "resHeight": 768,

    "time_bucket": ["2017-year", "2017-04-month", "2017-16-week", "2017-04-18-day", "2017-04-18 16-hour"],
    "referrer": "Standalone",
    "g_event_id": "abc",

    "user_agent": "abc"
    "_id": "abc",
} {
    "_id": "abc",
    "resolved": false,
    "timestamp": "2017-04-18T04:57:41 366000",
    "timestamp_utc": {
        "$date": 1492509461366
    },
    "sessionID": "abc",
    "resHeight": 768,

    "time_bucket": ["2017-year", "2017-04-month", "2017-16-week", "2017-04-18-day", "2017-04-18 16-hour"],
    "referrer": "Standalone",
    "g_event_id": "abc",

    "user_agent": "abc"
}
</code>```

I would like to wirte this to a json file. Here's the code that I am using for this purpose:

```<code>with open("filename", 'w') as outfile1:
    for row in data:
        outfile1.write(json.dumps(row))
</code>```

But this gives me a file with only 1 long row of data. I would like to have a row for each json object in my original data. I know there are some other StackOverflow questions that are trying to address somewhat similar situation (by externally inserting '\n' etc.), but it hasn't worked in my case for some reason. I believe there has to be a pythonic way to do this.

How do I achieve this?

答:
Use the indent argument to output json with extra whitespace. The default is to not output linebreaks or extra spaces.

```<code>with open('filename.json', 'w') as outfile1:
     json.dump(data, outfile1, indent=4)
</code>```

https://docs.python.org/3/library/json.html#basic-usage

Body:
I have a list of json objects that I would like to write to a json file. Example of my data is as follows:

    {
    "_id": "abc",
    "resolved": false,
    "timestamp": "2017-04-18T04:57:41 366000",
    "timestamp_utc": {
        "$date": 1492509461366
    },
    "sessionID": "abc",
    "resHeight": 768,

    "time_bucket": ["2017-year", "2017-04-month", "2017-16-week", "2017-04-18-day", "2017-04-18 16-hour"],
    "referrer": "Standalone",
    "g_event_id": "abc",

    "user_agent": "abc"
    "_id": "abc",
} {
    "_id": "abc",
    "resolved": false,
    "timestamp": "2017-04-18T04:57:41 366000",
    "timestamp_utc": {
        "$date": 1492509461366
    },
    "sessionID": "abc",
    "resHeight": 768,

    "time_bucket": ["2017-year", "2017-04-month", "2017-16-week", "2017-04-18-day", "2017-04-18 16-hour"],
    "referrer": "Standalone",
    "g_event_id": "abc",

    "user_agent": "abc"
}

I would like to wirte this to a json file. Here's the code that I am using for this purpose:

with open("filename", 'w') as outfile1:
    for row in data:
        outfile1.write(json.dumps(row))

But this gives me a file with only 1 long row of data. I would like to have a row for each json object in my original data. I know there are some other StackOverflow questions that are trying to address somewhat similar situation (by externally inserting '\n' etc.), but it hasn't worked in my case for some reason. I believe there has to be a pythonic way to do this.

How do I achieve this?

Body:
Use the indent argument to output json with extra whitespace. The default is to not output linebreaks or extra spaces.

with open('filename.json', 'w') as outfile1:
     json.dump(data, outfile1, indent=4)

https://docs.python.org/3/library/json.html#basic-usage


问:
Looping through the content of a file in RobotFramework
How can I loop through the contents of a file within Robot Framework?

My file contents would be like this:

1001

1002

1003

1004

I want to read the contents one by one, assign it to a variable and then do some operations with it.

答:
This solve my issue same like yours !

```<code>${File}=    Get File  Path\\FileName.txt
@{list}=    Split to lines  ${File}
:FOR    ${line} IN  @{list}
\   Log ${line}
\   ${Value}=   Get Variable Value  ${line}
\   Log ${Value}
</code>```

I am reading from 'text' file and 'Get Variable Value' is part of builtin library. Thanks!

Body:
This solve my issue same like yours !

${File}=    Get File  Path\\FileName.txt
@{list}=    Split to lines  ${File}
:FOR    ${line} IN  @{list}
\   Log ${line}
\   ${Value}=   Get Variable Value  ${line}
\   Log ${Value}

I am reading from 'text' file and 'Get Variable Value' is part of builtin library. Thanks!


问:
splitting up text with a regular expression in google app script (documentApp) with findText
In a google doc (not a spreadsheet) I have a wall of text that looks like

```<code> °foo bar header°foo bar bat paragraph°and another paragraph°and yet an other paragraph°and so on
</code>```

and I want to split up the text into paragraphs.

So I would like to get the text between the ° chars with help of a regexp. I would like to use

```<code>     var rangeElement = body.findText("°([^°]*)°");
</code>```

but that regexp makes google docs go "Service unavailable: Docs". Using a regexp like "°.?°" alleviates that problem, but does not isolate the text I want.

What is a regexp that would work? How can I proceed to process the substring from within the ( and )?

答:
To get all (multiple) matches, you can leverage the JavaScript RegExp witha g (global) modifier.

```<code>var rx = /°([^°]*)/g;
while (m=rx.exec(doc.getBody().getText())) {
    Logger.log("Matched: " + m[1]);
}
</code>```

The /°([^°]*)/g is a regex literal notation (mind there should be no quotes around it), where / are regex delimiters, °([^°]*) is the pattern matching ° symbol and then capturing into Group 1 any 0 or more chars other than ° (([^°]*)) any number of times (g).

To actually match all the occurrences, you need to call RegExp#exec multiple times and grab Group 1 value (m[1]).

Body:
In a google doc (not a spreadsheet) I have a wall of text that looks like

 °foo bar header°foo bar bat paragraph°and another paragraph°and yet an other paragraph°and so on

and I want to split up the text into paragraphs.

So I would like to get the text between the ° chars with help of a regexp. I would like to use

     var rangeElement = body.findText("°([^°]*)°");

but that regexp makes google docs go "Service unavailable: Docs". Using a regexp like "°.?°" alleviates that problem, but does not isolate the text I want.

What is a regexp that would work? How can I proceed to process the substring from within the ( and )?

Body:
To get all (multiple) matches, you can leverage the JavaScript RegExp witha g (global) modifier.

var rx = /°([^°]*)/g;
while (m=rx.exec(doc.getBody().getText())) {
    Logger.log("Matched: " + m[1]);
}

The /°([^°]*)/g is a regex literal notation (mind there should be no quotes around it), where / are regex delimiters, °([^°]*) is the pattern matching ° symbol and then capturing into Group 1 any 0 or more chars other than ° (([^°]*)) any number of times (g).

To actually match all the occurrences, you need to call RegExp#exec multiple times and grab Group 1 value (m[1]).


问:
ngOnDestroy Uncaught (in promise): TypeError: Cannot read property 'unsubscribe' of undefined
I'm getting an error when unsubscribing during the ngOnDestroy method in my shopping-edit.component.ts when i click the link to go to my recipes page. here is the image

error on link click

here is a link to my git https://github.com/CHBaker/First-Angular-App

and my code snippet:

```<code>import {
    Component,
    OnInit,
    OnDestroy,
    ViewChild
} from '@angular/core';
import { NgForm } from '@angular/forms';
import { Subscription } from 'rxjs/Subscription';

import { Ingredient } from '../../shared/ingredient.model';
import { ShoppingListService } from '../shopping-list.service';

@Component({
    selector: 'app-shopping-edit',
    templateUrl: './shopping-edit.component.html',
    styleUrls: ['./shopping-edit.component.css']
})
export class ShoppingEditComponent implements OnInit, OnDestroy {
    @ViewChild('f') slForm: NgForm;
    subscription: Subscription;
    editMode = false;
    editedItemIndex: number;
    editedItem: Ingredient;

    constructor(private slService: ShoppingListService) { }

    ngOnInit() {
        this.slService.startedEditing
            .subscribe(
                (index: number) => {
                    this.editedItemIndex = index;
                    this.editMode = true;
                    this.editedItem = this.slService.getIngredient(index);
                    this.slForm.setValue({
                        name: this.editedItem.name,
                        amount: this.editedItem.amount
                    })
                }
            );
    }

    onSubmit(form: NgForm) {
        const value = form.value;
        const newIngredient = new Ingredient(value.name, value.amount);
        if (this.editMode) {
            this.slService.updateIngredient(this.editedItemIndex, newIngredient);
        } else {
            this.slService.addIngredient(newIngredient);
        }
        this.editMode = false;
        form.reset();
    }

    onClear() {
        this.slForm.reset();
        this.editMode = false;
    }

    onDelete() {
        this.slService.deleteIngredient(this.editedItemIndex);
        this.onClear();
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}
</code>```

答:
Try this</p>

```<code>this.subscription = this.slService.startedEditing
        .subscribe(
            (index: number) => {
                this.editedItemIndex = index;
                this.editMode = true;
                this.editedItem = this.slService.getIngredient(index);
                this.slForm.setValue({
                    name: this.editedItem.name,
                    amount: this.editedItem.amount
                })
            }
        );
</code>```

Body:
I'm getting an error when unsubscribing during the ngOnDestroy method in my shopping-edit.component.ts when i click the link to go to my recipes page. here is the image

error on link click

here is a link to my git https://github.com/CHBaker/First-Angular-App

and my code snippet:

import {
    Component,
    OnInit,
    OnDestroy,
    ViewChild
} from '@angular/core';
import { NgForm } from '@angular/forms';
import { Subscription } from 'rxjs/Subscription';

import { Ingredient } from '../../shared/ingredient.model';
import { ShoppingListService } from '../shopping-list.service';

@Component({
    selector: 'app-shopping-edit',
    templateUrl: './shopping-edit.component.html',
    styleUrls: ['./shopping-edit.component.css']
})
export class ShoppingEditComponent implements OnInit, OnDestroy {
    @ViewChild('f') slForm: NgForm;
    subscription: Subscription;
    editMode = false;
    editedItemIndex: number;
    editedItem: Ingredient;

    constructor(private slService: ShoppingListService) { }

    ngOnInit() {
        this.slService.startedEditing
            .subscribe(
                (index: number) => {
                    this.editedItemIndex = index;
                    this.editMode = true;
                    this.editedItem = this.slService.getIngredient(index);
                    this.slForm.setValue({
                        name: this.editedItem.name,
                        amount: this.editedItem.amount
                    })
                }
            );
    }

    onSubmit(form: NgForm) {
        const value = form.value;
        const newIngredient = new Ingredient(value.name, value.amount);
        if (this.editMode) {
            this.slService.updateIngredient(this.editedItemIndex, newIngredient);
        } else {
            this.slService.addIngredient(newIngredient);
        }
        this.editMode = false;
        form.reset();
    }

    onClear() {
        this.slForm.reset();
        this.editMode = false;
    }

    onDelete() {
        this.slService.deleteIngredient(this.editedItemIndex);
        this.onClear();
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}

Body:
Try this

this.subscription = this.slService.startedEditing
        .subscribe(
            (index: number) => {
                this.editedItemIndex = index;
                this.editMode = true;
                this.editedItem = this.slService.getIngredient(index);
                this.slForm.setValue({
                    name: this.editedItem.name,
                    amount: this.editedItem.amount
                })
            }
        );


问:
QUERY_STRING Rewrite order
I have the following rewrite rules which are rewriting to the same location:

http://test.com/finance/payroll/forms/salary-payment-form.shtml?staff=test-edu-trust -> TO ->https://www.test.com/finance/BBBB.shtml?staff=test-edu-trust

```<code>RewriteRule %{QUERY_STRING} ^staff=test-edu-trust$
RewriteRule ^/finance/payroll/forms/salary-payment-form.shtml$ https://www.test.com/finance/BBBB.shtml?staff=test-edu-trust[R=301,L,NC]
</code>```

http://test.com/finance/payroll/forms/wages-payment-form.shtml?staff=test-comm-rac -> TO -> https://www.test.com/finance/BBBB.shtml?staff=test-comm-rac

```<code>RewriteRule %{QUERY_STRING} ^staff=test-comm-rac$
RewriteRule ^/finance/payroll/forms/salary-payment-form.shtml$ https://www.test.com/finance/BBBB.shtml?staff=test-comm-rac[R=301,L,NC]
</code>```

The problem is both rewrite to the same location - https://www.test.com/finance/BBBB.shtml?staff=test-edu-trust

If I change the order of the rules to below then they end up rewriting to the first location in order: https://www.test.com/finance/BBBB.shtml?staff=test-comm-rac as per below:

```<code>RewriteRule %{QUERY_STRING} ^staff=test-comm-rac$
RewriteRule ^/finance/payroll/forms/salary-payment-form.shtml$ https://www.test.com/finance/BBBB.shtml?staff=test-comm-rac[R=301,L,NC]

RewriteRule %{QUERY_STRING} ^staff=test-edu-trust$
RewriteRule ^/finance/payroll/forms/salary-payment-form.shtml$ https://www.test.com/finance/BBBB.shtml?staff=test-edu-trust[R=301,L,NC]
</code>```

What is causing the order of the rules here just to rewrite to the first one defined as I thought the QUERY_STRING would have caught this and sorted which url to rewrite to ??

答: Just noticed i have RewriteRule and not RewriteCond in for the QUERY_STRING !! Doh !!!</p>

Title: QUERY_STRING Rewrite order

Body:
I have the following rewrite rules which are rewriting to the same location:

http://test.com/finance/payroll/forms/salary-payment-form.shtml?staff=test-edu-trust -> TO ->https://www.test.com/finance/BBBB.shtml?staff=test-edu-trust

RewriteRule %{QUERY_STRING} ^staff=test-edu-trust$
RewriteRule ^/finance/payroll/forms/salary-payment-form.shtml$ https://www.test.com/finance/BBBB.shtml?staff=test-edu-trust[R=301,L,NC]

http://test.com/finance/payroll/forms/wages-payment-form.shtml?staff=test-comm-rac -> TO -> https://www.test.com/finance/BBBB.shtml?staff=test-comm-rac

RewriteRule %{QUERY_STRING} ^staff=test-comm-rac$
RewriteRule ^/finance/payroll/forms/salary-payment-form.shtml$ https://www.test.com/finance/BBBB.shtml?staff=test-comm-rac[R=301,L,NC]

The problem is both rewrite to the same location - https://www.test.com/finance/BBBB.shtml?staff=test-edu-trust

If I change the order of the rules to below then they end up rewriting to the first location in order: https://www.test.com/finance/BBBB.shtml?staff=test-comm-rac as per below:

RewriteRule %{QUERY_STRING} ^staff=test-comm-rac$
RewriteRule ^/finance/payroll/forms/salary-payment-form.shtml$ https://www.test.com/finance/BBBB.shtml?staff=test-comm-rac[R=301,L,NC]

RewriteRule %{QUERY_STRING} ^staff=test-edu-trust$
RewriteRule ^/finance/payroll/forms/salary-payment-form.shtml$ https://www.test.com/finance/BBBB.shtml?staff=test-edu-trust[R=301,L,NC]

What is causing the order of the rules here just to rewrite to the first one defined as I thought the QUERY_STRING would have caught this and sorted which url to rewrite to ??


问:
FactoryGirl attributes_for with associations
There is the following factory:

```<code>factory :car do
    name 'Some car'
    engine_value 1.6
    color '#ff0000'
    car_type
    engine_type
    transmission
    drive_type
    material
end
</code>```

As you see there are a lot of associated objects. But code

```<code>attributes_for(:car)
</code>```

generates only :name=>"Some car", :engine_value=>1.6, :color=>"#ff0000"} hash. I need to get a hash with all attributes. How can I do it? Thanks.

答:
You may want to omit the id, created_at and updated_at attributes.

FactoryGirl.build(:car).attributes.except('id', 'created_at', 'updated_at')

If you need the keys to be symbols (as in the keys generated by attributes_for):

FactoryGirl.build(:car).attributes.except('id', 'created_at', 'updated_at').symbolize_keys

Limitations:

It does not generate attributes for HMT and HABTM associations (as these associations are stored in a join table, not an actual attribute).

Association strategy in the factory must be create, as in association :user, strategy: :create. This strategy can make your factory very slow if you don't use it wisely.

Body:
There is the following factory:

factory :car do
    name 'Some car'
    engine_value 1.6
    color '#ff0000'
    car_type
    engine_type
    transmission
    drive_type
    material
end

As you see there are a lot of associated objects. But code

attributes_for(:car)

generates only :name=>"Some car", :engine_value=>1.6, :color=>"#ff0000"} hash. I need to get a hash with all attributes. How can I do it? Thanks.


问:
CakePHP plugin localization in different files
I've made ContentManager plugin for my cakephp (3.2) apps. It has base translation file in /plugins/ContentManager/src/Locale/ru/content_manager.po.

Now I want to add some additions translations on application level. So I need some additional po file for my plugin. If I put one more content_manager.po  file in app\src\Locale\ru folder, it overrides base file.

Is it possible to add file like content_manager.0.po, content_manager.base.po or something, and make whem work together? Anyway I need to extend plugin transalations somehow.

base file contains strings like these

```<code>msgid "tab_MenuItems"
msgid "content.type.News"
msgid "users.role.admin"
</code>```

and so on.

Additional file contains application-specific strings like:

```<code>msgid "content.type.Products"
msgid "content.type.Orders"
msgid "users.role.manager"
</code>```

plugin itself uses translations like (example, smarty) this:

```<code>{foreach $registered_types as $ct}
<li>{__d("content_manager", "content.type.$ct")}</li>
{/foreach}
</code>```

答:
You can add a default.po file in your apps ru locale folder, this file will by default be used by the so called "fallback loader", which is going to be used in case the requested message ID cannot be found in the primary domain, ie in content_manager.po.

In case you need more control, you can always build custom loaders/packages, like for example:

```<code>use Cake\I18n\I18n;
use Cake\I18n\MessagesFileLoader;

I18n::config('content_manager', function ($name, $locale) {
    $fileLoader = new MessagesFileLoader('content_manager', $locale, 'po');

    /* @var $package \Aura\Intl\Package  */
    $package = $fileLoader();
    $package->setFallback('content_manager.base');

    return $package;
});
</code>```

This would create a loader that internally pre-loads the default content_manager domain messages, and set the fallback loader domain to content_manager.base, so that it would try to load messages from your content_manager.base.po file in case there's no translation present in the default domain.

And don't forget to clear the cache (tmp/cache/persistent) after adding/modifying translations/loaders.

See also

Cookbook > Internationalization & Localization > Creating Generic Translators

API > \Cake\I18n\I18n::config()

API > \Cake\I18n\MessagesFileLoader

Body:
I've made ContentManager plugin for my cakephp (3.2) apps. It has base translation file in /plugins/ContentManager/src/Locale/ru/content_manager.po.

Now I want to add some additions translations on application level. So I need some additional po file for my plugin. If I put one more content_manager.po  file in app\src\Locale\ru folder, it overrides base file.

Is it possible to add file like content_manager.0.po, content_manager.base.po or something, and make whem work together? Anyway I need to extend plugin transalations somehow.

base file contains strings like these

msgid "tab_MenuItems"
msgid "content.type.News"
msgid "users.role.admin"

and so on.

Additional file contains application-specific strings like:

msgid "content.type.Products"
msgid "content.type.Orders"
msgid "users.role.manager"

plugin itself uses translations like (example, smarty) this:

{foreach $registered_types as $ct}

{__d("content_manager", "content.type.$ct")}

{/foreach}

Body:
You can add a default.po file in your apps ru locale folder, this file will by default be used by the so called "fallback loader", which is going to be used in case the requested message ID cannot be found in the primary domain, ie in content_manager.po.

In case you need more control, you can always build custom loaders/packages, like for example:

use Cake\I18n\I18n;
use Cake\I18n\MessagesFileLoader;

I18n::config('content_manager', function ($name, $locale) {
    $fileLoader = new MessagesFileLoader('content_manager', $locale, 'po');

    /* @var $package \Aura\Intl\Package  */
    $package = $fileLoader();
    $package->setFallback('content_manager.base');

    return $package;
});

This would create a loader that internally pre-loads the default content_manager domain messages, and set the fallback loader domain to content_manager.base, so that it would try to load messages from your content_manager.base.po file in case there's no translation present in the default domain.

And don't forget to clear the cache (tmp/cache/persistent) after adding/modifying translations/loaders.

See also

Cookbook > Internationalization & Localization > Creating Generic Translators

API > \Cake\I18n\I18n::config()

API > \Cake\I18n\MessagesFileLoader


问:
Launch app on background for manage notification
Hello I have trouble with manage notification

I have app with control weather in some place (when change I want build notification) one a day control it's okay, for example on 10:00 and ecery day, If I can run one methot/activity/class for control weather and launch notification if need..

I have only simple notofication from developer android.
and I have troubble for find some "advice" with my problem.. i find some with use firebase, but thing so it's not for me.

Thanks

答:
You need to use a Service (which is basically an Activity without an interface). They have a Context and you can send notifications from there.

Have a look here.


问:
Rename the url of the translated html files in the root (htaccess)
I am building a web app and trying to add two languages to the website. So I will make the same documents ending in -gr. Some examples of the files look like this:

English Language paths:

www.example.com/index.html

 www.example.com/Blog.html

Greek Language path:

www.example.com/index-gr.html

  www.example.com/Blog-gr.html

Is that possible to rename the greek files to something like the following example:

www.example.com/blog-gr.html/

should be renamed to

www.example.com/blog/gr

eg: Remove the -gr.html of all the greek documents and add /gr at the end.
Also only for index file,  example.com/index-gr.html should be example.com/gr
Thanks

答:
Try this

```<code>RewriteEngine on
RewriteBase /
RewriteRule ^(.*)/gr$ greek/$1 [NC,L]
</code>```

EDIT

```<code>RewriteEngine on
RewriteBase /
RewriteRule ^(.*)\.html/gr$ $1-gr.html [NC,L]
</code>```

Body:
Try this

RewriteEngine on
RewriteBase /
RewriteRule ^(.*)/gr$ greek/$1 [NC,L]

EDIT

RewriteEngine on
RewriteBase /
RewriteRule ^(.*)\.html/gr$ $1-gr.html [NC,L]


问:
NameError during python xml parsing
```<code>>>> stringx
'<?xml version="1.0"?><data><country name="Liechtenstein"><rank>1</rank><year>2008</year><gdppc>141100</gdppc><neighbor name="Austria" direction="E"/><neighbor name="Switzerland" direction="W"/></country><country name="Singapore"><rank>4</rank><year>2011</year><gdppc>59900</gdppc><neighbor name="Malaysia" direction="N"/></country><country name="Panama"><rank>68</rank><year>2011</year><gdppc>13600</gdppc><neighbor name="Costa Rica" direction="W"/><neighbor name="Colombia" direction="E"/></country></data>'
>>>
>>>
>>> e = xml.etree.ElementTree.fromstring(stringx)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'xml' is not defined
</code>```

Can someone suggest what am I missing here? is it the xml code or the way I am trying to parse?

答:
seems like you are missing import!

from xml.etree import ElementTree

```<code>stringx='<?xml version="1.0"?><data><country name="Liechtenstein"><rank>1</rank><year>2008</year><gdppc>141100</gdppc><neighbor name="Austria" direction="E"/><neighbor name="Switzerland" direction="W"/></country><country name="Singapore"><rank>4</rank><year>2011</year><gdppc>59900</gdppc><neighbor name="Malaysia" direction="N"/></country><country name="Panama"><rank>68</rank><year>2011</year><gdppc>13600</gdppc><neighbor name="Costa Rica" direction="W"/><neighbor name="Colombia" direction="E"/></country></data>'

e = ElementTree.fromstring(stringx) #will wok fine!
</code>```

Title: NameError during python xml parsing

Body:
>>> stringx
'<?xml version="1.0"?><data><country name="Liechtenstein"><rank>1</rank><year>2008</year><gdppc>141100</gdppc><neighbor name="Austria" direction="E"/><neighbor name="Switzerland" direction="W"/></country><country name="Singapore"><rank>4</rank><year>2011</year><gdppc>59900</gdppc><neighbor name="Malaysia" direction="N"/></country><country name="Panama"><rank>68</rank><year>2011</year><gdppc>13600</gdppc><neighbor name="Costa Rica" direction="W"/><neighbor name="Colombia" direction="E"/></country></data>'
>>>
>>>
>>> e = xml.etree.ElementTree.fromstring(stringx)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'xml' is not defined

Can someone suggest what am I missing here? is it the xml code or the way I am trying to parse?

Body:
seems like you are missing import!

from xml.etree import ElementTree

stringx='<?xml version="1.0"?><data><country name="Liechtenstein"><rank>1</rank><year>2008</year><gdppc>141100</gdppc><neighbor name="Austria" direction="E"/><neighbor name="Switzerland" direction="W"/></country><country name="Singapore"><rank>4</rank><year>2011</year><gdppc>59900</gdppc><neighbor name="Malaysia" direction="N"/></country><country name="Panama"><rank>68</rank><year>2011</year><gdppc>13600</gdppc><neighbor name="Costa Rica" direction="W"/><neighbor name="Colombia" direction="E"/></country></data>'

e = ElementTree.fromstring(stringx) #will wok fine!


问:
How to Ignore fields in a parent class when audditing with Javers
I have an entity which extends from anothers, like that:

```<code>public class House extends Building{
 public Integer idHouse
}

public class Building extends Structure{
}

public class Structure {
 public Integer field1;
}
</code>```

I need to audit changes in House objects but I don't want to include Structure.field1 field.
I tried this:

```<code>String skippedFields = ["field1"];
        EntityDefinition houseEntity =
                EntityDefinitionBuilder.entityDefinition(House.class)
                .withIdPropertyName("idHouse")
                .withIgnoredProperties(Arrays.asList(skippedFields))
                .build();

Javers javers = JaversBuilder.javers()
 .registerEntity(expedienteEntity)
    .registerJaversRepository(sqlRepository).build();
</code>```

But it seams to ignore the "IgnoeredPropertied". I also tried to map the structure class, but I can't because it doesn't have an id.

Any ideas on how can I ignore field1?
Thx!

答:
Can you show a failing test case for that issue?

I wrote the test (groovy) and everything looks fine
(your Entity has only one property - idHouse):

```<code>class StackCase extends Specification {

    class Structure {
        public Integer field1
    }

    class Building extends Structure{
    }

    class House extends Building{
        Integer idHouse
    }

    def "should use IgnoredProperties "(){
      given:
      def houseEntity =
              EntityDefinitionBuilder.entityDefinition(House)
                      .withIdPropertyName("idHouse")
                      .withIgnoredProperties(["field1"])
                      .build()

      def javers = JaversBuilder.javers()
              .registerEntity(houseEntity).build()

      def entityType = javers.getTypeMapping(House)
      println entityType.prettyPrint()

      expect:
      entityType.properties.size() == 1
    }
}
</code>```

output:

```<code>22:16:51.700 [main] INFO  org.javers.core.JaversBuilder - JaVers instance started in 723 ms
EntityType{
  baseType: class org.javers.core.StackCase$House
  typeName: org.javers.core.StackCase$House
  managedProperties:
    Field Integer idHouse; //declared in House
  idProperty: idHouse
}
</code>```

Body:
I have an entity which extends from anothers, like that:

public class House extends Building{
 public Integer idHouse
}

public class Building extends Structure{
}

public class Structure {
 public Integer field1;
}

I need to audit changes in House objects but I don't want to include Structure.field1 field.
I tried this:

String skippedFields = ["field1"];
        EntityDefinition houseEntity =
                EntityDefinitionBuilder.entityDefinition(House.class)
                .withIdPropertyName("idHouse")
                .withIgnoredProperties(Arrays.asList(skippedFields))
                .build();

Javers javers = JaversBuilder.javers()
 .registerEntity(expedienteEntity)
    .registerJaversRepository(sqlRepository).build();

But it seams to ignore the "IgnoeredPropertied". I also tried to map the structure class, but I can't because it doesn't have an id.

Any ideas on how can I ignore field1?
Thx!

Body:
Can you show a failing test case for that issue?

I wrote the test (groovy) and everything looks fine
(your Entity has only one property - idHouse):

class StackCase extends Specification {

    class Structure {
        public Integer field1
    }

    class Building extends Structure{
    }

    class House extends Building{
        Integer idHouse
    }

    def "should use IgnoredProperties "(){
      given:
      def houseEntity =
              EntityDefinitionBuilder.entityDefinition(House)
                      .withIdPropertyName("idHouse")
                      .withIgnoredProperties(["field1"])
                      .build()

      def javers = JaversBuilder.javers()
              .registerEntity(houseEntity).build()

      def entityType = javers.getTypeMapping(House)
      println entityType.prettyPrint()

      expect:
      entityType.properties.size() == 1
    }
}

output:

22:16:51.700 [main] INFO  org.javers.core.JaversBuilder - JaVers instance started in 723 ms
EntityType{
  baseType: class org.javers.core.StackCase$House
  typeName: org.javers.core.StackCase$House
  managedProperties:
    Field Integer idHouse; //declared in House
  idProperty: idHouse
}


问:
NullReferenceException only when building and running in android in unity
So I have the following code:

```<code>LongLat[0] = Convert.ToDouble(Input.location.lastData.latitude);
LongLat[1] = Convert.ToDouble(Input.location.lastData.longitude);
if (Input.location.status == LocationServiceStatus.Running) { print("Running"); }
print(LongLat[0]);
</code>```

I define LongLat as a public array:

```<code>public double[] LongLat = new double[2];
</code>```

When I run this in the unity editor I have no issues ( At a later point i redefine LongLat since obviously the pc has no GPS). But when I build and run on android I get a NullReferenceException on the fourth line, print(LongLat[0]), It is not clear to my why this is happening.

The location services are running.

Here is ouput from adb.

```<code>07-02 23:48:37.409 20555 20570 I Unity   : NullReferenceException: Object reference not set to an instance of an object
07-02 23:48:37.409 20555 20570 I Unity   :   at Location.GetLocation () [0x00065] in F:\Dropbox\Dropbox\UnityGames\Tagger\Assets\Location.cs:205
07-02 23:48:37.409 20555 20570 I Unity   :   at Location+<Start>c__Iterator0.MoveNext () [0x00233] in F:\Dropbox\Dropbox\UnityGames\Tagger\Assets\Location.cs:82
07-02 23:48:37.409 20555 20570 I Unity   :   at UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) [0x00028] in /Users/builduser/buildslave/unity/build/Runtime/Export/Coroutines.cs:17
</code>```

If I comment out

```<code>LongLat[0] = Input.location.lastData.latitude;
LongLat[1] = Input.location.lastData.longitude;
</code>```

and use:

```<code>LongLat[0] = 55.953251f;
LongLat[1] = 3.188267f;
</code>```

It works fine.

答:
So i managed to solve by not putting Input.location.lastData in a array but rather just using it directly.

I still don't know why putting in an array was so troublesome.

Body:
So I have the following code:

LongLat[0] = Convert.ToDouble(Input.location.lastData.latitude);
LongLat[1] = Convert.ToDouble(Input.location.lastData.longitude);
if (Input.location.status == LocationServiceStatus.Running) { print("Running"); }
print(LongLat[0]);

I define LongLat as a public array:

public double[] LongLat = new double[2];

When I run this in the unity editor I have no issues ( At a later point i redefine LongLat since obviously the pc has no GPS). But when I build and run on android I get a NullReferenceException on the fourth line, print(LongLat[0]), It is not clear to my why this is happening.

The location services are running.

Here is ouput from adb.

07-02 23:48:37.409 20555 20570 I Unity   : NullReferenceException: Object reference not set to an instance of an object
07-02 23:48:37.409 20555 20570 I Unity   :   at Location.GetLocation () [0x00065] in F:\Dropbox\Dropbox\UnityGames\Tagger\Assets\Location.cs:205
07-02 23:48:37.409 20555 20570 I Unity   :   at Location+<Start>c__Iterator0.MoveNext () [0x00233] in F:\Dropbox\Dropbox\UnityGames\Tagger\Assets\Location.cs:82
07-02 23:48:37.409 20555 20570 I Unity   :   at UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) [0x00028] in /Users/builduser/buildslave/unity/build/Runtime/Export/Coroutines.cs:17

If I comment out

LongLat[0] = Input.location.lastData.latitude;
LongLat[1] = Input.location.lastData.longitude;

and use:

LongLat[0] = 55.953251f;
LongLat[1] = 3.188267f;

It works fine.


问:
Remove duplicate file names from a listing, disregarding directory
I am running Linux and writing a BASH script.

I have a text file that has an absolute file path on each line. I have found that sometimes one of my text files will have an identical file but listed under a different path. I want to remove these lines that contain identical files such that the file is represented only once.

For instance, if I have:

```<code>/path/to/number1/file1.txt
/path/to/number1/file2.txt
/path/to/number1/file3.txt
/path/to/number2/file3.txt
</code>```

I want the resulting file to contain:

```<code>/path/to/number1/file1.txt
/path/to/number1/file2.txt
/path/to/number1/file3.txt
</code>```

The path length is variable (the file name cannot be guaranteed to be at field 4, for instance).

I have tried previous solutions to similar problems that use uniq, but uniq doesn't seem to provide an option to match the last field, nor does it allow one to set the delimiter. What are some solutions to this?

答:
With awk, you could do:

```<code>awk -F\/ '{ path=""; if ( path1[$NF] == "" ) { print $0;path1[$NF]=$0 } }' filename
</code>```

We build a variable path within awk. The filename is represented by $NF (the last field separated by /). We build an array of filenames (path1) with their associated paths. With each record/line in the file, this array is referenced to check if there is a path entry for the filename. If there is an entry, the record is ignored, hence stopping any duplication, otherwise the path is printed

Body:
I am running Linux and writing a BASH script.

I have a text file that has an absolute file path on each line. I have found that sometimes one of my text files will have an identical file but listed under a different path. I want to remove these lines that contain identical files such that the file is represented only once.

For instance, if I have:

/path/to/number1/file1.txt
/path/to/number1/file2.txt
/path/to/number1/file3.txt
/path/to/number2/file3.txt

I want the resulting file to contain:

/path/to/number1/file1.txt
/path/to/number1/file2.txt
/path/to/number1/file3.txt

The path length is variable (the file name cannot be guaranteed to be at field 4, for instance).

I have tried previous solutions to similar problems that use uniq, but uniq doesn't seem to provide an option to match the last field, nor does it allow one to set the delimiter. What are some solutions to this?

Body:
With awk, you could do:

awk -F\/ '{ path=""; if ( path1[$NF] == "" ) { print $0;path1[$NF]=$0 } }' filename

We build a variable path within awk. The filename is represented by $NF (the last field separated by /). We build an array of filenames (path1) with their associated paths. With each record/line in the file, this array is referenced to check if there is a path entry for the filename. If there is an entry, the record is ignored, hence stopping any duplication, otherwise the path is printed


问:
How to get call state of outgoing android call
I am originating a call from Android Studio. The code is as follows:
I want to get the state of the call at any point. The link: https://developer.android.com/reference/android/telecom/Call.html
shows the state of the call can be obtained by using the Class call.. SO if I use Call.getState() I should be able to get the current state. But I get the compilation error:
Error:(28, 20) error: Call() is not public in Call; cannot be accessed from outside package.  There are several call states defined in the enum: Dialing, Ringing, Connected, DIsconnected, Holding, etc.
When I run the code, it does make the call as I can see the screen of emulator making the call.

The developer guide does not provide any examples of using these classes.
Thank you for your help.

```<code>package com.example.ramesh.makeacall;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telecom.Call;
import android.telephony.*;

import android.util.Log;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Call call;
        call =  new Call();
        call();

    }
    private void call() {

        try {

            Intent callIntent = new Intent(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse("tel:5555551212"));
            System.out.println("====before startActivity====");
            startActivity(callIntent);

        } catch (ActivityNotFoundException e) {
            Log.e("helloAndroid","Call failed",e);
        }
    }

    }
</code>```

答:
Try to use like this(Haven't tried it though) -</p>

```<code>Call.Callback callback = new Call.Callback() {
    @Override
    public void onStateChanged(Call call, int state) {
        super.onStateChanged(call, state);
        if(state == Call.STATE_RINGING){
            //you code goes here
        }
    }
};
</code>```

Body:
I am originating a call from Android Studio. The code is as follows:
I want to get the state of the call at any point. The link: https://developer.android.com/reference/android/telecom/Call.html
shows the state of the call can be obtained by using the Class call.. SO if I use Call.getState() I should be able to get the current state. But I get the compilation error:
Error:(28, 20) error: Call() is not public in Call; cannot be accessed from outside package.  There are several call states defined in the enum: Dialing, Ringing, Connected, DIsconnected, Holding, etc.
When I run the code, it does make the call as I can see the screen of emulator making the call.

The developer guide does not provide any examples of using these classes.
Thank you for your help.

package com.example.ramesh.makeacall;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telecom.Call;
import android.telephony.*;

import android.util.Log;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Call call;
        call =  new Call();
        call();

    }
    private void call() {

        try {

            Intent callIntent = new Intent(Intent.ACTION_CALL);
            callIntent.setData(Uri.parse("tel:5555551212"));
            System.out.println("====before startActivity====");
            startActivity(callIntent);

        } catch (ActivityNotFoundException e) {
            Log.e("helloAndroid","Call failed",e);
        }
    }

    }

Body:
Try to use like this(Haven't tried it though) -

Call.Callback callback = new Call.Callback() {
    @Override
    public void onStateChanged(Call call, int state) {
        super.onStateChanged(call, state);
        if(state == Call.STATE_RINGING){
            //you code goes here
        }
    }
};


问:
How to get npm v5 install a dependency I just updated manually in package.json?
In my node.js project, I used to change version numbers of dependencies in the package.json file and then run npm install or npm update to install the configured versions.

However, since I'm using npm v5 this seems not to work anymore - neither an install nor update actually installs the updated versions. I'm running node.js v8.1.3 and npm v5.0.4.

Now I more and more resort to a terrible workaround to force npm to actually update depencencies, simply deleting and reinstalling all dependencies:

```<code>rm -rf node_modules package-lock.json && npm install
</code>```

This sort of feels like a bug rather than intended behavior. Any idea on how to get npm v5 working "normally"?

UPDATE:

looks like npm v5 indeed has a bug: npm update doesn't update devDependencies, see https://github.com/npm/npm/issues/16901

答:
This is a correct NPM@5.x behaviour. You should use a command line for manipulating with packages.

Case 1

You need the latest versions of all packages. Use npm update inside the folder.

Case 2

You need the latest version of package package-one and package-two. Use npm update package-one package-two.

Case 3
You need the specific version of package package-one and package-two. Use npm install package-one@a.b.c package-two@x.y.z.

At any case the command will update package.json, package-lock.json files and node_module folder.

Body:
In my node.js project, I used to change version numbers of dependencies in the package.json file and then run npm install or npm update to install the configured versions.

However, since I'm using npm v5 this seems not to work anymore - neither an install nor update actually installs the updated versions. I'm running node.js v8.1.3 and npm v5.0.4.

Now I more and more resort to a terrible workaround to force npm to actually update depencencies, simply deleting and reinstalling all dependencies:

rm -rf node_modules package-lock.json && npm install

This sort of feels like a bug rather than intended behavior. Any idea on how to get npm v5 working "normally"?

UPDATE:

looks like npm v5 indeed has a bug: npm update doesn't update devDependencies, see https://github.com/npm/npm/issues/16901


答: You can use regular expressions or RandomAccessFiles to get the data in the way you want.</p>

ContentLicense: CC BY-SA 2.5

Title: Parsing a log file in Java

Body:
All,

I have a log file with the below content.

Request from Centercord.
2010-12-14 12:42:13.724 [ 6796] ****************************
2010-12-14 12:42:13.724 [ 6796] 1111111111111111
2010-12-14 12:42:13.724 [ 6796]22222222222

Response from Centercord.
2010-12-14 12:42:21.802 [ 5960] 11111111111111
2010-12-14 12:42:21.802 [ 5960]  ffffffffffffffffffffffffffff
2010-12-14 12:42:21.802 [ 5960]  tttttttttttttttttttttttttttt

Request from Centercord.
2010-12-14 12:42:13.724 [ 6796] ****************************

I need to create two log files one is for storing all the Request details and the other one is for storing all the Response details. How can I parse this and prepare two log files?.

I need the below answer.

Log 1:

Request from Centercord.
2010-12-14 12:42:13.724 [ 6796] ****************************
2010-12-14 12:42:13.724 [ 6796] 1111111111111111
2010-12-14 12:42:13.724 [ 6796]22222222222

2010-12-14 12:42:13.724 [ 6796] ****************************

Log 2:

Response from Centercord.
2010-12-14 12:42:21.802 [ 5960] 11111111111111
2010-12-14 12:42:21.802 [ 5960]  ffffffffffffffffffffffffffff
2010-12-14 12:42:21.802 [ 5960]  tttttttttttttttttttttttttttt

Regards,
Kanagaraj


问:
Implement a CONTAINS (IN) in DB2?
I have a DB2 9.X table with a column named summary.

Here's an example.

SUMMARY

updated www.name1.do.com

Went from www.there2.do.com towww.here1.do.com

Backed up theretherethere.do.this.com and restored to hellothereworld.go.com

Those are three different rows.

In my program I've got a list of URLs. I need to search the database in a way that returns all the rows if the summary column CONTAINS any of the URLs in my list.

Thanks

答:
Store your URLs in a table (i.e. urls) and put '%' round your urls (i.e. %www.name1.do.com%) join both table using a cross join and select like this:</p>

```<code>select summary
from basetable, urls
where summary like urls.likecolumn
</code>```

Title: Implement a CONTAINS (IN) in DB2?

Body:
Store your URLs in a table (i.e. urls) and put '%' round your urls (i.e. %www.name1.do.com%) join both table using a cross join and select like this:

select summary
from basetable, urls
where summary like urls.likecolumn


问:
Mautic installation failed
I am installing Mautic(https://www.mautic.org) following the instructions.
And I got the following error on the first screen while installing it on localhost.

Warning:
  require(/Applications/MAMP/htdocs/mautic/app/../vendor/autoload.php):
  failed to open stream: No such file or directory in
  /Applications/MAMP/htdocs/mautic/app/autoload.php on line 15

Fatal error: require(): Failed opening required
  ‘/Applications/MAMP/htdocs/mautic/app/../vendor/autoload.php’
  (include_path=‘.:/Applications/MAMP/bin/php/php7.1.1/lib/php’) in
  /Applications/MAMP/htdocs/mautic/app/autoload.php on line 15

Environment : Mamp 4.1.1

PHP version : 7.1.1

MySQL version : 5.6.35

Looking for your help, thanks in advance.

答:
The question is what instructions are you following?

If you follow the instructions in the GitHub readme, read also the paragraph about where to download the production-ready package, because it seems that you are missing the dependencies in the vendor directory so you've probably downloaded the package directly from GitHub.

If you download that package, you'll need to run composer install to install the dependencies yourself, but it's easier and recommended to use the production package on production directly.

I'd recommend to follow this Basic Setup Guide.

Title: Mautic installation failed


问:
PHP extract (parsing) string
I'm using a regex to check a string for a certain format.

```<code>preg_match('/^\/answer ([1-9][0-9]*) (.{1,512})$/', $str, $hit, PREG_OFFSET_CAPTURE);
</code>```

Using this regex, the posted string needs to have this format:

/answer n x

n -> an integer > 0

x -> a string, 512 chars maximum

Now how to extract "n" and "x" the easiest way using PHP?
For example:

/answer 56 this is my sample text

Should lead to:

```<code>$value1 = 56;
$value2 = "this is my sample text";
</code>```

答:
Running this simple piece of code

```<code><?php
$hit = [];
$str = '/answer 56 this is my sample text';
preg_match('/^\/answer ([1-9][0-9]*) (.{1,512})$/', $str, $hit, PREG_OFFSET_CAPTURE);
echo'```',print_r($hit),'```';
</code>```

Will show you, that $hit has following values:

```<code>```Array
(
    [0] => Array
        (
            [0] => /answer 56 this is my sample text
            [1] => 0
        )

    [1] => Array
        (
            [0] => 56
            [1] => 8
        )

    [2] => Array
        (
            [0] => this is my sample text
            [1] => 11
        )

)
1```
</code>```

Here:

$hit[0][0] is full string that matches your pattern

$hit[1][0] is a substring that matches pattern [1-9][0-9]*

$hit[2][0] is a substring that matches pattern .{1,512}

So,

```<code>$value1 = $hit[1][0];
$value2 = $hit[2][0];
</code>```

Title: PHP extract (parsing) string

Body:
I'm using a regex to check a string for a certain format.

preg_match('/^\/answer ([1-9][0-9]*) (.{1,512})$/', $str, $hit, PREG_OFFSET_CAPTURE);

Using this regex, the posted string needs to have this format:

/answer n x

n -> an integer > 0

x -> a string, 512 chars maximum

Now how to extract "n" and "x" the easiest way using PHP?
For example:

/answer 56 this is my sample text

Should lead to:

$value1 = 56;
$value2 = "this is my sample text";

Body:
Running this simple piece of code

<?php
$hit = [];
$str = '/answer 56 this is my sample text';
preg_match('/^\/answer ([1-9][0-9]*) (.{1,512})$/', $str, $hit, PREG_OFFSET_CAPTURE);
echo'<pre>',print_r($hit),'</pre>';

Will show you, that $hit has following values:

<pre>Array
(
    [0] => Array
        (
            [0] => /answer 56 this is my sample text
            [1] => 0
        )

    [1] => Array
        (
            [0] => 56
            [1] => 8
        )

    [2] => Array
        (
            [0] => this is my sample text
            [1] => 11
        )

)
1</pre>

Here:

$hit[0][0] is full string that matches your pattern

$hit[1][0] is a substring that matches pattern [1-9][0-9]*

$hit[2][0] is a substring that matches pattern .{1,512}

So,

$value1 = $hit[1][0];
$value2 = $hit[2][0];