问:
Splice function on an array of objects
I'm doing a react/javascript exercice and i'm having some trouble understanding the use of splice() in it.
I have 8 cards, and i need to randomly assign 4 cards to 2 players. Now everything works fine, but i don't understand the [0] at the end of the let randPokemon = hand2.splice(randIndex, 1)[0]; line.

Here is the full code :

```<code>import React, { Component } from "react";
import Pokedex from "./Pokedex";

class Pokegame extends Component {
  static defaultProps = {
    pokemon: [
      { id: 4, name: "Charmander", type: "fire", experience: 62 },
      { id: 7, name: "Squirtle", type: "water", experience: 63 },
      { id: 11, name: "Metapod", type: "bug", experience: 72 },
      { id: 12, name: "Butterfree", type: "flying", experience: 178 },
      { id: 25, name: "Pikachu", type: "electric", experience: 112 },
      { id: 39, name: "Jigglypuff", type: "normal", experience: 95 },
      { id: 94, name: "Gengar", type: "poison", experience: 225 },
      { id: 133, name: "Eevee", type: "normal", experience: 65 }
    ]
  };

  render() {
    let hand1 = [];
    let hand2 = [...this.props.pokemon];

    while (hand1.length < hand2.length) {
      let randIndex = Math.floor(Math.random() * hand2.length);
      let randPokemon = hand2.splice(randIndex, 1)[0];
      hand1.push(randPokemon);
    }

    console.log(hand1);
    console.log(hand2);

    return (
      <div className="Pokegame">
        <h1>Pokegame!</h1>
      </div>
    );
  }
}

export default Pokegame;

</code>```

I understand (correct me if i'm wrong) that the splice() function can take 2 or more arguments : the first one is the index telling what position to add/remove items, the second one is the number of items to add/remove, and the next arguments being the items we want to add (but i don't use it here since i only want to remove the selected item and add it to the first hand).

Now in this case, i'm having trouble to understand how that [0] works or why it's here...

答: The splice-method adds or removes items from an array. It also returns always an  array-object, so the [0] is to access the first element in that array created/modified by splice.

Title: Splice function on an array of objects

Body:
I'm doing a react/javascript exercice and i'm having some trouble understanding the use of splice() in it.
I have 8 cards, and i need to randomly assign 4 cards to 2 players. Now everything works fine, but i don't understand the [0] at the end of the let randPokemon = hand2.splice(randIndex, 1)[0]; line.

Here is the full code :

import React, { Component } from "react";
import Pokedex from "./Pokedex";

class Pokegame extends Component {
  static defaultProps = {
    pokemon: [
      { id: 4, name: "Charmander", type: "fire", experience: 62 },
      { id: 7, name: "Squirtle", type: "water", experience: 63 },
      { id: 11, name: "Metapod", type: "bug", experience: 72 },
      { id: 12, name: "Butterfree", type: "flying", experience: 178 },
      { id: 25, name: "Pikachu", type: "electric", experience: 112 },
      { id: 39, name: "Jigglypuff", type: "normal", experience: 95 },
      { id: 94, name: "Gengar", type: "poison", experience: 225 },
      { id: 133, name: "Eevee", type: "normal", experience: 65 }
    ]
  };

  render() {
    let hand1 = [];
    let hand2 = [...this.props.pokemon];

    while (hand1.length < hand2.length) {
      let randIndex = Math.floor(Math.random() * hand2.length);
      let randPokemon = hand2.splice(randIndex, 1)[0];
      hand1.push(randPokemon);
    }

    console.log(hand1);
    console.log(hand2);

    return (

Pokegame!

    );
  }
}

export default Pokegame;

I understand (correct me if i'm wrong) that the splice() function can take 2 or more arguments : the first one is the index telling what position to add/remove items, the second one is the number of items to add/remove, and the next arguments being the items we want to add (but i don't use it here since i only want to remove the selected item and add it to the first hand).

Now in this case, i'm having trouble to understand how that [0] works or why it's here...


来源: stackexchange

问:
Help writing a stored procedure / SQL Query error
I have table tblcategory with columns categoryid , shopid , title, logicalcode.

I have a second table tblproduct with columns productid, shopid, producttitle ,price ,logicalcode , available.

I have a third table categoryproduct with columns categoryproductid, categoryid, productid

I have a grid view for displaying products in a given category with columns producttitle and logicalcode.

I have written a stored procedure with input parameter as categoryid (mandatory) to get the list of products in that category:

```<code>@categoryid int
AS
BEGIN
  SELECT P.Title, P.LogicalCode
  FROM tblProduct AS P
  JOIN  tblCategory AS C
  WHERE P.LogicalCode=C.LogicalCode AND
  WHERE C.CategoryID=@categoryid
END
</code>```

But I got the error near to "WHERE" condition

Would anyone please help me out?

答:
Should be:</p>

```<code>SELECT P.Title,P.LogicalCode
FROM tblProduct AS P JOIN  tblCategory AS C
WHERE P.LogicalCode=C.LogicalCode
AND  C.CategoryID=@categoryid
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have table tblcategory with columns categoryid , shopid , title, logicalcode.

I have a second table tblproduct with columns productid, shopid, producttitle ,price ,logicalcode , available.

I have a third table categoryproduct with columns categoryproductid, categoryid, productid

I have a grid view for displaying products in a given category with columns producttitle and logicalcode.

I have written a stored procedure with input parameter as categoryid (mandatory) to get the list of products in that category:

@categoryid int
AS
BEGIN
  SELECT P.Title, P.LogicalCode
  FROM tblProduct AS P
  JOIN  tblCategory AS C
  WHERE P.LogicalCode=C.LogicalCode AND
  WHERE C.CategoryID=@categoryid
END

But I got the error near to "WHERE" condition

Would anyone please help me out?

Body:
Should be:

SELECT P.Title,P.LogicalCode
FROM tblProduct AS P JOIN  tblCategory AS C
WHERE P.LogicalCode=C.LogicalCode
AND  C.CategoryID=@categoryid


问:
use module signature definition in module implementation
I'm not very familiar with modules in Coq, but it was brought up in a recent question I asked. I have the following code.

```<code>Module Type Sig.
Parameter n : nat.
Definition n_plus_1 := n + 1.
End Sig.

Module ModuleInstance <: Sig.
Definition n := 3.
End ModuleInstance.
</code>```

Coq complains about the definition of n_plus_1 when I try to run End ModuleInstance. I'm not sure if this is a correct way to use modules, but I want it to just use the definition in the signature, it's a complete definition that doesn't need any additional information. Is it possible to do it?

答:
As an alternative to https://stackoverflow.com/a/49322214/53974, one can sometimes use Include, which supports a very limited special case of recursive linking.
Like in that answer, you should put your definitions in a module functor, but then you can Include that, both in the rest of your signature, and in the implementing module. That allows to reuse your definitions to shorten the declarations, and to have them as part of the same module.

```<code>Require Import Omega.

Module Type Sig.
  Parameter n : nat.
End Sig.

(* this is the module functor *)
Module SigUtils (S:Sig).
  Definition n_plus_1 := S.n + 1.
End SigUtils.

Module ModuleInstance <: Sig.
  Definition n := 3.
  Include SigUtils.
End ModuleInstance.
Print ModuleInstance.

Module Type Sig2 <: Sig.
  Include Sig.
  Include SigUtils.
  Parameter n_plus_1_eq: n_plus_1 = 1 + n.
End Sig2.

Module ModuleInstance2 <: Sig2.
  Include ModuleInstance.

  Lemma n_plus_1_eq: n_plus_1 = 1 + n.
  Proof. unfold n_plus_1. omega. Qed.

  Lemma n_plus_1_neq: n_plus_1 <> 2 + n.
  Proof. unfold n_plus_1. omega. Qed.
End ModuleInstance2.

Print ModuleInstance2.
</code>```

However, you'll want to beware the semantics of Include (see e.g.
https://stackoverflow.com/a/49717951/53974). In particular, should you include a module in two different modules, you'll get distinct definitions. Above, SigUtils is included once in a Module Type and once in an implementing Module, which is allowed.

EDIT: I found a big application of this pattern in the Coq standard library.
Lots of properties of numbers are proved generically and collected in various module types (such as NExtraProp here), and then used in concrete definitions through Include, such as here.

Body:
I'm not very familiar with modules in Coq, but it was brought up in a recent question I asked. I have the following code.

Module Type Sig.
Parameter n : nat.
Definition n_plus_1 := n + 1.
End Sig.

Module ModuleInstance <: Sig.
Definition n := 3.
End ModuleInstance.

Coq complains about the definition of n_plus_1 when I try to run End ModuleInstance. I'm not sure if this is a correct way to use modules, but I want it to just use the definition in the signature, it's a complete definition that doesn't need any additional information. Is it possible to do it?

Body:
As an alternative to https://stackoverflow.com/a/49322214/53974, one can sometimes use Include, which supports a very limited special case of recursive linking.
Like in that answer, you should put your definitions in a module functor, but then you can Include that, both in the rest of your signature, and in the implementing module. That allows to reuse your definitions to shorten the declarations, and to have them as part of the same module.

Require Import Omega.

Module Type Sig.
  Parameter n : nat.
End Sig.

(* this is the module functor *)
Module SigUtils (S:Sig).
  Definition n_plus_1 := S.n + 1.
End SigUtils.

Module ModuleInstance <: Sig.
  Definition n := 3.
  Include SigUtils.
End ModuleInstance.
Print ModuleInstance.

Module Type Sig2 <: Sig.
  Include Sig.
  Include SigUtils.
  Parameter n_plus_1_eq: n_plus_1 = 1 + n.
End Sig2.

Module ModuleInstance2 <: Sig2.
  Include ModuleInstance.

  Lemma n_plus_1_eq: n_plus_1 = 1 + n.
  Proof. unfold n_plus_1. omega. Qed.

  Lemma n_plus_1_neq: n_plus_1 <> 2 + n.
  Proof. unfold n_plus_1. omega. Qed.
End ModuleInstance2.

Print ModuleInstance2.

However, you'll want to beware the semantics of Include (see e.g.
https://stackoverflow.com/a/49717951/53974). In particular, should you include a module in two different modules, you'll get distinct definitions. Above, SigUtils is included once in a Module Type and once in an implementing Module, which is allowed.

EDIT: I found a big application of this pattern in the Coq standard library.
Lots of properties of numbers are proved generically and collected in various module types (such as NExtraProp here), and then used in concrete definitions through Include, such as here.

ContentLicense: CC BY-SA 4.0


问:
How to sync cordova builded app with firebase
How does firebase sync a Cordova built app ???

I do want my firebase console to identify my Cordova apk.

(knowing how many users are on my app, analytics... )

答: You can use cordova-plugin-firebase https://www.npmjs.com/package/cordova-plugin-firebase


问:
Creating a wordpress virtual page with a function and page template
I'm trying to create a virtual contact page on wordpress. All the necessary data will be stored in a page template. But in my function I don't know how to link to the file.

When the user does to domain.com/contact I would like to redirect him to the contact.php file.

So far I got this function to work and show content from this line $post->post_content   = 'page template: contact.php'; but I would like to show the content from templates/contact.php

```<code>add_filter( 'the_posts', 'generate_contact_page', -10 );

function generate_contact_page( $posts ) {
global $wp, $wp_query;

$url_slug = 'contact'; // URL slug of the contact page

if ( ! defined( 'CONTACT_PAGE' ) && ( strtolower( $wp->request ) == $url_slug ) ) {

    // stop interferring with other $posts arrays on this page (only works if the sidebar is rendered *after* the main page)
    define( 'CONTACT_PAGE', true );

    // create a contact virtual page
    $post = new stdClass;
    $post->post_author    = 1;
    $post->post_name      = $url_slug;
    $post->guid           = home_url() . '/' . $url_slug;
    $post->post_title     = 'Contact page';
    $post->post_content   = 'page template: contact.php';
    $post->ID             = -999;
    $post->post_type      = 'page';
    $post->post_status    = 'static';
    $post->comment_status = 'closed';
    $post->ping_status    = 'open';
    $post->comment_count  = 0;
    $post->post_date      = current_time( 'mysql' );
    $post->post_date_gmt  = current_time( 'mysql', 1 );
    $posts                = NULL;
    $posts[]              = $post;

    // make wpQuery believe this is a real page too
    $wp_query->is_page             = true;
    $wp_query->is_singular         = true;
    $wp_query->is_home             = false;
    $wp_query->is_archive          = false;
    $wp_query->is_category         = false;
    unset( $wp_query->query[ 'error' ] );
    $wp_query->query_vars[ 'error' ] = '';
    $wp_query->is_404 = false;
}

return $posts;
}
</code>```

How can I achieve something like this? Maybe you know a better solution ?

答:
So for template output you can try this function

```<code>function get_template_output($slug = '', $name = '') {
    ob_start();
    get_template_part($lug, $name);
    return ob_get_clean();
}
</code>```

And then to assign content you will use

```<code>$content = get_template_output('templates/', 'contact');
</code>```

Body:
I'm trying to create a virtual contact page on wordpress. All the necessary data will be stored in a page template. But in my function I don't know how to link to the file.

When the user does to domain.com/contact I would like to redirect him to the contact.php file.

So far I got this function to work and show content from this line $post->post_content   = 'page template: contact.php'; but I would like to show the content from templates/contact.php

add_filter( 'the_posts', 'generate_contact_page', -10 );

function generate_contact_page( $posts ) {
global $wp, $wp_query;

$url_slug = 'contact'; // URL slug of the contact page

if ( ! defined( 'CONTACT_PAGE' ) && ( strtolower( $wp->request ) == $url_slug ) ) {

    // stop interferring with other $posts arrays on this page (only works if the sidebar is rendered *after* the main page)
    define( 'CONTACT_PAGE', true );

    // create a contact virtual page
    $post = new stdClass;
    $post->post_author    = 1;
    $post->post_name      = $url_slug;
    $post->guid           = home_url() . '/' . $url_slug;
    $post->post_title     = 'Contact page';
    $post->post_content   = 'page template: contact.php';
    $post->ID             = -999;
    $post->post_type      = 'page';
    $post->post_status    = 'static';
    $post->comment_status = 'closed';
    $post->ping_status    = 'open';
    $post->comment_count  = 0;
    $post->post_date      = current_time( 'mysql' );
    $post->post_date_gmt  = current_time( 'mysql', 1 );
    $posts                = NULL;
    $posts[]              = $post;

    // make wpQuery believe this is a real page too
    $wp_query->is_page             = true;
    $wp_query->is_singular         = true;
    $wp_query->is_home             = false;
    $wp_query->is_archive          = false;
    $wp_query->is_category         = false;
    unset( $wp_query->query[ 'error' ] );
    $wp_query->query_vars[ 'error' ] = '';
    $wp_query->is_404 = false;
}

return $posts;
}

How can I achieve something like this? Maybe you know a better solution ?

Body:
So for template output you can try this function

function get_template_output($slug = '', $name = '') {
    ob_start();
    get_template_part($lug, $name);
    return ob_get_clean();
}

And then to assign content you will use

$content = get_template_output('templates/', 'contact');


答:
If you take a look at the splice reference you'll see that it actually returns an array of items that were removed by the operation.

So in this case it would remove one pokemon from the hand2 array at the random index and return an array with one item.

[0] takes that item out of the array ad places it in the randPokemon variable.

Title: Splice function on an array of objects


答:
Because splice always returns an array - the [0] extracts the first (and only) element. You could use destructuring to achieve the same purpose:

```<code>let [randPokemon] = hand2.splice(randIndex, 1);
</code>```

Title: Splice function on an array of objects

Body:
Because splice always returns an array - the [0] extracts the first (and only) element. You could use destructuring to achieve the same purpose:

let [randPokemon] = hand2.splice(randIndex, 1);


问:
how to auto increment with 1 after deleting data from table
i'm deleting previous data and trying to insert new list of data,id values are keep on increment because of auto-increment. is it possible to have new auto increment id with 1 ?

and i tried with  ALTER TABLE table AUTO_INCREMENT = 1; its not working for me.

答:
You cannot reset the counter to a value less than or equal to the
  value that is currently in use. For both InnoDB and MyISAM, if the
  value is less than or equal to the maximum value currently in the
  AUTO_INCREMENT column, the value is reset to the current maximum
  AUTO_INCREMENT column value plus one.

And also read this article Link

Just visit this question


问:
Eager loading includes endless self-join tables without include tables
when i try to select some items, items are coming with their includes despite i did not include their object to linq

```<code>public List<Institution> GetListWithCities(Expression<Func<Institution,bool>> filter = null)
{

   using (var context = new DbContext())
   {
    return filter == null
           ? context.Set<Institution>()
                    .Include(x => x.City)
                    .ToList()
           : context.Set<Institution>()
                    .Include(x => x.City)
                    .Where(filter)
                    .ToList();
  }
}

[Table("Institution")]
 public class Institution{
    public int ID;
    public string Name;
    public int CITY_ID;
    public int RESPONSIBLE_INSTUTION_ID;
    public virtual City City{ get; set; }
    public virtual Institution ResponsibleInstution{ get; set; }
}
</code>```

I expect a result include with city of instution but my method returns city and responsible instution. And it continues recursively.

答:
People tend to use Include instead of Select while they don't plan to use the functionality that Include gives, but still wasting the processing power that Include uses.

In entity framework always use Select to fetch some data. Only user Include if you plan to update the included items.

One of the slower parts of a database query is the transport from the fetched data from the database management system to your local process. Hence it is wise to Select only those properties that you really plan to use.

Apparently your Institution is in exactly one City, namely the City that the foreign key (CityId?) is referring to. If Institution [10] is located in City [15], then Institution.CityId will have a value 15, equal to City.Id. So you are transferring this value twice.

```<code>using (var dbContext = new MyDbContext())
{
    IQueryable<Institution> filteredInstitutions = (filter == null) ?
        dbContext.Institutions :
        dbContext.Institutions.Where(filter);
    return filteredInstitutions.Select(institution => new Institution
    {
        // Select only the Institution properties that you actually plan to use:
        Id = institution.Id,
        Name = institution.Name,

        City = new City
        {
            Id = institution.City.Id,
            Name = institution.City.Name,
            ...
        }

        // not needed: you already know the value:
        // CityId = institution.City.Id,
});
</code>```

Possible improvement
Apparently you chose to add a layer between entity framework and the users of your functions: although they use your functions, they don't really have to know that you use entity framework to access the database. This gives your the freedom to use SQL instead of entity framework. Hell, it even gives you the freedom to get rid of your database and use an XML file instead of a DBMS: your users won't know the difference: nice if you want to write unit tests.

Although you chose to separate the method you use to persist the data, you chose to expose your database layout, inclusive foreign keys to the outside world. This makes it more difficult to change your database in future: your users have to change as well.

Consider writing repository classes for Institution and City that only expose those properties that the users of your persistency really need. If people only query "some properties of institutions with some properties of the City in which they are located", or the other way round "Several properties of Cities with several properties of the Institutions located in these Cities", then they won't need the foreign keys.

The intermediate repository classes give you more freedom to change your database. Apart from that, it will give you the freedom to hide certain properties for certain users.

For instance: suppose you add the possibility to delete an institution, but you don't want to immediately delete all information about this institution, for instance because this allows you to restore if someone accidently deletes the institution, you might add a nullable property ObsoleteDate

Moest people that query institutions, don't want the obsolete institutions. If you had an intermediate repository institution class, where you omitted the ObsoleteDate, and all queries removed all Institutions that have a non-zero ObsoleteData, then for your users it would be as if an obsolete institution would have been deleted from the database.

Only one user will need access to the ObsoleteDate: a cleaner task, that every now and then deleted all Institutions that are obsolete for a considerable time.

A third improvement for an intermediate repository class would be that you can give different users access to the same data, with different interfaces: some users can only query information about institutions, some are also allowed to change some data, while others are allowed to change other data. If you give them an interface, they can break this by casting them back to the original Institution.

With separate repository classes, you will have the possibility to give each of these users their own data, and nothing more than this data.

The disadvantage of a repository pattern is that you have to think about different users, and create different query functions. The advantages is that a repository is easier to change and easier to test, and thus easier to keep everything bug free after future changes.

Body:
when i try to select some items, items are coming with their includes despite i did not include their object to linq

public List<Institution> GetListWithCities(Expression<Func<Institution,bool>> filter = null)
{

   using (var context = new DbContext())
   {
    return filter == null
           ? context.Set<Institution>()
                    .Include(x => x.City)
                    .ToList()
           : context.Set<Institution>()
                    .Include(x => x.City)
                    .Where(filter)
                    .ToList();
  }
}

[Table("Institution")]
 public class Institution{
    public int ID;
    public string Name;
    public int CITY_ID;
    public int RESPONSIBLE_INSTUTION_ID;
    public virtual City City{ get; set; }
    public virtual Institution ResponsibleInstution{ get; set; }
}

I expect a result include with city of instution but my method returns city and responsible instution. And it continues recursively.

Body:
People tend to use Include instead of Select while they don't plan to use the functionality that Include gives, but still wasting the processing power that Include uses.

In entity framework always use Select to fetch some data. Only user Include if you plan to update the included items.

One of the slower parts of a database query is the transport from the fetched data from the database management system to your local process. Hence it is wise to Select only those properties that you really plan to use.

Apparently your Institution is in exactly one City, namely the City that the foreign key (CityId?) is referring to. If Institution [10] is located in City [15], then Institution.CityId will have a value 15, equal to City.Id. So you are transferring this value twice.

using (var dbContext = new MyDbContext())
{
    IQueryable<Institution> filteredInstitutions = (filter == null) ?
        dbContext.Institutions :
        dbContext.Institutions.Where(filter);
    return filteredInstitutions.Select(institution => new Institution
    {
        // Select only the Institution properties that you actually plan to use:
        Id = institution.Id,
        Name = institution.Name,

        City = new City
        {
            Id = institution.City.Id,
            Name = institution.City.Name,
            ...
        }

        // not needed: you already know the value:
        // CityId = institution.City.Id,
});

Possible improvement
Apparently you chose to add a layer between entity framework and the users of your functions: although they use your functions, they don't really have to know that you use entity framework to access the database. This gives your the freedom to use SQL instead of entity framework. Hell, it even gives you the freedom to get rid of your database and use an XML file instead of a DBMS: your users won't know the difference: nice if you want to write unit tests.

Although you chose to separate the method you use to persist the data, you chose to expose your database layout, inclusive foreign keys to the outside world. This makes it more difficult to change your database in future: your users have to change as well.

Consider writing repository classes for Institution and City that only expose those properties that the users of your persistency really need. If people only query "some properties of institutions with some properties of the City in which they are located", or the other way round "Several properties of Cities with several properties of the Institutions located in these Cities", then they won't need the foreign keys.

The intermediate repository classes give you more freedom to change your database. Apart from that, it will give you the freedom to hide certain properties for certain users.

For instance: suppose you add the possibility to delete an institution, but you don't want to immediately delete all information about this institution, for instance because this allows you to restore if someone accidently deletes the institution, you might add a nullable property ObsoleteDate

Moest people that query institutions, don't want the obsolete institutions. If you had an intermediate repository institution class, where you omitted the ObsoleteDate, and all queries removed all Institutions that have a non-zero ObsoleteData, then for your users it would be as if an obsolete institution would have been deleted from the database.

Only one user will need access to the ObsoleteDate: a cleaner task, that every now and then deleted all Institutions that are obsolete for a considerable time.

A third improvement for an intermediate repository class would be that you can give different users access to the same data, with different interfaces: some users can only query information about institutions, some are also allowed to change some data, while others are allowed to change other data. If you give them an interface, they can break this by casting them back to the original Institution.

With separate repository classes, you will have the possibility to give each of these users their own data, and nothing more than this data.

The disadvantage of a repository pattern is that you have to think about different users, and create different query functions. The advantages is that a repository is easier to change and easier to test, and thus easier to keep everything bug free after future changes.


问:
ZeroMQ, async blocking sockets
I'm building a distributed system and I would like asynchronous send and recv from both sides with blocking after high water mark.

PUSH/PULL sockets works great, but I wasn't able to bind a PUSH socket. Meaning I can't have a client-PUSH to server-PULL and a server-PUSH to client-PULL, if the client is behind a firewall, since the server can't connect to the client.

In the book, the following is written, but I can't find an example of it.
"REQ to DEALER: you could in theory do this, but it would break if you added a second REQ because DEALER has no way of sending a reply to the original peer. Thus the REQ socket would get confused, and/or return messages meant for another client." http://zguide.zeromq.org/php:chapter3

I only need a one-to-one connection, so this would in theory work for me.

My question is, what is the best practice to obtain asynchronous send and recv with ZeroMQ without dropping packets?

答:
Most ZeroMQ sockets can both bind (listen on a specific port, acting as a server) and connect (acting as a client). It is usually not related to the data flow. See the guide for more info.

Try to bind on your servers PUSH socket and connect from your clients PULL socket.

Title: ZeroMQ, async blocking sockets


问:
Configure ports in WebStorm - React + Node Express app
I am going to do a fullstack implementation with WebStorm IDE. I use react.js and node-express for this. I can do this in separate projects. But I want to know how to implement both backend and frontend in WebStorm project while configuring ports.

When starting the frontend we can give start html file in package.json file under "start": "parcel index.html". When starting backend we can give "node app.js" But this can be done when we are doing the implementation in two different projects.

But if we are doing both frontend and backend how can I start react part and node-express part on two different ports? For example:

- react app > localhost:1234

- node-express > localhost:3000

```<code>"start": "parcel index.html"
"start": "node app.js"
</code>```

// in package.json we can set only one start

答:
You can use a package like npm-run-all to achieve this. Install it then have two separate scripts (like start-front-end and start-server) in your package.json that npm-run-all runs both of e.g.</p>

```<code>"scripts": {
  "start-front-end": "parcel index.html --open",
  "start-server": "node app.js",
  "start": "npm-run-all start-server start-front-end",
}
</code>```

Body:
I am going to do a fullstack implementation with WebStorm IDE. I use react.js and node-express for this. I can do this in separate projects. But I want to know how to implement both backend and frontend in WebStorm project while configuring ports.

When starting the frontend we can give start html file in package.json file under "start": "parcel index.html". When starting backend we can give "node app.js" But this can be done when we are doing the implementation in two different projects.

But if we are doing both frontend and backend how can I start react part and node-express part on two different ports? For example:

- react app > localhost:1234

- node-express > localhost:3000

"start": "parcel index.html"
"start": "node app.js"

// in package.json we can set only one start

Body:
You can use a package like npm-run-all to achieve this. Install it then have two separate scripts (like start-front-end and start-server) in your package.json that npm-run-all runs both of e.g.

"scripts": {
  "start-front-end": "parcel index.html --open",
  "start-server": "node app.js",
  "start": "npm-run-all start-server start-front-end",
}


问:
How to display multiple widgets on the same page using MVC
I'm a bit confused about how MVC works and I can't find anything but basic examples.

I want to make a kind of widget-based design; you can choose various widgets to go on your page.  Each widget should be responsible for itself - it should have a controller and a view.   But what about the main page?  Suddenly I've got a page with lots of controllers on it!

The obvious thing to do is to embed the controllers in the view somehow... This is my widget {SomeWidget} but I've read that "breaks the MVC paradigm".

Some widgets will need to POST to different urls (like a search box goes to the result page) and some will need to POST back to the same URL (like adding a comment to an article brings you back to the article).

To top things off, the user should be able to edit the HTML around the widget - for example if they want a search box on the right, they can type
{SearchController}
 (in my paradigm-breaking world)

答:
The best information I've found on doing widgets in ASP.NET MVC is on Steve Sanderson's blog.  He explains his concept of partial requests which is a different technique than sub-controllers.

http://blog.codeville.net/2008/10/14/partial-requests-in-aspnet-mvc/

Partial Requests are easy You’ve heard of partial views, so how about
  partial requests? Within any MVC
  request, you can set up a collection
  of internal partial requests, each of
  which can set up its own internal
  partial requests and so on. Each
  partial request renders a plain old
  action method in any of your plain
  regular controllers, and each can
  produce an independent widget. I’m
  calling them partial “requests” rather
  than “controllers” because they run a
  proper MVC request-handling pipeline
  that’s compatible with your routing
  system and your controller factory.
  Still, as with subcontrollers, all the
  control remains in controllers, and
  the view can be ignorant.

OwnerDisplayName: RoBorg

OwnerDisplayName: JarrettV

ContentLicense: CC BY-SA 2.5


问:
String added to start of current working directory instead of the end
Im getting the current working directory and adding more strings on top of it, when i add a backslash to the path, it adds it to the start of the stiring.

How do i stop this from happening?

```<code>print(os.getcwd() + "\aaaa\aaaa")

This prints # aaaa\aaaa\Desktop\Test\Tails

instead of #C:\Users\Rick\Desktop\technical-test\aaaa\aaaa
</code>```

Any help would be appreciated

答:
try,

```<code>print(os.path.join(os.getcwd(), r"aaaa\aaaa"))
</code>```

or

```<code>print(os.getcwd() + r"\aaaa\aaaa")
</code>```

both will print ,

```<code>C:\Users\Rick\Desktop\technical-test\aaaa\aaaa
</code>```

Body:
Im getting the current working directory and adding more strings on top of it, when i add a backslash to the path, it adds it to the start of the stiring.

How do i stop this from happening?

print(os.getcwd() + "\aaaa\aaaa")

This prints # aaaa\aaaa\Desktop\Test\Tails

instead of #C:\Users\Rick\Desktop\technical-test\aaaa\aaaa

Any help would be appreciated

Body:
try,

print(os.path.join(os.getcwd(), r"aaaa\aaaa"))

or

print(os.getcwd() + r"\aaaa\aaaa")

both will print ,

C:\Users\Rick\Desktop\technical-test\aaaa\aaaa


答:
According to MDN the return value of the splice() is array consisting of removed elements from array.

Return Value

An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned

Its just a way to get the removed element of the array. hand2.splice(randIndex, 1) will return the removed elements from array. So in this case there is only 1 element so [0] will get that first element.

Title: Splice function on an array of objects


问:
ASP Identity sign in isPersistent does not work
I am using ASP Identity for authentication. Part of the Statup.Auth.cs looks like:

```<code>            app.UseCookieAuthentication(
            new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                           {
                               // Enables the application to validate the security stamp when the user logs in.
                               // This is a security feature which is used when you change a password or add an external login to your account.
                               OnValidateIdentity =
                                   SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                                       validateInterval: TimeSpan.FromMinutes(30),
                                       regenerateIdentity:
                                   (manager, user) =>
                                   user.GenerateUserIdentityAsync(manager))
                           },
                ExpireTimeSpan = TimeSpan.FromMinutes(Settings.Default.SessionExpireTimeoutInMinutes),
            });
</code>```

and part of my Login method:

```<code>SignInStatus result = await this.SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false);
</code>```

If a user selects "remember me" option, he should not be logged out until something like 30 days. If he doesn't select this option, he should be logged out automatically after some short period of time, let's say 10 minutes. At the moment user is logged out no matter if he selected the option.

答:
In my case, the problem was in machineKey.  The server that's hosting my website keeps changing its machineKey that is used in encrypting and decryption the tickets and the solution was to assign a fixed machineKey in Web.Config.

Check out this solution here.

Body:
I am using ASP Identity for authentication. Part of the Statup.Auth.cs looks like:

            app.UseCookieAuthentication(
            new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                           {
                               // Enables the application to validate the security stamp when the user logs in.
                               // This is a security feature which is used when you change a password or add an external login to your account.
                               OnValidateIdentity =
                                   SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                                       validateInterval: TimeSpan.FromMinutes(30),
                                       regenerateIdentity:
                                   (manager, user) =>
                                   user.GenerateUserIdentityAsync(manager))
                           },
                ExpireTimeSpan = TimeSpan.FromMinutes(Settings.Default.SessionExpireTimeoutInMinutes),
            });

and part of my Login method:

SignInStatus result = await this.SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: false);

If a user selects "remember me" option, he should not be logged out until something like 30 days. If he doesn't select this option, he should be logged out automatically after some short period of time, let's say 10 minutes. At the moment user is logged out no matter if he selected the option.


答: Array.splice() gives you the new spliced array. Even though there is only one value in the array, it’s still an array, so to access the variable, you would use [0].</p>

Title: Splice function on an array of objects


问:
Hashlib's md5 produces different output for same input
I'm trying to write a script that produces the hash value for all filenames and directory names in a specified root directory.
This is my script so far:

```<code>import hashlib
import os
import sys

class Hasher:
    def __init__(self):
        self.hash_func = hashlib.md5()

    def hash_file(self, file_path):
        with open(file_path, "rb") as file:
            self.hash_func.update(file.read())
        return self.hash_func.digest()

    def hash_dir(self, dir_path):
        for dirpath, dirnames, filenames in os.walk(dir_path):
            self.hash_func.update(dirpath.encode("utf-8"))
            for file_path in filenames:
                self.hash_func.update(file_path.encode("utf-8"))
        return self.hash_func.digest()

hasher = Hasher()
root_dir = "D:/folder/"
hash_1 = str(hasher.hash_dir(root_dir))
hash_2 = str(hasher.hash_dir(root_dir))
print(hash_1)
print(hash_2)
</code>```

For some reason, it produces two different hash values for the same directory, without any change in the directory whatsoever. How can I make it so that the same hash value is produced if the directory stays the same?

答:
The problem is that the hashlib.md5 object is reused every time, so you return a hash of the cumulative data, not only over the last/intended data.

You could solve this by creating a new Hasher object every time (so calling Hasher().hash_dir(root_dir) twice in this case). But since your Hasher class does not contain any other data than the md5 object and two methods that could be static, I would recommend to make both class methods static, and create the hashlib.md5 object in the methods itself:

import hashlib
import os

class Hasher:

    @staticmethod  # make it a static method
    def hash_file(file_path):  # no 'self' as first argument
        hash_func = hashlib.md5()  # create the hashlib.md5 object here
        with open(file_path, "rb") as file:
            hash_func.update(file.read())
        return hash_func.digest()

    @staticmethod  # make it a static method
    def hash_dir(dir_path):  # no 'self' as first argument
        hash_func = hashlib.md5()  # create the hashlib.md5 object here
        for dirpath, _, filenames in os.walk(dir_path):
            hash_func.update(dirpath.encode("utf-8"))
            for file_path in filenames:
                hash_func.update(file_path.encode("utf-8"))
        return hash_func.digest()

def main():
    root_dir = "D:/folder/"
    hash_1 = str(Hasher.hash_dir(root_dir))
    hash_2 = str(Hasher.hash_dir(root_dir))
    print(hash_1)
    print(hash_2)

if __name__ == "__main__":
    main()
```

Body:
I'm trying to write a script that produces the hash value for all filenames and directory names in a specified root directory.
This is my script so far:

import hashlib
import os
import sys

class Hasher:
    def __init__(self):
        self.hash_func = hashlib.md5()

    def hash_file(self, file_path):
        with open(file_path, "rb") as file:
            self.hash_func.update(file.read())
        return self.hash_func.digest()

    def hash_dir(self, dir_path):
        for dirpath, dirnames, filenames in os.walk(dir_path):
            self.hash_func.update(dirpath.encode("utf-8"))
            for file_path in filenames:
                self.hash_func.update(file_path.encode("utf-8"))
        return self.hash_func.digest()

hasher = Hasher()
root_dir = "D:/folder/"
hash_1 = str(hasher.hash_dir(root_dir))
hash_2 = str(hasher.hash_dir(root_dir))
print(hash_1)
print(hash_2)

For some reason, it produces two different hash values for the same directory, without any change in the directory whatsoever. How can I make it so that the same hash value is produced if the directory stays the same?


问:
Div with margin-left and width:100% overflowing on the right side
I have 2 nested div's that should be 100% wide. Unfortunately the inner div with the Textbox overflows and is actually larger than the outer div. It has a left margin and overflows by about the size of the margin.

How can I fix that?

```<code><div style="width:100%;">
    <div style="margin-left:45px; width:100%;">
    <asp:TextBox ID="txtTitle" runat="server" Width="100%"></asp:TextBox><br />
    </div>
</div>
</code>```

If I don't do the 100%, then the textbox is not 100% wide.

答: A div is a block element and by default 100% wide. You should just have to set the textarea width to 100%.</p>

Body:
I have 2 nested div's that should be 100% wide. Unfortunately the inner div with the Textbox overflows and is actually larger than the outer div. It has a left margin and overflows by about the size of the margin.

How can I fix that?

    <asp:TextBox ID="txtTitle" runat="server" Width="100%"></asp:TextBox>

If I don't do the 100%, then the textbox is not 100% wide.


问:
Why do I get "Cannot unify 't₂' with type 'f32'" when compiling and how do I solve it?
I'm trying to check if a point is inside a circle with origin at 1,1.
However, when I try to simply subtract '1.0' from the coordinates I get the error:

Error at exercise3.fut:2:6-14:
Cannot unify 't₂' with type f32' ('t₂' must be one of i8, i16, i32, i64, u8, u16, u32, u64 due to use at exercise3.fut:2:6-30).
When matching type
  t₂
with
  f32

What do I need to do to make the compiler comfortable with "x-1.0" (where x is of type f32)?

I've tried Changing the input type to 't' and writing x-(1.0f32) etc. but still get the same or similar errors.

This is the code that gives the problem:

```<code>let hit_register (x : f32) (y : f32) : bool =
    ((x - 1.0)^2.0 + (y - 1.0)^2.0) <= 1.0
</code>```

Seems like a simple enough function/problem, but i could not find any help with this already available online.

答:
The ^ operator stands for the bitwise xor of integral type arguments.

The exponentiation operator is **. It  is  defined for all numeric types.

Reference: https://futhark.readthedocs.io/en/latest/language-reference.html

Body:
I'm trying to check if a point is inside a circle with origin at 1,1.
However, when I try to simply subtract '1.0' from the coordinates I get the error:

Error at exercise3.fut:2:6-14:
Cannot unify 't₂' with type f32' ('t₂' must be one of i8, i16, i32, i64, u8, u16, u32, u64 due to use at exercise3.fut:2:6-30).
When matching type
  t₂
with
  f32

What do I need to do to make the compiler comfortable with "x-1.0" (where x is of type f32)?

I've tried Changing the input type to 't' and writing x-(1.0f32) etc. but still get the same or similar errors.

This is the code that gives the problem:

let hit_register (x : f32) (y : f32) : bool =
    ((x - 1.0)^2.0 + (y - 1.0)^2.0) <= 1.0

Seems like a simple enough function/problem, but i could not find any help with this already available online.


问:
How to print $1, $2 and then all remaining parameters together in AWK
I'm making a script that generates aliases/abbreviations from a base file. The base file structure is something like this:

```<code>sctl   sudo         systemctl
pac    sudo         pacman
</code>```

This works fine with the following code that reads the base file, removes comments and awks the abbreviation line on the abbreviation file:

```<code>    sed "s/\s*#.*$//;/^\s*$/d" $command_file |
    awk -v c=$cmd -v o="$comp" '{ print c" "$1""o"\""$2" "$3"\"" }' >> $file
</code>```

And the end result would be something like this:

```<code>abbr sctl "sudo systemctl"
abbr pac "sudo pacman"
</code>```

But this code doesn't work when the line has many parts after the 3rd parameter:

```<code>svu    playerctl    -p spotify volume +0.05
</code>```

How can i go about printing in that format? $1 $2 ($3..$N)

答:
Here is an awk (standard Linux - specific to gawk) script that does all the work in one sweep:

```<code>awk -v c="abbr" -v o=" " '/(^\s*$)|(^\s*#.*$)/ {next}  # discard empty lines and comments
{
    arg3=$0;                          # save current line to arg3 variable
    sub($1" "$2,"",arg3);             # remove $1  and $2 from arg3
    print(c" "$1""o"\""$2" "arg3"\"") # print formated output
}' input.txt
</code>```

input.txt

```<code>ctl   sudo         systemctl
# comment line
pac    sudo         pacman
   # comment line
demo1  sudo         arg1 arg2 arg3

demo2  sudo         arg4 -arg5 -arg6 456
                         # comment line
</code>```

Output:

```<code>abbr ctl "sudo          systemctl"
abbr pac "sudo          pacman"
abbr demo1 "sudo          arg1 arg2 arg3"
abbr demo2 "sudo          arg4 -arg5 -arg6 456"
</code>```

Body:
I'm making a script that generates aliases/abbreviations from a base file. The base file structure is something like this:

sctl   sudo         systemctl
pac    sudo         pacman

This works fine with the following code that reads the base file, removes comments and awks the abbreviation line on the abbreviation file:

    sed "s/\s*#.*$//;/^\s*$/d" $command_file |
    awk -v c=$cmd -v o="$comp" '{ print c" "$1""o"\""$2" "$3"\"" }' >> $file

And the end result would be something like this:

abbr sctl "sudo systemctl"
abbr pac "sudo pacman"

But this code doesn't work when the line has many parts after the 3rd parameter:

svu    playerctl    -p spotify volume +0.05

How can i go about printing in that format? $1 $2 ($3..$N)

Body:
Here is an awk (standard Linux - specific to gawk) script that does all the work in one sweep:

awk -v c="abbr" -v o=" " '/(^\s*$)|(^\s*#.*$)/ {next}  # discard empty lines and comments
{
    arg3=$0;                          # save current line to arg3 variable
    sub($1" "$2,"",arg3);             # remove $1  and $2 from arg3
    print(c" "$1""o"\""$2" "arg3"\"") # print formated output
}' input.txt

input.txt

ctl   sudo         systemctl
# comment line
pac    sudo         pacman
   # comment line
demo1  sudo         arg1 arg2 arg3

demo2  sudo         arg4 -arg5 -arg6 456
                         # comment line

Output:

abbr ctl "sudo          systemctl"
abbr pac "sudo          pacman"
abbr demo1 "sudo          arg1 arg2 arg3"
abbr demo2 "sudo          arg4 -arg5 -arg6 456"


问:
Link to an specific Sheet/cell of a Sharepoint Excel
I have an Excel Workbook uploaded to my Sharepoint site.
I want to create an http link to that Excel but I want to point to an specific Sheet and cell, so the Excel opens at that position.

At the following link, I found how to reference a sheet:
http://support.microsoft.com/kb/197922

So, I built my http link like this:

```<code><a href="http://SharepointSite/MyWorkBook.xls#Sheet2!D4">
</code>```

However, the Excel opens on Sheet 1, cell A1. Not Sheet2, cell D4

Why is this not working? Is there any way to open an Excel that is uploaded at sharepoint in an specific Sheet/cell?

As additional info, the link is located inside a Sharepoint Webpage. So other options are welcome!

Thanks

答: This also applies to hyperlinks from cell to cell in the same document. I got around this from removing all the spaces (replaced them with underscores) in my document name & tab names. </p>

Body:
I have an Excel Workbook uploaded to my Sharepoint site.
I want to create an http link to that Excel but I want to point to an specific Sheet and cell, so the Excel opens at that position.

At the following link, I found how to reference a sheet:
http://support.microsoft.com/kb/197922

So, I built my http link like this:

However, the Excel opens on Sheet 1, cell A1. Not Sheet2, cell D4

Why is this not working? Is there any way to open an Excel that is uploaded at sharepoint in an specific Sheet/cell?

As additional info, the link is located inside a Sharepoint Webpage. So other options are welcome!

Thanks


问:
Default argument in the middle of parameter list?
I saw a function declaration in our code that looked as follows

```<code>void error(char const *msg, bool showKind = true, bool exit);
</code>```

I thought first that this is an error because you cannot have default arguments in the middle of functions, but the compiler accepted this declaration. Has anyone seen this before? I'm using GCC4.5. Is this a GCC extension?

The weird thing is, if I take this out in a separate file and try to compile, GCC rejects it. I've double checked everything, including the compiler options used.

答:
That code would work if in the very first declaration of the function, the last parameter has default value, something like this:

```<code>//declaration
void error(char const *msg, bool showKind, bool exit = false);
</code>```

And then in the same scope you can provide default values for other arguments (from right side), in the later declaration, as:

```<code>void error(char const *msg, bool showKind = true, bool exit); //okay

//void error(char const *msg = 0 , bool showKind, bool exit); // error
</code>```

which can called as:

```<code>error("some error messsage");
error("some error messsage", false);
error("some error messsage", false, true);
</code>```

Online Demo : http://ideone.com/aFpUn

Note if you provide default value for the first parameter (from left), without providing default value for the second, it wouldn't compile (as expected) : http://ideone.com/5hj46

§8.3.6/4 says,

For non-template functions, default
  arguments can be added in later
  declarations of a function in the same
  scope.

Example from the Standard itself:

```<code>void f(int, int);
void f(int, int = 7);
</code>```

The second declaration adds default value!

Also see §8.3.6/6.

Body:
I saw a function declaration in our code that looked as follows

void error(char const *msg, bool showKind = true, bool exit);

I thought first that this is an error because you cannot have default arguments in the middle of functions, but the compiler accepted this declaration. Has anyone seen this before? I'm using GCC4.5. Is this a GCC extension?

The weird thing is, if I take this out in a separate file and try to compile, GCC rejects it. I've double checked everything, including the compiler options used.

Body:
That code would work if in the very first declaration of the function, the last parameter has default value, something like this:

//declaration
void error(char const *msg, bool showKind, bool exit = false);

And then in the same scope you can provide default values for other arguments (from right side), in the later declaration, as:

void error(char const *msg, bool showKind = true, bool exit); //okay

//void error(char const *msg = 0 , bool showKind, bool exit); // error

which can called as:

error("some error messsage");
error("some error messsage", false);
error("some error messsage", false, true);

Online Demo : http://ideone.com/aFpUn

Note if you provide default value for the first parameter (from left), without providing default value for the second, it wouldn't compile (as expected) : http://ideone.com/5hj46

§8.3.6/4 says,

For non-template functions, default
  arguments can be added in later
  declarations of a function in the same
  scope.

Example from the Standard itself:

void f(int, int);
void f(int, int = 7);

The second declaration adds default value!

Also see §8.3.6/6.


问:
Zxing - Integrating in PHP
I want to decode QRCode/Barcode and i have been searching around for a while,
zxing has a webservice here but it is not an API so i cant massively use for my own purpose. But zxing has an open source library.
Can any one help me how can i integrate it with my own php code?is there any way at all?
I also found php-zbarcode but it seems that it is discontinued.

Regards

答:
Try using this to scan QR Code. It can select both the front and back camera in mobile. This is set to the back camera in devices with 2 cameras.

https://github.com/schmich/instascan/

```<code><?php
    if(isset($_COOKIE['myJavascriptVar']))
    {
       $phpVar =  $_COOKIE['myJavascriptVar'];

    enter code here

    ?>

    <html>
<head>
 <script type="text/javascript" src="https://rawgit.com/schmich/instascan-builds/master/instascan.min.js" ></script>
</head>
    <body>

                    <h3 class="text-center" style="font-family: sans-serif;">Scan the QR Code by Placing the code in front your camera</h3>

        <video  id="preview"></video>

        <script>

            let scanner = new Instascan.Scanner(
                {
                    video: document.getElementById('preview')
                }
            );
            scanner.addListener('scan', function(content) {
                alert('QR Code Scanned Successfully: ' + content);

                document.cookie = "myJavascriptVar = " + content;

                var phpID = "<?php echo $actID ?>";
                window.location.href = "qrCode?id="+phpID;
            });
            Instascan.Camera.getCameras().then(cameras =>
            {
                if(cameras.length = 2){
                    scanner.start(cameras[1]);
                }
                 if(cameras.length = 1){
                    scanner.start(cameras[0]);
                } else {
                    console.error("Device does have have available or working camera!");
                }
            });

        </script>

     </body>
    </html>
</code>```

Title: Zxing - Integrating in PHP

Body:
Try using this to scan QR Code. It can select both the front and back camera in mobile. This is set to the back camera in devices with 2 cameras.

https://github.com/schmich/instascan/

<?php
    if(isset($_COOKIE['myJavascriptVar']))
    {
       $phpVar =  $_COOKIE['myJavascriptVar'];

    enter code here

    ?>

    <html>
<head>
 <script type="text/javascript" src="https://rawgit.com/schmich/instascan-builds/master/instascan.min.js" ></script>
</head>
    <body>

                    <h3 class="text-center" style="font-family: sans-serif;">Scan the QR Code by Placing the code in front your camera</h3>

        <video  id="preview"></video>

        <script>

            let scanner = new Instascan.Scanner(
                {
                    video: document.getElementById('preview')
                }
            );
            scanner.addListener('scan', function(content) {
                alert('QR Code Scanned Successfully: ' + content);

                document.cookie = "myJavascriptVar = " + content;

                var phpID = "<?php echo $actID ?>";
                window.location.href = "qrCode?id="+phpID;
            });
            Instascan.Camera.getCameras().then(cameras =>
            {
                if(cameras.length = 2){
                    scanner.start(cameras[1]);
                }
                 if(cameras.length = 1){
                    scanner.start(cameras[0]);
                } else {
                    console.error("Device does have have available or working camera!");
                }
            });

        </script>

     </body>
    </html>


问:
SUM of two rows returned by SQL subquery
I have created the following SQL query

```<code>SELECT ae.[intEntitlementID]
      ,SUM(decIncrease) - SUM([decDecrease]) as quantity
                ,(SELECT SUM([decCredit]) - SUM([decDebit]) as value
                FROM [tblMonetaryValueEvent]
                where [intEntitlementID] = ae.intEntitlementID
                and intSchemeYear <= @intSchemeYear
                group by intEntitlementID) AS VALUE
    ,(SUM(decIncrease) - SUM([decDecrease])) *
                (SELECT SUM([decCredit]) - SUM([decDebit]) as value
                FROM [tblMonetaryValueEvent]
                where [intEntitlementID] = ae.intEntitlementID
                and intSchemeYear <= @intSchemeYear
                group by intEntitlementID) AS TOTAL

  FROM [tblAllocationEvent] ae

  where ae.intBusinessID = @intBusinessID
  and ae.intSchemeYear <= @intSchemeYear
  group by ae.intEntitlementID

  HAVING SUM(decIncrease) - SUM([decDecrease]) > 0
</code>```

Which returns the following

I now need to find the sum of the two rows on the TOTAL column.

I want the following data to be output. 73046.908322 + 1150.946103

Does anybody have any tips on how to SUM the two results returned by the sub query?

Thanks

答:
as @mkRabbani said, you could improve your query...
I think next one might be
- more readable
- perform better (but I cannot test, because no data)

so, untested!:

```<code>WITH sums AS (
  SELECT
    ae.[intEntitlementID]
    ,SUM(decIncrease)-SUM(decDecrease) AS quantity
    ,SUM(decCredit)-SUM(decDebit) As value
  FROM [tblAllocationEvent] ae
  INNER JOIN [tblMonetaryValueEvent] ON [intEntitlementID] = ae.intEntitlementID
                                  and intSchemeYear <= ae.intSchemeYear
  where ae.intBusinessID = @intBusinessID
  and ae.intSchemeYear <= @intSchemeYear
  group by ae.intEntitlementID
)
SELECT
  intEntitlementID
  ,quantity
  ,value
  ,quantity * value as Total
FROM sums
</code>```

Body:
I have created the following SQL query

SELECT ae.[intEntitlementID]
      ,SUM(decIncrease) - SUM([decDecrease]) as quantity
                ,(SELECT SUM([decCredit]) - SUM([decDebit]) as value
                FROM [tblMonetaryValueEvent]
                where [intEntitlementID] = ae.intEntitlementID
                and intSchemeYear <= @intSchemeYear
                group by intEntitlementID) AS VALUE
    ,(SUM(decIncrease) - SUM([decDecrease])) *
                (SELECT SUM([decCredit]) - SUM([decDebit]) as value
                FROM [tblMonetaryValueEvent]
                where [intEntitlementID] = ae.intEntitlementID
                and intSchemeYear <= @intSchemeYear
                group by intEntitlementID) AS TOTAL

  FROM [tblAllocationEvent] ae

  where ae.intBusinessID = @intBusinessID
  and ae.intSchemeYear <= @intSchemeYear
  group by ae.intEntitlementID

  HAVING SUM(decIncrease) - SUM([decDecrease]) > 0

Which returns the following

I now need to find the sum of the two rows on the TOTAL column.

I want the following data to be output. 73046.908322 + 1150.946103

Does anybody have any tips on how to SUM the two results returned by the sub query?

Thanks

Body:
as @mkRabbani said, you could improve your query...
I think next one might be
- more readable
- perform better (but I cannot test, because no data)

so, untested!:

WITH sums AS (
  SELECT
    ae.[intEntitlementID]
    ,SUM(decIncrease)-SUM(decDecrease) AS quantity
    ,SUM(decCredit)-SUM(decDebit) As value
  FROM [tblAllocationEvent] ae
  INNER JOIN [tblMonetaryValueEvent] ON [intEntitlementID] = ae.intEntitlementID
                                  and intSchemeYear <= ae.intSchemeYear
  where ae.intBusinessID = @intBusinessID
  and ae.intSchemeYear <= @intSchemeYear
  group by ae.intEntitlementID
)
SELECT
  intEntitlementID
  ,quantity
  ,value
  ,quantity * value as Total
FROM sums


问:
Append Array Through If Statement
So, I am making an app that requires to select various things. You can select these by swiping to the right of the UITableView. I am using a UIContextualAction and I am using a switch statement to order out the functions and executable statements. Once the UITableView Cell is selected, it is to run off of one of my switch statements. This is from the indexPath.row chosen. Now once each object is selected, it will append the name into an array.

My problem: Once the object is appended, the array does not add on. For instance, I pick Snapchat. The array has "Snapchat" in it. If I were to also chose Instagram, the array should append "Instagram". It does, but it forgets about the "Snapchat" in it too, and when it prints, it only prints 1 selected object. (Which was the last one I picked)

How could I make an array where I can add more objects without it forgetting

I have looked at doing if statements on the tableview cell that was selected. Nothing works, and was wondering how I could fix this, or find a solution

```<code>var array = [String]()
var choice = indexPath.row
switch choice {
case 0:
    array.append("Instagram")
    print(array)
case 1:
    array.append("Snapchat")
    print(array)
case 2:
    array.append("VSCO")
    print(array)
default:
    print("Error")
    print(array)
</code>```

This is what I get when I select multiple and try to append the array.

```<code>["Instagram"]
["Snapchat"]
["VSCO"]
Error
</code>```

as you can see, they are not in the array form.

答:
It does add, but your var array = [String]() is a context variable, once the function is over it gets deinit, this is your structure:

```<code>--> Controller
   --> Function
       --> Array
</code>```

Place var array = [String]() on your controller instead of the function, like this:

```<code>--> Controller
   --> Array
   --> Function
</code>```

No need to change anything other than the array declaration position.

Note: You are printing them in array form, but with length == 1.

Title: Append Array Through If Statement

Body:
So, I am making an app that requires to select various things. You can select these by swiping to the right of the UITableView. I am using a UIContextualAction and I am using a switch statement to order out the functions and executable statements. Once the UITableView Cell is selected, it is to run off of one of my switch statements. This is from the indexPath.row chosen. Now once each object is selected, it will append the name into an array.

My problem: Once the object is appended, the array does not add on. For instance, I pick Snapchat. The array has "Snapchat" in it. If I were to also chose Instagram, the array should append "Instagram". It does, but it forgets about the "Snapchat" in it too, and when it prints, it only prints 1 selected object. (Which was the last one I picked)

How could I make an array where I can add more objects without it forgetting

I have looked at doing if statements on the tableview cell that was selected. Nothing works, and was wondering how I could fix this, or find a solution

var array = [String]()
var choice = indexPath.row
switch choice {
case 0:
    array.append("Instagram")
    print(array)
case 1:
    array.append("Snapchat")
    print(array)
case 2:
    array.append("VSCO")
    print(array)
default:
    print("Error")
    print(array)

This is what I get when I select multiple and try to append the array.

["Instagram"]
["Snapchat"]
["VSCO"]
Error

as you can see, they are not in the array form.

Body:
It does add, but your var array = [String]() is a context variable, once the function is over it gets deinit, this is your structure:

--> Controller
   --> Function
       --> Array

Place var array = [String]() on your controller instead of the function, like this:

--> Controller
   --> Array
   --> Function

No need to change anything other than the array declaration position.

Note: You are printing them in array form, but with length == 1.


问:
Collision Hit event only fires if the enemy is moving in Unreal?
So I have a pretty simple collision I'm trying to check for and I'm really not sure why it isn't working correctly. I have a VR character pawn with custom hand actors.  I simply want to check when the hands hit the enemy. The hand actors each have a mesh and a capsule collision component set to the same settings as my pawn.

I also have the enemy set up to detect collisions with the pawn if they run into it and have no problems there whether the enemy is stationary or moving.

My hands however, only fire off the enemy's hit event if the enemy is moving. If the enemy is stationary no hit events fire for hand collision.

Is there a reason why this would be happening? Any help would be greatly appreciated.

答:
I'm not really sure why my pawn collision works while the enemy is stationary. However, since my enemy is derived from a Character class there are limitations that don't allow for the character to be "pushed" while stationary. I'm assuming there is probably a variable that messes with the collision settings when the character is moving or stationary.

However, I was able to get it to work just not the way I had envisioned. Instead of looking for the hands in the Hit event I changed it to an Overlap event. Doing it this way was not hard but, also not really the solution I was looking for. However, it works.


问:
How to receive BOOT_COMPLETED on Android TV
I'm developing an app for Android TV. I have a sticky service & a broadcast receiver that should restart this service after system reboot.

The code works perfect for any phone, but, in the case of the TV, any of the actions that I defined in the receiver's intent isn't received, when turning on the TV from standby(using the remote). It works when I unplug the TV and plug it again.

Has anyone tried something similiar? Any advice might help. Thanks

I've tried  BOOT_COMPLETED, QUICKBOOT_POWERON, REBOOT, ACTION_POWER_CONNECTED.

Here is the receiver I've configured.

```<code><receiver
        android:name=".MyReceiver"
        android:directBootAware="true"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"
/>
            <action
android:name="android.intent.action.QUICKBOOT_POWERON" />
            <action android:name="android.intent.action.REBOOT" />
            <action
android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
            <action
android:name="android.intent.action.ACTION_POWER_CONNECTED" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>
</code>```

Expected to catch the action of turning on the device in the broadcast.

答:
Please check if you have added following permission. </p>

```<code>uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"
</code>```

Body:
I'm developing an app for Android TV. I have a sticky service & a broadcast receiver that should restart this service after system reboot.

The code works perfect for any phone, but, in the case of the TV, any of the actions that I defined in the receiver's intent isn't received, when turning on the TV from standby(using the remote). It works when I unplug the TV and plug it again.

Has anyone tried something similiar? Any advice might help. Thanks

I've tried  BOOT_COMPLETED, QUICKBOOT_POWERON, REBOOT, ACTION_POWER_CONNECTED.

Here is the receiver I've configured.

<receiver
        android:name=".MyReceiver"
        android:directBootAware="true"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"
/>
            <action
android:name="android.intent.action.QUICKBOOT_POWERON" />
            <action android:name="android.intent.action.REBOOT" />
            <action
android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
            <action
android:name="android.intent.action.ACTION_POWER_CONNECTED" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>

Expected to catch the action of turning on the device in the broadcast.

Body:
Please check if you have added following permission.

uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"


问:
Drawing functions starting from a specific point
I have a problem drawing different functions with PHP (GD, of course).
I managed to draw different functions but whenever the parameters of the function change - the function floats wherever it wants.
Let us say that I have a first function y=x^2 and I have to draw it from -5 to 5. This means that the first point would be at (-5;25). And I can move that to whatever point I want if I know that. But if I choose y=2x^2 with an interval x=(-5;5). The first point is at (-5;50). So I need help in calculating how to move any function to, let's say, (0;0).
The functions are parabola/catenary alike.</p>

答:
What you want to do is find the maximum boundaries of the graph you are making. To do this you have to check each inflection point as well as the range bounds. Store each coordinate pair in an array

Part 1 [Range Bounds]:
Collect the coordinates from the range bounds.

```<code><?php
$ybound[] = f($minX);
$ybound[] = f($maxX);
</code>```

Part 2 [Inflections]:
This part is more difficult. You can either have a series of equations to solve for inflections for each type of parabola, or you can just brute force it. To do this, just choose a small increment, (what ever your small increment is for drawing the line), I will use 0.1

```<code><?php
for($x = $minX; $x <= $maxX; $x += 0.1) {
    $ybound[] = f($x);
}
</code>```

Note, if you brute force, you can skip Part 1, otherwise, it would be faster if you could figure out the inflections for the scope of your project

Part 3 [Min Max]:
Now you get the min and max values from the array of possible y values.

```<code><?php
$minY = min($ybound);
$maxY = max($ybound);
</code>```

Part 4 [Shift]:
Now that you have this, it should be very simple to adjust. You take the top left corner and set that to 0,0 by adjusting each new coordinate to that value.

```<code><?php
$shiftX = -$minX;
$shiftY = $maxY;
</code>```

With this info, you can also determine your image size

```<code><?php
$imageX = $maxX - $minX;
$imageY = $maxY - $minY;
</code>```

Then as you generate your coordinates, you will shift each one, by adding the shift value to the coordinate.

```<code><?php
for($x = -$minX; $x <= $maxX; $x += 0.1) {
    $ycoor = $shiftY - f($x);
    $xcoor = $x + $shiftX;
    //draw ...
}
</code>```

Drawing the axis is also easy,

```<code><?php
$xaxis = $shiftY;
$yaxis = $shiftX;
</code>```

(I think I have all my signs correct. Forgive me if they are off)

Body:
What you want to do is find the maximum boundaries of the graph you are making. To do this you have to check each inflection point as well as the range bounds. Store each coordinate pair in an array

Part 1 [Range Bounds]:
Collect the coordinates from the range bounds.

<?php
$ybound[] = f($minX);
$ybound[] = f($maxX);

Part 2 [Inflections]:
This part is more difficult. You can either have a series of equations to solve for inflections for each type of parabola, or you can just brute force it. To do this, just choose a small increment, (what ever your small increment is for drawing the line), I will use 0.1

<?php
for($x = $minX; $x <= $maxX; $x += 0.1) {
    $ybound[] = f($x);
}

Note, if you brute force, you can skip Part 1, otherwise, it would be faster if you could figure out the inflections for the scope of your project

Part 3 [Min Max]:
Now you get the min and max values from the array of possible y values.

<?php
$minY = min($ybound);
$maxY = max($ybound);

Part 4 [Shift]:
Now that you have this, it should be very simple to adjust. You take the top left corner and set that to 0,0 by adjusting each new coordinate to that value.

<?php
$shiftX = -$minX;
$shiftY = $maxY;

With this info, you can also determine your image size

<?php
$imageX = $maxX - $minX;
$imageY = $maxY - $minY;

Then as you generate your coordinates, you will shift each one, by adding the shift value to the coordinate.

<?php
for($x = -$minX; $x <= $maxX; $x += 0.1) {
    $ycoor = $shiftY - f($x);
    $xcoor = $x + $shiftX;
    //draw ...
}

Drawing the axis is also easy,

<?php
$xaxis = $shiftY;
$yaxis = $shiftX;

(I think I have all my signs correct. Forgive me if they are off)


问:
org.openqa.selenium.SessionNotCreatedException: session not created: This version of ChromeDriver only supports Chrome version 75 using Selenium
I want to open the Chrome browser it displays error.

```<code>import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Homepage {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //Create Driver object
        System.setProperty("webdriver.chrome.driver", "C:\\Workdirectory\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
    }
}
</code>```

Here I am expecting My Chrome Browser but it throws an error like

```<code>Starting ChromeDriver 75.0.3770.8 (681f24ea911fe754973dda2fdc6d2a2e159dd300-refs/branch-heads/3770@{#40}) on port 21714
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: session not created: This version of ChromeDriver only supports Chrome version 75
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:48'
System info: host: 'DESKTOP-3JIP3OF', ip: '192.168.1.73', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_101'
Driver info: driver.version: ChromeDriver
</code>```

答:
Error session not created: This version of ChromeDriver only supports Chrome version 75. So there is a compatibility issue with the chrome browser version and the chromedriver version. Please get the appropriate chrome driver based on your chrome browser version from the below location.

http://chromedriver.chromium.org/downloads

Body:
I want to open the Chrome browser it displays error.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Homepage {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        //Create Driver object
        System.setProperty("webdriver.chrome.driver", "C:\\Workdirectory\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
    }
}

Here I am expecting My Chrome Browser but it throws an error like

Starting ChromeDriver 75.0.3770.8 (681f24ea911fe754973dda2fdc6d2a2e159dd300-refs/branch-heads/3770@{#40}) on port 21714
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: session not created: This version of ChromeDriver only supports Chrome version 75
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:48'
System info: host: 'DESKTOP-3JIP3OF', ip: '192.168.1.73', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_101'
Driver info: driver.version: ChromeDriver


问:
Jasmine: Test if array contains an object element with certain property without custom matcher
I have an array:

```<code>const dummyArr = [
    { name: "a", city: "c1" },
    { name: "b", city: "c2" },
    { name: "z", city: "c3" }
]
</code>```

I need to write a jasmine test, to verify if an element exists in an array with property name: b.

Not sure if I can use arrayContaining or objectContaining here.

Note: I need to verify this within toHaveBeenCalledWith

```<code>expect(obj.setArray).toHaveBeenCalledWith("personalDetails", .......)
</code>```

答:
Here's one other way to do it without a custom matcher.
I am assuming dummyArr is your fake data, and you want to verify setArray gets called with the second element (named 'b').

```<code>expect(obj.setArray).toHaveBeenCalledWith(
  jasmine.arrayContaining([dummyArr.find(el => e.name === 'b')])
);
</code>```

Depending on what you think it's readable, you could do the lookup before the expect:

```<code>const dummyEl = dummyArr.find(el => e.name === 'b');
expect(obj.setArray).toHaveBeenCalledWith(jasmine.arrayContaining([dummyEl]));
</code>```

Note that this passes when setArray gets called with any array containing that element, e.g. the whole dummyArr. If you want an exact match, use jasmine.arrayWithExactContents() instead.

Body:
I have an array:

const dummyArr = [
    { name: "a", city: "c1" },
    { name: "b", city: "c2" },
    { name: "z", city: "c3" }
]

I need to write a jasmine test, to verify if an element exists in an array with property name: b.

Not sure if I can use arrayContaining or objectContaining here.

Note: I need to verify this within toHaveBeenCalledWith

expect(obj.setArray).toHaveBeenCalledWith("personalDetails", .......)

Body:
Here's one other way to do it without a custom matcher.
I am assuming dummyArr is your fake data, and you want to verify setArray gets called with the second element (named 'b').

expect(obj.setArray).toHaveBeenCalledWith(
  jasmine.arrayContaining([dummyArr.find(el => e.name === 'b')])
);

Depending on what you think it's readable, you could do the lookup before the expect:

const dummyEl = dummyArr.find(el => e.name === 'b');
expect(obj.setArray).toHaveBeenCalledWith(jasmine.arrayContaining([dummyEl]));

Note that this passes when setArray gets called with any array containing that element, e.g. the whole dummyArr. If you want an exact match, use jasmine.arrayWithExactContents() instead.


问:
AntiForgeryToken Expiration Blank Page
I'm using IdentityServer4 with ASP.NET Core 2.2. On the Post Login method I have applied the ValidateAntiForgeryToken. Generally after 20 minutes to 2 hours of sitting on the login page and then attempting to login it produces a blank page.

If you look at Postman Console you get a 400 Bad Request message. I then set the Cookie Expiration on the AntiForgery options to 90 days. I was able to allow the page to sit for up to 6 hours and still login. However, after around 8 hours (overnight), I received the blank page again after attempting to login.

```<code>[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login
</code>```

```<code>services.AddAntiforgery(options =>
{
    options.Cookie.Expiration = TimeSpan.FromDays(90);
});
</code>```

I expect to be able to sit on the login page for 90 days which is the duration of the cookie but that doesn't work. How do I get the cookie for the AntiforgeryToken to last the entire 90 days or whatever time I set it to and not timeout or expire? Is there a way to catch this error and redirect the user back to the login method?

答:
This was my final solution. I added a attribute using the IAntifogery dependency injection.

```<code>public class CustomValidationAttribute : ActionFilterAttribute
{
    private IAntiforgery _antiForgery { get; }

    public CustomValidationAttribute(IAntiforgery antiforgery)
    {
        _antiForgery = antiforgery;
    }

    public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        var isRequestValid = await this._antiForgery.IsRequestValidAsync(context.HttpContext);
        if (!isRequestValid)
        {
            //Add Code here if token is not valid

            return;
        }

        await next();
    }
}
</code>```

Add the attribute to your controller methods that also use [HttpPost]

```<code>[TypeFilter(typeof(CustomValidationAttribute))]
</code>```

Title: AntiForgeryToken Expiration Blank Page

Body:
I'm using IdentityServer4 with ASP.NET Core 2.2. On the Post Login method I have applied the ValidateAntiForgeryToken. Generally after 20 minutes to 2 hours of sitting on the login page and then attempting to login it produces a blank page.

If you look at Postman Console you get a 400 Bad Request message. I then set the Cookie Expiration on the AntiForgery options to 90 days. I was able to allow the page to sit for up to 6 hours and still login. However, after around 8 hours (overnight), I received the blank page again after attempting to login.

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login

services.AddAntiforgery(options =>
{
    options.Cookie.Expiration = TimeSpan.FromDays(90);
});

I expect to be able to sit on the login page for 90 days which is the duration of the cookie but that doesn't work. How do I get the cookie for the AntiforgeryToken to last the entire 90 days or whatever time I set it to and not timeout or expire? Is there a way to catch this error and redirect the user back to the login method?

Body:
This was my final solution. I added a attribute using the IAntifogery dependency injection.

public class CustomValidationAttribute : ActionFilterAttribute
{
    private IAntiforgery _antiForgery { get; }

    public CustomValidationAttribute(IAntiforgery antiforgery)
    {
        _antiForgery = antiforgery;
    }

    public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        var isRequestValid = await this._antiForgery.IsRequestValidAsync(context.HttpContext);
        if (!isRequestValid)
        {
            //Add Code here if token is not valid

            return;
        }

        await next();
    }
}

Add the attribute to your controller methods that also use [HttpPost]

[TypeFilter(typeof(CustomValidationAttribute))]


问:
Struts2: reading an array of input into an action
I'm trying to get an array of input into my action class but it always returns null;

Here's the HTML for the input

```<code><input class="activityInput" type="text" name="sentdate[" + i + "]" value="1" />
<input class="activityInput" type="text" name="sentdate[" + i + "]" value="2" />
</code>```

and here's the class for the action

```<code>public class ActivityAction extends ActionSupport{
    private List sentdate;
    public List getSentdate() {
    return sentdate;
    }

    public void setSentdate(List sentdate) {
        this.sentdate = sentdate;
    }
}
</code>```

What am i doing wrong?

答:
Struts should populate List but don`t :)
The better solution of this problem is to use String instead List in Struts action class properties.
If you submit form with

```<code><input type="text" name="sentdate" value="1" />
<input type="text" name="sentdate" value="2" />
</code>```

you will reseive in "private String sentdate" this: 1,2
and you can split this string with comma delimiter and give you List..

Body:
I'm trying to get an array of input into my action class but it always returns null;

Here's the HTML for the input

<input class="activityInput" type="text" name="sentdate[" + i + "]" value="1" />
<input class="activityInput" type="text" name="sentdate[" + i + "]" value="2" />

and here's the class for the action

public class ActivityAction extends ActionSupport{
    private List sentdate;
    public List getSentdate() {
    return sentdate;
    }

    public void setSentdate(List sentdate) {
        this.sentdate = sentdate;
    }
}

What am i doing wrong?

Body:
Struts should populate List but don`t :)
The better solution of this problem is to use String instead List in Struts action class properties.
If you submit form with

<input type="text" name="sentdate" value="1" />
<input type="text" name="sentdate" value="2" />

you will reseive in "private String sentdate" this: 1,2
and you can split this string with comma delimiter and give you List..


问:
CryptoCurrency NODE.js Web3 Ethereum - Can't connect to TESTRPC
I am trying to connect to my testrpc instance from a my web3 application but I can't seem to connect. The below code should return an array of all the accounts in the testrpc chain.

Code:

```<code>Web3 = require('web3')
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
console.log(web3.eth.accounts);
</code>```

It returns the below and inside the object intelliJ the currentprovider object is as follows.

It just seems to print the object I think:

```<code>Accounts {
  eth:
   Eth {
     currentProvider: [Getter/Setter],
     _requestManager: RequestManager { provider: [Object], providers: [Object], subscriptions: {} },
     givenProvider: null,
     providers:
      { WebsocketProvider: [Function: WebsocketProvider],
        HttpProvider: [Function: HttpProvider],
        IpcProvider: [Function: IpcProvider] },
     _provider: HttpProvider { host: 'http://localhost:8545', timeout: 0, connected: false },
     setProvider: [Function],
     BatchRequest: [Function: bound Batch],
     extend:
      { [Function: ex]
        formatters: [Object],
        utils: [Object],
        Method: [Function: Method] },
     clearSubscriptions: [Function],
     getProtocolVersion: { [Function: send] request: [Function: bound ], call: 'eth_protocolVersion' },
     getCoinbase: { [Function: send] request: [Function: bound ], call: 'eth_coinbase' },
     isMining: { [Function: send] request: [Function: bound ], call: 'eth_mining' },
     getHashrate: { [Function: send] request: [Function: bound ], call: 'eth_hashrate' },
     isSyncing: { [Function: send] request: [Function: bound ], call: 'eth_syncing' },
     getGasPrice: { [Function: send] request: [Function: bound ], call: 'eth_gasPrice' },
     getAccounts: { [Function: send] request: [Function: bound ], call: 'eth_accounts' },
     getBlockNumber: { [Function: send] request: [Function: bound ], call: 'eth_blockNumber' },
     getBalance: { [Function: send] request: [Function: bound ], call: 'eth_getBalance' },
     getStorageAt: { [Function: send] request: [Function: bound ], call: 'eth_getStorageAt' },
     getCode: { [Function: send] request: [Function: bound ], call: 'eth_getCode' },
     getBlock: { [Function: send] request: [Function: bound ], call: [Function: blockCall] },
     getUncle: { [Function: send] request: [Function: bound ], call: [Function: uncleCall] },
     getCompilers: { [Function: send] request: [Function: bound ], call: 'eth_getCompilers' },
     getBlockTransactionCount:
      { [Function: send]
        request: [Function: bound ],
        call: [Function: getBlockTransactionCountCall] },
     getBlockUncleCount:
      { [Function: send]
        request: [Function: bound ],
        call: [Function: uncleCountCall] },
     getTransaction:
      { [Function: send]
        request: [Function: bound ],
        call: 'eth_getTransactionByHash' },
     getTransactionFromBlock:
      { [Function: send]
        request: [Function: bound ],
        call: [Function: transactionFromBlockCall] },
     getTransactionReceipt:
      { [Function: send]
        request: [Function: bound ],
        call: 'eth_getTransactionReceipt' },
     getTransactionCount: { [Function: send] request: [Function: bound ], call: 'eth_getTransactionCount' },
     call: { [Function: send] request: [Function: bound ], call: 'eth_call' },
     estimateGas: { [Function: send] request: [Function: bound ], call: 'eth_estimateGas' },
     sendSignedTransaction: { [Function: send] request: [Function: bound ], call: 'eth_sendRawTransaction' },
     signTransaction: { [Function: send] request: [Function: bound ], call: 'eth_signTransaction' },
     sendTransaction: { [Function: send] request: [Function: bound ], call: 'eth_sendTransaction' },
     sign: { [Function: send] request: [Function: bound ], call: 'eth_sign' },
     compile: { solidity: [Object], lll: [Object], serpent: [Object] },
     submitWork: { [Function: send] request: [Function: bound ], call: 'eth_submitWork' },
     getWork: { [Function: send] request: [Function: bound ], call: 'eth_getWork' },
     getPastLogs: { [Function: send] request: [Function: bound ], call: 'eth_getLogs' },
     subscribe: { [Function] call: undefined },
     net:
      Net {
        currentProvider: [Getter/Setter],
        _requestManager: [Object],
        givenProvider: null,
        providers: [Object],
        _provider: [Object],
        setProvider: [Function],
        BatchRequest: [Function: bound Batch],
        extend: [Object],
        getId: [Object],
        isListening: [Object],
        getPeerCount: [Object],
        getNetworkType: [Function: bound getNetworkType] },
     accounts: [Circular],
     personal:
      Personal {
        currentProvider: [Getter/Setter],
        _requestManager: [Object],
        givenProvider: null,
        providers: [Object],
        _provider: [Object],
        setProvider: [Function],
        BatchRequest: [Function: bound Batch],
        extend: [Object],
        getAccounts: [Object],
        newAccount: [Object],
        unlockAccount: [Object],
        sendTransaction: [Object],
        lockAccount: [Object],
        importRawKey: [Object],
        sign: [Object],
        ecRecover: [Object],
        net: [Object] },
     Contract: [Function: Contract],
     Iban:
      { [Function: Iban]
        toAddress: [Function],
        toIban: [Function],
        fromAddress: [Function],
        fromBban: [Function],
        createIndirect: [Function],
        isValid: [Function] },
     abi: ABICoder { _types: [Array] } },
  wallet:
   Wallet {
     length: 0,
     _accounts: [Circular],
     defaultKeyName: 'web3js_wallet' } }
</code>```

The testRPC server starts successfully too:

答:
Your connection is working.

To return an array of the accounts use web3.eth.getAccounts() rather than web3.eth.accounts.

The code above should look something like...

```<code>Web3 = require('web3')
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.getAccounts().then(accounts => console.log(accounts));
</code>```

giving you something like...

```<code>[ '0x09e67e758381Fb878b9B1dCB91f2D5a62E00035a',
  '0x1BaABCa410a88564aC2BD9b8570D21b6e898C4C3',
  '0x8bfF74332C52065d2CC46f96c191aCDeec1AFEF2',
  '0x19070EaC7D68a710A5843Ee8cA3de258024da3Cb',
  '0x909394eA6feA0aDba05f093Ae43782e42b462F56',
  '0x63527Ef51b17830d6F597686C366A1995fd31bb2',
  '0xf476D31fAD8605d9D9D7b557C5117Bbe102935bc',
  '0xA64ba4e9d332106181A073E6eD20F876D6e28856',
  '0x126533F5FC78E355Fc35476Ae1392D338366D229',
  '0x291c17c0901FC9143D0DC43E1455E20D26342377' ]
</code>```

Body:
I am trying to connect to my testrpc instance from a my web3 application but I can't seem to connect. The below code should return an array of all the accounts in the testrpc chain.

Code:

Web3 = require('web3')
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
console.log(web3.eth.accounts);

It returns the below and inside the object intelliJ the currentprovider object is as follows.

It just seems to print the object I think:

Accounts {
  eth:
   Eth {
     currentProvider: [Getter/Setter],
     _requestManager: RequestManager { provider: [Object], providers: [Object], subscriptions: {} },
     givenProvider: null,
     providers:
      { WebsocketProvider: [Function: WebsocketProvider],
        HttpProvider: [Function: HttpProvider],
        IpcProvider: [Function: IpcProvider] },
     _provider: HttpProvider { host: 'http://localhost:8545', timeout: 0, connected: false },
     setProvider: [Function],
     BatchRequest: [Function: bound Batch],
     extend:
      { [Function: ex]
        formatters: [Object],
        utils: [Object],
        Method: [Function: Method] },
     clearSubscriptions: [Function],
     getProtocolVersion: { [Function: send] request: [Function: bound ], call: 'eth_protocolVersion' },
     getCoinbase: { [Function: send] request: [Function: bound ], call: 'eth_coinbase' },
     isMining: { [Function: send] request: [Function: bound ], call: 'eth_mining' },
     getHashrate: { [Function: send] request: [Function: bound ], call: 'eth_hashrate' },
     isSyncing: { [Function: send] request: [Function: bound ], call: 'eth_syncing' },
     getGasPrice: { [Function: send] request: [Function: bound ], call: 'eth_gasPrice' },
     getAccounts: { [Function: send] request: [Function: bound ], call: 'eth_accounts' },
     getBlockNumber: { [Function: send] request: [Function: bound ], call: 'eth_blockNumber' },
     getBalance: { [Function: send] request: [Function: bound ], call: 'eth_getBalance' },
     getStorageAt: { [Function: send] request: [Function: bound ], call: 'eth_getStorageAt' },
     getCode: { [Function: send] request: [Function: bound ], call: 'eth_getCode' },
     getBlock: { [Function: send] request: [Function: bound ], call: [Function: blockCall] },
     getUncle: { [Function: send] request: [Function: bound ], call: [Function: uncleCall] },
     getCompilers: { [Function: send] request: [Function: bound ], call: 'eth_getCompilers' },
     getBlockTransactionCount:
      { [Function: send]
        request: [Function: bound ],
        call: [Function: getBlockTransactionCountCall] },
     getBlockUncleCount:
      { [Function: send]
        request: [Function: bound ],
        call: [Function: uncleCountCall] },
     getTransaction:
      { [Function: send]
        request: [Function: bound ],
        call: 'eth_getTransactionByHash' },
     getTransactionFromBlock:
      { [Function: send]
        request: [Function: bound ],
        call: [Function: transactionFromBlockCall] },
     getTransactionReceipt:
      { [Function: send]
        request: [Function: bound ],
        call: 'eth_getTransactionReceipt' },
     getTransactionCount: { [Function: send] request: [Function: bound ], call: 'eth_getTransactionCount' },
     call: { [Function: send] request: [Function: bound ], call: 'eth_call' },
     estimateGas: { [Function: send] request: [Function: bound ], call: 'eth_estimateGas' },
     sendSignedTransaction: { [Function: send] request: [Function: bound ], call: 'eth_sendRawTransaction' },
     signTransaction: { [Function: send] request: [Function: bound ], call: 'eth_signTransaction' },
     sendTransaction: { [Function: send] request: [Function: bound ], call: 'eth_sendTransaction' },
     sign: { [Function: send] request: [Function: bound ], call: 'eth_sign' },
     compile: { solidity: [Object], lll: [Object], serpent: [Object] },
     submitWork: { [Function: send] request: [Function: bound ], call: 'eth_submitWork' },
     getWork: { [Function: send] request: [Function: bound ], call: 'eth_getWork' },
     getPastLogs: { [Function: send] request: [Function: bound ], call: 'eth_getLogs' },
     subscribe: { [Function] call: undefined },
     net:
      Net {
        currentProvider: [Getter/Setter],
        _requestManager: [Object],
        givenProvider: null,
        providers: [Object],
        _provider: [Object],
        setProvider: [Function],
        BatchRequest: [Function: bound Batch],
        extend: [Object],
        getId: [Object],
        isListening: [Object],
        getPeerCount: [Object],
        getNetworkType: [Function: bound getNetworkType] },
     accounts: [Circular],
     personal:
      Personal {
        currentProvider: [Getter/Setter],
        _requestManager: [Object],
        givenProvider: null,
        providers: [Object],
        _provider: [Object],
        setProvider: [Function],
        BatchRequest: [Function: bound Batch],
        extend: [Object],
        getAccounts: [Object],
        newAccount: [Object],
        unlockAccount: [Object],
        sendTransaction: [Object],
        lockAccount: [Object],
        importRawKey: [Object],
        sign: [Object],
        ecRecover: [Object],
        net: [Object] },
     Contract: [Function: Contract],
     Iban:
      { [Function: Iban]
        toAddress: [Function],
        toIban: [Function],
        fromAddress: [Function],
        fromBban: [Function],
        createIndirect: [Function],
        isValid: [Function] },
     abi: ABICoder { _types: [Array] } },
  wallet:
   Wallet {
     length: 0,
     _accounts: [Circular],
     defaultKeyName: 'web3js_wallet' } }

The testRPC server starts successfully too:

Body:
Your connection is working.

To return an array of the accounts use web3.eth.getAccounts() rather than web3.eth.accounts.

The code above should look something like...

Web3 = require('web3')
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.getAccounts().then(accounts => console.log(accounts));

giving you something like...

[ '0x09e67e758381Fb878b9B1dCB91f2D5a62E00035a',
  '0x1BaABCa410a88564aC2BD9b8570D21b6e898C4C3',
  '0x8bfF74332C52065d2CC46f96c191aCDeec1AFEF2',
  '0x19070EaC7D68a710A5843Ee8cA3de258024da3Cb',
  '0x909394eA6feA0aDba05f093Ae43782e42b462F56',
  '0x63527Ef51b17830d6F597686C366A1995fd31bb2',
  '0xf476D31fAD8605d9D9D7b557C5117Bbe102935bc',
  '0xA64ba4e9d332106181A073E6eD20F876D6e28856',
  '0x126533F5FC78E355Fc35476Ae1392D338366D229',
  '0x291c17c0901FC9143D0DC43E1455E20D26342377' ]