问:
How to add Headers to Request in AfNetworking 3.0?
I am confused with adding headers in 'AFNetworking 3.0'. In the previous version, there is function known as RequestSerializer. How can I add specific headers to a Mutable Request?

```<code>{
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

 NSString *path = [[NSBundle mainBundle] pathForResource:@"uploadedImage_3" ofType:@"jpg"];
[formData appendPartWithFileURL:[NSURL fileURLWithPath:path] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
}
error:nil];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request addValue:@"8b10056e-59e6-4d2b-aa4f-b08f8afff80a" forHTTPHeaderField:@"session_key"];
[request addValue:@"0" forHTTPHeaderField:@"resume_key"];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
            uploadTaskWithStreamedRequest:request
            progress:^(NSProgress * _Nonnull uploadProgress) {
              // This is not called back on the main queue.
              // You are responsible for dispatching to the main queue for UI updates
              dispatch_async(dispatch_get_main_queue(), ^{
                //Update the progress view
                [_progressView setProgress:uploadProgress.fractionCompleted];
              });
            }
            completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
              if (error) {
                NSLog(@"Error: %@", error);
              } else {
                NSLog(@"%@ %@", response, responseObject);
              }
            }];

[uploadTask resume];
}
</code>```

Is this is how I should add the headers to the MutableURLRequest?

```<code>NSLocalizedDescription = Request failed: unsupported media type (415)}
</code>```

I am currently getting an error like above.

答:
I suggest you to write the code like these,</p>

```<code>func apiRequest(method:String, urlMethod:String, parametersDictionary:NSMutableDictionary, success:@escaping successDictionaryBlock, failure: @escaping failBlockErrorMessage){
        let requestUrl = @“www.requestUrl”

        let headerString = "\("Bearer") \(request Token)”
        let headers: HTTPHeaders = [
            "Authorization": headerString,

            ]

        Alamofire.request(requestUrl, method: .post, parameters: (parametersDictionary as NSDictionary) as? Parameters , encoding: JSONEncoding.default, headers: headers).responseJSON { response in

            if(response.result.error == nil){

                if((response.response?.statusCode)! < 500){

                    if(response.response?.statusCode == 200){

                        if let JSON = response.result.value {

                            let dict = JSON as! NSDictionary

                            let status :Bool = dict["status"] as! Bool

                            if(status){
                                success(dict)

                            }else{
                                failure(dict["message"] as! String)
                            }

                        }
                    }else{
                        failure("Something went wrong please try again")
                    }
                }else{
                    failure("Something went wrong please try again")
                }
            }
        }

    }
</code>```

Body:
I am confused with adding headers in 'AFNetworking 3.0'. In the previous version, there is function known as RequestSerializer. How can I add specific headers to a Mutable Request?

{
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

 NSString *path = [[NSBundle mainBundle] pathForResource:@"uploadedImage_3" ofType:@"jpg"];
[formData appendPartWithFileURL:[NSURL fileURLWithPath:path] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
}
error:nil];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request addValue:@"8b10056e-59e6-4d2b-aa4f-b08f8afff80a" forHTTPHeaderField:@"session_key"];
[request addValue:@"0" forHTTPHeaderField:@"resume_key"];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
            uploadTaskWithStreamedRequest:request
            progress:^(NSProgress * _Nonnull uploadProgress) {
              // This is not called back on the main queue.
              // You are responsible for dispatching to the main queue for UI updates
              dispatch_async(dispatch_get_main_queue(), ^{
                //Update the progress view
                [_progressView setProgress:uploadProgress.fractionCompleted];
              });
            }
            completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
              if (error) {
                NSLog(@"Error: %@", error);
              } else {
                NSLog(@"%@ %@", response, responseObject);
              }
            }];

[uploadTask resume];
}

Is this is how I should add the headers to the MutableURLRequest?

NSLocalizedDescription = Request failed: unsupported media type (415)}

I am currently getting an error like above.

Body:
I suggest you to write the code like these,

func apiRequest(method:String, urlMethod:String, parametersDictionary:NSMutableDictionary, success:@escaping successDictionaryBlock, failure: @escaping failBlockErrorMessage){
        let requestUrl = @“www.requestUrl”

        let headerString = "\("Bearer") \(request Token)”
        let headers: HTTPHeaders = [
            "Authorization": headerString,

            ]

        Alamofire.request(requestUrl, method: .post, parameters: (parametersDictionary as NSDictionary) as? Parameters , encoding: JSONEncoding.default, headers: headers).responseJSON { response in

            if(response.result.error == nil){

                if((response.response?.statusCode)! < 500){

                    if(response.response?.statusCode == 200){

                        if let JSON = response.result.value {

                            let dict = JSON as! NSDictionary

                            let status :Bool = dict["status"] as! Bool

                            if(status){
                                success(dict)

                            }else{
                                failure(dict["message"] as! String)
                            }

                        }
                    }else{
                        failure("Something went wrong please try again")
                    }
                }else{
                    failure("Something went wrong please try again")
                }
            }
        }

    }


来源: stackexchange

问:
Why occur Internal server error in my ajax query?
I want to pass some value to server and it has to return one string.

Jquery version

```<code> <script src="js/jquery-3.1.1.js"></script>
</code>```

Here is my code:

```<code> $('#btnSaveFile').click(function () {
    var fileName = $('#txtFileName').val();
    alert(fileName);
    $.ajax({
        url: 'ReportTotalSalesPivot.aspx/getFileExistOrNot',
        method: 'GET',      //method or type ?
        contentType: 'application/json',
        data: '{fileName:' + fileName +'}',  //UPDATED Line
        dataType: 'json',
        success: function (data) {
            alert('success');
            alert(data.d.exist);
        },
        error: function (error) {
            alert('fail');
            alert(error);
        }
    });
});
</code>```

Aspx code

```<code>    [WebMethod]
    public static string getFileExistOrNot(string fileName)
    {
        string cs = ConfigurationManager.ConnectionStrings["HQWebMatajer13"].ConnectionString;
        using (SqlConnection con = new SqlConnection(cs))
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "select ReportData FROM [HQWebMatajer].[dbo].[ReportSave] where Userfilename=@UserFileName  and ReportName=@ReportName";
            cmd.Parameters.AddWithValue("@UserFileName", fileName);
            cmd.Parameters.AddWithValue("@ReportName", "TotalSales");
            con.Open();
            var data = cmd.ExecuteScalar();
            if (data != null)
            {
                string exist = "dataExist";
                return exist;
            }
            else
            {
                string exist = "notExist";
                return exist;
            }
        }
    }
</code>```

Error Msg
GET http://localhost:55047/ReportTotalSalesPivot.aspx/getFileExistOrNot?fileName:www} 500 (Internal Server Error)

ExceptionType:"System.InvalidOperationException"

Message:"An attempt was made to call the method 'getFileExistOrNot' using a GET request, which is not allowed."

StackTrace:"   at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)
↵   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)".

I think this error it occurs in server side. But I don't know what is that

Updated

Error Message:"Invalid web service call, missing value for parameter:'fileName'."

答:
After one day I found What was my mistake.

This is the answer

```<code>data:'{fileName:"'+fileName+'"}'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to pass some value to server and it has to return one string.

Jquery version

Here is my code:

 $('#btnSaveFile').click(function () {
    var fileName = $('#txtFileName').val();
    alert(fileName);
    $.ajax({
        url: 'ReportTotalSalesPivot.aspx/getFileExistOrNot',
        method: 'GET',      //method or type ?
        contentType: 'application/json',
        data: '{fileName:' + fileName +'}',  //UPDATED Line
        dataType: 'json',
        success: function (data) {
            alert('success');
            alert(data.d.exist);
        },
        error: function (error) {
            alert('fail');
            alert(error);
        }
    });
});

Aspx code

    [WebMethod]
    public static string getFileExistOrNot(string fileName)
    {
        string cs = ConfigurationManager.ConnectionStrings["HQWebMatajer13"].ConnectionString;
        using (SqlConnection con = new SqlConnection(cs))
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "select ReportData FROM [HQWebMatajer].[dbo].[ReportSave] where Userfilename=@UserFileName  and ReportName=@ReportName";
            cmd.Parameters.AddWithValue("@UserFileName", fileName);
            cmd.Parameters.AddWithValue("@ReportName", "TotalSales");
            con.Open();
            var data = cmd.ExecuteScalar();
            if (data != null)
            {
                string exist = "dataExist";
                return exist;
            }
            else
            {
                string exist = "notExist";
                return exist;
            }
        }
    }

Error Msg
GET http://localhost:55047/ReportTotalSalesPivot.aspx/getFileExistOrNot?fileName:www} 500 (Internal Server Error)

ExceptionType:"System.InvalidOperationException"

Message:"An attempt was made to call the method 'getFileExistOrNot' using a GET request, which is not allowed."

StackTrace:"   at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)
↵   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)".

I think this error it occurs in server side. But I don't know what is that

Updated

Error Message:"Invalid web service call, missing value for parameter:'fileName'."

Body:
After one day I found What was my mistake.

This is the answer

data:'{fileName:"'+fileName+'"}'


问:
How do hashCode() and identityHashCode() work at the back end?
How do Object.hashCode() and System.identityHashCode() work at the back end? Does identityHashCode() return the reference of the object? Does hashCode() depend on the content or address of the object?

What is the difference between hashCode() and identityHashCode()?

答:
identityHashCode

public static int identityHashCode(Object x)

Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object's class overrides hashCode(). The hash code for the null reference is zero.

See [Java docs]

So if someone has overridden hashCode() method in its class but still want the default hashCode() value which would have been returned by Object hashCode() then use System.identityHashCode()

So, hashCode() internally calls System.identityHashCode() as long as you are not overriding it in you class, if you override hashCode() it will call your implementation.

ContentLicense: CC BY-SA 4.0


问:
gets a output as [Ljava.lang.Object;@1d4481
i am trying to print set of months and dates to a colum of a table.. it shows {Ljava.lang.Object;@1d4481 eror.. but when i try to print days to the rows it works fine.. i searched stackover thread and found similar qustion also, it says object type something..
here is my table properties

enter image description here

here is my code

```<code>    Calendar calendar = Calendar.getInstance();
    //System.out.println("The current date is : " + calendar.getTime());
    System.out.println("The current date is : " + calendar.getTime());

    calendar.set(1995, 10, 2);
    for(int i=0; i<2 ; i=i+1){
    calendar.add(Calendar.DATE, 1);
    //System.out.println(" Dates later: " + calendar.getTime());
    System.out.println(" Dates later: " + calendar.get(Calendar.MONTH)+"/"+calendar.get(Calendar.DATE));

    //System.out.println(" Dates later: " + Arrays.toString(calendar.get(Calendar.MONTH).toArray())+"/"+Arrays.toString(calendar.get(Calendar.DATE).toArray()));

    SimpleDateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd");
    String date = dFormat.format(jDateChooser1.getDate());
    DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
    //model.addRow(new Object[]{calendar});

     //model.addRow(new Object[]{calendar.get(Calendar.MONTH)+"/"+calendar.get(Calendar.DATE)});
     model.addColumn(new Object[]{calendar.get(Calendar.MONTH)+"/"+calendar.get(Calendar.DATE)});
    }
</code>```

答:
You can try by putting as a row like : model.addRow(); and by this method pass the String array with all column values.

Please refer the link: What is the easiest way to display the contents of an ArrayList of Objects in a JTable?

Body:
i am trying to print set of months and dates to a colum of a table.. it shows {Ljava.lang.Object;@1d4481 eror.. but when i try to print days to the rows it works fine.. i searched stackover thread and found similar qustion also, it says object type something..
here is my table properties

enter image description here

here is my code

    Calendar calendar = Calendar.getInstance();
    //System.out.println("The current date is : " + calendar.getTime());
    System.out.println("The current date is : " + calendar.getTime());

    calendar.set(1995, 10, 2);
    for(int i=0; i<2 ; i=i+1){
    calendar.add(Calendar.DATE, 1);
    //System.out.println(" Dates later: " + calendar.getTime());
    System.out.println(" Dates later: " + calendar.get(Calendar.MONTH)+"/"+calendar.get(Calendar.DATE));

    //System.out.println(" Dates later: " + Arrays.toString(calendar.get(Calendar.MONTH).toArray())+"/"+Arrays.toString(calendar.get(Calendar.DATE).toArray()));

    SimpleDateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd");
    String date = dFormat.format(jDateChooser1.getDate());
    DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
    //model.addRow(new Object[]{calendar});

     //model.addRow(new Object[]{calendar.get(Calendar.MONTH)+"/"+calendar.get(Calendar.DATE)});
     model.addColumn(new Object[]{calendar.get(Calendar.MONTH)+"/"+calendar.get(Calendar.DATE)});
    }


问:
Retrieve Access Token within a AAD secured Azure Web App
I have an Angular4 Application hosted in an Azure Web App and a .NET core Web API hosted in an Azure API App.

The API is secured with Azure Active Directory. Currently I use ng2-adal to aquire an access token which I inject to the headers to perform my API calls.

Now I try to remove the ng2-adal module and secure my Web App with the Authentication / Authorization feature using the same ClientId (like the API). When I browse to my website I get redirected to the AAD login and after I successfully login, I get redirected to my site. Now I wan't to call the API (that is secured with the same ClientId) within my Web App but can't find a way to retrieve the token.

Is there a way to retrieve the access token within my Angular App in this scenario?
It looks like the token is stored encrypted within the AppServiceAuthSession Cookie:

答:
The AppServiceAuthSession is cookie which is different than a token. In this scenario, you need to modify the config of Azure app to make it acquire the access_token for the web API.

We can use the Resource Explore to modify the settings like below:

1 . locate the angular web app

2 . locate the config->authsettings(resource is the clientId of Azure app which used to protect your apps)

```<code>"additionalLoginParams": [
  "response_type=code id_token",
  "resource=3fa9607b-63cc-4050-82b7-91e44ff1df38"
],
</code>```

3. config the redirect_uri for Azure app like below:
    https://appfei.azurewebsites.net/.auth/login/aad/callback

Then after you login in the angular app, you can get the access_token via the endpoint:
https://appfei.azurewebsites.net/.auth/me

Then we need to protect the web API using the Advanced Azure Active Settings like figure below to enable the access_token could call the web API:

Body:
The AppServiceAuthSession is cookie which is different than a token. In this scenario, you need to modify the config of Azure app to make it acquire the access_token for the web API.

We can use the Resource Explore to modify the settings like below:

1 . locate the angular web app

2 . locate the config->authsettings(resource is the clientId of Azure app which used to protect your apps)

"additionalLoginParams": [
  "response_type=code id_token",
  "resource=3fa9607b-63cc-4050-82b7-91e44ff1df38"
],

3. config the redirect_uri for Azure app like below:
    https://appfei.azurewebsites.net/.auth/login/aad/callback

Then after you login in the angular app, you can get the access_token via the endpoint:
https://appfei.azurewebsites.net/.auth/me

Then we need to protect the web API using the Advanced Azure Active Settings like figure below to enable the access_token could call the web API:


问:
Ansible playbook targeting two groups
I am writing an ansible playbook that upgrades Kubernetes version on the minions.

```<code>- name: Configure and start the Kubernetes Nodes
  hosts: kubernetes-minions
  serial: 1
  tasks:
   - name: backup K8S master files.
      shell: "{{item}}"
      with_items:
        - cp /etc/kubernetes/config /var/tmp/k8s-backup/
        - cp /etc/kubernetes/kubelet /var/tmp/k8s-backup/
   - name: cordon the minion.
      command: kubectl cordon {{ ansible_default_ipv4.interface }}
      delegate_to: kubernetes-master
   - name: Install latest version of Docker on Minion.
      yum: name=kubernetes-1.3.0-0.3.git86dc49a.el7 state=present
   - name: start the kubernetes kubelet
      service: name=kubelet state=restarted enabled=yes
   - name: start the kubernetes kube-proxy
      service: name=kube-proxy state=restarted enabled=yes
   - name: uncordon the minion.
      command: kubectl uncordon {{ ansible_default_ipv4.interface }}
      delegate_to: kubernetes-master
</code>```

My inventory file looks like::

```<code>[kubernetes-masters]
172.29.219.102

[kubernetes-minions]
172.29.219.105
172.29.219.106
172.29.219.107
</code>```

Now I have defined the target group tp be hosts: kubernetes-minions where the actual yum update is supposed to happen but before this step is run on EACH minion, I need to cordon this nodes on the kubernetes-master

Now the problem that I am having is how to tell ansible that for the step of cordon/uncordon , do it on the kubernetes-master node rather than the minion. I tried to use delegate_to: kubernetes-master but seems like its running the step on the minion itself.

EDIT :: The upgrade on the minions will be done sequentially and not in parallel to minimize downtime.

答:
Correct delegate_to indentation (should be on same level as task) and select single master from your group:

hosts:

```<code>[kubernetes-masters]
ku1

[kubernetes-minions]
ku2
ku3
</code>```

playbook:

```<code>---
- hosts: kubernetes-minions
  gather_facts: no
  connection: local
  serial: 1
  tasks:
      - debug: msg="cordon"
        delegate_to: "{{ groups['kubernetes-masters'] | first }}"

      - debug: msg="update minion"

      - debug: msg="uncordon"
        delegate_to: "{{ groups['kubernetes-masters'] | first }}"
</code>```

Title: Ansible playbook targeting two groups

Body:
I am writing an ansible playbook that upgrades Kubernetes version on the minions.

- name: Configure and start the Kubernetes Nodes
  hosts: kubernetes-minions
  serial: 1
  tasks:
   - name: backup K8S master files.
      shell: "{{item}}"
      with_items:
        - cp /etc/kubernetes/config /var/tmp/k8s-backup/
        - cp /etc/kubernetes/kubelet /var/tmp/k8s-backup/
   - name: cordon the minion.
      command: kubectl cordon {{ ansible_default_ipv4.interface }}
      delegate_to: kubernetes-master
   - name: Install latest version of Docker on Minion.
      yum: name=kubernetes-1.3.0-0.3.git86dc49a.el7 state=present
   - name: start the kubernetes kubelet
      service: name=kubelet state=restarted enabled=yes
   - name: start the kubernetes kube-proxy
      service: name=kube-proxy state=restarted enabled=yes
   - name: uncordon the minion.
      command: kubectl uncordon {{ ansible_default_ipv4.interface }}
      delegate_to: kubernetes-master

My inventory file looks like::

[kubernetes-masters]
172.29.219.102

[kubernetes-minions]
172.29.219.105
172.29.219.106
172.29.219.107

Now I have defined the target group tp be hosts: kubernetes-minions where the actual yum update is supposed to happen but before this step is run on EACH minion, I need to cordon this nodes on the kubernetes-master

Now the problem that I am having is how to tell ansible that for the step of cordon/uncordon , do it on the kubernetes-master node rather than the minion. I tried to use delegate_to: kubernetes-master but seems like its running the step on the minion itself.

EDIT :: The upgrade on the minions will be done sequentially and not in parallel to minimize downtime.

Body:
Correct delegate_to indentation (should be on same level as task) and select single master from your group:

hosts:

[kubernetes-masters]
ku1

[kubernetes-minions]
ku2
ku3

playbook:

---
- hosts: kubernetes-minions
  gather_facts: no
  connection: local
  serial: 1
  tasks:
      - debug: msg="cordon"
        delegate_to: "{{ groups['kubernetes-masters'] | first }}"

      - debug: msg="update minion"

      - debug: msg="uncordon"
        delegate_to: "{{ groups['kubernetes-masters'] | first }}"


问:
How do I calculate the date six months from the current date using the datetime Python module?
I am using the datetime Python module.  I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?

The reason I want to generate a date 6 months from the current date is to produce a review date.  If the user enters data into the system it will have a review date of 6 months from the date they entered the data.

答:
given that your datetime variable is called date:</p>

```<code>date=datetime.datetime(year=date.year+int((date.month+6)/12),
                       month=(date.month+6)%13 + (1 if (date.month +
                       months>12) else 0), day=date.day)
</code>```

OwnerDisplayName: Eef

LastEditorDisplayName: Eef

Body:
given that your datetime variable is called date:

date=datetime.datetime(year=date.year+int((date.month+6)/12),
                       month=(date.month+6)%13 + (1 if (date.month +
                       months>12) else 0), day=date.day)


问:
Escaping values with apostrophes for MySQL insert
I am trying to create some SQL insert statements and a few variables have names like the following:

"Aamma's Pastries"

I want to escape the quote (') as I am adding the value into the MySQL database. How do I do that with PHP?

答:
There is this function that you can use that escapes all characters that you need, here is a code example in php</p>

```<code><?php
$str = "Is your name O'reilly?";

// Outputs: Is your name O\'reilly?
echo addslashes($str);
?>
</code>```

Body:
There is this function that you can use that escapes all characters that you need, here is a code example in php

<?php
$str = "Is your name O'reilly?";

// Outputs: Is your name O\'reilly?
echo addslashes($str);
?>

ContentLicense: CC BY-SA 2.5


问:
ADB server version (36) doesn't match this client (39); killing
After installing the Android O preview on a test device my ADB stopped working and started giving me this error.

```<code>adb server version (36) doesn't match this client (39); killing...
adb E 03-27 08:01:55  2925 147690 usb_osx.cpp:333] Could not open interface: e00002c5
adb E 03-27 08:01:55  2925 147690 usb_osx.cpp:294] Could not find device interface
error: could not install *smartsocket* listener: Address already in use
ADB server didn't ACK
* failed to start daemon *
error: cannot connect to daemon
</code>```

The only answers I have come across on this issue referred to Genymotion being out of sync with ADB but I don’t use Genymotion. Any help would be greatly appreciated. I have already wiped and reinstalled Android Studio as well as all of its tools and settings yet seem to still have this issue.

答:
In my case this error occured when I set up my environment adb path as ~/.android-sdk/platform-tools (which happens when e.g. android-platform-tools is installed via homebrew), which version was 36, but Android Studio project has Android SDK next path ~/Library/Android/sdk which adb version was 39.

I have changed my PATH to platform-tools to ~/Library/Android/sdk/platform-tools and error was solved

Body:
After installing the Android O preview on a test device my ADB stopped working and started giving me this error.

adb server version (36) doesn't match this client (39); killing...
adb E 03-27 08:01:55  2925 147690 usb_osx.cpp:333] Could not open interface: e00002c5
adb E 03-27 08:01:55  2925 147690 usb_osx.cpp:294] Could not find device interface
error: could not install *smartsocket* listener: Address already in use
ADB server didn't ACK
* failed to start daemon *
error: cannot connect to daemon

The only answers I have come across on this issue referred to Genymotion being out of sync with ADB but I don’t use Genymotion. Any help would be greatly appreciated. I have already wiped and reinstalled Android Studio as well as all of its tools and settings yet seem to still have this issue.


问:
How to list images in a folder using a combo box or select specific items using browse in web page?
Im creating a data entry form, i would like to give them the option to select an image from a specific directory, in which they can select one image.
now i have some image in one directory, i want to know how can i show them to the user.

Please help

答:
You would need to use a server-side language to read the contents of a directory (PHP, for instance). There are many ways of doing this with PHP.

See http://php.net/manual/en/function.readdir.php


问:
how to split and push into an array from server json response
```<code>var jvar = '{"name":"sumit","age":"33"}';
var stdata = JSON.parse(jvar);

console.log( stdata.name ); //gives sumit
 but when i'm  give the variable value like jvar
var jvar = '{"name":"sumit"},{"age":"33"}';// my json response look like this
var stdata = JSON.parse(jvar);

console.log( stdata.name );
</code>```

its not working

please help

答:
According to JSON syntax curly braces hold objects and square brackets hold arrays. In your code, ypu have two different JSON object and they are not embraced by square brackets. It seems your server json response is inaccurate. Your code should look like:</p>

```<code>var jvar = '[{"name":"sumit"},{"age":"33"}]';
var stdata = JSON.parse(jvar);

var resultArray = [];
resultArray.push(jvar);

console.log(resultArray);
</code>```

Body:
var jvar = '{"name":"sumit","age":"33"}';
var stdata = JSON.parse(jvar);

console.log( stdata.name ); //gives sumit
 but when i'm  give the variable value like jvar
var jvar = '{"name":"sumit"},{"age":"33"}';// my json response look like this
var stdata = JSON.parse(jvar);

console.log( stdata.name );

its not working

please help

Body:
According to JSON syntax curly braces hold objects and square brackets hold arrays. In your code, ypu have two different JSON object and they are not embraced by square brackets. It seems your server json response is inaccurate. Your code should look like:

var jvar = '[{"name":"sumit"},{"age":"33"}]';
var stdata = JSON.parse(jvar);

var resultArray = [];
resultArray.push(jvar);

console.log(resultArray);


问:
Horizontal scroll on table doesn't work on iOS Safari
I'm writing a React app, and I can't get a horizontal scroll on my table working on iOS Safari only. It seems to work on everything else.

My JS file

```<code><div className={styles.parent}>
  <div className={styles.wrapper}>
    <table className={styles.table}>...</table>
  </div>
<div>
</code>```

My CSS

```<code>.parent {
  width: 100%;
  overflow-x: hidden;
}

.wrapper {
  position: relative;
}
.table {
  background: transparent;
  border-spacing: 12px 0;
  min-width: 1em;
  display: block;
  overflow-x: auto;
  max-width: none;
  -webkit-overflow-scrolling: touch !important;
}
</code>```

答:
Please try this one i hope it wil helpful to you.

```<code>.parent {
  width: 100%;
  overflow-x: auto;
}
</code>```

Thanks

Body:
I'm writing a React app, and I can't get a horizontal scroll on my table working on iOS Safari only. It seems to work on everything else.

My JS file

...

My CSS

.parent {
  width: 100%;
  overflow-x: hidden;
}

.wrapper {
  position: relative;
}
.table {
  background: transparent;
  border-spacing: 12px 0;
  min-width: 1em;
  display: block;
  overflow-x: auto;
  max-width: none;
  -webkit-overflow-scrolling: touch !important;
}

Body:
Please try this one i hope it wil helpful to you.

.parent {
  width: 100%;
  overflow-x: auto;
}

Thanks


问:
Issue deploying ASP.NET application, having MSAL and OWIN middleware
I have a web application in which, I have used Microsoft Authentication layer and custom OWIN middleware, this application is to integrate Microsoft Office Unified API's. All works great while the app is in development mode and development server.

But when it is deployed on local IIS or any other IIS server, it throws an error. The issue is when i try to log in after successfully crossing OWIN authentication. The next step is loading of API in async way. I face this issue while the code attempts to access: GetMyFilesAndFolders and GetUsers API.
There comes and error which states:

Access to the path 'C:\Windows\system32\config\systemprofile' is denied.

It tried a lot but no luck why this error is coming.

Any help will be highly appreciated.

You can get one reference https://graph.microsoft.io/en-us/docs
[enter image description here][1]

答: Issue has been solved as this was in the assembly code itself and not the issue of custom code. It has been resolved in the new Version of Carrot Search lingo 3G.</p>


问:
How do I change the color of the tab bar for one view controller?
I have a bar tint of white in app delegate for my tab bar, but I need it to be clear on one of the selected indexes. I add the below code to the view controller that needs to be clear, but it stays clear. How do I have it so this only applies to one tab.</p>

```<code>let tabBar = self.tabBarController?.tabBar
tabBar?.barTintColor = UIColor.clear
tabBar?.backgroundImage = UIImage()
tabBar?.shadowImage = UIImage()
</code>```

答:
Try this. Set UIColor.clear on one tab and a different color on other tab.</p>

```<code>let tabBar = self.tabBarController?.tabBar
let tabBarItems = tabBar?.items
if(tabBar?.selectedItem == tabBarItems?[0])
{
    tabBar?.barTintColor = UIColor.clear
}
else
{
    tabBar?.barTintColor = UIColor.red
}
</code>```

Body:
I have a bar tint of white in app delegate for my tab bar, but I need it to be clear on one of the selected indexes. I add the below code to the view controller that needs to be clear, but it stays clear. How do I have it so this only applies to one tab.

let tabBar = self.tabBarController?.tabBar
tabBar?.barTintColor = UIColor.clear
tabBar?.backgroundImage = UIImage()
tabBar?.shadowImage = UIImage()

Body:
Try this. Set UIColor.clear on one tab and a different color on other tab.

let tabBar = self.tabBarController?.tabBar
let tabBarItems = tabBar?.items
if(tabBar?.selectedItem == tabBarItems?[0])
{
    tabBar?.barTintColor = UIColor.clear
}
else
{
    tabBar?.barTintColor = UIColor.red
}


问:
Google maps not showing in bootstrap page
I am embedding a google map in web page based on Bootstrap css.
Here follows the code in which he id for the map-canvas is used.

```<code><div class="container-fluid">
        <div class="row" style="height:100%;">
            <div class="col-sm-3 col-md-2 sidebar">
                <ul class="nav nav-sidebar">
                    <li class="active"><a href="#">Overview</a></li>

                </ul>
            </div>
            <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main" style="height:100%; width:100%;">

                test
                <div style="height:100%; width:100%;">
                <input id="pac-input" class="controls" type="text" placeholder="Search Box">
                <div id="map-canvas" style="height:100%">s</div>
                </div>

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

After the page is loaded a javacript function is invoked which get the id of the map-canvas and substitute it with the map retrieved from Google.
The problem is that the map is not showing and I guess it depends on some issue related to the width or height of the different containers. How should I fix it?

here is a piece of the javascript

```<code>var map;
function initialize() {
    var markers = [];
    var mapOptions = {
        center : new google.maps.LatLng(43.77, 11.24),
        zoom : 4,
        scrollwheel : false,
        mapTypeId : google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById("map-canvas"),
            mapOptions);
    console.log("test");
    console.log(map);

}

google.maps.event.addDomListener(window, 'load', initialize);
</code>```

[upate]
Changed like this:

```<code><div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main" style="height:100%; width:100%;">

                <div class="row" style="100px;">
                <div style="height:100%; width:100%;">
                <div id="map-canvas">s</div>
                </div>
                </div>
            </div>
</div>
</code>```

But it doesn't work

答:
Set the "min-height" by this div will reserve space, you need to adjust min-height as per your layout.</p>

```<code>#map {
    min-height: 500px;
    width: 100%;
    height:100%
}

<div class="col-md-7">
   <div id="map"></div>
</div>
</code>```

Body:
I am embedding a google map in web page based on Bootstrap css.
Here follows the code in which he id for the map-canvas is used.

Overview

                test

                <input id="pac-input" class="controls" type="text" placeholder="Search Box">

s

After the page is loaded a javacript function is invoked which get the id of the map-canvas and substitute it with the map retrieved from Google.
The problem is that the map is not showing and I guess it depends on some issue related to the width or height of the different containers. How should I fix it?

here is a piece of the javascript

var map;
function initialize() {
    var markers = [];
    var mapOptions = {
        center : new google.maps.LatLng(43.77, 11.24),
        zoom : 4,
        scrollwheel : false,
        mapTypeId : google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById("map-canvas"),
            mapOptions);
    console.log("test");
    console.log(map);

}

google.maps.event.addDomListener(window, 'load', initialize);

[upate]
Changed like this:

s

But it doesn't work

Body:
Set the "min-height" by this div will reserve space, you need to adjust min-height as per your layout.

#map {
    min-height: 500px;
    width: 100%;
    height:100%
}

<div class="col-md-7">
   <div id="map"></div>
</div>


问:
Help with a simple C programming exercise
I'm new to C programming, having a bit of difficulty with a programming exercise, I'm sure this is simple for anyone who knows C, unfortunately you have to play by the rules of the exercise.

Here's the exercise:

Have a program request the user to
  enter an uppercase letter. Use nested
  loops to produce a pyramid pattern
  like this:

```<code>    A

   ABA

  ABCBA

 ABCDCBA

ABCDEDCBA
</code>```

The pattern should extend to the
  character entered. For example, the
  preceding pattern would result from an
  input value of E. Hint: Use an outer
  loop to handle the rows. Use three
  inner loops in a row, one to handle
  the spaces, one for printing letters
  in ascending order, and one for
  printing letters in descending order.

So I got this far:

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

int main(void) {

 int rows;
 int spaces;

 char asc;
 char desc;
 char input;

 printf("Please enter an uppercase letter: ");
 scanf("%c", &input);

 for (rows = 'A'; rows <= input; rows++) {
  for (spaces = input; spaces > rows; spaces--) {
   printf(" ");
  }
  for (asc = 'A'; asc <= rows; asc++) {
   printf("%c", asc);
  }
  for (desc = asc - 2; desc >= rows; desc--) {
   printf("%c", desc);
  }
  printf("\n");
 }
 return 0;
}
</code>```

答:
You're very close:

```<code>for (desc = asc - 2; desc >= 'A'; desc--) {
</code>```

Note that after the second inner loop, asc is rows + 1.  You're then initializing desc to rows - 1.  You should be able to see why >= rows is wrong, and will result in no iterations.

The correct condition is simply >= 'A'.

Body:
I'm new to C programming, having a bit of difficulty with a programming exercise, I'm sure this is simple for anyone who knows C, unfortunately you have to play by the rules of the exercise.

Here's the exercise:

Have a program request the user to
  enter an uppercase letter. Use nested
  loops to produce a pyramid pattern
  like this:

    A

   ABA

  ABCBA

 ABCDCBA

ABCDEDCBA

The pattern should extend to the
  character entered. For example, the
  preceding pattern would result from an
  input value of E. Hint: Use an outer
  loop to handle the rows. Use three
  inner loops in a row, one to handle
  the spaces, one for printing letters
  in ascending order, and one for
  printing letters in descending order.

So I got this far:

#include <stdio.h>

int main(void) {

 int rows;
 int spaces;

 char asc;
 char desc;
 char input;

 printf("Please enter an uppercase letter: ");
 scanf("%c", &input);

 for (rows = 'A'; rows <= input; rows++) {
  for (spaces = input; spaces > rows; spaces--) {
   printf(" ");
  }
  for (asc = 'A'; asc <= rows; asc++) {
   printf("%c", asc);
  }
  for (desc = asc - 2; desc >= rows; desc--) {
   printf("%c", desc);
  }
  printf("\n");
 }
 return 0;
}

Body:
You're very close:

for (desc = asc - 2; desc >= 'A'; desc--) {

Note that after the second inner loop, asc is rows + 1.  You're then initializing desc to rows - 1.  You should be able to see why >= rows is wrong, and will result in no iterations.

The correct condition is simply >= 'A'.


问:
Decoding audio data of Mediarecorder is failed on chrome
I using MediaRecorder to record microphone. The default format of MediaRecorder in chrome is video/webm. Here is short example:

```<code>navigator.mediaDevices.getUserMedia({audio: true,video: false})
        .then(function(stream) {
            var recordedChunks = [];
            var recorder = new MediaRecorder(stream);
            recorder.start(10);

            recorder.ondataavailable = function (event) {
                if (event.data.size > 0) {
                    recordedChunks.push(event.data);
                } else {
                    // ...
                }
            }

            setTimeout(function(){
                recorder.stop();
                var blob = new Blob(recordedChunks, {
                  "type": recordedChunks[0].type
                });

                var blobUrl = URL.createObjectURL(blob);

                var context = new AudioContext();
                var request = new XMLHttpRequest();
                request.open("GET", blobUrl, true);
                request.responseType = "arraybuffer";

                request.onload = function () {
                context.decodeAudioData(
                    request.response,
                    function (buffer) {
                        if (!buffer) {
                            alert("buffer is empty!");
                        }

                        var dataArray = buffer.getChannelData(0);

                        //process channel data...

                        context.close();
                    },
                    function (error) {
                    alert(error);
                    }
                );
            };

            request.send();

            }, 3000);

        })
        .catch(function(error) {
          console.log('error: ' + error);
        });
</code>```

This code is trow error of "Uncaught (in promise) DOMException: Unable to decode audio data" on context.decodeAudioData in chrome only.

What is wrong here and how can i fix it in chrome?

Here is working example in plunker: plunker

答:
Ok... There is no fix for the issue. This is a chrome bug and you can see it here

The fix of decoding audio from MediaRecorder will be available on chrome version 58. I already tested it on 58-beta and it works.

Body:
I using MediaRecorder to record microphone. The default format of MediaRecorder in chrome is video/webm. Here is short example:

navigator.mediaDevices.getUserMedia({audio: true,video: false})
        .then(function(stream) {
            var recordedChunks = [];
            var recorder = new MediaRecorder(stream);
            recorder.start(10);

            recorder.ondataavailable = function (event) {
                if (event.data.size > 0) {
                    recordedChunks.push(event.data);
                } else {
                    // ...
                }
            }

            setTimeout(function(){
                recorder.stop();
                var blob = new Blob(recordedChunks, {
                  "type": recordedChunks[0].type
                });

                var blobUrl = URL.createObjectURL(blob);

                var context = new AudioContext();
                var request = new XMLHttpRequest();
                request.open("GET", blobUrl, true);
                request.responseType = "arraybuffer";

                request.onload = function () {
                context.decodeAudioData(
                    request.response,
                    function (buffer) {
                        if (!buffer) {
                            alert("buffer is empty!");
                        }

                        var dataArray = buffer.getChannelData(0);

                        //process channel data...

                        context.close();
                    },
                    function (error) {
                    alert(error);
                    }
                );
            };

            request.send();

            }, 3000);

        })
        .catch(function(error) {
          console.log('error: ' + error);
        });

This code is trow error of "Uncaught (in promise) DOMException: Unable to decode audio data" on context.decodeAudioData in chrome only.

What is wrong here and how can i fix it in chrome?

Here is working example in plunker: plunker


问:
Status bar style bug with UIImagePickerController
I have my view controllers with the [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent]; method in AppDelegate.m. and ViewController based status bar apparence to "NO" in plist.

All works fine, but at a moment in app, user have to take picture or browse one from the library, and all works fine at that stage.

But after picking the image in the library, the status bar come back to black color and that the same for the followings view controllers...

Does anyone could help me for this ?

答:
It works like a charm for swift3 write in viewWillAppear :

```<code>func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {

        UIApplication.shared.setStatusBarStyle(.lightContent, animated: false)
    }
</code>```

Body:
It works like a charm for swift3 write in viewWillAppear :

func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {

        UIApplication.shared.setStatusBarStyle(.lightContent, animated: false)
    }


问:
Notice: Undefined index: when trying to submit form with a null array
Good day, could anybody be willing to explain this notice everytime I submit the form. This is my code below:

```<code><form action="" method="post" name="f">
<TABLE id="dataTable" border="1">
<thead>
        <tr>
            <td></td>
            <td>Product Name</td>
            <td>Model</td>
            <td>Description</td>
        </tr>
    </thead>
<tbody>

</tbody>
</TABLE>
<br>

<input type="text" name="ProductNme" id="item" >
<input type="text" name="ProductNme" id="price" >
<input type="text" name="ProductNme" id="qty" >

<input type="submit" name="submit" value="Submit">

<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />

<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
</code>```

```<code><?php

if($_POST['submit']) {

    $dbC = new imsFunction();

    if ($_POST['item'] == null) {
        echo 'No Data';
    } else {
        foreach ($_POST['item'] as $key => $value) {

            $item = $_POST["item"][$key];
            $price = $_POST["price"][$key];
            $qty = $_POST["qty"][$key];

                $sql = $dbC->qryExec('Insert Into tbl_test (item,price,quant) Values (?, ?, ?)', [$item, $price, $qty]);
                //$sql = mysql_query("insert into your_table_name values ('','$item', '$price', '$qty')");
            }
        }
    }
}
</code>```

?>

This is the javascript code to add the data to the table rows.

```<code>function addRow(tableID) {

    var enteredItem = $("#item").val();
    var enteredPrice = $("#price").val();
    var enteredQty= $("#qty").val();

    if (!enteredItem) {
        alert("Please entere item name!");
    } else {
        var table = document.getElementById(tableID);

        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);

        var cell1 = row.insertCell(0);
        var element1 = document.createElement("input");
        element1.type = "checkbox";
        element1.name="chkbox[]";
        cell1.appendChild(element1);

        var cell2 = row.insertCell(1);
        cell2.innerHTML = "<input type='text' name='item[]' value='"+enteredItem+"' readonly />";

        var cell3 = row.insertCell(2);
        cell3.innerHTML = "<input type='text'  name='price[]' value='"+enteredPrice+"' readonly />";

        var cell4 = row.insertCell(3);
        cell4.innerHTML = "<input type='text'  name='qty[]' value='"+enteredQty+"' readonly />";

        document.getElementById('item').value='';
    }
}
</code>```

The input was name like 'item[]'. what I want to do is to catch error if the user submit button without adding data first. But what happen is, it gives out a Notice that Undefined index: item in the foreach loop.

答:
When testing for incoming data, always assume the worst. In this case, the test $_POST['item']==null may fail if it hasn’t been set in the first place.

The safer approach is:

```<code>if(isset($_POST['item']) && is_array($_POST['item'])) {

}
</code>```

The second part of the test is just in case.

By the way, if you do test specifically for a null value you should use === to distinguish it from other falsy values.

Body:
Good day, could anybody be willing to explain this notice everytime I submit the form. This is my code below:

<form action="" method="post" name="f">

            Product Name
            Model
            Description

<input type="text" name="ProductNme" id="item" >
<input type="text" name="ProductNme" id="price" >
<input type="text" name="ProductNme" id="qty" >

<input type="submit" name="submit" value="Submit">

<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />

<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />

<?php

if($_POST['submit']) {

    $dbC = new imsFunction();

    if ($_POST['item'] == null) {
        echo 'No Data';
    } else {
        foreach ($_POST['item'] as $key => $value) {

            $item = $_POST["item"][$key];
            $price = $_POST["price"][$key];
            $qty = $_POST["qty"][$key];

                $sql = $dbC->qryExec('Insert Into tbl_test (item,price,quant) Values (?, ?, ?)', [$item, $price, $qty]);
                //$sql = mysql_query("insert into your_table_name values ('','$item', '$price', '$qty')");
            }
        }
    }
}

?>

This is the javascript code to add the data to the table rows.

function addRow(tableID) {

    var enteredItem = $("#item").val();
    var enteredPrice = $("#price").val();
    var enteredQty= $("#qty").val();

    if (!enteredItem) {
        alert("Please entere item name!");
    } else {
        var table = document.getElementById(tableID);

        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);

        var cell1 = row.insertCell(0);
        var element1 = document.createElement("input");
        element1.type = "checkbox";
        element1.name="chkbox[]";
        cell1.appendChild(element1);

        var cell2 = row.insertCell(1);
        cell2.innerHTML = "<input type='text' name='item[]' value='"+enteredItem+"' readonly />";

        var cell3 = row.insertCell(2);
        cell3.innerHTML = "<input type='text'  name='price[]' value='"+enteredPrice+"' readonly />";

        var cell4 = row.insertCell(3);
        cell4.innerHTML = "<input type='text'  name='qty[]' value='"+enteredQty+"' readonly />";

        document.getElementById('item').value='';
    }
}

The input was name like 'item[]'. what I want to do is to catch error if the user submit button without adding data first. But what happen is, it gives out a Notice that Undefined index: item in the foreach loop.

Body:
When testing for incoming data, always assume the worst. In this case, the test $_POST['item']==null may fail if it hasn’t been set in the first place.

The safer approach is:

if(isset($_POST['item']) && is_array($_POST['item'])) {

}

The second part of the test is just in case.

By the way, if you do test specifically for a null value you should use === to distinguish it from other falsy values.


问:
How can I put my J2ME application in mobile?
I have created a J2ME application in the NetBeans IDE.
Now I want put/install this application on my mobile device.
How can I do this?</p>

答: First you copy the your project's .jad and .jar files into your mobile. Then click the .jad file in your mobile. Then install it. Then the application is ready for executing in your mobile.</p>


问:
Javascript slideshow that changes background img of an element
trying to make a slideshow that utilizes background-image: property. Here is what I have so far.

```<code><div id="headerContent">
        <div id="rightArrow"></div><!-- end of rightArrow-->
        <div id="leftArrow"></div><!-- end of leftArrow-->
    </div><!-- end of headerContent-->

document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-1.png) no-repeat !important');

document.getElementById("rightArrow").addEventListener("click", changeImageRight);

function changeImageRight () {
    var i = 0;

    if(i == 0) {
        document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-1.png) no-repeat !important');
        i++;
    }
    else if (i == 1)
     {
        document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-2.png) no-repeat !important');
        i++;
    }
    else if (i == 2) {
        document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-3.png) no-repeat !important');
        i++;
    }
    else {
        document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-1.png) no-repeat !important');
        i++;
    }

}
</code>```

as you can see I increment i++ to change the background image. However, as it stands this doesn't do anything, and no image is displayed. And I included the !important attribute because it's the only way I can get the placeholder img to show at the start.

答:
Maybe you should think more like this:</p>

```<code>var changeImageRight = (function(){
  var i = 0;
  return function(){
    // better code than you wrote here
    // now you can expect i to hold scope
  }
}());
</code>```

Body:
trying to make a slideshow that utilizes background-image: property. Here is what I have so far.

document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-1.png) no-repeat !important');

document.getElementById("rightArrow").addEventListener("click", changeImageRight);

function changeImageRight () {
    var i = 0;

    if(i == 0) {
        document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-1.png) no-repeat !important');
        i++;
    }
    else if (i == 1)
     {
        document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-2.png) no-repeat !important');
        i++;
    }
    else if (i == 2) {
        document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-3.png) no-repeat !important');
        i++;
    }
    else {
        document.getElementById("headerContent").setAttribute('style', 'background:url(images/home-header-1.png) no-repeat !important');
        i++;
    }

}

as you can see I increment i++ to change the background image. However, as it stands this doesn't do anything, and no image is displayed. And I included the !important attribute because it's the only way I can get the placeholder img to show at the start.

Body:
Maybe you should think more like this:

var changeImageRight = (function(){
  var i = 0;
  return function(){
    // better code than you wrote here
    // now you can expect i to hold scope
  }
}());


问:
Reset identity seed after deleting records in SQL Server
I have inserted records into a SQL Server database table. The table had a primary key defined and the auto increment identity seed is set to “Yes”. This is done primarily because in SQL Azure, each table has to have a primary key and identity defined.

But since I have to delete some records from the table, the identity seed for those tables will be disturbed and the index column (which is auto-generated with an increment of 1) will get disturbed.

How can I reset the identity column after I deleted the records so that the column has sequence in ascending numerical order?

The identity column is not used as a foreign key anywhere in database.

答:
Reset identity column with new id...</p>

```<code>DECLARE @MAX INT
SELECT @MAX=ISNULL(MAX(Id),0) FROM [TestTable]

DBCC CHECKIDENT ('[TestTable]', RESEED,@MAX)
</code>```

Body:
Reset identity column with new id...

DECLARE @MAX INT
SELECT @MAX=ISNULL(MAX(Id),0) FROM [TestTable]

DBCC CHECKIDENT ('[TestTable]', RESEED,@MAX)


问:
IndexedDB work in Android native app
We've got application to view some specific materials. Among material types there is HTML5 presentation that is shown in WebView widget inside app. And now we need to get detailed information about this view (for example slide show duration, list element pick where it is available, etc).

It is what customer wants - we can't change it.

We decided to use IndexedDB inside HTML5 to store information locally. Now storing works (as I know :) ). Next problem is to get this information by app and it is not solved yet. Unfortunately google didn't help me.

How to get information from IndexedDB file if I know its path? Or do you know another way to transfer data from html to native app?

P.S. Writing custom browser could not be solution.

Update

Found solution to load file from JS. In chrome browser it automatically saves in downloads. In android app I'm setting to WebView object DownloadListener to listen file save event.

Catching save file works perfect. But the url path is looks like blob:file/... and I can't get info from it. Tried using ContentResolver, create File object, replace blob: string with nothing, start ACTION_VIEW intent - nothing helped.

Update

Tried to use DownloadManager and DownloadManager.Request - it throws following exception

```<code>java.lang.IllegalArgumentException: Can only download HTTP/HTTPS URIs: file:///fa4857ad-0e86-454a-a341-123729e9ece0
</code>```

Same with blob:file uri.

答: We decided to use ServerSocket for localhost as web server on device. And then Html sends to it http responce. May be using java script binding as wrote @Michael2 whould be better, but our solution was realized before his post. :-)

Title: IndexedDB work in Android native app

Body:
We've got application to view some specific materials. Among material types there is HTML5 presentation that is shown in WebView widget inside app. And now we need to get detailed information about this view (for example slide show duration, list element pick where it is available, etc).

It is what customer wants - we can't change it.

We decided to use IndexedDB inside HTML5 to store information locally. Now storing works (as I know :) ). Next problem is to get this information by app and it is not solved yet. Unfortunately google didn't help me.

How to get information from IndexedDB file if I know its path? Or do you know another way to transfer data from html to native app?

P.S. Writing custom browser could not be solution.

Update

Found solution to load file from JS. In chrome browser it automatically saves in downloads. In android app I'm setting to WebView object DownloadListener to listen file save event.

Catching save file works perfect. But the url path is looks like blob:file/... and I can't get info from it. Tried using ContentResolver, create File object, replace blob: string with nothing, start ACTION_VIEW intent - nothing helped.

Update

Tried to use DownloadManager and DownloadManager.Request - it throws following exception

java.lang.IllegalArgumentException: Can only download HTTP/HTTPS URIs: file:///fa4857ad-0e86-454a-a341-123729e9ece0

Same with blob:file uri.


问:
Using Protractor with Firefox or IE
Protractor works fine with Chrome, but I cannot get it to start up Firefox or Internet Explorer.

Windows 7

Node v6.9.1

Snippet from package.json:

```<code>"scripts": {
    ....
    "webdriver-manager-update": "webdriver-manager update --ie",
    "protractor": "protractor protractor.conf.js",
    ...
},
...
"devDependencies": {
    ...
    "protractor": "5.1.1",
    ...
}
</code>```

protractor.conf.js:

```<code>exports.config = {
    capabilities: {
      browserName: "firefox" // or "internet explorer"
    },
    specs: ["target/e2e/**/*.e2e-spec.js"]
};
</code>```

After running npm run webdriver-manager-update, <project-home>\node_modules\protractor\node_modules\webdriver-manager\selenium\ contains the files chromedriver_2.28.exe, geckodriver-v0.15.0.exe and IEDriverServer3.3.0.exe.

When running npm run protractor, I get an error:

```<code>[12:29:45] I/launcher - Running 1 instances of WebDriver
[12:29:45] I/local - Starting selenium standalone server...
[12:29:46] I/local - Selenium standalone server started at http://192.168.213.25:62661/wd/hub
[12:29:46] E/launcher - The path to the driver executable must be set by the webdriver.gecko.driver system property
</code>```

(for IE, it refers to the webdriver.ie.driver system property)

After lots of googling, I tried the following fixes:

a) Add <project-home>\node_modules\protractor\node_modules\webdriver-manager\selenium\ to the system environment variable Path. This seems to make no difference.

b) Add the following line to protractor.conf.js:

```<code>seleniumArgs: ["-Dwebdriver.gecko.driver=<project-home>\\node_modules\\protractor\\node_modules\\webdriver-manager\\selenium\\geckodriver-v0.15.0.exe"],
</code>```

Now npm run protractor yields:

```<code>[12:40:35] I/launcher - Running 1 instances of WebDriver
[12:40:35] I/local - Starting selenium standalone server...
[12:40:35] E/launcher - Error: Error: Server terminated early with status 1
    at Error (native)
    at earlyTermination.catch.e (<project-home>\node_modules\selenium-webdriver\remote\index.js:252:52)
    at process._tickCallback (internal/process/next_tick.js:103:7)
[12:40:35] E/launcher - Process exited with error code 100
</code>```

(analoguous behavior with IE)

My search results suggest I am not the only one having this problem, but unfortunately, I did not discover a solution.

答:
You could do this with a localSeleniumStandaloneOpts. The local driver option lets you start the selenium standalone server before the Protractor test, run the test, and finally takes down the server.

Another way you could do this is with webdriver-manager start --ie and the seleniumAddress in your configuration file. In your configuration file, you will set seleniumAddress: "http://127.0.0.1:4444/wd/hub".

A quick note about Firefox. Make sure that you are running the latest gecko driver and Firefox versions. If the Firefox tests are not running properly, look at the gecko driver github issues page.

Another note about Internet Explorer. You should use IE11 and the 32-bit driver version. If you look at the Protractor issues page, iedriver has been identified to have issues. I assume that these issues will not be fixed.

Title: Using Protractor with Firefox or IE

Body:
Protractor works fine with Chrome, but I cannot get it to start up Firefox or Internet Explorer.

Windows 7

Node v6.9.1

Snippet from package.json:

"scripts": {
    ....
    "webdriver-manager-update": "webdriver-manager update --ie",
    "protractor": "protractor protractor.conf.js",
    ...
},
...
"devDependencies": {
    ...
    "protractor": "5.1.1",
    ...
}

protractor.conf.js:

exports.config = {
    capabilities: {
      browserName: "firefox" // or "internet explorer"
    },
    specs: ["target/e2e/**/*.e2e-spec.js"]
};

After running npm run webdriver-manager-update, <project-home>\node_modules\protractor\node_modules\webdriver-manager\selenium\ contains the files chromedriver_2.28.exe, geckodriver-v0.15.0.exe and IEDriverServer3.3.0.exe.

When running npm run protractor, I get an error:

[12:29:45] I/launcher - Running 1 instances of WebDriver
[12:29:45] I/local - Starting selenium standalone server...
[12:29:46] I/local - Selenium standalone server started at http://192.168.213.25:62661/wd/hub
[12:29:46] E/launcher - The path to the driver executable must be set by the webdriver.gecko.driver system property

(for IE, it refers to the webdriver.ie.driver system property)

After lots of googling, I tried the following fixes:

a) Add <project-home>\node_modules\protractor\node_modules\webdriver-manager\selenium\ to the system environment variable Path. This seems to make no difference.

b) Add the following line to protractor.conf.js:

seleniumArgs: ["-Dwebdriver.gecko.driver=<project-home>\\node_modules\\protractor\\node_modules\\webdriver-manager\\selenium\\geckodriver-v0.15.0.exe"],

Now npm run protractor yields:

[12:40:35] I/launcher - Running 1 instances of WebDriver
[12:40:35] I/local - Starting selenium standalone server...
[12:40:35] E/launcher - Error: Error: Server terminated early with status 1
    at Error (native)
    at earlyTermination.catch.e (<project-home>\node_modules\selenium-webdriver\remote\index.js:252:52)
    at process._tickCallback (internal/process/next_tick.js:103:7)
[12:40:35] E/launcher - Process exited with error code 100

(analoguous behavior with IE)

My search results suggest I am not the only one having this problem, but unfortunately, I did not discover a solution.


问:
on register, check if username exists -- capitalization problem
My homefried account registration system proceeds thusly:

complete registration form

check if username already exists - reject/pass

copy data to temp user table, send confirmation email

upon using link in confirmation email, copy data from temp to active user table

The other day a user emailed me to say he was getting the error message "Could not create user."

I couldn't recall ever hearing that, so I dug into my registration code and that error pops out if the query to insert the temp data into the active user table fails.

It failed because his username, which has a unique index in the table, already existed in the active user table... but he had passed the initial existing username check...?

Turned out the name he had tried to register was "User" but there was already a "user" -- so case-insensitivity is coming into play.

Does username exist? query string:

```<code>SELECT username FROM user_basic_data WHERE username='$cleanTempUsername'
</code>```

Confirmed, now insert into active table string:

```<code>INSERT INTO user_basic_data (username, ...) VALUES ('$activeUsername', ...)
</code>```

So the case-sensitivity apparently applies when I run a select statement ("User" != "user") but does not apply when I run an insert.

Capitalization is important to many users, so what's my fix of least resistance from here?

答: You could do php strtolower() or mysql LOWER() to make the input a lowercase name regardless of the input. That way they can use whatever case they want but the database always deals with lowercase usernames. Of course, it means you can only have one username with the name 'user', but it does solve the case insensitivity problem and allow the users to type whatever case they want for their username with just a single change. Just don't do that with the password.</p>

Body:
My homefried account registration system proceeds thusly:

complete registration form

check if username already exists - reject/pass

copy data to temp user table, send confirmation email

upon using link in confirmation email, copy data from temp to active user table

The other day a user emailed me to say he was getting the error message "Could not create user."

I couldn't recall ever hearing that, so I dug into my registration code and that error pops out if the query to insert the temp data into the active user table fails.

It failed because his username, which has a unique index in the table, already existed in the active user table... but he had passed the initial existing username check...?

Turned out the name he had tried to register was "User" but there was already a "user" -- so case-insensitivity is coming into play.

Does username exist? query string:

SELECT username FROM user_basic_data WHERE username='$cleanTempUsername'

Confirmed, now insert into active table string:

INSERT INTO user_basic_data (username, ...) VALUES ('$activeUsername', ...)

So the case-sensitivity apparently applies when I run a select statement ("User" != "user") but does not apply when I run an insert.

Capitalization is important to many users, so what's my fix of least resistance from here?


问:
How to implement blocking ThreadPoolExecutor
I need to implement blocking ThreadPoolExecutor.

This is a very crucial requirement in our enterprise application.

It would do something like if ThreadPoolExecutor.submit() or ThreadPoolExecutor.execute() method blocks until a thread gets freed up for picking up a new task.

But in current implementation ThreadPoolExecutor.submit() and ThreadPoolExecutor.execute() methods throw RejectedExecutionException exception if all pooled threads get busy.

For example following code throws RejectedExecutionException:

```<code>import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class BlockingTPE {
    public static void main(String[] args) {
        ArrayBlockingQueue queue = new ArrayBlockingQueue(3);
        ThreadPoolExecutor tpExe = new ThreadPoolExecutor(1, 3, 30, TimeUnit.SECONDS, queue);
        int numJobs = 50;
        for (int i = 1; i <= numJobs; i++) {
            try {
                tpExe.submit(new WorkerThread(i));
                System.out.println("Added#" + (i));
            } catch (RejectedExecutionException e) {
                e.printStackTrace();
            }
        }
    }
}

class WorkerThread implements Runnable {
    int jobId;

    public WorkerThread(int jobId) {
        this.jobId = jobId;
    }

    public void run() {
        try {
            Thread.sleep(1000);
        }
        catch (Exception excep) {
        }
    }
}
</code>```

答:
As the javadoc of ThreadPoolExecutor states:

Creates a new ThreadPoolExecutor with the given initial parameters and
  default thread factory and rejected execution handler.

The rejected executor handler is an instance of AbortPolicy which will be called if the queue does not accept another task. The behavior as of the javadoc:

Always throws RejectedExecutionException.

Hence the blocking queue does not have any effect for you. I changed your code this way and it runs without any issues:

```<code>public static void main(String[] args) {
    ThreadPoolExecutor executor = new ThreadPoolExecutor(
            1, 3, 30, TimeUnit.SECONDS, new ArrayBlockingQueue(3));
    try {
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        int numJobs = 50;
        for (int i = 1; i <= numJobs; i++) {
            try {
                executor.submit(new WorkerThread(i));
                System.out.println("Added#" + (i));
            } catch (RejectedExecutionException e) {
                e.printStackTrace();
            }
        }
    } finally {
        executor.shutdown();
    }
}
</code>```

The decision you have to make is:

use an unbound queue to support all delayed tasks. For example LinkedBlockingQueue.

use a bound queue and let the current thread execute the task which does not fit into the full queue. For example see the code I posted along my answer.

discard tasks if the bounded queue is full. For example use ThreadPoolExecutor.DiscardPolicy as rejected execution handler.

Body:
I need to implement blocking ThreadPoolExecutor.

This is a very crucial requirement in our enterprise application.

It would do something like if ThreadPoolExecutor.submit() or ThreadPoolExecutor.execute() method blocks until a thread gets freed up for picking up a new task.

But in current implementation ThreadPoolExecutor.submit() and ThreadPoolExecutor.execute() methods throw RejectedExecutionException exception if all pooled threads get busy.

For example following code throws RejectedExecutionException:

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class BlockingTPE {
    public static void main(String[] args) {
        ArrayBlockingQueue queue = new ArrayBlockingQueue(3);
        ThreadPoolExecutor tpExe = new ThreadPoolExecutor(1, 3, 30, TimeUnit.SECONDS, queue);
        int numJobs = 50;
        for (int i = 1; i <= numJobs; i++) {
            try {
                tpExe.submit(new WorkerThread(i));
                System.out.println("Added#" + (i));
            } catch (RejectedExecutionException e) {
                e.printStackTrace();
            }
        }
    }
}

class WorkerThread implements Runnable {
    int jobId;

    public WorkerThread(int jobId) {
        this.jobId = jobId;
    }

    public void run() {
        try {
            Thread.sleep(1000);
        }
        catch (Exception excep) {
        }
    }
}

Body:
As the javadoc of ThreadPoolExecutor states:

Creates a new ThreadPoolExecutor with the given initial parameters and
  default thread factory and rejected execution handler.

The rejected executor handler is an instance of AbortPolicy which will be called if the queue does not accept another task. The behavior as of the javadoc:

Always throws RejectedExecutionException.

Hence the blocking queue does not have any effect for you. I changed your code this way and it runs without any issues:

public static void main(String[] args) {
    ThreadPoolExecutor executor = new ThreadPoolExecutor(
            1, 3, 30, TimeUnit.SECONDS, new ArrayBlockingQueue(3));
    try {
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        int numJobs = 50;
        for (int i = 1; i <= numJobs; i++) {
            try {
                executor.submit(new WorkerThread(i));
                System.out.println("Added#" + (i));
            } catch (RejectedExecutionException e) {
                e.printStackTrace();
            }
        }
    } finally {
        executor.shutdown();
    }
}

The decision you have to make is:

use an unbound queue to support all delayed tasks. For example LinkedBlockingQueue.

use a bound queue and let the current thread execute the task which does not fit into the full queue. For example see the code I posted along my answer.

discard tasks if the bounded queue is full. For example use ThreadPoolExecutor.DiscardPolicy as rejected execution handler.


问:
I'm getting NoSuchElement exception error
I have shared the below code please let me know the correction

```<code>import org.openqa.selenium.By;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class MyClass {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        /*System.setProperty("webdriver.ie.driver","D:\\Backup\\Documents\\Automation\\drivers\\IEDriverServer.exe");
        InternetExplorerDriver driver = new InternetExplorerDriver();
        driver.get("https://www.google.com");

        WebDriverWait driverWait = new WebDriverWait(driver,50);

        driverWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='lst-ib']"))).click();
        driver.findElementByXPath("//*[@id='lst-ib']").sendKeys("Make My Trip");
        driver.findElementById("_fZl").click();
        driverWait.until(ExpectedConditions.elementToBeClickable(By.linkText("MakeMyTrip, India's No 1 Travel Site | Book Hotels, Flights, Holiday ..."))).click();
        Screenshot S1 = new Screenshot();
        S1.Takescreen();*/
        String username = null;
        String password = null;
        MyClass C1 = new MyClass();
        C1.URLs(username, password);
    }

    public void URLs  (String username, String password) throws InterruptedException
    {

        System.setProperty("webdriver.ie.driver","D:\\Backup\\Documents\\Automation\\drivers\\IEDriverServer.exe");
        InternetExplorerDriver driver = new InternetExplorerDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://google.com");
        driver.findElement(By.className("lst lst-tbb sbibps")).sendKeys("irctc");
        driver.findElement(By.id("_fZl")).click();
        Thread.sleep(10000);
        driver.findElement(By.linkText("IRCTC Next Generation eTicketing System")).click();
        username = driver.findElement(By.id("usernameId")).getTagName();
        password = driver.findElement(By.className("loginPassword")).getTagName();
        System.out.println(username);
        System.out.println(password);
    }
}
</code>```

Error :

Exception in thread "main" org.openqa.selenium.NoSuchElementException:
  Unable to find element with class name == lst lst-tbb sbibps (WARNING:
  The server did not provide any stacktrace information) Command
  duration or timeout: 10.45 seconds

答:
Use following:</p>

```<code>driver.findElement(By.name("q")).sendKeys("irctc");
</code>```

Body:
I have shared the below code please let me know the correction

import org.openqa.selenium.By;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class MyClass {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub
        /*System.setProperty("webdriver.ie.driver","D:\\Backup\\Documents\\Automation\\drivers\\IEDriverServer.exe");
        InternetExplorerDriver driver = new InternetExplorerDriver();
        driver.get("https://www.google.com");

        WebDriverWait driverWait = new WebDriverWait(driver,50);

        driverWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='lst-ib']"))).click();
        driver.findElementByXPath("//*[@id='lst-ib']").sendKeys("Make My Trip");
        driver.findElementById("_fZl").click();
        driverWait.until(ExpectedConditions.elementToBeClickable(By.linkText("MakeMyTrip, India's No 1 Travel Site | Book Hotels, Flights, Holiday ..."))).click();
        Screenshot S1 = new Screenshot();
        S1.Takescreen();*/
        String username = null;
        String password = null;
        MyClass C1 = new MyClass();
        C1.URLs(username, password);
    }

    public void URLs  (String username, String password) throws InterruptedException
    {

        System.setProperty("webdriver.ie.driver","D:\\Backup\\Documents\\Automation\\drivers\\IEDriverServer.exe");
        InternetExplorerDriver driver = new InternetExplorerDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://google.com");
        driver.findElement(By.className("lst lst-tbb sbibps")).sendKeys("irctc");
        driver.findElement(By.id("_fZl")).click();
        Thread.sleep(10000);
        driver.findElement(By.linkText("IRCTC Next Generation eTicketing System")).click();
        username = driver.findElement(By.id("usernameId")).getTagName();
        password = driver.findElement(By.className("loginPassword")).getTagName();
        System.out.println(username);
        System.out.println(password);
    }
}

Error :

Exception in thread "main" org.openqa.selenium.NoSuchElementException:
  Unable to find element with class name == lst lst-tbb sbibps (WARNING:
  The server did not provide any stacktrace information) Command
  duration or timeout: 10.45 seconds

Body:
Use following:

driver.findElement(By.name("q")).sendKeys("irctc");


问:
Set UIImageView using URL
I am setting image in UIImageView using:

```<code>[self.imageView setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:[UIImage imageNamed:@"random_image"]];
</code>```

I am able to see the image on phone as expected.

However, if I use the method without placeholder argument

```<code>[self.imageView setImageWithURL:[NSURL URLWithString:urlString]];
</code>```

OR pass the placeholderImage as nil

```<code>[self.imageView setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:nil];
</code>```

then the image is not set and my imageView is blank. I understand that placeholder image is for "representing the current state of the asset suitable for temporarily displaying in your extension’s UI.".

I don't understand how its absence should impact me the way it is impacting. Any pointers?

答:
i hope these code will help u....</p>

```<code>dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
    dispatch_async(queue, ^{

        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:
                                                 [NSURL URLWithString:@“image URL”]]];
        dispatch_sync(dispatch_get_main_queue(), ^{

                [[cell myimage] setImage:image];

            }
         });
    });
</code>```

Title: Set UIImageView using URL

Body:
I am setting image in UIImageView using:

[self.imageView setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:[UIImage imageNamed:@"random_image"]];

I am able to see the image on phone as expected.

However, if I use the method without placeholder argument

[self.imageView setImageWithURL:[NSURL URLWithString:urlString]];

OR pass the placeholderImage as nil

[self.imageView setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:nil];

then the image is not set and my imageView is blank. I understand that placeholder image is for "representing the current state of the asset suitable for temporarily displaying in your extension’s UI.".

I don't understand how its absence should impact me the way it is impacting. Any pointers?

Body:
i hope these code will help u....

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
    dispatch_async(queue, ^{

        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:
                                                 [NSURL URLWithString:@“image URL”]]];
        dispatch_sync(dispatch_get_main_queue(), ^{

                [[cell myimage] setImage:image];

            }
         });
    });


问:
SAPUI5 : JSONModel is not a constructor
I have an SAPUI5 app with 2 views. When I try navigate from the first view to the second view with an router it throws this error:

"Uncaught TypeError: JSONModel is not a constructor(…)"

The problem is I have to consume the content of the JSON to fill a table and with this error it is still empty

In a similar case/application my code runs without a problem, so I would be happy if someone can  read my code if there are some errors...

Main.view.xml

```<code><mvc:View controllerName="App.controller.Main" xmlns:html="http://www.w3.org/1999/xhtml" xmlns:mvc="sap.ui.core.mvc"
displayBlock="true" xmlns="sap.m">
<App>
    <pages>
        <Page>
            <content>
                <Table id="paramTable" items="{/callbackData}" width="auto" class="sapUiResponsiveMargin">
                    <columns>
                        <Column>
                            <Label text="Parameter"></Label>
                        </Column>
                        <Column width="10%">
                            <Label text="CurrentVal"></Label>
                        </Column>
                        <Column width="10%">
                            <Label text="TargetVal"></Label>
                        </Column>
                        <Column width="30%">
                            <Label text="Description"></Label>
                        </Column>
                    </columns>
                    <items>
                        <ColumnListItem>
                            <cells>
                                <ObjectIdentifier title="{key}"></ObjectIdentifier>
                            </cells>
                            <Text text="{currentVal}"></Text>
                            <Text text="{operator} {targetVal}"></Text>
                        </ColumnListItem>
                    </items>
                </Table>
            </content>
        </Page>
    </pages>
</App>
</code>```

Main.controller.js

```<code>sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/ui/model/json/JSONModel"
], function(Controller , JSONModel) {
"use strict";

return Controller.extend("App.controller.Main", {

    onInit : function() {

        this.getView().setModel(new JSONModel({
            callbackData: []
        }));

    },

    setTableData : function() {
        var here = this;
        $.ajax({
            url : '../../test.xsjs',
            type : "GET",
            success : function(data) {
                here.getView().getModel().setProperty("/callbackData", data);
            }
        });
    }
});
});
</code>```

Thanks in advance!!!

答:
```<code>var oModel = new JSONModel({
                  callbackData: []
                 });

this.getView().setModel(oModel);
</code>```

Title: SAPUI5 : JSONModel is not a constructor

Body:
I have an SAPUI5 app with 2 views. When I try navigate from the first view to the second view with an router it throws this error:

"Uncaught TypeError: JSONModel is not a constructor(…)"

The problem is I have to consume the content of the JSON to fill a table and with this error it is still empty

In a similar case/application my code runs without a problem, so I would be happy if someone can  read my code if there are some errors...

Main.view.xml

<mvc:View controllerName="App.controller.Main" xmlns:html="http://www.w3.org/1999/xhtml" xmlns:mvc="sap.ui.core.mvc"
displayBlock="true" xmlns="sap.m">
<App>
    <pages>
        <Page>
            <content>

                    <columns>
                        <Column>

                        </Column>
                        <Column width="10%">

                        </Column>
                        <Column width="10%">

                        </Column>
                        <Column width="30%">

                        </Column>
                    </columns>
                    <items>
                        <ColumnListItem>
                            <cells>
                                <ObjectIdentifier title="{key}"></ObjectIdentifier>
                            </cells>
                            <Text text="{currentVal}"></Text>
                            <Text text="{operator} {targetVal}"></Text>
                        </ColumnListItem>
                    </items>

            </content>
        </Page>
    </pages>
</App>

Main.controller.js

sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/ui/model/json/JSONModel"
], function(Controller , JSONModel) {
"use strict";

return Controller.extend("App.controller.Main", {

    onInit : function() {

        this.getView().setModel(new JSONModel({
            callbackData: []
        }));

    },

    setTableData : function() {
        var here = this;
        $.ajax({
            url : '../../test.xsjs',
            type : "GET",
            success : function(data) {
                here.getView().getModel().setProperty("/callbackData", data);
            }
        });
    }
});
});

Thanks in advance!!!


问:
Replace For Loop with Numpy Vectorized Operation
In the code below, I have a simple for-loop that I'd like to replace with, hopefully, a faster vectorized numpy operation.

```<code>import numpy as np

b = np.array([9,8100,-60,7], dtype=np.float64)
a = np.array([584,-11,23,79,1001,0,-19], dtype=np.float64)
m = 3
n = b.shape[0]
l = n-m+1
k = a.shape[0]-m+1

QT = np.array([-85224., 181461., 580047., 8108811., 10149.])
QT_first = QT.copy()

out = [None] * l
for i in range(1, l):
    QT[1:] = QT[:k-1] - b[i-1]*a[:k-1] + b[i-1+m]*a[-(k-1):]
    QT[0] = QT_first[i]

    # Update: Use this QT to do something with the ith element of array x
    # As i updates in each iteration, QT changes
    out[i] = np.argmin((QT + b_mean[i] * m) / (b_stddev[i] * m * a_stddev))

return out
</code>```

I need a solution that is general enough to take on much longer arrays. Note that QT depends on the m and the length of b and will always be provided.

How can I replace the for-loop with a numpy vectorized operation so that it is faster?

Update

I modified the original code to more clearly demonstrate why a convolution does not solve my problem. Convolve only gives me the final QT but I actually need to use the intermediate QT values for another calculation before updating it for the iteration of the for-loop.

答:
I haven't studied this in enough detail to know exactly what it's doing - b[i-1]*a[:k-1] + b[i-1+m]*a[-(k-1):].  But I suspect it can be written without an i loop.  Some sort of -b[slice1]*a[slice2] + b[slice3]*a[slice4].

The leaves the question of whether

```<code>for i in range(1, l):
    QT[1:] = QT[:k-1] + c[i]
    QT[0] = QT_first[i]
</code>```

is inherently serial and iterative or not.  You probably understand what is going on better than I do.  I'd have to do a few manual loops to get a feel for what is happening.

Body:
In the code below, I have a simple for-loop that I'd like to replace with, hopefully, a faster vectorized numpy operation.

import numpy as np

b = np.array([9,8100,-60,7], dtype=np.float64)
a = np.array([584,-11,23,79,1001,0,-19], dtype=np.float64)
m = 3
n = b.shape[0]
l = n-m+1
k = a.shape[0]-m+1

QT = np.array([-85224., 181461., 580047., 8108811., 10149.])
QT_first = QT.copy()

out = [None] * l
for i in range(1, l):
    QT[1:] = QT[:k-1] - b[i-1]*a[:k-1] + b[i-1+m]*a[-(k-1):]
    QT[0] = QT_first[i]

    # Update: Use this QT to do something with the ith element of array x
    # As i updates in each iteration, QT changes
    out[i] = np.argmin((QT + b_mean[i] * m) / (b_stddev[i] * m * a_stddev))

return out

I need a solution that is general enough to take on much longer arrays. Note that QT depends on the m and the length of b and will always be provided.

How can I replace the for-loop with a numpy vectorized operation so that it is faster?

Update

I modified the original code to more clearly demonstrate why a convolution does not solve my problem. Convolve only gives me the final QT but I actually need to use the intermediate QT values for another calculation before updating it for the iteration of the for-loop.

Body:
I haven't studied this in enough detail to know exactly what it's doing - b[i-1]*a[:k-1] + b[i-1+m]*a[-(k-1):].  But I suspect it can be written without an i loop.  Some sort of -b[slice1]*a[slice2] + b[slice3]*a[slice4].

The leaves the question of whether

for i in range(1, l):
    QT[1:] = QT[:k-1] + c[i]
    QT[0] = QT_first[i]

is inherently serial and iterative or not.  You probably understand what is going on better than I do.  I'd have to do a few manual loops to get a feel for what is happening.


问:
SFTP using public key authentication in ASP.NET
How to send a CSV file to SFTP by using public key authentication?

What is the procedure to do it?

答:
Using SSH.NET library in C#:

const string hostname = "example.com";
const string username = "username";
const string privateKey = @"C:\mykey";
const string sourcePath = @"C:\local\path\file.txt";
const string targetPath = "/remote/path/file.txt";

AuthenticationMethod authenticationMethod =
    new PrivateKeyAuthenticationMethod(username,
        new PrivateKeyFile[]{new PrivateKeyFile(privateKey)});

ConnectionInfo connectionInfo = new ConnectionInfo(hostname, username, authenticationMethod);

using (SftpClient client = new SftpClient(connectionInfo))
{
    client.Connect();

    using (Stream fileStream = new FileStream(sourcePath, FileMode.Open))
    {
        client.UploadFile(fileStream, targetPath, true);
    }

    client.Disconnect();
}
```


问:
How to make full screen java applets?
I am designing a psychology experiment with java applets. I have to make my java applets full screen. What is the best way of doing this and how can I do this.

Since I haven't been using java applets for 3 years(The last time I've used it was for a course homework :) ) I have forgotten most of the concepts. I googled and found that link:
Dani web

But in the method described in above link you have to put a JFrame inside the applet which I have no idea how to do it.

Whatever I need a quick and dirty method b'cause I don't have much time and this is the reason why I asked it here.

Thanx in advance

答: I think you want to use WebStart. You can deploy from a browser but it is otherwise a full blown application. There are a few browserish security restrictions, but, as you're using an Applet currently, I think I can assume they're not a problem.</p>

OwnerDisplayName: holydiver

Title: How to make full screen java applets?

LastEditorDisplayName: cletus

OwnerDisplayName: sblundy


问:
windows environment variable PATH from cache
Whenever we change PATH variable value it will take effect until we do refresh or reboot the server and I suspect that the old PATH variable value is cached somewhere. Is there any way to get that cached PATH variable value to compare against the registry PATH variable value?</p>

答:
The changes are not at all dynamic by nature. When you change environment variables for Windows, then other processes need to be restarted to reflect the new changes.

So you can't expect that all the processes that were using the old path will get the changes just by clearing the cache.

But a reboot will do your work. It is not cached in the windows level, its cached with each application level who ever is reading the value from the PATH variable.

Although, a temp cache is there to hold the value. but still that will be wiped out once you will do a reset.

Hope it gives you the logical set off.


问:
What is the difference between the methods PutExtra and PutExtras in Android?
What is the difference between PutExtra() method and PutExtras() method in Android?

答:
Both methods are Intent by help of

PutExtra()  - we can store any primitive data type directly with (key,value) pair.

And PutExtras() - hold object of Bundle class object .
Bundle class provide us method of specific primitive data type methods to store data in it.

and put Bundle object in PutExtras() method without  key value pair.


问:
Converting XML to C# object
I need to get the OrderID from these xml data:

```<code><?xml version="1.0" encoding="utf-8"?>
<GetOrdersResponse xmlns="urn:ebay:apis:eBLBaseComponents">
  <Timestamp>2015-12-10T16:12:55.184Z</Timestamp>
  <Ack>Success</Ack>
  <Version>967</Version>
  <Build>e967_core_Bundled_5642307_R1</Build>
  <OrderArray>
    <Order>
      <OrderID>865826</OrderID>
      <OrderStatus>Active</OrderStatus>
   </Order>
  </OrderArray>
</GetOrdersResponse>
</code>```

I have tried this one but does not work.

```<code>var xDoc = XDocument.Parse(xmlResult);
var orderElements = xDoc.Elements("GetOrdersResponse").Elements("OrderArray").Elements("Order");
foreach (XElement elem in orderElements)
{
    var orderId = Convert.ToInt32(_xmlHelper.GetChildElementValue(elem, "OrderID"));
}
</code>```

Please advice.

答:
I wouldn't expect xDoc.Elements("GetOrdersResponse") to work, because that is looking in the default namespace, where-as everything here is in "urn:ebay:apis:eBLBaseComponents". As such, you'd need at a minimum to tell it that via XName:

```<code>    var xDoc = XDocument.Parse(xmlResult);
    XNamespace ns = "urn:ebay:apis:eBLBaseComponents";
    var orderElements = xDoc.Elements(ns + "GetOrdersResponse")
            .Elements(ns + "OrderArray").Elements(ns + "Order");
    foreach (XElement elem in orderElements)
    {
        var orderId = (int)elem.Element(ns + "OrderID");
    }
</code>```

(note the use of (int) to do xml-specific casting, too)

However, it may be easier to just use XmlSerializer and let it worry about unscrambling the data.

Title: Converting XML to C# object

Body:
I need to get the OrderID from these xml data:

<?xml version="1.0" encoding="utf-8"?>
<GetOrdersResponse xmlns="urn:ebay:apis:eBLBaseComponents">
  <Timestamp>2015-12-10T16:12:55.184Z</Timestamp>
  <Ack>Success</Ack>
  <Version>967</Version>
  <Build>e967_core_Bundled_5642307_R1</Build>
  <OrderArray>
    <Order>
      <OrderID>865826</OrderID>
      <OrderStatus>Active</OrderStatus>
   </Order>
  </OrderArray>
</GetOrdersResponse>

I have tried this one but does not work.

var xDoc = XDocument.Parse(xmlResult);
var orderElements = xDoc.Elements("GetOrdersResponse").Elements("OrderArray").Elements("Order");
foreach (XElement elem in orderElements)
{
    var orderId = Convert.ToInt32(_xmlHelper.GetChildElementValue(elem, "OrderID"));
}

Please advice.

Body:
I wouldn't expect xDoc.Elements("GetOrdersResponse") to work, because that is looking in the default namespace, where-as everything here is in "urn:ebay:apis:eBLBaseComponents". As such, you'd need at a minimum to tell it that via XName:

    var xDoc = XDocument.Parse(xmlResult);
    XNamespace ns = "urn:ebay:apis:eBLBaseComponents";
    var orderElements = xDoc.Elements(ns + "GetOrdersResponse")
            .Elements(ns + "OrderArray").Elements(ns + "Order");
    foreach (XElement elem in orderElements)
    {
        var orderId = (int)elem.Element(ns + "OrderID");
    }

(note the use of (int) to do xml-specific casting, too)

However, it may be easier to just use XmlSerializer and let it worry about unscrambling the data.