问:
How to set default date of format 'MM/dd/yyyy'
Here is my code for creating calendar by using Bootstrap datetimepicker:

```<code>$('#datetimepicker12').datetimepicker({
    inline: true,
    format: 'MM/dd/yyyy',
    minDate: new Date(moment(new Date()).add(0, 'days').toDate()),
    maxDate: new Date(moment(new Date()).add(7, 'days').toDate()),
});
</code>```

Now I want to set default date of calendar to be my custom date, its format is like this '2017-03-30'

How can I convert that to be the same format as format of datetimepicker that I have set before?

答:
Valid formats are documented here:

https://eonasdan.github.io/bootstrap-datetimepicker/Options/#format

and from there you can read:

See momentjs' docs for valid formats. Format also dictates what components are shown, e.g. MM/dd/YYYY will not display the time picker.

http://momentjs.com/docs/#/displaying/format/

So for your particular case it will be:

```<code>format: 'MM/DD/YYYY'  //(all uppercase)
</code>```

and to set the default value you need to use:

```<code>defaultDate:
</code>```

The documentation for defaultDate is here

Body:
Here is my code for creating calendar by using Bootstrap datetimepicker:

$('#datetimepicker12').datetimepicker({
    inline: true,
    format: 'MM/dd/yyyy',
    minDate: new Date(moment(new Date()).add(0, 'days').toDate()),
    maxDate: new Date(moment(new Date()).add(7, 'days').toDate()),
});

Now I want to set default date of calendar to be my custom date, its format is like this '2017-03-30'

How can I convert that to be the same format as format of datetimepicker that I have set before?

Body:
Valid formats are documented here:

https://eonasdan.github.io/bootstrap-datetimepicker/Options/#format

and from there you can read:

See momentjs' docs for valid formats. Format also dictates what components are shown, e.g. MM/dd/YYYY will not display the time picker.

http://momentjs.com/docs/#/displaying/format/

So for your particular case it will be:

format: 'MM/DD/YYYY'  //(all uppercase)

and to set the default value you need to use:

defaultDate:

The documentation for defaultDate is here


来源: stackexchange

问:
DataGrid row validation base on other rows
I want to validate a DataGridCell based on values of other DataGridRows in the same DataGrid. But in my inherited MyValidationRule object I can't access all bound items of the DataGrid, but only the current row.

How can I access other bound items of a DataGrid in the Validate() method of a ValidationRule?

答:
What you want to do I think is follow the visual tree up to the DataGrid and from there access the ItemsSource to perform the validation. Something like this...</p>

```<code>public class SampleRowValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        BindingGroup bg = value as BindingGroup;
        if (bg != null && bg.Items.Count > 0)
        {
            DataGridRow dgrow = bg.Owner as DataGridRow;
            if(dgrow != null)
            {
                DataGrid dg = GetParent<DataGrid>(dgrow);
                // ... add more
            }
        }
        return new ValidationResult(true, null);
    }
    private T GetParent<T>(DependencyObject d) where T : class
    {
        while (d != null && !(d is T))
        {
            d = VisualTreeHelper.GetParent(d);
        }
        return d as T;

    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
What you want to do I think is follow the visual tree up to the DataGrid and from there access the ItemsSource to perform the validation. Something like this...

public class SampleRowValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        BindingGroup bg = value as BindingGroup;
        if (bg != null && bg.Items.Count > 0)
        {
            DataGridRow dgrow = bg.Owner as DataGridRow;
            if(dgrow != null)
            {
                DataGrid dg = GetParent<DataGrid>(dgrow);
                // ... add more
            }
        }
        return new ValidationResult(true, null);
    }
    private T GetParent<T>(DependencyObject d) where T : class
    {
        while (d != null && !(d is T))
        {
            d = VisualTreeHelper.GetParent(d);
        }
        return d as T;

    }
}


问:
Java Loop for n integer sum
I have problem with the following question:

Write a program that prompts the user to enter an integer, n. The
  program will print the following results:

Sum of all even numbers between 1 and n (inclusive)

Sum of all odd numbers between 1 and n (inclusive)

Here the code I have so far, when I hit run I am getting exponentially large numbers that keep multiplying. I am aware my code is wrong. I dont know what I am doing wrong. Thank you.

```<code>package assig;

import java.util.Scanner;

public class Assignment4_Question1 {

public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter an integer: ");
int n = in.nextInt();
int evenSum = 0;
int oddSum= 0;

for (int i = 1; 1<=n; i++){
    if(i % 2 == 0){
    evenSum = evenSum + i;
    } else if (i % 2 != 0){
    oddSum = oddSum + i;
    }
    System.out.println(evenSum);
    System.out.println(oddSum);
    }
}
</code>```

答:
You loop is never ending !

```<code>    for (int i = 1; 1<=n; i++)
</code>```

So you are saying the loop will go infinte if you n is bigger than 1!

```<code>   for (int i = 1; i<=n; i++)
</code>```

The difference in here that you loop will go until i reach to n.

Title: Java Loop for n integer sum

Body:
I have problem with the following question:

Write a program that prompts the user to enter an integer, n. The
  program will print the following results:

Sum of all even numbers between 1 and n (inclusive)

Sum of all odd numbers between 1 and n (inclusive)

Here the code I have so far, when I hit run I am getting exponentially large numbers that keep multiplying. I am aware my code is wrong. I dont know what I am doing wrong. Thank you.

package assig;

import java.util.Scanner;

public class Assignment4_Question1 {

public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter an integer: ");
int n = in.nextInt();
int evenSum = 0;
int oddSum= 0;

for (int i = 1; 1<=n; i++){
    if(i % 2 == 0){
    evenSum = evenSum + i;
    } else if (i % 2 != 0){
    oddSum = oddSum + i;
    }
    System.out.println(evenSum);
    System.out.println(oddSum);
    }
}

Body:
You loop is never ending !

    for (int i = 1; 1<=n; i++)

So you are saying the loop will go infinte if you n is bigger than 1!

   for (int i = 1; i<=n; i++)

The difference in here that you loop will go until i reach to n.


问:
AngularJs how to insert one div in another?
I have dynamically created a "reply comment box" (it's a directive now <reply-comment></reply-comment>)

```<code><div class="comment-reply-wrap" ng-repeat="repUser in repUsers">
    <div class="comment">
      <div class="info" >
        <div class="left-side-info">
          <img src="img/avatar.png" alt="avatar" class="avatar">
          <span class="name">{{repUser.name}}</span>
        </div>
        <div class="right-side-info">
          <p class="user-text" ng-bind-html='repUser.text'>
            <img class="comment-image" src="">
          </p>
        </div>
        <div class="bottom">
          <span class="comment-email">{{repUser.email}}</span>
          <span class="comment-date">10/29/2010 at 6:40AM</span>
          <button type="submit" class="reply" ng-click="createReplyForm($event)">
            <i class="fa fa-reply" aria-hidden="true"></i>
          </button>
        </div>
      </div>
    </div>
  </div>
</code>```

Here is top-level 'comment box'

```<code><div class="comment-wrap" ng-repeat="mainComment in mainUsers">
    <div class="comment">
      <div class="info" >
        <div class="left-side-info">
          <img src="img/avatar.png" alt="avatar" class="avatar">
          <span class="name">{{mainComment.name}}</span>
        </div>
        <div class="right-side-info">
          <p class="user-text" ng-bind-html='mainComment.text'>
            <img class="comment-image" src="">
          </p>
        </div>
        <div class="bottom">
          <span class="comment-email">{{mainComment.email}}</span>
          <span class="comment-date">10/29/2010 at 6:40AM</span>
          <button type="submit" class="reply" ng-click="createReplyForm($event)"><i class="fa fa-reply" aria-hidden="true"></i></button>
        </div>
      </div>
    </div>
    <div class="cover" ng-repeat="reply in mainComment">
      <reply-comment></reply-comment>
    </div>

  </div>
</code>```

Controller

```<code>var app = angular.module('commentsApp', ['ngSanitize']);

app.controller('UserController', function($scope){

$scope.mainUsers = [];
$scope.repUsers = [];
$scope.bool = false;

$scope.addUser = function() {

//Dynamically create array of objects and push data

$scope.mainUsers.push({
  name: $scope.user.name,
  email: $scope.user.email,
  homepage: $scope.user.hompage,
  text: $scope.user.text
});

//Clear input fields in main form
$scope.user.name = '';
$scope.user.email = '';
$scope.user.homepage = '';
$scope.user.text = '';
};

$scope.addRepUser = function() {
 $scope.bool = false;
 //Dynamically create array of objects and push data

  $scope.repUsers.push({
  name: $scope.repUser.name,
  email: $scope.repUser.email,
  text: $scope.repUser.text
  });

 //Clear input fields in main form
 $scope.repUser.name = '';
 $scope.repUser.email = '';
 $scope.repUser.text = '';

 };

 $scope.createReplyForm = function($event) {
 $event.currentTarget.parentNode.parentNode.parentNode.parentNode;

 $scope.bool = true;
}

})
</code>```

I want to insert "replied comment" into wrap of "comment" on which i am replying to, because i want to chain these "comments". The aim is to create cascade commentaries.

To make this question clearer, check this  picture of what I want.

答:
You will want to create nesting directives of the same directive.

So you can make this comment item you have into a directive and then call it on itself. Example:

```<code><div class="comment-reply-wrap" ng-repeat="repUser in repUsers">
    <div class="comment">
      <div class="info" >
        <div class="left-side-info">
          <img src="img/avatar.png" alt="avatar" class="avatar">
          <span class="name">{{repUser.name}}</span>
        </div>
        <div class="right-side-info">
          <p class="user-text" ng-bind-html='repUser.text'>
            <img class="comment-image" src="">
          </p>
        </div>
        <div class="bottom">
          <span class="comment-email">{{repUser.email}}</span>
          <span class="comment-date">10/29/2010 at 6:40AM</span>
          <button type="submit" class="reply" ng-click="createReplyForm($event)">
            <i class="fa fa-reply" aria-hidden="true"></i>
          </button>
        </div>
      </div>
    </div>
    <div class="reply">
        <my-comment-directive ng-repeat="reply in comment.replies"  comment="reply"></my-comment-directive>
    </div>
  </div>
</code>```

So after seeing your data structures, I see a change you will need to make.  You want to iterate over comments, not over users.

Something like this

```<code>var commentsArray = [{text: 'comment 1', author: user1, replies: []}]
</code>```

Where replies are simply an array of the same type of format comments.

Body:
I have dynamically created a "reply comment box" (it's a directive now <reply-comment></reply-comment>)

          {{repUser.name}}

          {{repUser.email}}
          10/29/2010 at 6:40AM
          <button type="submit" class="reply" ng-click="createReplyForm($event)">

          </button>

Here is top-level 'comment box'

          {{mainComment.name}}

          {{mainComment.email}}
          10/29/2010 at 6:40AM
          <button type="submit" class="reply" ng-click="createReplyForm($event)"></button>

      <reply-comment></reply-comment>

Controller

var app = angular.module('commentsApp', ['ngSanitize']);

app.controller('UserController', function($scope){

$scope.mainUsers = [];
$scope.repUsers = [];
$scope.bool = false;

$scope.addUser = function() {

//Dynamically create array of objects and push data

$scope.mainUsers.push({
  name: $scope.user.name,
  email: $scope.user.email,
  homepage: $scope.user.hompage,
  text: $scope.user.text
});

//Clear input fields in main form
$scope.user.name = '';
$scope.user.email = '';
$scope.user.homepage = '';
$scope.user.text = '';
};

$scope.addRepUser = function() {
 $scope.bool = false;
 //Dynamically create array of objects and push data

  $scope.repUsers.push({
  name: $scope.repUser.name,
  email: $scope.repUser.email,
  text: $scope.repUser.text
  });

 //Clear input fields in main form
 $scope.repUser.name = '';
 $scope.repUser.email = '';
 $scope.repUser.text = '';

 };

 $scope.createReplyForm = function($event) {
 $event.currentTarget.parentNode.parentNode.parentNode.parentNode;

 $scope.bool = true;
}

})

I want to insert "replied comment" into wrap of "comment" on which i am replying to, because i want to chain these "comments". The aim is to create cascade commentaries.

To make this question clearer, check this  picture of what I want.

Body:
You will want to create nesting directives of the same directive.

So you can make this comment item you have into a directive and then call it on itself. Example:

<div class="comment-reply-wrap" ng-repeat="repUser in repUsers">
    <div class="comment">
      <div class="info" >
        <div class="left-side-info">
          <img src="img/avatar.png" alt="avatar" class="avatar">
          <span class="name">{{repUser.name}}</span>
        </div>
        <div class="right-side-info">
          <p class="user-text" ng-bind-html='repUser.text'>
            <img class="comment-image" src="">
          </p>
        </div>
        <div class="bottom">
          <span class="comment-email">{{repUser.email}}</span>
          <span class="comment-date">10/29/2010 at 6:40AM</span>
          <button type="submit" class="reply" ng-click="createReplyForm($event)">
            <i class="fa fa-reply" aria-hidden="true"></i>
          </button>
        </div>
      </div>
    </div>
    <div class="reply">
        <my-comment-directive ng-repeat="reply in comment.replies"  comment="reply"></my-comment-directive>
    </div>
  </div>

So after seeing your data structures, I see a change you will need to make.  You want to iterate over comments, not over users.

Something like this

var commentsArray = [{text: 'comment 1', author: user1, replies: []}]

Where replies are simply an array of the same type of format comments.


问:
I don't understand why is this step necessary to count the number of chars in text document
```<code>lines = File.readlines("new text document.txt")
lines_count = lines.size
text = lines.join
no_of_chars = text.length

puts "number of lines: #{lines_count}"
puts "number of chars: #{no_of_chars}"
</code>```

Hello my objective is to count the number of chars in the text document. What I do not understand is why is there a need to lines.join? And what is the program doing when you lines.join? Because when I puts lines or puts lines.join the program prints out the exact same thing. Therefore what I did (and what I think is correct) is

```<code>no_of_chars = lines.length
</code>```

which is obviously wrong since by doing that the no_of_char will result in an output that is same as number of lines.

答:
Slurping a file isn't a good way to find the number of characters because it's not scalable. It's easy these days to find files into the GB range, especially in production environments that will hit your Ruby process very hard when trying to slurp the entire file.

Instead, use this:

```<code>char_size = 0
File.foreach('path/to/file.txt') do |li|
  char_size += li.size
end
</code>```

foreach reads the file line-by-line, which, for a file over 1MB, is as fast or faster than using read or readlines, while still being scalable.

See "Why is "slurping" a file not a good practice?" for more information.

If you know the file contains single-byte characters, such as the traditional ASCII, ISO-8859 or Win-1252 character sets, you can do it even faster using File.size('path/to/file.txt').

Using size doesn't require reading the file at all, so it is much faster than any solution that actually opens and reads the content.

Body:
lines = File.readlines("new text document.txt")
lines_count = lines.size
text = lines.join
no_of_chars = text.length

puts "number of lines: #{lines_count}"
puts "number of chars: #{no_of_chars}"

Hello my objective is to count the number of chars in the text document. What I do not understand is why is there a need to lines.join? And what is the program doing when you lines.join? Because when I puts lines or puts lines.join the program prints out the exact same thing. Therefore what I did (and what I think is correct) is

no_of_chars = lines.length

which is obviously wrong since by doing that the no_of_char will result in an output that is same as number of lines.

Body:
Slurping a file isn't a good way to find the number of characters because it's not scalable. It's easy these days to find files into the GB range, especially in production environments that will hit your Ruby process very hard when trying to slurp the entire file.

Instead, use this:

char_size = 0
File.foreach('path/to/file.txt') do |li|
  char_size += li.size
end

foreach reads the file line-by-line, which, for a file over 1MB, is as fast or faster than using read or readlines, while still being scalable.

See "Why is "slurping" a file not a good practice?" for more information.

If you know the file contains single-byte characters, such as the traditional ASCII, ISO-8859 or Win-1252 character sets, you can do it even faster using File.size('path/to/file.txt').

Using size doesn't require reading the file at all, so it is much faster than any solution that actually opens and reads the content.


问:
How to unquote header without unquote other data?
I have data that looks like the following:

```<code>Scenario,ScenName,Step,Date,GBP_fx,EUR_fx
0,"assets",0,"30/09/2016",1,0.865126741
</code>```

It's a huge file with 100k observations. I read it in R and trim it down to 10k and then write it to csv. However, I couldn't find how to unquote only the header without losing the quotes within the data. If I keep quote = TRUE, this is what the final data looks like but I want to get rid of the quotes in the header.

```<code>"Scenario","ScenName","Step","Date","GBP_fx","EUR_fx"
0,"assets",0,"30/09/2016",1,0.865126741
</code>```

Any suggestions?

答:
I'm not sure everything is necessary, but if your input is saved in csv "mycsv.csv", and you are okay including stringr

```<code>library(stringr)
df = read.table("mycsv.csv", sep = ",", quote = "", header = TRUE)
colnames(df) = str_replace( str_replace(colnames(df), "X.", ""), "\\.", "" )
</code>```

Body:
I have data that looks like the following:

Scenario,ScenName,Step,Date,GBP_fx,EUR_fx
0,"assets",0,"30/09/2016",1,0.865126741

It's a huge file with 100k observations. I read it in R and trim it down to 10k and then write it to csv. However, I couldn't find how to unquote only the header without losing the quotes within the data. If I keep quote = TRUE, this is what the final data looks like but I want to get rid of the quotes in the header.

"Scenario","ScenName","Step","Date","GBP_fx","EUR_fx"
0,"assets",0,"30/09/2016",1,0.865126741

Any suggestions?

Body:
I'm not sure everything is necessary, but if your input is saved in csv "mycsv.csv", and you are okay including stringr

library(stringr)
df = read.table("mycsv.csv", sep = ",", quote = "", header = TRUE)
colnames(df) = str_replace( str_replace(colnames(df), "X.", ""), "\\.", "" )


问:
laravel 5.4 homestead setup
when I want add ssh-keygen in cmd  to setup laravel Homestead I recieve this picture:

and when I want add vagrant up this error occurred:

C:/Windows/Homestead/scripts/homestead.rb:118:in `read': No such file or directo                                                                                ry @ rb_sysopen - C:/Users/Hanie/.ssh/id_rsa (Errno::ENOENT)

and My Homestead.yaml is:

what is wrong?

答:
Just remove the 4096 number on your ssh-keygen command.
Try this:

```<code>ssh-keygen -t rsa -C "hanieasemi@gmail.com"
</code>```

Title: laravel 5.4 homestead setup

Body:
Just remove the 4096 number on your ssh-keygen command.
Try this:

ssh-keygen -t rsa -C "hanieasemi@gmail.com"


问:
Java program not liking the word "Scanner"
```<code>import java.lang.*;
import java.util.*;
import java.io.PrintWriter;
import java.io.FileReader;
import java.io.IOException;

public class Test
{
  public static void main(String[] args) throws IOException
  {
    Scanner infile = new Scanner(new FileReader("historyGrades.txt"));
    boolean[] correctAnswers = new boolean[20];
    infile.close();
  }
}
</code>```

I'm getting these errors for some reason:

```<code>C:\Users\Rawr\Documents\Test.java:11: cannot resolve symbol
symbol  : class Scanner
location: class Test
    Scanner infile = new Scanner(new FileReader("historyGrades.txt"));
    ^
C:\Users\Rawr\Documents\Test.java:11: cannot resolve symbol
symbol  : class Scanner
location: class Test
    Scanner infile = new Scanner(new FileReader("historyGrades.txt"));
                         ^
2 errors

Tool completed with exit code 1
</code>```

I have no idea what's going on.
Help is appreciated, Thanks.

答:
Run the following command on command prompt (terminal);

```<code>java -version
</code>```

If the returned version number is less than 1.5 then you have to download the new version of Java. Scanner class is not available in prior versions. Download the new version of SDK from here;

Java SE Downloads

After setting up the new version of Java, add the following import statement in your source file;

```<code>import java.util.Scanner;
</code>```

Now compile your source. It should go like a F16 now. But feel free to ask in case of any problem.

ContentLicense: CC BY-SA 2.5

Body:
import java.lang.*;
import java.util.*;
import java.io.PrintWriter;
import java.io.FileReader;
import java.io.IOException;

public class Test
{
  public static void main(String[] args) throws IOException
  {
    Scanner infile = new Scanner(new FileReader("historyGrades.txt"));
    boolean[] correctAnswers = new boolean[20];
    infile.close();
  }
}

I'm getting these errors for some reason:

C:\Users\Rawr\Documents\Test.java:11: cannot resolve symbol
symbol  : class Scanner
location: class Test
    Scanner infile = new Scanner(new FileReader("historyGrades.txt"));
    ^
C:\Users\Rawr\Documents\Test.java:11: cannot resolve symbol
symbol  : class Scanner
location: class Test
    Scanner infile = new Scanner(new FileReader("historyGrades.txt"));
                         ^
2 errors

Tool completed with exit code 1

I have no idea what's going on.
Help is appreciated, Thanks.

Body:
Run the following command on command prompt (terminal);

java -version

If the returned version number is less than 1.5 then you have to download the new version of Java. Scanner class is not available in prior versions. Download the new version of SDK from here;

Java SE Downloads

After setting up the new version of Java, add the following import statement in your source file;

import java.util.Scanner;

Now compile your source. It should go like a F16 now. But feel free to ask in case of any problem.


问:
How to avoid zombie processes in python?
In Python3, I have essentially the following code:

server.py:

```<code>import os
import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("127.0.0.1", 10000))
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.listen(5)

while True:
    print("waiting")
    connection, client_address = sock.accept()
    print("received")
    child_pid = os.fork()
    if child_pid == 0:
        print("connection received")
        received = connection.recv(1024)
        connection.sendall("OK".encode('utf-8'))
        os._exit(0)
</code>```

client.py:

```<code>import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("127.0.0.1", 10000))
sock.close()
</code>```

When I start the server and then the client, each time the client finishes a zombie process remains.

How to change the code so that no zombie process remains?

答:
The usual technique is to track all the child pids so that they can be killed when the main process exits or whenever you want the children to be cleaned-up.

You can periodically poll and reap processes as needed or wait until you're about to exit.

For an example of how to do this, look at the collect_children() code in the ForkingMixin for the SocketServer module.

The os module has a number of tools for managing the subprocesses like os.wait() and os.kill.

I don't know whether it fits your problem or not, but a multiprocessing.Pool() may be of some help.  It automatically manages a pool of subprocesses and reuses them for future tasks.  It is mainly helpful when there is only limited data exchange between the processes and whether the work is relatively homogenous (all the child processes are doing the same kind of work).

Body:
In Python3, I have essentially the following code:

server.py:

import os
import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("127.0.0.1", 10000))
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.listen(5)

while True:
    print("waiting")
    connection, client_address = sock.accept()
    print("received")
    child_pid = os.fork()
    if child_pid == 0:
        print("connection received")
        received = connection.recv(1024)
        connection.sendall("OK".encode('utf-8'))
        os._exit(0)

client.py:

import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("127.0.0.1", 10000))
sock.close()

When I start the server and then the client, each time the client finishes a zombie process remains.

How to change the code so that no zombie process remains?


问:
Limit maximum rows of SQLite and shift the whole table accordingly
What I want to do sounds easy to implement until I began to think about all the details... So I have a game with 3 difficulties and I save the scores achieved in each in 1 table. The table has 2 columns, one for the score and one invisible to the user for the difficulty so I can sort the scores accordingly. But currently the game is saving any score achieved with no order or maximum count which is not very convenient. Instead I want to limit it to the 3 highest scores for each difficulty and then when the top score for the easy  difficulty is achieved it should add that score to the first row shift the rows and delete the one that used to be 3th before for that difficulty.

Here is how the SQL is storing my scores currently:

what I want to do is limit the row to 9, currently it will keep adding to infinity and after that to make it store the 3 highest scores for each difficulty so that when they are displayed on the ListView in the app they are in decreasing order

答:
First, insert the new score. Then you want to delete the lowest score for that difficulty.

For a specific difficulty X, this query lists the rows you want to keep:

```<code>SELECT *
FROM MyTable
WHERE difficulty = X
ORDER BY score DESC
LIMIT 3;
</code>```

So you want to delete all rows that are not in that list:

```<code>DELETE FROM MyTable
WHERE difficulty = X
  AND ID NOT IN (SELECT ID
                 FROM MyTable
                 WHERE difficulty = X
                 ORDER BY score DESC
                 LIMIT 3);
</code>```

(This statement works correctly even if there are not yet three scores.)

Body:
First, insert the new score. Then you want to delete the lowest score for that difficulty.

For a specific difficulty X, this query lists the rows you want to keep:

SELECT *
FROM MyTable
WHERE difficulty = X
ORDER BY score DESC
LIMIT 3;

So you want to delete all rows that are not in that list:

DELETE FROM MyTable
WHERE difficulty = X
  AND ID NOT IN (SELECT ID
                 FROM MyTable
                 WHERE difficulty = X
                 ORDER BY score DESC
                 LIMIT 3);

(This statement works correctly even if there are not yet three scores.)


问:
Might a State pattern help if I have only a few states?
If something has only two to three states, is it overkill to use the State pattern?</p>

答: No, it's not overkill. Even if you have few actual states and don't anticipate adding more, using the State pattern will make your system easier to test as you can test individual states in isolation.</p>


问:
How do I switch the Activity with the bottomnavigation bar
I created a new project with the bottom-bar activity. This is the generated code:

```<code>package com.aaron.waller.mrpolitik;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;

import com.aaron.waller.mrpolitik.tabs.KommentareFragment;

public class MainActivity extends AppCompatActivity {

    private TextView mTextMessage;

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    mTextMessage.setText(R.string.title_home);
                    Intent fragen = new Intent(MainActivity.this, KommentareFragment.class);
                    startActivity(fragen);
                case R.id.navigation_dashboard:
                    mTextMessage.setText(R.string.title_dashboard);
                case R.id.navigation_notifications:
                    mTextMessage.setText(R.string.title_notifications);
            }
            return true;
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTextMessage = (TextView) findViewById(R.id.message);
        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
    }

}
</code>```

And I want to set these three fragments on the the navigation bar: FirstFragment SecondFragment ThirdFragment

Also I want to swipe between the Fragments, how can I do that?

答:
You can not load Fragments through Intent. To load fragments by BottomNavigationBar you can do as following:

First add FrameLayout to our activity_main.xml:

```<code>  <FrameLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
</code>```

Then replace this container with Fragments onNavigationItemSelected:

```<code> @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            FragmentManager fm = getFragmentManager();
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    mTextMessage.setText(R.string.title_home);
                    fm.beginTransaction().replace(R.id.container, new FirstFragment()).commit();
                case R.id.navigation_dashboard:
                    mTextMessage.setText(R.string.title_dashboard);
                    fm.beginTransaction().replace(R.id.container, new SecondFragment()).commit();
                case R.id.navigation_notifications:
                    mTextMessage.setText(R.string.title_notifications);
                    fm.beginTransaction().replace(R.id.container, new ThirdFragment()).commit();
            }
            return true;
        }
</code>```

To, create swipe effect between fragments you can use ViewPager. Here is a nice tutorial how to use ViewPager to swipe between fragments. Hope this helps.

Body:
I created a new project with the bottom-bar activity. This is the generated code:

package com.aaron.waller.mrpolitik;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;

import com.aaron.waller.mrpolitik.tabs.KommentareFragment;

public class MainActivity extends AppCompatActivity {

    private TextView mTextMessage;

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    mTextMessage.setText(R.string.title_home);
                    Intent fragen = new Intent(MainActivity.this, KommentareFragment.class);
                    startActivity(fragen);
                case R.id.navigation_dashboard:
                    mTextMessage.setText(R.string.title_dashboard);
                case R.id.navigation_notifications:
                    mTextMessage.setText(R.string.title_notifications);
            }
            return true;
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTextMessage = (TextView) findViewById(R.id.message);
        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
    }

}

And I want to set these three fragments on the the navigation bar: FirstFragment SecondFragment ThirdFragment

Also I want to swipe between the Fragments, how can I do that?

Body:
You can not load Fragments through Intent. To load fragments by BottomNavigationBar you can do as following:

First add FrameLayout to our activity_main.xml:

  <FrameLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Then replace this container with Fragments onNavigationItemSelected:

 @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            FragmentManager fm = getFragmentManager();
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    mTextMessage.setText(R.string.title_home);
                    fm.beginTransaction().replace(R.id.container, new FirstFragment()).commit();
                case R.id.navigation_dashboard:
                    mTextMessage.setText(R.string.title_dashboard);
                    fm.beginTransaction().replace(R.id.container, new SecondFragment()).commit();
                case R.id.navigation_notifications:
                    mTextMessage.setText(R.string.title_notifications);
                    fm.beginTransaction().replace(R.id.container, new ThirdFragment()).commit();
            }
            return true;
        }

To, create swipe effect between fragments you can use ViewPager. Here is a nice tutorial how to use ViewPager to swipe between fragments. Hope this helps.


问:
Filtering arrays by strings
I have a situation where I have an array of path names, e.g

```<code>[0]: /var/www/mysite/fred.md
[1]: /var/www/mysite/george.md
[2]: /var/www/mysite/arthur.md
[3]: /var/www/mysite/.htaccess
</code>```

I have another array of strings

```<code>[0]: fred
[1]: art
</code>```

I want to filter the array of path names so that I end up with an array of items where any part of the path name matches the string - so I should get

```<code>[0]: /var/www/mysite/fred.md
[1]: /var/www/mysite/arthur.md
</code>```

What's the most efficient way of doing this in PHP?

答:
Most efficient?

array_filter + your implementation of KMP algorithm.

But its only if you have large amounts of filtered data, if you need quick solution (but not stable and fast work for large amounts of data) use

array_filter, strpos and substr combinations, thay will work great for you, if speed not your priority.

Title: Filtering arrays by strings

Body:
I have a situation where I have an array of path names, e.g

[0]: /var/www/mysite/fred.md
[1]: /var/www/mysite/george.md
[2]: /var/www/mysite/arthur.md
[3]: /var/www/mysite/.htaccess

I have another array of strings

[0]: fred
[1]: art

I want to filter the array of path names so that I end up with an array of items where any part of the path name matches the string - so I should get

[0]: /var/www/mysite/fred.md
[1]: /var/www/mysite/arthur.md

What's the most efficient way of doing this in PHP?


问:
Docker: ENTRYPOINT can't execute command because it doesn't find the file
I'm trying to create a container from node js image and I have configured my Dockerfile as shown:

FROM node:boron

# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

# Install app dependencies
COPY package.json /usr/src/app
RUN npm install

# Bundle app source
COPY . /usr/src/app

VOLUME ./:/usr/src/app
ENTRYPOINT [ "npm run watch" ]
```

In the package.json I have a script called watch than runs the gulp task named watch-less.

If I run npm run watch in my local environment the command works but when I try running the container it doesn't and shows the next error:

docker: Error response from daemon: oci runtime error: container_linux.go:247: starting container process caused "exec: \"npm run watch\": executable file not found in $PATH".

答:
If you use the list notation for ENTRYPOINT, that is, with the [brackets], you must separate the arguments properly.

ENTRYPOINT ["npm", "run", "watch"]
```

Right now it is trying to find a file literally named "npm run watch" and that does not exist.

Body:
I'm trying to create a container from node js image and I have configured my Dockerfile as shown:

FROM node:boron

# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

# Install app dependencies
COPY package.json /usr/src/app
RUN npm install

# Bundle app source
COPY . /usr/src/app

VOLUME ./:/usr/src/app
ENTRYPOINT [ "npm run watch" ]

In the package.json I have a script called watch than runs the gulp task named watch-less.

If I run npm run watch in my local environment the command works but when I try running the container it doesn't and shows the next error:

docker: Error response from daemon: oci runtime error: container_linux.go:247: starting container process caused "exec: \"npm run watch\": executable file not found in $PATH".

Body:
If you use the list notation for ENTRYPOINT, that is, with the [brackets], you must separate the arguments properly.

ENTRYPOINT ["npm", "run", "watch"]

Right now it is trying to find a file literally named "npm run watch" and that does not exist.


问:
Python PIL/numpy conversion
I'm having problems converting between python PIL images and numpy arrays. I already checked existing Stackoverflow posts on this, but it didn't solve the problem:

```<code>import matplotlib.pyplot as plt
import numpy as np
import PIL

rgb_img = plt.imread('some-image.png')
PIL_rgb_img = PIL.Image.fromarray(np.uint8(rgb_img))

plt.imshow(PIL_rgb_img)
</code>```

I get a black screen. I tried with and without converting to uint8, and I also tried only keeping the RGB channels out of the entire RGBA data. Nothing worked.

答:
```<code>from PIL import Image
import numpy as np

#PIL to Numpy
pil_img = Image.open('some-image.png')
numpy_img = np.asarray(pil_img)

#Numpy to PIL
resultImage = Image.fromarray(numpy_img)
</code>```

Title: Python PIL/numpy conversion

Body:
I'm having problems converting between python PIL images and numpy arrays. I already checked existing Stackoverflow posts on this, but it didn't solve the problem:

import matplotlib.pyplot as plt
import numpy as np
import PIL

rgb_img = plt.imread('some-image.png')
PIL_rgb_img = PIL.Image.fromarray(np.uint8(rgb_img))

plt.imshow(PIL_rgb_img)

I get a black screen. I tried with and without converting to uint8, and I also tried only keeping the RGB channels out of the entire RGBA data. Nothing worked.


问:
Redux data is giving me undefined when calling on a component rendering
I am utilizing thunk with react and redux. My action creator executes an API call and returns data in a property "data" and my reducer returns that object. I have this returned object mapped to props in my component. Its an array of 16 items (each item is an image url). when I console.log(this) I can click through and see the data, but if I go further like console.log(this.props.showGallery.imageLinks) it shows undefined.

Another situation is that when I render { this.props.showGallery.imageLinks } I can clearly see all the text of the items in the array on my web page but when I use .map  on it, the console says cannot read property "map" of undefined and the web page is just empty. Am I doing this wrong? How can I make this data like normally?

Am I understanding redux concepts wrongly?

actions.js

```<code>export const SHOW_GALLERY = 'SHOW_GALLERY';
import axios from 'axios';

// FETCH THE IMAGES
export const actionGallery = () => {
  return ( dispatch ) => {
    axios.get('../images')
    .then(res => {
      if (res.status === 200) {
        return dispatch({ type: SHOW_GALLERY, data: [...res.data] });
      }
    })
    .catch(err => console.error(err));
  }
}
</code>```

reducer
images.js

```<code>import { HEAD_SELECTED, SHOW_GALLERY } from '../actions/actions';
import { actionSelectHeadImg } from '../actions/actions';
import { actionGallery } from '../actions/actions';

// Show the image links from an array
export function showGallery(state={}, action) {
  switch(action.type) {
    case SHOW_GALLERY:
      return Object.assign({}, state, { imageLinks: new Array(action.data) })
    default:
      return state;
    }
  }
</code>```

combined Reducers for above:

```<code>import React from 'react';
import { combineReducers } from 'redux';
import { showGallery, headSelected } from './images';

// Combine all your reducers to this
const allReducers =  combineReducers({
  showGallery,
  headSelected
});

export default allReducers;
</code>```

component / container
Gallery.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { actionGallery } from '../actions/actions';
import cheerio from 'cheerio';

class Gallery extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: []
    }
    this.props.actionGallery();
  }
  render() {
    return (
      <div>
        <h1>This is the Gallery.</h1>
        <br />
        <div className="container">
          <div className="row">
              <div className="col-md-8">
                <h2>H2 h2 h2 2h2 </h2>
                { this.props.showGallery.imageLinks.forEach((i, index) => {
                  <p>i</p>
                }) }
              </div>
          </div>
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    showGallery: state.showGallery,
    headSelected: state.headSelected,
    newState: state
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({
    actionGallery,
    actionSelectHeadImg
  }, dispatch)
}

export default connect(mapStateToProps, mapDispatchToProps)(Gallery);
</code>```

A regular component that just holds the other container/components

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import Gallery from './containers/Gallery';
import HeadingImg from './containers/HeadingImg';

class App extends React.Component {
  render() {
    //console.log(this.props.actionGallery())
    return (
      <div>
        <center>
          <h3>SELECTED IMAGE:</h3>
          <br />
          <HeadingImg />
          <hr />
          <Gallery />
        </center>
      </div>
    );
  }
}

export default App;
</code>```

TOP LEVEL COMPONENT (MAIN COMPONENT)

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import App from '../Components/Earth/app';
import allReducers from '../Components/Earth/reducers';
import thunk from 'redux-thunk';

const store = createStore(allReducers, applyMiddleware(thunk));

ReactDOM.render(
  <Provider store={store}>
    <App store={store}/>
  </Provider>
, document.getElementById("root"));
</code>```

答:
I'm assuming when you create your store, you only have the one reducer.  If that is the case then your assumption about 'state.showGallery' existing doesn't. Instead imageLinks will be in state without the 'showGallery'.

If my assumption is correct, then you should change your mapStateToProps to have showGallery as:

```<code>showGallery: { imageLinks: state.imageLinks },
</code>```

Body:
I am utilizing thunk with react and redux. My action creator executes an API call and returns data in a property "data" and my reducer returns that object. I have this returned object mapped to props in my component. Its an array of 16 items (each item is an image url). when I console.log(this) I can click through and see the data, but if I go further like console.log(this.props.showGallery.imageLinks) it shows undefined.

Another situation is that when I render { this.props.showGallery.imageLinks } I can clearly see all the text of the items in the array on my web page but when I use .map  on it, the console says cannot read property "map" of undefined and the web page is just empty. Am I doing this wrong? How can I make this data like normally?

Am I understanding redux concepts wrongly?

actions.js

export const SHOW_GALLERY = 'SHOW_GALLERY';
import axios from 'axios';

// FETCH THE IMAGES
export const actionGallery = () => {
  return ( dispatch ) => {
    axios.get('../images')
    .then(res => {
      if (res.status === 200) {
        return dispatch({ type: SHOW_GALLERY, data: [...res.data] });
      }
    })
    .catch(err => console.error(err));
  }
}

reducer
images.js

import { HEAD_SELECTED, SHOW_GALLERY } from '../actions/actions';
import { actionSelectHeadImg } from '../actions/actions';
import { actionGallery } from '../actions/actions';

// Show the image links from an array
export function showGallery(state={}, action) {
  switch(action.type) {
    case SHOW_GALLERY:
      return Object.assign({}, state, { imageLinks: new Array(action.data) })
    default:
      return state;
    }
  }

combined Reducers for above:

import React from 'react';
import { combineReducers } from 'redux';
import { showGallery, headSelected } from './images';

// Combine all your reducers to this
const allReducers =  combineReducers({
  showGallery,
  headSelected
});

export default allReducers;

component / container
Gallery.js

import React from 'react';
import ReactDOM from 'react-dom';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { actionGallery } from '../actions/actions';
import cheerio from 'cheerio';

class Gallery extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: []
    }
    this.props.actionGallery();
  }
  render() {
    return (

This is the Gallery.

H2 h2 h2 2h2

                { this.props.showGallery.imageLinks.forEach((i, index) => {

i

                }) }

    );
  }
}

function mapStateToProps(state) {
  return {
    showGallery: state.showGallery,
    headSelected: state.headSelected,
    newState: state
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({
    actionGallery,
    actionSelectHeadImg
  }, dispatch)
}

export default connect(mapStateToProps, mapDispatchToProps)(Gallery);

A regular component that just holds the other container/components

import React from 'react';
import ReactDOM from 'react-dom';
import Gallery from './containers/Gallery';
import HeadingImg from './containers/HeadingImg';

class App extends React.Component {
  render() {
    //console.log(this.props.actionGallery())
    return (

SELECTED IMAGE:

          <HeadingImg />

          <Gallery />

    );
  }
}

export default App;

TOP LEVEL COMPONENT (MAIN COMPONENT)

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import App from '../Components/Earth/app';
import allReducers from '../Components/Earth/reducers';
import thunk from 'redux-thunk';

const store = createStore(allReducers, applyMiddleware(thunk));

ReactDOM.render(
  <Provider store={store}>
    <App store={store}/>
  </Provider>
, document.getElementById("root"));

Body:
I'm assuming when you create your store, you only have the one reducer.  If that is the case then your assumption about 'state.showGallery' existing doesn't. Instead imageLinks will be in state without the 'showGallery'.

If my assumption is correct, then you should change your mapStateToProps to have showGallery as:

showGallery: { imageLinks: state.imageLinks },


问:
Bcrypt salt treating byte object as string and wont hash password
Answered

I have a Flask web app with a Postgres DB. I'm trying to implement database
salting with bcrypt, but it seems as though my byte representation is being viewed as a string. To be clear: I'm creating the hashed password with no problem, but when authorizing a login attempt, generating the comparison hash with the passed salt isn't working. Here's the error stack that occurs when I attempt to login:

```<code>lost/app/views/login.py", line 37, in login
authorized = helpers.authorize(username, password)

lost/app/helpers.py", line 108, in authorize
return _check_hash_for_user(username, password)

lost/app/helpers.py", line 93, in _check_hash_for_user
generated_hash = _recreate_hash(password, _get_salt_for_user(username))

lost/app/helpers.py", line 100, in _recreate_hash
hash_pass = bcrypt.hashpw(password.encode('utf-8'), salt)

lost/venv/lib/python3.6/site-packages/bcrypt/__init__.py", line 62, in hashpw
raise TypeError("Unicode-objects must be encoded before hashing")
</code>```

How my users table is created:

```<code>CREATE TABLE users (
    user_pk     SERIAL PRIMARY KEY,
    username    VARCHAR(16) UNIQUE NOT NULL,
    salt        VARCHAR(72) NOT NULL,
    password    VARCHAR(256) NOT NULL
</code>```

Relevant aspects of my login view

```<code>username = request.form.get('username', None)
password = request.form.get('password', None)

# If user exists...
authorized = helpers.authorize(username, password)

if authorized:
    # login...
</code>```

Here's how I created the user's password and salt

```<code>salt = bcrypt.gensalt(12)
password = bcrypt.hashpw(password.encode('utf-8'), salt)
</code>```

The auth aspect of helpers.py

```<code>def _get_hash_for_user(username):
    password = db_query("SELECT password FROM users WHERE username=%s;", [username])[0][0]
    return password

def _get_salt_for_user(username):
    salt = db_query("SELECT salt FROM users WHERE username=%s;", [username])[0][0]
    return salt

def _create_password_hash(password):
    salt = bcrypt.gensalt(16)
    hashed_pass = bcrypt.hashpw(password, salt)
    return hashed_pass, salt

def _check_hash_for_user(username, password):
    stored_hash = _get_hash_for_user(username)
    generated_hash = _recreate_hash(password, _get_salt_for_user(username))
    return stored_hash == generated_hash

def _recreate_hash(password, salt):
    hash_pass = bcrypt.hashpw(password.encode('utf-8'), salt)
    return hash_pass

def authorize(username, password):
    return _check_hash_for_user(username, password)
</code>```

edit:
At the behest of somebody trying to help me through this issue, I am now creating the users table with password and salt using BYTEA data type instead of VARCHAR() - other issues ensued, but I'll be working through them.

答:
As user2357112 indicated: you're getting your salt from the database as a str and it needs to be cast to bytes.

MCVE to reproduce error:

```<code>import bcrypt
salt = str(bcrypt.gensalt())
pw = "Dagg Durneden Co. Mfgrs. Green Hood Shirts"
pw_hash = bcrypt.hashpw(pw.encode('utf-8'), salt)
</code>```

Fix:

```<code>pw_hash = bcrypt.hashpw(pw.encode('utf-8'), bytes(salt))
</code>```

Body:
Answered

I have a Flask web app with a Postgres DB. I'm trying to implement database
salting with bcrypt, but it seems as though my byte representation is being viewed as a string. To be clear: I'm creating the hashed password with no problem, but when authorizing a login attempt, generating the comparison hash with the passed salt isn't working. Here's the error stack that occurs when I attempt to login:

lost/app/views/login.py", line 37, in login
authorized = helpers.authorize(username, password)

lost/app/helpers.py", line 108, in authorize
return _check_hash_for_user(username, password)

lost/app/helpers.py", line 93, in _check_hash_for_user
generated_hash = _recreate_hash(password, _get_salt_for_user(username))

lost/app/helpers.py", line 100, in _recreate_hash
hash_pass = bcrypt.hashpw(password.encode('utf-8'), salt)

lost/venv/lib/python3.6/site-packages/bcrypt/__init__.py", line 62, in hashpw
raise TypeError("Unicode-objects must be encoded before hashing")

How my users table is created:

CREATE TABLE users (
    user_pk     SERIAL PRIMARY KEY,
    username    VARCHAR(16) UNIQUE NOT NULL,
    salt        VARCHAR(72) NOT NULL,
    password    VARCHAR(256) NOT NULL

Relevant aspects of my login view

username = request.form.get('username', None)
password = request.form.get('password', None)

# If user exists...
authorized = helpers.authorize(username, password)

if authorized:
    # login...

Here's how I created the user's password and salt

salt = bcrypt.gensalt(12)
password = bcrypt.hashpw(password.encode('utf-8'), salt)

The auth aspect of helpers.py

def _get_hash_for_user(username):
    password = db_query("SELECT password FROM users WHERE username=%s;", [username])[0][0]
    return password

def _get_salt_for_user(username):
    salt = db_query("SELECT salt FROM users WHERE username=%s;", [username])[0][0]
    return salt

def _create_password_hash(password):
    salt = bcrypt.gensalt(16)
    hashed_pass = bcrypt.hashpw(password, salt)
    return hashed_pass, salt

def _check_hash_for_user(username, password):
    stored_hash = _get_hash_for_user(username)
    generated_hash = _recreate_hash(password, _get_salt_for_user(username))
    return stored_hash == generated_hash

def _recreate_hash(password, salt):
    hash_pass = bcrypt.hashpw(password.encode('utf-8'), salt)
    return hash_pass

def authorize(username, password):
    return _check_hash_for_user(username, password)

edit:
At the behest of somebody trying to help me through this issue, I am now creating the users table with password and salt using BYTEA data type instead of VARCHAR() - other issues ensued, but I'll be working through them.

Body:
As user2357112 indicated: you're getting your salt from the database as a str and it needs to be cast to bytes.

MCVE to reproduce error:

import bcrypt
salt = str(bcrypt.gensalt())
pw = "Dagg Durneden Co. Mfgrs. Green Hood Shirts"
pw_hash = bcrypt.hashpw(pw.encode('utf-8'), salt)

Fix:

pw_hash = bcrypt.hashpw(pw.encode('utf-8'), bytes(salt))


问:
Android Studio: SharedPreferences not working between activities
I'm currently working on an android app where I want to add a login/logout system using JDBC for the SQL and SharedPreferences to handle the sessions, the SQL works perfectly but when i go from the login activity to the main activity and try to get the values in the sharedpreferences it returns the default values.

Here is my Login Activity:

```<code>private TextView usernameHeader, passwordHeader;
private EditText username, password;
private Button loginButton;
private Handler alertHandler;
private String userRes, passwdRes;
SharedPreferences sharedPreferences;
public static final String MySession = "MySession";
public static final String nameField = "nameKey";
public static final String passwordField = "passwordKey";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    loginButton = (Button) findViewById(R.id.loginButton);

    username = (EditText) findViewById(R.id.username);
    password = (EditText) findViewById(R.id.passwd);

    loginButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            sqlThread.start(); //The loginIntent is called inside the thread using a handler
        }
    });

}

public void loginIntent(){

    try{
        sharedPreferences = getSharedPreferences(MySession, Context.MODE_PRIVATE);

        SharedPreferences.Editor editor = sharedPreferences.edit();

        editor.putString(nameField, userRes);
        editor.putString(passwordField, passwdRes);
        editor.apply();
        //editor.commit();

    }catch (Exception ex){
        ex.printStackTrace();
    }

    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
    startActivity(intent);

}
</code>```

Here's my Main Activity:

```<code>SharedPreferences sharedPreferences;
private String name;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    submitButton = (Button) findViewById(R.id.submitButton);

    mMapView = (MapView) findViewById(mapView);
    map = new ArcGISMap(Basemap.Type.TOPOGRAPHIC, 34.056295, -117.195800, 16);
    mMapView.setMap(map);

    sharedPreferences = getSharedPreferences(LoginActivity.MySession, Context.MODE_PRIVATE);

    name = (String) sharedPreferences.getString(LoginActivity.nameField,"");

    Toast.makeText(MainActivity.this,name,Toast.LENGTH_LONG).show();
}
</code>```

The Toast output is empty.

答:
Try editor.commit().

editor.apply() is asynchronous. and your LoginActivity jumps directly to the Main Activity and requests the stored info. It might be that the MainActivity is requesting the strings before they are committed to the storage.

Body:
I'm currently working on an android app where I want to add a login/logout system using JDBC for the SQL and SharedPreferences to handle the sessions, the SQL works perfectly but when i go from the login activity to the main activity and try to get the values in the sharedpreferences it returns the default values.

Here is my Login Activity:

private TextView usernameHeader, passwordHeader;
private EditText username, password;
private Button loginButton;
private Handler alertHandler;
private String userRes, passwdRes;
SharedPreferences sharedPreferences;
public static final String MySession = "MySession";
public static final String nameField = "nameKey";
public static final String passwordField = "passwordKey";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    loginButton = (Button) findViewById(R.id.loginButton);

    username = (EditText) findViewById(R.id.username);
    password = (EditText) findViewById(R.id.passwd);

    loginButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            sqlThread.start(); //The loginIntent is called inside the thread using a handler
        }
    });

}

public void loginIntent(){

    try{
        sharedPreferences = getSharedPreferences(MySession, Context.MODE_PRIVATE);

        SharedPreferences.Editor editor = sharedPreferences.edit();

        editor.putString(nameField, userRes);
        editor.putString(passwordField, passwdRes);
        editor.apply();
        //editor.commit();

    }catch (Exception ex){
        ex.printStackTrace();
    }

    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
    startActivity(intent);

}

Here's my Main Activity:

SharedPreferences sharedPreferences;
private String name;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    submitButton = (Button) findViewById(R.id.submitButton);

    mMapView = (MapView) findViewById(mapView);
    map = new ArcGISMap(Basemap.Type.TOPOGRAPHIC, 34.056295, -117.195800, 16);
    mMapView.setMap(map);

    sharedPreferences = getSharedPreferences(LoginActivity.MySession, Context.MODE_PRIVATE);

    name = (String) sharedPreferences.getString(LoginActivity.nameField,"");

    Toast.makeText(MainActivity.this,name,Toast.LENGTH_LONG).show();
}

The Toast output is empty.


问:
Extracting Value of Key in Atom by Converting String to Symbol
I have an atom:

```<code>{:answer1 "yes", :answer2 "no", :answer3 "maybe"}
</code>```

And I want to be able to use the variable x to extract the value of :answerx.

In my REPL, when I test out how to append to a string and then convert to symbol, this works:

```<code>(symbol (str ":answer" 2))
</code>```

Result is :answer2. However, when I attempt to do this within the atom, I get a result of nil:

```<code>(get @answers-atom (symbol (str ":answer" 2)))
</code>```

Any idea why this might be happening?

答:
It seems that you're mixing up symbols and keywords. For instance, in the map that you give at the beginning of your question, :answer1, :answer2, and :answer3 are keywords, but (symbol (str ":answer" 2)) is a symbol. To get a keyword, you need to instead use the keyword function:

```<code>(def m {:answer1 "yes" :answer2 "no" :answer3 "maybe"})

(get m (symbol (str ":answer" 2))) ;=> nil

(get m (keyword (str "answer" 2))) ;=> "no"
</code>```

Body:
I have an atom:

{:answer1 "yes", :answer2 "no", :answer3 "maybe"}

And I want to be able to use the variable x to extract the value of :answerx.

In my REPL, when I test out how to append to a string and then convert to symbol, this works:

(symbol (str ":answer" 2))

Result is :answer2. However, when I attempt to do this within the atom, I get a result of nil:

(get @answers-atom (symbol (str ":answer" 2)))

Any idea why this might be happening?

Body:
It seems that you're mixing up symbols and keywords. For instance, in the map that you give at the beginning of your question, :answer1, :answer2, and :answer3 are keywords, but (symbol (str ":answer" 2)) is a symbol. To get a keyword, you need to instead use the keyword function:

(def m {:answer1 "yes" :answer2 "no" :answer3 "maybe"})

(get m (symbol (str ":answer" 2))) ;=> nil

(get m (keyword (str "answer" 2))) ;=> "no"


问:
Keras plot after model is finished explanaition
It is not really a programming question, I apologise for that. I have trained my network and generated these graphs.
http://imgur.com/a/zOglL
http://imgur.com/a/90JKl

I am struggling to find an answer to what do Accuracy vs Val_Accuracy and Loss vs Val_loss really represent. I do understand that if val_loss starts to jump high it means that there is over fitting going on and network just starts to memorise the data rather then learning. Could anyone explain in a bit more detail what they all mean?

答: During a neural network training - you usually provide two sets of data - a train one and validation one. Your training algorithm is taking data from a train set - and using a calculus and backpropagation it's trying to decrease a cost function which somehow represents how good your representation is (smaller the better). Aside of this - a cost is computed for a validation set which is not seen by a training algorithm - so one may check if model doesn't overfit on a train data provided (this happens if train loss is substancially smaller than validation loss). Despite loss different metrics might be computed - one of them might be e.g. accuracy. Sometimes they give you better insights into how your model works because loss might be hard to understand. Metrics give you better understanding on if your model works good.


答:
```<code>ENTRYPOINT [ "npm run watch" ]
</code>```

This is an incorrect json syntax, it's looking for the executable npm run watch, not the executable npm with parameters run and watch:

With the json syntax you need to separate each argument. You can use the shell syntax:

```<code>ENTRYPOINT npm run watch
</code>```

Or you can update the json syntax like (assuming npm is installed in /usr/bin):

```<code>ENTRYPOINT [ "/usr/bin/npm", "run", "watch" ]
</code>```

You also have an incorrect volume definition:

```<code>VOLUME ./:/usr/src/app
</code>```

Dockerfiles cannot specify the how the volume is mounted to the host, only that an anonymous volume is defined at a specific directory location. With a syntax like:

```<code>VOLUME /usr/src/app
</code>```

I've got strong opinions against using a volume definition inside of the Dockerfile described in this blog post. In short, you can define the volume better in a docker-compose.yml, all you can do with a Dockerfile is create anonymous volumes that you'd need to still redefine elsewhere if you want to be able to easily reuse them later.

Title: Docker: ENTRYPOINT can't execute command because it doesn't find the file

Body:
ENTRYPOINT [ "npm run watch" ]

This is an incorrect json syntax, it's looking for the executable npm run watch, not the executable npm with parameters run and watch:

With the json syntax you need to separate each argument. You can use the shell syntax:

ENTRYPOINT npm run watch

Or you can update the json syntax like (assuming npm is installed in /usr/bin):

ENTRYPOINT [ "/usr/bin/npm", "run", "watch" ]

You also have an incorrect volume definition:

VOLUME ./:/usr/src/app

Dockerfiles cannot specify the how the volume is mounted to the host, only that an anonymous volume is defined at a specific directory location. With a syntax like:

VOLUME /usr/src/app

I've got strong opinions against using a volume definition inside of the Dockerfile described in this blog post. In short, you can define the volume better in a docker-compose.yml, all you can do with a Dockerfile is create anonymous volumes that you'd need to still redefine elsewhere if you want to be able to easily reuse them later.


问:
Implementing Cache in azure service fabrics
In my previous projects which are monolithic apps we used Redis as distributed cache.

In azure service fabrics we have concept called statefull services is this concept similar to distributed cache like redis or different. Can we create statefull service and use it as cache layer. Can any one guide if i am wrong?

答: It only makes sense to use reliable collections within the service boundaries because the read/write operations are local IO. It's replicated between service instances so that involves some network traffic between the nodes but it's minimal.  If you are trying to make a stateful service for the only sole purpose of caching data for external services it sort of goes against the best principles and should be similar to Redis in terms of performance (I didn't actually compare the numbers).</p>


问:
Responsive Menu hides inside the ads
my responsive menu is in side the adsense code here is the css of menu. I have an responsive website www.idealbanker.in but while clicking menu it goes in side the adsense ads kindly guide me to resolve it.

my responsive menu is in side the adsense code here is the css of menu. I have an responsive website www.idealbanker.in but while clicking menu it goes in side the adsense ads kindly guide me to resolve it.my responsive menu is in side the adsense code here is the css of menu. I have an responsive website www.idealbanker.in but while clicking menu it goes in side the adsense ads kindly guide me to resolve it.
enter image description here

```<code><style>
ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

li {
    float: left;
}

li a {
    display: inline-block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

li a:hover {
    background-color: #111;
}
ul.topnav {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

/* Float the list items side by side */
ul.topnav li {float: left;}

/* Style the links inside the list items */
ul.topnav li a {
    display: inline-block;
    color: #f2f2f2;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    transition: 0.3s;
    font-size: 17px;
}

/* Change background color of links on hover */
ul.topnav li a:hover {background-color: #555;}

/* Hide the list item that contains the link that should open and close the topnav on small screens */
ul.topnav li.icon {display: none;}
@media screen and (max-width:680px) {
  ul.topnav li:not(:first-child) {display: none;}
  ul.topnav li.icon {
    float: right;
    display: inline-block;
  }
}

/* The "responsive" class is added to the topnav with JavaScript when the user clicks on the icon. This class makes the topnav look good on small screens */
@media screen and (max-width:680px) {
  ul.topnav.responsive {position: relative;}
  ul.topnav.responsive li.icon {
    position: absolute;
    right: 0;
    top: 0;
  }
  ul.topnav.responsive li {
    float: none;
    display: inline;
  }
  ul.topnav.responsive li a {
    display: block;
    text-align: left;
  }
}

</style>
<script type="text/javascript">
function myFunction() {
    var x = document.getElementById("myTopnav");
    if (x.className === "topnav") {
        x.className += " responsive";
    } else {
        x.className = "topnav";
    }
}
</script>
</script>
</code>```

答:
Solution

```<code>ul.topnav.responsive {
    position:relative;
    z-index: 10;
}
</code>```

Add z-index property to specify the stack order.

Title: Responsive Menu hides inside the ads

Body:
my responsive menu is in side the adsense code here is the css of menu. I have an responsive website www.idealbanker.in but while clicking menu it goes in side the adsense ads kindly guide me to resolve it.

my responsive menu is in side the adsense code here is the css of menu. I have an responsive website www.idealbanker.in but while clicking menu it goes in side the adsense ads kindly guide me to resolve it.my responsive menu is in side the adsense code here is the css of menu. I have an responsive website www.idealbanker.in but while clicking menu it goes in side the adsense ads kindly guide me to resolve it.
enter image description here

</script>

Body:
Solution

ul.topnav.responsive {
    position:relative;
    z-index: 10;
}

Add z-index property to specify the stack order.


问:
boost::shared_array<char> to std::string
What is the best way to convert a boost::shared_array<char> to a std::string?
The following snippet works but it does not look very elegant.

```<code>boost::shared_array<char> boostString = DatabaseFileName.GetCString(CZString::eAscii);
std::string stdString;
for(size_t i = 0; boostString[i] != 0; i++)
{
    stdString.append(1, boostString[i]);
}
</code>```

答:
If you don't want to futz around with strncpy and worrying of the boost::shared_array<char> is null-terminated, you can write (assuming boostString and stdString from the original example:

```<code>std::copy(boostString.begin(), boostString.end(),
    std::back_inserter<std::string>(stdString));
</code>```

Body:
What is the best way to convert a boost::shared_array<char> to a std::string?
The following snippet works but it does not look very elegant.

boost::shared_array<char> boostString = DatabaseFileName.GetCString(CZString::eAscii);
std::string stdString;
for(size_t i = 0; boostString[i] != 0; i++)
{
    stdString.append(1, boostString[i]);
}

Body:
If you don't want to futz around with strncpy and worrying of the boost::shared_array<char> is null-terminated, you can write (assuming boostString and stdString from the original example:

std::copy(boostString.begin(), boostString.end(),
    std::back_inserter<std::string>(stdString));


问:
Angular 2 Deployment Issue
I have deployed my angular 2 Cli project in Amazon Ec2.
But I can't able run this. How can i run this project. When i am giving ng-serve command it builds and its displayed http://localhost:4200. How can i set default port and how can i run.

In local i have did ng-serve then i run it in my browser like "localhost:4200" it works. But in production, i don't know how to run.

Please give any solution.

答:
ng-serve runs a local node server, you should never use that node server in production. it's a development server only.

run ng build --prod copy the generated bundles and files from /dist into your production environment. In file system that is the directory that your server is serving.

for AWS instructions for static website take a look at http://docs.aws.amazon.com/gettingstarted/latest/swh/website-hosting-intro.html

Title: Angular 2 Deployment Issue


问:
how to merge database same row as one with addition of value
This is my database :

```<code>owner_id    qty    status
   1         20      in
   1         30      out
   3         10      in
</code>```

This is my php code to get all fields in yii :

```<code>if(isset($_POST['id']))
{$sp = Inventory::model()->findAll(array("condition"=>"product_id=".$_POST['id']));}
</code>```

It's give me result as database
in I need to merge owner_id 1 with addition in qty

need result like if i pass id 1 then result like

```<code>owner_id  qty  status
 1        50   {'in',out'}
</code>```

答:
you could use group_concat and group by  </p>

```<code> select  owner_id, sum(qty), concat('{', group_concat(status), '}')
 from my_table
 group by onwer_id
 where  owner_id =1
</code>```

Body:
This is my database :

owner_id    qty    status
   1         20      in
   1         30      out
   3         10      in

This is my php code to get all fields in yii :

if(isset($_POST['id']))
{$sp = Inventory::model()->findAll(array("condition"=>"product_id=".$_POST['id']));}

It's give me result as database
in I need to merge owner_id 1 with addition in qty

need result like if i pass id 1 then result like

owner_id  qty  status
 1        50   {'in',out'}

Body:
you could use group_concat and group by

 select  owner_id, sum(qty), concat('{', group_concat(status), '}')
 from my_table
 group by onwer_id
 where  owner_id =1


问:
What does bitwise-anding a byte with 0b1111_1111 do?
I have the following method:

```<code>int convert3ByteChunkTo24Bits(final byte[] bytes) {
    int bitsFor3ByteChunk = 0;

    bitsFor3ByteChunk = bitsFor3ByteChunk | (bytes[0] & 0b11111111);

    bitsFor3ByteChunk = bitsFor3ByteChunk << 8;
    bitsFor3ByteChunk = bitsFor3ByteChunk | (bytes[1] & 0b11111111);

    bitsFor3ByteChunk = bitsFor3ByteChunk << 8;
    bitsFor3ByteChunk = bitsFor3ByteChunk | (bytes[2] & 0b11111111);

    return bitsFor3ByteChunk & 0b00000000_11111111_11111111_11111111;
}
</code>```

Purpose of the method is to append bytes passed and return it in an int format. Here is a test method I have:

```<code>void testConvert3ByteChunkTo24Bits() {
    final byte ca = (byte) 0xCA;
    final byte fe = (byte) 0xFE;
    final byte ba = (byte) 0xBA;

    final byte[] man = {ca, fe, ba};
    final int bytesIn24Bits = base64EncoderHelper.convert3ByteChunkTo24Bits(man);

    System.out.println(bytesIn24Bits);
}
</code>```

Output of the result will be:

```<code>13303482
</code>```

which in binary is:

```<code>00000000110010101111111010111010
</code>```

This is correct and is the intended results since:

```<code>0xCA = 11001010
0xFE = 11111110
0xBA = 10111010
</code>```

So, so far so good. There is just one thing I do not understand, why do I need the logical ands as in

```<code>(bytes[0] & 0b11111111)
</code>```

When I do not do the bitwise-and operations, so if the implementation is as follows:

```<code>int convert3ByteChunkTo24Bits(final byte[] bytes) {
    int bitsFor3ByteChunk = 0;

    bitsFor3ByteChunk = bitsFor3ByteChunk | (bytes[0]);

    bitsFor3ByteChunk = bitsFor3ByteChunk << 8;
    bitsFor3ByteChunk = bitsFor3ByteChunk | (bytes[1]);

    bitsFor3ByteChunk = bitsFor3ByteChunk << 8;
    bitsFor3ByteChunk = bitsFor3ByteChunk | (bytes[2]);

    return bitsFor3ByteChunk & 0b00000000_11111111_11111111_11111111;
}
</code>```

result will be:

```<code>00000000111111111111111110111010
</code>```

What am I missing? What does

```<code>bytes[0] & 0b11111111
</code>```

fix here? (I found it kind of by trial - error and still curious why it works..)

答:
It handles signed bytes.

say byte[0] has a value of 0b10000000. That's looks like 128 to you and me, but to Java it looks like -128, due to two's complement arithmatic. When you use that value in a calculation with an int, it'll be sign-extended to an int with a value of 11111111111111111111111110000000, which is an int with a value of -128

To avoid the problem, this code performs a bitwise and with 0b11111111. This is an integer operation, so the byte is implicitly cast to the int 11111111111111111111111110000000, but the and turns it into 00000000000000000000000010000000, which is the desired 128.

This is a hack for the notorious Java problem of not having unsigned types.

Body:
I have the following method:

int convert3ByteChunkTo24Bits(final byte[] bytes) {
    int bitsFor3ByteChunk = 0;

    bitsFor3ByteChunk = bitsFor3ByteChunk | (bytes[0] & 0b11111111);

    bitsFor3ByteChunk = bitsFor3ByteChunk << 8;
    bitsFor3ByteChunk = bitsFor3ByteChunk | (bytes[1] & 0b11111111);

    bitsFor3ByteChunk = bitsFor3ByteChunk << 8;
    bitsFor3ByteChunk = bitsFor3ByteChunk | (bytes[2] & 0b11111111);

    return bitsFor3ByteChunk & 0b00000000_11111111_11111111_11111111;
}

Purpose of the method is to append bytes passed and return it in an int format. Here is a test method I have:

void testConvert3ByteChunkTo24Bits() {
    final byte ca = (byte) 0xCA;
    final byte fe = (byte) 0xFE;
    final byte ba = (byte) 0xBA;

    final byte[] man = {ca, fe, ba};
    final int bytesIn24Bits = base64EncoderHelper.convert3ByteChunkTo24Bits(man);

    System.out.println(bytesIn24Bits);
}

Output of the result will be:

13303482

which in binary is:

00000000110010101111111010111010

This is correct and is the intended results since:

0xCA = 11001010
0xFE = 11111110
0xBA = 10111010

So, so far so good. There is just one thing I do not understand, why do I need the logical ands as in

(bytes[0] & 0b11111111)

When I do not do the bitwise-and operations, so if the implementation is as follows:

int convert3ByteChunkTo24Bits(final byte[] bytes) {
    int bitsFor3ByteChunk = 0;

    bitsFor3ByteChunk = bitsFor3ByteChunk | (bytes[0]);

    bitsFor3ByteChunk = bitsFor3ByteChunk << 8;
    bitsFor3ByteChunk = bitsFor3ByteChunk | (bytes[1]);

    bitsFor3ByteChunk = bitsFor3ByteChunk << 8;
    bitsFor3ByteChunk = bitsFor3ByteChunk | (bytes[2]);

    return bitsFor3ByteChunk & 0b00000000_11111111_11111111_11111111;
}

result will be:

00000000111111111111111110111010

What am I missing? What does

bytes[0] & 0b11111111

fix here? (I found it kind of by trial - error and still curious why it works..)


问:
How to write console.log wrapper for Angular2 in Typescript?
Is there a way to write a global selfmade mylogger function that I could use in Angular2 typescript project for my services or components instead of console.log function ?

My desired result would be something like this:

mylogger.ts

```<code>function mylogger(msg){
    console.log(msg);
};
</code>```

user.service.ts

```<code>import 'commons/mylogger';
export class UserService{
  loadUserData(){
    mylogger('About to get something');
    return 'something';
  };
};
</code>```

答:
There is now an angular2 logger component on NPM which supports log levels.
https://www.npmjs.com/package/angular2-logger</p>

ContentLicense: CC BY-SA 4.0

Body:
Is there a way to write a global selfmade mylogger function that I could use in Angular2 typescript project for my services or components instead of console.log function ?

My desired result would be something like this:

mylogger.ts

function mylogger(msg){
    console.log(msg);
};

user.service.ts

import 'commons/mylogger';
export class UserService{
  loadUserData(){
    mylogger('About to get something');
    return 'something';
  };
};


答:
In:

```<code>bitsFor3ByteChunk = bitsFor3ByteChunk | (bytes[0] & 0b11111111);
</code>```

bytes[0] is first extended to int value (integers are all represented in two's-complement). Then for a value like 0xFF stored in a byte, the corresponding int value will be 0xFFFFFFFF. It is then masked to retain the lower 8 bits.

Title: What does bitwise-anding a byte with 0b1111_1111 do?

Body:
In:

bitsFor3ByteChunk = bitsFor3ByteChunk | (bytes[0] & 0b11111111);

bytes[0] is first extended to int value (integers are all represented in two's-complement). Then for a value like 0xFF stored in a byte, the corresponding int value will be 0xFFFFFFFF. It is then masked to retain the lower 8 bits.


问:
Tranistioning back end of Access database to ODBC in order to fix slowness
I've inherited the task of maintaining a massive Access database stored on a network drive. Users complain that the database is extremely slow. I'm hoping to fix this.

Here is some background:

From a development standpoint, the structure is messy. VBA is littered with unused procedures and modules. It seems that over the years developers have haphazardly slapped on additional features at the request of management. The whole thing is actually composed of a front end Access database and several Access databases that act as the back end where tables are stored. To use the database users open a separate Access database with an autoexecute that copies the front end to the user's local drive and opens the copy. The other developer claims that Access isn't well suited to handle the tasks we are asking it to do. While I agree, I also believe we can do a lot to improve what we got.

Now on to my questions:

Can I make this database significantly faster by consolidating the back end tables into an ODBC database? Does this ODBC database need its own server or can I use the existing share drive this database is currently stored in? How do I create an ODBC database?

I do not have much experience with databases beyond Access and SQL. I do have MS SQL Server Management Studio and TOAD but I've only used them for Querying existing ODBC databases. Any resources I should take a look at?

答:
Well, technically ODBC database is not an actual thing. Most commercial databases have ODBC drivers, including Access (which would also make it an ODBC database). What you can relatively easily convert Access back-ends to is SQL Server. There is even a (relatively flawed and a pain to set up but functional) migration wizard for that.

Depending on the database you may or may not see much of an improvement but, depending on your database skills, there is huge potential for improvement.

SQL server has a free version and can be hosted on any Windows computer, but having a dedicated server (or at least a server, even if it is not dedicated) has serious advantages.

Most of the above also applies to other database systems you could use like MySQL (also free but I am not aware of a migration tool).


问:
Make empty div of one line height
Is it possible to create a rule that will make the following HTML:

```<code><div style="width: 100%"></div>
</code>```

of one line height using just CSS, or do I need to put   as the content?

答:
The solution with visibility: hidden; is clever. It is simpler to set the content to Unicode character feff, which is the byte order mark. This has no width but has height; it behaves the same on every browser all the way back to IE6.

```<code>.your-selector:empty::before {
    content: '\feff';
}
</code>```

I have found that WebKit (at least on Mac OS) applies slightly different (1px) line height to bold text than normal text for some fonts. To enforce uniformity (in this case, we would need to apply even to non-empty selectors):

```<code>.your-selector::before {
    content: '\feff';
    font-weight: 900;
}
</code>```

Title: Make empty div of one line height

Body:
Is it possible to create a rule that will make the following HTML:

of one line height using just CSS, or do I need to put   as the content?

Body:
The solution with visibility: hidden; is clever. It is simpler to set the content to Unicode character feff, which is the byte order mark. This has no width but has height; it behaves the same on every browser all the way back to IE6.

.your-selector:empty::before {
    content: '\feff';
}

I have found that WebKit (at least on Mac OS) applies slightly different (1px) line height to bold text than normal text for some fonts. To enforce uniformity (in this case, we would need to apply even to non-empty selectors):

.your-selector::before {
    content: '\feff';
    font-weight: 900;
}


问:
00904. 00000 - "%s: invalid identifier"
Going crazy with this code.  Can Anybody put me on the right track?  I am using SQL Develope 3.1.07.  Thanks.

```<code>SELECT
    PHA.PO_HEADER_ID,
    PRLA.ATTRIBUTE1 As "REQUISITION_NUMBER",
    PHA.SEGMENT1 As PO_NUMBER,
    DECODE (nvl(REG.DOCUMENT_TYPE, '-'),
        'APW', 'Agreement for Performance of Work',
        'APWEMER', 'Agreement for Performance of Work - Emergency',
        'CONS', 'Consultant',
        'CONCEMER', 'Consultant - Emergency',
        'DFC', 'Direct Financial Contribution',
        'FELLOW', 'Fellowship',
        'GENEXT', 'General External Services',
        'IMPRESTCC', 'Imprest/Credit Card',
        'IS', 'Internal Services',
        'LOA', 'Letter of Agreement',
        'TSA', 'Technical Service Agreement') as DOCUMENT_TYPE,
   HAOU.NAME As BUDGET_CENTRE,
   PHA.CREATION_DATE As PO_CREATION_DATE,
   PHA.AUTHORIZATION_STATUS,
   PHA.APPROVED_DATE,
   PHA.COMMENTS,
   PHA.CLOSED_DATE,
   PHA.CLOSED_CODE,
   PDA.PO_DISTRIBUTION_ID,
   AIDA.INVOICE_ID,
   AIA.INVOICE_TYPE_LOOKUP_CODE AS INVOICE_TYPE,
   AIA.REMIT_TO_SUPPLIER_NAME AS SUPPLIER_NAME,
   AIA.REMIT_TO_SUPPLIER_ID AS SUPPLIER_ID,
   AIA.INVOICE_DATE, AIA.INVOICE_NUM,
   AIA.INVOICE_AMOUNT,
   AIA.INVOICE_CURRENCY_CODE AS INVOICE_CURRENCY,
   AIA.GL_DATE,
   AIA.PAYMENT_CURRENCY_CODE AS PAYMENT_CURRENCY,
   AIA.PAYMENT_CROSS_RATE_DATE AS PAYMENT_DATE,
   AIA.DESCRIPTION, AIA.EXCHANGE_DATE,
   AIA.EXCHANGE_RATE,
   AIA.BASE_AMOUNT AS FUNCTIONAL_CURRENCY_AMOUNT
FROM
   po_headers_all pha,
   po_distributions_all pda,
   ap_invoice_distributions_all aida,
   ap_invoices_all aia,
   po_requisition_lines_all prla,
   po_req_distributions_all prda,
   hr.hr_all_organization_units haou,
   pa.pa_projects_all ppa
LEFT JOIN
   xxwrp.xxwrp_service_reg_all reg
ON
   reg.po_header_id = pha.po_header_id
WHERE
   1=1
   AND pha.segment1 = '201251390'
   AND pda.req_distribution_id = prda.distribution_id
   AND prda.requisition_line_id = prla.requisition_line_id
   AND pha.po_header_id = pda.po_header_id
   AND pda.po_distribution_id = aida.po_distribution_id
   AND aida.invoice_id = aia.invoice_id
   AND pda.project_id = ppa.project_id
   AND haou.organization_id=ppa.carrying_out_organization_id
   AND pha.creation_date > aia.invoice_date
GROUP BY
   PHA.PO_HEADER_ID, PRLA.ATTRIBUTE1, PHA.SEGMENT1, REG.DOCUMENT_TYPE, HAOU.NAME, PHA.CREATION_DATE, PHA.AUTHORIZATION_STATUS, PHA.APPROVED_DATE, PHA.COMMENTS, PHA.CLOSED_DATE, PHA.CLOSED_CODE, PDA.PO_DISTRIBUTION_ID, AIDA.INVOICE_ID, AIA.INVOICE_TYPE_LOOKUP_CODE, AIA.REMIT_TO_SUPPLIER_NAME, AIA.REMIT_TO_SUPPLIER_ID, AIA.INVOICE_DATE, AIA.INVOICE_NUM, AIA.INVOICE_AMOUNT, AIA.INVOICE_CURRENCY_CODE, AIA.GL_DATE, AIA.PAYMENT_CURRENCY_CODE, AIA.PAYMENT_CROSS_RATE_DATE, AIA.DESCRIPTION, AIA.EXCHANGE_DATE, AIA.EXCHANGE_RATE, AIA.BASE_AMOUNT
</code>```

When I run it, it returns this error:

ORA-00904: "PHA"."PO_HEADER_ID": invalid identifier
  00904. 00000 -  "%s: invalid identifier"
  *Cause:

  *Action:
  Error at Line: 50 Column: 21

答:
The issue is in mixing the old Oracle syntax with the ANSI join syntax; for example, say you have these tables:

```<code>create table t1(n1 number);
create table t2(n2 number);
create table t3(n3 number);
</code>```

this is what you get:

```<code>SQL> select *
  2  from t1,t2
  3    left join t3 on t3.n3 = t1.n1
  4  where t1.n1 = t2.n2;
  left join t3 on t3.n3 = t1.n1
                          *
ERROR at line 3:
ORA-00904: "T1"."N1": invalid identifier

SQL> select *
  2  from t1
  3    inner join t2 on t1.n1 = t2.n2
  4    left join t3 on t3.n3 = t1.n1;

no rows selected
</code>```

Title: 00904. 00000 - "%s: invalid identifier"

Body:
Going crazy with this code.  Can Anybody put me on the right track?  I am using SQL Develope 3.1.07.  Thanks.

SELECT
    PHA.PO_HEADER_ID,
    PRLA.ATTRIBUTE1 As "REQUISITION_NUMBER",
    PHA.SEGMENT1 As PO_NUMBER,
    DECODE (nvl(REG.DOCUMENT_TYPE, '-'),
        'APW', 'Agreement for Performance of Work',
        'APWEMER', 'Agreement for Performance of Work - Emergency',
        'CONS', 'Consultant',
        'CONCEMER', 'Consultant - Emergency',
        'DFC', 'Direct Financial Contribution',
        'FELLOW', 'Fellowship',
        'GENEXT', 'General External Services',
        'IMPRESTCC', 'Imprest/Credit Card',
        'IS', 'Internal Services',
        'LOA', 'Letter of Agreement',
        'TSA', 'Technical Service Agreement') as DOCUMENT_TYPE,
   HAOU.NAME As BUDGET_CENTRE,
   PHA.CREATION_DATE As PO_CREATION_DATE,
   PHA.AUTHORIZATION_STATUS,
   PHA.APPROVED_DATE,
   PHA.COMMENTS,
   PHA.CLOSED_DATE,
   PHA.CLOSED_CODE,
   PDA.PO_DISTRIBUTION_ID,
   AIDA.INVOICE_ID,
   AIA.INVOICE_TYPE_LOOKUP_CODE AS INVOICE_TYPE,
   AIA.REMIT_TO_SUPPLIER_NAME AS SUPPLIER_NAME,
   AIA.REMIT_TO_SUPPLIER_ID AS SUPPLIER_ID,
   AIA.INVOICE_DATE, AIA.INVOICE_NUM,
   AIA.INVOICE_AMOUNT,
   AIA.INVOICE_CURRENCY_CODE AS INVOICE_CURRENCY,
   AIA.GL_DATE,
   AIA.PAYMENT_CURRENCY_CODE AS PAYMENT_CURRENCY,
   AIA.PAYMENT_CROSS_RATE_DATE AS PAYMENT_DATE,
   AIA.DESCRIPTION, AIA.EXCHANGE_DATE,
   AIA.EXCHANGE_RATE,
   AIA.BASE_AMOUNT AS FUNCTIONAL_CURRENCY_AMOUNT
FROM
   po_headers_all pha,
   po_distributions_all pda,
   ap_invoice_distributions_all aida,
   ap_invoices_all aia,
   po_requisition_lines_all prla,
   po_req_distributions_all prda,
   hr.hr_all_organization_units haou,
   pa.pa_projects_all ppa
LEFT JOIN
   xxwrp.xxwrp_service_reg_all reg
ON
   reg.po_header_id = pha.po_header_id
WHERE
   1=1
   AND pha.segment1 = '201251390'
   AND pda.req_distribution_id = prda.distribution_id
   AND prda.requisition_line_id = prla.requisition_line_id
   AND pha.po_header_id = pda.po_header_id
   AND pda.po_distribution_id = aida.po_distribution_id
   AND aida.invoice_id = aia.invoice_id
   AND pda.project_id = ppa.project_id
   AND haou.organization_id=ppa.carrying_out_organization_id
   AND pha.creation_date > aia.invoice_date
GROUP BY
   PHA.PO_HEADER_ID, PRLA.ATTRIBUTE1, PHA.SEGMENT1, REG.DOCUMENT_TYPE, HAOU.NAME, PHA.CREATION_DATE, PHA.AUTHORIZATION_STATUS, PHA.APPROVED_DATE, PHA.COMMENTS, PHA.CLOSED_DATE, PHA.CLOSED_CODE, PDA.PO_DISTRIBUTION_ID, AIDA.INVOICE_ID, AIA.INVOICE_TYPE_LOOKUP_CODE, AIA.REMIT_TO_SUPPLIER_NAME, AIA.REMIT_TO_SUPPLIER_ID, AIA.INVOICE_DATE, AIA.INVOICE_NUM, AIA.INVOICE_AMOUNT, AIA.INVOICE_CURRENCY_CODE, AIA.GL_DATE, AIA.PAYMENT_CURRENCY_CODE, AIA.PAYMENT_CROSS_RATE_DATE, AIA.DESCRIPTION, AIA.EXCHANGE_DATE, AIA.EXCHANGE_RATE, AIA.BASE_AMOUNT

When I run it, it returns this error:

ORA-00904: "PHA"."PO_HEADER_ID": invalid identifier
  00904. 00000 -  "%s: invalid identifier"
  *Cause:

  *Action:
  Error at Line: 50 Column: 21

Body:
The issue is in mixing the old Oracle syntax with the ANSI join syntax; for example, say you have these tables:

create table t1(n1 number);
create table t2(n2 number);
create table t3(n3 number);

this is what you get:

SQL> select *
  2  from t1,t2
  3    left join t3 on t3.n3 = t1.n1
  4  where t1.n1 = t2.n2;
  left join t3 on t3.n3 = t1.n1
                          *
ERROR at line 3:
ORA-00904: "T1"."N1": invalid identifier

SQL> select *
  2  from t1
  3    inner join t2 on t1.n1 = t2.n2
  4    left join t3 on t3.n3 = t1.n1;

no rows selected


问:
Dynamic object allocation using array of dynamic pointers - what delete to use?
Can someone help me understand these examples?

I think following code generates an array of 10 pointers that are using automatic memory allocation. Since we are using dynamic memory allocation for objects, pointers to the objects in array are lost when array goes out of scope, but objects remain in the memory until delete is called.

```<code>MyClass* c[10];
c[0] = new MyClass();
</code>```

I guess the following example generates array of ten objects that are using dynamic memory allocation. We have to use delete[] to delete array and objects.

```<code>MyClass* d = new MyClass[10];
</code>```

I guess in the following example we are allocating an array of 50 pointers to object. Do we have to call delete[] or delete or both here?

```<code>MyClass** b = new MyClass*[50];
b[0] = new MyClass();
</code>```

I know that there are better things I could use to manage memory allocation, but I am forced to use new and delete. Can someone check if my understanding is correct and explain what delete I have to use in third example?

Thanks.

答:
I think following code generates an array of 10 pointers that are
  using automatic memory allocation. Since we are using dynamic memory
  allocation for objects, pointers to the objects in array are lost when
  array goes out of scope, but objects remain in the memory until delete
  is called.

```<code>MyClass* c[10];
c[0] = new MyClass();
</code>```

Correct. When the array goes out of scope, the allocated MyClass instance will stay alive, but you have missed your chance to deallocate the memory until the process ends (in which case the OS will free the memory).

I guess the following example generates array of ten objects that are
  using dynamic memory allocation. We have to use delete[] to delete
  array and objects.

```<code>MyClass* d = new MyClass[10];
</code>```

Correct.

I guess in the following example we are allocating an array of 50
  pointers to object. Do we have to call delete[] or delete or both
  here?

```<code>MyClass** b = new MyClass*[50];
b[0] = new MyClass();
</code>```

First statement is correct, an array of 50 pointers to MyClass is allocated. Then a single instance of MyClass is allocated and its address is assigned to the first element of that array.

You have to call delete for each individually allocated element of the array first. After that, you have to call delete on the dynamically allocated array:

```<code>delete b[0];
delete[] b;
</code>```

Body:
Can someone help me understand these examples?

I think following code generates an array of 10 pointers that are using automatic memory allocation. Since we are using dynamic memory allocation for objects, pointers to the objects in array are lost when array goes out of scope, but objects remain in the memory until delete is called.

MyClass* c[10];
c[0] = new MyClass();

I guess the following example generates array of ten objects that are using dynamic memory allocation. We have to use delete[] to delete array and objects.

MyClass* d = new MyClass[10];

I guess in the following example we are allocating an array of 50 pointers to object. Do we have to call delete[] or delete or both here?

MyClass** b = new MyClass*[50];
b[0] = new MyClass();

I know that there are better things I could use to manage memory allocation, but I am forced to use new and delete. Can someone check if my understanding is correct and explain what delete I have to use in third example?

Thanks.

Body:
I think following code generates an array of 10 pointers that are
  using automatic memory allocation. Since we are using dynamic memory
  allocation for objects, pointers to the objects in array are lost when
  array goes out of scope, but objects remain in the memory until delete
  is called.

MyClass* c[10];
c[0] = new MyClass();

Correct. When the array goes out of scope, the allocated MyClass instance will stay alive, but you have missed your chance to deallocate the memory until the process ends (in which case the OS will free the memory).

I guess the following example generates array of ten objects that are
  using dynamic memory allocation. We have to use delete[] to delete
  array and objects.

MyClass* d = new MyClass[10];

Correct.

I guess in the following example we are allocating an array of 50
  pointers to object. Do we have to call delete[] or delete or both
  here?

MyClass** b = new MyClass*[50];
b[0] = new MyClass();

First statement is correct, an array of 50 pointers to MyClass is allocated. Then a single instance of MyClass is allocated and its address is assigned to the first element of that array.

You have to call delete for each individually allocated element of the array first. After that, you have to call delete on the dynamically allocated array:

delete b[0];
delete[] b;