问:
Sort an integer array, keeping first in place
How would I sort arrays as follows:

```<code>[10, 7, 12, 3, 5, 6] --> [10, 12, 3, 5, 6, 7]

[12, 8, 5, 9, 6, 10] --> [12, 5, 6, 8, 9, 10]
</code>```

keeping array[0] in place

with the next highest integer(s) following (if there are any)

then ascending from the lowest integer

答:
An easy solution could be to sort the entire array and then partition the resulting array on basis of your initial first element.

I.e.

first sort [10, 7, 12, 3] to [3, 7, 10, 12]

then split it into >= 10 and < 10: [10, 12] and [3, 7]

and finally combine both to [10, 12, 3, 7]

Sample implementation without polish:

function customSort(input) {
  var firstElem = input[0];
  var sortedInput = input.sort(function(a, b) { return a-b; });
  var firstElemPos = sortedInput.indexOf(firstElem);
  var greaterEqualsFirstElem = sortedInput.splice(firstElemPos);
  var lessThanFirstElem = sortedInput.splice(0, firstElemPos);
  return greaterEqualsFirstElem.concat(lessThanFirstElem);
}

console.log(customSort([10, 7, 12, 3, 5, 6]));
console.log(customSort([12, 8, 5, 9, 6, 10]));
console.log(customSort([12, 8, 5, 9, 12, 6, 10]));
console.log(customSort([12]));
console.log(customSort([]));```

Body:
How would I sort arrays as follows:

[10, 7, 12, 3, 5, 6] --> [10, 12, 3, 5, 6, 7]

[12, 8, 5, 9, 6, 10] --> [12, 5, 6, 8, 9, 10]

keeping array[0] in place

with the next highest integer(s) following (if there are any)

then ascending from the lowest integer


来源: stackexchange

问:
Dashboard with selectable Google chart type
I am not familiar with google charts, so excuse me if this question is somehow too broad or senseless.

I am wondering how it is possible to create a google charts dashboard with the chart type selectable from a list of possible charts. For the same set of data, all the applicable chart types should be shown and the user selects the one he wants. Afterward, the data are automatically rendered according to the the chart selected.

For example, check Visualizing SPARQL query results in GraphDB, the results of any query could be visualized using a set of corresponding google charts that could be selected and even configured. To try it, on the top right corner of the query edit pane, there is a folder icon where you can select a saved query and then at the bottom of the pane select google charts and configure then render the results.

Is this a component that already exists and I can use? Any suggestions?

答:
you can use the ChartWrapper class from the 'controls' package

it has a property for chartType...

```<code>var chart = new google.visualization.ChartWrapper({
  chartType: 'BarChart',  // <-- chart type property
  containerId: 'chart',
  dataTable: data,
  options: {
    height: 240,
    theme: 'maximized'
  }
});
</code>```

see following working snippet, the chart type is changed by the <select>

google.charts.load('current', {
  callback: drawChart,
  packages: ['controls', 'corechart']
});

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['x', 'y0'],
    ['a', 898],
    ['b', 37319],
    ['c', 8980],
    ['d', 35400]
  ]);

  var chartType = document.getElementById('chart-type');
  var chartWrapper = new google.visualization.ChartWrapper({
    chartType: chartType.value,
    containerId: 'chart',
    dataTable: data,
    options: {
      height: 240,
      theme: 'maximized'
    }
  });
  chartType.addEventListener('change', drawChartWrapper, false);
  drawChartWrapper();

  function drawChartWrapper() {
    chartWrapper.setChartType(chartType.value);
    chartWrapper.draw();
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  padding: 6px;
}</code>```

  <select id="chart-type">
    <option value="BarChart" selected>Bar</option>
    <option value="ColumnChart">Column</option>
    <option value="LineChart">Line</option>
    <option value="PieChart">Pie</option>
  </select>

```

ContentLicense: CC BY-SA 3.0

Body:
you can use the ChartWrapper class from the 'controls' package

it has a property for chartType...

var chart = new google.visualization.ChartWrapper({
  chartType: 'BarChart',  // <-- chart type property
  containerId: 'chart',
  dataTable: data,
  options: {
    height: 240,
    theme: 'maximized'
  }
});

see following working snippet, the chart type is changed by the <select>

google.charts.load('current', {
  callback: drawChart,
  packages: ['controls', 'corechart']
});

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['x', 'y0'],
    ['a', 898],
    ['b', 37319],
    ['c', 8980],
    ['d', 35400]
  ]);

  var chartType = document.getElementById('chart-type');
  var chartWrapper = new google.visualization.ChartWrapper({
    chartType: chartType.value,
    containerId: 'chart',
    dataTable: data,
    options: {
      height: 240,
      theme: 'maximized'
    }
  });
  chartType.addEventListener('change', drawChartWrapper, false);
  drawChartWrapper();

  function drawChartWrapper() {
    chartWrapper.setChartType(chartType.value);
    chartWrapper.draw();
  }
}

div {
  padding: 6px;
}

<script src="https://www.gstatic.com/charts/loader.js"></script>
<div>
  <select id="chart-type">
    <option value="BarChart" selected>Bar</option>
    <option value="ColumnChart">Column</option>
    <option value="LineChart">Line</option>
    <option value="PieChart">Pie</option>
  </select>
</div>
<div id="chart"></div>


问:
Overloading + operator for arrays in groovy
I am a groovy newbie. Maybe this is a piece of cake, but I want to overload the + operator for arrays/lists to code like this</p>

```<code>def a= [1,1,1]
def b= [2,2,2]

assert [3,3,3] == a + b
</code>```

答:
I wouldn't recommend globally overriding well-established behaviors. But, if you insist, this will do as you ask:

```<code>ArrayList.metaClass.plus << {Collection b ->
    [delegate, b].transpose().collect{x, y -> x+y}
}
</code>```

A more localized alternative would be to use a category:

```<code>class PlusCategory{
    public static Collection plus(Collection a, Collection b){
        [a, b].transpose().collect{x, y -> x+y}
    }
}
use (PlusCategory){
    assert [3, 3, 3] == [1, 1, 1] + [2, 2, 2]
}
</code>```

However, I would probably create a generic zipWith method (as in functional programming), allowing one to easily specify different behaviors...

```<code>Collection.metaClass.zipWith = {Collection b, Closure c ->
    [delegate, b].transpose().collect(c)
}
assert [3, 3, 3] == [1, 1, 1].zipWith([2, 2, 2]){a, b -> a+b}
assert [2, 2, 2] == [1, 1, 1].zipWith([2, 2, 2]){a, b -> a*b}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am a groovy newbie. Maybe this is a piece of cake, but I want to overload the + operator for arrays/lists to code like this

def a= [1,1,1]
def b= [2,2,2]

assert [3,3,3] == a + b

Body:
I wouldn't recommend globally overriding well-established behaviors. But, if you insist, this will do as you ask:

ArrayList.metaClass.plus << {Collection b ->
    [delegate, b].transpose().collect{x, y -> x+y}
}

A more localized alternative would be to use a category:

class PlusCategory{
    public static Collection plus(Collection a, Collection b){
        [a, b].transpose().collect{x, y -> x+y}
    }
}
use (PlusCategory){
    assert [3, 3, 3] == [1, 1, 1] + [2, 2, 2]
}

However, I would probably create a generic zipWith method (as in functional programming), allowing one to easily specify different behaviors...

Collection.metaClass.zipWith = {Collection b, Closure c ->
    [delegate, b].transpose().collect(c)
}
assert [3, 3, 3] == [1, 1, 1].zipWith([2, 2, 2]){a, b -> a+b}
assert [2, 2, 2] == [1, 1, 1].zipWith([2, 2, 2]){a, b -> a*b}


问:
Trying to make my 2D character double jump - it's not working and I don't know why?
I'm making a 2D platformer. Here's my code so far. The character jumps only when touching the ground as it should - but the code for double jumping doesn't work. Any help is appreciated. I'm new at scripting and I don't understand what I did wrong?</p>

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour {

    public float speed = 12f, jumpHeight = 30f;
    Rigidbody2D playerBody;
    Transform playerTrans, tagGround;
    bool isGrounded = false;
    public LayerMask playerMask;
    public float maxJumps = 2;
    public float jumpsLeft = 2;

    // Use this for initialization
    void Start ()
    {
        playerBody = this.GetComponent<Rigidbody2D>();
        playerTrans = this.transform;
        tagGround = GameObject.Find(this.name + "/tag_Ground").transform;

    }

    // Update is called once per frame
    public void FixedUpdate ()
    {
        isGrounded = Physics2D.Linecast(playerTrans.position, tagGround.position, playerMask);
        Move();
        Jump();
        DoubleJump();

    }

    private void Move()
    {
        float move = Input.GetAxisRaw("Horizontal") * speed;
        playerBody.velocity = new Vector2(move, playerBody.velocity.y);
    }

    private void Jump()

    {
        if (isGrounded)
        {

            if (Input.GetButtonDown("Jump"))
            {
                playerBody.velocity = new Vector2(playerBody.velocity.x, jumpHeight);

            }

        }

    }
    private void DoubleJump()
    {
        if (Input.GetButtonDown("Jump") && jumpsLeft > 0)
        {
            Jump();
            jumpsLeft--;
        }

        if (isGrounded)
        {
            jumpsLeft = maxJumps;
        }
    }
}
</code>```

答:
Try replacing your Jump method code with the DoubleJump method's code and remove the check for IsGrounded before applying the jump. Otherwise your character has to be on the ground every time. Then remove the DoubleJump method as it is no longer needed. If you're utilizing the DoubleJump as an added skill later in your game then just increase maxJumps as your player earns the skill. Set it to 1 initially so that they have to hit the ground every time.</p>

```<code>        private void Jump() {
        if (isGrounded) {
            jumpsLeft = maxJumps;
        }
        if (Input.GetButtonDown("Jump") && jumpsLeft > 0) {
            playerBody.velocity = new Vector2(playerBody.velocity.x, jumpHeight);
            jumpsLeft--;
        }
    }
</code>```

Body:
I'm making a 2D platformer. Here's my code so far. The character jumps only when touching the ground as it should - but the code for double jumping doesn't work. Any help is appreciated. I'm new at scripting and I don't understand what I did wrong?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour {

    public float speed = 12f, jumpHeight = 30f;
    Rigidbody2D playerBody;
    Transform playerTrans, tagGround;
    bool isGrounded = false;
    public LayerMask playerMask;
    public float maxJumps = 2;
    public float jumpsLeft = 2;

    // Use this for initialization
    void Start ()
    {
        playerBody = this.GetComponent<Rigidbody2D>();
        playerTrans = this.transform;
        tagGround = GameObject.Find(this.name + "/tag_Ground").transform;

    }

    // Update is called once per frame
    public void FixedUpdate ()
    {
        isGrounded = Physics2D.Linecast(playerTrans.position, tagGround.position, playerMask);
        Move();
        Jump();
        DoubleJump();

    }

    private void Move()
    {
        float move = Input.GetAxisRaw("Horizontal") * speed;
        playerBody.velocity = new Vector2(move, playerBody.velocity.y);
    }

    private void Jump()

    {
        if (isGrounded)
        {

            if (Input.GetButtonDown("Jump"))
            {
                playerBody.velocity = new Vector2(playerBody.velocity.x, jumpHeight);

            }

        }

    }
    private void DoubleJump()
    {
        if (Input.GetButtonDown("Jump") && jumpsLeft > 0)
        {
            Jump();
            jumpsLeft--;
        }

        if (isGrounded)
        {
            jumpsLeft = maxJumps;
        }
    }
}

Body:
Try replacing your Jump method code with the DoubleJump method's code and remove the check for IsGrounded before applying the jump. Otherwise your character has to be on the ground every time. Then remove the DoubleJump method as it is no longer needed. If you're utilizing the DoubleJump as an added skill later in your game then just increase maxJumps as your player earns the skill. Set it to 1 initially so that they have to hit the ground every time.

        private void Jump() {
        if (isGrounded) {
            jumpsLeft = maxJumps;
        }
        if (Input.GetButtonDown("Jump") && jumpsLeft > 0) {
            playerBody.velocity = new Vector2(playerBody.velocity.x, jumpHeight);
            jumpsLeft--;
        }
    }


问:
auto Copy Filemaker data to MySQL
I'm new to File maker but not to databases.  I'm having trouble navigating my way around a prefab-ed File maker solution that we use for a specific business process.  I would like to get 2 fields out of a table and copy them to a MySQL table so that I can manipulate the data in a database that I am more familiar with.  Ideally I would like this to happen automatically when data is updated or daily at a specified time.

Basically I want to do what this SQL statement would to, then copy the results to another table (a MySQL table) and not alter the original data at all.

```<code>SELECT field1, field2 FROM fmTable WHERE field3 = 1
</code>```

I'd prefer to do this from MySQL through a connector so that I leave the original FM solution untouched, but if it is only possible to do the select and push from FM I can do it that way too.

I have access to File maker Pro, Pro Advanced, and FM Server; if any of that makes a difference or helps.

Any help is much appreciated

答:
You are not saying which FileMaker version you are using, but in general, if you set up your FileMaker Pro or Server as an ODBC source, you can access the data directly with SQL.

This article from FileMaker support describes how to set up the DSN and ODBC client driver.

Title: auto Copy Filemaker data to MySQL

Body:
I'm new to File maker but not to databases.  I'm having trouble navigating my way around a prefab-ed File maker solution that we use for a specific business process.  I would like to get 2 fields out of a table and copy them to a MySQL table so that I can manipulate the data in a database that I am more familiar with.  Ideally I would like this to happen automatically when data is updated or daily at a specified time.

Basically I want to do what this SQL statement would to, then copy the results to another table (a MySQL table) and not alter the original data at all.

SELECT field1, field2 FROM fmTable WHERE field3 = 1

I'd prefer to do this from MySQL through a connector so that I leave the original FM solution untouched, but if it is only possible to do the select and push from FM I can do it that way too.

I have access to File maker Pro, Pro Advanced, and FM Server; if any of that makes a difference or helps.

Any help is much appreciated


问:
T-SQL Combine Ranges Based On Value
I am using SQL Server 2012 and have been struggling with this query for hours.    I am trying to aggregate mile post ranges based off the value in the Value column. The results should have unique segments with the highest value from the Value field for each segment.  Here's an example:

```<code>Mile_Marker_Start | Mile_Marker_End | Value
      0                100              5
     50                150              6
    100                200             10
     75                300              9
    150                200              7
</code>```

And here's the result I'm looking for:

```<code>Mile_Marker_Start | Mile_Marker_End | Value
       0                 50             5
      50                 75             6
      75                100             9
     100                200            10
     200                300             9
</code>```

As you can see, the row with a value of 9 got split into 2 rows because Value 10 was bigger. Also, the row with Value 7 does not display because Value 10 was bigger.  Can this be done without using a cursor?  Any help would be much appreciated.

Thanks

答:
I believe the following now does what you need. I'd recommend running all the parts separately so you can see what they do and how they work.</p>

```<code>DECLARE @input AS TABLE
(Mile_Marker_Start int, Mile_Marker_End int, Value int)

INSERT INTO @input VALUES
(0,100,5), (50,150,6), (100,200,10), (75,300,9), (150,200,7)

DECLARE @staging as table
(Mile_Marker int)

INSERT INTO @staging
SELECT Mile_Marker_Start from @input
UNION -- this will remove duplicates
SELECT Mile_Marker_End from @input
; -- we need semi-colon for the following CTE

-- this CTE gets the right values, but the rows aren't "collapsed"
WITH all_markers AS
(
SELECT
    groups.Mile_Marker_Start,
    groups.Mile_Marker_End,
    max(i3.Value) Value
FROM
(
SELECT
    s1.Mile_Marker Mile_Marker_Start,
    min(s2.Mile_Marker) Mile_Marker_End
FROM
    @staging s1
    JOIN @staging s2 ON
        s1.Mile_Marker < s2.Mile_Marker
GROUP BY
   s1.Mile_Marker
) as groups
JOIN @input i3 ON
    i3.Mile_Marker_Start < groups.Mile_Marker_End AND
    i3.Mile_Marker_End > groups.Mile_Marker_Start
GROUP BY
    groups.Mile_Marker_Start,
    groups.Mile_Marker_End
)

SELECT
    MIN(collapse.Mile_Marker_Start) as Mile_Marker_Start,
    MAX(collapse.Mile_Marker_End) as Mile_Marker_End,
    collapse.Value
FROM
    (-- Subquery get's IDs for the groups we're collapsing together
    SELECT
        am.*,
        ROW_NUMBER() OVER (ORDER BY am.Mile_Marker_Start) - ROW_NUMBER() OVER (PARTITION BY am.Value ORDER BY am.Mile_Marker_Start) GroupID
    FROM
        all_markers am
    ) AS COLLAPSE
GROUP BY
    collapse.GroupID,
    collapse.Value
ORDER BY
    MIN(collapse.Mile_Marker_Start)
</code>```

Title: T-SQL Combine Ranges Based On Value

Body:
I am using SQL Server 2012 and have been struggling with this query for hours.    I am trying to aggregate mile post ranges based off the value in the Value column. The results should have unique segments with the highest value from the Value field for each segment.  Here's an example:

Mile_Marker_Start | Mile_Marker_End | Value
      0                100              5
     50                150              6
    100                200             10
     75                300              9
    150                200              7

And here's the result I'm looking for:

Mile_Marker_Start | Mile_Marker_End | Value
       0                 50             5
      50                 75             6
      75                100             9
     100                200            10
     200                300             9

As you can see, the row with a value of 9 got split into 2 rows because Value 10 was bigger. Also, the row with Value 7 does not display because Value 10 was bigger.  Can this be done without using a cursor?  Any help would be much appreciated.

Thanks

Body:
I believe the following now does what you need. I'd recommend running all the parts separately so you can see what they do and how they work.

DECLARE @input AS TABLE
(Mile_Marker_Start int, Mile_Marker_End int, Value int)

INSERT INTO @input VALUES
(0,100,5), (50,150,6), (100,200,10), (75,300,9), (150,200,7)

DECLARE @staging as table
(Mile_Marker int)

INSERT INTO @staging
SELECT Mile_Marker_Start from @input
UNION -- this will remove duplicates
SELECT Mile_Marker_End from @input
; -- we need semi-colon for the following CTE

-- this CTE gets the right values, but the rows aren't "collapsed"
WITH all_markers AS
(
SELECT
    groups.Mile_Marker_Start,
    groups.Mile_Marker_End,
    max(i3.Value) Value
FROM
(
SELECT
    s1.Mile_Marker Mile_Marker_Start,
    min(s2.Mile_Marker) Mile_Marker_End
FROM
    @staging s1
    JOIN @staging s2 ON
        s1.Mile_Marker < s2.Mile_Marker
GROUP BY
   s1.Mile_Marker
) as groups
JOIN @input i3 ON
    i3.Mile_Marker_Start < groups.Mile_Marker_End AND
    i3.Mile_Marker_End > groups.Mile_Marker_Start
GROUP BY
    groups.Mile_Marker_Start,
    groups.Mile_Marker_End
)

SELECT
    MIN(collapse.Mile_Marker_Start) as Mile_Marker_Start,
    MAX(collapse.Mile_Marker_End) as Mile_Marker_End,
    collapse.Value
FROM
    (-- Subquery get's IDs for the groups we're collapsing together
    SELECT
        am.*,
        ROW_NUMBER() OVER (ORDER BY am.Mile_Marker_Start) - ROW_NUMBER() OVER (PARTITION BY am.Value ORDER BY am.Mile_Marker_Start) GroupID
    FROM
        all_markers am
    ) AS COLLAPSE
GROUP BY
    collapse.GroupID,
    collapse.Value
ORDER BY
    MIN(collapse.Mile_Marker_Start)


问:
How to combine multiple arrays in one JSON object
I want to display multiple arrays into one such that each time the object is created it get a key value and then forms a object to be more specific following is a short example.

How it is now:

```<code>name:[{},{},{},{}]
surname:[{},{},{},{}]
phone: [{},{},{},{}]
</code>```

How I want it to be:

```<code>xyz:[{name:{}, surname{}, phone{}},
     {name:{}, surname{}, phone{}},
     {name:{}, surname{}, phone{}}]
</code>```

I am exporting this in php so that I can use this JSON object in AngularJs ng-repeat directive.

following is the code:

declaring array:

```<code>$name = array();
$surname= array();
$phone= array();
</code>```

assigning values WHICH IS UNDER FOR EACH LOOP

```<code>$name[] = $values ($values wil have the values for the loop)
.....
</code>```

testing output

```<code><?php echo json_encode($name);
    echo json_encode($surname);
    echo json_encode($phone);
?>
</code>```

答:
A simple way of doing it (run):

```<code>$name = array("name 1", "name 2");
$surname = array("surname 1", "surname 2");
$phone = array("phone 1", "phone 2");

$output = array();
for($i = 0; $i < count($name); $i++){
    $output[] = array(
            'name' => $name[$i],
            'surname' => $surname[$i],
            'phone' => $phone[$i],
        );
}

print_r($output);
</code>```

Output:

```<code>Array
(
    [0] => Array
        (
            [name] => name 1
            [surname] => surname 1
            [phone] => phone 1
        )

    [1] => Array
        (
            [name] => name 2
            [surname] => surname 2
            [phone] => phone 2
        )

)
</code>```

Note: It assumes all arrays are of same size and have same keys.

But maybe it would be better to instead of saving each value to 3 different variables and then running this script, try saving the values already into the array as the desired output (if possible, of course, since we can't know).

Body:
I want to display multiple arrays into one such that each time the object is created it get a key value and then forms a object to be more specific following is a short example.

How it is now:

name:[{},{},{},{}]
surname:[{},{},{},{}]
phone: [{},{},{},{}]

How I want it to be:

xyz:[{name:{}, surname{}, phone{}},
     {name:{}, surname{}, phone{}},
     {name:{}, surname{}, phone{}}]

I am exporting this in php so that I can use this JSON object in AngularJs ng-repeat directive.

following is the code:

declaring array:

$name = array();
$surname= array();
$phone= array();

assigning values WHICH IS UNDER FOR EACH LOOP

$name[] = $values ($values wil have the values for the loop)
.....

testing output

<?php echo json_encode($name);
    echo json_encode($surname);
    echo json_encode($phone);
?>

Body:
A simple way of doing it (run):

$name = array("name 1", "name 2");
$surname = array("surname 1", "surname 2");
$phone = array("phone 1", "phone 2");

$output = array();
for($i = 0; $i < count($name); $i++){
    $output[] = array(
            'name' => $name[$i],
            'surname' => $surname[$i],
            'phone' => $phone[$i],
        );
}

print_r($output);

Output:

Array
(
    [0] => Array
        (
            [name] => name 1
            [surname] => surname 1
            [phone] => phone 1
        )

    [1] => Array
        (
            [name] => name 2
            [surname] => surname 2
            [phone] => phone 2
        )

)

Note: It assumes all arrays are of same size and have same keys.

But maybe it would be better to instead of saving each value to 3 different variables and then running this script, try saving the values already into the array as the desired output (if possible, of course, since we can't know).


问:
SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value
I have created a new column in my database through a migration as below :

```<code>public function up(){
  Schema::table('complains', function (Blueprint $table) {
  $table->integer('user_id')->after('id');
   });
}
</code>```

When I fill in my form to post data into the database, I get the error below :

SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into complains (title, body, name, regnumber, updated_at, created_at) values (Testing user id, Testing user id, John, cs-282-2145/2010, 2017-06-08 18:47:53, 2017-06-08 18:47:53))

How do I fix this?

答:
Here is the code for my controller :

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Complain;
use Illuminate\Support\Facades\Redirect;
use Session;
use Auth;

class ComplainController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('home');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, array(

            'title' => 'required|max:255',
            'body' => 'required'

            ));

        $complain = new Complain;

        $complain->user_id = Auth::user()->id;

        $complain->title = $request->title;
        $complain->body = $request->body;

        $complain->save();

        Session::flash('success', 'Your complain was sent to the operator, please wait for feedback.');

        return redirect::back();
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $complain = Complain::find($id);
        return view('admin')->withPost($complain);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
</code>```

This is my model :

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Complain extends Model
{

}
</code>```

Body:
I have created a new column in my database through a migration as below :

public function up(){
  Schema::table('complains', function (Blueprint $table) {
  $table->integer('user_id')->after('id');
   });
}

When I fill in my form to post data into the database, I get the error below :

SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into complains (title, body, name, regnumber, updated_at, created_at) values (Testing user id, Testing user id, John, cs-282-2145/2010, 2017-06-08 18:47:53, 2017-06-08 18:47:53))

How do I fix this?

Body:
Here is the code for my controller :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Complain;
use Illuminate\Support\Facades\Redirect;
use Session;
use Auth;

class ComplainController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('home');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, array(

            'title' => 'required|max:255',
            'body' => 'required'

            ));

        $complain = new Complain;

        $complain->user_id = Auth::user()->id;

        $complain->title = $request->title;
        $complain->body = $request->body;

        $complain->save();

        Session::flash('success', 'Your complain was sent to the operator, please wait for feedback.');

        return redirect::back();
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $complain = Complain::find($id);
        return view('admin')->withPost($complain);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

This is my model :

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Complain extends Model
{

}


问:
Display records only if its belongs from table(1) in PHP
i have 2 tables which are join together with the help of UNION and display the records using single while loop.

problem:
now the problem is i want do display records from table(1) and table(2) separately but condition is using only single while loop.

here is the SQL:`

```<code>$sql =  "(SELECT * FROM subject_first WHERE date BETWEEN '$user_from' AND '$user_to') UNION (SELECT * FROM subject_second WHERE date BETWEEN '$user_from' AND '$user_to')";
</code>```

is there any way to do it?.sorry to say but i am new to PHP.
any advise is appreciated.

答:
Just add a field to both sides of the query:

```<code>(SELECT *, 'subject_first' as `table` FROM subject_first WHERE date BETWEEN '$user_from' AND '$user_to')
UNION
(SELECT *, 'subject_second' as `table` FROM subject_second WHERE date BETWEEN '$user_from' AND '$user_to')
ORDER BY `table`
</code>```

I added the order by part so you can insert a
 or whatever to split the results.

Body:
i have 2 tables which are join together with the help of UNION and display the records using single while loop.

problem:
now the problem is i want do display records from table(1) and table(2) separately but condition is using only single while loop.

here is the SQL:`

$sql =  "(SELECT * FROM subject_first WHERE date BETWEEN '$user_from' AND '$user_to') UNION (SELECT * FROM subject_second WHERE date BETWEEN '$user_from' AND '$user_to')";

is there any way to do it?.sorry to say but i am new to PHP.
any advise is appreciated.

Body:
Just add a field to both sides of the query:

(SELECT *, 'subject_first' as `table` FROM subject_first WHERE date BETWEEN '$user_from' AND '$user_to')
UNION
(SELECT *, 'subject_second' as `table` FROM subject_second WHERE date BETWEEN '$user_from' AND '$user_to')
ORDER BY `table`

I added the order by part so you can insert a <br> or whatever to split the results.


问:
ZF3 - composer require module -> module could not be initialised
I am working with the skeleton-application as a base, using the Vagrant / Composer setup. After the initial install I realised I would need the LDAP module. I then ran composer require zendframework/zend-ldap which ran successfully and I have located the files in ~/vendor/zendframework/zend-ldap.

The issue is when I add 'Zend\Ldap' to my ~/config/modules.config.php I encounter the following error:

```<code>Fatal error: Uncaught Zend\ModuleManager\Exception\RuntimeException: Module (Zend\Ldap) could not be initialized. in /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php:203 Stack trace: #0 /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php(175): Zend\ModuleManager\ModuleManager->loadModuleByName(Object(Zend\ModuleManager\ModuleEvent))
#1 /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php(97): Zend\ModuleManager\ModuleManager->loadModule('Zend\\Ldap') #2 /var/www/vendor/zendframework/zend-eventmanager/src/EventManager.php(322): Zend\ModuleManager\ModuleManager->onLoadModules(Object(Zend\ModuleManager\ModuleEvent))
#3 /var/www/vendor/zendframework/zend-eventmanager/src/EventManager.php(171): Zend\EventManager\EventManager->triggerListeners(Object(Zend\ModuleManager\ModuleEvent))
#4 /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php(120): Zend\EventManager\EventManager->triggerEvent(Object(Zend\ModuleManager\ModuleEvent))
#5 /var/www/vendor/zendfr in /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php on line 203
</code>```

The ~/config/modules.config.php file:

```<code>/**
 * List of enabled modules for this application.
 *
 * This should be an array of module namespaces used in the application.
 */
return [
    'Zend\Session',
    'Zend\Mvc\Plugin\Prg',
    'Zend\Mvc\Plugin\Identity',
    'Zend\Mvc\Plugin\FlashMessenger',
    'Zend\Mvc\Plugin\FilePrg',
    'Zend\Log',
    'Zend\Form',
    'Zend\Db',
    'Zend\Router',
    'Zend\Validator',
    'Zend\Ldap',    // All is well if this is commented out
    'Application',

];
</code>```

and the ~/config/application.config.php file:

```<code>/**
 * If you need an environment-specific system or application configuration,
 * there is an example in the documentation
 * @see https://docs.zendframework.com/tutorials/advanced-config/#environment-specific-system-configuration
 * @see https://docs.zendframework.com/tutorials/advanced-config/#environment-specific-application-configuration
 */
return [
    // Retrieve list of modules used in this application.
    'modules' => require __DIR__ . '/modules.config.php',

    // These are various options for the listeners attached to the ModuleManager
    'module_listener_options' => [
        // This should be an array of paths in which modules reside.
        // If a string key is provided, the listener will consider that a module
        // namespace, the value of that key the specific path to that module's
        // Module class.
        'module_paths' => [
            './module',
            './vendor',
        ],

        // An array of paths from which to glob configuration files after
        // modules are loaded. These effectively override configuration
        // provided by modules themselves. Paths may use GLOB_BRACE notation.
        'config_glob_paths' => [
            realpath(__DIR__) . '/autoload/{{,*.}global,{,*.}local}.php',
        ],

        // Whether or not to enable a configuration cache.
        // If enabled, the merged configuration will be cached and used in
        // subsequent requests.
        'config_cache_enabled' => true,

        // The key used to create the configuration cache file name.
        'config_cache_key' => 'application.config.cache',

        // Whether or not to enable a module class map cache.
        // If enabled, creates a module class map cache which will be used
        // by in future requests, to reduce the autoloading process.
        'module_map_cache_enabled' => true,

        // The key used to create the class map cache file name.
        'module_map_cache_key' => 'application.module.cache',

        // The path in which to cache merged configuration.
        'cache_dir' => 'data/cache/',

        // Whether or not to enable modules dependency checking.
        // Enabled by default, prevents usage of modules that depend on other modules
        // that weren't loaded.
        // 'check_dependencies' => true,
    ],

    // Used to create an own service manager. May contain one or more child arrays.
    // 'service_listener_options' => [
    //     [
    //         'service_manager' => $stringServiceManagerName,
    //         'config_key'      => $stringConfigKey,
    //         'interface'       => $stringOptionalInterface,
    //         'method'          => $stringRequiredMethodName,
    //     ],
    // ],

    // Initial configuration with which to seed the ServiceManager.
    // Should be compatible with Zend\ServiceManager\Config.
    // 'service_manager' => [],
];
</code>```

I have tried removing cache folder, running composer update, restarting Vagrant, adding the full path to the 'modules_path' array in application.config.php but it is always the same error. Interestingly I run into the same issue with 'Zend\View' that was included from the install, but a module such as 'Zend\Session' can be added to the modules.config.php file with no issues (They are all located in the vendor/zendframework directory)

Can anyone point me in the right direction to resolve this issue?

答:
zend-ldap doesn't have a src/Module.php file, so you can't add it as a module. Also it doesn't seem to include a standard factory so you need to write one yourself. More info on how to set it up:

https://zendframework.github.io/zend-ldap/intro/

Body:
I am working with the skeleton-application as a base, using the Vagrant / Composer setup. After the initial install I realised I would need the LDAP module. I then ran composer require zendframework/zend-ldap which ran successfully and I have located the files in ~/vendor/zendframework/zend-ldap.

The issue is when I add 'Zend\Ldap' to my ~/config/modules.config.php I encounter the following error:

Fatal error: Uncaught Zend\ModuleManager\Exception\RuntimeException: Module (Zend\Ldap) could not be initialized. in /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php:203 Stack trace: #0 /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php(175): Zend\ModuleManager\ModuleManager->loadModuleByName(Object(Zend\ModuleManager\ModuleEvent))
#1 /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php(97): Zend\ModuleManager\ModuleManager->loadModule('Zend\\Ldap') #2 /var/www/vendor/zendframework/zend-eventmanager/src/EventManager.php(322): Zend\ModuleManager\ModuleManager->onLoadModules(Object(Zend\ModuleManager\ModuleEvent))
#3 /var/www/vendor/zendframework/zend-eventmanager/src/EventManager.php(171): Zend\EventManager\EventManager->triggerListeners(Object(Zend\ModuleManager\ModuleEvent))
#4 /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php(120): Zend\EventManager\EventManager->triggerEvent(Object(Zend\ModuleManager\ModuleEvent))
#5 /var/www/vendor/zendfr in /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php on line 203

The ~/config/modules.config.php file:

/**
 * List of enabled modules for this application.
 *
 * This should be an array of module namespaces used in the application.
 */
return [
    'Zend\Session',
    'Zend\Mvc\Plugin\Prg',
    'Zend\Mvc\Plugin\Identity',
    'Zend\Mvc\Plugin\FlashMessenger',
    'Zend\Mvc\Plugin\FilePrg',
    'Zend\Log',
    'Zend\Form',
    'Zend\Db',
    'Zend\Router',
    'Zend\Validator',
    'Zend\Ldap',    // All is well if this is commented out
    'Application',

];

and the ~/config/application.config.php file:

/**
 * If you need an environment-specific system or application configuration,
 * there is an example in the documentation
 * @see https://docs.zendframework.com/tutorials/advanced-config/#environment-specific-system-configuration
 * @see https://docs.zendframework.com/tutorials/advanced-config/#environment-specific-application-configuration
 */
return [
    // Retrieve list of modules used in this application.
    'modules' => require __DIR__ . '/modules.config.php',

    // These are various options for the listeners attached to the ModuleManager
    'module_listener_options' => [
        // This should be an array of paths in which modules reside.
        // If a string key is provided, the listener will consider that a module
        // namespace, the value of that key the specific path to that module's
        // Module class.
        'module_paths' => [
            './module',
            './vendor',
        ],

        // An array of paths from which to glob configuration files after
        // modules are loaded. These effectively override configuration
        // provided by modules themselves. Paths may use GLOB_BRACE notation.
        'config_glob_paths' => [
            realpath(__DIR__) . '/autoload/{{,*.}global,{,*.}local}.php',
        ],

        // Whether or not to enable a configuration cache.
        // If enabled, the merged configuration will be cached and used in
        // subsequent requests.
        'config_cache_enabled' => true,

        // The key used to create the configuration cache file name.
        'config_cache_key' => 'application.config.cache',

        // Whether or not to enable a module class map cache.
        // If enabled, creates a module class map cache which will be used
        // by in future requests, to reduce the autoloading process.
        'module_map_cache_enabled' => true,

        // The key used to create the class map cache file name.
        'module_map_cache_key' => 'application.module.cache',

        // The path in which to cache merged configuration.
        'cache_dir' => 'data/cache/',

        // Whether or not to enable modules dependency checking.
        // Enabled by default, prevents usage of modules that depend on other modules
        // that weren't loaded.
        // 'check_dependencies' => true,
    ],

    // Used to create an own service manager. May contain one or more child arrays.
    // 'service_listener_options' => [
    //     [
    //         'service_manager' => $stringServiceManagerName,
    //         'config_key'      => $stringConfigKey,
    //         'interface'       => $stringOptionalInterface,
    //         'method'          => $stringRequiredMethodName,
    //     ],
    // ],

    // Initial configuration with which to seed the ServiceManager.
    // Should be compatible with Zend\ServiceManager\Config.
    // 'service_manager' => [],
];

I have tried removing cache folder, running composer update, restarting Vagrant, adding the full path to the 'modules_path' array in application.config.php but it is always the same error. Interestingly I run into the same issue with 'Zend\View' that was included from the install, but a module such as 'Zend\Session' can be added to the modules.config.php file with no issues (They are all located in the vendor/zendframework directory)

Can anyone point me in the right direction to resolve this issue?


问:
libxml/tree.h no such file or directory
I am getting following errors.

libxml/tree.h no such file or directory

I have already added libxml2.dylib to my project, however I am getting this type of trouble.
Please help me.

答: i tought i added wrongly, then i realize the problem is it not support arc, so check the support one here, life saver -> http://www.michaelbabiy.com/arc-compliant-gdataxml-library/</p>

Title: libxml/tree.h no such file or directory


问:
How to extract a line and a line before that based on certain strings
I am trying to extract lines containing a certain string also 4 lines before it (just the fourth line not the ones in between). Right now I can get the line itself;

```<code>grep -n "my string" myfile.out > output.txt
</code>```

I can also get the lines before it, but not that specific one, all the four preceding lines;

```<code>grep "my string" -B 4 myfile.out > output.txt
</code>```

Let's take this example:

```<code> ! CREEK
 FLUX 6739, 6670, 6640, 6672, 6582, 6583, 6548, 6576, 6570 &
 656565
 ***
 ***  THE SUM OF SPECIFIED:   -1.192451
 ***  THE AVERAGE:  -6.2760599E-02
 ***  THE MAXIMUM:    0.000000
 ***  THE MINIMUM:  -0.4294980
 ***  THE SUM OF POSITIVE:    0.000000
 ***  THE SUM OF NEGATIVE:   -1.192451
</code>```

I want this output:

```<code> ! CREEK
 ***  THE SUM OF SPECIFIED:   -1.192451
</code>```

I would appreciate windows-batch-file solution or PowerShell as well.

答:
Poweshell solution :</p>

```<code># verbose version
Select-String "THE SUM OF SPECIFIED" -Path "C:\temp\test.txt" -Context 4,0 | foreach { $_.Context.PreContext[0]; $_.Line}

# or short version (with alias)
sls "THE SUM OF SPECIFIED" "C:\temp\test.txt" -Co 4,0 | % { $_.Context.PreContext[0]; $_.Line}
</code>```

Body:
I am trying to extract lines containing a certain string also 4 lines before it (just the fourth line not the ones in between). Right now I can get the line itself;

grep -n "my string" myfile.out > output.txt

I can also get the lines before it, but not that specific one, all the four preceding lines;

grep "my string" -B 4 myfile.out > output.txt

Let's take this example:

 ! CREEK
 FLUX 6739, 6670, 6640, 6672, 6582, 6583, 6548, 6576, 6570 &
 656565
 ***
 ***  THE SUM OF SPECIFIED:   -1.192451
 ***  THE AVERAGE:  -6.2760599E-02
 ***  THE MAXIMUM:    0.000000
 ***  THE MINIMUM:  -0.4294980
 ***  THE SUM OF POSITIVE:    0.000000
 ***  THE SUM OF NEGATIVE:   -1.192451

I want this output:

 ! CREEK
 ***  THE SUM OF SPECIFIED:   -1.192451

I would appreciate windows-batch-file solution or PowerShell as well.

Body:
Poweshell solution :

# verbose version
Select-String "THE SUM OF SPECIFIED" -Path "C:\temp\test.txt" -Context 4,0 | foreach { $_.Context.PreContext[0]; $_.Line}

# or short version (with alias)
sls "THE SUM OF SPECIFIED" "C:\temp\test.txt" -Co 4,0 | % { $_.Context.PreContext[0]; $_.Line}


问:
Forcing the Qt GUI to update
I am coding a boardgame in Qt where, after the player makes a move, the computer AI must pause and think for some time. However, while it is thinking, it seems the screen will not be updated until every line of code has been executed. Thus, the user would click on a square, see nothing happen for a few seconds, and then suddenly see the result of both his move and the computer's move.

In an attempt to fix this, I tried creating a new thread on which the AI runs its code, and then places its piece on the board. However, sometimes (and this is very inconsistent) the game crashes after the computer has made a move.

So can you guys either:

Tell me how force the MainWindow to update its contents

Help me try to debug the crashing problem (I'm totally new to threads)

EDIT--I tried setting breakpoints as suszterpatt suggested, and the program seems to crash consistently in the debugger (it wasn't before I set the breakpoints).

Anyways, as I step through the program, it seems to go through the run function fine, until it reaches the ending bracket, and then if I step through it jumps into line 317 on qthread_win.cpp, which just says

```<code>finish(arg); //line 317
return 0;
</code>```

If I step through that line, the debugger freezes up and Qt alerts me after 20 seconds. If I continue, I get the "This application has requested the Runtime to terminate it in an unusual way" message that I get when the program occasionally crashes when I'm not debugging.

What should I do now?

答: Try moving your code out of the separate thread. Once you have it working you can try moving it back and you will know any issues are threading related. I think your updating issue will go away if it's all on the same thread.</p>

Title: Forcing the Qt GUI to update

Body:
I am coding a boardgame in Qt where, after the player makes a move, the computer AI must pause and think for some time. However, while it is thinking, it seems the screen will not be updated until every line of code has been executed. Thus, the user would click on a square, see nothing happen for a few seconds, and then suddenly see the result of both his move and the computer's move.

In an attempt to fix this, I tried creating a new thread on which the AI runs its code, and then places its piece on the board. However, sometimes (and this is very inconsistent) the game crashes after the computer has made a move.

So can you guys either:

Tell me how force the MainWindow to update its contents

Help me try to debug the crashing problem (I'm totally new to threads)

EDIT--I tried setting breakpoints as suszterpatt suggested, and the program seems to crash consistently in the debugger (it wasn't before I set the breakpoints).

Anyways, as I step through the program, it seems to go through the run function fine, until it reaches the ending bracket, and then if I step through it jumps into line 317 on qthread_win.cpp, which just says

finish(arg); //line 317
return 0;

If I step through that line, the debugger freezes up and Qt alerts me after 20 seconds. If I continue, I get the "This application has requested the Runtime to terminate it in an unusual way" message that I get when the program occasionally crashes when I'm not debugging.

What should I do now?


问:
Upload a CSV file and read it in Bokeh Web app
I have a Bokeh plotting app, and I need to allow the user to upload a CSV file and modify the plots according to the data in it.
Is it possible to do this with the available widgets of Bokeh?
Thank you very much. </p>

答:
Although there is no native Bokeh widget for file input. It is quite doable to extend the current tools provided by Bokeh. This answer will try to guide you through the steps of creating a custom widget and modifying the bokeh javascript to read, parse and output the file.

First though a lot of the credit goes to bigreddot's previous answer on creating the widget. I simply extended the coffescript in his answer to add a file handling function.

Now we begin by creating a new bokeh class on python which will link up to the javascript class and hold the information generated by the file input.

models.py

```<code>from bokeh.core.properties import List, String, Dict, Int
from bokeh.models import LayoutDOM

class FileInput(LayoutDOM):
__implementation__ = 'static/js/extensions_file_input.coffee'
__javascript__ = './input_widget/static/js/papaparse.js'

value = String(help="""
Selected input file.
""")

file_name = String(help="""
Name of the input file.
""")

accept = String(help="""
Character string of accepted file types for the input. This should be
written like normal html.
""")

data = List(Dict(keys_type=String, values_type=Int), default=[], help="""
List of dictionary containing the inputed data. This the output of the parser.
""")
</code>```

Then we create the coffeescript implementation for our new python class. In this new class, there is an added file handler function which triggers on change of the file input widget. This file handler uses PapaParse to parse the csv and then saves the result in the class's data property. The javascript for PapaParse can be downloaded on their website.

You can extend and modify the parser for your desired application and data format.

extensions_file_input.coffee

```<code>import * as p from "core/properties"
import {WidgetBox, WidgetBoxView} from "models/layouts/widget_box"

export class FileInputView extends WidgetBoxView

  initialize: (options) ->
    super(options)
    input = document.createElement("input")
    input.type = "file"
    input.accept = @model.accept
    input.id = @model.id
    input.style = "width:" + @model.width + "px"
    input.onchange = () =>
      @model.value = input.value
      @model.file_name = input.files[0].name
      @file_handler(input)
    @el.appendChild(input)

  file_handler: (input) ->
    file = input.files[0]
    opts =
      header: true,
      dynamicTyping: true,
      delimiter: ",",
      newline: "\r\n",
      complete: (results) =>
        input.data = results.data
        @.model.data = results.data
    Papa.parse(file, opts)

export class FileInput extends WidgetBox
  default_view: FileInputView
  type: "FileInput"
  @define {
    value: [ p.String ]
    file_name: [ p.String ]
    accept: [ p.String ]
    data : [ p.Array ]
  }
</code>```

A
Back on the python side we can then attach a bokeh on_change to our new input class to trigger when it's data property changes. This will happen after the csv parsing is done. This example showcases the desired interaction.

main.py

```<code>from bokeh.core.properties import List, String, Dict, Int
from bokeh.models import LayoutDOM

from bokeh.layouts import column
from bokeh.models import Button, ColumnDataSource
from bokeh.io import curdoc
from bokeh.plotting import Figure

import pandas as pd

from models import FileInput

# Starting data
x = [1, 2, 3, 4]
y = x

source = ColumnDataSource(data=dict(x=x, y=y))

plot = Figure(plot_width=400, plot_height=400)
plot.circle('x', 'y', source=source, color="navy", alpha=0.5, size=20)

button_input = FileInput(id="fileSelect",
                         accept=".csv")

def change_plot_data(attr, old, new):
    new_df = pd.DataFrame(new)
    source.data = source.from_df(new_df[['x', 'y']])

button_input.on_change('data', change_plot_data)

layout = column(plot, button_input)
curdoc().add_root(layout)
</code>```

An example of a .csv file for this application would be. Make sure there is no extra line at the end of the csv.

```<code>x,y
0,2
2,3
6,4
7,5
10,25
</code>```

To run this example properly, bokeh must be set up in it's proper application file tree format.

```<code>input_widget
   |
   +---main.py
   +---models.py
   +---static
        +---js
            +--- extensions_file_input.coffee
            +--- papaparse.js
</code>```

To run this example, you need to be in the directory above the top most file and execute bokeh serve input_widget in the terminal.

Body:
Although there is no native Bokeh widget for file input. It is quite doable to extend the current tools provided by Bokeh. This answer will try to guide you through the steps of creating a custom widget and modifying the bokeh javascript to read, parse and output the file.

First though a lot of the credit goes to bigreddot's previous answer on creating the widget. I simply extended the coffescript in his answer to add a file handling function.

Now we begin by creating a new bokeh class on python which will link up to the javascript class and hold the information generated by the file input.

models.py

from bokeh.core.properties import List, String, Dict, Int
from bokeh.models import LayoutDOM

class FileInput(LayoutDOM):
__implementation__ = 'static/js/extensions_file_input.coffee'
__javascript__ = './input_widget/static/js/papaparse.js'

value = String(help="""
Selected input file.
""")

file_name = String(help="""
Name of the input file.
""")

accept = String(help="""
Character string of accepted file types for the input. This should be
written like normal html.
""")

data = List(Dict(keys_type=String, values_type=Int), default=[], help="""
List of dictionary containing the inputed data. This the output of the parser.
""")

Then we create the coffeescript implementation for our new python class. In this new class, there is an added file handler function which triggers on change of the file input widget. This file handler uses PapaParse to parse the csv and then saves the result in the class's data property. The javascript for PapaParse can be downloaded on their website.

You can extend and modify the parser for your desired application and data format.

extensions_file_input.coffee

import * as p from "core/properties"
import {WidgetBox, WidgetBoxView} from "models/layouts/widget_box"

export class FileInputView extends WidgetBoxView

  initialize: (options) ->
    super(options)
    input = document.createElement("input")
    input.type = "file"
    input.accept = @model.accept
    input.id = @model.id
    input.style = "width:" + @model.width + "px"
    input.onchange = () =>
      @model.value = input.value
      @model.file_name = input.files[0].name
      @file_handler(input)
    @el.appendChild(input)

  file_handler: (input) ->
    file = input.files[0]
    opts =
      header: true,
      dynamicTyping: true,
      delimiter: ",",
      newline: "\r\n",
      complete: (results) =>
        input.data = results.data
        @.model.data = results.data
    Papa.parse(file, opts)

export class FileInput extends WidgetBox
  default_view: FileInputView
  type: "FileInput"
  @define {
    value: [ p.String ]
    file_name: [ p.String ]
    accept: [ p.String ]
    data : [ p.Array ]
  }

A
Back on the python side we can then attach a bokeh on_change to our new input class to trigger when it's data property changes. This will happen after the csv parsing is done. This example showcases the desired interaction.

main.py

from bokeh.core.properties import List, String, Dict, Int
from bokeh.models import LayoutDOM

from bokeh.layouts import column
from bokeh.models import Button, ColumnDataSource
from bokeh.io import curdoc
from bokeh.plotting import Figure

import pandas as pd

from models import FileInput

# Starting data
x = [1, 2, 3, 4]
y = x

source = ColumnDataSource(data=dict(x=x, y=y))

plot = Figure(plot_width=400, plot_height=400)
plot.circle('x', 'y', source=source, color="navy", alpha=0.5, size=20)

button_input = FileInput(id="fileSelect",
                         accept=".csv")

def change_plot_data(attr, old, new):
    new_df = pd.DataFrame(new)
    source.data = source.from_df(new_df[['x', 'y']])

button_input.on_change('data', change_plot_data)

layout = column(plot, button_input)
curdoc().add_root(layout)

An example of a .csv file for this application would be. Make sure there is no extra line at the end of the csv.

x,y
0,2
2,3
6,4
7,5
10,25

To run this example properly, bokeh must be set up in it's proper application file tree format.

input_widget
   |
   +---main.py
   +---models.py
   +---static
        +---js
            +--- extensions_file_input.coffee
            +--- papaparse.js

To run this example, you need to be in the directory above the top most file and execute bokeh serve input_widget in the terminal.


问:
Changed password in connectionstring not released by DLL
We have a DLL project for a web app project in a solution. The DLL has connectionstrings for each distinct connection used by our app, passed in as properties via a method in the DLL. This all works and has been in production for a few years. Recently after a UAT release in which the database was refreshed, we found that the connections defined within the app which reference the password via ASP:SqlDataSource tag in the ConnectionString property still work, whereas the ones called from the DLL all fail. We have recycled the App Pool, and deleted the files in the \bin directory and re-published them, still those connections all fail with "Could not connect to SQL" error thrown.

Has anyone experienced and already fixed this sort of issue? Or have any other ideas to try? Thanks.

答:
We got it sorted. The DBA team had changed the password, but there was another underlying issue within the application which did not present itself in an exception with details that matched the actual problem. We truncated and re-imported our user credentials table and now all methods in the DLL work as expected.

Our methods in the DLL are all internals, and the initialization method populates private static strings for each connection string. It was only one of these that failed, so we knew it wasn't the DLL at fault. Just had to isolate the root cause and remedy it to get passed the initial fear that somehow the DLL did not obtain the new password.


问:
Accessing private member variables from prototype-defined functions
Is there any way to make “private” variables (those defined in the constructor), available to prototype-defined methods?

```<code>TestClass = function(){
    var privateField = "hello";
    this.nonProtoHello = function(){alert(privateField)};
};
TestClass.prototype.prototypeHello = function(){alert(privateField)};
</code>```

This works:

```<code>t.nonProtoHello()
</code>```

But this doesn’t:

```<code>t.prototypeHello()
</code>```

I’m used to defining my methods inside the constructor, but am moving away from that for a couple reasons.

答:
```<code>var getParams = function(_func) {
  res = _func.toString().split('function (')[1].split(')')[0].split(',')
  return res
}

function TestClass(){

  var private = {hidden: 'secret'}
  //clever magic accessor thing goes here
  if ( !(this instanceof arguments.callee) ) {
    for (var key in arguments) {
      if (typeof arguments[key] == 'function') {
        var keys = getParams(arguments[key])
        var params = []
        for (var i = 0; i <= keys.length; i++) {
          if (private[keys[i]] != undefined) {
            params.push(private[keys[i]])
          }
        }
        arguments[key].apply(null,params)
      }
    }
  }
}

TestClass.prototype.test = function(){
  var _hidden; //variable I want to get
  TestClass(function(hidden) {_hidden = hidden}) //invoke magic to get
};

new TestClass().test()
</code>```

How's this? Using an private accessor. Only allows you to get the variables though not to set them, depends on the use case.

OwnerDisplayName: morgancodes

Body:
Is there any way to make “private” variables (those defined in the constructor), available to prototype-defined methods?

TestClass = function(){
    var privateField = "hello";
    this.nonProtoHello = function(){alert(privateField)};
};
TestClass.prototype.prototypeHello = function(){alert(privateField)};

This works:

t.nonProtoHello()

But this doesn’t:

t.prototypeHello()

I’m used to defining my methods inside the constructor, but am moving away from that for a couple reasons.

LastEditorDisplayName: Triptych

Body:
var getParams = function(_func) {
  res = _func.toString().split('function (')[1].split(')')[0].split(',')
  return res
}

function TestClass(){

  var private = {hidden: 'secret'}
  //clever magic accessor thing goes here
  if ( !(this instanceof arguments.callee) ) {
    for (var key in arguments) {
      if (typeof arguments[key] == 'function') {
        var keys = getParams(arguments[key])
        var params = []
        for (var i = 0; i <= keys.length; i++) {
          if (private[keys[i]] != undefined) {
            params.push(private[keys[i]])
          }
        }
        arguments[key].apply(null,params)
      }
    }
  }
}

TestClass.prototype.test = function(){
  var _hidden; //variable I want to get
  TestClass(function(hidden) {_hidden = hidden}) //invoke magic to get
};

new TestClass().test()

How's this? Using an private accessor. Only allows you to get the variables though not to set them, depends on the use case.


问:
Jackson: deserialize epoch to LocalDate
I have following JSON:

```<code>{
      "id" : "1",
      "birthday" : 401280850089
}
</code>```

And POJO class:

```<code>public class FbProfile {
    long id;
    @JsonDeserialize(using = LocalDateDeserializer.class)
    LocalDate birthday;
}
</code>```

I am using Jackson to do deserialization:

```<code>public FbProfile loadFbProfile(File file) throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    FbProfile profile = mapper.readValue(file, FbProfile.class);
    return profile;
}
</code>```

But it throws an exception:

com.fasterxml.jackson.databind.JsonMappingException: Unexpected token
  (VALUE_NUMBER_INT), expected VALUE_STRING: Expected array or string.

How can I deserialize epoch to LocalDate? I would like to add that if I change the datatype from LocalDate to java.util.Date it works perfectly fine. So maybe it's better to deserialize to java.util.Date and create the getter and setter which will do the conversion to/from LocalDate.

答:
I found a way to do it without writing a custom deserializer, but it'll require some modifications.

First, the LocalDateDeserializer accepts a custom DateTimeFormatter. So, we need to create a formatter that accepts an epoch millis. I did this by joining the INSTANT_SECONS and MILLI_OF_SECOND fields:

```<code>// formatter that accepts an epoch millis value
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    // epoch seconds
    .appendValue(ChronoField.INSTANT_SECONDS, 1, 19, SignStyle.NEVER)
    // milliseconds
    .appendValue(ChronoField.MILLI_OF_SECOND, 3)
    // create formatter, using UTC as timezone
    .toFormatter().withZone(ZoneOffset.UTC);
</code>```

I also set the formatter with UTC zone, so it won't be affected by timezones and DST changes.

Then, I've created the deserializer and registered in my ObjectMapper:

```<code>ObjectMapper mapper = new ObjectMapper();
JavaTimeModule module = new JavaTimeModule();
// add the LocalDateDeserializer with the custom formatter
module.addDeserializer(LocalDate.class, new LocalDateDeserializer(formatter));
mapper.registerModule(module);
</code>```

I also had to remove the annotation from the birthday field (because the annotation seems to override the module configuration):

```<code>public class FbProfile {
    long id;

    // remove @JsonDeserialize annotation
    LocalDate birthday;
}
</code>```

And now the big issue: as the DateTimeFormatter accepts only String as input, and the JSON contains a number in birthday field, I had to change the JSON:

```<code>{
  "id" : "1",
  "birthday" : "401280850089"
}
</code>```

Note that I changed birthday to a String (put the value between quotes).

With this, the LocalDate is read from JSON correctly:

```<code>FbProfile value = mapper.readValue(json, FbProfile.class);
System.out.println(value.getBirthday()); // 1982-09-19
</code>```

Notes:

I couldn't find a way to pass the number directly to the formatter (as it takes only String as input), so I had to change the number to be a String. If you don't want to do that, then you'll have to write a custom converter anyway.

You can replace ZoneOffset.UTC with any timezone you want (even ZoneId.systemDefault()), it'll depend on what your application needs. But as told in @Ole V.V.'s comment, the timezone might cause the date to change.

Title: Jackson: deserialize epoch to LocalDate

Body:
I have following JSON:

{
      "id" : "1",
      "birthday" : 401280850089
}

And POJO class:

public class FbProfile {
    long id;
    @JsonDeserialize(using = LocalDateDeserializer.class)
    LocalDate birthday;
}

I am using Jackson to do deserialization:

public FbProfile loadFbProfile(File file) throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    FbProfile profile = mapper.readValue(file, FbProfile.class);
    return profile;
}

But it throws an exception:

com.fasterxml.jackson.databind.JsonMappingException: Unexpected token
  (VALUE_NUMBER_INT), expected VALUE_STRING: Expected array or string.

How can I deserialize epoch to LocalDate? I would like to add that if I change the datatype from LocalDate to java.util.Date it works perfectly fine. So maybe it's better to deserialize to java.util.Date and create the getter and setter which will do the conversion to/from LocalDate.

Body:
I found a way to do it without writing a custom deserializer, but it'll require some modifications.

First, the LocalDateDeserializer accepts a custom DateTimeFormatter. So, we need to create a formatter that accepts an epoch millis. I did this by joining the INSTANT_SECONS and MILLI_OF_SECOND fields:

// formatter that accepts an epoch millis value
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    // epoch seconds
    .appendValue(ChronoField.INSTANT_SECONDS, 1, 19, SignStyle.NEVER)
    // milliseconds
    .appendValue(ChronoField.MILLI_OF_SECOND, 3)
    // create formatter, using UTC as timezone
    .toFormatter().withZone(ZoneOffset.UTC);

I also set the formatter with UTC zone, so it won't be affected by timezones and DST changes.

Then, I've created the deserializer and registered in my ObjectMapper:

ObjectMapper mapper = new ObjectMapper();
JavaTimeModule module = new JavaTimeModule();
// add the LocalDateDeserializer with the custom formatter
module.addDeserializer(LocalDate.class, new LocalDateDeserializer(formatter));
mapper.registerModule(module);

I also had to remove the annotation from the birthday field (because the annotation seems to override the module configuration):

public class FbProfile {
    long id;

    // remove @JsonDeserialize annotation
    LocalDate birthday;
}

And now the big issue: as the DateTimeFormatter accepts only String as input, and the JSON contains a number in birthday field, I had to change the JSON:

{
  "id" : "1",
  "birthday" : "401280850089"
}

Note that I changed birthday to a String (put the value between quotes).

With this, the LocalDate is read from JSON correctly:

FbProfile value = mapper.readValue(json, FbProfile.class);
System.out.println(value.getBirthday()); // 1982-09-19

Notes:

I couldn't find a way to pass the number directly to the formatter (as it takes only String as input), so I had to change the number to be a String. If you don't want to do that, then you'll have to write a custom converter anyway.

You can replace ZoneOffset.UTC with any timezone you want (even ZoneId.systemDefault()), it'll depend on what your application needs. But as told in @Ole V.V.'s comment, the timezone might cause the date to change.


问:
What would be the fastest way to concatenate three files in C#?
I need to concatenate 3 files using C#. A header file, content, and a footer file, but I want to do this as cool as it can be done.

Cool = really small code or really fast (non-assembly code).

答:
Another way....how about letting the OS do it for you?:</p>

```<code>ProcessStartInfo psi = new ProcessStartInfo("cmd.exe",
        String.Format(@" /c copy {0} + {1} + {2} {3}",
            file1, file2, file3, dest));
psi.UseShellExecute = false;
Process process = Process.Start(psi);
process.WaitForExit();
</code>```

OwnerDisplayName: Bobby Bruckovnic

LastEditorDisplayName: bdukes

Body:
Another way....how about letting the OS do it for you?:

ProcessStartInfo psi = new ProcessStartInfo("cmd.exe",
        String.Format(@" /c copy {0} + {1} + {2} {3}",
            file1, file2, file3, dest));
psi.UseShellExecute = false;
Process process = Process.Start(psi);
process.WaitForExit();

OwnerDisplayName: Kev


问:
Column position out of range, ResultSet is '0'
Everything just worked don't know what I did ,but I keep getting the error when wanting to UPDATE information in my SQL database. Error : The column position '1' is out of range.  The number of columns for this ResultSet is '0'</p>

```<code>try
{
     String em = EmailField.getText();
     String na = NameField.getText();
     String su = SurnameField.getText();
     String i = IDField.getText();
     String ce = CellField.getText();

     String query2 = "UPDATE LouwDataBase.Table1Test "
                    + "SET Email = "+"'"+em+"'"+" , "
                    + "Name = "+"'"+na+"'"+" , "
                    + "Surname = "+"'"+su+"'"+" , "
                    + "ID = "+"'"+i+"'"+" , "
                    + "Cell = "+"'"+ce+"'"
                    + " WHERE Email = "+"'"+UserEmailID+"'";

      conn = DriverManager.getConnection("jdbc:derby://localhost:1527/MyDataBase", "LouwDataBase", "1234");
      stat = conn.createStatement();

      try (Connection conn = this.connect();
      PreparedStatement pstmt = conn.prepareStatement(query2))
      {
            pstmt.setString(1, em);
            pstmt.setString(3, na);
            pstmt.setString(4, su);
            pstmt.setString(5, i);
            pstmt.setString(6, ce);
            pstmt.executeUpdate();
       }
       catch (SQLException e)
       {
            System.out.println(e.getMessage());
       }
}
</code>```

答:
Since you're using PreparedStatement, I think you need to have question marks in the query and then use pstmt.setString().

```<code>try {
  String em = EmailField.getText();
  String na = NameField.getText();
  String su = SurnameField.getText();
  String i = IDField.getText();
  String ce = CellField.getText();

  String query2 = "UPDATE LouwDataBase.Table1Test "
                 + "SET Email = ?, "
                 + "Name = ?, "
                 + "Surname = ?, "
                 + "ID = ?, "
                 + "Cell = ?"
                 + " WHERE Email = ?";

  conn = DriverManager.getConnection("jdbc:derby://localhost:1527/MyDataBase", "LouwDataBase", "1234");
  stat = conn.createStatement();

  try (Connection conn = this.connect();
  PreparedStatement pstmt = conn.prepareStatement(query2)) {
      pstmt.setString(1, em);
      pstmt.setString(3, na);
      pstmt.setString(4, su);
      pstmt.setString(5, i);
      pstmt.setString(6, ce);
      pstmt.executeUpdate();
   }
   catch (SQLException e) {
      System.out.println(e.getMessage());
   }
}
</code>```

Body:
Everything just worked don't know what I did ,but I keep getting the error when wanting to UPDATE information in my SQL database. Error : The column position '1' is out of range.  The number of columns for this ResultSet is '0'

try
{
     String em = EmailField.getText();
     String na = NameField.getText();
     String su = SurnameField.getText();
     String i = IDField.getText();
     String ce = CellField.getText();

     String query2 = "UPDATE LouwDataBase.Table1Test "
                    + "SET Email = "+"'"+em+"'"+" , "
                    + "Name = "+"'"+na+"'"+" , "
                    + "Surname = "+"'"+su+"'"+" , "
                    + "ID = "+"'"+i+"'"+" , "
                    + "Cell = "+"'"+ce+"'"
                    + " WHERE Email = "+"'"+UserEmailID+"'";

      conn = DriverManager.getConnection("jdbc:derby://localhost:1527/MyDataBase", "LouwDataBase", "1234");
      stat = conn.createStatement();

      try (Connection conn = this.connect();
      PreparedStatement pstmt = conn.prepareStatement(query2))
      {
            pstmt.setString(1, em);
            pstmt.setString(3, na);
            pstmt.setString(4, su);
            pstmt.setString(5, i);
            pstmt.setString(6, ce);
            pstmt.executeUpdate();
       }
       catch (SQLException e)
       {
            System.out.println(e.getMessage());
       }
}

Body:
Since you're using PreparedStatement, I think you need to have question marks in the query and then use pstmt.setString().

try {
  String em = EmailField.getText();
  String na = NameField.getText();
  String su = SurnameField.getText();
  String i = IDField.getText();
  String ce = CellField.getText();

  String query2 = "UPDATE LouwDataBase.Table1Test "
                 + "SET Email = ?, "
                 + "Name = ?, "
                 + "Surname = ?, "
                 + "ID = ?, "
                 + "Cell = ?"
                 + " WHERE Email = ?";

  conn = DriverManager.getConnection("jdbc:derby://localhost:1527/MyDataBase", "LouwDataBase", "1234");
  stat = conn.createStatement();

  try (Connection conn = this.connect();
  PreparedStatement pstmt = conn.prepareStatement(query2)) {
      pstmt.setString(1, em);
      pstmt.setString(3, na);
      pstmt.setString(4, su);
      pstmt.setString(5, i);
      pstmt.setString(6, ce);
      pstmt.executeUpdate();
   }
   catch (SQLException e) {
      System.out.println(e.getMessage());
   }
}


问:
How to setup buttons with "imBack" type in Slack channel using ms bot builder
I've developed few bots using ms botbuilder, there was no problems with Buttons with "imBack" type on Skype, FB, Telegram and web chat.
However trying to make it work on Slack i found (and seems like its not documented) that you need extra configuring of Interactive Messages in APP admin panel. So here's my questions regarding this issue:

is it true that its the only way?

If so what's the real reason for that, everything works just fine in all   other channels.

Is there a way to setup it programmatically, cos it will be real bad for distribution of bot?

even when i setup endpoint in admin panel looks like it makes request that is barely compatible with how ms builder works (it sends some GET where we need post with relevant info)

Code sample:

```<code>...
var reply = activity.CreateReply("hi, can i ask you few question?");

reply.Attachments = new List<Attachment>(){};
var buttonSelect = new CardAction
{
    Value = $" /startCommand",
    Type = "imBack",
    Title = "ok, ask me"
};

var cardForButton = new ThumbnailCard { Buttons = new List<CardAction> { buttonSelect } };
reply.Attachments.Add(cardForButton.ToAttachment());

await connector.Conversations.CreateDirectConversationAsync(botaccount, userAccount, reply);
...
</code>```

答:
2 things you can try that are possible solutions

You probably did, but did you activate interactive messages in your slack api dashboard?

There is a token (Verification Token)  that you need to get from the oauth section of the Slack api site for your app.  you need to include that with the other information here https://slack.botframework.com/Dev/?botId={yourBotID}

Body:
I've developed few bots using ms botbuilder, there was no problems with Buttons with "imBack" type on Skype, FB, Telegram and web chat.
However trying to make it work on Slack i found (and seems like its not documented) that you need extra configuring of Interactive Messages in APP admin panel. So here's my questions regarding this issue:

is it true that its the only way?

If so what's the real reason for that, everything works just fine in all   other channels.

Is there a way to setup it programmatically, cos it will be real bad for distribution of bot?

even when i setup endpoint in admin panel looks like it makes request that is barely compatible with how ms builder works (it sends some GET where we need post with relevant info)

Code sample:

...
var reply = activity.CreateReply("hi, can i ask you few question?");

reply.Attachments = new List<Attachment>(){};
var buttonSelect = new CardAction
{
    Value = $" /startCommand",
    Type = "imBack",
    Title = "ok, ask me"
};

var cardForButton = new ThumbnailCard { Buttons = new List<CardAction> { buttonSelect } };
reply.Attachments.Add(cardForButton.ToAttachment());

await connector.Conversations.CreateDirectConversationAsync(botaccount, userAccount, reply);
...


问:
How to access environment variable externally in spring boot?
Is it possible to access environment variable of different application.properties from a single place. Actually we are building this software where we have different application.properties for different projects like user-asset. So is it possible to have all environment variable at one external place. If yes, how will it be accessed?</p>

答:
You would have an application.properties file that defines variables that would never change in what every situation you have.

application.properties

```<code>server.error.whitelabel.enabled=true #Just an example
</code>```

Then you could have a separate application.properties with a different name such as application-active.properties. This file would add onto the base application.properties file.

application-active.properties

```<code>example.enviroment.variable=${I_AM_AN_ENVIROMENT_VARIABLE}
</code>```

Then you could have a different application.properties file that has the same property name, in this case example.enviroment.variable.

application-dev.properties

```<code>example.enviroment.variable=${I_AM_A_DIFFERENT_ENVIRONMENT_VARIABLE}
</code>```

Then in your code, you would just need to grab the example.enviroment.variable property depending on the current profile and it would grab the correct environment variable.

To specify what application.properites look at using profiles in spring-boot.

Body:
You would have an application.properties file that defines variables that would never change in what every situation you have.

application.properties

server.error.whitelabel.enabled=true #Just an example

Then you could have a separate application.properties with a different name such as application-active.properties. This file would add onto the base application.properties file.

application-active.properties

example.enviroment.variable=${I_AM_AN_ENVIROMENT_VARIABLE}

Then you could have a different application.properties file that has the same property name, in this case example.enviroment.variable.

application-dev.properties

example.enviroment.variable=${I_AM_A_DIFFERENT_ENVIRONMENT_VARIABLE}

Then in your code, you would just need to grab the example.enviroment.variable property depending on the current profile and it would grab the correct environment variable.

To specify what application.properites look at using profiles in spring-boot.


问:
React Redux action payload not in componentDidMount
I have an action creator that I'm calling in componentWillMount, the return of that action payload is being assigned to state using setState. However, in componentDidMount I cannot access that property as the async call hasn't completed yet. What is the correct way to access this data in compoentDidMount?</p>

```<code>//component
class Dashboard extends Component {

componentWillMount() {
    this.setState(this.props.getUser());
  }

componentDidMount() {
    // this.state.user isn't available yet
}

render(){
  return(...);
}
}

//action
export function getUser() {
  return async function (dispatch) {
     const user = await axios.get(`${API_URL}user?token=${token}`);
     return dispatch({
      type: USER,
      payload: user,
     });
    }
  };
}
</code>```

答:
You need to use componentWillReceiveProps to do that, for example:

```<code>componentWillReceiveProps(nextProps) {
   if (nextProps.user !== this.state.user) {
       this.setState({
           user: nextProps.user
       });
   }
}
</code>```

now you can use user inside your component.

Here you can find more information.

Body:
I have an action creator that I'm calling in componentWillMount, the return of that action payload is being assigned to state using setState. However, in componentDidMount I cannot access that property as the async call hasn't completed yet. What is the correct way to access this data in compoentDidMount?

//component
class Dashboard extends Component {

componentWillMount() {
    this.setState(this.props.getUser());
  }

componentDidMount() {
    // this.state.user isn't available yet
}

render(){
  return(...);
}
}

//action
export function getUser() {
  return async function (dispatch) {
     const user = await axios.get(`${API_URL}user?token=${token}`);
     return dispatch({
      type: USER,
      payload: user,
     });
    }
  };
}

Body:
You need to use componentWillReceiveProps to do that, for example:

componentWillReceiveProps(nextProps) {
   if (nextProps.user !== this.state.user) {
       this.setState({
           user: nextProps.user
       });
   }
}

now you can use user inside your component.

Here you can find more information.


问:
Angular/TypeScript/RxJS - I've tried all renditions of map, concat, merge etc - trying to get nested items in array
Currently the following final lines (after retrieving from an Observable.forkJoin of 17 this.http.get requests):

```<code>        .map(data => Observable.from(data))
        .finally(() => { console.log(this.topicData) })
        .subscribe((data) => { this.topicData = data });
</code>```

And the console.log above you see gives me data in the following format:

As you can see, this has arrays within arrays.  I just want a single Observable array with the Objects nested two layers within shell arrays.  Again, I have tried all the maps, concat, reduce, merge etc.  With RxJS I feel like I just plug things in until it works.  When I read the documentation, I have difficulty understanding how it relates to what I am trying to do (training resources are welcome also).  For this problem in particular, does anybody know how I can return a single Observable array with the Objects?

Update with additional code from forkJoin:

```<code>return Observable.forkJoin(
            this.http.get(this.baseUrl + webs[0] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[1] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[2] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[3] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[4] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[5] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[6] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[7] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[8] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[9] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[10] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[11] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[12] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[13] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[14] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[15] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[16] + this.topicsRest, this.options).map((res: Response) => res.json().d.results)
        )
</code>```

答:
I tried something different to your approach, basically I flat the collections into a single array. Check:

http://plnkr.co/edit/c6lwtmYC91Yj4ji80CEa

```<code>interface Data {
  text: string;
  val: number;
};

// this could be a service method
method(): Observable<Data[]> {
    let example: Observable<Data[]>;
    const webs = [1, 2, 3];
    //created fake Observables with test data
    const source = forkJoin(webs.map(val => of<Data[]>([{ text: '1rst', val: val + 1 }, { text: '2nd', val: val + 2 }])));
    example = source.mergeMap(data => data).mergeMap(data => data).toArray();
    return example;
  }
</code>```

With this you will get an Observable that emits a single array with all the elements in the different arrays.

Hope it helps!

Body:
Currently the following final lines (after retrieving from an Observable.forkJoin of 17 this.http.get requests):

        .map(data => Observable.from(data))
        .finally(() => { console.log(this.topicData) })
        .subscribe((data) => { this.topicData = data });

And the console.log above you see gives me data in the following format:

As you can see, this has arrays within arrays.  I just want a single Observable array with the Objects nested two layers within shell arrays.  Again, I have tried all the maps, concat, reduce, merge etc.  With RxJS I feel like I just plug things in until it works.  When I read the documentation, I have difficulty understanding how it relates to what I am trying to do (training resources are welcome also).  For this problem in particular, does anybody know how I can return a single Observable array with the Objects?

Update with additional code from forkJoin:

return Observable.forkJoin(
            this.http.get(this.baseUrl + webs[0] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[1] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[2] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[3] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[4] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[5] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[6] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[7] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[8] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[9] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[10] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[11] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[12] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[13] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[14] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[15] + this.topicsRest, this.options).map((res: Response) => res.json().d.results),
            this.http.get(this.baseUrl + webs[16] + this.topicsRest, this.options).map((res: Response) => res.json().d.results)
        )

Body:
I tried something different to your approach, basically I flat the collections into a single array. Check:

http://plnkr.co/edit/c6lwtmYC91Yj4ji80CEa

interface Data {
  text: string;
  val: number;
};

// this could be a service method
method(): Observable<Data[]> {
    let example: Observable<Data[]>;
    const webs = [1, 2, 3];
    //created fake Observables with test data
    const source = forkJoin(webs.map(val => of<Data[]>([{ text: '1rst', val: val + 1 }, { text: '2nd', val: val + 2 }])));
    example = source.mergeMap(data => data).mergeMap(data => data).toArray();
    return example;
  }

With this you will get an Observable that emits a single array with all the elements in the different arrays.

Hope it helps!


问:
Why is this returning a value in Javascript's REPL?
When I execute this expression in Javascript's REPL (browser's console or node)

if(false) {4} else {5}

it returns 5 but I don't understand why.

An if isn't returning anything, for exemple I can't do:

var foo = if(false) {4} else {5}

So why does REPL return a value?

答:
It is true that if statements are statements and do not have a "value". In a normal JS script, nothing would happen when if(false) {4} else {5} is evaluated.

What consoles usually give you as a return value is the value of the last evaluated expression.

In your case, 5 is evaluated and returned.


问:
I am having issues instantiating a new client, how can I instantiate a new client?
My compiler returns errors saying I should pass in a key when I instantiate a new client, it says I should pass in a key when I instantiate a client.

I also get an error saying $token is not defined.

Please review the below code

```<code>var stream = require('getstream');
// Instantiate a new client (server side)
client = stream.connect('q3nwu4pbz222', '(secret)', '25553');
// Instantiate a new client (client side)
client = stream.connect('q3nwu4pbz222', null, '25553');
// Find your API keys here https://getstream.io/dashboard/

// Instantiate a feed using feed class 'user' and user id '1'
var user1 = client.feed('user', '1', token);

// Instantiate a feed for feed group 'user', user id '1' and a security token generated server side
user1 = client.feed('user', '1', $token);
</code>```

答:
JavaScript doesn't use $ prefixes for variables, but the example code you've given above also does not build a variable called token of any kind.

There are two client connections you can make with the stream-js library:

One happens in your Node.js application that runs on the server, and that one you would pass your API key and API secret. This gives you a read-write connection to Stream to read feeds but also to write activities, perform follow relationships, and to delete/update activities and unfollow other feeds, etc.

The other client would happen in the browser (where your API secret is null) but requires a token that gets generated by your back-end/server application and allows a read-only connection to Stream over websockets for real-time notifications. Your account has a limit on how many active websocket connections your browser clients can make to Stream.

As far as generating the token for the websocket connection, you would use code like this on the server-side:

```<code>backendClient = stream.connect(<API_KEY>, <API_SECRET>, <APP_ID>)
readonlyToken = backendClient.feed('user', '1').getReadOnlyToken();
</code>```

This generates a read-only token for the user:1 feed but cannot perform write functions like adding/editing/updating activity data or follow/unfollows, etc..

Then, you'd get that token to your front-end browser/client however you like. From there, then, the front-end client would make a connection to Stream using code like this:

```<code>browserClient = stream.connect('q3nwu4pbz222', null, '25553');
user1 = browserClient.feed('user', '1', readonlyToken);
user1.get({limit:5}, callbackWhenFinished);
</code>```

Body:
My compiler returns errors saying I should pass in a key when I instantiate a new client, it says I should pass in a key when I instantiate a client.

I also get an error saying $token is not defined.

Please review the below code

var stream = require('getstream');
// Instantiate a new client (server side)
client = stream.connect('q3nwu4pbz222', '(secret)', '25553');
// Instantiate a new client (client side)
client = stream.connect('q3nwu4pbz222', null, '25553');
// Find your API keys here https://getstream.io/dashboard/

// Instantiate a feed using feed class 'user' and user id '1'
var user1 = client.feed('user', '1', token);

// Instantiate a feed for feed group 'user', user id '1' and a security token generated server side
user1 = client.feed('user', '1', $token);

Body:
JavaScript doesn't use $ prefixes for variables, but the example code you've given above also does not build a variable called token of any kind.

There are two client connections you can make with the stream-js library:

One happens in your Node.js application that runs on the server, and that one you would pass your API key and API secret. This gives you a read-write connection to Stream to read feeds but also to write activities, perform follow relationships, and to delete/update activities and unfollow other feeds, etc.

The other client would happen in the browser (where your API secret is null) but requires a token that gets generated by your back-end/server application and allows a read-only connection to Stream over websockets for real-time notifications. Your account has a limit on how many active websocket connections your browser clients can make to Stream.

As far as generating the token for the websocket connection, you would use code like this on the server-side:

backendClient = stream.connect(<API_KEY>, <API_SECRET>, <APP_ID>)
readonlyToken = backendClient.feed('user', '1').getReadOnlyToken();

This generates a read-only token for the user:1 feed but cannot perform write functions like adding/editing/updating activity data or follow/unfollows, etc..

Then, you'd get that token to your front-end browser/client however you like. From there, then, the front-end client would make a connection to Stream using code like this:

browserClient = stream.connect('q3nwu4pbz222', null, '25553');
user1 = browserClient.feed('user', '1', readonlyToken);
user1.get({limit:5}, callbackWhenFinished);


问:
SQL and ASP.NET WHERE IN generates wrong
I have this line of code:

```<code>sql += " AND lc.name IN ('" + String.Join(",", id.type.ToArray()) + "')";
</code>```

There are two items in id.type and this code generates this:

```<code>AND lc.name IN ('towns back to back,towns 3 storey')
</code>```

Which will not work because it should be like this:

```<code>AND lc.name IN ('towns back to back' , 'towns 3 storey')
</code>```

How can I fix this?

答:
This is not a desirable approach, because it's open to SQL injection.  But there are a few things:

You have to accommodate for strings that contain single quotes.

It won't work if you just concatenate.  You have to wrap EACH item in single quotes.

Try:

```<code>sql += " AND lc.name IN (" + String.Join(",", id.type.ToArray().Select(i=>String.Format(i.Replace("'","''"),"'{0}'")) + ")";
</code>```

Body:
I have this line of code:

sql += " AND lc.name IN ('" + String.Join(",", id.type.ToArray()) + "')";

There are two items in id.type and this code generates this:

AND lc.name IN ('towns back to back,towns 3 storey')

Which will not work because it should be like this:

AND lc.name IN ('towns back to back' , 'towns 3 storey')

How can I fix this?

Body:
This is not a desirable approach, because it's open to SQL injection.  But there are a few things:

You have to accommodate for strings that contain single quotes.

It won't work if you just concatenate.  You have to wrap EACH item in single quotes.

Try:

sql += " AND lc.name IN (" + String.Join(",", id.type.ToArray().Select(i=>String.Format(i.Replace("'","''"),"'{0}'")) + ")";