问:
Unknown Property – yii\base\UnknownPropertyException
I got the error in the title when trying to display a relational field in the gridview.
I have the problem with statuscode.statusname.

What do I miss?
Thanks in advance!

My Projectsearch model:

```<code><?php namespace frontend\models;

use yii\base\Model;
use yii\data\ActiveDataProvider;
use frontend\models\Project;

class ProjectSearch extends Project
{
/**
 * {@inheritdoc}
 */
public function rules()
{
    return [
        [['id', 'client_id', 'status_id'], 'integer'],
        [['number', 'name'], 'safe'],
        [['client.name'], 'safe'],
        [['statuscode.statusname'], 'safe'],
    ];
}

/**
 * {@inheritdoc}
 */
public function scenarios()
{
    // bypass scenarios() implementation in the parent class
    return Model::scenarios();
}

public function attributes()
{
    // add related fields to searchable attributes
    return array_merge(parent::attributes(), ['client.name']);
    return array_merge(parent::attributes(), ['statuscode.statusname']);
}

/**
 * Creates data provider instance with search query applied
 *
 * @param array $params
 *
 * @return ActiveDataProvider
 */
public function search($params)
{
    $query = Project::find();

    // add conditions that should always apply here

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);

    $dataProvider->sort->attributes['client.name'] = [
        'asc' => ['client.name' => SORT_ASC],
        'desc' => ['client.name' => SORT_DESC],
    ];

    $dataProvider->sort->attributes['statuscode.statusname'] = [
        'asc' => ['statuscode.statusname' => SORT_ASC],
        'desc' => ['statuscode.statusname' => SORT_DESC],
    ];

    $this->load($params);

    if (!$this->validate()) {
        // uncomment the following line if you do not want to return any records when validation fails
        // $query->where('0=1');
        return $dataProvider;
    }

    $query->joinWith(['client' => function($query) {
    $query->from(['client' => 'clients']); }]);
    $query->joinWith(['statuscode' => function($query) { $query->from(['statuscode' => 'statuses']); }]);

    // grid filtering conditions

    $query->andFilterWhere(['like', 'project.number', $this->number])
        ->andFilterWhere(['like', 'project.name', $this->name])
        ->andFilterWhere(['LIKE', 'client.name', $this->getAttribute('client.name')])
        ->andFilterWhere(['LIKE', 'statuscode.statusname', $this->getAttribute('statuscode.statusname')]);
    return $dataProvider;
}
}
</code>```

My view:

```<code><?php

use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;

$this->title = 'Projects';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="project-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php Pjax::begin(); ?>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p><?= Html::a('Create Project', ['create'], ['class' => 'btn btn-success']) ?></p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'number',
'client.name',
'name',
    [
    'attribute' => 'statuscode.statusname',
    'label' => 'Projectstatus',
    ],
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
<?php Pjax::end(); ?>
</div>
</code>```

答:
Nevermind, i got it! :)

```<code>return array_merge(parent::attributes(), ['client.name', 'statuscode.statusname']);
</code>```

instead of:

```<code>return array_merge(parent::attributes(), ['client.name']);
return array_merge(parent::attributes(), ['statuscode.statusname']);
</code>```

LOL

Body:
I got the error in the title when trying to display a relational field in the gridview.
I have the problem with statuscode.statusname.

What do I miss?
Thanks in advance!

My Projectsearch model:

<?php namespace frontend\models;

use yii\base\Model;
use yii\data\ActiveDataProvider;
use frontend\models\Project;

class ProjectSearch extends Project
{
/**
 * {@inheritdoc}
 */
public function rules()
{
    return [
        [['id', 'client_id', 'status_id'], 'integer'],
        [['number', 'name'], 'safe'],
        [['client.name'], 'safe'],
        [['statuscode.statusname'], 'safe'],
    ];
}

/**
 * {@inheritdoc}
 */
public function scenarios()
{
    // bypass scenarios() implementation in the parent class
    return Model::scenarios();
}

public function attributes()
{
    // add related fields to searchable attributes
    return array_merge(parent::attributes(), ['client.name']);
    return array_merge(parent::attributes(), ['statuscode.statusname']);
}

/**
 * Creates data provider instance with search query applied
 *
 * @param array $params
 *
 * @return ActiveDataProvider
 */
public function search($params)
{
    $query = Project::find();

    // add conditions that should always apply here

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);

    $dataProvider->sort->attributes['client.name'] = [
        'asc' => ['client.name' => SORT_ASC],
        'desc' => ['client.name' => SORT_DESC],
    ];

    $dataProvider->sort->attributes['statuscode.statusname'] = [
        'asc' => ['statuscode.statusname' => SORT_ASC],
        'desc' => ['statuscode.statusname' => SORT_DESC],
    ];

    $this->load($params);

    if (!$this->validate()) {
        // uncomment the following line if you do not want to return any records when validation fails
        // $query->where('0=1');
        return $dataProvider;
    }

    $query->joinWith(['client' => function($query) {
    $query->from(['client' => 'clients']); }]);
    $query->joinWith(['statuscode' => function($query) { $query->from(['statuscode' => 'statuses']); }]);

    // grid filtering conditions

    $query->andFilterWhere(['like', 'project.number', $this->number])
        ->andFilterWhere(['like', 'project.name', $this->name])
        ->andFilterWhere(['LIKE', 'client.name', $this->getAttribute('client.name')])
        ->andFilterWhere(['LIKE', 'statuscode.statusname', $this->getAttribute('statuscode.statusname')]);
    return $dataProvider;
}
}

My view:

<?php

use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;

$this->title = 'Projects';
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

<?php Pjax::begin(); ?>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>

<?= Html::a('Create Project', ['create'], ['class' => 'btn btn-success']) ?>

<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'number',
'client.name',
'name',
    [
    'attribute' => 'statuscode.statusname',
    'label' => 'Projectstatus',
    ],
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
<?php Pjax::end(); ?>

Body:
Nevermind, i got it! :)

return array_merge(parent::attributes(), ['client.name', 'statuscode.statusname']);

instead of:

return array_merge(parent::attributes(), ['client.name']);
return array_merge(parent::attributes(), ['statuscode.statusname']);

LOL


来源: stackexchange

问:
RxJS: Emit the initial value before Delay
If I use delay() function like this, it emits data only after a time delay :

```<code>const TIME_DELAY = 5000;
return new Observable(observer => {
  observer.next(res);
}).delay(TIME_DELAY);
</code>```

But I need to initially emit the data, then emit it every TIME_DELAY milliseconds.
How can I do this?

答:
For your requirements, timer does exactly that. Something like:

```<code>return timer(0, TIME_DELAY).pipe(
  map(() => res)
);
</code>```

https://stackblitz.com/edit/typescript-v7auxo?file=index.ts

ContentLicense: CC BY-SA 4.0

Body:
If I use delay() function like this, it emits data only after a time delay :

const TIME_DELAY = 5000;
return new Observable(observer => {
  observer.next(res);
}).delay(TIME_DELAY);

But I need to initially emit the data, then emit it every TIME_DELAY milliseconds.
How can I do this?

Body:
For your requirements, timer does exactly that. Something like:

return timer(0, TIME_DELAY).pipe(
  map(() => res)
);

https://stackblitz.com/edit/typescript-v7auxo?file=index.ts


问:
how can this SQL be done in LINQ?
i have this simple SQL query...

```<code>-- BestSeller
SELECT TOP(1) v.make, v.model, COUNT(v.make) AS NoSold
FROM Vehicles v
group by v.make, v.model
order by NoSold DESC
</code>```

Im using entity framwork and want to do the same thing using linq. so far i have...

```<code>                var tester = (from v in DB.VP_Historical_Vehicles
                         group v by v.make into g
                         orderby g.Count() descending
                         select new { make = g.Key, model = g, count = g.Count() }).Take(1);

            foreach(var t in tester)
            {
                BestSeller.Make = t.make;
                BestSeller.Model = t.make;
                BestSeller.CountValue = t.count;
            }
</code>```

i keep getting timeouts, the database is large but the SQL runs very quick

any sugestions?

thanks

truegilly

答:
Group by a compound key.</p>

```<code>var t = (
    from v in DB.VP_Historical_Vehicles
    group v by new { v.make, v.model } into g
    orderby g.Count() descending
    select new { make = g.Key.make, model = g.Key.model, count = g.Count() }
    )
    .First();

BestSeller.Make = t.make;
BestSeller.Model = t.make;
BestSeller.CountValue = t.count;
</code>```

ContentLicense: CC BY-SA 3.0

Title: how can this SQL be done in LINQ?

Body:
i have this simple SQL query...

-- BestSeller
SELECT TOP(1) v.make, v.model, COUNT(v.make) AS NoSold
FROM Vehicles v
group by v.make, v.model
order by NoSold DESC

Im using entity framwork and want to do the same thing using linq. so far i have...

                var tester = (from v in DB.VP_Historical_Vehicles
                         group v by v.make into g
                         orderby g.Count() descending
                         select new { make = g.Key, model = g, count = g.Count() }).Take(1);

            foreach(var t in tester)
            {
                BestSeller.Make = t.make;
                BestSeller.Model = t.make;
                BestSeller.CountValue = t.count;
            }

i keep getting timeouts, the database is large but the SQL runs very quick

any sugestions?

thanks

truegilly

Body:
Group by a compound key.

var t = (
    from v in DB.VP_Historical_Vehicles
    group v by new { v.make, v.model } into g
    orderby g.Count() descending
    select new { make = g.Key.make, model = g.Key.model, count = g.Count() }
    )
    .First();

BestSeller.Make = t.make;
BestSeller.Model = t.make;
BestSeller.CountValue = t.count;


问:
How to manage (init\start\restart\create schema) my postgreSQL server when running on a single machine with a simple desktop c# app?
I want to use postgreSQL in my C# desktop application to save data on the same machine. I have little experience with DB in general and I'm trying to understand what are the best practices to handle the db server. Should my application installer supposed to create and start the db backend service? or should my application run it in start up? how to restart it if it crashes? when do i define the DB schema (all tables) - from the application or as a part of installation?

I'm using Npgsql on my client side without EF. In the past I worked with SQLite but since it dosent support concurrency I thought about moving to postgresql.

Thanks!

答:
Unlike Sqlite, PostgreSQL generally runs as a separate service on your machine. It is started when your operating system boots and is always running, so your application never has to start it up or shut it down.

If you're looking for options for distributing PostgreSQL as part of your own applications, so that users don't have to install it separately, that should be possible but I don't know of specific options.

Finally, creating the database and schema is typically something your application manages when it starts up. For example, it could check if the schema has already been created (e.g. by checking for the existence of a specific table) and create it if not. There are various ways to manage this kind of thing, but more detail about your scenario would be necessary.


问:
How to replace a list comprehension with a numpy command?
Is there a way to replace the following python list comprehension with a numpy function that doesn't work with loops?

a = np.array([0, 1, 1, 1, 0, 3])

bins = np.bincount(a)
>>> bins: [2 3 0 1]

a_counts = [bins[val] for val in y_true]
>>> a_counts: [2, 3, 3, 3, 2, 1]
```

So the basic idea is to generate an array where the actual values are replaced by the number of occurrences of that specific value in the array.

I want to do this calculation in a custom keras loss function which, to my knowledge, doesn't work with loops or list comprehensions.

答:
Or use collections.Counter:

```<code>from collections import Counter
l = [0, 1, 1, 1, 0, 3]
print(Counter(l))
</code>```

Which Outputs:

```<code>Counter({1: 3, 0: 2, 3: 1})
</code>```

Body:
Is there a way to replace the following python list comprehension with a numpy function that doesn't work with loops?

a = np.array([0, 1, 1, 1, 0, 3])

bins = np.bincount(a)
>>> bins: [2 3 0 1]

a_counts = [bins[val] for val in y_true]
>>> a_counts: [2, 3, 3, 3, 2, 1]

So the basic idea is to generate an array where the actual values are replaced by the number of occurrences of that specific value in the array.

I want to do this calculation in a custom keras loss function which, to my knowledge, doesn't work with loops or list comprehensions.

Body:
Or use collections.Counter:

from collections import Counter
l = [0, 1, 1, 1, 0, 3]
print(Counter(l))

Which Outputs:

Counter({1: 3, 0: 2, 3: 1})


问:
Correct way to add thirdy-party dependencies on a wildfly-swarm ejb-jar deployment
I'm trying to create a wildfly swarm jar for a ejb-jar deployment that contains only a MDB.

The bean onMessage method is using a thirdy party library that's included in the project dependencies.

The generated uber jar contains the library but for some reason I get a ClassNotFound exception when I try to use the library.

If we change the packaging type from simple "jar" to "war" everything works as expected.

What is the correct way to add thirdy-party dependency to a simple ejb-jar deployment for wildfly swarm ?

答:
I'm not sure what the "correct" solution is. It always seemed a bit odd to me that a thorntail package (formerlly wildfly swarm) always needed to be a WAR, and always needed to include undertow and/or jaxrs even if they were not being used.

As the first comment above aludes, it is posible to include third party dependencies in a JAR package.

Within src/main/resources of my maven project I've added the sub directories modules/com/example/mymodule/main and I've added module.xml inside of the main directory.

```<code><?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.3" name="com.example.mymodule">
<resources>
    <artifact name="org.apache.pdfbox:pdfbox:2.0.13" />
</resources>

<dependencies>
    <module name="org.apache.commons.logging"></module>
    <module name="org.apache.commons.io"></module>
    <module name="org.apache.httpcomponents"></module>
</dependencies>
</module>
</code>```

The above xml references maven artifacts that I have included in my POM. You can also reference other modules.

I then added a jboss-deployment-structure.xml to src/main/resources/META-INF

```<code><jboss-deployment-structure>
<deployment>
    <dependencies>
        <module name="com.example.mymodule" />
    </dependencies>
</deployment>
</jboss-deployment-structure>
</code>```

Any 3rd party dependency that you add to your POM will now need adding to module.xml. It's a bit of a pain I know, it would be really nice if there was something that the maven plugin could do to automate this.

Body:
I'm not sure what the "correct" solution is. It always seemed a bit odd to me that a thorntail package (formerlly wildfly swarm) always needed to be a WAR, and always needed to include undertow and/or jaxrs even if they were not being used.

As the first comment above aludes, it is posible to include third party dependencies in a JAR package.

Within src/main/resources of my maven project I've added the sub directories modules/com/example/mymodule/main and I've added module.xml inside of the main directory.

<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.3" name="com.example.mymodule">
<resources>
    <artifact name="org.apache.pdfbox:pdfbox:2.0.13" />
</resources>

<dependencies>
    <module name="org.apache.commons.logging"></module>
    <module name="org.apache.commons.io"></module>
    <module name="org.apache.httpcomponents"></module>
</dependencies>
</module>

The above xml references maven artifacts that I have included in my POM. You can also reference other modules.

I then added a jboss-deployment-structure.xml to src/main/resources/META-INF

<jboss-deployment-structure>
<deployment>
    <dependencies>
        <module name="com.example.mymodule" />
    </dependencies>
</deployment>
</jboss-deployment-structure>

Any 3rd party dependency that you add to your POM will now need adding to module.xml. It's a bit of a pain I know, it would be really nice if there was something that the maven plugin could do to automate this.


问:
Why are Symfony2 validation propertyPath valus in square brackets?
I am validating some values:

```<code>$collectionConstraint = new Collection(array(
    'email' => array(
        new NotBlank(),
        new Email(),
    ),
    'password'  => array(
         new NotBlank(),
         new MinLength(array('limit' => 6)),
         new MaxLength(array('limit' => 25)),
    ),
));
$data = array('email' => $this->getRequest()->get('email'), 'password' => $this->getRequest()->get('password'));
$errors = $this->get('validator')->validateValue($data, $collectionConstraint);
</code>```

But for some reason the fields (propertyPath) are stored with square brackets - I'd like to understand why Sf does that. I have to manually remove all the brackets which seems absurd so I think I am missing some functionality somewhere.

Dump of $errors:

```<code>Symfony\Component\Validator\ConstraintViolationList Object
(
    [violations:protected] => Array
        (
            [0] => Symfony\Component\Validator\ConstraintViolation Object
                (
                    [messageTemplate:protected] => This value should not be blank
                    [messageParameters:protected] => Array
                        (
                        )

                    [root:protected] => Array
                        (
                            [email] =>
                            [password] =>
                        )

                    [propertyPath:protected] => [email]
                    [invalidValue:protected] =>
                )

            [1] => Symfony\Component\Validator\ConstraintViolation Object
                (
                    [messageTemplate:protected] => This value should not be blank
                    [messageParameters:protected] => Array
                        (
                        )

                    [root:protected] => Array
                        (
                            [email] =>
                            [password] =>
                        )

                    [propertyPath:protected] => [password]
                    [invalidValue:protected] =>
                )

        )

)
</code>```

Even the toString function is useless.

```<code>"[email]: This value should not be blank","[password]: This value should not be blank"
</code>```

答:
PropertyAccessor's setValue is no real help because it cannot handle multiple violations for a single field. For instance, a field might be shorter than a constraint length and also contain illegal characters. For this, we would have two error messages.

I had to create my own code:

```<code>$messages = [];

foreach ($violations as $violation) {

    $field = substr($violation->getPropertyPath(), 1, -1);
    $messages[] = [$field => $violation->getMessage()];
}

$output = [
    'name' => array_unique(array_column($messages, 'name')),
    'email' => array_unique(array_column($messages, 'email')),
];

return $output;
</code>```

We manually strip the [] characters from the property path and create an
array of arrays of fields and corresponding messages. Later we transform the
array to group the messages by fields.

```<code>$session = $request->getSession();
$session->getFlashBag()->setAll($messages);
</code>```

In the controller, we add the messages to the flash bag.

Body:
I am validating some values:

$collectionConstraint = new Collection(array(
    'email' => array(
        new NotBlank(),
        new Email(),
    ),
    'password'  => array(
         new NotBlank(),
         new MinLength(array('limit' => 6)),
         new MaxLength(array('limit' => 25)),
    ),
));
$data = array('email' => $this->getRequest()->get('email'), 'password' => $this->getRequest()->get('password'));
$errors = $this->get('validator')->validateValue($data, $collectionConstraint);

But for some reason the fields (propertyPath) are stored with square brackets - I'd like to understand why Sf does that. I have to manually remove all the brackets which seems absurd so I think I am missing some functionality somewhere.

Dump of $errors:

Symfony\Component\Validator\ConstraintViolationList Object
(
    [violations:protected] => Array
        (
            [0] => Symfony\Component\Validator\ConstraintViolation Object
                (
                    [messageTemplate:protected] => This value should not be blank
                    [messageParameters:protected] => Array
                        (
                        )

                    [root:protected] => Array
                        (
                            [email] =>
                            [password] =>
                        )

                    [propertyPath:protected] => [email]
                    [invalidValue:protected] =>
                )

            [1] => Symfony\Component\Validator\ConstraintViolation Object
                (
                    [messageTemplate:protected] => This value should not be blank
                    [messageParameters:protected] => Array
                        (
                        )

                    [root:protected] => Array
                        (
                            [email] =>
                            [password] =>
                        )

                    [propertyPath:protected] => [password]
                    [invalidValue:protected] =>
                )

        )

)

Even the toString function is useless.

"[email]: This value should not be blank","[password]: This value should not be blank"

Body:
PropertyAccessor's setValue is no real help because it cannot handle multiple violations for a single field. For instance, a field might be shorter than a constraint length and also contain illegal characters. For this, we would have two error messages.

I had to create my own code:

$messages = [];

foreach ($violations as $violation) {

    $field = substr($violation->getPropertyPath(), 1, -1);
    $messages[] = [$field => $violation->getMessage()];
}

$output = [
    'name' => array_unique(array_column($messages, 'name')),
    'email' => array_unique(array_column($messages, 'email')),
];

return $output;

We manually strip the [] characters from the property path and create an
array of arrays of fields and corresponding messages. Later we transform the
array to group the messages by fields.

$session = $request->getSession();
$session->getFlashBag()->setAll($messages);

In the controller, we add the messages to the flash bag.


问:
Save data in a cakephp hasmany and belongsto association at once
I know this question is asked here a many times but I also tried to follow the solutions provided at my best. As I am learning a cakephp some solutions seemed difficult to implement in a code. I am using cakephp 2.5.

What I am trying to do is creating a problem report with attached one or more uploads. Here is some of what I have implemented so far:-

I have following models:

Candidate

CandidatesProblemReport

CandidatesProblemReportsUpload

There associations are as follows:

CandidatesProblemReport hasMany CandidatesProblemReportsUpload

Candidate hasMany CandidatesProblemReport

CandidatesProblemReport belongsTo Candidate

CandidatesProblemReportsUpload belongsTo CandidatesProblemReport

Candidate.php

```<code>    <?php

    class Candidate extends AppModel {

        public $name = 'Candidate';
        public $hasMany = array(

            'CandidatesProblemReport' => array(
                'className' => 'CandidatesProblemReport',
                'foreignKey' => 'candidate_id'
            )

        );
    }
</code>```

CandidatesProblemReport.php

```<code>    <?php

    class CandidatesProblemReport extends AppModel {

        public $name = "CandidatesProblemReport";
        public $belongsTo = array(
            'Candidate' => array(
                'className' => 'Candidate'
            )
        );
        public $hasMany = array(
            'Uploads' => array(
                'className' => 'CandidatesProblemReportsUpload'
            ),
            'Replies' => array(
                'className' => 'CandidatesProblemReportsReply'
            )
        );
    }
</code>```

CandidatesProblemReportsController.php

```<code>    class CandidatesProblemReportsController extends AppController {

        public $name = "CandidatesProblemReports";

        // ############# Report a Problem #############
        // ********************************************
        public function create() {
            $userid = $this->Auth->user('id'); // Grabs the current user id
            $this->set('userId', $userid); // Sends the current user id to the form

            if ($this->request->is('post') && !empty($this->request->data)):

                $this->CandidatesProblemReport->create();

                $report = $this->CandidatesProblemReport->save($this->request->data);
                if (!empty($report)):
                    $this->request->data['CandidatesProblemReportsUpload']['candidates_problem_report_id'] = $this->CandidatesProblemReport->id;
                endif;

                if ($this->CandidatesProblemReport->saveAssociated($this->request->data)):

                    $this->Session->setFlash('Your report has been submitted '
                            . 'successfully. Thank you!');

                    $this->redirect(array(
                        'action' => 'viewall')
                    );
                else:
                    $this->Session->setFlash('Your report could not be submitted, '
                            . 'please try again');
                endif;

            endif;
        }
    }
</code>```

create.ctp

```<code><h1>Create a report</h1>
<?php
echo $this->Form->create('CandidatesProblemReport', array('type' => 'file'));

echo $this->Form->input('CandidatesProblemReport.report_subject');

echo $this->Form->input('CandidatesProblemReport.report_handle_department', array(
    'options' => array(
        'Technical' => 'Technical',
        'Sales' => 'Sales',
        'Support' => 'Support',
        'Other' => 'Other'
    )
));
echo $this->Form->input('CandidatesProblemReport.report_description');

echo $this->Form->input('CandidatesProblemReport.report_date', array(
    'type' => 'hidden',
    'value' => date('Y-m-d H:i:s'))
);

echo $this->Form->input('CandidatesProblemReport.candidate_id', array(
    'type' => 'hidden',
    'value' => $userId)
);
?>

<div>
    <p><strong>Upload Screenshot/Files</strong></p>
    <hr>
</div>
<?php
echo $this->Form->input('CandidatesProblemReportsUpload.0.report_upload', array(
    'type' => 'file'
));
?>
<button class="add-new-upload" type="button">Add more</button>
<?php
echo $this->Form->end('submit');

echo $this->Html->script('jquery-2.1.1.min.js');
?>

<script type="text/javascript">
    var i = 1;
    $('.add-new-upload').click(function () {
        $('.file').append('<input type="file" name="data[CandidatesProblemReportsUpload]['
                + i +
                '][report_upload]" id="CandidatesProblemReportsUpload'
                + i +
                'ReportUpload">');
        i++;
    });
</script>
</code>```

Now what is happening is I am able to save the main model data i.e. CandidatesProblemReports but when I saveAssociated data it again saves the main model creating second duplicate entry but the uploads are not getting saved.

答: You can user $this->CandidatesProblemReport->saveAssociated($this->request->data) code to save associate data in multiple tables using one query.

Body:
I know this question is asked here a many times but I also tried to follow the solutions provided at my best. As I am learning a cakephp some solutions seemed difficult to implement in a code. I am using cakephp 2.5.

What I am trying to do is creating a problem report with attached one or more uploads. Here is some of what I have implemented so far:-

I have following models:

Candidate

CandidatesProblemReport

CandidatesProblemReportsUpload

There associations are as follows:

CandidatesProblemReport hasMany CandidatesProblemReportsUpload

Candidate hasMany CandidatesProblemReport

CandidatesProblemReport belongsTo Candidate

CandidatesProblemReportsUpload belongsTo CandidatesProblemReport

Candidate.php

    <?php

    class Candidate extends AppModel {

        public $name = 'Candidate';
        public $hasMany = array(

            'CandidatesProblemReport' => array(
                'className' => 'CandidatesProblemReport',
                'foreignKey' => 'candidate_id'
            )

        );
    }

CandidatesProblemReport.php

    <?php

    class CandidatesProblemReport extends AppModel {

        public $name = "CandidatesProblemReport";
        public $belongsTo = array(
            'Candidate' => array(
                'className' => 'Candidate'
            )
        );
        public $hasMany = array(
            'Uploads' => array(
                'className' => 'CandidatesProblemReportsUpload'
            ),
            'Replies' => array(
                'className' => 'CandidatesProblemReportsReply'
            )
        );
    }

CandidatesProblemReportsController.php

    class CandidatesProblemReportsController extends AppController {

        public $name = "CandidatesProblemReports";

        // ############# Report a Problem #############
        // ********************************************
        public function create() {
            $userid = $this->Auth->user('id'); // Grabs the current user id
            $this->set('userId', $userid); // Sends the current user id to the form

            if ($this->request->is('post') && !empty($this->request->data)):

                $this->CandidatesProblemReport->create();

                $report = $this->CandidatesProblemReport->save($this->request->data);
                if (!empty($report)):
                    $this->request->data['CandidatesProblemReportsUpload']['candidates_problem_report_id'] = $this->CandidatesProblemReport->id;
                endif;

                if ($this->CandidatesProblemReport->saveAssociated($this->request->data)):

                    $this->Session->setFlash('Your report has been submitted '
                            . 'successfully. Thank you!');

                    $this->redirect(array(
                        'action' => 'viewall')
                    );
                else:
                    $this->Session->setFlash('Your report could not be submitted, '
                            . 'please try again');
                endif;

            endif;
        }
    }

create.ctp

Create a report

<?php
echo $this->Form->create('CandidatesProblemReport', array('type' => 'file'));

echo $this->Form->input('CandidatesProblemReport.report_subject');

echo $this->Form->input('CandidatesProblemReport.report_handle_department', array(
    'options' => array(
        'Technical' => 'Technical',
        'Sales' => 'Sales',
        'Support' => 'Support',
        'Other' => 'Other'
    )
));
echo $this->Form->input('CandidatesProblemReport.report_description');

echo $this->Form->input('CandidatesProblemReport.report_date', array(
    'type' => 'hidden',
    'value' => date('Y-m-d H:i:s'))
);

echo $this->Form->input('CandidatesProblemReport.candidate_id', array(
    'type' => 'hidden',
    'value' => $userId)
);
?>

Upload Screenshot/Files

<?php
echo $this->Form->input('CandidatesProblemReportsUpload.0.report_upload', array(
    'type' => 'file'
));
?>
<button class="add-new-upload" type="button">Add more</button>
<?php
echo $this->Form->end('submit');

echo $this->Html->script('jquery-2.1.1.min.js');
?>

Now what is happening is I am able to save the main model data i.e. CandidatesProblemReports but when I saveAssociated data it again saves the main model creating second duplicate entry but the uploads are not getting saved.


问:
AppsFlyer GoogleTagManager Integration - different number of events
In our app, we use Google Tag Manager to send in-app events to both Firebase and AppsFlyer.
When we test it locally it works correctly in logs I can see that GTM saves Tag

```<code>GoogleTagManager info: Saved tag for URL https://api2.appsflyer.com/inappevent/idxxxxxxxx
</code>```

then after a while, GTM sends it

```<code>GoogleTagManager info: Sent hit https://api2.appsflyer.com/inappevent/idxxxxxxxx
</code>```

I check with Charles how the request looks like and everything looks good the payload is built correctly and I get 200 OK.

```<code>{
    "appsflyer_id": "XXXXX",
    "eventName": "af_initiated_checkout",
    "af_events_api": "true",
    "eventValue": "{\"af_price\":500,\"af_content_id\":\"x1\",\"af_content_type\":\"xxx\",\"af_currency\":\"EUR\",\"af_quantity\":8}",
    "idfa": "XXXX-XXXX-XXXX",
    "bundle_id": "com.superapp.superapp"
}
</code>```

After a few minutes, I can see the effect on the AppsFlyer dashboard.
but when we sent the app to the production (the same bundle id) we spotted that count of events is quite different between Firebase and AppsFlyer even 10 times more events in Firebase in some cases.
What can be the cause of that? How I can debug this problem?

答:
Here is Luc from AppsFlyer Support,
From your description, my guess is the following:

AppsFlyer dashboard is based on install date and shows life-time data, meaning that if you look at "last week", you see the data of user who installed your app last week. The number of events that GTM sent to AppsFlyer last week is likely much higher than events generated by installs of last week, since most of them correspond to older installs.

The only page of our dashboard which follows a different logic is the "Activity" page, which is based on event date. Could you compare the event number in GTM with the number of events in the Activity Page?

If that doesn't solve the problem, simply shoot an email to support@appsflyer.com with more details and the app_id, I'll have a look.

thanks and best,
Luc

Body:
In our app, we use Google Tag Manager to send in-app events to both Firebase and AppsFlyer.
When we test it locally it works correctly in logs I can see that GTM saves Tag

GoogleTagManager info: Saved tag for URL https://api2.appsflyer.com/inappevent/idxxxxxxxx

then after a while, GTM sends it

GoogleTagManager info: Sent hit https://api2.appsflyer.com/inappevent/idxxxxxxxx

I check with Charles how the request looks like and everything looks good the payload is built correctly and I get 200 OK.

{
    "appsflyer_id": "XXXXX",
    "eventName": "af_initiated_checkout",
    "af_events_api": "true",
    "eventValue": "{\"af_price\":500,\"af_content_id\":\"x1\",\"af_content_type\":\"xxx\",\"af_currency\":\"EUR\",\"af_quantity\":8}",
    "idfa": "XXXX-XXXX-XXXX",
    "bundle_id": "com.superapp.superapp"
}

After a few minutes, I can see the effect on the AppsFlyer dashboard.
but when we sent the app to the production (the same bundle id) we spotted that count of events is quite different between Firebase and AppsFlyer even 10 times more events in Firebase in some cases.
What can be the cause of that? How I can debug this problem?


答:
You just need to index the result from np.bincount with a:

```<code>a = np.array([0, 1, 1, 1, 0, 3])
bins = np.bincount(a)
a_counts = bins[a]
</code>```

```<code>print(a_counts)
# array([2, 3, 3, 3, 2, 1], dtype=int64)
</code>```

Title: How to replace a list comprehension with a numpy command?

Body:
You just need to index the result from np.bincount with a:

a = np.array([0, 1, 1, 1, 0, 3])
bins = np.bincount(a)
a_counts = bins[a]

print(a_counts)
# array([2, 3, 3, 3, 2, 1], dtype=int64)


答:
You should make use of timer function that allows you to specify initial delay (0 in your case), and then the interval in which the emissions repeat.

For example: const stream$ = timer(0, TIME_DELAY);

If you need to cast the result to another value or observable, you can add pipe and map or switchMap (in case of observable) operators.
For example:

```<code>const stream$ = timer(0, TIME_DELAY)
 .pipe(map(() => 'some value'));

// or
const stream$ = timer(0, TIME_DELAY)
 .pipe(switchMap(() => anotherObservable$));

</code>```

Title: RxJS: Emit the initial value before Delay

Body:
You should make use of timer function that allows you to specify initial delay (0 in your case), and then the interval in which the emissions repeat.

For example: const stream$ = timer(0, TIME_DELAY);

If you need to cast the result to another value or observable, you can add pipe and map or switchMap (in case of observable) operators.
For example:

const stream$ = timer(0, TIME_DELAY)
 .pipe(map(() => 'some value'));

// or
const stream$ = timer(0, TIME_DELAY)
 .pipe(switchMap(() => anotherObservable$));


问:
Corda Node deployment on aws
I am following this tutorial for deploying a node on aws using aws Corda AMI.

But after the registration step,

( java -jar corda.jar initial-registration -p PASSWORD_FOR_NETWORK_ROOT_TRUSTORE),

its throwing this error:

[ERROR] 10:14:31+0000 [main] internal.NodeStartupLogging.invoke -
  Exception during node startup: Network root trust store path:
  '/opt/corda/4.0/certificates/network-root-truststore.jks' doesn't
  exist [errorCode=szfwpy,
  moreInformationAt=https://errors.corda.net/ENT/4.0/szfwpy]

It seems like, it is not able to find network-root-truststore.

Can someone tell me where can we get this certificate from? I copied three certificates from an existing cordapp but it did not have network truststore.

Is there any proper resource for deploying the cordapp on AWS?

答: You need to contact a Corda network operator you plan to connect your node to and get information about Doorman (Identity Operator) and Network Map, as well as the Network Root Truststore file. The lack of the later is the reason of the issue you see.</p>

Title: Corda Node deployment on aws


问:
What does XmlReader.Parse() do?
edit: The project is an old project and the below code is one class in there that handles the xml.

There is a question to get the xsd from an old legacy application, but all it seems to be doing is: xmlReader.ParseXml(fileName,outputFile); in the ProcessXml() method.

```<code>using System;
using System.IO;
using System.Configuration;
using Utilities;
namespace JobProcessor
{

public class XmlJob : Job
{
    #region variables
    private string      ftpServer;
    private string      ftpUserName;
    private string      ftpPassWord;
    private string      ftpDestination;
    ///<summary>The xml reader used to get validation information from the xmp parsing</summary>
    protected XmlReader xmlReader   = new XmlReader();

    private string      outputFile;

    public XmlJob(string fileName, string type) : base(fileName, type){
        ftpServer       = ConfigurationManager.AppSettings[type + "-ftp"];
        ftpUserName     = ConfigurationManager.AppSettings[type + "-ftpUser"];
        ftpPassWord     = ConfigurationManager.AppSettings[type + "-ftpPass"];
        ftpDestination  = ConfigurationManager.AppSettings[type + "-ftpDest"];
    }

    protected bool ConfigureXmlReader(){
        int    recType    = 0;

        try{
            //set up the record types (i.e. the elements that trigger a new record in the output
            while(ConfigurationManager.AppSettings[type + "-RecordType" + recType.ToString("00")] != null){
                xmlReader.AddRecordType(ConfigurationManager.AppSettings[type + "-RecordType" + recType.ToString("00")],recType.ToString("00"));
                recType++;
            }
            //store the number of types
            xmlReader.SetNoRecordTypes(recType);
        }catch(Exception e){
            HandleError("Error loading record types\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }

        try{
            //set up the fields which make up each record type
            for(int i=0;i<recType;i++){
                xmlReader.AddFieldsList(i,ConfigurationManager.AppSettings[type + "-" + i.ToString("00") + "Fields"]);
            }
        }catch(Exception e){
            HandleError("Error loading field list\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }
        return(true);
    }

    public override void RunJob(){
        outputFile = Path.Combine(destinationDirectory, Path.GetFileNameWithoutExtension(fileName) + ".flat");

        if(!ConfigureXmlReader()){
            return;
        }

        if(!CheckInputFile()){
            return;
        }

        if(!ProcessXml()){
            return;
        }

        if(!Validate()){
            return;
        }

        if(ftpServer!=null && ftpUserName!=null && ftpPassWord!=null && ftpDestination!=null){
            if(!FtpFile()){
                return;
            }
        }

        MoveOriginalFile();
    }

    protected virtual bool Validate(){
        return(true);
    }

    protected bool ProcessXml(){
        /*
         * Process the xml file into a delimited format
         */

        try{
            xmlReader.ParseXml(fileName,outputFile);
        }catch(Exception e){
            HandleError("Error parsing XML file\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }
        return(true);
    }
    protected bool FtpFile(){
        try{
            FtpMethods.UploadFile(ftpServer,ftpUserName,ftpPassWord,outputFile,ftpDestination);
        }catch(Exception e){
            HandleError("Error FTPing file\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }
        return(true);
    }

    #endregion
}
</code>```

}

What exactly does this command do? F1 doesn't find anything and searching google gets me to a lot of xmlTextReaders.

答: I would guess that ParseXml was an extension method of XmlReader, if MSDN / F1 help doesn't give any information about the method definition? Or possibly, the author of the code subclassed from XmlReader and added this method.</p>

Title: What does XmlReader.Parse() do?

Body:
edit: The project is an old project and the below code is one class in there that handles the xml.

There is a question to get the xsd from an old legacy application, but all it seems to be doing is: xmlReader.ParseXml(fileName,outputFile); in the ProcessXml() method.

using System;
using System.IO;
using System.Configuration;
using Utilities;
namespace JobProcessor
{

public class XmlJob : Job
{
    #region variables
    private string      ftpServer;
    private string      ftpUserName;
    private string      ftpPassWord;
    private string      ftpDestination;
    ///The xml reader used to get validation information from the xmp parsing
    protected XmlReader xmlReader   = new XmlReader();

    private string      outputFile;

    public XmlJob(string fileName, string type) : base(fileName, type){
        ftpServer       = ConfigurationManager.AppSettings[type + "-ftp"];
        ftpUserName     = ConfigurationManager.AppSettings[type + "-ftpUser"];
        ftpPassWord     = ConfigurationManager.AppSettings[type + "-ftpPass"];
        ftpDestination  = ConfigurationManager.AppSettings[type + "-ftpDest"];
    }

    protected bool ConfigureXmlReader(){
        int    recType    = 0;

        try{
            //set up the record types (i.e. the elements that trigger a new record in the output
            while(ConfigurationManager.AppSettings[type + "-RecordType" + recType.ToString("00")] != null){
                xmlReader.AddRecordType(ConfigurationManager.AppSettings[type + "-RecordType" + recType.ToString("00")],recType.ToString("00"));
                recType++;
            }
            //store the number of types
            xmlReader.SetNoRecordTypes(recType);
        }catch(Exception e){
            HandleError("Error loading record types\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }

        try{
            //set up the fields which make up each record type
            for(int i=0;i<recType;i++){
                xmlReader.AddFieldsList(i,ConfigurationManager.AppSettings[type + "-" + i.ToString("00") + "Fields"]);
            }
        }catch(Exception e){
            HandleError("Error loading field list\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }
        return(true);
    }

    public override void RunJob(){
        outputFile = Path.Combine(destinationDirectory, Path.GetFileNameWithoutExtension(fileName) + ".flat");

        if(!ConfigureXmlReader()){
            return;
        }

        if(!CheckInputFile()){
            return;
        }

        if(!ProcessXml()){
            return;
        }

        if(!Validate()){
            return;
        }

        if(ftpServer!=null && ftpUserName!=null && ftpPassWord!=null && ftpDestination!=null){
            if(!FtpFile()){
                return;
            }
        }

        MoveOriginalFile();
    }

    protected virtual bool Validate(){
        return(true);
    }

    protected bool ProcessXml(){
        /*
         * Process the xml file into a delimited format
         */

        try{
            xmlReader.ParseXml(fileName,outputFile);
        }catch(Exception e){
            HandleError("Error parsing XML file\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }
        return(true);
    }
    protected bool FtpFile(){
        try{
            FtpMethods.UploadFile(ftpServer,ftpUserName,ftpPassWord,outputFile,ftpDestination);
        }catch(Exception e){
            HandleError("Error FTPing file\r\n" + e.ToString() + "\r\n" + e.StackTrace + "\r\n");
            return(false);
        }
        return(true);
    }

    #endregion
}

}

What exactly does this command do? F1 doesn't find anything and searching google gets me to a lot of xmlTextReaders.


问:
How to create inline_keyboard using json with multiple InlineKeyboardButton on same row?
Looking for json payload to create inline_keyboard with multiple InlineKeyboardButton on the same row.

The following code is working but creates 1 button per row.

```<code>{
  "telegram": {
    "text": "Pick a color",
    "reply_markup": {
      "inline_keyboard": [
        [
          {
            "text": "Red",
            "callback_data": "Red"
          }
        ],
        [
          {
            "text": "Pink",
            "callback_data": "Pink"
          }
        ]
      ]
    }
  }
}
</code>```

Telegram Card in Dialogflow is able to create multiple inline buttons similar to as shown below:

https://core.telegram.org/file/811140217/1/NkRCCLeQZVc/17a804837802700ea4

答:
inline_keyboard consists of rows, each row consists of buttons.

So just add buttons to the first row (Blue and Green in this case) like this:

```<code>{
  "telegram": {
    "text": "Pick a color",
    "reply_markup": {
      "inline_keyboard": [
        [
          {
            "text": "Red",
            "callback_data": "Red"
          },
          {
            "text": "Blue",
            "callback_data": "Blue"
          },
          {
            "text": "Green",
            "callback_data": "Green"
          }
        ]
      ]
    }
  }
}
</code>```

Body:
Looking for json payload to create inline_keyboard with multiple InlineKeyboardButton on the same row.

The following code is working but creates 1 button per row.

{
  "telegram": {
    "text": "Pick a color",
    "reply_markup": {
      "inline_keyboard": [
        [
          {
            "text": "Red",
            "callback_data": "Red"
          }
        ],
        [
          {
            "text": "Pink",
            "callback_data": "Pink"
          }
        ]
      ]
    }
  }
}

Telegram Card in Dialogflow is able to create multiple inline buttons similar to as shown below:

https://core.telegram.org/file/811140217/1/NkRCCLeQZVc/17a804837802700ea4

Body:
inline_keyboard consists of rows, each row consists of buttons.

So just add buttons to the first row (Blue and Green in this case) like this:

{
  "telegram": {
    "text": "Pick a color",
    "reply_markup": {
      "inline_keyboard": [
        [
          {
            "text": "Red",
            "callback_data": "Red"
          },
          {
            "text": "Blue",
            "callback_data": "Blue"
          },
          {
            "text": "Green",
            "callback_data": "Green"
          }
        ]
      ]
    }
  }
}


问:
Ajax post array when it's filled
I have global variable var distances = []. I have function to fill it but it takes some time. And I want to send it to Django view when it's filled. However due to JS asynchronous work I alway send empty array. How can I send filled array without setting timeout? My js code is

```<code>var distances = [] //array where some digits will be stored

function getAllDistances() //function where this digits being put in distances arr
//note that every digit is result of request to API of routing service so it takes
//some time to get thing done

function ajaxTest(){//function for sending array to Django view
    $.ajax({
        url:'test/',
        type:'POST',
        data:JSON.stringify({distances : distances}),
        dataType: 'json',
        success:function (data) {
            console.log("Ajax test success");
            console.log(data.result.text);//view should return some result
        },

        error:function () {
            console.log("Ajax test failure")
        }
    })
}

function doTheJob(){ //main function
    getAllDistances();
    ajaxTest();
}
</code>```

So everything is ok with request but it always sends empty array. Is it possible to make js send filled array without setting timeout? I guess callback will do thing here but correct me if I wrong

To make it more clear I'll add function that gets me distances

```<code>function getRoutSummary(i, j, q) {
                    var url = 'https://router.project-osrm.org/route/v1/driving/' +
                            coords[i][1] + ',' + coords[i][0] + ';' +
                            coords[j][1] + ',' + coords[j][0] +
                            '?geometries=geojson';
//coord is array of arrays with coordinates like
//[[lat1, long1], [lat2, long2], [lat3, long3]] where lat is latitude and long
//is longtitude

                    var req = new XMLHttpRequest();
                    req.responseType = 'json';
                    req.open('GET', url, true);
                    req.onload = function () {
                        var jsonResponse = req.response;
                        var distance = jsonResponse.routes[0].distance;
                        distances[q] = distance;
                    };
                    req.send();
            }
</code>```

And then I call this function in loop

```<code>function getAllDistances(){
                var q = 0;
                for (var i = 0; i < coords.length; i++){
                    for (var j = 0; j < coords.length; j++){
                        getRoutSummary(i, j, q);
                        q = q + 1;
                    }
                }
                console.log(distances);
            }
</code>```

答:
Use  promises with Promise.all()

```<code>distancePromise = [];

function getAllDistances() {
//a loop
var promise = getSingleDistance();
distancePromise.push(promise);
//return a array of promises
return distancePromise
}
//send the distances after all the promises have been resolved
Promise.all(distancePromise).then(function(distances) {
//save the distances
})
</code>```

Title: Ajax post array when it's filled

Body:
I have global variable var distances = []. I have function to fill it but it takes some time. And I want to send it to Django view when it's filled. However due to JS asynchronous work I alway send empty array. How can I send filled array without setting timeout? My js code is

var distances = [] //array where some digits will be stored

function getAllDistances() //function where this digits being put in distances arr
//note that every digit is result of request to API of routing service so it takes
//some time to get thing done

function ajaxTest(){//function for sending array to Django view
    $.ajax({
        url:'test/',
        type:'POST',
        data:JSON.stringify({distances : distances}),
        dataType: 'json',
        success:function (data) {
            console.log("Ajax test success");
            console.log(data.result.text);//view should return some result
        },

        error:function () {
            console.log("Ajax test failure")
        }
    })
}

function doTheJob(){ //main function
    getAllDistances();
    ajaxTest();
}

So everything is ok with request but it always sends empty array. Is it possible to make js send filled array without setting timeout? I guess callback will do thing here but correct me if I wrong

To make it more clear I'll add function that gets me distances

function getRoutSummary(i, j, q) {
                    var url = 'https://router.project-osrm.org/route/v1/driving/' +
                            coords[i][1] + ',' + coords[i][0] + ';' +
                            coords[j][1] + ',' + coords[j][0] +
                            '?geometries=geojson';
//coord is array of arrays with coordinates like
//[[lat1, long1], [lat2, long2], [lat3, long3]] where lat is latitude and long
//is longtitude

                    var req = new XMLHttpRequest();
                    req.responseType = 'json';
                    req.open('GET', url, true);
                    req.onload = function () {
                        var jsonResponse = req.response;
                        var distance = jsonResponse.routes[0].distance;
                        distances[q] = distance;
                    };
                    req.send();
            }

And then I call this function in loop

function getAllDistances(){
                var q = 0;
                for (var i = 0; i < coords.length; i++){
                    for (var j = 0; j < coords.length; j++){
                        getRoutSummary(i, j, q);
                        q = q + 1;
                    }
                }
                console.log(distances);
            }

Body:
Use  promises with Promise.all()

distancePromise = [];

function getAllDistances() {
//a loop
var promise = getSingleDistance();
distancePromise.push(promise);
//return a array of promises
return distancePromise
}
//send the distances after all the promises have been resolved
Promise.all(distancePromise).then(function(distances) {
//save the distances
})


问:
How do I use System.Data in a .NET Core RC2 console app (Linux, Debian 8)?
I've installed .NET Core RC2 on a Debian 8 amd64 system and would like to test if it's possible to query an instance of Microsoft SQL Server.

So I'd like to add to my project a dependency on the System.Data.SqlClient assembly.

Presently my project file created by running the dotnet new CLI tool looks like this:

```<code>{
  "version": "1.0.0-*",
  "buildOptions": {
    "emitEntryPoint": true
  },
  "dependencies": {
    "Microsoft.NETCore.App": {
      "type": "platform",
      "version": "1.0.0-rc2-3002702"
    }
  },
  "frameworks": {
    "netcoreapp1.0": {
      "imports": "dnxcore50"
    }
  }
}
</code>```

Using this answer to a similar query, I was able to add a reference to System.Data.Common changing the

```<code>"frameworks": {
  "netcoreapp1.0": {
    "imports": "dnxcore50"
  }
}
</code>```

fragment to

```<code>"frameworks": {
  "netcoreapp1.0": {
    "imports": "dnxcore50",
    "dependencies": {
      "System.Data.Common": "*"
    }
  }
}
</code>```

which made dotnet restore use NuGet to download a bunch of stuff.

I then tried to change that fragment to read

```<code>"frameworks": {
  "netcoreapp1.0": {
    "imports": "dnxcore50",
    "dependencies": {
      "System.Data.SqlClient": "*"
    }
  }
}
</code>```

but NuGet says it's

Unable to resolve 'System.Data.SqlClient' for '.NETCoreApp,Version=v1.0'.

If I change the version string to read "4.1.0-rc3-*" the error message just gets more specific:

Unable to resolve 'System.Data.SqlClient (>= 4.1.0-rc3)' for '.NETCoreApp,Version=v1.0'.

What I'm puzzled about is that the NuGet package gallery dedicated to .NET Core explicitly lists System.Data.SqlClient as available.

So what could I do to add a reference to System.Data.SqlClient assembly to my project and have NuGet download it?

On a side note, I'm currently playing around in a plain console with only the dotnet CLI tool.  Is there any way to manage project dependencies for a .NET Core project without resorting to installing IDEs?

答:
On my MINT 19 Tara I do not use System.Data.SqlClient but the newer version Microsoft.Data.SqlClient.
Check nuget

After typing the .NET-cli command, the package was downloaded and the reference was added to the project csproj file.

In the code, use the newer namespace:

using Microsoft.Data.SqlClient;

The "regular" code works fine:

```<code> public static void CreateCommand(string queryString, string connectionString)
    {
        using (SqlConnection connection = new SqlConnection(
                   connectionString))
        {
            SqlCommand command = new SqlCommand(queryString, connection);
            command.Connection.Open();
            SqlDataReader reader = command.ExecuteReader() ;
            while( reader.Read() ) {
                for (int i = 0; i < reader.FieldCount; i++)
                {
                   Console.WriteLine( "Column name={0}, Value={1}",
                        reader.GetName(i),
                        reader.GetValue(i) );
                }
            }
        }
    }
</code>```

Body:
I've installed .NET Core RC2 on a Debian 8 amd64 system and would like to test if it's possible to query an instance of Microsoft SQL Server.

So I'd like to add to my project a dependency on the System.Data.SqlClient assembly.

Presently my project file created by running the dotnet new CLI tool looks like this:

{
  "version": "1.0.0-*",
  "buildOptions": {
    "emitEntryPoint": true
  },
  "dependencies": {
    "Microsoft.NETCore.App": {
      "type": "platform",
      "version": "1.0.0-rc2-3002702"
    }
  },
  "frameworks": {
    "netcoreapp1.0": {
      "imports": "dnxcore50"
    }
  }
}

Using this answer to a similar query, I was able to add a reference to System.Data.Common changing the

"frameworks": {
  "netcoreapp1.0": {
    "imports": "dnxcore50"
  }
}

fragment to

"frameworks": {
  "netcoreapp1.0": {
    "imports": "dnxcore50",
    "dependencies": {
      "System.Data.Common": "*"
    }
  }
}

which made dotnet restore use NuGet to download a bunch of stuff.

I then tried to change that fragment to read

"frameworks": {
  "netcoreapp1.0": {
    "imports": "dnxcore50",
    "dependencies": {
      "System.Data.SqlClient": "*"
    }
  }
}

but NuGet says it's

Unable to resolve 'System.Data.SqlClient' for '.NETCoreApp,Version=v1.0'.

If I change the version string to read "4.1.0-rc3-*" the error message just gets more specific:

Unable to resolve 'System.Data.SqlClient (>= 4.1.0-rc3)' for '.NETCoreApp,Version=v1.0'.

What I'm puzzled about is that the NuGet package gallery dedicated to .NET Core explicitly lists System.Data.SqlClient as available.

So what could I do to add a reference to System.Data.SqlClient assembly to my project and have NuGet download it?

On a side note, I'm currently playing around in a plain console with only the dotnet CLI tool.  Is there any way to manage project dependencies for a .NET Core project without resorting to installing IDEs?

Body:
On my MINT 19 Tara I do not use System.Data.SqlClient but the newer version Microsoft.Data.SqlClient.
Check nuget

After typing the .NET-cli command, the package was downloaded and the reference was added to the project csproj file.

In the code, use the newer namespace:

using Microsoft.Data.SqlClient;

The "regular" code works fine:

 public static void CreateCommand(string queryString, string connectionString)
    {
        using (SqlConnection connection = new SqlConnection(
                   connectionString))
        {
            SqlCommand command = new SqlCommand(queryString, connection);
            command.Connection.Open();
            SqlDataReader reader = command.ExecuteReader() ;
            while( reader.Read() ) {
                for (int i = 0; i < reader.FieldCount; i++)
                {
                   Console.WriteLine( "Column name={0}, Value={1}",
                        reader.GetName(i),
                        reader.GetValue(i) );
                }
            }
        }
    }


问:
How to partition to spread values?
I have a table with data:

Customers

Sequence

ID

many other columns (not important)

Sample data:

```<code>Sequence ID
-----------
214906 2613
214906 2614
214906 2615
214907 2613
214907 2614
214907 2615
214908 2613
214908 2614
214908 2615
214000 2613
213004 4444
111111 5555
111111 5556
111112 5556
111112 5555
</code>```

How can I get the desired result below?

```<code>214906 2613
214907 2614
214908 2615
214000 2613
213004 4444
111111 5555
111112 5556
</code>```

I tried various stuff with ROW_NUMBER() OVER(PARTITION BY Sequence) but it did not help because I need to take row 1 in first group, row 2 in second group etc. In other words, I need to somehow spread those Sequences across ID's. I cannot partition by ID's either because they might appear more than once in the table

答:
I hope I understand you correctly. I use the count of IDs per sequence as a group factor (using SUM() with OVER clause without ORDER BY) and after that appropriate ranking and row numbering:

Input:

```<code>CREATE TABLE #Data (
    Sequence int,
    ID int
)
INSERT INTO #Data
    (Sequence, ID)
VALUES
    (214906, 2613),
    (214906, 2614),
    (214906, 2615),
    (214907, 2613),
    (214907, 2614),
    (214907, 2615),
    (214908, 2613),
    (214908, 2614),
    (214908, 2615),
    (214000, 2613),
    (213004, 4444),
    (111111, 5555),
    (111111, 5556),
    (111112, 5556),
    (111112, 5555)
</code>```

T-SQL:

```<code>;WITH SequenceCTE AS (
    SELECT
        *,
        COUNT(*) OVER (PARTITION BY Sequence) AS SequenceCnt
    FROM #Data
), RankCTE AS (
    SELECT
        *,
        DENSE_RANK() OVER (PARTITION BY SequenceCnt, Sequence ORDER BY SequenceCnt, ID) AS RankNo,
        ROW_NUMBER() OVER (PARTITION BY SequenceCnt, ID ORDER BY Sequence, ID) AS RowNo
    FROM SequenceCTE
)
SELECT Sequence, ID
FROM RankCTE
WHERE RankNo = RowNo
</code>```

Output:

```<code>----------------
Sequence    ID
----------------
214000      2613
213004      4444
111111      5555
111112      5556
214906      2613
214907      2614
214908      2615
</code>```

Update (special case with one ID in a sequence):

```<code>;WITH SequenceCTE AS (
    SELECT
        *,
        COUNT(*) OVER (PARTITION BY Sequence) AS SequenceCnt
    FROM #Data
), RankCTE AS (
    SELECT
        *,
        CASE
            WHEN SequenceCnt = 1 THEN 1
            ELSE DENSE_RANK() OVER (PARTITION BY SequenceCnt, Sequence ORDER BY SequenceCnt, ID)
        END AS RankNo,
        CASE
            WHEN SequenceCnt = 1 THEN 1
            ELSE ROW_NUMBER() OVER (PARTITION BY SequenceCnt, ID ORDER BY Sequence, ID)
        END AS RowNo
    FROM SequenceCTE
)
SELECT Sequence, ID
FROM RankCTE
WHERE RankNo = RowNo
</code>```

Title: How to partition to spread values?

Body:
I have a table with data:

Customers

Sequence

ID

many other columns (not important)

Sample data:

Sequence ID
-----------
214906 2613
214906 2614
214906 2615
214907 2613
214907 2614
214907 2615
214908 2613
214908 2614
214908 2615
214000 2613
213004 4444
111111 5555
111111 5556
111112 5556
111112 5555

How can I get the desired result below?

214906 2613
214907 2614
214908 2615
214000 2613
213004 4444
111111 5555
111112 5556

I tried various stuff with ROW_NUMBER() OVER(PARTITION BY Sequence) but it did not help because I need to take row 1 in first group, row 2 in second group etc. In other words, I need to somehow spread those Sequences across ID's. I cannot partition by ID's either because they might appear more than once in the table

Body:
I hope I understand you correctly. I use the count of IDs per sequence as a group factor (using SUM() with OVER clause without ORDER BY) and after that appropriate ranking and row numbering:

Input:

CREATE TABLE #Data (
    Sequence int,
    ID int
)
INSERT INTO #Data
    (Sequence, ID)
VALUES
    (214906, 2613),
    (214906, 2614),
    (214906, 2615),
    (214907, 2613),
    (214907, 2614),
    (214907, 2615),
    (214908, 2613),
    (214908, 2614),
    (214908, 2615),
    (214000, 2613),
    (213004, 4444),
    (111111, 5555),
    (111111, 5556),
    (111112, 5556),
    (111112, 5555)

T-SQL:

;WITH SequenceCTE AS (
    SELECT
        *,
        COUNT(*) OVER (PARTITION BY Sequence) AS SequenceCnt
    FROM #Data
), RankCTE AS (
    SELECT
        *,
        DENSE_RANK() OVER (PARTITION BY SequenceCnt, Sequence ORDER BY SequenceCnt, ID) AS RankNo,
        ROW_NUMBER() OVER (PARTITION BY SequenceCnt, ID ORDER BY Sequence, ID) AS RowNo
    FROM SequenceCTE
)
SELECT Sequence, ID
FROM RankCTE
WHERE RankNo = RowNo

Output:

----------------
Sequence    ID
----------------
214000      2613
213004      4444
111111      5555
111112      5556
214906      2613
214907      2614
214908      2615

Update (special case with one ID in a sequence):

;WITH SequenceCTE AS (
    SELECT
        *,
        COUNT(*) OVER (PARTITION BY Sequence) AS SequenceCnt
    FROM #Data
), RankCTE AS (
    SELECT
        *,
        CASE
            WHEN SequenceCnt = 1 THEN 1
            ELSE DENSE_RANK() OVER (PARTITION BY SequenceCnt, Sequence ORDER BY SequenceCnt, ID)
        END AS RankNo,
        CASE
            WHEN SequenceCnt = 1 THEN 1
            ELSE ROW_NUMBER() OVER (PARTITION BY SequenceCnt, ID ORDER BY Sequence, ID)
        END AS RowNo
    FROM SequenceCTE
)
SELECT Sequence, ID
FROM RankCTE
WHERE RankNo = RowNo


问:
Convert TSV to CSV, where TSV field has commas in it
I have a TSV with fields that look like:

```<code>name   location   1,2,3,4,5
</code>```

When I use sed 's/\w/,/g'
i end up with a csv where 1,2,3,4 and 5 are considered seperate entrys.
I would like it to be '1 2 3 4 5'
I've tried converting commas to white space before running the above command using

```<code>sed 's/,/\w/g'
</code>```

however when converting the whitespace back to commas it includes single white spaces as well as the tabs, so what is the regex for just a single whitespace character?

Desired output:

```<code>name, location,1 2 3 4 5,
</code>```

答:
As mentionned in a comment CSV usually deals with occurences of its separator character in values by enclosing the value in quotes, so I suggest you simply deal with this by enclosing every value in quotes :

```<code>sed -E 's/([^\t]*)(\t|$)/"\1",/g'
</code>```

You can try it here.

This leaves a trailing comma as in your sample output, if you want to avoid it you can use the following :

```<code>sed -E 's/\t+$//;s/^/"/;s/\t/","/g;s/$/"/'
</code>```

If your original data contains " you will however need to escape those, which you can achieve by adding the following substitution before the other(s) :

```<code>s/"/\\"/g
</code>```

As Ed Morton suggests we can also strip the trailing empty fields :

```<code>s/\t+$//
</code>```

In conclusion I'd use the following :

```<code>sed -E 's/"/\\"/g;s/\t+$//;s/^/"/;s/\t/","/g;s/$/"/'
</code>```

which you can try here.

Body:
I have a TSV with fields that look like:

name   location   1,2,3,4,5

When I use sed 's/\w/,/g'
i end up with a csv where 1,2,3,4 and 5 are considered seperate entrys.
I would like it to be '1 2 3 4 5'
I've tried converting commas to white space before running the above command using

sed 's/,/\w/g'

however when converting the whitespace back to commas it includes single white spaces as well as the tabs, so what is the regex for just a single whitespace character?

Desired output:

name, location,1 2 3 4 5,

Body:
As mentionned in a comment CSV usually deals with occurences of its separator character in values by enclosing the value in quotes, so I suggest you simply deal with this by enclosing every value in quotes :

sed -E 's/([^\t]*)(\t|$)/"\1",/g'

You can try it here.

This leaves a trailing comma as in your sample output, if you want to avoid it you can use the following :

sed -E 's/\t+$//;s/^/"/;s/\t/","/g;s/$/"/'

If your original data contains " you will however need to escape those, which you can achieve by adding the following substitution before the other(s) :

s/"/\\"/g

As Ed Morton suggests we can also strip the trailing empty fields :

s/\t+$//

In conclusion I'd use the following :

sed -E 's/"/\\"/g;s/\t+$//;s/^/"/;s/\t/","/g;s/$/"/'

which you can try here.


问:
What does JSON stringify do in react native
i am new to react native application development.I have some confusion regarding JSON.stringify method.Here is my code.

```<code>fetch('http://link.com', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'multipart/form-data',
        },
        body: formData

    }).then((response) => response.json())
    .then((responseJson) => {
        this.setState({
            loading_status: false
        })

        if (!responseJson.error) {

            var id = responseJson.result.id
            var roles_id = responseJson.result.roles_id

            AsyncStorage.multiSet([
                ['user_id', id.toString()],
                ['roles_id', roles_id.toString()],

            ]);

        } else {
            //error

        }

    }).catch((error) => {
        console.error(error);

        Platform.OS === 'android' ? ToastAndroid.show("Connection Error !", ToastAndroid.SHORT) : Alert.alert("Connection Error !")

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

But main problem arises when i started to make build for that.What i saw is that value which is not in string produces error while writing or reading data from async storage.
It gives me error in ios build something like.
NSnull cannot be converted into NSString
So i changed my code to something like this

```<code> if (!responseJson.error) {

    var id = JSON.stringify(responseJson.result.id)
    var roles_id = JSON.stringify(responseJson.result.roles_id)

    AsyncStorage.multiSet([
        ['user_id', id],
        ['roles_id', roles_id],

    ]);
}
</code>```

Now this works fine in ios build.So my doubt is that how can i parse a json or is there any standart way to parse json in react native so that i did not face problem which is faced while making ios build for react native.

答:
From your example, it's not clear where the null is coming from, but you can take a look at adding a replacer function into the JSON.stringify call.  See this link for details.  Something like:

```<code>function replacer(key, value) {
    if (value === null) {
        return undefined;
    }
    return value;
 }
 ...
 let result = JSON.stringify(responseJSON.result, replacer);
</code>```

This allows you to modify the stringify results as needed.

Body:
i am new to react native application development.I have some confusion regarding JSON.stringify method.Here is my code.

fetch('http://link.com', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'multipart/form-data',
        },
        body: formData

    }).then((response) => response.json())
    .then((responseJson) => {
        this.setState({
            loading_status: false
        })

        if (!responseJson.error) {

            var id = responseJson.result.id
            var roles_id = responseJson.result.roles_id

            AsyncStorage.multiSet([
                ['user_id', id.toString()],
                ['roles_id', roles_id.toString()],

            ]);

        } else {
            //error

        }

    }).catch((error) => {
        console.error(error);

        Platform.OS === 'android' ? ToastAndroid.show("Connection Error !", ToastAndroid.SHORT) : Alert.alert("Connection Error !")

        return;
    });

But main problem arises when i started to make build for that.What i saw is that value which is not in string produces error while writing or reading data from async storage.
It gives me error in ios build something like.
NSnull cannot be converted into NSString
So i changed my code to something like this

 if (!responseJson.error) {

    var id = JSON.stringify(responseJson.result.id)
    var roles_id = JSON.stringify(responseJson.result.roles_id)

    AsyncStorage.multiSet([
        ['user_id', id],
        ['roles_id', roles_id],

    ]);
}

Now this works fine in ios build.So my doubt is that how can i parse a json or is there any standart way to parse json in react native so that i did not face problem which is faced while making ios build for react native.

Body:
From your example, it's not clear where the null is coming from, but you can take a look at adding a replacer function into the JSON.stringify call.  See this link for details.  Something like:

function replacer(key, value) {
    if (value === null) {
        return undefined;
    }
    return value;
 }
 ...
 let result = JSON.stringify(responseJSON.result, replacer);

This allows you to modify the stringify results as needed.


问:
How can I shorten the use of this function? Alexa/NodeJs
I have this function that I am using to return a slot value. If the slot is a synonym, it will revise the synonym to the canonical slot value. Here is the code I have now:

```<code>var slotHelper = function() { };

slotHelper.prototype.slotValue = (slot, useId) => {
    let value = slot.value;
    let resolution = (
        slot.resolutions
        && slot.resolutions.resolutionsPerAuthority
        && slot.resolutions.resolutionsPerAuthority.length > 0
    )
        ? slot.resolutions.resolutionsPerAuthority[0]
        : null;
    if (resolution && resolution.status.code == 'ER_SUCCESS_MATCH') {
        let resolutionValue = resolution.values[0].value;
        value = resolutionValue.id && useId
            ? resolutionValue.id
            : resolutionValue.name;
    }
    return value;
};

//Example
//let category = slotValue(handlerInput.requestEnvelope.request.intent.slots.category, true);

module.exports = new slotHelper();
</code>```

I am trying to shorten the //example to where I can just type this:

```<code>let category = slotHelper.slotValue(category);
</code>```

And return the canonical slot value.

I have tried some different approaches and they all result in: "Error handled: category is not defined"

Here are the different approaches I tried:

```<code>var slotHelper = function() { };

slotHelper.prototype.slotValue = (slotName, useId) => {
    let slot = handlerInput.requestEnvelope.request.intent.slots[slotName];
    let value = slot.value;
    let resolution = (
        slot.resolutions
        && slot.resolutions.resolutionsPerAuthority
        && slot.resolutions.resolutionsPerAuthority.length > 0
    )
        ? slot.resolutions.resolutionsPerAuthority[0]
        : null;
    if (resolution && resolution.status.code == 'ER_SUCCESS_MATCH') {
        let resolutionValue = resolution.values[0].value;
        value = resolutionValue.id && useId
            ? resolutionValue.id
            : resolutionValue.name;
    }
    return value;
}

module.exports = new slotHelper();
</code>```

AND

```<code>var slotHelper = function() { };

slotHelper.prototype.slotValue = (slotName, useId) => {
    let slot = handlerInput.requestEnvelope.request.intent.slots.slotName;
    let value = slot.value;
    let resolution = (
        slot.resolutions
        && slot.resolutions.resolutionsPerAuthority
        && slot.resolutions.resolutionsPerAuthority.length > 0
    )
        ? slot.resolutions.resolutionsPerAuthority[0]
        : null;
    if (resolution && resolution.status.code == 'ER_SUCCESS_MATCH') {
        let resolutionValue = resolution.values[0].value;
        value = resolutionValue.id && useId
            ? resolutionValue.id
            : resolutionValue.name;
    }
    return value;
}

module.exports = new slotHelper();
</code>```

Of course, with the second one slotName is greyed out because that's not the right approach. Does anyone have any idea how I can revise this to where I can use:

```<code>let category = slotHelper.slotValue(category);
</code>```

I am trying to generalize this function so that I can use it for all my slots in the future. This would make it easier to work with in my code... instead of always having to put:

```<code>let category = slotHelper.slotValue(handlerInput.requestEnvelope.request.intent.slots.category);
</code>```

答:
I fixed it myself. I had to put:

```<code>let categories = handlerInput.requestEnvelope.request.intent.slots.category;
</code>```

and

```<code>let category = slotHelper.slotValue(categories);
</code>```

In my index.js (main file) instead of the helper function because the index.js uses the ask-sdk to build responses. The module I created didn't have that capability.

Body:
I have this function that I am using to return a slot value. If the slot is a synonym, it will revise the synonym to the canonical slot value. Here is the code I have now:

var slotHelper = function() { };

slotHelper.prototype.slotValue = (slot, useId) => {
    let value = slot.value;
    let resolution = (
        slot.resolutions
        && slot.resolutions.resolutionsPerAuthority
        && slot.resolutions.resolutionsPerAuthority.length > 0
    )
        ? slot.resolutions.resolutionsPerAuthority[0]
        : null;
    if (resolution && resolution.status.code == 'ER_SUCCESS_MATCH') {
        let resolutionValue = resolution.values[0].value;
        value = resolutionValue.id && useId
            ? resolutionValue.id
            : resolutionValue.name;
    }
    return value;
};

//Example
//let category = slotValue(handlerInput.requestEnvelope.request.intent.slots.category, true);

module.exports = new slotHelper();

I am trying to shorten the //example to where I can just type this:

let category = slotHelper.slotValue(category);

And return the canonical slot value.

I have tried some different approaches and they all result in: "Error handled: category is not defined"

Here are the different approaches I tried:

var slotHelper = function() { };

slotHelper.prototype.slotValue = (slotName, useId) => {
    let slot = handlerInput.requestEnvelope.request.intent.slots[slotName];
    let value = slot.value;
    let resolution = (
        slot.resolutions
        && slot.resolutions.resolutionsPerAuthority
        && slot.resolutions.resolutionsPerAuthority.length > 0
    )
        ? slot.resolutions.resolutionsPerAuthority[0]
        : null;
    if (resolution && resolution.status.code == 'ER_SUCCESS_MATCH') {
        let resolutionValue = resolution.values[0].value;
        value = resolutionValue.id && useId
            ? resolutionValue.id
            : resolutionValue.name;
    }
    return value;
}

module.exports = new slotHelper();

AND

var slotHelper = function() { };

slotHelper.prototype.slotValue = (slotName, useId) => {
    let slot = handlerInput.requestEnvelope.request.intent.slots.slotName;
    let value = slot.value;
    let resolution = (
        slot.resolutions
        && slot.resolutions.resolutionsPerAuthority
        && slot.resolutions.resolutionsPerAuthority.length > 0
    )
        ? slot.resolutions.resolutionsPerAuthority[0]
        : null;
    if (resolution && resolution.status.code == 'ER_SUCCESS_MATCH') {
        let resolutionValue = resolution.values[0].value;
        value = resolutionValue.id && useId
            ? resolutionValue.id
            : resolutionValue.name;
    }
    return value;
}

module.exports = new slotHelper();

Of course, with the second one slotName is greyed out because that's not the right approach. Does anyone have any idea how I can revise this to where I can use:

let category = slotHelper.slotValue(category);

I am trying to generalize this function so that I can use it for all my slots in the future. This would make it easier to work with in my code... instead of always having to put:

let category = slotHelper.slotValue(handlerInput.requestEnvelope.request.intent.slots.category);

Body:
I fixed it myself. I had to put:

let categories = handlerInput.requestEnvelope.request.intent.slots.category;

and

let category = slotHelper.slotValue(categories);

In my index.js (main file) instead of the helper function because the index.js uses the ask-sdk to build responses. The module I created didn't have that capability.


问:
JavaScript isset() equivalent
In PHP you can do if(isset($array['foo'])) { ... }. In JavaScript you often use if(array.foo) { ... } to do the same, but this is not exactly the same statement. The condition will also evaluate to false if array.foo does exists but is false or 0 (and probably other values as well).

What is the perfect equivalent of PHP's isset in JavaScript?

In a broader sense, a general, complete guide on JavaScript's handling of variables that don't exist, variables without a value, etc. would be convenient.

Update: 11 years and 11 months ago I posted this question, and wow, it still gets a lot of activity. Now, I'm pretty sure that when I wrote this, I only wanted to know how to check for the presence of a property in an associative array (a.k.a. dictionary), and as such the correct (for me) answers involve hasOwnProperty or the in operator. I wasn't interested in checking local or global variables.

But while I remember that well, that intent is not quite clear in the question as written, or even directly contradicted by it! I never mentioned the associative array, and PHP's isset does also do those other things. Let this be a lesson to all of us about how important it is to properly state your requirements in a question, and also how global variables, local variables, object properties, dictionary keys and what-have-you aren't Huey, Dewey, and Louie.

In the meantime (heh), many many people have provided answers to that effect as well, so for those of you who found this question through Google, well, I'm glad my vagueness helped in a way I guess. Anyway, just wanted to clarify that.

答:
I use a function that can check variables and objects. very convenient to work with jQuery</p>

```<code>    function _isset (variable) {
        if(typeof(variable) == "undefined" || variable == null)
            return false;
        else
            if(typeof(variable) == "object" && !variable.length)
                return false;
            else
                return true;
    };
</code>```

Title: JavaScript isset() equivalent

Body:
I use a function that can check variables and objects. very convenient to work with jQuery

    function _isset (variable) {
        if(typeof(variable) == "undefined" || variable == null)
            return false;
        else
            if(typeof(variable) == "object" && !variable.length)
                return false;
            else
                return true;
    };


问:
collect numbers and convert them to date in angularjs
I have 3 scopes in angularjs, one for year, one for month and one for day coming from 3 input boxes. I want to combine them as date, the following code insert the date correctly but with 22:00:00 added to it like  2019-06-01 22:00:00.000.
How to insert the date only without time

HTML

```<code><div class="col-md-1">
    <div class="form-group has-error">
        <label class="title_lable">Year:</label>
        <input id="code" type="number" class="form-control input-sm"
               ng-model="year">
    </div>
</div>
<div class="col-md-2">
    <div class="form-group has-error">
        <label class="title_lable">Latin Description:</label>
        <input type="text" class="form-control input-sm"
               ng-model="latindesc">
    </div>
</div>
<div class="col-md-2">
    <div class="form-group">
        <label class="title_lable">Local Description:</label>
        <input type="text" class="form-control input-sm"
               ng-model="localdesc">
    </div>
</div>
<div class="col-md-1">
    <div class="form-group">
        <label class="title_lable">Month:</label>
        <select ng-show="lang==1" class="form-control input-sm"
                ng-model="month"
                ng-options="m.mnthid as m.mnthanm for m in months">
        </select>
        <select ng-show="lang==0" class="form-control input-sm"
                ng-model="month"
                ng-options="m.mnthid as m.mnthenm for m in months">
        </select>
    </div>
</div>
<div class="col-md-1">
    <div class="form-group">
        <label class="title_lable">Day:</label>
        <input type="number" class="form-control input-sm" ng-model="day">
    </div>
</div>
</code>```

Angular

```<code>var dFrom = new Date($scope.month + '/' + ($scope.day + 1) + '/' + $scope.year );
        var days = $scope.ndays;
        console.log(days);
        var todate = new Date($scope.month + '/' + ($scope.day +1) + '/' + $scope.year);
        todate = addDays(todate, days - 1);
        console.log(todate);

        var vacation = {
            Sys_Key: $scope.syskey,
            Vac_Code: $scope.code,
            L_Desc: $scope.latindesc,
            A_Desc: $scope.localdesc,
            V_Start_Date: $scope.day,
            V_Month: $scope.month,
            V_Days_Count: $scope.ndays,
            V_Year: $scope.year,
            From_Date: dFrom,
            To_Date: todate
        }
</code>```

```<code>function addDays(startDate, numberOfDays) {
    var returnDate = new Date(
        startDate.getFullYear(),
        startDate.getMonth(),
        startDate.getDate() + numberOfDays,
        startDate.getHours(),
        startDate.getMinutes(),
        startDate.getSeconds()
    );
    return returnDate;
}
</code>```

答:
You can do it as,

let dateString = "05/05/1997";

let date = new Date(dateString);

console.log(date.toLocaleString('en-US', {
      day:"2-digit",
      month:"2-digit",
      year:"numeric"
    }));```

Please checkout following link,

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

Body:
I have 3 scopes in angularjs, one for year, one for month and one for day coming from 3 input boxes. I want to combine them as date, the following code insert the date correctly but with 22:00:00 added to it like  2019-06-01 22:00:00.000.
How to insert the date only without time

HTML

        Year:
        <input id="code" type="number" class="form-control input-sm"
               ng-model="year">

        Latin Description:
        <input type="text" class="form-control input-sm"
               ng-model="latindesc">

        Local Description:
        <input type="text" class="form-control input-sm"
               ng-model="localdesc">

        Month:
        <select ng-show="lang==1" class="form-control input-sm"
                ng-model="month"
                ng-options="m.mnthid as m.mnthanm for m in months">
        </select>
        <select ng-show="lang==0" class="form-control input-sm"
                ng-model="month"
                ng-options="m.mnthid as m.mnthenm for m in months">
        </select>

        Day:
        <input type="number" class="form-control input-sm" ng-model="day">

Angular

var dFrom = new Date($scope.month + '/' + ($scope.day + 1) + '/' + $scope.year );
        var days = $scope.ndays;
        console.log(days);
        var todate = new Date($scope.month + '/' + ($scope.day +1) + '/' + $scope.year);
        todate = addDays(todate, days - 1);
        console.log(todate);

        var vacation = {
            Sys_Key: $scope.syskey,
            Vac_Code: $scope.code,
            L_Desc: $scope.latindesc,
            A_Desc: $scope.localdesc,
            V_Start_Date: $scope.day,
            V_Month: $scope.month,
            V_Days_Count: $scope.ndays,
            V_Year: $scope.year,
            From_Date: dFrom,
            To_Date: todate
        }

function addDays(startDate, numberOfDays) {
    var returnDate = new Date(
        startDate.getFullYear(),
        startDate.getMonth(),
        startDate.getDate() + numberOfDays,
        startDate.getHours(),
        startDate.getMinutes(),
        startDate.getSeconds()
    );
    return returnDate;
}

Body:
You can do it as,

let dateString = "05/05/1997";

let date = new Date(dateString);

console.log(date.toLocaleString('en-US', {
      day:"2-digit",
      month:"2-digit",
      year:"numeric"
    }));

Please checkout following link,

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString


问:
Dart style recommendation on importing local file
Is there any recommendation how to import local files. In my case I would have 2 options:

import 'package:workshop/feed/item.dart';

import 'item.dart';

I haven't found anything on that on the guide Effective Dart: Style nor on Google search.

答:
There are at least two different recommendations, depending on who you ask.
Either works, I personally recommend the latter, shorter, variant.
It is sufficient and it avoids the issue of hard-coding your package name into every file. If you ever want to rename the package, that will be a drudge.

There is one issue which makes some people recommend the former format.
If you import a package library using a non-package: URI, say by having a file in the bin/ or test/ directory do an import like:

```<code>import "../lib/mylib.dart";
</code>```

then that library is now imported using two different URIs:

package:mypkg/mylib.dart and

file:///somewhere/mypkg/lib/mylib.dart

Since Dart identifies libraries by their import URIs, these two imports will be treated as different libraries, each with their own global and static variables, which just happen to have the same source code. That's an annoying problem, and can be hard to debug. If you use the long package:... import everywhere, then at least the issue is restricted to the first library you import. If you use a relative import, import "src/helper.dart";, then that library will now also exist in two versions:

package:mypkg/src/helper.dart and

file:///somewhere/mypkg/lib/src/helper.dart

The real issue here was the first import which contained a /lib/ in the path. You must never have such an import. Using package: URIs for all imports may reduce the issue, but not remove it.

I recommend using the relative path, and making sure that you never have a /lib/ in any import path. Libraries in the /lib/ directory of a pub package are package libraries and should be referred to using package: URIs. If you do that, then relative URIs will be resolved against the package URI and again be a package URI, and all is well.

Body:
There are at least two different recommendations, depending on who you ask.
Either works, I personally recommend the latter, shorter, variant.
It is sufficient and it avoids the issue of hard-coding your package name into every file. If you ever want to rename the package, that will be a drudge.

There is one issue which makes some people recommend the former format.
If you import a package library using a non-package: URI, say by having a file in the bin/ or test/ directory do an import like:

import "../lib/mylib.dart";

then that library is now imported using two different URIs:

package:mypkg/mylib.dart and

file:///somewhere/mypkg/lib/mylib.dart

Since Dart identifies libraries by their import URIs, these two imports will be treated as different libraries, each with their own global and static variables, which just happen to have the same source code. That's an annoying problem, and can be hard to debug. If you use the long package:... import everywhere, then at least the issue is restricted to the first library you import. If you use a relative import, import "src/helper.dart";, then that library will now also exist in two versions:

package:mypkg/src/helper.dart and

file:///somewhere/mypkg/lib/src/helper.dart

The real issue here was the first import which contained a /lib/ in the path. You must never have such an import. Using package: URIs for all imports may reduce the issue, but not remove it.

I recommend using the relative path, and making sure that you never have a /lib/ in any import path. Libraries in the /lib/ directory of a pub package are package libraries and should be referred to using package: URIs. If you do that, then relative URIs will be resolved against the package URI and again be a package URI, and all is well.