问:
How can I generate this error
Please assist me in generating an error for using a "$". I am able to successfully generate the error if I enter in negative numbers but I am not able to generate an error for having a "$" sign in my withdraw/deposit input. Hope this is not a stupid question.

Everytime I think I find an answer I enter the code and a new issue pops up.

Please forgive my formatting. It's horrid and I can't correct it. Learning process.

```<code>private void btnDepositActionPerformed(java.awt.event.ActionEvent evt) {
    int index = jComboBox1.getSelectedIndex();
    DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
    Date date = null;
    try {
        date = df.parse(txtOpenDate.getText());
    }
        catch (ParseException ex)
    {
Logger.getLogger(AccountApp.class.getName()).log(Level.SEVERE, null, ex);
    }
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(date);
    accounts = new;
  CheckingAccount(jComboBox1.getSelectedItem().toString(),txtCustomerName.getText(),cal,au.getBalance(index));
String input = (String)JOptionPane.showInputDialog(this,"Deposit amount for account "+jComboBox1.getSelectedItem().toString(),"Deposit to "+jComboBox1.getSelectedItem().toString(),JOptionPane.PLAIN_MESSAGE,null,null,"");
try{
        double amount = Double.parseDouble(input);
        if (amount>=0){
            double balance = accounts.deposit(amount);
            NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();
            txtBalance.setText(defaultFormat.format(balance));
            au.setBalance(index, balance);

        try { au.updateFile(au.getAccountNumber(index),
             au.getOpenDate(index),au.getCustomerName(index),
             au.getBalance(index));
            }
       catch (IOException ex) {
            }
        }
        else {
            NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();
            JOptionPane.showMessageDialog(
                    this, "Invalid deposit amount
                   "+defaultFormat.format(amount),
                    "Invalid deposit", JOptionPane.ERROR_MESSAGE);

        }
    }
    catch(Exception e){
    }
</code>```

答:
Doing a simple use of the methods in the string class will help:</p>

```<code> String x = "$123.33";
 System.out.println(x.contains("$"));
 System.out.println(x.indexOf("$"));
</code>```

Title: How can I generate this error

Body:
Please assist me in generating an error for using a "$". I am able to successfully generate the error if I enter in negative numbers but I am not able to generate an error for having a "$" sign in my withdraw/deposit input. Hope this is not a stupid question.

Everytime I think I find an answer I enter the code and a new issue pops up.

Please forgive my formatting. It's horrid and I can't correct it. Learning process.

private void btnDepositActionPerformed(java.awt.event.ActionEvent evt) {
    int index = jComboBox1.getSelectedIndex();
    DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
    Date date = null;
    try {
        date = df.parse(txtOpenDate.getText());
    }
        catch (ParseException ex)
    {
Logger.getLogger(AccountApp.class.getName()).log(Level.SEVERE, null, ex);
    }
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(date);
    accounts = new;
  CheckingAccount(jComboBox1.getSelectedItem().toString(),txtCustomerName.getText(),cal,au.getBalance(index));
String input = (String)JOptionPane.showInputDialog(this,"Deposit amount for account "+jComboBox1.getSelectedItem().toString(),"Deposit to "+jComboBox1.getSelectedItem().toString(),JOptionPane.PLAIN_MESSAGE,null,null,"");
try{
        double amount = Double.parseDouble(input);
        if (amount>=0){
            double balance = accounts.deposit(amount);
            NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();
            txtBalance.setText(defaultFormat.format(balance));
            au.setBalance(index, balance);

        try { au.updateFile(au.getAccountNumber(index),
             au.getOpenDate(index),au.getCustomerName(index),
             au.getBalance(index));
            }
       catch (IOException ex) {
            }
        }
        else {
            NumberFormat defaultFormat = NumberFormat.getCurrencyInstance();
            JOptionPane.showMessageDialog(
                    this, "Invalid deposit amount
                   "+defaultFormat.format(amount),
                    "Invalid deposit", JOptionPane.ERROR_MESSAGE);

        }
    }
    catch(Exception e){
    }

Body:
Doing a simple use of the methods in the string class will help:

 String x = "$123.33";
 System.out.println(x.contains("$"));
 System.out.println(x.indexOf("$"));


来源: stackexchange

问:
Check if dates are consecutive
I have a pandas dataframe with check-up dates as the index and a category and type of species.

```<code>Date    Category    Type
2016-11-21  Cat Animal
2016-11-21  Cat Animal
2017-01-03  Cat Animal
2016-11-01  Dog Animal
2017-01-03  Dog Animal
2016-10-03  Dog Animal
2017-02-01  Dog Animal
2017-03-01  Dog Animal
2016-12-01  Dog Animal
2016-11-21  Horse   Animal
2016-12-15  Horse   Animal
2017-02-04  Horse   Animal
</code>```

I need to determine for each category whether the dates were consecutive . Consecutive could mean a month is missing, this is seen in the horse category. The month of January is missing for horse, but overall the horse's check-up updates are increasing. So horse is valid.
Cat, however, is invalid since it received a check up twice in one day.

The final dataframe should be

```<code>Date    Category    Type
2016-11-01  Dog Animal
2017-01-03  Dog Animal
2016-10-03  Dog Animal
2017-02-01  Dog Animal
2017-03-01  Dog Animal
2016-12-01  Dog Animal
2016-11-21  Horse   Animal
2016-12-15  Horse   Animal
2017-02-04  Horse   Animal
</code>```

答:
Here is how you can exclude animals for which the index is not unique:

```<code>df.groupby('Category').filter(lambda x: x.index.is_unique)
</code>```

which gives the desired output:

```<code>           Category    Type
Date
2016-11-01      Dog  Animal
2017-01-03      Dog  Animal
2016-10-03      Dog  Animal
2017-02-01      Dog  Animal
2017-03-01      Dog  Animal
2016-12-01      Dog  Animal
2016-11-21    Horse  Animal
2016-12-15    Horse  Animal
2017-02-04    Horse  Animal
</code>```

Your question would suggest you want the dates to be strictly increasing, then you can do:

```<code>def index_diff(x):
    return ((d_1 - d_0).days for d_1, d_0 in zip(x.index[1:], x.index[:-1]))

df.groupby('Category').filter(lambda x: min(index_diff(x))> 0)
</code>```

Although this only returns

```<code>           Category    Type
Date
2016-11-21    Horse  Animal
2016-12-15    Horse  Animal
2017-02-04    Horse  Animal
</code>```

since for Dog you have 2017-01-03 appearing before 2016-10-03

ContentLicense: CC BY-SA 3.0

Title: Check if dates are consecutive

Body:
I have a pandas dataframe with check-up dates as the index and a category and type of species.

Date    Category    Type
2016-11-21  Cat Animal
2016-11-21  Cat Animal
2017-01-03  Cat Animal
2016-11-01  Dog Animal
2017-01-03  Dog Animal
2016-10-03  Dog Animal
2017-02-01  Dog Animal
2017-03-01  Dog Animal
2016-12-01  Dog Animal
2016-11-21  Horse   Animal
2016-12-15  Horse   Animal
2017-02-04  Horse   Animal

I need to determine for each category whether the dates were consecutive . Consecutive could mean a month is missing, this is seen in the horse category. The month of January is missing for horse, but overall the horse's check-up updates are increasing. So horse is valid.
Cat, however, is invalid since it received a check up twice in one day.

The final dataframe should be

Date    Category    Type
2016-11-01  Dog Animal
2017-01-03  Dog Animal
2016-10-03  Dog Animal
2017-02-01  Dog Animal
2017-03-01  Dog Animal
2016-12-01  Dog Animal
2016-11-21  Horse   Animal
2016-12-15  Horse   Animal
2017-02-04  Horse   Animal

Body:
Here is how you can exclude animals for which the index is not unique:

df.groupby('Category').filter(lambda x: x.index.is_unique)

which gives the desired output:

           Category    Type
Date
2016-11-01      Dog  Animal
2017-01-03      Dog  Animal
2016-10-03      Dog  Animal
2017-02-01      Dog  Animal
2017-03-01      Dog  Animal
2016-12-01      Dog  Animal
2016-11-21    Horse  Animal
2016-12-15    Horse  Animal
2017-02-04    Horse  Animal

Your question would suggest you want the dates to be strictly increasing, then you can do:

def index_diff(x):
    return ((d_1 - d_0).days for d_1, d_0 in zip(x.index[1:], x.index[:-1]))

df.groupby('Category').filter(lambda x: min(index_diff(x))> 0)

Although this only returns

           Category    Type
Date
2016-11-21    Horse  Animal
2016-12-15    Horse  Animal
2017-02-04    Horse  Animal

since for Dog you have 2017-01-03 appearing before 2016-10-03


问:
transposing a matrix using pointer C
I am trying to write a code that transposes a matrix using pointer and memory allocation.

When I run it, it freezes from the part that produces a matrix with rand function in the program given below.

So I couldn't check whether two functions( transpose, printMatrix) work.

What am I doing wrong??

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

int** transpose (int **matrix, int m, int n);
void printMatrix(int **matrix, int m, int n);

int main (void){
    int rows, cols;
    int r, c;
    int **matrix;

    printf("Number of Rows : ");
    scanf("%d", &rows);
    printf("Number of Cols : ");
    scanf("%d", &cols);

    matrix = (int **)malloc(rows*sizeof(int*));
    matrix[0] = malloc(rows*cols*sizeof(int));

    srand(2016);

 //error starts from here
    for( r = 0; r < rows; r++ ){
        for( c = 0; c < cols; c++ ){
            *(*(matrix + r)+c) = rand() % 99 + 1;
        }
    }

    printf("Matrix produced with seed number 2016\n");
    printMatrix(**matrix, rows, cols);

    matrix = transpose(**matrix, rows, cols);

    printf("Transposed Matrix\n");
    printMatrix(**matrix, rows, cols);
}

int** transpose (int **matrix, int rows, int cols){
    int tmp, i ,j;

    if( rows < cols ){
        matrix[0] = (int *)realloc(matrix[0], rows*rows*sizeof(int));
    }
    else if(cols < rows){
        matrix = (int **)realloc(matrix, cols*sizeof(int*));
    }

    for (i = 0; i < rows; i++) {
        for (j = 0 ; j < cols; j++) {
            tmp = *(*(matrix + i) + j);
            *(*(matrix + i) + j) = *(*(matrix + j) + i);
            *(*(matrix + j) + i) = tmp;
        }
    }
    return matrix;
}
void printMatrix(int **matrix, int m, int n){
    int i, j;

    for( i = 0; i < m; i++ ){
        for( j = 0; j < n; j++ ){
            printf("%3d", *(*(matrix + i )+j) );
        }
        printf("\n");
    }

}
</code>```

答:
You are allocating a contiguous array of rows * cols * sizeof(int) starting from matrix[0]:

```<code>matrix[0] = malloc(rows*cols*sizeof(int));
</code>```

I think that the allocation should be:

```<code>matrix = (int **)malloc(rows*sizeof(int*));
for(int i = 0; i < rows; i++)
   matrix[i] = (int*)malloc(cols*sizeof(int));
</code>```

Title: transposing a matrix using pointer C

Body:
I am trying to write a code that transposes a matrix using pointer and memory allocation.

When I run it, it freezes from the part that produces a matrix with rand function in the program given below.

So I couldn't check whether two functions( transpose, printMatrix) work.

What am I doing wrong??

# include <stdio.h>
# include <stdlib.h>

int** transpose (int **matrix, int m, int n);
void printMatrix(int **matrix, int m, int n);

int main (void){
    int rows, cols;
    int r, c;
    int **matrix;

    printf("Number of Rows : ");
    scanf("%d", &rows);
    printf("Number of Cols : ");
    scanf("%d", &cols);

    matrix = (int **)malloc(rows*sizeof(int*));
    matrix[0] = malloc(rows*cols*sizeof(int));

    srand(2016);

 //error starts from here
    for( r = 0; r < rows; r++ ){
        for( c = 0; c < cols; c++ ){
            *(*(matrix + r)+c) = rand() % 99 + 1;
        }
    }

    printf("Matrix produced with seed number 2016\n");
    printMatrix(**matrix, rows, cols);

    matrix = transpose(**matrix, rows, cols);

    printf("Transposed Matrix\n");
    printMatrix(**matrix, rows, cols);
}

int** transpose (int **matrix, int rows, int cols){
    int tmp, i ,j;

    if( rows < cols ){
        matrix[0] = (int *)realloc(matrix[0], rows*rows*sizeof(int));
    }
    else if(cols < rows){
        matrix = (int **)realloc(matrix, cols*sizeof(int*));
    }

    for (i = 0; i < rows; i++) {
        for (j = 0 ; j < cols; j++) {
            tmp = *(*(matrix + i) + j);
            *(*(matrix + i) + j) = *(*(matrix + j) + i);
            *(*(matrix + j) + i) = tmp;
        }
    }
    return matrix;
}
void printMatrix(int **matrix, int m, int n){
    int i, j;

    for( i = 0; i < m; i++ ){
        for( j = 0; j < n; j++ ){
            printf("%3d", *(*(matrix + i )+j) );
        }
        printf("\n");
    }

}

Body:
You are allocating a contiguous array of rows * cols * sizeof(int) starting from matrix[0]:

matrix[0] = malloc(rows*cols*sizeof(int));

I think that the allocation should be:

matrix = (int **)malloc(rows*sizeof(int*));
for(int i = 0; i < rows; i++)
   matrix[i] = (int*)malloc(cols*sizeof(int));


问:
Append HTML data jQuery
This time I wrote html in controller when I check a checkbox I get data in console but I want to get it in the form.

I have checkbox in foreach loop

```<code><input type='checkbox' value='{$student['id']}' name='student_ids[]' id='chkbx' required> {$student['name']}
</code>```

when click on checkboxes data load accordingly

its my html

```<code>    $str .= '<div class="form-group">
    <label class="control-label col-md-3">
    Student
    </label>
    <div class="col-md-4">
        <select id="students-clicked" class="form-control select2-multiple" multiple name="students[]">
            <option value=""></option>';
            foreach ($students as $students) {
                $str .= "<option value='{$student->id}'>{$student->name}</option>";
            }

$str .=         '</select>
    </div>
</div>';
</code>```

Jquery Method is as

```<code>    $('body').on('click', "#chkbx", function() {
    var class = $('input:checkbox:checked').map(function() {
        return this.value;
    }).get();
    $.ajax({
            url: '/trigger/studentsData',
            type: 'POST',
            data: {'trigger_type': 'click' , ids: class},
            success: function(result) {

            }
        });
});
</code>```

Except jQuery everything is written in controller this time I am getting HTML data in console how can I append it in my html form it should also update according to checkbox selection

答:
Don't append() rather use html() to override the content with the response data

```<code>success: function (result) {
    $("#container").html(result);
}
</code>```

Plus, if you have more than one checkboxes, don't use id, rather use class attribute to loop through them

Title: Append HTML data jQuery

Body:
This time I wrote html in controller when I check a checkbox I get data in console but I want to get it in the form.

I have checkbox in foreach loop

<input type='checkbox' value='{$student['id']}' name='student_ids[]' id='chkbx' required> {$student['name']}

when click on checkboxes data load accordingly

its my html

    $str .= '

    Student

        <select id="students-clicked" class="form-control select2-multiple" multiple name="students[]">
            <option value=""></option>';
            foreach ($students as $students) {
                $str .= "<option value='{$student->id}'>{$student->name}</option>";
            }

$str .=         '</select>

';

Jquery Method is as

    $('body').on('click', "#chkbx", function() {
    var class = $('input:checkbox:checked').map(function() {
        return this.value;
    }).get();
    $.ajax({
            url: '/trigger/studentsData',
            type: 'POST',
            data: {'trigger_type': 'click' , ids: class},
            success: function(result) {

            }
        });
});

Except jQuery everything is written in controller this time I am getting HTML data in console how can I append it in my html form it should also update according to checkbox selection

Body:
Don't append() rather use html() to override the content with the response data

success: function (result) {
    $("#container").html(result);
}

Plus, if you have more than one checkboxes, don't use id, rather use class attribute to loop through them


问:
3 boxes inline, content alignment
I have 3 boxes with dynamic content, in each box there is a form with submit button, and some other things. How to get the effect from the picture.

Height of the each box is max from all boxes. Submit buttons in one line, on the bottom.

body {
  width: 720px;
}
form input {
  display: block;
  margin-bottom: 15px;
  width: 100%;
}
form label {
  text-align: left;
  width: 100%;
  display: block;
}
.box-container {
  display: flex;
}
.box {
  border: 1px solid #000;
  flex: 1 1 auto;
  max-width: calc(33% - 2px);
  text-align: center;
  box-sizing: border-box;
  padding: 10px;
}
.box p {
  text-align: justify;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box-container">
  <div class="box">
    <h1>bla bla bla</h1>
    <p> some information dasd asd asd asdasdasfs dsgd dfg sdfg fsdg sdfg s</p>
    <form>
      <label>value 1</label>
      <input type="text"/>
      <label>value 2</label>
      <input type="text"/>
      <input type="submit" value="submit"/>
    </form>
  </div>
  <div class="box">
    <h1>bla bla bladada das dasd asd</h1>
    <p>Longer information<br> some information dasd asd asd asd an</p>
    <form>
      <label>value 1</label>
      <input type="text"/>
      <label>value 2</label>
      <input type="text"/>
      <label>value 3</label>
      <input type="text"/>
      <input type="submit" value="submit"/>
    </form>
  </div>
  <div class="box">
    <h1>bla bla b</h1>
    <p>Longer information</p>
    <form>
      <label>value 1</label>
      <input type="text"/>
      <input type="submit" value="submit"/>
    </form>
  </div>
<div></code>```

答:
I hope this is what you needed. I have added flex property to the form to take all the space available

body {
  width: 720px;
}

form {
  flex: 1 0 auto;
  position: relative;
  padding-bottom: 30px;
}

form input {
  display: block;
  margin-bottom: 15px;
  width: 100%;
}

form label {
  text-align: left;
  width: 100%;
  display: block;
}

form button {
  display: block;
  width: 100%;
  position: absolute;
  bottom: 10px;
}

.box-container {
  display: flex;
}

.box {
  border: 1px solid #000;
  flex: 1 1 auto;
  max-width: calc(33% - 2px);
  text-align: center;
  box-sizing: border-box;
  padding: 10px;
  display: flex;
  flex-direction: column;
}

.box p {
  text-align: justify;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box-container">
  <div class="box">
    <div>
      <h1>bla bla bla</h1>
      <p> some information dasd asd asd asdasdasfs dsgd dfg sdfg fsdg sdfg s</p>
    </div>
    <form>
      <label>value 1</label>
      <input type="text" />
      <label>value 2</label>
      <input type="text" />
      <button type="submit">Submit</button>
    </form>
  </div>
  <div class="box">
    <h1>bla bla bladada das dasd asd</h1>
    <p>Longer information<br> some information dasd asd asd asd an</p>
    <form>
      <label>value 1</label>
      <input type="text" />
      <label>value 2</label>
      <input type="text" />
      <label>value 3</label>
      <input type="text" />
      <button type="submit">Submit</button>
    </form>
  </div>
  <div class="box">
    <h1>bla bla b</h1>
    <p>Longer information</p>
    <form>
      <label>value 1</label>
      <input type="text" />
      <button type="submit">Submit</button>
    </form>
  </div>
  <div></code>```

Title: 3 boxes inline, content alignment

Body:
I have 3 boxes with dynamic content, in each box there is a form with submit button, and some other things. How to get the effect from the picture.

Height of the each box is max from all boxes. Submit buttons in one line, on the bottom.

body {
  width: 720px;
}
form input {
  display: block;
  margin-bottom: 15px;
  width: 100%;
}
form label {
  text-align: left;
  width: 100%;
  display: block;
}
.box-container {
  display: flex;
}
.box {
  border: 1px solid #000;
  flex: 1 1 auto;
  max-width: calc(33% - 2px);
  text-align: center;
  box-sizing: border-box;
  padding: 10px;
}
.box p {
  text-align: justify;
}

bla bla bla

 some information dasd asd asd asdasdasfs dsgd dfg sdfg fsdg sdfg s

    <form>
      value 1
      <input type="text"/>
      value 2
      <input type="text"/>
      <input type="submit" value="submit"/>
    </form>

bla bla bladada das dasd asd

Longer information
 some information dasd asd asd asd an

    <form>
      value 1
      <input type="text"/>
      value 2
      <input type="text"/>
      value 3
      <input type="text"/>
      <input type="submit" value="submit"/>
    </form>

bla bla b

Longer information

    <form>
      value 1
      <input type="text"/>
      <input type="submit" value="submit"/>
    </form>

Body:
I hope this is what you needed. I have added flex property to the form to take all the space available

body {
  width: 720px;
}

form {
  flex: 1 0 auto;
  position: relative;
  padding-bottom: 30px;
}

form input {
  display: block;
  margin-bottom: 15px;
  width: 100%;
}

form label {
  text-align: left;
  width: 100%;
  display: block;
}

form button {
  display: block;
  width: 100%;
  position: absolute;
  bottom: 10px;
}

.box-container {
  display: flex;
}

.box {
  border: 1px solid #000;
  flex: 1 1 auto;
  max-width: calc(33% - 2px);
  text-align: center;
  box-sizing: border-box;
  padding: 10px;
  display: flex;
  flex-direction: column;
}

.box p {
  text-align: justify;
}

<div class="box-container">
  <div class="box">
    <div>
      <h1>bla bla bla</h1>
      <p> some information dasd asd asd asdasdasfs dsgd dfg sdfg fsdg sdfg s</p>
    </div>
    <form>
      <label>value 1</label>
      <input type="text" />
      <label>value 2</label>
      <input type="text" />
      <button type="submit">Submit</button>
    </form>
  </div>
  <div class="box">
    <h1>bla bla bladada das dasd asd</h1>
    <p>Longer information<br> some information dasd asd asd asd an</p>
    <form>
      <label>value 1</label>
      <input type="text" />
      <label>value 2</label>
      <input type="text" />
      <label>value 3</label>
      <input type="text" />
      <button type="submit">Submit</button>
    </form>
  </div>
  <div class="box">
    <h1>bla bla b</h1>
    <p>Longer information</p>
    <form>
      <label>value 1</label>
      <input type="text" />
      <button type="submit">Submit</button>
    </form>
  </div>
  <div>


问:
Why does spark-shell fail with “error: not found: value spark”?
I use Spark 2.1.0.

When I run spark-shell, I encounter this error:

```<code><console>:14: error: not found: value spark
       import spark.implicits._
              ^
<console>:14: error: not found: value spark
       import spark.sql
              ^
</code>```

What could be the reason? How to fix it?

答:
The reason for the error is that the instance could not be created due to some earlier issues (which may have happened because you are on Windows and you have not installed winutils.exe binary or some other session keeps the local Derby-based metastore).

The recommendation is to scroll up and review the entire screen of logs where you find the root cause.

Body:
I use Spark 2.1.0.

When I run spark-shell, I encounter this error:

<console>:14: error: not found: value spark
       import spark.implicits._
              ^
<console>:14: error: not found: value spark
       import spark.sql
              ^

What could be the reason? How to fix it?


问:
Cannot access methods of pibase extension after upgrade to 6.2
We have an old custom-built plugin to manage a list of events, which does not work correctly after upgrading from TYPO3 4.5 to 6.2.

I believe I have done all the necessary migration steps, and the plugin seems to work in general. When I call just the page - without the GET-Parameters for the plugin, the main()-Action of the plugin is used correctly, i.e.

https://<our-domain>/login/myaccount/events/events.html

But any call to a method via the URL fails and I always end up with a 404. This URL worked in TYPO3 4.3+

https://<our-domain>/login/myaccount/events/events.html?tx_<our-extension>_pi2[action]=newEvent

I have searched and tried a lot of different things. I was wondering if the routing has changed so that the method is not called correctly.

How can I go about debugging this extension/plugin? How can I see what the GET-Parameter actually does to the plugin?

答:
After receiving no answer here, I cross-posted the question to the German TYPO3-Forum. And got the right hint by Jan:

cHash controls how the output of a plugin is cached or not. If not found, it was automatically redirecting to 404.


问:
How can I return a string literal from a Postgres function?
I got this working to return an integer:

```<code>CREATE FUNCTION my_function() RETURNS INTEGER AS $$
  SELECT 1 AS result;
$$ LANGUAGE SQL;
</code>```

But I want it to return a string, so I tweaked it to:

```<code>CREATE FUNCTION my_function() RETURNS TEXT AS $$
  SELECT '1' AS result;
$$ LANGUAGE SQL;
</code>```

But this fails with:

```<code>ERROR:  return type mismatch in function declared to return text
DETAIL:  Actual return type is unknown.
</code>```

What happened?  How can I return the string '1'?

答:
String literals are of type unknown. You can explicitly specify the type like this:

```<code>SELECT TEXT '1' AS result;
</code>```

Body:
I got this working to return an integer:

CREATE FUNCTION my_function() RETURNS INTEGER AS $$
  SELECT 1 AS result;
$$ LANGUAGE SQL;

But I want it to return a string, so I tweaked it to:

CREATE FUNCTION my_function() RETURNS TEXT AS $$
  SELECT '1' AS result;
$$ LANGUAGE SQL;

But this fails with:

ERROR:  return type mismatch in function declared to return text
DETAIL:  Actual return type is unknown.

What happened?  How can I return the string '1'?

Body:
String literals are of type unknown. You can explicitly specify the type like this:

SELECT TEXT '1' AS result;


问:
Sort Set when only specific objects are comparable
I have a Set of unique data. Let's say it looks like this:

```<code>0: domainA.org -> domainB.org
1: domainY.org -> domainZ.org
2: domainB.org -> domainC.org
3: domainD.org -> domainE.org
4: domainX.org -> domainY.org
5: domainC.org -> domainD.org
</code>```

In order to copy data related to domainA.org to B C D and E and doimanY.org to X and Z, I need to iterate over this set in the following order:

```<code>0: domainA.org -> domainB.org
2: domainB.org -> domainC.org
5: domainC.org -> domainD.org
3: domainD.org -> domainE.org

4: domainX.org -> domainY.org
1: domainY.org -> domainZ.org
</code>```

It doesn't matter if X -> Y -> Z is processed before A -> B -> C -> D -> E they aren't related to each other.

Sorting each "category" e.g. every independend part of data on its own is fairly easy.
I made my wrapper object for sourceDomain -> destinationDomain implement Comparable and used a SortedSet to do the sorting for me.
Now here's the problem.

This is what my comparteTo implementation looks like:

```<code>if (source.equals(other.destination)) {
    return 1;
} else if (destination.equals(other.source)) {
    return -1;
}
return 0;
</code>```

It is only able to compare 2 objects if they are next to each other in the final list otherwhise it "treats" the other objects as the same.

(Not to mention that TreeSet isn't adding items to itself if compareTo returns 0 at some point)
Because of that it's not sorting the data I showed in example 1 correctly.

My Idea would be to iterate over the source set and add compare the entries against every other entry and create seperate sets which i can join together once I finished sorting.

The complexity of this would at least be n^2 which is pretty bad.

My question: Can we do better than that?

答:
The thing you are looking for is a topological sort in a graph. There are various algorithms that can solve this, available in pseudo code on the Wikipedia article.

The easiest to implement is a depth-first-search, somewhat copied below:

```<code>L ← Empty list that will contain the sorted nodes
foreach node n do
    if not marked n then visit(n)

function visit(node n)
    if n has a temporary mark then stop (cyclic dependency found!)
    if n is not marked (i.e. has not been visited yet) then
        mark n temporarily
    for each node m with an edge from n to m do
        visit(m)
        mark n permanently
        unmark n temporarily
        add n to head of L
</code>```

This has at most time complexity O(nodes + edges), and in your case it would seem that nodes = edges, so that would be fast enough.

Body:
I have a Set of unique data. Let's say it looks like this:

0: domainA.org -> domainB.org
1: domainY.org -> domainZ.org
2: domainB.org -> domainC.org
3: domainD.org -> domainE.org
4: domainX.org -> domainY.org
5: domainC.org -> domainD.org

In order to copy data related to domainA.org to B C D and E and doimanY.org to X and Z, I need to iterate over this set in the following order:

0: domainA.org -> domainB.org
2: domainB.org -> domainC.org
5: domainC.org -> domainD.org
3: domainD.org -> domainE.org

4: domainX.org -> domainY.org
1: domainY.org -> domainZ.org

It doesn't matter if X -> Y -> Z is processed before A -> B -> C -> D -> E they aren't related to each other.

Sorting each "category" e.g. every independend part of data on its own is fairly easy.
I made my wrapper object for sourceDomain -> destinationDomain implement Comparable and used a SortedSet to do the sorting for me.
Now here's the problem.

This is what my comparteTo implementation looks like:

if (source.equals(other.destination)) {
    return 1;
} else if (destination.equals(other.source)) {
    return -1;
}
return 0;

It is only able to compare 2 objects if they are next to each other in the final list otherwhise it "treats" the other objects as the same.

(Not to mention that TreeSet isn't adding items to itself if compareTo returns 0 at some point)
Because of that it's not sorting the data I showed in example 1 correctly.

My Idea would be to iterate over the source set and add compare the entries against every other entry and create seperate sets which i can join together once I finished sorting.

The complexity of this would at least be n^2 which is pretty bad.

My question: Can we do better than that?

Body:
The thing you are looking for is a topological sort in a graph. There are various algorithms that can solve this, available in pseudo code on the Wikipedia article.

The easiest to implement is a depth-first-search, somewhat copied below:

L ← Empty list that will contain the sorted nodes
foreach node n do
    if not marked n then visit(n)

function visit(node n)
    if n has a temporary mark then stop (cyclic dependency found!)
    if n is not marked (i.e. has not been visited yet) then
        mark n temporarily
    for each node m with an edge from n to m do
        visit(m)
        mark n permanently
        unmark n temporarily
        add n to head of L

This has at most time complexity O(nodes + edges), and in your case it would seem that nodes = edges, so that would be fast enough.


答:
Your problem lies in the below code:

```<code>matrix = (int **)malloc(rows*sizeof(int*));
matrix[0] = malloc(rows*cols*sizeof(int));
</code>```

In the first statement you are trying to allocate a array of pointers. But, in the second statement you are allocating memory to only one pointer. So, when you try to do *(*(matrix + r)+c) , it accesses invalid memory.

You should be doing like below:

```<code>matrix = (int **)malloc(rows*sizeof(int*));
for (int i=0; i<rows; i++) {
    matrix[i] = malloc(cols*sizeof(int));
}
</code>```

Title: transposing a matrix using pointer C

Body:
Your problem lies in the below code:

matrix = (int **)malloc(rows*sizeof(int*));
matrix[0] = malloc(rows*cols*sizeof(int));

In the first statement you are trying to allocate a array of pointers. But, in the second statement you are allocating memory to only one pointer. So, when you try to do *(*(matrix + r)+c) , it accesses invalid memory.

You should be doing like below:

matrix = (int **)malloc(rows*sizeof(int*));
for (int i=0; i<rows; i++) {
    matrix[i] = malloc(cols*sizeof(int));
}


问:
How to get value attirbute value from php 2d session variable
I am having an php session array like

```<code>["cart"]["123"] = "Biscuit"
["cart"]["124"] = "Jam"
</code>```

If I want to access the 2nd element I will access array_values($_SESSION["cart"])[$i]
where $i runs in for loop. If I want to get the values "123" and "124", how can i achieve it in a for loop with only "cart" and $i..?

答:
```<code>foreach($_SESSION['cart'] as $key => $value)

{
  echo $key; // your 123 or 124 key
}
</code>```

Body:
I am having an php session array like

["cart"]["123"] = "Biscuit"
["cart"]["124"] = "Jam"

If I want to access the 2nd element I will access array_values($_SESSION["cart"])[$i]
where $i runs in for loop. If I want to get the values "123" and "124", how can i achieve it in a for loop with only "cart" and $i..?


问:
Mathematical Concept In Multi-Dimensional Array Sorting
I have found this code written online(not by me), and was hoping to get an answer on what the mathematical formula or concept is that makes this function work. I am curious as to how this person designed this. First, I will explain the requirements that the function must produce, then I will supply the code, and a link to a working code pen for further hacking. P.S. The problem uses the word "vector", but since this is Javascript, vector just means array.

Function Requirements

Given a vector of vectors of words, ex.
[['quick', 'lazy'], ['brown', 'black', 'grey'], ['fox', 'dog']].

Write a function that prints all combinations of one word from the first vector, one word from the second vector, etc.
The solution may not use recursion. The number of vectors and number of elements within each vector may vary.

Example output: 'quick, brown, dog', 'lazy black fox' etc.

My Current Level Of Understanding
I am already aware that by using the principle of multiplication, to find the number of possible combinations available in this scenario is to just multiply the lengths of each inner vector by each other. For this specific example, we get a total of 12(2x3x2) different possible combinations. Where I fall off however, is inside the 4 nested for loops section of the program.

Whoever wrote the code, clearly understands some concept or formula that I do not. Just two examples, are the "previous" variable used inside the loops, and the strategic placement of where they decide to increment the j variable. It seems to me that they might be aware of some mathematical formula.

Code
Below is the code without comments. If you however go to this codepen, I have included the same code with plenty of comments that explain how the program works, so you don't have to trace everything out from scratch. You can also test the output in the built-in console.

```<code>function comboMaker(vector) {

  var length = vector.length;

  var solutions = 1;
  for (var i = 0; i < length; i++) {
    solutions *= vector[i].length;
  }

  var combinations = [];
  for (var i = 0; i < solutions; i++) {
    combinations[i] = [];
  }

  var previous = 1;

  for (var i = 0; i < length; i++) {

    for (var j = 0; j < solutions;) {

      var wordCount = vector[i].length;
      previous *= vector[i].length;

      for (var l = 0; l < wordCount; l++) {

        for (var k = 0; k < (solutions/previous); k++) {
          combinations[j][i] = vector[i][l];
          j++
        }
      }
    }
  }

  for (var i = 0; i < solutions; i++) {
    console.log(combinations[i].join(" "));
  }
}

comboMaker([['quick', 'lazy'], ['brown', 'black', 'grey'], ['fox', 'dog']]);
</code>```

答:
A cooperation of .reduce() and .map() allows us to come up with a very efficient single liner answer for this question.

var data   = [['quick', 'lazy'], ['brown', 'black', 'grey'], ['fox', 'dog'],['jumps','runs']],
    result = data.reduce((p,c) => p.reduce((r,fw) => r.concat(c.map(sw => fw + " " + sw)),[]));
console.log(result);```

Body:
I have found this code written online(not by me), and was hoping to get an answer on what the mathematical formula or concept is that makes this function work. I am curious as to how this person designed this. First, I will explain the requirements that the function must produce, then I will supply the code, and a link to a working code pen for further hacking. P.S. The problem uses the word "vector", but since this is Javascript, vector just means array.

Function Requirements

Given a vector of vectors of words, ex.
[['quick', 'lazy'], ['brown', 'black', 'grey'], ['fox', 'dog']].

Write a function that prints all combinations of one word from the first vector, one word from the second vector, etc.
The solution may not use recursion. The number of vectors and number of elements within each vector may vary.

Example output: 'quick, brown, dog', 'lazy black fox' etc.

My Current Level Of Understanding
I am already aware that by using the principle of multiplication, to find the number of possible combinations available in this scenario is to just multiply the lengths of each inner vector by each other. For this specific example, we get a total of 12(2x3x2) different possible combinations. Where I fall off however, is inside the 4 nested for loops section of the program.

Whoever wrote the code, clearly understands some concept or formula that I do not. Just two examples, are the "previous" variable used inside the loops, and the strategic placement of where they decide to increment the j variable. It seems to me that they might be aware of some mathematical formula.

Code
Below is the code without comments. If you however go to this codepen, I have included the same code with plenty of comments that explain how the program works, so you don't have to trace everything out from scratch. You can also test the output in the built-in console.

function comboMaker(vector) {

  var length = vector.length;

  var solutions = 1;
  for (var i = 0; i < length; i++) {
    solutions *= vector[i].length;
  }

  var combinations = [];
  for (var i = 0; i < solutions; i++) {
    combinations[i] = [];
  }

  var previous = 1;

  for (var i = 0; i < length; i++) {

    for (var j = 0; j < solutions;) {

      var wordCount = vector[i].length;
      previous *= vector[i].length;

      for (var l = 0; l < wordCount; l++) {

        for (var k = 0; k < (solutions/previous); k++) {
          combinations[j][i] = vector[i][l];
          j++
        }
      }
    }
  }

  for (var i = 0; i < solutions; i++) {
    console.log(combinations[i].join(" "));
  }
}

comboMaker([['quick', 'lazy'], ['brown', 'black', 'grey'], ['fox', 'dog']]);


问:
Angular 2 submitting dynamic form
My DB has Questions, every question has 1-N questionTypes and a question with a questionType has 0-N possible answers

Im trying to implement a form with Angular 2 like this plnkr where I can insert as many answers(label+value) as I want with the add button and then save the answers for individual type with the save button.

The problem is that I dont know how to finish It, ¿any help?

答:
You must use FormBuilder if you want to use arrays in a form:

```<code>import {FormArray, FormBuilder, FormGroup} from '@angular/forms';

constructor(private fb: FormBuilder} {}

public questionsForm: FormGroup = this.fb.group({
  questions: this.fb.array([])
});

addInfo(label: string, value: string): void {

  const questions: FormArray = <FormArray>this.questionsForm.get('questions');

  questions.push(this.fb.group({label: label, value: value}));

  this.label = '';
  this.value = '';
}

saveQuestion(): void {

  // This will give you {questions: [{label: '', value: ''}, ...]}
  const formValue = this.questionsForm.value;
}
</code>```

And then template:

```<code><form [formGroup]="questionsForm" (ngSubmit)="saveQuestion()" novalidate>
  <div *ngFor="let info of questionForm.get('questions').controls" [formGroup]="info">
    <input formControlName="label>
    <input formControlName="value">
  </div>

  <input [(ngModel]="label" [ngModelOptions]="{standalone: true}" type="text" placeholder="label">
  <input [(ngModel]="value" [ngModelOptions]="{standalone: true}" type="text" placeholder="value">

  <button (click)="addInfo(label, value)">Add</button>

  <p>
    <button type="submit">Save Question</button>
  </p>
</form>
</code>```

Title: Angular 2 submitting dynamic form

Body:
You must use FormBuilder if you want to use arrays in a form:

import {FormArray, FormBuilder, FormGroup} from '@angular/forms';

constructor(private fb: FormBuilder} {}

public questionsForm: FormGroup = this.fb.group({
  questions: this.fb.array([])
});

addInfo(label: string, value: string): void {

  const questions: FormArray = <FormArray>this.questionsForm.get('questions');

  questions.push(this.fb.group({label: label, value: value}));

  this.label = '';
  this.value = '';
}

saveQuestion(): void {

  // This will give you {questions: [{label: '', value: ''}, ...]}
  const formValue = this.questionsForm.value;
}

And then template:

<form [formGroup]="questionsForm" (ngSubmit)="saveQuestion()" novalidate>
  <div *ngFor="let info of questionForm.get('questions').controls" [formGroup]="info">
    <input formControlName="label>
    <input formControlName="value">
  </div>

  <input [(ngModel]="label" [ngModelOptions]="{standalone: true}" type="text" placeholder="label">
  <input [(ngModel]="value" [ngModelOptions]="{standalone: true}" type="text" placeholder="value">

  <button (click)="addInfo(label, value)">Add</button>

  <p>
    <button type="submit">Save Question</button>
  </p>
</form>


问:
using git post-receive for overwriting files in multiple directories
I'm using git to deploy changes to the files on my server, but the files live in two directories (/var/www and /user/myfiles) but I want to just use one repo to push the changes. So I've set up a repo (/user/gitrepo) and I think, after looking around for solutions, the best approach is to use post-receive to overwrite the files in the other directories, but I don't know how to use the hook post-receive to do what I want (I'm a git noob). Can any one help?

To be clear I have files in user/gitrepo/www/file1 and user/gitrepo/myfiles/file2

I want to push changes to the repo and have var/www/file1 and user/myfiles/file2 be updated.

Thanks!

(also if you have something you think should work better and also uses git, could you give me a detailed how-to?).

答:
If your remote server is linux (which it likely is) you can use any terminal commands within your remote server.

Say for example you wish to delete a file you can use the command
rm file2

You can chain as many commands in the hook as you like.
To copy the contents of one folder to another you could use: cp Folder1/* Folder2/


答:
Add flex-direction: column; to the heading, content and form  and put justify-content: flex-end to form and it will fix the issue

```<code>.box h1,
.box p,
.box form {
    display: flex;
    flex-direction: column;
    width: 100%;
}
.box form {
    justify-content: flex-end;
}
</code>```

form input {
    display: block;
    margin-bottom: 15px;
    width: 100%;
}

form label {
    text-align: left;
    width: 100%;
    display: block;
}

.box-container {
    display: flex;
}

.box {
    border: 1px solid #000;
    flex: 1 1 auto;
    max-width: calc(33% - 2px);
    text-align: center;
    box-sizing: border-box;
    padding: 10px;
    display: flex;
    flex-wrap: wrap;
}

.box p {
    text-align: justify;
}

.box h1,
.box p,
.box form {
    display: flex;
    flex-direction: column;
    width: 100%;
}

.box form {
    justify-content: flex-end;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box-container">
  <div class="box">
    <h1>bla bla bla</h1>
    <p> some information dasd asd asd asdasdasfs dsgd dfg sdfg fsdg sdfg s</p>
    <form>
      <label>value 1</label>
      <input type="text" />
      <label>value 2</label>
      <input type="text" />
      <input type="submit" value="submit" />
    </form>
  </div>
  <div class="box">
    <h1>bla bla bladada das dasd asd</h1>
    <p>Longer information
      <br> some information dasd asd asd asd an</p>
    <form>
      <label>value 1</label>
      <input type="text" />
      <label>value 2</label>
      <input type="text" />
      <label>value 3</label>
      <input type="text" />
      <input type="submit" value="submit" />
    </form>
  </div>
  <div class="box">
    <h1>bla bla b</h1>
    <p>Longer information</p>
    <form>
      <label>value 1</label>
      <input type="text" />
      <input type="submit" value="submit" />
    </form>
  </div>
  <div></code>```

Title: 3 boxes inline, content alignment

Body:
Add flex-direction: column; to the heading, content and form  and put justify-content: flex-end to form and it will fix the issue

.box h1,
.box p,
.box form {
    display: flex;
    flex-direction: column;
    width: 100%;
}
.box form {
    justify-content: flex-end;
}

form input {
    display: block;
    margin-bottom: 15px;
    width: 100%;
}

form label {
    text-align: left;
    width: 100%;
    display: block;
}

.box-container {
    display: flex;
}

.box {
    border: 1px solid #000;
    flex: 1 1 auto;
    max-width: calc(33% - 2px);
    text-align: center;
    box-sizing: border-box;
    padding: 10px;
    display: flex;
    flex-wrap: wrap;
}

.box p {
    text-align: justify;
}

.box h1,
.box p,
.box form {
    display: flex;
    flex-direction: column;
    width: 100%;
}

.box form {
    justify-content: flex-end;
}

<div class="box-container">
  <div class="box">
    <h1>bla bla bla</h1>
    <p> some information dasd asd asd asdasdasfs dsgd dfg sdfg fsdg sdfg s</p>
    <form>
      <label>value 1</label>
      <input type="text" />
      <label>value 2</label>
      <input type="text" />
      <input type="submit" value="submit" />
    </form>
  </div>
  <div class="box">
    <h1>bla bla bladada das dasd asd</h1>
    <p>Longer information
      <br> some information dasd asd asd asd an</p>
    <form>
      <label>value 1</label>
      <input type="text" />
      <label>value 2</label>
      <input type="text" />
      <label>value 3</label>
      <input type="text" />
      <input type="submit" value="submit" />
    </form>
  </div>
  <div class="box">
    <h1>bla bla b</h1>
    <p>Longer information</p>
    <form>
      <label>value 1</label>
      <input type="text" />
      <input type="submit" value="submit" />
    </form>
  </div>
  <div>


问:
Finding span of each node in NLTK tree
I am new to nltk and finding it hard to deal with nltk tree. Given an nltk parsed tree from Penn treebank, I want to be able to count the span of each node recursively from bottom to up. Span of leaf nodes is 1. And the span of non terminal nodes is the sum of the span of its children. Could someone please show me how to do this?

Thank you.

答:
If t is any tree or subtree in an nltk.Tree, its number of leaves is given by len(t.leaves()).

```<code>>>> t = Tree.fromstring('(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))')
>>> t[1,1]
Tree('NP', [Tree('D', ['the']), Tree('N', ['cat'])])
>>> len(t[1,1].leaves())
2
</code>```

Title: Finding span of each node in NLTK tree

Body:
If t is any tree or subtree in an nltk.Tree, its number of leaves is given by len(t.leaves()).

>>> t = Tree.fromstring('(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))')
>>> t[1,1]
Tree('NP', [Tree('D', ['the']), Tree('N', ['cat'])])
>>> len(t[1,1].leaves())
2


答:
Using lodash, concat the arrays, groupBy date, and merge the objects. While merge, if both values are numbers, return their sum.

var arr1 = [{"name":{"s1":2},"type":{"t1":2},"info":{"m1":2},"date":"2017-06-04"}, {"name":{"s1":3},"type":{"t1":3},"info":{"m1":3},"date":"2017-06-05"}];

var arr2 = [{"name":{"s1":1},"type":{"t1":0},"info":{"m1":2},"date":"2017-06-05"}];

var result = _(arr1)
  .concat(arr2)
  .groupBy('date')
  .map(function(group) {
    return _.mergeWith({}, ...group, function(o1, o2) {
      if(_.isNumber(o1) && _.isNumber(o1)) {
        return o1 + o2;
      }
    });
  })
  .value();

console.log(result);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script></code>```

Title: merge nested array by key and sum values using lodash

Body:
var arr1 = [{
    "name": { "s1": 2 },
    "type": { "t1": 2 },
    "info": { "m1": 2 },
    "date": "2017-06-04"
  },
  {
    "name": { "s1": 3 },
    "type": { "t1": 3 },
    "info": { "m1": 3 },
    "date": "2017-06-05"
  }
];

var arr2 = [{
  "name": { "s1": 1 },
  "type": { "t1": 0 },
  "info": { "m1": 2 },
  "date": "2017-06-05"
}];

I have two array need result as below:

[
  {
    "name": { "s1": 2 },
    "type": { "t1": 2 },
    "info": { "m1": 2 },
    "date": "2017-06-04"
  },
  {
    "name": { "s1": 4 },
    "type": { "t1": 3 },
    "info": { "m1": 5 },
    "date": "2017-06-05"
  }
]

Body:
Using lodash, concat the arrays, groupBy date, and merge the objects. While merge, if both values are numbers, return their sum.

var arr1 = [{"name":{"s1":2},"type":{"t1":2},"info":{"m1":2},"date":"2017-06-04"}, {"name":{"s1":3},"type":{"t1":3},"info":{"m1":3},"date":"2017-06-05"}];

var arr2 = [{"name":{"s1":1},"type":{"t1":0},"info":{"m1":2},"date":"2017-06-05"}];

var result = _(arr1)
  .concat(arr2)
  .groupBy('date')
  .map(function(group) {
    return _.mergeWith({}, ...group, function(o1, o2) {
      if(_.isNumber(o1) && _.isNumber(o1)) {
        return o1 + o2;
      }
    });
  })
  .value();

console.log(result);

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


问:
Containerized Kafka client errors when producing messages to the host Kafka server
There are a number of similar types of queries on stackoverflow, but none quite match the problem that I am seeing.

I have a zookeeper/kafka setup on my server which work perfectly.  One can produce

```<code>bin/kafka-console-producer.sh --broker-list 192.168.2.80:9092 --topic test
</code>```

and consume

```<code>bin/kafka-console-consumer.sh --bootstrap-server 192.168.2.80:9092 --topic test --from-beginning
</code>```

locally on the Linux Ubuntu 16.04 server.

From a Docker container - also running Ubuntu 16.04 - I want to produce and consume.  The container's Kafka code was copied from that on the server.
Firstly I can create a new topic

```<code>bin/kafka-topics.sh --create --zookeeper 192.168.2.80:2181 --replication-factor 1 --partitions 1 --topic test2
</code>```

from the container and then list it again

```<code>bin/kafka-topics.sh --list --zookeeper 192.168.2.80:2181
</code>```

However when I try to produce new messages, using the above (kafka-console-producer.sh) command it fails with the following message:

```<code>[2017-06-05 13:59:05,317] ERROR Error when sending message to topic test2  with key: null, value: 2 bytes with error: (org.apache.kafka.clients.producer.internals.ErrorLoggingCallback)
org.apache.kafka.common.errors.TimeoutException: Expiring 1 record(s) for test2-0: 1526 ms has passed since batch creation plus linger time
</code>```

immediately after entering the text of the message and pressing enter.

It may seem strange running a Docker container on the same host, but once this works I will move the container to a separate host for production.

My kafka server.properties file:

```<code>listeners=PLAINTEXT://0.0.0.0:9092
</code>```

Kafka version:

```<code>2.12-0.10.2.1
</code>```

Docker version:

```<code>Docker version 1.12.6, build 78d1802
</code>```

答:
The problem is (slightly simplified) caused by how Kafka's protocol works.  Given a list of "bootstrap servers" (e.g. localhost:9092), a Kafka client will contact those bootstrap servers, but then use the hostnames of the actual Kafka brokers as returned by the bootstrap servers (the broker's advertised.listeners config, depending on your Kafka/Docker setup, might be set to e.g. kafka:9092).  So here, the client would talk to localhost:9092 for bootstrapping (which will work), but then switch to kafka:9092 (which will not work, "thanks" to the networking setup).

Fortunately there is a way to configure Kafka + Docker in a way that "just works", and it doesn't require shenanigans such as fiddling with your host's /etc/hosts file and such.  As part of this you need to set a few (new) Kafka settings though, which were added in kafka's KIP-103: Separation of Internal and External traffic.

Here's a snippet for Docker Compose (docker-compose.yml) that demonstrates how to do this:

```<code>---
version: '2'
services:
  zookeeper:
    image: confluentinc/cp-zookeeper:3.2.1
    hostname: zookeeper
    ports:
      - '32181:32181'
    environment:
      ZOOKEEPER_CLIENT_PORT: 32181

  kafka:
    image: confluentinc/cp-kafka:3.2.1
    hostname: kafka
    ports:
      - '9092:9092'
      - '29092:29092'
    depends_on:
      - zookeeper
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:32181
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:29092,PLAINTEXT_HOST://localhost:9092
      # Following line is needed for Kafka versions 0.11+
      # in case you run less than 3 Kafka brokers in your
      # cluster because the broker config
      # `offsets.topic.replication.factor` (default: 3)
      # is now enforced upon topic creation
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
</code>```

Here, the key settings are:

listener.security.protocol.map (which is being set via KAFKA_LISTENER_SECURITY_PROTOCOL_MAP)

inter.broker.listener.name

advertised.listeners

In the setup above, the containerized Kafka broker listens on localhost:9092 for access from your host machine (e.g. your Mac laptop) and on kafka:29092 for access from other containers.

A full end-to-end example is available at:
https://github.com/confluentinc/cp-docker-images/blob/v3.2.1/examples/kafka-streams-examples/docker-compose.yml (documentation at http://docs.confluent.io/3.2.1/cp-docker-images/docs/tutorials/kafka-streams-examples.html).

Body:
There are a number of similar types of queries on stackoverflow, but none quite match the problem that I am seeing.

I have a zookeeper/kafka setup on my server which work perfectly.  One can produce

bin/kafka-console-producer.sh --broker-list 192.168.2.80:9092 --topic test

and consume

bin/kafka-console-consumer.sh --bootstrap-server 192.168.2.80:9092 --topic test --from-beginning

locally on the Linux Ubuntu 16.04 server.

From a Docker container - also running Ubuntu 16.04 - I want to produce and consume.  The container's Kafka code was copied from that on the server.
Firstly I can create a new topic

bin/kafka-topics.sh --create --zookeeper 192.168.2.80:2181 --replication-factor 1 --partitions 1 --topic test2

from the container and then list it again

bin/kafka-topics.sh --list --zookeeper 192.168.2.80:2181

However when I try to produce new messages, using the above (kafka-console-producer.sh) command it fails with the following message:

[2017-06-05 13:59:05,317] ERROR Error when sending message to topic test2  with key: null, value: 2 bytes with error: (org.apache.kafka.clients.producer.internals.ErrorLoggingCallback)
org.apache.kafka.common.errors.TimeoutException: Expiring 1 record(s) for test2-0: 1526 ms has passed since batch creation plus linger time

immediately after entering the text of the message and pressing enter.

It may seem strange running a Docker container on the same host, but once this works I will move the container to a separate host for production.

My kafka server.properties file:

listeners=PLAINTEXT://0.0.0.0:9092

Kafka version:

2.12-0.10.2.1

Docker version:

Docker version 1.12.6, build 78d1802

Body:
The problem is (slightly simplified) caused by how Kafka's protocol works.  Given a list of "bootstrap servers" (e.g. localhost:9092), a Kafka client will contact those bootstrap servers, but then use the hostnames of the actual Kafka brokers as returned by the bootstrap servers (the broker's advertised.listeners config, depending on your Kafka/Docker setup, might be set to e.g. kafka:9092).  So here, the client would talk to localhost:9092 for bootstrapping (which will work), but then switch to kafka:9092 (which will not work, "thanks" to the networking setup).

Fortunately there is a way to configure Kafka + Docker in a way that "just works", and it doesn't require shenanigans such as fiddling with your host's /etc/hosts file and such.  As part of this you need to set a few (new) Kafka settings though, which were added in kafka's KIP-103: Separation of Internal and External traffic.

Here's a snippet for Docker Compose (docker-compose.yml) that demonstrates how to do this:

---
version: '2'
services:
  zookeeper:
    image: confluentinc/cp-zookeeper:3.2.1
    hostname: zookeeper
    ports:
      - '32181:32181'
    environment:
      ZOOKEEPER_CLIENT_PORT: 32181

  kafka:
    image: confluentinc/cp-kafka:3.2.1
    hostname: kafka
    ports:
      - '9092:9092'
      - '29092:29092'
    depends_on:
      - zookeeper
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:32181
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:29092,PLAINTEXT_HOST://localhost:9092
      # Following line is needed for Kafka versions 0.11+
      # in case you run less than 3 Kafka brokers in your
      # cluster because the broker config
      # `offsets.topic.replication.factor` (default: 3)
      # is now enforced upon topic creation
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1

Here, the key settings are:

listener.security.protocol.map (which is being set via KAFKA_LISTENER_SECURITY_PROTOCOL_MAP)

inter.broker.listener.name

advertised.listeners

In the setup above, the containerized Kafka broker listens on localhost:9092 for access from your host machine (e.g. your Mac laptop) and on kafka:29092 for access from other containers.

A full end-to-end example is available at:
https://github.com/confluentinc/cp-docker-images/blob/v3.2.1/examples/kafka-streams-examples/docker-compose.yml (documentation at http://docs.confluent.io/3.2.1/cp-docker-images/docs/tutorials/kafka-streams-examples.html).


问:
Media folder not showing images in Umbraco
I have migrated a umbraco site over. Hooked the databse up and everything is working fine but the images are not showing on the site and in the media folder.

I have set the permissions on the folder.

changed authentication on the folder to app pool.

tried changing virtualRoot to rootPath and rootUrl.

none of the above work. The files names are showing in the media window but no images (blank previews).

Funny thing is i can upload images now and there are showing so something to do with path.

hope someone can help. thanks

答:
Perhaps you need to tell Umbraco that it's running in a virtual directory.

There is a setting in the umbracoSettings.config which you can read about here: https://our.umbraco.org/documentation/reference/config/umbracosettings/#notifications (search for ResolveUrlsFromTextString)

Set the following to true:

```<code><ResolveUrlsFromTextString>true</ResolveUrlsFromTextString>
</code>```

Body:
Perhaps you need to tell Umbraco that it's running in a virtual directory.

There is a setting in the umbracoSettings.config which you can read about here: https://our.umbraco.org/documentation/reference/config/umbracosettings/#notifications (search for ResolveUrlsFromTextString)

Set the following to true:

<ResolveUrlsFromTextString>true</ResolveUrlsFromTextString>


问:
WordPress excerpt character count not working
My loop looks like this:

```<code><!-- loop for the posts here -->
<?php
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => 3,
        'category_name' => 'news'
    );
    $query = new WP_Query($args);
    while($query->have_posts()) : $query->the_post();
?>
    <div class="news_box_content">
        <h5><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h5>
        <figure><a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a></figure>
        <?php if($post->post_excerpt) { ?>
            <p><?php echo get_the_excerpt(); ?></p>
            <a href="<?php the_permalink(); ?>">Read more...</a>
        <?php } else {
            the_content('Read More');
        } ?>
    </div>
<?php endwhile; wp_reset_postdata(); ?>
</code>```

I used a function to count the excerpt length but it is not working.

```<code>function custom_excerpt_length(){
   return 10;
}
add_filter('excerpt_length', 'custom_excerpt_length');
</code>```

How can I limit the number of characters on any excerpt?

答:
Try this one. I always use this one</p>

```<code><?php
      $content = get_the_content();
      $content = strip_tags($content);

      $dots = strlen(substr($content,0,50)) < 50 ? " " : "...";
      echo substr($content,0,50) . $dots;
      ?>
</code>```

Body:
My loop looks like this:

<?php
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => 3,
        'category_name' => 'news'
    );
    $query = new WP_Query($args);
    while($query->have_posts()) : $query->the_post();
?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?>

        <?php if($post->post_excerpt) { ?>

<?php echo get_the_excerpt(); ?>

            <a href="<?php the_permalink(); ?>">Read more...
        <?php } else {
            the_content('Read More');
        } ?>

<?php endwhile; wp_reset_postdata(); ?>

I used a function to count the excerpt length but it is not working.

function custom_excerpt_length(){
   return 10;
}
add_filter('excerpt_length', 'custom_excerpt_length');

How can I limit the number of characters on any excerpt?

Body:
Try this one. I always use this one

<?php
      $content = get_the_content();
      $content = strip_tags($content);

      $dots = strlen(substr($content,0,50)) < 50 ? " " : "...";
      echo substr($content,0,50) . $dots;
      ?>


问:
string.join to append with some count and take rest to newline
I am using string.join appending many data  which is separated by comma.If we have more than 50,only first 10 are visible and others are not visible.It will exit the screen size.I want to display the data with some count in string within screen.

```<code>_validatonDictionary.AddError(string.Empty, string.Join(",", findduplicate) + "-Settlement POD," + string.Join(",", finddupl) + "-Ded are duplicate PODS");
</code>```

"findduplicate" and "finddupl"  is the list which consist of more than 100 item.I want to diplay maximum 10 one after other

答:
You can use Ceiling</p>

```<code>//Calculating number of loops to run
int ceilingLimit = 10;
int iCount = finddupl.Count() / ceilingLimit + (finddupl.Count() % ceilingLimit != 0 ? 1 : 0);;
for (int iLoopCount = 0; iLoopCount < iCount; ++iLoopCount)
{
     int iRecordCount = finddupl.Count() >= ceilingLimit ? ceilingLimit : finddupl.Count();
     var currentDupls = finddupl.Take(iRecordCount).ToList();
     _validatonDictionary.AddError(string.Empty, string.Join(",", findduplicate) + "-Settlement POD," + string.Join(",", currentDupls) + "-Ded are duplicate PODS");
}
</code>```

Body:
I am using string.join appending many data  which is separated by comma.If we have more than 50,only first 10 are visible and others are not visible.It will exit the screen size.I want to display the data with some count in string within screen.

_validatonDictionary.AddError(string.Empty, string.Join(",", findduplicate) + "-Settlement POD," + string.Join(",", finddupl) + "-Ded are duplicate PODS");

"findduplicate" and "finddupl"  is the list which consist of more than 100 item.I want to diplay maximum 10 one after other

Body:
You can use Ceiling

//Calculating number of loops to run
int ceilingLimit = 10;
int iCount = finddupl.Count() / ceilingLimit + (finddupl.Count() % ceilingLimit != 0 ? 1 : 0);;
for (int iLoopCount = 0; iLoopCount < iCount; ++iLoopCount)
{
     int iRecordCount = finddupl.Count() >= ceilingLimit ? ceilingLimit : finddupl.Count();
     var currentDupls = finddupl.Take(iRecordCount).ToList();
     _validatonDictionary.AddError(string.Empty, string.Join(",", findduplicate) + "-Settlement POD," + string.Join(",", currentDupls) + "-Ded are duplicate PODS");
}


问:
Catel ViewModelToModel not linking
I have a simple ViewModel which has two Models. So it looks like this:

```<code>public class ConnectionItemSelectorViewModel : ViewModelBase {
    ...

    #region AvailableConnectionsModel

    // Model Nr. 1
    [Model]
    public ConnectionList AvailableConnectionsModel
    {
        get { return GetValue<ConnectionList>(AvailableConnectionsModelProperty); }
        set { SetValue(AvailableConnectionsModelProperty, value); }
    }

    public static readonly PropertyData AvailableConnectionsModelProperty = RegisterProperty(nameof(AvailableConnectionsModel), typeof(ConnectionList), () => new ConnectionList());

    #endregion

    #region SelectedConnectionsModel

    // Model Nr. 2
    [Model]
    public ConnectionList SelectedConnectionsModel
    {
        get { return GetValue<ConnectionList>(SelectedConnectionsModelProperty); }
        set { SetValue(SelectedConnectionsModelProperty, value); }
    }

    public static readonly PropertyData SelectedConnectionsModelProperty = RegisterProperty(nameof(SelectedConnectionsModel), typeof(ConnectionList), () => new ConnectionList());

    #endregion

    ...
}
</code>```

ConnectionList extends ModelBase so I can use the [Model]-Attribute several times.

Now I want to expose the properties of the Model to the ViewModel:

```<code>public class ConnectionItemSelectorViewModel : ViewModelBase {
    ...
    // init Model properties

    #region AvailableConnections

    // Using a unique name for the property in the ViewModel
    // but linking to the "correct" property in the Model by its name
    [ViewModelToModel(nameof(AvailableConnectionsModel), nameof(ConnectionList.Connections))]
    public ObservableCollection<ConnectionItem> AvailableConnections
    {
        get { return GetValue<ObservableCollection<ConnectionItem>>(AvailableConnectionsProperty); }
        set { SetValue(AvailableConnectionsProperty, value); }
    }

    public static readonly PropertyData AvailableConnectionsProperty = RegisterProperty(nameof(AvailableConnections), typeof(ObservableCollection<ConnectionItem>), () => null);

    #endregion

    // linking other properties to the models
    ...
}
</code>```

The problem is that the linking doesn't work. So after initialization the property AvailableConnections (and the others also) are still null, though the Model itself is initialized correctly.

Am I missing something or isn't this possible at all?

thx in advance!

答: Try setting the MappingType on the ViewModelToModel attribute so that the model wins.

Title: Catel ViewModelToModel not linking

Body:
I have a simple ViewModel which has two Models. So it looks like this:

public class ConnectionItemSelectorViewModel : ViewModelBase {
    ...

    #region AvailableConnectionsModel

    // Model Nr. 1
    [Model]
    public ConnectionList AvailableConnectionsModel
    {
        get { return GetValue<ConnectionList>(AvailableConnectionsModelProperty); }
        set { SetValue(AvailableConnectionsModelProperty, value); }
    }

    public static readonly PropertyData AvailableConnectionsModelProperty = RegisterProperty(nameof(AvailableConnectionsModel), typeof(ConnectionList), () => new ConnectionList());

    #endregion

    #region SelectedConnectionsModel

    // Model Nr. 2
    [Model]
    public ConnectionList SelectedConnectionsModel
    {
        get { return GetValue<ConnectionList>(SelectedConnectionsModelProperty); }
        set { SetValue(SelectedConnectionsModelProperty, value); }
    }

    public static readonly PropertyData SelectedConnectionsModelProperty = RegisterProperty(nameof(SelectedConnectionsModel), typeof(ConnectionList), () => new ConnectionList());

    #endregion

    ...
}

ConnectionList extends ModelBase so I can use the [Model]-Attribute several times.

Now I want to expose the properties of the Model to the ViewModel:

public class ConnectionItemSelectorViewModel : ViewModelBase {
    ...
    // init Model properties

    #region AvailableConnections

    // Using a unique name for the property in the ViewModel
    // but linking to the "correct" property in the Model by its name
    [ViewModelToModel(nameof(AvailableConnectionsModel), nameof(ConnectionList.Connections))]
    public ObservableCollection<ConnectionItem> AvailableConnections
    {
        get { return GetValue<ObservableCollection<ConnectionItem>>(AvailableConnectionsProperty); }
        set { SetValue(AvailableConnectionsProperty, value); }
    }

    public static readonly PropertyData AvailableConnectionsProperty = RegisterProperty(nameof(AvailableConnections), typeof(ObservableCollection<ConnectionItem>), () => null);

    #endregion

    // linking other properties to the models
    ...
}

The problem is that the linking doesn't work. So after initialization the property AvailableConnections (and the others also) are still null, though the Model itself is initialized correctly.

Am I missing something or isn't this possible at all?

thx in advance!


问:
React router chunk bundle not fetched when visited that route
I want to load the bundle when the route url is visited. My server is django localhost:8000. My webpack splits up the bundle.

My router component:

import React from 'react';
import {BrowserRouter as Router, Route, Link, withRouter} from 'react-router-dom';

import App from '../app';
//import CollegeList from '../apps/college/CollegeList';
import CollegeDetail from '../apps/college/CollegeDetail';
import CourseList from '../apps/course/CourseList';
import CourseDetail from '../apps/course/CourseDetail';
import UniversityList from '../apps/university/UniversityList';
import UniversityDetail from '../apps/university/UniversityDetail';
import AdmissionList from '../apps/admission/AdmissionList';
import AdmissionDetail from '../apps/admission/AdmissionDetail';
import CareerList from '../apps/career/CareerList';
import CareerDetail from '../apps/career/CareerDetail';
import EventList from '../apps/event/EventList';
import EventDetail from '../apps/event/EventDetail';
import NewsList from '../apps/news/NewsList';
import NewsDetail from '../apps/news/NewsDetail';
import ScholarshipList from '../apps/scholarship/ScholarshipList';
import ScholarshipDetail from '../apps/scholarship/ScholarshipDetail';
import VacancyList from '../apps/vacancy/VacancyList';
import VacancyDetail from '../apps/vacancy/VacancyDetail';
import RankList from '../apps/rank/RankList';
import RankDetail from '../apps/rank/RankDetail';
import FacultyCourseList from '../apps/faculty/FacultyCourseList';
import LoginForm from '../apps/users/components/LoginForm';
import SignUpForm from '../apps/users/components/SignUpForm';
import Header from '../components/Header';
import Footer from '../components/Footer';
import LoadingComponent from '../components/LoadingComponent.js';

function loadRoute(cb) {
    return module => {console.log(module);cb(null, module.default)};
}

class AppRoute extends React.Component {
    render() {
        return (
            <Router>

                    <LoadingComponent/>

                    <Route exact path='/' component={App}/>
                    <Route exact path='/colleges' getComponent={(location, cb) => {
                        System.import('../apps/college/CollegeList')
                            .then(loadRoute(cb))
                            .catch((error) => {console.log('error')});
                    }}/>
                    <Route path='/colleges/:slug' component={CollegeDetail}/>
                    <Route exact path='/courses' component={CourseList}/>
                    <Route path='/courses/:slug' component={CourseDetail}/>
                    <Route exact path='/universities' component={UniversityList}/>
                    <Route path='/universities/:slug' component={UniversityDetail}/>
                    <Route exact path='/admissions' component={AdmissionList}/>
                    <Route path='/admissions/:slug' component={AdmissionDetail}/>
                    <Route exact path='/careers' component={CareerList}/>
                    <Route path='/careers/:slug' component={CareerDetail}/>
                    <Route exact path='/events' component={EventList}/>
                    <Route path='/events/:slug' component={EventDetail}/>
                    <Route exact path='/news' component={NewsList}/>
                    <Route path='/news/:slug' component={NewsDetail}/>
                    <Route exact path='/scholarships' component={ScholarshipList}/>
                    <Route path='/scholarships/:slug' component={ScholarshipDetail}/>
                    <Route exact path='/vacancies' component={VacancyList}/>
                    <Route path='/vacancies/:slug' component={VacancyDetail}/>
                    <Route exact path='/ranks' component={RankList}/>
                    <Route path='/ranks/:slug' component={RankDetail}/>
                    <Route exact path='/faculties' component={FacultyCourseList}/>
                    <Route path='/login' component={LoginForm}/>
                    <Route path='/signup' component={SignUpForm}/>

            </Router>
        )
    }
}

export default AppRoute```

According to documentation this should lazy-load my bundle when that route is visited. When I visit the url bundle is not fetch and nothing loads up.
enter image description here

Thanks.

答:
I am not familiar with System.import because it is deprecated in favor of import(). However, you are not passing the component to your loadRoute callback.

```<code>.then(module => loadRoute(cb, module))
</code>```

I don't think it would work in the way you implemented

Body:
I want to load the bundle when the route url is visited. My server is django localhost:8000. My webpack splits up the bundle.

My router component:

import React from 'react';
import {BrowserRouter as Router, Route, Link, withRouter} from 'react-router-dom';

import App from '../app';
//import CollegeList from '../apps/college/CollegeList';
import CollegeDetail from '../apps/college/CollegeDetail';
import CourseList from '../apps/course/CourseList';
import CourseDetail from '../apps/course/CourseDetail';
import UniversityList from '../apps/university/UniversityList';
import UniversityDetail from '../apps/university/UniversityDetail';
import AdmissionList from '../apps/admission/AdmissionList';
import AdmissionDetail from '../apps/admission/AdmissionDetail';
import CareerList from '../apps/career/CareerList';
import CareerDetail from '../apps/career/CareerDetail';
import EventList from '../apps/event/EventList';
import EventDetail from '../apps/event/EventDetail';
import NewsList from '../apps/news/NewsList';
import NewsDetail from '../apps/news/NewsDetail';
import ScholarshipList from '../apps/scholarship/ScholarshipList';
import ScholarshipDetail from '../apps/scholarship/ScholarshipDetail';
import VacancyList from '../apps/vacancy/VacancyList';
import VacancyDetail from '../apps/vacancy/VacancyDetail';
import RankList from '../apps/rank/RankList';
import RankDetail from '../apps/rank/RankDetail';
import FacultyCourseList from '../apps/faculty/FacultyCourseList';
import LoginForm from '../apps/users/components/LoginForm';
import SignUpForm from '../apps/users/components/SignUpForm';
import Header from '../components/Header';
import Footer from '../components/Footer';
import LoadingComponent from '../components/LoadingComponent.js';

function loadRoute(cb) {
    return module => {console.log(module);cb(null, module.default)};
}

class AppRoute extends React.Component {
    render() {
        return (
            <Router>

                    <LoadingComponent/>

                    <Route exact path='/' component={App}/>
                    <Route exact path='/colleges' getComponent={(location, cb) => {
                        System.import('../apps/college/CollegeList')
                            .then(loadRoute(cb))
                            .catch((error) => {console.log('error')});
                    }}/>
                    <Route path='/colleges/:slug' component={CollegeDetail}/>
                    <Route exact path='/courses' component={CourseList}/>
                    <Route path='/courses/:slug' component={CourseDetail}/>
                    <Route exact path='/universities' component={UniversityList}/>
                    <Route path='/universities/:slug' component={UniversityDetail}/>
                    <Route exact path='/admissions' component={AdmissionList}/>
                    <Route path='/admissions/:slug' component={AdmissionDetail}/>
                    <Route exact path='/careers' component={CareerList}/>
                    <Route path='/careers/:slug' component={CareerDetail}/>
                    <Route exact path='/events' component={EventList}/>
                    <Route path='/events/:slug' component={EventDetail}/>
                    <Route exact path='/news' component={NewsList}/>
                    <Route path='/news/:slug' component={NewsDetail}/>
                    <Route exact path='/scholarships' component={ScholarshipList}/>
                    <Route path='/scholarships/:slug' component={ScholarshipDetail}/>
                    <Route exact path='/vacancies' component={VacancyList}/>
                    <Route path='/vacancies/:slug' component={VacancyDetail}/>
                    <Route exact path='/ranks' component={RankList}/>
                    <Route path='/ranks/:slug' component={RankDetail}/>
                    <Route exact path='/faculties' component={FacultyCourseList}/>
                    <Route path='/login' component={LoginForm}/>
                    <Route path='/signup' component={SignUpForm}/>

            </Router>
        )
    }
}

export default AppRoute

According to documentation this should lazy-load my bundle when that route is visited. When I visit the url bundle is not fetch and nothing loads up.
enter image description here

Thanks.

Body:
I am not familiar with System.import because it is deprecated in favor of import(). However, you are not passing the component to your loadRoute callback.

.then(module => loadRoute(cb, module))

I don't think it would work in the way you implemented


问:
How to generate statically linked executables?
I am trying to create a static executable with Rust. I am not trying to statically link a particular library, I am trying to create a executable which does not use dynamic linking at all. I have the following (otherwise working) test:

```<code>$ cat hello.rs
fn main()
    {
    print!("Hello, world!\n");
    }
$ rustc hello.rs -o hello
$ file hello
hello: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV),
 dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, [etc]
</code>```

Note the dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2. Static executables have statically linked instead. (And in my case corrupted section header size, although I would be pleasantly astonished if I can convince Rust to replicate that.)

What options do I need to pass to rustc to get it to generate a actual static executable (for concreteness: one which even file agrees is statically linked).

答:
Since Rust 1.19, you can statically link the C runtime (CRT) to avoid this very common situation on Windows:

The program can't start because VCRUNTIME140.dll is missing from your
  computer. Try reinstalling the program to fix this problem.

Add this to your .cargo/config file, using the appropriate target triple for your platform:

```<code>[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static"]
</code>```

An alternative to editing .cargo/config is to pass -C target-feature=+crt-static to rustc by hand.

See also:

RFC

Pull Request

Cargo config documentation

Body:
I am trying to create a static executable with Rust. I am not trying to statically link a particular library, I am trying to create a executable which does not use dynamic linking at all. I have the following (otherwise working) test:

$ cat hello.rs
fn main()
    {
    print!("Hello, world!\n");
    }
$ rustc hello.rs -o hello
$ file hello
hello: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV),
 dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, [etc]

Note the dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2. Static executables have statically linked instead. (And in my case corrupted section header size, although I would be pleasantly astonished if I can convince Rust to replicate that.)

What options do I need to pass to rustc to get it to generate a actual static executable (for concreteness: one which even file agrees is statically linked).

Body:
Since Rust 1.19, you can statically link the C runtime (CRT) to avoid this very common situation on Windows:

The program can't start because VCRUNTIME140.dll is missing from your
  computer. Try reinstalling the program to fix this problem.

Add this to your .cargo/config file, using the appropriate target triple for your platform:

[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static"]

An alternative to editing .cargo/config is to pass -C target-feature=+crt-static to rustc by hand.

See also:

RFC

Pull Request

Cargo config documentation

ContentLicense: CC BY-SA 4.0


问:
jQuery code works with Firefox but not webKit
I'm having a problem using jQuery: I have what I want with Firefox, but when I try it with webkit (Chrome, Opera...) it doesn't works.
The idea of my code is to set all the <select> from a <form> in gray when the selected <option> is the value 0 (the first element of each <select>). When the <option> changes, the <select> has to go black. When you click on the 0 <option>, its text also changes from - to it's content="" text.

 So it's okay with Firefox but not webkit, it's pretty annoying. You can see all my code in this JSFiddle and test it : my JSFiddle.

 I think the problem comes from the use of $(this).parent() but I don't know how to avoid it.

Thanks

答:
A little help for you:

```<code>$("#pp").find("option").on("click", function() { ...
</code>```

The option itself does not fire a click event. Instead, use:

```<code>$("#pp").find("select").on("click", function() { ...
</code>```

Therefore, you need to modify your inner lines by removing the parent() methods from your code since you are now listening to the parent directly.

This should help you for the start ...

Body:
A little help for you:

$("#pp").find("option").on("click", function() { ...

The option itself does not fire a click event. Instead, use:

$("#pp").find("select").on("click", function() { ...

Therefore, you need to modify your inner lines by removing the parent() methods from your code since you are now listening to the parent directly.

This should help you for the start ...


问:
Pushing an object with unique_ptr into vector in C++
I have a simple class structure modelling a discrete simulation, with a vector of States, which each contain a number of Transitions, held as a vector of smart pointers. I've used smart pointers to hold the transitions as in my full application I need polymorphism.

```<code>#include <vector>
#include <memory>

class Transition {
    public:
        Transition() {}
};

class State {
    public:
        State(int num) : num(num), transitions() {}
        void add_transition(std::unique_ptr<Transition> trans) {
            transitions.push_back(std::move(trans));
        }

    private:
        int num;
        std::vector<std::unique_ptr<Transition>> transitions;
};

int main() {
    std::vector<State> states;
    for (int i = 0; i < 10; i++) {
        State nstate = State(i);
        for (int j = 0; j < 2; j++) {
            nstate.add_transition(std::move(std::unique_ptr<Transition>(new Transition())));
        }
        // This line causes compiler errors
        states.push_back(nstate);
    }
}
</code>```

I get compiler errors when adding the new state object to the vector:

```<code>Error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Transition; _Dp = std::default_delete<Transition>]’
 { ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
</code>```

I imagine this is due to vector making a copy of the State object which is also trying to make a copy of the vector of unique_ptrs which isn't allowed. I've seen that emplace_back doesn't make copies like push_back does but I still get the same error.

Adding the State object directly into the vector works, but I'd prefer to avoid this workaround as in my actual code I do more work with the State object rather than just adding transitions and don't want to keep accessing the vector.

```<code>int main() {
    std::vector<State> states;
    for (int i = 0; i < 10; i++) {
        states.push_back(State(i));
        for (int j = 0; j < 2; j++) {
            states[i].add_transition(std::move(std::unique_ptr<Transition>(new Transition())));
        }
    }
}
</code>```

答:
You should avoid using push_back and use emplace_back to create items inplace instead.

```<code>constexpr ::std::int32_t const states_count{10};
constexpr ::std::int32_t const transitions_per_state_count{2};
::std::vector< State > states;
states.reserve(states_count);
for(::std::int32_t state_index{}; states_count != state_index; ++state_index)
{
    states.emplace_back(state_index); // new state is added without copying or moving anything
    auto & nstate{states.back()};
    for(::std::int32_t transition_index{}; transitions_per_state_count != transition_index; ++transition_index)
    {
        nstate.add_transition(::std::unique_ptr< Transition >{new Transition{}});
    }
}
</code>```

Body:
I have a simple class structure modelling a discrete simulation, with a vector of States, which each contain a number of Transitions, held as a vector of smart pointers. I've used smart pointers to hold the transitions as in my full application I need polymorphism.

#include <vector>
#include <memory>

class Transition {
    public:
        Transition() {}
};

class State {
    public:
        State(int num) : num(num), transitions() {}
        void add_transition(std::unique_ptr<Transition> trans) {
            transitions.push_back(std::move(trans));
        }

    private:
        int num;
        std::vector<std::unique_ptr<Transition>> transitions;
};

int main() {
    std::vector<State> states;
    for (int i = 0; i < 10; i++) {
        State nstate = State(i);
        for (int j = 0; j < 2; j++) {
            nstate.add_transition(std::move(std::unique_ptr<Transition>(new Transition())));
        }
        // This line causes compiler errors
        states.push_back(nstate);
    }
}

I get compiler errors when adding the new state object to the vector:

Error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Transition; _Dp = std::default_delete<Transition>]’
 { ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }

I imagine this is due to vector making a copy of the State object which is also trying to make a copy of the vector of unique_ptrs which isn't allowed. I've seen that emplace_back doesn't make copies like push_back does but I still get the same error.

Adding the State object directly into the vector works, but I'd prefer to avoid this workaround as in my actual code I do more work with the State object rather than just adding transitions and don't want to keep accessing the vector.

int main() {
    std::vector<State> states;
    for (int i = 0; i < 10; i++) {
        states.push_back(State(i));
        for (int j = 0; j < 2; j++) {
            states[i].add_transition(std::move(std::unique_ptr<Transition>(new Transition())));
        }
    }
}

Body:
You should avoid using push_back and use emplace_back to create items inplace instead.

constexpr ::std::int32_t const states_count{10};
constexpr ::std::int32_t const transitions_per_state_count{2};
::std::vector< State > states;
states.reserve(states_count);
for(::std::int32_t state_index{}; states_count != state_index; ++state_index)
{
    states.emplace_back(state_index); // new state is added without copying or moving anything
    auto & nstate{states.back()};
    for(::std::int32_t transition_index{}; transitions_per_state_count != transition_index; ++transition_index)
    {
        nstate.add_transition(::std::unique_ptr< Transition >{new Transition{}});
    }
}


问:
Are theses two the same
The formula for a sensor I'm using is:

```<code>%RH  = (125 * rhData / 65536) - 6
</code>```

and the routine I've seen is:

```<code>*rhData = ( (uint32_t) readData[0] << 8 ) + ( readData[1] & 0xfc );
*rhData = ( ( ( *rhData ) * 15625L ) >> 13 ) - 6000;
</code>```

I cant see that the two are the same, can someone explain how it works?

Yours Simon M.

答:
It was a brain fade day!
Multiply 125 * 1000, then divide by 2 to find the lowest integer. (15625)

What threw me is 125^2 = 15625

Thanks

Yours Simon M.

Title: Are theses two the same

Body:
The formula for a sensor I'm using is:

%RH  = (125 * rhData / 65536) - 6

and the routine I've seen is:

*rhData = ( (uint32_t) readData[0] << 8 ) + ( readData[1] & 0xfc );
*rhData = ( ( ( *rhData ) * 15625L ) >> 13 ) - 6000;

I cant see that the two are the same, can someone explain how it works?

Yours Simon M.


问:
How to display the number of subroutines and their names in a perl script at the time of its execution?
Consider the following Perl script script.pl as an example:

```<code>use strict;
use warnings;
sub f1
{statements}
sub f2
{statements}
sub f3
{statements}
f1();f2();f3();
</code>```

When I execute the script, it should show the following output:

./script.pl

number of subroutines:3

  names of subroutines:f1 f2 f3

When the code is executed, how can I count the number of subroutines, get their names, and then print them during runtime?

答:
I think the function you're looking for is caller:

```<code>#!/usr/bin/env perl
use strict;
use warnings;

sub test {

   my (
      $package, $filename,  $line,     $subroutine,
      $hasargs, $wantarray, $evaltext, $is_require,
      $hints,   $bitmask,   $hinthash
     )
     = caller(0);
   print "$subroutine called at $line of $filename\n";
}

test;
</code>```

Note - without arguments, caller returns just package, filename and line. The number is a number of stack frames, in case you're nesting the subroutine.

Body:
Consider the following Perl script script.pl as an example:

use strict;
use warnings;
sub f1
{statements}
sub f2
{statements}
sub f3
{statements}
f1();f2();f3();

When I execute the script, it should show the following output:

./script.pl

number of subroutines:3

  names of subroutines:f1 f2 f3

When the code is executed, how can I count the number of subroutines, get their names, and then print them during runtime?

Body:
I think the function you're looking for is caller:

#!/usr/bin/env perl
use strict;
use warnings;

sub test {

   my (
      $package, $filename,  $line,     $subroutine,
      $hasargs, $wantarray, $evaltext, $is_require,
      $hints,   $bitmask,   $hinthash
     )
     = caller(0);
   print "$subroutine called at $line of $filename\n";
}

test;

Note - without arguments, caller returns just package, filename and line. The number is a number of stack frames, in case you're nesting the subroutine.


问:
read the following link
i want to go to next page of the following link

```<code><a href="javascript: __doPostBack('ctl00$PlaceHolderMain$g_781eb52f_faa9_4d59_9cae_2baec06ac484','dvt_firstrow={51};dvt_startposition={Paged=TRUE&p_Created_x0020_Date=6%2f9%2f2009%208%3a33%3a19%20AM&p_ID=216}');">
<img src="/_layouts/images/next.gif" border="0" alt="Next"></a></td></tr></table></div></td>
</code>```

how can i go next in java program

答:
Paged=TRUE&p_Created_x0020_Date=6%2f9%2f2009%208%3a33%3a19%20AM&p_ID=216

I guess Paged,p_Created_Date,p_ID are parameters you need to pass, to go to next page.

ContentLicense: CC BY-SA 2.5

Title: read the following link

Body:
i want to go to next page of the following link

how can i go next in java program