问:
Dynamically Sorting with LINQ
I have a collection of CLR objects. The class definition for the object has three properties: FirstName, LastName, BirthDate.

I have a string that reflects the name of the property the collection should be sorted by. In addition, I have a sorting direction. How do I dynamically apply this sorting information to my collection? Please note that sorting could be multi-layer, so for instance I could sort by LastName, and then by FirstName.

Currently, I'm trying the following without any luck:

```<code>var results = myCollection.OrderBy(sortProperty);
</code>```

However, I'm getting a message that says:

... does not contain a defintion for 'OrderBy'  and the best extension method overload ... has some invalid arguments.

答:
You need to build an Expression Tree and pass it to OrderBy.

It would look something like this:

```<code>var param = Expression.Parameter(typeof(MyClass));
var expression = Expression.Lambda<Func<MyClass, PropertyType>>(
    Expression.Property(param, sortProperty),
    param
);
</code>```

Alternatively, you can use Dynamic LINQ, which will allow your code to work as-is.

Title: Dynamically Sorting with LINQ

Body:
I have a collection of CLR objects. The class definition for the object has three properties: FirstName, LastName, BirthDate.

I have a string that reflects the name of the property the collection should be sorted by. In addition, I have a sorting direction. How do I dynamically apply this sorting information to my collection? Please note that sorting could be multi-layer, so for instance I could sort by LastName, and then by FirstName.

Currently, I'm trying the following without any luck:

var results = myCollection.OrderBy(sortProperty);

However, I'm getting a message that says:

... does not contain a defintion for 'OrderBy'  and the best extension method overload ... has some invalid arguments.

Body:
You need to build an Expression Tree and pass it to OrderBy.

It would look something like this:

var param = Expression.Parameter(typeof(MyClass));
var expression = Expression.Lambda<Func<MyClass, PropertyType>>(
    Expression.Property(param, sortProperty),
    param
);

Alternatively, you can use Dynamic LINQ, which will allow your code to work as-is.


来源: stackexchange

问:
functional interfaces of java 8 in java 7
are the functional interfaces of java 8 available somewhere (i.e. a jar) so I can use them in a Java 7 project? that way I could later on easier port the code to idiomatic java 8. if not, is that technically possible or do they make use of new features like default methods?

yes, i meant the interfaces in java.util.function. since adding packages with the java prefix seems to be disallowed importing them from somewhere else is not an option.

答:
In addition to the answer by @assylias which I think solves the problem in most cases, there is one more option, and that is, to make your own @FunctionalInterface and keep it that way.

It depends on where you use the functions. All of the aforementioned interfaces can be used by JDK utility classes. Predicate allows filtering, Supplier allows object creation, Function allows mapping ... In fact, Predicate and Supplier are rather straighforward, but Function and Consumer can be often unclear, especially BiFunction. They can also tie your hands in some use cases.

You can write your own interface that has any amount of inputs, throws checked exceptions, has generics only where you need them and its name says what it should be used for.

```<code>//@FunctionalInterface
public interface MyCustomInterface {
    <T> MyCustomOutput myCustomAction(MyCustomInput<T> str) throws MyCustomException;
}
</code>```

So, while the interfaces provided with JDK are useful, sometimes you might prefer to keep your own solution even in Java 8, just with the annotations, and lambdas instead of anonymous classes.

ContentLicense: CC BY-SA 3.0

Body:
In addition to the answer by @assylias which I think solves the problem in most cases, there is one more option, and that is, to make your own @FunctionalInterface and keep it that way.

It depends on where you use the functions. All of the aforementioned interfaces can be used by JDK utility classes. Predicate allows filtering, Supplier allows object creation, Function allows mapping ... In fact, Predicate and Supplier are rather straighforward, but Function and Consumer can be often unclear, especially BiFunction. They can also tie your hands in some use cases.

You can write your own interface that has any amount of inputs, throws checked exceptions, has generics only where you need them and its name says what it should be used for.

//@FunctionalInterface
public interface MyCustomInterface {
    <T> MyCustomOutput myCustomAction(MyCustomInput<T> str) throws MyCustomException;
}

So, while the interfaces provided with JDK are useful, sometimes you might prefer to keep your own solution even in Java 8, just with the annotations, and lambdas instead of anonymous classes.


问:
Is there a way to NOT load a specific control in ASP.NET/C#?
I've a container (RadDockZone - Telerik), and inside it, a textbox field with an "Asp:RequiredFieldValidator", which makes it mandatory. Every time that I work with AJAX operations, the entire container is "reloaded", including the RequiredFieldValidator. This makes the ValidationSummary show the same error message twice, until the page is completely reloaded (I'm using RadAjaxManager to solve the AJAX operations).

So, how can I "don't reload" a specific control (in this case, the RequiredFieldValidator) using C#?

Regards!

答: If you do not include the textbox (or its wrapping containers) in the list of controls updated by the ajax manager, the textbox and the respective required validator should not be updated on ajax requests and the error message should not be visualized.</p>

ContentLicense: CC BY-SA 2.5


问:
How to set environment for gfortran as a user in Linux?
I installed gfortran as a user in a server. But I can't able to set the environment. Would someone help me with it?

I am able to use gfortran with the following command:

```<code>/home/kay/gcc-4.8.5/bin/gfortran
</code>```

I tried to set my environment with following, but not working.

```<code>$ vi ~/.bashrc
$ export gfortran=/home/kay/gcc-4.8.5/bin/gfortran
$ source ~/.bashrc
</code>```

When I type:

```<code>$ gfortran
command not found
</code>```

But when I type:

```<code>$/home/kay/gcc-4.8.5/bin/gfortran
fatal error: no input file
</code>```

答:
The export command is used to define and environment variable. What you need is called an "alias".

Add this line to your ~/.bashrc file:

```<code>alias gfortran="/home/kay/gcc-4.8.5/bin/gfortran"
</code>```

Then run source ~/.bashrc and the gfortran command will execute the binary located at /home/kay/gcc-4.8.5/bin/gfortran.

Body:
I installed gfortran as a user in a server. But I can't able to set the environment. Would someone help me with it?

I am able to use gfortran with the following command:

/home/kay/gcc-4.8.5/bin/gfortran

I tried to set my environment with following, but not working.

$ vi ~/.bashrc
$ export gfortran=/home/kay/gcc-4.8.5/bin/gfortran
$ source ~/.bashrc

When I type:

$ gfortran
command not found

But when I type:

$/home/kay/gcc-4.8.5/bin/gfortran
fatal error: no input file

Body:
The export command is used to define and environment variable. What you need is called an "alias".

Add this line to your ~/.bashrc file:

alias gfortran="/home/kay/gcc-4.8.5/bin/gfortran"

Then run source ~/.bashrc and the gfortran command will execute the binary located at /home/kay/gcc-4.8.5/bin/gfortran.


问:
Error in receiving custom headers from microsoft edge browser in rails
My backend application is in RoR and front-end app is in Angular2
I am getting error in receiving headers in microsoft edge browser in production, the code works fine in other browsers like safari, chrome, mozila.
I am not getting the header 'auth_token' in Edge browser but it is working on localhost.

答:
I solved this problem by changing the header name from auth_token to auth-token and on the server side I received this like HTTP_AUTH_TOKEN.

Edge doesn't allow the underscores in the headers while other browsers does.


问:
Firebase/Swift - Outputting data from Firebase gone wrong
I am having an issue outputting data from Firbase properly. I have spent many hours and tried lots of different ways of doing this, creating different data structures etc but I would alway get a crash or nil output. My current code is working and outputting data from firebase into a table view, however the arrays are misaligned and the fields in one array for a particular user do not relate to the other, which is not correct..

I imagine there is a better way of doing this so any help or a point in the right direction with this would be much appreciated. Also please go easy on me, i'm knew to this :)

This is my firebase structure:

This is my Rentals model:

```<code>struct RentalObjects {

    var title: [String : AnyObject] = [:]
    var rentalType: [String : AnyObject] = [:]
    var dateAval: [String : AnyObject] = [:]
    var location: [String : AnyObject] = [:]
    var price: [String : AnyObject] = [:]
    var bond: [String : AnyObject] = [:]
    var pets: [String : AnyObject] = [:]
    var descripton: [String : AnyObject] = [:]

}
</code>```

This is my code for the VC outputting to the table view :

```<code>import UIKit
import FirebaseDatabase

class RentalTableViewVC: UIViewController, UITableViewDataSource, UITableViewDelegate{

    @IBOutlet weak var rentalImage: UIImageView!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var rentalTitle: UILabel!
    @IBOutlet weak var rentalPrice: UILabel!

    var rentalsObject = RentalObjects()
    var databaseRef:DatabaseReference?
    var handle: DatabaseHandle?

    var arrayOfTitles = [String?]()
    var arrayOfBond = [String?]()

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return rentalsObject.title.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell")

        for (_, value) in rentalsObject.title {
            arrayOfTitles.append(value as? String)

        }

        for (_, value) in rentalsObject.bond {

            arrayOfBond.append(value as? String)

        }

        cell.textLabel?.text = ("Title: \(String(describing: arrayOfTitles[indexPath.row]!)), Bond: \(String(describing: arrayOfBond[indexPath.row]!))")

        return cell
    }

    @IBAction func backPressed(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }

    override func viewDidLoad() {
    super.viewDidLoad()

        databaseRef = Database.database().reference().child("Rentals")
        databaseRef?.observe(DataEventType.value, with: { (snapshot) in

            for rentals in snapshot.children.allObjects as! [DataSnapshot] {

        switch rentals.key {

                case "title" :
                    let titleObj = rentals.value as! [String : AnyObject]

                    self.rentalsObject.title = titleObj

                case "rentalType":
                    let rentalTypeObj = rentals.value as! [String : AnyObject]
                    self.rentalsObject.rentalType = rentalTypeObj

                case "dateAval":
                    let dateAvalObj = rentals.value as! [String : AnyObject]
                    self.rentalsObject.dateAval = dateAvalObj
                case "location":
                    let locationObj = rentals.value as! [String : AnyObject]
                    self.rentalsObject.location = locationObj

                case "price" :
                    let priceObj = rentals.value as! [String : AnyObject]
                    self.rentalsObject.price = priceObj

                case "bond" :
                    let bondObj = rentals.value as! [String: AnyObject]
                    self.rentalsObject.bond = bondObj

                case "pets" :
                    let petsObj = rentals.value as! [String: AnyObject]
                    self.rentalsObject.pets = petsObj

                case "description":
                    let desObj = rentals.value as! [String: AnyObject]
                    self.rentalsObject.descripton = desObj

                default:
                    break

                }

            }
            self.tableView.reloadData()
        })

    }

}
</code>```

答:
Use .childAdded instead .value. ChildAdded get each object, while Value get all objects. You should remove for-loops from 'cellForRowAr' method.</p>

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell")

       cell.textLabel?.text = ("Title: \(String(describing: arrayOfTitles[indexPath.row]!)), Bond: \(String(describing: arrayOfBond[indexPath.row]!))")

       return cell
}

override func viewDidLoad() {
   super.viewDidLoad()

   databaseRef = Database.database().reference().child("Rentals")
   databaseRef?.observe(.childAdded, with: { (snapshot) in

       if let dictionary = snapshot.value as? [String: AnyObject] {

          switch snapshot.key {

             case "title" :
             _ = dictionary.map{self.arrayOfTitles.append($0.value as? String)}
             case "rentalType":

             case "dateAval":

             case "location":

             case "price" :

             case "bond" :
             _ = dictionary.map{self.arrayOfBond.append($0.value as? String)}
             case "pets" :

             case "description":

             default:
                break
           }
        }
     })
     self.tableView.reloadData()
}
</code>```

Body:
I am having an issue outputting data from Firbase properly. I have spent many hours and tried lots of different ways of doing this, creating different data structures etc but I would alway get a crash or nil output. My current code is working and outputting data from firebase into a table view, however the arrays are misaligned and the fields in one array for a particular user do not relate to the other, which is not correct..

I imagine there is a better way of doing this so any help or a point in the right direction with this would be much appreciated. Also please go easy on me, i'm knew to this :)

This is my firebase structure:

This is my Rentals model:

struct RentalObjects {

    var title: [String : AnyObject] = [:]
    var rentalType: [String : AnyObject] = [:]
    var dateAval: [String : AnyObject] = [:]
    var location: [String : AnyObject] = [:]
    var price: [String : AnyObject] = [:]
    var bond: [String : AnyObject] = [:]
    var pets: [String : AnyObject] = [:]
    var descripton: [String : AnyObject] = [:]

}

This is my code for the VC outputting to the table view :

import UIKit
import FirebaseDatabase

class RentalTableViewVC: UIViewController, UITableViewDataSource, UITableViewDelegate{

    @IBOutlet weak var rentalImage: UIImageView!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var rentalTitle: UILabel!
    @IBOutlet weak var rentalPrice: UILabel!

    var rentalsObject = RentalObjects()
    var databaseRef:DatabaseReference?
    var handle: DatabaseHandle?

    var arrayOfTitles = [String?]()
    var arrayOfBond = [String?]()

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return rentalsObject.title.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell")

        for (_, value) in rentalsObject.title {
            arrayOfTitles.append(value as? String)

        }

        for (_, value) in rentalsObject.bond {

            arrayOfBond.append(value as? String)

        }

        cell.textLabel?.text = ("Title: \(String(describing: arrayOfTitles[indexPath.row]!)), Bond: \(String(describing: arrayOfBond[indexPath.row]!))")

        return cell
    }

    @IBAction func backPressed(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }

    override func viewDidLoad() {
    super.viewDidLoad()

        databaseRef = Database.database().reference().child("Rentals")
        databaseRef?.observe(DataEventType.value, with: { (snapshot) in

            for rentals in snapshot.children.allObjects as! [DataSnapshot] {

        switch rentals.key {

                case "title" :
                    let titleObj = rentals.value as! [String : AnyObject]

                    self.rentalsObject.title = titleObj

                case "rentalType":
                    let rentalTypeObj = rentals.value as! [String : AnyObject]
                    self.rentalsObject.rentalType = rentalTypeObj

                case "dateAval":
                    let dateAvalObj = rentals.value as! [String : AnyObject]
                    self.rentalsObject.dateAval = dateAvalObj
                case "location":
                    let locationObj = rentals.value as! [String : AnyObject]
                    self.rentalsObject.location = locationObj

                case "price" :
                    let priceObj = rentals.value as! [String : AnyObject]
                    self.rentalsObject.price = priceObj

                case "bond" :
                    let bondObj = rentals.value as! [String: AnyObject]
                    self.rentalsObject.bond = bondObj

                case "pets" :
                    let petsObj = rentals.value as! [String: AnyObject]
                    self.rentalsObject.pets = petsObj

                case "description":
                    let desObj = rentals.value as! [String: AnyObject]
                    self.rentalsObject.descripton = desObj

                default:
                    break

                }

            }
            self.tableView.reloadData()
        })

    }

}

Body:
Use .childAdded instead .value. ChildAdded get each object, while Value get all objects. You should remove for-loops from 'cellForRowAr' method.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell")

       cell.textLabel?.text = ("Title: \(String(describing: arrayOfTitles[indexPath.row]!)), Bond: \(String(describing: arrayOfBond[indexPath.row]!))")

       return cell
}

override func viewDidLoad() {
   super.viewDidLoad()

   databaseRef = Database.database().reference().child("Rentals")
   databaseRef?.observe(.childAdded, with: { (snapshot) in

       if let dictionary = snapshot.value as? [String: AnyObject] {

          switch snapshot.key {

             case "title" :
             _ = dictionary.map{self.arrayOfTitles.append($0.value as? String)}
             case "rentalType":

             case "dateAval":

             case "location":

             case "price" :

             case "bond" :
             _ = dictionary.map{self.arrayOfBond.append($0.value as? String)}
             case "pets" :

             case "description":

             default:
                break
           }
        }
     })
     self.tableView.reloadData()
}


问:
How to stress test my page
I would like to test my web app under high load.

What I'd need to do is.
Load the page => click the button => fill the form => click the button.

I'd need to do this to simulate 5-10k page requests, which is expected to happen after we launch one service (based on previous years data as there's going to be some big pre-sale discount for only a couple of items)

What service or approach would be the most suitable to do this?

答: Gatling.io is another good tool you can use for this. </p>

Title: How to stress test my page


问:
XSLT missing linebreaks when selecting nodes by path expression
I am copying some nodes according to XSLT: Copy child elements of a complex type only once by using a path expression within a copy-of tag:

```<code><xsl:copy-of select="/xs:schema/xs:complexType[@name=current()/xs:element/@type]"/>
</code>```

In the output all linebreaks are missing at the elements processed by this statement. (Elesewhere they are shown) It looks like this:

```<code>...</xs:complexType><xs:complexType....
</code>```

I can only add linebreaks before and after, but not between them. How can i achive this? Thanx for your help!

答:
Your XPath expression only selects the xs:complexType elements, not the whitespace that separates them.

When you're working with a vocabulary such as XSD that doesn't use mixed content (except perhaps in annotations) it's probably best to remove all whitespace text nodes from the input using xsl:strip-space and then to generate new whitespace in the output using xsl:output indent='yes'.

Body:
I am copying some nodes according to XSLT: Copy child elements of a complex type only once by using a path expression within a copy-of tag:

<xsl:copy-of select="/xs:schema/xs:complexType[@name=current()/xs:element/@type]"/>

In the output all linebreaks are missing at the elements processed by this statement. (Elesewhere they are shown) It looks like this:

...</xs:complexType><xs:complexType....

I can only add linebreaks before and after, but not between them. How can i achive this? Thanx for your help!


问:
What's the meaning of CHECK_FOR_FORK?
I am reading the source code of Core Foundation. I see lots of code with CHECK_FOR_FORK. I don't know what does this mean and what is the use of it, can anyone help me?

Here is an example snippet:

```<code>#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI
extern uint8_t __CF120293;
extern uint8_t __CF120290;
extern void __THE_PROCESS_HAS_FORKED_AND_YOU_CANNOT_USE_THIS_COREFOUNDATION_FUNCTIONALITY___YOU_MUST_EXEC__(void);
#define CHECK_FOR_FORK() do { __CF120290 = true; if (__CF120293) __THE_PROCESS_HAS_FORKED_AND_YOU_CANNOT_USE_THIS_COREFOUNDATION_FUNCTIONALITY___YOU_MUST_EXEC__(); } while (0)
#define CHECK_FOR_FORK_RET(...) do { CHECK_FOR_FORK(); if (__CF120293) return __VA_ARGS__; } while (0)
#define HAS_FORKED() (__CF120293)
#endif
</code>```

答:
Forking is a system call where a process creates a copy of itself. CHECK_FOR_FORK is a boolean value in the code which checks whether the given process was forked.

Read more about forking on Wikipedia.

Title: What's the meaning of CHECK_FOR_FORK?

Body:
I am reading the source code of Core Foundation. I see lots of code with CHECK_FOR_FORK. I don't know what does this mean and what is the use of it, can anyone help me?

Here is an example snippet:

#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI
extern uint8_t __CF120293;
extern uint8_t __CF120290;
extern void __THE_PROCESS_HAS_FORKED_AND_YOU_CANNOT_USE_THIS_COREFOUNDATION_FUNCTIONALITY___YOU_MUST_EXEC__(void);
#define CHECK_FOR_FORK() do { __CF120290 = true; if (__CF120293) __THE_PROCESS_HAS_FORKED_AND_YOU_CANNOT_USE_THIS_COREFOUNDATION_FUNCTIONALITY___YOU_MUST_EXEC__(); } while (0)
#define CHECK_FOR_FORK_RET(...) do { CHECK_FOR_FORK(); if (__CF120293) return __VA_ARGS__; } while (0)
#define HAS_FORKED() (__CF120293)
#endif


问:
parsing a cv file
I want to write a code either in Java or PHP (Codeigniter) to extract information such as email and phone number of a user uploading hbis resume or cv to the site. Basically I want to build a cv parser.

Need help for this.

thanks

EDIT
The cv format will be in doc.

答:
I'd suggest you to build it using a set of regular expressions.
If you just want to extract phone number and email the parser is very simple. It will work almost 100% for emails and (I believe) 98% for phone numbers.

If you wish to extract other information it will be more complicated because there is no standards for CVs; information may be formatted using different ways. Anyway, good luck!

Title: parsing a cv file


问:
Can't extract data from Json
I can't extract data from json that I got from an api.
I tried for hours, tried all kinds of formats. Read Stackoverflow threads like How do I extract data from JSON with PHP?, but I can't see what I am doing wrong.

This is the code so far:

```<code>$api_results = '{"status":"0000","data":{"opening_price":"6998000","closing_price":"7270000","min_price":"6750000","max_price":"7997000","average_price":"7188302.5804","units_traded":"78484.9241002","volume_1day":"78484.9241002","volume_7day":"335611.84181738","buy_price":"7268000","sell_price":"7274000","date":"1510563513031"}}';

$results = json_decode($api_results, true);

// Some variations I tried:
var_dump($results->status[1]);
var_dump($results->data[1]->opening_price);
var_dump($results["data"][1]["opening_price"]);
</code>```

End result: NULL NULL NULL

What am I doing wrong?

Thanks for the answers! I will upvote the working ones. Seems I got confused in the formating!

答:
Have you read the documentation of  json_decode() (or, at least, the accepted answer of the question you linked)? If you pass TRUE as the second argument to json_decode() (and there is no decent reason to not pass it) then it decodes the JSON to associative arrays and not objects.

The elements in a PHP array can be accessed using the square bracket syntax.

A simple call to print_r($results) tells its structure:

```<code>Array
(
    [status] => 0000
    [data] => Array
        (
            [opening_price] => 6998000
            [closing_price] => 7270000
            [min_price] => 6750000
            [max_price] => 7997000
            [average_price] => 7188302.5804
            [units_traded] => 78484.9241002
            [volume_1day] => 78484.9241002
            [volume_7day] => 335611.84181738
            [buy_price] => 7268000
            [sell_price] => 7274000
            [date] => 1510563513031
        )
)
</code>```

Now, accessing its items is a piece of cake:

```<code>echo($results['status']);
# 0000
echo($results['data']['opening_price']);
# 6998000
</code>```

Title: Can't extract data from Json

Body:
I can't extract data from json that I got from an api.
I tried for hours, tried all kinds of formats. Read Stackoverflow threads like How do I extract data from JSON with PHP?, but I can't see what I am doing wrong.

This is the code so far:

$api_results = '{"status":"0000","data":{"opening_price":"6998000","closing_price":"7270000","min_price":"6750000","max_price":"7997000","average_price":"7188302.5804","units_traded":"78484.9241002","volume_1day":"78484.9241002","volume_7day":"335611.84181738","buy_price":"7268000","sell_price":"7274000","date":"1510563513031"}}';

$results = json_decode($api_results, true);

// Some variations I tried:
var_dump($results->status[1]);
var_dump($results->data[1]->opening_price);
var_dump($results["data"][1]["opening_price"]);

End result: NULL NULL NULL

What am I doing wrong?

Thanks for the answers! I will upvote the working ones. Seems I got confused in the formating!

Body:
Have you read the documentation of  json_decode() (or, at least, the accepted answer of the question you linked)? If you pass TRUE as the second argument to json_decode() (and there is no decent reason to not pass it) then it decodes the JSON to associative arrays and not objects.

The elements in a PHP array can be accessed using the square bracket syntax.

A simple call to print_r($results) tells its structure:

Array
(
    [status] => 0000
    [data] => Array
        (
            [opening_price] => 6998000
            [closing_price] => 7270000
            [min_price] => 6750000
            [max_price] => 7997000
            [average_price] => 7188302.5804
            [units_traded] => 78484.9241002
            [volume_1day] => 78484.9241002
            [volume_7day] => 335611.84181738
            [buy_price] => 7268000
            [sell_price] => 7274000
            [date] => 1510563513031
        )
)

Now, accessing its items is a piece of cake:

echo($results['status']);
# 0000
echo($results['data']['opening_price']);
# 6998000


问:
How to host WordPress blog in Azure webapp's subfolder?
I want to host a WordPress blog to my existing Azure webapp's sub directory so that user can visit the blog with the url "http://mywebappurl/blog/...". I have tried to follow the steps mentioned here

However, now when I visit the url  "http://mywebappurl/blog/", I get "Oops, that page can't be found" error as shown in the image.

When I see the error log I get error page as shown in the image:

From the image I get feeling that some problem is there with the mapping because it is not actually referring to the path ../blog/.. but I'm not aware how to fix this issue.

I can provide more details of Azure web app configuration as needed.

答:
I have covered this scenario in my blog post here: https://blogs.msdn.microsoft.com/kaushal/2014/04/19/microsoft-azure-web-sites-deploying-wordpress-to-a-virtual-directory-within-the-azure-web-site/ </p>

<p>This is regards to the old portal, but is still relevant with the new one too. </p>

Body:
I have covered this scenario in my blog post here: https://blogs.msdn.microsoft.com/kaushal/2014/04/19/microsoft-azure-web-sites-deploying-wordpress-to-a-virtual-directory-within-the-azure-web-site/

This is regards to the old portal, but is still relevant with the new one too.


答:
For this sort of dynamic work I've been using the Dynamic LINQ library which makes this sort of thing easy:

http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

http://msdn2.microsoft.com/en-us/vcsharp/bb894665.aspx

Title: Dynamically Sorting with LINQ


问:
Apache Flink: What is the difference of groupBy and partitioning in the DataSet API?
There are various partitioning function in Flink's Dataset API, such as partitionByHash and partitionByRange.

I would like to understand what is partitioning at the first place and what is the difference between groupBy and partitioning.

答:
Partitioning is a more low-level operation than groupBy and does not apply a function on the data. It rather defines how data is distributed across parallel task instances. Data can be partitioned with different methods such as hash partitioning or range partitioning.

groupBy is not an operation by itself. It always needs a function that is applied on the grouped DataSet such as reduce, groupReduce, or groupCombine. The groupBy API defines how records are grouped before they are given into the respective function. Grouping of records happens in two steps.

All records with the same grouping key must be moved to the same task instance. This is done by partitioning the data. Since there are usually more distinct grouping keys than task instances, a task instance must handle records with distinct grouping keys.

All records in the same task instance must be grouped on the key. This is usually done by sorting the data.

So, the first step of groupBy is partitioning.


问:
Typesafety with Function varargs as parametrs
I need to write a class with function like this

```<code>class Converter <T>{

    public <R> R convertBy(Function<T,?>... args){
        Function<T,?> function = args[0];
        // doing something
        return function.apply(t);
    }
}
</code>```

I need this method to be type safe i.e first Function need from args needs to have the same argument type as this class type. For example, if my Converter would be Converter<String> I need to check (at the compile time) if the first function has String parameter.

Also, when I wrote method like that is saying that it returns object, and I cannot do

```<code>int a = converter.convertBy(func1,func2);
</code>```

because is saying that Object is not convertible to int.

-- Edit

Maybe with bigger picture will be easier to get what is it about. So the meaning of convertBy function is that it can with easy combine diffrent operation on different types.

This is working, when I define function like

```<code>public <R> R convertBy(Function... args)
</code>```

but then It is not type safe. What I need, is to make sure If my Converter is 'Converter ' user cannot pass as first parametr function like
    Function func = (string)->{ return (String)string.length();}

Also I cannot change paramters from

```<code>convertBy(Function... args)
</code>```

to
    convertBy(Function first, Function... rest)

edit.
Well I what appeared later is that I can do that. But it still doesn't check.

Thank You.

答:
The way to make sure at compile time that your Function has return type R is to declare it as Function<T,R>.

If you also want to accept an unspecified number of other functions with different types, you could write your function like this:

```<code>public <R> R convertBy(Function<T,R> first, Function<?,?>... others)
</code>```

That way the return type matches the return type of the first function.
But without knowing what you're trying to do with those other functions, it is hard to know what types they are supposed to have.

Body:
I need to write a class with function like this

class Converter <T>{

    public <R> R convertBy(Function<T,?>... args){
        Function<T,?> function = args[0];
        // doing something
        return function.apply(t);
    }
}

I need this method to be type safe i.e first Function need from args needs to have the same argument type as this class type. For example, if my Converter would be Converter<String> I need to check (at the compile time) if the first function has String parameter.

Also, when I wrote method like that is saying that it returns object, and I cannot do

int a = converter.convertBy(func1,func2);

because is saying that Object is not convertible to int.

-- Edit

Maybe with bigger picture will be easier to get what is it about. So the meaning of convertBy function is that it can with easy combine diffrent operation on different types.

This is working, when I define function like

public <R> R convertBy(Function... args)

but then It is not type safe. What I need, is to make sure If my Converter is 'Converter ' user cannot pass as first parametr function like
    Function func = (string)->{ return (String)string.length();}

Also I cannot change paramters from

convertBy(Function... args)

to
    convertBy(Function first, Function... rest)

edit.
Well I what appeared later is that I can do that. But it still doesn't check.

Thank You.

Body:
The way to make sure at compile time that your Function has return type R is to declare it as Function<T,R>.

If you also want to accept an unspecified number of other functions with different types, you could write your function like this:

public <R> R convertBy(Function<T,R> first, Function<?,?>... others)

That way the return type matches the return type of the first function.
But without knowing what you're trying to do with those other functions, it is hard to know what types they are supposed to have.


问:
odd behavior when substituting parts of a string within a for loop
I'm trying to replace a series of numbers in a character string with information that comes from a dataframe.

My string comes from a text file that I imported using the readr package as follows: read_file("Human.txt")
I've checked the class, it is character. The string contains the following information (I've named it treeString):

"(1,2,((((3),884),(((((519,((516,517),(515,(518,(513,514))))),((((((((458,(457,(455,456))),459),(502,(454,(453,(451,452)))))"

My dataframe (labels.csv) was originally in factor format, but I changed the format of the second column to character using the following command: labels[,2] = as.character(labels[,2]). It looks like this

```<code>     v1     v2
1    1      name1
2    2      name2
3    3      name3
</code>```

My goal is to substitute every number in the string with the corresponding name (i.e. V2) in the dataframe. This should result in the following:

"(name1,name2,((((name3),884),(((((519,((516,517),(515,(518,(513,514))))),((((((((458,(457,(455,456))),459),(502,(454,(453,(451,452)))))"

Here is the code I am using to accomplish this:

```<code>for(i in 1:nrow(labels)){
  gsub(as.character(i), labels[i,2], treeString)
}
</code>```

The weird thing is that if I run the gsub() command on its own (with specified numbers - eg. 2) it does the substitution, however, when I run it in a loop it does not substitute the numbers.

答:
As pointed out by Kumar Manglam in the comments, you forgot to assign the result of gsub() back to treeString.

There is something else you should be aware of: The way you specified the regular expression in your question it will also replace patterns like "(241)" with "(name24name1)". To avoid this behaviour, you should check whether the numbers you want to replace are preceded by a comma or opening parenthesis and succeeded by a comma or closing parenthesis:

```<code># Option1
for(i in 1:nrow(labelnames)){
   reg_pattern <- paste0("(?<=[(,])(", i, ")(?=[),])")
   treeString  <- gsub(reg_pattern, labelnames$v2[i], treeString, perl=T)
}
</code>```

Another, nicer, option is drop the for-loop and do it all at once:

```<code># Option2
reg_pattern <- paste0("(?<=[(,])([1-", nrow(labelnames), "])(?=[),])")
treeString  <- gsub(reg_pattern, "name\\1", treeString, perl=T)

# Result
treeString
# "(name1,name2,((((name3),884),(((((519,((516,517),(515,(518,(513,514))))),((((((((458,(457,(455,456))),459),(502,(454,(453,(451,452)))))"
</code>```

Data

```<code> treeString <- "(1,2,((((3),884),(((((519,((516,517),(515,(518,(513,514))))),((((((((458,(457,(455,456))),459),(502,(454,(453,(451,452)))))"
 labelnames <- structure(list(v1 = 1:3, v2 = c("name1", "name2", "name3")), .Names = c("v1", "v2"), class = "data.frame", row.names = c(NA, -3L))
</code>```

Body:
I'm trying to replace a series of numbers in a character string with information that comes from a dataframe.

My string comes from a text file that I imported using the readr package as follows: read_file("Human.txt")
I've checked the class, it is character. The string contains the following information (I've named it treeString):

"(1,2,((((3),884),(((((519,((516,517),(515,(518,(513,514))))),((((((((458,(457,(455,456))),459),(502,(454,(453,(451,452)))))"

My dataframe (labels.csv) was originally in factor format, but I changed the format of the second column to character using the following command: labels[,2] = as.character(labels[,2]). It looks like this

     v1     v2
1    1      name1
2    2      name2
3    3      name3

My goal is to substitute every number in the string with the corresponding name (i.e. V2) in the dataframe. This should result in the following:

"(name1,name2,((((name3),884),(((((519,((516,517),(515,(518,(513,514))))),((((((((458,(457,(455,456))),459),(502,(454,(453,(451,452)))))"

Here is the code I am using to accomplish this:

for(i in 1:nrow(labels)){
  gsub(as.character(i), labels[i,2], treeString)
}

The weird thing is that if I run the gsub() command on its own (with specified numbers - eg. 2) it does the substitution, however, when I run it in a loop it does not substitute the numbers.

Body:
As pointed out by Kumar Manglam in the comments, you forgot to assign the result of gsub() back to treeString.

There is something else you should be aware of: The way you specified the regular expression in your question it will also replace patterns like "(241)" with "(name24name1)". To avoid this behaviour, you should check whether the numbers you want to replace are preceded by a comma or opening parenthesis and succeeded by a comma or closing parenthesis:

# Option1
for(i in 1:nrow(labelnames)){
   reg_pattern <- paste0("(?<=[(,])(", i, ")(?=[),])")
   treeString  <- gsub(reg_pattern, labelnames$v2[i], treeString, perl=T)
}

Another, nicer, option is drop the for-loop and do it all at once:

# Option2
reg_pattern <- paste0("(?<=[(,])([1-", nrow(labelnames), "])(?=[),])")
treeString  <- gsub(reg_pattern, "name\\1", treeString, perl=T)

# Result
treeString
# "(name1,name2,((((name3),884),(((((519,((516,517),(515,(518,(513,514))))),((((((((458,(457,(455,456))),459),(502,(454,(453,(451,452)))))"

Data

 treeString <- "(1,2,((((3),884),(((((519,((516,517),(515,(518,(513,514))))),((((((((458,(457,(455,456))),459),(502,(454,(453,(451,452)))))"
 labelnames <- structure(list(v1 = 1:3, v2 = c("name1", "name2", "name3")), .Names = c("v1", "v2"), class = "data.frame", row.names = c(NA, -3L))


问:
Exception when using POI FontFormatting setFontColor
Trying to use POI conditional formatting. I have the following method:

```<code>private final static Color PEAK_ORANGE = new Color(255, 239, 221);

public ConditionalFormattingRule getConditionalFormatting(ConditionalFormattingRule formattingContainer, FormatSpecs format){

    FontFormatting fontFmt = formattingContainer.createFontFormatting();
    fontFmt.setFontStyle(true, false);
    // fontFmt.setFontColorIndex((short)11);
    fontFmt.setFontColor(new XSSFColor(PEAK_ORANGE));

    PatternFormatting patternFmt = formattingContainer.createPatternFormatting();
    patternFmt.setFillBackgroundColor(new XSSFColor(PEAK_ORANGE));
    return formattingContainer;
}
</code>```

When I use the setFontColor() method I get index out of bounds exception.

When I use the setFontColorIndex() method using some arbitrary index value, I do not get the exception. Notice however that I use the exact same color reference in the call to set the background color

patternFmt.setFillBackgroundColor(new XSSFColor(PEAK_ORANGE));

and this works fine, no exceptions.

Has anyone else run into this? Am I missing something in the call to set the font color? I prefer to use my colors rather than those from the IndexedColors class.

答:
This looks like a small bug in Apache POI, a simple workaround is to first set an index-color and then set the actual intended full color, i.e.

```<code>    fontFmt.setFontColorIndex((short)1);
    fontFmt.setFontColor(new XSSFColor(PEAK_ORANGE));
</code>```

The setFontColorIndex() will initialize the internal structures so that setFontColor() will work.

FYI, the bug should be fixed in time for release 4.0 of Apache POI.

Body:
Trying to use POI conditional formatting. I have the following method:

private final static Color PEAK_ORANGE = new Color(255, 239, 221);

public ConditionalFormattingRule getConditionalFormatting(ConditionalFormattingRule formattingContainer, FormatSpecs format){

    FontFormatting fontFmt = formattingContainer.createFontFormatting();
    fontFmt.setFontStyle(true, false);
    // fontFmt.setFontColorIndex((short)11);
    fontFmt.setFontColor(new XSSFColor(PEAK_ORANGE));

    PatternFormatting patternFmt = formattingContainer.createPatternFormatting();
    patternFmt.setFillBackgroundColor(new XSSFColor(PEAK_ORANGE));
    return formattingContainer;
}

When I use the setFontColor() method I get index out of bounds exception.

When I use the setFontColorIndex() method using some arbitrary index value, I do not get the exception. Notice however that I use the exact same color reference in the call to set the background color

patternFmt.setFillBackgroundColor(new XSSFColor(PEAK_ORANGE));

and this works fine, no exceptions.

Has anyone else run into this? Am I missing something in the call to set the font color? I prefer to use my colors rather than those from the IndexedColors class.

Body:
This looks like a small bug in Apache POI, a simple workaround is to first set an index-color and then set the actual intended full color, i.e.

    fontFmt.setFontColorIndex((short)1);
    fontFmt.setFontColor(new XSSFColor(PEAK_ORANGE));

The setFontColorIndex() will initialize the internal structures so that setFontColor() will work.

FYI, the bug should be fixed in time for release 4.0 of Apache POI.


问:
Is there a way to make the compiler pick a certain overload where its somewhat ambiguous?
I got this:

```<code>json& add(char* key, char* value) {
    s.append("\"").append(key).append("\":\"").append(value).append("\",");
    return *this;
}

json& add(char* key, const char* value) {
    s.append("\"").append(key).append("\":\"").append(value).append("\",");
    return *this;
}

template <typename vt>
json& add(char* key, vt value) {
    s.append("\"").append(key).append("\":").append(std::to_string(value)).append(",");
    return *this;
}
</code>```

So 3 overloads for this function.

The first one is supposed to handle a char* value.

The last one is supposed to handle all the numeric types like uint_8t, int_8t, uint16_t .... float, double

if I use this function for example:

```<code>void test(json obj, char* value) {
    obj.add("test", value);
}
</code>```

Then everything works alright with just the first and the last overload. If I try to do this however:

```<code>void test(json obj) {
    obj.add("test", "blah");
}
</code>```

Then it will try to use the last overload (the one with the template) instead of the char* one since technically I'm passing a const char* to it.

So now I need to have the middle overload just for that.

Question is - is there a way to define a range of types for the template that its supposed to handle? To restrict vt to only the numeric types I mentioned? That should divert the compiler to use the char* overload instead and I wouldn't need the const char* one.

答:
The non-const char* overload is not needed as you don't modify the parameter.
So the remaining ones are the second and the last version of you overload.

You stated that the templated overload is only meant for integral or floating point number types. I would recommend to use std::enable_if_t<> to restrict access to these types.

I would also recommend to make your key a const char*.

```<code>#include <string>

class json
{
private:
    std::string s;

public:
    json& add(const char* key, const char* value) {
        s.append("\"").append(key).append("\":\"").append(value).append("\",");
        return *this;
    }

    template <typename vt, typename = std::enable_if_t<std::is_arithmetic_v<vt>>>
    json& add(const char* key, vt value) {
        s.append("\"").append(key).append("\":").append(std::to_string(value)).append(",");
        return *this;
    }
};

int main(int, char**)
{
    json j; double d = 0.1245;
    j.add("Hello1", "World");
    j.add("Hello2", 1234);
    j.add("Hello3", 1234.1f);
    j.add("Hello4", d);
}
</code>```

Body:
I got this:

json& add(char* key, char* value) {
    s.append("\"").append(key).append("\":\"").append(value).append("\",");
    return *this;
}

json& add(char* key, const char* value) {
    s.append("\"").append(key).append("\":\"").append(value).append("\",");
    return *this;
}

template <typename vt>
json& add(char* key, vt value) {
    s.append("\"").append(key).append("\":").append(std::to_string(value)).append(",");
    return *this;
}

So 3 overloads for this function.

The first one is supposed to handle a char* value.

The last one is supposed to handle all the numeric types like uint_8t, int_8t, uint16_t .... float, double

if I use this function for example:

void test(json obj, char* value) {
    obj.add("test", value);
}

Then everything works alright with just the first and the last overload. If I try to do this however:

void test(json obj) {
    obj.add("test", "blah");
}

Then it will try to use the last overload (the one with the template) instead of the char* one since technically I'm passing a const char* to it.

So now I need to have the middle overload just for that.

Question is - is there a way to define a range of types for the template that its supposed to handle? To restrict vt to only the numeric types I mentioned? That should divert the compiler to use the char* overload instead and I wouldn't need the const char* one.

Body:
The non-const char* overload is not needed as you don't modify the parameter.
So the remaining ones are the second and the last version of you overload.

You stated that the templated overload is only meant for integral or floating point number types. I would recommend to use std::enable_if_t<> to restrict access to these types.

I would also recommend to make your key a const char*.

#include <string>

class json
{
private:
    std::string s;

public:
    json& add(const char* key, const char* value) {
        s.append("\"").append(key).append("\":\"").append(value).append("\",");
        return *this;
    }

    template <typename vt, typename = std::enable_if_t<std::is_arithmetic_v<vt>>>
    json& add(const char* key, vt value) {
        s.append("\"").append(key).append("\":").append(std::to_string(value)).append(",");
        return *this;
    }
};

int main(int, char**)
{
    json j; double d = 0.1245;
    j.add("Hello1", "World");
    j.add("Hello2", 1234);
    j.add("Hello3", 1234.1f);
    j.add("Hello4", d);
}


问:
How to update / upgrade from Angular 4 to Angular 5+
I need to update my project from Angular 4 to Angular 5+ ,

I need to change all following dependencies to Angular 5+.

I also updated Angular CLI to 1.5.0.

I tried to create new project but it seems to create only Angular 4 project.

ng new NG5_Project

"dependencies": {
  "@angular/animations": "^4.2.4",
  "@angular/common": "^4.2.4",
  "@angular/compiler": "^4.2.4",
  "@angular/core": "^4.2.4",
  "@angular/forms": "^4.2.4",
  "@angular/http": "^4.2.4",
  "@angular/platform-browser": "^4.2.4",
  "@angular/platform-browser-dynamic": "^4.2.4",
  "@angular/router": "^4.2.4",
  "core-js": "^2.4.1",
  "rxjs": "^5.4.2",
  "zone.js": "^0.8.14"
}
```

What am I doing wrong.

CLI Config :

答:
This specific problem was fixed with Node version update.

I had to update Node version,

```<code>sudo apt-get install nodejs

npm uninstall -g @angular/cli

npm cache clean

npm install -g @angular/cli@latest

ng new ProjectName
</code>```

node --version ==> 8.9.0

ng --version ==> 1.5.0

"dependencies": {
    "@angular/animations": "^5.0.0",
    "@angular/common": "^5.0.0",
    "@angular/compiler": "^5.0.0",
    "@angular/core": "^5.0.0",
    "@angular/forms": "^5.0.0",
    "@angular/http": "^5.0.0",
    "@angular/platform-browser": "^5.0.0",
    "@angular/platform-browser-dynamic": "^5.0.0",
    "@angular/router": "^5.0.0",
    "rxjs": "^5.5.2",
    "zone.js": "^0.8.14"
}
```

UPDATE :

There is also official Angular update guide available now : https://update.angular.io

You can update Angular versions from minimum of v2.0 to latest version (v15.0 currently) with proper steps

ContentLicense: CC BY-SA 4.0

Body:
I need to update my project from Angular 4 to Angular 5+ ,

I need to change all following dependencies to Angular 5+.

I also updated Angular CLI to 1.5.0.

I tried to create new project but it seems to create only Angular 4 project.

ng new NG5_Project

"dependencies": {
  "@angular/animations": "^4.2.4",
  "@angular/common": "^4.2.4",
  "@angular/compiler": "^4.2.4",
  "@angular/core": "^4.2.4",
  "@angular/forms": "^4.2.4",
  "@angular/http": "^4.2.4",
  "@angular/platform-browser": "^4.2.4",
  "@angular/platform-browser-dynamic": "^4.2.4",
  "@angular/router": "^4.2.4",
  "core-js": "^2.4.1",
  "rxjs": "^5.4.2",
  "zone.js": "^0.8.14"
}

What am I doing wrong.

CLI Config :

Body:
This specific problem was fixed with Node version update.

I had to update Node version,

sudo apt-get install nodejs

npm uninstall -g @angular/cli

npm cache clean

npm install -g @angular/cli@latest

ng new ProjectName

node --version ==> 8.9.0

ng --version ==> 1.5.0

"dependencies": {
    "@angular/animations": "^5.0.0",
    "@angular/common": "^5.0.0",
    "@angular/compiler": "^5.0.0",
    "@angular/core": "^5.0.0",
    "@angular/forms": "^5.0.0",
    "@angular/http": "^5.0.0",
    "@angular/platform-browser": "^5.0.0",
    "@angular/platform-browser-dynamic": "^5.0.0",
    "@angular/router": "^5.0.0",
    "rxjs": "^5.5.2",
    "zone.js": "^0.8.14"
}

UPDATE :

There is also official Angular update guide available now : https://update.angular.io

You can update Angular versions from minimum of v2.0 to latest version (v15.0 currently) with proper steps


问:
Laravel 5.4 validator not seeing input field
So I'm trying to setup validation using the Validator facade. For some strange reason, the validator is not seeing one of the input fields though it's present in the request. Here's the validation code:

```<code>        $rules = [
            'name'          => 'required',
            'resource_type' => 'required',
            'semester'      => 'required',
            'file'          => 'required|max:8196'
        ];
        $messages = [
            'name.required' => 'The name field is required',
            'semester.required' => 'The semester field is required',
            'resource_type.required' => 'The resource_type field is required',
            'file.required' => 'The file field is required',
            'file.max' => 'The max file size is 8196 kilobytes',
        ];

        $validator = Validator::make($request->input(), $rules, $messages);
        if ($validator->fails()) {
            return response()->json($validator->messages(), 422);
        }
</code>```

And here's the test I'm running:

```<code>$file = UploadedFile::fake()->create('file.pdf', 512);
    $response = $this->json( "POST", 'api/v2/papers', [
        "name"          => $paper->name,
        "semester"      => $paper->semester,
        "resource_type" => $paper->resource_type,
        "file"          => $file,
    ] )->assertSuccessful();
</code>```

When I print the value of $response->content() I get

{"file":["The file field is required"]}

The file field is present so I'm not sure what is really going on?

Thanks in advance.

答:
Don't use $request->input(), it does not include files.

Use $request->all()

Body:
So I'm trying to setup validation using the Validator facade. For some strange reason, the validator is not seeing one of the input fields though it's present in the request. Here's the validation code:

        $rules = [
            'name'          => 'required',
            'resource_type' => 'required',
            'semester'      => 'required',
            'file'          => 'required|max:8196'
        ];
        $messages = [
            'name.required' => 'The name field is required',
            'semester.required' => 'The semester field is required',
            'resource_type.required' => 'The resource_type field is required',
            'file.required' => 'The file field is required',
            'file.max' => 'The max file size is 8196 kilobytes',
        ];

        $validator = Validator::make($request->input(), $rules, $messages);
        if ($validator->fails()) {
            return response()->json($validator->messages(), 422);
        }

And here's the test I'm running:

$file = UploadedFile::fake()->create('file.pdf', 512);
    $response = $this->json( "POST", 'api/v2/papers', [
        "name"          => $paper->name,
        "semester"      => $paper->semester,
        "resource_type" => $paper->resource_type,
        "file"          => $file,
    ] )->assertSuccessful();

When I print the value of $response->content() I get

{"file":["The file field is required"]}

The file field is present so I'm not sure what is really going on?

Thanks in advance.


问:
highcharts is not showing
I'm new at web developer. I created a simpe website to showing a char but I have a problem. My problem is when i'm using highcharts to display all of my data. My highcharts is not showing. I have searched in another articles but I still don't get solution of my problem.

I have checked my browser console, and I got error like this

error

This is my index.php

```<code><script type="text/javascript" src="extension/Highcharts/code/js/highcharts.js"></script>
<script type="text/javascript" src="extension/Highcharts/code/js/highcharts-more.js"></script>
<script type="text/javascript" src="extension/Highcharts/code/js/modules/exporting.js"></script>
<script type="text/javascript" src="extension/Highcharts/code/js/modules/offline-exporting.js"></script>

<script type="text/javascript">
    Highcharts.chart('container2', {
        chart: {
            type: 'bar'
        },
        title: {
            text: 'Dashboard'
        },
        xAxis: {
            categories: ['Fatmawati', 'Tebet', 'Bekasi', 'TB Simatupang', 'Senen'],
            title: {
                text: null
            }
        },
        yAxis: {
            min: 0,
            title: {
                text: 'Orang',
                align: 'high'
            },
            labels: {
                overflow: 'justify'
            }
        },
        tooltip: {
            valueSuffix: ' millions'
        },
        plotOptions: {
            bar: {
                dataLabels: {
                    enabled: true
                }
            }
        },
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'top',
            x: -40,
            y: 80,
            floating: true,
            borderWidth: 1,
            backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'),
            shadow: true
        },
        credits: {
            enabled: false
        },
        series: [{
            name: 'Peserta',
            data: [20, 15, 30, 67, 47]
        }]
    });
</script>

<html>
<head>
    <title>Absensi</title>
</head>
<body>
    <div id="container2" style="min-width: 310px; max-width: 800px; height: 400px; margin: 0 auto"></div>
</body>
</html>
</code>```

How to fix this? I'm using offline highcharts and i have downloaded highcharts files and paste them in my folder.

Any help is very useful for me.

UPDATE

I did some mistake when import js file from my folder and it is working now. Thanks for all helps.

答:
Accoring to highcharts error, Highcharts is unable to find HTML element to render. You're calling the function before the DOM is initialised. Try putting your script tag after the HTML body.

Highcharts error: https://www.highcharts.com/errors/13

Title: highcharts is not showing

Body:
I'm new at web developer. I created a simpe website to showing a char but I have a problem. My problem is when i'm using highcharts to display all of my data. My highcharts is not showing. I have searched in another articles but I still don't get solution of my problem.

I have checked my browser console, and I got error like this

error

This is my index.php

    <title>Absensi</title>

How to fix this? I'm using offline highcharts and i have downloaded highcharts files and paste them in my folder.

Any help is very useful for me.

UPDATE

I did some mistake when import js file from my folder and it is working now. Thanks for all helps.


问:
i m trying to access subfolder in assets folder actually i want to play a .mp3 file from that
How can i access specific directory at * ? I also retried access that directory via direct path, but it is not working.</p>

```<code>     try {
            // for assets folder add empty string
            String[] filelist = assetManager.list("");
            // for assets/subFolderInAssets add only subfolder name
            String[] filelistInSubfolder = assetManager.list("subFolderInAssets");
            String[] filelistInSubfolder1 = assetManager.list("subFolderInabcd");
            if (filelist == null) {
                // dir does not exist or is not a directory
                // *

            } else {
                for (int i=0; i<filelist.length; i++) {
                    // Get filename of file or directory
                    String filename = filelist[i];
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
</code>```

答:
```<code>  try {
            File rootFolder = new File(rootPath);
            File[] files = rootFolder.listFiles(); //here you will get NPE if directory doesn't contains  any file,handle it like this.
            for (File file : files) {
                if (file.isDirectory()) {
                    if (getPlayList(file.getAbsolutePath()) != null) {
                        fileList.addAll(getPlayList(file.getAbsolutePath()));
                    } else {
                        break;
                    }
                } else {

                   // do your stuff here
                }
            }
            return fileList;
        } catch (Exception e) {
            return null;
        }
</code>```

Body:
How can i access specific directory at * ? I also retried access that directory via direct path, but it is not working.

     try {
            // for assets folder add empty string
            String[] filelist = assetManager.list("");
            // for assets/subFolderInAssets add only subfolder name
            String[] filelistInSubfolder = assetManager.list("subFolderInAssets");
            String[] filelistInSubfolder1 = assetManager.list("subFolderInabcd");
            if (filelist == null) {
                // dir does not exist or is not a directory
                // *

            } else {
                for (int i=0; i<filelist.length; i++) {
                    // Get filename of file or directory
                    String filename = filelist[i];
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


问:
Add array name in beginning using PHP multidimensional arrays to convert MySQL to JSON
I want the array name institution to be displayed at the beginning.
My JSON Code currently displays the the following format.

```<code>{
    "institution": [],
    "id": "2",
    "name": "kjhl kjhl",
    "updated_date": "2017-11-12 21:43:13",
    "description": [{
        "id": "3",
        "description": "h,nm.,"
    }]
}
</code>```

I want JSON code to be displayed the following format.

```<code>{"institution":[{
    "id": "2",
    "name": "kjhl kjhl",
    "updated_date": "2017-11-12 21:43:13",
    "description": [{
        "id": "3",
        "description": "h,nm.,"
    }]
}]}
</code>```

Here is my code.

```<code><?php
include_once "db.php";

$usersList_array =array();
$user_array = array();
$note_array = array();
  if(isset($_POST['updated_date'])) {

$fetch_users = mysql_query( "SELECT * FROM test1 WHERE updated_date > timestamp('".$_POST["updated_date"]."')  ORDER BY id desc" );

 $user_array['institution'] = array();
while ($row_users = mysql_fetch_assoc($fetch_users)) {

    $user_array['id'] = $row_users['id'];
    $user_array['name'] = $row_users['name'].' '.$row_users['name'];
    $user_array['updated_date']=$row_users["updated_date"];
    $user_array['description'] = array();

    $fetch_notes = mysql_query("SELECT t2.id, t2.description FROM test2 t2 ,test1 t1 where t1.id=t2.oid and oid = ".$row_users['id']."");
    while ($row_notes = mysql_fetch_assoc($fetch_notes)) {
        $note_array['id']=$row_notes['id'];
        $note_array['description']=$row_notes['description'];
        array_push($user_array['description'],$note_array);

    }
          array_push($usersList_array,$user_array);
}

$jsonData = json_encode($usersList_array, 128);
echo $jsonData;

?>
</code>```

What do I need to change? Where is my error?

答:
I solved your problem.work fine now
at first i simulated your code.this is with my values.

```<code><?php

$usersList_array =array();
$user_array = array();
$note_array = array();

$user_array1['institution'] = array();

$user_array['id'] = "1";
$user_array['name'] = "mori";
$user_array['updated_date']="2017";

$user_array['description'] = array();

$note_array['id']="2";
$note_array['description']="descriptiondescription";

array_push($user_array['description'],$note_array);
array_push($user_array1['institution'],$user_array);
//$user_array1['institution'] =array($user_array);
//array_push($usersList_array,$user_array1);

 $jsonData = json_encode($user_array1, 128);
echo $jsonData;
?>
</code>```

And it is your code

```<code><?php
include_once "db.php";

$usersList_array =array();
$user_array = array();
$note_array = array();
  if(isset($_POST['updated_date'])) {

$fetch_users = mysql_query( "SELECT * FROM test1 WHERE updated_date > timestamp('".$_POST["updated_date"]."')  ORDER BY id desc" );

 $user_array1['institution'] = array();
while ($row_users = mysql_fetch_assoc($fetch_users)) {

    $user_array['id'] = $row_users['id'];
    $user_array['name'] = $row_users['name'].' '.$row_users['name'];
    $user_array['updated_date']=$row_users["updated_date"];
    $user_array['description'] = array();

    $fetch_notes = mysql_query("SELECT t2.id, t2.description FROM test2 t2 ,test1 t1 where t1.id=t2.oid and oid = ".$row_users['id']."");
    while ($row_notes = mysql_fetch_assoc($fetch_notes)) {
        $note_array['id']=$row_notes['id'];
        $note_array['description']=$row_notes['description'];
      //  array_push($user_array['description'],$note_array);
        array_push($user_array['description'],$note_array);

    }
          array_push($user_array1['institution'],$user_array);
         // array_push($usersList_array,$user_array1);

         // array_push($usersList_array,$user_array);
}

$jsonData = json_encode($usersList_array, 128);
echo $jsonData;

?>
</code>```

Body:
I want the array name institution to be displayed at the beginning.
My JSON Code currently displays the the following format.

{
    "institution": [],
    "id": "2",
    "name": "kjhl kjhl",
    "updated_date": "2017-11-12 21:43:13",
    "description": [{
        "id": "3",
        "description": "h,nm.,"
    }]
}

I want JSON code to be displayed the following format.

{"institution":[{
    "id": "2",
    "name": "kjhl kjhl",
    "updated_date": "2017-11-12 21:43:13",
    "description": [{
        "id": "3",
        "description": "h,nm.,"
    }]
}]}

Here is my code.

<?php
include_once "db.php";

$usersList_array =array();
$user_array = array();
$note_array = array();
  if(isset($_POST['updated_date'])) {

$fetch_users = mysql_query( "SELECT * FROM test1 WHERE updated_date > timestamp('".$_POST["updated_date"]."')  ORDER BY id desc" );

 $user_array['institution'] = array();
while ($row_users = mysql_fetch_assoc($fetch_users)) {

    $user_array['id'] = $row_users['id'];
    $user_array['name'] = $row_users['name'].' '.$row_users['name'];
    $user_array['updated_date']=$row_users["updated_date"];
    $user_array['description'] = array();

    $fetch_notes = mysql_query("SELECT t2.id, t2.description FROM test2 t2 ,test1 t1 where t1.id=t2.oid and oid = ".$row_users['id']."");
    while ($row_notes = mysql_fetch_assoc($fetch_notes)) {
        $note_array['id']=$row_notes['id'];
        $note_array['description']=$row_notes['description'];
        array_push($user_array['description'],$note_array);

    }
          array_push($usersList_array,$user_array);
}

$jsonData = json_encode($usersList_array, 128);
echo $jsonData;

?>

What do I need to change? Where is my error?

Body:
I solved your problem.work fine now
at first i simulated your code.this is with my values.

<?php

$usersList_array =array();
$user_array = array();
$note_array = array();

$user_array1['institution'] = array();

$user_array['id'] = "1";
$user_array['name'] = "mori";
$user_array['updated_date']="2017";

$user_array['description'] = array();

$note_array['id']="2";
$note_array['description']="descriptiondescription";

array_push($user_array['description'],$note_array);
array_push($user_array1['institution'],$user_array);
//$user_array1['institution'] =array($user_array);
//array_push($usersList_array,$user_array1);

 $jsonData = json_encode($user_array1, 128);
echo $jsonData;
?>

And it is your code

<?php
include_once "db.php";

$usersList_array =array();
$user_array = array();
$note_array = array();
  if(isset($_POST['updated_date'])) {

$fetch_users = mysql_query( "SELECT * FROM test1 WHERE updated_date > timestamp('".$_POST["updated_date"]."')  ORDER BY id desc" );

 $user_array1['institution'] = array();
while ($row_users = mysql_fetch_assoc($fetch_users)) {

    $user_array['id'] = $row_users['id'];
    $user_array['name'] = $row_users['name'].' '.$row_users['name'];
    $user_array['updated_date']=$row_users["updated_date"];
    $user_array['description'] = array();

    $fetch_notes = mysql_query("SELECT t2.id, t2.description FROM test2 t2 ,test1 t1 where t1.id=t2.oid and oid = ".$row_users['id']."");
    while ($row_notes = mysql_fetch_assoc($fetch_notes)) {
        $note_array['id']=$row_notes['id'];
        $note_array['description']=$row_notes['description'];
      //  array_push($user_array['description'],$note_array);
        array_push($user_array['description'],$note_array);

    }
          array_push($user_array1['institution'],$user_array);
         // array_push($usersList_array,$user_array1);

         // array_push($usersList_array,$user_array);
}

$jsonData = json_encode($usersList_array, 128);
echo $jsonData;

?>


问:
How to integrate Microsoft login in Android?
I downloaded one sample code from the following link:

https://github.com/OfficeDev/Office-365-SDK-for-Android

After this, I updated CLIENT_ID and REDIRECT_URI in Constants.
I'm getting following error

If any SDK available for Microsoft login, please provide me the links.

Thank you.

答:
I got following link to integrate Microsoft Graph in Android app :
Get started with Microsoft Graph in Android App

You can download sample code from given following url at 3rd point "Start Coding": Sample code link


问:
Prevent loading from cache for a JSON file
When I load the page for first time, I'm getting 200 status code and the page is loading file. The problem is from second time getting 304 status and the page is not working. How to set the cache control off for the particular JSON file in my JS file</p>

```<code>var app = angular.module("myApp", ['angular.filter']);

app.controller("deviceCtrl", function($scope, $rootScope, $http,$timeout)      {

var planReq = $http.get("data/callplans.json").then(function (response1) {
  $scope.callplanList = response1.data;
  return response1;
});

});
</code>```

答:
try this..:

var planReq = $http.get("data/callplans.json?r=" + Math.random() ).then(function (response1) {```

Body:
When I load the page for first time, I'm getting 200 status code and the page is loading file. The problem is from second time getting 304 status and the page is not working. How to set the cache control off for the particular JSON file in my JS file

var app = angular.module("myApp", ['angular.filter']);

app.controller("deviceCtrl", function($scope, $rootScope, $http,$timeout)      {

var planReq = $http.get("data/callplans.json").then(function (response1) {
  $scope.callplanList = response1.data;
  return response1;
});

});


问:
Is there a name for this type of popular footer?
Screenshot of a footer:

I'm unsure if there is a particular name for that kind of footer or if it's a widget for a certain framework. That particular example was taken from buffalonews.com

After I know the name I can refine my searching for implementing it. Thank you for your input.

答:
Looks like a fairly common set of copywrite notices.

There is no standard widget or way to present this, apart from legal requirements (which may vary depending on where the site operates from).


问:
Unhandled Promise rejection of a property undefined
```<code>setInterval(function(){

    for(i=1;i<=len;i++)
    {

        plug[i].getSysInfo().then(data => {

            var json = JSON.stringify(data,undefined,2);

            var obj = JSON.parse(json);
            var _macadd = obj.mac;

            plug[i].getConsumption().then(data => {

                var json = JSON.stringify(data,undefined,2);
                var obj = JSON.parse(json);
                var _current = obj.current;
                var _voltage = obj.voltage;
                var _power = (obj.power).toPrecision(5);
                var _total = obj.total;
                var _err_code = obj.err_code;
                console.log(_power);
                //console.log(_macadd);
                //console.log(voltage);
                if(_power > 1800)
                {
                    _power = 0.00;
                }
                //  var fs = require('fs');
                //  fs.writeFile("emeter.json", json);

                var sql1 = "INSERT INTO emeter SET ? ";
                var post1  = { macaddress: _macadd,current: _current,voltage: _voltage,power: _power, total: _total,err_code: _err_code};

                var tmp = JSON.stringify(post1,undefined,2);
                console.log(tmp);
                con.query(sql1, post1, function (err, result) {
                    if (err) throw err;
                    console.log("inserted");
                });

            });
        });
    }

},30000);
</code>```

While I run this, I am getting below error
Unhandled promise rejection Type error:
Cannot read property of 'getconsumption' of undefined.

The above code worked well when I replace the index with one value.To retrieve just one value it is working. When it is in For loop then the error message is returned. Please help me in solving this.

答:
You're trying to use a for loop index value inside an asynchronous callback.  The problem is that the .then() handlers are called AFTER the for loop has already finished and thus the for loop index is at its terminal value (beyond the end of the array) when you try to use it.

There are many ways to fix this.  One simple way would be to change this:

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

to this:

```<code>for(let i=1;i<=len;i++)
</code>```

Using ES6 let creates a new unique variable for each execution of the for loop so that each one maintains its own copy of the index, even for the duration of the asynchronous calls within that for loop block.

In ES5 (where you don't have let), you could change your loop to use .forEach():

```<code>plug.forEach(function(val, index) {
    // use val and index here rather than plug[i]
});
</code>```

This also creates a new val and index variable for each invocation of the loop.

Body:
setInterval(function(){

    for(i=1;i<=len;i++)
    {

        plug[i].getSysInfo().then(data => {

            var json = JSON.stringify(data,undefined,2);

            var obj = JSON.parse(json);
            var _macadd = obj.mac;

            plug[i].getConsumption().then(data => {

                var json = JSON.stringify(data,undefined,2);
                var obj = JSON.parse(json);
                var _current = obj.current;
                var _voltage = obj.voltage;
                var _power = (obj.power).toPrecision(5);
                var _total = obj.total;
                var _err_code = obj.err_code;
                console.log(_power);
                //console.log(_macadd);
                //console.log(voltage);
                if(_power > 1800)
                {
                    _power = 0.00;
                }
                //  var fs = require('fs');
                //  fs.writeFile("emeter.json", json);

                var sql1 = "INSERT INTO emeter SET ? ";
                var post1  = { macaddress: _macadd,current: _current,voltage: _voltage,power: _power, total: _total,err_code: _err_code};

                var tmp = JSON.stringify(post1,undefined,2);
                console.log(tmp);
                con.query(sql1, post1, function (err, result) {
                    if (err) throw err;
                    console.log("inserted");
                });

            });
        });
    }

},30000);

While I run this, I am getting below error
Unhandled promise rejection Type error:
Cannot read property of 'getconsumption' of undefined.

The above code worked well when I replace the index with one value.To retrieve just one value it is working. When it is in For loop then the error message is returned. Please help me in solving this.

Body:
You're trying to use a for loop index value inside an asynchronous callback.  The problem is that the .then() handlers are called AFTER the for loop has already finished and thus the for loop index is at its terminal value (beyond the end of the array) when you try to use it.

There are many ways to fix this.  One simple way would be to change this:

for(i=1;i<=len;i++)

to this:

for(let i=1;i<=len;i++)

Using ES6 let creates a new unique variable for each execution of the for loop so that each one maintains its own copy of the index, even for the duration of the asynchronous calls within that for loop block.

In ES5 (where you don't have let), you could change your loop to use .forEach():

plug.forEach(function(val, index) {
    // use val and index here rather than plug[i]
});

This also creates a new val and index variable for each invocation of the loop.


问:
SQL query to find top 2 customers done max amount of transaction( oracle db)
I want to get TOP  2 customers done maximum amount transaction from below the table.I am working on oracle db.

my table transactions:

```<code> tranID       PROD_ID       QTY      PRICE        CID
      1       100            5         10000      1000
      2       103            16        5000       1001
      3       102            8         5000       1003
      4       200            10        9000       1002
      5       204            8        9000         1002
      6       207            4         8000        1002
</code>```

CUSTOMERS

```<code>CID CNAME
1001  X
1002  Y
1003  Z
</code>```

答:
You could use a summ group by and a join  and last filter for rownum</p>

```<code>  select a.CID, b.CNAME, sum(a.QTY*a.PRICE) amount
  from transactions a
  INNER JOIN CUSTOMERS b on a.CID = b.CID
  WHERE ROWNUM < 3
  GROUP BY a.CID, b.CNAME
  ORDER BY amount
</code>```

Body:
I want to get TOP  2 customers done maximum amount transaction from below the table.I am working on oracle db.

my table transactions:

 tranID       PROD_ID       QTY      PRICE        CID
      1       100            5         10000      1000
      2       103            16        5000       1001
      3       102            8         5000       1003
      4       200            10        9000       1002
      5       204            8        9000         1002
      6       207            4         8000        1002

CUSTOMERS

CID CNAME
1001  X
1002  Y
1003  Z

Body:
You could use a summ group by and a join  and last filter for rownum

  select a.CID, b.CNAME, sum(a.QTY*a.PRICE) amount
  from transactions a
  INNER JOIN CUSTOMERS b on a.CID = b.CID
  WHERE ROWNUM < 3
  GROUP BY a.CID, b.CNAME
  ORDER BY amount


问:
Adding condition based on previous result on DispatchQueue
Is it possible to set a condition on the next queue of DispatchQueue? Supposed there are 2 API calls that should be executed synchronously, callAPI1 -> callAPI2. But, callAPI2 should be only executed if callAPI1 returning true. Please check code below for more clear situation:

```<code>    let dispatchQueue: DispatchQueue = DispatchQueue(label: "queue")
    let dispatchGroup = DispatchGroup()

    var isSuccess: Bool = false

    dispatchGroup.enter()
    dispatchQueue.sync {
        self.callAPI1(completion: { (result) in
            isSuccess = result
            dispatchGroup.leave()
        }
    }

    dispatchGroup.enter()
    dispatchQueue.sync {
        if isSuccess { //--> This one always get false
            self.callAPI2(completion: { (result) in
                isSuccess = result
                dispatchGroup.leave()
            })
        } else {
            dispatchGroup.leave()
        }
    }

    dispatchGroup.notify(queue: DispatchQueue.main, execute: {
        completion(isSuccess) //--> This one always get false
    })
</code>```

Currently above code always returning isSuccess as false despite on callAPI1's call returning true, which cause only callAPI1's is called.

答:
All non-playground code typed directly into answer, expect little errors.

It appears that you are trying to make an asynchronous call into a synchronous one, and the way you are attempting this simply will not work. Assuming callAPI1 is asynchronous then after:

```<code>self.callAPI1(completion: { (result) in
   isSuccess = result
}
</code>```

the completion block has (in all probability) not yet been run, you cannot test isSuccess immediately, as in:

```<code>self.callAPI1(completion: { (result) in
   isSuccess = result
}
if isSuccess
{
   // in all probability this will never be reached
}
</code>```

Wrapping the code into a synchronous block will have no effect whatsoever:

```<code>dispatchQueue.sync
{
   self.callAPI1(completion: { (result) in
      isSuccess = result
   }
   // at this point, in all probability, the completion block
   // has not yet run, therefore...
}
// at this point it has also not run
</code>```

A sync dispatch just runs its block on a different queue and waits for it to complete; if that block contains asynchronous code, as yours does, then it is not magically made synchronous - it executes asynchronously as normal, the synchronously dispatched block terminates, the sync dispatch returns, and your code continues. The sync dispatch has no real effect (apart from running the block on a different queue while blocking the current one).

If you need to sequence a number of asynchronous calls you can do it a number of ways. One method is to simply chain the calls through the completion blocks. Using this approach your code becomes:

```<code>self.callAPI1(completion: { (result) in
   if !result { completion(false) }
   else
   {
      self.callAPI2(completion: { (result) in
         completion(result)
      }
   }
}
</code>```

Using Semaphores

If you have a long sequence of such calls using the above pattern then the code can become very nested, in such a case instead of nesting you can use semaphores to sequence the calls. A simple semaphore can be used to block (thread) execution, using wait(), until it is signalled (by an unblocked thread), using signal().

Notice the emphasis here on blocking, once you introduce the ability to block execution all sorts of issues have to be considered: among them are UI responsiveness - blocking the UI thread is not good; deadlock - for example if the code that will issue semaphore wait and signal operations is executing on the same thread then after a wait there will be no signal...

Here is a sample Swift Playground script to demonstrate using semaphores. The pattern follows your original code but uses a semaphore in addition to your boolean.

```<code>import Cocoa

// some convenience functions for our dummy callAPI1 & callAPI2
func random(_ range : CountableClosedRange<UInt32>) -> UInt32
{
    let lower = range.lowerBound
    let upper = range.upperBound
    return lower + arc4random_uniform(upper - lower + 1)
}

func randomBool() -> Bool
{
    return random(0...1) == 1
}

class Demo
{
    // grab the global concurrent utility queue to schedule our work on
    let workerQueue = DispatchQueue.global(qos : .utility)

    // dummy callAPI1, just pauses and then randomly return success or failure
    func callAPI1(_ completion : @escaping (Bool) -> Void) -> Void
    {
        // do the "work" on workerQueue, which is concurrent so other work
        // can be executing, or *blocked*, on the same queue
        let pause = random(1...2)
        workerQueue.asyncAfter(deadline: .now() +  Double(pause))
        {
            // produce a random success result
            let success = randomBool()
            print("callAPI1 after \(pause) -> \(success)")
            completion(success)
        }
    }

    func callAPI2(_ completion : @escaping (Bool) -> Void) -> Void
    {
        let pause = random(1...2)
        workerQueue.asyncAfter(deadline: .now() +  Double(pause))
        {
            let success = randomBool()
            print("callAPI2 after \(pause) -> \(success)")
            completion(success)
        }
    }

    func runDemo(_ completion : @escaping (Bool) -> Void) -> Void
    {
        // We run the demo as a standard async function
        // which doesn't block the main thread
        workerQueue.async
        {
            print("Demo starting...")
            var isSuccess: Bool = false
            let semaphore = DispatchSemaphore(value: 0)

            // do the first call
            // this will asynchronously execute on a different thread
            // *including* its completion block
            self.callAPI1
            { (result) in
                isSuccess = result
                semaphore.signal() // signal completion
            }

            // we can safely wait for the semaphore to be
            // signalled as callAPI1 is executing on a different
            // thread so we will not deadlock
            semaphore.wait()

            if isSuccess
            {
                self.callAPI2
                { (result) in
                    isSuccess = result
                    semaphore.signal() // signal completion
                }
                semaphore.wait() // wait for completion
            }
            completion(isSuccess)
        }
    }
}

Demo().runDemo { (result) in print("Demo result: \(result)") }

// For the Playground
// ==================
// The Playground can terminate a program run once the main thread is done
// and before all async work is finished. This can result in incomplete execution
// and/or errors. To avoid this we sleep the main thread for a few seconds.
sleep(6)
print("All done")

// Run the Playground multiple times, the results should vary
// (different wait times, callAPI2 may not run). Wait until
// the "All done"" before starting next run
// (i.e. don't push stop, it confuses the Playground)
</code>```

Or...

Another approach to avoid the nesting is to design functions (or operators) which take two async methods and produce a single one by implementing the nesting pattern. Long nested sequences can then be reduce to more linear sequences. This approach is left as an exercise.

HTH

Body:
Is it possible to set a condition on the next queue of DispatchQueue? Supposed there are 2 API calls that should be executed synchronously, callAPI1 -> callAPI2. But, callAPI2 should be only executed if callAPI1 returning true. Please check code below for more clear situation:

    let dispatchQueue: DispatchQueue = DispatchQueue(label: "queue")
    let dispatchGroup = DispatchGroup()

    var isSuccess: Bool = false

    dispatchGroup.enter()
    dispatchQueue.sync {
        self.callAPI1(completion: { (result) in
            isSuccess = result
            dispatchGroup.leave()
        }
    }

    dispatchGroup.enter()
    dispatchQueue.sync {
        if isSuccess { //--> This one always get false
            self.callAPI2(completion: { (result) in
                isSuccess = result
                dispatchGroup.leave()
            })
        } else {
            dispatchGroup.leave()
        }
    }

    dispatchGroup.notify(queue: DispatchQueue.main, execute: {
        completion(isSuccess) //--> This one always get false
    })

Currently above code always returning isSuccess as false despite on callAPI1's call returning true, which cause only callAPI1's is called.

Body:
All non-playground code typed directly into answer, expect little errors.

It appears that you are trying to make an asynchronous call into a synchronous one, and the way you are attempting this simply will not work. Assuming callAPI1 is asynchronous then after:

self.callAPI1(completion: { (result) in
   isSuccess = result
}

the completion block has (in all probability) not yet been run, you cannot test isSuccess immediately, as in:

self.callAPI1(completion: { (result) in
   isSuccess = result
}
if isSuccess
{
   // in all probability this will never be reached
}

Wrapping the code into a synchronous block will have no effect whatsoever:

dispatchQueue.sync
{
   self.callAPI1(completion: { (result) in
      isSuccess = result
   }
   // at this point, in all probability, the completion block
   // has not yet run, therefore...
}
// at this point it has also not run

A sync dispatch just runs its block on a different queue and waits for it to complete; if that block contains asynchronous code, as yours does, then it is not magically made synchronous - it executes asynchronously as normal, the synchronously dispatched block terminates, the sync dispatch returns, and your code continues. The sync dispatch has no real effect (apart from running the block on a different queue while blocking the current one).

If you need to sequence a number of asynchronous calls you can do it a number of ways. One method is to simply chain the calls through the completion blocks. Using this approach your code becomes:

self.callAPI1(completion: { (result) in
   if !result { completion(false) }
   else
   {
      self.callAPI2(completion: { (result) in
         completion(result)
      }
   }
}

Using Semaphores

If you have a long sequence of such calls using the above pattern then the code can become very nested, in such a case instead of nesting you can use semaphores to sequence the calls. A simple semaphore can be used to block (thread) execution, using wait(), until it is signalled (by an unblocked thread), using signal().

Notice the emphasis here on blocking, once you introduce the ability to block execution all sorts of issues have to be considered: among them are UI responsiveness - blocking the UI thread is not good; deadlock - for example if the code that will issue semaphore wait and signal operations is executing on the same thread then after a wait there will be no signal...

Here is a sample Swift Playground script to demonstrate using semaphores. The pattern follows your original code but uses a semaphore in addition to your boolean.

import Cocoa

// some convenience functions for our dummy callAPI1 & callAPI2
func random(_ range : CountableClosedRange<UInt32>) -> UInt32
{
    let lower = range.lowerBound
    let upper = range.upperBound
    return lower + arc4random_uniform(upper - lower + 1)
}

func randomBool() -> Bool
{
    return random(0...1) == 1
}

class Demo
{
    // grab the global concurrent utility queue to schedule our work on
    let workerQueue = DispatchQueue.global(qos : .utility)

    // dummy callAPI1, just pauses and then randomly return success or failure
    func callAPI1(_ completion : @escaping (Bool) -> Void) -> Void
    {
        // do the "work" on workerQueue, which is concurrent so other work
        // can be executing, or *blocked*, on the same queue
        let pause = random(1...2)
        workerQueue.asyncAfter(deadline: .now() +  Double(pause))
        {
            // produce a random success result
            let success = randomBool()
            print("callAPI1 after \(pause) -> \(success)")
            completion(success)
        }
    }

    func callAPI2(_ completion : @escaping (Bool) -> Void) -> Void
    {
        let pause = random(1...2)
        workerQueue.asyncAfter(deadline: .now() +  Double(pause))
        {
            let success = randomBool()
            print("callAPI2 after \(pause) -> \(success)")
            completion(success)
        }
    }

    func runDemo(_ completion : @escaping (Bool) -> Void) -> Void
    {
        // We run the demo as a standard async function
        // which doesn't block the main thread
        workerQueue.async
        {
            print("Demo starting...")
            var isSuccess: Bool = false
            let semaphore = DispatchSemaphore(value: 0)

            // do the first call
            // this will asynchronously execute on a different thread
            // *including* its completion block
            self.callAPI1
            { (result) in
                isSuccess = result
                semaphore.signal() // signal completion
            }

            // we can safely wait for the semaphore to be
            // signalled as callAPI1 is executing on a different
            // thread so we will not deadlock
            semaphore.wait()

            if isSuccess
            {
                self.callAPI2
                { (result) in
                    isSuccess = result
                    semaphore.signal() // signal completion
                }
                semaphore.wait() // wait for completion
            }
            completion(isSuccess)
        }
    }
}

Demo().runDemo { (result) in print("Demo result: \(result)") }

// For the Playground
// ==================
// The Playground can terminate a program run once the main thread is done
// and before all async work is finished. This can result in incomplete execution
// and/or errors. To avoid this we sleep the main thread for a few seconds.
sleep(6)
print("All done")

// Run the Playground multiple times, the results should vary
// (different wait times, callAPI2 may not run). Wait until
// the "All done"" before starting next run
// (i.e. don't push stop, it confuses the Playground)

Or...

Another approach to avoid the nesting is to design functions (or operators) which take two async methods and produce a single one by implementing the nesting pattern. Long nested sequences can then be reduce to more linear sequences. This approach is left as an exercise.

HTH