问:
Having Troubles with trying to fix an error I'm receiving from MYSQL
Here is the PHP Code I have that is Causing this Error, I haven't had this error come up before and I searched and looked around before posting and Couldn't find a way to get ride of the error.

PHP (WORKING PHP) :

```<code>   <?php
    require('includes/config.php');
    $username = $_SESSION['username'];

    if($_POST['username'] != $_SESSION['user']['username'])
    {
        // Define our query parameter values
        $query_params = array(
            ':username' => $_POST['username']
        );

        $stmt = $db->prepare("SELECT username FROM members WHERE username = :username");
        $stmt->execute($query_params);

        // Retrieve results (if any)
        if($stmt->rowCount() > 0)
        {
            die("This username is already in use");
        }

        try
        {
            $query_params = array(
                ':username' => $_POST['username'],
                ':last_username' => $username
            );

            // Execute the query
            $stmt = $db->prepare("UPDATE members SET username = :username WHERE username = :last_username");
            $result = $stmt->execute($query_params);
        }
        catch(PDOException $ex)
        {
            // Note: On a production website, you should not output $ex->getMessage().
            // It may provide an attacker with helpful information about your code.
            die("Failed to run query: " . $ex->getMessage());
        }
          }

?>
</code>```

HTML:

```<code>                               <div id="changeusername" class="tab-pane">
                     <h3> Change Your Username : </h3>
  <form  method="post" action="changeusername.php" autocomplete="off">
                    <input type="text" name="username" id="username" class="form-control" placeholder="New Username" autofocus  value="<?php if(isset($error)){ echo $_POST['username']; } ?>" tabindex="1">
                    <br>
                    <input type="password" name="password" id="password" class="form-control" placeholder="Confirm Your Password">
                   <br>
                    <button class="btn btn-theme btn-block" name="submit" type="submit"><i class="fa fa-lock"></i> Change Username</button>

              </form>
</code>```

Error I'm Receiving, after I input Boom2 Which is the New Username and boom1 is the oldd Username:
Failed to run query: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''boom2' WHERE username = 'boom1'' at line 1

答:
I rewrite your php code to error if username exists and correct your update query. Please try it:</p>

```<code><?php
    require('includes/config.php');
    $username = $_SESSION['username'];

    if($_POST['username'] != $_SESSION['user']['username'])
    {
        // Define our query parameter values
        $query_params = array(
            ':username' => $_POST['username']
        );

        $stmt = $db->prepare("SELECT username FROM members WHERE username = :username");
        $stmt->execute($query_params);

        // Retrieve results (if any)
        if($stmt->rowCount() > 0)
        {
            die("This username is already in use");
        }

        try
        {
            $query_params = array(
                ':username' => $_POST['username'],
                ':last_username' => $username
            );

            // Execute the query
            $stmt = $db->prepare("UPDATE members SET username = :username WHERE username = :last_username");
            $result = $stmt->execute($query_params);
        }
        catch(PDOException $ex)
        {
            // Note: On a production website, you should not output $ex->getMessage().
            // It may provide an attacker with helpful information about your code.
            die("Failed to run query: " . $ex->getMessage());
        }

    }

?>
</code>```

Body:
Here is the PHP Code I have that is Causing this Error, I haven't had this error come up before and I searched and looked around before posting and Couldn't find a way to get ride of the error.

PHP (WORKING PHP) :

   <?php
    require('includes/config.php');
    $username = $_SESSION['username'];

    if($_POST['username'] != $_SESSION['user']['username'])
    {
        // Define our query parameter values
        $query_params = array(
            ':username' => $_POST['username']
        );

        $stmt = $db->prepare("SELECT username FROM members WHERE username = :username");
        $stmt->execute($query_params);

        // Retrieve results (if any)
        if($stmt->rowCount() > 0)
        {
            die("This username is already in use");
        }

        try
        {
            $query_params = array(
                ':username' => $_POST['username'],
                ':last_username' => $username
            );

            // Execute the query
            $stmt = $db->prepare("UPDATE members SET username = :username WHERE username = :last_username");
            $result = $stmt->execute($query_params);
        }
        catch(PDOException $ex)
        {
            // Note: On a production website, you should not output $ex->getMessage().
            // It may provide an attacker with helpful information about your code.
            die("Failed to run query: " . $ex->getMessage());
        }
          }

?>

HTML:

 Change Your Username :

  <form  method="post" action="changeusername.php" autocomplete="off">
                    <input type="text" name="username" id="username" class="form-control" placeholder="New Username" autofocus  value="<?php if(isset($error)){ echo $_POST['username']; } ?>" tabindex="1">

                    <input type="password" name="password" id="password" class="form-control" placeholder="Confirm Your Password">

                    <button class="btn btn-theme btn-block" name="submit" type="submit"> Change Username</button>

              </form>

Error I'm Receiving, after I input Boom2 Which is the New Username and boom1 is the oldd Username:
Failed to run query: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''boom2' WHERE username = 'boom1'' at line 1

Body:
I rewrite your php code to error if username exists and correct your update query. Please try it:

<?php
    require('includes/config.php');
    $username = $_SESSION['username'];

    if($_POST['username'] != $_SESSION['user']['username'])
    {
        // Define our query parameter values
        $query_params = array(
            ':username' => $_POST['username']
        );

        $stmt = $db->prepare("SELECT username FROM members WHERE username = :username");
        $stmt->execute($query_params);

        // Retrieve results (if any)
        if($stmt->rowCount() > 0)
        {
            die("This username is already in use");
        }

        try
        {
            $query_params = array(
                ':username' => $_POST['username'],
                ':last_username' => $username
            );

            // Execute the query
            $stmt = $db->prepare("UPDATE members SET username = :username WHERE username = :last_username");
            $result = $stmt->execute($query_params);
        }
        catch(PDOException $ex)
        {
            // Note: On a production website, you should not output $ex->getMessage().
            // It may provide an attacker with helpful information about your code.
            die("Failed to run query: " . $ex->getMessage());
        }

    }

?>


来源: stackexchange

问:
MS Access: How to disable Form autosave and create Save button
I understand that inputting data in a form in MS Access automatically updates the fields in the table. However, how do I disable this feature and instead allow a user to click a "Save" button at the end to update the records? Have been reading online that I need VBA etc. that I have no experience with.</p>

答:
Unfortunately you cannot disable autosaving in forms. As a workaround you can copy data to temporary table, allow user to edit the data as needed and by clicking "Save" button copy changed data back to main table.

Also as a workaround can be used canceling record saving as it described in the answer of @Kostas K. within one form, but in this case you won't be able to change edited record or use any controls outside of edit form if it is a subform, so Save button should be located on the same form as edited data.

ContentLicense: CC BY-SA 3.0


问:
How to uncheck first two checkbox of a group of check box?
I have a list of checkboxes. Checkbox name is CHKBOXPAYANYONE. It has four checkboxes. I want to unchecked first two check box. I am getting the checkbox item by using $("input[name=CHKBOXPAYANYONE]")[0] and $("input[name=CHKBOXPAYANYONE]")[1] . So please suggest how to uncheck them.

答:
Try this:

```<code>$("input[name=CHKBOXPAYANYONE]").eq(0).prop("checked",false);
$("input[name=CHKBOXPAYANYONE]").eq(1).prop("checked",false);
</code>```

OR

```<code>$("input[name=CHKBOXPAYANYONE]:eq(0)").prop("checked",false);
$("input[name=CHKBOXPAYANYONE]:eq(1)").prop("checked",false);
</code>```

Or You can use the loop also.
For more read the :eq selector.

And How to uncheck the checkbox.

Body:
Try this:

$("input[name=CHKBOXPAYANYONE]").eq(0).prop("checked",false);
$("input[name=CHKBOXPAYANYONE]").eq(1).prop("checked",false);

OR

$("input[name=CHKBOXPAYANYONE]:eq(0)").prop("checked",false);
$("input[name=CHKBOXPAYANYONE]:eq(1)").prop("checked",false);

Or You can use the loop also.
For more read the :eq selector.

And How to uncheck the checkbox.


问:
Upload image and text field to server multipart data in iOS objective c
I'm trying to upload the image file and three four text fields and I am receiving all the text fields in the server and I am not getting image name or image on the server. Below is my code:

```<code>- (IBAction)continueb:(id)sender {

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://test.kre8tives.com/barebon/customer_registerapi.php"]];

NSData *imageData = UIImageJPEGRepresentation(self.profilei.image, 1.0);

[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:@"POST"];

NSString *boundary = @"unique-consistent-string";

// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];

// post body
NSMutableData *body = [NSMutableData data];

NSString *test = [NSString stringWithFormat:@"+91%@cache",self.mobilestrp]; //Image name if you want a custom name

// add image data

if (imageData){
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@%@%@", @"Content-Disposition: form-data; name=\"image\"; filename=\"%@",test,@".png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:imageData];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}

//  parameter username
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"customer_name\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"%@",_nametf.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

//  parameter phone
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"phone\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"%@",self.mobilestrp dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

//  parameter email
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"email\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"%@",_emailtf.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

//  parameter dob
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"dob\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"%@",_dobtf.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

// setting the body of the post to the reqeust
[request setHTTPBody:body];

// set the content-length
NSString *postLength = [NSString stringWithFormat:@"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
       NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; // this is json string
    if(data.length > 0)
    {
        NSLog(@ "success:%@",requestReply);
        NSLog(@"data:%@",data);
    }
}];
[self performSegueWithIdentifier:@"b3" sender:self];
}
</code>```

above is my action button in this I am getting four text fields from the user and using image picker I am setting profile picture and that profile picture is stored in UIImage profile and I am not able to figure out what is the problem

below is my log:-

2017-06-07 11:08:34.737734+0530 MenuBar[1485:80176]
  [MobileAssetError:29] Unable to copy asset information from
  https://mesu.apple.com/assets/ for asset type
  com.apple.MobileAsset.TextInput.SpellChecker
      2017-06-07 11:08:56.007 MenuBar[1485:80118] success:/tmp/phpTMFhjM9047038606akshay1318a@gmail,com18-01-1995
      2017-06-07 11:08:59.622 MenuBar[1485:80118] data:<2f746d70 2f706870 544d4668 6a4d3930 34373033 38363036 616b7368 61793133
  31386140 676d6169 6c2c636f 6d31382d 30312d31 393935>

I have changed my PHP code to return whatever I get from the request to check the working of the request and I got the above reply from the request

答:
```<code>// Dictionary that holds post parameters. You can set your post parameters that your server accepts or programmed to accept.
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
[_params setObject:[NSString stringWithString:@"1.0"] forKey:[NSString stringWithString:@"ver"]];
[_params setObject:[NSString stringWithString:@"en"] forKey:[NSString stringWithString:@"lan"]];
[_params setObject:[NSString stringWithFormat:@"%d", userId] forKey:[NSString stringWithString:@"userId"]];
[_params setObject:[NSString stringWithFormat:@"%@",title] forKey:[NSString stringWithString:@"title"]];

// the boundary string : a random string, that will not repeat in post data, to separate post data fields.
NSString *BoundaryConstant = [NSString stringWithString:@"----------V2ymHFg03ehbqgZCaKO6jy"];

// string constant for the post parameter 'file'. My server uses this name: `file`. Your's may differ
NSString* FileParamConstant = [NSString stringWithString:@"file"];

// the server url to which the image (or the media) is uploaded. Use your server url here
NSURL* requestURL = [NSURL URLWithString:@""];

// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:@"POST"];

// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];

// post body
NSMutableData *body = [NSMutableData data];

// add params (all params are strings)
for (NSString *param in _params) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}

// add image data
NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0);
if (imageData) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:imageData];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}

[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];

// setting the body of the post to the reqeust
[request setHTTPBody:body];

// set the content-length
NSString *postLength = [NSString stringWithFormat:@"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

// set URL
[request setURL:requestURL];
</code>```

Body:
I'm trying to upload the image file and three four text fields and I am receiving all the text fields in the server and I am not getting image name or image on the server. Below is my code:

- (IBAction)continueb:(id)sender {

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://test.kre8tives.com/barebon/customer_registerapi.php"]];

NSData *imageData = UIImageJPEGRepresentation(self.profilei.image, 1.0);

[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:@"POST"];

NSString *boundary = @"unique-consistent-string";

// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];

// post body
NSMutableData *body = [NSMutableData data];

NSString *test = [NSString stringWithFormat:@"+91%@cache",self.mobilestrp]; //Image name if you want a custom name

// add image data

if (imageData){
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@%@%@", @"Content-Disposition: form-data; name=\"image\"; filename=\"%@",test,@".png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:imageData];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}

//  parameter username
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"customer_name\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"%@",_nametf.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

//  parameter phone
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"phone\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"%@",self.mobilestrp dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

//  parameter email
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"email\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"%@",_emailtf.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

//  parameter dob
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"dob\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"%@",_dobtf.text dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

// setting the body of the post to the reqeust
[request setHTTPBody:body];

// set the content-length
NSString *postLength = [NSString stringWithFormat:@"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
       NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; // this is json string
    if(data.length > 0)
    {
        NSLog(@ "success:%@",requestReply);
        NSLog(@"data:%@",data);
    }
}];
[self performSegueWithIdentifier:@"b3" sender:self];
}

above is my action button in this I am getting four text fields from the user and using image picker I am setting profile picture and that profile picture is stored in UIImage profile and I am not able to figure out what is the problem

below is my log:-

2017-06-07 11:08:34.737734+0530 MenuBar[1485:80176]
  [MobileAssetError:29] Unable to copy asset information from
  https://mesu.apple.com/assets/ for asset type
  com.apple.MobileAsset.TextInput.SpellChecker
      2017-06-07 11:08:56.007 MenuBar[1485:80118] success:/tmp/phpTMFhjM9047038606akshay1318a@gmail,com18-01-1995
      2017-06-07 11:08:59.622 MenuBar[1485:80118] data:<2f746d70 2f706870 544d4668 6a4d3930 34373033 38363036 616b7368 61793133
  31386140 676d6169 6c2c636f 6d31382d 30312d31 393935>

I have changed my PHP code to return whatever I get from the request to check the working of the request and I got the above reply from the request


问:
Change textview properties programatically from a fragment class
I am relatively new to Android Studio and I am starting to explore more the Android Navigation Drawer activities. I have been trying to change the font type of a textview from a fragment class and I just can't. I have tried many different solutions available here and none of them worked. In the picture, you can see my latest attempt.

In this image you can see the last code I tried to change the font from the fragment class

答:
Create one Class and name it whatever you want, that class will extend TextView, and that class will load the font. And further you can use that font in your xml itself.
Like this:

```<code>public class CustomEditTextGEFlowBook extends android.support.v7.widget.AppCompatEditText {

    public CustomEditTextGEFlowBook(Context context) {
        super(context);if(!isInEditMode())
        setFont(context);
    }

    public CustomEditTextGEFlowBook(Context context, AttributeSet attrs) {
        super(context, attrs);if(!isInEditMode())
        setFont(context);
    }

    public CustomEditTextGEFlowBook(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);if(!isInEditMode())
        setFont(context);
    }

    private void setFont(Context context) {
        Typeface font = Typeface.createFromAsset(getContext().getAssets(),
                "GOTHAM-BOOK.OTF");
        setTypeface(font);
    }
}
</code>```

Now from your xml, use your TextView or EditText like this.
.

```<code><com.packageName.CustomEditTextGEFlowBook
    android:id="@+id/radioOthers"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@null"
    android:hint="Mention the Issue"
    android:maxLength="50" />
</code>```

Body:
Create one Class and name it whatever you want, that class will extend TextView, and that class will load the font. And further you can use that font in your xml itself.
Like this:

public class CustomEditTextGEFlowBook extends android.support.v7.widget.AppCompatEditText {

    public CustomEditTextGEFlowBook(Context context) {
        super(context);if(!isInEditMode())
        setFont(context);
    }

    public CustomEditTextGEFlowBook(Context context, AttributeSet attrs) {
        super(context, attrs);if(!isInEditMode())
        setFont(context);
    }

    public CustomEditTextGEFlowBook(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);if(!isInEditMode())
        setFont(context);
    }

    private void setFont(Context context) {
        Typeface font = Typeface.createFromAsset(getContext().getAssets(),
                "GOTHAM-BOOK.OTF");
        setTypeface(font);
    }
}

Now from your xml, use your TextView or EditText like this.
.

<com.packageName.CustomEditTextGEFlowBook
    android:id="@+id/radioOthers"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@null"
    android:hint="Mention the Issue"
    android:maxLength="50" />


答: Verify whether font relative path is properly mentioned or not. </p>

Title: Change textview properties programatically from a fragment class

Body:
I am relatively new to Android Studio and I am starting to explore more the Android Navigation Drawer activities. I have been trying to change the font type of a textview from a fragment class and I just can't. I have tried many different solutions available here and none of them worked. In the picture, you can see my latest attempt.

In this image you can see the last code I tried to change the font from the fragment class


问:
Unable to Launch RIDE from command prompt
I want to start using the RIDE tool for automation but I am currently unable to launch it from the command prompt. The following are what I have installed.

Python 2.7.11 (32bit)

Wx Python 2.8.12.1(unicode) for Python 2.7

robotframework 3.0.2 (pip installed)

robotframework-ride 1.5.2.1 (pip installed)

When I launch ride.py from cmd, it opens up a word file which has the same ride.py which is installed in the C:\Python27\Scripts folder.

The same setup works on a different machine. I don't understand why in this machine, it opens up a word document instead of launching RIDE

答: Do a right click on ride.py and choose python as default program. </p>


答:
Use the :lt() to select the first 2 elements.

.prop("checked",false) will uncheck the checkbox.

$("input[name=CHKBOXPAYANYONE]:lt(2)").prop("checked",false)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="CHKBOXPAYANYONE" type="checkbox" checked/>
<input name="CHKBOXPAYANYONE" type="checkbox" checked/>
<input name="CHKBOXPAYANYONE" type="checkbox" checked/>
<input name="CHKBOXPAYANYONE" type="checkbox" checked/></code>```

Title: How to uncheck first two checkbox of a group of check box?

Body: I have a list of checkboxes. Checkbox name is CHKBOXPAYANYONE. It has four checkboxes. I want to unchecked first two check box. I am getting the checkbox item by using $("input[name=CHKBOXPAYANYONE]")[0] and $("input[name=CHKBOXPAYANYONE]")[1] . So please suggest how to uncheck them.

Body:
Use the :lt() to select the first 2 elements.

.prop("checked",false) will uncheck the checkbox.

$("input[name=CHKBOXPAYANYONE]:lt(2)").prop("checked",false)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="CHKBOXPAYANYONE" type="checkbox" checked/>
<input name="CHKBOXPAYANYONE" type="checkbox" checked/>
<input name="CHKBOXPAYANYONE" type="checkbox" checked/>
<input name="CHKBOXPAYANYONE" type="checkbox" checked/>


问:
How to use TextField add subview TagView programming by swift?
Sorry I'm beginner.
This is my tagView input Demo(import TagListView).

https://github.com/Bruce9487/TagViewTest

I want to practice tag input. But my constrain looks strange. I don't want tagView to update vertically. And textfield cursor always behind the tagView.How to set constrain of tagView correctly? Thanks.

update: (after I add @hament miglani answer)

答:
There is little mistake, U are not passing frame of the view! Thats why
this condition in TagListView always true

if currentRowTagCount == 0 || currentRowWidth + tagView.frame.width >
  self.frame.width

To solve this you have to pass frame when u are making its object in controller. Showing below:
Add this line of code

textFieldTagView.frame = textField.frame

in ViewController viewDidload method, just above this line
textField.addSubview(textFieldTagView)


问:
how to hide or delete the button on top_right statusBar?
when i use universal links in weixin, the domain appear on the top_right of statusbar, how to hide or delete the button?

enter image description here

答: This feature is used for jumping from one app to another. and Its generate every time when you use [UIApplication openURL:]. Apple not give rights to remove this features to developer. But in future, Apple publicly give access to edit or delete this feature because there are many case in this feature is not suitable.</p>


问:
unable to filter namewise
The query below works fine but I'm unable to search vehicle_name. Like I want to search for vehicle name 31 but when I enter it searches all instead of 31 only. Please help</p>

```<code> SELECT Vehicle_Name
    ,Total_Weight
    ,DATE
    ,bilty_No
FROM harvesting H
INNER JOIN Vehicle V
ON H.Vehicle_ID = V.Vehicle_ID

UNION all

SELECT Vehicle_Name
    ,Total_Weight
    ,DATE
    ,Bilty_No
FROM Blade_Harvesting BH
INNER JOIN Vehicle V
ON BH.Vehicle_ID = V.Vehicle_ID
</code>```

答:
you have to put where condition to your both select statement

```<code>SELECT Vehicle_Name
    ,Total_Weight
    ,DATE
    ,bilty_No
FROM harvesting H
INNER JOIN Vehicle V
ON H.Vehicle_ID = V.Vehicle_ID
where Vehicle_Name like '31%'
UNION all

SELECT Vehicle_Name
    ,Total_Weight
    ,DATE
    ,Bilty_No
FROM Blade_Harvesting BH
INNER JOIN Vehicle V
ON BH.Vehicle_ID = V.Vehicle_ID
where Vehicle_Name like '31%'
</code>```

while sending Vehicle name AS parameter

```<code> SELECT Vehicle_Name
        ,Total_Weight
        ,DATE
        ,bilty_No
    FROM harvesting H
    INNER JOIN Vehicle V
    ON H.Vehicle_ID = V.Vehicle_ID
    where Vehicle_Name = @Vehicle_Name
    UNION all

    SELECT Vehicle_Name
        ,Total_Weight
        ,DATE
        ,Bilty_No
    FROM Blade_Harvesting BH
    INNER JOIN Vehicle V
    ON BH.Vehicle_ID = V.Vehicle_ID
    where Vehicle_Name = @Vehicle_Name
</code>```

Title: unable to filter namewise

Body:
The query below works fine but I'm unable to search vehicle_name. Like I want to search for vehicle name 31 but when I enter it searches all instead of 31 only. Please help

 SELECT Vehicle_Name
    ,Total_Weight
    ,DATE
    ,bilty_No
FROM harvesting H
INNER JOIN Vehicle V
ON H.Vehicle_ID = V.Vehicle_ID

UNION all

SELECT Vehicle_Name
    ,Total_Weight
    ,DATE
    ,Bilty_No
FROM Blade_Harvesting BH
INNER JOIN Vehicle V
ON BH.Vehicle_ID = V.Vehicle_ID

Body:
you have to put where condition to your both select statement

SELECT Vehicle_Name
    ,Total_Weight
    ,DATE
    ,bilty_No
FROM harvesting H
INNER JOIN Vehicle V
ON H.Vehicle_ID = V.Vehicle_ID
where Vehicle_Name like '31%'
UNION all

SELECT Vehicle_Name
    ,Total_Weight
    ,DATE
    ,Bilty_No
FROM Blade_Harvesting BH
INNER JOIN Vehicle V
ON BH.Vehicle_ID = V.Vehicle_ID
where Vehicle_Name like '31%'

while sending Vehicle name AS parameter

 SELECT Vehicle_Name
        ,Total_Weight
        ,DATE
        ,bilty_No
    FROM harvesting H
    INNER JOIN Vehicle V
    ON H.Vehicle_ID = V.Vehicle_ID
    where Vehicle_Name = @Vehicle_Name
    UNION all

    SELECT Vehicle_Name
        ,Total_Weight
        ,DATE
        ,Bilty_No
    FROM Blade_Harvesting BH
    INNER JOIN Vehicle V
    ON BH.Vehicle_ID = V.Vehicle_ID
    where Vehicle_Name = @Vehicle_Name


问:
Whether all shards explain stages are same?
I have tree shard servers and one mongos server. I connect to the mongos server to run some queries. When I look at the explain output from these queries, it always gives me the same number of explain stages for each shard server. I wonder whether I can get a different number of explain execution stages for differen shard server. I have tried to create an index on one shard but not the other two. But it still gives me a same number of stages on explain query. </p>

答:
It is possible to have "SINGLE_SHARD" as a stage
e.g.

```<code>{

 "queryPlanner" : {

    "mongosPlannerVersion" : 1,

    "winningPlan" : {

       "stage" : "SINGLE_SHARD",
</code>```

It means that a single shard was sent to the query (as opposed to when you don't specify a shard key and it has to be sent to multiple shards)

Body:
It is possible to have "SINGLE_SHARD" as a stage
e.g.

{

 "queryPlanner" : {

    "mongosPlannerVersion" : 1,

    "winningPlan" : {

       "stage" : "SINGLE_SHARD",

It means that a single shard was sent to the query (as opposed to when you don't specify a shard key and it has to be sent to multiple shards)


问:
how to fixed undefined offset if array data is not equal to limit declared in forloop
so i have a single row data from my db.. from one id i have

```<code>id |  prescription
1  |  sildenafil  ()      25 mg ---- #60---1X per day    morning/
   |  lanoxin  ()      25 mg ---- #60---1X per day    morning/
   |  caltrate plus (caco3)       ---- #60---1X per day    evening/
</code>```

i use this loop to display the data above. so first after getting the data i use explode to separate those data with '/' at the end.. and then limit the data that is being displayed.

```<code><tbody>
    <?php
    for ($n=0; $n < 10; $n++) { ?>
        <tr>
            <td><?php

      $prescription_array=explode('/',$new_array2[$n]);
            echo $n+1;
            ?>
            </td>
            <td><?php

            for ($i=0; $i < 10; $i++) {
                echo "<font size='5'>".$prescription_array[$i]."</font>";
                $i++;
            }
                ?>
            </td>
        </tr>
    <?php }?>
</tbody>
</code>```

what im trying to achieve here is after getting the data from my data and separate it.. i want to limit the data that is being displayed to 10.
sample if have those 3 data only 3 will be displayed.. but my problem is since i limit the loop into 10 what happen is if my data consist only less than 10 i get an error.. Notice: Undefined offset since the data is less than 10.

is there any better approach to fix this?..

答:
You can break the loop if it exceeds the length

In your case, you can use:

```<code>if($n > count($new_array2) - 1) break;
</code>```

This stops the first loop. You can also check the other loop with:

```<code>if($i > count($prescription_array) - 1) break;
</code>```

Body:
so i have a single row data from my db.. from one id i have

id |  prescription
1  |  sildenafil  ()      25 mg ---- #60---1X per day    morning/
   |  lanoxin  ()      25 mg ---- #60---1X per day    morning/
   |  caltrate plus (caco3)       ---- #60---1X per day    evening/

i use this loop to display the data above. so first after getting the data i use explode to separate those data with '/' at the end.. and then limit the data that is being displayed.

    <?php
    for ($n=0; $n < 10; $n++) { ?>

            <?php

      $prescription_array=explode('/',$new_array2[$n]);
            echo $n+1;
            ?>

            <?php

            for ($i=0; $i < 10; $i++) {
                echo "".$prescription_array[$i]."";
                $i++;
            }
                ?>

    <?php }?>

what im trying to achieve here is after getting the data from my data and separate it.. i want to limit the data that is being displayed to 10.
sample if have those 3 data only 3 will be displayed.. but my problem is since i limit the loop into 10 what happen is if my data consist only less than 10 i get an error.. Notice: Undefined offset since the data is less than 10.

is there any better approach to fix this?..

Body:
You can break the loop if it exceeds the length

In your case, you can use:

if($n > count($new_array2) - 1) break;

This stops the first loop. You can also check the other loop with:

if($i > count($prescription_array) - 1) break;


问:
Alfresco - Want to Change Content store path
I want to change the existing content store path of my Alfresco instance just because it is about to get full. One solution is to move existing content store at another location and change the path in alfresco.global.properties but I want to write new data at another location and read the existing from the current one.</p>

答:
As far as i know, it will be kind of impossible thing in alfresco.First reason would be as below.

Dir Root is having indexes of files.If we devide it, for solr it will be diffucult to manage this things.

There are lot more other reasons as well.

But for solving this in future you can set up content store configuration.You will find details about that in below link.

http://docs.alfresco.com/5.1/concepts/manage-cs-home.html

Specially below one will be more usefull.

http://docs.alfresco.com/5.1/concepts/store-config-fullexample.html

This is available in enterprise version.I don't know 100% about content store, reading full documentation will might solve your problem.

ContentLicense: CC BY-SA 4.0


问:
How can i handle nested queries with promises instead of callback?
how can i do the following with bluebird promises. modules i am using are bluebird, promise-mysql

insert in table A and return a_id

insert records in table B using a_id as foreign key

insert records in table C using a_id as foreign key

now response is send to user that all records are added.

I am using native queries.

答:
I just checked and saw that functions in promise-mysql library return promises. Do you know what that means? You can just chain each and every one of them with .then().

Here is an example:

```<code>var mysql = require('promise-mysql');
var connection;

mysql.createConnection({
    host: 'localhost',
    user: 'sauron',
    password: 'theonetruering',
    database: 'mordor'
}).then(function(conn){
    connection = conn;
});
</code>```

and in your web service:

```<code>return connection.query('insert into a values(. . . . .)')
    .then(function(rows){
        var a_id = rows.insertId;
        return connection.query('insert into b values(. . . . .)')
            .then(function(rows){
                return connection.query('insert into c values(. . . . .)');
            });
    });
</code>```

You can actually chain at the end of the first .then(function(rows){}), but I just wanted to make sure that a_id won't exist out of where you insert into tables b and c.

Body:
I just checked and saw that functions in promise-mysql library return promises. Do you know what that means? You can just chain each and every one of them with .then().

Here is an example:

var mysql = require('promise-mysql');
var connection;

mysql.createConnection({
    host: 'localhost',
    user: 'sauron',
    password: 'theonetruering',
    database: 'mordor'
}).then(function(conn){
    connection = conn;
});

and in your web service:

return connection.query('insert into a values(. . . . .)')
    .then(function(rows){
        var a_id = rows.insertId;
        return connection.query('insert into b values(. . . . .)')
            .then(function(rows){
                return connection.query('insert into c values(. . . . .)');
            });
    });

You can actually chain at the end of the first .then(function(rows){}), but I just wanted to make sure that a_id won't exist out of where you insert into tables b and c.


答:
You can try :</p>

```<code>SELECT     Vehicle_Name,
           Total_Weight,
           DATE,
           bilty_No
FROM      (SELECT      Vehicle_Name,
                       Total_Weight,
                       DATE,
                       bilty_No
           FROM        harvesting H
           INNER JOIN  Vehicle V ON H.Vehicle_ID = V.Vehicle_ID

           UNION ALL

           SELECT      Vehicle_Name,
                       Total_Weight,
                       DATE,
                       Bilty_No
           FROM        Blade_Harvesting BH
           INNER JOIN  Vehicle V ON BH.Vehicle_ID = V.Vehicle_ID
           ) s
Where      s.Vehicle_ID = 31
</code>```

Title: unable to filter namewise

Body:
You can try :

SELECT     Vehicle_Name,
           Total_Weight,
           DATE,
           bilty_No
FROM      (SELECT      Vehicle_Name,
                       Total_Weight,
                       DATE,
                       bilty_No
           FROM        harvesting H
           INNER JOIN  Vehicle V ON H.Vehicle_ID = V.Vehicle_ID

           UNION ALL

           SELECT      Vehicle_Name,
                       Total_Weight,
                       DATE,
                       Bilty_No
           FROM        Blade_Harvesting BH
           INNER JOIN  Vehicle V ON BH.Vehicle_ID = V.Vehicle_ID
           ) s
Where      s.Vehicle_ID = 31


问:
android custom layout doesn't align correctly in gridView
I am having an layout issue where i have a custom layout I use in a gridView in which a checkbox is suppose to align at the bottom right corner of an imageView. The preview of the layout shows it looks correct but when it loads into the gridView it moves the check box to the top left of the imageView. I have tried making the image smaller in the gridView and also removing the spacing in in between objects in the gridview, but to no avail.

here is my custom layout for each item of the gridView

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
    android:id="@+id/imgThumb"
    android:layout_width="100dp"
    android:layout_height="100dp"/>

<CheckBox
    android:id="@+id/chkImage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignEnd="@+id/imgThumb"
    android:layout_alignRight="@+id/imgThumb"
    android:layout_alignBottom="@+id/imgThumb"/>

</RelativeLayout>
</code>```

and here is the gridView layout

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<GridView
    android:id="@+id/grdImages"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:numColumns="3"
    android:verticalSpacing="5dp"
    android:horizontalSpacing="5dp"
    android:columnWidth="90dp"
    android:stretchMode="columnWidth"
    android:gravity="center"/>

<Button
    android:id="@+id/btnSelect"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Select"
    android:layout_marginTop="5dp"/>

</LinearLayout>
</code>```

here is an image of what i would like the item in the gridview to look like, and this is also what the preview shows it will look like Preview

and this is what happens in the actual gridView GridView

答:
The issue occured because you do not set alignment for your ImageView.
Just set alignParentTop=true for ImageView.
Then, align the Checkbox below the ImageView by set its property layout_below point to ImageView's id.

Or, replace RelativeLayout by LinearLayout with orientation is vertical, since you have set ImageView witj fixed size.

Body:
I am having an layout issue where i have a custom layout I use in a gridView in which a checkbox is suppose to align at the bottom right corner of an imageView. The preview of the layout shows it looks correct but when it loads into the gridView it moves the check box to the top left of the imageView. I have tried making the image smaller in the gridView and also removing the spacing in in between objects in the gridview, but to no avail.

here is my custom layout for each item of the gridView

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
    android:id="@+id/imgThumb"
    android:layout_width="100dp"
    android:layout_height="100dp"/>

<CheckBox
    android:id="@+id/chkImage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignEnd="@+id/imgThumb"
    android:layout_alignRight="@+id/imgThumb"
    android:layout_alignBottom="@+id/imgThumb"/>

</RelativeLayout>

and here is the gridView layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<GridView
    android:id="@+id/grdImages"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:numColumns="3"
    android:verticalSpacing="5dp"
    android:horizontalSpacing="5dp"
    android:columnWidth="90dp"
    android:stretchMode="columnWidth"
    android:gravity="center"/>

<Button
    android:id="@+id/btnSelect"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Select"
    android:layout_marginTop="5dp"/>

</LinearLayout>

here is an image of what i would like the item in the gridview to look like, and this is also what the preview shows it will look like Preview

and this is what happens in the actual gridView GridView


问:
How to get file object with ng2-file-upload + angular 2
I want to accomplish upload on file drag:
I am using ng2-file-upload version 1.2.1 with following code snippet:

app.module.ts:

```<code>import { FileUploadModule } from 'ng2-file-upload/ng2-file-upload';
..
imports: [
        FileUploadModule
]
</code>```

component.ts:

```<code>import { FileUploader } from 'ng2-file-upload/ng2-file-upload';

...

class AppXYZComponent{
private uploader: FileUploader = new FileUploader({ url: 'blah.com' });

    public hasBaseDropZoneOver:boolean = false;
    //public hasAnotherDropZoneOver:boolean = false;

    public fileOverBase(e:any):void {
        console.log("hasBaseDropZoneOver", e);
        this.hasBaseDropZoneOver = e;
    }
}
</code>```

app.component.html:

```<code><div class="well" ng2FileDrop [uploader]="uploader" [ngClass]="{'another-file-over-class': hasBaseDropZoneOver}"
             (fileOver)="fileOverBase($event)"
             >
            Drop CSV here
        </div>
</code>```

The function fileOverBase gets successfully called on drag, with event e printed as true. Now How can i get the dragged file's object??

答:
You need to use the afterAddingfile method to get the file object in the ng2-file-upload plugin.</p>

```<code>import { FileUploader } from 'ng2-file-upload/ng2-file-upload';
...

class AppXYZComponent{
public uploader: FileUploader;
public hasBaseDropZoneOver:boolean = false;
//public hasAnotherDropZoneOver:boolean = false;

constructor(){
   this.uploader = new FileUploader({ url: 'blah.com' });
   this.uploader.onAfterAddingFile = (fileItem) => {
                fileItem.withCredentials = false;
                console.log(fileItem); // fileItem is the file object
            };
}
 public fileOverBase(e:any):void {
    console.log("hasBaseDropZoneOver", e);
    this.hasBaseDropZoneOver = e;
  }
}
</code>```

Body:
I want to accomplish upload on file drag:
I am using ng2-file-upload version 1.2.1 with following code snippet:

app.module.ts:

import { FileUploadModule } from 'ng2-file-upload/ng2-file-upload';
..
imports: [
        FileUploadModule
]

component.ts:

import { FileUploader } from 'ng2-file-upload/ng2-file-upload';

...

class AppXYZComponent{
private uploader: FileUploader = new FileUploader({ url: 'blah.com' });

    public hasBaseDropZoneOver:boolean = false;
    //public hasAnotherDropZoneOver:boolean = false;

    public fileOverBase(e:any):void {
        console.log("hasBaseDropZoneOver", e);
        this.hasBaseDropZoneOver = e;
    }
}

app.component.html:

            Drop CSV here

The function fileOverBase gets successfully called on drag, with event e printed as true. Now How can i get the dragged file's object??

Body:
You need to use the afterAddingfile method to get the file object in the ng2-file-upload plugin.

import { FileUploader } from 'ng2-file-upload/ng2-file-upload';
...

class AppXYZComponent{
public uploader: FileUploader;
public hasBaseDropZoneOver:boolean = false;
//public hasAnotherDropZoneOver:boolean = false;

constructor(){
   this.uploader = new FileUploader({ url: 'blah.com' });
   this.uploader.onAfterAddingFile = (fileItem) => {
                fileItem.withCredentials = false;
                console.log(fileItem); // fileItem is the file object
            };
}
 public fileOverBase(e:any):void {
    console.log("hasBaseDropZoneOver", e);
    this.hasBaseDropZoneOver = e;
  }
}


问:
ArrayStoreException:In Generic ArrayList
From the Java Docs of ArrayStoreException

Thrown to indicate that an attempt has been made to store the wrong
  type of object into an array of objects.

To avoid this exception i used generics.But when i ran the following Test program:

```<code>public class Test {
    public static void main(String[] args) {
        Collection<Number> nums = new ArrayList<Number>();
        nums.add(new Integer(1));
        nums.add(new Long(-1));
        Integer[] ints = nums.toArray(new Integer[nums.size()]);

        for (Integer integer : ints) {
            System.out.println(integer);
        }
    }
}
</code>```

I am getting ArrayStoreException as below - Which i am not expecting.

```<code>Exception in thread "main" java.lang.ArrayStoreException
    at java.lang.System.arraycopy(Native Method)
    at java.util.ArrayList.toArray(ArrayList.java:408)
</code>```

Can some one help me understand why is this exception thrown even if my list is of generic type.

答:
Your ArrayList contains a Long. A Long cannot be stored in an Integer array, since Integer is not a super type of Long.

The following will work:

```<code>Number[] ints = nums.toArray(new Number[nums.size()]);

for (Number integer : ints) {
    System.out.println(integer);
}
</code>```

This is clearly stated in the Javadoc of toArray:

Throws:

ArrayStoreException - if the runtime type of the specified array is not a supertype of the runtime type of every element in this collection

Body:
From the Java Docs of ArrayStoreException

Thrown to indicate that an attempt has been made to store the wrong
  type of object into an array of objects.

To avoid this exception i used generics.But when i ran the following Test program:

public class Test {
    public static void main(String[] args) {
        Collection<Number> nums = new ArrayList<Number>();
        nums.add(new Integer(1));
        nums.add(new Long(-1));
        Integer[] ints = nums.toArray(new Integer[nums.size()]);

        for (Integer integer : ints) {
            System.out.println(integer);
        }
    }
}

I am getting ArrayStoreException as below - Which i am not expecting.

Exception in thread "main" java.lang.ArrayStoreException
    at java.lang.System.arraycopy(Native Method)
    at java.util.ArrayList.toArray(ArrayList.java:408)

Can some one help me understand why is this exception thrown even if my list is of generic type.

Body:
Your ArrayList contains a Long. A Long cannot be stored in an Integer array, since Integer is not a super type of Long.

The following will work:

Number[] ints = nums.toArray(new Number[nums.size()]);

for (Number integer : ints) {
    System.out.println(integer);
}

This is clearly stated in the Javadoc of toArray:

Throws:

ArrayStoreException - if the runtime type of the specified array is not a supertype of the runtime type of every element in this collection


问:
How to get specific values of each field using php DOM Script ? for the below format?
I want to get the value of each field like "Delhi" , "Kolkatta".

How can i do this using php DOM Script ?

here is the source of the page to parsed.

```<code><tbody><tr>
<td>Delhi</td>
<td>66.91</td>
</tr>
<tr>
<td>Kolkata</td>
<td>69.52</td>
</tr>
<tr>
<td>Mumbai</td>
<td>78.44</td>
</tr>
<tr>
<td>Chennai</td>
<td>69.93</td>
</tr></tbody>
</code>```

答:
Alternatively you can use simplexml function, please someone correct me if it is wrong way or bad idea

```<code>$xml='<tbody><tr>
<td>Delhi</td>
<td>66.91</td>
</tr>
<tr>
<td>Kolkata</td>
<td>69.52</td>
</tr>
<tr>
<td>Mumbai</td>
<td>78.44</td>
</tr>
<tr>
<td>Chennai</td>
<td>69.93</td>
</tr></tbody> ';
echo "```";
$arr=simplexml_load_string($xml);
$arr_new=array();
$arr1=json_decode(json_encode((array)$arr), TRUE);
foreach($arr1 as $val){
    foreach($val as $k=>$v){
        $arr_new[$val[$k]['td'][0]]=$val[$k]['td'][1];
    }
}
```

<p>Output</p>

```Array
(
    [Delhi] => 66.91
    [Kolkata] => 69.52
    [Mumbai] => 78.44
    [Chennai] => 69.93
)
```

Body:
I want to get the value of each field like "Delhi" , "Kolkatta".

How can i do this using php DOM Script ?

here is the source of the page to parsed.

Delhi
66.91

Kolkata
69.52

Mumbai
78.44

Chennai
69.93

Body:
Alternatively you can use simplexml function, please someone correct me if it is wrong way or bad idea

$xml='<tbody><tr>
<td>Delhi</td>
<td>66.91</td>
</tr>
<tr>
<td>Kolkata</td>
<td>69.52</td>
</tr>
<tr>
<td>Mumbai</td>
<td>78.44</td>
</tr>
<tr>
<td>Chennai</td>
<td>69.93</td>
</tr></tbody> ';
echo "<pre>";
$arr=simplexml_load_string($xml);
$arr_new=array();
$arr1=json_decode(json_encode((array)$arr), TRUE);
foreach($arr1 as $val){
    foreach($val as $k=>$v){
        $arr_new[$val[$k]['td'][0]]=$val[$k]['td'][1];
    }
}

Output

Array
(
    [Delhi] => 66.91
    [Kolkata] => 69.52
    [Mumbai] => 78.44
    [Chennai] => 69.93
)


问:
How to implement such use case by Java Concurrency Lock
In the test case below, the update() method is called outside of the class which in running for every hour by one thread only. But there have multiple threads calling getKey1() and getKey2() at the same time.

So for this use case:

The most important is since getKey1() and getKey2() are calling almost at the same time, we must make sure

if flag is true, update both key1 and key2 and return the new key

if not, get the old key1 and key2

We donot want such case exist: update the key1 and get the old key2, but it's ok to get the old key1 and key2 for few request even we already update it.

```<code>public class Test {

    private Lock lock = new ReentrantLock();

    private AtomicBoolean flag1 = new AtomicBoolean(false);
    private AtomicBoolean flag2 = new AtomicBoolean(false);

    private volatile String key1;
    private volatile String key2;

    public Test(String key1, String key2) {
        this.key1 = key1;
        this.key2 = key2;
    }

    public void update() {
        lock.lock();
        try {
            flag1.compareAndSet(false, true);
            flag2.compareAndSet(false, true);
        } finally {
            lock.unlock();
        }
    }

    public String getKey1() {
        // TODO if the lock is holding... block over here
        if (flag1.get()) {
            // doing something for key 1
            key1 = getFromFile();
            flag1.set(false);
        }
        return key1;
    }

    public String getKey2() {
        // TODO if the lock is holding... block over here
        if (flag2.get()) {
            // doing something for key 1
            key2 = getFromFile();
            flag2.set(false);
        }
        return key1;
    }
}
</code>```

My idea is:

when update() is running, block both getKey1() and getKey2(), waiting to get the update key

when update() is not running, getKey1() and getKey2() should both be ok and return directly.

when calling either getKey1() or getKey2(), I think we do not need to block the update() method.

Anyone have any ideas about the implementation?

答:
Use tryLock()

```<code>public String getKey1() {
  if (lock.tryLock())
  {
    // Got the lock
    try
    {
        // Process record
    }
    finally
    {
        // Make sure to unlock so that we don't cause a deadlock
        lock.unlock();
    }
 }
}
</code>```

If you don't want getKey1() or getKey2() to perform locking. You can use the following approach,

```<code>static boolean isLocked=false;
public void update() {
        lock.lock();
        isLocked = true;
        try {
            flag1.compareAndSet(false, true);
            flag2.compareAndSet(false, true);
        } finally {
            lock.unlock();
            isLocked = false;
        }
    }

    public String getKey1() {
        while(isLocked); #wait till the lock release.
        if (flag1.get()) {
            // doing something for key 1
            key1 = getFromFile();
            flag1.set(false);
        }
        return key1;
    }
</code>```

Ref : how-do-determine-if-an-object-is-locked-synchronized-so-not-to-block-in-java

Body:
In the test case below, the update() method is called outside of the class which in running for every hour by one thread only. But there have multiple threads calling getKey1() and getKey2() at the same time.

So for this use case:

The most important is since getKey1() and getKey2() are calling almost at the same time, we must make sure

if flag is true, update both key1 and key2 and return the new key

if not, get the old key1 and key2

We donot want such case exist: update the key1 and get the old key2, but it's ok to get the old key1 and key2 for few request even we already update it.

public class Test {

    private Lock lock = new ReentrantLock();

    private AtomicBoolean flag1 = new AtomicBoolean(false);
    private AtomicBoolean flag2 = new AtomicBoolean(false);

    private volatile String key1;
    private volatile String key2;

    public Test(String key1, String key2) {
        this.key1 = key1;
        this.key2 = key2;
    }

    public void update() {
        lock.lock();
        try {
            flag1.compareAndSet(false, true);
            flag2.compareAndSet(false, true);
        } finally {
            lock.unlock();
        }
    }

    public String getKey1() {
        // TODO if the lock is holding... block over here
        if (flag1.get()) {
            // doing something for key 1
            key1 = getFromFile();
            flag1.set(false);
        }
        return key1;
    }

    public String getKey2() {
        // TODO if the lock is holding... block over here
        if (flag2.get()) {
            // doing something for key 1
            key2 = getFromFile();
            flag2.set(false);
        }
        return key1;
    }
}

My idea is:

when update() is running, block both getKey1() and getKey2(), waiting to get the update key

when update() is not running, getKey1() and getKey2() should both be ok and return directly.

when calling either getKey1() or getKey2(), I think we do not need to block the update() method.

Anyone have any ideas about the implementation?

Body:
Use tryLock()

public String getKey1() {
  if (lock.tryLock())
  {
    // Got the lock
    try
    {
        // Process record
    }
    finally
    {
        // Make sure to unlock so that we don't cause a deadlock
        lock.unlock();
    }
 }
}

If you don't want getKey1() or getKey2() to perform locking. You can use the following approach,

static boolean isLocked=false;
public void update() {
        lock.lock();
        isLocked = true;
        try {
            flag1.compareAndSet(false, true);
            flag2.compareAndSet(false, true);
        } finally {
            lock.unlock();
            isLocked = false;
        }
    }

    public String getKey1() {
        while(isLocked); #wait till the lock release.
        if (flag1.get()) {
            // doing something for key 1
            key1 = getFromFile();
            flag1.set(false);
        }
        return key1;
    }

Ref : how-do-determine-if-an-object-is-locked-synchronized-so-not-to-block-in-java


问:
String concatenation without strcat in C
I am having trouble concatenating strings in C, without strcat library function. Here is my code

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

int main()
{
  char *a1=(char*)malloc(100);
  strcpy(a1,"Vivek");
  char *b1=(char*)malloc(100);
  strcpy(b1,"Ratnavel");
  int i;
  int len=strlen(a1);

  for(i=0;i<strlen(b1);i++)
  {
     a1[i+len]=b1[i];
  }

  a1[i+len]='\0';
  printf("\n\n A: %s",a1);

  return 0;
}
</code>```

I made corrections to the code. This is working. Now can I do it without strcpy?

答:
You can do it using strcpy() too ;)</p>

```<code>char *a = (char *) malloc(100);
char *b = (char *) malloc(100);

strcpy(a, "abc");               // initializes a
strcpy(b, "def");               // and b

strcpy((a + strlen(a)), b);     // copy b at end of a

printf("%s\n",a);               // will produce: "abcdef"
</code>```

Body:
I am having trouble concatenating strings in C, without strcat library function. Here is my code

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main()
{
  char *a1=(char*)malloc(100);
  strcpy(a1,"Vivek");
  char *b1=(char*)malloc(100);
  strcpy(b1,"Ratnavel");
  int i;
  int len=strlen(a1);

  for(i=0;i<strlen(b1);i++)
  {
     a1[i+len]=b1[i];
  }

  a1[i+len]='\0';
  printf("\n\n A: %s",a1);

  return 0;
}

I made corrections to the code. This is working. Now can I do it without strcpy?

Body:
You can do it using strcpy() too ;)

char *a = (char *) malloc(100);
char *b = (char *) malloc(100);

strcpy(a, "abc");               // initializes a
strcpy(b, "def");               // and b

strcpy((a + strlen(a)), b);     // copy b at end of a

printf("%s\n",a);               // will produce: "abcdef"

ContentLicense: CC BY-SA 2.5


问:
How can I deploy table or view from SQL to AX
How can I deploy table or view from SQL to AX.

答: Tables and views which are created in AX are deployed to SQL but deployment from SQL to AX is not possible.</p>


问:
How to deploy a Spring Boot (Executable Jar) to Azure App Service
The problem is that currently Azure offers support for deployment of a WAR file into Tomcat.  Spring Boot does support deployment via a WAR, however this negates some of the benefits of using Spring Boot.</p>

答: Add web.config under wwwroot folder, in web.config mention your jar name. Once done, upload the required jar to same folder. To upload it via FTP you need to first set the credentials under Credentials blade under AppService in Azure</p>


问:
Triggering a class with its own id with find
I am using a waypoint to trigger specific elements. The div elements below all have the same class, so I am trying to trigger the id and then find the element's class and then `addClass('fadeDisplay').

Initially I tried creating a function for it to reduce the code, but once I could not get '$(this)to work with it, I attempted to do it by writing each specific element, like this$('#section3-box-img1')`.

My class is not adding and the waypoint element is firing in the correct place.

Does anyone see what I am doing wrong?

```<code><div class="section3-box-img" id="section3-box-img1"></div>
<div class="section3-box-img" id="section3-box-img2"></div>
<div class="section3-box-img" id="section3-box-img3"></div>

var section3img = $('.section3-box-img');
$('#section3-box-img1').waypoint(function() {
//section3Fade();
    $('#section3-box-img1').find(section3img).addClass('fadeDisplay');
}, {
    offset: '75%'
});
function section3Fade() {
    $(this).find('.section3-box-img').addClass('fadeDisplay');
}
</code>```

答:
```<code>$("[id^='section3-box-img']").waypoint(function() {
    $(this).addClass('fadeDisplay');
}, {
    offset: '75%'
});
</code>```

Body:
I am using a waypoint to trigger specific elements. The div elements below all have the same class, so I am trying to trigger the id and then find the element's class and then `addClass('fadeDisplay').

Initially I tried creating a function for it to reduce the code, but once I could not get '$(this)to work with it, I attempted to do it by writing each specific element, like this$('#section3-box-img1')`.

My class is not adding and the waypoint element is firing in the correct place.

Does anyone see what I am doing wrong?

var section3img = $('.section3-box-img');
$('#section3-box-img1').waypoint(function() {
//section3Fade();
    $('#section3-box-img1').find(section3img).addClass('fadeDisplay');
}, {
    offset: '75%'
});
function section3Fade() {
    $(this).find('.section3-box-img').addClass('fadeDisplay');
}


问:
What does it mean by "Objects are basic run-time entities in an object-oriented system"?
I recently started learning C++ and came across this sentence in a text book.Can anyone please explain what does this mean with an example. Thanks in advance.     </p>

答: as the objects didn't get the memory space while they are formed i.e. in the source code.These objects gets the memory space at run time i.e. after the formation of .exe(executable file).</p>


问:
How to read divolte-data Kafka channel with Druid-Tranquility (for Superset)?
On a Ubuntu server I set up Divolte Collector to gather clickstream data from websites. The data is being written to a Kafka channel named divolte-data. By setting up a Kafka consumer I can see the data coming in:

```<code>V0:j2ive5p1:QHQbOuiuZFozAVQfKqNWJoNstJhEZE85V0:j2pz3aw7:sDHKs71nHrTB5b_1TkKvWWtQ_rZDrvc2D0:B4aEGBSVgTXgxqB85aj4dGeoFjCqpeEGbannerClickMozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/58.0.3029.96 Chrome/58.0.3029.96 Safari/537.36ChromiumChromium8Google Inc. and contributorsBrowser58.0.3029.96"Personal computer
LinuxCanonical Ltd.
</code>```

Then I would like to visualize the data with Airbnb Superset which has several connectors to common databases including druid.io (which can read Spark).

It seems Divolte is storing data in Kafka in an unstructured way. But apparently it can map the data in a structured way. Should the input data be structured in JSON (like the docs says)?

And then how to read from Druid-Tranquility the data received at divolte-data Kafka channel? I tried changing the channel name in conf examples but this consumer then receives zero message.

答:
The solution I found is I can process Kafka messages in Python, for example with Kafka Python library, or Confluent Kafka Python, and then I will decode the messages with Avro readers.

I thought Avro library was just to read Avro files, but it actually solved the problem of decoding Kafka messages, as follow: I first import the libraries and give the schema file as a parameter and then create a function to decode the message into a dictionary, that I can use in the consumer loop.

```<code>from confluent_kafka import Consumer, KafkaError
from avro.io import DatumReader, BinaryDecoder
import avro.schema

schema = avro.schema.Parse(open("data_sources/EventRecord.avsc").read())
reader = DatumReader(schema)

def decode(msg_value):
    message_bytes = io.BytesIO(msg_value)
    decoder = BinaryDecoder(message_bytes)
    event_dict = reader.read(decoder)
    return event_dict

c = Consumer()
c.subscribe(topic)
running = True
while running:
    msg = c.poll()
    if not msg.error():
        msg_value = msg.value()
        event_dict = decode(msg_value)
        print(event_dict)
    elif msg.error().code() != KafkaError._PARTITION_EOF:
        print(msg.error())
        running = False
</code>```

Body:
On a Ubuntu server I set up Divolte Collector to gather clickstream data from websites. The data is being written to a Kafka channel named divolte-data. By setting up a Kafka consumer I can see the data coming in:

V0:j2ive5p1:QHQbOuiuZFozAVQfKqNWJoNstJhEZE85V0:j2pz3aw7:sDHKs71nHrTB5b_1TkKvWWtQ_rZDrvc2D0:B4aEGBSVgTXgxqB85aj4dGeoFjCqpeEGbannerClickMozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/58.0.3029.96 Chrome/58.0.3029.96 Safari/537.36ChromiumChromium8Google Inc. and contributorsBrowser58.0.3029.96"Personal computer
LinuxCanonical Ltd.

Then I would like to visualize the data with Airbnb Superset which has several connectors to common databases including druid.io (which can read Spark).

It seems Divolte is storing data in Kafka in an unstructured way. But apparently it can map the data in a structured way. Should the input data be structured in JSON (like the docs says)?

And then how to read from Druid-Tranquility the data received at divolte-data Kafka channel? I tried changing the channel name in conf examples but this consumer then receives zero message.

Body:
The solution I found is I can process Kafka messages in Python, for example with Kafka Python library, or Confluent Kafka Python, and then I will decode the messages with Avro readers.

I thought Avro library was just to read Avro files, but it actually solved the problem of decoding Kafka messages, as follow: I first import the libraries and give the schema file as a parameter and then create a function to decode the message into a dictionary, that I can use in the consumer loop.

from confluent_kafka import Consumer, KafkaError
from avro.io import DatumReader, BinaryDecoder
import avro.schema

schema = avro.schema.Parse(open("data_sources/EventRecord.avsc").read())
reader = DatumReader(schema)

def decode(msg_value):
    message_bytes = io.BytesIO(msg_value)
    decoder = BinaryDecoder(message_bytes)
    event_dict = reader.read(decoder)
    return event_dict

c = Consumer()
c.subscribe(topic)
running = True
while running:
    msg = c.poll()
    if not msg.error():
        msg_value = msg.value()
        event_dict = decode(msg_value)
        print(event_dict)
    elif msg.error().code() != KafkaError._PARTITION_EOF:
        print(msg.error())
        running = False


问:
using word2vec with heroku cloud platform
how can i use word2vec with heroku or any other cloud platform. I want to store my trained data set on cloud platform. so that every query can be retrieved through there.</p>

答:
I think you might want to take a look at Floydhub, which is a Deep Learning PaaS (dubbed by its creators as "Heroku for Deep Learning").
Specifically, I think you may want to take a look at this fastText example.

See Stock2Vec for an example of a Word2Vec model trained on Floydhub.


答:
you could use a $count instead of 10 as below:

```<code>$count = (count($prescription_array)<10)?count($prescription_array):10;
</code>```

this will assign 10 to $count if your array has more than 10 elements else it assigns the length of the array to $count.
you can now use $count in the condition for the loops.

and as for the outer loop, you could use a try-catch method.

```<code>try{
//array splitting of $newarray and assignment statement to $prescription_array
}

catch(Exception $e){
break;
}
</code>```

Title: how to fixed undefined offset if array data is not equal to limit declared in forloop

Body:
so i have a single row data from my db.. from one id i have

id |  prescription
1  |  sildenafil  ()      25 mg ---- #60---1X per day    morning/
   |  lanoxin  ()      25 mg ---- #60---1X per day    morning/
   |  caltrate plus (caco3)       ---- #60---1X per day    evening/

i use this loop to display the data above. so first after getting the data i use explode to separate those data with '/' at the end.. and then limit the data that is being displayed.

    <?php
    for ($n=0; $n < 10; $n++) { ?>

            <?php

      $prescription_array=explode('/',$new_array2[$n]);
            echo $n+1;
            ?>

            <?php

            for ($i=0; $i < 10; $i++) {
                echo "".$prescription_array[$i]."";
                $i++;
            }
                ?>

    <?php }?>

what im trying to achieve here is after getting the data from my data and separate it.. i want to limit the data that is being displayed to 10.
sample if have those 3 data only 3 will be displayed.. but my problem is since i limit the loop into 10 what happen is if my data consist only less than 10 i get an error.. Notice: Undefined offset since the data is less than 10.

is there any better approach to fix this?..

Body:
you could use a $count instead of 10 as below:

$count = (count($prescription_array)<10)?count($prescription_array):10;

this will assign 10 to $count if your array has more than 10 elements else it assigns the length of the array to $count.
you can now use $count in the condition for the loops.

and as for the outer loop, you could use a try-catch method.

try{
//array splitting of $newarray and assignment statement to $prescription_array
}

catch(Exception $e){
break;
}


问:
How to make a curl request from this data
As I need to use paypal payout in my project. This is what I got from the official paypal page.https://developer.paypal.com/docs/api/payments.payouts-batch/

```<code>curl -v -X POST https://api.sandbox.paypal.com/v1/payments/payouts \
-H "Content-Type:application/json" \
-H "Authorization: Bearer Access-Token" \
-d '{
  "sender_batch_header": {
  "sender_batch_id": "2014021801",
  "email_subject": "You have a payout!"
  },
  "items": [
  {
    "recipient_type": "EMAIL",
    "amount": {
    "value": "9.87",
    "currency": "USD"
    },
    "note": "Thanks for your patronage!",
    "sender_item_id": "201403140001",
    "receiver": "anybody01@gmail.com"
  },
  {
    "recipient_type": "PHONE",
    "amount": {
    "value": "112.34",
    "currency": "EUR"
    },
    "note": "Thanks for your support!",
    "sender_item_id": "201403140002",
    "receiver": "91-734-234-1234"
  },
  {
    "recipient_type": "PHONE",
    "amount": {
    "value": "5.32",
    "currency": "USD"
    },
    "note": "Thanks for your patronage!",
    "sender_item_id": "201403140003",
    "receiver": "408-234-1234"
  },
  {
    "recipient_type": "PHONE",
    "amount": {
    "value": "5.32",
    "currency": "USD"
    },
    "note": "Thanks for your patronage!",
    "sender_item_id": "201403140004",
    "receiver": "408-234-1234"
  }
  ]
}'
</code>```

and from this  I was able to make this in php.

```<code>$ch = curl_init();
        $header_object = (object) array('sender_batch_header'=>(object) array('sender_batch_id'=>"2014021801",'email_subject'=>"you got that"));
        $data_array = array('items'=>array(
    "recipient_type"=>"EMAIL",'amount'=>array('value'=>'9.87','CAD'),'note'=>'get your money',"sender_item_id"=>"232211",'receiver'=>"prabhs36@gmail.com"));
        $data = array($header_object,$data_array);
        // print_r($object);
        // die();
        $c_header =  ['Content-Type'=>'application/json"',
        'Authorization'=>'Bearer access_token_string_was_here'];
        // set URL and other appropriate options
        curl_setopt($ch, CURLOPT_URL, "https://api.sandbox.paypal.com/v1/payments/payouts");
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$c_header);
        // curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_POSTQUOTE, $data);

        // grab URL and pass it to the browser
        $data_2 = curl_exec($ch);

        // close cURL resource, and free up system resources
        curl_close($ch);
</code>```

I actually can't understand what is -d here means so what i could understand ,or i think it is , the $data variable is what i made. but I am getting the error that object of class std class cannot be converted to string. and array to string conversion.
Can anybody actually tell me that what is wrong and what should be done instead.

答:
-d means data, see https://curl.haxx.se/docs/manpage.html#-d

You should encode data to JSON using json_encode and put it into CURLOPT_POSTFIELDS option

```<code>$data = ['name' => 'Alice', 'age' => '25'];
$dataStr = json_encode($data);

$ch = curl_init('http://example.com');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataStr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Content-Length: ' . strlen($dataStr)
]);

$result = curl_exec($ch);
</code>```

UPDATE

To have your data encoded, just put it into array like that:

```<code>$data = [
    'sender_batch_header' => [
        'sender_batch_id' => '2014021801',
        'email_subject' => 'You have a payout!',
    ],
    'items' => [
        [
            'recipient_type' => 'email',
            // ...
        ],
        // ...
    ],
];
</code>```

UPDATE2

Consider using some HTTP client like Guzzle. It provides clean and simple interface for making HTTP requests. Example for your case:

```<code>$client = new GuzzleHttp\Client();

$data = [
    'sender_batch_header' => [
        'sender_batch_id' => '2014021801',
        'email_subject' => 'You have a payout!',
    ],
    'items' => [
        [
            'recipient_type' => 'email',
            // ...
        ],
        // ...
    ],
];

$res = $client->request('POST', 'https://api.sandbox.paypal.com/v1/payments/payouts', [
    'headers' => [
        'Authorization' => 'Bearer Access-Token',
    ],
    'json' => $data,
]);

echo $res->getStatusCode();
// "200"
echo $res->getHeader('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// {"batch_header":{"sender_batch_header"...
</code>```

Body:
As I need to use paypal payout in my project. This is what I got from the official paypal page.https://developer.paypal.com/docs/api/payments.payouts-batch/

curl -v -X POST https://api.sandbox.paypal.com/v1/payments/payouts \
-H "Content-Type:application/json" \
-H "Authorization: Bearer Access-Token" \
-d '{
  "sender_batch_header": {
  "sender_batch_id": "2014021801",
  "email_subject": "You have a payout!"
  },
  "items": [
  {
    "recipient_type": "EMAIL",
    "amount": {
    "value": "9.87",
    "currency": "USD"
    },
    "note": "Thanks for your patronage!",
    "sender_item_id": "201403140001",
    "receiver": "anybody01@gmail.com"
  },
  {
    "recipient_type": "PHONE",
    "amount": {
    "value": "112.34",
    "currency": "EUR"
    },
    "note": "Thanks for your support!",
    "sender_item_id": "201403140002",
    "receiver": "91-734-234-1234"
  },
  {
    "recipient_type": "PHONE",
    "amount": {
    "value": "5.32",
    "currency": "USD"
    },
    "note": "Thanks for your patronage!",
    "sender_item_id": "201403140003",
    "receiver": "408-234-1234"
  },
  {
    "recipient_type": "PHONE",
    "amount": {
    "value": "5.32",
    "currency": "USD"
    },
    "note": "Thanks for your patronage!",
    "sender_item_id": "201403140004",
    "receiver": "408-234-1234"
  }
  ]
}'

and from this  I was able to make this in php.

$ch = curl_init();
        $header_object = (object) array('sender_batch_header'=>(object) array('sender_batch_id'=>"2014021801",'email_subject'=>"you got that"));
        $data_array = array('items'=>array(
    "recipient_type"=>"EMAIL",'amount'=>array('value'=>'9.87','CAD'),'note'=>'get your money',"sender_item_id"=>"232211",'receiver'=>"prabhs36@gmail.com"));
        $data = array($header_object,$data_array);
        // print_r($object);
        // die();
        $c_header =  ['Content-Type'=>'application/json"',
        'Authorization'=>'Bearer access_token_string_was_here'];
        // set URL and other appropriate options
        curl_setopt($ch, CURLOPT_URL, "https://api.sandbox.paypal.com/v1/payments/payouts");
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$c_header);
        // curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_POSTQUOTE, $data);

        // grab URL and pass it to the browser
        $data_2 = curl_exec($ch);

        // close cURL resource, and free up system resources
        curl_close($ch);

I actually can't understand what is -d here means so what i could understand ,or i think it is , the $data variable is what i made. but I am getting the error that object of class std class cannot be converted to string. and array to string conversion.
Can anybody actually tell me that what is wrong and what should be done instead.

Body:
-d means data, see https://curl.haxx.se/docs/manpage.html#-d

You should encode data to JSON using json_encode and put it into CURLOPT_POSTFIELDS option

$data = ['name' => 'Alice', 'age' => '25'];
$dataStr = json_encode($data);

$ch = curl_init('http://example.com');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataStr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Content-Length: ' . strlen($dataStr)
]);

$result = curl_exec($ch);

UPDATE

To have your data encoded, just put it into array like that:

$data = [
    'sender_batch_header' => [
        'sender_batch_id' => '2014021801',
        'email_subject' => 'You have a payout!',
    ],
    'items' => [
        [
            'recipient_type' => 'email',
            // ...
        ],
        // ...
    ],
];

UPDATE2

Consider using some HTTP client like Guzzle. It provides clean and simple interface for making HTTP requests. Example for your case:

$client = new GuzzleHttp\Client();

$data = [
    'sender_batch_header' => [
        'sender_batch_id' => '2014021801',
        'email_subject' => 'You have a payout!',
    ],
    'items' => [
        [
            'recipient_type' => 'email',
            // ...
        ],
        // ...
    ],
];

$res = $client->request('POST', 'https://api.sandbox.paypal.com/v1/payments/payouts', [
    'headers' => [
        'Authorization' => 'Bearer Access-Token',
    ],
    'json' => $data,
]);

echo $res->getStatusCode();
// "200"
echo $res->getHeader('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// {"batch_header":{"sender_batch_header"...


问:
Change textview properties programatically from a fragment class
I am relatively new to Android Studio and I am starting to explore more the Android Navigation Drawer activities. I have been trying to change the font type of a textview from a fragment class and I just can't. I have tried many different solutions available here and none of them worked. In the picture, you can see my latest attempt.

In this image you can see the last code I tried to change the font from the fragment class

答:
I just checked your code, It looks okay to me. One change though, change your code from

```<code>return inflater.inflate(R.layout.fragment_main, container, false);
</code>```

to

```<code>return rootView;
</code>```

Also make sure you have provided the correct Font name

Body:
I just checked your code, It looks okay to me. One change though, change your code from

return inflater.inflate(R.layout.fragment_main, container, false);

to

return rootView;

Also make sure you have provided the correct Font name


答:
Try adding: android:layout_marginStart="xdp" being x a logical number for your case (can't say anything without seeing any image) to the xml bloq for the checkbox.

By the way, you should be using constraint layouts to avoid these kind of problems! And, if you already are, you just forget to constrain the checkbox.

Good luck.

Title: android custom layout doesn't align correctly in gridView

Body:
I am having an layout issue where i have a custom layout I use in a gridView in which a checkbox is suppose to align at the bottom right corner of an imageView. The preview of the layout shows it looks correct but when it loads into the gridView it moves the check box to the top left of the imageView. I have tried making the image smaller in the gridView and also removing the spacing in in between objects in the gridview, but to no avail.

here is my custom layout for each item of the gridView

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
    android:id="@+id/imgThumb"
    android:layout_width="100dp"
    android:layout_height="100dp"/>

<CheckBox
    android:id="@+id/chkImage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignEnd="@+id/imgThumb"
    android:layout_alignRight="@+id/imgThumb"
    android:layout_alignBottom="@+id/imgThumb"/>

</RelativeLayout>

and here is the gridView layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<GridView
    android:id="@+id/grdImages"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:numColumns="3"
    android:verticalSpacing="5dp"
    android:horizontalSpacing="5dp"
    android:columnWidth="90dp"
    android:stretchMode="columnWidth"
    android:gravity="center"/>

<Button
    android:id="@+id/btnSelect"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Select"
    android:layout_marginTop="5dp"/>

</LinearLayout>

here is an image of what i would like the item in the gridview to look like, and this is also what the preview shows it will look like Preview

and this is what happens in the actual gridView GridView


问:
How can we take the sum of each columns in SQL Server without using ;with cte?
How can I take sum of each rows by two row sum in 3rd column?

Here's a screenshot to illustrate:

You can see for id 1 sum is 10 but for id 2 sum is 10+50 = 60
and third sum is 60+100 = 160 and so on.

With Cte it is working fine for me. I need with out ;with cte means though code I need the sum

Example will as shown below

```<code>DECLARE @t TABLE(ColumnA INT, ColumnB VARCHAR(50));

INSERT INTO @t
VALUES (10,'1'), (50,'2'), (100,'3'), (5,'4'), (45,'5');

;WITH cte AS
(
   SELECT ColumnB, SUM(ColumnA) asum
   FROM @t
   GROUP BY ColumnB
), cteRanked AS
(
   SELECT asum, ColumnB, ROW_NUMBER() OVER(ORDER BY ColumnB) rownum
   FROM cte
)
SELECT
    (SELECT SUM(asum)
     FROM cteRanked c2
     WHERE c2.rownum <= c1.rownum) AS ColumnA,
    ColumnB
FROM
    cteRanked c1;
</code>```

答:
It looks like you need a simple running total.

There is an easy and efficient way to calculate running total in SQL Server 2012 and later. You can use SUM(...) OVER (ODER BY ...), like in the example below:

Sample data

```<code>DECLARE @t TABLE(ColumnA INT, ColumnB VARCHAR(50));

INSERT INTO @t
VALUES (10,'1'), (50,'2'), (100,'3'), (5,'4'), (45,'5');
</code>```

Query

```<code>SELECT
    ColumnB
    ,ColumnA
    ,SUM(ColumnA) OVER (ORDER BY ColumnB
        ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS SumColumnA
FROM @t
ORDER BY ColumnB;
</code>```

Result

```<code>+---------+---------+------------+
| ColumnB | ColumnA | SumColumnA |
+---------+---------+------------+
|       1 |      10 |         10 |
|       2 |      50 |         60 |
|       3 |     100 |        160 |
|       4 |       5 |        165 |
|       5 |      45 |        210 |
+---------+---------+------------+
</code>```

For SQL Server 2008 and below you need to use either correlated sub-queries as you do already or a simple cursor, which may be faster if the table is large.

Body:
How can I take sum of each rows by two row sum in 3rd column?

Here's a screenshot to illustrate:

You can see for id 1 sum is 10 but for id 2 sum is 10+50 = 60
and third sum is 60+100 = 160 and so on.

With Cte it is working fine for me. I need with out ;with cte means though code I need the sum

Example will as shown below

DECLARE @t TABLE(ColumnA INT, ColumnB VARCHAR(50));

INSERT INTO @t
VALUES (10,'1'), (50,'2'), (100,'3'), (5,'4'), (45,'5');

;WITH cte AS
(
   SELECT ColumnB, SUM(ColumnA) asum
   FROM @t
   GROUP BY ColumnB
), cteRanked AS
(
   SELECT asum, ColumnB, ROW_NUMBER() OVER(ORDER BY ColumnB) rownum
   FROM cte
)
SELECT
    (SELECT SUM(asum)
     FROM cteRanked c2
     WHERE c2.rownum <= c1.rownum) AS ColumnA,
    ColumnB
FROM
    cteRanked c1;

Body:
It looks like you need a simple running total.

There is an easy and efficient way to calculate running total in SQL Server 2012 and later. You can use SUM(...) OVER (ODER BY ...), like in the example below:

Sample data

DECLARE @t TABLE(ColumnA INT, ColumnB VARCHAR(50));

INSERT INTO @t
VALUES (10,'1'), (50,'2'), (100,'3'), (5,'4'), (45,'5');

Query

SELECT
    ColumnB
    ,ColumnA
    ,SUM(ColumnA) OVER (ORDER BY ColumnB
        ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS SumColumnA
FROM @t
ORDER BY ColumnB;

Result

+---------+---------+------------+
| ColumnB | ColumnA | SumColumnA |
+---------+---------+------------+
|       1 |      10 |         10 |
|       2 |      50 |         60 |
|       3 |     100 |        160 |
|       4 |       5 |        165 |
|       5 |      45 |        210 |
+---------+---------+------------+

For SQL Server 2008 and below you need to use either correlated sub-queries as you do already or a simple cursor, which may be faster if the table is large.


问:
Reverse last push on Github.
I have pushed on the wrong branch, I want to push on new branch but I have pushed on the master branch. Is there any way to Reverse the last committed push and get the last code and pushed again to the new branch?

答:
Undo the last commit by soft reset from local master branch and keep the changes locally (in working tree).

```<code>$ git checkout master
$ git reset --soft HEAD~1

$ git log               # make sure the last commit is reverted successfully as you expect.
</code>```

Checkout to a new branch (say, feature). Add, Commit, Push to remote branch (feature here).

```<code>$ git checkout -b feature   # checkout new branch with the local changes
$ git status                # see the changed files
$ git add .
$ git commit -m 'message'
$ git push origin HEAD
</code>```

Back to local master and do force push to update the remote master (delete remote master's last commit)

```<code>$ git checkout master
$ git push -f origin HEAD
</code>```

N.B: Force push needed since changing the history of the remote master.

Alternate: If you don't have force push permission or someone else Pulled the origin/master and got your last commit already. Then better you revert the last commit instead reset (history change).

```<code>$ git checkout master
$ git log                        # copy the last-commi-hash
$ git revert <last-commit-hash>
$ git push origin HEAD           # note, no force push is needed
</code>```

Create a new branch and cherry-pick the last commit and push to remote.

```<code>$ git checkout -b feature
$ git cherry-pick <last-commit-hash>
$ git push origin HEAD
</code>```

Title: Reverse last push on Github.

Body:
Undo the last commit by soft reset from local master branch and keep the changes locally (in working tree).

$ git checkout master
$ git reset --soft HEAD~1

$ git log               # make sure the last commit is reverted successfully as you expect.

Checkout to a new branch (say, feature). Add, Commit, Push to remote branch (feature here).

$ git checkout -b feature   # checkout new branch with the local changes
$ git status                # see the changed files
$ git add .
$ git commit -m 'message'
$ git push origin HEAD

Back to local master and do force push to update the remote master (delete remote master's last commit)

$ git checkout master
$ git push -f origin HEAD

N.B: Force push needed since changing the history of the remote master.

Alternate: If you don't have force push permission or someone else Pulled the origin/master and got your last commit already. Then better you revert the last commit instead reset (history change).

$ git checkout master
$ git log                        # copy the last-commi-hash
$ git revert <last-commit-hash>
$ git push origin HEAD           # note, no force push is needed

Create a new branch and cherry-pick the last commit and push to remote.

$ git checkout -b feature
$ git cherry-pick <last-commit-hash>
$ git push origin HEAD


问:
images not staying in place, dragging with adjustment of window
When I put some images on the page they will move across the screen when I try
and adjust the size of the window on my browser. The images I'm talking about in css are coded as .ex { position: absolute; top: 200px; right 200px; } and they move across the screen but some do not. why does this happen and how can I prevent it.

#logo {
  text-align: center;
  position: absolute;
  top: 0;
  right: 750px;
}

#logoleft {
  float: left;
  position: absolute;
  top: 0;
  left: 500px;
}

#logoright {
  float: right;
  position: absolute;
  top: 0;
  right: 420px;
}

#leftleft {
  position: absolute;
  left: 270px;
}

#rightright {
  position: absolute;
  right: 180px;
}

#bdlogo {
  position: absolute;
  top: 500px;
  left: 220px;
}

#logobelow {
  position: absolute;
  top: 150px;
  right: 750px;
}

#logoprayer {
  position: absolute;
  right: 200px;
  top: 500px;
}

#gc {
  position: fixed;
  top: 10px;
  right: 20px;
}

#ib {
  position: fixed;
  top: 10px;
  left: 70px;
}

#fc {
  position: fixed;
  top: 350px;
  right: 1040px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="rightright"><img src="data/pics/mr.png" width="140px;" height="140px;">
  <!--randomness-->
</div>
<div id="leftleft"><img src="data/pics/lr.png" width="140px;" height="140px;">
  <!--randomness-->
</div>
<div id="logoleft"><img src="data/pics/wom.png" width="145px" height="340px">
  <!--randomness-->
</div>
<div id="logo">
  <img src="data/pics/rslogo.png" width="450px;" height="170px;">
    <!--randomness-->

</div>
<div id="logoright"><img src="data/pics/emt.png" width="245px;" height="340px;">
  <!--randomness-->
</div>
<div id="bdlogo"><img src="data/pics/bd.gif">
  <!--randomness-->
</div>
<div id="logobelow">
  <img src="data/pics/fs.png">
    <!--randomness-->

</div>
<div id="logoprayer"><img src="data/pics/rc.gif" width="195px;" height="300px;">
  <!--randomness-->
</div>
<div id="gc"><img src="data/pics/gc.png" width="95px;" height="95px;">
  <!--randomness-->
</div>
<div id="ib"><img src="data/pics/ib.png" width="65px;" height="65px;">
  <!--randomness-->
</div>
<div id="fc"><img src="data/pics/fc.png" width="90" ; height="90" ;>
  <!--randomness-->
</div></code>```

答:
Some Of your elements are positioned fixed (position:fixed) which will cause the element place to stay on the same position of browser view point.

change them to position:absolute or position:relative;

```<code>#gc {
     position: absolute; top: 10px; right: 20px; /*consider using normal flow instead*/
}
#ib {
     position: absolute; top: 10px; left: 70px; /*consider using normal flow instead*/
}
 #fc {
     position: absolute; top: 350px; right: 1040px; /*consider using normal flow instead*/
}
</code>```

also you should consider using position:relative instead of position:absolute since it just position your elements absolutely where you defined(left:70px; for example) and it will stay on that position no mater what(changing your browser width won't change it). you should avoid using position absolute and try to position your element with margin and padding.

some tutorial about positioning :

https://alistapart.com/article/css-positioning-101

http://webdesign.about.com/od/beginningcss/p/aacss9layout.htm

use this link for better understanding of margin and padding:

https://www.w3schools.com/css/css_boxmodel.asp

Body:
Some Of your elements are positioned fixed (position:fixed) which will cause the element place to stay on the same position of browser view point.

change them to position:absolute or position:relative;

#gc {
     position: absolute; top: 10px; right: 20px; /*consider using normal flow instead*/
}
#ib {
     position: absolute; top: 10px; left: 70px; /*consider using normal flow instead*/
}
 #fc {
     position: absolute; top: 350px; right: 1040px; /*consider using normal flow instead*/
}

also you should consider using position:relative instead of position:absolute since it just position your elements absolutely where you defined(left:70px; for example) and it will stay on that position no mater what(changing your browser width won't change it). you should avoid using position absolute and try to position your element with margin and padding.

some tutorial about positioning :

https://alistapart.com/article/css-positioning-101

http://webdesign.about.com/od/beginningcss/p/aacss9layout.htm

use this link for better understanding of margin and padding:

https://www.w3schools.com/css/css_boxmodel.asp