问:
How to chain in javascript yet get value in between
ok weird title, I know. However the question is simple. In a class I want to be able to do these two things:

invoice.getAmount(); // returns 1000

and

invoice.getAmount().asCurrency(); // returns $1000.00

I can do either, just don't know how to get both to work.

What I have for now for the second idea:

```<code>getAmount() {
 this._temp = this.amount;
 return this;
}

asCurrency(){
  if(this._temp){
    return "$" + this._temp + ".00";
  }
}
</code>```

That's an ugly copy of what I really have but the concept is represented...

Any idea?

Thanks

答:
Remember that getAmount is returning a number.

Thus, there is no way to chain asCurrency on the return value of getAmount (without using valueOf) unless asCurrency exists on the Number prototype.

If you wanted to keep all this composed in your class without modifying the Number prototype, you need to either use valueOf (best solution), or make your return value of getAmount your class instance so that you can chain it with asCurrency.

Body:
ok weird title, I know. However the question is simple. In a class I want to be able to do these two things:

invoice.getAmount(); // returns 1000

and

invoice.getAmount().asCurrency(); // returns $1000.00

I can do either, just don't know how to get both to work.

What I have for now for the second idea:

getAmount() {
 this._temp = this.amount;
 return this;
}

asCurrency(){
  if(this._temp){
    return "$" + this._temp + ".00";
  }
}

That's an ugly copy of what I really have but the concept is represented...

Any idea?

Thanks


来源: stackexchange

问:
What is the most customisable apex-region type/ plug-in based on a table?
I'd like to display the contents of a database table in a more interesting manner than just a table; different positioning, fonts, sizes, colours etc.

Is there a region type or plugin that can achieve that?

I tried the cards view but I it's still very limited (for example a minimum of 2 cards per row when I only need 1) Or maybe I should deploy it as a classic report and then use javascript to rearrange everything? edit: I also considered rendering the page with pl/sql and htp, but that seems overly complicated...

As I'm new to APEX, any input would be much appreciated!

答:
What I ended up doing was using an interactive report with a 'detail view'. That way you can use html+css and reference the data from the columns by using #column_name#. I'm really satisfied with it.

However the above answers are also very interesting! I definitely learned a lot experimenting with them.

ContentLicense: CC BY-SA 3.0


问:
How do I resolve merge conflicts in a Git repository?
How do I resolve merge conflicts in my Git repository?</p>

答:
```<code>git fetch <br>
git checkout **your branch**<br>
git rebase master<br>
</code>```

In this step you will try to fix the conflict using your preferred IDE.

You can follow this link to check how to fix the conflict in the file.

```<code>git add<br>
git rebase --continue<br>
git commit --amend<br>
git push origin HEAD:refs/drafts/master  (push like a drafts)<br>
</code>```

Now everything is fine and you will find your commit in Gerrit.

OwnerDisplayName: Spoike

ContentLicense: CC BY-SA 4.0

Body:
git fetch <br>
git checkout **your branch**<br>
git rebase master<br>

In this step you will try to fix the conflict using your preferred IDE.

You can follow this link to check how to fix the conflict in the file.

git add<br>
git rebase --continue<br>
git commit --amend<br>
git push origin HEAD:refs/drafts/master  (push like a drafts)<br>

Now everything is fine and you will find your commit in Gerrit.


问:
Python typing Union of class and it's instance
Say I have

```<code>class Foo:
   pass
</code>```

and I want to write a function that may accept Foo instance or some of Foo subclasses (not instances). So I wrote

```<code>def bar(o: Union[Foo, Type[Foo]]):
    print(1)
</code>```

And get such errors:

```<code>TypeError                                 Traceback (most recent call last) <ipython-input-161-2a8355efa688> in <module>()
----> 1 def bar(o: Union[Foo, Type[Foo]]):
      2     print(1)
      3

/usr/lib/python3.5/typing.py in __getitem__(self, parameters)
    550             parameters = (parameters,)
    551         return self.__class__(self.__name__, self.__bases__,
--> 552                               dict(self.__dict__), parameters, _root=True)
    553
    554     def __eq__(self, other):

/usr/lib/python3.5/typing.py in __new__(cls, name, bases, namespace, parameters, _root)
    510                 continue
    511             if any(isinstance(t2, type) and issubclass(t1, t2)
--> 512                    for t2 in all_params - {t1} if not isinstance(t2, TypeVar)):
    513                 all_params.remove(t1)
    514         # It's not a union if there's only one type left.

/usr/lib/python3.5/typing.py in <genexpr>(.0)
    510                 continue
    511             if any(isinstance(t2, type) and issubclass(t1, t2)
--> 512                    for t2 in all_params - {t1} if not isinstance(t2, TypeVar)):
    513                 all_params.remove(t1)
    514         # It's not a union if there's only one type left.

/usr/lib/python3.5/typing.py in __subclasscheck__(self, cls)    1075   return True    1076                 # If we break out of the loop, the superclass gets a chance.
-> 1077         if super().__subclasscheck__(cls):    1078             return True    1079         if self.__extra__ is None or isinstance(cls, GenericMeta):

/home/alexey/dev/gcore/django/lib/python3.5/abc.py in
__subclasscheck__(cls, subclass)
    223                 return True
    224         # Check if it's a subclass of a subclass (recursive)
--> 225         for scls in cls.__subclasses__():
    226             if issubclass(subclass, scls):
    227                 cls._abc_cache.add(subclass)

TypeError: descriptor '__subclasses__' of 'type' object needs an argument
</code>```

Is it impossible to specify that type in python, or I used wrong approach?

答:
See typing/issue 266. This has been fixed and no longer appears in updated versions of Python.

With Python 3.6.1, the function is compiled fine and the annotations stored correctly:

```<code>>>> def bar(o: Union[Foo, Type[Foo]]):
...     print(1)
>>> typing.get_type_hints(bar)
{'o': typing.Union[__main__.Foo, typing.Type[__main__.Foo]]}
</code>```

Body:
Say I have

class Foo:
   pass

and I want to write a function that may accept Foo instance or some of Foo subclasses (not instances). So I wrote

def bar(o: Union[Foo, Type[Foo]]):
    print(1)

And get such errors:

TypeError                                 Traceback (most recent call last) <ipython-input-161-2a8355efa688> in <module>()
----> 1 def bar(o: Union[Foo, Type[Foo]]):
      2     print(1)
      3

/usr/lib/python3.5/typing.py in __getitem__(self, parameters)
    550             parameters = (parameters,)
    551         return self.__class__(self.__name__, self.__bases__,
--> 552                               dict(self.__dict__), parameters, _root=True)
    553
    554     def __eq__(self, other):

/usr/lib/python3.5/typing.py in __new__(cls, name, bases, namespace, parameters, _root)
    510                 continue
    511             if any(isinstance(t2, type) and issubclass(t1, t2)
--> 512                    for t2 in all_params - {t1} if not isinstance(t2, TypeVar)):
    513                 all_params.remove(t1)
    514         # It's not a union if there's only one type left.

/usr/lib/python3.5/typing.py in <genexpr>(.0)
    510                 continue
    511             if any(isinstance(t2, type) and issubclass(t1, t2)
--> 512                    for t2 in all_params - {t1} if not isinstance(t2, TypeVar)):
    513                 all_params.remove(t1)
    514         # It's not a union if there's only one type left.

/usr/lib/python3.5/typing.py in __subclasscheck__(self, cls)    1075   return True    1076                 # If we break out of the loop, the superclass gets a chance.
-> 1077         if super().__subclasscheck__(cls):    1078             return True    1079         if self.__extra__ is None or isinstance(cls, GenericMeta):

/home/alexey/dev/gcore/django/lib/python3.5/abc.py in
__subclasscheck__(cls, subclass)
    223                 return True
    224         # Check if it's a subclass of a subclass (recursive)
--> 225         for scls in cls.__subclasses__():
    226             if issubclass(subclass, scls):
    227                 cls._abc_cache.add(subclass)

TypeError: descriptor '__subclasses__' of 'type' object needs an argument

Is it impossible to specify that type in python, or I used wrong approach?

Body:
See typing/issue 266. This has been fixed and no longer appears in updated versions of Python.

With Python 3.6.1, the function is compiled fine and the annotations stored correctly:

>>> def bar(o: Union[Foo, Type[Foo]]):
...     print(1)
>>> typing.get_type_hints(bar)
{'o': typing.Union[__main__.Foo, typing.Type[__main__.Foo]]}


问:
Postgres Encryption of configuration files
Currently in Postgres the largest security hole is the .conf files that the database relies on, this is because someone with access to the system (not necessarily the database) can modify the files and gain entry.  Because of this I am seeking out resources on how to encrypt those .conf files and then decrypt them during each session of the database.  Performance is not really an issue at this point.  Does anyone have any resources on this or has anyone developed any prototypes that utilize this functionality?

Edit

Since there seems to be some confusion here about what it is I am asking.  The scenario can best be illustrated on a Windows box with the following groups:

1) Administrators  System Administrators

2) Database Administrators  Postgres Administrators

3) Auditors Security Auditors

The Auditors group typically needs access to log files and configuration files to ensure system security.  However, the issue comes when a member of the Auditors group needs to view the Postgres configuration and log files.  If this member decides that they want to access the database even though they do not have a database account it is a very short task to break in .  How does one go about preventing this?  Answers such as: Get better auditors are quite poor as you can never fully predict what people will do.

答:
You are fine.  No need to encrypt, so long as you have permissions on the *.conf files correct.

Your postgresql.conf and pg_hba.conf should both be marked as readable only by the postgres user/group.  If you don't have actual users with those permissions, then only root can see them.

ContentLicense: CC BY-SA 2.5


问:
MeteorJs doesn't add data to collection - I'm stuck at point 8 of Intermediate Meteor Tutorial
I was studying MeteorJs this days, but stuck at this point: Intermediate Meteor Tutorial #8 - Insert Permissions, Publishing & Meteor Toys.

```<code>errorClass {error: 404, reason: "Method '/recipes/insert' not found", details: undefined, message: "Method '/recipes/insert' not found [404]", errorType: "Meteor.Error"…}
</code>```

I checked all the code. I tried to combine some ideas with "todos" tutorial. I even added insecure and autopublish packages - but error still appears.

How you can see on Screenshot in Mongol-panel there are Recipes collection. But when I type in mongo shell : show collections, it shows only "Users" collection.

I liked beginning of this tutorial and I hope, I can finish it , please help me to fix this error.

答:
That is one way to do it, the other is

You add

```<code>this.Recipes = new Mongo.Collection('Recipes')
</code>```

to a none client or server file.

This automatically lets you access the Recipes collection to the entire proyect.

Body:
I was studying MeteorJs this days, but stuck at this point: Intermediate Meteor Tutorial #8 - Insert Permissions, Publishing & Meteor Toys.

errorClass {error: 404, reason: "Method '/recipes/insert' not found", details: undefined, message: "Method '/recipes/insert' not found [404]", errorType: "Meteor.Error"…}

I checked all the code. I tried to combine some ideas with "todos" tutorial. I even added insecure and autopublish packages - but error still appears.

How you can see on Screenshot in Mongol-panel there are Recipes collection. But when I type in mongo shell : show collections, it shows only "Users" collection.

I liked beginning of this tutorial and I hope, I can finish it , please help me to fix this error.

Body:
That is one way to do it, the other is

You add

this.Recipes = new Mongo.Collection('Recipes')

to a none client or server file.

This automatically lets you access the Recipes collection to the entire proyect.


问:
git clone all remote branches
I have a repository in github with X number of branches and a repository in a closed network.

I need to move all of the repository to the one on the closed network. How do I clone all the branches (not just the default master), so I could then push it to the closed-network one with all the branches existing.

Entering the repo binary is not the issue here.

I want the same result as if I cloned my repo and did git branch to each branch, so it would be initialized locally.

答:
Once created something like that.
Hopefully it still works.
Perhaps it could help you:
https://github.com/srfrnk/fetch-all</p>

Title: git clone all remote branches


问:
set a html option selected in a dropdown containing optgroup tag using javascript
I'm working With Html(JSP) and Javascript. I have a dropdown box with id "examcenter" containing many optgroup as shown in the following code. in the function loadDrivingSchool() in javascript, I would like to set selected the value of the selected element. the loadDrivingSchool() function calls a controller in a server and when I return the view, the dropdown list does not have a selected value. I want to set this selected value to the value that the user choose before the reloading of the page. I have try the following Javascript code but it is not working:

       document.getElementById('examcenter').getElementsByTagName('option')[examCenter].selected = 'selected' ;

```<code>    <select id="examcenter" onchange="loadDrivingSchool();">
        <optgroup label="ADAMAOUA">
                <option value="1">TIBATI</option>
                <option value="2">TIGNERE</option>
                <option value="3">MEIGANGA</option>
                <option value="4">BANYO</option>
                <option value="5">NGAOUNDERE</option>
        </optgroup>

        <optgroup label="CENTRE">
                <option value="6">YAOUNDE</option>
                <option value="7">ESEKA</option>
                <option value="8">AKONOLINGA</option>
                <option value="9">NANGA EBOKO</option>
                <option value="10">MONATELE</option>
                <option value="11">MBALMAYO</option>
                <option value="12">MFOU</option>
                <option value="13">NGOUMOU</option>
                <option value="14">BAFIA</option>
                <option value="15">NTUI</option>
        </optgroup>
        <optgroup label="EXTREME NORD">
                <option value="20">MAROUA</option>
                <option value="21">KAELE</option>
                <option value="22">KOUSSERI</option>
                <option value="23">MORA</option>
                <option value="24">YAGOUA</option>
                <option value="25">MOKOLO</option>
        </optgroup>

        <optgroup label="EST">
                <option value="16">YOKADOUMA</option>
                <option value="17">ABONG-MBANG</option>
                <option value="18">BATOURI</option>
                <option value="19">BERTOUA</option>
                <option value="62">NGUELEMENDOUKA</option>
        </optgroup>
</select>
</code>```

答:
What I think you are trying to do is keep a track of what the user has selected, without submitting that selected option. That can only be achieved if you keep a record of that in some way, possibly using the session attribute.

You can probably store the value of the selected options in a session and then get it's value using AJAX.

But if I am wrong and you are trying to just simply get the value of the selected option without leaving that page, then you can try this to display the value of the selected option in your dropdown:

```<code>alert( document.getElementById("examcenter").value );
</code>```

Also, I see a problem in your code. You are using

```<code>document.getElementById('examcenter').getElementsByTagName('option')[examCenter].selected = 'selected' ;
</code>```

Instead, you should use:

```<code>document.getElementsByTagName('option').selected = true ;
</code>```

Body:
I'm working With Html(JSP) and Javascript. I have a dropdown box with id "examcenter" containing many optgroup as shown in the following code. in the function loadDrivingSchool() in javascript, I would like to set selected the value of the selected element. the loadDrivingSchool() function calls a controller in a server and when I return the view, the dropdown list does not have a selected value. I want to set this selected value to the value that the user choose before the reloading of the page. I have try the following Javascript code but it is not working:

       document.getElementById('examcenter').getElementsByTagName('option')[examCenter].selected = 'selected' ;

    <select id="examcenter" onchange="loadDrivingSchool();">
        <optgroup label="ADAMAOUA">
                <option value="1">TIBATI</option>
                <option value="2">TIGNERE</option>
                <option value="3">MEIGANGA</option>
                <option value="4">BANYO</option>
                <option value="5">NGAOUNDERE</option>
        </optgroup>

        <optgroup label="CENTRE">
                <option value="6">YAOUNDE</option>
                <option value="7">ESEKA</option>
                <option value="8">AKONOLINGA</option>
                <option value="9">NANGA EBOKO</option>
                <option value="10">MONATELE</option>
                <option value="11">MBALMAYO</option>
                <option value="12">MFOU</option>
                <option value="13">NGOUMOU</option>
                <option value="14">BAFIA</option>
                <option value="15">NTUI</option>
        </optgroup>
        <optgroup label="EXTREME NORD">
                <option value="20">MAROUA</option>
                <option value="21">KAELE</option>
                <option value="22">KOUSSERI</option>
                <option value="23">MORA</option>
                <option value="24">YAGOUA</option>
                <option value="25">MOKOLO</option>
        </optgroup>

        <optgroup label="EST">
                <option value="16">YOKADOUMA</option>
                <option value="17">ABONG-MBANG</option>
                <option value="18">BATOURI</option>
                <option value="19">BERTOUA</option>
                <option value="62">NGUELEMENDOUKA</option>
        </optgroup>
</select>

Body:
What I think you are trying to do is keep a track of what the user has selected, without submitting that selected option. That can only be achieved if you keep a record of that in some way, possibly using the session attribute.

You can probably store the value of the selected options in a session and then get it's value using AJAX.

But if I am wrong and you are trying to just simply get the value of the selected option without leaving that page, then you can try this to display the value of the selected option in your dropdown:

alert( document.getElementById("examcenter").value );

Also, I see a problem in your code. You are using

document.getElementById('examcenter').getElementsByTagName('option')[examCenter].selected = 'selected' ;

Instead, you should use:

document.getElementsByTagName('option').selected = true ;


问:
Converting UIImage to NSData and NSData to NSString for posting images to a server
I have two UIImageViews. I want to post two images to server through the script. Before that I have to convert these images to data and data to string but I don't know how to convert the images from UIImageView to NSData and NSData to NSString.I have referred all the codes but it does not work. I would also like to know as to where should I declare the conversion coding (image to data and data to image) in my code?

This is what I have implemented

.h part

```<code>  #import <UIKit/UIKit.h>
  #import "GlobalAccessClass.h"
  #import  <QuartzCore/QuartzCore.h>

  @interface AskQuestionHome :  UIViewController<UITextViewDelegate,UITextFieldDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate>

  {

  }
  @property (strong, nonatomic) IBOutlet UIImageView *imgSecondImg;

  @property (strong, nonatomic) IBOutlet UIImageView *imgFirstImg;

  @property (strong, nonatomic) IBOutlet UITextView *txtviewAsk;

  -(IBAction)postbutton:(id)sender;

  @property (nonatomic,retain) NSString *datestr;

  @property(nonatomic,retain) NSData *imageData;

  @property(nonatomic,retain) NSString *postLength;

  @end
</code>```

.m part

```<code> -(void)post
 {
     NSMutableURLRequest *mutableurlrequest = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:@"http://www.alvinchuastudios.com/aNSWERED/insert_question.php"]];

  // create the Method  "POST" For POSTING the QUESTIION with IMAGES
        [mutableurlrequest setHTTPMethod:@"POST"];

        NSLog(@"the email is:%@",manage.transformEmail);
        NSLog(@"the cat is:%@",manage.transformCategories);
        NSLog(@"the text is:%@",textviewText.text);
       // NSLog(@"the firstimage is:%ld",(long)imgFirstImg.tag);
       // NSLog(@"the secondimage is:%ld",(long)imgSecondImg.tag);
       // NSlog(@"the status is:%d",1);
        NSLog(@"the user is:%@",manage.transformName);
        NSLog(@"the user registered is:%@",datestr);

  //passing the string to the server
        NSString *qususerUpdate =[NSString stringWithFormat:@"email_id=%@&cat=%@&q_text=%@&q_image1=%ld&q_image2=%ld&q_status=1&last_upd_by=%@&last_upd_timestamp=%@",manage.transformEmail,manage.transformCategories,textviewText.text,(long)imgFirstImg.tag,(long)imgSecondImg.tag,manage.transformName,datestr,Nil];

  //check the value that what we passed
        NSLog(@"the data Details is =%@", qususerUpdate);

  //Convert the String to Data
        NSData *data1 =[qususerUpdate dataUsingEncoding:NSUTF8StringEncoding];

  //Apply the data to the body
        [mutableurlrequest setHTTPBody:data1];

  //Create the response and Error
        NSError *err;
        NSURLResponse *response;
        NSData *responseData =[NSURLConnection sendSynchronousRequest:mutableurlrequest returningResponse:&response error:&err];
        NSString *resStr =[[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];

  //This is for Response
        NSLog(@"got response==%@", resStr);  }
</code>```

答:
After Long time I post my answer here.

Option 1 : Image to server and Image from Server

When we send image to server(UIImage-NSData-NSString), we need to use below coding

```<code>NSData *postData = UIImageJPEGRepresentation(myImage, 1.0);
NSString *strEncoded  = [postData base64EncodedStringWithOptions:0];
</code>```

When we get the image from server(NSString-NSData-UIImage),we need to use below coding

```<code>NSData *getData  = [[NSData alloc] initWithBase64EncodedString:strEncodedFromServer options:0];
UIImage *image = [UIImage imageWithData:getData];
</code>```

Option 2 : Simple String Encode,Decode Conversion

```<code>NSString *strName = @"iOS";
NSData *dataEncoded = [strName dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64EncodedString = [dataEncoded base64EncodedStringWithOptions:0];
NSLog(@"The Encoded String is - %@", base64EncodedString);

NSData *dataDecoded = [[NSData alloc] initWithBase64EncodedString:base64EncodedString options:0];
NSString *strDecoded = [[NSString alloc] initWithData:dataDecoded encoding:NSUTF8StringEncoding];
NSLog(@"The DeCoded String is - %@", strDecoded);
</code>```

Output Screenshot is

Option 3 : When we need to encode and decode the dictionary

```<code>NSDictionary *dictEncoded = @{
                                    @"OS":@"iOS",
                                    @"Mobile":@"iPhone",
                                    @"Version":@"iOS10"
                                };

NSData *dataDictEncode = [NSJSONSerialization dataWithJSONObject:dictEncoded options:(NSJSONWritingOptions) 0 error:nil];
NSString *strBase64Encode = [dataDictEncode base64EncodedStringWithOptions:0];
NSLog(@"The encoded dictionary is - %@", strBase64Encode);

NSData *dataDictDecode = [[NSData alloc] initWithBase64EncodedString:strBase64Encode options:0];
NSDictionary *dictDecoded = [NSJSONSerialization JSONObjectWithData:dataDictDecode options:NSJSONReadingMutableContainers error:nil];
NSLog(@"The decoded dictionary is - %@", dictDecoded);
</code>```

Output result is

Body:
I have two UIImageViews. I want to post two images to server through the script. Before that I have to convert these images to data and data to string but I don't know how to convert the images from UIImageView to NSData and NSData to NSString.I have referred all the codes but it does not work. I would also like to know as to where should I declare the conversion coding (image to data and data to image) in my code?

This is what I have implemented

.h part

  #import <UIKit/UIKit.h>
  #import "GlobalAccessClass.h"
  #import  <QuartzCore/QuartzCore.h>

  @interface AskQuestionHome :  UIViewController<UITextViewDelegate,UITextFieldDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate>

  {

  }
  @property (strong, nonatomic) IBOutlet UIImageView *imgSecondImg;

  @property (strong, nonatomic) IBOutlet UIImageView *imgFirstImg;

  @property (strong, nonatomic) IBOutlet UITextView *txtviewAsk;

  -(IBAction)postbutton:(id)sender;

  @property (nonatomic,retain) NSString *datestr;

  @property(nonatomic,retain) NSData *imageData;

  @property(nonatomic,retain) NSString *postLength;

  @end

.m part

 -(void)post
 {
     NSMutableURLRequest *mutableurlrequest = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:@"http://www.alvinchuastudios.com/aNSWERED/insert_question.php"]];

  // create the Method  "POST" For POSTING the QUESTIION with IMAGES
        [mutableurlrequest setHTTPMethod:@"POST"];

        NSLog(@"the email is:%@",manage.transformEmail);
        NSLog(@"the cat is:%@",manage.transformCategories);
        NSLog(@"the text is:%@",textviewText.text);
       // NSLog(@"the firstimage is:%ld",(long)imgFirstImg.tag);
       // NSLog(@"the secondimage is:%ld",(long)imgSecondImg.tag);
       // NSlog(@"the status is:%d",1);
        NSLog(@"the user is:%@",manage.transformName);
        NSLog(@"the user registered is:%@",datestr);

  //passing the string to the server
        NSString *qususerUpdate =[NSString stringWithFormat:@"email_id=%@&cat=%@&q_text=%@&q_image1=%ld&q_image2=%ld&q_status=1&last_upd_by=%@&last_upd_timestamp=%@",manage.transformEmail,manage.transformCategories,textviewText.text,(long)imgFirstImg.tag,(long)imgSecondImg.tag,manage.transformName,datestr,Nil];

  //check the value that what we passed
        NSLog(@"the data Details is =%@", qususerUpdate);

  //Convert the String to Data
        NSData *data1 =[qususerUpdate dataUsingEncoding:NSUTF8StringEncoding];

  //Apply the data to the body
        [mutableurlrequest setHTTPBody:data1];

  //Create the response and Error
        NSError *err;
        NSURLResponse *response;
        NSData *responseData =[NSURLConnection sendSynchronousRequest:mutableurlrequest returningResponse:&response error:&err];
        NSString *resStr =[[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];

  //This is for Response
        NSLog(@"got response==%@", resStr);  }

Body:
After Long time I post my answer here.

Option 1 : Image to server and Image from Server

When we send image to server(UIImage-NSData-NSString), we need to use below coding

NSData *postData = UIImageJPEGRepresentation(myImage, 1.0);
NSString *strEncoded  = [postData base64EncodedStringWithOptions:0];

When we get the image from server(NSString-NSData-UIImage),we need to use below coding

NSData *getData  = [[NSData alloc] initWithBase64EncodedString:strEncodedFromServer options:0];
UIImage *image = [UIImage imageWithData:getData];

Option 2 : Simple String Encode,Decode Conversion

NSString *strName = @"iOS";
NSData *dataEncoded = [strName dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64EncodedString = [dataEncoded base64EncodedStringWithOptions:0];
NSLog(@"The Encoded String is - %@", base64EncodedString);

NSData *dataDecoded = [[NSData alloc] initWithBase64EncodedString:base64EncodedString options:0];
NSString *strDecoded = [[NSString alloc] initWithData:dataDecoded encoding:NSUTF8StringEncoding];
NSLog(@"The DeCoded String is - %@", strDecoded);

Output Screenshot is

Option 3 : When we need to encode and decode the dictionary

NSDictionary *dictEncoded = @{
                                    @"OS":@"iOS",
                                    @"Mobile":@"iPhone",
                                    @"Version":@"iOS10"
                                };

NSData *dataDictEncode = [NSJSONSerialization dataWithJSONObject:dictEncoded options:(NSJSONWritingOptions) 0 error:nil];
NSString *strBase64Encode = [dataDictEncode base64EncodedStringWithOptions:0];
NSLog(@"The encoded dictionary is - %@", strBase64Encode);

NSData *dataDictDecode = [[NSData alloc] initWithBase64EncodedString:strBase64Encode options:0];
NSDictionary *dictDecoded = [NSJSONSerialization JSONObjectWithData:dataDictDecode options:NSJSONReadingMutableContainers error:nil];
NSLog(@"The decoded dictionary is - %@", dictDecoded);

Output result is


问:
Android - Resuming Camera Activity gets delayed
I was working on Camera Modules, and the only issue here is when I try to retake the camera, it will get delayed for a few secs before opening the Camera Preview again (see First image). Please take a look at my Camera Preview looks below

This is after i took the photo

When I click the retake button (middle one), it will take some times to reload the Camera Preview (first image). I've tried another app and found that when it retakes the photo, it will go to previous Camera Preview instantly (without delay), its like going back to previous page.

In Camera Preview, I implemented some canvas draw to create the overlay view. But I think it's not the problem, because the other app that i said previously also takes some times to load the Camera Preview at first. But, the only different is when they retake the photo, the Camera Preview will load instantly, while my app takes some times to reload the Camera Preview.

I implemented SurfaceHolder.Callback in my Class. I've tried to remove onResume and tweak some of the methods and it didn't help much.

Any idea how to handle this delay?

Thanks

答: For retake to work faster, you can restart camera preview under the hood immediately when the picture arrives, and show the (captured) image view on top, hiding the live camera video stream. If the user decides to retake the photo, you simply hide the overlay (can be a fragment, or just a layout with ImageView and buttons), and the live preview will immediately be available!</p>


问:
In rake how do I call a subdir Rakefile
In ant I'd do the following

```<code> <target name="subclient" >
     <ant antfile="suddir/build.xml" target="target1" useNativeBasedir="true"/>
 </target>
</code>```

How do I do this sort of thing in JRuby/Rake

答:
You can simply use Dir.chdir and launch a rake subprocess:

```<code>def rake(*args)
  ruby "-S", "rake", *args
end

task :subrake do
  Dir.chdir("subproject") do
    rake
  end
end
</code>```

Title: In rake how do I call a subdir Rakefile

Body:
In ant I'd do the following

 <target name="subclient" >
     <ant antfile="suddir/build.xml" target="target1" useNativeBasedir="true"/>
 </target>

How do I do this sort of thing in JRuby/Rake

Body:
You can simply use Dir.chdir and launch a rake subprocess:

def rake(*args)
  ruby "-S", "rake", *args
end

task :subrake do
  Dir.chdir("subproject") do
    rake
  end
end


答:
You can override a few built-ins (toString() and valueOf()) on the Invoice.prototype like so:

function Invoice(amount) {
  this.amount = amount;
}

Invoice.prototype.toString =
Invoice.prototype.valueOf = function valueOf() {
  return this.value;
};

Invoice.prototype.getAmount = function getAmount() {
  this.value = this.amount;

  return this;
};

Invoice.prototype.asCurrency = function asCurrency() {
  this.value = '$' + this.value.toFixed(2);

  return this;
};

var invoice = new Invoice(1000);

console.log(Number(invoice.getAmount()));
console.log(String(invoice.getAmount().asCurrency()));

// or more subtly
console.log(invoice.getAmount() + 0);
console.log(invoice.getAmount().asCurrency() + '');```
</div>
</div>
</p>

<p>Or using ES6 <code>class</code>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class Invoice {
  constructor(amount) {
    this.amount = amount;
  }

  toString() {
    return this.value;
  }

  valueOf() {
    return this.value;
  }

  getAmount() {
    this.value = this.amount;

    return this;
  }

  asCurrency() {
    this.value = '$' + this.value.toFixed(2);

    return this;
  }
}

var invoice = new Invoice(1000);

console.log(Number(invoice.getAmount()));
console.log(String(invoice.getAmount().asCurrency()));

// or more subtly
console.log(invoice.getAmount() + 0);
console.log(invoice.getAmount().asCurrency() + '');</code>```

Title: How to chain in javascript yet get value in between

Body:
You can override a few built-ins (toString() and valueOf()) on the Invoice.prototype like so:

function Invoice(amount) {
  this.amount = amount;
}

Invoice.prototype.toString =
Invoice.prototype.valueOf = function valueOf() {
  return this.value;
};

Invoice.prototype.getAmount = function getAmount() {
  this.value = this.amount;

  return this;
};

Invoice.prototype.asCurrency = function asCurrency() {
  this.value = '$' + this.value.toFixed(2);

  return this;
};

var invoice = new Invoice(1000);

console.log(Number(invoice.getAmount()));
console.log(String(invoice.getAmount().asCurrency()));

// or more subtly
console.log(invoice.getAmount() + 0);
console.log(invoice.getAmount().asCurrency() + '');

Or using ES6 class:

class Invoice {
  constructor(amount) {
    this.amount = amount;
  }

  toString() {
    return this.value;
  }

  valueOf() {
    return this.value;
  }

  getAmount() {
    this.value = this.amount;

    return this;
  }

  asCurrency() {
    this.value = '$' + this.value.toFixed(2);

    return this;
  }
}

var invoice = new Invoice(1000);

console.log(Number(invoice.getAmount()));
console.log(String(invoice.getAmount().asCurrency()));

// or more subtly
console.log(invoice.getAmount() + 0);
console.log(invoice.getAmount().asCurrency() + '');


问:
wordpress display the navbar menu item vertically
This is Y code of header.php but I can't understand why wp_nav_menu give me a vertical menu.

This is my code of header.php

```<code><div class="navbar-wrapper">

    <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="index.html"><img src="<?php bloginfo('stylesheet_directory'); ?>/assets/img/logo.png" alt="DevtechFreelancer"></a>
            </div>

            <?php
                wp_nav_menu( array(
                    'theme_location'    => 'primary',
                    'container'         => 'nav',
                    'container_class'   => 'navbar-collapse collapse',
                    'menu_class'        => 'nav navbar-nav navbar-right'
                ) );
            ?>

        </div>
    </nav>
 </div>
</code>```

Please help: I can't find a solution for this bug.

答:
this is the solution</p>

```<code><?php
                            wp_nav_menu( array(

                                'theme_location'    => 'primary',
                                'container'         => 'ul',
                                'container_class'   => 'navbar-collapse collapse',
                                'menu_class'        => 'nav navbar-nav navbar-right'

                            )   );
                        ?>
</code>```

Body:
This is Y code of header.php but I can't understand why wp_nav_menu give me a vertical menu.

This is my code of header.php

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    Toggle navigation

                </button>
                <img src="<?php bloginfo('stylesheet_directory'); ?>/assets/img/logo.png" alt="DevtechFreelancer">

            <?php
                wp_nav_menu( array(
                    'theme_location'    => 'primary',
                    'container'         => 'nav',
                    'container_class'   => 'navbar-collapse collapse',
                    'menu_class'        => 'nav navbar-nav navbar-right'
                ) );
            ?>

Please help: I can't find a solution for this bug.

Body:
this is the solution

<?php
                            wp_nav_menu( array(

                                'theme_location'    => 'primary',
                                'container'         => 'ul',
                                'container_class'   => 'navbar-collapse collapse',
                                'menu_class'        => 'nav navbar-nav navbar-right'

                            )   );
                        ?>


问:
javascript: Loop Function on Array With Holes
If I create a sparse array (which has some holes in it), the array functions, like .map(), .reduce(), .forEach() will skip these holes.

```<code>[, , 1, , 2].forEach((item) => console.log(item))
// 1
// 2
</code>```

what I'm looking for is an array function which does not skip the holes, and works like this:

```<code>[, , 1, , 2].fullForEach((item) => console.log(item))
// undefined
// undefined
// 1
// undefined
// 2
</code>```

I would like to loop on the original array, and NOT to convert the holes in the array to actual undefined values, i.e. none of the following is what I'm looking for:

```<code>Array.from([, , 1, , 2]).forEach();
[...[, , 1, , 2]].forEach();
</code>```

I'm looking for a functional solution for this, which means I'd like to get a solution without any for / while loop.

答:
You should not be using Array.prototype.find for this – find will stop iterating as soon as a truthy value is returned from the function. It's only continuing to iterate in the console.log example provided because console.log is a side-effecting function and always returns undefined, a non-truthy value.

Instead, you should make your own iterator that properly describes the behavior you actually intend. As others commented, there is nothing wrong with using a for or while loop – that's exactly how the native functionals like reduce and map are implemented anyway. What you're looking for is the creation of a functional interface – ie, it doesn't matter what your function looks like on the inside; the user of your function gets to work with it in a purely functional way.

Array.prototype.fullForEach = function (f, env) {
  for (let i = 0; i < this.length; i++)
    f.call(env, this[i], i, this)
}

Array.prototype.fullReduce = function (f, acc, env) {
  for (let i = 0; i < this.length; i++)
    acc = f.call(env, acc, this[i], i, this)
  return acc
}

Array.prototype.fullMap = function (f, env) {
  return this.fullReduce((acc, x, i) => [...acc, f.call(env, x, i, this)], [], env)
}

const arr = [,,,2,,]

arr.fullForEach((x, i, xs) => console.log(x, i, xs))
// undefined 0 [ , , , 2,  ]
// undefined 1 [ , , , 2,  ]
// undefined 2 [ , , , 2,  ]
// 2 3 [ , , , 2,  ]
// undefined 4 [ , , , 2,  ]

console.log(arr.fullMap(x => x ? x : 'void'))
// [ 'void', 'void', 'void', 2, 'void' ]

console.log(arr.fullMap(function (x) { return x ? x : this.default }, { default: 'void' }))
// [ 'void', 'void', 'void', 2, 'void' ]

console.log(arr.fullReduce((acc, x) => x ? acc + x : acc + '-', ''))
// ---2-

console.log(arr.fullReduce(function (acc, x) { return x ? acc + x : acc + this.default }, '', { default: '-' }))
// ---2-```

You can continue implementing the other useful functionals filter, every, some, etc.

I took care to ensure these behave like forEach, map, and reduce counterparts; specifically with regard to the ability to change the lambda's context – note, changing context only works with non-arrow functions, as demoed in the code

So what did we learn? We implemented functional interfaces for fullForEach, fullReduce, and fullMap using simple for loops. However, when the function is called, the user is not burdened with these details and is allowed to express their program in a functional style.

Body:
If I create a sparse array (which has some holes in it), the array functions, like .map(), .reduce(), .forEach() will skip these holes.

[, , 1, , 2].forEach((item) => console.log(item))
// 1
// 2

what I'm looking for is an array function which does not skip the holes, and works like this:

[, , 1, , 2].fullForEach((item) => console.log(item))
// undefined
// undefined
// 1
// undefined
// 2

I would like to loop on the original array, and NOT to convert the holes in the array to actual undefined values, i.e. none of the following is what I'm looking for:

Array.from([, , 1, , 2]).forEach();
[...[, , 1, , 2]].forEach();

I'm looking for a functional solution for this, which means I'd like to get a solution without any for / while loop.

Body:
You should not be using Array.prototype.find for this – find will stop iterating as soon as a truthy value is returned from the function. It's only continuing to iterate in the console.log example provided because console.log is a side-effecting function and always returns undefined, a non-truthy value.

Instead, you should make your own iterator that properly describes the behavior you actually intend. As others commented, there is nothing wrong with using a for or while loop – that's exactly how the native functionals like reduce and map are implemented anyway. What you're looking for is the creation of a functional interface – ie, it doesn't matter what your function looks like on the inside; the user of your function gets to work with it in a purely functional way.

Array.prototype.fullForEach = function (f, env) {
  for (let i = 0; i < this.length; i++)
    f.call(env, this[i], i, this)
}

Array.prototype.fullReduce = function (f, acc, env) {
  for (let i = 0; i < this.length; i++)
    acc = f.call(env, acc, this[i], i, this)
  return acc
}

Array.prototype.fullMap = function (f, env) {
  return this.fullReduce((acc, x, i) => [...acc, f.call(env, x, i, this)], [], env)
}

const arr = [,,,2,,]

arr.fullForEach((x, i, xs) => console.log(x, i, xs))
// undefined 0 [ , , , 2,  ]
// undefined 1 [ , , , 2,  ]
// undefined 2 [ , , , 2,  ]
// 2 3 [ , , , 2,  ]
// undefined 4 [ , , , 2,  ]

console.log(arr.fullMap(x => x ? x : 'void'))
// [ 'void', 'void', 'void', 2, 'void' ]

console.log(arr.fullMap(function (x) { return x ? x : this.default }, { default: 'void' }))
// [ 'void', 'void', 'void', 2, 'void' ]

console.log(arr.fullReduce((acc, x) => x ? acc + x : acc + '-', ''))
// ---2-

console.log(arr.fullReduce(function (acc, x) { return x ? acc + x : acc + this.default }, '', { default: '-' }))
// ---2-

You can continue implementing the other useful functionals filter, every, some, etc.

I took care to ensure these behave like forEach, map, and reduce counterparts; specifically with regard to the ability to change the lambda's context – note, changing context only works with non-arrow functions, as demoed in the code

So what did we learn? We implemented functional interfaces for fullForEach, fullReduce, and fullMap using simple for loops. However, when the function is called, the user is not burdened with these details and is allowed to express their program in a functional style.


问:
C. Ok in main but segmentation fault when inside function
This piece of code gives a segmentation fault but If the test function body in written directly in the main function it works properly. So, what do you think is causing this problem?

Segmentation fault:

```<code>#include<stdio.h>

int test()
{
    int i=0;
    int *p;
    printf("pass\n");
    for (i = 0; i < 24; i++)
    {
        printf("%d\n",i);
        *(p+i) = i;
        printf("%d\n",*(p+i));
    }
    return 1;

}

int main() {
    int x = 0;
    x = test();
}
</code>```

Working fine:

```<code>int main() {
    int i=0;
    int *p;
    printf("pass\n");
    for (i = 0; i < 24; i++)
    {
        printf("%d\n",i);
        *(p+i) = i;
        printf("%d\n",*(p+i));
    }
}
</code>```

EDIT: Before throwing me with a bunch of down votes, please try the code. I know it is bad programming. I'm evaluating some C code exames and had a student that wrote this. Yes, not very good, but is a fact that the working version is actually working.

答:
The p pointer is not initialized in both cases. It contains an undetermined value.

Dereferencing an uninitialized pointer is undefined behaviour (google that).

In the first case your pointer p happens  by chance to point somewhere where the dereferencement does not end up in a segfault (that is valid memory that your process is allowed to read), but in the second case it points to another location where dereferencement does end up in a segfault (dereferencement of memory that your process is not allowed to read).

Body:
This piece of code gives a segmentation fault but If the test function body in written directly in the main function it works properly. So, what do you think is causing this problem?

Segmentation fault:

#include<stdio.h>

int test()
{
    int i=0;
    int *p;
    printf("pass\n");
    for (i = 0; i < 24; i++)
    {
        printf("%d\n",i);
        *(p+i) = i;
        printf("%d\n",*(p+i));
    }
    return 1;

}

int main() {
    int x = 0;
    x = test();
}

Working fine:

int main() {
    int i=0;
    int *p;
    printf("pass\n");
    for (i = 0; i < 24; i++)
    {
        printf("%d\n",i);
        *(p+i) = i;
        printf("%d\n",*(p+i));
    }
}

EDIT: Before throwing me with a bunch of down votes, please try the code. I know it is bad programming. I'm evaluating some C code exames and had a student that wrote this. Yes, not very good, but is a fact that the working version is actually working.


问:
Make an array of my model with an auto-increment
I have a Model and I want make an array of this. The problem is I do it like this :

My code :

```<code>final WifiModel itemsData[] = {
                new WifiModel(nearbyAccessPoints.get(0).SSID, "name"),
                new WifiModel(nearbyAccessPoints.get(1).SSID, "name"),
                new WifiModel(nearbyAccessPoints.get(2).SSID, "name"),
                new WifiModel(nearbyAccessPoints.get(3).SSID, "name"),
                new WifiModel(nearbyAccessPoints.get(4).SSID, "name"),
        };
</code>```

And I would like to do a i++ form to i=4 for example.
How can I do that ?

My Model :

```<code>public class WifiModel {

    private String SSID;
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    WifiModel(String SSID, String name) {
        this.SSID = SSID;
        this.name = name;
    }

    public String getSSID() {
        return SSID;
    }

    public void setSSID(String SSID) {
        this.SSID = SSID;
    }
}
</code>```

答:
easy :)</p>

```<code>WifiModel itemsData[] = new WifiModel[5];
for(int i=0; i<5; i++) itemsData[i]=new WifiModel(nearbyAccessPoints.get(i).SSID, "name");
</code>```

Body:
I have a Model and I want make an array of this. The problem is I do it like this :

My code :

final WifiModel itemsData[] = {
                new WifiModel(nearbyAccessPoints.get(0).SSID, "name"),
                new WifiModel(nearbyAccessPoints.get(1).SSID, "name"),
                new WifiModel(nearbyAccessPoints.get(2).SSID, "name"),
                new WifiModel(nearbyAccessPoints.get(3).SSID, "name"),
                new WifiModel(nearbyAccessPoints.get(4).SSID, "name"),
        };

And I would like to do a i++ form to i=4 for example.
How can I do that ?

My Model :

public class WifiModel {

    private String SSID;
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    WifiModel(String SSID, String name) {
        this.SSID = SSID;
        this.name = name;
    }

    public String getSSID() {
        return SSID;
    }

    public void setSSID(String SSID) {
        this.SSID = SSID;
    }
}

Body:
easy :)

WifiModel itemsData[] = new WifiModel[5];
for(int i=0; i<5; i++) itemsData[i]=new WifiModel(nearbyAccessPoints.get(i).SSID, "name");


问:
Immutable vs Mutable types
I'm confused on what an immutable type is. I know the float object is considered to be immutable, with this type of example from my book:

```<code>class RoundFloat(float):
    def __new__(cls, val):
        return float.__new__(cls, round(val, 2))
</code>```

Is this considered to be immutable because of the class structure / hierarchy?, meaning float is at the top of the class and is its own method call. Similar to this type of example (even though my book says dict is mutable):

```<code>class SortedKeyDict(dict):
    def __new__(cls, val):
        return dict.__new__(cls, val.clear())
</code>```

Whereas something mutable has methods inside the class, with this type of example:

```<code>class SortedKeyDict_a(dict):
    def example(self):
        return self.keys()
</code>```

Also, for the last class(SortedKeyDict_a), if I pass this type of set to it:

```<code>d = (('zheng-cai', 67), ('hui-jun', 68),('xin-yi', 2))
</code>```

without calling the example method, it returns a dictionary. The SortedKeyDict with __new__ flags it as an error. I tried passing integers to the RoundFloat class with __new__ and it flagged no errors.

答:
I haven't read all the answers, but the selected answer is not correct and I think the author has an idea that being able to reassign a variable means that whatever datatype is mutable. That is not the case. Mutability has to do with passing by reference rather than passing by value.

Lets say you created a List

```<code>a = [1,2]
</code>```

If you were to say:

```<code>b = a
b[1] = 3
</code>```

Even though you reassigned a value on B, it will also reassign the value on a. Its because when you assign "b = a". You are passing the "Reference" to the object rather than a copy of the value. This is not the case with strings, floats etc. This makes list, dictionaries and the likes mutable, but booleans, floats etc immutable.

Title: Immutable vs Mutable types

Body:
I'm confused on what an immutable type is. I know the float object is considered to be immutable, with this type of example from my book:

class RoundFloat(float):
    def __new__(cls, val):
        return float.__new__(cls, round(val, 2))

Is this considered to be immutable because of the class structure / hierarchy?, meaning float is at the top of the class and is its own method call. Similar to this type of example (even though my book says dict is mutable):

class SortedKeyDict(dict):
    def __new__(cls, val):
        return dict.__new__(cls, val.clear())

Whereas something mutable has methods inside the class, with this type of example:

class SortedKeyDict_a(dict):
    def example(self):
        return self.keys()

Also, for the last class(SortedKeyDict_a), if I pass this type of set to it:

d = (('zheng-cai', 67), ('hui-jun', 68),('xin-yi', 2))

without calling the example method, it returns a dictionary. The SortedKeyDict with __new__ flags it as an error. I tried passing integers to the RoundFloat class with __new__ and it flagged no errors.

Body:
I haven't read all the answers, but the selected answer is not correct and I think the author has an idea that being able to reassign a variable means that whatever datatype is mutable. That is not the case. Mutability has to do with passing by reference rather than passing by value.

Lets say you created a List

a = [1,2]

If you were to say:

b = a
b[1] = 3

Even though you reassigned a value on B, it will also reassign the value on a. Its because when you assign "b = a". You are passing the "Reference" to the object rather than a copy of the value. This is not the case with strings, floats etc. This makes list, dictionaries and the likes mutable, but booleans, floats etc immutable.


问:
Searching a 3D array for closest point satisfying a certain predicate
I'm looking for an enumeration algorithm to search through a 3D array "sphering" around a given starting point.

Given an array a of size NxNxN where each N is 2^k for some k, and a point p in that array. The algorithm I'm looking for should do the following: If a[p] satisfies a certain predicate, the algorithm stops and p is returned. Otherwise the next point q is checked, where q is another point in the array that is the closest to p and hasn't been visited yet. If that doesn't match either, the next q'is checked an so on until in the worst case the whole array has been searched.

By "closest" here the perfect solution would be the point q that has the smallest Euclidean distance to p. As only discrete points have to be considered, perhaps some clever enumeration algorithm woukd make that possible. However, if this gets too complicated, the smallest Manhattan distance would be fine too. If there are several nearest points, it doesn't matter which one should be considered next.

Is there already an algorithm that can be used for this task?

答:
You can search for increasing squared distances, so you won't miss a point. This python code should make it clear:

import math
import itertools

# Calculates all points at a certain distance.
# Coordinate constraint: z <= y <= x
def get_points_at_squared_euclidean_distance(d):
    result = []
    x = int(math.floor(math.sqrt(d)))
    while 0 <= x:
        y = x
        while 0 <= y:
            target = d - x*x - y*y
            lower = 0
            upper = y + 1
            while lower < upper:
                middle = (lower + upper) / 2
                current = middle * middle
                if current == target:
                    result.append((x, y, middle))
                    break
                if current < target:
                    lower = middle + 1
                else:
                    upper = middle
            y -= 1
        x -= 1
    return result

# Creates all possible reflections of a point
def get_point_reflections(point):
    result = set()
    for p in itertools.permutations(point):
        for n in range(8):
            result.add((
                p[0] * (1 if n % 8 < 4 else -1),
                p[1] * (1 if n % 4 < 2 else -1),
                p[2] * (1 if n % 2 < 1 else -1),
            ))
    return sorted(result)

# Enumerates all points around a center, in increasing distance
def get_next_point_near(center):
    d = 0
    points_at_d = []
    while True:
        while not points_at_d:
            d += 1
            points_at_d = get_points_at_squared_euclidean_distance(d)
        point = points_at_d.pop()
        for reflection in get_point_reflections(point):
            yield (
                center[0] + reflection[0],
                center[1] + reflection[1],
                center[2] + reflection[2],
            )

# The function you asked for
def get_nearest_point(center, predicate):
    for point in get_next_point_near(center):
        if predicate(point):
            return point

# Example usage
print get_nearest_point((1,2,3), lambda p: sum(p) == 10)
```

Basically you consume points from the generator until one of them fulfills your predicate.

Body:
You can search for increasing squared distances, so you won't miss a point. This python code should make it clear:

import math
import itertools

# Calculates all points at a certain distance.
# Coordinate constraint: z <= y <= x
def get_points_at_squared_euclidean_distance(d):
    result = []
    x = int(math.floor(math.sqrt(d)))
    while 0 <= x:
        y = x
        while 0 <= y:
            target = d - x*x - y*y
            lower = 0
            upper = y + 1
            while lower < upper:
                middle = (lower + upper) / 2
                current = middle * middle
                if current == target:
                    result.append((x, y, middle))
                    break
                if current < target:
                    lower = middle + 1
                else:
                    upper = middle
            y -= 1
        x -= 1
    return result

# Creates all possible reflections of a point
def get_point_reflections(point):
    result = set()
    for p in itertools.permutations(point):
        for n in range(8):
            result.add((
                p[0] * (1 if n % 8 < 4 else -1),
                p[1] * (1 if n % 4 < 2 else -1),
                p[2] * (1 if n % 2 < 1 else -1),
            ))
    return sorted(result)

# Enumerates all points around a center, in increasing distance
def get_next_point_near(center):
    d = 0
    points_at_d = []
    while True:
        while not points_at_d:
            d += 1
            points_at_d = get_points_at_squared_euclidean_distance(d)
        point = points_at_d.pop()
        for reflection in get_point_reflections(point):
            yield (
                center[0] + reflection[0],
                center[1] + reflection[1],
                center[2] + reflection[2],
            )

# The function you asked for
def get_nearest_point(center, predicate):
    for point in get_next_point_near(center):
        if predicate(point):
            return point

# Example usage
print get_nearest_point((1,2,3), lambda p: sum(p) == 10)

Basically you consume points from the generator until one of them fulfills your predicate.


问:
JDBC Cannot connect to mysql
I'm trying to connect to mysql db using jdbc,but an exception occurred.Can anyone help me? thx!
driver version is 6.0.6 and mysql db version is  5.7.18.

it seems the error is caused by ArrayIndexOutOfBoundsException,but I really can't figure it out!

code:

```<code>    package test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Test {

    @org.junit.jupiter.api.Test
    public void test(){
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "admin");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
</code>```

stack

```<code>java.sql.SQLNonTransientConnectionException: Could not create connection to database server.
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:526)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:513)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:505)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:479)
    at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:1779)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:1596)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:633)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:347)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:219)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)
    at test.Test.test(Test.java:13)

Caused by: java.lang.ArrayIndexOutOfBoundsException: 39
    at com.mysql.cj.mysqla.io.Buffer.readInteger(Buffer.java:271)
    at com.mysql.cj.mysqla.io.MysqlaCapabilities.setInitialHandshakePacket(MysqlaCapabilities.java:62)
    at com.mysql.cj.mysqla.io.MysqlaProtocol.readServerCapabilities(MysqlaProtocol.java:482)
    at com.mysql.cj.mysqla.io.MysqlaProtocol.beforeHandshake(MysqlaProtocol.java:367)
    at com.mysql.cj.mysqla.io.MysqlaProtocol.connect(MysqlaProtocol.java:1412)
    at com.mysql.cj.mysqla.MysqlaSession.connect(MysqlaSession.java:132)
    at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:1726)
    ... 36 more
</code>```

答: As Mark said you should downgrade to 5.1.42 driver first. It helped me to at least to see what real error is. In my case it was connection to root account from another host. In you case it might be something else. 6.0.6 really still under development.</p>

Title: JDBC Cannot connect to mysql

Body:
I'm trying to connect to mysql db using jdbc,but an exception occurred.Can anyone help me? thx!
driver version is 6.0.6 and mysql db version is  5.7.18.

it seems the error is caused by ArrayIndexOutOfBoundsException,but I really can't figure it out!

code:

    package test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Test {

    @org.junit.jupiter.api.Test
    public void test(){
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "admin");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

stack

java.sql.SQLNonTransientConnectionException: Could not create connection to database server.
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:526)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:513)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:505)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:479)
    at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:1779)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:1596)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:633)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:347)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:219)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)
    at test.Test.test(Test.java:13)

Caused by: java.lang.ArrayIndexOutOfBoundsException: 39
    at com.mysql.cj.mysqla.io.Buffer.readInteger(Buffer.java:271)
    at com.mysql.cj.mysqla.io.MysqlaCapabilities.setInitialHandshakePacket(MysqlaCapabilities.java:62)
    at com.mysql.cj.mysqla.io.MysqlaProtocol.readServerCapabilities(MysqlaProtocol.java:482)
    at com.mysql.cj.mysqla.io.MysqlaProtocol.beforeHandshake(MysqlaProtocol.java:367)
    at com.mysql.cj.mysqla.io.MysqlaProtocol.connect(MysqlaProtocol.java:1412)
    at com.mysql.cj.mysqla.MysqlaSession.connect(MysqlaSession.java:132)
    at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:1726)
    ... 36 more


问:
Windows batch: variables set inside a loop are ignored
I'm using the following code inside a Windows batch (*.bat) file to run several SQL queries:

```<code>set PSTR=QUERY1,QUERY2

for %%a in (%PSTR%) do (

  set START=%date%:%time%
  "C:\Program Files\PostgreSQL\9.4\bin\psql.exe" -f "D:\SQL\%%a.sql" -h localhost -p 5432 -U postgres db_tom
  set END=%date%:%time%
  echo %%a  DEB %DEB%  FIN %FIN% >> "D:\LOGS\log.txt"
</code>```

The echo writes the following string inside the log.txt file:

```<code>QUERY1 START END
QUERY2 START END
</code>```

The variables set inside the loop are ignored. Is there another way to write this batch in order to get start and end datetime written down?

答:
```<code>setlocal enabledelayedexpansion
for %%a in ...(
 set start=!date!:!time!
 ...
 set end=!date!:!time!
 echo !start! !end!
)
</code>```

please consult any of the hundreds of SO items about delayed expansion - the setlocal enabledelayedexpansion invokes a mode where !var! retrieves the run-time value not the parse-time value of the variable.

Body:
I'm using the following code inside a Windows batch (*.bat) file to run several SQL queries:

set PSTR=QUERY1,QUERY2

for %%a in (%PSTR%) do (

  set START=%date%:%time%
  "C:\Program Files\PostgreSQL\9.4\bin\psql.exe" -f "D:\SQL\%%a.sql" -h localhost -p 5432 -U postgres db_tom
  set END=%date%:%time%
  echo %%a  DEB %DEB%  FIN %FIN% >> "D:\LOGS\log.txt"

The echo writes the following string inside the log.txt file:

QUERY1 START END
QUERY2 START END

The variables set inside the loop are ignored. Is there another way to write this batch in order to get start and end datetime written down?

Body:
setlocal enabledelayedexpansion
for %%a in ...(
 set start=!date!:!time!
 ...
 set end=!date!:!time!
 echo !start! !end!
)

please consult any of the hundreds of SO items about delayed expansion - the setlocal enabledelayedexpansion invokes a mode where !var! retrieves the run-time value not the parse-time value of the variable.


问:
Entity framework custom inheritance with caliburn.micro
I am writing a WPF app using caliburn.micro to work with a database. I am using entity framework with the database-first approach (since I already have a db) to generate classes. Is it possible to make the entity framework gererate classes that would inherit the PropertyChangedBase class of caliburn Or to make them implement the IHandle interface. I need these classes to have it for the views to know when the data has been changed.</p>

答:
You could edit the copy of the .tt template inside your project:

Modifying Entity Framework Types T4 Template

The auto-generated entity classes are created using this template.


问:
inconsistency between month, day, second representation of interval data type
I understand why postgresql uses month,day and second fields to representate the sql interval datatype. A month is not always the same length and a day can have 23, 24 or 25 hours if a daylight savings time adjustment is involved. this is from postgresql documentation.

But I then do not understand why this is not consequently handled both for months and days. see the following query which calculates an exact interval where the number of seconds between two points in time is exactly calculatable:

```<code>select ('2017-01-01'::timestamp-'2016-01-01'::timestamp); -->366 days.
</code>```

postgresql chooses to give a result in days. not in months and not in seconds.

But why is the result days and not seconds? it is NOT defined how long days are (they can be 23,24 or 25 hours long). so why does he not give output in seconds?

Then since the length of months is also not defined, why doesn't postgresql give an output of 12 month instead of 366 days?

He does not care that the length of days is not defined, but obviously he cares that the length of month is not defined.

Why this asymmetrie?

For further explanation, see this query:

```<code>select ('10 days'::interval-'24 hours'::interval); --> 10 days -24:00:00
</code>```

you see that postgresql correctly refuses to answer with 9 days. He is pretty aware of the problem that days and hours cannot be interchanged. But then again why does the first query return days?

答:
I can't answer your question, but I think I can point you in the right direction. I think the book SQL-99 Complete, Really is the most accessible source for understanding SQL intervals. It's available online: https://mariadb.com/kb/en/sql-99/08-temporal-values/.

SQL standards describe two kinds of intervals: year-month intervals and day-time intervals. It does this to prevent month parts and day parts from appearing in the same interval, because, as you already know, the number of days in a month is ambiguous. The number of days in the interval '3' month depends on which three months you're talking about.

I think this is the verbose, standard SQL way to write your first query.

```<code>select cast(timestamp '2017-01-01' - timestamp '2016-01-01' as interval day to hour) as new_column;
new_column
interval day to hour
--
366 days
</code>```

I suspect that you'll find that SQL standards have rules for what a SQL dbms is supposed to do when things like interval day to hour are omitted. PostgreSQL might or might not follow those rules.

postgresql chooses to give a result in days. not in months and not in seconds.

Standard SQL prevents month parts and day parts from appearing in the same interval. Also, the range of valid seconds is from 0 to 59.

```<code>select interval '59' second;
interval
interval second
--
00:00:59

select interval '60' second;
interval
interval second
--
00:01:00
</code>```

Body:
I understand why postgresql uses month,day and second fields to representate the sql interval datatype. A month is not always the same length and a day can have 23, 24 or 25 hours if a daylight savings time adjustment is involved. this is from postgresql documentation.

But I then do not understand why this is not consequently handled both for months and days. see the following query which calculates an exact interval where the number of seconds between two points in time is exactly calculatable:

select ('2017-01-01'::timestamp-'2016-01-01'::timestamp); -->366 days.

postgresql chooses to give a result in days. not in months and not in seconds.

But why is the result days and not seconds? it is NOT defined how long days are (they can be 23,24 or 25 hours long). so why does he not give output in seconds?

Then since the length of months is also not defined, why doesn't postgresql give an output of 12 month instead of 366 days?

He does not care that the length of days is not defined, but obviously he cares that the length of month is not defined.

Why this asymmetrie?

For further explanation, see this query:

select ('10 days'::interval-'24 hours'::interval); --> 10 days -24:00:00

you see that postgresql correctly refuses to answer with 9 days. He is pretty aware of the problem that days and hours cannot be interchanged. But then again why does the first query return days?

Body:
I can't answer your question, but I think I can point you in the right direction. I think the book SQL-99 Complete, Really is the most accessible source for understanding SQL intervals. It's available online: https://mariadb.com/kb/en/sql-99/08-temporal-values/.

SQL standards describe two kinds of intervals: year-month intervals and day-time intervals. It does this to prevent month parts and day parts from appearing in the same interval, because, as you already know, the number of days in a month is ambiguous. The number of days in the interval '3' month depends on which three months you're talking about.

I think this is the verbose, standard SQL way to write your first query.

select cast(timestamp '2017-01-01' - timestamp '2016-01-01' as interval day to hour) as new_column;
new_column
interval day to hour
--
366 days

I suspect that you'll find that SQL standards have rules for what a SQL dbms is supposed to do when things like interval day to hour are omitted. PostgreSQL might or might not follow those rules.

postgresql chooses to give a result in days. not in months and not in seconds.

Standard SQL prevents month parts and day parts from appearing in the same interval. Also, the range of valid seconds is from 0 to 59.

select interval '59' second;
interval
interval second
--
00:00:59

select interval '60' second;
interval
interval second
--
00:01:00


问:
Android Activity got hanged when executing a function via aidl even though the service is in another process Why?
I have included the following in manifest

```<code><service
    android:name=".AService"
    android:enabled="true"
    android:exported="true"
    android:process=":Adsadas"
    >
</code>```

In my activity, executed bind service and received the binder and executed the service function
  --> mRemoteService.firstFunc() -- executed this from Activity

In service

```<code> private final IService.Stub mBinder = new IService.Stub() {
         @Override
        public void firstFunc() throws RemoteException {
            Log.d(TAG,">>- firstFunc");
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
            }
            Log.d(TAG,"<<- firstFunc");
        }
}
</code>```

While executing firstFunc() from activity the UI got unresponsive for 10 sec even though I had added as seperate process in manifest. What might be the reason?

答:
You are using AIDL, which is running on your thread. You will need to run it on another thread or to use messenger for communicating with the service.

You can read more about communicating with service in https://developer.android.com/guide/components/bound-services.html

If it's only for running a function, consider using Handler or AsyncTask.

Body:
I have included the following in manifest

<service
    android:name=".AService"
    android:enabled="true"
    android:exported="true"
    android:process=":Adsadas"
    >

In my activity, executed bind service and received the binder and executed the service function
  --> mRemoteService.firstFunc() -- executed this from Activity

In service

 private final IService.Stub mBinder = new IService.Stub() {
         @Override
        public void firstFunc() throws RemoteException {
            Log.d(TAG,">>- firstFunc");
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
            }
            Log.d(TAG,"<<- firstFunc");
        }
}

While executing firstFunc() from activity the UI got unresponsive for 10 sec even though I had added as seperate process in manifest. What might be the reason?


答:
Arrays are not for dynamic length. You can use ArrayList instead to acheive this goal as following:</p>

```<code>ArrayList<WifiModel> itemsData = new ArrayList<>();

int n=4; // any number you want
for(int i=0;i<n;i++)
{
itemData.add(new WifiModel(nearbyAccessPoints.get(i).SSID, "name"));
}
</code>```

Title: Make an array of my model with an auto-increment

Body:
Arrays are not for dynamic length. You can use ArrayList instead to acheive this goal as following:

ArrayList<WifiModel> itemsData = new ArrayList<>();

int n=4; // any number you want
for(int i=0;i<n;i++)
{
itemData.add(new WifiModel(nearbyAccessPoints.get(i).SSID, "name"));
}


问:
WPF: Detect when Window loses focus
How do I detect when my window loses focus?</p>

答:
Use the Window.Deactivated event.

You may be looking for the Application.Deactivated event, which fires only if the user switched to a different application.

Title: WPF: Detect when Window loses focus


问:
codeigniter upload images from different inputs
my code is working fine in the single upload, but I want to make a loop for my code that I won't repeatedly create a function over and over because of using two different inputs.

```<code>public function uploadImage_1()
{
    $config['upload_path'] = './uploads';
    $config['allowed_types'] = 'gif|jpg|png|jpeg';
    $config['max_size'] = '2608';
    $config['max_width'] = '2608';
    $config['max_height'] = '2608';
    $this->load->library('upload', $config);
    if ( !$this->upload->do_upload('userfile1')){
        $error = array('error' => $this->upload->display_errors());
    }else{
        $fileName = $this->upload->data();
        $post_image = $fileName['file_name'];
        return $post_image;
    }
}

public function uploadImage_2()
{}
</code>```

`  View

```<code><input type="file" name="userfile1" size="20" required/>
<input type="file" name="userfile2" size="20" required/>`
</code>```

答:
You can pass the input field name as parameter into your function.

like this:

```<code>public function uploadImage($input_field_name)
{
    $config['upload_path'] = './uploads';
    $config['allowed_types'] = 'gif|jpg|png|jpeg';
    $config['max_size'] = '2608';
    $config['max_width'] = '2608';
    $config['max_height'] = '2608';
    $this->load->library('upload', $config);

    if ( !$this->upload->do_upload($input_field_name)){
        $error = array('error' => $this->upload->display_errors());
    }else{
        $fileName = $this->upload->data();
        $post_image = $fileName['file_name'];
        return $post_image;
    }
}
</code>```

Now use the above function like this:

```<code>// These variables stores the name of your files
$fileName_1 = $this->uploadImage('userfile1');
$fileName_2 = $this->uploadImage('userfile2');
</code>```

Body:
my code is working fine in the single upload, but I want to make a loop for my code that I won't repeatedly create a function over and over because of using two different inputs.

public function uploadImage_1()
{
    $config['upload_path'] = './uploads';
    $config['allowed_types'] = 'gif|jpg|png|jpeg';
    $config['max_size'] = '2608';
    $config['max_width'] = '2608';
    $config['max_height'] = '2608';
    $this->load->library('upload', $config);
    if ( !$this->upload->do_upload('userfile1')){
        $error = array('error' => $this->upload->display_errors());
    }else{
        $fileName = $this->upload->data();
        $post_image = $fileName['file_name'];
        return $post_image;
    }
}

public function uploadImage_2()
{}

`  View

<input type="file" name="userfile1" size="20" required/>
<input type="file" name="userfile2" size="20" required/>`

Body:
You can pass the input field name as parameter into your function.

like this:

public function uploadImage($input_field_name)
{
    $config['upload_path'] = './uploads';
    $config['allowed_types'] = 'gif|jpg|png|jpeg';
    $config['max_size'] = '2608';
    $config['max_width'] = '2608';
    $config['max_height'] = '2608';
    $this->load->library('upload', $config);

    if ( !$this->upload->do_upload($input_field_name)){
        $error = array('error' => $this->upload->display_errors());
    }else{
        $fileName = $this->upload->data();
        $post_image = $fileName['file_name'];
        return $post_image;
    }
}

Now use the above function like this:

// These variables stores the name of your files
$fileName_1 = $this->uploadImage('userfile1');
$fileName_2 = $this->uploadImage('userfile2');


问:
Add script to file in powershell
I am having long script that need to be added to created file, problem is its a script and it contains lots of special chars.

And I am getting a lot of error, I've put script in '' but it did not work as i expected.

Is there an easy way to do it, like taking a text and just adding it to file, somehow with special chars?

```<code>powershell.exe Add-Content C:\Testing\Powershell\PageFeature.ps1 - 'Function Press-Button
{
    Add-Type -AssemblyName System.Windows.Forms
    [System.Windows.Forms.SendKeys]::SendWait('~');
}

Function Resize-Window
{
    $pshost = get-host
    $pswindow = $pshost.ui.rawui

    $newsize = $pswindow.buffersize
    $newsize.height = 300
    $newsize.width = 128
    $pswindow.buffersize = $newsize

    $newsize = $pswindow.windowsize
    $newsize.height = 5
    $newsize.width = 128
    $pswindow.windowsize = $newsize
}

Function Run-Tool
{
    $ps = new-object System.Diagnostics.Process
    $ps.StartInfo.Filename = "C:\Testing\bin.exe"
    $ps.StartInfo.RedirectStandardInput = $true
    $ps.StartInfo.UseShellExecute = $false

    $ps.start()

    while ( ! $ps.HasExited ) {
        Start-Sleep -s 5
        write-host "I will press button now..."
        Press-Button
    }

    Write-Output "Default key was pressed"
    Write-Output "exit code: $($ps.ExitCode)"
}

Resize-Window
Run-Tool'
</code>```

答:
You should dot-source your external script.  This effectively dumps the contents of that script into your working script.  At the top (or wherever you want the code to be initialized):</p>

```<code>. "\\Path\to\Script.ps1"
</code>```

Title: Add script to file in powershell

Body:
I am having long script that need to be added to created file, problem is its a script and it contains lots of special chars.

And I am getting a lot of error, I've put script in '' but it did not work as i expected.

Is there an easy way to do it, like taking a text and just adding it to file, somehow with special chars?

powershell.exe Add-Content C:\Testing\Powershell\PageFeature.ps1 - 'Function Press-Button
{
    Add-Type -AssemblyName System.Windows.Forms
    [System.Windows.Forms.SendKeys]::SendWait('~');
}

Function Resize-Window
{
    $pshost = get-host
    $pswindow = $pshost.ui.rawui

    $newsize = $pswindow.buffersize
    $newsize.height = 300
    $newsize.width = 128
    $pswindow.buffersize = $newsize

    $newsize = $pswindow.windowsize
    $newsize.height = 5
    $newsize.width = 128
    $pswindow.windowsize = $newsize
}

Function Run-Tool
{
    $ps = new-object System.Diagnostics.Process
    $ps.StartInfo.Filename = "C:\Testing\bin.exe"
    $ps.StartInfo.RedirectStandardInput = $true
    $ps.StartInfo.UseShellExecute = $false

    $ps.start()

    while ( ! $ps.HasExited ) {
        Start-Sleep -s 5
        write-host "I will press button now..."
        Press-Button
    }

    Write-Output "Default key was pressed"
    Write-Output "exit code: $($ps.ExitCode)"
}

Resize-Window
Run-Tool'

Body:
You should dot-source your external script.  This effectively dumps the contents of that script into your working script.  At the top (or wherever you want the code to be initialized):

. "\\Path\to\Script.ps1"


问:
Error :- java runtime environment JRE or java development kit must be available in order to run eclipse
I tried to run "eclipse-jee-juno-win32-x86_64" , but it raised the following error " java runtime environment JRE or java development kit must be available in order to run eclipse. No java virtual machine was found after searching in the folloiwng location ........ ".

Baring in mind that i have both java jre7 and Java jdk1.7.0_06 installed at C:\Program Files\Java.

The other strange thing also that Eclipse used to run without any problems yesterday , but today i have downloaded the JDK 1.7.0_06 and i set the JAVA_HOME to be "C:\Program Files\Java\jdk1.7.0_06"so i don't know if the problem is related to this ???.

So what might be the problem in running Eclipse?
BR

答:
This problem is because of the fact that eclipse is not able to find Java ,

Check the java directory
cd /Library/Java/JavaVirtualMachines///Contents/Home/jre/bin

If thats not present down JDK from http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

Once JDK is installed change eclipse.ini file

On Mac:
Right click on Eclipse icon and click "Show package Content"

Navigate to eclipse>Contents>Eclipse>eclipse.ini

Open the file and replace the java path after "-vm" with this

/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/bin


问:
What differs in the destruction of stl::unordered_map and stl::vector
I am looking for a more in detail answer, rather than UB is UB.

I have a piece of legacy code that I know is the culprit of an exception. We previously memset a vector, and once it was changed to an unordered_map it threw an exception on destruction. What in the source code makes memsetting a vector differ from an unordered_map? They both interact with contiguous memory...

In our code we have this. (I apologize for pseudo code, but the point should still be understandable...)

```<code>class B
{
    std::vector<CustomObject> vect;
};

struct STRUCT_A
{
    B b;
};
</code>```

Later on we do this...

```<code>STRUCT_A m_struct_a;
memset(&m_struct_a, 0, sizeof(STRUCT_A));
</code>```

This works perfectly fine even if we memset an stl::container! However, if we change class B to have a map then an exception occurs on the destructor.

```<code>class B
{
    std::map<CustomObject> vect;
};
</code>```

So I thought it had to do with the vector being contiguous, so I changed it to an unordered_map

```<code>class B
{
    std::unordered_map<CustomObject> vect;
};
</code>```

An exception is still thrown on the destructor. I thought it was pretty interesting, and thought it was a good question to ask...

答:
Take a look at the source for your implementation's containers.

In libstdc++, the destructor for std::vector calls CustomObject::~CustomObject() for each element in the range [begin(), end()) and then deallocates the memory. Since you memset the vector to 0, begin() == end() == 0, the range is empty and the member's destructor is never called. Similarly, the deallocation is fine since it checks that the storage is non-null before deallocating.

In std::map, the destructor tries to walk the nodes of the _Rb_tree, which fails because the root node has null pointers. In std::unordered_map, the destructor calls __builtin_memset on the bucket array, which fails because the pointer to the array has been cleared.

Body:
I am looking for a more in detail answer, rather than UB is UB.

I have a piece of legacy code that I know is the culprit of an exception. We previously memset a vector, and once it was changed to an unordered_map it threw an exception on destruction. What in the source code makes memsetting a vector differ from an unordered_map? They both interact with contiguous memory...

In our code we have this. (I apologize for pseudo code, but the point should still be understandable...)

class B
{
    std::vector<CustomObject> vect;
};

struct STRUCT_A
{
    B b;
};

Later on we do this...

STRUCT_A m_struct_a;
memset(&m_struct_a, 0, sizeof(STRUCT_A));

This works perfectly fine even if we memset an stl::container! However, if we change class B to have a map then an exception occurs on the destructor.

class B
{
    std::map<CustomObject> vect;
};

So I thought it had to do with the vector being contiguous, so I changed it to an unordered_map

class B
{
    std::unordered_map<CustomObject> vect;
};

An exception is still thrown on the destructor. I thought it was pretty interesting, and thought it was a good question to ask...


问:
How to chain in javascript yet get value in between
ok weird title, I know. However the question is simple. In a class I want to be able to do these two things:

invoice.getAmount(); // returns 1000

and

invoice.getAmount().asCurrency(); // returns $1000.00

I can do either, just don't know how to get both to work.

What I have for now for the second idea:

```<code>getAmount() {
 this._temp = this.amount;
 return this;
}

asCurrency(){
  if(this._temp){
    return "$" + this._temp + ".00";
  }
}
</code>```

That's an ugly copy of what I really have but the concept is represented...

Any idea?

Thanks

答:
Trick is to use the valueOf() method.

```<code>class Invoice {

  constructor(value) {
    this.value = value;
  }

  getAmount() {
    return {
      valueOf: _ => this.value,
      asCurrency: _ => '$' + this.value
    }
  }
}

const i = new Invoice(150);

console.log(i.getAmount() + 10); // 160
console.log(i.getAmount().asCurrency()); // '$150'
</code>```

Body:
ok weird title, I know. However the question is simple. In a class I want to be able to do these two things:

invoice.getAmount(); // returns 1000

and

invoice.getAmount().asCurrency(); // returns $1000.00

I can do either, just don't know how to get both to work.

What I have for now for the second idea:

getAmount() {
 this._temp = this.amount;
 return this;
}

asCurrency(){
  if(this._temp){
    return "$" + this._temp + ".00";
  }
}

That's an ugly copy of what I really have but the concept is represented...

Any idea?

Thanks

Body:
Trick is to use the valueOf() method.

class Invoice {

  constructor(value) {
    this.value = value;
  }

  getAmount() {
    return {
      valueOf: _ => this.value,
      asCurrency: _ => '$' + this.value
    }
  }
}

const i = new Invoice(150);

console.log(i.getAmount() + 10); // 160
console.log(i.getAmount().asCurrency()); // '$150'


问:
Difference between binding with map index or dot notation
Are there any functional or performance differences between the following two blocks?

```<code><foo ng-if="bar['qux']">
<foo ng-if="bar.qux">
</code>```

Does it make a difference if bar.qux is/isn't initially defined?

Note: I fully understand how objects work in plain Javascript. This is a NOT a question about Javascript, it's about differences that might exist in AngularJS (because of parsing, or any other implementation details)

答:
I've created a proper jsPerf test case to make sure which notation would be parsed faster and the results are that dot notations are around 6% faster than bracket notation.

JsPerf test case: https://jsperf.com/test-angularjs-parse-speed.

Dot notation is faster, however, performance differences seems to be too little, so I you can choose which of them to use based on what is more readable and practical for you (or your team). Because both run in more than 10,000,000 Operations per second 7% wouldn't cause any performance issue for your app for such simple expression.

Body:
Are there any functional or performance differences between the following two blocks?

<foo ng-if="bar['qux']">
<foo ng-if="bar.qux">

Does it make a difference if bar.qux is/isn't initially defined?

Note: I fully understand how objects work in plain Javascript. This is a NOT a question about Javascript, it's about differences that might exist in AngularJS (because of parsing, or any other implementation details)


问:
Vlookup/Index on data with gaps
I have a simple data set that consists of some numbers:

```<code>  A   B  C  D  E  F  G

  a   1  2  3     5
  b   1  3     4     6
  c   1     2     5  6
</code>```

I want to use a vlookup/Index formula in another sheet from this data without showing the gaps. For example in my second sheet I would like the data displayed as below:

```<code>  A   B  C  D  E  F  G
  a   1  2  3  5
  b   1  3  4  6
  c   1  2  5  6
</code>```

Is there a way of doing this without copying and pasting?

答:
There are easier ways but... Assuming data is in Sheet1, starting in A1, in A1 of the other sheet:

```<code>=IF(Sheet1!A1=0,VLOOKUP(9,$1:$1,0),Sheet1!A1)
</code>```

drag across to G1 and A1:G1 down to Row5. Delete Row2. Select A1:G4, HOME > Editing, Find & Select, Go To Special..., Formulas (only), tick Errors (only), OK, right-click within selection, Delete...,  Shift cells left, OK.

Title: Vlookup/Index on data with gaps

Body:
I have a simple data set that consists of some numbers:

  A   B  C  D  E  F  G

  a   1  2  3     5
  b   1  3     4     6
  c   1     2     5  6

I want to use a vlookup/Index formula in another sheet from this data without showing the gaps. For example in my second sheet I would like the data displayed as below:

  A   B  C  D  E  F  G
  a   1  2  3  5
  b   1  3  4  6
  c   1  2  5  6

Is there a way of doing this without copying and pasting?

Body:
There are easier ways but... Assuming data is in Sheet1, starting in A1, in A1 of the other sheet:

=IF(Sheet1!A1=0,VLOOKUP(9,$1:$1,0),Sheet1!A1)

drag across to G1 and A1:G1 down to Row5. Delete Row2. Select A1:G4, HOME > Editing, Find & Select, Go To Special..., Formulas (only), tick Errors (only), OK, right-click within selection, Delete...,  Shift cells left, OK.


问:
error returned when installing webpack
I am working on this tutorial. And I got up to the point where it asks me to install webpack, but when I do using:

```<code>npm install --save-dev webpack
</code>```

I get the following error:

webpack-dev-server@2.5.0 requires a peer of webpack@^2.2.0 but none
was installed.

Any ideas?

答:
I am also learning from that tutorial. Like the error says, that you have webpack-dev-server@2.5.0 but you are missing the matching version of webpack. If you check the package.json, then you would find the webpack version to be different (maybe it's 3.0.0?).

So, install webpack@^2.2.0 like below:

```<code>npm install --save-dev webpack@^2.2.0
</code>```

P.S. As I am a beginner, so I may be wrong. Please excuse, if that's the case.

Title: error returned when installing webpack

Body:
I am working on this tutorial. And I got up to the point where it asks me to install webpack, but when I do using:

npm install --save-dev webpack

I get the following error:

webpack-dev-server@2.5.0 requires a peer of webpack@^2.2.0 but none
was installed.

Any ideas?

Body:
I am also learning from that tutorial. Like the error says, that you have webpack-dev-server@2.5.0 but you are missing the matching version of webpack. If you check the package.json, then you would find the webpack version to be different (maybe it's 3.0.0?).

So, install webpack@^2.2.0 like below:

npm install --save-dev webpack@^2.2.0

P.S. As I am a beginner, so I may be wrong. Please excuse, if that's the case.


问:
Exposing a web site through web services
I know what I am asking is somehow weird. There is a web application (which we don't have access to its source code), and we want to expose a few of its features as web services.

I was thinking to use something like Selenium WebDriver, so I simulate web clicks on the application according to the web service request.

I want to know whether this is a better solution or pattern to do this.

I shall mention that the application is written using Java, Spring MVC (it is not SPA) and Spring Security. And there is a CAS server providing SSO.

答:
We do something similar to access web banking on behalf of a user, scrape his account data and obtain a credit score. In most cases, we have managed to reverse-engineer mobile apps and sniff traffic to use undocumented APIs. In others, we have to fall back to web scraping.

You can have two other types of applications to scrape:

Data is essentially the same for any user, like product listings in Amazon

Data is specific to each user, like in a banking app.

In the firs case, you could have your scraper running and populating a local database and use your local data to provide the web service. In the later case, you cannot do that and you need to scrape the site on user's request.

I understand from your explanation that you are in this later case.

When web scraping you can find really difficult web apps:

Some may require you to send data from previous requests to the next

Others render most data on the client with JavaScript

If any of these two is your case, Selenium will make your implementation easier though not performant.

Implementing the first without selenium will require you to do lots of trial an error to get the thing working because you will be simulating the requests and you will need to know what data is expected from the client. Whereas if you use selenium you will be executing the same interactions that you do with the browser and hence sending the expected data.
Implementing the second case requires your scraper to support JavaScript. AFAIK best support is provided by selenium. HtmlUnit claims to provide fair support, and I think JSoup provides no support to JavaScript.

Finally, if your solution takes too much time you can mitigate the problem providing your web service with a notification mechanism, similar to Webhooks or Resthooks:

A client of your web service would make a request for data providing a URI they would like to get notified when the results are ready.

Your service would respond immediatly with an id of the request and start scraping the necessary info in the background.

If you use skinny payload model, when the scraping is done, you store the response in your data store with an id identifying the original request. This response will be exposed as a resource.

You would execute an HTTPPOST on the URI provided by the client. In the body of the request you would add the URI of the response resource.

The client can now GET the response resource and because the request and response have the same id, the client can correlate both.


问:
Ajax request not firing in new version of jquery
I have a small script that checks the username in the database if it is taken it will say taken if its available it will say available. currently the below code works perfectly in jQuery v1.7.2

How ever I need to update it to work with the current version of jQuery v3.2.1,
but trying to use the current jquery version it just says checking availability and nothing else.

```<code>$(document).ready(function() {
  $("#username").keyup(function() {
    var username = $("#username").val();
    var msgbox = $("#status");

    if (username.length > 3) {
      $("#status").html('');

      $.ajax({
        type: "POST",
        url: "includes/user_check.php",
        data: "username=" + username,
        success: function(msg) {
          $("#status").ajaxComplete(function(event, request) {
            if (msg == 'OK') {

              $("#username").removeClass("red");
              $("#username").addClass("green");
              msgbox.html('Available');
            } else {
              $("#username").removeClass("green");
              $("#username").addClass("red");
              msgbox.html(msg);
            }

          });
        }
      });
    } else {
      $("#username").addClass("red");
      $("#status").html('<font color="#cc0000">To Short</font>');
    }
    return false;
  });
});
</code>```

答: If your not familiar with jQuery and cannot get a straight answer you can always use the jQuery migrate. This may help you if you cannot get any help here.</p>

Body:
I have a small script that checks the username in the database if it is taken it will say taken if its available it will say available. currently the below code works perfectly in jQuery v1.7.2

How ever I need to update it to work with the current version of jQuery v3.2.1,
but trying to use the current jquery version it just says checking availability and nothing else.

$(document).ready(function() {
  $("#username").keyup(function() {
    var username = $("#username").val();
    var msgbox = $("#status");

    if (username.length > 3) {
      $("#status").html('');

      $.ajax({
        type: "POST",
        url: "includes/user_check.php",
        data: "username=" + username,
        success: function(msg) {
          $("#status").ajaxComplete(function(event, request) {
            if (msg == 'OK') {

              $("#username").removeClass("red");
              $("#username").addClass("green");
              msgbox.html('Available');
            } else {
              $("#username").removeClass("green");
              $("#username").addClass("red");
              msgbox.html(msg);
            }

          });
        }
      });
    } else {
      $("#username").addClass("red");
      $("#status").html('To Short');
    }
    return false;
  });
});