问:
Python - Using list of strings as class data member. When strings contain variables, variables don't update
Is there a way to change variables within lists within classes after the class instance has been initialized?  (Sorry, sounds more complicated than it is!)

I'm writing a game and storing all of my display text as array elements in instances of a "Text" class. I wrote the following example program to test what I'm trying to do:

```<code>#****************************************#
#INITIALIZE CLASS (to hold text component)
#****************************************#
class Text:
        def __init__(self, array, maxIndex):

            #list of text
            self.list = array

            #number of items in list
            self.max = maxIndex

#set global variable to 7
globalv = 7

#****************************************#
#INITIALIZE VARIABLE-ENHANCED TEXT
#necessary because variables inside class
#data member arrays seem to have a local
#scope, and can't be changed after they
#are initialized
#****************************************#
varLine = Text(["This line contains globalv, which holds: {}".format(globalv)], 0)

print varLine.list[varLine.max]
#prints 7

#CHANGE VALUE OF globalv:
print "Directly accessing globalv: {}".format(globalv)
#prints 7
print "\nUpdate value of globalv to 9"
globalv = 9
print "Directly accessing globalv: {}".format(globalv)
#prints 9

#Try to change and re-print variable
#doesn't work, despite the fact that "global" has changed outside of the class
print "\nfirst try:"

#call print function on globalv directly:
    print "Directly accessing globalv: {}".format(globalv)
    #prints 9

    #print it from the class:
    print "Printing from class:"
    print varLine.list[varLine.max])
    #prints 7

#Change variable by re-initializing class
print "\nsecond try:"
varLine = Text(["This line contains globalv, which holds: {}".format(globalv)], 0)

    #call print function on globalv directly:
    print "Directly accessing globalv: {}".format(globalv)
    #prints 9

    #print it from the class:
    print "Printing from class:"
    print varLine.list[varLine.max])
    #prints 9
</code>```

答:
Answer is easy.

```<code>str.format()
</code>```

Function returns copy of string with intrerpolated values.
So Your Class contains :

```<code>vaeLine.list = ["Copy of formating string with resolved value"]
</code>```

When You change global var to soemthing this string isn't reevaluated

And this string copy is immutable so Your class is holding array which is muteable but its holding just an  already resolved string with value 7. So changing global doesnt affect this stirng.

Body:
Is there a way to change variables within lists within classes after the class instance has been initialized?  (Sorry, sounds more complicated than it is!)

I'm writing a game and storing all of my display text as array elements in instances of a "Text" class. I wrote the following example program to test what I'm trying to do:

#****************************************#
#INITIALIZE CLASS (to hold text component)
#****************************************#
class Text:
        def __init__(self, array, maxIndex):

            #list of text
            self.list = array

            #number of items in list
            self.max = maxIndex

#set global variable to 7
globalv = 7

#****************************************#
#INITIALIZE VARIABLE-ENHANCED TEXT
#necessary because variables inside class
#data member arrays seem to have a local
#scope, and can't be changed after they
#are initialized
#****************************************#
varLine = Text(["This line contains globalv, which holds: {}".format(globalv)], 0)

print varLine.list[varLine.max]
#prints 7

#CHANGE VALUE OF globalv:
print "Directly accessing globalv: {}".format(globalv)
#prints 7
print "\nUpdate value of globalv to 9"
globalv = 9
print "Directly accessing globalv: {}".format(globalv)
#prints 9

#Try to change and re-print variable
#doesn't work, despite the fact that "global" has changed outside of the class
print "\nfirst try:"

#call print function on globalv directly:
    print "Directly accessing globalv: {}".format(globalv)
    #prints 9

    #print it from the class:
    print "Printing from class:"
    print varLine.list[varLine.max])
    #prints 7

#Change variable by re-initializing class
print "\nsecond try:"
varLine = Text(["This line contains globalv, which holds: {}".format(globalv)], 0)

    #call print function on globalv directly:
    print "Directly accessing globalv: {}".format(globalv)
    #prints 9

    #print it from the class:
    print "Printing from class:"
    print varLine.list[varLine.max])
    #prints 9

Body:
Answer is easy.

str.format()

Function returns copy of string with intrerpolated values.
So Your Class contains :

vaeLine.list = ["Copy of formating string with resolved value"]

When You change global var to soemthing this string isn't reevaluated

And this string copy is immutable so Your class is holding array which is muteable but its holding just an  already resolved string with value 7. So changing global doesnt affect this stirng.


来源: stackexchange

问:
how to convert soap response to object
I have an xml file and a matching object definition.

How can i fill an instance of the object with the xml data?

I have registered to get ebay notification, and it sent me an xml in soap format.

How can i listen to this soap request and parse it into its matching object ?

答:
http://msdn.microsoft.com/en-us/library/182eeyhh(VS.71).aspx

Serialization is the process of converting an object into a form that can be readily transported. For example, you can serialize an object and transport it over the Internet using HTTP between a client and a server. On the other end, deserialization reconstructs the object from the stream.

XML serialization serializes only the public fields and property values of an object into an XML stream. XML serialization does not include type information. For example, if you have a Book object that exists in the Library namespace, there is no guarantee that it will be deserialized into an object of the same type.

Or, the more up to date version: http://msdn.microsoft.com/en-us/library/182eeyhh(v=VS.100).aspx

Read the stuff on deserialisation.

ContentLicense: CC BY-SA 2.5

Title: how to convert soap response to object


问:
Gson LinkedTree map cannot be casted to InformativeItemProvider
To start: I know this error is common and it might seem duplicate.

But its not, read the code and I will explain my error.

My plugin for in this case Minecraft exists out of 3 Important classes, but only it the JSONConfig all the magic is happening:

JSONConfig.java

```<code>public class JSONConfig {
    private String Path;
    private Map<String,Object> config;
    private File pathfile;
    public JSONConfig(String path)
    {
        this.Path = path;
        pathfile = new File(path);
        if (pathfile.exists()){
            JsonParser jp = new JsonParser();
            try {
                Type typeOfHashMap = new TypeToken<Map<String,Object>>() { }.getType();
                this.config = new Gson().fromJson(FileUtils.readFileToString(new File(path)), typeOfHashMap);
            } catch (IOException e) {
                Core.jp.getServer().getConsoleSender().sendMessage(ChatColor.RED+"[InformativeItems]: Whoops, our JSONConfigReader could not read the config: "+path);
                e.printStackTrace();
            }
        } else {
            this.config = new HashMap<String,Object>();
            try {
                FileUtils.writeStringToFile(pathfile, config.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Core.jp.getServer().getConsoleSender().sendMessage(ChatColor.GREEN+"[InformativeItems]: Config Loaded ("+path+")");
    }

    public Map<String,Object> getConfig(){return this.config;}

    public void reload(){
        JsonParser jp = new JsonParser();
        try {
            Type typeOfHashMap = new TypeToken<Map<String,Object>>() { }.getType();
            this.config = new Gson().fromJson(FileUtils.readFileToString(new File(this.Path)), typeOfHashMap);
        } catch (IOException e) {
            Core.jp.getServer().getConsoleSender().sendMessage(ChatColor.RED+"[InformativeItems]: Whoops, our JSONConfigReader could not read the config: "+Path);
            e.printStackTrace();
        }
    }

    public void save(){
        try {
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            FileUtils.writeStringToFile(pathfile, gson.toJson(gson.toJsonTree(config)));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
</code>```

In the core i have a statement that reads the config and loops trough its values.

All the values where serialized from a config that only contained one type of class as values: InformativeItemProvider.

As you can see in the JSONConfig all the keys/values are stored in a Map, the keys are in an Object class so they can be casted to anything.

So since i knew all the values in this case (in the core) would all be InformativeItemProviders i did let the all the values be casted to a InformativeItemProvider. And that is where it goes wrong.

The json is succesfully converted from a string to an map.
But when i try to cast the object from the map to InformativeItemProvider (what it actually is) it gives me the error.

Thanks in advance!

答:
When you create the following TypeToken:

```<code>Type typeOfHashMap = new TypeToken<Map<String,Object>>() { }.getType();
</code>```

You don't tell Gson anything about the type of objects you want it to create. Therefore, it will simply create the most vague objects representing JSON substructures: LinkedTreeMaps. That's why you get a ClassCastException if you try to cast these objects into something else.

A first solution to your problem is to use a Map<String,InformativeItemProvider> instead. And provide a TypeToken that actually gives information about the concrete type you want:

```<code>Type typeOfHashMap = new TypeToken<Map<String,InformativeItemProvider>>() { }.getType();
</code>```

Then, if you want to re-use your class, you may first separate json parsing from file I/O, and you'll see there's almost nothing to reuse regarding the Gson part.

ContentLicense: CC BY-SA 3.0

Body:
To start: I know this error is common and it might seem duplicate.

But its not, read the code and I will explain my error.

My plugin for in this case Minecraft exists out of 3 Important classes, but only it the JSONConfig all the magic is happening:

JSONConfig.java

public class JSONConfig {
    private String Path;
    private Map<String,Object> config;
    private File pathfile;
    public JSONConfig(String path)
    {
        this.Path = path;
        pathfile = new File(path);
        if (pathfile.exists()){
            JsonParser jp = new JsonParser();
            try {
                Type typeOfHashMap = new TypeToken<Map<String,Object>>() { }.getType();
                this.config = new Gson().fromJson(FileUtils.readFileToString(new File(path)), typeOfHashMap);
            } catch (IOException e) {
                Core.jp.getServer().getConsoleSender().sendMessage(ChatColor.RED+"[InformativeItems]: Whoops, our JSONConfigReader could not read the config: "+path);
                e.printStackTrace();
            }
        } else {
            this.config = new HashMap<String,Object>();
            try {
                FileUtils.writeStringToFile(pathfile, config.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Core.jp.getServer().getConsoleSender().sendMessage(ChatColor.GREEN+"[InformativeItems]: Config Loaded ("+path+")");
    }

    public Map<String,Object> getConfig(){return this.config;}

    public void reload(){
        JsonParser jp = new JsonParser();
        try {
            Type typeOfHashMap = new TypeToken<Map<String,Object>>() { }.getType();
            this.config = new Gson().fromJson(FileUtils.readFileToString(new File(this.Path)), typeOfHashMap);
        } catch (IOException e) {
            Core.jp.getServer().getConsoleSender().sendMessage(ChatColor.RED+"[InformativeItems]: Whoops, our JSONConfigReader could not read the config: "+Path);
            e.printStackTrace();
        }
    }

    public void save(){
        try {
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            FileUtils.writeStringToFile(pathfile, gson.toJson(gson.toJsonTree(config)));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

In the core i have a statement that reads the config and loops trough its values.

All the values where serialized from a config that only contained one type of class as values: InformativeItemProvider.

As you can see in the JSONConfig all the keys/values are stored in a Map, the keys are in an Object class so they can be casted to anything.

So since i knew all the values in this case (in the core) would all be InformativeItemProviders i did let the all the values be casted to a InformativeItemProvider. And that is where it goes wrong.

The json is succesfully converted from a string to an map.
But when i try to cast the object from the map to InformativeItemProvider (what it actually is) it gives me the error.

Thanks in advance!

Body:
When you create the following TypeToken:

Type typeOfHashMap = new TypeToken<Map<String,Object>>() { }.getType();

You don't tell Gson anything about the type of objects you want it to create. Therefore, it will simply create the most vague objects representing JSON substructures: LinkedTreeMaps. That's why you get a ClassCastException if you try to cast these objects into something else.

A first solution to your problem is to use a Map<String,InformativeItemProvider> instead. And provide a TypeToken that actually gives information about the concrete type you want:

Type typeOfHashMap = new TypeToken<Map<String,InformativeItemProvider>>() { }.getType();

Then, if you want to re-use your class, you may first separate json parsing from file I/O, and you'll see there's almost nothing to reuse regarding the Gson part.


问:
d3 multi circle series data chart

How would this be adapted to superimpose a second set of circles?

```<code>  var data = [{
    "name": "Twitter",
    "items": [{
      "value": 2000
    }, {
      "value": 3000
    }]
  }, {
    "name": "Facebook",
    "items": [{
      "value": 200
    }, {
      "value": 300
    }]
  }, {
    "name": "Ebay",
    "items": [{
      "value": 1000
    }, {
      "value": 2000
    }]
  }, {
    "name": "Foursquare",
    "items": [{
      "value": 2000
    }, {
      "value": 3000
    }]
  }]
</code>```

with the option of adding other data sets - the goal to create a 2D pyramid of sorts with different coloured circles representing the different data sets -- with the largest dataset taking the base circle.

http://jsfiddle.net/0aqvx66j/4/

```<code>function circleMaker() {

    var counter = 0;
    series = 0

    var set = svg.append("g")
      .attr("class", "series" + series);

    set.selectAll("circle")
      .data(data)
      .enter().append("circle")
      .attr("class", "series" + series)
      .attr("cy", 60)
      .attr("cx", function(d, i) {
        if (i) {
          return (counter += Math.sqrt(data[i - 1].items[series].value) + Math.sqrt(data[i].items[series].value));
        } else {
          return counter;
        }
      })
      .attr("fill", function(d, i) {
        var colorArray = ["#00ccff", "#fcdd0a"];
        return colorArray[series];
      })
      .attr("r", function(d) {
        return Math.sqrt(d.items[series].value);
      });

}
</code>```

eventually maybe even flip between the different data sets to always place the largest circle as the background. So like this

答:
Most of it is just organising the data before plotting it. Within each series give each item an index, and then sort by value. The index property will then tell us the initial position of each item in the series. The first item in each series will now be the biggest value. Use this to build an offset for each series, and sum all these offsets to make a scale for positioning.

Then make group elements for each series, positioning using the offset we calculated.

Within each group, draw the circle elements. Since we sorted them they'll be drawn biggest first. The .index property can be used to colour by their original place in the series.

http://jsfiddle.net/0ht35rpb/2/

```<code>var width = 600;
var height = 400;
var svg = d3.select('svg').attr("width", width).attr("height",height);

  var data = [{
    "name": "Twitter",
    "items": [{
      "value": 2000
    }, {
      "value": 3000
    }]
  }, {
    "name": "Facebook",
    "items": [{
      "value": 200
    }, {
      "value": 300
    }]
  }, {
    "name": "Ebay",
    "items": [{
      "value": 2000
    }, {
      "value": 1000
    }]
  }, {
    "name": "Foursquare",
    "items": [{
      "value": 2000
    }, {
      "value": 3000
    },
    {
      "value": 4000
    }]
  }];

  // organise the data.
  // Insert indices and sort items in each series
  // keep a running total of max circle size in each series
  // for later positioning
  var x = 0;
  var totalWidth = d3.sum (
    data.map (function (series) {
      series.items.forEach (function (item, i) {
            item.index = i;
      });
      series.items.sort (function (a, b) {
        return b.value - a.value;
      });
      var maxr = Math.sqrt(series.items[0].value);
      x += maxr;
      series.xcentre = x;
      x += maxr;
      return maxr * 2;
    })
  );

  // make scales for position and colour
  var scale = d3.scale.linear().domain([0,totalWidth]).range([0, width]);
  var colScale = d3.scale.category10();

  // add a group per series, position the group according to the values and position scale  we calculated above
 var groups = svg.selectAll("g").data(data);
 groups.enter().append("g");
 groups.attr("transform", function(d) {
        return ("translate("+scale(d.xcentre)+",0)");
 });

 // then add circles per series, biggest first as items are sorted
 // colour according to index (the property we inserted previously so we can
 // keep track of their original position in the series)
 var circles = groups.selectAll("circle").data(function(d) { return d.items;}, function(d) { return d.index; });
 circles.enter().append("circle").attr("cy", height/2).attr("cx",0);

 circles
    .attr("r", function(d) { return scale(Math.sqrt (d.value)); })
  .style ("fill", function (d) { return colScale(d.index); });
</code>```

Title: d3 multi circle series data chart

Body:
How would this be adapted to superimpose a second set of circles?

  var data = [{
    "name": "Twitter",
    "items": [{
      "value": 2000
    }, {
      "value": 3000
    }]
  }, {
    "name": "Facebook",
    "items": [{
      "value": 200
    }, {
      "value": 300
    }]
  }, {
    "name": "Ebay",
    "items": [{
      "value": 1000
    }, {
      "value": 2000
    }]
  }, {
    "name": "Foursquare",
    "items": [{
      "value": 2000
    }, {
      "value": 3000
    }]
  }]

with the option of adding other data sets - the goal to create a 2D pyramid of sorts with different coloured circles representing the different data sets -- with the largest dataset taking the base circle.

http://jsfiddle.net/0aqvx66j/4/

function circleMaker() {

    var counter = 0;
    series = 0

    var set = svg.append("g")
      .attr("class", "series" + series);

    set.selectAll("circle")
      .data(data)
      .enter().append("circle")
      .attr("class", "series" + series)
      .attr("cy", 60)
      .attr("cx", function(d, i) {
        if (i) {
          return (counter += Math.sqrt(data[i - 1].items[series].value) + Math.sqrt(data[i].items[series].value));
        } else {
          return counter;
        }
      })
      .attr("fill", function(d, i) {
        var colorArray = ["#00ccff", "#fcdd0a"];
        return colorArray[series];
      })
      .attr("r", function(d) {
        return Math.sqrt(d.items[series].value);
      });

}

eventually maybe even flip between the different data sets to always place the largest circle as the background. So like this

Body:
Most of it is just organising the data before plotting it. Within each series give each item an index, and then sort by value. The index property will then tell us the initial position of each item in the series. The first item in each series will now be the biggest value. Use this to build an offset for each series, and sum all these offsets to make a scale for positioning.

Then make group elements for each series, positioning using the offset we calculated.

Within each group, draw the circle elements. Since we sorted them they'll be drawn biggest first. The .index property can be used to colour by their original place in the series.

http://jsfiddle.net/0ht35rpb/2/

var width = 600;
var height = 400;
var svg = d3.select('svg').attr("width", width).attr("height",height);

  var data = [{
    "name": "Twitter",
    "items": [{
      "value": 2000
    }, {
      "value": 3000
    }]
  }, {
    "name": "Facebook",
    "items": [{
      "value": 200
    }, {
      "value": 300
    }]
  }, {
    "name": "Ebay",
    "items": [{
      "value": 2000
    }, {
      "value": 1000
    }]
  }, {
    "name": "Foursquare",
    "items": [{
      "value": 2000
    }, {
      "value": 3000
    },
    {
      "value": 4000
    }]
  }];

  // organise the data.
  // Insert indices and sort items in each series
  // keep a running total of max circle size in each series
  // for later positioning
  var x = 0;
  var totalWidth = d3.sum (
    data.map (function (series) {
      series.items.forEach (function (item, i) {
            item.index = i;
      });
      series.items.sort (function (a, b) {
        return b.value - a.value;
      });
      var maxr = Math.sqrt(series.items[0].value);
      x += maxr;
      series.xcentre = x;
      x += maxr;
      return maxr * 2;
    })
  );

  // make scales for position and colour
  var scale = d3.scale.linear().domain([0,totalWidth]).range([0, width]);
  var colScale = d3.scale.category10();

  // add a group per series, position the group according to the values and position scale  we calculated above
 var groups = svg.selectAll("g").data(data);
 groups.enter().append("g");
 groups.attr("transform", function(d) {
        return ("translate("+scale(d.xcentre)+",0)");
 });

 // then add circles per series, biggest first as items are sorted
 // colour according to index (the property we inserted previously so we can
 // keep track of their original position in the series)
 var circles = groups.selectAll("circle").data(function(d) { return d.items;}, function(d) { return d.index; });
 circles.enter().append("circle").attr("cy", height/2).attr("cx",0);

 circles
    .attr("r", function(d) { return scale(Math.sqrt (d.value)); })
  .style ("fill", function (d) { return colScale(d.index); });


问:
How to initialize a static member variable in class with template functions
As far as I found, there were articles about initializing a static variables in class templates. However, I´m using a normal class with member function templates, so I have to ask.

In short version(not whole class definition) I have a class that look like this:

```<code>class BatchManager
{
    private:

        static std::vector<BaseBatch_P> _BATCHES;

    public:

        template <class T>
        static void placeData(T* data){

            //Loop through the entire container
            for (auto&& b: _BATCHES)
                if (b==data){
                    dynamic_cast<Batch<T>>(b)->draw(data);
                }

            //If no bach found, create a new One
            createNewBatch(data);
        }
};
</code>```

However, when I want to access the member variables inside the function, it shows:
undefined reference to BatchManager::_BATCHES

Then I´ve tried the following: keep definition in class header :

```<code> //BatchManager.h

 template <typename T>
 static void placeData(T* data);
</code>```

And cpp file:

```<code>std::map<GLuint,BaseBatch_P> BatchManager::_TEXTURE_MAP;

template <typename T>
void BatchManager::placeData(T* data){

    //Loop through the entire container
    for (auto&& b: _BATCHES)
        if (b==data){
            dynamic_cast<Batch<T>>(b)->draw(data);
        }

    //If no bach found, create a new One
    createNewBatch(data);
}
</code>```

It fixes the first problem, but then another appears, and it happens when I want to call my static function from the program:

```<code>BatchManager::render(_data);
</code>```

Error message looks like this:

```<code>undefined reference to BatchManager::placeData<DataType>(DataType*)
</code>```

How can i fix this problem? Or am I doing something wrong?

答:
Something like this:</p>

```<code>#include <vector>
#include <typeinfo>

struct BaseBatch {

    virtual const std::type_info& get_type() const = 0;
    virtual ~BaseBatch() = default;
};

template<class T>
struct Batch : BaseBatch
{

    const std::type_info& get_type() const override
    {
        return typeid(T);
    }

    void draw(T* data) {}
};

using BaseBatch_P = BaseBatch*;

class BatchManager
{
private:

    static std::vector<BaseBatch_P>& get_batches() {
        static std::vector<BaseBatch_P> _;
        return _;
    }

public:

    template <class T>
    static void placeData(T* data){

        //Loop through the entire container
        bool found = false;
        for (auto&& b: get_batches())
            if (b->get_type() == typeid(T)) {
                dynamic_cast<Batch<T>*>(b)->draw(data);
                found = true;
            }

        //If no bach found, create a new One
        if (not found) {
            get_batches().push_back(new Batch<T>);
        }
    }
};
</code>```

Body:
As far as I found, there were articles about initializing a static variables in class templates. However, I´m using a normal class with member function templates, so I have to ask.

In short version(not whole class definition) I have a class that look like this:

class BatchManager
{
    private:

        static std::vector<BaseBatch_P> _BATCHES;

    public:

        template <class T>
        static void placeData(T* data){

            //Loop through the entire container
            for (auto&& b: _BATCHES)
                if (b==data){
                    dynamic_cast<Batch<T>>(b)->draw(data);
                }

            //If no bach found, create a new One
            createNewBatch(data);
        }
};

However, when I want to access the member variables inside the function, it shows:
undefined reference to BatchManager::_BATCHES

Then I´ve tried the following: keep definition in class header :

 //BatchManager.h

 template <typename T>
 static void placeData(T* data);

And cpp file:

std::map<GLuint,BaseBatch_P> BatchManager::_TEXTURE_MAP;

template <typename T>
void BatchManager::placeData(T* data){

    //Loop through the entire container
    for (auto&& b: _BATCHES)
        if (b==data){
            dynamic_cast<Batch<T>>(b)->draw(data);
        }

    //If no bach found, create a new One
    createNewBatch(data);
}

It fixes the first problem, but then another appears, and it happens when I want to call my static function from the program:

BatchManager::render(_data);

Error message looks like this:

undefined reference to BatchManager::placeData<DataType>(DataType*)

How can i fix this problem? Or am I doing something wrong?

Body:
Something like this:

#include <vector>
#include <typeinfo>

struct BaseBatch {

    virtual const std::type_info& get_type() const = 0;
    virtual ~BaseBatch() = default;
};

template<class T>
struct Batch : BaseBatch
{

    const std::type_info& get_type() const override
    {
        return typeid(T);
    }

    void draw(T* data) {}
};

using BaseBatch_P = BaseBatch*;

class BatchManager
{
private:

    static std::vector<BaseBatch_P>& get_batches() {
        static std::vector<BaseBatch_P> _;
        return _;
    }

public:

    template <class T>
    static void placeData(T* data){

        //Loop through the entire container
        bool found = false;
        for (auto&& b: get_batches())
            if (b->get_type() == typeid(T)) {
                dynamic_cast<Batch<T>*>(b)->draw(data);
                found = true;
            }

        //If no bach found, create a new One
        if (not found) {
            get_batches().push_back(new Batch<T>);
        }
    }
};


问:
Can I generate a random float on the whole space?
I am trying to generate a random number that range from Number.MIN_VALUE to Number.MAX_VALUE, but the following algorithm fails due to buffer overflows (I guess) :

var randFloat = Math.floor(Math.random() * (Number.MAX_VALUE - Number.MIN_VALUE)) + Number.MIN_VALUE```

Is there any way to do it ?

答:
What you could do:

```<code>function IEEEToDouble(f)
{
    return new Float64Array(f.buffer)[0];
}

var array = new Uint32Array(2); // here we allocate a 2 element unsigned 32 bit ints
window.crypto.getRandomValues(array); // here we generate 64 bits of random values
var f = IEEEToDouble(array); // and convert 64 bits to a double precision number
</code>```

This generates a uniformly distributed double precision IEEE754 number. So every possible value in the whole space is equally possible to get with this code, including NaNs (it's quite a lot of NaNs there actually - 2^53 - 2) and Infinitys.

References:

The initial implementation of the IEEEToDouble function borrowed from https://stackoverflow.com/a/21282715/251311

RandomSource.getRandomValues()

Body:
I am trying to generate a random number that range from Number.MIN_VALUE to Number.MAX_VALUE, but the following algorithm fails due to buffer overflows (I guess) :

var randFloat = Math.floor(Math.random() * (Number.MAX_VALUE - Number.MIN_VALUE)) + Number.MIN_VALUE

Is there any way to do it ?

Body:
What you could do:

function IEEEToDouble(f)
{
    return new Float64Array(f.buffer)[0];
}

var array = new Uint32Array(2); // here we allocate a 2 element unsigned 32 bit ints
window.crypto.getRandomValues(array); // here we generate 64 bits of random values
var f = IEEEToDouble(array); // and convert 64 bits to a double precision number

This generates a uniformly distributed double precision IEEE754 number. So every possible value in the whole space is equally possible to get with this code, including NaNs (it's quite a lot of NaNs there actually - 2^53 - 2) and Infinitys.

References:

The initial implementation of the IEEEToDouble function borrowed from https://stackoverflow.com/a/21282715/251311

RandomSource.getRandomValues()


问:
matplotlib ArtistAnimation returns a blank video
I'm trying to produce an animation of a networkx graph changing over time. I'm using the networkx_draw utilities to create matplotlib figures of the graph, and matplotlib's ArtistAnimation module to create an animation from the artists networkx produces. I've made a minimum reproduction of what I'm doing here:

```<code>import numpy as np
import networkx as nx
import matplotlib.animation as animation
import matplotlib.pyplot as plt

# Instantiate the graph model
G = nx.Graph()
G.add_edge(1, 2)

# Keep track of highest node ID
G.maxNode = 2

fig = plt.figure()
nx.draw(G)
ims = []

for timeStep in xrange(10):

    G.add_edge(G.maxNode,G.maxNode+1)
    G.maxNode += 1

    pos = nx.drawing.spring_layout(G)
    nodes = nx.drawing.draw_networkx_nodes(G, pos)
    lines = nx.drawing.draw_networkx_edges(G, pos)

    ims.append((nodes,lines,))
    plt.pause(.2)
    plt.cla()

im_ani = animation.ArtistAnimation(fig, ims, interval=200,            repeat_delay=3000,blit=True)
im_ani.save('im.mp4', metadata={'artist':'Guido'})
</code>```

The process works fine while displaying the figures live, it produces exactly the animation I want. And it even produces a looping animation in a figure at the end of the script, again what I want, which would suggest that the animation process worked. However when I open the "im.mp4" file saved to disk, it is a blank white image which runs for the expected period of time, never showing any of the graph images which were showed live.

I'm using networkx version 1.11, and matplotlib version 2.0. I'm using ffmpeg for the animation, and am running on a Mac, OSX 10.12.3.

What am I doing incorrectly?

答:
The short answer: If you don't want to have an empty animation, do not clear the axes! I.e. remove the line plt.cla(). You should then also remove the initial nx.draw(G), because this is not added to the ims array and would otherwise stick around in every frame of the animation.

The reasons and a longer explanation can be found in this question,

Matplotlib video creation, where a similar case is tackled.

The drawback is of course that when removing the plt.cla() you'll end up with a crowded animation on screen; so you need to decide whether to plot on screen or whether to save beforehands.

Body:
I'm trying to produce an animation of a networkx graph changing over time. I'm using the networkx_draw utilities to create matplotlib figures of the graph, and matplotlib's ArtistAnimation module to create an animation from the artists networkx produces. I've made a minimum reproduction of what I'm doing here:

import numpy as np
import networkx as nx
import matplotlib.animation as animation
import matplotlib.pyplot as plt

# Instantiate the graph model
G = nx.Graph()
G.add_edge(1, 2)

# Keep track of highest node ID
G.maxNode = 2

fig = plt.figure()
nx.draw(G)
ims = []

for timeStep in xrange(10):

    G.add_edge(G.maxNode,G.maxNode+1)
    G.maxNode += 1

    pos = nx.drawing.spring_layout(G)
    nodes = nx.drawing.draw_networkx_nodes(G, pos)
    lines = nx.drawing.draw_networkx_edges(G, pos)

    ims.append((nodes,lines,))
    plt.pause(.2)
    plt.cla()

im_ani = animation.ArtistAnimation(fig, ims, interval=200,            repeat_delay=3000,blit=True)
im_ani.save('im.mp4', metadata={'artist':'Guido'})

The process works fine while displaying the figures live, it produces exactly the animation I want. And it even produces a looping animation in a figure at the end of the script, again what I want, which would suggest that the animation process worked. However when I open the "im.mp4" file saved to disk, it is a blank white image which runs for the expected period of time, never showing any of the graph images which were showed live.

I'm using networkx version 1.11, and matplotlib version 2.0. I'm using ffmpeg for the animation, and am running on a Mac, OSX 10.12.3.

What am I doing incorrectly?


问:
powershell.exe -file string array as parameter
I'm actually writing a plugin with powershell for a monitoring solution.

This monitoring solution runs the powershell skript from the command line cmd.

One of the input parameters is a string array but it looks  like cmd can't hand over the array to the powershell.

Here a example script that I've wrote to explain you the problem:

```<code>param (
    [array]$myarray
)

Write-Host 'My array is a ' $myarray.GetType()
Write-Host 'How much value do I have in my array?' $myarray.count
Write-Host 'My content is' $myarray
</code>```

When I run this script from a powershell console my output is right:

```<code>.\Test-Script.ps1 -myarray bla1, bla2

My array is a  System.Object[]
How much value do I have in my array? 2
My content is bla1 bla2
</code>```

now I run the same from the cmd and the array is not interpreted as it should:

```<code>powershell.exe -file Test-Script.ps1 -myarray bla1, bla2

My array is a  System.Object[]
How much value do I have in my array? 1
My content is bla1,
</code>```

My question is now how to commit the array to the powershell script? I have tried quite every thing....
Escaping with ^ , brackets, sing quotes , double quotes and so on. but nothing helped...

I am thankful for every hint :)

答:
When calling the script from CMD, do:

```<code>powershell.exe -command ".\Test-Script.ps1 -myarray bla1, bla2"
</code>```

Results in:

```<code>My array is a  System.Object[]
How much value do I have in my array? 2
My content is bla1 bla2
</code>```

From my experience, using the command argument rather than the file argument, then wrapping the entire command in quotes causes things to behave more like you'd expect them to as if you were running from the PoSh console.

Also, if you want to make your param statement specific to a string, or array of strings, you can write the statement like:

```<code>param (
    [string[]]$myarray
)
Write-Host 'My array is a ' $myarray.GetType()
Write-Host 'How much value do I have in my array?' $myarray.count
Write-Host 'My content is' $myarray
</code>```

The result is:

```<code>My array is a  System.String[]
How much value do I have in my array? 2
My content is bla1 bla2
</code>```

As you have it now, it will accept an array with elements of any type, depending on your application, you may want it to only accept arrays with elements of a specific type. Defining an array like [typename[]] specifies that it's an array with elements of typename.

Body:
I'm actually writing a plugin with powershell for a monitoring solution.

This monitoring solution runs the powershell skript from the command line cmd.

One of the input parameters is a string array but it looks  like cmd can't hand over the array to the powershell.

Here a example script that I've wrote to explain you the problem:

param (
    [array]$myarray
)

Write-Host 'My array is a ' $myarray.GetType()
Write-Host 'How much value do I have in my array?' $myarray.count
Write-Host 'My content is' $myarray

When I run this script from a powershell console my output is right:

.\Test-Script.ps1 -myarray bla1, bla2

My array is a  System.Object[]
How much value do I have in my array? 2
My content is bla1 bla2

now I run the same from the cmd and the array is not interpreted as it should:

powershell.exe -file Test-Script.ps1 -myarray bla1, bla2

My array is a  System.Object[]
How much value do I have in my array? 1
My content is bla1,

My question is now how to commit the array to the powershell script? I have tried quite every thing....
Escaping with ^ , brackets, sing quotes , double quotes and so on. but nothing helped...

I am thankful for every hint :)

Body:
When calling the script from CMD, do:

powershell.exe -command ".\Test-Script.ps1 -myarray bla1, bla2"

Results in:

My array is a  System.Object[]
How much value do I have in my array? 2
My content is bla1 bla2

From my experience, using the command argument rather than the file argument, then wrapping the entire command in quotes causes things to behave more like you'd expect them to as if you were running from the PoSh console.

Also, if you want to make your param statement specific to a string, or array of strings, you can write the statement like:

param (
    [string[]]$myarray
)
Write-Host 'My array is a ' $myarray.GetType()
Write-Host 'How much value do I have in my array?' $myarray.count
Write-Host 'My content is' $myarray

The result is:

My array is a  System.String[]
How much value do I have in my array? 2
My content is bla1 bla2

As you have it now, it will accept an array with elements of any type, depending on your application, you may want it to only accept arrays with elements of a specific type. Defining an array like [typename[]] specifies that it's an array with elements of typename.


问:
Where can I find JARS for Oracle Agile PLM
I want to download files under attachments section of a part.
Where can I find the jars to write the code?

Which jar has AgileSessionFactory

答: The jars are AgileAPI.jar and pxapi.jar. You can find them under the agile_home/integration/sdk/lib directory.</p>


问:
Concatenate the database name in a SQL multipart identifier
I'm writing a stored procedure and I'm trying to concatenate the database name in the multipart identifier after FROM without success. This is one way that I tried but it didn't work

```<code>INSERT INTO CONTROL_LOGISTICA.dbo.ITEMS_TRAMITE (NRODCTO, TIPODCTO, PRODUCTO, EMPRESA, CODUSUARIO, CODUBICA, CANTIDAD, CCHECK_HIJO)
    SELECT
        @pNrodcto, @pTipodcto,
        M.PRODUCTO, @pEmpresa, @pUsuario,
        M.CODUBICA, M.CANTIDAD, 0
    FROM
        "@mEmpresa".dbo.MVTRADE M WITH(NOLOCK) -- Here I'm stuck
    INNER JOIN
        Dbo.vReporteMercia_ESP P ON P.PRODUCTO = M.PRODUCTO
    WHERE
        M.CANTIDAD <> 0 AND M.Origen = 'FAC'
        AND M.NRODCTO = @pNrodcto AND M.TIPODCTO = @pTipodcto
</code>```

I get the variable directly from the stored procedure

```<code>@pEmpresa AS char(20)
</code>```

I know that I can do an IF like

```<code>IF (@pEmpresa = 'John Doe')
 BEGIN
 --..... and the query here
 END
</code>```

Is it possible to concatenate the database name using the variable? How? Or should I just use the IF?

答:
Instead of creating the query dynamically with different database names, create the database connection dynamically and omit this database name from the query. Instead specify the database name of the second table (Dbo.vReporteMercia_ESP). I assume that the other table is always from the same database.

Depending on the connection type, you would have to set Initial Catalog=<database name> or Database=<database name> dynamically in the connection string.

```<code>SELECT ...
FROM
    dbo.MVTRADE M WITH(NOLOCK) -- Database from dynamic connection
INNER JOIN
    MyNonDynamicDatabase.dbo.vReporteMercia_ESP P ON P.PRODUCTO = M.PRODUCTO
...
</code>```

Body:
I'm writing a stored procedure and I'm trying to concatenate the database name in the multipart identifier after FROM without success. This is one way that I tried but it didn't work

INSERT INTO CONTROL_LOGISTICA.dbo.ITEMS_TRAMITE (NRODCTO, TIPODCTO, PRODUCTO, EMPRESA, CODUSUARIO, CODUBICA, CANTIDAD, CCHECK_HIJO)
    SELECT
        @pNrodcto, @pTipodcto,
        M.PRODUCTO, @pEmpresa, @pUsuario,
        M.CODUBICA, M.CANTIDAD, 0
    FROM
        "@mEmpresa".dbo.MVTRADE M WITH(NOLOCK) -- Here I'm stuck
    INNER JOIN
        Dbo.vReporteMercia_ESP P ON P.PRODUCTO = M.PRODUCTO
    WHERE
        M.CANTIDAD <> 0 AND M.Origen = 'FAC'
        AND M.NRODCTO = @pNrodcto AND M.TIPODCTO = @pTipodcto

I get the variable directly from the stored procedure

@pEmpresa AS char(20)

I know that I can do an IF like

IF (@pEmpresa = 'John Doe')
 BEGIN
 --..... and the query here
 END

Is it possible to concatenate the database name using the variable? How? Or should I just use the IF?

Body:
Instead of creating the query dynamically with different database names, create the database connection dynamically and omit this database name from the query. Instead specify the database name of the second table (Dbo.vReporteMercia_ESP). I assume that the other table is always from the same database.

Depending on the connection type, you would have to set Initial Catalog=<database name> or Database=<database name> dynamically in the connection string.

SELECT ...
FROM
    dbo.MVTRADE M WITH(NOLOCK) -- Database from dynamic connection
INNER JOIN
    MyNonDynamicDatabase.dbo.vReporteMercia_ESP P ON P.PRODUCTO = M.PRODUCTO
...


问:
File Download Java without Temporary file
I am trying to create a file and send as a response so that file can be downloaded. I am not sure how to do it. My current code

```<code>  String fileName = "fileToBeSaved.csv";
  File file = new File(fileName);
  FileWriter writer = new FileWriter(file);
  writer.append(data);
  writer.flush();
  writer.close();

  Response.ResponseBuilder response = Response.ok((Object) file);
  response.header("Content-Disposition","attachment; filename=\"fileName.csv\"");

  return response.build();
</code>```

This code creates a temporary file on my system. And when the browser receives the response it gets the path to file, like "C:/folderName/FileName"...Upon mentioning this path on the browser, I get the option to download the file.

What I want to achieve is:
I want to create a file (But don't want any temporary file to be created on my system) and send as a response. The browser should receive a prompt asking whether to download the file or not as a response.
Can some one guide me what am I doing wrong?

答:
I finally found the way.

```<code>Response.ResponseBuilder response = Response.ok();
response.header("Content-Disposition", "attachment; filename=\"filename.csv\"");
response.entity(contentAsString);
return response.build();
</code>```

If you cannot build a string out of the contents of the file, then a work-around is:

```<code>ByteArrayOutputStream bo = new ByteArrayOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(bo));
//for loop can be any content.. I am just showing a represenatation.
for (int i = 0; i < content.size(); i++) {
    writer.write(content.get(i));
}
writer.flush();
Response.ResponseBuilder response = Response.ok();
response.type(MediaType.APPLICATION_OCTET_STREAM);
response.header("Content-Disposition", "attachment");
response.entity(bo.toByteArray());
return response.build();
</code>```

In the above code, I am building a file and sending to GUI. No temporary file was created.

Hope it helps.

Thanks!

Body:
I am trying to create a file and send as a response so that file can be downloaded. I am not sure how to do it. My current code

  String fileName = "fileToBeSaved.csv";
  File file = new File(fileName);
  FileWriter writer = new FileWriter(file);
  writer.append(data);
  writer.flush();
  writer.close();

  Response.ResponseBuilder response = Response.ok((Object) file);
  response.header("Content-Disposition","attachment; filename=\"fileName.csv\"");

  return response.build();

This code creates a temporary file on my system. And when the browser receives the response it gets the path to file, like "C:/folderName/FileName"...Upon mentioning this path on the browser, I get the option to download the file.

What I want to achieve is:
I want to create a file (But don't want any temporary file to be created on my system) and send as a response. The browser should receive a prompt asking whether to download the file or not as a response.
Can some one guide me what am I doing wrong?

Body:
I finally found the way.

Response.ResponseBuilder response = Response.ok();
response.header("Content-Disposition", "attachment; filename=\"filename.csv\"");
response.entity(contentAsString);
return response.build();

If you cannot build a string out of the contents of the file, then a work-around is:

ByteArrayOutputStream bo = new ByteArrayOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(bo));
//for loop can be any content.. I am just showing a represenatation.
for (int i = 0; i < content.size(); i++) {
    writer.write(content.get(i));
}
writer.flush();
Response.ResponseBuilder response = Response.ok();
response.type(MediaType.APPLICATION_OCTET_STREAM);
response.header("Content-Disposition", "attachment");
response.entity(bo.toByteArray());
return response.build();

In the above code, I am building a file and sending to GUI. No temporary file was created.

Hope it helps.

Thanks!


问:
Angular2: Component host property
What does @Component.host property stand for?

According to Angular2 documentation it stands for:

host - map of class property to host element bindings for events, properties and attributes.

I don't quite figure out what's it for?

I'm posing this in order to understand a stuff code I've stuck last days.

The code is:

```<code>@Component({
  selector: 'layout',
  encapsulation: ViewEncapsulation.None,
  templateUrl: './layout.template.html',
  host: {
    '[class.nav-static]' : 'config.state["nav-static"]',
    '[class.chat-sidebar-opened]' : 'chatOpened',
    '[class.app]' : 'true',
    id: 'app'
  }
})
export class Layout {
</code>```

答:
based on this document, the directive properties inside your host property ([class.nav-static], [class.chat-sidebar-opened] and [class.app] in your code snippet) should get changed whenever their corresponding expression values get changed.

For example, your [class.nav-static] property will get the value of 'config.state["nav-static"]' expression and it will get updated whenever the expression's value gets updated.

Title: Angular2: Component host property

Body:
What does @Component.host property stand for?

According to Angular2 documentation it stands for:

host - map of class property to host element bindings for events, properties and attributes.

I don't quite figure out what's it for?

I'm posing this in order to understand a stuff code I've stuck last days.

The code is:

@Component({
  selector: 'layout',
  encapsulation: ViewEncapsulation.None,
  templateUrl: './layout.template.html',
  host: {
    '[class.nav-static]' : 'config.state["nav-static"]',
    '[class.chat-sidebar-opened]' : 'chatOpened',
    '[class.app]' : 'true',
    id: 'app'
  }
})
export class Layout {

ContentLicense: CC BY-SA 4.0


问:
Is it possible to use WebClient to retrieve a file from the browser cache without checking for a newer version of the file?
I am using an instance of WebClient in my Silverlight application to retrieve an image file for display. In order to service this application, I have set up a WCF REST service. The following is a snippet of code I wrote for that service:

```<code>DateTime modSince = WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.IfModifiedSince]
    == null
    ? DateTime.MinValue
    : DateTime.Parse(WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.IfModifiedSince].ToString());

FileInfo fInfo = new FileInfo(filePath);

if (fInfo.LastWriteTime > modSince)
{
    WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";
    WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.OK;
    WebOperationContext.Current.OutgoingResponse.LastModified = fInfo.LastWriteTime;
}
else
{
    WebOperationContext.Current.OutgoingResponse.SuppressEntityBody = true;
    WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotModified;
}
</code>```

The service is set up such that on a request for an image file, the if-modified-since attribute of the request header is examined.  If this value is less than the last time the file is modified, the file is returned.  Otherwise, a 304 message is returned.

We are interested in making the transaction faster.  Since the images rarely, if ever, change it is desirable to look up the cache for a copy of the image before making a request to the server, which would save on network latency.  In trying to implement this for IE, I have changed the Temporary Internet Files settings to "never check for newer versions of stored pages".  When I enter in the browser's address bar the REST service URL for an image that has a copy stored in the cache, the copy is retrieved from the cache without the server being called.  However, when the URL is entered as a parameter to the WebClient's OpenReadAsync method a GET request is sent to the server, leading to a 304 message.

Is there any way I could use the WebClient to look up the cache without a GET request being sent to the server?

答:
You need to set the CahcePolicy on the WebClient:

```<code>WebClient wc = new WebClient();
wc.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.CacheIfAvailable);
</code>```

This will use Microsoft.Win32.WinInetCache by default which is IE's cache manager.

UPDATE

OK, I did not realise it is SL. In that case, if the image is small I think it is easier to simplify things by retrieving from the server anyway. If the file is large, expose a method to return the date it was last changed and implement a local caching using Isolated Storage.

Body:
I am using an instance of WebClient in my Silverlight application to retrieve an image file for display. In order to service this application, I have set up a WCF REST service. The following is a snippet of code I wrote for that service:

DateTime modSince = WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.IfModifiedSince]
    == null
    ? DateTime.MinValue
    : DateTime.Parse(WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.IfModifiedSince].ToString());

FileInfo fInfo = new FileInfo(filePath);

if (fInfo.LastWriteTime > modSince)
{
    WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";
    WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.OK;
    WebOperationContext.Current.OutgoingResponse.LastModified = fInfo.LastWriteTime;
}
else
{
    WebOperationContext.Current.OutgoingResponse.SuppressEntityBody = true;
    WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotModified;
}

The service is set up such that on a request for an image file, the if-modified-since attribute of the request header is examined.  If this value is less than the last time the file is modified, the file is returned.  Otherwise, a 304 message is returned.

We are interested in making the transaction faster.  Since the images rarely, if ever, change it is desirable to look up the cache for a copy of the image before making a request to the server, which would save on network latency.  In trying to implement this for IE, I have changed the Temporary Internet Files settings to "never check for newer versions of stored pages".  When I enter in the browser's address bar the REST service URL for an image that has a copy stored in the cache, the copy is retrieved from the cache without the server being called.  However, when the URL is entered as a parameter to the WebClient's OpenReadAsync method a GET request is sent to the server, leading to a 304 message.

Is there any way I could use the WebClient to look up the cache without a GET request being sent to the server?

Body:
You need to set the CahcePolicy on the WebClient:

WebClient wc = new WebClient();
wc.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.CacheIfAvailable);

This will use Microsoft.Win32.WinInetCache by default which is IE's cache manager.

UPDATE

OK, I did not realise it is SL. In that case, if the image is small I think it is easier to simplify things by retrieving from the server anyway. If the file is large, expose a method to return the date it was last changed and implement a local caching using Isolated Storage.


问:
How to create a list of customers who buy less over time?
I have customer transactions data as shown below and need to create a list of only those customers whose total ordered units is consistently lesser than the previous order. i.e.Total Qty purchased in the nth order is less than Total Qty purchased in n-1 th order, and the next previous order is also less. Another way to say it, list the customers buy fewer units as time goes forward.

```<code>Custid  date    units
123 28-03-17    100
123 27-03-17    100
123 26-03-17    100
999 25-03-17    10
999 24-03-17    20
893 24-03-17    39
893 28-03-17    48
893 24-03-17    10
893 19-03-17    75
893 12-02-17    10
</code>```

Such that the output of the code should be customer 999.

I initially thought of using the lag function after sorting the transactions and then using a conditional statement but the number of transactions varies across customers.

Regards

答:
Use lag() and conditional aggregation:

```<code>select custid
from (select t.*,
             lag(units) over (partition by custid order by date) as prev_units
      from t
     ) t
group by custid
having sum(case when units >= pev_units then 1 else 0 end) = 0;
</code>```

Body:
I have customer transactions data as shown below and need to create a list of only those customers whose total ordered units is consistently lesser than the previous order. i.e.Total Qty purchased in the nth order is less than Total Qty purchased in n-1 th order, and the next previous order is also less. Another way to say it, list the customers buy fewer units as time goes forward.

Custid  date    units
123 28-03-17    100
123 27-03-17    100
123 26-03-17    100
999 25-03-17    10
999 24-03-17    20
893 24-03-17    39
893 28-03-17    48
893 24-03-17    10
893 19-03-17    75
893 12-02-17    10

Such that the output of the code should be customer 999.

I initially thought of using the lag function after sorting the transactions and then using a conditional statement but the number of transactions varies across customers.

Regards

Body:
Use lag() and conditional aggregation:

select custid
from (select t.*,
             lag(units) over (partition by custid order by date) as prev_units
      from t
     ) t
group by custid
having sum(case when units >= pev_units then 1 else 0 end) = 0;


问:
What is the best collation when using JSON and some special characters
I'm trying to get data from mysql database with php and JSON and it's not working because of the collation I've chosen.
I'm using these characters  : ® ,é, è , ™, É
My deafult collation in mysql is: latin1_swedish_ci,and my server default collation is: utf8mb4_unicode_ci.
Should I just remove those special characters or what?
this the php code: </p>

```<code><?php
require "conn.php";
$sql = "select * from produit";
$result = mysqli_query($conn, $sql); // result contient tous les produits
$response = array(); // on déclare un array
// pour chaque ligne de la table
while ($row = mysqli_fetch_array($result)) {
array_push($response, array("id_produit"=>$row[0] , "nom"=>$row[1], "catégorie"=>$row[2], "description"=>$row[3], "type"=>$row[4], "prix"=>$row[5], "qte_stock"=>$row[6]));
}
echo json_encode(array("server_response"=> $response));
mysqli_close($conn);

 ?>
</code>```

<p>show create table produit : </p>

```<code>CREATE TABLE `produit` (
 `id_produit` int(11) NOT NULL AUTO_INCREMENT,
 `nom` varchar(255) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL,
 `catégorie` varchar(255) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL,
 `description` text COLLATE utf8mb4_unicode_520_ci NOT NULL,
 `type` varchar(255) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL,
 `prix` int(11) DEFAULT NULL,
 `qte_stock` int(11) DEFAULT NULL,
 PRIMARY KEY (`id_produit`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci
</code>```

答:
For all those wondering how to solve the problem with french characters and JSON trust me I've tried everything these days the only thing that works is :

```<code>echo json_encode(array("server_response"=>$response), JSON_UNESCAPED_UNICODE);
</code>```

here's the link for more information http://php.net/manual/fr/function.json-encode.php thank god for that, I lost hope for a second

Body:
I'm trying to get data from mysql database with php and JSON and it's not working because of the collation I've chosen.
I'm using these characters  : ® ,é, è , ™, É
My deafult collation in mysql is: latin1_swedish_ci,and my server default collation is: utf8mb4_unicode_ci.
Should I just remove those special characters or what?
this the php code:

<?php
require "conn.php";
$sql = "select * from produit";
$result = mysqli_query($conn, $sql); // result contient tous les produits
$response = array(); // on déclare un array
// pour chaque ligne de la table
while ($row = mysqli_fetch_array($result)) {
array_push($response, array("id_produit"=>$row[0] , "nom"=>$row[1], "catégorie"=>$row[2], "description"=>$row[3], "type"=>$row[4], "prix"=>$row[5], "qte_stock"=>$row[6]));
}
echo json_encode(array("server_response"=> $response));
mysqli_close($conn);

 ?>

show create table produit :

CREATE TABLE `produit` (
 `id_produit` int(11) NOT NULL AUTO_INCREMENT,
 `nom` varchar(255) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL,
 `catégorie` varchar(255) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL,
 `description` text COLLATE utf8mb4_unicode_520_ci NOT NULL,
 `type` varchar(255) COLLATE utf8mb4_unicode_520_ci DEFAULT NULL,
 `prix` int(11) DEFAULT NULL,
 `qte_stock` int(11) DEFAULT NULL,
 PRIMARY KEY (`id_produit`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci

Body:
For all those wondering how to solve the problem with french characters and JSON trust me I've tried everything these days the only thing that works is :

echo json_encode(array("server_response"=>$response), JSON_UNESCAPED_UNICODE);

here's the link for more information http://php.net/manual/fr/function.json-encode.php thank god for that, I lost hope for a second


问:
How to extract the numbers into a separate array from a string
Given this string

```<code>"In 2015, I want to know how much does iPhone 6+ cost?"
</code>```

how can I return [2015, 6]?

My first attempt at this was

```<code>numbers = str.tr("^0-9", '')
</code>```

but that produces 20156.

答:
scan is better, but this also works.

```<code>"In 2015, I want to know how much does iPhone 6+ cost?".gsub(/\D/,' ').split
  #=> ["2015", "6"]
</code>```

Body:
Given this string

"In 2015, I want to know how much does iPhone 6+ cost?"

how can I return [2015, 6]?

My first attempt at this was

numbers = str.tr("^0-9", '')

but that produces 20156.

Body:
scan is better, but this also works.

"In 2015, I want to know how much does iPhone 6+ cost?".gsub(/\D/,' ').split
  #=> ["2015", "6"]


问:
How to download files from adf.ly to a remote server?
I am trying to download a file to a remote server from the website adf.ly, but when I try wget it downloads the website html code. Help?

答: Make sure you are wget'ing the link to the actual file, not the ad.fly link. Ad.fly has it setup this way to force you to watch their ads.</p>


问:
do i need "Java Advanced Imaging API" to learn "image processing" in Java
do i need "Java Advanced Imaging API" to learn "image processing" in Java?

and is there any good link for learning "image processing" in java?

答:
No. However, there is a good Java program called "ImageJ" (google it).
It will get you off to a flying start, as you can start writing your own plugins for it in Java, with minimal effort and complexity. Also, there are many plugins and classes contributed for it and freely available. </p>


问:
typescript: resolving typeahead.js with typescript and webpack 2
I am getting the following error from webpack.

ERROR in ./wwwroot/js/admin/infrastructure/typeaheadComponent.ts
  Module not found: Error: Can't resolve 'typeahead' in ...

I have the following installed

```<code>npm install typeahead.js
npm install @types/typeahead
</code>```

My typescript is as follows, using node module resolution.

```<code>import { module } from "angular";
import "typeahead";
// necessary to import typeahead into JQuery, as otherwise
// typeahead below is not defined.

class TypeAheadController {
    foo(e) {
       $(e).typeahead(...)
    }
}
</code>```

this generates javascript as follows:

```<code>"use strict";
var angular_1 = require("angular");
require("typeahead");
var TypeAheadController = (function () { ...
</code>```

My webpack.config.js is as follows:

```<code>module.exports = {
    context: __dirname,
    entry: [
        "./app.ts",
        "./tab.ts",
        "./client/clientService.ts",
        "./client/clientSearchComponent.ts",
        "./infrastructure/messageComponent.ts",
        "./infrastructure/typeaheadComponent.ts",
        "./url.ts"],
    output: {
        filename: "./wwwroot/js/admin/admin.js"
    },
    devtool: "source-map",
    module: {
        rules: [
            { test: /\.ts$/, use: 'ts-loader' }
        ]
    }
};
</code>```

imported into a gulp task.

How do I specify that typeahead is located in node_modules/typeahead.js/dist/typeahead.bundle.js

答:
The module is called typeadhead.js so you also need to import typeahead.js, not typeahead.

```<code>import "typeahead.js";
</code>```

The import is always the same as the name you use to install it with npm. And it's not even special, it simple looks into node_modules and finds the directory with the given name. Then it looks into package.json and imports the file specified in the main field. See also Node.js - Folders as Modules.

You could use resolve.alias to change the name of the import, but there is not really a good reason for doing that in this case.

Body:
I am getting the following error from webpack.

ERROR in ./wwwroot/js/admin/infrastructure/typeaheadComponent.ts
  Module not found: Error: Can't resolve 'typeahead' in ...

I have the following installed

npm install typeahead.js
npm install @types/typeahead

My typescript is as follows, using node module resolution.

import { module } from "angular";
import "typeahead";
// necessary to import typeahead into JQuery, as otherwise
// typeahead below is not defined.

class TypeAheadController {
    foo(e) {
       $(e).typeahead(...)
    }
}

this generates javascript as follows:

"use strict";
var angular_1 = require("angular");
require("typeahead");
var TypeAheadController = (function () { ...

My webpack.config.js is as follows:

module.exports = {
    context: __dirname,
    entry: [
        "./app.ts",
        "./tab.ts",
        "./client/clientService.ts",
        "./client/clientSearchComponent.ts",
        "./infrastructure/messageComponent.ts",
        "./infrastructure/typeaheadComponent.ts",
        "./url.ts"],
    output: {
        filename: "./wwwroot/js/admin/admin.js"
    },
    devtool: "source-map",
    module: {
        rules: [
            { test: /\.ts$/, use: 'ts-loader' }
        ]
    }
};

imported into a gulp task.

How do I specify that typeahead is located in node_modules/typeahead.js/dist/typeahead.bundle.js

Body:
The module is called typeadhead.js so you also need to import typeahead.js, not typeahead.

import "typeahead.js";

The import is always the same as the name you use to install it with npm. And it's not even special, it simple looks into node_modules and finds the directory with the given name. Then it looks into package.json and imports the file specified in the main field. See also Node.js - Folders as Modules.

You could use resolve.alias to change the name of the import, but there is not really a good reason for doing that in this case.


问:
Sort Model by a nested Relationship count
Room Model

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Room extends Model
{
    /**
     * Get the comments for the room.
     */
    public function comments()
    {
        return $this->hasMany('App\Comment');
    }
}
</code>```

Comment Model

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{

    /**
     * Get the room that owns the comment.
     */
    public function room()
    {
        return $this->belongsTo('App\Room');
    }

    public function upvotes() {
        return $this->hasMany('App\Upvote');
    }
}
</code>```

Upvote Model

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class Upvote extends Model
{

    /**
     * Get the comment that the upvote belongs to.
     */
    public function comment() {
        return $this->belongsTo('App\Comment');
    }
}
</code>```

How would I be able to have a list of comments for the room that is sorted by the count of upvotes each comment has?

I have searched online and have only managed to find answers relating to having the model sorted by its directed relation e.g $room->comments() rather than being sorted by $room->comments()->upvotes()?

Thanks

答:
You can try this with a join and a raw query:</p>

```<code>$comments = \App\Comment::join('upvotes', function($j) {
            $j->on('upvotes.comment_id', '=', 'comments.id');
        })
        ->where('comments.room_id', $roomId)
        ->with('upvotes')
        ->groupBy('comments.id')
        ->orderBy('count', 'desc')
        ->select((['comments.*', \DB::raw('COUNT(upvotes.comment_id) as count')]))->get();
</code>```

Body:
Room Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Room extends Model
{
    /**
     * Get the comments for the room.
     */
    public function comments()
    {
        return $this->hasMany('App\Comment');
    }
}

Comment Model

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{

    /**
     * Get the room that owns the comment.
     */
    public function room()
    {
        return $this->belongsTo('App\Room');
    }

    public function upvotes() {
        return $this->hasMany('App\Upvote');
    }
}

Upvote Model

namespace App;

use Illuminate\Database\Eloquent\Model;

class Upvote extends Model
{

    /**
     * Get the comment that the upvote belongs to.
     */
    public function comment() {
        return $this->belongsTo('App\Comment');
    }
}

How would I be able to have a list of comments for the room that is sorted by the count of upvotes each comment has?

I have searched online and have only managed to find answers relating to having the model sorted by its directed relation e.g $room->comments() rather than being sorted by $room->comments()->upvotes()?

Thanks

Body:
You can try this with a join and a raw query:

$comments = \App\Comment::join('upvotes', function($j) {
            $j->on('upvotes.comment_id', '=', 'comments.id');
        })
        ->where('comments.room_id', $roomId)
        ->with('upvotes')
        ->groupBy('comments.id')
        ->orderBy('count', 'desc')
        ->select((['comments.*', \DB::raw('COUNT(upvotes.comment_id) as count')]))->get();


问:
ADB server version (36) doesn't match this client (39); killing
After installing the Android O preview on a test device my ADB stopped working and started giving me this error.

```<code>adb server version (36) doesn't match this client (39); killing...
adb E 03-27 08:01:55  2925 147690 usb_osx.cpp:333] Could not open interface: e00002c5
adb E 03-27 08:01:55  2925 147690 usb_osx.cpp:294] Could not find device interface
error: could not install *smartsocket* listener: Address already in use
ADB server didn't ACK
* failed to start daemon *
error: cannot connect to daemon
</code>```

The only answers I have come across on this issue referred to Genymotion being out of sync with ADB but I don’t use Genymotion. Any help would be greatly appreciated. I have already wiped and reinstalled Android Studio as well as all of its tools and settings yet seem to still have this issue.

答:
This works for me...

go to GenyMotion settings -> ADB tab

instead of Use Genymotion Android tools, choose custom Android SDK Tools and then browse your installed SDK.

Body:
After installing the Android O preview on a test device my ADB stopped working and started giving me this error.

adb server version (36) doesn't match this client (39); killing...
adb E 03-27 08:01:55  2925 147690 usb_osx.cpp:333] Could not open interface: e00002c5
adb E 03-27 08:01:55  2925 147690 usb_osx.cpp:294] Could not find device interface
error: could not install *smartsocket* listener: Address already in use
ADB server didn't ACK
* failed to start daemon *
error: cannot connect to daemon

The only answers I have come across on this issue referred to Genymotion being out of sync with ADB but I don’t use Genymotion. Any help would be greatly appreciated. I have already wiped and reinstalled Android Studio as well as all of its tools and settings yet seem to still have this issue.


问:
In this IronPython example what is the @ symbol doing and how is it implemented?
http://www.ironpython.info/index.php/Using_Python_Classes_from_.NET/CSharp_IP_2.6

```<code>   string code = @"
   print 'test = ' + test
   class MyClass:
       def __init__(self):
           pass

       def somemethod(self):
           print 'in some method'

       def isodd(self, n):
           return 1 == n % 2
   ";
</code>```

Is that '@' part of C# or is that something added by IronPython? If the latter, how do you do that in C#, some kind of operator overloading (basically could I then make '@' do whatever I want, etc)? Example implementation would be great. Otherwise, what's going on here?

答:
```<code>string path = @"C:\Sweet\now\I\can\use\backslashes\without\writing\them\all\twice.txt"
</code>```

Body:
http://www.ironpython.info/index.php/Using_Python_Classes_from_.NET/CSharp_IP_2.6

   string code = @"
   print 'test = ' + test
   class MyClass:
       def __init__(self):
           pass

       def somemethod(self):
           print 'in some method'

       def isodd(self, n):
           return 1 == n % 2
   ";

Is that '@' part of C# or is that something added by IronPython? If the latter, how do you do that in C#, some kind of operator overloading (basically could I then make '@' do whatever I want, etc)? Example implementation would be great. Otherwise, what's going on here?


问:
Mongodb flexible email notification conditions
I am searching for a way to store conditions in mongodb, to be queried and checked, then do something as a result of the condition check.

First off here is an example of the event object that I am considering

```<code>{
  "name": "My Event",
  "created": 1490726092221,
  "startDate": 1490726092221,
  "endDate": 1490726097810,
  "notifications": [
    {
      "message": "{event.Name} Created", // message template
      "status": 0, // 0=initialized 1=failed 2=sent
      "sendDate": null, // date that the notification was sent
      "sentTo": ["c2a34dfg32c1d4583e73a123"] //members to send notification to
      "criteria": {
        "script": "event.created >= 0 && this.status < 2"
      }
    }
  ],
  "members": [
    {
      "_id": "c2a34dfg32c1d4583e73a123" // Reference to the user
    }
  ]
}
</code>```

The use case, I want to have customizated notifications for an event. So if an event is scheduled it could have notifications for when it is created, when the event start date is within a few days, when a member joins etc. While I could code all of these into javascript functions and correspond to them by an enum for the notification criteria, or have hooks for when certain events happen, this seems like a strict approach.

What I am envisioning is possibly a scripting language that can be stored as a string on the document, which can be queried and evaluated, which will return a boolean to trigger the notification or not.

The script would need to have the event as an input variable, as well as a few special input variables to be available to the script.

This could be done with javascript and eval() but that scares me. Are there any other tools that can be used for this use case? Or, are there any suggestions for a better approach to this problem?

答: Sounds like you are building a workflow engine with a MongoDB back end.  I would start by researching things like the ones listed in this answer Workflow engine in Javascript</p>

Body:
I am searching for a way to store conditions in mongodb, to be queried and checked, then do something as a result of the condition check.

First off here is an example of the event object that I am considering

{
  "name": "My Event",
  "created": 1490726092221,
  "startDate": 1490726092221,
  "endDate": 1490726097810,
  "notifications": [
    {
      "message": "{event.Name} Created", // message template
      "status": 0, // 0=initialized 1=failed 2=sent
      "sendDate": null, // date that the notification was sent
      "sentTo": ["c2a34dfg32c1d4583e73a123"] //members to send notification to
      "criteria": {
        "script": "event.created >= 0 && this.status < 2"
      }
    }
  ],
  "members": [
    {
      "_id": "c2a34dfg32c1d4583e73a123" // Reference to the user
    }
  ]
}

The use case, I want to have customizated notifications for an event. So if an event is scheduled it could have notifications for when it is created, when the event start date is within a few days, when a member joins etc. While I could code all of these into javascript functions and correspond to them by an enum for the notification criteria, or have hooks for when certain events happen, this seems like a strict approach.

What I am envisioning is possibly a scripting language that can be stored as a string on the document, which can be queried and evaluated, which will return a boolean to trigger the notification or not.

The script would need to have the event as an input variable, as well as a few special input variables to be available to the script.

This could be done with javascript and eval() but that scares me. Are there any other tools that can be used for this use case? Or, are there any suggestions for a better approach to this problem?


问:
How to get parameter value from query string?
How can I define a route in my routes.jsx file to capture the __firebase_request_key parameter value from a URL generated by Twitter's single sign on process after the redirect from their servers?

```<code>http://localhost:8000/#/signin?_k=v9ifuf&__firebase_request_key=blablabla
</code>```

I tried with the following routes configuration, but the :redirectParam is not catching the mentioned param:

```<code><Router>
  <Route path="/" component={Main}>
    <Route path="signin" component={SignIn}>
      <Route path=":redirectParam" component={TwitterSsoButton} />
    </Route>
  </Route>
</Router>
</code>```

答:
In the component where you need to access the parameters you can use

this.props.location.state.from.search

which will reveal the whole query string (everything after the ? sign)

Body:
How can I define a route in my routes.jsx file to capture the __firebase_request_key parameter value from a URL generated by Twitter's single sign on process after the redirect from their servers?

http://localhost:8000/#/signin?_k=v9ifuf&__firebase_request_key=blablabla

I tried with the following routes configuration, but the :redirectParam is not catching the mentioned param:

<Router>
  <Route path="/" component={Main}>
    <Route path="signin" component={SignIn}>
      <Route path=":redirectParam" component={TwitterSsoButton} />
    </Route>
  </Route>
</Router>


问:
Authorization in Facebook, Swift 3, FBSDK
I am trying to create an API for login user on facebook, but I have this error:

Thread 1:EXC_BAD_INSTRUCTION(code=EXC_I386_INVOP,subcode=0x0)

on this line:

```<code>self.accessToken = jsonData["access_token"].string!
</code>```

Console shows:

My Code:

fatal error: unexpectedly found nil while unwrapping an Optional value
      (lldb)

```<code>func login(userType: String, completionHandler: @escaping (NSError?) -> Void) {

        let path = "api/social/convert-token/"
        let url = baseURL!.appendingPathComponent(path)
        let params: [String: Any] = [
            "grant_type": "convert_token",
            "client_id": CLIENT_ID,
            "client_secret": CLIENT_SECRET,
            "backend": "facebook",
            "token": FBSDKAccessToken.current().tokenString,
            "user_type": userType
        ]

        Alamofire.request(url!, method: .post, parameters: params, encoding: URLEncoding(), headers: nil).responseJSON { (response) in

            switch response.result {
            case .success(let value):

                let jsonData = JSON(value)

                self.accessToken = jsonData["access_token"].string!
                self.refreshToken = jsonData["refresh_token"].string!
                self.expired = Date().addingTimeInterval(TimeInterval(jsonData["expires_in"].int!))

                completionHandler(nil)
                break

            case .failure(let error):
                completionHandler(error as NSError?)
                break
            }
        }
    }
</code>```

答:
If you decide to use FBSDK, you should use kit's functions to get data from Facebook. FBSDK has integrated functions for working with the network.

Details

xCode 8.2.1, Swift 3

Full Sample: authorisation Facebook in Swift 3 FBSDK

Podfile

```<code>target '{YOUR_PROJECT_NAME}' do
  use_frameworks!
  pod 'FBSDKCoreKit'
  pod 'FBSDKLoginKit'
  pod 'FBSDKShareKit'
end
</code>```

Info.plist

add to plist

```<code><key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
    <array>
        <string>fb{your-app-id}</string>
    </array>
    </dict>
</array>
<key>FacebookAppID</key>
<string>{your-app-id}</string>
<key>FacebookDisplayName</key>
<string>{your-app-name}</string>
<key>LSApplicationQueriesSchemes</key>
<array>
    <string>fbapi</string>
    <string>fb-messenger-api</string>
    <string>fbauth2</string>
    <string>fbshareextension</string>
</array>
<key>NSPhotoLibraryUsageDescription</key>
<string>{human-readable reason for photo access}</string>
</code>```

AppDelegate

add to AppDelegate class

```<code>func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    return FBSDKApplicationDelegate.sharedInstance().application(app, open: url, options: options)
}
</code>```

ViewController.swift

```<code>import UIKit
import FBSDKLoginKit

class ViewController: UIViewController {

    let loginManager = FBSDKLoginManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        FBSDKProfile.enableUpdates(onAccessTokenChange: true)

        let button = UIButton(frame: CGRect(x: 40, y: 40, width: 200, height: 40))
        button.setTitle("Button", for: .normal)
        button.setTitleColor(.blue, for: .normal)
        button.addTarget(self, action: #selector(ViewController.login), for: .touchUpInside)
        view.addSubview(button)
    }

    func login() {
        if let token = FBSDKAccessToken.current() {
            // User is logged in, do work such as go to next view controller.
            print(token)
        } else {
            loginManager.logIn(withReadPermissions: ["public_profile"], from: self) { (loginManagerLoginResult, error) in

                FBSDKProfile.enableUpdates(onAccessTokenChange: true)
                print("token \(FBSDKAccessToken.current().tokenString)")

                FBSDKGraphRequest(graphPath: "me", parameters: nil).start(completionHandler: { (connection, result, error) -> Void in
                    if error == nil{
                        if let dict = result as? Dictionary<String, AnyObject>{
                            print(dict)
                        }
                    }
                })
            }
        }
    }
}
</code>```

Result

You will be logged in and get user ID and name.

Read about

https://developers.facebook.com/docs/ios/getting-started
https://developers.facebook.com/docs/reference/ios/current/class/FBSDKLoginManager

Body:
I am trying to create an API for login user on facebook, but I have this error:

Thread 1:EXC_BAD_INSTRUCTION(code=EXC_I386_INVOP,subcode=0x0)

on this line:

self.accessToken = jsonData["access_token"].string!

Console shows:

My Code:

fatal error: unexpectedly found nil while unwrapping an Optional value
      (lldb)

func login(userType: String, completionHandler: @escaping (NSError?) -> Void) {

        let path = "api/social/convert-token/"
        let url = baseURL!.appendingPathComponent(path)
        let params: [String: Any] = [
            "grant_type": "convert_token",
            "client_id": CLIENT_ID,
            "client_secret": CLIENT_SECRET,
            "backend": "facebook",
            "token": FBSDKAccessToken.current().tokenString,
            "user_type": userType
        ]

        Alamofire.request(url!, method: .post, parameters: params, encoding: URLEncoding(), headers: nil).responseJSON { (response) in

            switch response.result {
            case .success(let value):

                let jsonData = JSON(value)

                self.accessToken = jsonData["access_token"].string!
                self.refreshToken = jsonData["refresh_token"].string!
                self.expired = Date().addingTimeInterval(TimeInterval(jsonData["expires_in"].int!))

                completionHandler(nil)
                break

            case .failure(let error):
                completionHandler(error as NSError?)
                break
            }
        }
    }

Body:
If you decide to use FBSDK, you should use kit's functions to get data from Facebook. FBSDK has integrated functions for working with the network.

Details

xCode 8.2.1, Swift 3

Full Sample: authorisation Facebook in Swift 3 FBSDK

Podfile

target '{YOUR_PROJECT_NAME}' do
  use_frameworks!
  pod 'FBSDKCoreKit'
  pod 'FBSDKLoginKit'
  pod 'FBSDKShareKit'
end

Info.plist

add to plist

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
    <array>
        <string>fb{your-app-id}</string>
    </array>
    </dict>
</array>
<key>FacebookAppID</key>
<string>{your-app-id}</string>
<key>FacebookDisplayName</key>
<string>{your-app-name}</string>
<key>LSApplicationQueriesSchemes</key>
<array>
    <string>fbapi</string>
    <string>fb-messenger-api</string>
    <string>fbauth2</string>
    <string>fbshareextension</string>
</array>
<key>NSPhotoLibraryUsageDescription</key>
<string>{human-readable reason for photo access}</string>

AppDelegate

add to AppDelegate class

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    return FBSDKApplicationDelegate.sharedInstance().application(app, open: url, options: options)
}

ViewController.swift

import UIKit
import FBSDKLoginKit

class ViewController: UIViewController {

    let loginManager = FBSDKLoginManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        FBSDKProfile.enableUpdates(onAccessTokenChange: true)

        let button = UIButton(frame: CGRect(x: 40, y: 40, width: 200, height: 40))
        button.setTitle("Button", for: .normal)
        button.setTitleColor(.blue, for: .normal)
        button.addTarget(self, action: #selector(ViewController.login), for: .touchUpInside)
        view.addSubview(button)
    }

    func login() {
        if let token = FBSDKAccessToken.current() {
            // User is logged in, do work such as go to next view controller.
            print(token)
        } else {
            loginManager.logIn(withReadPermissions: ["public_profile"], from: self) { (loginManagerLoginResult, error) in

                FBSDKProfile.enableUpdates(onAccessTokenChange: true)
                print("token \(FBSDKAccessToken.current().tokenString)")

                FBSDKGraphRequest(graphPath: "me", parameters: nil).start(completionHandler: { (connection, result, error) -> Void in
                    if error == nil{
                        if let dict = result as? Dictionary<String, AnyObject>{
                            print(dict)
                        }
                    }
                })
            }
        }
    }
}

Result

You will be logged in and get user ID and name.

Read about

https://developers.facebook.com/docs/ios/getting-started
https://developers.facebook.com/docs/reference/ios/current/class/FBSDKLoginManager


问:
KeyError in append dict
I have large peace of data, iterate true this in loop and append values by key:

```<code>for q in my_dict:
output.append({"roomsCount": q['roomsCount'], "totalArea": float(q['totalArea']),
"floorNumber": q['floorNumber'],"price": int(q['bargainTerms']['price']), ...})
</code>```

Sometimes i got : KeyError: 'roomsCount' or KeyError: 'totalArea' etc. if key doesn't exist.

How i can set default value for any key in case if this key not exist? Without repeat try: except for each of my key:value pairs

答:
Solved by adding dict.get, thanks for comments. My code</p>

```<code>for q in mydict:
        output.append(
            {"roomsCount": q.get('roomsCount', 0), "totalArea": float(q.get('totalArea', 0)), "floorNumber": q.get('floorNumber',0),
             "price": int(q.get('bargainTerms''price',0))...})
</code>```

Title: KeyError in append dict

Body:
I have large peace of data, iterate true this in loop and append values by key:

for q in my_dict:
output.append({"roomsCount": q['roomsCount'], "totalArea": float(q['totalArea']),
"floorNumber": q['floorNumber'],"price": int(q['bargainTerms']['price']), ...})

Sometimes i got : KeyError: 'roomsCount' or KeyError: 'totalArea' etc. if key doesn't exist.

How i can set default value for any key in case if this key not exist? Without repeat try: except for each of my key:value pairs

Body:
Solved by adding dict.get, thanks for comments. My code

for q in mydict:
        output.append(
            {"roomsCount": q.get('roomsCount', 0), "totalArea": float(q.get('totalArea', 0)), "floorNumber": q.get('floorNumber',0),
             "price": int(q.get('bargainTerms''price',0))...})


问:
PyQt4 PostgreSQL QSqlQuery BC information loss
PyQt4 PostgreSQL QSqlQuery BC information loss

I am programming with PyQt4 and PostgreSQL, and I have a problem
reading dates before Christ (BC). With psql, all is OK:

```<code># SELECT id, born, givname FROM person WHERE id=100000;
   id   |     born      | givname
--------+---------------+---------
 100000 | 0428-01-01 BC | Plato
(1 row)
</code>```

But it seems the sign of the year, i.e. BC/AD information,
is lost somewhere on the way from the PostgreSQL server
to the PyQt QSqlQuery class.

see this Python code snippet:

```<code>from PyQt4.QtSql import QSqlQuery
sql = 'SELECT born FROM person WHERE id=100000'
query = QSqlQuery(sql)
query.next()
v = query.value(0)
print "v:", v
print "type:", type(v)
print "typename:", v.typeName()
d = v.toDate()
print "valid:", d.isValid()
print "d:", d, d.toString()
print 'dd.MM.yyyy:', d.toString('dd.MM.yyyy')
print "year:", d.year() # should be negative
print "toPyDate:", d.toPyDate()
print "toJulianDay:", d.toJulianDay()
</code>```

output:

```<code>v: <PyQt4.QtCore.QVariant object at 0xb216cd84>
type: <class 'PyQt4.QtCore.QVariant'>
typename: QDate
valid: True
d: PyQt4.QtCore.QDate(428, 1, 1) So. Jan 1 428
dd.MM.yyyy: 01.01.0428
year: 428
toPyDate: 0428-01-01
toJulianDay: 1877385
</code>```

Question:
Where is the BC information lost and how can I get it?

Answers to the posters' questions:

What is the actual julian day integer value that is stored in the datebase?

```<code>volker=# SELECT id, born, extract(julian from born), givname FROM person WHERE id=100000;
   id   |     born      | date_part | givname
--------+---------------+-----------+---------
 100000 | 0428-01-01 BC |   1565102 | Plato
</code>```

In PostgreSQL: (www.postgresql.org/docs/9.0/static/functions-formatting.html)
Julian Day (days since November 24, 4714 BC at midnight)
PostgreSQL returns 0 for SELECT EXTRACT(JULIAN FROM '4714-11-24 BC'::DATE);

Qt has a different definition for Julian day.
From pyqt.sourceforge.net/Docs/PyQt4/qdate.html#fromJulianDay:
"The range of valid dates is from January 2nd, 4713 BCE, ...".
(Maybe that's the difference between the proleptic Julian Calendar and
the proleptic Gregorian Calendar, as in the post by ekhumoro.)

Note that January 1st, 4713 BCE seems not to be considered valid:

```<code>>>> j1 = QDate.fromJulianDay(1)
>>> print j1.getDate()
(-4713, 1, 2)
>>> print j1.toString()
Di. Jan 2 -4713
>>> j0 = QDate.fromJulianDay(0)
>>> print j0.toString()

>>> print j0.getDate()
(-4713, 1, 1)
</code>```

But what is the actual value stored in the database?
I don't know what the server stores internally, I only take
as a reference what it passes to the psql client,
and that seems to be an ISO date string,
format YYYY-MM-DD, with ' BC' appended for BC years.
By the way, reading https://en.wikipedia.org/wiki/ISO_8601#Years
it seems BC notation is not ISO, but a year sign is.
That leads to the next question: Can I configure the server so it
yields '-0428-01-01' instead of '0428-01-01 BC'?

答:
OK, it's more a workaround than a solution,
but as ekhumoro suggested, I can retrieve the date
as a string (resp. TEXT in PostgreSQL), simply like this:

```<code>SELECT born::TEXT FROM person WHERE id=100000;
</code>```

giving the result:

```<code>0428-01-01 BC
</code>```

as string which I can parse for the BC suffix.

Using integer values is also possible, but then I have to deal with the difference between proleptic Julian (Qt) vs proleptic Gregorian (PostgreSQL) dates, which seems more complicated.

Body:
PyQt4 PostgreSQL QSqlQuery BC information loss

I am programming with PyQt4 and PostgreSQL, and I have a problem
reading dates before Christ (BC). With psql, all is OK:

# SELECT id, born, givname FROM person WHERE id=100000;
   id   |     born      | givname
--------+---------------+---------
 100000 | 0428-01-01 BC | Plato
(1 row)

But it seems the sign of the year, i.e. BC/AD information,
is lost somewhere on the way from the PostgreSQL server
to the PyQt QSqlQuery class.

see this Python code snippet:

from PyQt4.QtSql import QSqlQuery
sql = 'SELECT born FROM person WHERE id=100000'
query = QSqlQuery(sql)
query.next()
v = query.value(0)
print "v:", v
print "type:", type(v)
print "typename:", v.typeName()
d = v.toDate()
print "valid:", d.isValid()
print "d:", d, d.toString()
print 'dd.MM.yyyy:', d.toString('dd.MM.yyyy')
print "year:", d.year() # should be negative
print "toPyDate:", d.toPyDate()
print "toJulianDay:", d.toJulianDay()

output:

v: <PyQt4.QtCore.QVariant object at 0xb216cd84>
type: <class 'PyQt4.QtCore.QVariant'>
typename: QDate
valid: True
d: PyQt4.QtCore.QDate(428, 1, 1) So. Jan 1 428
dd.MM.yyyy: 01.01.0428
year: 428
toPyDate: 0428-01-01
toJulianDay: 1877385

Question:
Where is the BC information lost and how can I get it?

Answers to the posters' questions:

What is the actual julian day integer value that is stored in the datebase?

volker=# SELECT id, born, extract(julian from born), givname FROM person WHERE id=100000;
   id   |     born      | date_part | givname
--------+---------------+-----------+---------
 100000 | 0428-01-01 BC |   1565102 | Plato

In PostgreSQL: (www.postgresql.org/docs/9.0/static/functions-formatting.html)
Julian Day (days since November 24, 4714 BC at midnight)
PostgreSQL returns 0 for SELECT EXTRACT(JULIAN FROM '4714-11-24 BC'::DATE);

Qt has a different definition for Julian day.
From pyqt.sourceforge.net/Docs/PyQt4/qdate.html#fromJulianDay:
"The range of valid dates is from January 2nd, 4713 BCE, ...".
(Maybe that's the difference between the proleptic Julian Calendar and
the proleptic Gregorian Calendar, as in the post by ekhumoro.)

Note that January 1st, 4713 BCE seems not to be considered valid:

>>> j1 = QDate.fromJulianDay(1)
>>> print j1.getDate()
(-4713, 1, 2)
>>> print j1.toString()
Di. Jan 2 -4713
>>> j0 = QDate.fromJulianDay(0)
>>> print j0.toString()

>>> print j0.getDate()
(-4713, 1, 1)

But what is the actual value stored in the database?
I don't know what the server stores internally, I only take
as a reference what it passes to the psql client,
and that seems to be an ISO date string,
format YYYY-MM-DD, with ' BC' appended for BC years.
By the way, reading https://en.wikipedia.org/wiki/ISO_8601#Years
it seems BC notation is not ISO, but a year sign is.
That leads to the next question: Can I configure the server so it
yields '-0428-01-01' instead of '0428-01-01 BC'?

Body:
OK, it's more a workaround than a solution,
but as ekhumoro suggested, I can retrieve the date
as a string (resp. TEXT in PostgreSQL), simply like this:

SELECT born::TEXT FROM person WHERE id=100000;

giving the result:

0428-01-01 BC

as string which I can parse for the BC suffix.

Using integer values is also possible, but then I have to deal with the difference between proleptic Julian (Qt) vs proleptic Gregorian (PostgreSQL) dates, which seems more complicated.


问:
How to generate a random 8 digit string and verify that it was not generated already in feasible amount of time?
I need to generate a random string 8 digit long and next time when I generate the random number make sure it was not already generated. If we simply think I have to store every confirmation number generated and every time I try to generate a new one, verify that it was not already generated by looking at the stored values.

In my case the numbers are stored in database.

But if the already generated numbers are a lot, it can take significant time to validate that. What is the best way to approach this problem? This should work something like youtube video Id. It probably never happens that by chance youtube video id generator generates same video id twice. So they are definitely verifying that each time they generate a new videoid that it wasn't already generated and used for some other video. There can be a lot of them.

By feasible amount of time I mean something that would be useful to use from the website. If for a user of a website, I am asking certain information and creating a unique identifier for him/her, then I don't want the website to be slow because I am verifying that the randomly generated identifier doesn't already exist in the database.

答:
If you are using a random generator, and you need to check to make sure each number/string is unique, you can't just pick and check for uniqueness in a loop.  This will always take longer the more numbers you pick, and there is no reason that you can't just keep randomly picking 1 forever.

The only way to really get around the problem of uniqueness checks taking arbitrarily long is to create a shuffled list of all possible results and then removing one at a time.  You can generate the list in sequence and then use the Fisher Yates Shuffle to shuffle the list relatively efficiently.

The list of all 8 digits strings is quite long, but that is the safe way, and it will get smaller as you go on.


答:
Use the withCount() method which will calculate number of upvotes for each comment and will create upvotes_count property:

```<code> Comment::where('room_id', $roomId)
        ->withCount('upvotes')
        ->orderBy('upvotes_count', 'desc')
        ->get();
</code>```

Title: Sort Model by a nested Relationship count

Body:
Use the withCount() method which will calculate number of upvotes for each comment and will create upvotes_count property:

 Comment::where('room_id', $roomId)
        ->withCount('upvotes')
        ->orderBy('upvotes_count', 'desc')
        ->get();


问:
Is there a way to make css letter-spacing: 0.5 px?
I ran across the problem, I need to make it easy for users to read the text, so I used letter-spacing of 1 px, but it looks ugly, so I thought I'll use half a pixel so 0.5px, but it doesn't work, I tried using em attributes, but didn't achieve the task.

So is there a way to make letter spacing half pixel (cross browser solution if possible)

答:
Fractional letter-spacing values are supported by Webkit, Firefox, Chrome and Opera, since the end of 2013.

Confirmed by CSS Tricks - https://css-tricks.com/almanac/properties/l/letter-spacing/

And I just tested it.