问:
kivy collide_point behavior not as expected
I want to create an application in which, three columns of labels appear side by side. Each column should be included in a BoxLayout. Scrolling the mouse wheel up and down, and depending on whether the cursor is located in the left or right BoxLayout, different events should be triggered and the labels of the left or right column should be changed accordingly.

This is the code I created:

```<code>from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout

matrix = [500, 500, 500, 5, 5]

class LoginScreen(BoxLayout):

    def __init__(self, **kwargs):
        super(LoginScreen, self).__init__(**kwargs)
        self.orientation = 'horizontal'

        self.container_L = MyLayout_L(orientation = 'vertical', on_touch_down = self.change_label_L)
        self.container_M = BoxLayout(orientation = 'vertical')
        self.container_R = MyLayout_R(orientation = 'vertical', on_touch_down = self.change_label_R)

        self.label_L0 = Label(text = '3', font_size = 30)
        self.label_L1 = Label(text = '4', font_size = 30)
        self.label_L2 = Label(text = '5', font_size = 30)
        self.label_L3 = Label(text = '6', font_size = 30)
        self.label_L4 = Label(text = '7', font_size = 30)

        label_L_list = [self.label_L0, self.label_L1, self.label_L2, self.label_L3, self.label_L4]
        for item in label_L_list:
            self.container_L.add_widget(item)

        self.label_M0 = Label(text = '500', font_size = 30)
        label_M_list = [self.label_M0]
        for item in label_M_list:
            self.container_M.add_widget(item)

        self.label_R0 = Label(text = '3', font_size = 30)
        self.label_R1 = Label(text = '4', font_size = 30)
        self.label_R2 = Label(text = '5', font_size = 30)
        self.label_R3 = Label(text = '6', font_size = 30)
        self.label_R4 = Label(text = '7', font_size = 30)

        label_R_list = [self.label_R0, self.label_R1, self.label_R2, self.label_R3, self.label_R4]
        for item in label_R_list:
            self.container_R.add_widget(item)

        self.add_widget(self.container_L)
        self.add_widget(self.container_M)
        self.add_widget(self.container_R)

    def change_label_L(self, instance, Label):
        print 'L ', matrix
        counter = matrix[3]
        self.label_L0.text = str(counter-2)
        self.label_L1.text = str(counter-1)
        self.label_L2.text = str(counter)
        self.label_L3.text = str(counter+1)
        self.label_L4.text = str(counter+2)

    def change_label_R(self, instance, BoxLayout):
        print 'R ', matrix
        counter = matrix[4]
        self.label_R0.text = str(counter-2)
        self.label_R1.text = str(counter-1)
        self.label_R2.text = str(counter)
        self.label_R3.text = str(counter+1)
        self.label_R4.text = str(counter+2)

class MyLayout_L(BoxLayout):
    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            if touch.button == 'scrollup':
                self.calc_plus()
            elif touch.button == 'scrolldown':
                self.calc_minus()
    def calc_plus(self):
        matrix[3] += 1
    def calc_minus(self):
        matrix[3] -= 1

class MyLayout_R(BoxLayout):
    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            if touch.button == 'scrollup':
                self.calc_plus2()
            elif touch.button == 'scrolldown':
                self.calc_minus2()
    def calc_plus2(self):
        matrix[4] += 1
    def calc_minus2(self):
        matrix[4] -= 1

class MyApp(App):
    def build(self):
        return LoginScreen()

if __name__ == '__main__':
    MyApp().run()
</code>```

Now, the problem is that the code has some strange behavior. The classes MyLayout_R and MyLayout_L have been created in order to recognize whether the cursor of the mouse is located to the left of right BoxLayout, and make the on_touch_down events trigger the change_label_R or change_label_L functions.

Yet, in the terminal I see that both functions are triggered simultaneously (see the print 'L ', matrix and print 'R ', matrix lines in the code which are both executed while scrolling).

Also, the labels in the BoxLayouts are changing, but not exactly as planned.

When I change the location of the cursor, the left BoxLayout label
will always skip a step (compare the terminal output and the labels).

Also, when changing the location, the first scrolling will trigger
the old Boxlayout and the next scrollings will trigger the present
one.

Since collide_point checks if the cursor is located inside the area of the widget at hand, why does scrolling affects both BoxLayouts? I guess that I miss something important here, thus any help would be appreciated.

答:
Here is your code, edited to only have one on_touch_down() method for each of your MyLayout classes.</p>

```<code>from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout

matrix = [500, 500, 500, 5, 5]

class LoginScreen(BoxLayout):

    def __init__(self, **kwargs):
        super(LoginScreen, self).__init__(**kwargs)
        self.orientation = 'horizontal'

        self.container_L = MyLayout_L(orientation = 'vertical', on_touch_down = self.change_label_L)
        self.container_M = BoxLayout(orientation = 'vertical')
        self.container_R = MyLayout_R(orientation = 'vertical', on_touch_down = self.change_label_R)

        self.label_L0 = Label(text = '3', font_size = 30)
        self.label_L1 = Label(text = '4', font_size = 30)
        self.label_L2 = Label(text = '5', font_size = 30)
        self.label_L3 = Label(text = '6', font_size = 30)
        self.label_L4 = Label(text = '7', font_size = 30)

        label_L_list = [self.label_L0, self.label_L1, self.label_L2, self.label_L3, self.label_L4]
        for item in label_L_list:
            self.container_L.add_widget(item)

        self.label_M0 = Label(text = '500', font_size = 30)
        label_M_list = [self.label_M0]
        for item in label_M_list:
            self.container_M.add_widget(item)

        self.label_R0 = Label(text = '3', font_size = 30)
        self.label_R1 = Label(text = '4', font_size = 30)
        self.label_R2 = Label(text = '5', font_size = 30)
        self.label_R3 = Label(text = '6', font_size = 30)
        self.label_R4 = Label(text = '7', font_size = 30)

        label_R_list = [self.label_R0, self.label_R1, self.label_R2, self.label_R3, self.label_R4]
        for item in label_R_list:
            self.container_R.add_widget(item)

        self.add_widget(self.container_L)
        self.add_widget(self.container_M)
        self.add_widget(self.container_R)

    def change_label_L(self, instance, touch):
        if instance.collide_point(*touch.pos):
            print 'L ', matrix
            counter = matrix[3]
            self.label_L0.text = str(counter-2)
            self.label_L1.text = str(counter-1)
            self.label_L2.text = str(counter)
            self.label_L3.text = str(counter+1)
            self.label_L4.text = str(counter+2)
            if touch.button == 'scrollup':
                instance.calc_plus()
            elif touch.button == 'scrolldown':
                instance.calc_minus()

    def change_label_R(self, instance, touch):
        if instance.collide_point(*touch.pos):
            print 'R ', matrix
            counter = matrix[4]
            self.label_R0.text = str(counter-2)
            self.label_R1.text = str(counter-1)
            self.label_R2.text = str(counter)
            self.label_R3.text = str(counter+1)
            self.label_R4.text = str(counter+2)
            if touch.button == 'scrollup':
                instance.calc_plus2()
            elif touch.button == 'scrolldown':
                instance.calc_minus2()

class MyLayout_L(BoxLayout):
    def calc_plus(self):
        matrix[3] += 1
    def calc_minus(self):
        matrix[3] -= 1

class MyLayout_R(BoxLayout):
    def calc_plus2(self):
        matrix[4] += 1
    def calc_minus2(self):
        matrix[4] -= 1

class MyApp(App):
    def build(self):
        return LoginScreen()

if __name__ == '__main__':
    MyApp().run()
</code>```

Body:
I want to create an application in which, three columns of labels appear side by side. Each column should be included in a BoxLayout. Scrolling the mouse wheel up and down, and depending on whether the cursor is located in the left or right BoxLayout, different events should be triggered and the labels of the left or right column should be changed accordingly.

This is the code I created:

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout

matrix = [500, 500, 500, 5, 5]

class LoginScreen(BoxLayout):

    def __init__(self, **kwargs):
        super(LoginScreen, self).__init__(**kwargs)
        self.orientation = 'horizontal'

        self.container_L = MyLayout_L(orientation = 'vertical', on_touch_down = self.change_label_L)
        self.container_M = BoxLayout(orientation = 'vertical')
        self.container_R = MyLayout_R(orientation = 'vertical', on_touch_down = self.change_label_R)

        self.label_L0 = Label(text = '3', font_size = 30)
        self.label_L1 = Label(text = '4', font_size = 30)
        self.label_L2 = Label(text = '5', font_size = 30)
        self.label_L3 = Label(text = '6', font_size = 30)
        self.label_L4 = Label(text = '7', font_size = 30)

        label_L_list = [self.label_L0, self.label_L1, self.label_L2, self.label_L3, self.label_L4]
        for item in label_L_list:
            self.container_L.add_widget(item)

        self.label_M0 = Label(text = '500', font_size = 30)
        label_M_list = [self.label_M0]
        for item in label_M_list:
            self.container_M.add_widget(item)

        self.label_R0 = Label(text = '3', font_size = 30)
        self.label_R1 = Label(text = '4', font_size = 30)
        self.label_R2 = Label(text = '5', font_size = 30)
        self.label_R3 = Label(text = '6', font_size = 30)
        self.label_R4 = Label(text = '7', font_size = 30)

        label_R_list = [self.label_R0, self.label_R1, self.label_R2, self.label_R3, self.label_R4]
        for item in label_R_list:
            self.container_R.add_widget(item)

        self.add_widget(self.container_L)
        self.add_widget(self.container_M)
        self.add_widget(self.container_R)

    def change_label_L(self, instance, Label):
        print 'L ', matrix
        counter = matrix[3]
        self.label_L0.text = str(counter-2)
        self.label_L1.text = str(counter-1)
        self.label_L2.text = str(counter)
        self.label_L3.text = str(counter+1)
        self.label_L4.text = str(counter+2)

    def change_label_R(self, instance, BoxLayout):
        print 'R ', matrix
        counter = matrix[4]
        self.label_R0.text = str(counter-2)
        self.label_R1.text = str(counter-1)
        self.label_R2.text = str(counter)
        self.label_R3.text = str(counter+1)
        self.label_R4.text = str(counter+2)

class MyLayout_L(BoxLayout):
    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            if touch.button == 'scrollup':
                self.calc_plus()
            elif touch.button == 'scrolldown':
                self.calc_minus()
    def calc_plus(self):
        matrix[3] += 1
    def calc_minus(self):
        matrix[3] -= 1

class MyLayout_R(BoxLayout):
    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            if touch.button == 'scrollup':
                self.calc_plus2()
            elif touch.button == 'scrolldown':
                self.calc_minus2()
    def calc_plus2(self):
        matrix[4] += 1
    def calc_minus2(self):
        matrix[4] -= 1

class MyApp(App):
    def build(self):
        return LoginScreen()

if __name__ == '__main__':
    MyApp().run()

Now, the problem is that the code has some strange behavior. The classes MyLayout_R and MyLayout_L have been created in order to recognize whether the cursor of the mouse is located to the left of right BoxLayout, and make the on_touch_down events trigger the change_label_R or change_label_L functions.

Yet, in the terminal I see that both functions are triggered simultaneously (see the print 'L ', matrix and print 'R ', matrix lines in the code which are both executed while scrolling).

Also, the labels in the BoxLayouts are changing, but not exactly as planned.

When I change the location of the cursor, the left BoxLayout label
will always skip a step (compare the terminal output and the labels).

Also, when changing the location, the first scrolling will trigger
the old Boxlayout and the next scrollings will trigger the present
one.

Since collide_point checks if the cursor is located inside the area of the widget at hand, why does scrolling affects both BoxLayouts? I guess that I miss something important here, thus any help would be appreciated.

Body:
Here is your code, edited to only have one on_touch_down() method for each of your MyLayout classes.

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout

matrix = [500, 500, 500, 5, 5]

class LoginScreen(BoxLayout):

    def __init__(self, **kwargs):
        super(LoginScreen, self).__init__(**kwargs)
        self.orientation = 'horizontal'

        self.container_L = MyLayout_L(orientation = 'vertical', on_touch_down = self.change_label_L)
        self.container_M = BoxLayout(orientation = 'vertical')
        self.container_R = MyLayout_R(orientation = 'vertical', on_touch_down = self.change_label_R)

        self.label_L0 = Label(text = '3', font_size = 30)
        self.label_L1 = Label(text = '4', font_size = 30)
        self.label_L2 = Label(text = '5', font_size = 30)
        self.label_L3 = Label(text = '6', font_size = 30)
        self.label_L4 = Label(text = '7', font_size = 30)

        label_L_list = [self.label_L0, self.label_L1, self.label_L2, self.label_L3, self.label_L4]
        for item in label_L_list:
            self.container_L.add_widget(item)

        self.label_M0 = Label(text = '500', font_size = 30)
        label_M_list = [self.label_M0]
        for item in label_M_list:
            self.container_M.add_widget(item)

        self.label_R0 = Label(text = '3', font_size = 30)
        self.label_R1 = Label(text = '4', font_size = 30)
        self.label_R2 = Label(text = '5', font_size = 30)
        self.label_R3 = Label(text = '6', font_size = 30)
        self.label_R4 = Label(text = '7', font_size = 30)

        label_R_list = [self.label_R0, self.label_R1, self.label_R2, self.label_R3, self.label_R4]
        for item in label_R_list:
            self.container_R.add_widget(item)

        self.add_widget(self.container_L)
        self.add_widget(self.container_M)
        self.add_widget(self.container_R)

    def change_label_L(self, instance, touch):
        if instance.collide_point(*touch.pos):
            print 'L ', matrix
            counter = matrix[3]
            self.label_L0.text = str(counter-2)
            self.label_L1.text = str(counter-1)
            self.label_L2.text = str(counter)
            self.label_L3.text = str(counter+1)
            self.label_L4.text = str(counter+2)
            if touch.button == 'scrollup':
                instance.calc_plus()
            elif touch.button == 'scrolldown':
                instance.calc_minus()

    def change_label_R(self, instance, touch):
        if instance.collide_point(*touch.pos):
            print 'R ', matrix
            counter = matrix[4]
            self.label_R0.text = str(counter-2)
            self.label_R1.text = str(counter-1)
            self.label_R2.text = str(counter)
            self.label_R3.text = str(counter+1)
            self.label_R4.text = str(counter+2)
            if touch.button == 'scrollup':
                instance.calc_plus2()
            elif touch.button == 'scrolldown':
                instance.calc_minus2()

class MyLayout_L(BoxLayout):
    def calc_plus(self):
        matrix[3] += 1
    def calc_minus(self):
        matrix[3] -= 1

class MyLayout_R(BoxLayout):
    def calc_plus2(self):
        matrix[4] += 1
    def calc_minus2(self):
        matrix[4] -= 1

class MyApp(App):
    def build(self):
        return LoginScreen()

if __name__ == '__main__':
    MyApp().run()


来源: stackexchange

问:
showDialog barrierDismissible and the return value
If I'm trying to get an answer from the user, I might use a dialog and I might want to make it user friendly incase the user wants to cancel. In such a case I'd use barrierDismissible: true (which I think is the default for showDialog anyways.)

If I call showDialog in that way, and I'm taking its return value, as the answer from the user, how do identify the case where the user clicked on the background to dismiss the dialog. In a case such as this I would want to ignore the return value of showDialog rather than think the user intentionally chose not to select or type anything (such as in a TextField).

答:
Seem I've identified the answer with a little experimentation.

showDialog returns null when you dismiss the dialog. If your using a TextField, that text field doesn't give you a null value for an empty input, it gives you a zero length string.

So its easy to identify the 2 different scenarios.

ContentLicense: CC BY-SA 3.0


问:
Foreach loop with double condition in java8 using lambda
I have an exercise with this description:

```<code>1122 produces a sum of 3 (1 + 2) because the first digit (1) matches the second digit and the third digit (2) matches the fourth digit.
1111 produces 4 because each digit (all 1) matches the next.
1234 produces 0 because no digit matches the next.
91212129 produces 9 because the only digit that matches the next one is the last digit, 9.
</code>```

I have written the following code:

```<code>String inputString = "1111"; // taking this number as example

int sum = 0;
for (int i = 0; i < inputString.length() - 1; i++) {
    if (inputString.charAt(i) == inputString.charAt(i + 1)) {
        sum += Integer.parseInt(String.valueOf(inputString.charAt(i)));
    }
    if (i + 2 == inputString.length() - 1) {
        if (inputString.charAt(i + 2) == inputString.charAt(0)) {
            sum += Integer.parseInt(String.valueOf(inputString.charAt(i + 2)));
        }
    }
}
</code>```

The result of sum is 4, which is correct.

Now I'm trying to write the same one in Java8 using lambda but I can't figure out how to get the last condition inside my stream.

This is how far I got:

```<code>Integer sum = IntStream.range(0, (inputString.length() - 1)).boxed()
                .filter(j -> inputString.charAt(j) == inputString.charAt(j + 1))
                .mapToInt(i -> Integer.parseInt(String.valueOf(inputString.charAt(i)))).sum();
</code>```

答:
Seems like I have enormously overcomplicated my previous answer. Considering this is just for exercise purposes then you could just use a lambda statement block:

```<code>int sum1 = IntStream.range(0, inputString.length() - 1)
                .map(i -> {
                       int tempSum = 0;
                       if(areEqual(inputString, i, i + 1))
                             tempSum += mapper(inputString, i);

                       if (i + 2 == inputString.length() - 1)
                           if(areEqual(inputString, i + 2, 0))
                               tempSum += mapper(inputString, i + 2);

                       return tempSum;
                   }
                )
                .sum();
</code>```

helper functions:

```<code>public static int mapper(String value, int index){
    return Integer.parseInt(String.valueOf(value.charAt(index)));
}

public static boolean areEqual(String inputString, int firstIndex, int secondIndex){
      return inputString.charAt(firstIndex) == inputString.charAt(secondIndex);
}
</code>```

Body:
I have an exercise with this description:

1122 produces a sum of 3 (1 + 2) because the first digit (1) matches the second digit and the third digit (2) matches the fourth digit.
1111 produces 4 because each digit (all 1) matches the next.
1234 produces 0 because no digit matches the next.
91212129 produces 9 because the only digit that matches the next one is the last digit, 9.

I have written the following code:

String inputString = "1111"; // taking this number as example

int sum = 0;
for (int i = 0; i < inputString.length() - 1; i++) {
    if (inputString.charAt(i) == inputString.charAt(i + 1)) {
        sum += Integer.parseInt(String.valueOf(inputString.charAt(i)));
    }
    if (i + 2 == inputString.length() - 1) {
        if (inputString.charAt(i + 2) == inputString.charAt(0)) {
            sum += Integer.parseInt(String.valueOf(inputString.charAt(i + 2)));
        }
    }
}

The result of sum is 4, which is correct.

Now I'm trying to write the same one in Java8 using lambda but I can't figure out how to get the last condition inside my stream.

This is how far I got:

Integer sum = IntStream.range(0, (inputString.length() - 1)).boxed()
                .filter(j -> inputString.charAt(j) == inputString.charAt(j + 1))
                .mapToInt(i -> Integer.parseInt(String.valueOf(inputString.charAt(i)))).sum();

Body:
Seems like I have enormously overcomplicated my previous answer. Considering this is just for exercise purposes then you could just use a lambda statement block:

int sum1 = IntStream.range(0, inputString.length() - 1)
                .map(i -> {
                       int tempSum = 0;
                       if(areEqual(inputString, i, i + 1))
                             tempSum += mapper(inputString, i);

                       if (i + 2 == inputString.length() - 1)
                           if(areEqual(inputString, i + 2, 0))
                               tempSum += mapper(inputString, i + 2);

                       return tempSum;
                   }
                )
                .sum();

helper functions:

public static int mapper(String value, int index){
    return Integer.parseInt(String.valueOf(value.charAt(index)));
}

public static boolean areEqual(String inputString, int firstIndex, int secondIndex){
      return inputString.charAt(firstIndex) == inputString.charAt(secondIndex);
}


问:
Detect html table cell value change
How am I able to detect change in html table on any cell? Currently I can only detect change in one cell, I could repeat the same code for all table cell ID but wondering if there is an efficient way.

Note that I have other inputs in my form and only wish to detect ones relevant to the table below:

Code:

html:

```<code><table id="myTable" border="1" data-mini="true" >
<tbody>
<tr>
<th>Drawing Number</th>
<th>Description</th>
<th>Sheet Number</th>
<th>Issue</th>
</tr>
<tr>
<td><input name="drawing-n-1" id="drawing-n-1" type="text" /></td>
<td><input name="drawing-d-1" type="text" /></td>
<td><input name="drawing-s-1" type="text" /></td>
<td><input name="drawing-i-1" type="text" /></td>
<td><input name="drawing-n-2" id="drawing-n-2" type="text" /></td>
<td><input name="drawing-d-2" type="text" /></td>
<td><input name="drawing-s-2" type="text" /></td>
<td><input name="drawing-i-2" type="text" /></td>
</tr>
</tbody>
</table>
</code>```

javascript:

```<code>var drawing_input = 'drawing-n-1';
$('#'+drawing_input).change(function(e) {
    alert("aha");
    var data = $('#'+drawing_input).val();
});
</code>```

答:
With jQuery you needn't be so specific. Just change the selector to listen for all <input>s.

```<code>$('input').on('change',
</code>```

This selector will pick every <input> on the page.

Or if you need to isolate the table's inputs, add the table's id in the selector.

```<code>$('#xTable input').on('change'...
</code>```

This selector will pick every <input> within the table.

Saw that you needed only to listen for inputs with ids. If so then you can use the brackets and ^=:

```<code>$("#xTable input[id^='drawing-n-']").on('change'....
</code>```

This means get any <input> that has an [ id that starts ^= with "drawing-n-" ] which is in a
 with the id of xTable.

That selector will pick only input#drawing-n-1 and input#drawing-n-2

Demo

$("#xTable input[id^='drawing-n-']").on('change', function(e) {
  var data = $(this).val();
  console.log(data);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="xTable" border="1" data-mini="true">
  <tbody>
    <tr>
      <th>Drawing Number</th>
      <th>Description</th>
      <th>Sheet Number</th>
      <th>Issue</th>

    </tr>
    <tr>
      <td><input name="drawing-n-1" id="drawing-n-1" type="text" /></td>
      <td><input name="drawing-d-1" type="text" /></td>
      <td><input name="drawing-s-1" type="text" /></td>
      <td><input name="drawing-i-1" type="text" /></td>
      <td><input name="drawing-n-2" id="drawing-n-2" type="text" /></td>
      <td><input name="drawing-d-2" type="text" /></td>
      <td><input name="drawing-s-2" type="text" /></td>
      <td><input name="drawing-i-2" type="text" /></td>
    </tr>
  </tbody>
</table>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Title: Detect html table cell value change

Body:
How am I able to detect change in html table on any cell? Currently I can only detect change in one cell, I could repeat the same code for all table cell ID but wondering if there is an efficient way.

Note that I have other inputs in my form and only wish to detect ones relevant to the table below:

Code:

html:

Drawing Number
Description
Sheet Number
Issue

<input name="drawing-n-1" id="drawing-n-1" type="text" />
<input name="drawing-d-1" type="text" />
<input name="drawing-s-1" type="text" />
<input name="drawing-i-1" type="text" />
<input name="drawing-n-2" id="drawing-n-2" type="text" />
<input name="drawing-d-2" type="text" />
<input name="drawing-s-2" type="text" />
<input name="drawing-i-2" type="text" />

javascript:

var drawing_input = 'drawing-n-1';
$('#'+drawing_input).change(function(e) {
    alert("aha");
    var data = $('#'+drawing_input).val();
});

Body:
With jQuery you needn't be so specific. Just change the selector to listen for all <input>s.

$('input').on('change',

This selector will pick every <input> on the page.

Or if you need to isolate the table's inputs, add the table's id in the selector.

$('#xTable input').on('change'...

This selector will pick every <input> within the table.

Saw that you needed only to listen for inputs with ids. If so then you can use the brackets and ^=:

$("#xTable input[id^='drawing-n-']").on('change'....

This means get any <input> that has an [ id that starts ^= with "drawing-n-" ] which is in a <table> with the id of xTable.

That selector will pick only input#drawing-n-1 and input#drawing-n-2

Demo

$("#xTable input[id^='drawing-n-']").on('change', function(e) {
  var data = $(this).val();
  console.log(data);
});

<table id="xTable" border="1" data-mini="true">
  <tbody>
    <tr>
      <th>Drawing Number</th>
      <th>Description</th>
      <th>Sheet Number</th>
      <th>Issue</th>

    </tr>
    <tr>
      <td><input name="drawing-n-1" id="drawing-n-1" type="text" /></td>
      <td><input name="drawing-d-1" type="text" /></td>
      <td><input name="drawing-s-1" type="text" /></td>
      <td><input name="drawing-i-1" type="text" /></td>
      <td><input name="drawing-n-2" id="drawing-n-2" type="text" /></td>
      <td><input name="drawing-d-2" type="text" /></td>
      <td><input name="drawing-s-2" type="text" /></td>
      <td><input name="drawing-i-2" type="text" /></td>
    </tr>
  </tbody>
</table>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
Is there a simple way to copy a repository fragment from CodeCommit to S3?
I use a combination of a static code generator and webpack to generate a static site, which I then manually copy to S3 (to further expose it though CloudFront) via the AWS cli.

I manage my code with git locally and on a local git server, and was considering a move to CodeCommit to have a complete integration with AWS. The first step would be to synchronize the dest folder of my repo with an S3 bucket.

I was hoping for a simple integration ("copy upon a push event") but did not find any. I saw a few discussions on that subject with a recent blog post being the closest to what I want to achieve.

It is however a complicated process, involving mysterious setups across three services.

Is there something I missed? A more obvious solution that the answer to a previous SO question?

答:
Are you currently a CodePipeline user?  The simplest way would probably be to set up a pipeline with CodeCommit as a source action (CodePipeline automatically uploads all artifacts to S3, and you can specify the bucket on pipeline creation); however, I don't know if that's as simple a solution as you're hoping to find, since it involves configuring at least one other service.

-Paige@AWS


问:
Scrollbar overlaps content on IE/Edge
I would like to have an horizontal scrollbar and no vertical scroll on a root container and vertical scrollbar on sub-containers and no horizontal scrollbar.
Compatibility needed : IE, Edge, Chrome, FF. (Latest versions)

```<code><rootcontainer> => horizontal scroll
 <subcontainer1> => vertical scroll
  <data></data>
 </subcontainer1>
 <subcontainer2> => vertical scroll
   <data></data>
 </subcontainer2>
</rootcontainer>
</code>```

No problem with the scroll on Chrome and FF, but on IE11 and Edge, the scroll of the root container is overlapping with the content of the sub container.

Note: each subcontainer must have a width equals to 50% of the subcontainer.

Here is my problem in a fiddle.

What did I missed to make it work ?

EDIT :

Windows 10 Edge

Windows 10 IE

Please note that on IE11, the borders are not visibles.
The bug is more visible on Edge

答:
Are you using windows 8+? Can post a screenshot of the issue?

(I'm using IE11 and Windows 7 and it looks fine)

There is an issue (or design feature, depending on how you look at it) with IE10+ on Windows 8+ where the scrollbar overlays the content. Try the following and let me know if it fixes your problem.

```<code>.document,
.meta,
.viewer,
.other-doc {
    -ms-overflow-style: scrollbar;
}
</code>```

Check out https://msdn.microsoft.com/en-us/library/mt712067(v=vs.85).aspx

Title: Scrollbar overlaps content on IE/Edge

Body:
I would like to have an horizontal scrollbar and no vertical scroll on a root container and vertical scrollbar on sub-containers and no horizontal scrollbar.
Compatibility needed : IE, Edge, Chrome, FF. (Latest versions)

<rootcontainer> => horizontal scroll
 <subcontainer1> => vertical scroll
  <data></data>
 </subcontainer1>
 <subcontainer2> => vertical scroll
   <data></data>
 </subcontainer2>
</rootcontainer>

No problem with the scroll on Chrome and FF, but on IE11 and Edge, the scroll of the root container is overlapping with the content of the sub container.

Note: each subcontainer must have a width equals to 50% of the subcontainer.

Here is my problem in a fiddle.

What did I missed to make it work ?

EDIT :

Windows 10 Edge

Windows 10 IE

Please note that on IE11, the borders are not visibles.
The bug is more visible on Edge

Body:
Are you using windows 8+? Can post a screenshot of the issue?

(I'm using IE11 and Windows 7 and it looks fine)

There is an issue (or design feature, depending on how you look at it) with IE10+ on Windows 8+ where the scrollbar overlays the content. Try the following and let me know if it fixes your problem.

.document,
.meta,
.viewer,
.other-doc {
    -ms-overflow-style: scrollbar;
}

Check out https://msdn.microsoft.com/en-us/library/mt712067(v=vs.85).aspx


问:
NGINX restriction I.P not working
I have a problem with my configuration, I use nginx/1.10.3, php5-fpm.

this is my default config location :

```<code>location / {
  try_files $uri $uri/ =404;
  allow 1.2.3.4; #my ip
  allow 127.0.0.1;
  allow 11.22.33.44; #server ip
  deny all;
}
</code>```

when I try to access 11.22.33.44 i have an 403 Forbidden:

```<code>2017/03/08 16:30:25 [error] 340#340: *3 access forbidden by rule, client: 1.2.3.4, server: _, request: "GET / HTTP/1.1", host: "11.22.33.44"
</code>```

Thanks for your help !

Resolve, solution :

```<code>location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
        allow 127.0.0.1;
        allow 1.2.3.4; #my ip
        deny all;
}
</code>```

答:
Checking you .conf file,Make sure that the automatic index is open, or there will be this error</p>

```<code> autoindex on;
</code>```

Title: NGINX restriction I.P not working

Body:
I have a problem with my configuration, I use nginx/1.10.3, php5-fpm.

this is my default config location :

location / {
  try_files $uri $uri/ =404;
  allow 1.2.3.4; #my ip
  allow 127.0.0.1;
  allow 11.22.33.44; #server ip
  deny all;
}

when I try to access 11.22.33.44 i have an 403 Forbidden:

2017/03/08 16:30:25 [error] 340#340: *3 access forbidden by rule, client: 1.2.3.4, server: _, request: "GET / HTTP/1.1", host: "11.22.33.44"

Thanks for your help !

Resolve, solution :

location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
        allow 127.0.0.1;
        allow 1.2.3.4; #my ip
        deny all;
}

Body:
Checking you .conf file,Make sure that the automatic index is open, or there will be this error

 autoindex on;


问:
Return in a map only when promises resolve
I am using loadash map function to do some structuring of data. The data returns a set of ids for which i need to query the db and add the result to the map and then return but the data is returned later and my function returns first. How to make the return of map wait and then return in function.

```<code>let result = _.chain(value)
        .groupBy('pubId')
        .pairs()
        .map(function(currentItem) {
          let item =  _.object(_.zip(['ID', 'targetting'], currentItem));
          propsToBeDeleted.forEach(function(prop) {
            item.targetting.forEach(d => {
              item.publishername = d.RTB.name;
              item.type = d.type;
              delete d[prop];
            });
          });
          item.targetting.map(d => {
            if (d.type == 15) {
              d.name = Object.keys(JSON.parse(d.value));
              d.value = Object.values(JSON.parse(d.value))[0];
              item.dspIds = [];
            }
            if (d.type == 16) {
              let value = JSON.parse(d.value);
              d.name = Object.keys(JSON.parse(d.value)).filter(d => d != 'profileId');
              d.value = value;
              item.dspIds = d.value.profileId;
              dspAccount.find({where: {id: 139}}, (err, data) => {
                // async call wait here to get data and attach to item
                 item.x = data ;
              });
              delete d.value.profileId;
              d.value = JSON.stringify(d.value);
            }
          });
          return item;
        })
        .value();
</code>```

I also tried using promises

```<code>promises.push(new Promise((resolve, reject) => {
        if (data.id) {
          XX.upsertWithWhere({id: data.id}, payload, (err, data) => {
            if (err) {
              return reject(err);
            }
            return resolve(data);
          });
        }
      }));
    });
    Promise.all(promises).then((data) => {
      callback(null, data);
    }, err => {
      callback(err);
    });
</code>```

Update
i have already listed the promise .all method that doesnot work . So it cannot be called duplicate

答:
Things are slightly tricky because you have an outer .map() and an inner .map(), containing an asynchronous element.

The asynchronous element effectively makes the whole thing asynchronous, requiring that :

the array of Promises generated by the inner .map() is aggregated with Promise.all(), and the aggregate Promise returned to the outer .map().

the array of Promises generated by the outer .map() is aggregated with Promise.all().

the results (an array of items) is available only via a chained .then().

First, to make the main code block simpler and easier to read, create a promisified version of dspAccount.findAsync().

```<code>dspAccount.findAsync = function(query) {
    return new Promise(function(resolve, reject) {
        dspAccount.find(query, (err, data) => {
            if(err) {
                reject(err);
            } else {
                resolve(data);
            }
        });
    });
}
</code>```

Then the main code block can be written as follows :

```<code>let outerPromises = _.chain(value)
.groupBy('pubId')
.pairs()
.map(function(currentItem) {
    let item = _.object(_.zip(['ID', 'targetting'], currentItem));
    item.targetting.forEach(d => {
        item.publishername = d.RTB.name;
        item.type = d.type;
        propsToBeDeleted.forEach(function(prop) {
            delete d[prop];
        });
    });
    let innerPromises = item.targetting.map(d => {
        let value = JSON.parse(d.value);
        if (d.type == 15) { // synchronous - `innerPromises` receives a null
            item.dspIds = []; //
            d.name = Object.keys(value);
            d.value = Object.values(value)[0];
            return null;
        }
        if (d.type == 16) { // asynchronous - `innerPromises` receives a Promise
            return dspAccount.findAsync({where: {id: 139}})
            .then(data => {
                d.name = Object.keys(value).filter(d => d != 'profileId');
                item.dspIds = value.profileId;
                delete value.profileId;
                item.x = data;
                d.value = JSON.stringify(value);
            });
        }
    });
    return Promise.all(innerPromises).then(() => item); // aggregate inner promises and return
})
.value(); //  returns the outerPromises array

Promise.all(outerPromises)  // aggregate outer promises
.then(items => {
    // do stuff with items here
})
.catch(error => {
    // something went wrong
    // log/display error
    // take remedial action as required
});
</code>```

I expect there's still some work to do. It doesn't look right that item should be mutated in the item.targetting.map() loop. The last element of item.targetting to deliver its result (synch or asynch) will determine the composition of item. That may not be what you want. If it is what you want, then more control will need to be exercised to ensure that the last result delivered is the result arising from the final element of item.targetting.

Body:
I am using loadash map function to do some structuring of data. The data returns a set of ids for which i need to query the db and add the result to the map and then return but the data is returned later and my function returns first. How to make the return of map wait and then return in function.

let result = _.chain(value)
        .groupBy('pubId')
        .pairs()
        .map(function(currentItem) {
          let item =  _.object(_.zip(['ID', 'targetting'], currentItem));
          propsToBeDeleted.forEach(function(prop) {
            item.targetting.forEach(d => {
              item.publishername = d.RTB.name;
              item.type = d.type;
              delete d[prop];
            });
          });
          item.targetting.map(d => {
            if (d.type == 15) {
              d.name = Object.keys(JSON.parse(d.value));
              d.value = Object.values(JSON.parse(d.value))[0];
              item.dspIds = [];
            }
            if (d.type == 16) {
              let value = JSON.parse(d.value);
              d.name = Object.keys(JSON.parse(d.value)).filter(d => d != 'profileId');
              d.value = value;
              item.dspIds = d.value.profileId;
              dspAccount.find({where: {id: 139}}, (err, data) => {
                // async call wait here to get data and attach to item
                 item.x = data ;
              });
              delete d.value.profileId;
              d.value = JSON.stringify(d.value);
            }
          });
          return item;
        })
        .value();

I also tried using promises

promises.push(new Promise((resolve, reject) => {
        if (data.id) {
          XX.upsertWithWhere({id: data.id}, payload, (err, data) => {
            if (err) {
              return reject(err);
            }
            return resolve(data);
          });
        }
      }));
    });
    Promise.all(promises).then((data) => {
      callback(null, data);
    }, err => {
      callback(err);
    });

Update
i have already listed the promise .all method that doesnot work . So it cannot be called duplicate

Body:
Things are slightly tricky because you have an outer .map() and an inner .map(), containing an asynchronous element.

The asynchronous element effectively makes the whole thing asynchronous, requiring that :

the array of Promises generated by the inner .map() is aggregated with Promise.all(), and the aggregate Promise returned to the outer .map().

the array of Promises generated by the outer .map() is aggregated with Promise.all().

the results (an array of items) is available only via a chained .then().

First, to make the main code block simpler and easier to read, create a promisified version of dspAccount.findAsync().

dspAccount.findAsync = function(query) {
    return new Promise(function(resolve, reject) {
        dspAccount.find(query, (err, data) => {
            if(err) {
                reject(err);
            } else {
                resolve(data);
            }
        });
    });
}

Then the main code block can be written as follows :

let outerPromises = _.chain(value)
.groupBy('pubId')
.pairs()
.map(function(currentItem) {
    let item = _.object(_.zip(['ID', 'targetting'], currentItem));
    item.targetting.forEach(d => {
        item.publishername = d.RTB.name;
        item.type = d.type;
        propsToBeDeleted.forEach(function(prop) {
            delete d[prop];
        });
    });
    let innerPromises = item.targetting.map(d => {
        let value = JSON.parse(d.value);
        if (d.type == 15) { // synchronous - `innerPromises` receives a null
            item.dspIds = []; //
            d.name = Object.keys(value);
            d.value = Object.values(value)[0];
            return null;
        }
        if (d.type == 16) { // asynchronous - `innerPromises` receives a Promise
            return dspAccount.findAsync({where: {id: 139}})
            .then(data => {
                d.name = Object.keys(value).filter(d => d != 'profileId');
                item.dspIds = value.profileId;
                delete value.profileId;
                item.x = data;
                d.value = JSON.stringify(value);
            });
        }
    });
    return Promise.all(innerPromises).then(() => item); // aggregate inner promises and return
})
.value(); //  returns the outerPromises array

Promise.all(outerPromises)  // aggregate outer promises
.then(items => {
    // do stuff with items here
})
.catch(error => {
    // something went wrong
    // log/display error
    // take remedial action as required
});

I expect there's still some work to do. It doesn't look right that item should be mutated in the item.targetting.map() loop. The last element of item.targetting to deliver its result (synch or asynch) will determine the composition of item. That may not be what you want. If it is what you want, then more control will need to be exercised to ensure that the last result delivered is the result arising from the final element of item.targetting.


问:
Does Amazon pass custom headers to origin?
I am using CloudFront to front requests to our service hosted outside of amazon. The service is protected and we expect an "Authorization" header to be passed by the applications invoking our service.

We have tried invoking our service from Cloud Front but looks like the header is getting dropped by cloud front. Hence the service rejects the request and client gets 401 forbidden response.
For some static requests, which do not need authorization, we are not getting any error and are getting proper response from CloudFront.

I have gone through CloudFront documentation and there is no specific information available on how headers are handled and hence was hoping that they will be passed as is, but looks like thats not the case. Any guidance from you folks?

答:
In addition to specifying them under the Origin Behaviour section, you can also add custom headers to your origin configuration. In the AWS documentation for CloudFront custom headers:

If the header names and values that you specify are not already present in the viewer request, CloudFront adds them. If a header is present, CloudFront overwrites the header value before forwarding the request to the origin.

The benefit of this is that you can then use an All/wildcard setting for whitelisting your headers in the behaviour section.


问:
How to add value base on specific character ,also fix with certain digits in R
There is the basic width : xxxx.xxxxxx (4digits before "." 6 digits after".")

Have to add "0" when each side before and after "." is not enough digits.

Use regexr find "[.]" location with combination of str_pad can
fix the first 4 digits but

don't know how to add value after the specific character with fixed digits.
(cannot find a library can count the location from somewhere specified)

Data like this

```<code>> df
         Category
1       300.030340
2      3400.040290
3        700.07011
4        1700.0901
5       700.070114
6         700.0791
7       3600.05059
8        4400.0402
</code>```

Desired data

```<code>> df
         Category
1      0300.030340
2      3400.040290
3      0700.070110
4      1700.090100
5      0700.070114
6      0700.079100
7      3600.050590
8      4400.040200
</code>```

I am beginner of coding that sometime can't understand some regex like "["
e.t.c .With some explain of them would be super helpful.

Also i have a combination like this :

```<code>df$Category<-ifelse(regexpr("[.]",df$Category)==4,
             paste("0",df1$Category,sep = ""),df$Category)

df$Category<-str_pad(df$Category,11,side = c("right"),pad="0")
</code>```

Desire to know are there is any better way do this , especially count and
return the location from the END until specific character appear.

答:
There are plenty of great tricks, functions, and shortcuts to be learned, and I would encourage you to explore them all! For example, if you're trying to win code golf, you will want to use @akrun's sprintf() approach. Since you stated you're a beginner, it might be more helpful to breakdown the problem into its component parts. One transparent and easy-to-follow, in my opinion, approach would be to utilize the stringr package:

```<code>library(stringr)

location_of_dot <- str_locate(df$Category, "\\.")[, 1]
substring_left_of_dot <- str_sub(df$Category, end = location_of_dot - 1)
substring_right_of_dot <- str_sub(df$Category, start = location_of_dot + 1)

pad_left <- str_pad(substring_left_of_dot, 4, side = "left", pad = "0")
pad_right <- str_pad(substring_right_of_dot, 6, side = "right", pad = "0")

result <- paste0(pad_left, ".", pad_right)
result
</code>```

Body:
There is the basic width : xxxx.xxxxxx (4digits before "." 6 digits after".")

Have to add "0" when each side before and after "." is not enough digits.

Use regexr find "[.]" location with combination of str_pad can
fix the first 4 digits but

don't know how to add value after the specific character with fixed digits.
(cannot find a library can count the location from somewhere specified)

Data like this

> df
         Category
1       300.030340
2      3400.040290
3        700.07011
4        1700.0901
5       700.070114
6         700.0791
7       3600.05059
8        4400.0402

Desired data

> df
         Category
1      0300.030340
2      3400.040290
3      0700.070110
4      1700.090100
5      0700.070114
6      0700.079100
7      3600.050590
8      4400.040200

I am beginner of coding that sometime can't understand some regex like "["
e.t.c .With some explain of them would be super helpful.

Also i have a combination like this :

df$Category<-ifelse(regexpr("[.]",df$Category)==4,
             paste("0",df1$Category,sep = ""),df$Category)

df$Category<-str_pad(df$Category,11,side = c("right"),pad="0")

Desire to know are there is any better way do this , especially count and
return the location from the END until specific character appear.

Body:
There are plenty of great tricks, functions, and shortcuts to be learned, and I would encourage you to explore them all! For example, if you're trying to win code golf, you will want to use @akrun's sprintf() approach. Since you stated you're a beginner, it might be more helpful to breakdown the problem into its component parts. One transparent and easy-to-follow, in my opinion, approach would be to utilize the stringr package:

library(stringr)

location_of_dot <- str_locate(df$Category, "\\.")[, 1]
substring_left_of_dot <- str_sub(df$Category, end = location_of_dot - 1)
substring_right_of_dot <- str_sub(df$Category, start = location_of_dot + 1)

pad_left <- str_pad(substring_left_of_dot, 4, side = "left", pad = "0")
pad_right <- str_pad(substring_right_of_dot, 6, side = "right", pad = "0")

result <- paste0(pad_left, ".", pad_right)
result


问:
SonarQube - Ignoring java interaces and annotations
I am trying to find out how to configure SonarQube to ignore interface class and annotation classes (@interface) when examining my code.  So far no success.

Can anyone help me?

答:
To specify which files are and are not included in an analysis go to Administration > General Settings > Analysis Scope > Files.

You should set below properties:

Source File Exclusions

Patterns used to exclude some source files from analysis.

Global Source File Exclusions

Patterns used to exclude some source files from analysis. They apply to every project and cannot be overridden.

For more info read sonarQube docs.


问:
mysql string compares - md5 faster?
Would an indexed compare of two string fields be faster if those fields were md5'd during the import, and the md5 field used in the compare instead of the source string field?</p>

答:
Possibly, if the strings were very long or very similar.

More importantly though, if the strings are very long, the index for the MD5 column would likely be smaller.  Smaller means more likely to fit into memory, and faster to read from the disk.  So if there were any performance improvement to be gained by doing this, most of it would probably come from that.

That said, you'd have to weigh any performance gain in reading with the extra cost of calculating the checksum and writing the value and the increased table size due to the new column being added.

ContentLicense: CC BY-SA 2.5

Title: mysql string compares - md5 faster?


问:
Multiprocessing 2 different functions python3
I am struggling for a while with Multiprocessing in Python. I would like to run 2 independent functions simultaneously, wait until both calculations are finished and then continue with the output of both functions. Something like this:

```<code># Function A:
def jobA(num):
    result=num*2
    return result

# Fuction B:
def jobB(num):
    result=num^3
    return result

 # Parallel process function:

{resultA,resultB}=runInParallel(jobA(num),jobB(num))
</code>```

I found other examples of multiprocessing however they used only one function or didn't returned an output. Anyone knows how to do this? Many thanks!

答:
I'd recommend creating processes manually (rather than as part of a pool), and sending the return values to the main process through a multiprocessing.Queue. These queues can share almost any Python object in a safe and relatively efficient way.

Here's an example, using the jobs you've posted.

```<code>def jobA(num, q):
    q.put(num * 2)

def jobB(num, q):
    q.put(num ^ 3)

import multiprocessing as mp
q = mp.Queue()
jobs = (jobA, jobB)
args = ((10, q), (2, q))
for job, arg in zip(jobs, args):
    mp.Process(target=job, args=arg).start()

for i in range(len(jobs)):
    print('Result of job {} is: {}'.format(i, q.get()))
</code>```

This prints out:

```<code>Result of job 0 is: 20
Result of job 1 is: 1
</code>```

But you can of course do whatever further processing you'd like using these values.

Body:
I am struggling for a while with Multiprocessing in Python. I would like to run 2 independent functions simultaneously, wait until both calculations are finished and then continue with the output of both functions. Something like this:

# Function A:
def jobA(num):
    result=num*2
    return result

# Fuction B:
def jobB(num):
    result=num^3
    return result

 # Parallel process function:

{resultA,resultB}=runInParallel(jobA(num),jobB(num))

I found other examples of multiprocessing however they used only one function or didn't returned an output. Anyone knows how to do this? Many thanks!

Body:
I'd recommend creating processes manually (rather than as part of a pool), and sending the return values to the main process through a multiprocessing.Queue. These queues can share almost any Python object in a safe and relatively efficient way.

Here's an example, using the jobs you've posted.

def jobA(num, q):
    q.put(num * 2)

def jobB(num, q):
    q.put(num ^ 3)

import multiprocessing as mp
q = mp.Queue()
jobs = (jobA, jobB)
args = ((10, q), (2, q))
for job, arg in zip(jobs, args):
    mp.Process(target=job, args=arg).start()

for i in range(len(jobs)):
    print('Result of job {} is: {}'.format(i, q.get()))

This prints out:

Result of job 0 is: 20
Result of job 1 is: 1

But you can of course do whatever further processing you'd like using these values.


问:
I have an Uncaught Reference Error that says a function is not defined, even though it seems to be defined
I am trying to perform some javascript code when an input field's input changes. I started by specifying an oninput event handler function name.

```<code><input type="text" name="venue_name" value="<?php echo $event->venue_name(); ?>"
    class="form-control w2bw2c-name w2bw2c-venue-name" placeholder="Search..."
    oninput="inputChange()">
</code>```

I had the inputChange function defined outside my document-ready function, and this worked for a while, but now it is not working. Now I have this code:

```<code><input type="text" name="venue_name" value="<?php echo $event->venue_name(); ?>"
    class="form-control w2bw2c-name w2bw2c-venue-name" placeholder="Search...">
</code>```

Within my document.ready function I have:

```<code>$('select.w2bw2c-name').input(function() {
    inputChange(this);
});
</code>```

Outside my document.ready function, I have the function:

```<code>function inputChange(x) {
    ... some code ...
};
</code>```

Now when I enter some text into the input field I get the message that inputChange is not defined. Perhaps it is complicating that I must use a class as a selector, but the input field may appear multiple times within a form, and I got it to work initially.

答: I had my javascript at the end of my HTML. I moved some of it (the so-called "undefined" functions) to the head of my HTML and the events fired as they were supposed to. Problem now is that the called function inputChange makes an AJAX call to the database and not all the data is getting returned (to populate an autosuggest list). I'll save that for another question.</p>

Body:
I am trying to perform some javascript code when an input field's input changes. I started by specifying an oninput event handler function name.

<input type="text" name="venue_name" value="<?php echo $event->venue_name(); ?>"
    class="form-control w2bw2c-name w2bw2c-venue-name" placeholder="Search..."
    oninput="inputChange()">

I had the inputChange function defined outside my document-ready function, and this worked for a while, but now it is not working. Now I have this code:

<input type="text" name="venue_name" value="<?php echo $event->venue_name(); ?>"
    class="form-control w2bw2c-name w2bw2c-venue-name" placeholder="Search...">

Within my document.ready function I have:

$('select.w2bw2c-name').input(function() {
    inputChange(this);
});

Outside my document.ready function, I have the function:

function inputChange(x) {
    ... some code ...
};

Now when I enter some text into the input field I get the message that inputChange is not defined. Perhaps it is complicating that I must use a class as a selector, but the input field may appear multiple times within a form, and I got it to work initially.


问:
Python APScheduler how to disable logging
I set up APScheduler to run every second via cron schedule (kind of needed/wanted).  Right now I have logger sending everything to console.

If it wasn't for logging is greatly important to what I'm working on, it'd be okay.  But, I need logging.  What I don't want is APScheduler's info logging.  Stuff like this:

```INFO     at 2013-05-26 13:05:06,007 : Job "loadavg.run (trigger: cron[year='*', month='*', day='*', week='*', day_of_week='*', hour='*', minute='*', second='*'], next run at: 2013-05-26 13:05:06)" executed successfully
INFO     at 2013-05-26 13:05:06,008 : Running job "cpu.run (trigger: cron[year='*', month='*', day='*', week='*', day_of_week='*', hour='*', minute='*', second='*'], next run at: 2013-05-26 13:05:07)" (scheduled at 2013-05-26 13:05:06)```

I have this in my code after I add the cron jobs:

```logging.getLogger("apscheduler.scheduler").setLevel(logging.DEBUG)```

There's not any, as far as I know, configuration options for APScheduler to specify logging information, either.

I know I can specify the level of the logger to ERROR or something, but when it gets set to INFO I don't want all of this (what seems to be useless) information logged as well.

答:
Here's my code, which works without complaining about missing handlers:

```<code>scheduler = BackgroundScheduler()
scheduler.start()
scheduler.add_job(every_minute, trigger='cron', second=0, id='every_minute')
logging.getLogger('apscheduler.executors.default').setLevel(logging.WARNING)
</code>```

It does not disable scheduler logging completely, but it does remove the info messages the OP wanted to be rid of.

Body:
I set up APScheduler to run every second via cron schedule (kind of needed/wanted).  Right now I have logger sending everything to console.

If it wasn't for logging is greatly important to what I'm working on, it'd be okay.  But, I need logging.  What I don't want is APScheduler's info logging.  Stuff like this:

INFO     at 2013-05-26 13:05:06,007 : Job "loadavg.run (trigger: cron[year='*', month='*', day='*', week='*', day_of_week='*', hour='*', minute='*', second='*'], next run at: 2013-05-26 13:05:06)" executed successfully
INFO     at 2013-05-26 13:05:06,008 : Running job "cpu.run (trigger: cron[year='*', month='*', day='*', week='*', day_of_week='*', hour='*', minute='*', second='*'], next run at: 2013-05-26 13:05:07)" (scheduled at 2013-05-26 13:05:06)

I have this in my code after I add the cron jobs:

logging.getLogger("apscheduler.scheduler").setLevel(logging.DEBUG)

There's not any, as far as I know, configuration options for APScheduler to specify logging information, either.

I know I can specify the level of the logger to ERROR or something, but when it gets set to INFO I don't want all of this (what seems to be useless) information logged as well.

Body:
Here's my code, which works without complaining about missing handlers:

scheduler = BackgroundScheduler()
scheduler.start()
scheduler.add_job(every_minute, trigger='cron', second=0, id='every_minute')
logging.getLogger('apscheduler.executors.default').setLevel(logging.WARNING)

It does not disable scheduler logging completely, but it does remove the info messages the OP wanted to be rid of.


问:
How to perform a git merge in a Jenkins pipeline?
When Jenkins builds a non-master git branch, I want to merge in master automatically at a specific point. I don't want to use the git plugin's auto merge feature.

However, I've added the stage:

```<code>stage('Merge master') {
  sh 'git merge master'
}
</code>```

But I get an error:

```<code>merge: master - not something we can merge
</code>```

Jenkins seems to be checking out my branch in a weird way that prevents me being able to then merge master. What do I need to do to merge master into my branch?

答: I believe you should be able to accomplish this with just the Git Plugin. Under Additional Behaviors, there is an option to Merge before build. Furthermore, you may be able to piggyback off of this within a Pipeline script

Body:
When Jenkins builds a non-master git branch, I want to merge in master automatically at a specific point. I don't want to use the git plugin's auto merge feature.

However, I've added the stage:

stage('Merge master') {
  sh 'git merge master'
}

But I get an error:

merge: master - not something we can merge

Jenkins seems to be checking out my branch in a weird way that prevents me being able to then merge master. What do I need to do to merge master into my branch?


问:
declare an interface thrift
How can I declare an interface in Thrift? I mean I have the interface IClient and I use it as parameter in login function in Server:

```<code>public interface IServer {
    void login(Pers pers, IClient client) throws ConcursException;
}
</code>```

I have to use Thrift (Java server, C# client) and I don't know how to declare the interface for using it in login function.

Here is the IClient interface:

```<code>public interface IClient
{
    void increasedNrParticipants(Proba proba);
}
</code>```

Thank you!

答:
There is an RPC framework that uses the standard thrift Protocol named "thrifty", and it is the same effect as using thrift IDL to define the service, that is, thrify can be compatible with code that uses thrift IDL, which is very helpful for cross-platform and it uses DotNetty (windows is iocp, linux is nio)

```<code>[ThriftStruct]
public class LogEntry
{

    [ThriftConstructor]
    public LogEntry([ThriftField(1)]String category, [ThriftField(2)]String message)
    {
        this.Category = category;
        this.Message = message;
    }

    [ThriftField(1)]
    public String Category { get; }

    [ThriftField(2)]
    public String Message { get; }
}

[ThriftService("scribe")]
public interface IScribe
{
    [ThriftMethod("getMessages")]
    List<LogEntry> GetMessages();

    [ThriftMethod]
    ResultCode Log(List<LogEntry> messages);
}

public class Scribe : IScribe
{
    public List<LogEntry> GetMessages()
    {
        return new List<LogEntry>
        {
            new LogEntry { Category = "c1", Message = Guid.NewGuid().ToString() },
            new LogEntry { Category = "c2", Message = Guid.NewGuid().ToString() },
            new LogEntry { Category = "c3", Message = Guid.NewGuid().ToString() }
        };
    }

    public ResultCode Log(List<LogEntry> messages)
    {
        return ResultCode.TRY_LATER;
    }
}
</code>```

more detail: https://github.com/endink/Thrifty

Title: declare an interface thrift

Body:
How can I declare an interface in Thrift? I mean I have the interface IClient and I use it as parameter in login function in Server:

public interface IServer {
    void login(Pers pers, IClient client) throws ConcursException;
}

I have to use Thrift (Java server, C# client) and I don't know how to declare the interface for using it in login function.

Here is the IClient interface:

public interface IClient
{
    void increasedNrParticipants(Proba proba);
}

Thank you!

Body:
There is an RPC framework that uses the standard thrift Protocol named "thrifty", and it is the same effect as using thrift IDL to define the service, that is, thrify can be compatible with code that uses thrift IDL, which is very helpful for cross-platform and it uses DotNetty (windows is iocp, linux is nio)

[ThriftStruct]
public class LogEntry
{

    [ThriftConstructor]
    public LogEntry([ThriftField(1)]String category, [ThriftField(2)]String message)
    {
        this.Category = category;
        this.Message = message;
    }

    [ThriftField(1)]
    public String Category { get; }

    [ThriftField(2)]
    public String Message { get; }
}

[ThriftService("scribe")]
public interface IScribe
{
    [ThriftMethod("getMessages")]
    List<LogEntry> GetMessages();

    [ThriftMethod]
    ResultCode Log(List<LogEntry> messages);
}

public class Scribe : IScribe
{
    public List<LogEntry> GetMessages()
    {
        return new List<LogEntry>
        {
            new LogEntry { Category = "c1", Message = Guid.NewGuid().ToString() },
            new LogEntry { Category = "c2", Message = Guid.NewGuid().ToString() },
            new LogEntry { Category = "c3", Message = Guid.NewGuid().ToString() }
        };
    }

    public ResultCode Log(List<LogEntry> messages)
    {
        return ResultCode.TRY_LATER;
    }
}

more detail: https://github.com/endink/Thrifty


问:
Receiving "Value cannot be null. Parameter name: httpContext" when sending MVC Mailer email from ASP MVC
My MVC Mailer instance is failing when I send from the server. I'm getting the error Value cannot be null.Parameter name: httpContext when I attempt to send an email.

my code looks like this:

```<code>    public static void SendApproval(TimeOffRequest request)
    {
        MailService mailer = new MailService();
        mailer.ViewData.Model = request;

        MvcMailMessage mailMessage = new MvcMailMessage
        {
            Subject = $"PTO request approved for {request.StartTime} to {request.EndTime}",
            From = new MailAddress("calendar@company.com"),
        };
        mailMessage.To.Add(new MailAddress(request.Requester.Email));

        if (mailMessage.To.Count == 0)
            return;

        mailer.PopulateBody(mailMessage, "RequestApproved");
        mailMessage.Send();
    }
</code>```

It's specifically failing on the line mailer.PopulateBody(mailMessage, "RequestApproved");

It is being called from the post of a controller endpoint. Why is the context missing in this scenario? I attempted to manually pass the context and that failed as well.

Heres the top of the stack trace:

```<code>System.Web.Routing.RouteCollection.GetRouteData(HttpContextBase httpContext) +505
   Mvc.Mailer.MailerBase.CreateControllerContext() +98
   Mvc.Mailer.MailerBase.ViewExists(String viewName, String masterName) +127
</code>```

答:
MVCMailer's PopulateBody method has 3 arguments and 4 arguments overload in MailerBase class (3 arguments version actually calls 4 arguments overload with masterName set as null):

```<code>// 3 arguments overload
public virtual void PopulateBody(MailMessage mailMessage, string viewName, Dictionary<string, string> linkedResources)
{
    PopulateBody(mailMessage, viewName, null, linkedResources);
}

// 4 arguments overload
public virtual void PopulateBody(MailMessage mailMessage, string viewName, string masterName = null, Dictionary<string, string> linkedResources = null)
{
    ...
}
</code>```

Based from that findings, use additional null to fill unnecessary method arguments, either using 3 or 4 arguments version:

```<code>// 3 arguments
mailer.PopulateBody(mailMessage, "RequestApproved", null);

// 4 arguments
mailer.PopulateBody(mailMessage, "RequestApproved", null, null);
</code>```

Since the possible cause originated from MailerBase class (in var routeData = RouteTable.Routes.GetRouteData(CurrentHttpContext); where CurrentHttpContext passed null value), you can see utilization of null-checking for HttpContextBase virtual property in this request.

Similar issue:

MvcMailer unit tests: System.ArgumentNullException httpContext cannot be null

Body:
My MVC Mailer instance is failing when I send from the server. I'm getting the error Value cannot be null.Parameter name: httpContext when I attempt to send an email.

my code looks like this:

    public static void SendApproval(TimeOffRequest request)
    {
        MailService mailer = new MailService();
        mailer.ViewData.Model = request;

        MvcMailMessage mailMessage = new MvcMailMessage
        {
            Subject = $"PTO request approved for {request.StartTime} to {request.EndTime}",
            From = new MailAddress("calendar@company.com"),
        };
        mailMessage.To.Add(new MailAddress(request.Requester.Email));

        if (mailMessage.To.Count == 0)
            return;

        mailer.PopulateBody(mailMessage, "RequestApproved");
        mailMessage.Send();
    }

It's specifically failing on the line mailer.PopulateBody(mailMessage, "RequestApproved");

It is being called from the post of a controller endpoint. Why is the context missing in this scenario? I attempted to manually pass the context and that failed as well.

Heres the top of the stack trace:

System.Web.Routing.RouteCollection.GetRouteData(HttpContextBase httpContext) +505
   Mvc.Mailer.MailerBase.CreateControllerContext() +98
   Mvc.Mailer.MailerBase.ViewExists(String viewName, String masterName) +127

Body:
MVCMailer's PopulateBody method has 3 arguments and 4 arguments overload in MailerBase class (3 arguments version actually calls 4 arguments overload with masterName set as null):

// 3 arguments overload
public virtual void PopulateBody(MailMessage mailMessage, string viewName, Dictionary<string, string> linkedResources)
{
    PopulateBody(mailMessage, viewName, null, linkedResources);
}

// 4 arguments overload
public virtual void PopulateBody(MailMessage mailMessage, string viewName, string masterName = null, Dictionary<string, string> linkedResources = null)
{
    ...
}

Based from that findings, use additional null to fill unnecessary method arguments, either using 3 or 4 arguments version:

// 3 arguments
mailer.PopulateBody(mailMessage, "RequestApproved", null);

// 4 arguments
mailer.PopulateBody(mailMessage, "RequestApproved", null, null);

Since the possible cause originated from MailerBase class (in var routeData = RouteTable.Routes.GetRouteData(CurrentHttpContext); where CurrentHttpContext passed null value), you can see utilization of null-checking for HttpContextBase virtual property in this request.

Similar issue:

MvcMailer unit tests: System.ArgumentNullException httpContext cannot be null


答:
Use separate in tidyr to separate Category on decimal. Use str_pad from stringr to add zeros in the front or back and paste them together.

```<code>library(tidyr) # to separate columns on decimal
library(dplyr) # to mutate and pipes
library(stringr) # to strpad
input_data <- read.table(text ="        Category
1       300.030340
2      3400.040290
3        700.07011
4        1700.0901
5       700.070114
6         700.0791
7       3600.05059
8        4400.0402", header = TRUE, stringsAsFactors = FALSE) %>%
  separate(Category, into = c("col1", "col2")) %>%
  mutate(col1 = str_pad(col1, width = 4, side= "left", pad  ="0"),
         col2 = str_pad(col2, width = 6, side= "right", pad  ="0"),
         Category = paste(col1, col2, sep = ".")) %>%
  select(-col1, -col2)
</code>```

Title: How to add value base on specific character ,also fix with certain digits in R

Body:
Use separate in tidyr to separate Category on decimal. Use str_pad from stringr to add zeros in the front or back and paste them together.

library(tidyr) # to separate columns on decimal
library(dplyr) # to mutate and pipes
library(stringr) # to strpad
input_data <- read.table(text ="        Category
1       300.030340
2      3400.040290
3        700.07011
4        1700.0901
5       700.070114
6         700.0791
7       3600.05059
8        4400.0402", header = TRUE, stringsAsFactors = FALSE) %>%
  separate(Category, into = c("col1", "col2")) %>%
  mutate(col1 = str_pad(col1, width = 4, side= "left", pad  ="0"),
         col2 = str_pad(col2, width = 6, side= "right", pad  ="0"),
         Category = paste(col1, col2, sep = ".")) %>%
  select(-col1, -col2)


问:
Sending POST info via PHP (curl) or jQuery - IP problem -
Im sending post info by using php curl. its okay. no problem. however it sends server's IP. this is a problem for me.

jquery is sending post info with user's IP, however jQuery have cross domain problem. it is not sending post info to another domain. It only works for same domain.

I wanna send post info (to another domain) + user ip (not server ip). Id like to learn your advices... Well, is there any other ways to make this job?

Thanks, Regards.

答:
You can also set up a php script that will proxify your call.

In the same domain, put a php script that will catch the post args, and resend it thru a curl call. then print the result that will catched by your jquery ajax call.


问:
How to capture value of data-network property in a data layer variable?
I am trying to capture the value data-network 'facebook' of the SVG icon in Google Taga Manager using a data layer variable.

The code for the data layer element that I came up with is as follows

```<code>gtm.element.parentElement.previousSibling.parentElement.parentNode.attributes.0.nodeValue
</code>```

this data layer variable should get value just as 'facebook'.

I am probably a little far off right now. Any ideas how I would be able to do that?

I am open to creating a custom javascript variable which will get the data-network value of the clicked element.

答:
I was able to get the value facebook in a data layer variable using Google Tag Manager using the below value - </p>

```<code>gtm.element.parentElement.attributes.1.nodeValue
</code>```

Body:
I am trying to capture the value data-network 'facebook' of the SVG icon in Google Taga Manager using a data layer variable.

The code for the data layer element that I came up with is as follows

gtm.element.parentElement.previousSibling.parentElement.parentNode.attributes.0.nodeValue

this data layer variable should get value just as 'facebook'.

I am probably a little far off right now. Any ideas how I would be able to do that?

I am open to creating a custom javascript variable which will get the data-network value of the clicked element.

Body:
I was able to get the value facebook in a data layer variable using Google Tag Manager using the below value -

gtm.element.parentElement.attributes.1.nodeValue


问:
Assert if any of two strings are present
I have a webpage with two different strings depending on time of the day - "Good day" or "Good night".

Is there any way to do some sort of assert_content(my_string) that check if one of the two given strings is present?

It doesn't matter which one is present, just that one is.

答:
While Sebastian's answer will work as long as the page is loaded when you go to check, it loses Capybaras waiting/retrying behavior and can lead to flaky tests if used to check content while a page is changing (immediately after clicking a button, etc).

When using minitest a better solution would be to continue using the Capybara provided assert_content matcher but pass it a regex

```<code>assert_content(/Good day|Good night/)
</code>```

If using RSpec you can do the same

```<code>expect(page).to have_content(/Good day|Good night/)
</code>```

or you can write it in a potentially more readable manner

```<code>expect(page).to have_content('Good day').or(have_content('Good night'))
</code>```

Body:
While Sebastian's answer will work as long as the page is loaded when you go to check, it loses Capybaras waiting/retrying behavior and can lead to flaky tests if used to check content while a page is changing (immediately after clicking a button, etc).

When using minitest a better solution would be to continue using the Capybara provided assert_content matcher but pass it a regex

assert_content(/Good day|Good night/)

If using RSpec you can do the same

expect(page).to have_content(/Good day|Good night/)

or you can write it in a potentially more readable manner

expect(page).to have_content('Good day').or(have_content('Good night'))


问:
OpenLayers: How to detect the map view is completely loaded?
I'm implementing map exporting functionality using OpenLayers 3.

But there is one problem: one cannot determine whether the map view is completely loaded or a few tiles is missing yet.

It seems there is no such API or event. The close one is tileloadstart - tileloadend pair. But OpenLayers loads tiles asynchronously, and before the tile is actually loading the tileloadstart is not fired - that is, a tile that is queued in the tile queue does not fire the event before actually loading.

Hot can I detect the map view is completely loaded?

答:
I eventually implemented the export function successfully. Below is the rough explanation.

Register tileloadstart, tileloadend, tileloaderror event handlers on the ol.sources using ol.source.on(), and start managing the tile load count.

Register postcompose event handlers on the ol.Map using ol.Map.once().

call ol.Map.renderSync(). This triggers the tile loading, so from now if there is no tile loading, it will mean that all tile have been loaded.

On postcompose event handler, capture the map content from event.context using event.context.canvas.toDataURL(), and register postrender function using event.frameState.postRenderFunctions.push() (a bit hacky).

On the registered postrender function, check the tile load count (which can be managed by the tileload* event handlers). If the count is not zero, abandon the captured content. Else, the capture is done.

On tileloadend and tileloaderror, if the tile load count becomes zero, retry from the step 3 above.


问:
List all required modules in Java9?
How can I list all required modules in Java9?

For system modules, this works:

```<code>ModuleFinder.ofSystem()
    .findAll()
    .stream()
    ...
</code>```

however, not seeing atm how to get a list of the modules that my current code requires.

This question is about querying all the modules programatically. It's not about resolving modularity issues.

答:
You might want to make use of the example as provided in the Javadoc for ModuleLayer to get a ModuleLayer of your module named let's say one to find out the descriptor and further the set of requires object in its module dependencies.

```<code>ModuleFinder finder = ModuleFinder.of(Paths.get("/path/to/module/in/out/production/")); // this is generally a path where I build my modules to

ModuleLayer parent = ModuleLayer.boot();

Configuration cf = parent.configuration()
                         .resolve(finder, ModuleFinder.of(), Set.of("one")); // name of module in module-info

ClassLoader scl = ClassLoader.getSystemClassLoader();
ModuleLayer layer = parent.defineModulesWithManyLoaders(cf, scl);

layer.modules()
     .stream()
     .map(Module::getDescriptor) // get the descriptor of module
     .map(ModuleDescriptor::requires) // set of requires in the module dependencies
     .forEach(System.out::println);
</code>```

Title: List all required modules in Java9?

Body:
How can I list all required modules in Java9?

For system modules, this works:

ModuleFinder.ofSystem()
    .findAll()
    .stream()
    ...

however, not seeing atm how to get a list of the modules that my current code requires.

This question is about querying all the modules programatically. It's not about resolving modularity issues.

Body:
You might want to make use of the example as provided in the Javadoc for ModuleLayer to get a ModuleLayer of your module named let's say one to find out the descriptor and further the set of requires object in its module dependencies.

ModuleFinder finder = ModuleFinder.of(Paths.get("/path/to/module/in/out/production/")); // this is generally a path where I build my modules to

ModuleLayer parent = ModuleLayer.boot();

Configuration cf = parent.configuration()
                         .resolve(finder, ModuleFinder.of(), Set.of("one")); // name of module in module-info

ClassLoader scl = ClassLoader.getSystemClassLoader();
ModuleLayer layer = parent.defineModulesWithManyLoaders(cf, scl);

layer.modules()
     .stream()
     .map(Module::getDescriptor) // get the descriptor of module
     .map(ModuleDescriptor::requires) // set of requires in the module dependencies
     .forEach(System.out::println);


问:
ELB listener configuration for WSS websocket
My Websocket WS works fine.But When I use WSS , it fails with below error.

WebSocket connection to 'wss://mywebsocket.ca/' failed: Error in connection establishment: net::ERR_INSECURE_RESPONSE
It feels some SSL issue. I have my certificates configured properly and all other url through this ELB works fine. my Ws curl works good.

What could be the issue? Could it be the listerner configuraiton of ELB for HTTPS is not done properly.

I am just using some chrome extensions to connect Websocket.No code here.

答:
This took me a while to figure out. I hope I haven't forgotten anything in the answer below as it was a while ago I did it.

First of all you need to bypass CloudFront as it doesn't run well with websockets (unless something has changed recently). Setup an A alias Route 53 record pointing to your load balancer (i.e. websockets.domain.com).

Setup a listener for your port in your in your load balancer (i.e. 5678). Note that you should use SSL (Secure TCP) protocol. You also need a SSL certificate to your listener. Use ACM for this, it gives you the option there.

Remember to change your websockets connection to use this new connection as well.


问:
Difference between HTTP redirect codes
The differences between the various HTTP 3XX redirect codes are not clear to me.  Yes, I've read the spec, but there seems to be some discrepancy between the standard and actual practice here.

The 301 redirect code seems clear enough: This means the resource was permanently moved to another URI, and future requests should use that URI.

And the 307 redirect code also seems clear: it means the redirect is temporary, and future requests should still use the original URI.

But I can't tell what the difference is between 302 and 303, or why either of them are really different from 301.  It seems that 302 was originally intended to be a temporary redirect, (like 307), but in practice, most browsers treated it like a 303.  But what's the difference between a 303 and a 301?  Is 301 supposed to mean the redirect is more permanent?

答:
The difference between 303 and 307 is this:

303: See other. The request is received correctly, but the results should be retrieved using a GET on the redirect url.

307: Temporary redirect. The entire request should be redirected to the new url. Any post data should be re-posted.

Note that 302 was intended to have the behavior of 307, but most browsers implemented it as the behavior of 303 (both of which didn't exist back then). Therefore, those two new codes were introduced to replace 302.

The difference between 301 and 303:

301: The document is moved. Future requests should use the new url. This url is obsolete.

Note: Be careful with this code. Browsers and proxies tend to apply really agressive caching on it, so if you reply with a 301 it might take a long while for someone to revisit that url.

303: The request is received correctly. Any PUT requests are processed. The resulting document can be retrieved from the redirect url. Future request should still go to the original url.

Title: Difference between HTTP redirect codes


问:
How to check if letter in a string appear in another string in the same order

I would love to check if the letters from a text appear in another text in the same order.

```<code>text    "Ce"
name    "Arsenic"
Answer   False

for x in text:
    if x.lower() not in name.lower():
        return False
</code>```

I would like that the order is checked too so that the elements appear in the same order in the other string : True else False.

At the moment my code only checks if the letters also appear in the string but not if they are in the same order.

答:
Essentially, you want to check if text is contained in name. So instead of doing it at the character by character level (i.e. if all characters in text appears in name, the way that you are doing now), use the in operator on the two strings to check if text is in name.

i.e.
return text.lower() in name.lower()

see https://www.pythoncentral.io/how-to-see-if-a-string-contains-another-string-in-python/

Body:
I would love to check if the letters from a text appear in another text in the same order.

text    "Ce"
name    "Arsenic"
Answer   False

for x in text:
    if x.lower() not in name.lower():
        return False

I would like that the order is checked too so that the elements appear in the same order in the other string : True else False.

At the moment my code only checks if the letters also appear in the string but not if they are in the same order.