问:
Keep 2 <select> in sync when value changes
I have two <select>s with the same <option>s.

If a user selects a value in the first one, the value on the second one should change as well to keep both in sync.

This is what I tried so far:

function data_copy() {
  if (document.form1.copy[0].checked) {
    for (i = document.form1.state.options.length-1; i >= 0; i--) {
      if (document.form1.state.options[i].selected)
        document.form1.state2.options[i].selected = true;
    }
  } else {
    document.form1.state2.options[0].selected = true;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body bgcolor="#ffffff" text="#000000" link="#0000ff" vlink="#800080" alink="#ff0000">
  <table width='400' border='0' cellspacing='1' cellpadding='0'>
    <form name=form1 method=post action='http://www.plus2net.com'>

      <tr><td >State</td><td>
        <SELECT NAME="state" onchange="data_copy()">
          <Option value="One">One</option>
          <Option value="Two">Two</option>
          <Option value="Three">Three</option>
          <Option value="Four">Four</option>
        </SELECT>
      </td></tr>

      <tr><td >
      <tr><td >State</td><td>
        <SELECT NAME="state2" >
          <Option value="One">One</option>
          <Option value="Two">Two</option>
          <Option value="Three">Three</option>
          <Option value="Four">Four</option>
        </SELECT>
      </td></tr>

      <tr><td colspan=2 align=center><input type=submit value=Submit>
    </form></td></tr>
  </table>
</body></code>```

答:
You can just get a reference to both <select> using document.getElemebtById, document.querySelector(...) or any other document.getElement...() function and, once the first one changes, assign its value to the second one:

```<code>const state1 = document.getElementById('state1');
const state2 = document.getElementById('state2');

state1.onchange = function(e) {
    state2.value = e.target.value;
};
</code>```

Also, there are multiple issues with your code:

A <form> is not allowed inside a
, so you either wrap the whole table with it or put it in a single cell. Inside a
 element you can only use
, <colgroup>,
,
,
 and
.

Unquoted HTML attributes are also valid but, if they contain untrusted data, it will be more difficult to escape them to avoid XSS attacks. Actually, most HTML escaping tools will assume the usage of quotes. Anyway, you should also be consistent with that, so either use double, single or no quotes at all.

You should use lowercase for your HTML code. While browsers will still understand uppercase, it is a convention to use lowercase due to its better readability. This comes from the old xHTML which required lowercase.

You should also avoid using event attributes in order to keep your presentation and your logic separated and also due to the way the scope for inline elements is resolved.

There's a good explanation on that in this other answer: onclick="" vs event handler

You should not use HTML attributes to style your elements. That's CSS concern.

Actually, bgcolor, text, link... Are all unsupported in HTML5.

Lastly, if you are using the
 element just for layout, without any semantic meaning, then you should use other elements instead, maybe
 and
 or just
, and position them using CSS.

Maybe Flexbox can come in handy, although position, float and display should be more than enough for your use case.

All together, it should look like this:

const state1 = document.getElementById('state1');
const state2 = document.getElementById('state2');

state1.onchange = function(e) {
  state2.value = e.target.value;
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font-family: sans-serif;
}

table {
  background: #FFF;
  color: #000;
  width: 400px;
  border: none;
  border-collapse: collapse;
}

td {
  padding: .25rem;
}

select {
  width: 100%;
}

.legend {
  width: 50px;
  text-align: right;
  text-transform: uppercase;
  font-size: .75rem;
}

.button {
  width: 100%;
  border: none;
  background: #FFF;
  padding: .5rem;
  border-radius: 2px;
  color: #000;
  text-transform: uppercase;
  font-size: .75rem;
  margin: 1rem 0 0;
  box-shadow: 0 0 1rem rgba(0, 0, 0, .25);
  transition: box-shadow ease-in .125s;
}

.button:hover {
  box-shadow: 0 0 .5rem rgba(0, 0, 0, .25);
}</code>```

<form
  name="form"
  method="post"
  action="http://www.plus2net.com">

      State

        <select name="state" id="state1">
          <option value="One">One</option>
          <option value="Two">Two</option>
          <option value="Three">Three</option>
          <option value="Four">Four</option>
        </select>

      State

        <select name="state2" id="state2">
        <option value="One">One</option>
        <option value="Two">Two</option>
        <option value="Three">Three</option>
        <option value="Four">Four</option>
        </select>

        <input type="submit" value="submit" class="button">

</form>```

Body:
I have two <select>s with the same <option>s.

If a user selects a value in the first one, the value on the second one should change as well to keep both in sync.

This is what I tried so far:

function data_copy() {
  if (document.form1.copy[0].checked) {
    for (i = document.form1.state.options.length-1; i >= 0; i--) {
      if (document.form1.state.options[i].selected)
        document.form1.state2.options[i].selected = true;
    }
  } else {
    document.form1.state2.options[0].selected = true;
  }
}

    <form name=form1 method=post action='http://www.plus2net.com'>

State
        <SELECT NAME="state" onchange="data_copy()">
          <Option value="One">One</option>
          <Option value="Two">Two</option>
          <Option value="Three">Three</option>
          <Option value="Four">Four</option>
        </SELECT>

State
        <SELECT NAME="state2" >
          <Option value="One">One</option>
          <Option value="Two">Two</option>
          <Option value="Three">Three</option>
          <Option value="Four">Four</option>
        </SELECT>

<input type=submit value=Submit>
    </form>

Body:
You can just get a reference to both <select> using document.getElemebtById, document.querySelector(...) or any other document.getElement...() function and, once the first one changes, assign its value to the second one:

const state1 = document.getElementById('state1');
const state2 = document.getElementById('state2');

state1.onchange = function(e) {
    state2.value = e.target.value;
};

Also, there are multiple issues with your code:

A <form> is not allowed inside a <table>, so you either wrap the whole table with it or put it in a single cell. Inside a <table> element you can only use <caption>, <colgroup>, <thead>, <tfoot>, <tbody> and <tr>.

Unquoted HTML attributes are also valid but, if they contain untrusted data, it will be more difficult to escape them to avoid XSS attacks. Actually, most HTML escaping tools will assume the usage of quotes. Anyway, you should also be consistent with that, so either use double, single or no quotes at all.

You should use lowercase for your HTML code. While browsers will still understand uppercase, it is a convention to use lowercase due to its better readability. This comes from the old xHTML which required lowercase.

You should also avoid using event attributes in order to keep your presentation and your logic separated and also due to the way the scope for inline elements is resolved.

There's a good explanation on that in this other answer: onclick="" vs event handler

You should not use HTML attributes to style your elements. That's CSS concern.

Actually, bgcolor, text, link... Are all unsupported in HTML5.

Lastly, if you are using the <table> element just for layout, without any semantic meaning, then you should use other elements instead, maybe <ul> and <li> or just <div>, and position them using CSS.

Maybe Flexbox can come in handy, although position, float and display should be more than enough for your use case.

All together, it should look like this:

const state1 = document.getElementById('state1');
const state2 = document.getElementById('state2');

state1.onchange = function(e) {
  state2.value = e.target.value;
};

body {
  font-family: sans-serif;
}

table {
  background: #FFF;
  color: #000;
  width: 400px;
  border: none;
  border-collapse: collapse;
}

td {
  padding: .25rem;
}

select {
  width: 100%;
}

.legend {
  width: 50px;
  text-align: right;
  text-transform: uppercase;
  font-size: .75rem;
}

.button {
  width: 100%;
  border: none;
  background: #FFF;
  padding: .5rem;
  border-radius: 2px;
  color: #000;
  text-transform: uppercase;
  font-size: .75rem;
  margin: 1rem 0 0;
  box-shadow: 0 0 1rem rgba(0, 0, 0, .25);
  transition: box-shadow ease-in .125s;
}

.button:hover {
  box-shadow: 0 0 .5rem rgba(0, 0, 0, .25);
}

<form
  name="form"
  method="post"
  action="http://www.plus2net.com">

  <table>
    <tr>
      <td class="legend">State</td>
      <td>
        <select name="state" id="state1">
          <option value="One">One</option>
          <option value="Two">Two</option>
          <option value="Three">Three</option>
          <option value="Four">Four</option>
        </select>
      </td>
    </tr>

    <tr>
      <td class="legend">State</td>
      <td>
        <select name="state2" id="state2">
        <option value="One">One</option>
        <option value="Two">Two</option>
        <option value="Three">Three</option>
        <option value="Four">Four</option>
        </select>
     </td>
   </tr>

    <tr>
      <td colspan="2">
        <input type="submit" value="submit" class="button">
      </td>
    </tr>
  </table>

</form>


来源: stackexchange

问:
Standard ML running multiple functions in a loop (Using recursion or any other means)
I have defined three different functions that will perform calculations and return a value.  These functions will consistently be redefining a variable until a specific condition is reached.  I am having issues getting these to run in a "loop" scenario.  I know functional languages are not best for performing loops and you should use recursion...but I am having a hard time wrapping my head around how to perform this.

I will make some real simple arbitrary functions to explain my situation.

```<code>fun add_them (a,b) =
    a+b;

fun substract_them (c,d) =
    c-d;

fun add_them2 (e,f) =
    e-f;

val a = 5;
val b = 7;
val c = 10;
val d = 1;

val a = add_them (a,b);
val d = add_them2 (c,d);
</code>```

So let's say I want to run the last two lines a 1000 times.  So Val A and Val D will keep getting added up to a huge number.  Now I could literally copy and paste those two lines a 1000 times and get the result I want..but this of course defeats the purpose of programming :)

I was trying to create a loop that I can throw these two functions in.  I was coming up with something like below, but I would have no idea how to incorporate these two.  Perhaps I am going at this completely backwards.

```<code>fun whileloop (x,a) =
    if (a<1)
    then x
    else whileloop(x+1,a-1);
</code>```

So my goal was to insert those above val a and val d expressions into another function using recursion and run it a certain amount of times.  Any help would be much appreciated.

答:
A function that simply iterates another function n times is given in my answer here. But it sounds like you want to apply a given function n times to a seed, like so:

```<code>f (f (f (f ... (f x) ... )))
</code>```

That can be accomplished by the following function:

```<code>fun repeat n f x = if n = 0 then x else repeat (n-1) f (f x)
</code>```

For example,

```<code>val n = repeat 20 (fn => n + 1) 0
</code>```

results in 20.

Or perhaps you want to repeat based on a condition instead of a count:

```<code>fun repeatWhile p f x = if p x then repeatWhile p f (f x) else x
</code>```

For example,

```<code>val n = repeatWhile (fn x => x > 0) (fn x => x - 1) 20
</code>```

returns 0.

Both functions are polymorphic, so also work with tuples. For example:

```<code>val (x, y) = repeatWhile (fn (a, b) => a > 0) (fn (a, b) => (a-1, b+1)) (20, 0)
</code>```

returns (0, 20).

If you dislike using two separate function parameters for condition and "action", you can also combine them by having it return a pair:

```<code>fun repeatWhile2 f x =
    let val (c, y) = f x in if c then repeatWhile2 f y else x end
</code>```

Then:

```<code>repeatWhile (fn (a, b) => (a > 0, (a-1, b+2))) (20, 0)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have defined three different functions that will perform calculations and return a value.  These functions will consistently be redefining a variable until a specific condition is reached.  I am having issues getting these to run in a "loop" scenario.  I know functional languages are not best for performing loops and you should use recursion...but I am having a hard time wrapping my head around how to perform this.

I will make some real simple arbitrary functions to explain my situation.

fun add_them (a,b) =
    a+b;

fun substract_them (c,d) =
    c-d;

fun add_them2 (e,f) =
    e-f;

val a = 5;
val b = 7;
val c = 10;
val d = 1;

val a = add_them (a,b);
val d = add_them2 (c,d);

So let's say I want to run the last two lines a 1000 times.  So Val A and Val D will keep getting added up to a huge number.  Now I could literally copy and paste those two lines a 1000 times and get the result I want..but this of course defeats the purpose of programming :)

I was trying to create a loop that I can throw these two functions in.  I was coming up with something like below, but I would have no idea how to incorporate these two.  Perhaps I am going at this completely backwards.

fun whileloop (x,a) =
    if (a<1)
    then x
    else whileloop(x+1,a-1);

So my goal was to insert those above val a and val d expressions into another function using recursion and run it a certain amount of times.  Any help would be much appreciated.

Body:
A function that simply iterates another function n times is given in my answer here. But it sounds like you want to apply a given function n times to a seed, like so:

f (f (f (f ... (f x) ... )))

That can be accomplished by the following function:

fun repeat n f x = if n = 0 then x else repeat (n-1) f (f x)

For example,

val n = repeat 20 (fn => n + 1) 0

results in 20.

Or perhaps you want to repeat based on a condition instead of a count:

fun repeatWhile p f x = if p x then repeatWhile p f (f x) else x

For example,

val n = repeatWhile (fn x => x > 0) (fn x => x - 1) 20

returns 0.

Both functions are polymorphic, so also work with tuples. For example:

val (x, y) = repeatWhile (fn (a, b) => a > 0) (fn (a, b) => (a-1, b+1)) (20, 0)

returns (0, 20).

If you dislike using two separate function parameters for condition and "action", you can also combine them by having it return a pair:

fun repeatWhile2 f x =
    let val (c, y) = f x in if c then repeatWhile2 f y else x end

Then:

repeatWhile (fn (a, b) => (a > 0, (a-1, b+2))) (20, 0)


问:
C++ Printing Odd numbers instead of Prime Numbers
I have been working on an assignment question for days and cannot seem to get the correct output (I've tried so many things!) The question is:

Write a program that uses two nested for loops and the modulus operator (%) to detect and print the prime numbers from 1 to 10,000.

I have been doing from 1 to 10 as a small test to ensure its working. I am getting 2,3,5,7,9 as my output, so I know something is wrong. When I increase the number from 10 to 20 it is printing 2 plus all odd numbers. I am including my code below. Thanks!!

```<code>int main() {

        for (int i=2; i <=10; i++){
            for (int j=2; j<=i; j++){
                if (i%j==0 && j!=i) {

                    break;
                }

                else {

                    cout<< i <<endl;
                    break;
                }
            }
        }
}
</code>```

答:
The problem lies in the if-else branch. Your inner loop will be run exactly once because it will break out of the inner loop as a result of your if else branch.

When you first enter the inner loop the value of j is 2. Your condition will test if variable i is divisible by 2. If it is it breaks. Other wise (your else branch) will print the value of i and breaks out.
Hence printing odd numbers.

Break out of the inner loop and check whether j equals i in outer loop. You have to make j available for outer loop.

Body:
I have been working on an assignment question for days and cannot seem to get the correct output (I've tried so many things!) The question is:

Write a program that uses two nested for loops and the modulus operator (%) to detect and print the prime numbers from 1 to 10,000.

I have been doing from 1 to 10 as a small test to ensure its working. I am getting 2,3,5,7,9 as my output, so I know something is wrong. When I increase the number from 10 to 20 it is printing 2 plus all odd numbers. I am including my code below. Thanks!!

int main() {

        for (int i=2; i <=10; i++){
            for (int j=2; j<=i; j++){
                if (i%j==0 && j!=i) {

                    break;
                }

                else {

                    cout<< i <<endl;
                    break;
                }
            }
        }
}


问:
"Java for Windows missing" dialogue while installing Eclipse
I tried installing Eclipse Neon.3 (4.6.3) for 64 bit. The installer keeps redirecting me to a page that tells me to install a Java JRE/IDE (http://download.eclipse.org/oomph/jre/?vm=1_1_7_0_64_0&pn=Eclipse%20Installer&pu=http://wiki.eclipse.org/Eclipse_Installer&pi=http://download.eclipse.org/oomph/jre/128x128.png), even though I've installed the JRE(1.8.0, for 64 bit) and set the paths correctly.The Environment variables dialog box

Is it something wrong with the path? Or do I have to download the IDE too?
P.S. I'm sort of a noobie here, so I can't directly insert the image, sorry.
Any help?

答: Try installing the "64 bit" rather than the "86 bit", worked for me</p>


问:
I try to run a script through TextWrangler - no module as matplotlib
I have Python 3.6 installed on my Mac OS X. When I wrote my script I wrote the following

```<code>import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader.data as web
</code>```

but then when I run it, I get the following error message:

Traceback (most recent call last): File
  "/Users/YoavPoni/Documents/Python/TextWranglerRunTemp-sen.py", line
  4, in  import matplotlib.pyplot as plt
  ModuleNotFoundError: No module named 'matplotlib'

Any suggestions?

答:
You might need to change the Python you are invoking when running the program. Currently, you may be using the standard Python that comes from Mac OS X (that does not have matplotlib installed). What you need to do is run your code with the Python that has matplotlib installed in its library.

You should include a line at the beginning of your Python code like

#!/usr/bin/env python

With /usr/bin/env being the full path to the Python interpreter with matplotlib installed.

Body:
I have Python 3.6 installed on my Mac OS X. When I wrote my script I wrote the following

import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader.data as web

but then when I run it, I get the following error message:

Traceback (most recent call last): File
  "/Users/YoavPoni/Documents/Python/TextWranglerRunTemp-sen.py", line
  4, in  import matplotlib.pyplot as plt
  ModuleNotFoundError: No module named 'matplotlib'

Any suggestions?


问:
How to plot surface plot

Is there an inbuilt / m file in Matlab
  to obtain the highly fluctuatiing and
  multiple peaks of the plot of an
  alpine function? I want to obtain a
  similar figure in 3D which is !alt
  text and

The formula (probably) is

z=sin(x1)sin(x2)\sqrt{x1x2}

How does one plot a surface plot for the major functions like alpine,rosenbrock, egg crate function etc in a colorful illustrative way. Kindly help with a sample code.

答:
this may not be the answer you are looking for but i thought it might help you

i faced the same problem when i had to plot Kaplan Meier Survival Curve programmatically

what we did (me and my team) was first getting the formula then we contructed a datatable that used this formula.

the datatable once formed was the datasource for chart control where you can edit the visual output as preferred.

look at the code below (it is only part of it) to have an idea. if you need more code please let me know

```<code>  'Start generating the life tables

Dim myTable As New DataTable

myTable.Columns.Add("Survial Status")
myTable.Columns.Add("Remaining Patients")
myTable.Columns.Add("Survial Duration")
myTable.Columns.Add("Survial Propability")
myTable.Columns.Add("Cumulative Survial Propability")

Dim myFirstRow As DataRow = myTable.NewRow
myFirstRow.Item(0) = 1
myFirstRow.Item(1) = CasesCount
myFirstRow.Item(2) = 0
myFirstRow.Item(3) = 1
myFirstRow.Item(4) = 1

myTable.Rows.Add(myFirstRow)

Dim Ptnseq = CasesCount

For I = 1 To CasesCount

    Dim myRow As DataRow = myTable.NewRow

    'Get only one record  from KaplanTable
    Dim Kaplantmp = myReader.Read
    Ptnseq = Ptnseq - 1

    myRow.Item(0) = myReader.GetValue(2)
    myRow.Item(1) = Ptnseq 'Sets the total number of remaining patients
    myRow.Item(2) = myReader.GetValue(3)

    If myRow.Item(0) = 0 Then
        myRow.Item(3) = myTable.Rows(I - 1).Item(3)
        myRow.Item(4) = myTable.Rows(I - 1).Item(4)
    ElseIf myRow.Item(0) = 1 Then
        myRow.Item(3) = myRow.Item(1) / myTable.Rows(I - 1).Item(1)
        myRow.Item(4) = myRow.Item(3) * myTable.Rows(I - 1).Item(4)
    End If

    myTable.Rows.Add(myRow)

Next I

'Finished generating the lifetables, bind it to a grid

Dim myGrid As New GridView 'Create a new dynamc Grid
Dim myLabel As New Label 'Create a new dynamic label for this grid
myPage.Form.Controls.Add(myLabel) 'add the label, then
myPage.Form.Controls.Add(myGrid) 'add the grid
myGrid.DataSource = myTable 'Bind the grid to the calculated lifetables
myGrid.DataBind()

DrawKaplanCurve(myTable, myChart, Stratum)
myLabel.Text = "Current Stratum is: " & Stratum & "<br/>" & "Total Number of cases is: " & (myTable.Rows.Count - 1).ToString & " Cases"

Return myTable.Rows.Count - 1

End Function

Public Shared Sub DrawKaplanCurve(ByVal myTable As DataTable, ByVal myChart As Chart, ByVal Stratum As String)

Dim KaplanSeries As New Series
KaplanSeries.ChartType = SeriesChartType.StepLine
KaplanSeries.Name = Stratum

Dim CensoredSeries As New Series
CensoredSeries.ChartType = SeriesChartType.Stock
CensoredSeries.Name = "Censored " & Stratum

For I = 1 To myTable.Rows.Count - 1

    Dim myPoint As New DataPoint
    Dim xval As Double = myTable.Rows(I).Item(2)
    Dim yval As Double = myTable.Rows(I).Item(4)
    myPoint.SetValueXY(xval, yval)

    ' If alive case, then add to censored data
    If myTable.Rows(I).Item(0) = 0 Then
        Dim CensoredPoint As New DataPoint
        CensoredPoint.SetValueXY(myPoint.XValue, yval - 0.01, yval + 0.01)
        CensoredPoint.ToolTip = "Censored Case Number " & myTable.Rows(I).Item(1).ToString & vbNewLine & "Survival Duration = " & myTable.Rows(I).Item(2).ToString & " months" & vbNewLine & "Cumulative Survival Propability = " & Round(yval * 100, 2).ToString & "%"
        CensoredPoint.Color = myPoint.Color
        If I <> myTable.Rows.Count - 1 Then CensoredSeries.Points.Add(CensoredPoint) 'add all except the last point because it shouldn't be censored
    End If

    'myPoint.ToolTip = "Case Number " & myTable.Rows(I).Item(1).ToString & vbNewLine & "Survival Duration = " & myTable.Rows(I).Item(2).ToString & " months"
    If I = myTable.Rows.Count - 1 Then myPoint.Label = Round(yval * 100, 2).ToString & "%"
    KaplanSeries.Points.Add(myPoint)

Next

myChart.Series.Add(KaplanSeries)
myChart.Series.Add(CensoredSeries)
myChart.Series(CensoredSeries.Name).IsVisibleInLegend = False
Dim myLegend As New Legend
myLegend.TitleForeColor = myChart.Series(myChart.Series.Count - 1).Color
myChart.Legends.Add(myLegend)

End Sub
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to plot surface plot

Body:
this may not be the answer you are looking for but i thought it might help you

i faced the same problem when i had to plot Kaplan Meier Survival Curve programmatically

what we did (me and my team) was first getting the formula then we contructed a datatable that used this formula.

the datatable once formed was the datasource for chart control where you can edit the visual output as preferred.

look at the code below (it is only part of it) to have an idea. if you need more code please let me know

  'Start generating the life tables

Dim myTable As New DataTable

myTable.Columns.Add("Survial Status")
myTable.Columns.Add("Remaining Patients")
myTable.Columns.Add("Survial Duration")
myTable.Columns.Add("Survial Propability")
myTable.Columns.Add("Cumulative Survial Propability")

Dim myFirstRow As DataRow = myTable.NewRow
myFirstRow.Item(0) = 1
myFirstRow.Item(1) = CasesCount
myFirstRow.Item(2) = 0
myFirstRow.Item(3) = 1
myFirstRow.Item(4) = 1

myTable.Rows.Add(myFirstRow)

Dim Ptnseq = CasesCount

For I = 1 To CasesCount

    Dim myRow As DataRow = myTable.NewRow

    'Get only one record  from KaplanTable
    Dim Kaplantmp = myReader.Read
    Ptnseq = Ptnseq - 1

    myRow.Item(0) = myReader.GetValue(2)
    myRow.Item(1) = Ptnseq 'Sets the total number of remaining patients
    myRow.Item(2) = myReader.GetValue(3)

    If myRow.Item(0) = 0 Then
        myRow.Item(3) = myTable.Rows(I - 1).Item(3)
        myRow.Item(4) = myTable.Rows(I - 1).Item(4)
    ElseIf myRow.Item(0) = 1 Then
        myRow.Item(3) = myRow.Item(1) / myTable.Rows(I - 1).Item(1)
        myRow.Item(4) = myRow.Item(3) * myTable.Rows(I - 1).Item(4)
    End If

    myTable.Rows.Add(myRow)

Next I

'Finished generating the lifetables, bind it to a grid

Dim myGrid As New GridView 'Create a new dynamc Grid
Dim myLabel As New Label 'Create a new dynamic label for this grid
myPage.Form.Controls.Add(myLabel) 'add the label, then
myPage.Form.Controls.Add(myGrid) 'add the grid
myGrid.DataSource = myTable 'Bind the grid to the calculated lifetables
myGrid.DataBind()

DrawKaplanCurve(myTable, myChart, Stratum)
myLabel.Text = "Current Stratum is: " & Stratum & "<br/>" & "Total Number of cases is: " & (myTable.Rows.Count - 1).ToString & " Cases"

Return myTable.Rows.Count - 1

End Function

Public Shared Sub DrawKaplanCurve(ByVal myTable As DataTable, ByVal myChart As Chart, ByVal Stratum As String)

Dim KaplanSeries As New Series
KaplanSeries.ChartType = SeriesChartType.StepLine
KaplanSeries.Name = Stratum

Dim CensoredSeries As New Series
CensoredSeries.ChartType = SeriesChartType.Stock
CensoredSeries.Name = "Censored " & Stratum

For I = 1 To myTable.Rows.Count - 1

    Dim myPoint As New DataPoint
    Dim xval As Double = myTable.Rows(I).Item(2)
    Dim yval As Double = myTable.Rows(I).Item(4)
    myPoint.SetValueXY(xval, yval)

    ' If alive case, then add to censored data
    If myTable.Rows(I).Item(0) = 0 Then
        Dim CensoredPoint As New DataPoint
        CensoredPoint.SetValueXY(myPoint.XValue, yval - 0.01, yval + 0.01)
        CensoredPoint.ToolTip = "Censored Case Number " & myTable.Rows(I).Item(1).ToString & vbNewLine & "Survival Duration = " & myTable.Rows(I).Item(2).ToString & " months" & vbNewLine & "Cumulative Survival Propability = " & Round(yval * 100, 2).ToString & "%"
        CensoredPoint.Color = myPoint.Color
        If I <> myTable.Rows.Count - 1 Then CensoredSeries.Points.Add(CensoredPoint) 'add all except the last point because it shouldn't be censored
    End If

    'myPoint.ToolTip = "Case Number " & myTable.Rows(I).Item(1).ToString & vbNewLine & "Survival Duration = " & myTable.Rows(I).Item(2).ToString & " months"
    If I = myTable.Rows.Count - 1 Then myPoint.Label = Round(yval * 100, 2).ToString & "%"
    KaplanSeries.Points.Add(myPoint)

Next

myChart.Series.Add(KaplanSeries)
myChart.Series.Add(CensoredSeries)
myChart.Series(CensoredSeries.Name).IsVisibleInLegend = False
Dim myLegend As New Legend
myLegend.TitleForeColor = myChart.Series(myChart.Series.Count - 1).Color
myChart.Legends.Add(myLegend)

End Sub


问:
Awk Command not working as it should, output is wrong, sed command?
I tried this little script on my dataset and for some reason I am not getting the desired output? can someone have a look ? Maybe you can figure it out? Also if you could offer a SED command solution.

Script

```<code>awk -v RS= -F '<connection name="|<hostPort>' '
{
sub(/".*/, "", $2)
split($3, tokens, /[:<]/)
printf "%-6s %s %s\n", $2, tokens[1], tokens[2]
}
'
</code>```

input

```<code><hostPort>srv1:33333</hostPort>
<hostPort>srv2:33333</hostPort>
<connection name="boing_ny__Primary__" transport="tcp">
<hostPort>srv1:33333</hostPort>
<connection name="boing_ny__Backup__" transport="tcp">
<hostPort>srv2:33333</hostPort>
<connection name="boy_ny__Primary__" transport="tcp">
<hostPort>srv1:6666</hostPort>
<connection name="boy_ny__Backup__" transport="tcp">
<hostPort>srv2:6666</hostPort>
<connection name="song_ny__Primary__" transport="tcp">
<hostPort>srv1:55555</hostPort>
<connection name="song_ny__Backup__" transport="tcp">
<hostPort>srv2:55555</hostPort>
<connection name="bob_ny__Primary__" transport="tcp">
<hostPort>srv3:33333</hostPort>
<connection name="bob_ny__Backup__" transport="tcp">
<hostPort>srv4:33333</hostPort>
<hostPort>srv1:4444</hostPort>
<hostPort>srv2:4444</hostPort>
<hostPort>srv1:4444</hostPort>
</code>```

Current output

```<code>srv1:33333</hostPort>
srv2 33333
</code>```

desired output

```<code>boing_ny__Primary__  srv1 33333
boing_ny__Backup__   srv2 33333
boy_ny__Primary__     srv1 6666
boy_ny__Backup__   srv2 6666
song_ny__Primary__ srv1 55555
song_ny__Backup__ srv2 55555
bob_ny__Primary__ srv3 33333
bob_ny__Backup__ srv4 33333
</code>```

答:
```<code>$ awk -F'[":<>]' '/hostPort/{if (n!="") print n, $3, $4; n=""; next} {n=$3}' file
boing_ny__Primary__ srv1 33333
boing_ny__Backup__ srv2 33333
boy_ny__Primary__ srv1 6666
boy_ny__Backup__ srv2 6666
song_ny__Primary__ srv1 55555
song_ny__Backup__ srv2 55555
bob_ny__Primary__ srv3 33333
bob_ny__Backup__ srv4 33333
</code>```

Body:
I tried this little script on my dataset and for some reason I am not getting the desired output? can someone have a look ? Maybe you can figure it out? Also if you could offer a SED command solution.

Script

awk -v RS= -F '<connection name="|<hostPort>' '
{
sub(/".*/, "", $2)
split($3, tokens, /[:<]/)
printf "%-6s %s %s\n", $2, tokens[1], tokens[2]
}
'

input

<hostPort>srv1:33333</hostPort>
<hostPort>srv2:33333</hostPort>
<connection name="boing_ny__Primary__" transport="tcp">
<hostPort>srv1:33333</hostPort>
<connection name="boing_ny__Backup__" transport="tcp">
<hostPort>srv2:33333</hostPort>
<connection name="boy_ny__Primary__" transport="tcp">
<hostPort>srv1:6666</hostPort>
<connection name="boy_ny__Backup__" transport="tcp">
<hostPort>srv2:6666</hostPort>
<connection name="song_ny__Primary__" transport="tcp">
<hostPort>srv1:55555</hostPort>
<connection name="song_ny__Backup__" transport="tcp">
<hostPort>srv2:55555</hostPort>
<connection name="bob_ny__Primary__" transport="tcp">
<hostPort>srv3:33333</hostPort>
<connection name="bob_ny__Backup__" transport="tcp">
<hostPort>srv4:33333</hostPort>
<hostPort>srv1:4444</hostPort>
<hostPort>srv2:4444</hostPort>
<hostPort>srv1:4444</hostPort>

Current output

srv1:33333</hostPort>
srv2 33333

desired output

boing_ny__Primary__  srv1 33333
boing_ny__Backup__   srv2 33333
boy_ny__Primary__     srv1 6666
boy_ny__Backup__   srv2 6666
song_ny__Primary__ srv1 55555
song_ny__Backup__ srv2 55555
bob_ny__Primary__ srv3 33333
bob_ny__Backup__ srv4 33333


问:
Laravel using user id in route
So I have a route profile/{user_id}

How do I redirect user to that URL when they click on link?

Here's my controller:

```<code>{
    function checkid($user_id) {
      if (Auth::check())
      {
        $user_id = Auth::id();
        return view('profile', [
        'id' => $user_id
        ]);
      }
    }
}
</code>```

答:
You can redirect with the redirect() helper method like this:

```<code>return redirect()->url('/profile/' . $user_id);
</code>```

But I'm not really following your usecase? Why do you want to redirect? Do you always want the user to go to their own profile? Because right now you are using the id from the authenticated user, so the user_id parameter is pretty much useless.

Title: Laravel using user id in route

Body:
So I have a route profile/{user_id}

How do I redirect user to that URL when they click on link?

Here's my controller:

{
    function checkid($user_id) {
      if (Auth::check())
      {
        $user_id = Auth::id();
        return view('profile', [
        'id' => $user_id
        ]);
      }
    }
}

Body:
You can redirect with the redirect() helper method like this:

return redirect()->url('/profile/' . $user_id);

But I'm not really following your usecase? Why do you want to redirect? Do you always want the user to go to their own profile? Because right now you are using the id from the authenticated user, so the user_id parameter is pretty much useless.


问:
Regex with nested group and dot causes wacky matching
I cannot understand why the following regex and text yield their results. I am using the regex find function in notepad++ with no Wrap_around and no matching newline. The regex:

```<code>name ="[\w]+\.((?:[\w]*\.?)+)" p
</code>```

when applied to the text:

name ="data.messageHeader.msg_time_tag.$date" pzb

this is line 2

The entire text ends up highlighted, which should be impossible, since the regex should not be able to match the dollar sign or the newline/carriage return.

I have also tried applying the regex to the text with python 're'. In this case, I parsed the full file line by line. Initially, python correctly did not match the lines with dollar signs, but those lines would take a few seconds to finish even though they were only about 100 characters. By the fourth or fifth line that contained the structure of my sample, where the dot-separated words contained a '$', python froze up until I manually stopped it.

The python code used:

```<code>import re
def main():
    pattern = re.compile(r"name =\"\w+\.((?:\w+\.?)+)\" p")
    with open(r"filepath", "r") as f:
        i = 0
        for line in f:
            match = pattern.search(line)
            if (match):
                print('<Match: %r, groups=%r>' % (match.group(), match.groups()))
            else:
                print("line %d nomatch" % (i))
            i+=1
            match = None
            #it = pattern.finditer(f.read())
            #for element in it:
                #displaymatch(element)

def displaymatch(match):
    if match is None:
        return None
    print('<Match: %r, groups=%r>' % (match.group(), match.groups()))
main()
</code>```

Can you explain why this is happening?

答:
I get a long pause in Notepad++ before the text is selected, which suggests that it was caught in an infinite loop, and selecting all the text is just it's default behavior when breaking out of a loop like that.

Now, since this section (?:[\w]*\.?) can collapse down to nothing, and it can appear one or more times, I guess it's just repeatedly matching nothing until it finds something to match the $.

name ="[\w]+\.((?:[\w$]*\.?)+)" p seems to work correctly.

UPDATE:
This seems to handle what you ask:

```<code>name ="\w+\.(?:(\w+\.)*\w+)" p
</code>```

Body:
I cannot understand why the following regex and text yield their results. I am using the regex find function in notepad++ with no Wrap_around and no matching newline. The regex:

name ="[\w]+\.((?:[\w]*\.?)+)" p

when applied to the text:

name ="data.messageHeader.msg_time_tag.$date" pzb

this is line 2

The entire text ends up highlighted, which should be impossible, since the regex should not be able to match the dollar sign or the newline/carriage return.

I have also tried applying the regex to the text with python 're'. In this case, I parsed the full file line by line. Initially, python correctly did not match the lines with dollar signs, but those lines would take a few seconds to finish even though they were only about 100 characters. By the fourth or fifth line that contained the structure of my sample, where the dot-separated words contained a '$', python froze up until I manually stopped it.

The python code used:

import re
def main():
    pattern = re.compile(r"name =\"\w+\.((?:\w+\.?)+)\" p")
    with open(r"filepath", "r") as f:
        i = 0
        for line in f:
            match = pattern.search(line)
            if (match):
                print('<Match: %r, groups=%r>' % (match.group(), match.groups()))
            else:
                print("line %d nomatch" % (i))
            i+=1
            match = None
            #it = pattern.finditer(f.read())
            #for element in it:
                #displaymatch(element)

def displaymatch(match):
    if match is None:
        return None
    print('<Match: %r, groups=%r>' % (match.group(), match.groups()))
main()

Can you explain why this is happening?

Body:
I get a long pause in Notepad++ before the text is selected, which suggests that it was caught in an infinite loop, and selecting all the text is just it's default behavior when breaking out of a loop like that.

Now, since this section (?:[\w]*\.?) can collapse down to nothing, and it can appear one or more times, I guess it's just repeatedly matching nothing until it finds something to match the $.

name ="[\w]+\.((?:[\w$]*\.?)+)" p seems to work correctly.

UPDATE:
This seems to handle what you ask:

name ="\w+\.(?:(\w+\.)*\w+)" p


问:
Angular 2 Scroll to top on Route Change
In my Angular 2 app when I scroll down a page and click the link at the bottom of the page, it does change the route and takes me to the next page but it doesn't scroll to the top of the page. As a result, if the first page is lengthy and 2nd page has few contents, it gives an impression that the 2nd page lacks the contents. Since the contents are visible only if a user scrolls to the top of the page.

I can scroll the window to the top of the page in ngInit of the component but, is there any better solution that can automatically handle all routes in my app?

答:
Angular 6.1 and later:

Angular 6.1 (released on 2018-07-25) added built-in support to handle this issue, through a feature called "Router Scroll Position Restoration". As described in the official Angular blog, you just need to enable this in the router configuration like this:

RouterModule.forRoot(routes, {scrollPositionRestoration: 'enabled'})
```
<p>Furthermore, the blog states "It is expected that this will become the default in a future major release". So far this hasn't happened (as of Angular 13.0), but eventually you won't need to do anything at all in your code, and this will just work correctly out of the box.</p>
<p>You can see more details about this feature and how to customize this behavior in the official docs.</p>
<p><strong>Angular 6.0 and earlier</strong>:</p>
<p>While @GuilhermeMeireles's excellent answer fixes the original problem, it introduces a new one, by breaking the normal behavior you expect when you navigate back or forward (with browser buttons or via Location in code). The expected behavior is that when you navigate back to the page, it should remain scrolled down to the same location it was when you clicked on the link, but scrolling to the top when arriving at every page obviously breaks this expectation.</p>
<p>The code below expands the logic to detect this kind of navigation by subscribing to Location's PopStateEvent sequence and skipping the scroll-to-top logic if the newly arrived-at page is a result of such an event.</p>
<p>If the page you navigate back from is long enough to cover the whole viewport, the scroll position is restored automatically, but as @JordanNelson correctly pointed out, if the page is shorter you need to keep track of the original y scroll position and restored it explicitly when you go back to the page. The updated version of the code covers this case too, by always explicitly restoring the scroll position.</p>

<pre class="lang-js prettyprint-override"><code>import { Component, OnInit } from '@angular/core';
import { Router, NavigationStart, NavigationEnd } from '@angular/router';
import { Location, PopStateEvent } from "@angular/common";

@Component({
    selector: 'my-app',
    template: '<ng-content></ng-content>',
})
export class MyAppComponent implements OnInit {

    private lastPoppedUrl: string;
    private yScrollStack: number[] = [];

    constructor(private router: Router, private location: Location) { }

    ngOnInit() {
        this.location.subscribe((ev:PopStateEvent) => {
            this.lastPoppedUrl = ev.url;
        });
        this.router.events.subscribe((ev:any) => {
            if (ev instanceof NavigationStart) {
                if (ev.url != this.lastPoppedUrl)
                    this.yScrollStack.push(window.scrollY);
            } else if (ev instanceof NavigationEnd) {
                if (ev.url == this.lastPoppedUrl) {
                    this.lastPoppedUrl = undefined;
                    window.scrollTo(0, this.yScrollStack.pop());
                } else
                    window.scrollTo(0, 0);
            }
        });
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Angular 2 Scroll to top on Route Change

Body:
Angular 6.1 and later:

Angular 6.1 (released on 2018-07-25) added built-in support to handle this issue, through a feature called "Router Scroll Position Restoration". As described in the official Angular blog, you just need to enable this in the router configuration like this:

RouterModule.forRoot(routes, {scrollPositionRestoration: 'enabled'})

Furthermore, the blog states "It is expected that this will become the default in a future major release". So far this hasn't happened (as of Angular 13.0), but eventually you won't need to do anything at all in your code, and this will just work correctly out of the box.

You can see more details about this feature and how to customize this behavior in the official docs.

Angular 6.0 and earlier:

While @GuilhermeMeireles's excellent answer fixes the original problem, it introduces a new one, by breaking the normal behavior you expect when you navigate back or forward (with browser buttons or via Location in code). The expected behavior is that when you navigate back to the page, it should remain scrolled down to the same location it was when you clicked on the link, but scrolling to the top when arriving at every page obviously breaks this expectation.

The code below expands the logic to detect this kind of navigation by subscribing to Location's PopStateEvent sequence and skipping the scroll-to-top logic if the newly arrived-at page is a result of such an event.

If the page you navigate back from is long enough to cover the whole viewport, the scroll position is restored automatically, but as @JordanNelson correctly pointed out, if the page is shorter you need to keep track of the original y scroll position and restored it explicitly when you go back to the page. The updated version of the code covers this case too, by always explicitly restoring the scroll position.

import { Component, OnInit } from '@angular/core';
import { Router, NavigationStart, NavigationEnd } from '@angular/router';
import { Location, PopStateEvent } from "@angular/common";

@Component({
    selector: 'my-app',
    template: '<ng-content></ng-content>',
})
export class MyAppComponent implements OnInit {

    private lastPoppedUrl: string;
    private yScrollStack: number[] = [];

    constructor(private router: Router, private location: Location) { }

    ngOnInit() {
        this.location.subscribe((ev:PopStateEvent) => {
            this.lastPoppedUrl = ev.url;
        });
        this.router.events.subscribe((ev:any) => {
            if (ev instanceof NavigationStart) {
                if (ev.url != this.lastPoppedUrl)
                    this.yScrollStack.push(window.scrollY);
            } else if (ev instanceof NavigationEnd) {
                if (ev.url == this.lastPoppedUrl) {
                    this.lastPoppedUrl = undefined;
                    window.scrollTo(0, this.yScrollStack.pop());
                } else
                    window.scrollTo(0, 0);
            }
        });
    }
}


问:
Do browsers need to re-download customized fonts every time they access a website?
Suppose I have a website in which I have customized fonts, and all the .otf files are about 1MB.

Now, when a user visits the website, the fonts will be downloaded. The question is, will these fonts remain in the user's browser as installed all the time? I.e. Even if the user turns off the browser, will the fonts remain in there? Or are .otf files just like all the .css .html files? Which can be cached but then need to be downloaded again?

If the latter, how do we deal with this problem? I mean making the user download 1MB of fonts is not good for UX. How other websites deal with this problem? Is some kind of local storage used?

答:
All external includes in a page can be cached: e.g.

Images (GIF, JPG, PNG)

CSS stylesheets

JavaScript/JSON files

Audio

Video

Etc.

The key is setting the right HTTP Response headers to enable them to be cached for as long as you'd like them to be.

```<code>//PHP style, other server lang syntaxes will vary
header("Cache-Control: max-age=31536000"); //365 days
</code>```

You can't guarantee that the end user will keep them in the cache, but the Cache-Control headers tell the browser how long they can keep them for.

Unfortunately some users have their browser configured to flush the cache on closing, or only maintain a very small cache.  You can track your web server logs/stats to see if your users are caching things well.

Body:
All external includes in a page can be cached: e.g.

Images (GIF, JPG, PNG)

CSS stylesheets

JavaScript/JSON files

Audio

Video

Etc.

The key is setting the right HTTP Response headers to enable them to be cached for as long as you'd like them to be.

//PHP style, other server lang syntaxes will vary
header("Cache-Control: max-age=31536000"); //365 days

You can't guarantee that the end user will keep them in the cache, but the Cache-Control headers tell the browser how long they can keep them for.

Unfortunately some users have their browser configured to flush the cache on closing, or only maintain a very small cache.  You can track your web server logs/stats to see if your users are caching things well.


问:
jQuery hasClass and if
I have a problem with jquery hasClass.

```<code>$(document).ready(function () {

var body = $('body'),
    leftPane = $('.pane-left');

leftPane.on('click', function () {

    body.removeClass('left-closed');
    body.addClass('left-open');
    $('.pane-left h2').fadeIn(600);

    setTimeout(function() {
        rightPane.fadeOut(0);
        $('.pane-left-wrap').fadeIn(100);
        $('.pane-left-wrap .secondary-nav li:first-child').fadeIn(100);
        $('.pane-left-wrap .secondary-nav li:nth-child(2)').fadeIn(600);
        $('.pane-left-wrap .secondary-nav li:nth-child(3)').fadeIn(1200);
        $('.pane-left-wrap .secondary-nav li:nth-child(4)').fadeIn(1800);
        $('.pane-left-wrap .secondary-nav li:nth-child(5)').fadeIn(2400);
    }, 600);

});

if(body.hasClass('left-open')) {

    leftPane.on('click', function () {

        body.removeClass('left-open');
        body.addClass('left-closed');
        $('.pane-left h2').fadeOut(600);

    });

}

});
</code>```

I click pane-left and left-open is added to my body tag. Then i click again but the code inside my if() is unreachable. Why is that?

答:
If condition only run once in document.ready state, so you must be add if in your click event. But you have a action in click event and i think it's correct code for your purpose:

```<code>$(document).ready(function () {

    var body = $('body'),
        leftPane = $('.pane-left');

    leftPane.on('click', function () {

        if(body.hasClass('left-open')) {
            body.removeClass('left-open');
            body.addClass('left-closed');
            $('.pane-left h2').fadeOut(600);
        } else {
            body.removeClass('left-closed');
            body.addClass('left-open');
            $('.pane-left h2').fadeIn(600);

            setTimeout(function() {
                rightPane.fadeOut(0);
                $('.pane-left-wrap').fadeIn(100);
                $('.pane-left-wrap .secondary-nav li:first-child').fadeIn(100);
                $('.pane-left-wrap .secondary-nav li:nth-child(2)').fadeIn(600);
                $('.pane-left-wrap .secondary-nav li:nth-child(3)').fadeIn(1200);
                $('.pane-left-wrap .secondary-nav li:nth-child(4)').fadeIn(1800);
                $('.pane-left-wrap .secondary-nav li:nth-child(5)').fadeIn(2400);
            }, 600);
        }
    });

});
</code>```

Title: jQuery hasClass and if

Body:
I have a problem with jquery hasClass.

$(document).ready(function () {

var body = $('body'),
    leftPane = $('.pane-left');

leftPane.on('click', function () {

    body.removeClass('left-closed');
    body.addClass('left-open');
    $('.pane-left h2').fadeIn(600);

    setTimeout(function() {
        rightPane.fadeOut(0);
        $('.pane-left-wrap').fadeIn(100);
        $('.pane-left-wrap .secondary-nav li:first-child').fadeIn(100);
        $('.pane-left-wrap .secondary-nav li:nth-child(2)').fadeIn(600);
        $('.pane-left-wrap .secondary-nav li:nth-child(3)').fadeIn(1200);
        $('.pane-left-wrap .secondary-nav li:nth-child(4)').fadeIn(1800);
        $('.pane-left-wrap .secondary-nav li:nth-child(5)').fadeIn(2400);
    }, 600);

});

if(body.hasClass('left-open')) {

    leftPane.on('click', function () {

        body.removeClass('left-open');
        body.addClass('left-closed');
        $('.pane-left h2').fadeOut(600);

    });

}

});

I click pane-left and left-open is added to my body tag. Then i click again but the code inside my if() is unreachable. Why is that?

Body:
If condition only run once in document.ready state, so you must be add if in your click event. But you have a action in click event and i think it's correct code for your purpose:

$(document).ready(function () {

    var body = $('body'),
        leftPane = $('.pane-left');

    leftPane.on('click', function () {

        if(body.hasClass('left-open')) {
            body.removeClass('left-open');
            body.addClass('left-closed');
            $('.pane-left h2').fadeOut(600);
        } else {
            body.removeClass('left-closed');
            body.addClass('left-open');
            $('.pane-left h2').fadeIn(600);

            setTimeout(function() {
                rightPane.fadeOut(0);
                $('.pane-left-wrap').fadeIn(100);
                $('.pane-left-wrap .secondary-nav li:first-child').fadeIn(100);
                $('.pane-left-wrap .secondary-nav li:nth-child(2)').fadeIn(600);
                $('.pane-left-wrap .secondary-nav li:nth-child(3)').fadeIn(1200);
                $('.pane-left-wrap .secondary-nav li:nth-child(4)').fadeIn(1800);
                $('.pane-left-wrap .secondary-nav li:nth-child(5)').fadeIn(2400);
            }, 600);
        }
    });

});


问:
Why do I get a System.IO.FileLoadException for the System.Runtime.InteropServices assembly when using SqlClient in .NET Core?
I developed a .NET Core application.
The solution consists of netstandard1.6 from the library and the console application netcoreapp1.1.
Both projects use SqlClient.
If I do publish on Windows and run, then everything will work out well.
If I run on Linux then the application crash and an error occurs:

Unhandled Exception: System.Data.SqlClient.SqlException: A
  network-related or instance-specific error occurred while establishing
  a connection to SQL Server. The server was not found or was not
  accessible. Verify that the instance name is correct and that SQL
  Server is configured to allow remote connections. (provider: TCP
  Provider, error: 35 - An internal exception was caught) --->
  System.AggregateException: One or more errors occurred. (The type
  initializer for 'System.Runtime.Versioning.BinaryCompatibility' threw
  an exception.) ---> System.TypeInitializationException: The type
  initializer for 'System.Runtime.Versioning.BinaryCompatibility' threw
  an exception. ---> System.IO.FileLoadException: Could not load file
  or assembly 'System.Runtime.InteropServices, Version=4.1.1.0,
  Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The located
  assembly's manifest definition does not match the assembly reference.
  (Exception from HRESULT: 0x80131040)

PS: In fact, the server is available and you can connect to it from the application you just created on Linux.

```<code>dotnet --info
Product Information:
Version:            1.0.4
Commit SHA-1 hash:  af1e6684fd

Runtime Environment:
OS Name:     ubuntu
OS Version:  16.04
OS Platform: Linux
RID:         ubuntu.16.04-x64
Base Path:   /usr/share/dotnet/sdk/1.0.4
</code>```

答:
Most likely you are missing one of the dependcies

Here is my snippet:

```<code>apt-get update \
&& apt-get install -y --no-install-recommends \
    libc6 \
    libcurl3 \
    libgcc1 \
    libgssapi-krb5-2 \
    libicu52 \
    liblttng-ust0 \
    libgdiplus \
    libssl1.0.0 \
    libstdc++6 \
    libunwind8 \
    libuuid1 \
    zlib1g \
</code>```

if not refer to this

Body:
I developed a .NET Core application.
The solution consists of netstandard1.6 from the library and the console application netcoreapp1.1.
Both projects use SqlClient.
If I do publish on Windows and run, then everything will work out well.
If I run on Linux then the application crash and an error occurs:

Unhandled Exception: System.Data.SqlClient.SqlException: A
  network-related or instance-specific error occurred while establishing
  a connection to SQL Server. The server was not found or was not
  accessible. Verify that the instance name is correct and that SQL
  Server is configured to allow remote connections. (provider: TCP
  Provider, error: 35 - An internal exception was caught) --->
  System.AggregateException: One or more errors occurred. (The type
  initializer for 'System.Runtime.Versioning.BinaryCompatibility' threw
  an exception.) ---> System.TypeInitializationException: The type
  initializer for 'System.Runtime.Versioning.BinaryCompatibility' threw
  an exception. ---> System.IO.FileLoadException: Could not load file
  or assembly 'System.Runtime.InteropServices, Version=4.1.1.0,
  Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The located
  assembly's manifest definition does not match the assembly reference.
  (Exception from HRESULT: 0x80131040)

PS: In fact, the server is available and you can connect to it from the application you just created on Linux.

dotnet --info
Product Information:
Version:            1.0.4
Commit SHA-1 hash:  af1e6684fd

Runtime Environment:
OS Name:     ubuntu
OS Version:  16.04
OS Platform: Linux
RID:         ubuntu.16.04-x64
Base Path:   /usr/share/dotnet/sdk/1.0.4

Body:
Most likely you are missing one of the dependcies

Here is my snippet:

apt-get update \
&& apt-get install -y --no-install-recommends \
    libc6 \
    libcurl3 \
    libgcc1 \
    libgssapi-krb5-2 \
    libicu52 \
    liblttng-ust0 \
    libgdiplus \
    libssl1.0.0 \
    libstdc++6 \
    libunwind8 \
    libuuid1 \
    zlib1g \

if not refer to this


问:
Unable to get the tab content on right side
I have a peculiar problem of tab content not floating on right side as its tabs are on right side too. Below is the picture to get a better idea:

I have tried floating the tab content right but not working. Rather its going past right where I can't see anything. This problem exists for both Live Chat and Mail Us tabs.

Below is the codepen.

HTML Code

```<code><div class="tab-pane livechat wow animated bounceInLeft" id="chat">
     <div class="chatwidget">
                <a href="#" class="wow animated shake">Click for Chat</a>
     </div>
</div>
</code>```

CSS3

```<code>.livechat {
position: absolute;
bottom: 0px;
width: 50%;
background-color: #eee;
height: 370px;
text-align: center;
box-shadow: 0 0 20px grey;
float: right;
}
.chatwidget {
  padding: 150px;
  font-size: 24px;
 }
</code>```

答:
Instead of float:right, use right:0px;

```<code>.livechat {
    position: absolute;
    bottom: 0px;
    width: 50%;
    background-color: #eee;
    height: 370px;
    text-align: center;
    box-shadow: 0 0 20px grey;
    right: 0;
}
</code>```

Body:
I have a peculiar problem of tab content not floating on right side as its tabs are on right side too. Below is the picture to get a better idea:

I have tried floating the tab content right but not working. Rather its going past right where I can't see anything. This problem exists for both Live Chat and Mail Us tabs.

Below is the codepen.

HTML Code

                Click for Chat

CSS3

.livechat {
position: absolute;
bottom: 0px;
width: 50%;
background-color: #eee;
height: 370px;
text-align: center;
box-shadow: 0 0 20px grey;
float: right;
}
.chatwidget {
  padding: 150px;
  font-size: 24px;
 }

Body:
Instead of float:right, use right:0px;

.livechat {
    position: absolute;
    bottom: 0px;
    width: 50%;
    background-color: #eee;
    height: 370px;
    text-align: center;
    box-shadow: 0 0 20px grey;
    right: 0;
}


问:
Can't make a new Jekyll project
I am using Bash on Ubuntu on Windows.

I can create projects but for some reason they end up being creating in a directory that I don't even have access to. I am quite new to terminals. Does anybody know how to fix this (i.e. how to create a project in a directory that I actually have on my computer)?

As you can see in the screenshot, the new project has been installed in /home/[my username]/test123. That directory doesn't exist on my computer.

Edit: Can I get some help instead of being mercilessly downvoted?

答:
Posting a solution from a query in Jekyll's own forum:

Apparently, the root directory for "Bash on Ubuntu on Windows" is C:\Users[Username]\AppData\Local\Lxss\rootfs (More Info).

The project file you create can be found in the path mentioned above.

Title: Can't make a new Jekyll project


答:
To right align an absolute positioned element, use right: 0; instead of float: right, float has no effect on absolute positioned elements.

Updated codepen

```<code>.livechat {
    position: absolute;
    bottom: 0px;
    width: 50%;
    right: 0;
    background-color: #eee;
    height: 370px;
    text-align: center;
    box-shadow: 0 0 20px grey;
}
</code>```

Title: Unable to get the tab content on right side

Body:
To right align an absolute positioned element, use right: 0; instead of float: right, float has no effect on absolute positioned elements.

Updated codepen

.livechat {
    position: absolute;
    bottom: 0px;
    width: 50%;
    right: 0;
    background-color: #eee;
    height: 370px;
    text-align: center;
    box-shadow: 0 0 20px grey;
}


问:
How to get a part of the levels of a categorical variable?
My data set looks like the following:

```<code>        dsn                register_at
1 AC000W000014612   Thu Mar 02 21:34:30 UTC 2017
2 AC000W000016124   Tue Mar 14 19:40:57 UTC 2017
3 AC000W000016219   Tue Apr 14 19:29:10 UTC 2017
</code>```

I need to get just the month specification like Mar, Apr etc for each dsn. How do I grab only the month specification from the register at variable?

答:
You should perform the following steps:

Set up your locale to English (if your machine's locale is already English, you can skip this step!)

Use the as.Date function to format your data (Please check the format string below)

Once the data is in Date format, just extract the month part from the date.

Sample code:

```<code>#Create the data frame
mdata <- data.frame(dsn=character(0), register_at=character(0))
mdata <- edit(mdata)

#Set the locale to en_US (This is required, because month/date names are in english)
Sys.setlocale(category = "LC_TIME", locale="English_US.1252")
Sys.getlocale()

#Convert the variable to date
mdata$register_at_date <- as.Date(mdata$register_at,format="%a %b %d %H:%M:%S UTC %Y")

#Extract the month part
mdata$month <- months(mdata$register_at_date)

#Print out the data frame
print(mdata)
</code>```

Body:
My data set looks like the following:

        dsn                register_at
1 AC000W000014612   Thu Mar 02 21:34:30 UTC 2017
2 AC000W000016124   Tue Mar 14 19:40:57 UTC 2017
3 AC000W000016219   Tue Apr 14 19:29:10 UTC 2017

I need to get just the month specification like Mar, Apr etc for each dsn. How do I grab only the month specification from the register at variable?

Body:
You should perform the following steps:

Set up your locale to English (if your machine's locale is already English, you can skip this step!)

Use the as.Date function to format your data (Please check the format string below)

Once the data is in Date format, just extract the month part from the date.

Sample code:

#Create the data frame
mdata <- data.frame(dsn=character(0), register_at=character(0))
mdata <- edit(mdata)

#Set the locale to en_US (This is required, because month/date names are in english)
Sys.setlocale(category = "LC_TIME", locale="English_US.1252")
Sys.getlocale()

#Convert the variable to date
mdata$register_at_date <- as.Date(mdata$register_at,format="%a %b %d %H:%M:%S UTC %Y")

#Extract the month part
mdata$month <- months(mdata$register_at_date)

#Print out the data frame
print(mdata)


问:
I can't create a fixed position using css "
" not working
I want to enter Adsense code under a fixed position on the side bar so that it scrolls with the page.
I am trying

```<code><div style='position: fixed'>
    adsense code
</div>
</code>```

The Adsense ad works fine without the css code however when i add the div it goes blank and nothing shows. What am i doing wrong?

答: You should add width and height settings to that DIV, otherwise (with position: fixed) it will be 0x0 = invisible.

Title: I can't create a fixed position using css "<div style='position: fixed'>" not working

Body:
I want to enter Adsense code under a fixed position on the side bar so that it scrolls with the page.
I am trying

    adsense code

The Adsense ad works fine without the css code however when i add the div it goes blank and nothing shows. What am i doing wrong?


问:
for each loop in java not working with a array that changes as loop progresses
In this I have provided an array of arrays which changes as loop progresses , and the result was not as expected.
Please tell me why that happened.

```<code>public class forEach2 {

public static void main(String[] args) {

    int a [][] = {{ 1,2,3},{4 ,5,6},{7,8,9}};
    int proArr = 0;
    for (int pro : a[proArr] ){
        System.out.println(pro);
        proArr ++;
    }

}
</code>```

result -

```<code>1
2
3
</code>```

here , as the loop starts the value of proArr (which is handling the Array of Arrays , array 'a' to be more specific) changes but that puts no effect o the result.

the result is the data of a[0];

why is this happening in the for loop of Java ?

答:
You program is doing exactly as you have asked.

```<code>for ( x in { 1, 2, 3 } )
    echo x
</code>```

You loop a total of thee times, iterating each object in index 0 of the multi dimensional array. What do you expect?

In this example, proArr is meaningless after you start the for loop, as the incremented value is never consumed.

If you wish to print the whole multi dimensional array, you must use two nested loops.

```<code>// Loop super array, getting each nested array
for ( int[] x : a ) {

    // Loop each nested array and print
    for ( int y : x ) {

        System.out.println(y);
    }
}
</code>```

Edit

Update to print only first element of each array like OP needs

```<code>// Loop super array, getting each nested array
for ( int[] x : a ) {

    // Print first element of each
    System.out.println(x[0]);
}
</code>```

Body:
In this I have provided an array of arrays which changes as loop progresses , and the result was not as expected.
Please tell me why that happened.

public class forEach2 {

public static void main(String[] args) {

    int a [][] = {{ 1,2,3},{4 ,5,6},{7,8,9}};
    int proArr = 0;
    for (int pro : a[proArr] ){
        System.out.println(pro);
        proArr ++;
    }

}

result -

1
2
3

here , as the loop starts the value of proArr (which is handling the Array of Arrays , array 'a' to be more specific) changes but that puts no effect o the result.

the result is the data of a[0];

why is this happening in the for loop of Java ?

Body:
You program is doing exactly as you have asked.

for ( x in { 1, 2, 3 } )
    echo x

You loop a total of thee times, iterating each object in index 0 of the multi dimensional array. What do you expect?

In this example, proArr is meaningless after you start the for loop, as the incremented value is never consumed.

If you wish to print the whole multi dimensional array, you must use two nested loops.

// Loop super array, getting each nested array
for ( int[] x : a ) {

    // Loop each nested array and print
    for ( int y : x ) {

        System.out.println(y);
    }
}

Edit

Update to print only first element of each array like OP needs

// Loop super array, getting each nested array
for ( int[] x : a ) {

    // Print first element of each
    System.out.println(x[0]);
}


问:
How can recover the GCM API key? or know which account have the GCM API key?
I have a problem with the GCM API.

I have an application developed by other person in my company a few months ago and he is no longer working in the company, the problem is that in this moment the GCM API is response with the error “Invalid (legacy) Server-key delivered or Sender is not authorized to perform request”, I found that this error occurred because the key is deleted but I don’t know with which account was created this key and I can’t change the key by a new key because I need send a notification to all devices and the new key require that the devices to be registered again.
How can recover the key? or know which account have the key?

Thanks.

答:
AFAIK, you can't recover the Server Key. The Invalid Legacy Server Key doesn't signify that the key was deleted, it's just that you're using an old API key (see my answer here) and should use the Server key with a new format -- this is automatically generated by importing the corresponding project to Firebase, then going to the Project Settings > Cloud Messaging tab.

The tokens are not tied to the Server Key, it is only used for authorization when sending the messages. The tokens are instead, tied to the corresponding Sender ID.

If you have no way of identifying which project owns it, you should reach out to Firebase Support directly, providing as much details as you can.


问:
SharePointOnlineCredentials Missing or not found
I have added Sharepoint reference in my project. Even after adding reference, it is showing:

SharePointOnlineCredentials Missing or not found.

Can anyone suggest a solution?

答:
Its possible that you are missing a reference to another required assembly.  Check this out - http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.sharepointonlinecredentials.aspx.

If that doesn't solve it, check to be sure that you are using the correct SDK/runtime versions for the Sharepoint version you are trying to deploy for.


问:
Remove selected drop down1 value in drop down2 in select2 jquery
I have 5 drop downs in which if i select one value in drop down 1 and that selected value should not be there in remaining drop downs.

Im using select2 dropdown.
Here i have tried this one
    HTML:

      1
      2
      3
      4
      5

```<code><select class="select2" id="select2">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

<select class="select2" id="select3">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

<select class="select2" id="select4">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

<select class="select2" id="select5">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

jQuery:

$("select").on("select2:select", function (evt) {
    var element = evt.params.data.element;
    var $element = $(element);
    $element.detach();
    $(this).append($element);
    $('.#merchant_referral_customer_gms_id2').trigger("change");
});
</code>```

This one removing option in self dropdown not in others.

Can  any one please help out.

答:
$(document).ready(function() {
  $(".select_tes").select2();

  $('.select_tes').change(function(){
    var selected = $(this).val();
    $('.select_tes').find("option[value="+selected+"]").detach();
  })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />

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

<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

<select class='select_tes'>
  <option value='1'>tes1</option>
  <option value='2'>tes2</option>
  <option value='3'>tes3</option>
</select>

<select class='select_tes'>
  <option value='1'>tes1</option>
  <option value='2'>tes2</option>
  <option value='3'>tes3</option>
</select></code>```

Body:
I have 5 drop downs in which if i select one value in drop down 1 and that selected value should not be there in remaining drop downs.

Im using select2 dropdown.
Here i have tried this one
    HTML:

      1
      2
      3
      4
      5

<select class="select2" id="select2">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

<select class="select2" id="select3">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

<select class="select2" id="select4">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

<select class="select2" id="select5">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

jQuery:

$("select").on("select2:select", function (evt) {
    var element = evt.params.data.element;
    var $element = $(element);
    $element.detach();
    $(this).append($element);
    $('.#merchant_referral_customer_gms_id2').trigger("change");
});

This one removing option in self dropdown not in others.

Can  any one please help out.

Body:
$(document).ready(function() {
  $(".select_tes").select2();

  $('.select_tes').change(function(){
    var selected = $(this).val();
    $('.select_tes').find("option[value="+selected+"]").detach();
  })
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />

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

<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

<select class='select_tes'>
  <option value='1'>tes1</option>
  <option value='2'>tes2</option>
  <option value='3'>tes3</option>
</select>

<select class='select_tes'>
  <option value='1'>tes1</option>
  <option value='2'>tes2</option>
  <option value='3'>tes3</option>
</select>


问:
How to put divs on opposite sides of parent div, with parent width relative to them on scaling?
I have a container div (that cannot be floated) with two children elements. I want child elements to be on opposite sides - first on left, second on right. On 100% browser width children summary width is less than container, but on greater scales it is not, so container should be greater too. How to set container to grow when it's gloat child grow?

UPD: something like this
 I need all elements to stay one line in any scale.

```<code> <div id="page">
     <div id="container">
         <div id="left">
           <div>first</div>
           <div>second</div>
           <div>third</div>
         </div>
         <div id="right">
            right
         </div>
      </div>
    </div>
    <style>
    #page {
      background-color: grey;
      width: 100%;
      height: 300px;
    }
    #container {
      /*this styles are needed to other parts*/
      position: relative;
      clear: both;
      /*=====================================*/
      background-color:red;
      height: 50px;
      width: 90%;
      margin: 0 5%;
    }
    #left {
        float: left;
        background-color: blue;
    }
    #left div {
      width: 50px;
      display: inline-block;
    }
    #right{
     float: right;
     background-color: green;
     display: block;
     max-width: 200px;
    }
    </style>
</code>```

答:
something like this ?

I've used display:flex to let the two divs line up nicely, floats only needed for the inner boxed

https://jsfiddle.net/070rk2e1/1/

Body:
I have a container div (that cannot be floated) with two children elements. I want child elements to be on opposite sides - first on left, second on right. On 100% browser width children summary width is less than container, but on greater scales it is not, so container should be greater too. How to set container to grow when it's gloat child grow?

UPD: something like this
 I need all elements to stay one line in any scale.

first

second

third

            right


问:
How do I get DotNetOpenAuth to open a popup window for authentication?
I am relatively new to web development, so perhaps this is a rookie question.  I am trying to set up an ASP.NET MVC web site to implement DotNetOpenAuth as an OpenID relying party.

Right now it is all functioning, so that is pretty exciting.  My goal though was to have the OpenID authentication take place it a popup window.  This seems to be the default behavior when you using WebForms with the DNOA custom controls, but I haven't been able to figure it out in MVC.

I thought I was getting close with this:

```<code>var request = OpenIdRp.CreateRequest(id);
request.AddExtension(new UIRequest(Mode = UIModes.Popup));
</code>```

But the Mode field of the UIRequest is read-only.

Does anybody know how to create a request that tells the OpenID provider to open a popup window?

Thanks for any help.  So far I have been unable to track down any samples of this in action.

答:
On the v.3.4.5 I am using, Mode property of the UIRequest has both getter and setter.

```<code>var req = openid.CreateRequest(openid_identifier);

                    // Add UI Request
                    if (req.DiscoveryResult.IsExtensionSupported<UIRequest>())
                    {
                        req.AddExtension(new UIRequest()
                        {
                            Mode = UIModes.Popup
                        });
</code>```

You have to create the popup yourself. After the authentication takes place, you should refresh the parent window and close the popup.
At the form's submission I have

```<code><form action="/Account/OpenIdLogOn" target="popupWin" onsubmit="return openWindow('/Account/OpenIdLogOn', 'popupWin', 500, 500);">
</code>```

where

```<code>function openWindow(url, wname, width, height) {
    window.open(url, wname, "height=" + height + ",width=" + width + "location = 0, status = 1, resizable = 0, scrollbars=1, toolbar = 0");
    return true;
}
</code>```

and at the result view I have the following javascript

```<code>    <script type="text/javascript">
        $(function () {
            if (window.opener) {
                window.opener.location.href = window.opener.location.href;
                window.close();
            }
        });
    </script>
</code>```

I hope this makes sense.

Body:
I am relatively new to web development, so perhaps this is a rookie question.  I am trying to set up an ASP.NET MVC web site to implement DotNetOpenAuth as an OpenID relying party.

Right now it is all functioning, so that is pretty exciting.  My goal though was to have the OpenID authentication take place it a popup window.  This seems to be the default behavior when you using WebForms with the DNOA custom controls, but I haven't been able to figure it out in MVC.

I thought I was getting close with this:

var request = OpenIdRp.CreateRequest(id);
request.AddExtension(new UIRequest(Mode = UIModes.Popup));

But the Mode field of the UIRequest is read-only.

Does anybody know how to create a request that tells the OpenID provider to open a popup window?

Thanks for any help.  So far I have been unable to track down any samples of this in action.

Body:
On the v.3.4.5 I am using, Mode property of the UIRequest has both getter and setter.

var req = openid.CreateRequest(openid_identifier);

                    // Add UI Request
                    if (req.DiscoveryResult.IsExtensionSupported<UIRequest>())
                    {
                        req.AddExtension(new UIRequest()
                        {
                            Mode = UIModes.Popup
                        });

You have to create the popup yourself. After the authentication takes place, you should refresh the parent window and close the popup.
At the form's submission I have

<form action="/Account/OpenIdLogOn" target="popupWin" onsubmit="return openWindow('/Account/OpenIdLogOn', 'popupWin', 500, 500);">

where

function openWindow(url, wname, width, height) {
    window.open(url, wname, "height=" + height + ",width=" + width + "location = 0, status = 1, resizable = 0, scrollbars=1, toolbar = 0");
    return true;
}

and at the result view I have the following javascript

    <script type="text/javascript">
        $(function () {
            if (window.opener) {
                window.opener.location.href = window.opener.location.href;
                window.close();
            }
        });
    </script>

I hope this makes sense.


问:
DIV not displaying all JSON retrieved data
Why is this code not displaying all the data. It cuts off the display.

```<code><script type="text/javascript">
    $(document).ready(function() {
        var url = "http://xxxxxxx/integration/json_news.php";
        $.getJSON(url, function(result) {
            console.log(result);
            $.each(result, function(i, field) {
                var source = field.source;
                var summary = field.summary;
                var heading = field.heading;
                var news_date = field.news_date;
                $("#newsview").append("<tr class='even gradeA' width = '30px'><td><li><b>"+heading+" - "+news_date+"</b> <br />"+summary+"</i></li><br /></td></tr>");
            });
        });
    });
    </script>
</code>```

This is the DIV I am calling the ajax code.

```<code><!--NEWS PAGE -->
                <div data-page="news" class="page cached">
                    <div class="page-content">
                        <div id="newsview"></div>

                    </div>
                </div>
</code>```

I am using IntelXDK and building a Framework7 hybrid application

Somehow I can figure out why this is so when I test on the mobile phone. Could it be that Framework7 doesnot display data beyond certain size? Or my code is faulty somehow.

答:
Unfortunately your js-generated HTML is not valid.

You're appending table rows tr to div. They also contain li.

tr should be a child node of table and li should be a child node of ul or ol.

Also width = '30px' should be without spaces: width='30px'.
BTW, do you really want so narrow container for your content?

And you have closing  tag which does not have open  before.

I suggest the following:

```<code>$("#newsview").append(
   '<div class="even gradeA"><b>'+
    heading+ ' - ' +news_date+
   '</b><br><i>' +summary+ '</i></div>'
 );
</code>```

And then use CSS to style it.

Body:
Why is this code not displaying all the data. It cuts off the display.

This is the DIV I am calling the ajax code.

I am using IntelXDK and building a Framework7 hybrid application

Somehow I can figure out why this is so when I test on the mobile phone. Could it be that Framework7 doesnot display data beyond certain size? Or my code is faulty somehow.

Body:
Unfortunately your js-generated HTML is not valid.

You're appending table rows tr to div. They also contain li.

tr should be a child node of table and li should be a child node of ul or ol.

Also width = '30px' should be without spaces: width='30px'.
BTW, do you really want so narrow container for your content?

And you have closing </i> tag which does not have open <i> before.

I suggest the following:

$("#newsview").append(
   '<div class="even gradeA"><b>'+
    heading+ ' - ' +news_date+
   '</b><br><i>' +summary+ '</i></div>'
 );

And then use CSS to style it.


问:
Java jSch Exec with progress bar and real time output to a JTextArea
I'm developing a program in java to download files directly to my server, for that I'm using jSch to connect via ssh and do a wget command, but i would like to stream the output to a JTextArea, and I've already done that, but it will only print it when the download is finished, and i would like to print it as the output of wget command in real time.

CustomOutputStream code:

```<code>public class CustomOutputStream extends OutputStream{
private JTextArea textArea;

    public CustomOutputStream(JTextArea textArea) {
        this.textArea = textArea;
    }

    @Override
    public void write(int b) throws IOException {
        // redirects data to the text area
        textArea.append(String.valueOf((char) b));
        // scrolls the text area to the end of data
        textArea.setCaretPosition(textArea.getText().length());
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        String s = new String(b,off,len);
        textArea.append(s);
        textArea.setCaretPosition(textArea.getText().length());
    }

    @Override
    public void write(byte[] b) throws IOException {
        this.write(b, 0, b.length);
    }
</code>```

}

here is the Exec code:

```<code>Properties props = new Properties();
    props.put("StrictHostKeyChecking", "no");
    int port = 22;

    JSch jsch=new JSch();

    Session session=jsch.getSession(username, host, 22);
    session.setConfig(props);
    session.setPassword(password);
    session.connect();
    String command =  "cd " + info.downPath + " && printf \"" + downLinks + "\" l> d.txt && wget -i d.txt";
    Channel channel=session.openChannel("exec");
    InputStream in=channel.getInputStream();
    OutputStream out = channel.getOutputStream();
    ((ChannelExec)channel).setCommand(command);
    //((ChannelExec)channel).setErrStream(System.err);
    //((ChannelExec)channel).setOutputStream(System.out);
    ((ChannelExec)channel).setErrStream(new CustomOutputStream(taOutput));
    //((ChannelExec)channel).setOutputStream(new CustomOutputStream(taOutput));
    channel.connect();
    byte[] tmp=new byte[1024];
    while(true){
      while(in.available()>0){
        int i=in.read(tmp, 0, 1024);
        if(i<0)break;
        System.out.print(new String(tmp, 0, i));
      }
      if(channel.isClosed()){
        if(in.available()>0) continue;
        System.out.println("exit-status: "+channel.getExitStatus());
        break;
      }
      try{Thread.sleep(1000);}catch(Exception ee){}
    }
    channel.disconnect();
    session.disconnect();
    bar.setValue(100);
</code>```

答:
After some help e more search, i just create a new thread the handler the connection.

Here is the example i took:
from this link :

```<code>one = new Thread() {
public void run() {
    try {
        System.out.println("Does it work?");

        Thread.sleep(1000);

        System.out.println("Nope, it doesnt...again.");
    } catch(InterruptedException v) {
        System.out.println(v);
    }
}
</code>```

};

one.start();

Body:
I'm developing a program in java to download files directly to my server, for that I'm using jSch to connect via ssh and do a wget command, but i would like to stream the output to a JTextArea, and I've already done that, but it will only print it when the download is finished, and i would like to print it as the output of wget command in real time.

CustomOutputStream code:

public class CustomOutputStream extends OutputStream{
private JTextArea textArea;

    public CustomOutputStream(JTextArea textArea) {
        this.textArea = textArea;
    }

    @Override
    public void write(int b) throws IOException {
        // redirects data to the text area
        textArea.append(String.valueOf((char) b));
        // scrolls the text area to the end of data
        textArea.setCaretPosition(textArea.getText().length());
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        String s = new String(b,off,len);
        textArea.append(s);
        textArea.setCaretPosition(textArea.getText().length());
    }

    @Override
    public void write(byte[] b) throws IOException {
        this.write(b, 0, b.length);
    }

}

here is the Exec code:

Properties props = new Properties();
    props.put("StrictHostKeyChecking", "no");
    int port = 22;

    JSch jsch=new JSch();

    Session session=jsch.getSession(username, host, 22);
    session.setConfig(props);
    session.setPassword(password);
    session.connect();
    String command =  "cd " + info.downPath + " && printf \"" + downLinks + "\" l> d.txt && wget -i d.txt";
    Channel channel=session.openChannel("exec");
    InputStream in=channel.getInputStream();
    OutputStream out = channel.getOutputStream();
    ((ChannelExec)channel).setCommand(command);
    //((ChannelExec)channel).setErrStream(System.err);
    //((ChannelExec)channel).setOutputStream(System.out);
    ((ChannelExec)channel).setErrStream(new CustomOutputStream(taOutput));
    //((ChannelExec)channel).setOutputStream(new CustomOutputStream(taOutput));
    channel.connect();
    byte[] tmp=new byte[1024];
    while(true){
      while(in.available()>0){
        int i=in.read(tmp, 0, 1024);
        if(i<0)break;
        System.out.print(new String(tmp, 0, i));
      }
      if(channel.isClosed()){
        if(in.available()>0) continue;
        System.out.println("exit-status: "+channel.getExitStatus());
        break;
      }
      try{Thread.sleep(1000);}catch(Exception ee){}
    }
    channel.disconnect();
    session.disconnect();
    bar.setValue(100);

Body:
After some help e more search, i just create a new thread the handler the connection.

Here is the example i took:
from this link :

one = new Thread() {
public void run() {
    try {
        System.out.println("Does it work?");

        Thread.sleep(1000);

        System.out.println("Nope, it doesnt...again.");
    } catch(InterruptedException v) {
        System.out.println(v);
    }
}

};

one.start();


问:
Laravel using user id in route
So I have a route profile/{user_id}

How do I redirect user to that URL when they click on link?

Here's my controller:

```<code>{
    function checkid($user_id) {
      if (Auth::check())
      {
        $user_id = Auth::id();
        return view('profile', [
        'id' => $user_id
        ]);
      }
    }
}
</code>```

答:
Bit confused with the question but Laravel uses ID as default for dependency injection and changing it is easy: just change the routeKey in the model BUT in your instance, you're using the signed in user. So forgot the id!

```<code><?php

    namespace App\Http\Controllers;

    class RandomController extends Controller {
        public function index()
        {
            return view('profile');//use auth facade in blade.
        }
    }
</code>```

In your routes use a middleware to prevent none authenticated users from reaching this method

```<code><?php

Route::group('/loggedin', [
    'middleware' => 'auth',
], function() {

    Route::get('/profile', 'RandomController@index')->name('profile.index');

});
</code>```

Now to redirect in your blade file use the route function, don't forget to clear your cache if you've cached your routes!

```<code><h1>Hi! {{Auth::user()->name}}</h1>
<a href="{{route('profile.index')}}">View profile</a>
</code>```

Because I used the name method on the Route I can pass that route name into the route function. Using php artisan route:list will list all your route parameters which is cool because it will also tell you the names and middlewares etc.

if I had a route which required a parameter; the route function accepts an array of params as the second parameter. route('profile.index', ['I_am_a_fake_param' => $user->id,]).

Let me know if you need help with anything else.

Title: Laravel using user id in route

Body:
So I have a route profile/{user_id}

How do I redirect user to that URL when they click on link?

Here's my controller:

{
    function checkid($user_id) {
      if (Auth::check())
      {
        $user_id = Auth::id();
        return view('profile', [
        'id' => $user_id
        ]);
      }
    }
}

Body:
Bit confused with the question but Laravel uses ID as default for dependency injection and changing it is easy: just change the routeKey in the model BUT in your instance, you're using the signed in user. So forgot the id!

<?php

    namespace App\Http\Controllers;

    class RandomController extends Controller {
        public function index()
        {
            return view('profile');//use auth facade in blade.
        }
    }

In your routes use a middleware to prevent none authenticated users from reaching this method

<?php

Route::group('/loggedin', [
    'middleware' => 'auth',
], function() {

    Route::get('/profile', 'RandomController@index')->name('profile.index');

});

Now to redirect in your blade file use the route function, don't forget to clear your cache if you've cached your routes!

<h1>Hi! {{Auth::user()->name}}</h1>
<a href="{{route('profile.index')}}">View profile</a>

Because I used the name method on the Route I can pass that route name into the route function. Using php artisan route:list will list all your route parameters which is cool because it will also tell you the names and middlewares etc.

if I had a route which required a parameter; the route function accepts an array of params as the second parameter. route('profile.index', ['I_am_a_fake_param' => $user->id,]).

Let me know if you need help with anything else.


问:
Get user's recent media with account username instead of user ID
So I want to use the Instagram API to get a specific user's (NOT MY USER) recent media. Instagram has the following endpoint for doing so:

```<code>(GET) https://api.instagram.com/v1/users/{user-id}/media/recent/?access_token=ACCESS-TOKEN
</code>```

This is a problem because I do not have the user's ID (why would I, Instagram?). What I do have is the account username (as most people would), e.g. @thisisauser.

I've been reading the API docs and I can't find an endpoint that will give me the user ID for a specific account username. I mean, yes, there is:

```<code>(GET) https://api.instagram.com/v1/users/search?q=jack&access_token=ACCESS-TOKEN
</code>```

...but it doesn't do what I need it to do, which is to search for an exact match.

I've also checked out other threads on Stack Overflow and other websites. However, the alternative solutions offered are, at best, questionable.

The fact that this whole thing is an actual issue surprises me. I mean, SURELY there's a legitimate, Instagram-approved, precise and straightforward way of either:

obtaining a user's recent media by providing the account username (which is what people know you by... not a sequence of numbers)
OR

obtaining a user's ID via an exact match search, with no chance of multiple possible results

FYI: I'm doing this server-side, using PHP and cURL.

Side note: If I have to make a separate request to the API in order to convert an account username to a user ID, that's just a waste of a request, one more for the hourly limit. Just an observation, in case any member of the Instagram team happens to see this.

答:
You can get all of a user's information (including the id) by requesting this URL:

```<code>https://www.instagram.com/{username}/?__a=1
</code>```

For example, this gets you all of the information related to the account taylorswift:

```<code>https://www.instagram.com/taylorswift/?__a=1
</code>```

Body:
So I want to use the Instagram API to get a specific user's (NOT MY USER) recent media. Instagram has the following endpoint for doing so:

(GET) https://api.instagram.com/v1/users/{user-id}/media/recent/?access_token=ACCESS-TOKEN

This is a problem because I do not have the user's ID (why would I, Instagram?). What I do have is the account username (as most people would), e.g. @thisisauser.

I've been reading the API docs and I can't find an endpoint that will give me the user ID for a specific account username. I mean, yes, there is:

(GET) https://api.instagram.com/v1/users/search?q=jack&access_token=ACCESS-TOKEN

...but it doesn't do what I need it to do, which is to search for an exact match.

I've also checked out other threads on Stack Overflow and other websites. However, the alternative solutions offered are, at best, questionable.

The fact that this whole thing is an actual issue surprises me. I mean, SURELY there's a legitimate, Instagram-approved, precise and straightforward way of either:

obtaining a user's recent media by providing the account username (which is what people know you by... not a sequence of numbers)
OR

obtaining a user's ID via an exact match search, with no chance of multiple possible results

FYI: I'm doing this server-side, using PHP and cURL.

Side note: If I have to make a separate request to the API in order to convert an account username to a user ID, that's just a waste of a request, one more for the hourly limit. Just an observation, in case any member of the Instagram team happens to see this.

Body:
You can get all of a user's information (including the id) by requesting this URL:

https://www.instagram.com/{username}/?__a=1

For example, this gets you all of the information related to the account taylorswift:

https://www.instagram.com/taylorswift/?__a=1