问:
Core Data using auto generated Primary Key PK
I have a simple Person entity in Core Data, I noticed that when adding data, each row is auto generated a unique PK called objectID

I wish to retrieve the records using the objectID but I am getting the following error:

Terminating app due to uncaught exception
  'NSInvalidArgumentException', reason: 'keypath objectID not found in
  entity < NSSQLEntity Person id=2 >'

```<code>func fetchPerson(withID personID: Int,
                 context: NSManagedObjectContext,
                 completion: @escaping ([Person]?) -> Void) {

    let fetchRequest: NSFetchRequest<Person> = Person.fetchRequest()

    let predicate = NSPredicate(format: "\(#keyPath(Person.objectID)) == \(personID)")
    fetchRequest.predicate = predicate

    //perform aynchronous operation:
    context.perform {
        do {
            let persons = try fetchRequest.execute()
            //success - return array of persons
            completion(persons)
        } catch {
            //error - return nil
            completion(nil)
        }

    }

}
</code>```

Calling the above :

```<code>//fetch person with specific id:
let personID: Int = 2
fetchPerson(withID: personID, context: persistentContainer.viewContext) { (persons: [Person]?) in
    if persons != nil {

        print("Fetching person with personID: \(personID)")
        for person in persons! {
            print("Person: \(person.objectID) - \(person.firstName!) \(person.lastName!)")
        }

    }
}
</code>```

答:
The objectID is a property of NSManagedObject but is not the name of a field in the persistent store or part of the entity description. You can't use it in predicates because it's not there to use as a filter. There is a field in the primary store that corresponds to the object ID, but it's also not available to fetch requests because that's not how Core Data is intended to be used.

If you want a primary key with Core Data, you need to create it yourself. Or if you really want SQL-style coding, use SQLite directly and don't get Core Data involved.

Body:
I have a simple Person entity in Core Data, I noticed that when adding data, each row is auto generated a unique PK called objectID

I wish to retrieve the records using the objectID but I am getting the following error:

Terminating app due to uncaught exception
  'NSInvalidArgumentException', reason: 'keypath objectID not found in
  entity < NSSQLEntity Person id=2 >'

func fetchPerson(withID personID: Int,
                 context: NSManagedObjectContext,
                 completion: @escaping ([Person]?) -> Void) {

    let fetchRequest: NSFetchRequest<Person> = Person.fetchRequest()

    let predicate = NSPredicate(format: "\(#keyPath(Person.objectID)) == \(personID)")
    fetchRequest.predicate = predicate

    //perform aynchronous operation:
    context.perform {
        do {
            let persons = try fetchRequest.execute()
            //success - return array of persons
            completion(persons)
        } catch {
            //error - return nil
            completion(nil)
        }

    }

}

Calling the above :

//fetch person with specific id:
let personID: Int = 2
fetchPerson(withID: personID, context: persistentContainer.viewContext) { (persons: [Person]?) in
    if persons != nil {

        print("Fetching person with personID: \(personID)")
        for person in persons! {
            print("Person: \(person.objectID) - \(person.firstName!) \(person.lastName!)")
        }

    }
}


来源: stackexchange

问:
Export Data-tier application error
I am trying to export a rather simple database using the Export Data-tier application and keep getting the following error:

One or more unsupported elements were found in the schema used as part of a data package.
Error SQL71564: The element Extended Property: [dbo].[DailyResult].[ScanTypeID].[MS_Description] is not supported when used as part of a data package (.bacpac file).

I have removed the description for the indicated column, but continue to receive this error. Any ideas?

答:
I had a database reference in the offending object.  Once i removed that it exported without an issue. I changed;
    [MyDatabase].[Work].[Job]
to
    [Work].[Job]

ContentLicense: CC BY-SA 3.0

Title: Export Data-tier application error


问:
Calculation of dimensions for a 3D bounding Box
EDIT: I am trying to calculate the dimensions of 3D bounding boxes using three vectors that contain elements representing the 3 coordinates of my box, namely Cluster_x, Cluster_y, and Cluster_z. The algorithm I am applying to find the values for the center is as below. I don't know where am I going wrong. </p>

```<code>            tFloat32 x_max = *std::max_element(Cluster_x.begin(), Cluster_x.end());
            tFloat32 x_min = *std::min_element(Cluster_x.begin(), Cluster_x.end());

            tFloat32 y_max = *std::max_element(Cluster_y.begin(), Cluster_y.end());
            tFloat32 y_min = *std::min_element(Cluster_y.begin(), Cluster_y.end());

            tFloat32 z_max = *std::max_element(Cluster_z.begin(), Cluster_z.end());
            tFloat32 z_min = *std::min_element(Cluster_z.begin(), Cluster_z.end());

                //Center//

            tFloat32 c_x = (x_max - x_min) / 2;
            tFloat32 c_y = (y_max - y_min) / 2;
            tFloat32 c_z = (z_max - z_min) / 2;

            cetuc::BoundingBox NewBox(cetuc::Point3D(c_x,c_y,c_z), cetuc::Point3D(8, 8, 10), cetuc::Point3D(0, 0, 0));
</code>```

答: To make std::max_element work you must provide either operator< overloading for your element type tFloat32 or predicate for comparison. And in your case, it is better to use std::minmax_element

Body:
EDIT: I am trying to calculate the dimensions of 3D bounding boxes using three vectors that contain elements representing the 3 coordinates of my box, namely Cluster_x, Cluster_y, and Cluster_z. The algorithm I am applying to find the values for the center is as below. I don't know where am I going wrong.

            tFloat32 x_max = *std::max_element(Cluster_x.begin(), Cluster_x.end());
            tFloat32 x_min = *std::min_element(Cluster_x.begin(), Cluster_x.end());

            tFloat32 y_max = *std::max_element(Cluster_y.begin(), Cluster_y.end());
            tFloat32 y_min = *std::min_element(Cluster_y.begin(), Cluster_y.end());

            tFloat32 z_max = *std::max_element(Cluster_z.begin(), Cluster_z.end());
            tFloat32 z_min = *std::min_element(Cluster_z.begin(), Cluster_z.end());

                //Center//

            tFloat32 c_x = (x_max - x_min) / 2;
            tFloat32 c_y = (y_max - y_min) / 2;
            tFloat32 c_z = (z_max - z_min) / 2;

            cetuc::BoundingBox NewBox(cetuc::Point3D(c_x,c_y,c_z), cetuc::Point3D(8, 8, 10), cetuc::Point3D(0, 0, 0));


问:
Sum of columns of a row from a list (without 'sum' function)
So I have this function here:

```<code>def row_sums(square):
    """Returns a list of the row sums in a magic square"""
    numbers = []
    for row in square:
        result = 0
        for col in row:
            result += col
        numbers.append(result)
    return numbers
</code>```

Which when a magic square like the following is entered, it will return the sum of the rows without using the in-built function "sum":

```<code>square = [
   [1, 2, 3, 4],
   [5, 6, 7, 8],
   [9, 10, 11, 12],
   [13, 14, 15, 16]
]
print(row_sums(square))
</code>```

And so this will return:

```<code>[10, 26, 42, 58]
</code>```

So this one good, but for the next question in my lab quiz. It is asking me to modify the function so that it will print the sum of the columns. So for example entering the same:

```<code>square = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16]
]
print(column_sums(square))
</code>```

Will return

```<code>[28, 32, 36, 40]
</code>```

Having trouble figuring this out. Will be great if someones has some time to help me out! (Note: the purpose of the function is not to use the "sum" function which is unusual but it is for nested loop practise)
Cheers

答:
You can use this to do the required OP ..

```<code>sum_of_columns = [sum([row[i] for row in square]) for i in range(0,len(square[0]))]
</code>```

Without built in sum function :

```<code>def array_sum(a):
  result=0
  for i in a:
     result+=i
  return result

sum_of_columns = [array_sum([row[i] for row in square]) for i in range(0,len(square[0]))]
</code>```

According to OP condition function to do column_sum :

```<code>def column_sums(square):
   """Returns a list of the columns sums in a magic square"""
   numbers = []
   for i in range(0, len(square[0])):
       result = 0
       for row in square:
           result += row[i]
       numbers.append(result)
   return numbers
</code>```

Body:
So I have this function here:

def row_sums(square):
    """Returns a list of the row sums in a magic square"""
    numbers = []
    for row in square:
        result = 0
        for col in row:
            result += col
        numbers.append(result)
    return numbers

Which when a magic square like the following is entered, it will return the sum of the rows without using the in-built function "sum":

square = [
   [1, 2, 3, 4],
   [5, 6, 7, 8],
   [9, 10, 11, 12],
   [13, 14, 15, 16]
]
print(row_sums(square))

And so this will return:

[10, 26, 42, 58]

So this one good, but for the next question in my lab quiz. It is asking me to modify the function so that it will print the sum of the columns. So for example entering the same:

square = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16]
]
print(column_sums(square))

Will return

[28, 32, 36, 40]

Having trouble figuring this out. Will be great if someones has some time to help me out! (Note: the purpose of the function is not to use the "sum" function which is unusual but it is for nested loop practise)
Cheers

Body:
You can use this to do the required OP ..

sum_of_columns = [sum([row[i] for row in square]) for i in range(0,len(square[0]))]

Without built in sum function :

def array_sum(a):
  result=0
  for i in a:
     result+=i
  return result

sum_of_columns = [array_sum([row[i] for row in square]) for i in range(0,len(square[0]))]

According to OP condition function to do column_sum :

def column_sums(square):
   """Returns a list of the columns sums in a magic square"""
   numbers = []
   for i in range(0, len(square[0])):
       result = 0
       for row in square:
           result += row[i]
       numbers.append(result)
   return numbers


问:
Can I put an iAd banner in the middle of View?
Is it possible to place iAd banner somewhere else than is top or bottom? I wish I could place it in the middle of my UIView.

tnx

答: It is possible, but it is not advised, because of Apple's HIG.</p>

ContentLicense: CC BY-SA 2.5


问:
Python: Take the Log of all elements in a 2D array
I have a 2D numpy array:

```<code>>>> arr = np.arange(1,10).reshape((3,3))
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
</code>```

I wish to take the logarithm of all elements within the array.
The following code works but it's a bit clunky

```<code>>>> from math import log10
>>> logArr = np.empty((3,3))
>>> for i in range(3):
...     for j in range(3):
...             logArr[i][j] = log10(arr[i][j])
...
array([[ 0.        ,  0.30103   ,  0.47712125],
       [ 0.60205999,  0.69897   ,  0.77815125],
       [ 0.84509804,  0.90308999,  0.95424251]])
</code>```

Does there exist a more efficient/'pythonic' way of doing such an operation?

Body:
I have a 2D numpy array:

>>> arr = np.arange(1,10).reshape((3,3))
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

I wish to take the logarithm of all elements within the array.
The following code works but it's a bit clunky

>>> from math import log10
>>> logArr = np.empty((3,3))
>>> for i in range(3):
...     for j in range(3):
...             logArr[i][j] = log10(arr[i][j])
...
array([[ 0.        ,  0.30103   ,  0.47712125],
       [ 0.60205999,  0.69897   ,  0.77815125],
       [ 0.84509804,  0.90308999,  0.95424251]])

Does there exist a more efficient/'pythonic' way of doing such an operation?

Body:
There is a numpy function for that, try numpy.log

>>> arr = np.arange(1,10).reshape((3,3))
>>> np.log(arr)
array([[ 0.        ,  0.69314718,  1.09861229],
       [ 1.38629436,  1.60943791,  1.79175947],
       [ 1.94591015,  2.07944154,  2.19722458]])

Or like in your implementation, you can use numpyp.log10 to find the logs in base 10.

>>> np.log10(arr)
array([[ 0.        ,  0.30103   ,  0.47712125],
       [ 0.60205999,  0.69897   ,  0.77815125],
       [ 0.84509804,  0.90308999,  0.95424251]])


问:
C# not recognizing a string sent to powershell somehow
I want to remove an email alias from a mailbox which is selected by the user.

```<code>string removeAlias = "Set-Mailbox \"" + userLabel.Text + "\" -EmailAddresses @{remove=\"" + textBox2.Text + "\"}";
</code>```

However, this does not work and I am not getting any error. Also, the following code works to add an email alias:

```<code>string setAlias = "Set-Mailbox \"" + userLabel.Text + "\" -EmailAddresses @{add=\"" + alias + "\"}";
</code>```

I still cant figure out why this does not work. Any help would be really appreciated.

答:
for any one facing such trouble. There was a whitespace in my alias string and so Powershell was not accepting it. I used the following to get rid of whitespaces:

selectedAlias = Regex.Replace(selectedAlias, "[\n\r\t]", "");

Body:
I want to remove an email alias from a mailbox which is selected by the user.

string removeAlias = "Set-Mailbox \"" + userLabel.Text + "\" -EmailAddresses @{remove=\"" + textBox2.Text + "\"}";

However, this does not work and I am not getting any error. Also, the following code works to add an email alias:

string setAlias = "Set-Mailbox \"" + userLabel.Text + "\" -EmailAddresses @{add=\"" + alias + "\"}";

I still cant figure out why this does not work. Any help would be really appreciated.


问:
Swift 3 prepare for segue not passing if segue.identifier == "showChildFiles" when the segue identifier seems correct
I am creating an app where parents can login and view information about their local child care centre. However, the code that runs the view controller for the login isn't working properly. I want my code to perform a segue using the identifier "ShowChildFiles" once the user presses the login button. But in the prepare(for segue: UIStoryboardSegue, sender: Any?) function I have a check for the correct segue identifier (if  segue.identifier == "ShowChildFiles") however it is not passing this if statement. I am printing out the identifier when it fails and it is returning "ShowChildFiles".

Here is the code

```<code>import Foundation
import UIKit

class MyChildLoginViewController: UIViewController {

    @IBOutlet weak var usernameTextField: UITextField!

    @IBOutlet weak var passwordTextField: UITextField!

    @IBAction func loginButtonPressed(_ sender: Any) {

        var request = URLRequest(url: URL(string: "myLogin.php")!)
        request.httpMethod = "POST"
        let postString = "userName=" + usernameTextField.text! + "&password=" + passwordTextField.text!
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {                                                 // check for fundamental networking error
                print("error=\(error)")
                return
            }

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(response)")
            }

            let responseString = String(data: data, encoding: .utf8)
            print("responseString = \(responseString)")

            if(responseString == "true"){
                //Login successful
                DispatchQueue.main.async(//Not sure why but this has to be executed asynchronously
                    execute: {
                        self.performSegue(withIdentifier: "ShowChildFiles", sender: Any?.self)
                    })

            }else if(responseString == "false"){
                //incorrect password
            }else if(responseString == "incorrect username"){
                //We dont recognise this username
            }else{
                //something went wrong
            }
        }
        task.resume()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(MyChildLoginViewController.dismissKeyboard))//Dismisses keyboard when screen tapped
        view.addGestureRecognizer(tap)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

     // MARK: - Navigation
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.

        if  segue.identifier == "ShowChildFiles" ,
            let destination = segue.destination as? ChildFilesTableViewController {
            print("preparing for segue")
            destination.passedString = self.getFamID()
        }else{
            print(segue.identifier!)
            print("not going in the correct place")
        }

     }

    func getFamID() -> String{

        let cs: [Character] = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o","p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", " "]
        /*var cs = Set(chars.characters)*/
        var user = [Character](usernameTextField.text!.lowercased().characters)
        var famID = ""
        for index in 0 ... user.count - 1 {
            if(!cs.contains(user[index])){
                famID = famID + String(user[index])
            }
        }
        return famID

    }
    //Calls this function when the tap is recognized.
    func dismissKeyboard() {
        //Causes the view (or one of its embedded text fields) to resign the first responder status.
        view.endEditing(true)
    }
}
</code>```

答: Since you seem to have proven by your logging that the segue identifier is what you think it is, "ShowChildFiles" — and indeed, it could hardly be otherwise, as that is the identifier you used to perform the segue in the first place — one must conclude that the part of the if condition that is failing is the second part, let destination = segue.destination as? ChildFilesTableViewController. Evidently the segue's destination is not a ChildFilesTableViewController. (Why not print(type(of:segue.destination)) as part of your logging, and find out?)

Body:
I am creating an app where parents can login and view information about their local child care centre. However, the code that runs the view controller for the login isn't working properly. I want my code to perform a segue using the identifier "ShowChildFiles" once the user presses the login button. But in the prepare(for segue: UIStoryboardSegue, sender: Any?) function I have a check for the correct segue identifier (if  segue.identifier == "ShowChildFiles") however it is not passing this if statement. I am printing out the identifier when it fails and it is returning "ShowChildFiles".

Here is the code

import Foundation
import UIKit

class MyChildLoginViewController: UIViewController {

    @IBOutlet weak var usernameTextField: UITextField!

    @IBOutlet weak var passwordTextField: UITextField!

    @IBAction func loginButtonPressed(_ sender: Any) {

        var request = URLRequest(url: URL(string: "myLogin.php")!)
        request.httpMethod = "POST"
        let postString = "userName=" + usernameTextField.text! + "&password=" + passwordTextField.text!
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {                                                 // check for fundamental networking error
                print("error=\(error)")
                return
            }

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(response)")
            }

            let responseString = String(data: data, encoding: .utf8)
            print("responseString = \(responseString)")

            if(responseString == "true"){
                //Login successful
                DispatchQueue.main.async(//Not sure why but this has to be executed asynchronously
                    execute: {
                        self.performSegue(withIdentifier: "ShowChildFiles", sender: Any?.self)
                    })

            }else if(responseString == "false"){
                //incorrect password
            }else if(responseString == "incorrect username"){
                //We dont recognise this username
            }else{
                //something went wrong
            }
        }
        task.resume()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(MyChildLoginViewController.dismissKeyboard))//Dismisses keyboard when screen tapped
        view.addGestureRecognizer(tap)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

     // MARK: - Navigation
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.

        if  segue.identifier == "ShowChildFiles" ,
            let destination = segue.destination as? ChildFilesTableViewController {
            print("preparing for segue")
            destination.passedString = self.getFamID()
        }else{
            print(segue.identifier!)
            print("not going in the correct place")
        }

     }

    func getFamID() -> String{

        let cs: [Character] = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o","p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", " "]
        /*var cs = Set(chars.characters)*/
        var user = [Character](usernameTextField.text!.lowercased().characters)
        var famID = ""
        for index in 0 ... user.count - 1 {
            if(!cs.contains(user[index])){
                famID = famID + String(user[index])
            }
        }
        return famID

    }
    //Calls this function when the tap is recognized.
    func dismissKeyboard() {
        //Causes the view (or one of its embedded text fields) to resign the first responder status.
        view.endEditing(true)
    }
}


问:
Python 3 Dictionary sorted with wrong output
I am currently doing an Assignment; however, I got some interesting output which confused me so much.

I am trying to sort the following dictionary:

```<code>result = {'A1': '9', 'A2': '14', 'A3': '16', 'A4': '0', 'B1': '53', 'B2': '267', 'B3': '75', 'B4': '22', 'C1': '19', 'C2': '407', 'C3': '171', 'C4': '56', 'C5': '10', 'D3': '47', 'D4': '34', 'D5': '10'}
</code>```

My sorting code with Python 3 is the following : (only sorted by value)

```<code>sortedList = [v for v in sorted(result.values())]
</code>```

The output is :

```<code>['0', '10', '10', '14', '16', '171', '19', '22', '267', '34', '407', '47', '53', '56', '75', '9']
</code>```

which is not fully sorted. The output is quite strange.

Why it is happened like this?
I have used another dict to test like this:

```<code>testD = {'A':'5','B': '9','c': '8','d': '6'}
</code>```

the output is right :

```<code>['5', '6', '8', '9']
</code>```

Is there something wrong with my result dictionary or is there something I am missing?

答: Strings will be ordered with a lexical sort. To sort your data numerically, convert the values into integers first.</p>

Body:
I am currently doing an Assignment; however, I got some interesting output which confused me so much.

I am trying to sort the following dictionary:

result = {'A1': '9', 'A2': '14', 'A3': '16', 'A4': '0', 'B1': '53', 'B2': '267', 'B3': '75', 'B4': '22', 'C1': '19', 'C2': '407', 'C3': '171', 'C4': '56', 'C5': '10', 'D3': '47', 'D4': '34', 'D5': '10'}

My sorting code with Python 3 is the following : (only sorted by value)

sortedList = [v for v in sorted(result.values())]

The output is :

['0', '10', '10', '14', '16', '171', '19', '22', '267', '34', '407', '47', '53', '56', '75', '9']

which is not fully sorted. The output is quite strange.

Why it is happened like this?
I have used another dict to test like this:

testD = {'A':'5','B': '9','c': '8','d': '6'}

the output is right :

['5', '6', '8', '9']

Is there something wrong with my result dictionary or is there something I am missing?


问:
Spring-Boot Custom Repository
I have been reading about Spring Boot custom repository. I have dozens of blogs explaining how to implement those but none of them explained scenario when we actually need it?

I mean one example where we cannot live without custom repo. I mean if there is case of complex query, we can anyhow achieve it using @Query.

Please explain.

答:
I find them useful when working with a program generator like jHipster. They keep your code separate from the generated code.

The xxxRepositoryCustom.java xxxRepositoryImpl will not be overwritten when the entities are re-generated by a dumb programmer (me.)  The queries themselves have some complex logic that can not be expressed in a simple @Query

Title: Spring-Boot Custom Repository


问:
How might an "API Level Analyser" tool work?
I work on a high-profile app which runs on all versions of Android. Unfortunately for me the last update on Market included an absolutely-last-minute patch <sigh> which introduced a dependency on an API introduced in 2.0. Every 1.x client who upgraded promptly crashed, causing us to (quite reasonably) get slaughtered in market feedback.

Obviously there are procedural issues here... under no circumstances should we have shipped code not tested on all 4 major platform versions... but that's not why I'm here.

It occurs to me that the tools should be a lot more proactive to avoid this problem.

Put simply, during development I would like to be able to see a list of every place I use an API which was introduced at a level above that specified by android:targetSdkVersion.

My question is: How would such a tool work? Would it be possible to write something that looks in each android.jar under <sdk-root>/platforms  of each platform (to build some kind of list of function signatures paired with version numbers) and then do some kind of search? I just don't know enough about the guts of Java/Dalvik to get a real handle on solving the problem.

答:
Ok, I am in the middle of writing a decent answer to this question. In a nutshell I am first building a database by chucking the Android SDK .jars through the standard javap tool. This allows me to build a massive list of APIs (functions, constants, etc) paired with the API level they were introduced in.

The second half of the tool runs on your own .apk and runs dexdump to get an annotated disassembly of each .class. It's then childs play (or should be) to cross-reference each function call to it's API level.

I should have this working within a week or so, will bung it online somewhere.


问:
With React / Redux, how do I dynamically pre-load state?
I'm having a hard time pre-loading state with React / Redux.

Before marking this as duplicate, I've already read these:

http://redux.js.org/docs/recipes/reducers/InitializingState.htm

Redux - managing preload state

What are your best practices for preloading initialState in your Redux apps?

Here's my scenario:

I'm using Node + React + Redux.

When I load a page, from the server, I load User object from the database. I need this User object to be in the state without a roundtrip to the server.

Because the User object is dynamic, I can't have it in the bundle.

I'm not using server-rendering.

My problem:

How do I initially load the User object from the server into my store in the Client?

In this answer, Dan Abramov says:

On the client, you’d read it from a global variable, and create the client store instance with it. In other words you never have to manually create initialState—you’re supposed to grab it on the server with store.getState(), pass it to client, and create a store with it.

So, I'm assuming that, by global variable, he means something like this:

```<code>// Here, window._initialState.user is being sent to the client in a <script/> tag.
const store = createStore(reducers, { user: window._initialState.user);
</code>```

The above might work, the problem is that I don't have confidence that this is actually a good practice because I didn't find any example on the internet about it.

So, Is this the right thing to do? Is there a better / more recommended way of doing it?

答:
When I load a page, from the server, I load User object from the database. I need this User object to be in the state without a roundtrip to the server.

I would argue that you should make an initial round trip to the server if you're not server rendering. The way I see it is that you have to make at least two calls to the server: one for your cache-able bundle, and one for the data. Even if you're loading a script that will set a global variable with some initial state, you still have to make another call to get the bundle right? I might be misunderstanding but I don't see an advantage in setting the initial state in the way you're describing. If you're not server rendering then maybe a plain-ole restful API and SPA is simpler.

How do I initially load the User object from the server into my store in the Client?

My suggestion is to just make the that first round trip the server and wait for the fetch promise to resolve, then create your store and render the app.

```<code>fetch('http://example.com/something').then(data => data.json()).then(initalState => {
    render(
        <Provider store={/*stored created with initalState*/}>
            <App />
        </Provider>,
        document.getElementById('app')
    )
});
</code>```

Again, I might be misunderstanding your problem/architecture here but this is just my two cents. Good luck!

Body:
I'm having a hard time pre-loading state with React / Redux.

Before marking this as duplicate, I've already read these:

http://redux.js.org/docs/recipes/reducers/InitializingState.htm

Redux - managing preload state

What are your best practices for preloading initialState in your Redux apps?

Here's my scenario:

I'm using Node + React + Redux.

When I load a page, from the server, I load User object from the database. I need this User object to be in the state without a roundtrip to the server.

Because the User object is dynamic, I can't have it in the bundle.

I'm not using server-rendering.

My problem:

How do I initially load the User object from the server into my store in the Client?

In this answer, Dan Abramov says:

On the client, you’d read it from a global variable, and create the client store instance with it. In other words you never have to manually create initialState—you’re supposed to grab it on the server with store.getState(), pass it to client, and create a store with it.

So, I'm assuming that, by global variable, he means something like this:

// Here, window._initialState.user is being sent to the client in a

Body:
When I load a page, from the server, I load User object from the database. I need this User object to be in the state without a roundtrip to the server.

I would argue that you should make an initial round trip to the server if you're not server rendering. The way I see it is that you have to make at least two calls to the server: one for your cache-able bundle, and one for the data. Even if you're loading a script that will set a global variable with some initial state, you still have to make another call to get the bundle right? I might be misunderstanding but I don't see an advantage in setting the initial state in the way you're describing. If you're not server rendering then maybe a plain-ole restful API and SPA is simpler.

How do I initially load the User object from the server into my store in the Client?

My suggestion is to just make the that first round trip the server and wait for the fetch promise to resolve, then create your store and render the app.

fetch('http://example.com/something').then(data => data.json()).then(initalState => {
    render(
        <Provider store={/*stored created with initalState*/}>
            <App />
        </Provider>,
        document.getElementById('app')
    )
});

Again, I might be misunderstanding your problem/architecture here but this is just my two cents. Good luck!


问:
Creating an array with large initial size in powershell
The only way I know to create an array in powershell is

$arr = @(1, 2, 3)

However, this creating method is not convenient if I want to create an array with large initial size such as 10000.

Because I don't want to write code like this

$arr = @(0, 0, 0, 0, 0, 0, ... ,0) # 10000 0s in this line of code

Writing code like the following is not efficient.

```<code>$arr = @()
for ($i = 1; $i -le 10000; $i++) {
  $arr += 0
}
</code>```

Because whenever += operator is executed, all of the elements in the old array would be copied into a newly created array.

What's the best way to create an array with large initial size in powershell?

答:
You could always do this:

```<code>$a = @(0..9999)
$a.length
</code>```

This is nearly like what you are already doing, except that you don't have to
write out all the values.

Body:
The only way I know to create an array in powershell is

$arr = @(1, 2, 3)

However, this creating method is not convenient if I want to create an array with large initial size such as 10000.

Because I don't want to write code like this

$arr = @(0, 0, 0, 0, 0, 0, ... ,0) # 10000 0s in this line of code

Writing code like the following is not efficient.

$arr = @()
for ($i = 1; $i -le 10000; $i++) {
  $arr += 0
}

Because whenever += operator is executed, all of the elements in the old array would be copied into a newly created array.

What's the best way to create an array with large initial size in powershell?

Body:
You could always do this:

$a = @(0..9999)
$a.length

This is nearly like what you are already doing, except that you don't have to
write out all the values.


问:
What have I messed up in the VBA loop for each worksheet?
I currently have to send multiple letters out at one time and often replace only 1 or two words within a cell. The problem is that I need those words to be bolded and it would be tedious to use this macro individually on 150 worksheets. I am very new to coding and have tried to search online to edit this code to loop through all of the worksheets, but everything I try seems to only change the current sheet I am on. Below is my current code with what I thought would cause the loop, but instead of looping through the worksheets it seems to only loop through the single worksheet I am on, asking if I would like to bold another word on that sheet.

Origanal code:

```<code>Sub FindAndBold()
Dim ws As Worksheet
Dim sFind As String
Dim rCell As Range
Dim rng As Range
Dim lCount As Long
Dim iLen As Integer
Dim iFind As Integer
Dim iStart As Integer

On Error Resume Next
Set rng = ActiveSheet.UsedRange. _
  SpecialCells(xlCellTypeConstants, xlTextValues)
On Error GoTo ErrHandler
If rng Is Nothing Then
    MsgBox "There are no cells with text"
    GoTo ExitHandler
End If

sFind = InputBox( _
  Prompt:="What do you want to BOLD?", _
  Title:="Text to Bold")
If sFind = "" Then
    MsgBox "No text was listed"
    GoTo ExitHandler
End If

iLen = Len(sFind)
lCount = 0

For Each rCell In rng
    With rCell
        iFind = InStr(.Value, sFind)
        Do While iFind > 0
            .Characters(iFind, iLen).Font.Bold = True
            lCount = lCount + 1
            iStart = iFind + iLen
            iFind = InStr(iStart, .Value, sFind)
        Loop
    End With
Next

If lCount = 0 Then
    MsgBox "There were no occurrences of" & _
      vbCrLf & "' " & sFind & " '" & _
      vbCrLf & "to bold."
ElseIf lCount = 1 Then
    MsgBox "One occurrence of" & _
      vbCrLf & "' " & sFind & " '" & _
      vbCrLf & "was made bold."
Else
    MsgBox lCount & " occurrences of" & _
      vbCrLf & "' " & sFind & " '" & _
      vbCrLf & "were made bold."
End If

ExitHandler:
    Set rCell = Nothing
    Set rng = Nothing
    Exit Sub

ErrHandler:
    MsgBox Err.Description
    Resume ExitHandler
End Sub
</code>```

My most recent attempt:

```<code>Sub FindAndBold()
Dim ws As Worksheet
Dim sFind As String
Dim rCell As Range
Dim rng As Range
Dim lCount As Long
Dim iLen As Integer
Dim iFind As Integer
Dim iStart As Integer
For Each ws In ActiveWorkbook.Worksheets

   On Error Resume Next
    Set rng = ActiveSheet.UsedRange. _
      SpecialCells(xlCellTypeConstants, xlTextValues)
    On Error GoTo ErrHandler
    If rng Is Nothing Then
        MsgBox "There are no cells with text"
        GoTo ExitHandler
    End If

    sFind = InputBox( _
      Prompt:="What do you want to BOLD?", _
      Title:="Text to Bold")
    If sFind = "" Then
        MsgBox "No text was listed"
        GoTo ExitHandler
    End If

    iLen = Len(sFind)
    lCount = 0

    For Each rCell In rng
        With rCell
            iFind = InStr(.Value, sFind)
            Do While iFind > 0
                .Characters(iFind, iLen).Font.Bold = True
                lCount = lCount + 1
               iStart = iFind + iLen
               iFind = InStr(iStart, .Value, sFind)
           Loop
       End With
   Next

    If lCount = 0 Then
        MsgBox "There were no occurrences of" & _
          vbCrLf & "' " & sFind & " '" & _
          vbCrLf & "to bold."
    ElseIf lCount = 1 Then
        MsgBox "One occurrence of" & _
          vbCrLf & "' " & sFind & " '" & _
          vbCrLf & "was made bold."
    Else
        MsgBox lCount & " occurrences of" & _
          vbCrLf & "' " & sFind & " '" & _
         vbCrLf & "were made bold."
    End If
Next ws
ExitHandler:
    Set rCell = Nothing
    Set rng = Nothing
    Exit Sub

ErrHandler:
    MsgBox Err.Description
    Resume ExitHandler
End Sub
</code>```

Corrected working code provided provided by YowE3K:

```<code>Sub FindAndBold()
Dim ws As Worksheet
Dim sFind As String
Dim rCell As Range
Dim rng As Range
Dim lCount As Long
Dim iLen As Integer
Dim iFind As Integer
Dim iStart As Integer

   For Each ws In ActiveWorkbook.Worksheets
    Set rng = Nothing
    Set rng = ws.UsedRange.SpecialCells(xlCellTypeConstants, xlTextValues)
    If rng Is Nothing Then
        MsgBox "There are no cells with text"
        GoTo ExitHandler
    End If

    sFind = InputBox( _
      Prompt:="What do you want to BOLD?", _
      Title:="Text to Bold")
    If sFind = "" Then
        MsgBox "No text was listed"
        GoTo ExitHandler
    End If

    iLen = Len(sFind)
    lCount = 0

    For Each rCell In rng
        With rCell
            iFind = InStr(.Value, sFind)
            Do While iFind > 0
                .Characters(iFind, iLen).Font.Bold = True
                lCount = lCount + 1
               iStart = iFind + iLen
               iFind = InStr(iStart, .Value, sFind)
           Loop
       End With
   Next

    If lCount = 0 Then
        MsgBox "There were no occurrences of" & _
          vbCrLf & "' " & sFind & " '" & _
          vbCrLf & "to bold on worksheet '" & ws.Name & "'."
    ElseIf lCount = 1 Then
        MsgBox "One occurrence of" & _
          vbCrLf & "' " & sFind & " '" & _
          vbCrLf & "was made bold on worksheet '" & ws.Name & "'."
    Else
        MsgBox lCount & " occurrences of" & _
          vbCrLf & "' " & sFind & " '" & _
         vbCrLf & "were made bold on worksheet '" & ws.Name & "'."
    End If
Next ws
ExitHandler:
    Set rCell = Nothing
    Set rng = Nothing
    Exit Sub

End Sub
</code>```

答:
You are setting up a loop to go through each worksheet (using ws as your reference to the sheet currently being processed), but then processing a range on the ActiveSheet.  Use ws instead of ActiveSheet.

You should also set rng to Nothing before attempting to set it to the UsedRange.SpecialCells or else, if that crashes, your If rng Is Nothing Then statement won't work (because rng will still be set to whatever it was set to on the previous iteration through the loop).

```<code>'...
For Each ws In ActiveWorkbook.Worksheets
    Set rng = Nothing
    On Error Resume Next
    Set rng = ws.UsedRange.SpecialCells(xlCellTypeConstants, xlTextValues)
    On Error GoTo ErrHandler
    If rng Is Nothing Then
'...
</code>```

Body:
I currently have to send multiple letters out at one time and often replace only 1 or two words within a cell. The problem is that I need those words to be bolded and it would be tedious to use this macro individually on 150 worksheets. I am very new to coding and have tried to search online to edit this code to loop through all of the worksheets, but everything I try seems to only change the current sheet I am on. Below is my current code with what I thought would cause the loop, but instead of looping through the worksheets it seems to only loop through the single worksheet I am on, asking if I would like to bold another word on that sheet.

Origanal code:

Sub FindAndBold()
Dim ws As Worksheet
Dim sFind As String
Dim rCell As Range
Dim rng As Range
Dim lCount As Long
Dim iLen As Integer
Dim iFind As Integer
Dim iStart As Integer

On Error Resume Next
Set rng = ActiveSheet.UsedRange. _
  SpecialCells(xlCellTypeConstants, xlTextValues)
On Error GoTo ErrHandler
If rng Is Nothing Then
    MsgBox "There are no cells with text"
    GoTo ExitHandler
End If

sFind = InputBox( _
  Prompt:="What do you want to BOLD?", _
  Title:="Text to Bold")
If sFind = "" Then
    MsgBox "No text was listed"
    GoTo ExitHandler
End If

iLen = Len(sFind)
lCount = 0

For Each rCell In rng
    With rCell
        iFind = InStr(.Value, sFind)
        Do While iFind > 0
            .Characters(iFind, iLen).Font.Bold = True
            lCount = lCount + 1
            iStart = iFind + iLen
            iFind = InStr(iStart, .Value, sFind)
        Loop
    End With
Next

If lCount = 0 Then
    MsgBox "There were no occurrences of" & _
      vbCrLf & "' " & sFind & " '" & _
      vbCrLf & "to bold."
ElseIf lCount = 1 Then
    MsgBox "One occurrence of" & _
      vbCrLf & "' " & sFind & " '" & _
      vbCrLf & "was made bold."
Else
    MsgBox lCount & " occurrences of" & _
      vbCrLf & "' " & sFind & " '" & _
      vbCrLf & "were made bold."
End If

ExitHandler:
    Set rCell = Nothing
    Set rng = Nothing
    Exit Sub

ErrHandler:
    MsgBox Err.Description
    Resume ExitHandler
End Sub

My most recent attempt:

Sub FindAndBold()
Dim ws As Worksheet
Dim sFind As String
Dim rCell As Range
Dim rng As Range
Dim lCount As Long
Dim iLen As Integer
Dim iFind As Integer
Dim iStart As Integer
For Each ws In ActiveWorkbook.Worksheets

   On Error Resume Next
    Set rng = ActiveSheet.UsedRange. _
      SpecialCells(xlCellTypeConstants, xlTextValues)
    On Error GoTo ErrHandler
    If rng Is Nothing Then
        MsgBox "There are no cells with text"
        GoTo ExitHandler
    End If

    sFind = InputBox( _
      Prompt:="What do you want to BOLD?", _
      Title:="Text to Bold")
    If sFind = "" Then
        MsgBox "No text was listed"
        GoTo ExitHandler
    End If

    iLen = Len(sFind)
    lCount = 0

    For Each rCell In rng
        With rCell
            iFind = InStr(.Value, sFind)
            Do While iFind > 0
                .Characters(iFind, iLen).Font.Bold = True
                lCount = lCount + 1
               iStart = iFind + iLen
               iFind = InStr(iStart, .Value, sFind)
           Loop
       End With
   Next

    If lCount = 0 Then
        MsgBox "There were no occurrences of" & _
          vbCrLf & "' " & sFind & " '" & _
          vbCrLf & "to bold."
    ElseIf lCount = 1 Then
        MsgBox "One occurrence of" & _
          vbCrLf & "' " & sFind & " '" & _
          vbCrLf & "was made bold."
    Else
        MsgBox lCount & " occurrences of" & _
          vbCrLf & "' " & sFind & " '" & _
         vbCrLf & "were made bold."
    End If
Next ws
ExitHandler:
    Set rCell = Nothing
    Set rng = Nothing
    Exit Sub

ErrHandler:
    MsgBox Err.Description
    Resume ExitHandler
End Sub

Corrected working code provided provided by YowE3K:

Sub FindAndBold()
Dim ws As Worksheet
Dim sFind As String
Dim rCell As Range
Dim rng As Range
Dim lCount As Long
Dim iLen As Integer
Dim iFind As Integer
Dim iStart As Integer

   For Each ws In ActiveWorkbook.Worksheets
    Set rng = Nothing
    Set rng = ws.UsedRange.SpecialCells(xlCellTypeConstants, xlTextValues)
    If rng Is Nothing Then
        MsgBox "There are no cells with text"
        GoTo ExitHandler
    End If

    sFind = InputBox( _
      Prompt:="What do you want to BOLD?", _
      Title:="Text to Bold")
    If sFind = "" Then
        MsgBox "No text was listed"
        GoTo ExitHandler
    End If

    iLen = Len(sFind)
    lCount = 0

    For Each rCell In rng
        With rCell
            iFind = InStr(.Value, sFind)
            Do While iFind > 0
                .Characters(iFind, iLen).Font.Bold = True
                lCount = lCount + 1
               iStart = iFind + iLen
               iFind = InStr(iStart, .Value, sFind)
           Loop
       End With
   Next

    If lCount = 0 Then
        MsgBox "There were no occurrences of" & _
          vbCrLf & "' " & sFind & " '" & _
          vbCrLf & "to bold on worksheet '" & ws.Name & "'."
    ElseIf lCount = 1 Then
        MsgBox "One occurrence of" & _
          vbCrLf & "' " & sFind & " '" & _
          vbCrLf & "was made bold on worksheet '" & ws.Name & "'."
    Else
        MsgBox lCount & " occurrences of" & _
          vbCrLf & "' " & sFind & " '" & _
         vbCrLf & "were made bold on worksheet '" & ws.Name & "'."
    End If
Next ws
ExitHandler:
    Set rCell = Nothing
    Set rng = Nothing
    Exit Sub

End Sub

Body:
You are setting up a loop to go through each worksheet (using ws as your reference to the sheet currently being processed), but then processing a range on the ActiveSheet.  Use ws instead of ActiveSheet.

You should also set rng to Nothing before attempting to set it to the UsedRange.SpecialCells or else, if that crashes, your If rng Is Nothing Then statement won't work (because rng will still be set to whatever it was set to on the previous iteration through the loop).

'...
For Each ws In ActiveWorkbook.Worksheets
    Set rng = Nothing
    On Error Resume Next
    Set rng = ws.UsedRange.SpecialCells(xlCellTypeConstants, xlTextValues)
    On Error GoTo ErrHandler
    If rng Is Nothing Then
'...


问:
How can I Sum / Group By the results of this table
I have a table of hours which looks like :

I want to sum the hours_spent results for this week only and group the results by the created_by person. I have this query which returns the correct data for showing only results in this week :

```<code>SELECT staff_id, first_name,  last_name, date_entered, `hours_spent` as total_hours FROM hours LEFT JOIN staff ON hours.created_by = staff.staff_id where yearweek(`date_entered`) = yearweek(curdate());
</code>```

But when I add the SUM(hours_spent) as total_hours and group by staff_id like the example below I get 0 results.

```<code>SELECT staff_id, date_entered, first_name, last_name, SUM(`hours_spent`) as total_hours FROM hours LEFT JOIN staff ON hours.created_by = staff.staff_id group by staff_id having yearweek(`date_entered`) = yearweek(curdate());
</code>```

I'm assuming it's not working because the Having part of my statement doesn't return individual rows of dates so it breaks.

I feel like I am doing this the hard way. Should I be trying to run a second summing query on the results of the first query rather than combine it all into one (I was hoping for cleanliness). Or should I be using a subquery to filter out the dates that aren't this week then group the totals if so how could I accomplish this?

答:
I got what I was expecting with :

SELECT staff.first_name,staff.last_name, sum(hours_spent)
FROM hours
LEFT JOIN staff ON hours.created_by = staff.staff_id
WHERE yearweek(date_entered,1) = (yearweek(curdate(),1)-1)
GROUP BY created_by

Body:
I have a table of hours which looks like :

I want to sum the hours_spent results for this week only and group the results by the created_by person. I have this query which returns the correct data for showing only results in this week :

SELECT staff_id, first_name,  last_name, date_entered, `hours_spent` as total_hours FROM hours LEFT JOIN staff ON hours.created_by = staff.staff_id where yearweek(`date_entered`) = yearweek(curdate());

But when I add the SUM(hours_spent) as total_hours and group by staff_id like the example below I get 0 results.

SELECT staff_id, date_entered, first_name, last_name, SUM(`hours_spent`) as total_hours FROM hours LEFT JOIN staff ON hours.created_by = staff.staff_id group by staff_id having yearweek(`date_entered`) = yearweek(curdate());

I'm assuming it's not working because the Having part of my statement doesn't return individual rows of dates so it breaks.

I feel like I am doing this the hard way. Should I be trying to run a second summing query on the results of the first query rather than combine it all into one (I was hoping for cleanliness). Or should I be using a subquery to filter out the dates that aren't this week then group the totals if so how could I accomplish this?


问:
How to call two functions in a let..in.. in SML/NJ

I'm trying to call two separate functions within a function. One
  function generates and presents a random List to a user and the other
  function uses the random list and sorts it.

```<code>fun getNumber() = (
print "Please enter the number of integers: ";
let
    val str = valOf (TextIO.inputLine TextIO.stdIn)
    val i : int = valOf (Int.fromString str)
    in(
    randomList(i);
    mergeSortDriver(randomList(i)))
end
);
</code>```

The above code only executes the mergeSortDriver. I've tried
  multiple ways such as removing the parentheses, trying nested in
  statements, and other methods but they do not work or they either give
  me an error. So how can I call both of these functions and have both
  present their data?

答:
```<code>fun getNumber() = (
print "Please enter the number of integers: ";
let
    val str = valOf (TextIO.inputLine TextIO.stdIn)
    val i : int = valOf (Int.fromString str)
    in(
    randomList(i),
    mergeSortDriver(randomList(i)))
end
);
</code>```

I needed to change the ; to a , within the in statement

Body:
I'm trying to call two separate functions within a function. One
  function generates and presents a random List to a user and the other
  function uses the random list and sorts it.

fun getNumber() = (
print "Please enter the number of integers: ";
let
    val str = valOf (TextIO.inputLine TextIO.stdIn)
    val i : int = valOf (Int.fromString str)
    in(
    randomList(i);
    mergeSortDriver(randomList(i)))
end
);

The above code only executes the mergeSortDriver. I've tried
  multiple ways such as removing the parentheses, trying nested in
  statements, and other methods but they do not work or they either give
  me an error. So how can I call both of these functions and have both
  present their data?

Body:
fun getNumber() = (
print "Please enter the number of integers: ";
let
    val str = valOf (TextIO.inputLine TextIO.stdIn)
    val i : int = valOf (Int.fromString str)
    in(
    randomList(i),
    mergeSortDriver(randomList(i)))
end
);

I needed to change the ; to a , within the in statement


问:
How to zip a file while writing to it?
Does anyone know of a way to zip a stream that you are writing to? I'm trying to avoid writing the file to the disk, and was wondering if I can just compress data as you are writing it to the stream.

The use case behind this is that the raw file is going to be very large and we want to avoid having to write the entire thing unzipped onto the disk.

答:
I think you would be interested in ZipOutputStream.  You can write to that stream, and then write it out to a zipped file.

Also, check out this tutorial for working with compressed (zipped) files in Java.  Here is a snippet from that tutorial, which might be a helpful illustration:

```<code>     BufferedInputStream origin = null;
     FileOutputStream dest = new
       FileOutputStream("c:\\zip\\myfigs.zip");
     ZipOutputStream out = new ZipOutputStream(new
       BufferedOutputStream(dest));
     //out.setMethod(ZipOutputStream.DEFLATED);
     byte data[] = new byte[BUFFER];
     // get a list of files from current directory
     File f = new File(".");
     String files[] = f.list();

     for (int i=0; i<files.length; i++) {
        System.out.println("Adding: "+files[i]);
        FileInputStream fi = new
          FileInputStream(files[i]);
        origin = new
          BufferedInputStream(fi, BUFFER);
        ZipEntry entry = new ZipEntry(files[i]);
        out.putNextEntry(entry);
        int count;
        while((count = origin.read(data, 0,
          BUFFER)) != -1) {
           out.write(data, 0, count);
        }
        origin.close();
     }
     out.close();
</code>```

Title: How to zip a file while writing to it?

Body:
I think you would be interested in ZipOutputStream.  You can write to that stream, and then write it out to a zipped file.

Also, check out this tutorial for working with compressed (zipped) files in Java.  Here is a snippet from that tutorial, which might be a helpful illustration:

     BufferedInputStream origin = null;
     FileOutputStream dest = new
       FileOutputStream("c:\\zip\\myfigs.zip");
     ZipOutputStream out = new ZipOutputStream(new
       BufferedOutputStream(dest));
     //out.setMethod(ZipOutputStream.DEFLATED);
     byte data[] = new byte[BUFFER];
     // get a list of files from current directory
     File f = new File(".");
     String files[] = f.list();

     for (int i=0; i<files.length; i++) {
        System.out.println("Adding: "+files[i]);
        FileInputStream fi = new
          FileInputStream(files[i]);
        origin = new
          BufferedInputStream(fi, BUFFER);
        ZipEntry entry = new ZipEntry(files[i]);
        out.putNextEntry(entry);
        int count;
        while((count = origin.read(data, 0,
          BUFFER)) != -1) {
           out.write(data, 0, count);
        }
        origin.close();
     }
     out.close();


问:
Javascript: Return a promise inside async function
Would it make any difference if I have:

```<code>async function test () {
  const foo = await bar()
  return Promise.all([promise1, promise2])
}
</code>```

instead of:

```<code>async function test () {
  const foo = await bar()
  const [result1, result2] = await Promise.all([promise1, promise2])
  // Given that I don't care about result1, result2 in this `test` function
  return [result1, result2]
}
</code>```

I get the same result if I do either. E.g. I can do this for either case:

```<code>test().then(([result1, result2]) => { ... })
</code>```

but I am more curious about the underlying mechanism how they both behave the same.

In other words, how does async function handle it if inside the function I return a promise instead of a value?

答:
I would think the way async functions works in respect to the return value is it checks whether that value is wrapped in a Promise object, and if not, does it automatically. If you explicitly return a Promise, then the function does nothing with it. I tested this out by returning a new Promise inside an async function:

```<code>async function test(){
var duration = resolveAfter(500)
    return new Promise((resolve, reject) =>{})
}

var neverresolved = test()
</code>```

The result is neverresolved contains a Promise that's always in the pending state, as expected.

Body:
Would it make any difference if I have:

async function test () {
  const foo = await bar()
  return Promise.all([promise1, promise2])
}

instead of:

async function test () {
  const foo = await bar()
  const [result1, result2] = await Promise.all([promise1, promise2])
  // Given that I don't care about result1, result2 in this `test` function
  return [result1, result2]
}

I get the same result if I do either. E.g. I can do this for either case:

test().then(([result1, result2]) => { ... })

but I am more curious about the underlying mechanism how they both behave the same.

In other words, how does async function handle it if inside the function I return a promise instead of a value?

Body:
I would think the way async functions works in respect to the return value is it checks whether that value is wrapped in a Promise object, and if not, does it automatically. If you explicitly return a Promise, then the function does nothing with it. I tested this out by returning a new Promise inside an async function:

async function test(){
var duration = resolveAfter(500)
    return new Promise((resolve, reject) =>{})
}

var neverresolved = test()

The result is neverresolved contains a Promise that's always in the pending state, as expected.


问:
How to debug VSTS extension build summary tab without deploying to VSTS service?
I need to develop a fairly complex UI for VSTS build summary tab. I'm using VS Code as the code editor. Following url describes how to debug using Edge browser, however this approach require constantly packaging and deploying extension to VSTS making it time consuming.
https://www.visualstudio.com/en-us/docs/integrate/extensions/test/debug-in-browser

I tried to directly load the .html (summary tab) using View In Browser extension and following message displayed in browser console,

```<code>No handler found on any channel for message:
{"id":1,"methodName":"initialHandshake","instanceId":"VSS.HostControl","params":[{"notifyLoadSucceeded":true,"vssSDKVersion":2}],"jsonrpc":"2.0","handshakeToken":"4234q23rqfafaf23r"}
</code>```

Is there any better way of debugging the application while developing?

答:
You can develop locally. Since VSTS uses an iframe to show your extension's content, you can run a local server and reference that in the vss-extension.json manifest.

First, in the vss-extension.json, set the baseUri property to where you are running your project locally, such as https://localhost:8889. You need to be running it as https for VSTS to serve the content, as otherwise you will get a "Mixed Content" error and VSTS will refuse to display your extension's content.

Then, publish your extension and run it locally. Wha-la, you should have local development. There may be more trial and error needed, let me know if there's any steps that I'm missing.

If the link still works (you know how the Interent is), this starter project is a great start: https://github.com/Microsoft/vsts-extension-multivalue-control

Body:
I need to develop a fairly complex UI for VSTS build summary tab. I'm using VS Code as the code editor. Following url describes how to debug using Edge browser, however this approach require constantly packaging and deploying extension to VSTS making it time consuming.
https://www.visualstudio.com/en-us/docs/integrate/extensions/test/debug-in-browser

I tried to directly load the .html (summary tab) using View In Browser extension and following message displayed in browser console,

No handler found on any channel for message:
{"id":1,"methodName":"initialHandshake","instanceId":"VSS.HostControl","params":[{"notifyLoadSucceeded":true,"vssSDKVersion":2}],"jsonrpc":"2.0","handshakeToken":"4234q23rqfafaf23r"}

Is there any better way of debugging the application while developing?


问:
Extract records from compiled search program, C
Does anybody have an idea on how to extract all information from a compiled, record search program?

I think the program works by using a binary search. It was compiled and the database was in the program. The only way to see the records is to make a correct search.

Is there some way that I can bruteforce the program and extract all information?
The record is searched by the ID which starts with 1 and 10 digit long [ 1xxxxxxxxx ].
If you want to try, 1112700303 will work but I don't have the other numbers.

I've tried some Decompiler but I have no idea what I'm doing.

The program can be downloaded from here:
https://docs.google.com/file/d/0B9fwDRGBsrxBT3FiSFdaTnJZcUk/edit

Your help is appreciated as it will increase my knowledge and learn something new here :D

答: This can probably be achieved by using Snowman. It might not get the exact source code you are looking for but enough to extract all the data you need such has the constant strings. </p>


问:
postgreSQL alter column data type to timestamp without time zone
I want to alter one column of data from text into type timestamp. There is no time zone in my data. The format of my data is like 28-03-17 17:22, including time and date but no time zone. In other words, all my data are in the same time zone. How can I do it?

I tried multiple ways below, but I still can not find the right approach. Hope you can help me.

Certainly, I can build a new table if my trouble can be solved.

```<code>alter table AB
alter create_time type TIMESTAMP;

ERROR:  column "create_time" cannot be cast automatically to type timestamp without time zone
HINT:  You might need to specify "USING create_time::timestamp without time zone".
********** Error **********

ERROR: column "create_time" cannot be cast automatically to type timestamp without time zone
SQL state: 42804
Hint: You might need to specify "USING create_time::timestamp without time zone".
</code>```

```<code>alter table AB
alter create_time type TIMESTAMP without time zone;

ERROR:  column "create_time" cannot be cast automatically to type timestamp without time zone
HINT:  You might need to specify "USING create_time::timestamp without time zone".
********** Error **********

ERROR: column "create_time" cannot be cast automatically to type timestamp without time zone
SQL state: 42804
Hint: You might need to specify "USING create_time::timestamp without time zone".
</code>```

```<code>alter table AB
alter create_time::without time zone type TIMESTAMP;

ERROR:  syntax error at or near "::"
LINE 2:  alter create_time::without time zone type TIMESTAM
                          ^
********** Error **********

ERROR: syntax error at or near "::"
SQL state: 42601
Character: 50
</code>```

```<code>alter table AB
alter create_time UTC type TIMESTAMP;

ERROR:  syntax error at or near "UTC"
LINE 2: alter create_time UTC type TIMESTAMP;
                          ^
********** Error **********

ERROR: syntax error at or near "UTC"
SQL state: 42601
Character: 50
</code>```

答:
If create_time is of type TEXT with valid date value, it'll be easier to proceed with the change as follows (Be advised to first do a table dump as a backup):

```<code>-- Create a temporary TIMESTAMP column
ALTER TABLE AB ADD COLUMN create_time_holder TIMESTAMP without time zone NULL;

-- Copy casted value over to the temporary column
UPDATE AB SET create_time_holder = create_time::TIMESTAMP;

-- Modify original column using the temporary column
ALTER TABLE AB ALTER COLUMN create_time TYPE TIMESTAMP without time zone USING create_time_holder;

-- Drop the temporary column (after examining altered column values)
ALTER TABLE AB DROP COLUMN create_time_holder;
</code>```

Body:
I want to alter one column of data from text into type timestamp. There is no time zone in my data. The format of my data is like 28-03-17 17:22, including time and date but no time zone. In other words, all my data are in the same time zone. How can I do it?

I tried multiple ways below, but I still can not find the right approach. Hope you can help me.

Certainly, I can build a new table if my trouble can be solved.

alter table AB
alter create_time type TIMESTAMP;

ERROR:  column "create_time" cannot be cast automatically to type timestamp without time zone
HINT:  You might need to specify "USING create_time::timestamp without time zone".
********** Error **********

ERROR: column "create_time" cannot be cast automatically to type timestamp without time zone
SQL state: 42804
Hint: You might need to specify "USING create_time::timestamp without time zone".

alter table AB
alter create_time type TIMESTAMP without time zone;

ERROR:  column "create_time" cannot be cast automatically to type timestamp without time zone
HINT:  You might need to specify "USING create_time::timestamp without time zone".
********** Error **********

ERROR: column "create_time" cannot be cast automatically to type timestamp without time zone
SQL state: 42804
Hint: You might need to specify "USING create_time::timestamp without time zone".

alter table AB
alter create_time::without time zone type TIMESTAMP;

ERROR:  syntax error at or near "::"
LINE 2:  alter create_time::without time zone type TIMESTAM
                          ^
********** Error **********

ERROR: syntax error at or near "::"
SQL state: 42601
Character: 50

alter table AB
alter create_time UTC type TIMESTAMP;

ERROR:  syntax error at or near "UTC"
LINE 2: alter create_time UTC type TIMESTAMP;
                          ^
********** Error **********

ERROR: syntax error at or near "UTC"
SQL state: 42601
Character: 50

Body:
If create_time is of type TEXT with valid date value, it'll be easier to proceed with the change as follows (Be advised to first do a table dump as a backup):

-- Create a temporary TIMESTAMP column
ALTER TABLE AB ADD COLUMN create_time_holder TIMESTAMP without time zone NULL;

-- Copy casted value over to the temporary column
UPDATE AB SET create_time_holder = create_time::TIMESTAMP;

-- Modify original column using the temporary column
ALTER TABLE AB ALTER COLUMN create_time TYPE TIMESTAMP without time zone USING create_time_holder;

-- Drop the temporary column (after examining altered column values)
ALTER TABLE AB DROP COLUMN create_time_holder;


问:
Change image onclick (specific patern)
So, I'm new to javascript and I got this assignment:

"Find a figure with the number 1 and name it "one.jpg" on a page.
  Change the figure (figure 2) to "two.jpg" when it is clicked.
  Change after another click to "three.jpg" then back to "one.jpg"

However, I cannot seem to find a solution for this. All examples I found use buttons.

答:
This is I think what you want to happen.</p>

```<code><img src="one.jpg" id="imageid" onclick="img_clicked()">
<script>
    var clicks = 1;
    function img_clicked() {
        clicks ++;
        switch(clicks) {
            case 1: document.getElementById("imageid").src="one.jpg"; break;
            case 2: document.getElementById("imageid").src="two.jpg"; break;
            case 3: document.getElementById("imageid").src="three.jpg"; clicks = 0; break;
        }
    }
</script>
</script>
</code>```

Title: Change image onclick (specific patern)

Body:
This is I think what you want to happen.

<img src="one.jpg" id="imageid" onclick="img_clicked()">
<script>
    var clicks = 1;
    function img_clicked() {
        clicks ++;
        switch(clicks) {
            case 1: document.getElementById("imageid").src="one.jpg"; break;
            case 2: document.getElementById("imageid").src="two.jpg"; break;
            case 3: document.getElementById("imageid").src="three.jpg"; clicks = 0; break;
        }
    }
</script>
</script>


问:
Browser Repaint/Reflow performance: using CSS3 Gradients vs PNG Gradients
I am working at an app that causes lots of browser reflows. Performance is a key issue here. From the performance point of view Is it better to use a CSS3 gradient or an image gradient for some DOM elements? Does a page that uses CSS text shadows and gradients will have a slower reflow as a page that uses images to achieve those visual effects?
Also, are there any reflow tests out there I can use?</p>

答:
It depends a lot on how the browser renders it, but for the most part those things will render slower. In addition, you'll have a less pixel-perfect display in older browsers. However, this also serves to segment your audience, as generally those with updated browsers also have updated computers. So, it's a trade-off that can work in your favor to essentially serve a stripped down version of your site to those that wouldn't be able to handle it. It's not guaranteed, but I've found it usually balances out pretty well.

Overall, real-world testing is the way to go. Build it, see if it works, and fix performance issues once you find them. I wouldn't hesitate just because there's a chance it might not work. If it works just fine and you don't try it, you'll never know!


问:
How to fill in NA values with grouped means in R
Say I have a df that looks like:

```<code>rat  let num
1     A   3
3     c   12
3     B   41
1     B   NA
1     A   NA
2     B   2
2     C   20
1     C   NA
2     A   33
3     C   10
</code>```

I would like to group_by 'rat' and 'let' and get the mean of 'num' for each group and use that to fill in the NA values.

I have done the grouping and got the mean but don't know how to apply the values to fill in the NA values in my original df. Different methods would be greatly appreciated! Thanks.

```<code>df %>% group_by(rat,let) %>% summarise(num_avg = mean(num,na.rm=T))
</code>```

答:
Here's one way.  </p>

```<code>df <- df %>% group_by(rat,let) %>% mutate(num_avg = mean(num,na.rm=T))
df$num[is.na(df$num)] <- df$num_avg[is.na(df$num)]
</code>```

Body:
Say I have a df that looks like:

rat  let num
1     A   3
3     c   12
3     B   41
1     B   NA
1     A   NA
2     B   2
2     C   20
1     C   NA
2     A   33
3     C   10

I would like to group_by 'rat' and 'let' and get the mean of 'num' for each group and use that to fill in the NA values.

I have done the grouping and got the mean but don't know how to apply the values to fill in the NA values in my original df. Different methods would be greatly appreciated! Thanks.

df %>% group_by(rat,let) %>% summarise(num_avg = mean(num,na.rm=T))

Body:
Here's one way.

df <- df %>% group_by(rat,let) %>% mutate(num_avg = mean(num,na.rm=T))
df$num[is.na(df$num)] <- df$num_avg[is.na(df$num)]


问:
Is it possible in MySQL to update only the nth occurence?
My table has data like so

```<code>  products_parent_id | products_quantity
        2               5
        2               7
        2               9
        2               4
</code>```

My SQL statement looks like so (so far):

```<code>UPDATE ' . TABLE_PRODUCTS . ' SET products_quantity = products_quantity +' . $order['products_quantity'] . ', products_ordered = products_ordered - ' . $order['products_quantity'] . ' WHERE products_parent_id = ' . (int)$order['products_id']
</code>```

Now what I want to do, is update only say the 3rd occurrence of products_parent_id (in this case, 3rd from the top is 9)

To SELECT the 3rd occurrence, I used this at the end of my statements LIMIT($grade, 1)

Is there a way to UPDATE using MySQL but only the 3rd/4th/etc occurrence? Will it be reliable?

Thank you

答:
Your question doesn't make your reasons for doing this update entirely clear, but it does remind me of when I've been generating sample entries in a DB table and wanted to move a handful of them into category A or category B.

Your SQL query doesn't specify an ORDER BY, so Martin's answer is correct in saying that you may not get the same result order each time. However, if your ORDER BY was based on a particular ID, and that ID was sequential, you would be able to use modulo to access each third record.

Eg:

```<code>mysql> create table foo ( id int ) ;
Query OK, 0 rows affected (0.01 sec)

mysql> insert into foo values (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11), (15) ;
Query OK, 12 rows affected (0.00 sec)
Records: 12  Duplicates: 0  Warnings: 0

mysql> select * from foo where id%3=0;
+------+
| id   |
+------+
|    3 |
|    6 |
|    9 |
|   15 |
+------+
4 rows in set (0.00 sec)
</code>```

If that method works for you, you could do your update to hit every third entry by using

```<code>UPDATE [ ... ] WHERE id % 3 = 0 ;
</code>```

(Update, where id / 3 has a remainder of 0).

OwnerDisplayName: alex

Body:
My table has data like so

  products_parent_id | products_quantity
        2               5
        2               7
        2               9
        2               4

My SQL statement looks like so (so far):

UPDATE ' . TABLE_PRODUCTS . ' SET products_quantity = products_quantity +' . $order['products_quantity'] . ', products_ordered = products_ordered - ' . $order['products_quantity'] . ' WHERE products_parent_id = ' . (int)$order['products_id']

Now what I want to do, is update only say the 3rd occurrence of products_parent_id (in this case, 3rd from the top is 9)

To SELECT the 3rd occurrence, I used this at the end of my statements LIMIT($grade, 1)

Is there a way to UPDATE using MySQL but only the 3rd/4th/etc occurrence? Will it be reliable?

Thank you

Body:
Your question doesn't make your reasons for doing this update entirely clear, but it does remind me of when I've been generating sample entries in a DB table and wanted to move a handful of them into category A or category B.

Your SQL query doesn't specify an ORDER BY, so Martin's answer is correct in saying that you may not get the same result order each time. However, if your ORDER BY was based on a particular ID, and that ID was sequential, you would be able to use modulo to access each third record.

Eg:

mysql> create table foo ( id int ) ;
Query OK, 0 rows affected (0.01 sec)

mysql> insert into foo values (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11), (15) ;
Query OK, 12 rows affected (0.00 sec)
Records: 12  Duplicates: 0  Warnings: 0

mysql> select * from foo where id%3=0;
+------+
| id   |
+------+
|    3 |
|    6 |
|    9 |
|   15 |
+------+
4 rows in set (0.00 sec)

If that method works for you, you could do your update to hit every third entry by using

UPDATE [ ... ] WHERE id % 3 = 0 ;

(Update, where id / 3 has a remainder of 0).

OwnerDisplayName: Chris Burgess


问:
mySQL: is it possible to make this query any faster?
I have a table "test" containing millions of entries. Each row contains a floating point "feature" and a "count" how often this feature is present in item "id". The primary key for this table is the combination of "id" and "feature", i.e. every item may have multiple features. There are usually a couple of hundred to a couple of thousand feature entries per item id.

```<code>create table test
(
    id      int not null,
    feature double not null,
    count   int not null
);
</code>```

The task is to find the 500 most similar items to a given reference item. Similarity is measured in number of identical feature values in both items. The query I have come up with is quoted below, but despite properly using indices its execution plan still contains "using temporary" and "using filesort", giving unacceptable performance for my use case.

```<code>select
    t1.id,
    t2.id,
    sum( least( t1.count, t2.count )) as priority
from test as t1
inner join test as t2
     on t2.feature = t1.feature
where t1.id = {some user supplied id value}
group by t1.id, t2.id
order by priority desc
limit 500;
</code>```

Any ideas on how to improve on this? The schema can be modified and indices added as needed.

答:
Can you knock it down to just one table? Usinq subqueries you might be able to avoid the join and it will be a win if the subqueries are faster, indexed, and executed exactly once. Something like this (untested).

select

t2.id,

SUM( t2.count ) as priority

from test as t2

where t2.id = {some user supplied id value} AND

      t2.count > (SELECT MIN(count) FROM test t1 WHERE id= {some user supplied value} ) AND

      t2.feature IN (SELECT feature FROM test t1 WHERE id= {some user supplied value} )

group by t1.id

order by priority desc

limit 500;

If that doesnt work Mysql is terrible at realizing the inner selects are constant tables and will re-execute them for each row. Wrapping them in a select again forces a constant table lookup. Heres a hack:

select

    t1.id,

    SUM( t2.count ) as priority

from test as t2

where t2.id = {some user supplied id value} AND

      t2.count > (

                   SELECT * FROM (

                     SELECT MIN(count) FROM test t1 WHERE id= {some user supplied
value} ) as const ) AND

      t2.feature IN ( SELECT * from (

                      SELECT feature FROM test t1 WHERE id= {some user supplied value}
) as const )

group by t1.id

order by priority desc

limit 500;

Body:
I have a table "test" containing millions of entries. Each row contains a floating point "feature" and a "count" how often this feature is present in item "id". The primary key for this table is the combination of "id" and "feature", i.e. every item may have multiple features. There are usually a couple of hundred to a couple of thousand feature entries per item id.

create table test
(
    id      int not null,
    feature double not null,
    count   int not null
);

The task is to find the 500 most similar items to a given reference item. Similarity is measured in number of identical feature values in both items. The query I have come up with is quoted below, but despite properly using indices its execution plan still contains "using temporary" and "using filesort", giving unacceptable performance for my use case.

select
    t1.id,
    t2.id,
    sum( least( t1.count, t2.count )) as priority
from test as t1
inner join test as t2
     on t2.feature = t1.feature
where t1.id = {some user supplied id value}
group by t1.id, t2.id
order by priority desc
limit 500;

Any ideas on how to improve on this? The schema can be modified and indices added as needed.


问:
How to execute promises sequentially, passing the parameters from an array?
```<code>var myArray = [1, 2, 3, 4, 5, 6]

function myPromise(num){
  return new Promise(res => {
    window.setTimeout(()=>{
      res(  console.log("done: " + num)  )
    },2000)
  })
}

myPromise(myArray[0])
  .then(x => myPromise(myArray[1]))
  .then(x => myPromise(myArray[2]))
  .then(x => myPromise(myArray[3]))
  .then(x => myPromise(myArray[4]))
  .then(x => myPromise(myArray[5]))
</code>```

Right now, if I execute the statement above, it will run sequentially. In my actual use case the array is dynamically populated and I need to execute the myPromise() function for each member in myArray.

How can I make a "pauseable loop" that will loop for each item in the array, execute myPromise and wait for the promise to be resolved before continuing to the next iteration?

答:
You could use Array.reduce.

```<code>//type: [number]
var myArray = [1, 2, 3, 4, 5, 6] //doesn't really matter

//type: number -> Promise<number>
function myPromise(num){
  return new Promise((resolve) => {
    window.setTimeout(()=>{
      resolve(console.log("done: " + num)  )
    },2000)
  })
}

//Array.reduce has type: [a] ~> ((b, a) -> b), b) -> b
//So it can have type:
//[number] ~> ((Promise<number>, number) -> Promise<number>), Promise<number>) -> Promise<number>
//Therefore we need to give reduce a function that takes a Promise
//resolving to a number and a number which makes a new promise.
//This is the function we want:

function sequencePromises(promise, number) {
  return new Promise((resolve) => {
    resolve(promise.then(_ => myPromise(number)));
  });
}

myArray.reduce(sequencePromises, Promise.resolve());
</code>```

Of course, this simplistic approach won't work if you have a promise which can error, or if you need previous results, so you might want to make sequencePromises more generic:

```<code>function genericSequencePromises(promiseFunction) {
  return (promise, parameter) => {
    return new Promise((resolve, reject) =>
                         return promiseFunction(resolve,
                                                reject,
                                                promise,
                                                parameter));
  }
}
</code>```

Then you can do whatever you want as long as you return a Promise.

Finally, you might benefit from this little helper:

```<code>function promiseSeries(array, reducer) {
  return array.reduce(reducer, Promise.resolve());
}
</code>```

Bringing it all together:

```<code>let sequencePromises = genericSequencePromises((resolve, reject, promise, num) => {
  resolve(promise.then(_ => console.log(`done: ${num}`)));
}

promiseSeries(myArray, sequencePromises);
</code>```

This way, you can not only handle the case in your question, but much more complex cases.

ContentLicense: CC BY-SA 4.0

Body:
var myArray = [1, 2, 3, 4, 5, 6]

function myPromise(num){
  return new Promise(res => {
    window.setTimeout(()=>{
      res(  console.log("done: " + num)  )
    },2000)
  })
}

myPromise(myArray[0])
  .then(x => myPromise(myArray[1]))
  .then(x => myPromise(myArray[2]))
  .then(x => myPromise(myArray[3]))
  .then(x => myPromise(myArray[4]))
  .then(x => myPromise(myArray[5]))

Right now, if I execute the statement above, it will run sequentially. In my actual use case the array is dynamically populated and I need to execute the myPromise() function for each member in myArray.

How can I make a "pauseable loop" that will loop for each item in the array, execute myPromise and wait for the promise to be resolved before continuing to the next iteration?

Body:
You could use Array.reduce.

//type: [number]
var myArray = [1, 2, 3, 4, 5, 6] //doesn't really matter

//type: number -> Promise<number>
function myPromise(num){
  return new Promise((resolve) => {
    window.setTimeout(()=>{
      resolve(console.log("done: " + num)  )
    },2000)
  })
}

//Array.reduce has type: [a] ~> ((b, a) -> b), b) -> b
//So it can have type:
//[number] ~> ((Promise<number>, number) -> Promise<number>), Promise<number>) -> Promise<number>
//Therefore we need to give reduce a function that takes a Promise
//resolving to a number and a number which makes a new promise.
//This is the function we want:

function sequencePromises(promise, number) {
  return new Promise((resolve) => {
    resolve(promise.then(_ => myPromise(number)));
  });
}

myArray.reduce(sequencePromises, Promise.resolve());

Of course, this simplistic approach won't work if you have a promise which can error, or if you need previous results, so you might want to make sequencePromises more generic:

function genericSequencePromises(promiseFunction) {
  return (promise, parameter) => {
    return new Promise((resolve, reject) =>
                         return promiseFunction(resolve,
                                                reject,
                                                promise,
                                                parameter));
  }
}

Then you can do whatever you want as long as you return a Promise.

Finally, you might benefit from this little helper:

function promiseSeries(array, reducer) {
  return array.reduce(reducer, Promise.resolve());
}

Bringing it all together:

let sequencePromises = genericSequencePromises((resolve, reject, promise, num) => {
  resolve(promise.then(_ => console.log(`done: ${num}`)));
}

promiseSeries(myArray, sequencePromises);

This way, you can not only handle the case in your question, but much more complex cases.


问:
NSTimeZone isDaylightSavingTime giving wrong value
Currently GMT-0700(US/pacific) is already in day-light-saving

But I am getting "NO" from NSTimeZone

```<code>NSTimeZone *timeZone = [NSTimeZone timeZoneForSecondsFromGMT:secondsFromGMT]; //Getting timezone as GMT-0700
BOOL isDaylightSavingTime = [timeZone isDaylightSavingTime]; //getting boolean value as NO
</code>```

How to fix this issue?

REQUIREMENT :I want to know ,my receiver is using dayLightSavingTime or not.i will get only receiver offset value.I have to support different timezones()..What is the best approach to do this

答: Other answers mentioning timeZoneWithName are correct but there's one more detail I don't think has been mentioned. The reason that timeZoneForSecondsFromGMT doesn't work is that GMT does not have daylight savings time (or summer time, as it's more sensibly called in some other countries). GMT doesn't jump forward or back; it always moves ahead by one second per second. Since you ask for a fixed number of seconds from GMT, the result also does not have GMT. If it gave you a time zone that observed daylight saving time, the number of seconds from GMT would have to change twice a year. But since you asked for a fixed number of seconds, you get a result that doesn't do that, and never reports daylight saving time in effect.

Body:
Currently GMT-0700(US/pacific) is already in day-light-saving

But I am getting "NO" from NSTimeZone

NSTimeZone *timeZone = [NSTimeZone timeZoneForSecondsFromGMT:secondsFromGMT]; //Getting timezone as GMT-0700
BOOL isDaylightSavingTime = [timeZone isDaylightSavingTime]; //getting boolean value as NO

How to fix this issue?

REQUIREMENT :I want to know ,my receiver is using dayLightSavingTime or not.i will get only receiver offset value.I have to support different timezones()..What is the best approach to do this


问:
Ubuntu OpenCV not compiling
I'm trying to compile OpenCV 3.2 with contributions with the following commands:

```<code>1.
cmake -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=OFF -DCMAKE_INSTALL_PREFIX=/usr/local/ -DOPENCV_EXTRA_MODULES_PATH=/home/matteo/Desktop/Xilinx/OpenCV/source/opencv_contrib/modules/ /home/matteo/Desktop/Xilinx/OpenCV/source/opencv-3.2.0/
2.
make -j7 # runs 7 jobs in parallel
3.
sudo make install
</code>```

Can you explain why I get

```<code>...
........
...........
........................
-- VTK is not found. Please set -DVTK_DIR in CMake to VTK build directory, or to VTK install subdirectory with VTKConfig.cmake file
-- Caffe:   NO
-- Protobuf:   NO
-- Glog:   NO
-- Downloading ...
CMake Error at cmake/OpenCVUtils.cmake:1043 (file):
  file DOWNLOAD cannot open file for write.
Call Stack (most recent call first):
  ../opencv_contrib/modules/dnn/cmake/OpenCVFindLibProtobuf.cmake:32 (ocv_download)
  ../opencv_contrib/modules/dnn/CMakeLists.txt:5 (include)

CMake Error at cmake/OpenCVUtils.cmake:1047 (message):
  Failed to download .  Status=
Call Stack (most recent call first):
  ../opencv_contrib/modules/dnn/cmake/OpenCVFindLibProtobuf.cmake:32 (ocv_download)
  ../opencv_contrib/modules/dnn/CMakeLists.txt:5 (include)

-- Configuring incomplete, errors occurred!
</code>```

I'm working with Ubuntu 16.04 . I already had OpenCV on the system: maybe I unistall it in the wrong way? I remember to compile OpenCV 3.2 with the same command used above.

答: There is a right conflict in your build folder (may result from your previous sudo make install). I don't remember how I fixed it, but you can try recursively chown to both source and build folders (or chmod to 777).

Title: Ubuntu OpenCV not compiling

Body:
I'm trying to compile OpenCV 3.2 with contributions with the following commands:

1.
cmake -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=OFF -DCMAKE_INSTALL_PREFIX=/usr/local/ -DOPENCV_EXTRA_MODULES_PATH=/home/matteo/Desktop/Xilinx/OpenCV/source/opencv_contrib/modules/ /home/matteo/Desktop/Xilinx/OpenCV/source/opencv-3.2.0/
2.
make -j7 # runs 7 jobs in parallel
3.
sudo make install

Can you explain why I get

...
........
...........
........................
-- VTK is not found. Please set -DVTK_DIR in CMake to VTK build directory, or to VTK install subdirectory with VTKConfig.cmake file
-- Caffe:   NO
-- Protobuf:   NO
-- Glog:   NO
-- Downloading ...
CMake Error at cmake/OpenCVUtils.cmake:1043 (file):
  file DOWNLOAD cannot open file for write.
Call Stack (most recent call first):
  ../opencv_contrib/modules/dnn/cmake/OpenCVFindLibProtobuf.cmake:32 (ocv_download)
  ../opencv_contrib/modules/dnn/CMakeLists.txt:5 (include)

CMake Error at cmake/OpenCVUtils.cmake:1047 (message):
  Failed to download .  Status=
Call Stack (most recent call first):
  ../opencv_contrib/modules/dnn/cmake/OpenCVFindLibProtobuf.cmake:32 (ocv_download)
  ../opencv_contrib/modules/dnn/CMakeLists.txt:5 (include)

-- Configuring incomplete, errors occurred!

I'm working with Ubuntu 16.04 . I already had OpenCV on the system: maybe I unistall it in the wrong way? I remember to compile OpenCV 3.2 with the same command used above.


问:
Plotting a location into an irregular rectangle
I have 4 Point values: TopLeft, TopRight, BottomLeft, BottomRight. These define a 4 sided shape (like a distorted rectangle) on my monitor. These are the point a Tobii gaze device thinks I am looking at when in fact I am looking at the four corners of my monitor.

This picture shows a bitmap on the left representing my monitor, and the points the Tobii device tells me I am looking at when I am in fact looking at the corners of the screen. (It's a representation, not real).

I want to use those four calibration points to take a screen X,Y position that is from an inaccurate gaze position and correct it so that it is positioned as per the image on the right.

答:
Edit: New solution for the edited question is at the end.

This problem is call bilinear interpolation.

Once you grasp the idea, it will be very easy and you would remember it for the rest of your life.

It would be quite long to post all detail here, but I will try.

First, I will name the point on the left to be (x,y) and the right to be (X,Y).

Let (x1,y1), (x1,y2), (x2,y1), (x2,y2) be the corner points on the left rectangle.

Secondly, let's split the problem into 2 bilinear interpolation problems:

want to find X

want to find Y

Let's find them one by one (X or Y).

Define : Qxx are the value of X or Y of the four corner in the right rectangle.

Suppose that we want to find the value of the unknown function f at
  the point (x, y). It is assumed that we know the value of f at the
  four points Q11 = (x1, y1), Q12 = (x1, y2), Q21 = (x2, y1), and Q22 =
  (x2, y2).

The f(x,y) of your problem is X or Y in your question.

Then you interpolate f(x,y1) and f(x,y2) to be f(x,y) in the same way.

Finally, you will got X or Y=f(x,y)

Reference : All pictures/formulas/text here are  copied from the wiki link (some with modification).

Edit: After the question has been edited, it become very different.

 The new one is opposite, and it is called "inverse bilinear interpolation" which is far harder.

 For more information, please read http://www.iquilezles.org/www/articles/ibilinear/ibilinear.htm


问:
Python 3 Dictionary sorted with wrong output
I am currently doing an Assignment; however, I got some interesting output which confused me so much.

I am trying to sort the following dictionary:

```<code>result = {'A1': '9', 'A2': '14', 'A3': '16', 'A4': '0', 'B1': '53', 'B2': '267', 'B3': '75', 'B4': '22', 'C1': '19', 'C2': '407', 'C3': '171', 'C4': '56', 'C5': '10', 'D3': '47', 'D4': '34', 'D5': '10'}
</code>```

My sorting code with Python 3 is the following : (only sorted by value)

```<code>sortedList = [v for v in sorted(result.values())]
</code>```

The output is :

```<code>['0', '10', '10', '14', '16', '171', '19', '22', '267', '34', '407', '47', '53', '56', '75', '9']
</code>```

which is not fully sorted. The output is quite strange.

Why it is happened like this?
I have used another dict to test like this:

```<code>testD = {'A':'5','B': '9','c': '8','d': '6'}
</code>```

the output is right :

```<code>['5', '6', '8', '9']
</code>```

Is there something wrong with my result dictionary or is there something I am missing?

答:
As the value of dictionary are string so there is lexical sorting based on ascii values.

As evident, you need the values to be sorted according to their integer values.

```<code>result = {'A1': '9', 'A2': '14', 'A3': '16', 'A4': '0', 'B1': '53', 'B2': '267', 'B3': '75', 'B4': '22', 'C1': '19', 'C2': '407', 'C3': '171', 'C4': '56', 'C5': '10', 'D3': '47', 'D4': '34', 'D5': '10'}
</code>```

As mentioned in the comments by @AChampion, you can pass the sort value type by using key something like this :

```<code>sortedList = sorted(result.values(), key = int)
print(sortedList)
</code>```

Or you can do something like this :

```<code>result_ints = dict((k,int(v)) for k,v in result.items())
sortedList = [str(v) for v in sorted(result_ints.values())]
print(sortedList)
</code>```

Both of the above code snippets will result in :

```<code>['0', '9', '10', '10', '14', '16', '19', '22', '34', '47', '53', '56', '75', '171', '267', '407']
</code>```

Body:
I am currently doing an Assignment; however, I got some interesting output which confused me so much.

I am trying to sort the following dictionary:

result = {'A1': '9', 'A2': '14', 'A3': '16', 'A4': '0', 'B1': '53', 'B2': '267', 'B3': '75', 'B4': '22', 'C1': '19', 'C2': '407', 'C3': '171', 'C4': '56', 'C5': '10', 'D3': '47', 'D4': '34', 'D5': '10'}

My sorting code with Python 3 is the following : (only sorted by value)

sortedList = [v for v in sorted(result.values())]

The output is :

['0', '10', '10', '14', '16', '171', '19', '22', '267', '34', '407', '47', '53', '56', '75', '9']

which is not fully sorted. The output is quite strange.

Why it is happened like this?
I have used another dict to test like this:

testD = {'A':'5','B': '9','c': '8','d': '6'}

the output is right :

['5', '6', '8', '9']

Is there something wrong with my result dictionary or is there something I am missing?

Body:
As the value of dictionary are string so there is lexical sorting based on ascii values.

As evident, you need the values to be sorted according to their integer values.

result = {'A1': '9', 'A2': '14', 'A3': '16', 'A4': '0', 'B1': '53', 'B2': '267', 'B3': '75', 'B4': '22', 'C1': '19', 'C2': '407', 'C3': '171', 'C4': '56', 'C5': '10', 'D3': '47', 'D4': '34', 'D5': '10'}

As mentioned in the comments by @AChampion, you can pass the sort value type by using key something like this :

sortedList = sorted(result.values(), key = int)
print(sortedList)

Or you can do something like this :

result_ints = dict((k,int(v)) for k,v in result.items())
sortedList = [str(v) for v in sorted(result_ints.values())]
print(sortedList)

Both of the above code snippets will result in :

['0', '9', '10', '10', '14', '16', '19', '22', '34', '47', '53', '56', '75', '171', '267', '407']