问:
Angular 4 + RxJS filtering
I am trying to wrap my head around RxJS and I have a question.  To better understand how everything works, I started a new blank Angular 4 application generated with Angular CLI.  In it, I am running the following code:

this.http.get('./src/app/data/products.json')
    .map(res => res.json())
    .filter((item: any) => {
      let price = parseFloat(item.price);
      return price < 5.0 && price >= 2.5;
    })
    .subscribe((list: Array<ProductModel>) => {
      this.error = '';
      this.products = list;
    },
    error => {
      this.error = error;
    });```
</div>
</div>
</p>

<p>The problem is that filter receives the whole object as a parameter and I cannot filter the individual items.  Using RxJS in a non-angular solution, I used this code:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let products = Observable.create(observer => {
    let xhr = new XMLHttpRequest();

    let onLoad = () => {
        let productsList = JSON.parse(xhr.responseText);
        observer.next(productsList);
        observer.complete();
    }

    xhr.addEventListener('load', onLoad);

    xhr.open('GET', 'products.json');
    xhr.send();

    return () => {
        console.log('cleanup');
        xhr.removeEventListener('load', onLoad);
        xhr.abort();
    }
})
.flatMap(Observable.from)
.filter(item => {
    let price = parseFloat(item.price);
    return price < 5.0 && price >= 2.5;
});

let subscr = products.subscribe(
    product => {
        let li = document.createElement('li');
        li.innerText = product.product_name + ' ' + product.price;
        list$.appendChild(li);
    },
    error => {
        console.log(`Error: ${error}`);
    },
    () => {
        console.log('complete');
        subscr.unsubscribe();
    }
);</code>```

The difference here is that I used flatMap, but if I try the same code in the Angular version I get:
Argument of type '{ (ish: ObservableInput, scheduler?: IScheduler): Observable; (ish: ArrayLike, ...' is not assignable to parameter of type '(value: any, index: number) => ObservableInput'.
  Types of parameters 'scheduler' and 'index' are incompatible.
    Type 'number' is not assignable to type 'IScheduler'.

I was just wondering why the same scenario produces different results.  Is Angular using a different flavor of RxJS?  What is the most efficient way to filter the results in the Angular version?

Thank you.

答:
Below i found from one of SO answer : Angular 2: How to use Observable filter

```<code>.map(content => response.json().data)
.concatMap(arr => Observable.from(arr))
.filter(item => item.Type === 5)
.subscribe(val => console.log(val))
</code>```

if you do as above than it convert your array back to observable stream and you can apply filter on it.

But i still think better to makse use of filter function of array rather than going for rxjs filter function

I do like this , first map response to json , than subscribe and assign value to my object of array and than apply filtering ..

because first you convert your response to proper object type than filtering becomes easy

```<code>this.http.get('./src/app/data/products.json')
    .map(res => res.json())
    .subscribe((list: Array<ProductModel>) => {
      this.error = '';
      this.products = list;
    };
</code>```

once you get object you dont need to user rxJs filter method also, you can use normal array filter method as below

```<code>this.filterobj = this.object.filter(obj=> obj.property == val);
</code>```

and if in your object price value is already float than you can do this

```<code>let filterProduct = this.products.
              filter(o=> o.price < 5.0 && o.price >= 2.5);
</code>```

or

```<code>FilterProduct(element, index, array) {
     let price = parseFloat(element.price);
     return price < 5.0 && price >= 2.5;
}

var filterProduct = this.ProductArray.filter(this.FilterProduct);
</code>```

Title: Angular 4 + RxJS filtering

Body:
I am trying to wrap my head around RxJS and I have a question.  To better understand how everything works, I started a new blank Angular 4 application generated with Angular CLI.  In it, I am running the following code:

this.http.get('./src/app/data/products.json')
    .map(res => res.json())
    .filter((item: any) => {
      let price = parseFloat(item.price);
      return price < 5.0 && price >= 2.5;
    })
    .subscribe((list: Array<ProductModel>) => {
      this.error = '';
      this.products = list;
    },
    error => {
      this.error = error;
    });

The problem is that filter receives the whole object as a parameter and I cannot filter the individual items.  Using RxJS in a non-angular solution, I used this code:

let products = Observable.create(observer => {
    let xhr = new XMLHttpRequest();

    let onLoad = () => {
        let productsList = JSON.parse(xhr.responseText);
        observer.next(productsList);
        observer.complete();
    }

    xhr.addEventListener('load', onLoad);

    xhr.open('GET', 'products.json');
    xhr.send();

    return () => {
        console.log('cleanup');
        xhr.removeEventListener('load', onLoad);
        xhr.abort();
    }
})
.flatMap(Observable.from)
.filter(item => {
    let price = parseFloat(item.price);
    return price < 5.0 && price >= 2.5;
});

let subscr = products.subscribe(
    product => {
        let li = document.createElement('li');
        li.innerText = product.product_name + ' ' + product.price;
        list$.appendChild(li);
    },
    error => {
        console.log(`Error: ${error}`);
    },
    () => {
        console.log('complete');
        subscr.unsubscribe();
    }
);

The difference here is that I used flatMap, but if I try the same code in the Angular version I get:
Argument of type '{ (ish: ObservableInput, scheduler?: IScheduler): Observable; (ish: ArrayLike, ...' is not assignable to parameter of type '(value: any, index: number) => ObservableInput'.
  Types of parameters 'scheduler' and 'index' are incompatible.
    Type 'number' is not assignable to type 'IScheduler'.

I was just wondering why the same scenario produces different results.  Is Angular using a different flavor of RxJS?  What is the most efficient way to filter the results in the Angular version?

Thank you.

Body:
Below i found from one of SO answer : Angular 2: How to use Observable filter

.map(content => response.json().data)
.concatMap(arr => Observable.from(arr))
.filter(item => item.Type === 5)
.subscribe(val => console.log(val))

if you do as above than it convert your array back to observable stream and you can apply filter on it.

But i still think better to makse use of filter function of array rather than going for rxjs filter function

I do like this , first map response to json , than subscribe and assign value to my object of array and than apply filtering ..

because first you convert your response to proper object type than filtering becomes easy

this.http.get('./src/app/data/products.json')
    .map(res => res.json())
    .subscribe((list: Array<ProductModel>) => {
      this.error = '';
      this.products = list;
    };

once you get object you dont need to user rxJs filter method also, you can use normal array filter method as below

this.filterobj = this.object.filter(obj=> obj.property == val);

and if in your object price value is already float than you can do this

let filterProduct = this.products.
              filter(o=> o.price < 5.0 && o.price >= 2.5);

or

FilterProduct(element, index, array) {
     let price = parseFloat(element.price);
     return price < 5.0 && price >= 2.5;
}

var filterProduct = this.ProductArray.filter(this.FilterProduct);


来源: stackexchange

问:
How to parse ant like path
How do I parse paths such as /aaa/bbb/**/*.java as used in ant. I guess I could have looked into the source code. Is there is simple solution.

答: You can use Ant's DirectoryScanner.</p>

ContentLicense: CC BY-SA 2.5

Title: How to parse ant like path

Body: You can use Ant's DirectoryScanner.


问:
Toggle between two colors when key is pressed
I'm currently learning C# with Unity and I created a simple game where you can change the color of the player (which is red by default) by clicking the "C" key (which will change to green).
The code works but, the problem is, I don't know how to create a code that changes the green color to red color again by using the same key ("C").
The only alternative I know is to create another if but with a different button.
Here is my code:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class cubecolor : MonoBehaviour {

    // Use this for initialization
    void Start () {
        gameObject.GetComponent<Renderer> ().material.color = Color.red;

    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKey(KeyCode.C))
            gameObject.GetComponent<Renderer> ().material.color = Color.green;

    }
}
</code>```

答:
Create an if-else structure within the if (Input.GetKey(KeyCode.C)):

```<code> void Update () {
        if (Input.GetKey(KeyCode.C))
        {
            var myObject = gameObject.GetComponent<Renderer>();

            Color currentColor = myObject.material.color;
            if(currentColor == Color.green)
            {
               myObject.material.color = Color.Red;
            }
            else
            {
               myObject.material.color = Color.Green;
            }
        }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm currently learning C# with Unity and I created a simple game where you can change the color of the player (which is red by default) by clicking the "C" key (which will change to green).
The code works but, the problem is, I don't know how to create a code that changes the green color to red color again by using the same key ("C").
The only alternative I know is to create another if but with a different button.
Here is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class cubecolor : MonoBehaviour {

    // Use this for initialization
    void Start () {
        gameObject.GetComponent<Renderer> ().material.color = Color.red;

    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKey(KeyCode.C))
            gameObject.GetComponent<Renderer> ().material.color = Color.green;

    }
}

Body:
Create an if-else structure within the if (Input.GetKey(KeyCode.C)):

 void Update () {
        if (Input.GetKey(KeyCode.C))
        {
            var myObject = gameObject.GetComponent<Renderer>();

            Color currentColor = myObject.material.color;
            if(currentColor == Color.green)
            {
               myObject.material.color = Color.Red;
            }
            else
            {
               myObject.material.color = Color.Green;
            }
        }


问:
eclipse project has jar in referenced library not listed as dependency
I have a java project setup in eclipse to build with maven. Project itself is a multi-module maven project (but I am not using m2e plugin rather maven-eclipse plugin, and eclipse project does not have maven nature)

When running mvn install within eclipse, everything compiles fine, but when I run the same command in command prompt, I get compile errors due to a missing dependency.

I see that the jar it's looking for is neither listed explicitly as dependency in pom.xml or is a transitive dependency. I tried running mvn dependency:tree but also couldn't see this jar.

How can this jar be available in eclipse?

Update: two missing jars are

```<code><dependency>
    <groupId>org.springframework.integration</groupId>
    <artifactId>spring-integration-jms</artifactId>
</dependency>
<dependency>
    <groupId>javax.jms</groupId>
    <artifactId>jms</artifactId>
</dependency>
</code>```

答:
I solved the issue. Problem had to do with my invalid global mirror settings that redirected traffic to wrong remote repository so it could not find and install dependencies, later causing compile error.

In eclipse, I was using embedded maven referencing user settings only with no global settings therefore it worked fine.

Body:
I have a java project setup in eclipse to build with maven. Project itself is a multi-module maven project (but I am not using m2e plugin rather maven-eclipse plugin, and eclipse project does not have maven nature)

When running mvn install within eclipse, everything compiles fine, but when I run the same command in command prompt, I get compile errors due to a missing dependency.

I see that the jar it's looking for is neither listed explicitly as dependency in pom.xml or is a transitive dependency. I tried running mvn dependency:tree but also couldn't see this jar.

How can this jar be available in eclipse?

Update: two missing jars are

<dependency>
    <groupId>org.springframework.integration</groupId>
    <artifactId>spring-integration-jms</artifactId>
</dependency>
<dependency>
    <groupId>javax.jms</groupId>
    <artifactId>jms</artifactId>
</dependency>


问:
candlestick charts using Matplotlib skip weekends
I need some help. I am learning between matplotlib and numpy. I am simply reproducing a piece of code from "Intraday candlestick charts using Matplotlib" with my own csv file to learn from that code. The different part of my code that is different from it is the following:

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

from mpl_finance import candlestick_ohlc
from matplotlib.dates import num2date

# data in a text file, 5 columns: time, opening, close, high, low
# note that I'm using the time you formated into an ordinal float data =
np.loadtxt("/Users/paul/Documents/python/Quant/INTC.csv",       delimiter=",")
</code>```

I am getting an error that says

```<code>ValueError: could not convert string to float: b'Date'.
</code>```

I even try to use this line and still gives me the same error message

```<code>data = np.genfromtxt("/Users/paul/Documents/python/Quant/INTC.csv", delimiter=",", skip_header=1, usecols=[0,1,2,3,4], dtype=(dt, float,float,float, float))"
</code>```

it's probably a basic concept that I am not understanding. much appriciated  for some guidance.

sample data:

```<code>Date,Open,High,Low,Close,Volume,Adj Close
2017-11-06,46.599998,46.740002,46.090000,46.700001,46.700001,34035000
2017-11-07,46.700001,47.090000,46.389999,46.779999,46.779999,24461400
2017-11-08,46.619999,46.700001,46.279999,46.700001,46.700001,21565800
2017-11-09,46.049999,46.389999,45.650002,46.299999,46.299999,25570400
2017-11-10,46.040001,46.090000,45.380001,45.580002,45.580002,24095400
2017-11-13,45.259998,45.939999,45.250000,45.750000,45.750000,18999000
</code>```

Body:
I need some help. I am learning between matplotlib and numpy. I am simply reproducing a piece of code from "Intraday candlestick charts using Matplotlib" with my own csv file to learn from that code. The different part of my code that is different from it is the following:

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

from mpl_finance import candlestick_ohlc
from matplotlib.dates import num2date

# data in a text file, 5 columns: time, opening, close, high, low
# note that I'm using the time you formated into an ordinal float data =
np.loadtxt("/Users/paul/Documents/python/Quant/INTC.csv",       delimiter=",")

I am getting an error that says

ValueError: could not convert string to float: b'Date'.

I even try to use this line and still gives me the same error message

data = np.genfromtxt("/Users/paul/Documents/python/Quant/INTC.csv", delimiter=",", skip_header=1, usecols=[0,1,2,3,4], dtype=(dt, float,float,float, float))"

it's probably a basic concept that I am not understanding. much appriciated  for some guidance.

sample data:

Date,Open,High,Low,Close,Volume,Adj Close
2017-11-06,46.599998,46.740002,46.090000,46.700001,46.700001,34035000
2017-11-07,46.700001,47.090000,46.389999,46.779999,46.779999,24461400
2017-11-08,46.619999,46.700001,46.279999,46.700001,46.700001,21565800
2017-11-09,46.049999,46.389999,45.650002,46.299999,46.299999,25570400
2017-11-10,46.040001,46.090000,45.380001,45.580002,45.580002,24095400
2017-11-13,45.259998,45.939999,45.250000,45.750000,45.750000,18999000

Body:
You can import "Date column' (string) by converting it to a datetime object. Once you have it as a datetime object you can filter out the weekends as shown below. you can plot the filtered data in matplotlib as matplotlib understands datetime objects. hope that helps.

'''
data in csv
Date,Open,High,Low,Close,Volume,Adj Close
2017-12-06,46.599998,46.740002,46.090000,46.700001,46.700001,34035000
2017-12-07,46.700001,47.090000,46.389999,46.779999,46.779999,24461400
2017-12-08,46.619999,46.700001,46.279999,46.700001,46.700001,21565800
2017-12-09,46.049999,46.389999,45.650002,46.299999,46.299999,25570400
2017-12-10,46.040001,46.090000,45.380001,45.580002,45.580002,24095400
2017-12-13,45.259998,45.939999,45.250000,45.750000,45.750000,18999000
'''

import numpy as np
from datetime import datetime

# use converter to convert a string object to datetime object. Note dtype is object for all columns
data = np.genfromtxt(r'stock.csv', delimiter = ',', names = True,
                    converters={0: lambda x: datetime.strptime(x, "%Y-%m-%d")}, dtype=object)

print data

'''
[ (datetime.datetime(2017, 12, 6, 0, 0), '46.599998', '46.740002', '46.090000', '46.700001', '46.700001', '34035000')
 (datetime.datetime(2017, 12, 7, 0, 0), '46.700001', '47.090000', '46.389999', '46.779999', '46.779999', '24461400')
 (datetime.datetime(2017, 12, 8, 0, 0), '46.619999', '46.700001', '46.279999', '46.700001', '46.700001', '21565800')
 (datetime.datetime(2017, 12, 9, 0, 0), '46.049999', '46.389999', '45.650002', '46.299999', '46.299999', '25570400')
 (datetime.datetime(2017, 12, 10, 0, 0), '46.040001', '46.090000', '45.380001', '45.580002', '45.580002', '24095400')
 (datetime.datetime(2017, 12, 13, 0, 0), '45.259998', '45.939999', '45.250000', '45.750000', '45.750000', '18999000')]
'''

# check if a day is a weekday or not
def check_weekday_or_not(datetime_object):
    if datetime_object.weekday() not in [5,6]:
        # datetime.weekday() returns 5 and 6 for saturday and Sunday
        return True
    else:
        return False

# create a function to apply on each row of the matrix
vfunc =np.vectorize(check_weekday_or_not)
filter_mask = vfunc(data['Date'])
print filter_mask
#[ True  True  True False False  True]

# Apply the filter mask to obtain an array without weekends.
print data[filter_mask]
'''
array([ (datetime.datetime(2017, 12, 6, 0, 0), '46.599998', '46.740002', '46.090000', '46.700001', '46.700001', '34035000'),
       (datetime.datetime(2017, 12, 7, 0, 0), '46.700001', '47.090000', '46.389999', '46.779999', '46.779999', '24461400'),
       (datetime.datetime(2017, 12, 8, 0, 0), '46.619999', '46.700001', '46.279999', '46.700001', '46.700001', '21565800'),
       (datetime.datetime(2017, 12, 13, 0, 0), '45.259998', '45.939999', '45.250000', '45.750000', '45.750000', '18999000')],
      dtype=[('Date', 'O'), ('Open', 'O'), ('High', 'O'), ('Low', 'O'), ('Close', 'O'), ('Volume', 'O'), ('Adj_Close', 'O')])
'''


问:
Internal server error ajax submission
I have a function that triggers on a button click that passes the following argument: insertSongPlay(newSong.songID); when I console.log the newSong.songID I see a value of 90, which is desired.

This function is called here which runs an ajax call:

```<code>function insertSongPlay(songID)

{
    $.ajax
    ({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: "/Album/InsertSongPlay/",
        data: JSON.stringify({ "songID": songID }),
        success: function(data)
        {

            console.log("submitted");
            console.log(songID);
            //TODO: Indicate Success
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            //TODO: Indicate Error
            console.log(errorThrown);
        }
    });
}
</code>```

Here is the corresponding ajax url found in my AlbumController:

```<code>public JsonResult InsertSongPlay(int songID)
{
    try
    {
        EntityDataAccess.InsertSongPlay(songID);
        return Json(true);
    }
    catch(Exception ex)
    {
        return Json(ex);
    }
}
</code>```

Then in my EntityDataAccess.cs the following is run from the InsertSongPlay entity data access:

```<code>public static SongPlayDaily InsertSongPlay(int songID)
{
    using(var Context = GetContext())
    {
        var currentSongPlay = Context.SongPlayDailies.FirstOrDefault(x => x.SongID == songID && x.PlayDate == DateTime.Now.Date);
        if (currentSongPlay != null)
            currentSongPlay.NumberOfPlays++;
        else
        {
            currentSongPlay = new SongPlayDaily();
            currentSongPlay.SongID = songID;
            currentSongPlay.PlayDate = DateTime.Now.Date;
            currentSongPlay.NumberOfPlays = 1;
            Context.SongPlayDailies.Add(currentSongPlay);
        }
        Context.SaveChanges();
        return currentSongPlay;
    }
}
</code>```

However, my ajax call always throws an error and prints Internal Server Error to the console log. The Visual Studio debug mode indicates some sort of circular reference error. I'm not quite sure where I'm going wrong.

Thanks!

答:
As we figured out in comments - there are multiple problems here. First,

```<code>return Json(ex);
</code>```

Is a bad idea. That will inspect all properties of exception and try to serialize them, and all properties of those properties, to json. As you see, that is not going well, and also completely unnecessary. If you want to return error response to client - prepare it (use ex.Message for example). Plus, you don't want to return sensetive information (like stack trace) to your clients on every error.

Besides that - by doing return Json() on exception -  you violate HTTP conventions. Json() will return response with status code 200 OK. But in your case it's not really "ok" - so you should return another status code indicating error. If not that circular reference error - your code in ajax "error" handler would never has been triggered, even when there was really an error.

Easiest way to fix it is just remove try-catch completely and let framework handle that for you.

Second problem is

```<code>x.PlayDate == DateTime.Now.Date
</code>```

filter in query. Entity Framework has problem with accessing Date property of DateTime objects and refuses to convert that into SQL query. You can either move that to another variable:

```<code>var today = DateTime.Now.Date;
Where(x => x.PlayDate == today)
</code>```

or use DbFunctions.TruncateTime:

```<code>Where(x => x.PlayDate == DbFunctions.TruncateTime(DateTime.Now))
</code>```

Note that those ways are not exactly equivalent. First will compare with exact date value, and second will use SQL SYSDATETIME() function. In this case that hardly matters though.

Title: Internal server error ajax submission

Body:
I have a function that triggers on a button click that passes the following argument: insertSongPlay(newSong.songID); when I console.log the newSong.songID I see a value of 90, which is desired.

This function is called here which runs an ajax call:

function insertSongPlay(songID)

{
    $.ajax
    ({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: "/Album/InsertSongPlay/",
        data: JSON.stringify({ "songID": songID }),
        success: function(data)
        {

            console.log("submitted");
            console.log(songID);
            //TODO: Indicate Success
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            //TODO: Indicate Error
            console.log(errorThrown);
        }
    });
}

Here is the corresponding ajax url found in my AlbumController:

public JsonResult InsertSongPlay(int songID)
{
    try
    {
        EntityDataAccess.InsertSongPlay(songID);
        return Json(true);
    }
    catch(Exception ex)
    {
        return Json(ex);
    }
}

Then in my EntityDataAccess.cs the following is run from the InsertSongPlay entity data access:

public static SongPlayDaily InsertSongPlay(int songID)
{
    using(var Context = GetContext())
    {
        var currentSongPlay = Context.SongPlayDailies.FirstOrDefault(x => x.SongID == songID && x.PlayDate == DateTime.Now.Date);
        if (currentSongPlay != null)
            currentSongPlay.NumberOfPlays++;
        else
        {
            currentSongPlay = new SongPlayDaily();
            currentSongPlay.SongID = songID;
            currentSongPlay.PlayDate = DateTime.Now.Date;
            currentSongPlay.NumberOfPlays = 1;
            Context.SongPlayDailies.Add(currentSongPlay);
        }
        Context.SaveChanges();
        return currentSongPlay;
    }
}

However, my ajax call always throws an error and prints Internal Server Error to the console log. The Visual Studio debug mode indicates some sort of circular reference error. I'm not quite sure where I'm going wrong.

Thanks!

Body:
As we figured out in comments - there are multiple problems here. First,

return Json(ex);

Is a bad idea. That will inspect all properties of exception and try to serialize them, and all properties of those properties, to json. As you see, that is not going well, and also completely unnecessary. If you want to return error response to client - prepare it (use ex.Message for example). Plus, you don't want to return sensetive information (like stack trace) to your clients on every error.

Besides that - by doing return Json() on exception -  you violate HTTP conventions. Json() will return response with status code 200 OK. But in your case it's not really "ok" - so you should return another status code indicating error. If not that circular reference error - your code in ajax "error" handler would never has been triggered, even when there was really an error.

Easiest way to fix it is just remove try-catch completely and let framework handle that for you.

Second problem is

x.PlayDate == DateTime.Now.Date

filter in query. Entity Framework has problem with accessing Date property of DateTime objects and refuses to convert that into SQL query. You can either move that to another variable:

var today = DateTime.Now.Date;
Where(x => x.PlayDate == today)

or use DbFunctions.TruncateTime:

Where(x => x.PlayDate == DbFunctions.TruncateTime(DateTime.Now))

Note that those ways are not exactly equivalent. First will compare with exact date value, and second will use SQL SYSDATETIME() function. In this case that hardly matters though.


问:
Subclass __init__ is not called if superclass __new__ is defined
See the following ipython session:

```<code>$ ipython --no-banner

In [1]: class foo(object):
   ...:     def __new__(self, *args, **kwargs):
   ...:         print 'in superclass __new__'
   ...:         return self
   ...:
   ...: class bar(foo):
   ...:     def __init__(self, *args, **kwargs):
   ...:         print 'in subclass __init__'
   ...:         self.val = 42
   ...:

In [2]: b = bar()
in superclass __new__

In [3]: b.val
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-c55d38c9d4d9> in <module>()
----> 1 b.val

AttributeError: type object 'bar' has no attribute 'val'
</code>```

What is going on here? Why does defining __new__ in foo prevent the __init__ from running in bar?

答:
Your __new__ function signature implies you don't quite understand what is going on. The first argument to __new__ will be the class, calling it self which is conventionally used for the instance should be a warning: __new__ is a constructor, the instance doesn't exist yet. So what happens is you are returning an object that isn't the same type as the class, (it is the class in fact, so it is of type type) thus, __init__ is skipped! You want something like this:

```<code>In [4]: class Foo(object):
   ...:     def __new__(cls, *args, **kwargs):
   ...:         print 'in superclass __new__'
   ...:         return super(Foo, cls).__new__(cls, *args, **kwargs)
   ...:
   ...: class Bar(Foo):
   ...:     def __init__(self, *args, **kwargs):
   ...:         print 'in subclass __init__'
   ...:         self.val = 42
   ...:

In [5]: b = Bar()
in superclass __new__
in subclass __init__
</code>```

Body:
See the following ipython session:

$ ipython --no-banner

In [1]: class foo(object):
   ...:     def __new__(self, *args, **kwargs):
   ...:         print 'in superclass __new__'
   ...:         return self
   ...:
   ...: class bar(foo):
   ...:     def __init__(self, *args, **kwargs):
   ...:         print 'in subclass __init__'
   ...:         self.val = 42
   ...:

In [2]: b = bar()
in superclass __new__

In [3]: b.val
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-c55d38c9d4d9> in <module>()
----> 1 b.val

AttributeError: type object 'bar' has no attribute 'val'

What is going on here? Why does defining __new__ in foo prevent the __init__ from running in bar?

Body:
Your __new__ function signature implies you don't quite understand what is going on. The first argument to __new__ will be the class, calling it self which is conventionally used for the instance should be a warning: __new__ is a constructor, the instance doesn't exist yet. So what happens is you are returning an object that isn't the same type as the class, (it is the class in fact, so it is of type type) thus, __init__ is skipped! You want something like this:

In [4]: class Foo(object):
   ...:     def __new__(cls, *args, **kwargs):
   ...:         print 'in superclass __new__'
   ...:         return super(Foo, cls).__new__(cls, *args, **kwargs)
   ...:
   ...: class Bar(Foo):
   ...:     def __init__(self, *args, **kwargs):
   ...:         print 'in subclass __init__'
   ...:         self.val = 42
   ...:

In [5]: b = Bar()
in superclass __new__
in subclass __init__


问:
How to create a transparent glass cup in OpenGL ES/OpenGL?
Is there a way to create a glass cup with OpenGL ES/OpenGl? And if it's possible, what can i read to start creating? Need to get the most realistic view of a glass, for example -

see glass cup image

For simplicity, without handles.

Maybe, anybody has example with sources?

Thanks.

答:
With programmable shaders it is possible to create nice glass effects, such as reflection combined with refraction.  OpenGL ES 2.0 has programmable shaders, but OpenGL ES 1.X does not.

A good example of glass with OpenGL ES 2.0 comes with AMD RenderMonkey (free).  Download here, and have a look at the glass examples.


问:
Django, how to access models inside a model through a model field
I have two models that have a many-to-one relationship between them.

```<code>from django.db import models

class Continent(models.Model):
    name = models.CharField(max_length=255, unique=True)
    code = models.CharField(max_length=2, unique=True, primary_key=False)
    c = Continent.objects.get(id=1)
    countries = c.country_set.all()
    class Meta:
        ordering = ["name"]

class Country(models.Model):
    name = models.CharField(max_length=255, unique=True)
    capital = models.CharField(max_length=255)
    code = models.CharField(max_length=2, unique=True, primary_key=False)
    continent = models.ForeignKey('Continent')
    population = models.PositiveIntegerField()
    area = PositiveIntegerField()
    class Meta:
        ordering = ["name"]
</code>```

I want the countries of a continent to be accessible through a countries attribute within the Continent model. I tried to follow the relationship "backward" like in the documentation (link below), but can't get it to work.
https://docs.djangoproject.com/en/1.11/topics/db/queries/#backwards-related-objects

答:
You need to set a related_name parameter in the ForeignKey relation. This will automatically add a field with that name to the Continent model.

So this is how your models will look (note the 'related_name' parameter in Country.continent foreign key field):

```<code>class Continent(models.Model):
    name = models.CharField(max_length=255, unique=True)
    code = models.CharField(max_length=2, unique=True, primary_key=False)

    class Meta:
        ordering = ["name"]

class Country(models.Model):
    name = models.CharField(max_length=255, unique=True)
    capital = models.CharField(max_length=255)
    code = models.CharField(max_length=2, unique=True, primary_key=False)
    continent = models.ForeignKey('Continent', related_name='countries')
    population = models.PositiveIntegerField()
    area = PositiveIntegerField()
    class Meta:
        ordering = ["name"]
</code>```

Now you can do something like this:

```<code>def test():
    c = Continent.objects.get(id=1)
    for country in c.countries.all():
        print(c.name)
</code>```

country_set is the default name used as the related name. You don't need to set it as an explicit field in the Continent class. It is created behind the scenes.

Body:
I have two models that have a many-to-one relationship between them.

from django.db import models

class Continent(models.Model):
    name = models.CharField(max_length=255, unique=True)
    code = models.CharField(max_length=2, unique=True, primary_key=False)
    c = Continent.objects.get(id=1)
    countries = c.country_set.all()
    class Meta:
        ordering = ["name"]

class Country(models.Model):
    name = models.CharField(max_length=255, unique=True)
    capital = models.CharField(max_length=255)
    code = models.CharField(max_length=2, unique=True, primary_key=False)
    continent = models.ForeignKey('Continent')
    population = models.PositiveIntegerField()
    area = PositiveIntegerField()
    class Meta:
        ordering = ["name"]

I want the countries of a continent to be accessible through a countries attribute within the Continent model. I tried to follow the relationship "backward" like in the documentation (link below), but can't get it to work.
https://docs.djangoproject.com/en/1.11/topics/db/queries/#backwards-related-objects

Body:
You need to set a related_name parameter in the ForeignKey relation. This will automatically add a field with that name to the Continent model.

So this is how your models will look (note the 'related_name' parameter in Country.continent foreign key field):

class Continent(models.Model):
    name = models.CharField(max_length=255, unique=True)
    code = models.CharField(max_length=2, unique=True, primary_key=False)

    class Meta:
        ordering = ["name"]

class Country(models.Model):
    name = models.CharField(max_length=255, unique=True)
    capital = models.CharField(max_length=255)
    code = models.CharField(max_length=2, unique=True, primary_key=False)
    continent = models.ForeignKey('Continent', related_name='countries')
    population = models.PositiveIntegerField()
    area = PositiveIntegerField()
    class Meta:
        ordering = ["name"]

Now you can do something like this:

def test():
    c = Continent.objects.get(id=1)
    for country in c.countries.all():
        print(c.name)

country_set is the default name used as the related name. You don't need to set it as an explicit field in the Continent class. It is created behind the scenes.


问:
Get the up vector of the camera in ARKit
I'm trying to get the four vectors that make up the boundaries of the frustum in ARKit, and the solution I came up with is as follows:

Find the field of view angles of the camera

Then find the direction and up vectors of the camera

Using these information, find the four vectors using cross products and rotations

This may be a sloppy way of doing it, however it is the best one I got so far.

I am able to get the FOV angles and the direction vector from the ARCamera.intrinsics and ARCamera.transform properties. However, I don't know how to get the up vector of the camera at this point.

Below is the piece of code I use to find the FOV angles and the direction vector:

```<code>func session(_ session: ARSession, didUpdate frame: ARFrame) {
  if xFovDegrees == nil || yFovDegrees == nil {
    let imageResolution = frame.camera.imageResolution
    let intrinsics = frame.camera.intrinsics
    xFovDegrees = 2 * atan(Float(imageResolution.width) / (2 * intrinsics[0,0])) * 180 / Float.pi
    yFovDegrees = 2 * atan(Float(imageResolution.height) / (2 * intrinsics[1,1])) * 180 / Float.pi
  }

  let cameraTransform = SCNMatrix4(frame.camera.transform)
  let cameraDirection = SCNVector3(-1 * cameraTransform.m31,
                                   -1 * cameraTransform.m32,
                                   -1 * cameraTransform.m33)
}
</code>```

I am also open to suggestions for ways to find the the four vectors I'm trying to get.

答:
I had not understood how this line worked:

```<code>let cameraDirection = SCNVector3(-1 * cameraTransform.m31,
                                 -1 * cameraTransform.m32,
                                 -1 * cameraTransform.m33)
</code>```

This gives the direction vector of the camera because the 3rd row of the transformation matrix gives where the new z-direction of the transformed camera points at. We multiply it by -1 because the default direction of the camera is the negative z-axis.

Considering this information and the fact that the default up vector for a camera is the positive y-axis, the 2nd row of the transformation matrix gives us the up vector of the camera. The following code gives me what I want:

```<code>let cameraUp = SCNVector3(cameraTransform.m21,
                          cameraTransform.m22,
                          cameraTransform.m23)
</code>```

Body:
I'm trying to get the four vectors that make up the boundaries of the frustum in ARKit, and the solution I came up with is as follows:

Find the field of view angles of the camera

Then find the direction and up vectors of the camera

Using these information, find the four vectors using cross products and rotations

This may be a sloppy way of doing it, however it is the best one I got so far.

I am able to get the FOV angles and the direction vector from the ARCamera.intrinsics and ARCamera.transform properties. However, I don't know how to get the up vector of the camera at this point.

Below is the piece of code I use to find the FOV angles and the direction vector:

func session(_ session: ARSession, didUpdate frame: ARFrame) {
  if xFovDegrees == nil || yFovDegrees == nil {
    let imageResolution = frame.camera.imageResolution
    let intrinsics = frame.camera.intrinsics
    xFovDegrees = 2 * atan(Float(imageResolution.width) / (2 * intrinsics[0,0])) * 180 / Float.pi
    yFovDegrees = 2 * atan(Float(imageResolution.height) / (2 * intrinsics[1,1])) * 180 / Float.pi
  }

  let cameraTransform = SCNMatrix4(frame.camera.transform)
  let cameraDirection = SCNVector3(-1 * cameraTransform.m31,
                                   -1 * cameraTransform.m32,
                                   -1 * cameraTransform.m33)
}

I am also open to suggestions for ways to find the the four vectors I'm trying to get.

Body:
I had not understood how this line worked:

let cameraDirection = SCNVector3(-1 * cameraTransform.m31,
                                 -1 * cameraTransform.m32,
                                 -1 * cameraTransform.m33)

This gives the direction vector of the camera because the 3rd row of the transformation matrix gives where the new z-direction of the transformed camera points at. We multiply it by -1 because the default direction of the camera is the negative z-axis.

Considering this information and the fact that the default up vector for a camera is the positive y-axis, the 2nd row of the transformation matrix gives us the up vector of the camera. The following code gives me what I want:

let cameraUp = SCNVector3(cameraTransform.m21,
                          cameraTransform.m22,
                          cameraTransform.m23)


问:
Grails: Bi-directional one-to-many results in endless recursion (StackOverflow)
I've recently taken over a Grails project from another person.

I'm using Grails 3.2.11 and Hibernate 4.3.10

I'm adding new features and one of them is expanding the datamodel. There are Stories with Tags and I want to combine them into TagAliasGroups. So I've added:

```<code>import groovy.transform.EqualsAndHashCode

@EqualsAndHashCode
class TagAliasGroup {
    Date created = new Date()

    Set aliases

    static hasMany = [aliases: Tag]
[...]
</code>```

In the Tag class I referred to that:

```<code>import groovy.transform.EqualsAndHashCode

@EqualsAndHashCode
class Tag {
    String tag
    Boolean promoted
    Boolean isCategory
    Date created = new Date()

    TagAliasGroup aliasGroup

[...]
</code>```

The DB-Schema was updated correctly and I can write new data sets just fine. But when trying to access the "aliases" set from the TagAliasGroup, I get an endless recursion inside of Hibernate and a StackOverflow Exception as a consequence:

```<code>def getAliasList() {
    try
    {
        if(aliasGroup)
        {
            Set al = aliasGroup.aliases
            // al.remove(this)

            return al.join(", ")
        }
        else return ""
    }
    catch(Exception e){
        return e.getMessage()
    }
}
</code>```

The "return al.join(", ")" throws the exception, but any other access to the Collection has the same result. The debugger also gets an exception when trying to evaluate "al".
When stepping into Hibernate at that point, it looks to me as the code tries to dereference and resolve the proxy for the TagAliasGroup over and over again.

I made a simple workaround by making "aliases" transient:

```<code>import groovy.transform.EqualsAndHashCode

@EqualsAndHashCode
class TagAliasGroup {
    Date created = new Date()

    // Set aliases
    // static hasMany = [aliases: Tag]

    def getAliases() {
        return Tag.findAllByAliasGroup(this)
    }
</code>```

This is working perfectly, but it cannot be the correct solution. Especially since I'd expect that hibernate would cache the result and be more efficient because of that.

What am I missing? It must be something obvious but I cannot figure out what.

Here's the exception:

```<code>java.lang.StackOverflowError: null
        at org.apache.commons.logging.impl.SLF4JLocationAwareLog.isDebugEnabled(SLF4JLocationAwareLog.java:67)
        at org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy$LazyConnectionInvocationHandler.getTargetConnection(LazyConnectionDataSourceProxy.java:429)
        at org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy$LazyConnectionInvocationHandler.invoke(LazyConnectionDataSourceProxy.java:376)
        at org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy$TransactionAwareInvocationHandler.invoke(TransactionAwareDataSourceProxy.java:240)
        at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:162)
        at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:186)
        at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:160)
        at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.prepareQueryStatement(AbstractLoadPlanBasedLoader.java:257)
        at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeQueryStatement(AbstractLoadPlanBasedLoader.java:201)
        at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:137)
        at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:102)
        at org.hibernate.loader.collection.plan.AbstractLoadPlanBasedCollectionInitializer.initialize(AbstractLoadPlanBasedCollectionInitializer.java:100)
        at org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:693)
        at org.hibernate.event.internal.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:92)
        at org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:1933)
        at org.hibernate.collection.internal.AbstractPersistentCollection$4.doWork(AbstractPersistentCollection.java:558)
        at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:260)
        at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:554)
        at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:142)
        at org.hibernate.collection.internal.PersistentSet.hashCode(PersistentSet.java:447)
        at org.codehaus.groovy.util.HashCodeHelper.updateHash(HashCodeHelper.java:84)
        at org.codehaus.groovy.util.HashCodeHelper.updateHash(HashCodeHelper.java:84)
        at java.util.HashMap.hash(HashMap.java:339)
        at java.util.HashMap.put(HashMap.java:612)
        at java.util.HashSet.add(HashSet.java:220)
        at java.util.AbstractCollection.addAll(AbstractCollection.java:344)
        at org.hibernate.collection.internal.PersistentSet.endRead(PersistentSet.java:344)
        at org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollection(CollectionLoadContext.java:251)
        at org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:238)
        at org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:211)
        at org.hibernate.loader.plan.exec.process.internal.CollectionReferenceInitializerImpl.endLoading(CollectionReferenceInitializerImpl.java:168)
        at org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.finishLoadingCollections(AbstractRowReader.java:255)
        at org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.finishUp(AbstractRowReader.java:218)
        at org.hibernate.loader.plan.exec.process.internal.ResultSetProcessorImpl.extractResults(ResultSetProcessorImpl.java:140)
        at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:138)
        at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:102)
        at org.hibernate.loader.collection.plan.AbstractLoadPlanBasedCollectionInitializer.initialize(AbstractLoadPlanBasedCollectionInitializer.java:100)
        at org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:693)
        at org.hibernate.event.internal.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:92)
        at org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:1933)
</code>```

Repeating from here on endlessly.

答:
I'll prefix this answer by saying in my experience using hasMany, belongsTo, or any of the other qualifiers causes way more problems than it helps.  Unless you absolutely need what they provide (cascading, specific hibernate level caching, etc). Just stick with keeping the simple reference you have on Tag and remove the 'hasMany' from TagAliasGroup, and use dynamic finder to load the tags as per your workaround.  That said, sticking with your design, I think you need 'belongsTo' to avoid the recursion of a circular back reference to TagAliasGroup for the given tag.</p>

```<code>class Tag {
 ....
 static belongsTo = [TagAliasGroup: aliasGroup]
 ....
}
</code>```

Body:
I've recently taken over a Grails project from another person.

I'm using Grails 3.2.11 and Hibernate 4.3.10

I'm adding new features and one of them is expanding the datamodel. There are Stories with Tags and I want to combine them into TagAliasGroups. So I've added:

import groovy.transform.EqualsAndHashCode

@EqualsAndHashCode
class TagAliasGroup {
    Date created = new Date()

    Set aliases

    static hasMany = [aliases: Tag]
[...]

In the Tag class I referred to that:

import groovy.transform.EqualsAndHashCode

@EqualsAndHashCode
class Tag {
    String tag
    Boolean promoted
    Boolean isCategory
    Date created = new Date()

    TagAliasGroup aliasGroup

[...]

The DB-Schema was updated correctly and I can write new data sets just fine. But when trying to access the "aliases" set from the TagAliasGroup, I get an endless recursion inside of Hibernate and a StackOverflow Exception as a consequence:

def getAliasList() {
    try
    {
        if(aliasGroup)
        {
            Set al = aliasGroup.aliases
            // al.remove(this)

            return al.join(", ")
        }
        else return ""
    }
    catch(Exception e){
        return e.getMessage()
    }
}

The "return al.join(", ")" throws the exception, but any other access to the Collection has the same result. The debugger also gets an exception when trying to evaluate "al".
When stepping into Hibernate at that point, it looks to me as the code tries to dereference and resolve the proxy for the TagAliasGroup over and over again.

I made a simple workaround by making "aliases" transient:

import groovy.transform.EqualsAndHashCode

@EqualsAndHashCode
class TagAliasGroup {
    Date created = new Date()

    // Set aliases
    // static hasMany = [aliases: Tag]

    def getAliases() {
        return Tag.findAllByAliasGroup(this)
    }

This is working perfectly, but it cannot be the correct solution. Especially since I'd expect that hibernate would cache the result and be more efficient because of that.

What am I missing? It must be something obvious but I cannot figure out what.

Here's the exception:

java.lang.StackOverflowError: null
        at org.apache.commons.logging.impl.SLF4JLocationAwareLog.isDebugEnabled(SLF4JLocationAwareLog.java:67)
        at org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy$LazyConnectionInvocationHandler.getTargetConnection(LazyConnectionDataSourceProxy.java:429)
        at org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy$LazyConnectionInvocationHandler.invoke(LazyConnectionDataSourceProxy.java:376)
        at org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy$TransactionAwareInvocationHandler.invoke(TransactionAwareDataSourceProxy.java:240)
        at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:162)
        at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:186)
        at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:160)
        at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.prepareQueryStatement(AbstractLoadPlanBasedLoader.java:257)
        at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeQueryStatement(AbstractLoadPlanBasedLoader.java:201)
        at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:137)
        at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:102)
        at org.hibernate.loader.collection.plan.AbstractLoadPlanBasedCollectionInitializer.initialize(AbstractLoadPlanBasedCollectionInitializer.java:100)
        at org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:693)
        at org.hibernate.event.internal.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:92)
        at org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:1933)
        at org.hibernate.collection.internal.AbstractPersistentCollection$4.doWork(AbstractPersistentCollection.java:558)
        at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:260)
        at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:554)
        at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:142)
        at org.hibernate.collection.internal.PersistentSet.hashCode(PersistentSet.java:447)
        at org.codehaus.groovy.util.HashCodeHelper.updateHash(HashCodeHelper.java:84)
        at org.codehaus.groovy.util.HashCodeHelper.updateHash(HashCodeHelper.java:84)
        at java.util.HashMap.hash(HashMap.java:339)
        at java.util.HashMap.put(HashMap.java:612)
        at java.util.HashSet.add(HashSet.java:220)
        at java.util.AbstractCollection.addAll(AbstractCollection.java:344)
        at org.hibernate.collection.internal.PersistentSet.endRead(PersistentSet.java:344)
        at org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollection(CollectionLoadContext.java:251)
        at org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:238)
        at org.hibernate.engine.loading.internal.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:211)
        at org.hibernate.loader.plan.exec.process.internal.CollectionReferenceInitializerImpl.endLoading(CollectionReferenceInitializerImpl.java:168)
        at org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.finishLoadingCollections(AbstractRowReader.java:255)
        at org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.finishUp(AbstractRowReader.java:218)
        at org.hibernate.loader.plan.exec.process.internal.ResultSetProcessorImpl.extractResults(ResultSetProcessorImpl.java:140)
        at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:138)
        at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:102)
        at org.hibernate.loader.collection.plan.AbstractLoadPlanBasedCollectionInitializer.initialize(AbstractLoadPlanBasedCollectionInitializer.java:100)
        at org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:693)
        at org.hibernate.event.internal.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:92)
        at org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:1933)

Repeating from here on endlessly.

Body:
I'll prefix this answer by saying in my experience using hasMany, belongsTo, or any of the other qualifiers causes way more problems than it helps.  Unless you absolutely need what they provide (cascading, specific hibernate level caching, etc). Just stick with keeping the simple reference you have on Tag and remove the 'hasMany' from TagAliasGroup, and use dynamic finder to load the tags as per your workaround.  That said, sticking with your design, I think you need 'belongsTo' to avoid the recursion of a circular back reference to TagAliasGroup for the given tag.

class Tag {
 ....
 static belongsTo = [TagAliasGroup: aliasGroup]
 ....
}


问:
JS Add events to a List where rows are added dynamically

Hi,
I am inserting rows in a list dynamically. Right now that is happening on a click of button but eventually that data will come from a DB. That works fine!

What I want to do is that once the list is presented to a user, s/he will take the mouse over the desired list item. At that time the item should be highlighted.
So I want to add mouseover and mouseout event to each row.
But the event is triggered on the function declaration itself.
Please find the JSfiddle link here:
https://jsfiddle.net/indiaaditya/ycyb9dot/

The problem section is here::

```<code>function AddEventsToTableForEachRow(tableId) {
  //Get the NodeList
  alert("Function Called!");
  var nodelist = document.querySelectorAll(".classTableElement");
  var lclCntr = 0;
  alert("Elements found:" + nodelist.length);
  //Set ID's for all the elements
  var strInloop = "";
  //This loop sets the ID for each row.
  for (lclCntr = 0; lclCntr < nodelist.length; lclCntr++) {
    strInloop = "tr" + lclCntr;
    nodelist[lclCntr].setAttribute("id", strInloop);
  }
  //This loop adds event for each row.
  for (lclCntr = 0; lclCntr < nodelist.length; lclCntr++) {
    strInloop = "tr" + lclCntr;
    var rowElement = document.getElementById(strInloop);
    rowElement.addEventListener("onmouseover", alert("A"), false);
  }
}
</code>```

Explanation of JSFiddle code:

1. Click on Generate List button to add rows.

2. Click on GlowRecord Button to highlight the first row. Click it again to remove the highlight. This is the desired function on mouseover and mouseout.

3. Click on AddEvents to generate the events. This is the part of code that is not working

 AddEvents calls

    AddEventsToTableForEachRow('tblTestList')

function.
But this function immediately calls the alert function calls in it.

Expected result is that after calling AddEventsToTableForEachRow, the events should be attached to each row and when the mouse mover to the row, alert message should be shown.

In effect, as mentioned before the alert functions inside AddEventsToTableForEachRow are called immediately and no action on mouseover.

For those who question why I have not used jquery:
a. I am a complete novice to JS/HTML/CSS. I am from C/C++ background and have come to this side because of the ease of building the UI with HTML/CSS/JS.
b. I am learning on the fly and found DOM to be much cleaner and easier to understand.
But after spending 3 days on this issue I am ready for anything and everything. (But will be happier if I get DOM based solution!)

Thanks in advance.

Kind Regards,
Aditya

答:
I would change the following line:

```<code> rowElement.addEventListener("onmouseover", alert("A"), false);
</code>```

to

```<code> rowElement.onmouseover = function() { alert("A"); };
</code>```

Modified fiddle: https://jsfiddle.net/ywvv0brv/

Body:
Hi,
I am inserting rows in a list dynamically. Right now that is happening on a click of button but eventually that data will come from a DB. That works fine!

What I want to do is that once the list is presented to a user, s/he will take the mouse over the desired list item. At that time the item should be highlighted.
So I want to add mouseover and mouseout event to each row.
But the event is triggered on the function declaration itself.
Please find the JSfiddle link here:
https://jsfiddle.net/indiaaditya/ycyb9dot/

The problem section is here::

function AddEventsToTableForEachRow(tableId) {
  //Get the NodeList
  alert("Function Called!");
  var nodelist = document.querySelectorAll(".classTableElement");
  var lclCntr = 0;
  alert("Elements found:" + nodelist.length);
  //Set ID's for all the elements
  var strInloop = "";
  //This loop sets the ID for each row.
  for (lclCntr = 0; lclCntr < nodelist.length; lclCntr++) {
    strInloop = "tr" + lclCntr;
    nodelist[lclCntr].setAttribute("id", strInloop);
  }
  //This loop adds event for each row.
  for (lclCntr = 0; lclCntr < nodelist.length; lclCntr++) {
    strInloop = "tr" + lclCntr;
    var rowElement = document.getElementById(strInloop);
    rowElement.addEventListener("onmouseover", alert("A"), false);
  }
}

Explanation of JSFiddle code:

1. Click on Generate List button to add rows.

2. Click on GlowRecord Button to highlight the first row. Click it again to remove the highlight. This is the desired function on mouseover and mouseout.

3. Click on AddEvents to generate the events. This is the part of code that is not working

 AddEvents calls

    AddEventsToTableForEachRow('tblTestList')

function.
But this function immediately calls the alert function calls in it.

Expected result is that after calling AddEventsToTableForEachRow, the events should be attached to each row and when the mouse mover to the row, alert message should be shown.

In effect, as mentioned before the alert functions inside AddEventsToTableForEachRow are called immediately and no action on mouseover.

For those who question why I have not used jquery:
a. I am a complete novice to JS/HTML/CSS. I am from C/C++ background and have come to this side because of the ease of building the UI with HTML/CSS/JS.
b. I am learning on the fly and found DOM to be much cleaner and easier to understand.
But after spending 3 days on this issue I am ready for anything and everything. (But will be happier if I get DOM based solution!)

Thanks in advance.

Kind Regards,
Aditya

Body:
I would change the following line:

 rowElement.addEventListener("onmouseover", alert("A"), false);

to

 rowElement.onmouseover = function() { alert("A"); };

Modified fiddle: https://jsfiddle.net/ywvv0brv/


问:
Trying to mock delay in API response: Cannot read property 'then' of undefined
In my React app I'm trying to fake a delay in mock API response

Uncaught TypeError: Cannot read property 'then' of undefined

```<code>createDraft() {
  // Post to Mock API
  const newDraft = {
    name: this.state.draftName,
    created_by: this.props.user,
    created: getDate()
  };

  /* ERROR HERE */
  this.props.create(newDraft).then((res) => {
    console.log(' res', res);
    // Display loading spinner while waiting on Promise

    // Close modal and redirect to Draft Summary view
    this.props.closeModal();
  });
}
</code>```

The action:

```<code>export const create = newDraft => dispatch => all()
  .then(() => setTimeout(() => {
    dispatch({
      type: CREATE,
      newDraft
    });
    return 'Draft created!';
  }, 2000))
  .catch(() => {
    dispatch({
      type: REQUEST_ERROR,
      payload: apiErrors.BAD_REQUEST
    });
  });
</code>```

Connected area:

```<code>const mapDispatchToProps = dispatch => ({
  create: (newDraft) => { dispatch(create(newDraft)); }
});

export const CreateDraftModalJest = CreateDraftModal;

export default connect(cleanMapStateToProps([
  'user'
]), mapDispatchToProps)(CreateDraftModal);
</code>```

Also tried this with same result

```<code>function DelayPromise(t) {
  return new Promise(((resolve) => {
    setTimeout(resolve, t);
  }));
}

export const create = newDraft => dispatch => all()
  .then(DelayPromise(2000))
  .then(() => {
    console.log('created called', newDraft);
    dispatch({
      type: CREATE,
      newDraft
    });
  })
  .then(() => 'Draft created!')
  .catch(() => {
    dispatch({
      type: REQUEST_ERROR,
      payload: apiErrors.BAD_REQUEST
    });
  });
</code>```

答:
It's possible that your this.props.create() action creator is not bound to dispatch, and therefore not returning the promise as expected.

Are you using react-redux connect() properly?

EDIT:

Your mapDispatchToProps is not returning the promise. Do this instead:

```<code>const mapDispatchToProps = dispatch => ({
  create: (newDraft) => dispatch(create(newDraft)),
});
</code>```

Body:
In my React app I'm trying to fake a delay in mock API response

Uncaught TypeError: Cannot read property 'then' of undefined

createDraft() {
  // Post to Mock API
  const newDraft = {
    name: this.state.draftName,
    created_by: this.props.user,
    created: getDate()
  };

  /* ERROR HERE */
  this.props.create(newDraft).then((res) => {
    console.log(' res', res);
    // Display loading spinner while waiting on Promise

    // Close modal and redirect to Draft Summary view
    this.props.closeModal();
  });
}

The action:

export const create = newDraft => dispatch => all()
  .then(() => setTimeout(() => {
    dispatch({
      type: CREATE,
      newDraft
    });
    return 'Draft created!';
  }, 2000))
  .catch(() => {
    dispatch({
      type: REQUEST_ERROR,
      payload: apiErrors.BAD_REQUEST
    });
  });

Connected area:

const mapDispatchToProps = dispatch => ({
  create: (newDraft) => { dispatch(create(newDraft)); }
});

export const CreateDraftModalJest = CreateDraftModal;

export default connect(cleanMapStateToProps([
  'user'
]), mapDispatchToProps)(CreateDraftModal);

Also tried this with same result

function DelayPromise(t) {
  return new Promise(((resolve) => {
    setTimeout(resolve, t);
  }));
}

export const create = newDraft => dispatch => all()
  .then(DelayPromise(2000))
  .then(() => {
    console.log('created called', newDraft);
    dispatch({
      type: CREATE,
      newDraft
    });
  })
  .then(() => 'Draft created!')
  .catch(() => {
    dispatch({
      type: REQUEST_ERROR,
      payload: apiErrors.BAD_REQUEST
    });
  });

Body:
It's possible that your this.props.create() action creator is not bound to dispatch, and therefore not returning the promise as expected.

Are you using react-redux connect() properly?

EDIT:

Your mapDispatchToProps is not returning the promise. Do this instead:

const mapDispatchToProps = dispatch => ({
  create: (newDraft) => dispatch(create(newDraft)),
});


问:
Regular Expression for First name
I've got a RegEx pattern fro user first and last name. They can only contain alphabetic characters, spaces (0 - any ), hyphens (0 - any), apostrophes ' (0 - any ) and number of symbols 1 - 40. First and Last name can not start with '  or whitespace

Here is my pattern code.

```<code>^^[a-zA-Z]+[\-\'\s]?[a-zA-Z ]{1,40}$
</code>```

But RegEx does now allow to use this sample  Endevald O'McKnight

答:
You may use

```<code>^(?=.{1,40}$)[a-zA-Z]+(?:[-'\s][a-zA-Z]+)*$
</code>```

See the regex demo.

Details

^ - a start of a string

(?=.{1,40}$) - there must be 1 to 40 chars other than line break chars in the string

[a-zA-Z]+ - 1 or more ASCII letters

(?: - starto of a non-capturing group repeated 0 or more times matching sequences of

[-'\s] - a -, ' or whitespace

[a-zA-Z]+ - 1+ ASCII letters

)* - end of the grouping

$ - end of string

Title: Regular Expression for First name

Body:
I've got a RegEx pattern fro user first and last name. They can only contain alphabetic characters, spaces (0 - any ), hyphens (0 - any), apostrophes ' (0 - any ) and number of symbols 1 - 40. First and Last name can not start with '  or whitespace

Here is my pattern code.

^^[a-zA-Z]+[\-\'\s]?[a-zA-Z ]{1,40}$

But RegEx does now allow to use this sample  Endevald O'McKnight

Body:
You may use

^(?=.{1,40}$)[a-zA-Z]+(?:[-'\s][a-zA-Z]+)*$

See the regex demo.

Details

^ - a start of a string

(?=.{1,40}$) - there must be 1 to 40 chars other than line break chars in the string

[a-zA-Z]+ - 1 or more ASCII letters

(?: - starto of a non-capturing group repeated 0 or more times matching sequences of

[-'\s] - a -, ' or whitespace

[a-zA-Z]+ - 1+ ASCII letters

)* - end of the grouping

$ - end of string


问:
Cloud Functions for Firebase - functions.database.instance (and InstanceBuilder) not found
I'm trying to add listeners in my cloud functions to a second database instance according to the documentation here using:

```<code>exports.myHandler = functions.database.instance('foo').ref('bar')...
</code>```

I am getting an error that the functions.database.instance() function doesn't exist. I have updated my functions using npm upgrade and firebase-functions specifically using npm install --save firebase-functions. I still don't see any reference to InstanceBuilder or functions.database.instance() in the source code. Has this functionality actually been released? Am I missing something?

答: I updated the dependencies in package.json to use the latest versions of firebase-admin and firebase-functions, and it's fixed.</p>

Body:
I'm trying to add listeners in my cloud functions to a second database instance according to the documentation here using:

exports.myHandler = functions.database.instance('foo').ref('bar')...

I am getting an error that the functions.database.instance() function doesn't exist. I have updated my functions using npm upgrade and firebase-functions specifically using npm install --save firebase-functions. I still don't see any reference to InstanceBuilder or functions.database.instance() in the source code. Has this functionality actually been released? Am I missing something?


问:
Trying to get a Java function to return an array based on a string parameter passed to it
Here's what I am trying to do; I am trying to write a small program that uses a function to get an array containing the members of a department based on the department selected. There are about 40 departments, and each department has 1 to 4 members. So this what I did, but I can't seem to resolve to a variable:

From main:

```<code>String[]names = initial(department)
</code>```

Departments is the name of the department being passed to the function. In the function I have:

```<code>public static String[] initial (String responsibleDepartment) {

    if (responsibleDepartment.equals("Accounts Receivable")) {
        String[] assignInitial = {"Mike Davis", "Ben Jones", "Ann Smith"}
     }

    if (responsibleDepartment.equals("Customer Service")) {
        String[] assignInitial = {"Mary Wexler", "Turd Ferguson"}
     }

   // and 38 more if statements with the rest of the departments. Finally I have:
        return assignInitial;
        }
</code>```

So the way it stands, "assignInitial cannot be resolved to a variable" (that's what it says by the return statement.) If I try to initialize the variable before the first "if" statement, and then remove the initialization of String[] next to the assignInitial in the first "if" statement, then it says "Array constants can only be used in initializers." I am sure there is a better way to do this, but I can't seem to make any headway with what I am found online. Any takers?

Thank you much!
-The Munch

答:
I think you're taking the wrong approach here.

Your entire method is fundamentally doing exactly the same thing as a Map: "given this (String) input, what resulting (array of Strings) output does it map to?"

So as an exact rewrite of your existing code, I would first do this:

```<code>private static final Map<String, String[]> INITIALS_BY_DEPARTMENT;

static {
    INITIALS_BY_DEPARTMENT = new HashMap<>();
    INITIALS_BY_DEPARTMENT.put("Accounts Receivable", new String[]{"Mike Davis", "Ben Jones", "Ann Smith"});
    INITIALS_BY_DEPARTMENT.put("Customer Service", new String[]{"Mary Wexler", "Turd Ferguson"});
    // other assignments
}

public static String[] initial (String responsibleDepartment) {
    return INITIALS_BY_DEPARTMENT.get(responsibleDepartment);
}
</code>```

There's still a bad smell with this code, which is that you have data mixed up in your logic.  Ideally, there would be some external database or other configuration that defined which people were responsible for each department.  Instead of defining a constant map in your code, you would read this into that map at startup.  This way you haven't hardcoded values, and you don't run the risk of falling out of date with reality.

Sometimes of course this isn't possible, and the information is purely internal to your application.  But for the use case implied here, the mappings from departments to users is almost certainly defined in some external system.  Even if you're not able to read from that right now, at least separate your mappings into a config file, and have a loader to read that.  This way you have separated your data from the logic, and can easily switch to reading from a different source in future.

Body:
Here's what I am trying to do; I am trying to write a small program that uses a function to get an array containing the members of a department based on the department selected. There are about 40 departments, and each department has 1 to 4 members. So this what I did, but I can't seem to resolve to a variable:

From main:

String[]names = initial(department)

Departments is the name of the department being passed to the function. In the function I have:

public static String[] initial (String responsibleDepartment) {

    if (responsibleDepartment.equals("Accounts Receivable")) {
        String[] assignInitial = {"Mike Davis", "Ben Jones", "Ann Smith"}
     }

    if (responsibleDepartment.equals("Customer Service")) {
        String[] assignInitial = {"Mary Wexler", "Turd Ferguson"}
     }

   // and 38 more if statements with the rest of the departments. Finally I have:
        return assignInitial;
        }

So the way it stands, "assignInitial cannot be resolved to a variable" (that's what it says by the return statement.) If I try to initialize the variable before the first "if" statement, and then remove the initialization of String[] next to the assignInitial in the first "if" statement, then it says "Array constants can only be used in initializers." I am sure there is a better way to do this, but I can't seem to make any headway with what I am found online. Any takers?

Thank you much!
-The Munch

Body:
I think you're taking the wrong approach here.

Your entire method is fundamentally doing exactly the same thing as a Map: "given this (String) input, what resulting (array of Strings) output does it map to?"

So as an exact rewrite of your existing code, I would first do this:

private static final Map<String, String[]> INITIALS_BY_DEPARTMENT;

static {
    INITIALS_BY_DEPARTMENT = new HashMap<>();
    INITIALS_BY_DEPARTMENT.put("Accounts Receivable", new String[]{"Mike Davis", "Ben Jones", "Ann Smith"});
    INITIALS_BY_DEPARTMENT.put("Customer Service", new String[]{"Mary Wexler", "Turd Ferguson"});
    // other assignments
}

public static String[] initial (String responsibleDepartment) {
    return INITIALS_BY_DEPARTMENT.get(responsibleDepartment);
}

There's still a bad smell with this code, which is that you have data mixed up in your logic.  Ideally, there would be some external database or other configuration that defined which people were responsible for each department.  Instead of defining a constant map in your code, you would read this into that map at startup.  This way you haven't hardcoded values, and you don't run the risk of falling out of date with reality.

Sometimes of course this isn't possible, and the information is purely internal to your application.  But for the use case implied here, the mappings from departments to users is almost certainly defined in some external system.  Even if you're not able to read from that right now, at least separate your mappings into a config file, and have a loader to read that.  This way you have separated your data from the logic, and can easily switch to reading from a different source in future.


问:
Unable to use WriteTo.ElasticSearch using serilog sink for elasticsearch
I am using SeriLog 2.5.0 and the Serilogs.Sinks.ElasticSearch 5.3.0 nuget packages to ingest the logs to ElasticSearch (It is a console application).

I am working on a POC code to check if i am able to write my logs to local ElasticSearch Instance. I am following the below tutorial

https://improveandrepeat.com/2014/10/elasticsearch-as-a-sink-for-serilog/

I am not able to use the below code as ElasticSearch is not found in the WriteTo

```<code>Log.Logger = new LoggerConfiguration().WriteTo.ElasticSearch(new ElasticSearchSinkOptions()).CreateLogger();
</code>```

Could someone who is already using this let me know if the versions of both the nuget packages makes sense. I have downloaded all the latest packages.

Body:
I am using SeriLog 2.5.0 and the Serilogs.Sinks.ElasticSearch 5.3.0 nuget packages to ingest the logs to ElasticSearch (It is a console application).

I am working on a POC code to check if i am able to write my logs to local ElasticSearch Instance. I am following the below tutorial

https://improveandrepeat.com/2014/10/elasticsearch-as-a-sink-for-serilog/

I am not able to use the below code as ElasticSearch is not found in the WriteTo

Log.Logger = new LoggerConfiguration().WriteTo.ElasticSearch(new ElasticSearchSinkOptions()).CreateLogger();

Could someone who is already using this let me know if the versions of both the nuget packages makes sense. I have downloaded all the latest packages.


问:
Axios can GET but not POST to the same URL

I'm building a react app

In one component I'm writing this GET request which works:

In another component I'm writing this POST request:

Which then returns this 404 error:

And I have no idea how my GET works but my POST returns 404:not found when I'm requesting the same file both times?

UPDATE:

I'm running a node.js server now but it's a bit of a frankenstein's monster as this really isn't an area I have an understanding of. Does anyone know what I'm doing wrong?

```<code>// Server setup from node.js website
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

// Trying to listen for data from React app to feed into JSON (broken)
var express = require("express");
var myParser = require("body-parser");
var app = express();

app.use(myParser.urlencoded({extended : true}));
app.post("/scene-setup.json", function(request, response) {
    console.log(request.body); //This prints the JSON document received (if it is a JSON document)
});
app.listen(3001);

// Updating JSON file with "obj" (working)
var jsonfile = require('jsonfile')

var file = './scene-setup.json'
var obj = {name: 'JP'}

jsonfile.writeFile(file, obj, function (err) {
  console.error(err)
})
</code>```

答:
Axios is used for making HTTP requests. So, you should have a backend server running that can handle these requests. I am not sure what exactly is the data that you want to save. If you need access to that data, should be saving it on the backend.

If you want to save some data just on the client side, HTML5 filesystem API might be something you want to look at. It can manage some data in the limited sandboxed part of user's filesystem.

Body:
I'm building a react app

In one component I'm writing this GET request which works:

In another component I'm writing this POST request:

Which then returns this 404 error:

And I have no idea how my GET works but my POST returns 404:not found when I'm requesting the same file both times?

UPDATE:

I'm running a node.js server now but it's a bit of a frankenstein's monster as this really isn't an area I have an understanding of. Does anyone know what I'm doing wrong?

// Server setup from node.js website
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

// Trying to listen for data from React app to feed into JSON (broken)
var express = require("express");
var myParser = require("body-parser");
var app = express();

app.use(myParser.urlencoded({extended : true}));
app.post("/scene-setup.json", function(request, response) {
    console.log(request.body); //This prints the JSON document received (if it is a JSON document)
});
app.listen(3001);

// Updating JSON file with "obj" (working)
var jsonfile = require('jsonfile')

var file = './scene-setup.json'
var obj = {name: 'JP'}

jsonfile.writeFile(file, obj, function (err) {
  console.error(err)
})


问:
changing select's parent li elements class
I have selects in list items. onchange of select, if selected options value is empty, I would like to give the parent li element a "isnotselected" class, else if selected option's value is not empty, I would like to give the parent li element a "isselected" class. How can I do this via jQuery?</p>

```<code><ul>
  <li>
    <select>
      <option value="">Select Value</option>
      <option value="1">Value 1</option>
      <option value="2">Value 2</option>
    </select>
  </li>
  <li>
    <select>
      <option value="">Select Value</option>
      <option value="1">Value 1</option>
      <option value="2">Value 2</option>
    </select>
  </li>
  <li>
    <select>
      <option value="">Select Value</option>
      <option value="1">Value 1</option>
      <option value="2">Value 2</option>
    </select>
  </li>
  <li>
    <select>
      <option value="">Select Value</option>
      <option value="1">Value 1</option>
      <option value="2">Value 2</option>
    </select>
  </li>
</ul>
</code>```

答:
Example on jsfiddle

```<code>$("select").change(function(){
    var $li = $(this).parents("li");
    $li.removeClass("isselected").removeClass("isnotselected");
    if($(this).val())
    {
        $li.addClass("isselected");
    }
    else
    {
        $li.addClass("isnotselected");
    }
});
</code>```

All you need to do is register the change event to the select element to add remove the class isselected and isnotselected.

Body:
I have selects in list items. onchange of select, if selected options value is empty, I would like to give the parent li element a "isnotselected" class, else if selected option's value is not empty, I would like to give the parent li element a "isselected" class. How can I do this via jQuery?

    <select>
      <option value="">Select Value</option>
      <option value="1">Value 1</option>
      <option value="2">Value 2</option>
    </select>

    <select>
      <option value="">Select Value</option>
      <option value="1">Value 1</option>
      <option value="2">Value 2</option>
    </select>

    <select>
      <option value="">Select Value</option>
      <option value="1">Value 1</option>
      <option value="2">Value 2</option>
    </select>

    <select>
      <option value="">Select Value</option>
      <option value="1">Value 1</option>
      <option value="2">Value 2</option>
    </select>

Body:
Example on jsfiddle

$("select").change(function(){
    var $li = $(this).parents("li");
    $li.removeClass("isselected").removeClass("isnotselected");
    if($(this).val())
    {
        $li.addClass("isselected");
    }
    else
    {
        $li.addClass("isnotselected");
    }
});

All you need to do is register the change event to the select element to add remove the class isselected and isnotselected.


问:
NuGet Packing a Nuspec: Value cannot be null or empty string. Parameter name: value
I'm packaging up a bunch of javascript for a website.  Here's what my .nuspec looks like.

```<code><?xml version="1.0"?>
<package xmlns="http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd">
  <metadata>
    <version>$version$</version>
    <authors>Author Person</authors>
    <owners>Company Name</owners>
    <id>PackageNameId</id>
    <title>PackageNameId</title>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>Description text stuff</description>
    <copyright>Company Copyright Info</copyright>
  </metadata>
  <files>
    <file src="www\**" target="" />  <!--It just packages everything in the www folder in the same directory as this .nuspec -->
  </files>
</package>
</code>```

It just packages everything in that www folder.  The $version$ token should be getting replaced by the NugetPackage version flag in TFS (what I'm building in).

I don't see anything called value, so I'm really at a loss for why it's throwing an error.

Here's the full error:

```<code>Attempting to build package from 'PackageName.nuspec'.

##[error]Value cannot be null or an empty string.

##[error]Parameter name: value
</code>```

答:
I took an existing package that I am using and removed the version (e.g. <version></version>). The error I got when I tried to run nuget pack mypackage.nuspec:

```<code>Attempting to build package from 'mypackage.nuspec'.
Value cannot be null or an empty string.
Parameter name: value
</code>```

There are 4 required values for a nuspec file:

Id

Version

Authors

Description

Since you are getting this error, I would guess that whatever your $version$ token is not being passed appropriately or used correctly.

Body:
I'm packaging up a bunch of javascript for a website.  Here's what my .nuspec looks like.

<?xml version="1.0"?>
<package xmlns="http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd">
  <metadata>
    <version>$version$</version>
    <authors>Author Person</authors>
    <owners>Company Name</owners>
    <id>PackageNameId</id>
    <title>PackageNameId</title>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>Description text stuff</description>
    <copyright>Company Copyright Info</copyright>
  </metadata>
  <files>
    <file src="www\**" target="" />
  </files>
</package>

It just packages everything in that www folder.  The $version$ token should be getting replaced by the NugetPackage version flag in TFS (what I'm building in).

I don't see anything called value, so I'm really at a loss for why it's throwing an error.

Here's the full error:

Attempting to build package from 'PackageName.nuspec'.

##[error]Value cannot be null or an empty string.

##[error]Parameter name: value

Body:
I took an existing package that I am using and removed the version (e.g. <version></version>). The error I got when I tried to run nuget pack mypackage.nuspec:

Attempting to build package from 'mypackage.nuspec'.
Value cannot be null or an empty string.
Parameter name: value

There are 4 required values for a nuspec file:

Id

Version

Authors

Description

Since you are getting this error, I would guess that whatever your $version$ token is not being passed appropriately or used correctly.


问:
Find index of object in array with highest value in property
I've got an array with objects:

```<code>var articles = [];
var article = {};

Simple loop that iterates x times {
        article.text = "foobar";
        article.color = "red";
        article.number = 5;
        articles.push(article);
}
</code>```

I have no idea how many objects there will be in my array but they will all have different values for their properties, I just gave some examples here.

Question

I need to find a way to go through all these objects and retrieve the index of the object that has the highest value in article.number. How can I achieve this? I may only use javascript, jQuery, etc.. no other languages.

I'm guessing this will involve using both $.grep and Math.max but I'm stuck, I've never worked with $.grep before.

In short:

```<code>var highestNumber = index of object where article.number is highest
</code>```

答:
```<code>items =>
    items
        .reduce(
            ( highest, item, index ) =>
                item > highest.item
                    ? { item, index }
                    : highest
        ,   { item: Number.NEGATIVE_INFINITY }
        )
        .index
</code>```

Body:
I've got an array with objects:

var articles = [];
var article = {};

Simple loop that iterates x times {
        article.text = "foobar";
        article.color = "red";
        article.number = 5;
        articles.push(article);
}

I have no idea how many objects there will be in my array but they will all have different values for their properties, I just gave some examples here.

Question

I need to find a way to go through all these objects and retrieve the index of the object that has the highest value in article.number. How can I achieve this? I may only use javascript, jQuery, etc.. no other languages.

I'm guessing this will involve using both $.grep and Math.max but I'm stuck, I've never worked with $.grep before.

In short:

var highestNumber = index of object where article.number is highest


问:
C++ sending a packet over socket
I'm trying to communicate with a server program I installed. The server sends and receives all data in the form of constructed packets that follow the setup of:
int int int string nullbyte
like this:

little endian signed int -> The size of the ID (4 bytes) + size of Type (4 bytes) + size of Body (minimum 1 for null terminator) + null byte for a minimum of 10 as the value;

little endian signed int -> id

little endian signed int -> packet type

Null terminiated ascii string -> body

null byte

I've managed to read the packets just fine but when I try to send the packet with the password, the server completely ignores it which means the packet is wrong some how. I construct the packet like this:

```<code>void Packet::build(){

/*
 * Create unsigned char vector to store
 * the data while we build the byte array
 * and create a pointer so the byte array can
 * be modified by the required functions.
 */
std::vector<unsigned char> packet(m_size);
unsigned char *ptr = packet.data();

/*
 * Convert each of the three integers as well
 * as the string into bytes which will be stored
 * back into the memory that ptr points to.
 *
 * Packet data follows format:
 * int32 -> Size of ID + Server Data + body (minimum of 10).
 * int32 -> ID of request. Used to match to response.
 * int32 -> Server Data type. Identifies type of request.
 * String -> Minimum of 1 byte for null terminator.
 * String -> Null terminator.
 */
storeInt32Le(ptr, m_sizeInPacket);
storeInt32Le(ptr, m_requestID);
storeInt32Le(ptr, m_serverData);
storeStringNt(ptr, m_body);

/*
 * Store the vector in member variable m_cmdBytes;
 *
 */
m_cmdBytes = packet;
}
</code>```

storeInt32Le:

```<code>void Packet::storeInt32Le(unsigned char* &buffer, int32_t value) {
/*
 * Copy the integer to a byte array using
 * bitwise AND with mask to ensure the right
 * bits are copied to each segment then
 * increment the pointer by 4 for the next
 * iteration.
 */
buffer[0] = value & 0xFF;
buffer[1] = (value >> 8) & 0xFF;
buffer[2] = (value >> 16) & 0xFF;
buffer[3] = (value >> 24) & 0xFF;
buffer += 4;
}
</code>```

storeStringNt:

```<code>void Packet::storeStringNt(unsigned char* &buffer, const string &s) {
/*
 * Get the size of the string to be copied
 * then do a memcpy of string char array to
 * the buffer.
 */
size_t size = s.size() + 1;
memcpy(buffer, s.c_str(), size);
buffer += size;
</code>```

}

And finally, I send it with:

```<code>bool Connection::sendCmd(Packet packet) {
unsigned char *pBytes = packet.bytes().data();
size_t size = packet.size();

while (size > 0){
    int val = send(m_socket, pBytes, size, 0);

    if (val <= 0) {
        return false;
    }

    pBytes += val;
    size -= val;
}

return true;
}
</code>```

Packet::bytes() just returns m_cmdBytes

答:
As stated in comments, you are:

making assumptions about the byte size and endian of your compiler's int data type.  Since your protocol requires a very specific byte size and endian for its integers, you need to force your code to follow those requirements when preparing the packet.

using memcpy() incorrectly.  You have the source and destination buffers reversed.

are not ensuring that send() is actually sending the full packet correctly.

Try something more like this:

```<code>void store_uint32_le(unsigned char* &buffer, uint32_t value)
{
    buffer[0] = value & 0xFF;
    buffer[1] = (value >> 8)  & 0xFF;
    buffer[2] = (value >> 16) & 0xFF;
    buffer[3] = (value >> 24) & 0xFF;
    buffer += 4;
}

void store_string_nt(unsigned char* &buffer, const std::string &s)
{
    size_t size = s.size() + 1;
    memcpy(buffer, s.c_str(), size);
    buffer += size;
}

...

std::vector<unsigned char> packet(13 + m_body.size());

unsigned char *ptr = packet.data(); // or = &packet[0] prior to C++11
store_uint32_le(ptr, packet.size() - 4);
store_uint32_le(ptr, m_requestID);
store_uint32_le(ptr, m_serverData);
store_string_nt(ptr, m_body);

...

unsigned char *pBytes = packet.data(); // or = &packet[0] prior to C++11
size_t size = packet.size();
while (size > 0)
{
    int val = send(m_socket, pBytes, size, 0);
    if (val < 0)
    {
        // if your socket is non-blocking, enable this...
        /*
        #ifdef _WINDOWS // check your compiler for specific defines...
        if (WSAGetLastError() == WSAEWOULDBLOCK)
        #else
        if ((errno == EAGAIN) || (errno == EWOULDBLOCK) || (errno == EINTR))
        #endif
            continue;
        */

        return false;
    }

    if (val == 0)
        return false;

    pBytes += val;
    size -= val;
}

return true;
</code>```

Title: C++ sending a packet over socket

Body:
I'm trying to communicate with a server program I installed. The server sends and receives all data in the form of constructed packets that follow the setup of:
int int int string nullbyte
like this:

little endian signed int -> The size of the ID (4 bytes) + size of Type (4 bytes) + size of Body (minimum 1 for null terminator) + null byte for a minimum of 10 as the value;

little endian signed int -> id

little endian signed int -> packet type

Null terminiated ascii string -> body

null byte

I've managed to read the packets just fine but when I try to send the packet with the password, the server completely ignores it which means the packet is wrong some how. I construct the packet like this:

void Packet::build(){

/*
 * Create unsigned char vector to store
 * the data while we build the byte array
 * and create a pointer so the byte array can
 * be modified by the required functions.
 */
std::vector<unsigned char> packet(m_size);
unsigned char *ptr = packet.data();

/*
 * Convert each of the three integers as well
 * as the string into bytes which will be stored
 * back into the memory that ptr points to.
 *
 * Packet data follows format:
 * int32 -> Size of ID + Server Data + body (minimum of 10).
 * int32 -> ID of request. Used to match to response.
 * int32 -> Server Data type. Identifies type of request.
 * String -> Minimum of 1 byte for null terminator.
 * String -> Null terminator.
 */
storeInt32Le(ptr, m_sizeInPacket);
storeInt32Le(ptr, m_requestID);
storeInt32Le(ptr, m_serverData);
storeStringNt(ptr, m_body);

/*
 * Store the vector in member variable m_cmdBytes;
 *
 */
m_cmdBytes = packet;
}

storeInt32Le:

void Packet::storeInt32Le(unsigned char* &buffer, int32_t value) {
/*
 * Copy the integer to a byte array using
 * bitwise AND with mask to ensure the right
 * bits are copied to each segment then
 * increment the pointer by 4 for the next
 * iteration.
 */
buffer[0] = value & 0xFF;
buffer[1] = (value >> 8) & 0xFF;
buffer[2] = (value >> 16) & 0xFF;
buffer[3] = (value >> 24) & 0xFF;
buffer += 4;
}

storeStringNt:

void Packet::storeStringNt(unsigned char* &buffer, const string &s) {
/*
 * Get the size of the string to be copied
 * then do a memcpy of string char array to
 * the buffer.
 */
size_t size = s.size() + 1;
memcpy(buffer, s.c_str(), size);
buffer += size;

}

And finally, I send it with:

bool Connection::sendCmd(Packet packet) {
unsigned char *pBytes = packet.bytes().data();
size_t size = packet.size();

while (size > 0){
    int val = send(m_socket, pBytes, size, 0);

    if (val <= 0) {
        return false;
    }

    pBytes += val;
    size -= val;
}

return true;
}

Packet::bytes() just returns m_cmdBytes

Body:
As stated in comments, you are:

making assumptions about the byte size and endian of your compiler's int data type.  Since your protocol requires a very specific byte size and endian for its integers, you need to force your code to follow those requirements when preparing the packet.

using memcpy() incorrectly.  You have the source and destination buffers reversed.

are not ensuring that send() is actually sending the full packet correctly.

Try something more like this:

void store_uint32_le(unsigned char* &buffer, uint32_t value)
{
    buffer[0] = value & 0xFF;
    buffer[1] = (value >> 8)  & 0xFF;
    buffer[2] = (value >> 16) & 0xFF;
    buffer[3] = (value >> 24) & 0xFF;
    buffer += 4;
}

void store_string_nt(unsigned char* &buffer, const std::string &s)
{
    size_t size = s.size() + 1;
    memcpy(buffer, s.c_str(), size);
    buffer += size;
}

...

std::vector<unsigned char> packet(13 + m_body.size());

unsigned char *ptr = packet.data(); // or = &packet[0] prior to C++11
store_uint32_le(ptr, packet.size() - 4);
store_uint32_le(ptr, m_requestID);
store_uint32_le(ptr, m_serverData);
store_string_nt(ptr, m_body);

...

unsigned char *pBytes = packet.data(); // or = &packet[0] prior to C++11
size_t size = packet.size();
while (size > 0)
{
    int val = send(m_socket, pBytes, size, 0);
    if (val < 0)
    {
        // if your socket is non-blocking, enable this...
        /*
        #ifdef _WINDOWS // check your compiler for specific defines...
        if (WSAGetLastError() == WSAEWOULDBLOCK)
        #else
        if ((errno == EAGAIN) || (errno == EWOULDBLOCK) || (errno == EINTR))
        #endif
            continue;
        */

        return false;
    }

    if (val == 0)
        return false;

    pBytes += val;
    size -= val;
}

return true;