问:
How to reload Div with dynamic time
I have an HTML table with JSON data which I am rendering on UI in parts.

What I am doing

I am calling full data at once via ajax, then dividing the data into 12-12 rows because one page can max have 12 rows as of my requirement

I am refreshing the div in each 3 seconds and showing 12-12 rows at one time

When page lodes I am showing first 12 rows then after 3 seconds hiding first 12 and showing next 12

This is how I am doing My work

What I am trying to achieve

When full data is loaded then page shows blank which is not to the requirement

I am trying to make that ajax call again when full data is loaded

Working code

$(document).ready(function() {
  myFun();

  function myFun() {
    $.ajax({
      async: true,
      url: "MenuDisplay",
      method: "GET",
      dataType: "json",
      contentType: "application/json; charset=utf-8",
      success: function(tableValue) {

        addTable(tableValue)
        window.setInterval(showRows, 3000);
        showRows();

      }
    });
  }

  function showRows() {
    // Any TRs that are not hidden and not already shown get "already-shown" applies
    if ($(".hidden:lt(12)").length > 0) {
      $("tr:not(.hidden):not(.already-shown)").addClass("already-shown");
    } else {
      $("tr:not(.hidden):not(.already-shown)").addClass("already-shown"); // this one is also calling after 3 seconds after last page i want to call this imidiatly
      $.ajax({
        async: true,
        url: "MenuDisplay",
        method: "GET",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function(tableValue) {

          addTable(tableValue)

        }
      });
    }

    $(".hidden:lt(12)").removeClass("hidden"); // this one is to hide previous  rows and show next
  }

  function addTable(tableValue) {
    var $tbl = $("
", {
        "class": "table fixed"
      }),
      $tb = $("
"),
      $trh = $("
");

    var split = Math.round(tableValue.length / 4);
    for (i = 0; i < split; i++) {
      $tr = $("
", {
        class: "hidden "
      });

      for (j = 0; j < 4; j++) {
        $.each(tableValue[split * j + i], function(key, value) {
          if (typeof(value) === "number") {
            $("", {
              "class": "text-right color" + (j + 1)
            }).html(value).appendTo($tr);
          } else {
            $("", {
              "class": "text-left color" + (j + 1)
            }).html(value).appendTo($tr);
          }

        });
      }
      $tr.appendTo($tb);
    }
    $tbl.append($tb);
    $("#DisplayTable").html($tbl);
  }

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>tbody>tr>td {
  white-space: normal;
  border-collapse: collapse;
  font-family: Verdana;
  font-weight: bold;
  font-size: .9em;
}

td:nth-child(2),
td:nth-child(4),
td:nth-child(6),
td:nth-child(8) {
  width: 85px;
  max-width: 85px;
  height: 63px
}

.fixed {
  table-layout: fixed;
}

.color1 {
  background: #4AD184;
}

.color2 {
  background: #EA69EF;
}

.color3 {
  background: #E1A558;
}

.color4 {
  background: #F4F065;
}

.hidden,
.already-shown {
  display: none;
}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

```

Check This fiddle for working example with JSON data

答:
I checked your fiddle and understood that you need to stop adding the 'already-shown' class in your last page.
I have wrapped an if condition here.

```<code>if($(".hidden:lt(12)").length > 0){
  $("tr:not(.hidden):not(.already-shown)").addClass("already-shown");
}
</code>```

You should also consider clearing the setInterval in the else block.

Adding fiddle for your reference https://jsfiddle.net/s7gqe1na/1/

Title: How to reload Div with dynamic time

Body:
I have an HTML table with JSON data which I am rendering on UI in parts.

What I am doing

I am calling full data at once via ajax, then dividing the data into 12-12 rows because one page can max have 12 rows as of my requirement

I am refreshing the div in each 3 seconds and showing 12-12 rows at one time

When page lodes I am showing first 12 rows then after 3 seconds hiding first 12 and showing next 12

This is how I am doing My work

What I am trying to achieve

When full data is loaded then page shows blank which is not to the requirement

I am trying to make that ajax call again when full data is loaded

Working code

$(document).ready(function() {
  myFun();

  function myFun() {
    $.ajax({
      async: true,
      url: "MenuDisplay",
      method: "GET",
      dataType: "json",
      contentType: "application/json; charset=utf-8",
      success: function(tableValue) {

        addTable(tableValue)
        window.setInterval(showRows, 3000);
        showRows();

      }
    });
  }

  function showRows() {
    // Any TRs that are not hidden and not already shown get "already-shown" applies
    if ($(".hidden:lt(12)").length > 0) {
      $("tr:not(.hidden):not(.already-shown)").addClass("already-shown");
    } else {
      $("tr:not(.hidden):not(.already-shown)").addClass("already-shown"); // this one is also calling after 3 seconds after last page i want to call this imidiatly
      $.ajax({
        async: true,
        url: "MenuDisplay",
        method: "GET",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function(tableValue) {

          addTable(tableValue)

        }
      });
    }

    $(".hidden:lt(12)").removeClass("hidden"); // this one is to hide previous  rows and show next
  }

  function addTable(tableValue) {
    var $tbl = $("
", {
        "class": "table fixed"
      }),
      $tb = $("
"),
      $trh = $("
");

    var split = Math.round(tableValue.length / 4);
    for (i = 0; i < split; i++) {
      $tr = $("
", {
        class: "hidden "
      });

      for (j = 0; j < 4; j++) {
        $.each(tableValue[split * j + i], function(key, value) {
          if (typeof(value) === "number") {
            $("", {
              "class": "text-right color" + (j + 1)
            }).html(value).appendTo($tr);
          } else {
            $("", {
              "class": "text-left color" + (j + 1)
            }).html(value).appendTo($tr);
          }

        });
      }
      $tr.appendTo($tb);
    }
    $tbl.append($tb);
    $("#DisplayTable").html($tbl);
  }

});

tbody>tr>td {
  white-space: normal;
  border-collapse: collapse;
  font-family: Verdana;
  font-weight: bold;
  font-size: .9em;
}

td:nth-child(2),
td:nth-child(4),
td:nth-child(6),
td:nth-child(8) {
  width: 85px;
  max-width: 85px;
  height: 63px
}

.fixed {
  table-layout: fixed;
}

.color1 {
  background: #4AD184;
}

.color2 {
  background: #EA69EF;
}

.color3 {
  background: #E1A558;
}

.color4 {
  background: #F4F065;
}

.hidden,
.already-shown {
  display: none;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

Check This fiddle for working example with JSON data

Body:
I checked your fiddle and understood that you need to stop adding the 'already-shown' class in your last page.
I have wrapped an if condition here.

if($(".hidden:lt(12)").length > 0){
  $("tr:not(.hidden):not(.already-shown)").addClass("already-shown");
}

You should also consider clearing the setInterval in the else block.

Adding fiddle for your reference https://jsfiddle.net/s7gqe1na/1/


来源: stackexchange

问:
How to push value in for loop to the mongo document?
I want to store every day of the year in the Mongo Database.

I'm not quite sure how to do this. I've been trying to use $push method and .update method. They both seems to be bad in this case.

My controller:

```<code>exports.reflux = (req, res) => {
    const newDay = new Calendar();

    for(let i=3; i<367; i++) {
        newDay({$push: {day: new Date(new Date().getFullYear(), 0, i), offWork: true, description: ' '}});

    }
    // for(let i=3; i<367; i++){
    //
    //     {$push: {newDay.day = new Date(new Date().getFullYear(), 0, i);}}
    //     newDay.day =
    //     newDay.offWork = true;
    //     newDay.description = '';
    // }

    newDay.save();

};
</code>```

I expect the output to be collection of ducuments for every single day of the year.

答:
Ok, Done.</p>

```<code>exports.reflux = (req, res) => {
    for(let i=3; i<367; i++) {
        const newDay = new Calendar();
        newDay.day = new Date(new Date().getFullYear(), 0, i);
        newDay.offWork = true;
        newDay.description = '';

        newDay.save(err => {
            if(err) {
                console.log('error');
            }
        });

    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to store every day of the year in the Mongo Database.

I'm not quite sure how to do this. I've been trying to use $push method and .update method. They both seems to be bad in this case.

My controller:

exports.reflux = (req, res) => {
    const newDay = new Calendar();

    for(let i=3; i<367; i++) {
        newDay({$push: {day: new Date(new Date().getFullYear(), 0, i), offWork: true, description: ' '}});

    }
    // for(let i=3; i<367; i++){
    //
    //     {$push: {newDay.day = new Date(new Date().getFullYear(), 0, i);}}
    //     newDay.day =
    //     newDay.offWork = true;
    //     newDay.description = '';
    // }

    newDay.save();

};

I expect the output to be collection of ducuments for every single day of the year.

Body:
Ok, Done.

exports.reflux = (req, res) => {
    for(let i=3; i<367; i++) {
        const newDay = new Calendar();
        newDay.day = new Date(new Date().getFullYear(), 0, i);
        newDay.offWork = true;
        newDay.description = '';

        newDay.save(err => {
            if(err) {
                console.log('error');
            }
        });

    }


问:
Prevent springboot failsafe plugin default execution
I have a sample springboot java application.
This is my pom file

```<code>    <groupId>com.sample.this</groupId>
    <artifactId>example</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
    </parent>

<profiles>
    <profile>
        <id>profile1</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-failsafe-plugin</artifactId>
                    <executions>
                        <execution>
                            <id>id1</id>
                            <goals>
                                <goal>integration-test</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>
</code>```

When I run mvn verify -Pprofile1, the failsafe plugin runs twice.

Here are the logs -

```<code>[INFO] --- maven-failsafe-plugin:2.22.1:integration-test (default) @ junit.example ---
.
.
.
[INFO] --- maven-failsafe-plugin:2.22.1:integration-test (id1) @ junit.example ---
</code>```

When I remove springboot starter parent pom, then the failsafe plugin runs once as expected. Here is that log -

```<code>[INFO] --- maven-failsafe-plugin:2.22.1:integration-test (id1) @ junit.example ---
</code>```

So, springboot runs its default failsafe plugin in integration-test phase if it doesnt find one in my pom.

I cant add a default execution step in my failsafe plugin declaration.
How do I stop springboot to stop running its failsafe plugin ?

I can add this in my pom to make it work -

```<code>                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                        </goals>
                        <configuration>
                            <skipITs>true</skipITs>
                        </configuration>
                    </execution>
</code>```

But this doesnt look intuitive .

Is there any other way around ?

I dont want to add springboot plugin in my pom file

答:
Please check the following. Here, default execution has been disabled:</p>

```<code>     <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
    </parent>

    <profiles>
        <profile>
            <id>profile1</id>
            <build>
                <plugins>
                    <plugin>
                        <artifactId>maven-failsafe-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>default</id>
                                <phase>none</phase>
                            </execution>
                            <execution>
                                <id>id1</id>
                                <goals>
                                    <goal>integration-test</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

</code>```

Body:
I have a sample springboot java application.
This is my pom file

    <groupId>com.sample.this</groupId>
    <artifactId>example</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
    </parent>

<profiles>
    <profile>
        <id>profile1</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-failsafe-plugin</artifactId>
                    <executions>
                        <execution>
                            <id>id1</id>
                            <goals>
                                <goal>integration-test</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>

When I run mvn verify -Pprofile1, the failsafe plugin runs twice.

Here are the logs -

[INFO] --- maven-failsafe-plugin:2.22.1:integration-test (default) @ junit.example ---
.
.
.
[INFO] --- maven-failsafe-plugin:2.22.1:integration-test (id1) @ junit.example ---

When I remove springboot starter parent pom, then the failsafe plugin runs once as expected. Here is that log -

[INFO] --- maven-failsafe-plugin:2.22.1:integration-test (id1) @ junit.example ---

So, springboot runs its default failsafe plugin in integration-test phase if it doesnt find one in my pom.

I cant add a default execution step in my failsafe plugin declaration.
How do I stop springboot to stop running its failsafe plugin ?

I can add this in my pom to make it work -

                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                        </goals>
                        <configuration>
                            <skipITs>true</skipITs>
                        </configuration>
                    </execution>

But this doesnt look intuitive .

Is there any other way around ?

I dont want to add springboot plugin in my pom file

Body:
Please check the following. Here, default execution has been disabled:

     <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
    </parent>

    <profiles>
        <profile>
            <id>profile1</id>
            <build>
                <plugins>
                    <plugin>
                        <artifactId>maven-failsafe-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>default</id>
                                <phase>none</phase>
                            </execution>
                            <execution>
                                <id>id1</id>
                                <goals>
                                    <goal>integration-test</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>


问:
Select range of two columns which are also greater
I have a case where there is a table with order value and those limits and ranges like below

```<code>Id       Value       Range_From         Range_To

1        360.0         500               1000
2        1001.0        1001              2000
3        3000.0        1001              2000
</code>```

I need an output of 3rd record where the 2nd and 3rd records fall between 1001 and 2000. But when I query that using SQL BETWEEN I am only getting the record 2 because that is falling under Range_From and Range_To for Between condition.

Example:

```<code>SELECT * FROM Table WHERE Value BETWEEN Range_From AND Range_To;
</code>```

The above query will only give the 2nd record. How to get the third record as this is also satisfying the condition.

Also I only need to get the record as output which ever value is highest and it should also fall in the Range_From and Range_To

答:
I think you want below query:

```<code>SELECT * FROM (
        SELECT value, row_number() over(order by value desc) as RN FROM Table WHERE Value BETWEEN Range_From AND Range_To;
) A WHERE RN = 1
</code>```

You won't be able to get the 3rd row because it doesn't satisfy the condition. 3000 is not between 1001 and 2000

Body:
I have a case where there is a table with order value and those limits and ranges like below

Id       Value       Range_From         Range_To

1        360.0         500               1000
2        1001.0        1001              2000
3        3000.0        1001              2000

I need an output of 3rd record where the 2nd and 3rd records fall between 1001 and 2000. But when I query that using SQL BETWEEN I am only getting the record 2 because that is falling under Range_From and Range_To for Between condition.

Example:

SELECT * FROM Table WHERE Value BETWEEN Range_From AND Range_To;

The above query will only give the 2nd record. How to get the third record as this is also satisfying the condition.

Also I only need to get the record as output which ever value is highest and it should also fall in the Range_From and Range_To

Body:
I think you want below query:

SELECT * FROM (
        SELECT value, row_number() over(order by value desc) as RN FROM Table WHERE Value BETWEEN Range_From AND Range_To;
) A WHERE RN = 1

You won't be able to get the 3rd row because it doesn't satisfy the condition. 3000 is not between 1001 and 2000


问:
Form not found or not recognized
I have ModelMultipleChoiceField form in my form.py like this :

```<code>class UserResponseSearchForm(forms.Form):
    def __init__(self, *args, **kwargs):
        qry = kwargs.pop('qry')
        super(UserResponseSearchForm,self).__init__(*args, **kwargs)
        self.fields['gejala_id0'] = forms.ModelMultipleChoiceField(queryset=Gejala.objects.filter(gejala__icontains=qry).values_list('gejala', flat=True).distinct().order_by('gejala'),widget=forms.CheckboxSelectMultiple, required=False)

    gejala_id1 = forms.ModelMultipleChoiceField(queryset=Gejala.objects.all().values_list('gejala', flat=True).distinct().filter(id_organ=1).order_by('gejala'), widget=forms.CheckboxSelectMultiple, required=False)
    gejala_id2 = forms.ModelMultipleChoiceField(queryset=Gejala.objects.all().values_list('gejala', flat=True).distinct().filter(id_organ=2).order_by('gejala'), widget=forms.CheckboxSelectMultiple, required=False)
    gejala_id3 = forms.ModelMultipleChoiceField(queryset=Gejala.objects.all().values_list('gejala', flat=True).distinct().filter(id_organ=3).order_by('gejala'), widget=forms.CheckboxSelectMultiple, required=False)
</code>```

And my views.py like this :

```<code>def responsePenyakit(request):
if request.user.is_authenticated:
    if request.method == 'POST':
        form = UserResponseForm(request.POST)
        gejala0 = form["gejala_id0"].data
        gejala1 = form["gejala_id1"].data
        gejala2 = form["gejala_id2"].data
        gejala3 = form["gejala_id3"].data

        if (len(gejala0) > 0):
            for i in range(0, len(gejala0)):
                userAnswer = UserAnswer()
                userAnswer.gejala_answer = gejala1[i]
                userAnswer.user_id = request.user.id
                userAnswer.number_diagnosis = user.number_diagnosis + 1
                userAnswer.save()
                print(gejala0)

        if (len(gejala1) > 0):
            for i in range(0, len(gejala1)):
                userAnswer = UserAnswer()
                userAnswer.gejala_answer = gejala1[i]
                userAnswer.user_id = request.user.id
                userAnswer.number_diagnosis = user.number_diagnosis + 1
                userAnswer.save()

        if (len(gejala2) > 0):
            for i in range(0, len(gejala2)):
                userAnswer = UserAnswer()
                userAnswer.gejala_answer = gejala2[i]
                userAnswer.user_id = request.user.id
                userAnswer.number_diagnosis = user.number_diagnosis + 1
                userAnswer.save()

        if (len(gejala3) > 0):
            for i in range(0, len(gejala3)):
                userAnswer = UserAnswer()
                userAnswer.gejala_answer = gejala3[i]
                userAnswer.user_id = request.user.id
                userAnswer.number_diagnosis = user.number_diagnosis + 1
                userAnswer.save()
    return redirect('diagnosis_penyakit:response_matching')
else:
    raise Http404
</code>```

I want to get the data what i choose from gejala_id0 form. I try to get the data like what i do in my views.py.

But there is return error Key 'gejala_id0' not found in 'UserResponseForm'. What's the problem in there? I think what i do is correct. CMIIW

Please help me. I am new in django

答:
create field first and then change queryset in __init__.

```<code>class UserResponseSearchForm(forms.Form):
    def __init__(self, *args, **kwargs):
        qry = kwargs.pop('qry')
        super(UserResponseSearchForm,self).__init__(*args, **kwargs)
        self.fields['gejala_id0'].queryset = Gejala.objects.filter(gejala__icontains=qry).values_list('gejala', flat=True).distinct().order_by('gejala')

    gejala_id0 = forms.ModelMultipleChoiceField(queryset=Gejala.objects.none(), widget=forms.CheckboxSelectMultiple, required=False)
    gejala_id1 = forms.ModelMultipleChoiceField(queryset=Gejala.objects.all().values_list('gejala', flat=True).distinct().filter(id_organ=1).order_by('gejala'), widget=forms.CheckboxSelectMultiple, required=False)
    gejala_id2 = forms.ModelMultipleChoiceField(queryset=Gejala.objects.all().values_list('gejala', flat=True).distinct().filter(id_organ=2).order_by('gejala'), widget=forms.CheckboxSelectMultiple, required=False)
    gejala_id3 = forms.ModelMultipleChoiceField(queryset=Gejala.objects.all().values_list('gejala', flat=True).distinct().filter(id_organ=3).order_by('gejala'), widget=forms.CheckboxSelectMultiple, required=False)
</code>```

also send qry to form:

```<code>def responsePenyakit(request):
if request.user.is_authenticated:
    if request.method == 'POST':
        form = UserResponseForm(data=request.POST, qry=query)
</code>```

Title: Form not found or not recognized

Body:
I have ModelMultipleChoiceField form in my form.py like this :

class UserResponseSearchForm(forms.Form):
    def __init__(self, *args, **kwargs):
        qry = kwargs.pop('qry')
        super(UserResponseSearchForm,self).__init__(*args, **kwargs)
        self.fields['gejala_id0'] = forms.ModelMultipleChoiceField(queryset=Gejala.objects.filter(gejala__icontains=qry).values_list('gejala', flat=True).distinct().order_by('gejala'),widget=forms.CheckboxSelectMultiple, required=False)

    gejala_id1 = forms.ModelMultipleChoiceField(queryset=Gejala.objects.all().values_list('gejala', flat=True).distinct().filter(id_organ=1).order_by('gejala'), widget=forms.CheckboxSelectMultiple, required=False)
    gejala_id2 = forms.ModelMultipleChoiceField(queryset=Gejala.objects.all().values_list('gejala', flat=True).distinct().filter(id_organ=2).order_by('gejala'), widget=forms.CheckboxSelectMultiple, required=False)
    gejala_id3 = forms.ModelMultipleChoiceField(queryset=Gejala.objects.all().values_list('gejala', flat=True).distinct().filter(id_organ=3).order_by('gejala'), widget=forms.CheckboxSelectMultiple, required=False)

And my views.py like this :

def responsePenyakit(request):
if request.user.is_authenticated:
    if request.method == 'POST':
        form = UserResponseForm(request.POST)
        gejala0 = form["gejala_id0"].data
        gejala1 = form["gejala_id1"].data
        gejala2 = form["gejala_id2"].data
        gejala3 = form["gejala_id3"].data

        if (len(gejala0) > 0):
            for i in range(0, len(gejala0)):
                userAnswer = UserAnswer()
                userAnswer.gejala_answer = gejala1[i]
                userAnswer.user_id = request.user.id
                userAnswer.number_diagnosis = user.number_diagnosis + 1
                userAnswer.save()
                print(gejala0)

        if (len(gejala1) > 0):
            for i in range(0, len(gejala1)):
                userAnswer = UserAnswer()
                userAnswer.gejala_answer = gejala1[i]
                userAnswer.user_id = request.user.id
                userAnswer.number_diagnosis = user.number_diagnosis + 1
                userAnswer.save()

        if (len(gejala2) > 0):
            for i in range(0, len(gejala2)):
                userAnswer = UserAnswer()
                userAnswer.gejala_answer = gejala2[i]
                userAnswer.user_id = request.user.id
                userAnswer.number_diagnosis = user.number_diagnosis + 1
                userAnswer.save()

        if (len(gejala3) > 0):
            for i in range(0, len(gejala3)):
                userAnswer = UserAnswer()
                userAnswer.gejala_answer = gejala3[i]
                userAnswer.user_id = request.user.id
                userAnswer.number_diagnosis = user.number_diagnosis + 1
                userAnswer.save()
    return redirect('diagnosis_penyakit:response_matching')
else:
    raise Http404

I want to get the data what i choose from gejala_id0 form. I try to get the data like what i do in my views.py.

But there is return error Key 'gejala_id0' not found in 'UserResponseForm'. What's the problem in there? I think what i do is correct. CMIIW

Please help me. I am new in django

Body:
create field first and then change queryset in __init__.

class UserResponseSearchForm(forms.Form):
    def __init__(self, *args, **kwargs):
        qry = kwargs.pop('qry')
        super(UserResponseSearchForm,self).__init__(*args, **kwargs)
        self.fields['gejala_id0'].queryset = Gejala.objects.filter(gejala__icontains=qry).values_list('gejala', flat=True).distinct().order_by('gejala')

    gejala_id0 = forms.ModelMultipleChoiceField(queryset=Gejala.objects.none(), widget=forms.CheckboxSelectMultiple, required=False)
    gejala_id1 = forms.ModelMultipleChoiceField(queryset=Gejala.objects.all().values_list('gejala', flat=True).distinct().filter(id_organ=1).order_by('gejala'), widget=forms.CheckboxSelectMultiple, required=False)
    gejala_id2 = forms.ModelMultipleChoiceField(queryset=Gejala.objects.all().values_list('gejala', flat=True).distinct().filter(id_organ=2).order_by('gejala'), widget=forms.CheckboxSelectMultiple, required=False)
    gejala_id3 = forms.ModelMultipleChoiceField(queryset=Gejala.objects.all().values_list('gejala', flat=True).distinct().filter(id_organ=3).order_by('gejala'), widget=forms.CheckboxSelectMultiple, required=False)

also send qry to form:

def responsePenyakit(request):
if request.user.is_authenticated:
    if request.method == 'POST':
        form = UserResponseForm(data=request.POST, qry=query)


问:
How to hide whole line of text with words
I tried to follow the format for when I was hiding pets in my game but it didn't turn out the same.

How would I hide a line like this? I get how to hide a radio button.

I've tried something similar to what I did for radio buttons but it didn't turn out the same. how do I give those lines of text/other things a name so I can hide then till a condition is met?

This is my current Javascript:

```<code>var Silver = document.getElementById('Silver');
var Gold = document.getElementById('Gold');
var Diamond = document.getElementById('Diamond');

function checkUnlockOre() {
    if (Mininglv >= 10) {
        Silver.style.visibility = 'visible'
    } else {
        Silver.style.visibility = 'hidden'
    }
     if (Mininglv >= 20) {
        Gold.style.visibility = 'visible'
    } else {
         Gold.style.visibility = 'hidden'
    }
    if (Mininglv >= 30) {
         Diamond.style.visibility = 'visible'
    } else {
        Diamond.style.visibility = 'hidden'
    }

}

checkUnlockOre()
</code>```

HTML code:

```<code><div>
    <br />
    Bronze: <span id="Bronze">0</span>
    <br />
    Silver: <span id="Silver">0</span>
    <br />
    Gold: <span id="Gold">0</span>
    <br />
    Diamond: <span id="Diamond">0</span>
</div>
</code>```

I expect the ores to be not visible until a condition is met, but my actual outcome they are all visible and I can't figure out how to hide those lines.

答:
Add parent span and hide full part based on condition.

var Silver = document.getElementById('Silver');
var Gold = document.getElementById('Gold');
var Diamond = document.getElementById('Diamond');

var SilverParent = document.getElementById('SilverParent');
var GoldParent = document.getElementById('GoldParent');
var DiamondParent = document.getElementById('DiamondParent');

var Mininglv = 5;
function checkUnlockOre() {
    if (Mininglv >= 10) {
        SilverParent.style.visibility = 'visible'
    } else {
        SilverParent.style.visibility = 'hidden'
    }
     if (Mininglv >= 20) {
        GoldParent.style.visibility = 'visible'
    } else {
         GoldParent.style.visibility = 'hidden'
    }
    if (Mininglv >= 30) {
         DiamondParent.style.visibility = 'visible'
    } else {
        DiamondParent.style.visibility = 'hidden'
    }

}

checkUnlockOre()```
<pre class="snippet-code-html lang-html prettyprint-override"><code><br />
  <span id="BronzeParent">
  Bronze: <span id="Bronze">0</span>
   <br />
  </span>

  <span id="SilverParent">
  Silver: <span id="Silver">0</span>
  <br />
  </span>

  <span id="GoldParent">
  Gold: <span id="Gold">0</span>
  <br />
  </span>

  <span id="DiamondParent">
  Diamond: <span id="Diamond">0</span>
  </span>
</div></code>```

Body:
I tried to follow the format for when I was hiding pets in my game but it didn't turn out the same.

How would I hide a line like this? I get how to hide a radio button.

I've tried something similar to what I did for radio buttons but it didn't turn out the same. how do I give those lines of text/other things a name so I can hide then till a condition is met?

This is my current Javascript:

var Silver = document.getElementById('Silver');
var Gold = document.getElementById('Gold');
var Diamond = document.getElementById('Diamond');

function checkUnlockOre() {
    if (Mininglv >= 10) {
        Silver.style.visibility = 'visible'
    } else {
        Silver.style.visibility = 'hidden'
    }
     if (Mininglv >= 20) {
        Gold.style.visibility = 'visible'
    } else {
         Gold.style.visibility = 'hidden'
    }
    if (Mininglv >= 30) {
         Diamond.style.visibility = 'visible'
    } else {
        Diamond.style.visibility = 'hidden'
    }

}

checkUnlockOre()

HTML code:

    Bronze: 0

    Silver: 0

    Gold: 0

    Diamond: 0

I expect the ores to be not visible until a condition is met, but my actual outcome they are all visible and I can't figure out how to hide those lines.

Body:
Add parent span and hide full part based on condition.

var Silver = document.getElementById('Silver');
var Gold = document.getElementById('Gold');
var Diamond = document.getElementById('Diamond');

var SilverParent = document.getElementById('SilverParent');
var GoldParent = document.getElementById('GoldParent');
var DiamondParent = document.getElementById('DiamondParent');

var Mininglv = 5;
function checkUnlockOre() {
    if (Mininglv >= 10) {
        SilverParent.style.visibility = 'visible'
    } else {
        SilverParent.style.visibility = 'hidden'
    }
     if (Mininglv >= 20) {
        GoldParent.style.visibility = 'visible'
    } else {
         GoldParent.style.visibility = 'hidden'
    }
    if (Mininglv >= 30) {
         DiamondParent.style.visibility = 'visible'
    } else {
        DiamondParent.style.visibility = 'hidden'
    }

}

checkUnlockOre()

<br />
  <span id="BronzeParent">
  Bronze: <span id="Bronze">0</span>
   <br />
  </span>

  <span id="SilverParent">
  Silver: <span id="Silver">0</span>
  <br />
  </span>

  <span id="GoldParent">
  Gold: <span id="Gold">0</span>
  <br />
  </span>

  <span id="DiamondParent">
  Diamond: <span id="Diamond">0</span>
  </span>
</div>


问:
AWS ELB Intermittent 502 gateway timeout error
I have an ELB in front of a node.js application deployed on 3 EC2 instances.

I have started observing intermittent HTTP 502 Bad Gateway error.

Following is an excerpt from my access logs. There is no pattern to these 502 errors so I am unable to narrow down the cause ?

Is it an ELB issue or an app issue ?

Can access logs help me figure this out ?

This occurs for 5 requests in every 100 requests

```<code>*type*                     https
*timestamp*                2019-05-08T14:50:11.438405Z
*elb*                      <my-elb>
*client:port*              clientIp:port
*target:port*              targetIp:port
*request_processing_time*  0
*target_processing_time*.  2.596
*response_processing_time* -1
*elb_status_code*          502
*target_status_code*       -
*received_bytes*           792
*sent_bytes*               293
*request*                  POST https://app/app-url/2.0/resourcepath/id/abc?queryParamA=abc&queryParamB=false&queryParamC=6b84c34 HTTP/1.1
*user_agent*               Apache-CXF/3.2.5
*ssl_cipher*               ssl-cipher
*ssl_protocol*             TLSv1.2
*target_group_arn*         arn
*trace_id*                 traceId
*domain_name*              cool-domain-name
*chosen_cert_arn*          session-reused
*matched_rule_priority*    0
*request_creation_time*    2019-05-08T14:50:08.841000Z
*actions_executed*         forward
*redirect_url*             -
*error_reason*             -
</code>```

答:
Here is a reference link to start with:
https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-troubleshooting.html#http-502-issues

The most common among them is the backend keep-alive is less then the ELB , ELB keeps the connection open while backend has closed it and when ELB uses the same TCP connection, it gets RESET.

Body:
I have an ELB in front of a node.js application deployed on 3 EC2 instances.

I have started observing intermittent HTTP 502 Bad Gateway error.

Following is an excerpt from my access logs. There is no pattern to these 502 errors so I am unable to narrow down the cause ?

Is it an ELB issue or an app issue ?

Can access logs help me figure this out ?

This occurs for 5 requests in every 100 requests

*type*                     https
*timestamp*                2019-05-08T14:50:11.438405Z
*elb*                      <my-elb>
*client:port*              clientIp:port
*target:port*              targetIp:port
*request_processing_time*  0
*target_processing_time*.  2.596
*response_processing_time* -1
*elb_status_code*          502
*target_status_code*       -
*received_bytes*           792
*sent_bytes*               293
*request*                  POST https://app/app-url/2.0/resourcepath/id/abc?queryParamA=abc&queryParamB=false&queryParamC=6b84c34 HTTP/1.1
*user_agent*               Apache-CXF/3.2.5
*ssl_cipher*               ssl-cipher
*ssl_protocol*             TLSv1.2
*target_group_arn*         arn
*trace_id*                 traceId
*domain_name*              cool-domain-name
*chosen_cert_arn*          session-reused
*matched_rule_priority*    0
*request_creation_time*    2019-05-08T14:50:08.841000Z
*actions_executed*         forward
*redirect_url*             -
*error_reason*             -


问:
DatagridView: How to delete selected cells
There are number of questions on here about how to delete selected rows, but none about how to delete selected cells. That is, I would like for the user to be able to select cells from different rows and different columns, and be able to delete the contents. What I currenlty have is :

```<code>private void btnDelete_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
        {
            int rowIndex = cell.RowIndex;
            int colIndex = cell.ColumnIndex;
            dataGridView1.Rows[rowIndex].Cells[colIndex].Value = 0;
        }
    }
</code>```

So the user has to select the required cells and then push the delete button(here I assumed all my columns are of numeric type, so 0 works). But it doesn't leave the cells completely empty. Here is another attempt:

```<code>private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
    {
          if (e.KeyCode == Keys.Delete && dataGridView1.CurrentCell.Selected)
        {
           dataGridView1.CurrentCell.Value = null;
           e.Handled = true;
        }
    }
</code>```

Unfortunately this event gets caught by my dataGridView1_DataError event, where I have

```<code>bindingSource1.CancelEdit();
</code>```

And so I can't assign null to cell contents.

Goal

I would like to emulate the row delete behaviour, where you can select a row, push the delete key and then all cell contents of that row are left blank. I would like to do this, instead of leaving zeros in the cells. How can I do that?

答:
Please use the following code:</p>

```<code>private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Delete)
    {
        foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
        {
            cell.Value = "";
        }
        e.Handled = true;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
There are number of questions on here about how to delete selected rows, but none about how to delete selected cells. That is, I would like for the user to be able to select cells from different rows and different columns, and be able to delete the contents. What I currenlty have is :

private void btnDelete_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
        {
            int rowIndex = cell.RowIndex;
            int colIndex = cell.ColumnIndex;
            dataGridView1.Rows[rowIndex].Cells[colIndex].Value = 0;
        }
    }

So the user has to select the required cells and then push the delete button(here I assumed all my columns are of numeric type, so 0 works). But it doesn't leave the cells completely empty. Here is another attempt:

private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
    {
          if (e.KeyCode == Keys.Delete && dataGridView1.CurrentCell.Selected)
        {
           dataGridView1.CurrentCell.Value = null;
           e.Handled = true;
        }
    }

Unfortunately this event gets caught by my dataGridView1_DataError event, where I have

bindingSource1.CancelEdit();

And so I can't assign null to cell contents.

Goal

I would like to emulate the row delete behaviour, where you can select a row, push the delete key and then all cell contents of that row are left blank. I would like to do this, instead of leaving zeros in the cells. How can I do that?

Body:
Please use the following code:

private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Delete)
    {
        foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
        {
            cell.Value = "";
        }
        e.Handled = true;
    }
}


答:
You can use

insertMany

First, create an array of objects (all your days) then do insert

```<code>let days = [];
for(let i=3; i<367; i++) {
    days.push({day: new Date(new Date().getFullYear(), 0, i), offWork: true, description: ' '});
}

newDay.insertMany(days, function(err) {

});
</code>```

Title: How to push value in for loop to the mongo document?

Body:
You can use

insertMany

First, create an array of objects (all your days) then do insert

let days = [];
for(let i=3; i<367; i++) {
    days.push({day: new Date(new Date().getFullYear(), 0, i), offWork: true, description: ' '});
}

newDay.insertMany(days, function(err) {

});


问:
How can you run a python function stored in a different file
I know how to do this in C, but I'm not sure how to do it in python. I'm trying to make a python program which will read from an external file, then execute a function name which was read from that file. Example:

File structure:

```<code>main.py
map.py
Scripts/
  script1.py
</code>```

map.py contains just an array and a function to get the correct array index:

```<code>map = ["One","script1.function_one","Two","scrip1.function_two"]
def return_mapping(str):
  for i in range(0,len(map)):
    if str in map[i]:
      return map[i+1]
</code>```

The functions: "function_one()" and "function_two()" are defined in script1.py.
main.py will contain something like this:

```<code>selection = raw_input("What function would you like to run?")
function_ptr = map.return_mapping(selection)
#This is where I don't know what the correct code is... I want to now execute
#whatever function was returned.
</code>```

Any suggestions?

答:
If you want to be able to use a path to any file, no matter where it is:</p>

```<code>import imp
import sys

mod = imp.load_source('any_name', 'path_to_your_file')
# this will get and execute your function
get_attr(mod, 'your_function_name')()
# if you want to execute load_source more than once you have to do the following, otherwise the code is not updated:
del sys.modules['any_name']
</code>```

Body:
I know how to do this in C, but I'm not sure how to do it in python. I'm trying to make a python program which will read from an external file, then execute a function name which was read from that file. Example:

File structure:

main.py
map.py
Scripts/
  script1.py

map.py contains just an array and a function to get the correct array index:

map = ["One","script1.function_one","Two","scrip1.function_two"]
def return_mapping(str):
  for i in range(0,len(map)):
    if str in map[i]:
      return map[i+1]

The functions: "function_one()" and "function_two()" are defined in script1.py.
main.py will contain something like this:

selection = raw_input("What function would you like to run?")
function_ptr = map.return_mapping(selection)
#This is where I don't know what the correct code is... I want to now execute
#whatever function was returned.

Any suggestions?

Body:
If you want to be able to use a path to any file, no matter where it is:

import imp
import sys

mod = imp.load_source('any_name', 'path_to_your_file')
# this will get and execute your function
get_attr(mod, 'your_function_name')()
# if you want to execute load_source more than once you have to do the following, otherwise the code is not updated:
del sys.modules['any_name']


问:
Laravel 'WHERE' function in query breaks API?
I'm trying to make Gantt's chart using DHTMLX Gantt API.

The goal is to show only certain Gantt's lines to certain users. So for example: if I open a contract it shows me the Gantt's chart of that contract, but if I have permission for ex: purchases, then it should only show me the line with certain permission ID which is in the DB table Task.

Now the problem is somewhere around this function:

```<code>    public function getOne($id){
      $tasks = new Task();
      $links = new Link();

      return response()->json([
          "data" => $tasks->where('relation_id', $id)->where('permission', 2)->get(),
          "links" => $links->all()
      ]);
    }
</code>```

The 'relation_id' works fine and shows only a single project, but when I try to add another WHERE it just breaks without errors and doesn't load the chart information.

I think it has to do something with the JSON as if I do just send this query on any other page without inserting into GANTT (just as JSON) it shows me the correct information.

So basically I need to make that query work with this API, I have no clue about why 1 extra line of statement would break it.

I also tried the WHERE statement like this:

```<code>"data" => $tasks->where([['relation_id', '=', $id],['permission','=',2]])->get()
</code>```

Here is the link to the Gantt chart: link

I followed the steps in their documentation to start: link

答:
Hi your instantiating an object and trying to access a static method hence, its failing

try this

```<code>public function getOne($id){
  $tasks = Task::query();
  $links = Link::query();

  return response()->json([
      "data" => $tasks->where('relation_id', $id)->where('permission', 2)->get(),
      "links" => $links->get()
  ]);
}
</code>```

Body:
I'm trying to make Gantt's chart using DHTMLX Gantt API.

The goal is to show only certain Gantt's lines to certain users. So for example: if I open a contract it shows me the Gantt's chart of that contract, but if I have permission for ex: purchases, then it should only show me the line with certain permission ID which is in the DB table Task.

Now the problem is somewhere around this function:

    public function getOne($id){
      $tasks = new Task();
      $links = new Link();

      return response()->json([
          "data" => $tasks->where('relation_id', $id)->where('permission', 2)->get(),
          "links" => $links->all()
      ]);
    }

The 'relation_id' works fine and shows only a single project, but when I try to add another WHERE it just breaks without errors and doesn't load the chart information.

I think it has to do something with the JSON as if I do just send this query on any other page without inserting into GANTT (just as JSON) it shows me the correct information.

So basically I need to make that query work with this API, I have no clue about why 1 extra line of statement would break it.

I also tried the WHERE statement like this:

"data" => $tasks->where([['relation_id', '=', $id],['permission','=',2]])->get()

Here is the link to the Gantt chart: link

I followed the steps in their documentation to start: link

Body:
Hi your instantiating an object and trying to access a static method hence, its failing

try this

public function getOne($id){
  $tasks = Task::query();
  $links = Link::query();

  return response()->json([
      "data" => $tasks->where('relation_id', $id)->where('permission', 2)->get(),
      "links" => $links->get()
  ]);
}


问:
How to calculate days and float in one own function
i want calculate days and float in my function

so this is my dataframe

```<code>In[1]
df = {'Loan Nego': [2019-03-01, 2019-03-01], 'New Maturity': [2019-03-11, 2019-03-29],'Loan Amount in OCUR': [1000, 2000]}

Out[1]
Loan Nego          New Maturity          Loan Amount in OCUR
2019-03-01         2019-03-11            1000
2019-03-01         2019-03-29            2000

In[2]
df.dtypes

Out[2]

New Maturity               datetime64[ns]
Loan Nego                  datetime64[ns]
Loan Amount in OCUR        float64

</code>```

and i want to input this data frame into my function

```<code># Equation CLOF
def clof(loan,maturity, amount):
days = (maturity-loan).days
return ((amount * days)/ 360) * (2.36/100)
</code>```

i've tried but ther's is alert like this

AttributeError: 'Series' object has no attribute 'days'

```<code>df["New Interest"] = clof(df["Loan Nego"],df["New Maturity"],df["Loan Amount in OCUR"])
</code>```

it doesn't work,

AttributeError: 'Series' object has no attribute 'days

my expectation

```<code>Loan Nego          New Maturity          Loan Amount in OCUR       New Interest
2019-03-01         2019-03-11            1000                        0.65
2019-03-01         2019-03-29            2000                        3.671

</code>```

Ther's solution?

答:
Use Series.dt.days, because working with Series in your function, not with scalars:

```<code>def clof(loan,maturity, amount):
    days = (maturity-loan).dt.days
    return ((amount * days)/ 360) * (2.36/100)

df["New Interest"] = clof(df["Loan Nego"],df["New Maturity"],df["Loan Amount in OCUR"])
print (df)
   Loan Nego New Maturity  Loan Amount in OCUR  New Interest
0 2019-03-01   2019-03-11                 1000      0.655556
1 2019-03-01   2019-03-29                 2000      3.671111
</code>```

Body:
i want calculate days and float in my function

so this is my dataframe

In[1]
df = {'Loan Nego': [2019-03-01, 2019-03-01], 'New Maturity': [2019-03-11, 2019-03-29],'Loan Amount in OCUR': [1000, 2000]}

Out[1]
Loan Nego          New Maturity          Loan Amount in OCUR
2019-03-01         2019-03-11            1000
2019-03-01         2019-03-29            2000

In[2]
df.dtypes

Out[2]

New Maturity               datetime64[ns]
Loan Nego                  datetime64[ns]
Loan Amount in OCUR        float64

and i want to input this data frame into my function

# Equation CLOF
def clof(loan,maturity, amount):
days = (maturity-loan).days
return ((amount * days)/ 360) * (2.36/100)

i've tried but ther's is alert like this

AttributeError: 'Series' object has no attribute 'days'

df["New Interest"] = clof(df["Loan Nego"],df["New Maturity"],df["Loan Amount in OCUR"])

it doesn't work,

AttributeError: 'Series' object has no attribute 'days

my expectation

Loan Nego          New Maturity          Loan Amount in OCUR       New Interest
2019-03-01         2019-03-11            1000                        0.65
2019-03-01         2019-03-29            2000                        3.671

Ther's solution?

Body:
Use Series.dt.days, because working with Series in your function, not with scalars:

def clof(loan,maturity, amount):
    days = (maturity-loan).dt.days
    return ((amount * days)/ 360) * (2.36/100)

df["New Interest"] = clof(df["Loan Nego"],df["New Maturity"],df["Loan Amount in OCUR"])
print (df)
   Loan Nego New Maturity  Loan Amount in OCUR  New Interest
0 2019-03-01   2019-03-11                 1000      0.655556
1 2019-03-01   2019-03-29                 2000      3.671111


问:
Replacing a portion of a string with an exact matching
I just want to replace a portion of a string only if matches the given text.
My use case is as follows:

```<code>    var text = "<wd:response><wd:response-data></wd:response-data></wd:response >";
    string result = text.Replace("wd:response", "response");

    /*
     * expecting the below text
      <response><wd:response-data></wd:response-data></response>
     *
     */
</code>```

I followed the following answers:

Way to have String.Replace only hit "whole words"

Regular expression for exact match of a string

But I failed to achieve what I want.

Please share your thoughts/solutions.

Sample on
https://dotnetfiddle.net/pMkO8Q

答:
In general, you should really be parsing and manipulating XML as XML, using functions that know how XML works and what's legal in the language. Regex and other naive text manipulation will often lead you into trouble.

That said, for a very simple solution to this specific problem, you can do this with two replaces:

```<code>var text = "<wd:response><wd:response-data></wd:response-data></wd:response >";
text.Replace("wd:response>", "response>").Replace("wd:response ", "response ")
</code>```

(Note the spaces at the end of the parameters to the second replace.)

Alternatively use a regex similar to "wd:response\s*>"

Body:
I just want to replace a portion of a string only if matches the given text.
My use case is as follows:

    var text = "<wd:response><wd:response-data></wd:response-data></wd:response >";
    string result = text.Replace("wd:response", "response");

    /*
     * expecting the below text
      <response><wd:response-data></wd:response-data></response>
     *
     */

I followed the following answers:

Way to have String.Replace only hit "whole words"

Regular expression for exact match of a string

But I failed to achieve what I want.

Please share your thoughts/solutions.

Sample on
https://dotnetfiddle.net/pMkO8Q

Body:
In general, you should really be parsing and manipulating XML as XML, using functions that know how XML works and what's legal in the language. Regex and other naive text manipulation will often lead you into trouble.

That said, for a very simple solution to this specific problem, you can do this with two replaces:

var text = "<wd:response><wd:response-data></wd:response-data></wd:response >";
text.Replace("wd:response>", "response>").Replace("wd:response ", "response ")

(Note the spaces at the end of the parameters to the second replace.)

Alternatively use a regex similar to "wd:response\s*>"


问:
Slow Transitions in react native router flux
I'm using React-Native-Router-Flux for navigations in my react native project. When I move from screen A -> B such that screen B has network call, the transition is not smooth. There is a noticeable lagging in the transition.

Any suggestions how I can make the transition more smooth?

And, I'm very deep into the project with very strict deadlines, so changing the whole navigation will be very tough for me. My router component looks like-

```<code><Scene key="drawer" component={Drawer} open={false} type="replace" initial={this.state.flag ? false : true}>
     <Scene key="root">
         <Scene key="home" component={Home} title="HOME" initial hideNavBar type="replace" />
         <Scene key="dashboard" component={Dashboard} hideNavBar={true} title="MENU DETAILS" />
         <Scene key="order" component={Order} hideNavBar={true} title="ORDER SUMMARY" />
    </Scene>
</Scene>
</code>```

Now, I use Actions.dashboard() on a button click to move to dashboard, where I have a network call in componentDidMount() which fetches the data and dispatches an action to update the reducer and as a result returns a new state.

Similarly, in Order component, I'm making network call in componentDidMount() and this time I simply do this.setState({data}) to update the component with the fetched data.

In both the navigation, Home -> Dashboard and Home -> Order, I'm having this "not smooth" transition.

答: I also had the same problem while running in Android. Just stop the JS Remote Debugging and try it  again it will then have smooth transition. I had this problem while signing in with auth with firebase. But its solved now!

Body:
I'm using React-Native-Router-Flux for navigations in my react native project. When I move from screen A -> B such that screen B has network call, the transition is not smooth. There is a noticeable lagging in the transition.

Any suggestions how I can make the transition more smooth?

And, I'm very deep into the project with very strict deadlines, so changing the whole navigation will be very tough for me. My router component looks like-

<Scene key="drawer" component={Drawer} open={false} type="replace" initial={this.state.flag ? false : true}>
     <Scene key="root">
         <Scene key="home" component={Home} title="HOME" initial hideNavBar type="replace" />
         <Scene key="dashboard" component={Dashboard} hideNavBar={true} title="MENU DETAILS" />
         <Scene key="order" component={Order} hideNavBar={true} title="ORDER SUMMARY" />
    </Scene>
</Scene>

Now, I use Actions.dashboard() on a button click to move to dashboard, where I have a network call in componentDidMount() which fetches the data and dispatches an action to update the reducer and as a result returns a new state.

Similarly, in Order component, I'm making network call in componentDidMount() and this time I simply do this.setState({data}) to update the component with the fetched data.

In both the navigation, Home -> Dashboard and Home -> Order, I'm having this "not smooth" transition.


问:
How to protect azure web app from abusive calls?
I have two web apps in azure one angular 6 the other one is .net core web api. Angular app consumes the apis to get data.  Some of these apis are public apis. It means authentication is not needed for them to be called.

My questions is, what the best approaches are to protect these public apis? By protecting, I mean not letting anonymous users to call these apis and abuse data.

In my mind these are what I can do:

CORS, but the problem is postman and other rest tool still can call my apis

Using azure api management? By rate limiting? Is there a better way?

Use some sort of api key but the angular app will expose them anyway.

In my c# app I get user agent, host, Origin of the call and restrict based on those?

Basically I want to restrict anonymous user from manipulating and calling my post apis and push not relevant or duplicate data to my back-end without using any sort of AD as my apis are going to be public. I want only a few authorized app can call my apis.

Please tell me which one of the above are the right one and please recommend a better approach.

P.S: my backend is .net core 2.2,

Thanks

答:
I can recommend below solution,

Host your APIs on Azure API app and import it to APIM. Then Configure IP restriction on API APP using the IPs of APIM. That mean, only APIM can access your API host. or you can implement client certification authentication between APIM and API host.
https://learn.microsoft.com/en-us/azure/app-service/app-service-ip-restrictions
https://learn.microsoft.com/en-us/azure/api-management/api-management-howto-mutual-certificates

02.Next enable subscription key/API key on APIM and keep these key on Azure key vault. So you don't need to hard code these keys on frontend. I hope you host this Angular app on Azure. (I am not Angular expert...just check online for docs)
https://learn.microsoft.com/en-us/azure/key-vault/quick-create-node

03.Later based on your scenario, If need you can apply Rate policies.
https://github.com/MicrosoftDocs/azure-docs/blob/master/articles/api-management/api-management-sample-flexible-throttling.md


问:
how to remove dynamic components from array
I can't cope with proper rendering after removing an element using deleteData() from an array of objects that simultaneously serves to create dynamic components.

The element gets removed correctly but it acts as if the component didn't know that it should refresh, and Vue does not know that the data has changed.

In the chrome Vue extension, the correct element is removed, but the Vue in the DOM removes the last element()

Vue:

```<code> <template>
  <b-container>
    <SectionSelector :AddSection="AddSection"/>
      <component v-for="(section, index) in sections"
              :key="index"
              :is="section.type"
              :sectionIndex="index"
              :sectionData="section[index]"
              :deleteData="deleteData"
              @sectionDataEmit="sectionDataEmit"/>
  </b-container>
</template>

<script>
  import SectionSelector from './components/SectionSelector.vue';
  import FullText from './components/sections/FullText.vue';
  import FullImage from './components/sections/FullImage.vue';
  import ImageRightTextLeft from './components/sections/ImageRightTextLeft.vue';
  import ImageLeftTextRight from './components/sections/ImageLeftTextRight.vue';
  import Vue from 'vue'

  export default {
    data() {
      return {
        sections: []
      }
    },
    methods: {
      AddSection(sectionData) {
        this.sections.push(sectionData);
      },
      updateSection(sectionIndex, sectionData) {
        Vue.set(this.sections, sectionIndex, sectionData);
      },
      sectionDataEmit(emitData) {
        Vue.set(this.sections, emitData.position, emitData.content);
      },
      deleteData(index) {
        // eslint-disable-next-line
        console.log(index)
        this.$delete(this.sections, index);
      }
    },
    components: {
      SectionSelector,
      FullText,
      FullImage,
      ImageRightTextLeft,
      ImageLeftTextRight
    }
  }
</script>
</code>```

component:

```<code>    <template>
  <b-row>
    <h3>Full text {{ sectionIndex+1 }}</h3>
    <b-button variant="danger"
            @click="deleteButton(sectionIndex)">delete</b-button>
    <b-textarea :value="sectionData"
              @input="sectionDataEmit" />
  </b-row>
</template>

<script>
  export default {
    props: ['sectionIndex', 'sectionData', 'deleteData'],
    methods: {
      sectionDataEmit(value) {
        let emitData = {
          position: this.sectionIndex,
          content: {
            type: 'FullText',
            fields: {
              text: value
            }
          }
        }
        this.$emit('sectionDataEmit', emitData)
      },
      deleteButton(index) {
        this.deleteData(index)
      }
    }
  }
</script>
</code>```

before deleteData()

after deleteData()

答:
Since you are trying to render a list of stateful components and not plain/simple DOM nodes, it becomes critical to have a key as a really unique attribute. Using an index as a key attribute value does not guarantee uniqueness. You can read more about it here.

Why does this happen?

Vue.js uses Virtual DOM (VDOM) internally for efficient rendering of the UI. So when your array changes, Vue.js uses VDOM to update the DOM. VDOM has no knowledge of Vue.js component or its state. So, there is a chance that VDOM may assign a wrong DOM element to a component. This is where the key attribute helps Vue.js to keep track of components and its DOM element.

What happens when you use index for key attribute?

Imagine you have use index as a key attribute. Now, you have initially five items in an array to render. For each item, it instantiates a component instance. So, five DOM elements and five component

component0 - DOM0 - index 0

component1 - DOM1 - index 1

component2 - DOM2 - index 2

component3 - DOM3 - index 3

component4 - DOM4 - index 4

Now, say you remove the 3rd item using splice method:

```<code>array.splice(2, 1);
</code>```

After doing the above operation, array length changes from 5 to 4. For vue.js, it is the 4th index i.e. fifth item is gone. Index 2 is still there and never gone; thus its associated component2 is still valid. So instead, it goes and kills the component4 referred by index 4 (since index 4 no longer exists for this array). In short, it destroys the wrong component.

component0 - DOM0 - index 0

component1 - DOM1 - index 1

component2 - DOM2 - index 2

component3 - DOM3 - index 3

<s>component4 - DOM4 - index 4</s>

Solution?

You should have some unique key, id, for each sectionData to uniquely identify itself in the list. Imagine, if you have to sort sections array, that unique id should still be the same even after sorting (using index for id will change its id after reordering and things gets messed up with VDOM).

Read more about these rules here on this Vue.js forum thread.

Body:
I can't cope with proper rendering after removing an element using deleteData() from an array of objects that simultaneously serves to create dynamic components.

The element gets removed correctly but it acts as if the component didn't know that it should refresh, and Vue does not know that the data has changed.

In the chrome Vue extension, the correct element is removed, but the Vue in the DOM removes the last element()

Vue:

 <template>

    <SectionSelector :AddSection="AddSection"/>
      <component v-for="(section, index) in sections"
              :key="index"
              :is="section.type"
              :sectionIndex="index"
              :sectionData="section[index]"
              :deleteData="deleteData"
              @sectionDataEmit="sectionDataEmit"/>

</template>

component:

    <template>

Full text {{ sectionIndex+1 }}

    delete

</template>

before deleteData()

after deleteData()

Body:
Since you are trying to render a list of stateful components and not plain/simple DOM nodes, it becomes critical to have a key as a really unique attribute. Using an index as a key attribute value does not guarantee uniqueness. You can read more about it here.

Why does this happen?

Vue.js uses Virtual DOM (VDOM) internally for efficient rendering of the UI. So when your array changes, Vue.js uses VDOM to update the DOM. VDOM has no knowledge of Vue.js component or its state. So, there is a chance that VDOM may assign a wrong DOM element to a component. This is where the key attribute helps Vue.js to keep track of components and its DOM element.

What happens when you use index for key attribute?

Imagine you have use index as a key attribute. Now, you have initially five items in an array to render. For each item, it instantiates a component instance. So, five DOM elements and five component

component0 - DOM0 - index 0

component1 - DOM1 - index 1

component2 - DOM2 - index 2

component3 - DOM3 - index 3

component4 - DOM4 - index 4

Now, say you remove the 3rd item using splice method:

array.splice(2, 1);

After doing the above operation, array length changes from 5 to 4. For vue.js, it is the 4th index i.e. fifth item is gone. Index 2 is still there and never gone; thus its associated component2 is still valid. So instead, it goes and kills the component4 referred by index 4 (since index 4 no longer exists for this array). In short, it destroys the wrong component.

component0 - DOM0 - index 0

component1 - DOM1 - index 1

component2 - DOM2 - index 2

component3 - DOM3 - index 3

<s>component4 - DOM4 - index 4</s>

Solution?

You should have some unique key, id, for each sectionData to uniquely identify itself in the list. Imagine, if you have to sort sections array, that unique id should still be the same even after sorting (using index for id will change its id after reordering and things gets messed up with VDOM).

Read more about these rules here on this Vue.js forum thread.


问:
How to add history in my this.props? For push to link
```<code>  changeRoutePath = (e) =>{
      e.preventDefault();
      this.props.onClose();
      this.props.history.push('/company/orgStructure');
 };
 <Link
        to={{
          pathname: '/company/orgStructure',
          state: {
            fromNotifications: true
                 }
          }}
         onClick={(e) => this.changeRoutePath(e)}>
       Prevent
</Link>
</code>```

I have error Uncaught TypeError: Cannot read property 'push' of undefined

Need to go on /company/orgStructure page and take some info in state! How to do it?
If i use just link without onclick i cant use this.props.onClose for close modal. How to push info and go to orgStructure?

console.log(this.props);

```<code>bgClose: false
className: ""
container: true
employeeCode: "00-005424"
escClose: false
onClose: ƒ ()
open: true
showModalEmployeeShortProfile: ƒ ()
stack: true
template: null
title: "Профиль сотрудника"
width: 960
</code>```

答:
If your component is not bind with react-router-dom you won't be getting their methods in your props, here you don't have access to location, history and match in your props which are props from react router which means your component is not connected with router.

you just have to import withRouter from react router dom which is a HOC and wrap your component in it, than you'll have access to history in your props.

```<code>import {withRouter} from 'react-router-dom'
class yourComponent extends React.Component{
render(){}
}
export default withRouter(yourComponent)
</code>```

Body:
  changeRoutePath = (e) =>{
      e.preventDefault();
      this.props.onClose();
      this.props.history.push('/company/orgStructure');
 };
 <Link
        to={{
          pathname: '/company/orgStructure',
          state: {
            fromNotifications: true
                 }
          }}
         onClick={(e) => this.changeRoutePath(e)}>
       Prevent
</Link>

I have error Uncaught TypeError: Cannot read property 'push' of undefined

Need to go on /company/orgStructure page and take some info in state! How to do it?
If i use just link without onclick i cant use this.props.onClose for close modal. How to push info and go to orgStructure?

console.log(this.props);

bgClose: false
className: ""
container: true
employeeCode: "00-005424"
escClose: false
onClose: ƒ ()
open: true
showModalEmployeeShortProfile: ƒ ()
stack: true
template: null
title: "Профиль сотрудника"
width: 960

Body:
If your component is not bind with react-router-dom you won't be getting their methods in your props, here you don't have access to location, history and match in your props which are props from react router which means your component is not connected with router.

you just have to import withRouter from react router dom which is a HOC and wrap your component in it, than you'll have access to history in your props.

import {withRouter} from 'react-router-dom'
class yourComponent extends React.Component{
render(){}
}
export default withRouter(yourComponent)


问:
Set index to group of repetitive row values in a csv file using Python
I am new to python. I want to set index to specific set of row elements which are repetitive for each group.
My dataframe:

```<code>data_dict ={'0_deg': [2, 11, 21, -17, 5, 40, 22, 7, 20, -6, -6, -6, 24, 21, 20, 61, 21, 5, 2, 17],
 '10_deg': [12, -21, 11, 1, 4, -2, 33, 53, 18, 10, -3, -1, 23, 18, 23, 8, 11, -25, 21, -14],
 '20_deg': [23, -10, 3, 20, -41, 13, 10, 5, -9, 7, -4, -21, 14, -26, -31, 9, 1, -15, 3, -6],
 '30_deg': [12, 9, -5, 4, 9, -46, 1, -8, -27, 3, -9, -14, 15, -6, 14, 7, -11, 5, 19, -4]}
</code>```

```<code>data_dict = pd.read_csv('Dataset.csv')
data_dict = data_dict.set_index('Indexes')

#row idx of a group in this list
idx =[4,10,37,109,133]
</code>```

Here a list is created as idx and index values are written maunally.

But for a bigger matrix of 1000+ indexes(random values) per group, this would be a very difficult task.

What I want is that when I read a CSV file, the 1st value in the row should be selected and until the same value occurs in the same index, it should be considered as 1 group, and the indexes for 1st group must get stored in idx

Eg: In my small version of dataset, from 1st column Indexes, the 1st values i.e. 4,10,37,109,133 are my indexxes for 1st group. These values repeat in same sequence for next groups.
Only they shoud not be entered manually in code. A group should be considered unitl next 4 occurs. So index values 4 to 133 must be considered as 1 group under idx. This is because I need idx for further part of the code.

My actual dataset has 1000+ index values per group. So idx must automatically take all values of a group.

```<code># getting some dimensions and sorting the data
row_idx_length = len(idx)
group_length = len(data_dict['0_deg'])
number_of_groups = len(data_dict.keys())
idx = idx*number_of_groups
data_arr = np.zeros((group_length,number_of_groups),dtype=np.int32)
</code>```

Body:
I am new to python. I want to set index to specific set of row elements which are repetitive for each group.
My dataframe:

data_dict ={'0_deg': [2, 11, 21, -17, 5, 40, 22, 7, 20, -6, -6, -6, 24, 21, 20, 61, 21, 5, 2, 17],
 '10_deg': [12, -21, 11, 1, 4, -2, 33, 53, 18, 10, -3, -1, 23, 18, 23, 8, 11, -25, 21, -14],
 '20_deg': [23, -10, 3, 20, -41, 13, 10, 5, -9, 7, -4, -21, 14, -26, -31, 9, 1, -15, 3, -6],
 '30_deg': [12, 9, -5, 4, 9, -46, 1, -8, -27, 3, -9, -14, 15, -6, 14, 7, -11, 5, 19, -4]}

data_dict = pd.read_csv('Dataset.csv')
data_dict = data_dict.set_index('Indexes')

#row idx of a group in this list
idx =[4,10,37,109,133]

Here a list is created as idx and index values are written maunally.

But for a bigger matrix of 1000+ indexes(random values) per group, this would be a very difficult task.

What I want is that when I read a CSV file, the 1st value in the row should be selected and until the same value occurs in the same index, it should be considered as 1 group, and the indexes for 1st group must get stored in idx

Eg: In my small version of dataset, from 1st column Indexes, the 1st values i.e. 4,10,37,109,133 are my indexxes for 1st group. These values repeat in same sequence for next groups.
Only they shoud not be entered manually in code. A group should be considered unitl next 4 occurs. So index values 4 to 133 must be considered as 1 group under idx. This is because I need idx for further part of the code.

My actual dataset has 1000+ index values per group. So idx must automatically take all values of a group.

# getting some dimensions and sorting the data
row_idx_length = len(idx)
group_length = len(data_dict['0_deg'])
number_of_groups = len(data_dict.keys())
idx = idx*number_of_groups
data_arr = np.zeros((group_length,number_of_groups),dtype=np.int32)

Body:
If i understand your question correctly, you need to actually get the idx given the dataframe with the index setup like that.

data_dict ={'0_deg': [2, 11, 21, -17, 5, 40, 22, 7, 20, -6, -6, -6, 24, 21, 20, 61, 21, 5, 2, 17],
 '10_deg': [12, -21, 11, 1, 4, -2, 33, 53, 18, 10, -3, -1, 23, 18, 23, 8, 11, -25, 21, -14],
 '20_deg': [23, -10, 3, 20, -41, 13, 10, 5, -9, 7, -4, -21, 14, -26, -31, 9, 1, -15, 3, -6],
 '30_deg': [12, 9, -5, 4, 9, -46, 1, -8, -27, 3, -9, -14, 15, -6, 14, 7, -11, 5, 19, -4]}
import pandas as pd
df = pd.DataFrame(data_dict)

idx =[4,10,37,109,133]
df.index = idx * (len(df)//len(idx))

print(df)
#Output:
     0_deg  10_deg  20_deg  30_deg  groups
4        2      12      23      12       1
10      11     -21     -10       9       1
37      21      11       3      -5       1
109    -17       1      20       4       1
133      5       4     -41       9       1
4       40      -2      13     -46       2
10      22      33      10       1       2
37       7      53       5      -8       2
109     20      18      -9     -27       2
133     -6      10       7       3       2
4       -6      -3      -4      -9       3
10      -6      -1     -21     -14       3
37      24      23      14      15       3
109     21      18     -26      -6       3
133     20      23     -31      14       3
4       61       8       9       7       4
10      21      11       1     -11       4
37       5     -25     -15       5       4
109      2      21       3      19       4
133     17     -14      -6      -4       4

With the setup done, you just need to calculate where the 0th value repeats. You could just calculate it directly, but perhaps it is also more useful to make an additional column for further calculations.

temp = df.index == df.index[0]
groups = temp.cumsum()
idx_out = list(df.index[groups == 1])

print(idx_out) #[4, 10, 37, 109, 133]

#Optional:

df['groups'] = groups #can be very useful for aggregations and groupby calculations


问:
why (navigator.devicememory) is not accurate for devices with more than 6gb of ram?
I want to get device Memory (80% of time android phones) I wrote this code.

```<code> <html>
    <body>
    <p class="ram-description">Your device memory is <span id="result">unknown</span> GB.</p>

<script>
document.getElementById('result').innerHTML = navigator.deviceMemory || 'unknown'
</script>
</body>
</html>
</code>```

but I think (navigator.deviceMemory) is not working for phones o other devices with more than 4 GB of RAM

for example, my phone has 6GB ram and it shows 4GB
my laptop has 16GB and it shows 8GB

can anyone help me?

```<code><html>
<body>
<p class="ram-description"><b id="result">Your device memory is <b id="result">unknown</b> GiB.</p>

<script>
document.getElementById('result').innerHTML = navigator.deviceMemory || 'unknown'
</script>
</body>
</html>
</code>```

答:
lower and upper bounds are used to protect privacy of owners of very low- or high-end devices

Quoted from https://developer.mozilla.org/en-US/docs/Web/API/Navigator/deviceMemory

Body:
I want to get device Memory (80% of time android phones) I wrote this code.

Your device memory is unknown GB.

but I think (navigator.deviceMemory) is not working for phones o other devices with more than 4 GB of RAM

for example, my phone has 6GB ram and it shows 4GB
my laptop has 16GB and it shows 8GB

can anyone help me?

Your device memory is unknown GiB.


问:
Display issue in internet explorer
I have one query regarding display in internet explorer. While edit one particular field then save, after that changes are reflecting in chrome but same changes are not reflecting in internet explorer.Could someone suggest reason behind this and guide further?</p>

答: After analysis and debugging I came to know that issue was related with cache clearance of internet explorer. Once cache and cookies are cleared then applied changes are reflecting in IE as well. So it is resolved now .Thanks:) </p>

Title: Display issue in internet explorer


问:
match two lists by common value (id)
I want create a new list such that the keys are used to match the roles.

For example two lists:

[['9', u'bob'], ['18', u'alice']]

[['1', 'officer'], ['2', 'nurse'], ['9', 'teacher'],['18', 'unknown']]

I'd like a new list that is:

[['9', u'bob', 'teacher'], ['18', u'alice' 'unknown']] or

[[u'bob', 'teacher'], [u'alice' 'unknown']]

答:
try this:

```<code>names = [[9, u'bob'], [18, u'alice']]

roles = [[1, 'officer'], [2, 'nurse'], [9, 'teacher'],[18, 'unknown']]

mapper = dict(roles)
print([[x[0],x[1],mapper[x[0]]] for x in names])
</code>```

assuming numbers in roles are of the same type i.e either integers or strings. In this case i have taken them as integers to match with names.

Title: match two lists by common value (id)

Body:
try this:

names = [[9, u'bob'], [18, u'alice']]

roles = [[1, 'officer'], [2, 'nurse'], [9, 'teacher'],[18, 'unknown']]

mapper = dict(roles)
print([[x[0],x[1],mapper[x[0]]] for x in names])

assuming numbers in roles are of the same type i.e either integers or strings. In this case i have taken them as integers to match with names.


问:
Varying 0-1px gap between div background and border on High-DPI displays
Here is an isolated example of a button I've created in CSS. It features a 1px border with a gradient, and a background gradient. The background gradient is implemented as a pseudo-element to allow its opacity to be faded on hover.

https://codepen.io/anon/pen/wbYoeo?editors=1100

```<code>.Button
{
  width: 200px;
  height: 30px;
  cursor: pointer;
    padding: 0.8rem;
    border-style: solid;
    border-image: linear-gradient(
        to right,
        green 0%,
        blue 100%);
    border-image-slice: 1;
    border-width: 1px;
    position: relative;
  margin-top: 10px;
    transition: color 0.2s;
}

.Button::before
{
    content: '';
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background-image: linear-gradient(
        to right,
        green 0%,
        blue 100%);
    opacity: 0.5;
    transition: opacity 0.2s;
}
</code>```

The button doesn't render identically between monitors of differing DPI. Screenshots of the button rendered in Chrome on Windows with varying DPI scales:

100% DPI-scaled monitor, rendering correctly with no gap.

150% DPI-scaled monitor, showing a gap between the background and border.

175% DPI-scaled monitor, showing a gap between the background and border.

200% DPI-scaled monitor, rendering correctly with no gap.

I've tried several strategies to render the button, but they all result in the gap:

Tried using an image with a gradient instead of linear-gradient on both the border-image and background-image.

Tried to use an explicit div for the background gradient instead of a pseudo element.

Tried to use an explicit div for the background gradient instead of a pseudo element, and also used a solid left and right border and ::before and ::after pseudo-elements with linear-gradient backgrounds for the top and bottom borders.

答:
Cause?

I would take an (uneducated) guess that this is caused by sub-pixels when scaling. It can't be a fraction of a pixel, so it chooses a whole pixel value; the parent's calculated value is 1px bigger than the value given to the children at some scales.

Workaround

Take the border off the button div itself, and put it on an ::after pseudo-element so the border and background are both children. The border now appears to scale consistently with the background gradient.

Example

.Button {
  width: 200px;
  height: 30px;
  cursor: pointer;
  padding: 0.8rem;
  position: relative;
  margin-top: 10px;
  transition: color 0.2s;
}

.Button::before {
  content: '';
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background-image: linear-gradient( to right, green 0%, blue 100%);
  opacity: 0.2;
  transition: opacity 0.2s;
}

.Button:hover::before {
  opacity: 0.5;
}

.Button:active::before {
  opacity: 1;
}

.Button::after {
  content: '';
  border-style: solid;
  border-image: linear-gradient( to right, green 0%, blue 100%);
  border-image-slice: 1;
  border-width: 1px;
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
}

html {
  height: 100%;
  display: table;
  margin: auto;
}

body {
  background: black;
  display: table-cell;
  vertical-align: middle;
  color: white;
  font-family: sans-serif;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Click it:
<div class="Button"></div></code>```

Body:
Here is an isolated example of a button I've created in CSS. It features a 1px border with a gradient, and a background gradient. The background gradient is implemented as a pseudo-element to allow its opacity to be faded on hover.

https://codepen.io/anon/pen/wbYoeo?editors=1100

.Button
{
  width: 200px;
  height: 30px;
  cursor: pointer;
    padding: 0.8rem;
    border-style: solid;
    border-image: linear-gradient(
        to right,
        green 0%,
        blue 100%);
    border-image-slice: 1;
    border-width: 1px;
    position: relative;
  margin-top: 10px;
    transition: color 0.2s;
}

.Button::before
{
    content: '';
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background-image: linear-gradient(
        to right,
        green 0%,
        blue 100%);
    opacity: 0.5;
    transition: opacity 0.2s;
}

The button doesn't render identically between monitors of differing DPI. Screenshots of the button rendered in Chrome on Windows with varying DPI scales:

100% DPI-scaled monitor, rendering correctly with no gap.

150% DPI-scaled monitor, showing a gap between the background and border.

175% DPI-scaled monitor, showing a gap between the background and border.

200% DPI-scaled monitor, rendering correctly with no gap.

I've tried several strategies to render the button, but they all result in the gap:

Tried using an image with a gradient instead of linear-gradient on both the border-image and background-image.

Tried to use an explicit div for the background gradient instead of a pseudo element.

Tried to use an explicit div for the background gradient instead of a pseudo element, and also used a solid left and right border and ::before and ::after pseudo-elements with linear-gradient backgrounds for the top and bottom borders.

Body:
Cause?

I would take an (uneducated) guess that this is caused by sub-pixels when scaling. It can't be a fraction of a pixel, so it chooses a whole pixel value; the parent's calculated value is 1px bigger than the value given to the children at some scales.

Workaround

Take the border off the button div itself, and put it on an ::after pseudo-element so the border and background are both children. The border now appears to scale consistently with the background gradient.

Example

.Button {
  width: 200px;
  height: 30px;
  cursor: pointer;
  padding: 0.8rem;
  position: relative;
  margin-top: 10px;
  transition: color 0.2s;
}

.Button::before {
  content: '';
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background-image: linear-gradient( to right, green 0%, blue 100%);
  opacity: 0.2;
  transition: opacity 0.2s;
}

.Button:hover::before {
  opacity: 0.5;
}

.Button:active::before {
  opacity: 1;
}

.Button::after {
  content: '';
  border-style: solid;
  border-image: linear-gradient( to right, green 0%, blue 100%);
  border-image-slice: 1;
  border-width: 1px;
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
}

html {
  height: 100%;
  display: table;
  margin: auto;
}

body {
  background: black;
  display: table-cell;
  vertical-align: middle;
  color: white;
  font-family: sans-serif;
}

Click it:
<div class="Button"></div>


问:
How do I alias python2 to python3 in a docker container?
I am trying to set the default python in my docker container to be python3 and have set the aliases in the dockerfile. When I open the .bashrc file, they show up. As far as I can tell, it should work but the default python version is still 2.7. if I run which python, it will still point to usr/bin/python rather than python3. Same with pip. Can anyone tell me what the problem is? Here is the command I'm using to alias:

```<code>   RUN \
   echo 'alias python="/usr/bin/python3"' >> /root/.bashrc && \
   echo 'alias pip="/usr/bin/pip3"' >> /root/.bashrc

</code>```

Does this look right? I am using ubuntu 17.10

答:
The answer above is great, except it should be as follows:

```<code>RUN ln -s /usr/bin/python3 /usr/bin/python && \
    ln -s /usr/bin/pip3 /usr/bin/pip
</code>```

Perhaps they typo-ed by writing ls which just lists the contents of the directory, rather than using ln which actually creates symlinks.

Body:
I am trying to set the default python in my docker container to be python3 and have set the aliases in the dockerfile. When I open the .bashrc file, they show up. As far as I can tell, it should work but the default python version is still 2.7. if I run which python, it will still point to usr/bin/python rather than python3. Same with pip. Can anyone tell me what the problem is? Here is the command I'm using to alias:

   RUN \
   echo 'alias python="/usr/bin/python3"' >> /root/.bashrc && \
   echo 'alias pip="/usr/bin/pip3"' >> /root/.bashrc

Does this look right? I am using ubuntu 17.10

Body:
The answer above is great, except it should be as follows:

RUN ln -s /usr/bin/python3 /usr/bin/python && \
    ln -s /usr/bin/pip3 /usr/bin/pip

Perhaps they typo-ed by writing ls which just lists the contents of the directory, rather than using ln which actually creates symlinks.


问:
How to read XML using XPath in Java
I want to read XML data using XPath in Java, so for the information I have gathered I am not able to parse XML according to my requirement.

here is what I want to do:

Get XML file from online via its URL, then use XPath to parse it, I want to create two methods in it. One is in which I enter a specific node attribute id, and I get all the child nodes as result, and second is suppose I just want to get a specific child node value only

```<code><?xml version="1.0"?>
<howto>
  <topic name="Java">
      <url>http://www.rgagnonjavahowto.htm</url>
  <car>taxi</car>
  </topic>
  <topic name="PowerBuilder">
       <url>http://www.rgagnon/pbhowto.htm</url>
       <url>http://www.rgagnon/pbhowtonew.htm</url>
  </topic>
  <topic name="Javascript">
        <url>http://www.rgagnon/jshowto.htm</url>
  </topic>
 <topic name="VBScript">
       <url>http://www.rgagnon/vbshowto.htm</url>
 </topic>
 </howto>
</code>```

In above example I want to read all the elements if I search via @name and also one function in which I just want the url from @name 'Javascript' only return one node element.

答:
If you have a xml like below

```<code><e:Envelope
    xmlns:d = "http://www.w3.org/2001/XMLSchema"
    xmlns:e = "http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:wn0 = "http://systinet.com/xsd/SchemaTypes/"
    xmlns:i = "http://www.w3.org/2001/XMLSchema-instance">
    <e:Header>
        <Friends>
            <friend>
                <Name>Testabc</Name>
                <Age>12121</Age>
                <Phone>Testpqr</Phone>
            </friend>
        </Friends>
    </e:Header>
    <e:Body>
        <n0:ForAnsiHeaderOperResponse xmlns:n0 = "http://systinet.com/wsdl/com/magicsoftware/ibolt/localhost/ForAnsiHeader/ForAnsiHeaderImpl#ForAnsiHeaderOper?KExqYXZhL2xhbmcvU3RyaW5nOylMamF2YS9sYW5nL1N0cmluZzs=">
            <response i:type = "d:string">12--abc--pqr</response>
        </n0:ForAnsiHeaderOperResponse>
    </e:Body>
</e:Envelope>
</code>```

and wanted to extract the below xml

```<code><e:Header>
   <Friends>
      <friend>
         <Name>Testabc</Name>
         <Age>12121</Age>
         <Phone>Testpqr</Phone>
      </friend>
   </Friends>
</e:Header>
</code>```

The below code helps to achieve the same

```<code>public static void main(String[] args) {

    File fXmlFile = new File("C://Users//abhijitb//Desktop//Test.xml");
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document document;
    Node result = null;
    try {
        document = dbf.newDocumentBuilder().parse(fXmlFile);
        XPath xPath = XPathFactory.newInstance().newXPath();
        String xpathStr = "//Envelope//Header";
        result = (Node) xPath.evaluate(xpathStr, document, XPathConstants.NODE);
        System.out.println(nodeToString(result));
    } catch (SAXException | IOException | ParserConfigurationException | XPathExpressionException
            | TransformerException e) {
        e.printStackTrace();
    }
}

private static String nodeToString(Node node) throws TransformerException {
    StringWriter buf = new StringWriter();
    Transformer xform = TransformerFactory.newInstance().newTransformer();
    xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    xform.transform(new DOMSource(node), new StreamResult(buf));
    return (buf.toString());
}
</code>```

Now if you want only the xml like below

```<code><Friends>
   <friend>
      <Name>Testabc</Name>
      <Age>12121</Age>
      <Phone>Testpqr</Phone>
   </friend>
</Friends>
</code>```

You need to change the

String xpathStr = "//Envelope//Header"; to String xpathStr = "//Envelope//Header/*";

Title: How to read XML using XPath in Java

Body:
I want to read XML data using XPath in Java, so for the information I have gathered I am not able to parse XML according to my requirement.

here is what I want to do:

Get XML file from online via its URL, then use XPath to parse it, I want to create two methods in it. One is in which I enter a specific node attribute id, and I get all the child nodes as result, and second is suppose I just want to get a specific child node value only

<?xml version="1.0"?>
<howto>
  <topic name="Java">
      <url>http://www.rgagnonjavahowto.htm</url>
  <car>taxi</car>
  </topic>
  <topic name="PowerBuilder">
       <url>http://www.rgagnon/pbhowto.htm</url>
       <url>http://www.rgagnon/pbhowtonew.htm</url>
  </topic>
  <topic name="Javascript">
        <url>http://www.rgagnon/jshowto.htm</url>
  </topic>
 <topic name="VBScript">
       <url>http://www.rgagnon/vbshowto.htm</url>
 </topic>
 </howto>

In above example I want to read all the elements if I search via @name and also one function in which I just want the url from @name 'Javascript' only return one node element.

Body:
If you have a xml like below

<e:Envelope
    xmlns:d = "http://www.w3.org/2001/XMLSchema"
    xmlns:e = "http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:wn0 = "http://systinet.com/xsd/SchemaTypes/"
    xmlns:i = "http://www.w3.org/2001/XMLSchema-instance">
    <e:Header>
        <Friends>
            <friend>
                <Name>Testabc</Name>
                <Age>12121</Age>
                <Phone>Testpqr</Phone>
            </friend>
        </Friends>
    </e:Header>
    <e:Body>
        <n0:ForAnsiHeaderOperResponse xmlns:n0 = "http://systinet.com/wsdl/com/magicsoftware/ibolt/localhost/ForAnsiHeader/ForAnsiHeaderImpl#ForAnsiHeaderOper?KExqYXZhL2xhbmcvU3RyaW5nOylMamF2YS9sYW5nL1N0cmluZzs=">
            <response i:type = "d:string">12--abc--pqr</response>
        </n0:ForAnsiHeaderOperResponse>
    </e:Body>
</e:Envelope>

and wanted to extract the below xml

<e:Header>
   <Friends>
      <friend>
         <Name>Testabc</Name>
         <Age>12121</Age>
         <Phone>Testpqr</Phone>
      </friend>
   </Friends>
</e:Header>

The below code helps to achieve the same

public static void main(String[] args) {

    File fXmlFile = new File("C://Users//abhijitb//Desktop//Test.xml");
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document document;
    Node result = null;
    try {
        document = dbf.newDocumentBuilder().parse(fXmlFile);
        XPath xPath = XPathFactory.newInstance().newXPath();
        String xpathStr = "//Envelope//Header";
        result = (Node) xPath.evaluate(xpathStr, document, XPathConstants.NODE);
        System.out.println(nodeToString(result));
    } catch (SAXException | IOException | ParserConfigurationException | XPathExpressionException
            | TransformerException e) {
        e.printStackTrace();
    }
}

private static String nodeToString(Node node) throws TransformerException {
    StringWriter buf = new StringWriter();
    Transformer xform = TransformerFactory.newInstance().newTransformer();
    xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    xform.transform(new DOMSource(node), new StreamResult(buf));
    return (buf.toString());
}

Now if you want only the xml like below

<Friends>
   <friend>
      <Name>Testabc</Name>
      <Age>12121</Age>
      <Phone>Testpqr</Phone>
   </friend>
</Friends>

You need to change the

String xpathStr = "//Envelope//Header"; to String xpathStr = "//Envelope//Header/*";


问:
The required column was not present in the results of a 'FromSql' operation
I've just starting learning MVC6 with EF7.  I have a stored proc that I'd like to return a portion of the fields that are in my model.  If I don't return every field in my model, I'm getting "The required column 'FirstName' was not present in the results of a 'FromSql' operation".

Is there a way to get make some columns not required so I can return just a portion of the fields in my model?

model:

```<code>public class LoginViewModel
{
    [Key]
    public int UserID { get; set; }

    [Required]
    [Display(Name = "Username")]
    public string Username { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Protected ID")]
    public string ProtectedID { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
}
</code>```

My proc for testing:

```<code>CREATE PROCEDURE [dbo].[aaa_TopXXUsersTest]
@NumToReturn int = 10
AS
BEGIN
    SET NOCOUNT ON;
    select top(@NumToReturn) UserID, LastName, Username,Password, ProtectedID from Users where Deleted = 0

END
</code>```

and last, my controller code:

```<code>public IActionResult Index()
{
    var user = _context.Set<LoginViewModel>().FromSql("dbo.aaa_TopXXUsersTest @NumToReturn = {0}", 20);

    return View(user);
}
</code>```

If I include all the fields of my model in my stored proc the call work fine, but I can't seem to return just a subset.  Is there a way to make some of the fields not required?

答:
It requires a Id column to be returned from the SP.

```<code>select top(@NumToReturn) 0 AS 'Id', UserID, LastName, Username,Password, ProtectedID
  from Users
 where Deleted = 0
</code>```

Or Change UserID to Id from select and model

Body:
I've just starting learning MVC6 with EF7.  I have a stored proc that I'd like to return a portion of the fields that are in my model.  If I don't return every field in my model, I'm getting "The required column 'FirstName' was not present in the results of a 'FromSql' operation".

Is there a way to get make some columns not required so I can return just a portion of the fields in my model?

model:

public class LoginViewModel
{
    [Key]
    public int UserID { get; set; }

    [Required]
    [Display(Name = "Username")]
    public string Username { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Protected ID")]
    public string ProtectedID { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
}

My proc for testing:

CREATE PROCEDURE [dbo].[aaa_TopXXUsersTest]
@NumToReturn int = 10
AS
BEGIN
    SET NOCOUNT ON;
    select top(@NumToReturn) UserID, LastName, Username,Password, ProtectedID from Users where Deleted = 0

END

and last, my controller code:

public IActionResult Index()
{
    var user = _context.Set<LoginViewModel>().FromSql("dbo.aaa_TopXXUsersTest @NumToReturn = {0}", 20);

    return View(user);
}

If I include all the fields of my model in my stored proc the call work fine, but I can't seem to return just a subset.  Is there a way to make some of the fields not required?

Body:
It requires a Id column to be returned from the SP.

select top(@NumToReturn) 0 AS 'Id', UserID, LastName, Username,Password, ProtectedID
  from Users
 where Deleted = 0

Or Change UserID to Id from select and model


Title: match two lists by common value (id)

Body:
I want create a new list such that the keys are used to match the roles.

For example two lists:

[['9', u'bob'], ['18', u'alice']]

[['1', 'officer'], ['2', 'nurse'], ['9', 'teacher'],['18', 'unknown']]

I'd like a new list that is:

[['9', u'bob', 'teacher'], ['18', u'alice' 'unknown']] or

[[u'bob', 'teacher'], [u'alice' 'unknown']]

Body:
d1 = dict([[9, u'bob'], [18, u'alice']])

d2 = dict([[1, 'officer'], [2, 'nurse'], ['9', 'teacher'],['18', 'unknown']])

d = []
for k in d1:
    if str(k) in d2:
       d.append((k, d1[k], d2[str(k)]))