问:
Converting Parse PFGeoPoint into an annotation on the map
I am trying to convert a saved PFGeopoint objects in Parse server into an annotation but i can't seem to figure it out and i don't know what's wrong.
I tried to apply the code from this question : Converting Parse GeoPoint into a CLLocation in Swift but i still couldn't figure it out.

Here is my Code :

```<code>import UIKit
import MapKit
import CoreLocation
import Parse

class MapVC: UIViewController, MKMapViewDelegate {

fileprivate let locationManager = CLLocationManager()
fileprivate var startedLoadingPOIs = false
fileprivate var places = [Place]()

var descLocation: PFGeoPoint = PFGeoPoint()
var mapHasCenteredOnce = false

    @IBOutlet weak var mapView: MKMapView!
    override func viewDidLoad() {
        super.viewDidLoad()

        mapView.delegate = self

        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        locationManager.startUpdatingLocation()
        locationManager.requestWhenInUseAuthorization()
        mapView.userTrackingMode = MKUserTrackingMode.followWithHeading

    }

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

        var annotationView: MKAnnotationView?

        if annotation.isKind(of: MKUserLocation.self) {
            annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "User")
            annotationView?.image = UIImage(named: "loc.png")
        }

        return annotationView
    }

}

extension MapVC: CLLocationManagerDelegate {

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        //1
        if locations.count > 0 {
            let location = locations.last!
            print("Accuracy: \(location.horizontalAccuracy)")

            //2
            if location.horizontalAccuracy < 100 {
                //3
                manager.stopUpdatingLocation()
                let span = MKCoordinateSpan(latitudeDelta: 0.014, longitudeDelta: 0.014)
                let region = MKCoordinateRegion(center: location.coordinate, span: span)
                mapView.region = region

                if !startedLoadingPOIs {
                    startedLoadingPOIs = true
                    let loader = PlacesLoader()
                    loader.loadPOIS(location: location, radius: 1000) { placesDict, error in
                        if let dict = placesDict {

                            let query = PFQuery(className: "posts")
                            if let latitude = (PFUser.current()?["location"] as AnyObject).latitude {
                                if let longitude = (PFUser.current()?["location"] as AnyObject).longitude {
                                    let geoPoint = PFGeoPoint(latitude: latitude, longitude: longitude)
                                    query.whereKey("postLocation", nearGeoPoint: geoPoint, withinKilometers: 1)
                                }
                            }
                            query.findObjectsInBackground { (objects: [PFObject]?, error: Error?) in
                                if error == nil {

                                    for object in objects! {
                                        let pfObject = object as PFObject

                                        let caption = pfObject["title"] as! String

                                        self.descLocation = object["postLocation"] as! PFGeoPoint

                                        let latitude: CLLocationDegrees = self.descLocation.latitude
                                        let longitude: CLLocationDegrees = self.descLocation.longitude
                                        let location = CLLocation(latitude: latitude, longitude: longitude)

                                        let place = Place(location: location, name: caption )
                                        self.places.append(place)
                                        let annotation = PlaceAnnotation(location: place.location!.coordinate, title: place.placeName)
                                        DispatchQueue.main.async {
                                        self.mapView.addAnnotation(annotation)
                                        }

                                    }
                                }
                            }

                        }
                    }
                }

}
}
}

}
</code>```

答:
I just had two uanessacry lines that blocked the operation, removed them and it worked for me.

loader.loadPOIS(location: location, radius: 1000) { placesDict, error in
                        if let dict = placesDict {

Body:
I am trying to convert a saved PFGeopoint objects in Parse server into an annotation but i can't seem to figure it out and i don't know what's wrong.
I tried to apply the code from this question : Converting Parse GeoPoint into a CLLocation in Swift but i still couldn't figure it out.

Here is my Code :

import UIKit
import MapKit
import CoreLocation
import Parse

class MapVC: UIViewController, MKMapViewDelegate {

fileprivate let locationManager = CLLocationManager()
fileprivate var startedLoadingPOIs = false
fileprivate var places = [Place]()

var descLocation: PFGeoPoint = PFGeoPoint()
var mapHasCenteredOnce = false

    @IBOutlet weak var mapView: MKMapView!
    override func viewDidLoad() {
        super.viewDidLoad()

        mapView.delegate = self

        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        locationManager.startUpdatingLocation()
        locationManager.requestWhenInUseAuthorization()
        mapView.userTrackingMode = MKUserTrackingMode.followWithHeading

    }

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

        var annotationView: MKAnnotationView?

        if annotation.isKind(of: MKUserLocation.self) {
            annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "User")
            annotationView?.image = UIImage(named: "loc.png")
        }

        return annotationView
    }

}

extension MapVC: CLLocationManagerDelegate {

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        //1
        if locations.count > 0 {
            let location = locations.last!
            print("Accuracy: \(location.horizontalAccuracy)")

            //2
            if location.horizontalAccuracy < 100 {
                //3
                manager.stopUpdatingLocation()
                let span = MKCoordinateSpan(latitudeDelta: 0.014, longitudeDelta: 0.014)
                let region = MKCoordinateRegion(center: location.coordinate, span: span)
                mapView.region = region

                if !startedLoadingPOIs {
                    startedLoadingPOIs = true
                    let loader = PlacesLoader()
                    loader.loadPOIS(location: location, radius: 1000) { placesDict, error in
                        if let dict = placesDict {

                            let query = PFQuery(className: "posts")
                            if let latitude = (PFUser.current()?["location"] as AnyObject).latitude {
                                if let longitude = (PFUser.current()?["location"] as AnyObject).longitude {
                                    let geoPoint = PFGeoPoint(latitude: latitude, longitude: longitude)
                                    query.whereKey("postLocation", nearGeoPoint: geoPoint, withinKilometers: 1)
                                }
                            }
                            query.findObjectsInBackground { (objects: [PFObject]?, error: Error?) in
                                if error == nil {

                                    for object in objects! {
                                        let pfObject = object as PFObject

                                        let caption = pfObject["title"] as! String

                                        self.descLocation = object["postLocation"] as! PFGeoPoint

                                        let latitude: CLLocationDegrees = self.descLocation.latitude
                                        let longitude: CLLocationDegrees = self.descLocation.longitude
                                        let location = CLLocation(latitude: latitude, longitude: longitude)

                                        let place = Place(location: location, name: caption )
                                        self.places.append(place)
                                        let annotation = PlaceAnnotation(location: place.location!.coordinate, title: place.placeName)
                                        DispatchQueue.main.async {
                                        self.mapView.addAnnotation(annotation)
                                        }

                                    }
                                }
                            }

                        }
                    }
                }

}
}
}

}


来源: stackexchange

问:
StaleElementReferenceException on Python Selenium
I am getting the following error while using Selenium in python:

```<code>selenium.common.exceptions.StaleElementReferenceException: Message: u'stale element reference: element is not attached to the page document\n
</code>```

Interestingly enough, the error pops up at different times in the for loop.  Sometimes it gets through eg. 4 iterations and other times eg. 7.

Some of the relevant code being run is:

```<code>for i in range(0, 22):
    u = driver.find_elements_by_id("data")
    text = u[0].get_attribute("innerHTML")
    driver.find_elements_by_class_name("aclassname")[0].click()
</code>```

What does this error mean and what is something I can try to fix this?

答:
It means the element is no longer in the DOM, or it changed.

The following code will help you find the element by controlling and ignoring StaleElementExceptions and handling them just like any other NoSuchElementException. It waits for the element to NOT be stale, just like it waits for the element to be present. It also serves as a good example on how to properly wait for conditions in Selenium.

```<code>from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions

my_element_id = 'something123'
ignored_exceptions=(NoSuchElementException,StaleElementReferenceException,)
your_element = WebDriverWait(your_driver, some_timeout,ignored_exceptions=ignored_exceptions)\
                        .until(expected_conditions.presence_of_element_located((By.ID, my_element_id)))
</code>```

To better understand the problem, imagine you are inside a for loop and think what happens during the iterations:

something changes when you click on the element (last line)

So the page is changing

You enter the next iteration. Now are trying to find a new element (your first line inside the loop).

You found the element

It finishes changing

You try to use it by getting an attribute

Bam! The element is old. You got it in step 4, but it finished changing on step 5

ContentLicense: CC BY-SA 4.0

Body:
I am getting the following error while using Selenium in python:

selenium.common.exceptions.StaleElementReferenceException: Message: u'stale element reference: element is not attached to the page document\n

Interestingly enough, the error pops up at different times in the for loop.  Sometimes it gets through eg. 4 iterations and other times eg. 7.

Some of the relevant code being run is:

for i in range(0, 22):
    u = driver.find_elements_by_id("data")
    text = u[0].get_attribute("innerHTML")
    driver.find_elements_by_class_name("aclassname")[0].click()

What does this error mean and what is something I can try to fix this?

Body:
It means the element is no longer in the DOM, or it changed.

The following code will help you find the element by controlling and ignoring StaleElementExceptions and handling them just like any other NoSuchElementException. It waits for the element to NOT be stale, just like it waits for the element to be present. It also serves as a good example on how to properly wait for conditions in Selenium.

from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions

my_element_id = 'something123'
ignored_exceptions=(NoSuchElementException,StaleElementReferenceException,)
your_element = WebDriverWait(your_driver, some_timeout,ignored_exceptions=ignored_exceptions)\
                        .until(expected_conditions.presence_of_element_located((By.ID, my_element_id)))

To better understand the problem, imagine you are inside a for loop and think what happens during the iterations:

something changes when you click on the element (last line)

So the page is changing

You enter the next iteration. Now are trying to find a new element (your first line inside the loop).

You found the element

It finishes changing

You try to use it by getting an attribute

Bam! The element is old. You got it in step 4, but it finished changing on step 5


问:
Why do we need an Object Relational Mapper?
I bought a book on Hibernate.  I wanted to learn on what Hibernate is and what is Object Relational Mapping in general.

Harnessing Hibernate has good topics on Hibernate and I do think that I am able to write simple mapping classes now. My problem is, I think I am way ahead on the Hibernate but I really don't know why we need one.

The book explains Hibernate clearly but I think I am at lost because it does not discuss why we need Hibernate and an ORM.

答:
Using an ORM like (N)Hibernate just makes sure that you don't have to worry much about writing SQL queries, it helps you focus on the 'domain' (business logic).

However, it is required to have some understanding of the underlying DB (and sql) in order to be able to create performant apps. :)

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
returning the largest odd number from a list none if no odd exist
here's the question, homework what I follow there after,not correct.

def largest_odd_times(L):
        """ Assumes L is a non-empty list of ints
            Returns the largest element of L that occurs an odd number
            of times in L. If no such element exists, returns None """

```<code>    # Your code here
</code>```

For example, if
• largest_odd_times([2,2,4,4]) returns None
• largest_odd_times([3,9,5,3,5,3]) returns 9

```<code>from collections import Counter
        L = [3, 3, 2, 0, 9]
        def largest_odd_times(L):
            """ Assumes L is a non-empty list of ints
                Returns the largest element of L that occurs an odd number
                of times in L. If no such element exists, returns None """
            L.sort(reverse=True)
            counted = Counter(L).items()
            for x in counted:
                if x[1] % 2 == 1:
                    return x[0]
            return None

    Test: largest_odd_times([3, 2])
    my output:2, correct output 3
    Test: largest_odd_times([3, 3, 2, 0])
    myoutput,0 correct output 2
    Test: largest_odd_times([6, 8, 6, 8, 6, 8, 6, 8, 6, 8])
    My output, none, correct output 8
    Test: largest_odd_times([2, 4, 5, 4, 5, 4, 2, 2])
    my output 5, correct 4

    What wrong in this code, explanation of  where I went wrong and what should have done and fixing will be really great.
    Thank you.
</code>```

答:
here's what I did

def largest_odd_times(L):
    '''
    L is list, returns largest element of L that occurs an odd # of times
    '''

```<code>try:
    m = max(L) #finds largest element in list

except ValueError: # if there is none (eg. empty list)
    return None
count = L.count(m)  # how many times does the max element occur

if count%2 == 1 :  # check if its odd
    return m
else:
    L = [x for x in L if x != m]  # if it's not odd, remove all instances
    return largest_odd_times(L)
</code>```

Body:
here's the question, homework what I follow there after,not correct.

def largest_odd_times(L):
        """ Assumes L is a non-empty list of ints
            Returns the largest element of L that occurs an odd number
            of times in L. If no such element exists, returns None """

    # Your code here

For example, if
• largest_odd_times([2,2,4,4]) returns None
• largest_odd_times([3,9,5,3,5,3]) returns 9

from collections import Counter
        L = [3, 3, 2, 0, 9]
        def largest_odd_times(L):
            """ Assumes L is a non-empty list of ints
                Returns the largest element of L that occurs an odd number
                of times in L. If no such element exists, returns None """
            L.sort(reverse=True)
            counted = Counter(L).items()
            for x in counted:
                if x[1] % 2 == 1:
                    return x[0]
            return None

    Test: largest_odd_times([3, 2])
    my output:2, correct output 3
    Test: largest_odd_times([3, 3, 2, 0])
    myoutput,0 correct output 2
    Test: largest_odd_times([6, 8, 6, 8, 6, 8, 6, 8, 6, 8])
    My output, none, correct output 8
    Test: largest_odd_times([2, 4, 5, 4, 5, 4, 2, 2])
    my output 5, correct 4

    What wrong in this code, explanation of  where I went wrong and what should have done and fixing will be really great.
    Thank you.

Body:
here's what I did

def largest_odd_times(L):
    '''
    L is list, returns largest element of L that occurs an odd # of times
    '''

try:
    m = max(L) #finds largest element in list

except ValueError: # if there is none (eg. empty list)
    return None
count = L.count(m)  # how many times does the max element occur

if count%2 == 1 :  # check if its odd
    return m
else:
    L = [x for x in L if x != m]  # if it's not odd, remove all instances
    return largest_odd_times(L)


问:
Split string to maximum length and append the rest to the last array item
Is there a way for me to split a string into an array and limit to x and if there are more parts than the limit append to the last array item?

So, for example I have

```<code>'Billy Bob Joe'.split(' ', 2) // Outputs ["Billy", "Bob"]
</code>```

I would like to output

```<code>["Billy", "Bob Joe"]
</code>```

Is there a way for this to be easily done in JavaScript?

答:
You can create a function that will create a regex string matching the number of words passed as an argument.

  const buildRegexString = function(numWords) {
      let regexStr = '^'
      for (let i = 1; i < numWords; i++) {
          regexStr += '(\\S+)\\s';
      }
      regexStr += '(.*)';

      return regexStr;
}

 const input = 'Billy Bob Joe Ringo George';
 const regex = new RegExp(buildRegexString(3));

 const match = input.match(regex);
 const result = match.slice(1);

 console.log(result);```

Body:
Is there a way for me to split a string into an array and limit to x and if there are more parts than the limit append to the last array item?

So, for example I have

'Billy Bob Joe'.split(' ', 2) // Outputs ["Billy", "Bob"]

I would like to output

["Billy", "Bob Joe"]

Is there a way for this to be easily done in JavaScript?


问:
create new column using a shift within a groupby values
I want to create a new column which is a result of a shift function applied to a grouped values.

```<code>df = pd.DataFrame({'X': [0,1,0,1,0,1,0,1], 'Y':[2,4,3,1,2,3,4,5]})

df

   X  Y
0  0  2
1  1  4
2  0  3
3  1  1
4  0  2
5  1  3
6  0  4
7  1  5

def func(x):
     x['Z'] = test['Y']-test['Y'].shift(1)
     return x

df_new = df.groupby('X').apply(func)

   X  Y    Z
0  0  2  NaN
1  1  4  2.0
2  0  3 -1.0
3  1  1 -2.0
4  0  2  1.0
5  1  3  1.0
6  0  4  1.0
7  1  5  1.0
</code>```

As you can see from the output the values are shifted sequentally without accounting for a group by.

I have seen a similar question, but I could not figure out why it does not work as expected.

Python Pandas: how to add a totally new column to a data frame inside of a groupby/transform operation

答:
The values are shifted without accounting for the groups because your func uses test (presumably some other object, likely another name for what you call df) directly instead of simply the group x.

```<code>def func(x):
    x['Z'] = x['Y']-x['Y'].shift(1)
    return x
</code>```

gives me

```<code>In [8]: df_new
Out[8]:
   X  Y    Z
0  0  2  NaN
1  1  4  NaN
2  0  3  1.0
3  1  1 -3.0
4  0  2 -1.0
5  1  3  2.0
6  0  4  2.0
7  1  5  2.0
</code>```

but note that in this particular case you don't need to write a custom function, you can just call diff on the groupby object directly.  (Of course other functions you might want to work with may be more complicated).

```<code>In [13]: df_new["Z2"] = df.groupby("X")["Y"].diff()

In [14]: df_new
Out[14]:
   X  Y    Z   Z2
0  0  2  NaN  NaN
1  1  4  NaN  NaN
2  0  3  1.0  1.0
3  1  1 -3.0 -3.0
4  0  2 -1.0 -1.0
5  1  3  2.0  2.0
6  0  4  2.0  2.0
7  1  5  2.0  2.0
</code>```

Body:
I want to create a new column which is a result of a shift function applied to a grouped values.

df = pd.DataFrame({'X': [0,1,0,1,0,1,0,1], 'Y':[2,4,3,1,2,3,4,5]})

df

   X  Y
0  0  2
1  1  4
2  0  3
3  1  1
4  0  2
5  1  3
6  0  4
7  1  5

def func(x):
     x['Z'] = test['Y']-test['Y'].shift(1)
     return x

df_new = df.groupby('X').apply(func)

   X  Y    Z
0  0  2  NaN
1  1  4  2.0
2  0  3 -1.0
3  1  1 -2.0
4  0  2  1.0
5  1  3  1.0
6  0  4  1.0
7  1  5  1.0

As you can see from the output the values are shifted sequentally without accounting for a group by.

I have seen a similar question, but I could not figure out why it does not work as expected.

Python Pandas: how to add a totally new column to a data frame inside of a groupby/transform operation

Body:
The values are shifted without accounting for the groups because your func uses test (presumably some other object, likely another name for what you call df) directly instead of simply the group x.

def func(x):
    x['Z'] = x['Y']-x['Y'].shift(1)
    return x

gives me

In [8]: df_new
Out[8]:
   X  Y    Z
0  0  2  NaN
1  1  4  NaN
2  0  3  1.0
3  1  1 -3.0
4  0  2 -1.0
5  1  3  2.0
6  0  4  2.0
7  1  5  2.0

but note that in this particular case you don't need to write a custom function, you can just call diff on the groupby object directly.  (Of course other functions you might want to work with may be more complicated).

In [13]: df_new["Z2"] = df.groupby("X")["Y"].diff()

In [14]: df_new
Out[14]:
   X  Y    Z   Z2
0  0  2  NaN  NaN
1  1  4  NaN  NaN
2  0  3  1.0  1.0
3  1  1 -3.0 -3.0
4  0  2 -1.0 -1.0
5  1  3  2.0  2.0
6  0  4  2.0  2.0
7  1  5  2.0  2.0


问:
Property Editor not registered with the PropertyEditorManager error on Custom Validation Tag (java)
I am using TomCat 5.5 with MyFaces 1.1 and am trying to implement a custom regex validation tag.

My RegExValidator class looks like this:

```<code>public class RegExValidator implements Validator, StateHolder {
  private String regex;
  private boolean transientValue = false;

  public RegExValidator() {
    super();
  }

  public RegExValidator(String regex) {
    this();
    this.regex = regex;
  }

  public void validate(FacesContext context, UIComponent component, Object toValidate) throws ValidatorException {

    if ((context == null) || (component == null)) {
throw new NullPointerException();
    }
    if (!(component instanceof UIInput)) {
        return;
    }
    if (null == regex || null == toValidate) {
        return;
    }

    String val = (String) toValidate;

    if (!val.matches(regex)) {
        FacesMessage errMsg = MessageFactory.createFacesMessage(context, Constants.FORMAT_INVALID_MESSAGE_ID, FacesMessage.SEVERITY_ERROR, (new Object[]{regex}));
        throw new ValidatorException(errMsg);
    }
}

public Object saveState(FacesContext context) {
    Object[] values = new Object[1];
    values[0] = regex;

    return (values);
}

public void restoreState(FacesContext context, Object state) {
    Object[] values = (Object[]) state;
    regex = (String) values[0];
}

public String getRegex() {
    return regex;
}

public void setRegex(String regex) {
    this.regex = regex;
}

public boolean isTransient() {
    return transientValue;
}

public void setTransient(boolean transientValue) {
    this.transientValue = transientValue;
}
}
</code>```

My RegExValidatorTag class looks like this:

```<code>@SuppressWarnings("serial")
public class RegExValidatorTag extends ValidatorELTag {

private static String validatorID = null;
protected ValueExpression regex = null;

public RegExValidatorTag() {
    super();

    if (validatorID == null) {
        validatorID = "RegExValidator";
    }
}

public Validator createValidator() throws JspException {

    FacesContext facesContext = FacesContext.getCurrentInstance();
    RegExValidator result = null;

    if (validatorID != null) {
        result = (RegExValidator) facesContext.getApplication().createValidator(validatorID);
    }

    String patterns = null;

    if (regex != null) {
        if (!regex.isLiteralText()) {
            patterns = (String) regex.getValue(facesContext.getELContext());
        } else {
            patterns = regex.getExpressionString();
        }
    }

    result.setRegex(patterns);

    return result;
}

public void setValidatorID(String validatorID) {
    RegExValidatorTag.validatorID = validatorID;
}

/**
 * @param regex
 *            the regex to set
 */
public void setRegex(ValueExpression regex) {
    this.regex = regex;
}
}
</code>```

My Taglibrary Descriptor looks like this:

<tag>
    <name>regexValidator</name>
    <tag-class>com.company.components.taglib.RegExValidatorTag</tag-class>

    <attribute>
        <name>regex</name>
        <required>true</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
</tag>
```
<p>My face-common-config.xml has a Validator tag like this:</p>
<pre class="lang-xml prettyprint-override"><code><validator>
    <description>
        Validate an input string value against a regular
        expression specified by the "regex" attribute.
    </description>
    <validator-id>RegExValidator</validator-id>
    <validator-class>com.company.components.validators.RegExValidator</validator-class>
    <attribute>
        <description>
            The regular expression to test the value against
        </description>
        <attribute-name>regex</attribute-name>
        <attribute-class>java.lang.String</attribute-class>
    </attribute>
</validator>
</code>```

And later on it is supposed to be used in a jsp file like this:

```<code><tc:in value="${dataBean.currentBean.field}">
  <a:regexValidator regex="${dataBean.currentBean.validationRegEx}" />
</tc:in>
</code>```

When calling the page, the following error comes up:

javax.servlet.ServletException: javax.servlet.jsp.JspException: org.apache.jasper.JasperException: Unable to convert string "[\d{4}]" to class "javax.el.ValueExpression" for attribute "regex": Property Editor not registered with the PropertyEditorManager

Caused by:
org.apache.jasper.JasperException - Unable to convert string "[\d{4}]" to class "javax.el.ValueExpression" for attribute "regex": Property Editor not registered with the PropertyEditorManager

I hope I provided enough details for someone to help me out on this...

答:
I seem to have a similar problem like yours, I'm trying to find the solution but seems that the problem is when using Tomcat or the application server(WebSphere Application Server 7.0) JSF libraries, my problem is that the new application server has new JSF libraries (1.2) instead of the 1.1 libraries that my old application server had. (Version 6.1)

To be more specific. my problem is described here. http://www-01.ibm.com/support/docview.wss?uid=swg21318801

Body:
I am using TomCat 5.5 with MyFaces 1.1 and am trying to implement a custom regex validation tag.

My RegExValidator class looks like this:

public class RegExValidator implements Validator, StateHolder {
  private String regex;
  private boolean transientValue = false;

  public RegExValidator() {
    super();
  }

  public RegExValidator(String regex) {
    this();
    this.regex = regex;
  }

  public void validate(FacesContext context, UIComponent component, Object toValidate) throws ValidatorException {

    if ((context == null) || (component == null)) {
throw new NullPointerException();
    }
    if (!(component instanceof UIInput)) {
        return;
    }
    if (null == regex || null == toValidate) {
        return;
    }

    String val = (String) toValidate;

    if (!val.matches(regex)) {
        FacesMessage errMsg = MessageFactory.createFacesMessage(context, Constants.FORMAT_INVALID_MESSAGE_ID, FacesMessage.SEVERITY_ERROR, (new Object[]{regex}));
        throw new ValidatorException(errMsg);
    }
}

public Object saveState(FacesContext context) {
    Object[] values = new Object[1];
    values[0] = regex;

    return (values);
}

public void restoreState(FacesContext context, Object state) {
    Object[] values = (Object[]) state;
    regex = (String) values[0];
}

public String getRegex() {
    return regex;
}

public void setRegex(String regex) {
    this.regex = regex;
}

public boolean isTransient() {
    return transientValue;
}

public void setTransient(boolean transientValue) {
    this.transientValue = transientValue;
}
}

My RegExValidatorTag class looks like this:

@SuppressWarnings("serial")
public class RegExValidatorTag extends ValidatorELTag {

private static String validatorID = null;
protected ValueExpression regex = null;

public RegExValidatorTag() {
    super();

    if (validatorID == null) {
        validatorID = "RegExValidator";
    }
}

public Validator createValidator() throws JspException {

    FacesContext facesContext = FacesContext.getCurrentInstance();
    RegExValidator result = null;

    if (validatorID != null) {
        result = (RegExValidator) facesContext.getApplication().createValidator(validatorID);
    }

    String patterns = null;

    if (regex != null) {
        if (!regex.isLiteralText()) {
            patterns = (String) regex.getValue(facesContext.getELContext());
        } else {
            patterns = regex.getExpressionString();
        }
    }

    result.setRegex(patterns);

    return result;
}

public void setValidatorID(String validatorID) {
    RegExValidatorTag.validatorID = validatorID;
}

/**
 * @param regex
 *            the regex to set
 */
public void setRegex(ValueExpression regex) {
    this.regex = regex;
}
}

My Taglibrary Descriptor looks like this:

<tag>
    <name>regexValidator</name>
    <tag-class>com.company.components.taglib.RegExValidatorTag</tag-class>

    <attribute>
        <name>regex</name>
        <required>true</required>
        <rtexprvalue>false</rtexprvalue>
    </attribute>
</tag>

My face-common-config.xml has a Validator tag like this:

<validator>
    <description>
        Validate an input string value against a regular
        expression specified by the "regex" attribute.
    </description>
    <validator-id>RegExValidator</validator-id>
    <validator-class>com.company.components.validators.RegExValidator</validator-class>
    <attribute>
        <description>
            The regular expression to test the value against
        </description>
        <attribute-name>regex</attribute-name>
        <attribute-class>java.lang.String</attribute-class>
    </attribute>
</validator>

And later on it is supposed to be used in a jsp file like this:

<tc:in value="${dataBean.currentBean.field}">

</tc:in>

When calling the page, the following error comes up:

javax.servlet.ServletException: javax.servlet.jsp.JspException: org.apache.jasper.JasperException: Unable to convert string "[\d{4}]" to class "javax.el.ValueExpression" for attribute "regex": Property Editor not registered with the PropertyEditorManager

Caused by:
org.apache.jasper.JasperException - Unable to convert string "[\d{4}]" to class "javax.el.ValueExpression" for attribute "regex": Property Editor not registered with the PropertyEditorManager

I hope I provided enough details for someone to help me out on this...


问:
Possible to have two apps respond to the the same base URL using Firebase
I currently have a scenario where I have app A and a sister app called app B. I would like to have app A and app B respond to a Firebase dynamic link and be able to either app A or app B opened depending on which app the user has on their phone.

Is it possible to achieve this in Firebase. So if I have www.mydomain.com/data/myData. If person A has app A on their phone, the when person A presses www.mydomain.com/data/myData, the app A opens. But if person B who has app B installed on their phone press www.mydomain.com/data/myData then app B opens. Is this possible at all on FireBase?

Ultimately what I'm trying to do is have two apps be able to acquire information from say a URL like, www.mydomain.com/data/myData and use myData as needed in each separate app.

Think of it as two apps "sharing" data between each other.

From an iOS perspective, based on this tutorial and this response from branch on SO, clearly this is possible but does Firebase cater for an app being able to respond to two custom URLs.

答:
Disclaimer: I haven't actually tested this all the way through.

This should be possible with Dynamic Links. When you visit the Overview section of the Firebase console, you have the option to add multiple apps to a Firebase single project. Both apps are correctly inserted into the apple-app-site-association file, which means every Dynamic Link in that Firebase project will be a  Universal Link that should correctly triggers either app.

There are a couple caveats to be aware of:

Behavior if both apps are installed on a device is undefined.

For obvious reasons, you have to pick just one of the App Store pages as the app-not-installed fallback location. A workaround for this could be sending the user to a non-store page.


问:
Incorrect ruby version when installing bundle in rails project
I have a problem when running bundle install in the root of sharetribe rails's project. It shows me this error message:

Your Ruby version is 2.4.0, but your Gemfile specified 2.3.1

I tried installing rvm and installing the 2.3.1 version required to run this project but nothing changes and it still throwing this output.

Have anyone faced this problem before ?

答:
What does it say when you run bundle env in the terminal?

Is it the same ruby version?

I tried gem install bundler one time i had the same problem and bundle updated and worked.

You can read more about it here.

Good luck!


问:
Realm Query Notification not firing using Kotlin
I'm not able to get Realm Query Notifications to fire in Android using Kotlin. I've tried the full (1) and lambda (2) syntax for this separately:

```<code>object DataService {

    val realm: Realm = Realm.getDefaultInstance()

    var allDogs: RealmResults<Dog> = realm.where(Dog::class.java).findAll()

    fun start() {

        // (1)
        allDogs.addChangeListener(object: RealmChangeListener<RealmResults<Dog>> {
            override fun onChange(element: RealmResults<Dog>?) {
                print("Ping?")
            }
        })

        // (2)
        allDogs.addChangeListener {
            // This listener doesn't fire when I create managed the Dog object below
            print("Ping?")
        }

        realm.executeTransaction {
            realm.createObject(Dog::class.java)
        }
    }
}
</code>```

I'm wondering if it has to do with this line from the documentation:

Change listeners only work on Looper threads. For non-looper threads,
  you manually have to use Realm.waitForChange() instead.

答: This happens not because you're using kotlin, it does because you're not keeping any reference to the RealmResult objects, if you are creating listeners for them, save the results first as properties or class members and then add the listeners.</p>

Body:
I'm not able to get Realm Query Notifications to fire in Android using Kotlin. I've tried the full (1) and lambda (2) syntax for this separately:

object DataService {

    val realm: Realm = Realm.getDefaultInstance()

    var allDogs: RealmResults<Dog> = realm.where(Dog::class.java).findAll()

    fun start() {

        // (1)
        allDogs.addChangeListener(object: RealmChangeListener<RealmResults<Dog>> {
            override fun onChange(element: RealmResults<Dog>?) {
                print("Ping?")
            }
        })

        // (2)
        allDogs.addChangeListener {
            // This listener doesn't fire when I create managed the Dog object below
            print("Ping?")
        }

        realm.executeTransaction {
            realm.createObject(Dog::class.java)
        }
    }
}

I'm wondering if it has to do with this line from the documentation:

Change listeners only work on Looper threads. For non-looper threads,
  you manually have to use Realm.waitForChange() instead.


问:
Date range question
If I have 2 dates, 21/05/2010 and 23/05/2010, how can I find out if 22/05/2006 7:16 AM exists in between them?

I am using the following code to calculate the min/max date and will then SELECT ALL records in the table that are clear to update them.

```<code>    $today = date('l');

    if($today == 'Wednesday'){
        $min = date('d/m/Y', strtotime('0 days'));
        $max = date('d/m/Y', strtotime('+6 days'));
    }else if($today == 'Thursday'){
        $min = date('d/m/Y', strtotime('-1 days'));
        $max = date('d/m/Y', strtotime('+5 days'));
    }else if($today == 'Friday'){
        $min = date('d/m/Y', strtotime('-2 days'));
        $max = date('d/m/Y', strtotime('+4 days'));
    }else if($today == 'Saturday'){
        $min = date('d/m/Y', strtotime('-3 days'));
        $max = date('d/m/Y', strtotime('+3 days'));
    }else if($today == 'Sunday'){
        $min = date('d/m/Y', strtotime('-4 days'));
        $max = date('d/m/Y', strtotime('+2 days'));
    }else if($today == 'Monday'){
        $min = date('d/m/Y', strtotime('-5 days'));
        $max = date('d/m/Y', strtotime('+1 days'));
    }else if($today == 'Tuesday'){
        $min = date('d/m/Y', strtotime('-6 days'));
        $max = date('d/m/Y', strtotime('0 days'));
    }
</code>```

答:
Explode your dates and use the parts in a mktime() to get their timestamp values. Then it's a simple matter of checking if your timestamp is larger or smaller than the others.

http://php.net/manual/en/function.mktime.php

Pseudocode:

```<code>$parts= explode("/", "21/05/2010");
$timestamp1= mktime($parts[0], $parts[1], ...);

if($timestamp1 < $timestamp2...) {
    print "timestamp1 is older then timestamp2";
}
</code>```

Title: Date range question

Body:
If I have 2 dates, 21/05/2010 and 23/05/2010, how can I find out if 22/05/2006 7:16 AM exists in between them?

I am using the following code to calculate the min/max date and will then SELECT ALL records in the table that are clear to update them.

    $today = date('l');

    if($today == 'Wednesday'){
        $min = date('d/m/Y', strtotime('0 days'));
        $max = date('d/m/Y', strtotime('+6 days'));
    }else if($today == 'Thursday'){
        $min = date('d/m/Y', strtotime('-1 days'));
        $max = date('d/m/Y', strtotime('+5 days'));
    }else if($today == 'Friday'){
        $min = date('d/m/Y', strtotime('-2 days'));
        $max = date('d/m/Y', strtotime('+4 days'));
    }else if($today == 'Saturday'){
        $min = date('d/m/Y', strtotime('-3 days'));
        $max = date('d/m/Y', strtotime('+3 days'));
    }else if($today == 'Sunday'){
        $min = date('d/m/Y', strtotime('-4 days'));
        $max = date('d/m/Y', strtotime('+2 days'));
    }else if($today == 'Monday'){
        $min = date('d/m/Y', strtotime('-5 days'));
        $max = date('d/m/Y', strtotime('+1 days'));
    }else if($today == 'Tuesday'){
        $min = date('d/m/Y', strtotime('-6 days'));
        $max = date('d/m/Y', strtotime('0 days'));
    }

Body:
Explode your dates and use the parts in a mktime() to get their timestamp values. Then it's a simple matter of checking if your timestamp is larger or smaller than the others.

http://php.net/manual/en/function.mktime.php

Pseudocode:

$parts= explode("/", "21/05/2010");
$timestamp1= mktime($parts[0], $parts[1], ...);

if($timestamp1 < $timestamp2...) {
    print "timestamp1 is older then timestamp2";
}


问:
H1 Tag not responsive
I have the H1 tag set but its not responsive. I have the code as follows which I thought should work but obviously not.</p>

```<code><div class="middle">
        <h1>Cheryl Cox Counselling</h1></div>

body {
font-size: 100%;
}

.middle {
display: flex;
width: 55%;
justify-content: center;
}

h1 {
font-family: 'Great Vibes', cursive;
font-size: 7em;
padding-top: .5em;
color: grey;
text-shadow: -1px -1px 0px rgba(255, 255, 255, 0.3), 1px 1px 0px
rgba(0, 0, 0, 0.8);
}
</code>```

答:
The below should be responsive. You were using a very big font-size and hence it was not breaking the word. The code below will break the word but in order to make the font-size responsive, you will have to use media queries at your breakpoints.

https://jsfiddle.net/71dfq220/2/

```<code><div class="middle">
  <h1>Cheryl Cox Counselling</h1>
</div>

body {
font-size: 100%;
}

.middle{
  width:100%;
  position:relative;
}

h1 {
font-family: 'Great Vibes', cursive;
font-size: 5em;
white-space:normal;
word-break: break-all;
color: grey;
text-shadow: -1px -1px 0px rgba(255, 255, 255, 0.3), 1px 1px 0px
rgba(0, 0, 0, 0.8);
text-align:center;
width:100%;
}
</code>```

Title: H1 Tag not responsive

Body:
I have the H1 tag set but its not responsive. I have the code as follows which I thought should work but obviously not.

Cheryl Cox Counselling

body {
font-size: 100%;
}

.middle {
display: flex;
width: 55%;
justify-content: center;
}

h1 {
font-family: 'Great Vibes', cursive;
font-size: 7em;
padding-top: .5em;
color: grey;
text-shadow: -1px -1px 0px rgba(255, 255, 255, 0.3), 1px 1px 0px
rgba(0, 0, 0, 0.8);
}

Body:
The below should be responsive. You were using a very big font-size and hence it was not breaking the word. The code below will break the word but in order to make the font-size responsive, you will have to use media queries at your breakpoints.

https://jsfiddle.net/71dfq220/2/

<div class="middle">
  <h1>Cheryl Cox Counselling</h1>
</div>

body {
font-size: 100%;
}

.middle{
  width:100%;
  position:relative;
}

h1 {
font-family: 'Great Vibes', cursive;
font-size: 5em;
white-space:normal;
word-break: break-all;
color: grey;
text-shadow: -1px -1px 0px rgba(255, 255, 255, 0.3), 1px 1px 0px
rgba(0, 0, 0, 0.8);
text-align:center;
width:100%;
}


问:
Access frame via "relative=up" with Selenium & Ruby
Recently I've used command "selectFrame > relative=up" in Selenium IDE to switch between nested frames. Since i've decided to rewrite all code in Selenium and Ruby, i can't find this command analog for mentioned language.

I can't select frame by name because it different after any reload. Other frame attributes are:

```<code>iframe id="ext-comp-1465" name="ext-comp-1465" frameborder="0" src="/5005700001V96Ub/e?retURL=%2F5005700001V96Ub&isdtp=vw&cancelURL=%2F5005700001V96Ub&nonce=a37ade0829c6d08539a765cd370dff0766cd596851439e853d68a60e9d7c28d0&sfdcIFrameOrigin=https%3A%2F%2F*************.com" class=" x-border-panel" style="left: 0px; top: 0px; width: 329px; height: 641px;"></iframe
</code>```

Please advise how i can get to this frame using "relative=up" option  or other frame attributes. Thanks in advance.

答:
Final solution:</p>

```<code>frames = @driver.find_elements(:xpath, '//iframe[starts-with(@id,ext-comp-)]')
@driver.switch_to.frame frames[1]
</code>```

Body:
Recently I've used command "selectFrame > relative=up" in Selenium IDE to switch between nested frames. Since i've decided to rewrite all code in Selenium and Ruby, i can't find this command analog for mentioned language.

I can't select frame by name because it different after any reload. Other frame attributes are:

iframe id="ext-comp-1465" name="ext-comp-1465" frameborder="0" src="/5005700001V96Ub/e?retURL=%2F5005700001V96Ub&isdtp=vw&cancelURL=%2F5005700001V96Ub&nonce=a37ade0829c6d08539a765cd370dff0766cd596851439e853d68a60e9d7c28d0&sfdcIFrameOrigin=https%3A%2F%2F*************.com" class=" x-border-panel" style="left: 0px; top: 0px; width: 329px; height: 641px;"></iframe

Please advise how i can get to this frame using "relative=up" option  or other frame attributes. Thanks in advance.

Body:
Final solution:

frames = @driver.find_elements(:xpath, '//iframe[starts-with(@id,ext-comp-)]')
@driver.switch_to.frame frames[1]


问:
hiding element with document.getElementsByClassName using onclick method
I know, that there is similar topic, but knowledge from there just do not work for me.

So I want to make first div element 'disappear', when img is clicked.. the problem is, that I have second function on img and something won't work. To be more precise - functions like/displike works good.. so I think, that I do not pass parameter to function hide properly. And I don't have error in my console.

By the way - I used two functions in onclick on purpose, taking element by class name is also made on purpose, cause I have a few elements using same ID's.

Pasted fragment from my code:

```<code><script type="text/javascript">
function hide(clicked){
    var click = document.getElementsByClassName('clicked');
           for(var i = 0; i < click.length; i = i + 1) {
       click[i].style.display="none";
    }
}
</script>

<div class="<?php echo $user['id']; ?>" id="single">
   <div class="buttons"><img  class="single-button-red" id="<?php echo $user['id']; ?>" src="red-button.png" onclick="dislike(this.id);hide(this.id);" /><img class="single-button-green" id="<?php echo $user['id']; ?>" src="green-button.png" onclick="like(this.id);hide(this.id);"/></div>
   <div class="single-content"><?php echo $user['name']. "<br />". $user['age']. " lat"."<br />".distance($row['latitude'], $row['longitude'], $user['latitude'], $user['longitude'])." km"; ?></div>
   <a href="/user.php?id=<?php echo $user['id']; ?>">
      <div class="user-img"></div>
   </a>
</div>
<?php
</code>```

答:
```<code><img onClick='hideFunction(div_id)' source='path/to/img'>

<script type="text/javascript">
function hideFunction(div_id){
    var div = document.getElementsByid(div_id);
    div.style.display="none";
}
</script>
</code>```

Body:
I know, that there is similar topic, but knowledge from there just do not work for me.

So I want to make first div element 'disappear', when img is clicked.. the problem is, that I have second function on img and something won't work. To be more precise - functions like/displike works good.. so I think, that I do not pass parameter to function hide properly. And I don't have error in my console.

By the way - I used two functions in onclick on purpose, taking element by class name is also made on purpose, cause I have a few elements using same ID's.

Pasted fragment from my code:

<div class="<?php echo $user['id']; ?>" id="single">

<img  class="single-button-red" id="<?php echo $user['id']; ?>" src="red-button.png" onclick="dislike(this.id);hide(this.id);" /><img class="single-button-green" id="<?php echo $user['id']; ?>" src="green-button.png" onclick="like(this.id);hide(this.id);"/>

<?php echo $user['name']. "
". $user['age']. " lat"."
".distance($row['latitude'], $row['longitude'], $user['latitude'], $user['longitude'])." km"; ?>

   <a href="/user.php?id=<?php echo $user['id']; ?>">

<?php


问:
Socket Listening / Connecting
I'm making a keylogger that sends each keystroke to the remote server. So far, it only works when I set localhost as the address. Otherwise, the client server connection is simply not working.... I have made sure the port is open on my router. What do I need to make this work?

Server (all the sending and receiving works when the client and server use localhost, it is handled elsewhere obv):

```<code>SOCKET retConnect() {
        SOCKADDR_IN addr;
        int addrlen = sizeof(addr);
        addr.sin_addr.s_addr = htonl(INADDR_ANY);
        addr.sin_port = htons(9901);
        addr.sin_family = AF_INET;
        SOCKET sListen = socket(AF_INET, SOCK_STREAM, NULL);
        bind(sListen, (SOCKADDR*)&addr, sizeof(addr));
        listen(sListen, SOMAXCONN);

        SOCKET newConnection;
        newConnection = accept(sListen, (SOCKADDR*)&addr, &addrlen);
        return newConnection;

    }
</code>```

Client (all the sending and receiving works when the client and server use localhost, it is handled elsewhere obv):

```<code>SOCKET retconnect() {
        SOCKADDR_IN addr;
        int sizeofaddr = sizeof(addr);
        addr.sin_addr.s_addr = inet_addr("72.208.184.42");
        addr.sin_port = htons(9901);
        addr.sin_family = AF_INET;

        SOCKET Connection = socket(AF_INET, SOCK_STREAM, NULL);
        if (connect(Connection, (SOCKADDR*)&addr, sizeofaddr) != 0)
        {
            MessageBoxA(NULL, "Failed to Connect, are you connected to the same port as the server?", "Error", MB_OK | MB_ICONERROR);
            return 0; //Failed to Connect
        }
        else return Connection;

    }
</code>```

edit: the client is not connecting to the remote server.

I'm not entirely familiar with a lot of networking terms, so please explain simply.

答:
Since your server only binds localhost(127.0.0.1).

Change the IP address for listen '127.0.0.1' to '0.0.0.0' or '72.208.184.42' as your client code does.

Title: Socket Listening / Connecting

Body:
I'm making a keylogger that sends each keystroke to the remote server. So far, it only works when I set localhost as the address. Otherwise, the client server connection is simply not working.... I have made sure the port is open on my router. What do I need to make this work?

Server (all the sending and receiving works when the client and server use localhost, it is handled elsewhere obv):

SOCKET retConnect() {
        SOCKADDR_IN addr;
        int addrlen = sizeof(addr);
        addr.sin_addr.s_addr = htonl(INADDR_ANY);
        addr.sin_port = htons(9901);
        addr.sin_family = AF_INET;
        SOCKET sListen = socket(AF_INET, SOCK_STREAM, NULL);
        bind(sListen, (SOCKADDR*)&addr, sizeof(addr));
        listen(sListen, SOMAXCONN);

        SOCKET newConnection;
        newConnection = accept(sListen, (SOCKADDR*)&addr, &addrlen);
        return newConnection;

    }

Client (all the sending and receiving works when the client and server use localhost, it is handled elsewhere obv):

SOCKET retconnect() {
        SOCKADDR_IN addr;
        int sizeofaddr = sizeof(addr);
        addr.sin_addr.s_addr = inet_addr("72.208.184.42");
        addr.sin_port = htons(9901);
        addr.sin_family = AF_INET;

        SOCKET Connection = socket(AF_INET, SOCK_STREAM, NULL);
        if (connect(Connection, (SOCKADDR*)&addr, sizeofaddr) != 0)
        {
            MessageBoxA(NULL, "Failed to Connect, are you connected to the same port as the server?", "Error", MB_OK | MB_ICONERROR);
            return 0; //Failed to Connect
        }
        else return Connection;

    }

edit: the client is not connecting to the remote server.

I'm not entirely familiar with a lot of networking terms, so please explain simply.


问:
Finding closest match in collection of numbers
So I got asked today what was the best way to find the closes match within a collection.

For example, you've got an array like this:

```<code>1, 3, 8, 10, 13, ...
</code>```

What number is closest to 4?

Collection is numerical, unordered and can be anything. Same with the number to match.

Lets see what we can come up with, from the various languages of choice.

答:
11 bytes in J:

```<code>C=:0{]/:|@-
</code>```

Examples:

```<code>>> a =: 1 3 8 10 13
>> 4 C a
3
>> 11 C a
10
>> 12 C a
13
</code>```

my breakdown for the layman:

```<code>0{         First element of
]          the right argument
/:         sorted by
|          absolute value
@          of
-          subtraction
</code>```

OwnerDisplayName: Slace

Body:
So I got asked today what was the best way to find the closes match within a collection.

For example, you've got an array like this:

1, 3, 8, 10, 13, ...

What number is closest to 4?

Collection is numerical, unordered and can be anything. Same with the number to match.

Lets see what we can come up with, from the various languages of choice.

LastEditorDisplayName: Allain Lalonde

Body:
11 bytes in J:

C=:0{]/:|@-

Examples:

>> a =: 1 3 8 10 13
>> 4 C a
3
>> 11 C a
10
>> 12 C a
13

my breakdown for the layman:

0{         First element of
]          the right argument
/:         sorted by
|          absolute value
@          of
-          subtraction

OwnerDisplayName: Jimmy

LastEditorDisplayName: Jimmy


问:
disabling children of a JPanel
Suppose I have a hierarchy like this:

```<code>JPanel panel1;
   JCheckBox cb1;
   JCheckBox cb2;
   JRadioButton rb1;
   JRadioButton rb2;
     ...
</code>```

I have a condition where I want to set individual groups of controls within the panel to be enabled/disabled. That works fine. (e.g. enable cb1 and cb2 when one condition is true, disable them when it is false.)

I would like to disable and re-enable the whole panel. If I call panel1.setEnabled(false) this does not work, it only disables the panel, but does not affect its children.

If I enumerate the panel's children, and call setEnabled(false) on each of them, that would work, but then I would have to store the child enabled state when I re-enable the panel.

Is there a simpler way?

答: JXLayer is a great way to achieve it. It can be used for any Swing component.</p>

Title: disabling children of a JPanel

Body:
Suppose I have a hierarchy like this:

JPanel panel1;
   JCheckBox cb1;
   JCheckBox cb2;
   JRadioButton rb1;
   JRadioButton rb2;
     ...

I have a condition where I want to set individual groups of controls within the panel to be enabled/disabled. That works fine. (e.g. enable cb1 and cb2 when one condition is true, disable them when it is false.)

I would like to disable and re-enable the whole panel. If I call panel1.setEnabled(false) this does not work, it only disables the panel, but does not affect its children.

If I enumerate the panel's children, and call setEnabled(false) on each of them, that would work, but then I would have to store the child enabled state when I re-enable the panel.

Is there a simpler way?


问:
React-Virtualized: Forcing row style repaint instead of styleCache
In a Table, I have rows that have different heights depending on the data. For example:

Everything works fine, until I sort out the columns and the cached row heights outputs an undesirable result.

I discovered it's the top css property which causes the result

It is reset by a cache, which I think is happening here.

But I still can't figure out how to fix this.

答:
The top property is how react-virtualized positions windowed rows. (You might want to step through a couple of these slides for an overview of how the library works.)

You're right that the issue is ultimately a caching one though. If the data for your list/table/grid changes, you'll need to let react-virtualized know that its cached sizes may be invalid. Assuming you have a ref handle on your Table then you can just call recomputeRowHeights like so:

```<code>// Passing 0 (or no index) means to recompute all rows
tableRef.recomputeRowHeights(0);
</code>```

Are you using CellMeasurer to measure your Table rows? If so, you'll want to make sure you're passing an keyMapper that knows how to identify your rows by id rather than index. (This way you won't need to re-measure every row after a sort operation.) For example:

```<code>const keyMapper = (rowIndex, columnIndex) => {
  const data = yourArray[rowIndex]; // Assuming your data is in an Array
  return `${data.id}:${columnIndex}`; // Assuming your data has an 'id' attribute
}
</code>```

It's built with List rather than Table but you can see an example of CellMeasurer being used in this mock Twitter app (source code here).

Body:
The top property is how react-virtualized positions windowed rows. (You might want to step through a couple of these slides for an overview of how the library works.)

You're right that the issue is ultimately a caching one though. If the data for your list/table/grid changes, you'll need to let react-virtualized know that its cached sizes may be invalid. Assuming you have a ref handle on your Table then you can just call recomputeRowHeights like so:

// Passing 0 (or no index) means to recompute all rows
tableRef.recomputeRowHeights(0);

Are you using CellMeasurer to measure your Table rows? If so, you'll want to make sure you're passing an keyMapper that knows how to identify your rows by id rather than index. (This way you won't need to re-measure every row after a sort operation.) For example:

const keyMapper = (rowIndex, columnIndex) => {
  const data = yourArray[rowIndex]; // Assuming your data is in an Array
  return `${data.id}:${columnIndex}`; // Assuming your data has an 'id' attribute
}

It's built with List rather than Table but you can see an example of CellMeasurer being used in this mock Twitter app (source code here).


问:
Threadpool deadlock with Task.Result
We have a large legacy with asp.net system, we have started using some async methods from an infrastructure library that we cannot change.
The system doesn't use tasks in most places but the infrastructure exposes only async methods.

In the code we use the following pattern to use the async methods:

Task.Run(() => Foo()).Result

We use the Task.Run to prevent a deadlock if somewhere in the code someone didn't use ConfigureAwait(false), There are a lot of places that someone could have missed and it has happened before.
And we use Task.Result to integrate it with the existing sync code base.

After experiencing heavy load We've noticed that that we are getting timeouts but the servers are not doing any work(Low CPU), we've found out that when there are a lot of calls to the server and the thread pool reaches the maximal number of threads the threads reach a deadlock in the Task.Result as it blocks the thread until the task is finished but the task can't run as there are no thread pool threads available to run it.

The best solution would be to change the code to work async all the way, but that is not an option right now.
Also removing the Task.Run could work but it's too risky as there is not enough test coverage to know that we will not cause new deadlocks in untested flows.

I've tried to implement a new task scheduler that will not use the thread pool but a different set of threads to run the Foo task, but internal task are being executed on the default task scheduler that I do not want to replace.

Any ideas how this can be resolved without a huge change to the code base?

This is a small sample app that reproduces the issue, using only 10 threads and not the real limit. In the sample Foo will never be called.

```<code>class Program
{
    static void Main(string[] args)
    {
        ThreadPool.SetMaxThreads(10, 10);
        ThreadPool.SetMinThreads(10, 10);

        for (int i = 0; i < 10; i++)
        {
            ThreadPool.QueueUserWorkItem(CallBack);
        }

        Console.ReadKey();
    }

    private static void CallBack(object state)
    {
        Thread.Sleep(1000);

        var result = Task.Run(() => Foo()).Result;
    }

    public static async Task<string> Foo()
    {
        await Task.Delay(100);
        return "";
    }
}
</code>```

答:
You have explained your issue very well.

As you are using Task.Run then blocking on the result, you are using 1-2 threads, when really with async you want to use 0-1 threads.

If you are using Task.Run too liberally through your code then there is a chance you'll have multiple layers of blocking threads, making thread usage get really ugly fast, and you'll hit the maximum capacity as you've described.

As an aside, forget trying to find async deadlocks in unit tests (or console apps) as it requires as non-default SynchronizationContext.

The best and right solution would be to make everything top-to-bottom async or sync, but given you are constrained, I'd suggest investigating this wonderful library from the Microsoft vs team and look at JoinableTaskFactory.Run(...), this will run continuations on the blocking thread, and plays well when you nest this pattern at multiple levels. Using this approach, you will get closer to the synchronous equivalent code.

To reiterate, these techniques are workarounds, and if you are justifying these workarounds by respecting the existing code, the best way to respect it is to do it right, and make it fully sync, or top-to-bottom async.

Title: Threadpool deadlock with Task.Result

Body:
We have a large legacy with asp.net system, we have started using some async methods from an infrastructure library that we cannot change.
The system doesn't use tasks in most places but the infrastructure exposes only async methods.

In the code we use the following pattern to use the async methods:

Task.Run(() => Foo()).Result

We use the Task.Run to prevent a deadlock if somewhere in the code someone didn't use ConfigureAwait(false), There are a lot of places that someone could have missed and it has happened before.
And we use Task.Result to integrate it with the existing sync code base.

After experiencing heavy load We've noticed that that we are getting timeouts but the servers are not doing any work(Low CPU), we've found out that when there are a lot of calls to the server and the thread pool reaches the maximal number of threads the threads reach a deadlock in the Task.Result as it blocks the thread until the task is finished but the task can't run as there are no thread pool threads available to run it.

The best solution would be to change the code to work async all the way, but that is not an option right now.
Also removing the Task.Run could work but it's too risky as there is not enough test coverage to know that we will not cause new deadlocks in untested flows.

I've tried to implement a new task scheduler that will not use the thread pool but a different set of threads to run the Foo task, but internal task are being executed on the default task scheduler that I do not want to replace.

Any ideas how this can be resolved without a huge change to the code base?

This is a small sample app that reproduces the issue, using only 10 threads and not the real limit. In the sample Foo will never be called.

class Program
{
    static void Main(string[] args)
    {
        ThreadPool.SetMaxThreads(10, 10);
        ThreadPool.SetMinThreads(10, 10);

        for (int i = 0; i < 10; i++)
        {
            ThreadPool.QueueUserWorkItem(CallBack);
        }

        Console.ReadKey();
    }

    private static void CallBack(object state)
    {
        Thread.Sleep(1000);

        var result = Task.Run(() => Foo()).Result;
    }

    public static async Task<string> Foo()
    {
        await Task.Delay(100);
        return "";
    }
}


问:
Transposing parts of a data frame to individual columns
I am new to R and struggling with it a bit. I have a data frame like this

```<code>reg     12345
val1    1
val2    0
reg     45678
val1    0
val2    0
val3    1
reg     97654
val1    1
reg     567834
val3    1
reg     567845
val2    0
val4    1
</code>```

My goal is to transform data into this format into

```<code> reg     val1    val2    val3    val4
 12345   1       0       0       0
 45678   0       0       1       0
 97654   1       0       0       0
 567834  0       0       1       0
 567845  0       0       0       1
</code>```

Hoping somebody can guide me here. My data source is less than 200 lines and there are no constraints with regards to the approach. Please assume that the
machine running had adequate memory and processing power.

答:
Even if this is a duplicate, I didn't see the following answer, so...start with the original data:

```<code>df <- data.frame( A = c("reg","val1","val2","reg","val1","val2","val3","reg","val1","reg","val3","reg","val2","val4"),
                  B = c(12345, 1, 0, 45678, 0, 0, 1, 97654, 1, 567834, 1, 567845, 0, 1))
</code>```

I use tidyverse verbs, and a trick to add labels (in dummy) to each "reg" group using cumsum:

```<code>install.packages("tidyverse")
library(tidyverse)
df1 <- df %>%
          mutate(dummy = cumsum(A=="reg")) %>%
          group_by(dummy) %>%
          nest() %>%
          mutate(data = map(data, ~spread(.x, A, B))) %>%
          unnest() %>%
          select(-dummy)
</code>```

This results in:

```<code>     reg  val1  val2  val3  val4
1  12345     1     0    NA    NA
2  45678     0     0     1    NA
3  97654     1    NA    NA    NA
4 567834    NA    NA     1    NA
5 567845    NA     0    NA     1
</code>```

I prefer to keep the NAs, but if you don't:

```<code>df1[is.na(df1)] <- 0

     reg  val1  val2  val3  val4
1  12345     1     0     0     0
2  45678     0     0     1     0
3  97654     1     0     0     0
4 567834     0     0     1     0
5 567845     0     0     0     1
</code>```

Body:
I am new to R and struggling with it a bit. I have a data frame like this

reg     12345
val1    1
val2    0
reg     45678
val1    0
val2    0
val3    1
reg     97654
val1    1
reg     567834
val3    1
reg     567845
val2    0
val4    1

My goal is to transform data into this format into

 reg     val1    val2    val3    val4
 12345   1       0       0       0
 45678   0       0       1       0
 97654   1       0       0       0
 567834  0       0       1       0
 567845  0       0       0       1

Hoping somebody can guide me here. My data source is less than 200 lines and there are no constraints with regards to the approach. Please assume that the
machine running had adequate memory and processing power.

Body:
Even if this is a duplicate, I didn't see the following answer, so...start with the original data:

df <- data.frame( A = c("reg","val1","val2","reg","val1","val2","val3","reg","val1","reg","val3","reg","val2","val4"),
                  B = c(12345, 1, 0, 45678, 0, 0, 1, 97654, 1, 567834, 1, 567845, 0, 1))

I use tidyverse verbs, and a trick to add labels (in dummy) to each "reg" group using cumsum:

install.packages("tidyverse")
library(tidyverse)
df1 <- df %>%
          mutate(dummy = cumsum(A=="reg")) %>%
          group_by(dummy) %>%
          nest() %>%
          mutate(data = map(data, ~spread(.x, A, B))) %>%
          unnest() %>%
          select(-dummy)

This results in:

     reg  val1  val2  val3  val4
1  12345     1     0    NA    NA
2  45678     0     0     1    NA
3  97654     1    NA    NA    NA
4 567834    NA    NA     1    NA
5 567845    NA     0    NA     1

I prefer to keep the NAs, but if you don't:

df1[is.na(df1)] <- 0

     reg  val1  val2  val3  val4
1  12345     1     0     0     0
2  45678     0     0     1     0
3  97654     1     0     0     0
4 567834     0     0     1     0
5 567845     0     0     0     1


问:
In Java, how do I test if an object's monitor is locked using traditional low-level locking mechanisms?
In Java, how do I test if an object's monitor is locked? In other words, given a object obj, does any thread own obj's monitor?

I do not care which thread owns the monitor. All I need to test is if ANY thread owns a given object's monitor. Since a thread other than the current thread could own the monitor, Thread.holdsLock( obj ) is not enough as it only checks the current thread.

I am trying to figure the simplest solution possible.

This is not a duplicate because:

I cannot use higher-level/newer concurrency/locking mechanisms. I cannot use Lock, etc. I must use low-level/old/traditional currency/locking mechanisms such as synchronized, wait(), etc.

I am not trying to find a time to execute code when has monitor has become unlocked. I am trying to execute code when a monitor is locked.
In fact, to give a little bit of background, this part of a unit test where I am trying to start run two threads which both need to lock the same object.

I cannot call internal private JVM dependent methods such as sun.* .

As a result, in order to test for correct handling of concurrency. I need to

Create the two threads.

Start thread 1 .

As soon as thread 1 owns the monitor, suspend thread 1 .

Start thread 2 .

As soon as thread 2 is blocked by thread 1, suspend thread 2 .

Resume thread 1 .

Join thread 1 .

Run some assertions.

Resume thread 2 .

Join thread 2 .

Run some assertions.

What I am trying to figure out is the best way to do #3, primarily, determining when thread 1 owns the monitor.

答:
If you really want to do this using thread suspension, you can have thread 1 set a thread safe flag when it has the monitor and observe the flag  from your test thread.

However, I doubt that's the best way to put together your test.  If you just want to test the business logic in your threads, you can run thread 1, join it, run your first set of assertions, then run thread 2, join it, and run your second set of assertions.  Better yet, you could put the business logic in Runnables and test them in your test thread by invoking the run() method directly.

If there's an issue with thread synchronization that you are trying to get at, my experience is that using time delays is a better way to test those issues than interacting directly with the threads, as interacting directly with the threads may introduce or hide synchronization issues.  For more on that, see my answer on the general question of testing threaded code here:

How should I unit test threaded code?


问:
How to get image files from a directory and order by last modified?
I'm creating an image gallery and would like for my most recent uploaded images to be at the front.

This is what I currently have:

```<code>$files = glob("images/*.*");
for ($i=0; $i<count($files); $i++) {
    $image = $files[$i];
    $supported_file = array('gif','jpg','jpeg','png');

    $ext = strtolower(pathinfo($image, PATHINFO_EXTENSION));
    if (in_array($ext, $supported_file)) {
        echo basename($image)."<br />"; // show only image name if you want to show full path then use this code // echo $image."<br />";
        echo '<img src="'.$image .'" alt="Random image" />'."<br /><br />";
    } else {
        continue;
    }
}
</code>```

But I'm not sure how to make it display in order of last uploaded.

答:
```<code>$files = glob("*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}",GLOB_BRACE);
$sorted_files=array(); /* a new array that have modification time as values
and files as keys the purpose is to sort files according to the values in reverse order */
foreach ($files as $file)
{
    $sorted_files[$file]=filemtime($file);
}
arsort($sorted_files);
foreach ($sorted_files as $image=>$mtime)
{
    echo basename($image)."<br />"; // show only image name if you want to show full path then use this code // echo $image."<br />";
    echo '<img src="'.$image .'" alt="Random image" />'."<br /><br />";
}
</code>```

Body:
I'm creating an image gallery and would like for my most recent uploaded images to be at the front.

This is what I currently have:

$files = glob("images/*.*");
for ($i=0; $i<count($files); $i++) {
    $image = $files[$i];
    $supported_file = array('gif','jpg','jpeg','png');

    $ext = strtolower(pathinfo($image, PATHINFO_EXTENSION));
    if (in_array($ext, $supported_file)) {
        echo basename($image)."
"; // show only image name if you want to show full path then use this code // echo $image."
";
        echo ''."

";
    } else {
        continue;
    }
}

But I'm not sure how to make it display in order of last uploaded.


问:
Getting the current logged in user (FullToken Context)
I have a Problem, which is... i start a programm with right click -> run as administrator.
Which means the programm is running in an administrative context.

```<code>WindowsIdentity.GetCurrent().Name;
</code>```

if i try to get the user name that way i will get the user that started the programm as admin.. for example "administrator", but what i need is the name of the current logged in user which is for example: bob

Can anybody help me out? :)

答:
Maybe you could start as normal user, save user name, then programmatically request elevation :

Windows 7 and Vista UAC - Programmatically requesting elevation in C#

Body:
I have a Problem, which is... i start a programm with right click -> run as administrator.
Which means the programm is running in an administrative context.

WindowsIdentity.GetCurrent().Name;

if i try to get the user name that way i will get the user that started the programm as admin.. for example "administrator", but what i need is the name of the current logged in user which is for example: bob

Can anybody help me out? :)


问:
Android multiple and dynamically images aligned
Right now, I have a RecyclerView and multiple CardView to show my items.

My CardView have a RelativeLayout where I add some ImageViews (in this case 3, but can be more).

Each of my items will have a list of images to show, lets suppose #item1 have Facebook, Twitter and Youtube, but #item2 just have Facebook and Youtube images.

How should I align the images? If I just remove Twitter image, I need to update layout_toLeftOf of my Facebook image to Youtube image.

I think I shouldn't do this kind of logic to all my items, it will be over power...

Example image:
https://i.stack.imgur.com/uJZTi.png

```<code><android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
card_view:cardCornerRadius="4dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/card_height"
        android:orientation="vertical">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_horizontal">

            <ImageView
                android:id="@+id/coverImageView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center"
                android:scaleType="centerCrop"
                />

            <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="end|top">
                <ImageView android:background="@null"
                    android:id="@+id/facebook"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/facebook_icon"
                    android:layout_toLeftOf="@+id/twitter"/>
                <ImageView android:background="@null"
                    android:id="@+id/twitter"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/twitter_icon"
                    android:layout_toLeftOf="@+id/youtube"/>
                <ImageView android:background="@null"
                    android:id="@+id/youtube"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/youtube_icon"
                    android:layout_alignParentRight="true"/>
            </RelativeLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="left|bottom"
                android:background="@android:drawable/screen_background_dark_transparent"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/titleTextView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:padding="16dp"
                    android:textSize="@dimen/text_size"
                    android:textColor="#FFFFFF"
                    android:textStyle="bold" />
            </LinearLayout>
        </FrameLayout>
    </LinearLayout>
</code>```

答:
It's better to work with LinearLayout in this case and use layout_alignParentRight and layout_alignParentTop="true" instead of android:layout_gravity="end|top" like below :</p>

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_alignParentRight="true"
                android:layout_alignParentTop="true">
                <ImageView android:background="@null"
                    android:id="@+id/facebook"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/facebook_icon"
                    android:layout_weight="1"/>
                <ImageView android:background="@null"
                    android:id="@+id/twitter"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/twitter_icon"
                    android:layout_weight="1"/>
                <ImageView android:background="@null"
                    android:id="@+id/youtube"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/youtube_icon"
                    android:layout_weight="1"/>
            </LinearLayout>
</code>```

Body:
Right now, I have a RecyclerView and multiple CardView to show my items.

My CardView have a RelativeLayout where I add some ImageViews (in this case 3, but can be more).

Each of my items will have a list of images to show, lets suppose #item1 have Facebook, Twitter and Youtube, but #item2 just have Facebook and Youtube images.

How should I align the images? If I just remove Twitter image, I need to update layout_toLeftOf of my Facebook image to Youtube image.

I think I shouldn't do this kind of logic to all my items, it will be over power...

Example image:
https://i.stack.imgur.com/uJZTi.png

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
card_view:cardCornerRadius="4dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/card_height"
        android:orientation="vertical">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_horizontal">

            <ImageView
                android:id="@+id/coverImageView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center"
                android:scaleType="centerCrop"
                />

            <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="end|top">
                <ImageView android:background="@null"
                    android:id="@+id/facebook"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/facebook_icon"
                    android:layout_toLeftOf="@+id/twitter"/>
                <ImageView android:background="@null"
                    android:id="@+id/twitter"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/twitter_icon"
                    android:layout_toLeftOf="@+id/youtube"/>
                <ImageView android:background="@null"
                    android:id="@+id/youtube"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/youtube_icon"
                    android:layout_alignParentRight="true"/>
            </RelativeLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="left|bottom"
                android:background="@android:drawable/screen_background_dark_transparent"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/titleTextView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:padding="16dp"
                    android:textSize="@dimen/text_size"
                    android:textColor="#FFFFFF"
                    android:textStyle="bold" />
            </LinearLayout>
        </FrameLayout>
    </LinearLayout>

Body:
It's better to work with LinearLayout in this case and use layout_alignParentRight and layout_alignParentTop="true" instead of android:layout_gravity="end|top" like below :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_alignParentRight="true"
                android:layout_alignParentTop="true">
                <ImageView android:background="@null"
                    android:id="@+id/facebook"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/facebook_icon"
                    android:layout_weight="1"/>
                <ImageView android:background="@null"
                    android:id="@+id/twitter"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/twitter_icon"
                    android:layout_weight="1"/>
                <ImageView android:background="@null"
                    android:id="@+id/youtube"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/youtube_icon"
                    android:layout_weight="1"/>
            </LinearLayout>


问:
What is a None value?
I have been studying Python, and I read a chapter which describes the None value, but unfortunately this book isn't very clear at some points. I thought that I would find the answer to my question, if I share it there.

I want to know what the None value is and what do you use it for?

And also, I don't get this part of the book:

Assigning a value of None to a variable is one way to reset it to
  its original, empty state.

What does that mean?

The answers were great, although I didn't understand most of answers due to my low knowledge of the computer world (I haven't learned about classes, objects, etc.). What does this sentence mean?

Assigning a value of None to a variable is one way to reset it
  to its original, empty state.

Final:

Finally I've got my answer from looking to different answers. I must appreciate all the people who put their times to help me (especially Martijn Pieters and DSM), and I wish that I could choose all answers as the best, but the selection is limited to one. All of the answers were great.

答:
Other answers have already explained meaning of None beautifully. However, I would still like to throw more light on this using an example.

Example:

```<code>def extendList(val, list=[]):
    list.append(val)
    return list

list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')

print "list1 = %s" % list1
print "list2 = %s" % list2
print "list3 = %s" % list3
</code>```

Now try to guess output of above list. Well, the answer is surprisingly as below:

```<code>list1 = [10, 'a']
list2 = [123]
list3 = [10, 'a']
</code>```

But Why?

Many will mistakenly expect list1 to be equal to [10] and list3 to be equal to ['a'], thinking that the list argument will be set to its default value of [] each time extendList is called.

However, what actually happens is that the new default list is created only once when the function is defined, and that same list is then used subsequently whenever extendList is invoked without a list argument being specified. This is because expressions in default arguments are calculated when the function is defined, not when it’s called.

list1 and list3 are therefore operating on the same default list, whereas list2 is operating on a separate list that it created (by passing its own empty list as the value for the list parameter).

'None' the savior: (Modify example above to produce desired behavior)

```<code>def extendList(val, list=None):
    if list is None:
       list = []
    list.append(val)
    return list

list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')

print "list1 = %s" % list1
print "list2 = %s" % list2
print "list3 = %s" % list3
</code>```

With this revised implementation, the output would be:

```<code>list1 = [10]
list2 = [123]
list3 = ['a']
</code>```

Note - Example credit to toptal.com

Title: What is a None value?

Body:
Other answers have already explained meaning of None beautifully. However, I would still like to throw more light on this using an example.

Example:

def extendList(val, list=[]):
    list.append(val)
    return list

list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')

print "list1 = %s" % list1
print "list2 = %s" % list2
print "list3 = %s" % list3

Now try to guess output of above list. Well, the answer is surprisingly as below:

list1 = [10, 'a']
list2 = [123]
list3 = [10, 'a']

But Why?

Many will mistakenly expect list1 to be equal to [10] and list3 to be equal to ['a'], thinking that the list argument will be set to its default value of [] each time extendList is called.

However, what actually happens is that the new default list is created only once when the function is defined, and that same list is then used subsequently whenever extendList is invoked without a list argument being specified. This is because expressions in default arguments are calculated when the function is defined, not when it’s called.

list1 and list3 are therefore operating on the same default list, whereas list2 is operating on a separate list that it created (by passing its own empty list as the value for the list parameter).

'None' the savior: (Modify example above to produce desired behavior)

def extendList(val, list=None):
    if list is None:
       list = []
    list.append(val)
    return list

list1 = extendList(10)
list2 = extendList(123,[])
list3 = extendList('a')

print "list1 = %s" % list1
print "list2 = %s" % list2
print "list3 = %s" % list3

With this revised implementation, the output would be:

list1 = [10]
list2 = [123]
list3 = ['a']

Note - Example credit to toptal.com


问:
Trying to return a JSON result from an API using async await pattern
I am trying to call this API using the async await style but having some issues.

```<code>public async Task<User> GetUser(int userId)
{
    User user = null;
    HttpResponseMessage response = await client.GetAsync("/user/...");
    if(response.IsSuccessStatusCode)
    {
        var result = await response.Content.ReadAsStringAsync();
        user = JsonConvert.DeserializeObject<User>(result);
    }

    return user;
}
</code>```

I am calling the above method in my console app:

```<code>var user = apiClient.GetUser(123);

Console.WriteLine($"user result is {user.Result.UserId}");
</code>```

I get the error:

An unhandled exception of type 'System.NullReferenceException
  Object reference not set to an instance..

Is my code snippet following the best practise is there something wrong?

My endpoint works fine when I test using Postman.

Update

The interface for my GetUser method is:

```<code>Task<User> GetUser(int userId);
</code>```

答:
Best practice to always initialize object.

```<code>User user = new User();  // Ensuring it will return a empty object instead of null.
</code>```

Without seeing the actual full code, it is hard to figure out what is insider GetAsync(...)

Body:
I am trying to call this API using the async await style but having some issues.

public async Task<User> GetUser(int userId)
{
    User user = null;
    HttpResponseMessage response = await client.GetAsync("/user/...");
    if(response.IsSuccessStatusCode)
    {
        var result = await response.Content.ReadAsStringAsync();
        user = JsonConvert.DeserializeObject<User>(result);
    }

    return user;
}

I am calling the above method in my console app:

var user = apiClient.GetUser(123);

Console.WriteLine($"user result is {user.Result.UserId}");

I get the error:

An unhandled exception of type 'System.NullReferenceException
  Object reference not set to an instance..

Is my code snippet following the best practise is there something wrong?

My endpoint works fine when I test using Postman.

Update

The interface for my GetUser method is:

Task<User> GetUser(int userId);

Body:
Best practice to always initialize object.

User user = new User();  // Ensuring it will return a empty object instead of null.

Without seeing the actual full code, it is hard to figure out what is insider GetAsync(...)


问:
Uncaught Error: Cannot use object of type WP_Term as array
I had this issue since I updated my WordPress, in my website I have a custom post which contains some custom categories, something like that:

1) Parent category: Food |
   Child: Fries, Hamburger, Maple Syrup…

2) Parent category: Year |
   Child: 2016, 2015, 2014…

3) Parent category: Country |
   Child: USA, Canada, Spain…

So when I'm writting my custom post, I would chose within those categories and just choose (tickle the box) the category that I need. And it would shown something like that:

Title: New recipe

Content: My text

Terms: Food: Mapple Syrup / Country: Canada / Year: 2014

But now, the terms doesn't show at all, and I get this error message:
 Cannot use object of type WP_Term as array

I used to have the following PHP code which allowed to me to retrieve the child category's parent (and used it as a prefix) and also allowed to me change the order.

```<code>  $term_list = wp_get_post_terms($post->ID, 'project_cat', array("fields" => "all"));
                            $terms_hierarchy = array();
                            foreach ($term_list as $term_single) {
                                $parent = $term_single->parent;
                                if ($parent != 0) {
                                    $terms_hierarchy[$parent][] = get_term($parent)->slug;
                                    $terms_hierarchy[$parent]['children'][$term_single->term_id] = $term_single->name;
                                } else {
                                    $terms_hierarchy[$parent] = $term_single;
                                }
                            }
   //PHP indicated this line:
                            foreach ($terms_hierarchy as $key => $term) {
                                echo "<span>$term[0]: </span>";
                                if (!empty($term['children'])) {
                                    $s_children = '';
                                    foreach ($term['children'] as $key => $child) {
                                        if ($term[0] == 'client') {
                                            $tax_meta = get_term_meta($key);
                                            if(!empty($tax_meta['external_url'][0])){
                                               $s_children .= "<a target='_blank' href='{$tax_meta['external_url'][0]}'>$child</a>, ";
                                            }
                                            else {
                                                $s_children .= $child . ', ';
                                            }
                                        }
                                        else {
                                            $s_children .= $child . ', ';
                                        }
                                    }
                                    echo rtrim($s_children, ', ') . "<br />";
                                }
                            }
</code>```

I'll be really grateful if someone can help to figure out what went wrong?

Thanks for your time

答:
$terms_hierarchy is not an array it is an Std Object. So ...

$term['children']

... would actually be ...

$term->children

Body:
I had this issue since I updated my WordPress, in my website I have a custom post which contains some custom categories, something like that:

1) Parent category: Food |
   Child: Fries, Hamburger, Maple Syrup…

2) Parent category: Year |
   Child: 2016, 2015, 2014…

3) Parent category: Country |
   Child: USA, Canada, Spain…

So when I'm writting my custom post, I would chose within those categories and just choose (tickle the box) the category that I need. And it would shown something like that:

Title: New recipe

Content: My text

Terms: Food: Mapple Syrup / Country: Canada / Year: 2014

But now, the terms doesn't show at all, and I get this error message:
 Cannot use object of type WP_Term as array

I used to have the following PHP code which allowed to me to retrieve the child category's parent (and used it as a prefix) and also allowed to me change the order.

  $term_list = wp_get_post_terms($post->ID, 'project_cat', array("fields" => "all"));
                            $terms_hierarchy = array();
                            foreach ($term_list as $term_single) {
                                $parent = $term_single->parent;
                                if ($parent != 0) {
                                    $terms_hierarchy[$parent][] = get_term($parent)->slug;
                                    $terms_hierarchy[$parent]['children'][$term_single->term_id] = $term_single->name;
                                } else {
                                    $terms_hierarchy[$parent] = $term_single;
                                }
                            }
   //PHP indicated this line:
                            foreach ($terms_hierarchy as $key => $term) {
                                echo "$term[0]: ";
                                if (!empty($term['children'])) {
                                    $s_children = '';
                                    foreach ($term['children'] as $key => $child) {
                                        if ($term[0] == 'client') {
                                            $tax_meta = get_term_meta($key);
                                            if(!empty($tax_meta['external_url'][0])){
                                               $s_children .= "$child, ";
                                            }
                                            else {
                                                $s_children .= $child . ', ';
                                            }
                                        }
                                        else {
                                            $s_children .= $child . ', ';
                                        }
                                    }
                                    echo rtrim($s_children, ', ') . "
";
                                }
                            }

I'll be really grateful if someone can help to figure out what went wrong?

Thanks for your time


问:
Any-type variable assignment
Is it possible to get warn from compiler in way like this:

```<code>let a: any = '123';
let b: number;
let c: string = '123';

b = a; <--- I want warning
b = c; <--- compile error
</code>```

or may be something like tslint can do that?

答:
Is it possible to get warn from compiler in way like this

No. any is a type explicitly existing for the purpose of compatibility with all (i.e. any) types.

Title: Any-type variable assignment

Body:
Is it possible to get warn from compiler in way like this:

let a: any = '123';
let b: number;
let c: string = '123';

b = a; <--- I want warning
b = c; <--- compile error

or may be something like tslint can do that?


问:
How to convert Hex to binary in excel 2013 , then save each bit in different cell
I want to convert Hex number to binary and then each bit of that binary should be saved in different cell. is it possible to do in excel 2013.
for e.g.
hexno. B
binary: 1011,
then 1,0,1,1 should be stored separately in a cell.</p>

答:
Say hexadecimal value is in A1 then to convert to binary, say in B1:

```<code>=HEX2BIN(A1)
</code>```

HEX2BIN.

From there you might use a formula in C1 and copy it across to the right as suitable:

```<code>=MID($B1,COLUMN()-2,1)
</code>```

but assuming you have several numbers to deal with I suggest don't fill your sheet with formulae but apply Text to Columns. Copy formula results in ColumnB and Paste Special...., Values over the top. Select ColumnB, DATA - Data Tools, Text to Columns, Fixed width, parse at every required individual character position, Finish.

Body:
Say hexadecimal value is in A1 then to convert to binary, say in B1:

=HEX2BIN(A1)

HEX2BIN.

From there you might use a formula in C1 and copy it across to the right as suitable:

=MID($B1,COLUMN()-2,1)

but assuming you have several numbers to deal with I suggest don't fill your sheet with formulae but apply Text to Columns. Copy formula results in ColumnB and Paste Special...., Values over the top. Select ColumnB, DATA - Data Tools, Text to Columns, Fixed width, parse at every required individual character position, Finish.