问:
SQL Like or REGEXP filter results even when everything should be matched
this is what i have

```<code>SELECT node.nid AS nid, node.type AS node_type, product.*
FROM ml_node node
LEFT JOIN ml_content_type_product product
  ON node.vid = product.vid
WHERE (node.type in('product'))
  AND product.field_sockel_value REGEXP '.*'
  AND product.field_artikel_value REGEXP '.*'
  AND product.field_leistung_value REGEXP '.*'
  AND product.field_licht_farbe_value REGEXP '.*'
  AND product.field_rubrik_value REGEXP '.*'
  AND product.field_artikelgruppe_value REGEXP '.*'
ORDER BY product.field_artikel_value
</code>```

Having these where-conditions I would assume that this gives the same results as:

```<code>SELECT node.nid AS nid, node.type AS node_type, product.*
FROM ml_node node
LEFT JOIN ml_content_type_product product
  ON node.vid = product.vid
WHERE (node.type in('product'))
ORDER BY product.field_artikel_value
</code>```

But it does not. The first returns 494 rows and the last one gives 717. So there's missing a bunch of rows. When I use this query

```<code>SELECT node.nid AS nid, node.type AS node_type, product.*
FROM ml_node node
LEFT JOIN ml_content_type_product product
  ON node.vid = product.vid
WHERE (node.type in('product'))
  AND product.field_artikel_value REGEXP '.*'
  AND product.field_leistung_value REGEXP '.*'
  AND product.field_rubrik_value REGEXP '.*'
  AND product.field_artikelgruppe_value REGEXP '.*'
ORDER BY product.field_artikel_value
</code>```

I also do get 717 rows. So… what could it be that makes those removed conditions so special? The columns are all of type longtext (because the cms does so) and have the exact same attributes.

BTW i noticed the same behavior when using LIKE instead of REGEXP.

答:
This could be caused by NULL values in certain rows.  A NULL field will evaluate to False when compared with another value.

If you want to get all the values back with your second query, move the product-table-related expressions in the WHERE clause into your join criteria, so you end up with:

```<code>SELECT node.nid AS nid, node.type AS node_type, product.*
FROM ml_node node
  LEFT JOIN ml_content_type_product product
  ON node.vid = product.vid
    AND product.field_sockel_value REGEXP '.*'
    AND product.field_artikel_value REGEXP '.*'
    AND product.field_leistung_value REGEXP '.*'
    AND product.field_licht_farbe_value REGEXP '.*'
    AND product.field_rubrik_value REGEXP '.*'
    AND product.field_artikelgruppe_value REGEXP '.*'
WHERE (node.type in('product'))
ORDER BY product.field_artikel_value
</code>```

This will ensure the join is only made when it meets your other criteria, but will still return all of your node records, where the type is correct.

Body:
this is what i have

SELECT node.nid AS nid, node.type AS node_type, product.*
FROM ml_node node
LEFT JOIN ml_content_type_product product
  ON node.vid = product.vid
WHERE (node.type in('product'))
  AND product.field_sockel_value REGEXP '.*'
  AND product.field_artikel_value REGEXP '.*'
  AND product.field_leistung_value REGEXP '.*'
  AND product.field_licht_farbe_value REGEXP '.*'
  AND product.field_rubrik_value REGEXP '.*'
  AND product.field_artikelgruppe_value REGEXP '.*'
ORDER BY product.field_artikel_value

Having these where-conditions I would assume that this gives the same results as:

SELECT node.nid AS nid, node.type AS node_type, product.*
FROM ml_node node
LEFT JOIN ml_content_type_product product
  ON node.vid = product.vid
WHERE (node.type in('product'))
ORDER BY product.field_artikel_value

But it does not. The first returns 494 rows and the last one gives 717. So there's missing a bunch of rows. When I use this query

SELECT node.nid AS nid, node.type AS node_type, product.*
FROM ml_node node
LEFT JOIN ml_content_type_product product
  ON node.vid = product.vid
WHERE (node.type in('product'))
  AND product.field_artikel_value REGEXP '.*'
  AND product.field_leistung_value REGEXP '.*'
  AND product.field_rubrik_value REGEXP '.*'
  AND product.field_artikelgruppe_value REGEXP '.*'
ORDER BY product.field_artikel_value

I also do get 717 rows. So… what could it be that makes those removed conditions so special? The columns are all of type longtext (because the cms does so) and have the exact same attributes.

BTW i noticed the same behavior when using LIKE instead of REGEXP.

Body:
This could be caused by NULL values in certain rows.  A NULL field will evaluate to False when compared with another value.

If you want to get all the values back with your second query, move the product-table-related expressions in the WHERE clause into your join criteria, so you end up with:

SELECT node.nid AS nid, node.type AS node_type, product.*
FROM ml_node node
  LEFT JOIN ml_content_type_product product
  ON node.vid = product.vid
    AND product.field_sockel_value REGEXP '.*'
    AND product.field_artikel_value REGEXP '.*'
    AND product.field_leistung_value REGEXP '.*'
    AND product.field_licht_farbe_value REGEXP '.*'
    AND product.field_rubrik_value REGEXP '.*'
    AND product.field_artikelgruppe_value REGEXP '.*'
WHERE (node.type in('product'))
ORDER BY product.field_artikel_value

This will ensure the join is only made when it meets your other criteria, but will still return all of your node records, where the type is correct.


来源: stackexchange

问:
Not ableTo Serialize Dictionary with Complex key using Json.net
I have a dictionary with a custom .net Type as Its key.I am trying to serialize this dictionary to JSON using JSON.net, However its not able to Convert Keys to Proper Value during Serialization.

```<code>class ListBaseClass
{
    public String testA;
    public String testB;
}
-----
var details = new Dictionary<ListBaseClass, string>();
details.Add(new ListBaseClass { testA = "Hello", testB = "World" }, "Normal");
var results = Newtonsoft.Json.JsonConvert.SerializeObject(details);
var data = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<ListBaseClass, string>> results);
</code>```

This Give me --> "{\"JSonSerialization.ListBaseClass\":\"Normal\"}"

However if I have my Custom type as value in Dictionary it Works well

```<code>  var details = new Dictionary<string, ListBaseClass>();
  details.Add("Normal", new ListBaseClass { testA = "Hello", testB = "World" });
  var results = Newtonsoft.Json.JsonConvert.SerializeObject(details);
  var data = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, ListBaseClass>>(results);
</code>```

This Give me --> "{\"Normal\":{\"testA\":\"Hello\",\"testB\":\"World\"}}"

Can Someone Suggest If I am hitting some limitation of Json.net or I am doing Something Wrong?

答:
This is a pretty common problem people run into when they start using serializers. While it is a little puzzling why the limitation you discovered exists, there is a simple solution.

When I first wrote this answer a number of years back, Gordon Bean had replied with a workable solution to the problem using a type converter. You probably don't want to use that approach, though. It works, but it provides a serialized string for output. If you are using JSON, this will give you a less than ideal result, since you really want a JSON representation of an object and not a string representation.

for example, let's suppose that you have a data structure that associates unique grid points with strings:

```<code>class Point
{
    public int x { get; set; }
    public int y { get; set; }
}

public Dictionary<Point,string> Locations { get; set; };
</code>```

Using the TypeConverter override, you will get a string representation of this object when you serialize it.

```<code>"Locations": {
  "4,3": "foo",
  "3,4": "bar"
},
</code>```

But what we really want is:

```<code>"Locations": {
  { "x": 4, "y": 3 }: "foo",
  { "x": 3, "y": 4 }: "bar"
},
</code>```

There are several problems with overriding the TypeConverter to serialize / deserialize the class.

First, this is not JSON, and you might have to write additional custom logic to deal with serialize and deserialize it elsewhere. (perhaps Javascript in your client layer, for example?)

Second, anywhere else that uses this object will now produce this string, where previously it serialized properly to an object. For example,

```<code>"GridCenterPoint": { "x": 0, "y": 0 },
</code>```

now serializes to:

```<code>"GridCenterPoint": "0,0",
</code>```

You can control the TypeConverter formatting a little, but you cannot get away from the fact it is rendered as a string and not an object.

This problem isn't a problem with the serializer, since Json.NET chews through complex objects without missing a beat, it is a problem with the way that dictionary keys are processed. If you try taking the example object, and serializing a List or even a Hashset, you notice that there isn't a problem producing proper JSON. This gives us a much simpler way to solve this problem.

Ideally, we would like to just tell Json.NET to serialize the key as whatever object type it is, and not force it to be a string. Since that doesn't seem to be an option, the other way is to give Json.NET something that it can work with: a List<KeyValuePair<T,K>>.

If you feed a list of KeyValuePairs into Json.NET's serializer, you get exactly what you expect. For example, here is a much simpler wrapper that you could implement:

```<code>    private Dictionary<Point, string> _Locations;
    public List<KeyValuePair<Point, string>> SerializedLocations
    {
        get { return _Locations.ToList(); }
        set { _Locations= value.ToDictionary(x => x.Key, x => x.Value); }
    }
</code>```

Update from  @bmw15 comment:

You can make the Dictionary prop public, add a [JsonIgnore] to it, and make
the list of KeyValuePairs private, with a [JsonProperty] attribute

This trick works, because keys in a kvp aren't forced into string format. Why does the type converter generate a string format, you ask? It beats the hell out of me. The Dictionary object implements the IEnumerable<KeyValuePair<TKey, TValue>> interface, so there shouldn't be any problem in serializing it in the same fashion as the list of kvps, since that is essentially what a dictionary is. Someone (James Newton?) made a decision when writing the Newtonsoft dictionary serializer that complex keys were too messy to deal with. There are probably some corner cases I have not considered that make this a much more sticky problem.

I think that this is a much better solution because it produces actual JSON objects, is technically simpler, and doesn't produce any side effects resulting from replacing the serializer.

ContentLicense: CC BY-SA 3.0

Body:
I have a dictionary with a custom .net Type as Its key.I am trying to serialize this dictionary to JSON using JSON.net, However its not able to Convert Keys to Proper Value during Serialization.

class ListBaseClass
{
    public String testA;
    public String testB;
}
-----
var details = new Dictionary<ListBaseClass, string>();
details.Add(new ListBaseClass { testA = "Hello", testB = "World" }, "Normal");
var results = Newtonsoft.Json.JsonConvert.SerializeObject(details);
var data = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<ListBaseClass, string>> results);

This Give me --> "{\"JSonSerialization.ListBaseClass\":\"Normal\"}"

However if I have my Custom type as value in Dictionary it Works well

  var details = new Dictionary<string, ListBaseClass>();
  details.Add("Normal", new ListBaseClass { testA = "Hello", testB = "World" });
  var results = Newtonsoft.Json.JsonConvert.SerializeObject(details);
  var data = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, ListBaseClass>>(results);

This Give me --> "{\"Normal\":{\"testA\":\"Hello\",\"testB\":\"World\"}}"

Can Someone Suggest If I am hitting some limitation of Json.net or I am doing Something Wrong?

Body:
This is a pretty common problem people run into when they start using serializers. While it is a little puzzling why the limitation you discovered exists, there is a simple solution.

When I first wrote this answer a number of years back, Gordon Bean had replied with a workable solution to the problem using a type converter. You probably don't want to use that approach, though. It works, but it provides a serialized string for output. If you are using JSON, this will give you a less than ideal result, since you really want a JSON representation of an object and not a string representation.

for example, let's suppose that you have a data structure that associates unique grid points with strings:

class Point
{
    public int x { get; set; }
    public int y { get; set; }
}

public Dictionary<Point,string> Locations { get; set; };

Using the TypeConverter override, you will get a string representation of this object when you serialize it.

"Locations": {
  "4,3": "foo",
  "3,4": "bar"
},

But what we really want is:

"Locations": {
  { "x": 4, "y": 3 }: "foo",
  { "x": 3, "y": 4 }: "bar"
},

There are several problems with overriding the TypeConverter to serialize / deserialize the class.

First, this is not JSON, and you might have to write additional custom logic to deal with serialize and deserialize it elsewhere. (perhaps Javascript in your client layer, for example?)

Second, anywhere else that uses this object will now produce this string, where previously it serialized properly to an object. For example,

"GridCenterPoint": { "x": 0, "y": 0 },

now serializes to:

"GridCenterPoint": "0,0",

You can control the TypeConverter formatting a little, but you cannot get away from the fact it is rendered as a string and not an object.

This problem isn't a problem with the serializer, since Json.NET chews through complex objects without missing a beat, it is a problem with the way that dictionary keys are processed. If you try taking the example object, and serializing a List or even a Hashset, you notice that there isn't a problem producing proper JSON. This gives us a much simpler way to solve this problem.

Ideally, we would like to just tell Json.NET to serialize the key as whatever object type it is, and not force it to be a string. Since that doesn't seem to be an option, the other way is to give Json.NET something that it can work with: a List<KeyValuePair<T,K>>.

If you feed a list of KeyValuePairs into Json.NET's serializer, you get exactly what you expect. For example, here is a much simpler wrapper that you could implement:

    private Dictionary<Point, string> _Locations;
    public List<KeyValuePair<Point, string>> SerializedLocations
    {
        get { return _Locations.ToList(); }
        set { _Locations= value.ToDictionary(x => x.Key, x => x.Value); }
    }

Update from  @bmw15 comment:

You can make the Dictionary prop public, add a [JsonIgnore] to it, and make
the list of KeyValuePairs private, with a [JsonProperty] attribute

This trick works, because keys in a kvp aren't forced into string format. Why does the type converter generate a string format, you ask? It beats the hell out of me. The Dictionary object implements the IEnumerable<KeyValuePair<TKey, TValue>> interface, so there shouldn't be any problem in serializing it in the same fashion as the list of kvps, since that is essentially what a dictionary is. Someone (James Newton?) made a decision when writing the Newtonsoft dictionary serializer that complex keys were too messy to deal with. There are probably some corner cases I have not considered that make this a much more sticky problem.

I think that this is a much better solution because it produces actual JSON objects, is technically simpler, and doesn't produce any side effects resulting from replacing the serializer.

ContentLicense: CC BY-SA 4.0


问:
How to Stop observable.timer in Angular2
I am implementing the following functions in Angular2's Component:

```<code>export class MypageEditComponent {

  ngOnInit() {
    this.timer = Observable.timer(100, 100);
    this.timer.subscribe(t => {
      this.setFormData();
  }

  private setFormData() {
    this.editUserAcountType = this.authStore.registerInfo.account_type;
    this.editAddress = this.authStore.registerInfo.email;
    this.editUserName = this.authStore.registerInfo.username;
  }
}
</code>```

I want to stop the repeat of Observable.timer once the value is correctly stored with setFormData().

But do not know how, please tell me.

答:
A nuance which previous answers haven't really covered is that there is no need to stop an observable timer/interval - at least not by interacting with the observable or the timer itself.

I found myself here because I was setting up an observable using a timer in a HostedService's start method, and in the stop method it seemed like I should be stopping it, or disposing of something surely? - well... no. The observable timer does not need to be stopped or disposed in this way, only the subscriptions, and this is why...

Observable timers and intervals are examples of cold streams (though they appear to behave as hot).  They are passive not active, they do not produce data till subscribed to, and stop producing data when no subscribers.  Therefore, disposal of all subscriptions should be all that's required to stop the timer producing data.

More info here... [http://introtorx.com/Content/v1.0.10621.0/14_HotAndColdObservables.html]

Body:
I am implementing the following functions in Angular2's Component:

export class MypageEditComponent {

  ngOnInit() {
    this.timer = Observable.timer(100, 100);
    this.timer.subscribe(t => {
      this.setFormData();
  }

  private setFormData() {
    this.editUserAcountType = this.authStore.registerInfo.account_type;
    this.editAddress = this.authStore.registerInfo.email;
    this.editUserName = this.authStore.registerInfo.username;
  }
}

I want to stop the repeat of Observable.timer once the value is correctly stored with setFormData().

But do not know how, please tell me.


问:
Type classes, implicit conversion, multiple type parameters
I am trying to create a type class with multiple type parameters.
I am trying to invoke the method implicitly based on the types

I am showing  a simple snippet of the code I have tried.

```<code>object operation {
// Define generic trait class
  trait Operator[T, U] {
    def addition[T, U](l: U, r: T)(implicit p: Parameters): U
  }

  object Operator {
// Define type class.
    implicit object IntOperator extends Operator[Int, Float] {
      def addition(l: Int, r: Float): Float = {
        r
      }
    }
  }
// Create mapping for implicit call.
  def addition[T, U](l: T, r: U)(implicit op: Operator[T, U]): U = op.addition(l, r,)
  }

import  operation._

def fn(a: UInt, b: Float)
addition(a,b)
</code>```

If I use a single type parameter i.e., only [T,U] then this code compiles fine. However If I use two type parameters i.e., Operator[T,U] then the addition(a,b) complains
No implicits found for parameter Operator[T,U]. Any help would be appreciated.

I hope the simplified code snippet elaborates on what I am trying to do.

答:
Just to let you know this compiles and works as expected.

```<code>object operation {
  trait Operator[T, U] {
    def addition(l: T, r: U): U
  }

  object Operator {
    implicit final val IntFloatOperator: Operator[Int, Float] =
      new Operator[Int, Float] {
        override def addition(l: Int, r: Float): Float = l + r
      }
  }

  def addition[T, U](l: T, r: U)(implicit op: Operator[T, U]): U = op.addition(l, r)
}

def fn(a: Int, b: Float): Float = operation.addition(a, b)
fn(1, 10.0f) // 11.0F
</code>```

Edit

Addressing the comment you can either:

1) Provide the required implicit.

```<code>def fn[T1 <: Int, T2 <: Float](a: T1, b: T2)(implicit op: Operator[T1, U1]): U1 =
  op.addition(a, b)
</code>```

(Note: The user of the method is in charge of having in scope an implicit of type Operator[T1, U1] for the types he/she is using.)

2) Explicitly summon the IntFloatOperator.

def fn[T1 <: Int, T2 <: Float](a: T1, b: T2): T2 =
  implicitly[Operator[Int, Float]].addition(a, b)

(Note: that it is common to provide a custom summoner, to reduce boilerplate.)

```<code>object Operator {
  // Summoner.
  def apply[T, U](implicit op: Operator[T, U]): Operator[T, U] = op

  ...
}

def fn[T1 <: Int, T2 <: Float](a: T1, b: T2): T2 =
  Operator[Int, Float].addition(a, b)
</code>```

Body:
I am trying to create a type class with multiple type parameters.
I am trying to invoke the method implicitly based on the types

I am showing  a simple snippet of the code I have tried.

object operation {
// Define generic trait class
  trait Operator[T, U] {
    def addition[T, U](l: U, r: T)(implicit p: Parameters): U
  }

  object Operator {
// Define type class.
    implicit object IntOperator extends Operator[Int, Float] {
      def addition(l: Int, r: Float): Float = {
        r
      }
    }
  }
// Create mapping for implicit call.
  def addition[T, U](l: T, r: U)(implicit op: Operator[T, U]): U = op.addition(l, r,)
  }

import  operation._

def fn(a: UInt, b: Float)
addition(a,b)

If I use a single type parameter i.e., only [T,U] then this code compiles fine. However If I use two type parameters i.e., Operator[T,U] then the addition(a,b) complains
No implicits found for parameter Operator[T,U]. Any help would be appreciated.

I hope the simplified code snippet elaborates on what I am trying to do.

Body:
Just to let you know this compiles and works as expected.

object operation {
  trait Operator[T, U] {
    def addition(l: T, r: U): U
  }

  object Operator {
    implicit final val IntFloatOperator: Operator[Int, Float] =
      new Operator[Int, Float] {
        override def addition(l: Int, r: Float): Float = l + r
      }
  }

  def addition[T, U](l: T, r: U)(implicit op: Operator[T, U]): U = op.addition(l, r)
}

def fn(a: Int, b: Float): Float = operation.addition(a, b)
fn(1, 10.0f) // 11.0F

Edit

Addressing the comment you can either:

1) Provide the required implicit.

def fn[T1 <: Int, T2 <: Float](a: T1, b: T2)(implicit op: Operator[T1, U1]): U1 =
  op.addition(a, b)

(Note: The user of the method is in charge of having in scope an implicit of type Operator[T1, U1] for the types he/she is using.)

2) Explicitly summon the IntFloatOperator.

def fn[T1 <: Int, T2 <: Float](a: T1, b: T2): T2 =
  implicitly[Operator[Int, Float]].addition(a, b)

(Note: that it is common to provide a custom summoner, to reduce boilerplate.)

object Operator {
  // Summoner.
  def apply[T, U](implicit op: Operator[T, U]): Operator[T, U] = op

  ...
}

def fn[T1 <: Int, T2 <: Float](a: T1, b: T2): T2 =
  Operator[Int, Float].addition(a, b)


问:
What is the best approach to clone objects properties when using map()?
I want to add a new property (contactDetails.countryName) and assign a value to a nested object stored in an array called users using the function map().

I've recently learned that I should use the spread operator (...) and then create / assign the new property in order to avoid mutating my original array of objects so I've developed 2 different implementations for this but I'm not really confident I'm following the best practices to accomplish I want to regarding the semantic and performance.

What would be the best approach to accomplish what I want to do in your opinion?

```<code>const countries = [
  { id: 3, countryName : "UK" },
  { id: 4, countryName : "Spain" },
  { id: 6, countryName : "Germany"}
];

const users = [
  { id : 1,
    name: "Douglas Camp",
    dateOfBirth: "23-06-1984",
    contactDetails:
      {
        country: 3,
        phone: "7373724997"
      }
  },
  {
    id : 2,
    name: "Martin Stein",
    dateOfBirth: "19-08-1992",
    contactDetails:
      {
        country: 6,
        phone: "3334343434"
      }
  },
];

const usersData = users.map(user=> {

// Version 1 : using spreading operator twice

const newUser = {
    ...user,
    contactDetails: {
      ...user.contactDetails,
      countryName: countries.find(c=> c.id == user.contactDetails.country).countryName
    }
  };
  return newUser;
});

// Version 2: copying the original object property and using spread operator only for cloning the nested object properties

const newUser = {
    id: user.id,
    name: user.name,
    dateOfBirth: user.dateOfBirth,
    contactDetails: {
      ...user.contactDetails,
      countryName: countries.find(c=> c.id == user.contactDetails.country).countryName
    }
  };

console.log(users);
console.log(usersData);
</code>```

答:
I normally use version 1, the spread operator twice. I also would consider checking out immer which allows you to do mutable updates on a cloned draft and handles merging it back for you.

```<code>const newUser = immer(user, draft => {
  draft.contactDetails.countryName = countries.find(
    c => c.id == user.contactDetails.country).countryName
  )
})
</code>```

Just edit the specific property you want and immer handles copying the rest of it.

Body:
I want to add a new property (contactDetails.countryName) and assign a value to a nested object stored in an array called users using the function map().

I've recently learned that I should use the spread operator (...) and then create / assign the new property in order to avoid mutating my original array of objects so I've developed 2 different implementations for this but I'm not really confident I'm following the best practices to accomplish I want to regarding the semantic and performance.

What would be the best approach to accomplish what I want to do in your opinion?

const countries = [
  { id: 3, countryName : "UK" },
  { id: 4, countryName : "Spain" },
  { id: 6, countryName : "Germany"}
];

const users = [
  { id : 1,
    name: "Douglas Camp",
    dateOfBirth: "23-06-1984",
    contactDetails:
      {
        country: 3,
        phone: "7373724997"
      }
  },
  {
    id : 2,
    name: "Martin Stein",
    dateOfBirth: "19-08-1992",
    contactDetails:
      {
        country: 6,
        phone: "3334343434"
      }
  },
];

const usersData = users.map(user=> {

// Version 1 : using spreading operator twice

const newUser = {
    ...user,
    contactDetails: {
      ...user.contactDetails,
      countryName: countries.find(c=> c.id == user.contactDetails.country).countryName
    }
  };
  return newUser;
});

// Version 2: copying the original object property and using spread operator only for cloning the nested object properties

const newUser = {
    id: user.id,
    name: user.name,
    dateOfBirth: user.dateOfBirth,
    contactDetails: {
      ...user.contactDetails,
      countryName: countries.find(c=> c.id == user.contactDetails.country).countryName
    }
  };

console.log(users);
console.log(usersData);

Body:
I normally use version 1, the spread operator twice. I also would consider checking out immer which allows you to do mutable updates on a cloned draft and handles merging it back for you.

const newUser = immer(user, draft => {
  draft.contactDetails.countryName = countries.find(
    c => c.id == user.contactDetails.country).countryName
  )
})

Just edit the specific property you want and immer handles copying the rest of it.


问:
How to plot roads on maps between two points based on GeoJSON file?
I want to visualize possible roads between two points, something like google map, I have a GeoJSON file that contains the roads network, is it possible or is there any algorithm to plot only roads between two points?

-This is what I have done, and I want the line to be according to the roads.

答:
What platform do you use? For PostgreSQL / PostGIS there is PG Routing extension that you can use. It can find shortest path between vertices of road network. So you would need to find the vertices of the road network closest to the start and destination, and then find a route between them. There are plenty of guides, e.g. https://anitagraser.com/2011/02/07/a-beginners-guide-to-pgrouting/

If you are using raw Python, recreate Dijkstra Shortest Path algorithm.


问:
Flex: How to create an Image control from a flash.display.Bitmap?
I need to create an Image control from a Bitmap because I have an ItemRedender to use in a List control.

I'm trying to show a list of images (Bitmaps) in a List control and I couldn't by now.

答:
Try this example hopefully this will helps

Please modify image paths

```<code><?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:Script>
        <![CDATA[
            [Embed(source="assets/<image1>")]
            [Bindable]
            public var img1:Class;

            [Embed(source="assets/<image2>")]
            [Bindable]
            public var img2:Class;
            [Bindable]
            private var arr:Array = new Array({image:img1},{image:img2});

        ]]>
    </mx:Script>
    <mx:List dataProvider="{arr}" width="100%" height="100%">
        <mx:itemRenderer>
            <mx:Component>
                <mx:Image source="{data.image}"/>
            </mx:Component>
        </mx:itemRenderer>
    </mx:List>
</mx:Application>
</code>```

Body:
Try this example hopefully this will helps

Please modify image paths

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    <mx:Script>
        <![CDATA[
            [Embed(source="assets/<image1>")]
            [Bindable]
            public var img1:Class;

            [Embed(source="assets/<image2>")]
            [Bindable]
            public var img2:Class;
            [Bindable]
            private var arr:Array = new Array({image:img1},{image:img2});

        ]]>
    </mx:Script>
    <mx:List dataProvider="{arr}" width="100%" height="100%">
        <mx:itemRenderer>
            <mx:Component>
                <mx:Image source="{data.image}"/>
            </mx:Component>
        </mx:itemRenderer>
    </mx:List>
</mx:Application>


答:
Cloning and merging MapsSection
Just like Arrays, Maps can be cloned:</p>

```<code>var original = new Map([
  [1, 'one']
]);

var clone = new Map(original);

console.log(clone.get(1)); // one
console.log(original === clone); // false. Useful for shallow comparison
</code>```

Title: What is the best approach to clone objects properties when using map()?

Body:
Cloning and merging MapsSection
Just like Arrays, Maps can be cloned:

var original = new Map([
  [1, 'one']
]);

var clone = new Map(original);

console.log(clone.get(1)); // one
console.log(original === clone); // false. Useful for shallow comparison


问:
Case When Syntax Is Returning Extra NULLS
I am using a Case When in the below code and the outcome produces extra NULL values that should not be there. Any ideas what I am doing wrong with the below code?

```<code>SELECT distinct
Case when
status_level = 'CLAIM'
AND
 status = 'CLOSED'
THEN effective_date
END FirstCloseDate
FROM
STATUS
</code>```

Current results are:

```<code>+----------------+
| FirstCloseDate |
+----------------+
| (null)         |
| 02-JUL-18      |
+----------------+
</code>```

Result should be

```<code>+----------------+
| FirstCloseDate |
+----------------+
| 02-JUL-18      |
+----------------+
</code>```

Thanks for any help in advance!

答:
CASE yields NULL if none of the WHEN branches match and no ELSE branch is defined. So you get NULLs for records where status_level = 'CLAIM' AND status = 'CLOSED' is not satisfied.

Your expected result looks like you just want records, that fulfill the status_level = 'CLAIM' AND status = 'CLOSED' condition. To filter records use a WHERE clause not a CASE in the list of columns.

```<code>SELECT DISTINCT
       effective_date firstclosedate
       FROM status
       WHERE status_level = 'CLAIM'
             AND status = 'CLOSED';
</code>```

You can additionally filter effective_dates that are NULL should there be any if you want to omit them.

```<code>SELECT DISTINCT
       effective_date firstclosedate
       FROM status
       WHERE status_level = 'CLAIM'
             AND status = 'CLOSED'
             AND effective_date IS NOT NULL;
</code>```

Body:
I am using a Case When in the below code and the outcome produces extra NULL values that should not be there. Any ideas what I am doing wrong with the below code?

SELECT distinct
Case when
status_level = 'CLAIM'
AND
 status = 'CLOSED'
THEN effective_date
END FirstCloseDate
FROM
STATUS

Current results are:

+----------------+
| FirstCloseDate |
+----------------+
| (null)         |
| 02-JUL-18      |
+----------------+

Result should be

+----------------+
| FirstCloseDate |
+----------------+
| 02-JUL-18      |
+----------------+

Thanks for any help in advance!

Body:
CASE yields NULL if none of the WHEN branches match and no ELSE branch is defined. So you get NULLs for records where status_level = 'CLAIM' AND status = 'CLOSED' is not satisfied.

Your expected result looks like you just want records, that fulfill the status_level = 'CLAIM' AND status = 'CLOSED' condition. To filter records use a WHERE clause not a CASE in the list of columns.

SELECT DISTINCT
       effective_date firstclosedate
       FROM status
       WHERE status_level = 'CLAIM'
             AND status = 'CLOSED';

You can additionally filter effective_dates that are NULL should there be any if you want to omit them.

SELECT DISTINCT
       effective_date firstclosedate
       FROM status
       WHERE status_level = 'CLAIM'
             AND status = 'CLOSED'
             AND effective_date IS NOT NULL;


答: I personally like to use Version 1, as it makes your code much less redundant and easier to read. It also passes all the properties of  'user' down to newUser. </p>


问:
How to increase the highest overshooting bounds for ElasticOutCurve in Flutter?
For ElasticOutCurve, I would like to increase the highest value of overshooting bounds. I tried to create a custom curve or increasing the period, so far no luck.

How can I achieve this?

答:
First let's take a look at the source of ElasticOutCurve (from flutter source):

class ElasticOutCurve extends Curve {
  /// Creates an elastic-out curve.
  ///
  /// Rather than creating a new instance, consider using [Curves.elasticOut].
  const ElasticOutCurve([this.period = 0.4]);

  /// The duration of the oscillation.
  final double period;

  @override
  double transformInternal(double t) {
    final double s = period / 4.0;
    return math.pow(2.0, -10 * t) * math.sin((t - s) * (math.pi * 2.0) / period) + 1.0;
  }

  @override
  String toString() {
    return '$runtimeType($period)';
  }
}
```

We can see that all they're doing is some basic math.

Here's a graph showing the easing curve from the fluter algorithm:

And here's what happens if you multiply the (pow * sin) section by 3:

All credit goes to Wolfram Alpha for the charts.

If you played with the different constants you can also adjust it in other ways, although you'll want to make sure it always starts at 0 and ends at 1.

It's unfortunate that the Flutter team didn't make the curve a bit more flexible, but since flutter is open source it's easy enough to copy their curve to make your own.

Body:
First let's take a look at the source of ElasticOutCurve (from flutter source):

class ElasticOutCurve extends Curve {
  /// Creates an elastic-out curve.
  ///
  /// Rather than creating a new instance, consider using [Curves.elasticOut].
  const ElasticOutCurve([this.period = 0.4]);

  /// The duration of the oscillation.
  final double period;

  @override
  double transformInternal(double t) {
    final double s = period / 4.0;
    return math.pow(2.0, -10 * t) * math.sin((t - s) * (math.pi * 2.0) / period) + 1.0;
  }

  @override
  String toString() {
    return '$runtimeType($period)';
  }
}

We can see that all they're doing is some basic math.

Here's a graph showing the easing curve from the fluter algorithm:

And here's what happens if you multiply the (pow * sin) section by 3:

All credit goes to Wolfram Alpha for the charts.

If you played with the different constants you can also adjust it in other ways, although you'll want to make sure it always starts at 0 and ends at 1.

It's unfortunate that the Flutter team didn't make the curve a bit more flexible, but since flutter is open source it's easy enough to copy their curve to make your own.


问:
How to Dynamically Autofill Cells
I would like to dynamically fill a column. However, with the VBA code I have now, the formula fills all the way to the max row count (1.04 million). I would like it to stop at the max rows found in the column to its left (same as manual auto fill)

```<code>Sub Vlookup()

Range("C2").Select
ActiveCell.FormulaR1C1 =
"=IFERROR(VLOOKUP(RC[-2],'C:\Test.xlsx'!R2C6:R1000C15,10,FALSE),"""")"
Selection.AutoFill Destination:=Range("C2", Range("C2").End(xlDown))

End Sub
</code>```

I tried to use

```<code>Selection.Autofill Destination :=
Range("C2",Selection.Range("C2").End(xldown))
</code>```

But that didnt seem to work either

答:
You always want to use Long when finding the last row.  Integers only go to 32,767 and there are over 1 million rows.  You should also avoid using Select.

```<code>Dim lastRow as Long
lastRow=Cells(Rows.Count,2).End(xlup).Row

Range("C2").AutoFill Destination:=Range("C2:C" & lastRow)
</code>```

Title: How to Dynamically Autofill Cells

Body:
I would like to dynamically fill a column. However, with the VBA code I have now, the formula fills all the way to the max row count (1.04 million). I would like it to stop at the max rows found in the column to its left (same as manual auto fill)

Sub Vlookup()

Range("C2").Select
ActiveCell.FormulaR1C1 =
"=IFERROR(VLOOKUP(RC[-2],'C:\Test.xlsx'!R2C6:R1000C15,10,FALSE),"""")"
Selection.AutoFill Destination:=Range("C2", Range("C2").End(xlDown))

End Sub

I tried to use

Selection.Autofill Destination :=
Range("C2",Selection.Range("C2").End(xldown))

But that didnt seem to work either

Body:
You always want to use Long when finding the last row.  Integers only go to 32,767 and there are over 1 million rows.  You should also avoid using Select.

Dim lastRow as Long
lastRow=Cells(Rows.Count,2).End(xlup).Row

Range("C2").AutoFill Destination:=Range("C2:C" & lastRow)


问:
Python3 Parsing Email Body Differently than Python2
Currently I am working on an email parser that simply uses imaplib to establish a connection to my gmail account and read new emails.

This all works fine and the results are as expected when running my script using python2 (i.e "python myScript.py")

For example, if I had an email that looked like this:

```<code>To: receiver@qwerty.com
From: sender@asdf.com
Subject: Test Subject

Test1
Test2
</code>```

My script will output as expected:

```<code>To: receiver@qwerty.com
From: sender@asdf.com
Subject: Test Subject
Body: Test1
Test2
</code>```

However, when running this using python3 (i.e "python3 myScript.py"), the results are not the same and escaped characters are shown in the message body, see below:

```<code>To: receiver@qwerty.com
From: sender@asdf.com
Subject: Test Subject
Body: b'Test1\r\nTest2\r\n'
</code>```

And below is the code used for this process:

```<code>def readMailbox(mail):
    res, data = mail.uid('search', None, 'UNSEEN')
    i = len(data[0].split())

    for x in range(i):
        latestEmailUID = data[0].split()[x]
        result, emailData = mail.uid('fetch', latestEmailUID, '(RFC822)')
        emailMessage = email.message_from_string(emailData[0][1].decode('utf-8'))

        emailFrom = str(email.header.make_header(email.header.decode_header(emailMessage['From'])))
        emailTo = str(email.header.make_header(email.header.decode_header(emailMessage['To'])))
        subject = str(email.header.make_header(email.header.decode_header(emailMessage['Subject'])))

        # Body details
        for part in emailMessage.walk():
            if part.get_content_type() == 'text/plain':
                body = part.get_payload(decode=True)
                print('To: %s' % emailTo)
                print('From: %s' % emailFrom)
                print('Subject: %s' % subject)
                print('Body: %s' % body)
</code>```

I am going to need to be able to capture the string body without showing escaped characters for use later on. Can anyone explain to me please why this is happening, or what I need to be doing differently in python3 so that I can parse the bodies of the email normally?

Thank you for your time, any guidance in the right direction would be greatly appreciated!

答:
The 'b' in front of the string means it is still a bytes array and has not yet been decoded.

Decoded with 'utf-8' like the other strings, it should print the special characters as one would expect

```<code>...
body = part.get_payload(decode=True)
body = body.decode('utf-8')
print('Body: %s' % body)
...
</code>```

Body:
Currently I am working on an email parser that simply uses imaplib to establish a connection to my gmail account and read new emails.

This all works fine and the results are as expected when running my script using python2 (i.e "python myScript.py")

For example, if I had an email that looked like this:

To: receiver@qwerty.com
From: sender@asdf.com
Subject: Test Subject

Test1
Test2

My script will output as expected:

To: receiver@qwerty.com
From: sender@asdf.com
Subject: Test Subject
Body: Test1
Test2

However, when running this using python3 (i.e "python3 myScript.py"), the results are not the same and escaped characters are shown in the message body, see below:

To: receiver@qwerty.com
From: sender@asdf.com
Subject: Test Subject
Body: b'Test1\r\nTest2\r\n'

And below is the code used for this process:

def readMailbox(mail):
    res, data = mail.uid('search', None, 'UNSEEN')
    i = len(data[0].split())

    for x in range(i):
        latestEmailUID = data[0].split()[x]
        result, emailData = mail.uid('fetch', latestEmailUID, '(RFC822)')
        emailMessage = email.message_from_string(emailData[0][1].decode('utf-8'))

        emailFrom = str(email.header.make_header(email.header.decode_header(emailMessage['From'])))
        emailTo = str(email.header.make_header(email.header.decode_header(emailMessage['To'])))
        subject = str(email.header.make_header(email.header.decode_header(emailMessage['Subject'])))

        # Body details
        for part in emailMessage.walk():
            if part.get_content_type() == 'text/plain':
                body = part.get_payload(decode=True)
                print('To: %s' % emailTo)
                print('From: %s' % emailFrom)
                print('Subject: %s' % subject)
                print('Body: %s' % body)

I am going to need to be able to capture the string body without showing escaped characters for use later on. Can anyone explain to me please why this is happening, or what I need to be doing differently in python3 so that I can parse the bodies of the email normally?

Thank you for your time, any guidance in the right direction would be greatly appreciated!

Body:
The 'b' in front of the string means it is still a bytes array and has not yet been decoded.

Decoded with 'utf-8' like the other strings, it should print the special characters as one would expect

...
body = part.get_payload(decode=True)
body = body.decode('utf-8')
print('Body: %s' % body)
...


问:
Update Kivy text variable with StringpPoperty and ID
So my problem is how do i update text to label. Should I use id:s in KV file and string property or is there even any other way?

Main.Py

```<code>    print_label = StringProperty()

    print_label = lyrics

class MyApp(App):
    def build(self):
        Window.clearcolor = (.13, .13, .13, 1)
        return MyFloatLayout()```
my.kv
```<Button>:
    font_size: 40
    color: 0.1,0.5,0.6,1
    size_hint: 0.3, 0.1

<FloatLayout>:
    print_label: print_label

    Label:
        pos_hint:{"top":1}
        id: print_label
        text: ""

    Button:
        pos_hint:{"bottom":1}
        text: "RE-SEARCH"
        font_size: 10
        on_press: root.btn()

</code>```

答:
Problem - update Label's text

how do i update text to label. Should I use id:s in KV file and string
  property or is there even any other way?

Solution

There are three options to the problem.

Option 1 - Using ids

The pros of using ids is that the App is smaller i.e. less coding and attributes used.

An id is a weakref to the widget and not the widget itself. As a
  consequence, storing the id is not sufficient to keep the widget from
  being garbage collected.

...

self.ids method is very concise.

Snippets - py file

```<code>class FloatLayout(FloatLayout):
    ...
    self.ids.print_label.text = lyrics
</code>```

Snippets - kv file

```<code><FloatLayout>:

    Label:
        pos_hint:{"top":1}
        id: print_label
        text: ""
</code>```

Option 2 - Using Stringproperty

An attribute of type Stringproperty produce an event such that when the attribute's value changes, all properties that reference that attribute are automatically updated.

Snippets - py file

```<code>class FloatLayout(FloatLayout):
    print_label = StringProperty('')
    ...
    self.print_label = lyrics
</code>```

Snippets - kv file

```<code><FloatLayout>:

    Label:
        pos_hint:{"top":1}
        text: root.print_label
</code>```

Option 3 - Using Objectproperty

Using Objectproperty to linking up a Label widget, also requires an id declared in kv file.

Although the self.ids method is very concise, it is generally
  regarded as ‘best practice’ to use the ObjectProperty. This creates a
  direct reference, provides faster access and is more explicit.

Snippets - py file

```<code>class FloatLayout(FloatLayout):
    print_label = ObjectProperty(None)
    ...
    self.print_label.text = lyrics
</code>```

Snippets - kv file

```<code><FloatLayout>:
    print_label: print_label

    Label:
        pos_hint:{"top":1}
        id: print_label
        text: ""
</code>```

Body:
So my problem is how do i update text to label. Should I use id:s in KV file and string property or is there even any other way?

Main.Py

    print_label = StringProperty()

    print_label = lyrics

class MyApp(App):
    def build(self):
        Window.clearcolor = (.13, .13, .13, 1)
        return MyFloatLayout()```
my.kv
```<Button>:
    font_size: 40
    color: 0.1,0.5,0.6,1
    size_hint: 0.3, 0.1

<FloatLayout>:
    print_label: print_label

    Label:
        pos_hint:{"top":1}
        id: print_label
        text: ""

    Button:
        pos_hint:{"bottom":1}
        text: "RE-SEARCH"
        font_size: 10
        on_press: root.btn()

Body:
Problem - update Label's text

how do i update text to label. Should I use id:s in KV file and string
  property or is there even any other way?

Solution

There are three options to the problem.

Option 1 - Using ids

The pros of using ids is that the App is smaller i.e. less coding and attributes used.

An id is a weakref to the widget and not the widget itself. As a
  consequence, storing the id is not sufficient to keep the widget from
  being garbage collected.

...

self.ids method is very concise.

Snippets - py file

class FloatLayout(FloatLayout):
    ...
    self.ids.print_label.text = lyrics

Snippets - kv file

<FloatLayout>:

    Label:
        pos_hint:{"top":1}
        id: print_label
        text: ""

Option 2 - Using Stringproperty

An attribute of type Stringproperty produce an event such that when the attribute's value changes, all properties that reference that attribute are automatically updated.

Snippets - py file

class FloatLayout(FloatLayout):
    print_label = StringProperty('')
    ...
    self.print_label = lyrics

Snippets - kv file

<FloatLayout>:

    Label:
        pos_hint:{"top":1}
        text: root.print_label

Option 3 - Using Objectproperty

Using Objectproperty to linking up a Label widget, also requires an id declared in kv file.

Although the self.ids method is very concise, it is generally
  regarded as ‘best practice’ to use the ObjectProperty. This creates a
  direct reference, provides faster access and is more explicit.

Snippets - py file

class FloatLayout(FloatLayout):
    print_label = ObjectProperty(None)
    ...
    self.print_label.text = lyrics

Snippets - kv file

<FloatLayout>:
    print_label: print_label

    Label:
        pos_hint:{"top":1}
        id: print_label
        text: ""


问:
Why don't these voxels I am drawing using GL.POINTS line up? How can I fix it?
I have been working on a voxel engine using webgl. It uses gl.points to draw voxels using a square based on your distance to the point.

Here is the basics of how it work

```<code>Vertex:

//Get position using the projection matrix and block XYZ
gl_Position =  uMatrix * uModelMatrix * vec4(aPixelPosition[0],-aPixelPosition[2],aPixelPosition[1],1.0);

//Set size of point based on screen height and divide it by depth to size based on distance
gl_PointSize = (uScreenSize[1]) / gl_Position[2];
</code>```

And here is how that looks when it is from a non-problematic angle.

You can see, it looks just how I want to (of course its not as good as real cubes, but preforms amazing on mobile) now lets go inside of this hollow cube and see what it looks like. This picture is me looking into the corner

I changed the background color to highlight the issue. Basically if you are looking directly at the blocks, they work fine, but if they are at an angle to you, they are too small and leave large gaps. This picture is me looking at a wall directly

You can see facing the back wall works perfect, but all the other walls look bad.

So clearly I am doing something wrong, or not thinking about something properly. I have tried a lot of different things to try and repair it but none of my fixes work proper.

I have tried making it so blocks towards the edge of the screen are bigger, this fixes the problem but it also makes blocks bigger that don't need to be. Like for example looking at a flat wall, the edges would become much bigger even though  looking at a flat wall doesn't have the issue.

I have also tried making the squares much bigger and this fixes it but then they overlap everywhere and it doesn't look nearly as clean.

You can see the example of the problem here (just takes a second to generate the structure)
 https://sebastian97.itch.io/voxel-glitchy
WASD- movement
Arrow keys / mouse - Look

答:
Assuming you have your projection matrix separated out I think you want gl_PointSize to be

```<code>vec4 modelViewPosition = view * model * position;

gl_PointSize = someSize / -modelViewPosition.z;

gl_Position = projection * modelViewPosition;
</code>```

'use strict';

/* global window, twgl, requestAnimationFrame, document */

const height = 120;
const width = 30
const position = [];
const color = [];
const normal = [];
for (let z = 0; z < width; ++z) {
  for (let x = 0; x < width; ++x) {
    position.push(x, 0, z);
    color.push(r(0.5), 1, r(0.5));
    normal.push(0, 1, 0);
  }
}
for (let y = 1; y < height ; ++y) {
  for (let x = 0; x < width; ++x) {
    position.push(x, -y, 0);
    color.push(0.6, 0.6, r(0.5));
    normal.push(0, 0, -1);

    position.push(x, -y, width - 1);
    color.push(0.6, 0.6, r(0.5));
    normal.push(0, 0, 1);

    position.push(0, -y, x);
    color.push(0.6, 0.6, r(0.5));
    normal.push(-1, 0, 0);

    position.push(width - 1, -y, x);
    color.push(0.6, 0.6, r(0.5));
    normal.push(1, 0, 0);
  }
}

function r(min, max) {
  if (max === undefined) {
    max = min;
    min = 0;
  }
  return Math.random() * (max - min) + min;
}

const m4 = twgl.m4;
const v3 = twgl.v3;
const gl = document.querySelector('canvas').getContext('webgl');

const vs = `
attribute vec4 position;
attribute vec3 normal;
attribute vec3 color;

uniform mat4 projection;
uniform mat4 modelView;

varying vec3 v_normal;
varying vec3 v_color;

void main() {
  vec4 modelViewPosition = modelView * position;
  gl_Position = projection * modelViewPosition;
  gl_PointSize = 850.0 / -modelViewPosition.z;
  v_normal = mat3(modelView) * normal;
  v_color = color;
}
`;

const fs = `
precision highp float;

varying vec3 v_normal;
varying vec3 v_color;

void main() {
  vec3 lightDirection = normalize(vec3(1, 2, 3));  // arbitrary light direction

  float l = dot(lightDirection, normalize(v_normal)) * .5 + .5;
  gl_FragColor = vec4(v_color * l, 1);
}
`;

// compile shader, link, look up locations
const programInfo = twgl.createProgramInfo(gl, [vs, fs]);

// make some vertex data
const bufferInfo = twgl.createBufferInfoFromArrays(gl, {
  position,
  normal,
  color: { numComponents: 3, data: color },
});

const keys = [];
const eye = [10, 10, 55];
const target = [0, 0, 0];
const up = [0, 1, 0];
const speed = 50;

const kUp = 38;
const kDown = 40;
const kLeft = 37;
const kRight = 39;
const kForward = 87;
const kBackward = 83;
const kSlideLeft = 65;
const kSlideRight = 68;

const keyMove = new Map();
keyMove.set(kForward,    { ndx: 8, eye:  1, target: -1 });
keyMove.set(kBackward,   { ndx: 8, eye:  1, target:  1 });
keyMove.set(kSlideLeft,  { ndx: 0, eye:  1, target: -1 });
keyMove.set(kSlideRight, { ndx: 0, eye:  1, target:  1 });
keyMove.set(kLeft,       { ndx: 0, eye:  0, target: -1 });
keyMove.set(kRight,      { ndx: 0, eye:  0, target:  1 });
keyMove.set(kUp,         { ndx: 4, eye:  0, target: -1 });
keyMove.set(kDown,       { ndx: 4, eye:  0, target:  1 });

let then = 0;
function render(time) {
  time *= 0.001;  // seconds
  const deltaTime = time - then;
  then = time;

  twgl.resizeCanvasToDisplaySize(gl.canvas);

  gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
  gl.enable(gl.DEPTH_TEST);
  gl.enable(gl.CULL_FACE);

  const fov = Math.PI * 0.25;
  const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
  const near = 0.1;
  const far = 1000;
  const projection = m4.perspective(fov, aspect, near, far);

  const camera = m4.lookAt(eye, target, up);
  const view = m4.inverse(camera);
  const modelView = m4.translate(view, [width / -2, 0, width / -2]);

  keyMove.forEach((move, key) => {
    if (keys[key]) {
      const dir = camera.slice(move.ndx, move.ndx + 3);
      const delta = v3.mulScalar(dir, deltaTime * speed * move.target);
     v3.add(target, delta, target);
   if (move.eye) {
     v3.add(eye, delta, eye);
      }
    }
  });

  gl.useProgram(programInfo.program);

  // calls gl.bindBuffer, gl.enableVertexAttribArray, gl.vertexAttribPointer
  twgl.setBuffersAndAttributes(gl, programInfo, bufferInfo);

  // calls gl.activeTexture, gl.bindTexture, gl.uniformXXX
  twgl.setUniforms(programInfo, {
    projection,
    modelView,
  });

  // calls gl.drawArrays or gl.drawElements
  twgl.drawBufferInfo(gl, bufferInfo, gl.POINTS);

  requestAnimationFrame(render);
}
requestAnimationFrame(render);

window.addEventListener('keydown', (e) => {
  e.preventDefault();
  keys[e.keyCode] = true;
});
window.addEventListener('keyup', (e) => {
  keys[e.keyCode] = false;
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { margin: 0; }
canvas { width: 100vw; height: 100vh; display: block; }
#i { position: absolute; top: 0; left: 5px; font-family: monospace; }</code>```

<canvas></canvas>

ASWD ⬆⬇⬅➡
```

Body:
I have been working on a voxel engine using webgl. It uses gl.points to draw voxels using a square based on your distance to the point.

Here is the basics of how it work

Vertex:

//Get position using the projection matrix and block XYZ
gl_Position =  uMatrix * uModelMatrix * vec4(aPixelPosition[0],-aPixelPosition[2],aPixelPosition[1],1.0);

//Set size of point based on screen height and divide it by depth to size based on distance
gl_PointSize = (uScreenSize[1]) / gl_Position[2];

And here is how that looks when it is from a non-problematic angle.

You can see, it looks just how I want to (of course its not as good as real cubes, but preforms amazing on mobile) now lets go inside of this hollow cube and see what it looks like. This picture is me looking into the corner

I changed the background color to highlight the issue. Basically if you are looking directly at the blocks, they work fine, but if they are at an angle to you, they are too small and leave large gaps. This picture is me looking at a wall directly

You can see facing the back wall works perfect, but all the other walls look bad.

So clearly I am doing something wrong, or not thinking about something properly. I have tried a lot of different things to try and repair it but none of my fixes work proper.

I have tried making it so blocks towards the edge of the screen are bigger, this fixes the problem but it also makes blocks bigger that don't need to be. Like for example looking at a flat wall, the edges would become much bigger even though  looking at a flat wall doesn't have the issue.

I have also tried making the squares much bigger and this fixes it but then they overlap everywhere and it doesn't look nearly as clean.

You can see the example of the problem here (just takes a second to generate the structure)
 https://sebastian97.itch.io/voxel-glitchy
WASD- movement
Arrow keys / mouse - Look

Body:
Assuming you have your projection matrix separated out I think you want gl_PointSize to be

vec4 modelViewPosition = view * model * position;

gl_PointSize = someSize / -modelViewPosition.z;

gl_Position = projection * modelViewPosition;

'use strict';

/* global window, twgl, requestAnimationFrame, document */

const height = 120;
const width = 30
const position = [];
const color = [];
const normal = [];
for (let z = 0; z < width; ++z) {
  for (let x = 0; x < width; ++x) {
    position.push(x, 0, z);
    color.push(r(0.5), 1, r(0.5));
    normal.push(0, 1, 0);
  }
}
for (let y = 1; y < height ; ++y) {
  for (let x = 0; x < width; ++x) {
    position.push(x, -y, 0);
    color.push(0.6, 0.6, r(0.5));
    normal.push(0, 0, -1);

    position.push(x, -y, width - 1);
    color.push(0.6, 0.6, r(0.5));
    normal.push(0, 0, 1);

    position.push(0, -y, x);
    color.push(0.6, 0.6, r(0.5));
    normal.push(-1, 0, 0);

    position.push(width - 1, -y, x);
    color.push(0.6, 0.6, r(0.5));
    normal.push(1, 0, 0);
  }
}

function r(min, max) {
  if (max === undefined) {
    max = min;
    min = 0;
  }
  return Math.random() * (max - min) + min;
}

const m4 = twgl.m4;
const v3 = twgl.v3;
const gl = document.querySelector('canvas').getContext('webgl');

const vs = `
attribute vec4 position;
attribute vec3 normal;
attribute vec3 color;

uniform mat4 projection;
uniform mat4 modelView;

varying vec3 v_normal;
varying vec3 v_color;

void main() {
  vec4 modelViewPosition = modelView * position;
  gl_Position = projection * modelViewPosition;
  gl_PointSize = 850.0 / -modelViewPosition.z;
  v_normal = mat3(modelView) * normal;
  v_color = color;
}
`;

const fs = `
precision highp float;

varying vec3 v_normal;
varying vec3 v_color;

void main() {
  vec3 lightDirection = normalize(vec3(1, 2, 3));  // arbitrary light direction

  float l = dot(lightDirection, normalize(v_normal)) * .5 + .5;
  gl_FragColor = vec4(v_color * l, 1);
}
`;

// compile shader, link, look up locations
const programInfo = twgl.createProgramInfo(gl, [vs, fs]);

// make some vertex data
const bufferInfo = twgl.createBufferInfoFromArrays(gl, {
  position,
  normal,
  color: { numComponents: 3, data: color },
});

const keys = [];
const eye = [10, 10, 55];
const target = [0, 0, 0];
const up = [0, 1, 0];
const speed = 50;

const kUp = 38;
const kDown = 40;
const kLeft = 37;
const kRight = 39;
const kForward = 87;
const kBackward = 83;
const kSlideLeft = 65;
const kSlideRight = 68;

const keyMove = new Map();
keyMove.set(kForward,    { ndx: 8, eye:  1, target: -1 });
keyMove.set(kBackward,   { ndx: 8, eye:  1, target:  1 });
keyMove.set(kSlideLeft,  { ndx: 0, eye:  1, target: -1 });
keyMove.set(kSlideRight, { ndx: 0, eye:  1, target:  1 });
keyMove.set(kLeft,       { ndx: 0, eye:  0, target: -1 });
keyMove.set(kRight,      { ndx: 0, eye:  0, target:  1 });
keyMove.set(kUp,         { ndx: 4, eye:  0, target: -1 });
keyMove.set(kDown,       { ndx: 4, eye:  0, target:  1 });

let then = 0;
function render(time) {
  time *= 0.001;  // seconds
  const deltaTime = time - then;
  then = time;

  twgl.resizeCanvasToDisplaySize(gl.canvas);

  gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
  gl.enable(gl.DEPTH_TEST);
  gl.enable(gl.CULL_FACE);

  const fov = Math.PI * 0.25;
  const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
  const near = 0.1;
  const far = 1000;
  const projection = m4.perspective(fov, aspect, near, far);

  const camera = m4.lookAt(eye, target, up);
  const view = m4.inverse(camera);
  const modelView = m4.translate(view, [width / -2, 0, width / -2]);

  keyMove.forEach((move, key) => {
    if (keys[key]) {
      const dir = camera.slice(move.ndx, move.ndx + 3);
      const delta = v3.mulScalar(dir, deltaTime * speed * move.target);
     v3.add(target, delta, target);
   if (move.eye) {
     v3.add(eye, delta, eye);
      }
    }
  });

  gl.useProgram(programInfo.program);

  // calls gl.bindBuffer, gl.enableVertexAttribArray, gl.vertexAttribPointer
  twgl.setBuffersAndAttributes(gl, programInfo, bufferInfo);

  // calls gl.activeTexture, gl.bindTexture, gl.uniformXXX
  twgl.setUniforms(programInfo, {
    projection,
    modelView,
  });

  // calls gl.drawArrays or gl.drawElements
  twgl.drawBufferInfo(gl, bufferInfo, gl.POINTS);

  requestAnimationFrame(render);
}
requestAnimationFrame(render);

window.addEventListener('keydown', (e) => {
  e.preventDefault();
  keys[e.keyCode] = true;
});
window.addEventListener('keyup', (e) => {
  keys[e.keyCode] = false;
});

body { margin: 0; }
canvas { width: 100vw; height: 100vh; display: block; }
#i { position: absolute; top: 0; left: 5px; font-family: monospace; }

<script src="https://twgljs.org/dist/4.x/twgl-full.min.js"></script>
<canvas></canvas>
<div id="i">ASWD ⬆⬇⬅➡</div>


问:
How to have a function as a member in a struct
How can I specify a function in a struct definition? Something like this:

struct Operation {
    params: Vec<String>,
    ops: Function<Vec<String>> -> Vec<String>,
}
```

I know that the syntax Function<Vec<String>> -> Vec<String> is incorrect, but I am trying to specify that "Operation" has a field called ops that is a closure that takes a Vec<String> and returns a Vec<String>.

答:
You can use Box<dyn Fn(ArgType) -> RetType> to store an arbitrary function:

```<code>struct Operation {
    params: Vec<String>,
    ops: Box<dyn Fn(Vec<String>) -> Vec<String>>,
}
</code>```

In general, the Fn trait (along with FnOnce and FnMut) can be used for any callable value, such as a function or a closure, that has the given function signature.

To create a Box<dyn Fn...> value, wrap any callable value with Box::new:

```<code>let obj = Operation {
    params: Vec::new(),
    // wrap a closure
    ops: Box::new(|strings| {
        /* do something... */
        strings
    }),
};

// call the function or closure inside the Box
(obj.ops)(Vec::new())
</code>```

Body:
How can I specify a function in a struct definition? Something like this:

struct Operation {
    params: Vec<String>,
    ops: Function<Vec<String>> -> Vec<String>,
}

I know that the syntax Function<Vec<String>> -> Vec<String> is incorrect, but I am trying to specify that "Operation" has a field called ops that is a closure that takes a Vec<String> and returns a Vec<String>.

Body:
You can use Box<dyn Fn(ArgType) -> RetType> to store an arbitrary function:

struct Operation {
    params: Vec<String>,
    ops: Box<dyn Fn(Vec<String>) -> Vec<String>>,
}

In general, the Fn trait (along with FnOnce and FnMut) can be used for any callable value, such as a function or a closure, that has the given function signature.

To create a Box<dyn Fn...> value, wrap any callable value with Box::new:

let obj = Operation {
    params: Vec::new(),
    // wrap a closure
    ops: Box::new(|strings| {
        /* do something... */
        strings
    }),
};

// call the function or closure inside the Box
(obj.ops)(Vec::new())


问:
Javascript using Fetch and pagination, recursive?
Hello I'm new to Javascript and APIs.

But I have an excersise where I should get Data from.

https://swapi.co/api/planets/

The problem is that it doesn't list all the planets at once so that URL only shows the first 10 entries while https://swapi.co/api/planets/?page=2 shows the next and so on.

This is my current code, it works but I don't think I'm going as I'm supposed to so I wonder how you would solve this problem.

https://codepen.io/indiehjaerta/pen/QQXVJX

var starWarsAPI = new StarWarsAPI();
starWarsAPI.Initialize();

function StarWarsAPI()
{
    this.planets = new Array();

    this.Initialize = function()
    {
        this.LoadPlanets("https://swapi.co/api/planets");
    }

    this.LoadPlanets = function(aURL)
    {

        fetch(aURL).then(
            function (response)
            {
                if (response.status !== 200)
                {
                    console.log('Looks like there was a problem. Status Code: ' + response.status);
                    return;
                }

                response.json().then(
                    data => this.LoadPlanetsRecursive(data)
                );
            }.bind(this)
        ).catch(function (err)
        {
            console.log('Fetch Error :-S', err);
        });
    }

    this.LoadPlanetsRecursive = function(aData)
    {

        for (let planet of aData.results)
        {
            let newPlanet = new Planet(planet);
            this.planets.push(newPlanet);
        }

        if (aData.next != null)
        {
            fetch(aData.next).then(
                function (response)
                {
                    if (response.status !== 200)
                    {
                        console.log('Looks like there was a problem. Status Code: ' + response.status);
                        return;
                    }

                    response.json().then(
                        data => this.LoadPlanetsRecursive(data)
                    );
                }.bind(this)
            ).catch(function (err)
            {
                console.log('Fetch Error :-S', err);
            });
        }
    }
this.PresentPlanetsInHTML = function()
{

}
}

function Planet(aPlanet)
{
    this.name = aPlanet.name;
    console.log(this);
}```

2nd question is where I should put my "PresentData" so I know that all planets have been loaded and not 1 by 1 when the're added to the array.

答:
I had similar needs so I wrote a library called fetch-paginate - here's an example:</p>
```<code>fetchPaginate.default("https://swapi.co/api/planets", {
  getItems: page => page.results,
  params: true
})
.then(res => {
  res.items.forEach(planet => {
    const newPlanet = new Planet(planet);
    this.planets.push(newPlanet);
  })
})
</code>```

Body:
Hello I'm new to Javascript and APIs.

But I have an excersise where I should get Data from.

https://swapi.co/api/planets/

The problem is that it doesn't list all the planets at once so that URL only shows the first 10 entries while https://swapi.co/api/planets/?page=2 shows the next and so on.

This is my current code, it works but I don't think I'm going as I'm supposed to so I wonder how you would solve this problem.

https://codepen.io/indiehjaerta/pen/QQXVJX

var starWarsAPI = new StarWarsAPI();
starWarsAPI.Initialize();

function StarWarsAPI()
{
    this.planets = new Array();

    this.Initialize = function()
    {
        this.LoadPlanets("https://swapi.co/api/planets");
    }

    this.LoadPlanets = function(aURL)
    {

        fetch(aURL).then(
            function (response)
            {
                if (response.status !== 200)
                {
                    console.log('Looks like there was a problem. Status Code: ' + response.status);
                    return;
                }

                response.json().then(
                    data => this.LoadPlanetsRecursive(data)
                );
            }.bind(this)
        ).catch(function (err)
        {
            console.log('Fetch Error :-S', err);
        });
    }

    this.LoadPlanetsRecursive = function(aData)
    {

        for (let planet of aData.results)
        {
            let newPlanet = new Planet(planet);
            this.planets.push(newPlanet);
        }

        if (aData.next != null)
        {
            fetch(aData.next).then(
                function (response)
                {
                    if (response.status !== 200)
                    {
                        console.log('Looks like there was a problem. Status Code: ' + response.status);
                        return;
                    }

                    response.json().then(
                        data => this.LoadPlanetsRecursive(data)
                    );
                }.bind(this)
            ).catch(function (err)
            {
                console.log('Fetch Error :-S', err);
            });
        }
    }
this.PresentPlanetsInHTML = function()
{

}
}

function Planet(aPlanet)
{
    this.name = aPlanet.name;
    console.log(this);
}

2nd question is where I should put my "PresentData" so I know that all planets have been loaded and not 1 by 1 when the're added to the array.

Body:
I had similar needs so I wrote a library called fetch-paginate - here's an example:

fetchPaginate.default("https://swapi.co/api/planets", {
  getItems: page => page.results,
  params: true
})
.then(res => {
  res.items.forEach(planet => {
    const newPlanet = new Planet(planet);
    this.planets.push(newPlanet);
  })
})


问:
fullcalendar don't show start_time event
i have a fullcalendar set this:

```<code>allDaySlot: true,
allDayDefault:true,
</code>```

this is capture:

in this case i try to show the event and start time , but dont show on the month, week or day event.
in the day button is show the event and only show on all-day slot, i would like show on the 2 parts timeline and all-day please any suggest.

update:

i would like sometime like this:

in this case show all events, start time in all-day slot and timeline.

thanks.

答:
I am not sure if this is what you are looking for. I have forked a Pen and tried to implement different scenarios which might be serving your needs.

I think you are missing the renderevents in your code:

```<code> //An all day event example
 $('#calendar').fullCalendar('renderEvent', {
          title: 'dynamic event',
          start: '2019-05-28',
          allDay: true
        });
  //Not an all day event example
  $('#calendar').fullCalendar('renderEvent', {
          title: 'not an all day event',
          start: '2019-05-28',
          allDay: false
        });
  //An event spanning between two dates
  $('#calendar').fullCalendar('renderEvent', {
          title: 'event with start and end dates',
          start: '2019-05-29',
          end: '2019-05-31'
        });
</code>```

Relevant code can be found here in a Pen which I forked from anon. Let me know if you still have issues.

Body:
i have a fullcalendar set this:

allDaySlot: true,
allDayDefault:true,

this is capture:

in this case i try to show the event and start time , but dont show on the month, week or day event.
in the day button is show the event and only show on all-day slot, i would like show on the 2 parts timeline and all-day please any suggest.

update:

i would like sometime like this:

in this case show all events, start time in all-day slot and timeline.

thanks.

Body:
I am not sure if this is what you are looking for. I have forked a Pen and tried to implement different scenarios which might be serving your needs.

I think you are missing the renderevents in your code:

 //An all day event example
 $('#calendar').fullCalendar('renderEvent', {
          title: 'dynamic event',
          start: '2019-05-28',
          allDay: true
        });
  //Not an all day event example
  $('#calendar').fullCalendar('renderEvent', {
          title: 'not an all day event',
          start: '2019-05-28',
          allDay: false
        });
  //An event spanning between two dates
  $('#calendar').fullCalendar('renderEvent', {
          title: 'event with start and end dates',
          start: '2019-05-29',
          end: '2019-05-31'
        });

Relevant code can be found here in a Pen which I forked from anon. Let me know if you still have issues.


问:
nodeJS max header size in http.request
With nodeJS v0.10.28, is there a limit in the size/length of the header content in an http request?

Let me explain:

I need to consume rest services provided by a 3rd party provider.  The data returned to me is in the header of the request, the body is mostly empty (120 or so chars).  The amount of data in the header varies from a few chars to several 100kb.

```<code>var https = require('https');

var httpHeaders = {
    Authorization: 'Basic ' + new Buffer(user + ':' + psw).toString('base64'),
    accept: '*/*',
    'Content-Type': 'text/plain; charset=utf-8'
};
var options = {
    host: "www.website.com",
    port: 8080,
    path: "/" ,
    method: 'GET',
    headers: httpHeaders,
    rejectUnauthorized: false,
    requestCert: true,
    agent: false
};

https.request(options, function(res) {
    res.setEncoding('utf8');
    if (res.statusCode == 200) {
        var json = res.headers["someHeaderInfo"];
        callback(null,{ "result" : JSON.parse(json) });
    } else {
        callback({ "error" : res.statusCode  });
    }
}).on('data', function (chunk) {
    console.log('BODY: ' + chunk);
}).on('error', function(e, res) {
    console.log("  Got error: " + e.message);
    callback({ "error" : e.message });
}).end();
</code>```

The code above works fine for smaller size headers but fails on the on('error', with "Parse Error" message on larger headers.

Removing the on error clause throws this exception:

```<code>Error: Parse Error
    at CleartextStream.socketOnData (http.js:1583:20)
    at CleartextStream.read [as _read] (tls.js:511:12)
    at CleartextStream.Readable.read (_stream_readable.js:320:10)
    at EncryptedStream.write [as _write] (tls.js:366:25)
    at doWrite (_stream_writable.js:226:10)
    at writeOrBuffer (_stream_writable.js:216:5)
    at EncryptedStream.Writable.write (_stream_writable.js:183:11)
    at write (_stream_readable.js:582:24)
    at flow (_stream_readable.js:591:7)
    at Socket.pipeOnReadable (_stream_readable.js:623:5)
</code>```

Is there a limit on the header size, can it me changed? what solution do I have?

Thanks

答:
Use --max-http-header-size on the node command-line to accept larger headers. If you get "node: bad option: --max-http-header-size", upgrade to node v10.15.0 or newer. Relevant changelog

node --max-http-header-size 15000 client.js
```

Credit to @murad.

Title: nodeJS max header size in http.request

Body:
With nodeJS v0.10.28, is there a limit in the size/length of the header content in an http request?

Let me explain:

I need to consume rest services provided by a 3rd party provider.  The data returned to me is in the header of the request, the body is mostly empty (120 or so chars).  The amount of data in the header varies from a few chars to several 100kb.

var https = require('https');

var httpHeaders = {
    Authorization: 'Basic ' + new Buffer(user + ':' + psw).toString('base64'),
    accept: '*/*',
    'Content-Type': 'text/plain; charset=utf-8'
};
var options = {
    host: "www.website.com",
    port: 8080,
    path: "/" ,
    method: 'GET',
    headers: httpHeaders,
    rejectUnauthorized: false,
    requestCert: true,
    agent: false
};

https.request(options, function(res) {
    res.setEncoding('utf8');
    if (res.statusCode == 200) {
        var json = res.headers["someHeaderInfo"];
        callback(null,{ "result" : JSON.parse(json) });
    } else {
        callback({ "error" : res.statusCode  });
    }
}).on('data', function (chunk) {
    console.log('BODY: ' + chunk);
}).on('error', function(e, res) {
    console.log("  Got error: " + e.message);
    callback({ "error" : e.message });
}).end();

The code above works fine for smaller size headers but fails on the on('error', with "Parse Error" message on larger headers.

Removing the on error clause throws this exception:

Error: Parse Error
    at CleartextStream.socketOnData (http.js:1583:20)
    at CleartextStream.read [as _read] (tls.js:511:12)
    at CleartextStream.Readable.read (_stream_readable.js:320:10)
    at EncryptedStream.write [as _write] (tls.js:366:25)
    at doWrite (_stream_writable.js:226:10)
    at writeOrBuffer (_stream_writable.js:216:5)
    at EncryptedStream.Writable.write (_stream_writable.js:183:11)
    at write (_stream_readable.js:582:24)
    at flow (_stream_readable.js:591:7)
    at Socket.pipeOnReadable (_stream_readable.js:623:5)

Is there a limit on the header size, can it me changed? what solution do I have?

Thanks

Body:
Use --max-http-header-size on the node command-line to accept larger headers. If you get "node: bad option: --max-http-header-size", upgrade to node v10.15.0 or newer. Relevant changelog

node --max-http-header-size 15000 client.js

Credit to @murad.


问:
Interate through multiple dictionaries in a Pickle file
I must to use pickle to store some data. I've created a class to handle the i/o of the data, one the functions is resposible for loading the data and print all the informations, but when I call the function to print out the data, it only interates through the first dictionary. All the inputs are being saved (as I openned the pickle file and could see some data related to other inputs).

I've checked some of the stackoverflow questions like: Iterating over dictionaries using 'for' loops and Best way to loop through multiple dictionaries in Python but none of the examples  gave me the expected output.

This is the DataBase class which is resposible to handle pickle:

```<code>
import pickle
from pathlib import Path

class DataBase:
    def __init__(self, out_file):
        self.out_file = out_file

    def Create(self, file_name):
        if not Path(self.out_file).exists():
            with open(self.out_file, "w+b") as this_file:
                new_file = pickle.dump(file_name, this_file, pickle.HIGHEST_PROTOCOL)
        elif Path(self.out_file).exists():
            self.Update(file_name)
        else:
            print("Unknown error!")

    def Update(self, file_name):
        with open(self.out_file, "a+b") as this_file:
            updated_file = pickle.dump(file_name, this_file, pickle.HIGHEST_PROTOCOL)

    def Load(self):
        with open(self.out_file, "rb") as this_file:
            loaded_file = pickle.load(this_file)
            return loaded_file

    def PrintFile(self):
        for k, v in self.Load().items():
            print(f"{k} {v}")

</code>```

This is the code I've written for testing the class:

```<code>from DataBase import DataBase as DB

dict0 = {1:'A', 2:'E', 3:'I', 4:'O', 5:'U'}
dict1 = {0:"Water", 1:"Fire", 2:"Air", 3:"Sand"}
db = DB("test")
db.Create(dict0)
db.Create(dict1)
db.PrintFile()
</code>```

I expected the output to be:

```<code>1 A
2 E
3 I
4 O
5 U
0 Water
1 Fire
2 Air
3 Sand
</code>```

However the output I get is:

```<code>1 A
2 E
3 I
4 O
5 U
</code>```

The whole information is being saved, when I open the pickle file with a text ediot, I can see some o the information stored there:

��#}�(K�A�K�E�K�I�K�O�K�U�u.��)}�(K�Water�K�Fire�K�Air�K�Sand�u

We can see for example Air in the file.

What can I do to have the expected output?

答: You could try combining the two dictionaries before you pickle them, but this might not be what you want for your specific application. My speculation is that the .load part of db.printfile() is not loading both dictionaries and therefore is only printing/returning the first one.

Body:
I must to use pickle to store some data. I've created a class to handle the i/o of the data, one the functions is resposible for loading the data and print all the informations, but when I call the function to print out the data, it only interates through the first dictionary. All the inputs are being saved (as I openned the pickle file and could see some data related to other inputs).

I've checked some of the stackoverflow questions like: Iterating over dictionaries using 'for' loops and Best way to loop through multiple dictionaries in Python but none of the examples  gave me the expected output.

This is the DataBase class which is resposible to handle pickle:

import pickle
from pathlib import Path

class DataBase:
    def __init__(self, out_file):
        self.out_file = out_file

    def Create(self, file_name):
        if not Path(self.out_file).exists():
            with open(self.out_file, "w+b") as this_file:
                new_file = pickle.dump(file_name, this_file, pickle.HIGHEST_PROTOCOL)
        elif Path(self.out_file).exists():
            self.Update(file_name)
        else:
            print("Unknown error!")

    def Update(self, file_name):
        with open(self.out_file, "a+b") as this_file:
            updated_file = pickle.dump(file_name, this_file, pickle.HIGHEST_PROTOCOL)

    def Load(self):
        with open(self.out_file, "rb") as this_file:
            loaded_file = pickle.load(this_file)
            return loaded_file

    def PrintFile(self):
        for k, v in self.Load().items():
            print(f"{k} {v}")

This is the code I've written for testing the class:

from DataBase import DataBase as DB

dict0 = {1:'A', 2:'E', 3:'I', 4:'O', 5:'U'}
dict1 = {0:"Water", 1:"Fire", 2:"Air", 3:"Sand"}
db = DB("test")
db.Create(dict0)
db.Create(dict1)
db.PrintFile()

I expected the output to be:

1 A
2 E
3 I
4 O
5 U
0 Water
1 Fire
2 Air
3 Sand

However the output I get is:

1 A
2 E
3 I
4 O
5 U

The whole information is being saved, when I open the pickle file with a text ediot, I can see some o the information stored there:

��#}�(K�A�K�E�K�I�K�O�K�U�u.��)}�(K�Water�K�Fire�K�Air�K�Sand�u

We can see for example Air in the file.

What can I do to have the expected output?


问:
Tracking model changes in SQLAlchemy
I want to log every action what will be done with some SQLAlchemy-Models.

So, I have a after_insert, after_delete and before_update hooks, where I will save previous and current representation of model,

```<code>def keep_logs(cls):
    @event.listens_for(cls, 'after_delete')
    def after_delete_trigger(mapper, connection, target):
        pass

    @event.listens_for(cls, 'after_insert')
    def after_insert_trigger(mapper, connection, target):
        pass

    @event.listens_for(cls, 'before_update')
    def before_update_trigger(mapper, connection, target):
        prev = cls.query.filter_by(id=target.id).one()
        # comparing previous and current model

MODELS_TO_LOGGING = (
    User,
)
for cls in MODELS_TO_LOGGING:
    keep_logs(cls)
</code>```

But there is one problem: when I'm trying to find model in before_update hook, SQLA returns modified (dirty) version.
How can I get previous version of model before updating it?
Is there a different way to keep model changes?

Thanks!

答:
I had a similar problem but wanted to be able to keep track of the deltas as changes are made to sqlalchemy models instead of just the new values. I wrote this slight extension to davidism's answer to do that along with slightly better handling of before and after, since they are lists sometimes or empty tuples other times:

  from sqlalchemy import inspect

  def get_model_changes(model):
    """
    Return a dictionary containing changes made to the model since it was
    fetched from the database.

    The dictionary is of the form {'property_name': [old_value, new_value]}

    Example:
      user = get_user_by_id(420)
      >>> '<User id=402 email="business_email@gmail.com">'
      get_model_changes(user)
      >>> {}
      user.email = 'new_email@who-dis.biz'
      get_model_changes(user)
      >>> {'email': ['business_email@gmail.com', 'new_email@who-dis.biz']}
    """
    state = inspect(model)
    changes = {}
    for attr in state.attrs:
      hist = state.get_history(attr.key, True)

      if not hist.has_changes():
        continue

      old_value = hist.deleted[0] if hist.deleted else None
      new_value = hist.added[0] if hist.added else None
      changes[attr.key] = [old_value, new_value]

    return changes

  def has_model_changed(model):
    """
    Return True if there are any unsaved changes on the model.
    """
    return bool(get_model_changes(model))
```

Title: Tracking model changes in SQLAlchemy

Body:
I want to log every action what will be done with some SQLAlchemy-Models.

So, I have a after_insert, after_delete and before_update hooks, where I will save previous and current representation of model,

def keep_logs(cls):
    @event.listens_for(cls, 'after_delete')
    def after_delete_trigger(mapper, connection, target):
        pass

    @event.listens_for(cls, 'after_insert')
    def after_insert_trigger(mapper, connection, target):
        pass

    @event.listens_for(cls, 'before_update')
    def before_update_trigger(mapper, connection, target):
        prev = cls.query.filter_by(id=target.id).one()
        # comparing previous and current model

MODELS_TO_LOGGING = (
    User,
)
for cls in MODELS_TO_LOGGING:
    keep_logs(cls)

But there is one problem: when I'm trying to find model in before_update hook, SQLA returns modified (dirty) version.
How can I get previous version of model before updating it?
Is there a different way to keep model changes?

Thanks!


问:
C++17 Partial Deduction Guide
I am trying to write a deduction guide, that only detects one of many typename's from given constructor argument and requires user to enter int size manually

template <int size, typename T>
struct Board
{
            array<array<T, size>, size> values;

            explicit Board(const vector<T>& raw_values){

            }
};
template <int size, typename T> Board(const vector<T>&) -> Board<int size, T>;
```

<p>The idea above is that user should still be forced to enter "<code>int size</code>" argument of template, but "<code>typename T</code>" should be deduced from the argument of constructor, is this possible?</p>

<p>After correct specification, this is how method should be called</p>

<pre class="lang-cpp prettyprint-override"><code>auto b = Board<3>(initialStateVector);
</code>```

Currently, it requires to me to enter like this;

auto b = Board<3, int>(initialStateVector);
```

<p>So basically, I want "<code>int</code>" above to be deduced from given <code>initialStateVector</code>, which has type</p>

<pre class="lang-cpp prettyprint-override"><code>const vector<int>& raw_values
</code>```

答:
The idea above is that user should still be forced to enter "int size" argument of template, but "typename T" should be deduced from the argument of constructor, is this possible?

According a note (and following examples) in this cppreference page

Class template argument deduction is only performed if no template argument list is present. If a template argument list is specified, deduction does not take place.

no, this isn't possible (not in C++17; we can hope in future versions of the standard).

If you want explicit the size and let deduce the type, the best I can imagine is pass through a good-old make_something function.

I mean something as follows (using std::size_t for the size, as in std::array and almost all STL)

```<code>template <std::size_t S, typename T>
Board<S, T> make_Board (std::vector<T> const & v)
 { return {v}; }

// ...

auto b = make_Board<3>(initialStateVector);
</code>```

that should works also in C++11.

Title: C++17 Partial Deduction Guide

Body:
I am trying to write a deduction guide, that only detects one of many typename's from given constructor argument and requires user to enter int size manually

template <int size, typename T>
struct Board
{
            array<array<T, size>, size> values;

            explicit Board(const vector<T>& raw_values){

            }
};
template <int size, typename T> Board(const vector<T>&) -> Board<int size, T>;

The idea above is that user should still be forced to enter "int size" argument of template, but "typename T" should be deduced from the argument of constructor, is this possible?

After correct specification, this is how method should be called

auto b = Board<3>(initialStateVector);

Currently, it requires to me to enter like this;

auto b = Board<3, int>(initialStateVector);

So basically, I want "int" above to be deduced from given initialStateVector, which has type

const vector<int>& raw_values

Body:
The idea above is that user should still be forced to enter "int size" argument of template, but "typename T" should be deduced from the argument of constructor, is this possible?

According a note (and following examples) in this cppreference page

Class template argument deduction is only performed if no template argument list is present. If a template argument list is specified, deduction does not take place.

no, this isn't possible (not in C++17; we can hope in future versions of the standard).

If you want explicit the size and let deduce the type, the best I can imagine is pass through a good-old make_something function.

I mean something as follows (using std::size_t for the size, as in std::array and almost all STL)

template <std::size_t S, typename T>
Board<S, T> make_Board (std::vector<T> const & v)
 { return {v}; }

// ...

auto b = make_Board<3>(initialStateVector);

that should works also in C++11.


问:
How to implement A Cache by using ReadWriteLock in java?
My main question is "Do I really need recheck the value in the following code"?

The following code describes how to implement a cache by using ReadWriteLock.

```<code>public class ReadWriteLockCache {
private Map<String, Object> cache = new HashMap<String, Object>();
private ReadWriteLock rwl = new ReentrantReadWriteLock();

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
}

public Object getData(String key) {
    rwl.readLock().lock();

    Object value = null;

    try {
        value = cache.get(key);

        if (value == null) {
            rwl.readLock().unlock(); //line1
            rwl.writeLock().lock(); //line2

            try {
                if (value == null) //line3
                 {
                    value = "aaaa"; // may get data from db
                                    //line5 put the data into cache.

                    cache.put(key, value);
                }
            } finally {
                rwl.writeLock().unlock();
            }

            rwl.readLock().lock();
        }
    } finally {
        rwl.readLock().unlock();
    }

    return value;
}
</code>```

}

Whether Should I still need to recheck the value at the 'line3' ?

As I know, the value object is must be null when excuted to line3,
because it's a local variable (when it's null)and it's cann't be A state variable of our main obj:ReadWriteLockCache.

What we should really do is recall the get method ,and check the key's value is whether putted by some other thread or not.

The code should like this:

```<code>                    value = cache.get(key);
                if (value == null) //line3
                 {
                    value = "aaaa";
                    cache.put(key, value);
                }
</code>```

Anyone can help?Am I right? I'm confused.

答:
Yes you should as read lock can be read by multiple threads at the same time
there might be one thread executing line 3 and other thread might be waiting in line 2

But as other suggested use concurrent hashmap

Body:
My main question is "Do I really need recheck the value in the following code"?

The following code describes how to implement a cache by using ReadWriteLock.

public class ReadWriteLockCache {
private Map<String, Object> cache = new HashMap<String, Object>();
private ReadWriteLock rwl = new ReentrantReadWriteLock();

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
}

public Object getData(String key) {
    rwl.readLock().lock();

    Object value = null;

    try {
        value = cache.get(key);

        if (value == null) {
            rwl.readLock().unlock(); //line1
            rwl.writeLock().lock(); //line2

            try {
                if (value == null) //line3
                 {
                    value = "aaaa"; // may get data from db
                                    //line5 put the data into cache.

                    cache.put(key, value);
                }
            } finally {
                rwl.writeLock().unlock();
            }

            rwl.readLock().lock();
        }
    } finally {
        rwl.readLock().unlock();
    }

    return value;
}

}

Whether Should I still need to recheck the value at the 'line3' ?

As I know, the value object is must be null when excuted to line3,
because it's a local variable (when it's null)and it's cann't be A state variable of our main obj:ReadWriteLockCache.

What we should really do is recall the get method ,and check the key's value is whether putted by some other thread or not.

The code should like this:

                    value = cache.get(key);
                if (value == null) //line3
                 {
                    value = "aaaa";
                    cache.put(key, value);
                }

Anyone can help?Am I right? I'm confused.


问:
Remove readonly attribute from directory
How can I programatically remove the readonly attribute from a directory in C#?</p>

答:
Using the -= assignment operator is dangerous for two reasons:

1) It works ONLY IF the ReadOnly attribute is set, thus a test is required beforehand.

2) It is performing a subtract operation, which is not is not the best choice when working with binary flags. The subtract operation works if condition 1 (above) is true, but additional subtract operations will ALTER OTHER BITS in the FileAttributes field!

Use &= ~FileAttributes.ReadOnly; to remove ReadOnly flag.

Use |= FileAttributes.ReadOnly; to apply ReadOnly flag.


问:
Get message size in Gmail API
Using Gmail API, I try to find specific e-mails by size.
I want to be able to read the message size.

In the API site I cannot find such a method.

I've seen other methods with .js script, but I'm using google script as below:

```<code>function label_messages_without_response() {
  var emailAddress = Session.getEffectiveUser().getEmail();
  //Logger.log(emailAddress);

  threads = GmailApp.search("less");

  var size_total = 0;

  Logger.log(size_total);
  for (var i = 0; i < threads.length; i++)
  {
    var thread = threads[i];
    var lastMessage = thread.getMessages()[thread.getMessageCount()-1];
    //size_total+= thread.getMessages()[0].getSubject();
    Logger.log(thread.getMessages()[0].getSubject());
   }

  Logger.log(size_total);
}
</code>```

答:
You want to retrieve the total size of emails which are retrieved by GmailApp.search().

The unit of size you think is "bytes".

You want to achieve this using Google Apps Script.

If my understanding is correct, how about this sample script? The size using as size:, larger: and smaller: of the search query is the body size. In this sample script, I used this.

Sample script:

```<code>function label_messages_without_response() {
  var threads = GmailApp.search("less");
  var size_total = 0;
  for (var i = 0; i < threads.length; i++) {
    var messages = threads[i].getMessages();
    for (var j = 0; j < messages.length; j++) {
      var mailSize = messages[j].getBody().length; // Or  messages[j].getRawContent().length
      size_total += mailSize;
      Logger.log("Subject: %s, size: %s", messages[j].getSubject(), mailSize);
    }
  }
  Logger.log("Total size: %s", size_total);
}
</code>```

Note:

If you want to retrieve whole size of each email, please replace var mailSize = messages[j].getBody().length to var mailSize = messages[j].getRawContent().length. By this, the size which includes the special characters in the body, the attachment files and headers can be retrieved.

References:

Search operators you can use with Gmail

getBody()

getRawContent()

Title: Get message size in Gmail API

Body:
Using Gmail API, I try to find specific e-mails by size.
I want to be able to read the message size.

In the API site I cannot find such a method.

I've seen other methods with .js script, but I'm using google script as below:

function label_messages_without_response() {
  var emailAddress = Session.getEffectiveUser().getEmail();
  //Logger.log(emailAddress);

  threads = GmailApp.search("less");

  var size_total = 0;

  Logger.log(size_total);
  for (var i = 0; i < threads.length; i++)
  {
    var thread = threads[i];
    var lastMessage = thread.getMessages()[thread.getMessageCount()-1];
    //size_total+= thread.getMessages()[0].getSubject();
    Logger.log(thread.getMessages()[0].getSubject());
   }

  Logger.log(size_total);
}

Body:
You want to retrieve the total size of emails which are retrieved by GmailApp.search().

The unit of size you think is "bytes".

You want to achieve this using Google Apps Script.

If my understanding is correct, how about this sample script? The size using as size:, larger: and smaller: of the search query is the body size. In this sample script, I used this.

Sample script:

function label_messages_without_response() {
  var threads = GmailApp.search("less");
  var size_total = 0;
  for (var i = 0; i < threads.length; i++) {
    var messages = threads[i].getMessages();
    for (var j = 0; j < messages.length; j++) {
      var mailSize = messages[j].getBody().length; // Or  messages[j].getRawContent().length
      size_total += mailSize;
      Logger.log("Subject: %s, size: %s", messages[j].getSubject(), mailSize);
    }
  }
  Logger.log("Total size: %s", size_total);
}

Note:

If you want to retrieve whole size of each email, please replace var mailSize = messages[j].getBody().length to var mailSize = messages[j].getRawContent().length. By this, the size which includes the special characters in the body, the attachment files and headers can be retrieved.

References:

Search operators you can use with Gmail

getBody()

getRawContent()