问:
How can I create a view from already populated table in php and mysql?
Good day,

I am still pretty new at this and any advice will be highly appreciated.

I have created a database with players for a sports team. Now I want to use the displayed table to create a view for the players that will be selected with the team to show the team sheet.

I cannot find a way to get this to work. I want to add a submit button or something like it so that all the players that are checked be populated into a view and displayed afterwards to be printed.

Any advice would be highly appreciated.

Table displayed:

```<code><thead>
    <tr>
        <th>Name</th>
        <th>Surname</th>
        <th>School</th>
        <th>Age</th>
        <th>Age Group</th>
        <th>Edit</th>
        <th>Delete</th>
        <th>Add to Team</th>

        <form action="" method="post">
    </tr>
</thead>
<!-- Table body -->
<tbody>
    <?php foreach($result as $index => $row) : ?>
    <tr>
        <td align="left"><?php echo $row['Name']; ?></td>
        <td align="left"><?php echo $row['Surname']; ?></td>
        <td align="left"><?php echo $row['School']; ?></td>
        <td align="left"><?php echo $row['Age']; ?></td>
        <td align="left"><?php echo $row['age_group']; ?></td>
        <td><a href="edit_player.php" title="Edit" onclick="return confirm('Confirm Player Delete ?')"></span> Edit</td>
        <td><a href="" title="Delete" onclick="return confirm('Confirm Player Delete ?')"></span> Delete</td>
        <td><input type="checkbox" name="add_to_team"/>Add to Team </span></td>
    </tr>
</tbody>
</code>```

Table structrue for players:

```<code>+---------------------------------------+
|   `Name` text NOT NULL,               |
|   `Surname` text NOT NULL,            |
|   `Id_num` varchar(13) NOT NULL,      |
|   `School` text NOT NULL,             |
|   `Age` varchar(2) NOT NULL,          |
|   `Address` varchar(200) NOT NULL,    |
|   `Address2` varchar(20) NOT NULL,    |
|   `City` varchar(20) NOT NULL,        |
|   `Postal_code` varchar(4) NOT NULL,  |
|   `player_pic` longblob NOT NULL,     |
|   `birth_cert` longblob NOT NULL,     |
|   `Club` varchar(30) NOT NULL,        |
|   `age_group` varchar(8) NOT NULL,    |
|   `DOB` varchar(11) NOT NULL,         |
|   `posistion` varchar(30) NOT NULL,   |
|   `contact` varchar(10) NOT NULL,     |
|   `f_name` varchar(30) NOT NULL,      |
|   `f_phone` varchar(30) NOT NULL,     |
|   `f_email` varchar(50) NOT NULL,     |
|   `m_name` varchar(30) NOT NULL,      |
|   `m_phone` varchar(30) NOT NULL,     |
|   `m_email` varchar(50) NOT NULL,     |
|   `medical_aid` varchar(30) NOT NULL, |
|   `med_num` varchar(15) NOT NULL,     |
|   `med_card` blob NOT NULL,           |
|   `ice_name` varchar(20) NOT NULL,    |
|   `ice_surname` varchar(20) NOT NULL, |
|   `ice_number` varchar(20) NOT NULL,  |
|   `jersey_size` varchar(5) NOT NULL,  |
|   `short_size` varchar(5) NOT NULL,   |
|   `golf_shirt` varchar(5) NOT NULL    |
+---------------------------------------+
</code>```

Table structre for Teams:

```<code>+-------------------------------------+
| `Club` varchar(20) NOT NULL,        |
|   `Name` varchar(20) NOT NULL,      |
|   `Surname` varchar(20) NOT NULL,   |
|   `Posisiton` varchar(20) NOT NULL, |
|   `Picture` blob NOT NULL,          |
|   `Team` varchar(5) NOT NULL,       |
|   `date` date NOT NULL,             |
|   `Id_num` varchar(13) NOT NULL     |
+-------------------------------------+
</code>```

答:
I guess your Id_num columns in your Players and Teams tables are unique identifiers. That's a guess because ordinarily such unique identifiers are defined as integers something like this to guarantee they are unique.

```<code>    ...
    Id_Num INT NOT NULL AUTO_INCREMENT,
    ...
    PRIMARY KEY (Id_Num),
    ...
</code>```

At any rate, if you're setting up relationships between players and teams, you have two choices.

First choice: if a player can only be on one team:

This is known in our trade as a one-to-many relationship. One Team, many Players.

Add a column to the Players table called Team_Id_Num. When you assign a player to a team, UPDATE the player's row and put the team's Id_Num value into that column for the player.

Then to get all the players on a team use a JOIN query like this:

```<code>   SELECT Teams.Name, Teams.Club, Players.Surname, Players.Name
     FROM Teams
     JOIN Players ON Players.Team_Id_Num = Teams.Id_Num
    WHERE Teams.Club = 'Manchester United'
</code>```

Finally, if you really want an SQL VIEW for this you can do something like this

```<code>  CREATE VIEW Roster AS
       SELECT Teams.Name TeamName, Teams.Club, Players.Surname, Players.Name
         FROM Teams
         JOIN Players ON Players.Team_Id_Num = Teams.Id_Num
</code>```

then query it by saying

```<code>      SELECT * FROM Roster WHERE Club = 'Arsenal'
</code>```

Second choice: if a player can be on more than one team.

This is known in our trade as a many-to-many relationship. Many Teams, many Players.

Add a new table, containing two columns, called Players_Teams. This table defines the relationships between players and teams. These are the columns.  It's sometimes called a join table.

```<code> Players_Id_Num
 Teams_Id_Num
</code>```

When you assign a player to a team, INSERT a row into this table containing the Id_Num values for the player and the team in question.

If the team later sacks the player, DELETE the corresponding row.

Then to get all the players on a team use a JOIN query like this:

```<code>   SELECT Teams.Name, Teams.Club, Players.Surname, Players.Name
     FROM Teams
     JOIN Players_Teams ON Teams.Id_Num = Players_Teams.Teams_Id_Num
     JOIN Players ON Players_Teams.Player_Id_Num = Player.Id_Num
    WHERE Teams.Club = 'Manchester United'
</code>```

Finally, if you really want an SQL view, you can create it like this

```<code>   CREATE VIEW Roster AS
        SELECT Teams.Name TeamName, Teams.Club, Players.Surname, Players.Name
          FROM Teams
          JOIN Players_Teams ON Teams.Id_Num = Players_Teams.Teams_Id_Num
          JOIN Players ON Players_Teams.Player_Id_Num = Player.Id_Num
</code>```

and query it the same way as I showed earlier.

Body:
Good day,

I am still pretty new at this and any advice will be highly appreciated.

I have created a database with players for a sports team. Now I want to use the displayed table to create a view for the players that will be selected with the team to show the team sheet.

I cannot find a way to get this to work. I want to add a submit button or something like it so that all the players that are checked be populated into a view and displayed afterwards to be printed.

Any advice would be highly appreciated.

Table displayed:

        Name
        Surname
        School
        Age
        Age Group
        Edit
        Delete
        Add to Team

        <form action="" method="post">

    <?php foreach($result as $index => $row) : ?>

        <?php echo $row['Name']; ?>
        <?php echo $row['Surname']; ?>
        <?php echo $row['School']; ?>
        <?php echo $row['Age']; ?>
        <?php echo $row['age_group']; ?>
         Edit
         Delete
        <input type="checkbox" name="add_to_team"/>Add to Team

Table structrue for players:

+---------------------------------------+
|   `Name` text NOT NULL,               |
|   `Surname` text NOT NULL,            |
|   `Id_num` varchar(13) NOT NULL,      |
|   `School` text NOT NULL,             |
|   `Age` varchar(2) NOT NULL,          |
|   `Address` varchar(200) NOT NULL,    |
|   `Address2` varchar(20) NOT NULL,    |
|   `City` varchar(20) NOT NULL,        |
|   `Postal_code` varchar(4) NOT NULL,  |
|   `player_pic` longblob NOT NULL,     |
|   `birth_cert` longblob NOT NULL,     |
|   `Club` varchar(30) NOT NULL,        |
|   `age_group` varchar(8) NOT NULL,    |
|   `DOB` varchar(11) NOT NULL,         |
|   `posistion` varchar(30) NOT NULL,   |
|   `contact` varchar(10) NOT NULL,     |
|   `f_name` varchar(30) NOT NULL,      |
|   `f_phone` varchar(30) NOT NULL,     |
|   `f_email` varchar(50) NOT NULL,     |
|   `m_name` varchar(30) NOT NULL,      |
|   `m_phone` varchar(30) NOT NULL,     |
|   `m_email` varchar(50) NOT NULL,     |
|   `medical_aid` varchar(30) NOT NULL, |
|   `med_num` varchar(15) NOT NULL,     |
|   `med_card` blob NOT NULL,           |
|   `ice_name` varchar(20) NOT NULL,    |
|   `ice_surname` varchar(20) NOT NULL, |
|   `ice_number` varchar(20) NOT NULL,  |
|   `jersey_size` varchar(5) NOT NULL,  |
|   `short_size` varchar(5) NOT NULL,   |
|   `golf_shirt` varchar(5) NOT NULL    |
+---------------------------------------+

Table structre for Teams:

+-------------------------------------+
| `Club` varchar(20) NOT NULL,        |
|   `Name` varchar(20) NOT NULL,      |
|   `Surname` varchar(20) NOT NULL,   |
|   `Posisiton` varchar(20) NOT NULL, |
|   `Picture` blob NOT NULL,          |
|   `Team` varchar(5) NOT NULL,       |
|   `date` date NOT NULL,             |
|   `Id_num` varchar(13) NOT NULL     |
+-------------------------------------+

Body:
I guess your Id_num columns in your Players and Teams tables are unique identifiers. That's a guess because ordinarily such unique identifiers are defined as integers something like this to guarantee they are unique.

    ...
    Id_Num INT NOT NULL AUTO_INCREMENT,
    ...
    PRIMARY KEY (Id_Num),
    ...

At any rate, if you're setting up relationships between players and teams, you have two choices.

First choice: if a player can only be on one team:

This is known in our trade as a one-to-many relationship. One Team, many Players.

Add a column to the Players table called Team_Id_Num. When you assign a player to a team, UPDATE the player's row and put the team's Id_Num value into that column for the player.

Then to get all the players on a team use a JOIN query like this:

   SELECT Teams.Name, Teams.Club, Players.Surname, Players.Name
     FROM Teams
     JOIN Players ON Players.Team_Id_Num = Teams.Id_Num
    WHERE Teams.Club = 'Manchester United'

Finally, if you really want an SQL VIEW for this you can do something like this

  CREATE VIEW Roster AS
       SELECT Teams.Name TeamName, Teams.Club, Players.Surname, Players.Name
         FROM Teams
         JOIN Players ON Players.Team_Id_Num = Teams.Id_Num

then query it by saying

      SELECT * FROM Roster WHERE Club = 'Arsenal'

Second choice: if a player can be on more than one team.

This is known in our trade as a many-to-many relationship. Many Teams, many Players.

Add a new table, containing two columns, called Players_Teams. This table defines the relationships between players and teams. These are the columns.  It's sometimes called a join table.

 Players_Id_Num
 Teams_Id_Num

When you assign a player to a team, INSERT a row into this table containing the Id_Num values for the player and the team in question.

If the team later sacks the player, DELETE the corresponding row.

Then to get all the players on a team use a JOIN query like this:

   SELECT Teams.Name, Teams.Club, Players.Surname, Players.Name
     FROM Teams
     JOIN Players_Teams ON Teams.Id_Num = Players_Teams.Teams_Id_Num
     JOIN Players ON Players_Teams.Player_Id_Num = Player.Id_Num
    WHERE Teams.Club = 'Manchester United'

Finally, if you really want an SQL view, you can create it like this

   CREATE VIEW Roster AS
        SELECT Teams.Name TeamName, Teams.Club, Players.Surname, Players.Name
          FROM Teams
          JOIN Players_Teams ON Teams.Id_Num = Players_Teams.Teams_Id_Num
          JOIN Players ON Players_Teams.Player_Id_Num = Player.Id_Num

and query it the same way as I showed earlier.


来源: stackexchange

问:
angular2 populate ngFor in different grid cells
I have an array: hobbies=['Reading','Sport','Travelling','Movies','Cooking','Singing'];

and in template right now I am populating it manually:

```<code><div class="my-checkbox">
    <!-- Hobbies -->
    <span style="float: left; width: 100px;"><h5>Hobbies</h5></span>

    <div class="mdl-grid">
        <div class="mdl-cell mdl-cell--4-col">
            <label #checkbox_1 class="mdl-checkbox mdl-js-checkbox" for="checkbox-1">
                <input type="checkbox" id="checkbox-1" name="hobbies" value="sport"
                class="mdl-checkbox__input" >
                <span class="mdl-checkbox__label">Sports</span>
            </label>
            <label #checkbox_2 class="mdl-checkbox mdl-js-checkbox" for="checkbox-2">
                <input type="checkbox" id="checkbox-2" name="hobbies" value="reading" class="mdl-checkbox__input">
                <span class="mdl-checkbox__label">Reading</span>
            </label>
        </div>
        <div class="mdl-cell mdl-cell--4-col">

            <label #checkbox_3 class="mdl-checkbox mdl-js-checkbox" for="checkbox-3">
                <input type="checkbox" id="checkbox-3" name="hobbies" value="singing"
                class="mdl-checkbox__input">
                <span class="mdl-checkbox__label">Singing</span>
            </label>
            <label #checkbox_4 class="mdl-checkbox mdl-js-checkbox" for="checkbox-4">
                <input type="checkbox" id="checkbox-4" name="hobbies" value="travelling"
                class="mdl-checkbox__input">
                <span class="mdl-checkbox__label">Travelling</span>
            </label>
        </div>
        <div class="mdl-cell mdl-cell--4-col">
            <label #checkbox_5 class="mdl-checkbox mdl-js-checkbox" for="checkbox-5">
                <input type="checkbox" id="checkbox-5" name="hobbies" value="movies"
                class="mdl-checkbox__input">
                <span class="mdl-checkbox__label">Movies</span>
            </label>
            <label #checkbox_6 class="mdl-checkbox mdl-js-checkbox" for="checkbox-6">
                <input type="checkbox" id="checkbox-6" name="hobbies" value="cooking"
                class="mdl-checkbox__input">
                <span class="mdl-checkbox__label">Cooking</span>
            </label>
        </div>
    </div>
</code>```

Which looks like following:

I would like to instead use ngFor to populate these checkboxes but keeping the structure intact i.e. alternate values are inserted into consecutive cells something like:

```<code><div class="mdl-grid" *ngFor="let hobby of hobbies">
 <div class="mdl-cell mdl-cell--4-col">
    <label #checkbox_1 class="mdl-checkbox mdl-js-checkbox" for="checkbox-1">
        <input type="checkbox" id="checkbox-1" name="hobbies" value="sport"
        class="mdl-checkbox__input" >
        <span class="mdl-checkbox__label">{{hobby}}</span>
    </label>
    <label #checkbox_2 class="mdl-checkbox mdl-js-checkbox" for="checkbox-1">
        <input type="checkbox" id="checkbox-1" name="hobbies" value="sport"
        class="mdl-checkbox__input" >
        <span class="mdl-checkbox__label">{{hobby}}</span>
    </label>
 </div>
</div>
</code>```

Also, as this is mdl-stepper #checkbox_1or the label is also important because I upgrade elements in my component like following:

```<code>@ViewChild('checkbox_2') checkbox_2:ElementRef;
@ViewChild('checkbox_3') checkbox_3:ElementRef;
@ViewChild('checkbox_4') checkbox_4:ElementRef;
@ViewChild('checkbox_5') checkbox_5:ElementRef;
@ViewChild('checkbox_6') checkbox_6:ElementRef;

componentHandler.upgradeElement(this.checkbox_1.nativeElement);
componentHandler.upgradeElement(this.checkbox_2.nativeElement);
componentHandler.upgradeElement(this.checkbox_3.nativeElement);
componentHandler.upgradeElement(this.checkbox_4.nativeElement);
componentHandler.upgradeElement(this.checkbox_5.nativeElement);
componentHandler.upgradeElement(this.checkbox_6.nativeElement);
</code>```

How can I achieve this?

UPDATE:

When I tried with above mentioned ngFor loop I get like following:

答:
You can create pipe that will split your array into chunks of 2 elements. It might look like this:

chunks.pipe.ts

```<code>@Pipe({ name: 'chunks' })
export class ChunksPipe implements PipeTransform {
  transform(arr: any, chunkSize: number) {
    return arr.reduce((prev, cur, index) => (index % chunkSize) ? prev : prev.concat([arr.slice(index, index + chunkSize)]), []);
  }
}
</code>```

And then you can use this ChunksPipe like this:

component.html

```<code><div class="mdl-grid">
  <div *ngFor="let chunk of hobbies | chunks: 2" class="mdl-cell mdl-cell--4-col">
    <label *ngFor="let hobby of chunk" #checkbox class="mdl-checkbox mdl-js-checkbox">
      <input type="checkbox" name="hobbies" [value]="hobby" class="mdl-checkbox__input">
      <span class="mdl-checkbox__label">{{hobby}}</span>
    </label>
  </div>
</div>
</code>```

To upgrade elements i would get elements via @ViewChildren

component.ts

```<code>hobbies = ['Sport', 'Reading', 'Singing', 'Travelling', 'Movies', 'Cooking' ];

@ViewChildren('checkbox') checkboxes: QueryList<ElementRef>;

ngAfterViewInit() {
  this.checkboxes.forEach(cbx => componentHandler.upgradeElement(cbx.nativeElement));
}
</code>```

P.S. Alternative way is using directive that will do it internally

Plunker Example

See also Grid Example

ContentLicense: CC BY-SA 3.0

Body:
I have an array: hobbies=['Reading','Sport','Travelling','Movies','Cooking','Singing'];

and in template right now I am populating it manually:

Hobbies

                <input type="checkbox" id="checkbox-1" name="hobbies" value="sport"
                class="mdl-checkbox__input" >
                Sports

                <input type="checkbox" id="checkbox-2" name="hobbies" value="reading" class="mdl-checkbox__input">
                Reading

                <input type="checkbox" id="checkbox-3" name="hobbies" value="singing"
                class="mdl-checkbox__input">
                Singing

                <input type="checkbox" id="checkbox-4" name="hobbies" value="travelling"
                class="mdl-checkbox__input">
                Travelling

                <input type="checkbox" id="checkbox-5" name="hobbies" value="movies"
                class="mdl-checkbox__input">
                Movies

                <input type="checkbox" id="checkbox-6" name="hobbies" value="cooking"
                class="mdl-checkbox__input">
                Cooking

Which looks like following:

I would like to instead use ngFor to populate these checkboxes but keeping the structure intact i.e. alternate values are inserted into consecutive cells something like:

        <input type="checkbox" id="checkbox-1" name="hobbies" value="sport"
        class="mdl-checkbox__input" >
        {{hobby}}

        <input type="checkbox" id="checkbox-1" name="hobbies" value="sport"
        class="mdl-checkbox__input" >
        {{hobby}}

Also, as this is mdl-stepper #checkbox_1or the label is also important because I upgrade elements in my component like following:

@ViewChild('checkbox_2') checkbox_2:ElementRef;
@ViewChild('checkbox_3') checkbox_3:ElementRef;
@ViewChild('checkbox_4') checkbox_4:ElementRef;
@ViewChild('checkbox_5') checkbox_5:ElementRef;
@ViewChild('checkbox_6') checkbox_6:ElementRef;

componentHandler.upgradeElement(this.checkbox_1.nativeElement);
componentHandler.upgradeElement(this.checkbox_2.nativeElement);
componentHandler.upgradeElement(this.checkbox_3.nativeElement);
componentHandler.upgradeElement(this.checkbox_4.nativeElement);
componentHandler.upgradeElement(this.checkbox_5.nativeElement);
componentHandler.upgradeElement(this.checkbox_6.nativeElement);

How can I achieve this?

UPDATE:

When I tried with above mentioned ngFor loop I get like following:

Body:
You can create pipe that will split your array into chunks of 2 elements. It might look like this:

chunks.pipe.ts

@Pipe({ name: 'chunks' })
export class ChunksPipe implements PipeTransform {
  transform(arr: any, chunkSize: number) {
    return arr.reduce((prev, cur, index) => (index % chunkSize) ? prev : prev.concat([arr.slice(index, index + chunkSize)]), []);
  }
}

And then you can use this ChunksPipe like this:

component.html

<div class="mdl-grid">
  <div *ngFor="let chunk of hobbies | chunks: 2" class="mdl-cell mdl-cell--4-col">
    <label *ngFor="let hobby of chunk" #checkbox class="mdl-checkbox mdl-js-checkbox">
      <input type="checkbox" name="hobbies" [value]="hobby" class="mdl-checkbox__input">
      <span class="mdl-checkbox__label">{{hobby}}</span>
    </label>
  </div>
</div>

To upgrade elements i would get elements via @ViewChildren

component.ts

hobbies = ['Sport', 'Reading', 'Singing', 'Travelling', 'Movies', 'Cooking' ];

@ViewChildren('checkbox') checkboxes: QueryList<ElementRef>;

ngAfterViewInit() {
  this.checkboxes.forEach(cbx => componentHandler.upgradeElement(cbx.nativeElement));
}

P.S. Alternative way is using directive that will do it internally

Plunker Example

See also Grid Example


问:
A Stranger Error of database in Intellij IDEA
I got a error called java.lang.AbstractMethodError: com.mysql.jdbc.Connection.isValid(I)Z when I connected IDEA with mysql database.
I think my configuration is correct as below.In addition, the test is successful.
The configuration pic

And then the something stranger happened. I cannot get the any schemes from my database on the database tool window,but I can get them with Navicat. When I type SELECT * FROM message into console, that error appeared as below.

```<code>[2017-03-29 17:51:28] java.lang.AbstractMethodError: com.mysql.jdbc.Connection.isValid(I)Z
[2017-03-29 17:51:28]   at com.intellij.database.remote.jdbc.impl.RemoteConnectionImpl.isValid(RemoteConnectionImpl.java:108)
[2017-03-29 17:51:28]   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[2017-03-29 17:51:28]   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
[2017-03-29 17:51:28]   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[2017-03-29 17:51:28]   at java.lang.reflect.Method.invoke(Method.java:497)
[2017-03-29 17:51:28]   at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:323)
[2017-03-29 17:51:28]   at sun.rmi.transport.Transport$1.run(Transport.java:200)
[2017-03-29 17:51:28]   at sun.rmi.transport.Transport$1.run(Transport.java:197)
[2017-03-29 17:51:28]   at java.security.AccessController.doPrivileged(Native Method)
[2017-03-29 17:51:28]   at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
[2017-03-29 17:51:28]   at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
[2017-03-29 17:51:28]   at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
[2017-03-29 17:51:28]   at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$256(TCPTransport.java:683)
[2017-03-29 17:51:28]   at java.security.AccessController.doPrivileged(Native Method)
[2017-03-29 17:51:28]   at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
[2017-03-29 17:51:28]   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
[2017-03-29 17:51:28]   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
[2017-03-29 17:51:28]   at java.lang.Thread.run(Thread.java:745)
</code>```

I search Internet for this question via google, then I upgrade mysql driver  to even ver.5.1.40.But it doesn't work as well.
The driver pic

So, How to deal with this error? It stuck me two days.
Thanks in advance.

答:
I solved it by changing to the older version of IDEA.
When I used the database of IDEA of Version 2016.1.4, it did work.</p>

Body:
I got a error called java.lang.AbstractMethodError: com.mysql.jdbc.Connection.isValid(I)Z when I connected IDEA with mysql database.
I think my configuration is correct as below.In addition, the test is successful.
The configuration pic

And then the something stranger happened. I cannot get the any schemes from my database on the database tool window,but I can get them with Navicat. When I type SELECT * FROM message into console, that error appeared as below.

[2017-03-29 17:51:28] java.lang.AbstractMethodError: com.mysql.jdbc.Connection.isValid(I)Z
[2017-03-29 17:51:28]   at com.intellij.database.remote.jdbc.impl.RemoteConnectionImpl.isValid(RemoteConnectionImpl.java:108)
[2017-03-29 17:51:28]   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[2017-03-29 17:51:28]   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
[2017-03-29 17:51:28]   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[2017-03-29 17:51:28]   at java.lang.reflect.Method.invoke(Method.java:497)
[2017-03-29 17:51:28]   at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:323)
[2017-03-29 17:51:28]   at sun.rmi.transport.Transport$1.run(Transport.java:200)
[2017-03-29 17:51:28]   at sun.rmi.transport.Transport$1.run(Transport.java:197)
[2017-03-29 17:51:28]   at java.security.AccessController.doPrivileged(Native Method)
[2017-03-29 17:51:28]   at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
[2017-03-29 17:51:28]   at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
[2017-03-29 17:51:28]   at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
[2017-03-29 17:51:28]   at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$256(TCPTransport.java:683)
[2017-03-29 17:51:28]   at java.security.AccessController.doPrivileged(Native Method)
[2017-03-29 17:51:28]   at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
[2017-03-29 17:51:28]   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
[2017-03-29 17:51:28]   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
[2017-03-29 17:51:28]   at java.lang.Thread.run(Thread.java:745)

I search Internet for this question via google, then I upgrade mysql driver  to even ver.5.1.40.But it doesn't work as well.
The driver pic

So, How to deal with this error? It stuck me two days.
Thanks in advance.


问:
Separating Divs

I am trying to separate this 2 divs with a space between them (Please see Picture 1).
The problem is when I add margin or padding this happens (Please see Picture 2).

Here is my code, Please take note I am not using Bootstrap:

.row {
  margin-left: -0.75rem !important;
  margin-right: -0.75rem !important;
}

.col-50 {
  width: 50%;
  float: left;
  position: relative;
  min-height: 1px;
  margin-left: 0.75rem !important;
  margin-right: 0.75rem !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="col-50">
    <div class="card-box">
      <h4 class="header-title">View Data</h4>
      <div class="table-container">
        <div class="row">
          <div class="col-50">
            <div class="btn-group">
              <span>Excel</span>
              <span>PDF</span>
            </div>
          </div>
          <div class="col-50">
            <form class="pull-right">
              <input type="text" placeholder="Search..." class="form-control">
              <span><i class="fa fa-search"></i></span>
            </form>
          </div>
        </div>
        <div class="row">
          <div class="col-100">

          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="col-50">
    <div class="card-box">
      <h4 class="header-title">View Data</h4>
      <div class="table-container">
        <div class="row">
          <div class="col-50">
            <div class="btn-group">
              <span>Excel</span>
              <span>PDF</span>
            </div>
          </div>
          <div class="col-50">
            <form class="pull-right">
              <input type="text" placeholder="Search..." class="form-control">
              <span><i class="fa fa-search"></i></span>
            </form>
          </div>
        </div>
        <div class="row">
          <div class="col-100">

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

Here is my HTML and CSS code. I am trying to make this work for days. Please help. I want to separate these 2 divs with equal space between them perfectly. I am trying to mimic the grid from Bootstrap in order to learn before I try the Bootstrap approach.

答:
Have you tried adding margin-right / left to the .cardbox div?

EDIT:

You have to extend the width on row/container, the div you have around the whole page.

Title: Separating Divs

Body:
I am trying to separate this 2 divs with a space between them (Please see Picture 1).
The problem is when I add margin or padding this happens (Please see Picture 2).

Here is my code, Please take note I am not using Bootstrap:

.row {
  margin-left: -0.75rem !important;
  margin-right: -0.75rem !important;
}

.col-50 {
  width: 50%;
  float: left;
  position: relative;
  min-height: 1px;
  margin-left: 0.75rem !important;
  margin-right: 0.75rem !important;
}

View Data

              Excel
              PDF

            <form class="pull-right">
              <input type="text" placeholder="Search..." class="form-control">

            </form>

View Data

              Excel
              PDF

            <form class="pull-right">
              <input type="text" placeholder="Search..." class="form-control">

            </form>

Here is my HTML and CSS code. I am trying to make this work for days. Please help. I want to separate these 2 divs with equal space between them perfectly. I am trying to mimic the grid from Bootstrap in order to learn before I try the Bootstrap approach.


问:
Configuration for create-react-app after ejecting to build a component library
I started to build a component library that I want to publish on NPM (and reuse in other apps) by creating a React app using create-react-app. Unfortunately the create-react-app default configuration doesn't seem to support building such component libraries (see these issues). So it seems I have to eject.

Do you have some instructions what to configure after ejecting to make this a component library I can reuse in other apps (I guess some Webpack stuff)?

答:
This is super simple - you don't actually need webpack if you want to publish a package. Don't install it just for that if you don't want to.

If you use ES6:

You can use a simple script to create a dist folder that babel will create the files after transpiling:

```<code>"scripts": {
    // other scripts
    // .. might want to change "rm -rf" below if you're on a PC
    "build:production": "rm -rf es && cross-env NODE_ENV=production node_modules/.bin/babel ./src -d es"
  },
</code>```

What this does is:

Remove the es folder, which is a build folder.

Runs babel for your files (in case they are located in src folder, change it to wherever your files reside) and create the es folder with the transpiled files.

In order to use the script above you need to install the following dependencies:

babel-cli / babel-core / babel-preset-es2015 / cross-env

Make sure you have a .babelrc file so that babel will work:

```<code>{
  "presets": [
    ["es2015", { "modules": false }]
  ]
}
</code>```

Now all you have to do (after running npm run build:production) is to run:

```<code>npm publish
</code>```

And your library is published in npm. This is also the command you run if you want to update, just don't forget to update the version number in your package.json.

In case you have files you dont want published to npm, just have a file in your root called .npmignore (similar to .gitignore) and list everything you want excluded.

If you don't use ES6:

In this case you don't need to transpile anything, just go straight to the npm publish section above and run it on the root folder you want published.

Body:
This is super simple - you don't actually need webpack if you want to publish a package. Don't install it just for that if you don't want to.

If you use ES6:

You can use a simple script to create a dist folder that babel will create the files after transpiling:

"scripts": {
    // other scripts
    // .. might want to change "rm -rf" below if you're on a PC
    "build:production": "rm -rf es && cross-env NODE_ENV=production node_modules/.bin/babel ./src -d es"
  },

What this does is:

Remove the es folder, which is a build folder.

Runs babel for your files (in case they are located in src folder, change it to wherever your files reside) and create the es folder with the transpiled files.

In order to use the script above you need to install the following dependencies:

babel-cli / babel-core / babel-preset-es2015 / cross-env

Make sure you have a .babelrc file so that babel will work:

{
  "presets": [
    ["es2015", { "modules": false }]
  ]
}

Now all you have to do (after running npm run build:production) is to run:

npm publish

And your library is published in npm. This is also the command you run if you want to update, just don't forget to update the version number in your package.json.

In case you have files you dont want published to npm, just have a file in your root called .npmignore (similar to .gitignore) and list everything you want excluded.

If you don't use ES6:

In this case you don't need to transpile anything, just go straight to the npm publish section above and run it on the root folder you want published.


问:
pandas DataFrame error "tuple index out of range"
I have a problem backward filling a numpy date vector using the current version of pandas. The same code works with an earlier version. The following demonstrates my problem:

The older version (0.7.3) works

```<code>C:\WINDOWS\system32>pip show pandas
Name: pandas
Version: 0.7.3
Summary: Powerful data structures for data analysis and statistics
Home-page: http://pandas.pydata.org
Author: The PyData Development Team
Author-email: pydata@googlegroups.com
License: BSD
Location: c:\program files\python\python27\lib\site-packages
Requires: python-dateutil, numpy

C:\WINDOWS\system32>python
Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:24:40) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> d=np.array([None, None, None, None, dt.now(), None])
>>> b = DataFrame(d)
>>> b.fillna(method='backfill')
                            0
0  2017-04-02 12:21:18.175000
1  2017-04-02 12:21:18.175000
2  2017-04-02 12:21:18.175000
3  2017-04-02 12:21:18.175000
4  2017-04-02 12:21:18.175000
5                        None
>>>
</code>```

The current vesion (0.19.2) doesn't work:

```<code>C:\WINDOWS\system32>pip show pandas
Name: pandas
Version: 0.19.2
Summary: Powerful data structures for data analysis, time series,and statistics
Home-page: http://pandas.pydata.org
Author: The PyData Development Team
Author-email: pydata@googlegroups.com
License: BSD
Location: c:\program files\python\python27\lib\site-packages
Requires: pytz, python-dateutil, numpy

C:\WINDOWS\system32>python
Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:24:40) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime as dt
>>> import numpy as np
>>> from pandas import DataFrame
>>> d=np.array([None, None, None, None, dt.now(), None])
>>> b = DataFrame(d)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Program Files\Python\Python27\lib\site-packages\pandas\core\frame.py", line 297, in __init__
    copy=copy)
  File "C:\Program Files\Python\Python27\lib\site-packages\pandas\core\frame.py", line 474, in _init_ndarray
    return create_block_manager_from_blocks([values], [columns, index])
  File "C:\Program Files\Python\Python27\lib\site-packages\pandas\core\internals.py", line 4256, in create_block_manager_from_blocks
    construction_error(tot_items, blocks[0].shape[1:], axes, e)
  File "C:\Program Files\Python\Python27\lib\site-packages\pandas\core\internals.py", line 4230, in construction_error
    if block_shape[0] == 0:
IndexError: tuple index out of range
>>>
</code>```

Am I doing something wrong or is it, as I think, a bug in pandas? If its a bug how do I report that?

EDIT: This was filed as a bug report with Pandas and will be fixed in the next minor relase (0.19.3)

Body:
I have a problem backward filling a numpy date vector using the current version of pandas. The same code works with an earlier version. The following demonstrates my problem:

The older version (0.7.3) works

C:\WINDOWS\system32>pip show pandas
Name: pandas
Version: 0.7.3
Summary: Powerful data structures for data analysis and statistics
Home-page: http://pandas.pydata.org
Author: The PyData Development Team
Author-email: pydata@googlegroups.com
License: BSD
Location: c:\program files\python\python27\lib\site-packages
Requires: python-dateutil, numpy

C:\WINDOWS\system32>python
Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:24:40) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> d=np.array([None, None, None, None, dt.now(), None])
>>> b = DataFrame(d)
>>> b.fillna(method='backfill')
                            0
0  2017-04-02 12:21:18.175000
1  2017-04-02 12:21:18.175000
2  2017-04-02 12:21:18.175000
3  2017-04-02 12:21:18.175000
4  2017-04-02 12:21:18.175000
5                        None
>>>

The current vesion (0.19.2) doesn't work:

C:\WINDOWS\system32>pip show pandas
Name: pandas
Version: 0.19.2
Summary: Powerful data structures for data analysis, time series,and statistics
Home-page: http://pandas.pydata.org
Author: The PyData Development Team
Author-email: pydata@googlegroups.com
License: BSD
Location: c:\program files\python\python27\lib\site-packages
Requires: pytz, python-dateutil, numpy

C:\WINDOWS\system32>python
Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:24:40) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime as dt
>>> import numpy as np
>>> from pandas import DataFrame
>>> d=np.array([None, None, None, None, dt.now(), None])
>>> b = DataFrame(d)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Program Files\Python\Python27\lib\site-packages\pandas\core\frame.py", line 297, in __init__
    copy=copy)
  File "C:\Program Files\Python\Python27\lib\site-packages\pandas\core\frame.py", line 474, in _init_ndarray
    return create_block_manager_from_blocks([values], [columns, index])
  File "C:\Program Files\Python\Python27\lib\site-packages\pandas\core\internals.py", line 4256, in create_block_manager_from_blocks
    construction_error(tot_items, blocks[0].shape[1:], axes, e)
  File "C:\Program Files\Python\Python27\lib\site-packages\pandas\core\internals.py", line 4230, in construction_error
    if block_shape[0] == 0:
IndexError: tuple index out of range
>>>

Am I doing something wrong or is it, as I think, a bug in pandas? If its a bug how do I report that?

EDIT: This was filed as a bug report with Pandas and will be fixed in the next minor relase (0.19.3)

Body:
Try to specify (or cast) the dtype explicitly:

In [18]: d=np.array([None, None, None, None, pd.datetime.now(), None])

In [19]: b = DataFrame(d.astype('datetime64[ms]'))

In [20]: b
Out[20]:
                        0
0                     NaT
1                     NaT
2                     NaT
3                     NaT
4 2017-04-02 20:34:20.381
5                     NaT

In [21]: b.bfill()
Out[21]:
                        0
0 2017-04-02 20:34:20.381
1 2017-04-02 20:34:20.381
2 2017-04-02 20:34:20.381
3 2017-04-02 20:34:20.381
4 2017-04-02 20:34:20.381
5                     NaT


问:
Json from a get API Call C#
I have a GET API Call as below:

```<code>static void Main()
{
    RunAsync().Wait();
}

static async Task RunAsync()
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("myurl");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("usr", "pwd");
        HttpResponseMessage response = await client.GetAsync("");
        if (response.IsSuccessStatusCode)
        {
            Console.WriteLine(response.Content);
        }
    }
}
</code>```

How do I read the JSON response from the API ?

I was trying to do this:

```<code> response.Content = new ObjectContent<Response>(new Response()
                    {
                        responseCode = Response.ResponseCodes.ItemNotFound
                    }, new JsonMediaTypeFormatter(), "application/json");
</code>```

but I have not been successful yet. Could someone help please?

UPDATE:

My updated code looks like this now:

```<code>static async Task RunAsync()
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("myurl");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("BT", "pwd");
        HttpResponseMessage response = await client.GetAsync("");
        if (response.IsSuccessStatusCode)
        {
            Console.WriteLine(response.Content);
            var json = await response.Content.ReadAsStringAsync();
            Product myprod = JsonConvert.DeserializeObject<Product>(json);

            var results = myprod.result;

            for(int i=1;i<=results.Count;i++)
            {
                var value1 = results[0][0];
                var value2 = results[0][1];
                var value3 = "Nilisha";
                using (SqlConnection conn = new SqlConnection())
                {
                    conn.ConnectionString = "Server=[xx.xx.xx.xx];Database=[Mydb];User ID=sa;Password=abc@321;Trusted_Connection=true";
                    conn.Open();
                    SqlCommand insertCommand = new SqlCommand("INSERT INTO PortalData (LCID, TimeStamp, Name) VALUES ( @1, @2, @3)", conn);
                    insertCommand.Parameters.Add(new SqlParameter("1", value1));
                    insertCommand.Parameters.Add(new SqlParameter("2", value2));
                    insertCommand.Parameters.Add(new SqlParameter("3", value3));

                    Console.WriteLine("Commands executed! Total rows affected are " + insertCommand.ExecuteNonQuery());
                    conn.Close();
                }
            }
            Console.ReadLine();
        }
    }
}
</code>```

Are we allowed to use insert db calls inside the static async Task RunAsync() function ?

答:
You can use a great library called JSON.Net. It supports converting native C# object's to JSON and back.

You can add the library from NuGet under the name Newtonsoft.Json

for this example I created some sample data in JSON

```<code>{
  "User": "John Skeet",
  "Age": 50,
  "hobby": [
    "dancing",
    "sleeping",
    "writing C#"
  ]
}
</code>```

If I wanted to use the library I would first import the library.

```<code>using Newtonsoft.Json;
</code>```

After that I would

make the request

read the response as a string and store it.

If you know how the JSON object will be formatted then you can create a predefined C# Class with properties. Json.Net will map the (exact) name of the class properties to the same name in the JSON data.

so for our class

```<code>public class Person
{
    public string User { get; set; } //Maps to { "User" : "value" }
    public int Age { get; set; }    //Maps to { "Age" : value }
    public List<string> Hobby { get; set; } //Maps to { ["value1","value2","..."] }
}
</code>```

this would suffice. you can then convert the retrieved Json data using the method JsonConvert.DeserializeObject<Person>(StringWithJson) this will return an Person object.

Title: Json from a get API Call C#

Body:
I have a GET API Call as below:

static void Main()
{
    RunAsync().Wait();
}

static async Task RunAsync()
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("myurl");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("usr", "pwd");
        HttpResponseMessage response = await client.GetAsync("");
        if (response.IsSuccessStatusCode)
        {
            Console.WriteLine(response.Content);
        }
    }
}

How do I read the JSON response from the API ?

I was trying to do this:

 response.Content = new ObjectContent<Response>(new Response()
                    {
                        responseCode = Response.ResponseCodes.ItemNotFound
                    }, new JsonMediaTypeFormatter(), "application/json");

but I have not been successful yet. Could someone help please?

UPDATE:

My updated code looks like this now:

static async Task RunAsync()
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("myurl");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("BT", "pwd");
        HttpResponseMessage response = await client.GetAsync("");
        if (response.IsSuccessStatusCode)
        {
            Console.WriteLine(response.Content);
            var json = await response.Content.ReadAsStringAsync();
            Product myprod = JsonConvert.DeserializeObject<Product>(json);

            var results = myprod.result;

            for(int i=1;i<=results.Count;i++)
            {
                var value1 = results[0][0];
                var value2 = results[0][1];
                var value3 = "Nilisha";
                using (SqlConnection conn = new SqlConnection())
                {
                    conn.ConnectionString = "Server=[xx.xx.xx.xx];Database=[Mydb];User ID=sa;Password=abc@321;Trusted_Connection=true";
                    conn.Open();
                    SqlCommand insertCommand = new SqlCommand("INSERT INTO PortalData (LCID, TimeStamp, Name) VALUES ( @1, @2, @3)", conn);
                    insertCommand.Parameters.Add(new SqlParameter("1", value1));
                    insertCommand.Parameters.Add(new SqlParameter("2", value2));
                    insertCommand.Parameters.Add(new SqlParameter("3", value3));

                    Console.WriteLine("Commands executed! Total rows affected are " + insertCommand.ExecuteNonQuery());
                    conn.Close();
                }
            }
            Console.ReadLine();
        }
    }
}

Are we allowed to use insert db calls inside the static async Task RunAsync() function ?

Body:
You can use a great library called JSON.Net. It supports converting native C# object's to JSON and back.

You can add the library from NuGet under the name Newtonsoft.Json

for this example I created some sample data in JSON

{
  "User": "John Skeet",
  "Age": 50,
  "hobby": [
    "dancing",
    "sleeping",
    "writing C#"
  ]
}

If I wanted to use the library I would first import the library.

using Newtonsoft.Json;

After that I would

make the request

read the response as a string and store it.

If you know how the JSON object will be formatted then you can create a predefined C# Class with properties. Json.Net will map the (exact) name of the class properties to the same name in the JSON data.

so for our class

public class Person
{
    public string User { get; set; } //Maps to { "User" : "value" }
    public int Age { get; set; }    //Maps to { "Age" : value }
    public List<string> Hobby { get; set; } //Maps to { ["value1","value2","..."] }
}

this would suffice. you can then convert the retrieved Json data using the method JsonConvert.DeserializeObject<Person>(StringWithJson) this will return an Person object.


问:
Working with onPause, onRestart, in Tab Widget - Android
I have a ListView that is inside a TabWidget. When I select an item on the ListView and go to the child ListView, the TabWidget disappears. This is fine, except that it invokes the onPause method, and thus causes onRestart to be called when I return to the parent ListView.

I have onRestart setup to retrieve updated data from the server, but I do not want this to occur everytime the user returns to the parent ListView. I only want onRestart to be called when the app comes alive from running in the background. I have tried implementing a Boolean variable to determine if I should execute the code that is inside onRestart, but there doesn't seem to be a way to get around the effects of this.

Ideas?

答:
You could fire off your child activity with startActivityForResult and set a flag in onActivityResult to not reload (which should be called when the user backs into the listview from the detail page). You'd have a member variable (let's say mReload) that you'd set to true in onCreate and onRestart, and to false in onActivityResult, then process the reload onResume if mReload is true (and set it back to false so a normal resume won't trigger the reload).

Alternative: just set a flag (mLeftPage) in your activity on the row's click listener. On restart, if mLeftPage is true, don't reload the list and set mLeftPage back to false. Otherwise, reload.

ContentLicense: CC BY-SA 2.5


问:
How to get the next row value in another column
I have Table called Opp Table

```<code>   OppID         actualclosedate
--------------------------------------
    1            10-March
</code>```

I have a Table called stagechange

```<code>--------------------------------------
   OppID      Stage       createdon
--------------------------------------
    1         Propsect    1-Jan
    1         Qualify     15-Jan
    1         Develop     25-Jan
    1         Qualify     9-Feb
    1         Develop     7-March
    1         Prospect    9-April
</code>```

How Can I create a new column and get the next row value that is in createdon column; to have something like this. If there is no more next values, we get the date from other table like actual close date in Opp Table

```<code>--------------------------------------
   OppID      Stage       createdon   newcolumn
--------------------------------------
    1         Propsect    1-Jan        15-Jan
    1         Qualify     15-Jan       25-Jan
    1         Develop     25-Jan       9-Feb
    1         Qualify     9-Feb        7-March
    1         Develop     7-March      9-April
    1         Prospect    9-April     10-March ----(actualclosedate)
</code>```

答:
Assuming createdOn is stored as a valid date/time type and by next you mean next by this column, then just use lead():

```<code>select sc.*,
       lead(createdOn) over (partition by OppId order by createdOn) as next_created_on
from stagechange sc;
</code>```

This assumes (although not explicitly stated in the question) that you want the next date per OppId.

lead() is an ANSI standard function available in most, but not all databases.

Body:
I have Table called Opp Table

   OppID         actualclosedate
--------------------------------------
    1            10-March

I have a Table called stagechange

--------------------------------------
   OppID      Stage       createdon
--------------------------------------
    1         Propsect    1-Jan
    1         Qualify     15-Jan
    1         Develop     25-Jan
    1         Qualify     9-Feb
    1         Develop     7-March
    1         Prospect    9-April

How Can I create a new column and get the next row value that is in createdon column; to have something like this. If there is no more next values, we get the date from other table like actual close date in Opp Table

--------------------------------------
   OppID      Stage       createdon   newcolumn
--------------------------------------
    1         Propsect    1-Jan        15-Jan
    1         Qualify     15-Jan       25-Jan
    1         Develop     25-Jan       9-Feb
    1         Qualify     9-Feb        7-March
    1         Develop     7-March      9-April
    1         Prospect    9-April     10-March ----(actualclosedate)

Body:
Assuming createdOn is stored as a valid date/time type and by next you mean next by this column, then just use lead():

select sc.*,
       lead(createdOn) over (partition by OppId order by createdOn) as next_created_on
from stagechange sc;

This assumes (although not explicitly stated in the question) that you want the next date per OppId.

lead() is an ANSI standard function available in most, but not all databases.


问:
Array of structs - C bad value
I'm facing a quite interesting problem in C.
So I have a struct which looks like this:

```<code>struct Question {
    int year;
    char* month;
    char* day;
    char* hour;
    char* minute;
    char* second;
    char* question;
    int answerCount;
    char* answers[1024];
} questions[100];
</code>```

There, I'm initializing an array of Question structs called questions, with the size of 100.

So I want to fill that array from a file looking like this:

```<code>2017 04 01 12 38 00 OK? 2 NO NO
2017 04 01 14 15 00 WHAT? 4 YES YES YES YES
</code>```

The structure:
year month day hour minute second question answercount answers

I'm processing the file like this:

```<code>...
int id = 0;
int j;

char line[2048];
while ( (fgets(line, sizeof(line), fp)) != NULL) {

        char* p = strtok(line, " ");
        char* tokens[1024];
        char* token;

        int i = 0;
        int counter = 0;

        while((p != NULL)) {
            switch(counter) {
                case 0: questions[id].year = atoi(p); break; // year
                case 1: questions[id].month = p; break; // month
                case 2: questions[id].day = p; break; // day
                case 3: questions[id].hour =p; break; // hour
                case 4: questions[id].minute = p; break; // minute
                case 5: questions[id].second = p; break; // seconds
                case 6: questions[id].question = p; break; // question
                case 7:
                questions[id].answerCount = atoi(p);
                int qcount = atoi(p);
                int k;
                int l = j;
                //printf("count : %d", qcount);
                for (k = 0; k < qcount; ++k) {
                    p = strtok(NULL, " ");
                    ++l;
                    questions[id].answers[k] = p;
                }
                break;
                default: break;
            }
            p = strtok(NULL, " ");
            ++counter;
        }
        ++id;

    }
    fclose(fp);
...
</code>```

After that, if I printf the questions[0].question element in the while loop, I get "OK?", however if I print the same thing after the while loop, I get "WHAT?".

I've spent a lot of time thinking what I might do wrong, but no success.

Thanks for your help.

答:
In your structure, you are having many char pointers, for all of them you are assigning pointer values returned from strtok. You need to understand that the contents of pointers returned by strtok will change overtime with each call to strtok and you are not supposed to store those pointers for future use. Refer to man of strtok.

You need to either change the char * in your structure to char array or alloc memory for those char * and then copy the contents of the pointer to returned by strtok to it. Otherwise you may end up getting weird behavior from your program.

Title: Array of structs - C bad value

Body:
I'm facing a quite interesting problem in C.
So I have a struct which looks like this:

struct Question {
    int year;
    char* month;
    char* day;
    char* hour;
    char* minute;
    char* second;
    char* question;
    int answerCount;
    char* answers[1024];
} questions[100];

There, I'm initializing an array of Question structs called questions, with the size of 100.

So I want to fill that array from a file looking like this:

2017 04 01 12 38 00 OK? 2 NO NO
2017 04 01 14 15 00 WHAT? 4 YES YES YES YES

The structure:
year month day hour minute second question answercount answers

I'm processing the file like this:

...
int id = 0;
int j;

char line[2048];
while ( (fgets(line, sizeof(line), fp)) != NULL) {

        char* p = strtok(line, " ");
        char* tokens[1024];
        char* token;

        int i = 0;
        int counter = 0;

        while((p != NULL)) {
            switch(counter) {
                case 0: questions[id].year = atoi(p); break; // year
                case 1: questions[id].month = p; break; // month
                case 2: questions[id].day = p; break; // day
                case 3: questions[id].hour =p; break; // hour
                case 4: questions[id].minute = p; break; // minute
                case 5: questions[id].second = p; break; // seconds
                case 6: questions[id].question = p; break; // question
                case 7:
                questions[id].answerCount = atoi(p);
                int qcount = atoi(p);
                int k;
                int l = j;
                //printf("count : %d", qcount);
                for (k = 0; k < qcount; ++k) {
                    p = strtok(NULL, " ");
                    ++l;
                    questions[id].answers[k] = p;
                }
                break;
                default: break;
            }
            p = strtok(NULL, " ");
            ++counter;
        }
        ++id;

    }
    fclose(fp);
...

After that, if I printf the questions[0].question element in the while loop, I get "OK?", however if I print the same thing after the while loop, I get "WHAT?".

I've spent a lot of time thinking what I might do wrong, but no success.

Thanks for your help.


问:
Javascript cannot call THIS in code
I'm am using module js syntax and I have some code like this:

```<code>var myModule = {

    settings: {
        myage: 25
    },

    init: function() {

        //init code here

    },

    someFunction1: function(param1) {

        //function code here

    },

    someFunction2: function() {

       myModule.someFunction1(myparam);

    }

}
</code>```

The above will work fine but if I tried:

```<code>someFunction2: function() {

    this.someFunction1(myparam);

}
</code>```

It will not find the function.

Can't I use this.someFunction1... ?

答:
this is who called the function.

myModule.someFunction2() will have this=myModule

someFunction2 = myModule.someFunction2; someFunction2() will have this=window

(you didn't show how you're calling it though)

Title: Javascript cannot call THIS in code

Body:
I'm am using module js syntax and I have some code like this:

var myModule = {

    settings: {
        myage: 25
    },

    init: function() {

        //init code here

    },

    someFunction1: function(param1) {

        //function code here

    },

    someFunction2: function() {

       myModule.someFunction1(myparam);

    }

}

The above will work fine but if I tried:

someFunction2: function() {

    this.someFunction1(myparam);

}

It will not find the function.

Can't I use this.someFunction1... ?


问:
Python Spark-Streaming get n max keys
I am doing a simple wordcount with Spark Streaming. How do I get the n most used words, or in other words, get the first n keys with the highest values?

Here is my code so far:

```<code>counts = lines.flatMap(lambda line: line.split(" ")) \
.map(lambda word: (word, 1)) \
.reduceByKeyAndWindow(lambda a, b: a+b, lambda a, b: a-b, 30, 2)

output = counts.map(lambda (a, b):(b, a)).transform(lambda rdd: rdd.sortByKey(ascending=False)).map(lambda (a, b):(b, a))
</code>```

Which already sorts the list in descending order, now I need to just take the top n elements. There is examples out there how to do it in Scala, which uses rdd.take() and then filter the rdd based on list.contains. But Python doesn't have list.contains.

答:
You can always use Python to explore the List. Seems you have not explored much in python. In Pythonyou can perform List operations.

```<code>If value in Mylist:
#Do your action
</code>```

If you wanted to take N number of element from List

```<code>list[:10]
</code>```

will give you the first 10 elements of this list using slicing.

Python List document

Please have look on this answer pythons-slice-notation

Title: Python Spark-Streaming get n max keys

Body:
I am doing a simple wordcount with Spark Streaming. How do I get the n most used words, or in other words, get the first n keys with the highest values?

Here is my code so far:

counts = lines.flatMap(lambda line: line.split(" ")) \
.map(lambda word: (word, 1)) \
.reduceByKeyAndWindow(lambda a, b: a+b, lambda a, b: a-b, 30, 2)

output = counts.map(lambda (a, b):(b, a)).transform(lambda rdd: rdd.sortByKey(ascending=False)).map(lambda (a, b):(b, a))

Which already sorts the list in descending order, now I need to just take the top n elements. There is examples out there how to do it in Scala, which uses rdd.take() and then filter the rdd based on list.contains. But Python doesn't have list.contains.

Body:
You can always use Python to explore the List. Seems you have not explored much in python. In Pythonyou can perform List operations.

If value in Mylist:
#Do your action

If you wanted to take N number of element from List

list[:10]

will give you the first 10 elements of this list using slicing.

Python List document

Please have look on this answer pythons-slice-notation


问:
Bulk insert using EntityFramework Extended
According to this, bulk insert in Entity can be made using the following code:

```<code> var customers = GetCustomers();
 db.Customers.AddRange(customers);
 db.SaveChanges();
</code>```

I used SQL Profiler to verify how many insert queries were executed and I saw there was an insert for each element of the list.

Why?

答:
AddRange

Add range doesn't perform a BulkInsert, it simply DetectChanges once after all entities are added to the set.

The DetectChange method can be VERY slow.

See: Entity Framework - DetectChanges Performance

As you noticed, it saves entities one by one in the database which is INSANELY slow.

EF.Extended

This library is not longer supported, and there is no Bulk Insert feature.

Bulk Insert Library

There is three major library supporting Bulk Insert:

Entity Framework Extensions (Paid but supported)

EntityFramework.BulkInsert (No longer supported)

EFUtilities (No longer supported)

Be careful, both free libraries don't support all inheritances and associations.

Disclaimer: I'm the owner of the project Entity Framework Extensions

In addition of Bulk Insert, this library allows you to perform all bulk operations:

BulkSaveChanges

BulkInsert

BulkUpdate

BulkDelete

BulkMerge

BulkSynchronize

Example:

```<code>// Easy to use
context.BulkSaveChanges();

// Easy to customize
context.BulkSaveChanges(bulk => bulk.BatchSize = 100);

// Perform Bulk Operations
context.BulkDelete(customers);
context.BulkInsert(customers);
context.BulkUpdate(customers);

// Customize Primary Key
context.BulkMerge(customers, operation => {
   operation.ColumnPrimaryKeyExpression =
        customer => customer.Code;
});
</code>```

Body:
According to this, bulk insert in Entity can be made using the following code:

 var customers = GetCustomers();
 db.Customers.AddRange(customers);
 db.SaveChanges();

I used SQL Profiler to verify how many insert queries were executed and I saw there was an insert for each element of the list.

Why?

Body:
AddRange

Add range doesn't perform a BulkInsert, it simply DetectChanges once after all entities are added to the set.

The DetectChange method can be VERY slow.

See: Entity Framework - DetectChanges Performance

As you noticed, it saves entities one by one in the database which is INSANELY slow.

EF.Extended

This library is not longer supported, and there is no Bulk Insert feature.

Bulk Insert Library

There is three major library supporting Bulk Insert:

Entity Framework Extensions (Paid but supported)

EntityFramework.BulkInsert (No longer supported)

EFUtilities (No longer supported)

Be careful, both free libraries don't support all inheritances and associations.

Disclaimer: I'm the owner of the project Entity Framework Extensions

In addition of Bulk Insert, this library allows you to perform all bulk operations:

BulkSaveChanges

BulkInsert

BulkUpdate

BulkDelete

BulkMerge

BulkSynchronize

Example:

// Easy to use
context.BulkSaveChanges();

// Easy to customize
context.BulkSaveChanges(bulk => bulk.BatchSize = 100);

// Perform Bulk Operations
context.BulkDelete(customers);
context.BulkInsert(customers);
context.BulkUpdate(customers);

// Customize Primary Key
context.BulkMerge(customers, operation => {
   operation.ColumnPrimaryKeyExpression =
        customer => customer.Code;
});

ContentLicense: CC BY-SA 4.0


问:
Where can I find a list of textual MIME types?
I want to make a list of MIME Types which can be compressed by gzip. The first obvious ones to includes are those which begin with "text/". Beyond that I can only add the ones off the top of my head which I know are textual, like "application/json".

Is there a list, canonical or otherwise, that I can refer to?

答:
If you're here looking for a list to put in your gzip_types for Nginx, this is a good starting point (taken from a quick scan of obviously compressable types from /etc/nginx/mime.types):

```<code>gzip_types text/css text/xml application/javascript application/atom+xml application/rss+xml text/mathml text/plain text/x-component image/svg+xml application/json application/vnd.google-earth.kml+xml application/x-perl application/xhtml+xml application/xspf+xml;
</code>```

(text/html is always included, and should not be duplicated in gzip_types)

Body:
If you're here looking for a list to put in your gzip_types for Nginx, this is a good starting point (taken from a quick scan of obviously compressable types from /etc/nginx/mime.types):

gzip_types text/css text/xml application/javascript application/atom+xml application/rss+xml text/mathml text/plain text/x-component image/svg+xml application/json application/vnd.google-earth.kml+xml application/x-perl application/xhtml+xml application/xspf+xml;

(text/html is always included, and should not be duplicated in gzip_types)


问:
Error while installing Dynamic Code Evolution VM (DCE) with Java 8
I am running Ubuntu 17.04 (64-bit) with Java 8. I am facing following error while installing Dynamic Code Evolution VM (DCE) with Java 8.

Could not find data/64/lib/amd64/server/libjvm.so in jar-file.

I have tried to put amd64 libraries in classpath as:

```<code>export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/jvm/java-8-oracle/jre/lib/amd64/:/usr/lib/jvm/java-8-oracle/jre/lib/amd64/server/
</code>```

It didn't work.

Also, I created /etc/ld.so.conf.d/java.conf file and added following lines to it:

```<code>/usr/lib/jvm/java-8-oracle/jre/lib/amd64
/usr/lib/jvm/java-8-oracle/jre/lib/amd64/server
</code>```

And then executed following command:

```<code>sudo ldconfig
</code>```

It didn't work either. Kindly share some pointers. Thanks.

答: Used latest executable from forked Project of DCEVM Project on GitHub. It worked!</p>

Body:
I am running Ubuntu 17.04 (64-bit) with Java 8. I am facing following error while installing Dynamic Code Evolution VM (DCE) with Java 8.

Could not find data/64/lib/amd64/server/libjvm.so in jar-file.

I have tried to put amd64 libraries in classpath as:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/jvm/java-8-oracle/jre/lib/amd64/:/usr/lib/jvm/java-8-oracle/jre/lib/amd64/server/

It didn't work.

Also, I created /etc/ld.so.conf.d/java.conf file and added following lines to it:

/usr/lib/jvm/java-8-oracle/jre/lib/amd64
/usr/lib/jvm/java-8-oracle/jre/lib/amd64/server

And then executed following command:

sudo ldconfig

It didn't work either. Kindly share some pointers. Thanks.


问:
Finding the address range of the data segment
As a programming exercise, I am writing a mark-and-sweep garbage collector in C. I wish to scan the data segment (globals, etc.) for pointers to allocated memory, but I don't know how to get the range of the addresses of this segment. How could I do this?</p>

答:
If you're working on Windows, then there are Windows API that would help you.

```<code>//store the base address the loaded Module
dllImageBase = (char*)hModule; //suppose hModule is the handle to the loaded Module (.exe or .dll)

//get the address of NT Header
IMAGE_NT_HEADERS *pNtHdr = ImageNtHeader(hModule);

//after Nt headers comes the table of section, so get the addess of section table
IMAGE_SECTION_HEADER *pSectionHdr = (IMAGE_SECTION_HEADER *) (pNtHdr + 1);

ImageSectionInfo *pSectionInfo = NULL;

//iterate through the list of all sections, and check the section name in the if conditon. etc
for ( int i = 0 ; i < pNtHdr->FileHeader.NumberOfSections ; i++ )
{
     char *name = (char*) pSectionHdr->Name;
     if ( memcmp(name, ".data", 5) == 0 )
     {
          pSectionInfo = new ImageSectionInfo(".data");
          pSectionInfo->SectionAddress = dllImageBase + pSectionHdr->VirtualAddress;

          **//range of the data segment - something you're looking for**
          pSectionInfo->SectionSize = pSectionHdr->Misc.VirtualSize;
          break;
      }
      pSectionHdr++;
}
</code>```

Define ImageSectionInfo as,

```<code>struct ImageSectionInfo
{
      char SectionName[IMAGE_SIZEOF_SHORT_NAME];//the macro is defined WinNT.h
      char *SectionAddress;
      int SectionSize;
      ImageSectionInfo(const char* name)
      {
            strcpy(SectioName, name);
       }
};
</code>```

Here's a complete, minimal WIN32 console program you can run in Visual Studio that demonstrates the use of the Windows API:

```<code>#include <stdio.h>
#include <Windows.h>
#include <DbgHelp.h>
#pragma comment( lib, "dbghelp.lib" )

void print_PE_section_info(HANDLE hModule) // hModule is the handle to a loaded Module (.exe or .dll)
{
   // get the location of the module's IMAGE_NT_HEADERS structure
   IMAGE_NT_HEADERS *pNtHdr = ImageNtHeader(hModule);

   // section table immediately follows the IMAGE_NT_HEADERS
   IMAGE_SECTION_HEADER *pSectionHdr = (IMAGE_SECTION_HEADER *)(pNtHdr + 1);

   const char* imageBase = (const char*)hModule;
   char scnName[sizeof(pSectionHdr->Name) + 1];
   scnName[sizeof(scnName) - 1] = '\0'; // enforce nul-termination for scn names that are the whole length of pSectionHdr->Name[]

   for (int scn = 0; scn < pNtHdr->FileHeader.NumberOfSections; ++scn)
   {
      // Note: pSectionHdr->Name[] is 8 bytes long. If the scn name is 8 bytes long, ->Name[] will
      // not be nul-terminated. For this reason, copy it to a local buffer that's nul-terminated
      // to be sure we only print the real scn name, and no extra garbage beyond it.
      strncpy(scnName, (const char*)pSectionHdr->Name, sizeof(pSectionHdr->Name));

      printf("  Section %3d: %p...%p %-10s (%u bytes)\n",
         scn,
         imageBase + pSectionHdr->VirtualAddress,
         imageBase + pSectionHdr->VirtualAddress + pSectionHdr->Misc.VirtualSize - 1,
         scnName,
         pSectionHdr->Misc.VirtualSize);
      ++pSectionHdr;
   }
}

// For demo purpopses, create an extra constant data section whose name is exactly 8 bytes long (the max)
#pragma const_seg(".t_const") // begin allocating const data in a new section whose name is 8 bytes long (the max)
const char const_string1[] = "This string is allocated in a special const data segment named \".t_const\".";
#pragma const_seg() // resume allocating const data in the normal .rdata section

int main(int argc, const char* argv[])
{
   print_PE_section_info(GetModuleHandle(NULL)); // print section info for "this process's .exe file" (NULL)
}
</code>```

This page may be helpful if you're interested in additional uses of the DbgHelp library.

You can read the PE image format here, to know it in details. Once you understand the PE format, you'll be able to work with the above code, and can even modify it to meet your need.

PE Format

Peering Inside the PE: A Tour of the Win32 Portable Executable File Format

An In-Depth Look into the Win32 Portable Executable File Format, Part 1

An In-Depth Look into the Win32 Portable Executable File Format, Part 2

Windows API and Structures

IMAGE_SECTION_HEADER Structure

ImageNtHeader Function

IMAGE_NT_HEADERS Structure

I think this would help you to great extent, and the rest you can research yourself :-)

By the way, you can also see this thread, as all of these are somehow related to this:

Scenario: Global variables in DLL which is used by Multi-threaded Application

Body:
If you're working on Windows, then there are Windows API that would help you.

//store the base address the loaded Module
dllImageBase = (char*)hModule; //suppose hModule is the handle to the loaded Module (.exe or .dll)

//get the address of NT Header
IMAGE_NT_HEADERS *pNtHdr = ImageNtHeader(hModule);

//after Nt headers comes the table of section, so get the addess of section table
IMAGE_SECTION_HEADER *pSectionHdr = (IMAGE_SECTION_HEADER *) (pNtHdr + 1);

ImageSectionInfo *pSectionInfo = NULL;

//iterate through the list of all sections, and check the section name in the if conditon. etc
for ( int i = 0 ; i < pNtHdr->FileHeader.NumberOfSections ; i++ )
{
     char *name = (char*) pSectionHdr->Name;
     if ( memcmp(name, ".data", 5) == 0 )
     {
          pSectionInfo = new ImageSectionInfo(".data");
          pSectionInfo->SectionAddress = dllImageBase + pSectionHdr->VirtualAddress;

          **//range of the data segment - something you're looking for**
          pSectionInfo->SectionSize = pSectionHdr->Misc.VirtualSize;
          break;
      }
      pSectionHdr++;
}

Define ImageSectionInfo as,

struct ImageSectionInfo
{
      char SectionName[IMAGE_SIZEOF_SHORT_NAME];//the macro is defined WinNT.h
      char *SectionAddress;
      int SectionSize;
      ImageSectionInfo(const char* name)
      {
            strcpy(SectioName, name);
       }
};

Here's a complete, minimal WIN32 console program you can run in Visual Studio that demonstrates the use of the Windows API:

#include <stdio.h>
#include <Windows.h>
#include <DbgHelp.h>
#pragma comment( lib, "dbghelp.lib" )

void print_PE_section_info(HANDLE hModule) // hModule is the handle to a loaded Module (.exe or .dll)
{
   // get the location of the module's IMAGE_NT_HEADERS structure
   IMAGE_NT_HEADERS *pNtHdr = ImageNtHeader(hModule);

   // section table immediately follows the IMAGE_NT_HEADERS
   IMAGE_SECTION_HEADER *pSectionHdr = (IMAGE_SECTION_HEADER *)(pNtHdr + 1);

   const char* imageBase = (const char*)hModule;
   char scnName[sizeof(pSectionHdr->Name) + 1];
   scnName[sizeof(scnName) - 1] = '\0'; // enforce nul-termination for scn names that are the whole length of pSectionHdr->Name[]

   for (int scn = 0; scn < pNtHdr->FileHeader.NumberOfSections; ++scn)
   {
      // Note: pSectionHdr->Name[] is 8 bytes long. If the scn name is 8 bytes long, ->Name[] will
      // not be nul-terminated. For this reason, copy it to a local buffer that's nul-terminated
      // to be sure we only print the real scn name, and no extra garbage beyond it.
      strncpy(scnName, (const char*)pSectionHdr->Name, sizeof(pSectionHdr->Name));

      printf("  Section %3d: %p...%p %-10s (%u bytes)\n",
         scn,
         imageBase + pSectionHdr->VirtualAddress,
         imageBase + pSectionHdr->VirtualAddress + pSectionHdr->Misc.VirtualSize - 1,
         scnName,
         pSectionHdr->Misc.VirtualSize);
      ++pSectionHdr;
   }
}

// For demo purpopses, create an extra constant data section whose name is exactly 8 bytes long (the max)
#pragma const_seg(".t_const") // begin allocating const data in a new section whose name is 8 bytes long (the max)
const char const_string1[] = "This string is allocated in a special const data segment named \".t_const\".";
#pragma const_seg() // resume allocating const data in the normal .rdata section

int main(int argc, const char* argv[])
{
   print_PE_section_info(GetModuleHandle(NULL)); // print section info for "this process's .exe file" (NULL)
}

This page may be helpful if you're interested in additional uses of the DbgHelp library.

You can read the PE image format here, to know it in details. Once you understand the PE format, you'll be able to work with the above code, and can even modify it to meet your need.

PE Format

Peering Inside the PE: A Tour of the Win32 Portable Executable File Format

An In-Depth Look into the Win32 Portable Executable File Format, Part 1

An In-Depth Look into the Win32 Portable Executable File Format, Part 2

Windows API and Structures

IMAGE_SECTION_HEADER Structure

ImageNtHeader Function

IMAGE_NT_HEADERS Structure

I think this would help you to great extent, and the rest you can research yourself :-)

By the way, you can also see this thread, as all of these are somehow related to this:

Scenario: Global variables in DLL which is used by Multi-threaded Application


问:
How to use CASE in my Scenario in SQL Server?
I have to calculate total quantity with certain cases.

#customerSales table:

```<code>ItemLookupCode  TotalQuantity
-----------------------------
111A000         20
111B001         320
111D000         5
111D001         5
111D002         1
111D003         1
</code>```

#temp_ItemRelations table

```<code>ID  ItemLookupCode  ChildItemLookupCode1   Child1Piece    ChildItemLookupCode2  Child2Piece   ChildItemLookupCode    Child3Piece
---------------------------------------------------------------------------------------------------------------
352 111A000         111A001                5                       111A002         3                   NULL             NULL
365 111B000         111B001                4                       NULL          NULL                  NULL             NULL
377 111C000         111C001                10                      111C002         5                  111C003            1
412 111D000         111D001                12                      111D002         8                  111D003            4
601 111E000         111E001                16                      111E002         6                  111E003            1
</code>```

You can see 111D000 of ItemLookupCode in #temp_ItemRelations, all children are sold including parent.

So output should be like below

```<code> ItemLookupCode     TotalQuantity    //parent    + child1 + child2 + child3
 111D000                77           //  5       + (5*12) + (1*8)  + (1*4)
 111A000                20           //  20      + no child
 111B000               1280          // noparent + (4*320)+ nochild2 & 3
</code>```

I tried the following query. But I don't how to sum those values. I know the following query is wrong. But I tried.

```<code>SELECT
    ir.ItemLookupCode,
    (CASE
        WHEN cs.ItemLookupCode = ir.ItemLookupCode
           THEN cs.TotalQuantity
        WHEN cs.itemlookupcode = ir1.childitemlookupcode1
           THEN (cs.TotalQuantity * ir.Child1Piece)
        WHEN cs.itemlookupcode = ir2.childitemlookupcode2
           THEN (cs.TotalQuantity * ir.Child2Piece)
        WHEN cs.itemlookupcode = ir3.childitemlookupcode
           THEN (cs.TotalQuantity * ir.Child3Piece)
        ELSE 0
     END) AS TotalQuantity
FROM
    #temp_ItemRelations ir
LEFT JOIN
    #customerSales cs ON cs.itemlookupcode = ir.itemlookupcode
LEFT JOIN
    #temp_ItemRelations ir1 ON cs.itemlookupcode = ir1.childitemlookupcode1
LEFT JOIN
    #temp_ItemRelations ir2 ON cs.itemlookupcode = ir2.childitemlookupcode2
LEFT JOIN
    #temp_ItemRelations ir3 ON cs.itemlookupcode = ir3.childitemlookupcode
</code>```

答:
When you do

CASE WHEN condition1 THEN expression1
     WHEN condition2 THEN expression2
...

This will mean that when condition1 is TRUE, the result will be expression1.
There will only be a check for condition2 when condition1 is FALSE.

Body:
I have to calculate total quantity with certain cases.

#customerSales table:

ItemLookupCode  TotalQuantity
-----------------------------
111A000         20
111B001         320
111D000         5
111D001         5
111D002         1
111D003         1

#temp_ItemRelations table

ID  ItemLookupCode  ChildItemLookupCode1   Child1Piece    ChildItemLookupCode2  Child2Piece   ChildItemLookupCode    Child3Piece
---------------------------------------------------------------------------------------------------------------
352 111A000         111A001                5                       111A002         3                   NULL             NULL
365 111B000         111B001                4                       NULL          NULL                  NULL             NULL
377 111C000         111C001                10                      111C002         5                  111C003            1
412 111D000         111D001                12                      111D002         8                  111D003            4
601 111E000         111E001                16                      111E002         6                  111E003            1

You can see 111D000 of ItemLookupCode in #temp_ItemRelations, all children are sold including parent.

So output should be like below

 ItemLookupCode     TotalQuantity    //parent    + child1 + child2 + child3
 111D000                77           //  5       + (5*12) + (1*8)  + (1*4)
 111A000                20           //  20      + no child
 111B000               1280          // noparent + (4*320)+ nochild2 & 3

I tried the following query. But I don't how to sum those values. I know the following query is wrong. But I tried.

SELECT
    ir.ItemLookupCode,
    (CASE
        WHEN cs.ItemLookupCode = ir.ItemLookupCode
           THEN cs.TotalQuantity
        WHEN cs.itemlookupcode = ir1.childitemlookupcode1
           THEN (cs.TotalQuantity * ir.Child1Piece)
        WHEN cs.itemlookupcode = ir2.childitemlookupcode2
           THEN (cs.TotalQuantity * ir.Child2Piece)
        WHEN cs.itemlookupcode = ir3.childitemlookupcode
           THEN (cs.TotalQuantity * ir.Child3Piece)
        ELSE 0
     END) AS TotalQuantity
FROM
    #temp_ItemRelations ir
LEFT JOIN
    #customerSales cs ON cs.itemlookupcode = ir.itemlookupcode
LEFT JOIN
    #temp_ItemRelations ir1 ON cs.itemlookupcode = ir1.childitemlookupcode1
LEFT JOIN
    #temp_ItemRelations ir2 ON cs.itemlookupcode = ir2.childitemlookupcode2
LEFT JOIN
    #temp_ItemRelations ir3 ON cs.itemlookupcode = ir3.childitemlookupcode


问:
Having trouble loading jquery into WordPress using many methods
I've now tried several methods to load jquery into wordpress and can't get anything to work. I've tried injecting code directly into wp-config.php, tried using the Use Google Libraries plugin and tried different code in my functions.php file and nothing will work. I've even tried adding jquery directly via cdn to my header and footer files and neither works.

Can anyone think of anything else I can try to get it to work or does anyone have any idea what might be causing this issue?

functions.php:

```<code><?php

function wpb_custom_new_menu() {
    register_nav_menu('my-custom-menu',__( 'My Custom Menu' ));
}

add_action( 'init', 'wpb_custom_new_menu' );

function enqueue_stylesheets() {

    //For registering Styles

    wp_enqueue_style('style', get_stylesheet_directory_uri() . '/css/style.css');

    wp_enqueue_style('fonts', 'https://fonts.googleapis.com/css?family=Open+Sans:400,600,700|Raleway:400,500,600,700,900');

    wp_enqueue_style('fontAwesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css');

    wp_enqueue_style('bootstrapCSS', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');

    //For registering Scripts files
    wp_enqueue_script( 'bootstrapJS', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js', array('jquery'), '3.3.4', true );

    wp_register_script('navbarScroll', get_stylesheet_directory_uri() . '/js/navbarScroll.js', array( 'jquery' ), '', true );

    wp_enqueue_script('navbarScroll');

    wp_register_script( 'navbarScroll', get_template_directory_uri() . '/js/jquery.navbarScroll.js', array( 'jquery' ), '', true );

    wp_enqueue_script( 'navbarScroll' );
}

add_action( 'wp_enqueue_scripts', 'enqueue_stylesheets' );
</code>```

答:
Please remove last 2 argument Or you can enter only argument which having data, please don't pass like (' ') in the argument.
Check the below example.

```<code>/**
 * Enqueue a script with jQuery as a dependency.
 */
function wpdocs_scripts_method () {
  wp_enqueue_script ('custom-script', get_stylesheet_directory_uri (). '/Js/custom_script. js', array ('jquery'));
}
add_action ('wp_enqueue_scripts', 'wpdocs_scripts_method');
</code>```

Also check that JS is exists or not in the destination folder

Body:
I've now tried several methods to load jquery into wordpress and can't get anything to work. I've tried injecting code directly into wp-config.php, tried using the Use Google Libraries plugin and tried different code in my functions.php file and nothing will work. I've even tried adding jquery directly via cdn to my header and footer files and neither works.

Can anyone think of anything else I can try to get it to work or does anyone have any idea what might be causing this issue?

functions.php:

<?php

function wpb_custom_new_menu() {
    register_nav_menu('my-custom-menu',__( 'My Custom Menu' ));
}

add_action( 'init', 'wpb_custom_new_menu' );

function enqueue_stylesheets() {

    //For registering Styles

    wp_enqueue_style('style', get_stylesheet_directory_uri() . '/css/style.css');

    wp_enqueue_style('fonts', 'https://fonts.googleapis.com/css?family=Open+Sans:400,600,700|Raleway:400,500,600,700,900');

    wp_enqueue_style('fontAwesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css');

    wp_enqueue_style('bootstrapCSS', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');

    //For registering Scripts files
    wp_enqueue_script( 'bootstrapJS', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js', array('jquery'), '3.3.4', true );

    wp_register_script('navbarScroll', get_stylesheet_directory_uri() . '/js/navbarScroll.js', array( 'jquery' ), '', true );

    wp_enqueue_script('navbarScroll');

    wp_register_script( 'navbarScroll', get_template_directory_uri() . '/js/jquery.navbarScroll.js', array( 'jquery' ), '', true );

    wp_enqueue_script( 'navbarScroll' );
}

add_action( 'wp_enqueue_scripts', 'enqueue_stylesheets' );

Body:
Please remove last 2 argument Or you can enter only argument which having data, please don't pass like (' ') in the argument.
Check the below example.

/**
 * Enqueue a script with jQuery as a dependency.
 */
function wpdocs_scripts_method () {
  wp_enqueue_script ('custom-script', get_stylesheet_directory_uri (). '/Js/custom_script. js', array ('jquery'));
}
add_action ('wp_enqueue_scripts', 'wpdocs_scripts_method');

Also check that JS is exists or not in the destination folder


问:
C array of pointers to double
I'm getting a memory problem in c++ code, for sure I'm wrong but I don't get the problem. I've declare an array of three pointer to double and allocate memory.

```<code>double *myDoubles[3];

for(int i=0;i<3;i++) {
   myDoubles[i]= (double *) malloc(1000*sizeof(double));
}

myDoubles[2][999]=10.55;
</code>```

Whats wrong?

EDIT

As @EdHeal comments and also @PhilippKiener I should not be using malloc at all. But it's difficult to forget malloc before 25 years with it.
After all my problem was another bug in another place and actually I was writing out of limits :). My fault!

答:
You allocated 1000 bytes each time instead of 1000 doubles.
what you should do is:

```<code>malloc(1000 * sizeof(double));
</code>```

Your complete code should look like this:

```<code>double* myDoubles[3];
for(int i = 0; i < 3; i++) {
    myDoubles[i] = (double*) malloc(1000 * sizeof(double));
}
myDoubles[2][999] = 10.55;
</code>```

Title: C array of pointers to double

Body:
I'm getting a memory problem in c++ code, for sure I'm wrong but I don't get the problem. I've declare an array of three pointer to double and allocate memory.

double *myDoubles[3];

for(int i=0;i<3;i++) {
   myDoubles[i]= (double *) malloc(1000*sizeof(double));
}

myDoubles[2][999]=10.55;

Whats wrong?

EDIT

As @EdHeal comments and also @PhilippKiener I should not be using malloc at all. But it's difficult to forget malloc before 25 years with it.
After all my problem was another bug in another place and actually I was writing out of limits :). My fault!

Body:
You allocated 1000 bytes each time instead of 1000 doubles.
what you should do is:

malloc(1000 * sizeof(double));

Your complete code should look like this:

double* myDoubles[3];
for(int i = 0; i < 3; i++) {
    myDoubles[i] = (double*) malloc(1000 * sizeof(double));
}
myDoubles[2][999] = 10.55;


问:
Cannot show the "block" by using JavaScript
I cannot show the block "login" after the page has loaded.
I already tried using visibility or display to make the "block" hidden or not.

And already tried to put the script part into different place:

<!DOCTYPE html>

  <meta charset="utf-8" />
  <link rel="stylesheet" type="text/css" href="../css/common.css">

  <title>City's Video</title>

      <form method="post" action="home.html">
        Name: <input type="text" name="name">
 Password: <input type="password" name="password">

        <input type="submit" name="Login" value="Login"> <input type="reset" value="reset">
      </form>

```

Body:
getElementByClassName returns an array-like object of all elements which have all of the given class names.
so you have to select the div like this:

document.getElementsByClassName("login")[0].style.display ='block';

https://developer.mozilla.org/en/docs/Web/API/Document/getElementsByClassName

and you need to call functions with parentheses:
<body onload="showlogin()">


问:
Neo4j cypher query with aggregate function returns incomplete result
everyone! I have a Neo4j database which contains information about visitors who visit a number of checkpoints at specific moments of time. visitors, visits and checkpoints are represented as nodes.

Each visitor is identified by his/her device MAC address, each checkpoint has a unique id.

Each visit node contains an EnterTime property, which is the time (num of millisec since 1970) when the visitor with some specific MAC address is first noticed near the respective checkpoint.

Note: the duration of a visit should be calculated as the difference between EnterTime of the next visit and the EnterTime of this visit. Each checkpoint may be visited more than once.

The database is created with this cypher query:

```<code>//Create visitors:
CREATE (Visitor1: Visitor {MAC:'00:0a:95:9d:68:16'})
CREATE (Visitor2: Visitor {MAC:'00:0a:95:9d:68:17'})
CREATE (Visitor3: Visitor {MAC:'00:0a:95:9d:68:18'})

//Create CheckPoints:
CREATE (CheckPoint1: CheckPoint {CheckPointId: 1})
CREATE (CheckPoint2: CheckPoint {CheckPointId: 2})
CREATE (CheckPoint3: CheckPoint {CheckPointId: 3})
CREATE (CheckPoint4: CheckPoint {CheckPointId: 4})
CREATE (CheckPoint5: CheckPoint {CheckPointId: 5})

//Create visits:
//by visitor 1:
CREATE  (Visitor1)-[:MAKES]->(Visit1: Visit {EnterTime: 1488358800000})-[:TO]->(CheckPoint1)
CREATE  (Visitor1)-[:MAKES]->(Visit2: Visit {EnterTime: 1488359400000})-[:TO]->(CheckPoint2)
CREATE  (Visitor1)-[:MAKES]->(Visit3: Visit {EnterTime: 1488361200000})-[:TO]->(CheckPoint3)
CREATE  (Visitor1)-[:MAKES]->(Visit4: Visit {EnterTime: 1488363600000})-[:TO]->(CheckPoint4)
CREATE  (Visitor1)-[:MAKES]->(Visit5: Visit {EnterTime: 1488364800000})-[:TO]->(CheckPoint5)
CREATE  (Visitor1)-[:MAKES]->(Visit6: Visit {EnterTime: 1488365400000})-[:TO]->(CheckPoint1)

//by visitor 2:
CREATE  (Visitor2)-[:MAKES]->(Visit7: Visit {EnterTime: 1488358800000})-[:TO]->(CheckPoint1)
CREATE  (Visitor2)-[:MAKES]->(Visit8: Visit {EnterTime: 1488360300000})-[:TO]->(CheckPoint4)
CREATE  (Visitor2)-[:MAKES]->(Visit9: Visit {EnterTime: 1488362400000})-[:TO]->(CheckPoint2)
CREATE  (Visitor2)-[:MAKES]->(Visit10: Visit {EnterTime: 1488363000000})-[:TO]->(CheckPoint1)

//by visitor 3:
CREATE  (Visitor3)-[:MAKES]->(Visit11: Visit {EnterTime: 1488353820000})-[:TO]->(CheckPoint1)
CREATE  (Visitor3)-[:MAKES]->(Visit12: Visit {EnterTime: 1488354600000})-[:TO]->(CheckPoint4)
CREATE  (Visitor3)-[:MAKES]->(Visit13: Visit {EnterTime: 1488358200000})-[:TO]->(CheckPoint3)
CREATE  (Visitor3)-[:MAKES]->(Visit14: Visit {EnterTime: 1488359700000})-[:TO]->(CheckPoint1)
</code>```

I am writing a cypher query to find the total time of visits to each checkpoint.
I am trying this one:

```<code>match (vr: Visitor)-->(v1: Visit)-->(cp1: CheckPoint),
 (vr)-->(v2: Visit)-->()
where v2.EnterTime > v1.EnterTime
with cp1.CheckPointId as CheckPointId,
     v1.EnterTime as EnterTime,
     min((v2.EnterTime - v1.EnterTime) / 60000) as visit_duration
return CheckPointId, sum(visit_duration) as total_visit_duration
order by CheckPointId;
</code>```

The result should be:

```<code>cp1  - 48 min
cp2 – 40 min
cp3 – 65 min
cp4 – 115 min
cp5 – 10 min
</code>```

But my query returns an incorrect result:

```<code>cp1  - 23 min
cp2 – 40 min
cp3 – 65 min
cp4 – 115 min
cp5 – 10 min
</code>```

Obviously, the error is that the length of the visit by visitor (mac == 00:0a:95:9d:68:17) to the checkpoint with id == 1 is not taken into consideration. But it is my guess.

What is the problem with my query? How can it be improved to return the correct result?

Your help will be much appreciated! Thanks!

答:
I think what you are looking for is this:

```<code>match ()<--(v2:Visit)<--(vr: Visitor)-->(v1: Visit)-->(cp1: CheckPoint)
where v2.EnterTime > v1.EnterTime
with vr,
 cp1.CheckPointId as CheckPointId,
 v1.EnterTime as EnterTime,
 min((v2.EnterTime - v1.EnterTime) / 60000) as visit_duration
return CheckPointId, sum(visit_duration) as total_visit_duration
order by CheckPointId;
</code>```

I added vr in with statement. Cypher groups by the all the values you put in with statement. The reason why your code didnt work is because v1.EnterTime for checkpoint 1 for visitor 1 and 2 is the same. Because you had only EnterTime and CheckpointID in with statement, cypher grouped by EnterTime and so because you have the min(v2.EnterTime - v1.EnterTime) it just took the smaller one and did not use both. Now that we introduce Visitor in the with statement, it will group by visitor also, which solves our problem, if two people start same checkpoint at same time.

Hope this helps

Body:
everyone! I have a Neo4j database which contains information about visitors who visit a number of checkpoints at specific moments of time. visitors, visits and checkpoints are represented as nodes.

Each visitor is identified by his/her device MAC address, each checkpoint has a unique id.

Each visit node contains an EnterTime property, which is the time (num of millisec since 1970) when the visitor with some specific MAC address is first noticed near the respective checkpoint.

Note: the duration of a visit should be calculated as the difference between EnterTime of the next visit and the EnterTime of this visit. Each checkpoint may be visited more than once.

The database is created with this cypher query:

//Create visitors:
CREATE (Visitor1: Visitor {MAC:'00:0a:95:9d:68:16'})
CREATE (Visitor2: Visitor {MAC:'00:0a:95:9d:68:17'})
CREATE (Visitor3: Visitor {MAC:'00:0a:95:9d:68:18'})

//Create CheckPoints:
CREATE (CheckPoint1: CheckPoint {CheckPointId: 1})
CREATE (CheckPoint2: CheckPoint {CheckPointId: 2})
CREATE (CheckPoint3: CheckPoint {CheckPointId: 3})
CREATE (CheckPoint4: CheckPoint {CheckPointId: 4})
CREATE (CheckPoint5: CheckPoint {CheckPointId: 5})

//Create visits:
//by visitor 1:
CREATE  (Visitor1)-[:MAKES]->(Visit1: Visit {EnterTime: 1488358800000})-[:TO]->(CheckPoint1)
CREATE  (Visitor1)-[:MAKES]->(Visit2: Visit {EnterTime: 1488359400000})-[:TO]->(CheckPoint2)
CREATE  (Visitor1)-[:MAKES]->(Visit3: Visit {EnterTime: 1488361200000})-[:TO]->(CheckPoint3)
CREATE  (Visitor1)-[:MAKES]->(Visit4: Visit {EnterTime: 1488363600000})-[:TO]->(CheckPoint4)
CREATE  (Visitor1)-[:MAKES]->(Visit5: Visit {EnterTime: 1488364800000})-[:TO]->(CheckPoint5)
CREATE  (Visitor1)-[:MAKES]->(Visit6: Visit {EnterTime: 1488365400000})-[:TO]->(CheckPoint1)

//by visitor 2:
CREATE  (Visitor2)-[:MAKES]->(Visit7: Visit {EnterTime: 1488358800000})-[:TO]->(CheckPoint1)
CREATE  (Visitor2)-[:MAKES]->(Visit8: Visit {EnterTime: 1488360300000})-[:TO]->(CheckPoint4)
CREATE  (Visitor2)-[:MAKES]->(Visit9: Visit {EnterTime: 1488362400000})-[:TO]->(CheckPoint2)
CREATE  (Visitor2)-[:MAKES]->(Visit10: Visit {EnterTime: 1488363000000})-[:TO]->(CheckPoint1)

//by visitor 3:
CREATE  (Visitor3)-[:MAKES]->(Visit11: Visit {EnterTime: 1488353820000})-[:TO]->(CheckPoint1)
CREATE  (Visitor3)-[:MAKES]->(Visit12: Visit {EnterTime: 1488354600000})-[:TO]->(CheckPoint4)
CREATE  (Visitor3)-[:MAKES]->(Visit13: Visit {EnterTime: 1488358200000})-[:TO]->(CheckPoint3)
CREATE  (Visitor3)-[:MAKES]->(Visit14: Visit {EnterTime: 1488359700000})-[:TO]->(CheckPoint1)

I am writing a cypher query to find the total time of visits to each checkpoint.
I am trying this one:

match (vr: Visitor)-->(v1: Visit)-->(cp1: CheckPoint),
 (vr)-->(v2: Visit)-->()
where v2.EnterTime > v1.EnterTime
with cp1.CheckPointId as CheckPointId,
     v1.EnterTime as EnterTime,
     min((v2.EnterTime - v1.EnterTime) / 60000) as visit_duration
return CheckPointId, sum(visit_duration) as total_visit_duration
order by CheckPointId;

The result should be:

cp1  - 48 min
cp2 – 40 min
cp3 – 65 min
cp4 – 115 min
cp5 – 10 min

But my query returns an incorrect result:

cp1  - 23 min
cp2 – 40 min
cp3 – 65 min
cp4 – 115 min
cp5 – 10 min

Obviously, the error is that the length of the visit by visitor (mac == 00:0a:95:9d:68:17) to the checkpoint with id == 1 is not taken into consideration. But it is my guess.

What is the problem with my query? How can it be improved to return the correct result?

Your help will be much appreciated! Thanks!

Body:
I think what you are looking for is this:

match ()<--(v2:Visit)<--(vr: Visitor)-->(v1: Visit)-->(cp1: CheckPoint)
where v2.EnterTime > v1.EnterTime
with vr,
 cp1.CheckPointId as CheckPointId,
 v1.EnterTime as EnterTime,
 min((v2.EnterTime - v1.EnterTime) / 60000) as visit_duration
return CheckPointId, sum(visit_duration) as total_visit_duration
order by CheckPointId;

I added vr in with statement. Cypher groups by the all the values you put in with statement. The reason why your code didnt work is because v1.EnterTime for checkpoint 1 for visitor 1 and 2 is the same. Because you had only EnterTime and CheckpointID in with statement, cypher grouped by EnterTime and so because you have the min(v2.EnterTime - v1.EnterTime) it just took the smaller one and did not use both. Now that we introduce Visitor in the with statement, it will group by visitor also, which solves our problem, if two people start same checkpoint at same time.

Hope this helps