答:
This is because happening because when you are pushing the object into the array, you are in fact pushing reference to the object.

```<code>arr.push(obj);
</code>```

So when you change the any value within the object it changes only in one place, but the contents of your array in fact are referencing the same object. To avoid this you can do this to push the data to your array,

```<code>arr.push(JSON.parse(JSON.stringify(obj)));
</code>```

Title: Modifying the javascript array and pushing it into array is copying to every element in array

Body:
I am not able to understand why it is copying the modified value to every element in the javascript array. Can somebody please explain the concept why?

var obj = {x:12};

var arr =[];

for(var i=0;i<5;i++){
    obj["x"] = i;
    arr.push(obj);
    println("Inside -> " + JSON.stringify(arr));
}
println("Output -> " + JSON.stringify(arr));

Output of the above code returns -

Inside -> [{"x":0}]
Inside -> [{"x":1},{"x":1}]
Inside -> [{"x":2},{"x":2},{"x":2}]
Inside -> [{"x":3},{"x":3},{"x":3},{"x":3}]
Inside -> [{"x":4},{"x":4},{"x":4},{"x":4},{"x":4}]

Output -> [{"x":4},{"x":4},{"x":4},{"x":4},{"x":4}]

Body:
This is because happening because when you are pushing the object into the array, you are in fact pushing reference to the object.

arr.push(obj);

So when you change the any value within the object it changes only in one place, but the contents of your array in fact are referencing the same object. To avoid this you can do this to push the data to your array,

arr.push(JSON.parse(JSON.stringify(obj)));


来源: stackexchange

问:
digital signature
All,

I need to digitally sign a zip file. I am not sure how to do that. What does the digital signature do for me? And just as importantly, how do i verify the digital signature?

答:
Recent versions of APPNOTE (this is where PKWare publishes ZIP format specification) describe digital signature of ZIP archives. The problem is that they don't let one implement signing functionality and reserve it for their own use in their SecureZip software. From legal point of view you are allowed only to perform validation of ZIP archive signatures. </p>

<p>Our SecureBlackbox component library includes ZIP processing components, which include, among many other functions, validation of ZIP archive signatures. We attempted to acquire a license from PKWare to perform signing as well, but they didn't even discuss such option internally, so they were not able to give us a definite answer. </p>

ContentLicense: CC BY-SA 2.5

Title: digital signature

Body:
Recent versions of APPNOTE (this is where PKWare publishes ZIP format specification) describe digital signature of ZIP archives. The problem is that they don't let one implement signing functionality and reserve it for their own use in their SecureZip software. From legal point of view you are allowed only to perform validation of ZIP archive signatures.

Our SecureBlackbox component library includes ZIP processing components, which include, among many other functions, validation of ZIP archive signatures. We attempted to acquire a license from PKWare to perform signing as well, but they didn't even discuss such option internally, so they were not able to give us a definite answer.


问:
How to store selected contacts into an array in IOS 9 using swift
I fetched the contacts details and I want to store them into an array .I have tried but it stores like single contact as one array. but I want to store all of them into one array. how to store them.please guide me.
First it display all the contacts from our phone and I have selected particular contact.That selected contacts should be stored in an array
Thank you</p>

```<code>import UIKit
import ContactsUI

class ViewController: UIViewController ,CNContactPickerDelegate {
    let contactStore = CNContactStore()
    let amount = 200
    //var selectedContact:CNContact = CNContact()
    //var results:[CNContact] = []
    var res:CNContact = CNContact()
    var a = [String]()
    override func viewDidLoad() {
        super.viewDidLoad()
         perform(#selector(contactPicker(_:didSelect:)), with: nil, afterDelay: 0)
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    override func viewDidAppear(_ animated: Bool) {
         super.viewDidAppear(animated)

    }

    @IBAction func contact(_ sender: Any) {
        let cnPicker = CNContactPickerViewController()
        cnPicker.delegate = self
        self.present(cnPicker, animated: true, completion: nil)
        do {
            try contactStore.enumerateContacts(with: CNContactFetchRequest(keysToFetch: [CNContactGivenNameKey as CNKeyDescriptor, CNContactFamilyNameKey as CNKeyDescriptor, CNContactMiddleNameKey as CNKeyDescriptor, CNContactEmailAddressesKey as CNKeyDescriptor,CNContactPhoneNumbersKey as CNKeyDescriptor])) {
                (contact, cursor) -> Void in
                self.res = contact
                ///let data = Data(name: contact.givenName)
                //self.dataArray?.addObject(data)
            }
        }
        catch
        {
            print("Handle the error please")
        }
    }
    func contactPicker(_ picker: CNContactPickerViewController, didSelect contacts: [CNContact]) {
        contacts.forEach { contact in
            //let storyboard = UIStoryboard(name:"Main",bundle:nil)
            a = [contact.givenName]
            print("name of contacts in array \(a)")
            let n = a.flatMap({$0}).count
            print(n)
            let res = amount/n
            print(res)
            for c in a {
                print ("split money \(c):\(res)")
            }
            //print(a.count)
            let displayViewController = self.storyboard?.instantiateViewController(withIdentifier: "DisplayViewControllerr")as! DisplayViewControllerr
              displayViewController.b = a
            let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
            appDelegate.window?.rootViewController = displayViewController
            self.navigationController?.pushViewController(displayViewController, animated: true)
            //self.present(displayViewController,animated:false,completion: nil)

            }
    }

    func contactPickerDidCancel(_ picker: CNContactPickerViewController) {
        print("Cancel Contact Picker")
    }

}
</code>```

答:
```<code>#import <Contacts/Contacts.h>

 CNContactStore *store = [[CNContactStore alloc] init];
        [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted == YES) {
                //keys with fetching properties
                NSArray *keys = @[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey];
                NSString *containerId = store.defaultContainerIdentifier;
                NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
                NSError *error;
                NSArray *cnContacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];
                if (error) {
                    NSLog(@"error fetching contacts %@", error);
                } else {

                    NSLog(@"Contact Array %@",cnContacts.description);
                }
            }
        }];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I fetched the contacts details and I want to store them into an array .I have tried but it stores like single contact as one array. but I want to store all of them into one array. how to store them.please guide me.
First it display all the contacts from our phone and I have selected particular contact.That selected contacts should be stored in an array
Thank you

import UIKit
import ContactsUI

class ViewController: UIViewController ,CNContactPickerDelegate {
    let contactStore = CNContactStore()
    let amount = 200
    //var selectedContact:CNContact = CNContact()
    //var results:[CNContact] = []
    var res:CNContact = CNContact()
    var a = [String]()
    override func viewDidLoad() {
        super.viewDidLoad()
         perform(#selector(contactPicker(_:didSelect:)), with: nil, afterDelay: 0)
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    override func viewDidAppear(_ animated: Bool) {
         super.viewDidAppear(animated)

    }

    @IBAction func contact(_ sender: Any) {
        let cnPicker = CNContactPickerViewController()
        cnPicker.delegate = self
        self.present(cnPicker, animated: true, completion: nil)
        do {
            try contactStore.enumerateContacts(with: CNContactFetchRequest(keysToFetch: [CNContactGivenNameKey as CNKeyDescriptor, CNContactFamilyNameKey as CNKeyDescriptor, CNContactMiddleNameKey as CNKeyDescriptor, CNContactEmailAddressesKey as CNKeyDescriptor,CNContactPhoneNumbersKey as CNKeyDescriptor])) {
                (contact, cursor) -> Void in
                self.res = contact
                ///let data = Data(name: contact.givenName)
                //self.dataArray?.addObject(data)
            }
        }
        catch
        {
            print("Handle the error please")
        }
    }
    func contactPicker(_ picker: CNContactPickerViewController, didSelect contacts: [CNContact]) {
        contacts.forEach { contact in
            //let storyboard = UIStoryboard(name:"Main",bundle:nil)
            a = [contact.givenName]
            print("name of contacts in array \(a)")
            let n = a.flatMap({$0}).count
            print(n)
            let res = amount/n
            print(res)
            for c in a {
                print ("split money \(c):\(res)")
            }
            //print(a.count)
            let displayViewController = self.storyboard?.instantiateViewController(withIdentifier: "DisplayViewControllerr")as! DisplayViewControllerr
              displayViewController.b = a
            let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
            appDelegate.window?.rootViewController = displayViewController
            self.navigationController?.pushViewController(displayViewController, animated: true)
            //self.present(displayViewController,animated:false,completion: nil)

            }
    }

    func contactPickerDidCancel(_ picker: CNContactPickerViewController) {
        print("Cancel Contact Picker")
    }

}


问:
Python slicing - Skips certain number of rows
I currently have 500 rows of data. I want to use the first fifty rows, then skip 50 rows and so on. How do I go on about doing this?</p>

答:
```<code>print([x for i, x in enumerate(range(500)) if divmod(i, 50)[0] % 2 == 0])
</code>```


问:
Learning PHP and Yii Together
I'm not really debating which PHP framework to use as much as I'm trying to understand if it is feasible to expect to learn PHP and Yii simultaneously. I've worked a lot with ASP Classic, VBA/Access, and VB6 so I have programming experience but little to no experience real programming - OOP, PHP, or frameworks.

I often see people recommending that you have several years of experience with PHP and OOP before you learn Yii.

I have a fair-sized web app project coming up which should really be built in PHP/MySQL. I'm just trying to get a better handle on whether I need to hire someone, take private training, or whether I should plan to be in development for 15 years or until bankruptcy, whichever occurs first. :-)

答:
I learned PHP first, then PHP OOP, then a MVC.

I think this is the best route. Because MVC is requires OOP and you should learn OOP first before trying MVC.

Title: Learning PHP and Yii Together


问:
Python | numpy | list indices must be integers, not tuple
My data file looks like this

```<code>#weight, height and gender
45 145 f
89 154 m
56 163 m
-1 165 f
65 175 m
-1 125 m
65 169 f
</code>```

as you can see that for 2 entries i have weight as -1, these are outliers and i want to remove them. that is remove that entry that is outlier.
So i try to read this file using numpy, as in np.loadtxt, so the code for it goes like

```<code>data = np.loadtxt('whData.dat',dtype=np.object,comments='#',delimiter=None)
X = data[:,0:2].astype(np.float)
y = data[:,2]
X = X.T
...
</code>```

in order to remove the outlier i define a function that iterates the data and returns a new data that has no outliers.

```<code>def remove_outlier2(data):
    non_outlier = []
    for x in data:
        if x[0] != '-1':
            non_outlier.append(x)
    return non_outlier
</code>```

and i call this after loading the data from file, that is

```<code>data = np.loadtxt('whData.dat',dtype=np.object,comments='#',delimiter=None)
data = remove_outlier2(data)
np.asarray(data)
X = data[:,0:2].astype(np.float)
y = data[:,2]
X = X.T
...
</code>```

But now i get this error, which i am not able to resolve.

```<code>Traceback (most recent call last):

  File "<ipython-input-2-2aec95447a79>", line 1, in <module>
    runfile('C:/Users/xxx/py_workspace/pattern/whExample.py', wdir='C:/Users/xxx/py_workspace/pattern')

  File "C:\Users\xxx\AppData\Local\Continuum\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 699, in runfile
    execfile(filename, namespace)

  File "C:\Users\xxx\AppData\Local\Continuum\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 74, in execfile
    exec(compile(scripttext, filename, 'exec'), glob, loc)

  File "C:/Users/xxx/py_workspace/pattern/whExample.py", line 79, in <module>
    X = data[:,0:2].astype(np.float)

TypeError: list indices must be integers, not tuple
</code>```

I also tried to print the data just after reading it from file, and it looks like this in Spyder

```<code>[['45' '145' 'f']
    ['89' '154' 'm']
    ['56' '163' 'm']
    ['-1' '165' 'f']
    ['65' '175' 'm']
    ['-1' '125' 'm']
    ['65' '169' 'f']]
</code>```

I tried to google and find out what i am doing wrong but couldn't figure out.
How can i resolve this?

Thanks

答:
So finally from suggestions in the comment section, all i had to do is use the output of np.asarray(), that is

```<code>data = np.loadtxt('whData.dat',dtype=np.object,comments='#',delimiter=None)
# reomve outliers
data = remove_outlier2(data)
data = np.asarray(data)
</code>```

and things worked fine.

Body:
My data file looks like this

#weight, height and gender
45 145 f
89 154 m
56 163 m
-1 165 f
65 175 m
-1 125 m
65 169 f

as you can see that for 2 entries i have weight as -1, these are outliers and i want to remove them. that is remove that entry that is outlier.
So i try to read this file using numpy, as in np.loadtxt, so the code for it goes like

data = np.loadtxt('whData.dat',dtype=np.object,comments='#',delimiter=None)
X = data[:,0:2].astype(np.float)
y = data[:,2]
X = X.T
...

in order to remove the outlier i define a function that iterates the data and returns a new data that has no outliers.

def remove_outlier2(data):
    non_outlier = []
    for x in data:
        if x[0] != '-1':
            non_outlier.append(x)
    return non_outlier

and i call this after loading the data from file, that is

data = np.loadtxt('whData.dat',dtype=np.object,comments='#',delimiter=None)
data = remove_outlier2(data)
np.asarray(data)
X = data[:,0:2].astype(np.float)
y = data[:,2]
X = X.T
...

But now i get this error, which i am not able to resolve.

Traceback (most recent call last):

  File "<ipython-input-2-2aec95447a79>", line 1, in <module>
    runfile('C:/Users/xxx/py_workspace/pattern/whExample.py', wdir='C:/Users/xxx/py_workspace/pattern')

  File "C:\Users\xxx\AppData\Local\Continuum\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 699, in runfile
    execfile(filename, namespace)

  File "C:\Users\xxx\AppData\Local\Continuum\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 74, in execfile
    exec(compile(scripttext, filename, 'exec'), glob, loc)

  File "C:/Users/xxx/py_workspace/pattern/whExample.py", line 79, in <module>
    X = data[:,0:2].astype(np.float)

TypeError: list indices must be integers, not tuple

I also tried to print the data just after reading it from file, and it looks like this in Spyder

[['45' '145' 'f']
    ['89' '154' 'm']
    ['56' '163' 'm']
    ['-1' '165' 'f']
    ['65' '175' 'm']
    ['-1' '125' 'm']
    ['65' '169' 'f']]

I tried to google and find out what i am doing wrong but couldn't figure out.
How can i resolve this?

Thanks

Body:
So finally from suggestions in the comment section, all i had to do is use the output of np.asarray(), that is

data = np.loadtxt('whData.dat',dtype=np.object,comments='#',delimiter=None)
# reomve outliers
data = remove_outlier2(data)
data = np.asarray(data)

and things worked fine.


问:
Sort a list of lists by minimum value
I am trying to sort the lists inside a list by their minimum integer value. This is where I am at so far.

```<code>var SortedList = from lists in List
                 orderby lists.List.Min(Min=>Min.value)
                 ascending
                 select list ;
</code>```

For example:

```<code>var x = new List<int>{ 5, 10, 4, 3, 0 };
var y = new List<int> { 4, -1, -5, 3, 2 };
var z = new List<int> { 3, 1, 0, -2, 2 };

var ListofLists = new List<List<int>> {x, y, z};
</code>```

The output of my Linq shall be, to sort the lists by the minimum value in the list of lists. The sequence for the Lists in my example would be:

y -> z -> x

I have tried a lot of linq expressions and searched through the web. The question seems to be very simple... Thanks for any kind of help!

答:
It's as easy as:

```<code>var sorted = ListofLists.OrderBy(l => l.Min());
</code>```

Or, if you prefer query syntax, you should do:

```<code>var sorted = from list in ListofLists
             orderby list.Min()
             select list;
</code>```

Here it is in action: https://dotnetfiddle.net/bnfGOG

Title: Sort a list of lists by minimum value

Body:
I am trying to sort the lists inside a list by their minimum integer value. This is where I am at so far.

var SortedList = from lists in List
                 orderby lists.List.Min(Min=>Min.value)
                 ascending
                 select list ;

For example:

var x = new List<int>{ 5, 10, 4, 3, 0 };
var y = new List<int> { 4, -1, -5, 3, 2 };
var z = new List<int> { 3, 1, 0, -2, 2 };

var ListofLists = new List<List<int>> {x, y, z};

The output of my Linq shall be, to sort the lists by the minimum value in the list of lists. The sequence for the Lists in my example would be:

y -> z -> x

I have tried a lot of linq expressions and searched through the web. The question seems to be very simple... Thanks for any kind of help!

Body:
It's as easy as:

var sorted = ListofLists.OrderBy(l => l.Min());

Or, if you prefer query syntax, you should do:

var sorted = from list in ListofLists
             orderby list.Min()
             select list;

Here it is in action: https://dotnetfiddle.net/bnfGOG


问:
Reading Javascript FormData value in Asp.net Web api Httpresponsemessage
I have a Web api which is decorated with [HttpPost] which is used to upload all information passed in parameter but getting this error

Error

Controller

```<code>  [HttpPost]
   public HttpResponseMessage questionnairesubmit(HttpRequestMessage form)
    {

     //want to get json of "questionlist" which is send from javascript like
      var QuestionnaireList = JsonConvert.DeserializeObject<List<outRightLogos.Areas.client.WebApiModel.AttributeValueTB>>(form["questionlist"]);

    }
</code>```

Here is javascript sending Json model with name questionlist this I want to fetch in controller.I read FormData() from Here

Javascript

```<code>var data = new FormData();
var QuestionnaireList = [];
 QuestionnaireList.push({

            FieldID: $(this).attr("data-fieldid"),
            attributeID: $(this).attr("data-attributeid"),
            attributeValue: $(this).val(),
            websitesID: 2,
            OrderID: $('#orderid').val(),
            orderbitID: $('#orderbidid').val(),
            serviceId: $(this).attr("data-serviceid"),
            subServiceId: $(this).attr("data-subserviceid"),
            IsSubmit: IsSubmit,
        });

data.append("questionlist", JSON.stringify(QuestionnaireList));
$.ajax({
                    type: "POST",
                    url: path,
                    contentType: 'application/json',//"application/json; charset=utf-8",
                    processData: false,
                    dataType: "json",
                    data: data,

                    success: function (result) {

                        if (result.sucess == "save") {
                            alert('Your form has been saved.');

                        }
                        else if (result.sucess == "Submit") {
                            alert('Your form has been submitted.');
                            window.location.href = result.Url;
                        }
                    },
                    error: function (result) {
                        alert('Oh no ');
                    }

                });
</code>```

Here is a model class AttributeValueTB

Class

```<code> public class AttributeValueTB
{
    public long attributeValueID { get; set; }

    [Required]
    [StringLength(200)]
    public string attributeValueCode { get; set; }

    public int FieldID { get; set; }

    public int attributeID { get; set; }

    public string attributeValue { get; set; }

    public int websitesID { get; set; }

    public long OrderID { get; set; }
    public long orderbitID { get; set; }
    public long serviceId { get; set; }
    public long subServiceId { get; set; }
    public string extra1 { get; set; }
    public string extra2 { get; set; }
    [StringLength(200)]
    public string attributeCode { get; set; }
    public bool isActive { get; set; }

    public bool isShow { get; set; }
    public bool IsSubmit { get; set; }

    [Column(TypeName = "date")]
    public DateTime? createDate { get; set; }

    [Column(TypeName = "date")]
    public DateTime? modifiedDate { get; set; }

    public int? createBy { get; set; }

    public int? modifiedBy { get; set; }

    [Column(TypeName = "timestamp")]
    [MaxLength(8)]
    [Timestamp]
    public byte[] Timestamp { get; set; }
}
</code>```

答:
you need to collect information from 'jsoncontent' not from 'form'

```<code>HttpContent requestContent = Request.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result;
entityclass obj= JsonConvert.DeserializeObject<entityclass>(jsonContent);
</code>```

and if you using class object as parameter also work with your context, need to change the method as put like this.

```<code>[HttpPut]
public HttpResponseMessage Put(int id)
{
  HttpContent requestContent = Request.Content;
  string jsonContent = requestContent.ReadAsStringAsync().Result;
  entityclass obj= JsonConvert.DeserializeObject<entityclass>(jsonContent);
  ...
}
</code>```

Body:
I have a Web api which is decorated with [HttpPost] which is used to upload all information passed in parameter but getting this error

Error

Controller

  [HttpPost]
   public HttpResponseMessage questionnairesubmit(HttpRequestMessage form)
    {

     //want to get json of "questionlist" which is send from javascript like
      var QuestionnaireList = JsonConvert.DeserializeObject<List<outRightLogos.Areas.client.WebApiModel.AttributeValueTB>>(form["questionlist"]);

    }

Here is javascript sending Json model with name questionlist this I want to fetch in controller.I read FormData() from Here

Javascript

var data = new FormData();
var QuestionnaireList = [];
 QuestionnaireList.push({

            FieldID: $(this).attr("data-fieldid"),
            attributeID: $(this).attr("data-attributeid"),
            attributeValue: $(this).val(),
            websitesID: 2,
            OrderID: $('#orderid').val(),
            orderbitID: $('#orderbidid').val(),
            serviceId: $(this).attr("data-serviceid"),
            subServiceId: $(this).attr("data-subserviceid"),
            IsSubmit: IsSubmit,
        });

data.append("questionlist", JSON.stringify(QuestionnaireList));
$.ajax({
                    type: "POST",
                    url: path,
                    contentType: 'application/json',//"application/json; charset=utf-8",
                    processData: false,
                    dataType: "json",
                    data: data,

                    success: function (result) {

                        if (result.sucess == "save") {
                            alert('Your form has been saved.');

                        }
                        else if (result.sucess == "Submit") {
                            alert('Your form has been submitted.');
                            window.location.href = result.Url;
                        }
                    },
                    error: function (result) {
                        alert('Oh no ');
                    }

                });

Here is a model class AttributeValueTB

Class

 public class AttributeValueTB
{
    public long attributeValueID { get; set; }

    [Required]
    [StringLength(200)]
    public string attributeValueCode { get; set; }

    public int FieldID { get; set; }

    public int attributeID { get; set; }

    public string attributeValue { get; set; }

    public int websitesID { get; set; }

    public long OrderID { get; set; }
    public long orderbitID { get; set; }
    public long serviceId { get; set; }
    public long subServiceId { get; set; }
    public string extra1 { get; set; }
    public string extra2 { get; set; }
    [StringLength(200)]
    public string attributeCode { get; set; }
    public bool isActive { get; set; }

    public bool isShow { get; set; }
    public bool IsSubmit { get; set; }

    [Column(TypeName = "date")]
    public DateTime? createDate { get; set; }

    [Column(TypeName = "date")]
    public DateTime? modifiedDate { get; set; }

    public int? createBy { get; set; }

    public int? modifiedBy { get; set; }

    [Column(TypeName = "timestamp")]
    [MaxLength(8)]
    [Timestamp]
    public byte[] Timestamp { get; set; }
}

Body:
you need to collect information from 'jsoncontent' not from 'form'

HttpContent requestContent = Request.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result;
entityclass obj= JsonConvert.DeserializeObject<entityclass>(jsonContent);

and if you using class object as parameter also work with your context, need to change the method as put like this.

[HttpPut]
public HttpResponseMessage Put(int id)
{
  HttpContent requestContent = Request.Content;
  string jsonContent = requestContent.ReadAsStringAsync().Result;
  entityclass obj= JsonConvert.DeserializeObject<entityclass>(jsonContent);
  ...
}


问:
How to sort a list of objects by date when date is String?
I have the following Java POJO, Start date is a string:

POJO Object:

```<code>public class Schedule {

    private String id;

    private String startDate = "";

    //const and getters and setters
}
</code>```

I want to sort a list of these objects by the start date field:

Adding POJOS to list:

```<code>List<Schedule> schedules = new ArrayList<Schedule>();

Schedule s1 = new Schedule();
s1.setStartDate("2018-09-01T15:00:00+0000");

Schedule s2 = new Schedule();
s2.setStartDate("2018-09-15T15:00:00+0000");

schedules.add(s1);
schedules.add(s2);
</code>```

I have tried writing a comparator but it does not seem to work, is there a way of sorting strings by date (earliest first)?

Edit: I am currently using Java 7

答:
I think that you can create a custom comparator with an structure similar to the below:</p>

```<code>Collections.sort(datestring, new Comparator<String>() {
    DateFormat df = new SimpleDateFormat("your format");
    @Override
    public int compare(String s1, String s2) {
       try {
            return df.parse(s1).compareTo(df.parse(s2));
        } catch (ParseException e) {
            throw new IllegalArgumentException(e);
        }
    }
});
</code>```

Body:
I have the following Java POJO, Start date is a string:

POJO Object:

public class Schedule {

    private String id;

    private String startDate = "";

    //const and getters and setters
}

I want to sort a list of these objects by the start date field:

Adding POJOS to list:

List<Schedule> schedules = new ArrayList<Schedule>();

Schedule s1 = new Schedule();
s1.setStartDate("2018-09-01T15:00:00+0000");

Schedule s2 = new Schedule();
s2.setStartDate("2018-09-15T15:00:00+0000");

schedules.add(s1);
schedules.add(s2);

I have tried writing a comparator but it does not seem to work, is there a way of sorting strings by date (earliest first)?

Edit: I am currently using Java 7

Body:
I think that you can create a custom comparator with an structure similar to the below:

Collections.sort(datestring, new Comparator<String>() {
    DateFormat df = new SimpleDateFormat("your format");
    @Override
    public int compare(String s1, String s2) {
       try {
            return df.parse(s1).compareTo(df.parse(s2));
        } catch (ParseException e) {
            throw new IllegalArgumentException(e);
        }
    }
});


问:
Google Authentication error Ruby on Rails
I'm trying to implement Google authentication on my Rails app but I'm having some trouble.

Following https://richonrails.com/articles/google-authentication-in-ruby-on-rails/, I created my initializer with the keys I got from Google's developer console 'omniauth.rb'

```<code>OmniAuth.config.logger = Rails.logger

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :google_oauth2, '*****', '*****', {client_options: {ssl: {ca_file: Rails.root.join("cacert.pem").to_s}}}
end
</code>```

I added some routes

```<code>  # GOOGLE AUTH
  get 'auth/:provider/callback', to: 'sessions#create'
  get 'auth/failure', to: redirect('/')
  get 'signout', to: 'sessions#destroy', as: 'signout'
</code>```

My sessions' create action

```<code>def create
    user = User.from_omniauth(env["omniauth.auth"])
    sign_in user
    flash[:success] = 'Logged in!'
    redirect_to root_path
end
</code>```

And the User.from_omniauth method in user's model

```<code>def self.from_omniauth(auth)
    where(provider: auth.provider, uid: auth.uid).first_or_initialize.tap do |user|
      user.password = user.password_confirmation = user.password_digest =  SecureRandom.urlsafe_base64(n=6)
      user.provider = auth.provider
      user.uid = auth.uid
      user.name = auth.info.name
      user.oauth_token = auth.credentials.token
      user.oauth_expires_at = Time.at(auth.credentials.expires_at)
      user.save!
    end
  end
</code>```

I set a random password because I'm using also bcrypt authentication and it forces that every user has one password

Lastly, in my view I have a button for login

```<code>= link_to "Sign in with Google", "/auth/google_oauth2", id: "sign_in", class: "btn btn-primary"
</code>```

The problem is that it doesn't work, when I click it an error shows on sessions' create user = User.from_omniauth(env["omniauth.auth"]):

```<code>NameError at /auth/google_oauth2/callback
undefined local variable or method `env' for #<SessionsController:0x956eb90>
</code>```

Other times it throws SSL_connect SYSCALL returned=5 errno=0 state=SSLv2/v3 read server hello A (OpenSSL::SSL::SSLError) in another line but I guess that's a different mistake.

答:
There is no env method available.
Instead of this, use

user = User.from_omniauth(request.env["omniauth.auth"])

in your create method as request.env["omniauth.auth"] object has the information sent by google after authentication of user to your application.

Body:
I'm trying to implement Google authentication on my Rails app but I'm having some trouble.

Following https://richonrails.com/articles/google-authentication-in-ruby-on-rails/, I created my initializer with the keys I got from Google's developer console 'omniauth.rb'

OmniAuth.config.logger = Rails.logger

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :google_oauth2, '*****', '*****', {client_options: {ssl: {ca_file: Rails.root.join("cacert.pem").to_s}}}
end

I added some routes

  # GOOGLE AUTH
  get 'auth/:provider/callback', to: 'sessions#create'
  get 'auth/failure', to: redirect('/')
  get 'signout', to: 'sessions#destroy', as: 'signout'

My sessions' create action

def create
    user = User.from_omniauth(env["omniauth.auth"])
    sign_in user
    flash[:success] = 'Logged in!'
    redirect_to root_path
end

And the User.from_omniauth method in user's model

def self.from_omniauth(auth)
    where(provider: auth.provider, uid: auth.uid).first_or_initialize.tap do |user|
      user.password = user.password_confirmation = user.password_digest =  SecureRandom.urlsafe_base64(n=6)
      user.provider = auth.provider
      user.uid = auth.uid
      user.name = auth.info.name
      user.oauth_token = auth.credentials.token
      user.oauth_expires_at = Time.at(auth.credentials.expires_at)
      user.save!
    end
  end

I set a random password because I'm using also bcrypt authentication and it forces that every user has one password

Lastly, in my view I have a button for login

= link_to "Sign in with Google", "/auth/google_oauth2", id: "sign_in", class: "btn btn-primary"

The problem is that it doesn't work, when I click it an error shows on sessions' create user = User.from_omniauth(env["omniauth.auth"]):

NameError at /auth/google_oauth2/callback
undefined local variable or method `env' for #<SessionsController:0x956eb90>

Other times it throws SSL_connect SYSCALL returned=5 errno=0 state=SSLv2/v3 read server hello A (OpenSSL::SSL::SSLError) in another line but I guess that's a different mistake.

ContentLicense: CC BY-SA 4.0


问:
Am I using Javascript call-backs appropriately (object-oriented style)?
I have the following code example to use an object that receives the action from the callback.  Doesn't seem like this is a good design pattern.  Or is it?

When setTimeOut() fires on the function after 1 second, it uses the objInstance global variable (DOM scope) to access the ClassExample object instance.  Can someone recommend a better way to utilize callbacks within an object oriented design?

The whole idea is so I can use the callback to update data within my object instance (increment a variable for example).

```<code>function ClassExample{
    this.initiate = function() {
        setTimeOut(objInstance.afterTimeOut,1000); //using the objects global handle
    }

    this.afterTimeOut = function() {
        alert("Received!");
    }

}

var objInstance = new ClassExample(); //instance
objInstance.initiate();
</code>```

答:
You are right it is not the optimal way of doing what you are aiming for. however i have to wonder why you need to break the callstack as part of the initiation, it seems very academic.

apart from that if i had to do that, i'd probably use a closure like so:

```<code>function ClassExample{
    this.initiate = function() {
        setTimeOut((function(self) { return function() { self.afterTimeout();}})(this),1000); //using the objects global handle
    }

    this.afterTimeOut = function() {
        alert("Received!");
    }

}

var objInstance = new ClassExample(); //instance
objInstance.initiate()
</code>```

Body:
I have the following code example to use an object that receives the action from the callback.  Doesn't seem like this is a good design pattern.  Or is it?

When setTimeOut() fires on the function after 1 second, it uses the objInstance global variable (DOM scope) to access the ClassExample object instance.  Can someone recommend a better way to utilize callbacks within an object oriented design?

The whole idea is so I can use the callback to update data within my object instance (increment a variable for example).

function ClassExample{
    this.initiate = function() {
        setTimeOut(objInstance.afterTimeOut,1000); //using the objects global handle
    }

    this.afterTimeOut = function() {
        alert("Received!");
    }

}

var objInstance = new ClassExample(); //instance
objInstance.initiate();

Body:
You are right it is not the optimal way of doing what you are aiming for. however i have to wonder why you need to break the callstack as part of the initiation, it seems very academic.

apart from that if i had to do that, i'd probably use a closure like so:

function ClassExample{
    this.initiate = function() {
        setTimeOut((function(self) { return function() { self.afterTimeout();}})(this),1000); //using the objects global handle
    }

    this.afterTimeOut = function() {
        alert("Received!");
    }

}

var objInstance = new ClassExample(); //instance
objInstance.initiate()


问:
Split string in a column into three columns in the same table and insert it into new table
Hello I am a beginner here.. here is my question

I have a table "tspade" with two columns that is shown below :

```<code>No  | Unixdatetime                                      |

1   | 1234567890 -1 #SUP: 2                             |

2   | 2345678901 -1 #SUP: 2                             |

3   | 3456789012 -1 #SUP: 3                             |

4   | 4567890123 -1 5678901234 -1 #SUP: 2               |

5   | 6789012345 -1 7890123456 -1 8901234567 -1 #SUP: 2 |
</code>```

I'd like to convert that table into like this :

```<code>No  | Unixdatetime1 | Unixdatetime2 | Unixdatetime3 |

1   | 1234567890    | 0             | 0             |

2   | 2345678901    | 0             | 0             |

3   | 3456789012    | 0             | 0             |

4   | 4567890123    | 5678901234    | 0             |

5   | 6789012345    | 7890123456    | 8901234567    |
</code>```

and save that to table try

I used this query :

```<code>Insert Into try (No,Unixdatetime1,Unixdatetime2,Unixdatetime3)
SELECT `No`, `Unixdatetime`,
    SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', 1 ) AS Unixdatetime1,
    SUBSTRING_INDEX(SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', 2 ),' -1 ',-1) AS Unixdatetime2,
    SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', -1 ) AS Unixdatetime3
FROM tspade
</code>```

but it couldn't work...
Any advice or help?
Thanks in advance

答:
4 column in value and 5 in insert

(and you should not  use alias for select ) in insert select  the number and data type of column in value cluase and in select cluase must match

eg :

```<code>  Insert Into try (No,Unixdatetime1,Unixdatetime2,Unixdatetime3)
  SELECT `No`
      ,  SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', 1 )
      , SUBSTRING_INDEX(SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', 2 ),' -1 ',-1)
      , SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', -1 )
  FROM tspade
</code>```

Body:
Hello I am a beginner here.. here is my question

I have a table "tspade" with two columns that is shown below :

No  | Unixdatetime                                      |

1   | 1234567890 -1 #SUP: 2                             |

2   | 2345678901 -1 #SUP: 2                             |

3   | 3456789012 -1 #SUP: 3                             |

4   | 4567890123 -1 5678901234 -1 #SUP: 2               |

5   | 6789012345 -1 7890123456 -1 8901234567 -1 #SUP: 2 |

I'd like to convert that table into like this :

No  | Unixdatetime1 | Unixdatetime2 | Unixdatetime3 |

1   | 1234567890    | 0             | 0             |

2   | 2345678901    | 0             | 0             |

3   | 3456789012    | 0             | 0             |

4   | 4567890123    | 5678901234    | 0             |

5   | 6789012345    | 7890123456    | 8901234567    |

and save that to table try

I used this query :

Insert Into try (No,Unixdatetime1,Unixdatetime2,Unixdatetime3)
SELECT `No`, `Unixdatetime`,
    SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', 1 ) AS Unixdatetime1,
    SUBSTRING_INDEX(SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', 2 ),' -1 ',-1) AS Unixdatetime2,
    SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', -1 ) AS Unixdatetime3
FROM tspade

but it couldn't work...
Any advice or help?
Thanks in advance

Body:
4 column in value and 5 in insert

(and you should not  use alias for select ) in insert select  the number and data type of column in value cluase and in select cluase must match

eg :

  Insert Into try (No,Unixdatetime1,Unixdatetime2,Unixdatetime3)
  SELECT `No`
      ,  SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', 1 )
      , SUBSTRING_INDEX(SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', 2 ),' -1 ',-1)
      , SUBSTRING_INDEX( `Unixdatetime` , ' -1 ', -1 )
  FROM tspade


问:
Modifying the javascript array and pushing it into array is copying to every element in array
I am not able to understand why it is copying the modified value to every element in the javascript array. Can somebody please explain the concept why?

```<code>var obj = {x:12};

var arr =[];

for(var i=0;i<5;i++){
    obj["x"] = i;
    arr.push(obj);
    println("Inside -> " + JSON.stringify(arr));
}
println("Output -> " + JSON.stringify(arr));
</code>```

Output of the above code returns -

```<code>Inside -> [{"x":0}]
Inside -> [{"x":1},{"x":1}]
Inside -> [{"x":2},{"x":2},{"x":2}]
Inside -> [{"x":3},{"x":3},{"x":3},{"x":3}]
Inside -> [{"x":4},{"x":4},{"x":4},{"x":4},{"x":4}]

Output -> [{"x":4},{"x":4},{"x":4},{"x":4},{"x":4}]
</code>```

答:
Because you're pushing a reference to obj so whenever you make a push using the same object you basically duplicate the instance of it, also when you change 1 instance all of them will change value:

Imagine you have object A what you're doing is ...

```<code>for (var i = 0; i < 5; i++) {
  A = i;
  arr.push(A);
}
</code>```

So you will push a total of 5 equal object instances and when you change 1 all of them will change value, instead you should use an approach like:

```<code>for (var i = 0; i < 5; i++) {
  arr.push({ x: i });
}
</code>```

So every time you will create a new object and the result will be:

[{x:1},{x:2},{x:3},{x:4},{x:5}]

Body:
I am not able to understand why it is copying the modified value to every element in the javascript array. Can somebody please explain the concept why?

var obj = {x:12};

var arr =[];

for(var i=0;i<5;i++){
    obj["x"] = i;
    arr.push(obj);
    println("Inside -> " + JSON.stringify(arr));
}
println("Output -> " + JSON.stringify(arr));

Output of the above code returns -

Inside -> [{"x":0}]
Inside -> [{"x":1},{"x":1}]
Inside -> [{"x":2},{"x":2},{"x":2}]
Inside -> [{"x":3},{"x":3},{"x":3},{"x":3}]
Inside -> [{"x":4},{"x":4},{"x":4},{"x":4},{"x":4}]

Output -> [{"x":4},{"x":4},{"x":4},{"x":4},{"x":4}]

Body:
Because you're pushing a reference to obj so whenever you make a push using the same object you basically duplicate the instance of it, also when you change 1 instance all of them will change value:

Imagine you have object A what you're doing is ...

for (var i = 0; i < 5; i++) {
  A = i;
  arr.push(A);
}

So you will push a total of 5 equal object instances and when you change 1 all of them will change value, instead you should use an approach like:

for (var i = 0; i < 5; i++) {
  arr.push({ x: i });
}

So every time you will create a new object and the result will be:

[{x:1},{x:2},{x:3},{x:4},{x:5}]


问:
Which language uses .pde extension?
While searching for an implementation of the Barnsley's Fern fractal I came across a implementation that has .pde extension. Which programming language uses this extension?

Implementation Page

答:
Software application written with Arduino, an IDE used for prototyping electronics; contains source code written in the Arduino programming language; enables developers to control the electronics on an Arduino circuit board.

To avoid file association conflicts with the Processing software, Arduino changed the Sketch file extension to .INO with the version 1.0 release. Therefore, while Arduino can still open ".pde" files, the ".ino" file extension should be used instead.

Each PDE file is stored in its own folder when saved from the Processing IDE. It is saved with any other program assets, such as images. The project folder and PDE filename prefix have the same name. When the PDE file is run, it is opened in a Java display window, which renders and runs the resulting program.

Processing is commonly used in educational settings for teaching basic programming skills in a visual environment.

Title: Which language uses .pde extension?


问:
pupulating/fill spinner with retrofill2 after callback process
I'm attempting to populating/fill Spinner with retrofit2, but this ever give me error or return object null . (Error message: https://pastebin.com/V4N5S3ih  )
heres my code:

```<code>public String[] dat;
getAkun.getAkunUserKategori("jan","pemasukan", new Akun_Get.dataCallBack() {
        @Override
        public void getData(List<tblAkunDatabase> value) {
            result = value;

            if(result.size() > 0)
            {

                dat = new String[result.size()];
                for(int i = 0;i< result.size();i++)
                {
                    dat[i] = String.valueOf(result.get(i).getKdAkun());

                }

            }
            else
            {
                dat = new String[1];
                dat[0] = "Empty";
                AllData(dat);

            }
        }

    });

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, dat);
    spin.setAdapter(adapter);
</code>```

that's the part of my code, Thank you

UPDATE

```<code>getAkun.getAkunUserKategori("jan","pemasukan", new Akun_Get.dataCallBack() {
        @Override
        public void getData(List<tblAkunDatabase> value) {
            result = value;

            if(result.size() > 0)
            {

                dat = new String[result.size()];
                for(int i = 0;i< result.size();i++)
                {
                    dat[i] = String.valueOf(result.get(i).getKdAkun());

                }

                ArrayAdapter<String> adapter = new ArrayAdapter<String>(Input_Jurnal.this, android.R.layout.simple_list_item_single_choice, dat);
                spin.setAdapter(adapter);

            }
            else
            {
                dat = new String[1];
                dat[0] = "Empty";

                ArrayAdapter<String> adapter = new ArrayAdapter<String>(Input_Jurnal.this, android.R.layout.simple_list_item_single_choice, dat);
                spin.setAdapter(adapter);
            }
        }

    });
</code>```

I try to put arrayadapter in callback process but I got annother error message: https://pastebin.com/ahZ2RnCg

答:
UPDATE
finally, I fount the clue:

```<code>getAkun.getAkunUserKategori("jan","pemasukan", new Akun_Get.dataCallBack() {
        @Override
        public void getData(List<tblAkunDatabase> value) {
            result = value;

            if(result.size() > 0)
            {

                dat = new String[result.size()];
                for(int i = 0;i< result.size();i++)
                {
                    dat[i] = String.valueOf(result.get(i).getKdAkun());
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(Input_Jurnal.this, android.R.layout.simple_dropdown_item_1line, dat);
                    spin.setAdapter(adapter);

                }

            }
            else
            {
                dat = new String[1];
                dat[0] = "Empty";

                ArrayAdapter<String> adapter = new ArrayAdapter<String>(Input_Jurnal.this, android.R.layout.simple_list_item_single_choice, dat);
                spin.setAdapter(adapter);
            }
        }

    });
</code>```

so, I put ArrayAdaptor and Spinner widget into a itteration on callback

Body:
I'm attempting to populating/fill Spinner with retrofit2, but this ever give me error or return object null . (Error message: https://pastebin.com/V4N5S3ih  )
heres my code:

public String[] dat;
getAkun.getAkunUserKategori("jan","pemasukan", new Akun_Get.dataCallBack() {
        @Override
        public void getData(List<tblAkunDatabase> value) {
            result = value;

            if(result.size() > 0)
            {

                dat = new String[result.size()];
                for(int i = 0;i< result.size();i++)
                {
                    dat[i] = String.valueOf(result.get(i).getKdAkun());

                }

            }
            else
            {
                dat = new String[1];
                dat[0] = "Empty";
                AllData(dat);

            }
        }

    });

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, dat);
    spin.setAdapter(adapter);

that's the part of my code, Thank you

UPDATE

getAkun.getAkunUserKategori("jan","pemasukan", new Akun_Get.dataCallBack() {
        @Override
        public void getData(List<tblAkunDatabase> value) {
            result = value;

            if(result.size() > 0)
            {

                dat = new String[result.size()];
                for(int i = 0;i< result.size();i++)
                {
                    dat[i] = String.valueOf(result.get(i).getKdAkun());

                }

                ArrayAdapter<String> adapter = new ArrayAdapter<String>(Input_Jurnal.this, android.R.layout.simple_list_item_single_choice, dat);
                spin.setAdapter(adapter);

            }
            else
            {
                dat = new String[1];
                dat[0] = "Empty";

                ArrayAdapter<String> adapter = new ArrayAdapter<String>(Input_Jurnal.this, android.R.layout.simple_list_item_single_choice, dat);
                spin.setAdapter(adapter);
            }
        }

    });

I try to put arrayadapter in callback process but I got annother error message: https://pastebin.com/ahZ2RnCg

Body:
UPDATE
finally, I fount the clue:

getAkun.getAkunUserKategori("jan","pemasukan", new Akun_Get.dataCallBack() {
        @Override
        public void getData(List<tblAkunDatabase> value) {
            result = value;

            if(result.size() > 0)
            {

                dat = new String[result.size()];
                for(int i = 0;i< result.size();i++)
                {
                    dat[i] = String.valueOf(result.get(i).getKdAkun());
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(Input_Jurnal.this, android.R.layout.simple_dropdown_item_1line, dat);
                    spin.setAdapter(adapter);

                }

            }
            else
            {
                dat = new String[1];
                dat[0] = "Empty";

                ArrayAdapter<String> adapter = new ArrayAdapter<String>(Input_Jurnal.this, android.R.layout.simple_list_item_single_choice, dat);
                spin.setAdapter(adapter);
            }
        }

    });

so, I put ArrayAdaptor and Spinner widget into a itteration on callback


问:
Reading from DatagramSocket in Java EE (EJB 3.0) environment
In my application based on JBoss (version 5) I need to listen for UDP packets.

The easiest way (and probably the only one  ) is to open DatagramSocket on certain port (using JBoss @Service singleton bean) and call receive(...) method. The first part is pretty easy - I've tested it and works as expected. Second part - receiving packets is more complicated.

I am wondering about design of such a code. As it is stated in DatagramSocket javadoc, receive is a blocking operation - it blocks until packet is retrieved. How to code it to make sure that it is fast, scalable and thread-safe?

I thought about writing stateless beans that holds a reference to singleton with opened connection, and these beans are calling receive method - but I am not very sure how JBoss would manage them (one bean calls receive() and until packet arrives it is blocked).
Is there any pattern to use?

答: Open source frameworks like Apache Camel etc are meant to support these kind of use cases. They are well tested and proven to be working in production. My suggestion is to depend on those libraries than creating your own.</p>


问:
How to set Current Month and year in my number picker index?
How to can I set the current month and year in my NumberPicker index ? I have two NumberPicker instances - the first is for the and second is for the year. Both are set as string arrays, but how do I set current position as the current month?

Here is my current code:

```<code>final String wheelMenu2[] = {
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun",
    "Jul",
    "Aug",
    "Sep",
    "Oct",
    "Nov",
    "Dec"
};

NumberPicker numberPicker2 = (NumberPicker) findViewById(R.id.numberpicker2);
numberPicker2.setMinValue(0);
numberPicker2.setMaxValue(wheelMenu2.length-1);
numberPicker2.setWrapSelectorWheel(true);
numberPicker2.setDisplayedValues(wheelMenu2);

int posmonthwheel2 =numberPicker2.getValue();
s4 = wheelMenu2[posmonthwheel2];
</code>```

答:
```<code>    SimpleDateFormat dayFormat = new SimpleDateFormat("MMM", Locale.US);

    Calendar calendar = Calendar.getInstance();
    String month = dayFormat.format(calendar.getTime());
</code>```

month will give have the value of the current month i.e, Jan, Feb, Mar etc. Use this to compare with your array and set it to the view

and for setting in your number formatter use the below method,

numberPicker.setValue(// int position value of the result);

Body:
How to can I set the current month and year in my NumberPicker index ? I have two NumberPicker instances - the first is for the and second is for the year. Both are set as string arrays, but how do I set current position as the current month?

Here is my current code:

final String wheelMenu2[] = {
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun",
    "Jul",
    "Aug",
    "Sep",
    "Oct",
    "Nov",
    "Dec"
};

NumberPicker numberPicker2 = (NumberPicker) findViewById(R.id.numberpicker2);
numberPicker2.setMinValue(0);
numberPicker2.setMaxValue(wheelMenu2.length-1);
numberPicker2.setWrapSelectorWheel(true);
numberPicker2.setDisplayedValues(wheelMenu2);

int posmonthwheel2 =numberPicker2.getValue();
s4 = wheelMenu2[posmonthwheel2];

Body:
    SimpleDateFormat dayFormat = new SimpleDateFormat("MMM", Locale.US);

    Calendar calendar = Calendar.getInstance();
    String month = dayFormat.format(calendar.getTime());

month will give have the value of the current month i.e, Jan, Feb, Mar etc. Use this to compare with your array and set it to the view

and for setting in your number formatter use the below method,

numberPicker.setValue(// int position value of the result);


问:
On mobile phones have to click twice to click button
I have a question. I have some product blocks where a transparent overlay comes over the product block where the buttons to show information or place in cart are shown. I use a small JavaScript function on the href>, but the issue is, when the product block is clicked on mobile phones, the overlay comes up, but you have to click twice to reach the buttons, because somehow it first clicks the href>

this is the product block:

```<code><div class="block shadow1">
  <a href="" class="trigger"></a>
  <div class="overlay"></div>
  <div class="overlay-content smaller">
    <div class="align">
      <div class="vertical">
        <a href="'.$permalink.'" title="'.$title.'">
          <div class="button permalink">
            <div class="align">
              <div class="vertical">
                <img src="'.$imagesrc.'/images/info.svg">
              </div>
            </div>
          </div>
        </a>
        <div class="button transparent add-to-cart">
          <div class="align">
            <div class="vertical">
              <img src="'.$imagesrc.'/images/add-to-cart_1.svg">
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
</code>```

And this is the JavaScript:

```<code>$('a.trigger').on('click', function() {
  $(this).toggle('static');
    return false;
});
</code>```

答:
Please change the javascript like the following. It should be working.</p>

```<code>$("body").on('click touchstart', 'a.trigger', function() {
    $(this).toggle('static');
    return false;
});
</code>```

Body:
I have a question. I have some product blocks where a transparent overlay comes over the product block where the buttons to show information or place in cart are shown. I use a small JavaScript function on the , but the issue is, when the product block is clicked on mobile phones, the overlay comes up, but you have to click twice to reach the buttons, because somehow it first clicks the

this is the product block:

And this is the JavaScript:

$('a.trigger').on('click', function() {
  $(this).toggle('static');
    return false;
});

Body:
Please change the javascript like the following. It should be working.

$("body").on('click touchstart', 'a.trigger', function() {
    $(this).toggle('static');
    return false;
});


问:
After Adding RxJava2, application crashes on SocketTimeout
Previously in my app, I was making two API calls sequentially: isCategoryPromoted and loadCategoryServices.

I added RxJava2 into the project so that the requests could be done in parrallel. The code below summarises the implementation:

```<code>public class ServicesListViewModel{

    public final ObservableBoolean loading = new ObservableBoolean();
    public final ObservableField<String> loadServicesError = new ObservableField<>();

    public void start() {
        loading.set(true);

        final long categoryId = category.getCategoryId();

        final Disposable disposable = Flowable.combineLatest(
                categoriesRepository.isPromotedCategory(categoryId),
                categoriesRepository.loadServices(categoryId),
                (isPromoted, services) -> {

                    //..processing
                }
        ).doOnError(t -> {
            loading.set(false);
            loadServicesError.set(t.getMessage());
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe();
        compositeDisposable.add(disposable);
    }
}
</code>```

,

```<code>public class ServicesListActivity extends BaseActivity{

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //inject viewmodel

        setupView();
        bindView();

        viewModel.start();
    }

    private void bindView() {
        loadingObserver = new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                if (viewModel.loading.get()) {
                    showProgressDialog();
                } else {
                    hideProgressDialog();
                }
                binding.btnNext.setEnabled(!viewModel.loading.get());
            }
        };
        viewModel.loading.addOnPropertyChangedCallback(loadingObserver);

        loadServicesErrorObserver = new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                showErrorDialog(viewModel.loadServicesError.get(), FINISH_ON_CLICK, false);
            }
        };
        viewModel.loadServicesError.addOnPropertyChangedCallback(loadServicesErrorObserver);

    }
}
</code>```

When the request times out, loadServicesError gets set and the code in showErrorDialog executes successfully. However just before the error dialog is displayed, the application crashes. The following trace appears in LogCat:

java.net.SocketTimeoutException: failed to connect to my.api.com/
  (port 443) from /192.168.0.10 (port 49969) after 10000000ms:
  isConnected failed: ETIMEDOUT (Connection timed out)
      at libcore.io.IoBridge.isConnected(IoBridge.java:271)
      at libcore.io.IoBridge.connectErrno(IoBridge.java:188)
      at libcore.io.IoBridge.connect(IoBridge.java:130)
      //..truncated..
      at com.myapp.networking.ApiFactory$2.intercept(ApiFactory.java:166)
      //..truncated.. Caused by: android.system.ErrnoException: isConnected failed: ETIMEDOUT (Connection timed out)
      at libcore.io.IoBridge.isConnected(IoBridge.java:262)     ... 37 more Force finishing activity ServicesListActivity

The stacktrace includes this line: com.myapp.networking.ApiFactory$2.intercept(ApiFactory.java:166)

which is where I intercept the request to include an Authorization token:

```<code>builder.interceptors().add(new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        final Request original = chain.request();

        Request.Builder newBuilder = original.newBuilder()
        newBuilder.addHeader("Authorization",apiDelegate.getAccessToken());

        return chain.proceed(request);//line in stack-tract
    }
});
</code>```

My question is: how do I handle this exception?

It seems to be that the system decides that the Activity needs to be finished because the request timed out.

Before adding RxJava2, the same code worked fine so I'm fairly certain the issue is not outside the code posted above.

I've gone through StackOverflow and it seems nearly all the questions suggest simply increasing the session time-out time. I believe this is a hack and there ought to be a perfectly sensible way of solving this issue.

UPDATE

CategoriesRepository.kt

```<code>override fun isPromotedCategory(categoryId: Long): Flowable<Boolean> = localSource.isPromotedCategory(categoryId)

override fun loadCategoryServices(categoryId: Long): Flowable<CategoryQuestions>
            = remoteSource.loadCategoryServices(categoryId)
</code>```

CategoriesLocalDatsSource.kt

```<code>override fun isPromotedCategory(categoryId: Long): Flowable<Boolean> {
    return Flowable.create<Boolean>({ subscriber ->
        val isPromotedCategory = dbHelper.promotedCategoryDao.idExists(categoryId)

        subscriber.onNext(isPromotedCategory)
        subscriber.onComplete()
    }, BackpressureStrategy.BUFFER)
}
</code>```

CategoriesRemoteDataSource.kt

```<code>override fun loadCategoryServices(categoryId: Long): Flowable<CategoryServices> {
    return Flowable.create<CategoryServices>({
        service().loadCategoryServices(categoryId)
                .enqueue(object : ApiCallback<CategoryServices>() {
                    override fun success(services: CategoryServices?, response: Response<*>?) {
                        it.onNext(services)
                        it.onComplete()
                    }

                    override fun failure(throwable: Throwable?) {
                        it.onError(throwable)
                    }
                })
    }, BackpressureStrategy.BUFFER)
}
</code>```

答:
As @Bob Dalgleish said onError doesn't do what you expect it does.
subscribe() has multiple parameters it can take to reflect results, second parameter is what you consider "onError". Remember that exceptions are stream terminal events, that means stream becomes unusable after an exception unless you add error handling operators such as onErrorReturn()

Body:
Previously in my app, I was making two API calls sequentially: isCategoryPromoted and loadCategoryServices.

I added RxJava2 into the project so that the requests could be done in parrallel. The code below summarises the implementation:

public class ServicesListViewModel{

    public final ObservableBoolean loading = new ObservableBoolean();
    public final ObservableField<String> loadServicesError = new ObservableField<>();

    public void start() {
        loading.set(true);

        final long categoryId = category.getCategoryId();

        final Disposable disposable = Flowable.combineLatest(
                categoriesRepository.isPromotedCategory(categoryId),
                categoriesRepository.loadServices(categoryId),
                (isPromoted, services) -> {

                    //..processing
                }
        ).doOnError(t -> {
            loading.set(false);
            loadServicesError.set(t.getMessage());
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe();
        compositeDisposable.add(disposable);
    }
}

,

public class ServicesListActivity extends BaseActivity{

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //inject viewmodel

        setupView();
        bindView();

        viewModel.start();
    }

    private void bindView() {
        loadingObserver = new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                if (viewModel.loading.get()) {
                    showProgressDialog();
                } else {
                    hideProgressDialog();
                }
                binding.btnNext.setEnabled(!viewModel.loading.get());
            }
        };
        viewModel.loading.addOnPropertyChangedCallback(loadingObserver);

        loadServicesErrorObserver = new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                showErrorDialog(viewModel.loadServicesError.get(), FINISH_ON_CLICK, false);
            }
        };
        viewModel.loadServicesError.addOnPropertyChangedCallback(loadServicesErrorObserver);

    }
}

When the request times out, loadServicesError gets set and the code in showErrorDialog executes successfully. However just before the error dialog is displayed, the application crashes. The following trace appears in LogCat:

java.net.SocketTimeoutException: failed to connect to my.api.com/
  (port 443) from /192.168.0.10 (port 49969) after 10000000ms:
  isConnected failed: ETIMEDOUT (Connection timed out)
      at libcore.io.IoBridge.isConnected(IoBridge.java:271)
      at libcore.io.IoBridge.connectErrno(IoBridge.java:188)
      at libcore.io.IoBridge.connect(IoBridge.java:130)
      //..truncated..
      at com.myapp.networking.ApiFactory$2.intercept(ApiFactory.java:166)
      //..truncated.. Caused by: android.system.ErrnoException: isConnected failed: ETIMEDOUT (Connection timed out)
      at libcore.io.IoBridge.isConnected(IoBridge.java:262)     ... 37 more Force finishing activity ServicesListActivity

The stacktrace includes this line: com.myapp.networking.ApiFactory$2.intercept(ApiFactory.java:166)

which is where I intercept the request to include an Authorization token:

builder.interceptors().add(new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        final Request original = chain.request();

        Request.Builder newBuilder = original.newBuilder()
        newBuilder.addHeader("Authorization",apiDelegate.getAccessToken());

        return chain.proceed(request);//line in stack-tract
    }
});

My question is: how do I handle this exception?

It seems to be that the system decides that the Activity needs to be finished because the request timed out.

Before adding RxJava2, the same code worked fine so I'm fairly certain the issue is not outside the code posted above.

I've gone through StackOverflow and it seems nearly all the questions suggest simply increasing the session time-out time. I believe this is a hack and there ought to be a perfectly sensible way of solving this issue.

UPDATE

CategoriesRepository.kt

override fun isPromotedCategory(categoryId: Long): Flowable<Boolean> = localSource.isPromotedCategory(categoryId)

override fun loadCategoryServices(categoryId: Long): Flowable<CategoryQuestions>
            = remoteSource.loadCategoryServices(categoryId)

CategoriesLocalDatsSource.kt

override fun isPromotedCategory(categoryId: Long): Flowable<Boolean> {
    return Flowable.create<Boolean>({ subscriber ->
        val isPromotedCategory = dbHelper.promotedCategoryDao.idExists(categoryId)

        subscriber.onNext(isPromotedCategory)
        subscriber.onComplete()
    }, BackpressureStrategy.BUFFER)
}

CategoriesRemoteDataSource.kt

override fun loadCategoryServices(categoryId: Long): Flowable<CategoryServices> {
    return Flowable.create<CategoryServices>({
        service().loadCategoryServices(categoryId)
                .enqueue(object : ApiCallback<CategoryServices>() {
                    override fun success(services: CategoryServices?, response: Response<*>?) {
                        it.onNext(services)
                        it.onComplete()
                    }

                    override fun failure(throwable: Throwable?) {
                        it.onError(throwable)
                    }
                })
    }, BackpressureStrategy.BUFFER)
}


问:
Datagridview remove all columns
Is it possible in a single hit to remove all columns from a datagrid?

I know I could loop though and remove them one by one, or remove the whole thing and create it.

But it is possible to simply clear columns and leave the grid in place so users can start fresh.
i.e. put it back to its original state.

OK here is the code I have

```<code>private void PopulateGrid()
    {
        UserVGrid.AutoGenerateColumns = false;
        UserVGrid.Columns.Clear();
        List<string> _values = populate.GetVaribles;
        foreach (var line in _values)
        {
            if (!line.Contains("Startind"))
            {
                string[] newline = line.Split('=');
                DataGridViewColumn newColumn = new DataGridViewTextBoxColumn();
                newColumn.Name = newline[0];
                newColumn.HeaderText = newline[1];
                newColumn.ToolTipText = newline[2];
                UserVGrid.Columns.Add(newColumn);

            }
        }
</code>```

so lets assume _values has apple, pear as values

running this method once and i get a datagrid with two colums named  apple and pear.

running it a second time this time with _values containg char , table.

And i end up with 4 colums apple, pear, chair and table. What I want is the second time it is run it clears the grid fist and then applied the new colums.

Cheers

Aaron

答:
for removing a columns of dataGridView you can do like that  "P_Comment"  is Columns Name

```<code>        dataGridView1.Columns.Remove("p_Comment");
</code>```

and for remove all columns you can use

```<code>dataGridView1.Columns.Clear();
</code>```

Title: Datagridview remove all columns

Body:
Is it possible in a single hit to remove all columns from a datagrid?

I know I could loop though and remove them one by one, or remove the whole thing and create it.

But it is possible to simply clear columns and leave the grid in place so users can start fresh.
i.e. put it back to its original state.

OK here is the code I have

private void PopulateGrid()
    {
        UserVGrid.AutoGenerateColumns = false;
        UserVGrid.Columns.Clear();
        List<string> _values = populate.GetVaribles;
        foreach (var line in _values)
        {
            if (!line.Contains("Startind"))
            {
                string[] newline = line.Split('=');
                DataGridViewColumn newColumn = new DataGridViewTextBoxColumn();
                newColumn.Name = newline[0];
                newColumn.HeaderText = newline[1];
                newColumn.ToolTipText = newline[2];
                UserVGrid.Columns.Add(newColumn);

            }
        }

so lets assume _values has apple, pear as values

running this method once and i get a datagrid with two colums named  apple and pear.

running it a second time this time with _values containg char , table.

And i end up with 4 colums apple, pear, chair and table. What I want is the second time it is run it clears the grid fist and then applied the new colums.

Cheers

Aaron

Body:
for removing a columns of dataGridView you can do like that  "P_Comment"  is Columns Name

        dataGridView1.Columns.Remove("p_Comment");

and for remove all columns you can use

dataGridView1.Columns.Clear();


问:
Single Spring repository to produce different objects or entities
I have repository in my spring project:

```<code>@Repository
public interface UserRepository extends JpaRepository<User, Long> {

    boolean existsById(long id);

    List<User> findAllByEmail(String email);

}
</code>```

It works fine but appeared necessary to use LightUser

```<code>public class LightUser implements Identifiable<Long>, Auditable {

    @Id
    @Column
    private Long id;

    @Enumerated(EnumType.STRING)
    @Column(nullable = false, updatable = false)
    private UserType userType;

    @Column(nullable = false, unique = true)
    private String email;

    @Column(nullable = false)
    private String domain;

    // get/set methods/ equals/hashcode
}
</code>```

LightUser entity contains a few fields I need in general (all fields precent in User entity), and I want do request to DB using repository mapping results into LightUser (it would be really good to map into dto).

Is it possible add special method into UserRepository to cover my needs or i should create similar one for same table but for LightUser? If it possible, provide example please or core idea.

答:
First of all, you have to remove @Repository annotation from your interface since it's redundant.

And yes, you can select into LightUser using two ways:

1) Projection

You have to create projection with needed properties:

```<code>interface LightUser {
    Long getId();
    String getEmail();
}
</code>```

And add appropriate select method:

```<code>@Query("SELECT u.id AS id, u.email AS email FROM User u WHERE u.id = :id")
LightUser findLightUser(@Param("id") String id)
</code>```

The disadvantage of this way is that your projection should be an interface (but if you use this for REST, it's OK)

2) DTO

Your DTO should have a constructor with needed fields, for instance, id and email:

```<code>class LightUser {
    private Long id;
    private String email;

    public LightUser(Long id, String email) {
        this.id = id;
        this.email = email;
    }

    // getters and setters
}
</code>```

and then you can write a select for this DTO:

```<code>@Query("SELECT new com.test.LightUser(u.id, u.email) FROM User u WHERE u.id = :id")
LightUser findLightUser(@Param("id") String id)
</code>```

Since your LightUser is like DTO, you have to use second way.

Body:
I have repository in my spring project:

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

    boolean existsById(long id);

    List<User> findAllByEmail(String email);

}

It works fine but appeared necessary to use LightUser

public class LightUser implements Identifiable<Long>, Auditable {

    @Id
    @Column
    private Long id;

    @Enumerated(EnumType.STRING)
    @Column(nullable = false, updatable = false)
    private UserType userType;

    @Column(nullable = false, unique = true)
    private String email;

    @Column(nullable = false)
    private String domain;

    // get/set methods/ equals/hashcode
}

LightUser entity contains a few fields I need in general (all fields precent in User entity), and I want do request to DB using repository mapping results into LightUser (it would be really good to map into dto).

Is it possible add special method into UserRepository to cover my needs or i should create similar one for same table but for LightUser? If it possible, provide example please or core idea.

Body:
First of all, you have to remove @Repository annotation from your interface since it's redundant.

And yes, you can select into LightUser using two ways:

1) Projection

You have to create projection with needed properties:

interface LightUser {
    Long getId();
    String getEmail();
}

And add appropriate select method:

@Query("SELECT u.id AS id, u.email AS email FROM User u WHERE u.id = :id")
LightUser findLightUser(@Param("id") String id)

The disadvantage of this way is that your projection should be an interface (but if you use this for REST, it's OK)

2) DTO

Your DTO should have a constructor with needed fields, for instance, id and email:

class LightUser {
    private Long id;
    private String email;

    public LightUser(Long id, String email) {
        this.id = id;
        this.email = email;
    }

    // getters and setters
}

and then you can write a select for this DTO:

@Query("SELECT new com.test.LightUser(u.id, u.email) FROM User u WHERE u.id = :id")
LightUser findLightUser(@Param("id") String id)

Since your LightUser is like DTO, you have to use second way.


问:
Dependency Property Binding and Update in Custom Control
I have created a simplified version of my code that experiences the same issue.  The issue is that I'm not sure why the dependency property in my custom control is not updating when it gets changed in the model.

Model:

```<code>public class MainWindowModel : INotifyPropertyChanged
{
    private bool isChecked;
    public bool IsChecked { get { return isChecked; } set { isChecked = value; OnPropertyChanged("IsChecked"); } }

    public event PropertyChangedEventHandler PropertyChanged;
    void OnPropertyChanged(string prop)
    {
        if (this.PropertyChanged != null)
            this.PropertyChanged(this, new PropertyChangedEventArgs(prop));
    }
}
</code>```

XAML:

```<code><Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:custom="clr-namespace:WpfApplication1"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <custom:CustomTextbox x:Name="TextboxName" HorizontalAlignment="Center" VerticalAlignment="Center" Width="200" TextChanged="CustomTextbox_TextChanged">
        <custom:CustomTextbox.CustomTextboxItems>
            <custom:CustomTextboxItem IsChecked="{Binding IsChecked}" />
        </custom:CustomTextbox.CustomTextboxItems>
    </custom:CustomTextbox>

    <Button Content="Do It" Click="Button_Click" HorizontalAlignment="Center" VerticalAlignment="Bottom" Margin="0,0,0,20" />
</Grid>
</Window>
</code>```

Code Behind:

```<code>public partial class MainWindow : Window
{
    MainWindowModel model;

    public MainWindow()
    {
        InitializeComponent();

        model = new MainWindowModel();
        this.DataContext = model;
    }

    private void CustomTextbox_TextChanged(object sender, TextChangedEventArgs e)
    {
        model.IsChecked = true;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        if (TextboxName.CustomTextboxItems[0].IsChecked)
        {
            TextboxName.Text = "Property successfully changed";
        }
    }
}
</code>```

Custom Control:

```<code>public class CustomTextbox : TextBox
{
    public CustomTextbox()
    {
        CustomTextboxItems = new ObservableCollection<CustomTextboxItem>();
    }

    public ObservableCollection<CustomTextboxItem> CustomTextboxItems { get; set; }
}

public class CustomTextboxItem : FrameworkElement
{
    public static readonly DependencyProperty IsCheckedProperty = DependencyProperty.Register("IsChecked", typeof(bool), typeof(CustomTextboxItem), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

    public bool IsChecked
    {
        get { return (bool)GetValue(IsCheckedProperty); }

        set { SetValue(IsCheckedProperty, value); }
    }
}
</code>```

As you can see in the custom control, I have a collection of items that contain objects with dependency properties that I want to bind to.  So I create the objects in the xaml and setup the binding, but when I update the binded property in the model, it doesn't change it in the custom control.  Any ideas?

答:
Look for binding errors in the Visual Studio output window. I think you'll find something telling you the binding on the check box has failed.

Your CustomTextBox control has a collection of CustomTextBoxItem objects, against which you're setting a binding. However, at no point are you adding those items to the logical tree. Read my post here to see how to add those items to the logical tree.

Body:
I have created a simplified version of my code that experiences the same issue.  The issue is that I'm not sure why the dependency property in my custom control is not updating when it gets changed in the model.

Model:

public class MainWindowModel : INotifyPropertyChanged
{
    private bool isChecked;
    public bool IsChecked { get { return isChecked; } set { isChecked = value; OnPropertyChanged("IsChecked"); } }

    public event PropertyChangedEventHandler PropertyChanged;
    void OnPropertyChanged(string prop)
    {
        if (this.PropertyChanged != null)
            this.PropertyChanged(this, new PropertyChangedEventArgs(prop));
    }
}

XAML:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:custom="clr-namespace:WpfApplication1"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <custom:CustomTextbox x:Name="TextboxName" HorizontalAlignment="Center" VerticalAlignment="Center" Width="200" TextChanged="CustomTextbox_TextChanged">
        <custom:CustomTextbox.CustomTextboxItems>
            <custom:CustomTextboxItem IsChecked="{Binding IsChecked}" />
        </custom:CustomTextbox.CustomTextboxItems>
    </custom:CustomTextbox>

    <Button Content="Do It" Click="Button_Click" HorizontalAlignment="Center" VerticalAlignment="Bottom" Margin="0,0,0,20" />
</Grid>
</Window>

Code Behind:

public partial class MainWindow : Window
{
    MainWindowModel model;

    public MainWindow()
    {
        InitializeComponent();

        model = new MainWindowModel();
        this.DataContext = model;
    }

    private void CustomTextbox_TextChanged(object sender, TextChangedEventArgs e)
    {
        model.IsChecked = true;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        if (TextboxName.CustomTextboxItems[0].IsChecked)
        {
            TextboxName.Text = "Property successfully changed";
        }
    }
}

Custom Control:

public class CustomTextbox : TextBox
{
    public CustomTextbox()
    {
        CustomTextboxItems = new ObservableCollection<CustomTextboxItem>();
    }

    public ObservableCollection<CustomTextboxItem> CustomTextboxItems { get; set; }
}

public class CustomTextboxItem : FrameworkElement
{
    public static readonly DependencyProperty IsCheckedProperty = DependencyProperty.Register("IsChecked", typeof(bool), typeof(CustomTextboxItem), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

    public bool IsChecked
    {
        get { return (bool)GetValue(IsCheckedProperty); }

        set { SetValue(IsCheckedProperty, value); }
    }
}

As you can see in the custom control, I have a collection of items that contain objects with dependency properties that I want to bind to.  So I create the objects in the xaml and setup the binding, but when I update the binded property in the model, it doesn't change it in the custom control.  Any ideas?


问:
Python 3.0 Calling a value from a class function to print
Trying to call the total hours from the class/function down to the instance of the class I created below. (hope i worded that correctly)

```<code>class Employee:
  def __init__(self):
    self.wage = 0
    self.hours = 0
    if self.hours > 40:
      self.ot = self.hours - 40                 #overtime hours
      self.earned_ot = self.wage * 1.5          #overtime wage rate
      self.ot_total = self.ot * self.earned_ot  #pay for overtime hours
      self.pay = self.wage * 40                 #standard hour wage
      self.total = self.pay + self.ot_total     #standard wage + ot hour wage
    else:
      self.total = self.wage * self.hours

alice = Employee()
alice.wage = 20
alice.hours = 40
#alice.total =

bob = Employee()
bob.wage = 15
bob.hours = 50
#bob.total =

print("Alice: \n Net pay: ${} \nBob: \n Net pay: ${}" .format(alice.total,
bob.total))
</code>```

Issue I'm having seems simple enough but I can't for the life of me figure it out. I commented out the alice.total and bob.total for now, but those are what I need to get the print to work correctly.

I feel like i'm forgetting something simple, but browsing back through my notes/texts I can't figure it out. Does anyone who sees the issue that I'm having, have a link to something that might explain this? I'm not looking for an outright answer, just a point in the right direction.

Thanks.

答:
Looks like your code would benefit from changing the constructor to:

```<code>class Employee:
    def __init__(self, wage=0, hours=0):
        self.wage = wage
        self.hours = hours
</code>```

and placing the rest of the code in a method:

```<code>class Employee:
    ....

    def get_total(self):
        total = ... # calculate from self.wage and self.hours
        return total

alice = Employee(wage=20, hours=40)
print(alice.get_total())
</code>```

Body:
Trying to call the total hours from the class/function down to the instance of the class I created below. (hope i worded that correctly)

class Employee:
  def __init__(self):
    self.wage = 0
    self.hours = 0
    if self.hours > 40:
      self.ot = self.hours - 40                 #overtime hours
      self.earned_ot = self.wage * 1.5          #overtime wage rate
      self.ot_total = self.ot * self.earned_ot  #pay for overtime hours
      self.pay = self.wage * 40                 #standard hour wage
      self.total = self.pay + self.ot_total     #standard wage + ot hour wage
    else:
      self.total = self.wage * self.hours

alice = Employee()
alice.wage = 20
alice.hours = 40
#alice.total =

bob = Employee()
bob.wage = 15
bob.hours = 50
#bob.total =

print("Alice: \n Net pay: ${} \nBob: \n Net pay: ${}" .format(alice.total,
bob.total))

Issue I'm having seems simple enough but I can't for the life of me figure it out. I commented out the alice.total and bob.total for now, but those are what I need to get the print to work correctly.

I feel like i'm forgetting something simple, but browsing back through my notes/texts I can't figure it out. Does anyone who sees the issue that I'm having, have a link to something that might explain this? I'm not looking for an outright answer, just a point in the right direction.

Thanks.

Body:
Looks like your code would benefit from changing the constructor to:

class Employee:
    def __init__(self, wage=0, hours=0):
        self.wage = wage
        self.hours = hours

and placing the rest of the code in a method:

class Employee:
    ....

    def get_total(self):
        total = ... # calculate from self.wage and self.hours
        return total

alice = Employee(wage=20, hours=40)
print(alice.get_total())


问:
Cannot execute script: Insufficient memory to continue the execution of the program
I have a 123MB sql file which I need to execute in my local PC. But I am getting

```<code>Cannot execute script: Insufficient memory to continue the execution of the program
</code>```

How to solve this issue?

答:
Try this step,

1)Open PowerShell

2)Write this command:

```<code>sqlcmd -S PCNAME\SQLEXPRESS -U user -P password -d databanse_name -i C:\script.sql
</code>```

3)Press Return

:-)

Body:
I have a 123MB sql file which I need to execute in my local PC. But I am getting

Cannot execute script: Insufficient memory to continue the execution of the program

How to solve this issue?

Body:
Try this step,

1)Open PowerShell

2)Write this command:

sqlcmd -S PCNAME\SQLEXPRESS -U user -P password -d databanse_name -i C:\script.sql

3)Press Return

:-)


问:
Merge field watermark - Microsoft Word 2013
I want to add a conditional Watermark in a word document using merge field. Is there any way to accomplish this? Is there any way to use merge field condition like below to add "DRAFT" watermark? or any other way to use a condition to make a watermark visible on the document? I am using Microsoft Word 2013. Thanks in advance for your help guys.</p>

```<code>{ IF"{MERGEFIELD SampleField}"="Yes" "DRAFT" "" }
</code>```

答:
The correct format:
{ IF { MERGEFIELD PrintCopy = 1 "ORIGINAL" "COPY" }}

Add spaces before and after the equal sign
Make sure the entire row (text above) is highlighted in grey when you click on it in the word document, otherwise it is only text once merged.

Body:
I want to add a conditional Watermark in a word document using merge field. Is there any way to accomplish this? Is there any way to use merge field condition like below to add "DRAFT" watermark? or any other way to use a condition to make a watermark visible on the document? I am using Microsoft Word 2013. Thanks in advance for your help guys.

{ IF"{MERGEFIELD SampleField}"="Yes" "DRAFT" "" }


问:
multi-node registration failures on mesos
I have a simple mesos cluster 1 master and 2 agents. All are VPS and connected over virtual lan. When I start the master and agent services, I see that I was able to see both the agents activated on the master via mesos UI. When I deploy a simple application (cmd: "echo hello; sleep 5") via marathon UI, the mesos UI shows that the program executed and completed on agent 1, however, on agent 2 the application status is ALWAYS staged.

In the log, for agent 2, I see that agent 2 never registers, while agent 1 does. Below is agent 2 log.

```<code>I1114 07:54:05.399139  8985 slave.cpp:251] Flags at startup: --appc_simple_discovery_uri_prefix="http://" --appc_store_dir="/tmp/mesos/store/appc" --authenticate_http_executors="false" --authenticate_http_readonly="false" --authenticate_http_readwrite="false" --authenticatee="crammd5" --authentication_backoff_factor="1secs" --authorizer="local" --cgroups_cpu_enable_pids_and_tids_count="false" --cgroups_enable_cfs="false" --cgroups_hierarchy="/sys/fs/cgroup" --cgroups_limit_swap="false" --cgroups_root="mesos" --container_disk_watch_interval="15secs" --containerizers="mesos" --default_role="*" --disallow_sharing_agent_pid_namespace="false" --disk_watch_interval="1mins" --docker="docker" --docker_kill_orphans="true" --docker_registry="https://registry-1.docker.io" --docker_remove_delay="6hrs" --docker_socket="/var/run/docker.sock" --docker_stop_timeout="0ns" --docker_store_dir="/tmp/mesos/store/docker" --docker_volume_checkpoint_dir="/var/run/mesos/isolators/docker/volume" --enforce_container_disk_quota="false" --executor_registration_timeout="1mins" --executor_reregistration_timeout="2secs" --executor_shutdown_grace_period="5secs" --fetcher_cache_dir="/tmp/mesos/fetch" --fetcher_cache_size="2GB" --frameworks_home="" --gc_delay="1weeks" --gc_disk_headroom="0.1" --hadoop_home="" --help="false" --hostname_lookup="true" --http_command_executor="false" --http_heartbeat_interval="30secs" --initialize_driver_logging="true" --ip="10.0.0.5" --isolation="posix/cpu,posix/mem" --launcher="linux" --launcher_dir="/usr/libexec/mesos" --logbufsecs="0" --logging_level="INFO" --master="10.0.0.6:5050" --max_completed_executors_per_framework="150" --oversubscribed_resources_interval="15secs" --perf_duration="10secs" --perf_interval="1mins" --port="5051" --qos_correction_interval_min="0ns" --quiet="false" --recover="reconnect" --recovery_timeout="15mins" --registration_backoff_factor="1secs" --revocable_cpu_low_priority="true" --runtime_dir="/var/run/mesos" --sandbox_directory="/mnt/mesos/sandbox" --strict="true" --switch_user="true" --systemd_enable_support="true" --systemd_runtime_directory="/run/systemd/system" --version="false" --work_dir="/var/lib/mesos/agent"
I1114 07:54:05.401047  8985 slave.cpp:565] Agent resources: [{"name":"cpus","scalar":{"value":4.0},"type":"SCALAR"},{"name":"mem","scalar":{"value":6959.0},"type":"SCALAR"},{"name":"disk","scalar":{"value":43131.0},"type":"SCALAR"},{"name":"ports","ranges":{"range":[{"begin":31000,"end":32000}]},"type":"RANGES"}]
I1114 07:54:05.404896  8985 slave.cpp:573] Agent attributes: [  ]
I1114 07:54:05.404913  8985 slave.cpp:582] Agent hostname: 10.0.0.5
I1114 07:54:05.405012  8982 status_update_manager.cpp:177] Pausing sending status updates
I1114 07:54:05.405889  8983 state.cpp:64] Recovering state from '/var/lib/mesos/agent/meta'
I1114 07:54:05.405936  8983 state.cpp:722] No committed checkpointed resources found at '/var/lib/mesos/agent/meta/resources/resources.info'
I1114 07:54:05.406015  8983 state.cpp:108] Failed to find the latest agent from '/var/lib/mesos/agent/meta'
I1114 07:54:05.411798  8987 status_update_manager.cpp:203] Recovering status update manager
I1114 07:54:05.411916  8988 containerizer.cpp:609] Recovering containerizer
I1114 07:54:05.413099  8985 provisioner.cpp:416] Provisioner recovery complete
I1114 07:54:05.413230  8984 slave.cpp:6295] Finished recovery
I1114 07:54:05.413630  8984 status_update_manager.cpp:177] Pausing sending status updates
I1114 07:54:05.413666  8981 slave.cpp:971] New master detected at master@10.0.0.6:5050
I1114 07:54:05.413694  8981 slave.cpp:995] No credentials provided. Attempting to register without authentication
I1114 07:54:05.413712  8981 slave.cpp:1006] Detecting new master
</code>```

agent #1 log is the same as above, but in the end it has these extra lines

```<code>I1114 07:57:17.609352  1645 slave.cpp:1006] Detecting new master
I1114 07:57:18.426383  1642 slave.cpp:1286] Re-registered with master master@10.0.0.6:5050
I1114 07:57:18.426463  1645 status_update_manager.cpp:184] Resuming sending status updates
I1114 07:57:18.426465  1642 slave.cpp:1323] Forwarding total oversubscribed resources {}
</code>```

am I configuring something wrong? or is this some bug in mesos? (unlikely I guess).

答:
Firewall was enabled
Had to open up port 5050 and 5051 on agent 2. Now it works fine
Ufw allow 5050
Ufw allow 5051</p>

Body:
I have a simple mesos cluster 1 master and 2 agents. All are VPS and connected over virtual lan. When I start the master and agent services, I see that I was able to see both the agents activated on the master via mesos UI. When I deploy a simple application (cmd: "echo hello; sleep 5") via marathon UI, the mesos UI shows that the program executed and completed on agent 1, however, on agent 2 the application status is ALWAYS staged.

In the log, for agent 2, I see that agent 2 never registers, while agent 1 does. Below is agent 2 log.

I1114 07:54:05.399139  8985 slave.cpp:251] Flags at startup: --appc_simple_discovery_uri_prefix="http://" --appc_store_dir="/tmp/mesos/store/appc" --authenticate_http_executors="false" --authenticate_http_readonly="false" --authenticate_http_readwrite="false" --authenticatee="crammd5" --authentication_backoff_factor="1secs" --authorizer="local" --cgroups_cpu_enable_pids_and_tids_count="false" --cgroups_enable_cfs="false" --cgroups_hierarchy="/sys/fs/cgroup" --cgroups_limit_swap="false" --cgroups_root="mesos" --container_disk_watch_interval="15secs" --containerizers="mesos" --default_role="*" --disallow_sharing_agent_pid_namespace="false" --disk_watch_interval="1mins" --docker="docker" --docker_kill_orphans="true" --docker_registry="https://registry-1.docker.io" --docker_remove_delay="6hrs" --docker_socket="/var/run/docker.sock" --docker_stop_timeout="0ns" --docker_store_dir="/tmp/mesos/store/docker" --docker_volume_checkpoint_dir="/var/run/mesos/isolators/docker/volume" --enforce_container_disk_quota="false" --executor_registration_timeout="1mins" --executor_reregistration_timeout="2secs" --executor_shutdown_grace_period="5secs" --fetcher_cache_dir="/tmp/mesos/fetch" --fetcher_cache_size="2GB" --frameworks_home="" --gc_delay="1weeks" --gc_disk_headroom="0.1" --hadoop_home="" --help="false" --hostname_lookup="true" --http_command_executor="false" --http_heartbeat_interval="30secs" --initialize_driver_logging="true" --ip="10.0.0.5" --isolation="posix/cpu,posix/mem" --launcher="linux" --launcher_dir="/usr/libexec/mesos" --logbufsecs="0" --logging_level="INFO" --master="10.0.0.6:5050" --max_completed_executors_per_framework="150" --oversubscribed_resources_interval="15secs" --perf_duration="10secs" --perf_interval="1mins" --port="5051" --qos_correction_interval_min="0ns" --quiet="false" --recover="reconnect" --recovery_timeout="15mins" --registration_backoff_factor="1secs" --revocable_cpu_low_priority="true" --runtime_dir="/var/run/mesos" --sandbox_directory="/mnt/mesos/sandbox" --strict="true" --switch_user="true" --systemd_enable_support="true" --systemd_runtime_directory="/run/systemd/system" --version="false" --work_dir="/var/lib/mesos/agent"
I1114 07:54:05.401047  8985 slave.cpp:565] Agent resources: [{"name":"cpus","scalar":{"value":4.0},"type":"SCALAR"},{"name":"mem","scalar":{"value":6959.0},"type":"SCALAR"},{"name":"disk","scalar":{"value":43131.0},"type":"SCALAR"},{"name":"ports","ranges":{"range":[{"begin":31000,"end":32000}]},"type":"RANGES"}]
I1114 07:54:05.404896  8985 slave.cpp:573] Agent attributes: [  ]
I1114 07:54:05.404913  8985 slave.cpp:582] Agent hostname: 10.0.0.5
I1114 07:54:05.405012  8982 status_update_manager.cpp:177] Pausing sending status updates
I1114 07:54:05.405889  8983 state.cpp:64] Recovering state from '/var/lib/mesos/agent/meta'
I1114 07:54:05.405936  8983 state.cpp:722] No committed checkpointed resources found at '/var/lib/mesos/agent/meta/resources/resources.info'
I1114 07:54:05.406015  8983 state.cpp:108] Failed to find the latest agent from '/var/lib/mesos/agent/meta'
I1114 07:54:05.411798  8987 status_update_manager.cpp:203] Recovering status update manager
I1114 07:54:05.411916  8988 containerizer.cpp:609] Recovering containerizer
I1114 07:54:05.413099  8985 provisioner.cpp:416] Provisioner recovery complete
I1114 07:54:05.413230  8984 slave.cpp:6295] Finished recovery
I1114 07:54:05.413630  8984 status_update_manager.cpp:177] Pausing sending status updates
I1114 07:54:05.413666  8981 slave.cpp:971] New master detected at master@10.0.0.6:5050
I1114 07:54:05.413694  8981 slave.cpp:995] No credentials provided. Attempting to register without authentication
I1114 07:54:05.413712  8981 slave.cpp:1006] Detecting new master

agent #1 log is the same as above, but in the end it has these extra lines

I1114 07:57:17.609352  1645 slave.cpp:1006] Detecting new master
I1114 07:57:18.426383  1642 slave.cpp:1286] Re-registered with master master@10.0.0.6:5050
I1114 07:57:18.426463  1645 status_update_manager.cpp:184] Resuming sending status updates
I1114 07:57:18.426465  1642 slave.cpp:1323] Forwarding total oversubscribed resources {}

am I configuring something wrong? or is this some bug in mesos? (unlikely I guess).