问:
android call runtime permission with dialog
I have app that requests runtime permission for call on app start with dialog,  but somehow my code doesn't request any permission or work. I need that when the app starts; ask the user for permission to call and in case the user refused, ask again for permission and move to in permissions settings.

Here's my code:

```<code>public class MainActivity extends AppCompatActivity {
private FirebaseAnalytics mFirebaseAnalytics;
private AdView mAdView;

private Button button_id;
private Button button_mobily;
private Button button_stc;
private Button button_zain;
private Button button_share;
private Button button_exit;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.dash);
    NativeExpressAdView adView = (NativeExpressAdView)findViewById(R.id.adView);

    AdRequest request = new AdRequest.Builder().build();
    adView.loadAd(request);

    mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
    Bundle bundle = new Bundle();
    bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "main");
    bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "opened");
    bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "image");
    mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);

    isPermissionGranted();

    button_exit = (Button) findViewById(R.id.exit_buton_id);
    button_share = (Button) findViewById(R.id.Share_buton);
    button_id = (Button) findViewById(R.id.edit_id);
    button_mobily = (Button) findViewById(R.id.mobily_buton);
    button_stc = (Button) findViewById(R.id.stc_buton);
    button_zain = (Button) findViewById(R.id.zain_buton);

    button_id.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            Intent myIntent = new Intent(MainActivity.this, NationalId.class);
            MainActivity.this.startActivity(myIntent);

        }
    });

    button_share.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            try {
                Intent i = new Intent(Intent.ACTION_SEND);
                i.setType("text/plain");
                i.putExtra(Intent.EXTRA_SUBJECT, "test");
                String sAux = "\n download my app\n\n";
                sAux = sAux + "https://play.google.com/store/apps/details?id=Orion.Soft \n\n";
                i.putExtra(Intent.EXTRA_TEXT, sAux);
                startActivity(Intent.createChooser(i, "share on"));
            } catch (Exception e) {
                //e.toString();
            }

        }
    });

    button_exit.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {

            close();
        }
    });

    button_mobily.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            Intent myIntent = new Intent(MainActivity.this, OpreatorMobily.class);
            MainActivity.this.startActivity(myIntent);
        }
    });

    button_stc.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            Intent myIntent = new Intent(MainActivity.this, OpreatorSTC.class);
            MainActivity.this.startActivity(myIntent);
        }
    });

    button_zain.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            Intent myIntent = new Intent(MainActivity.this, OpreatorZain.class);
            MainActivity.this.startActivity(myIntent);
        }
    });

}

public boolean isPermissionGranted() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission.CALL_PHONE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v("TAG", "Permission is granted");
            return true;
        } else {

            Log.v("TAG", "Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, 1);
            return false;
        }
    } else { //permission is automatically granted on sdk<23 upon installation
        Log.v("TAG", "Permission is granted");
        return true;
    }
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {

        case 1: {

            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_SHORT).show();

            } else {
                Toast.makeText(getApplicationContext(), "Permission denied", Toast.LENGTH_SHORT).show();
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

public void close() {
    // TODO Auto-generated method stub
    finish();
    System.exit(0);
}

}
</code>```

答:
I found a simple Github library developed by "Nabin Bhandari". It is easy to implement and can be customized directly. Github library link...

Please add this dependency to add this library to your code.

implementation 'com.nabinbhandari.android:permissions:3.8'

This allow you to request single permission, multiple permission and do customize your own dialog.

Furthermore,

You can also override other methods like onDenied, onJustBlocked, etc if you want to change the default behaviour.

Dialogue messages and texts can be modified by building the options parameter.

See documentation in the source code for more customizations.

Use this code to ask multiple permissions samuntanely.

String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
Permissions.check(this/*context*/, permissions, null/*rationale*/, null/*options*/, new PermissionHandler() {
    @Override
    public void onGranted() {
        // do your task.
    }
});```
</div>
</div>
</p>

<p>Use this code if you want to Customized permissions request:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
String rationale = "Please provide location permission so that you can ...";
Permissions.Options options = new Permissions.Options()
        .setRationaleDialogTitle("Info")
        .setSettingsDialogTitle("Warning");

Permissions.check(this/*context*/, permissions, rationale, options, new PermissionHandler() {
    @Override
    public void onGranted() {
        // do your task.
    }

    @Override
    public void onDenied(Context context, ArrayList<String> deniedPermissions) {
        // permission denied, block the feature.
    }
});</code>```

Body:
I have app that requests runtime permission for call on app start with dialog,  but somehow my code doesn't request any permission or work. I need that when the app starts; ask the user for permission to call and in case the user refused, ask again for permission and move to in permissions settings.

Here's my code:

public class MainActivity extends AppCompatActivity {
private FirebaseAnalytics mFirebaseAnalytics;
private AdView mAdView;

private Button button_id;
private Button button_mobily;
private Button button_stc;
private Button button_zain;
private Button button_share;
private Button button_exit;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.dash);
    NativeExpressAdView adView = (NativeExpressAdView)findViewById(R.id.adView);

    AdRequest request = new AdRequest.Builder().build();
    adView.loadAd(request);

    mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
    Bundle bundle = new Bundle();
    bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "main");
    bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "opened");
    bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "image");
    mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);

    isPermissionGranted();

    button_exit = (Button) findViewById(R.id.exit_buton_id);
    button_share = (Button) findViewById(R.id.Share_buton);
    button_id = (Button) findViewById(R.id.edit_id);
    button_mobily = (Button) findViewById(R.id.mobily_buton);
    button_stc = (Button) findViewById(R.id.stc_buton);
    button_zain = (Button) findViewById(R.id.zain_buton);

    button_id.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            Intent myIntent = new Intent(MainActivity.this, NationalId.class);
            MainActivity.this.startActivity(myIntent);

        }
    });

    button_share.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            try {
                Intent i = new Intent(Intent.ACTION_SEND);
                i.setType("text/plain");
                i.putExtra(Intent.EXTRA_SUBJECT, "test");
                String sAux = "\n download my app\n\n";
                sAux = sAux + "https://play.google.com/store/apps/details?id=Orion.Soft \n\n";
                i.putExtra(Intent.EXTRA_TEXT, sAux);
                startActivity(Intent.createChooser(i, "share on"));
            } catch (Exception e) {
                //e.toString();
            }

        }
    });

    button_exit.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {

            close();
        }
    });

    button_mobily.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            Intent myIntent = new Intent(MainActivity.this, OpreatorMobily.class);
            MainActivity.this.startActivity(myIntent);
        }
    });

    button_stc.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            Intent myIntent = new Intent(MainActivity.this, OpreatorSTC.class);
            MainActivity.this.startActivity(myIntent);
        }
    });

    button_zain.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            Intent myIntent = new Intent(MainActivity.this, OpreatorZain.class);
            MainActivity.this.startActivity(myIntent);
        }
    });

}

public boolean isPermissionGranted() {
    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission.CALL_PHONE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v("TAG", "Permission is granted");
            return true;
        } else {

            Log.v("TAG", "Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, 1);
            return false;
        }
    } else { //permission is automatically granted on sdk<23 upon installation
        Log.v("TAG", "Permission is granted");
        return true;
    }
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {

        case 1: {

            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_SHORT).show();

            } else {
                Toast.makeText(getApplicationContext(), "Permission denied", Toast.LENGTH_SHORT).show();
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

public void close() {
    // TODO Auto-generated method stub
    finish();
    System.exit(0);
}

}

Body:
I found a simple Github library developed by "Nabin Bhandari". It is easy to implement and can be customized directly. Github library link...

Please add this dependency to add this library to your code.

implementation 'com.nabinbhandari.android:permissions:3.8'

This allow you to request single permission, multiple permission and do customize your own dialog.

Furthermore,

You can also override other methods like onDenied, onJustBlocked, etc if you want to change the default behaviour.

Dialogue messages and texts can be modified by building the options parameter.

See documentation in the source code for more customizations.

Use this code to ask multiple permissions samuntanely.

String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
Permissions.check(this/*context*/, permissions, null/*rationale*/, null/*options*/, new PermissionHandler() {
    @Override
    public void onGranted() {
        // do your task.
    }
});

Use this code if you want to Customized permissions request:

String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
String rationale = "Please provide location permission so that you can ...";
Permissions.Options options = new Permissions.Options()
        .setRationaleDialogTitle("Info")
        .setSettingsDialogTitle("Warning");

Permissions.check(this/*context*/, permissions, rationale, options, new PermissionHandler() {
    @Override
    public void onGranted() {
        // do your task.
    }

    @Override
    public void onDenied(Context context, ArrayList<String> deniedPermissions) {
        // permission denied, block the feature.
    }
});


来源: stackexchange

问:
Cypress not finding data-test element
Morning/evening everyone. Have a weird issue that, according to the best practices, should just work.
I have the following element on a page which I need to click:

Sign out

I'm doing this in my test:

cy.get('[data-test="sign-out-link"]') .should('be.visible') .click()

But cypress times out saying the element cannot be found...

This gives the same behaviour:
cy.get('a[data-test="sign-out-link"]') .should('be.visible') .click()

Even this just fails, which is kinda weird (it should find that text fairly easily):

cy.contains('Sign out').click()

Anything obvious I'm doing wrong?

答:
Have you tried to find out this element in selector playground. check here.
One obvious error I see is on your hyperlink. Try with below</p>

```<code>cy.get('a[data-test=sign-out-link]').should('be.visible').click()
</code>```

ContentLicense: CC BY-SA 4.0

Title: Cypress not finding data-test element

Body:
Have you tried to find out this element in selector playground. check here.
One obvious error I see is on your hyperlink. Try with below

cy.get('a[data-test=sign-out-link]').should('be.visible').click()


问:
How to add Icon and Tooltip in Echart Title?
Want to add icon with Tooltip, in Echarts.
Need like below example. Thank you.

答:
I have given the answer to this question in JavaScript as well as Angular

How to display the icons in tooltip echarts

We cannot add icon but we can definitely use svg path as done by me.
Please let me know if you need any assistance.


问:
how to add the comma in a string to a single cell in csv
while i was trying to write some text to a CSV, I found out that it cut the text at the first comma in the text and thus writing the string to 2 different cell instead of 1. is there anyway around this issue as the text will be crawled from the web instead of input

the gist of the function code is

```<code>String text = "hello, this is me";
        try {
            PrintWriter csv = new PrintWriter(new File("test.csv"));
            csv.write(text);
            csv.close();
        }
        catch(Exception e) {

        }
</code>```

答:
test.csv

```<code>a;b;c
d;e;f
</code>```

test2.csv

```<code>a;b;c
,;e;f
</code>```

Java code using opencsv:

```<code>import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;

import com.opencsv.CSVParserBuilder;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import com.opencsv.CSVWriter;

public class Sof {

    public static void main(String[] args) {
        CSVReader reader;
        try (CSVWriter writer = new CSVWriter(new FileWriter(new File("src/main/resources/test2.csv")), ';', Character.MIN_VALUE, '\\', "\n");) {
            reader = new CSVReaderBuilder(new InputStreamReader(new FileInputStream("src/main/resources/test.csv"), StandardCharsets.UTF_8))
                    .withCSVParser(new CSVParserBuilder().withSeparator(';').build()).build();
            final List<String[]> csvBody = reader.readAll();
            System.out.println(csvBody.size());
            csvBody.get(1)[0] = ",";
            writer.writeAll(csvBody);
            writer.flush();
            reader.close();
        } catch (final IOException e1) {
            System.err.println(e1);
        }

    }

}
</code>```

Body:
while i was trying to write some text to a CSV, I found out that it cut the text at the first comma in the text and thus writing the string to 2 different cell instead of 1. is there anyway around this issue as the text will be crawled from the web instead of input

the gist of the function code is

String text = "hello, this is me";
        try {
            PrintWriter csv = new PrintWriter(new File("test.csv"));
            csv.write(text);
            csv.close();
        }
        catch(Exception e) {

        }

Body:
test.csv

a;b;c
d;e;f

test2.csv

a;b;c
,;e;f

Java code using opencsv:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;

import com.opencsv.CSVParserBuilder;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import com.opencsv.CSVWriter;

public class Sof {

    public static void main(String[] args) {
        CSVReader reader;
        try (CSVWriter writer = new CSVWriter(new FileWriter(new File("src/main/resources/test2.csv")), ';', Character.MIN_VALUE, '\\', "\n");) {
            reader = new CSVReaderBuilder(new InputStreamReader(new FileInputStream("src/main/resources/test.csv"), StandardCharsets.UTF_8))
                    .withCSVParser(new CSVParserBuilder().withSeparator(';').build()).build();
            final List<String[]> csvBody = reader.readAll();
            System.out.println(csvBody.size());
            csvBody.get(1)[0] = ",";
            writer.writeAll(csvBody);
            writer.flush();
            reader.close();
        } catch (final IOException e1) {
            System.err.println(e1);
        }

    }

}


问:
CI: Why do all my jqxhr requests fail when $config['csrf_protection'] = TRUE?
In going through my CI 3.1.11 code to clean it up (hosted by XAMPP v2.3.4 localhost) it seems I have done something to prevent the server from accepting any jqxhr requests if I have CI's Cross-Site Request Forgery (csrf) protection running.

I am using other http requsts to get information from the server and external files such as lines in the  that load jquery, my css file, etc. These work fine no matter the state of the csrf setting.

When I have set:
    $config['csrf_protection'] = TRUE; My jqxhr requests always get the http 403 error (rejected request that implies a suspected hacking attempt). My basic question is to understand why this happens so I can correct it and run the csrf protection.

I don't know if this is related but I found that I only need to provide the controller and function to the jqxhr rather than the complete url. Most examples I've seen online provide embedded Php code to insert the base_url in front. Something in the system (CI?) seems to want to prepend the base_url  to the controller/function no matter what. If I insert it myself, it creates an unusable url with the base_url appearing twice.

If I use . . .
    var url= "C_library/updateTitle";
     $.post(url, { 'tID':tID, 'newTitle':newTitle }, function(data) { . .

. . . the request works if csrf is not running. If csrf protection is running, this would be a typical console error report:

```<code>XHRPOSThttp://localhost/MZlocal/C_library/updateTitle [HTTP/1.1 403 Forbidden 32ms]
</code>```

Note that the url is correctly formed.

Also, probably not relevant but here's my .htaccess file - which works (eliminates "index.php" from the address bar).

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</code>```

csrf protection is an important feature of CI that I'd really like to understand better. Any help or hints as to where I should look is appreciated.

Full csrf config.php:

```<code>$config['csrf_protection'] = TRUE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();
</code>```

答:
In your Form data you must  pass  security token when CSRF is TRUE

```<code><input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>" />
</code>```

Body:
In going through my CI 3.1.11 code to clean it up (hosted by XAMPP v2.3.4 localhost) it seems I have done something to prevent the server from accepting any jqxhr requests if I have CI's Cross-Site Request Forgery (csrf) protection running.

I am using other http requsts to get information from the server and external files such as lines in the  that load jquery, my css file, etc. These work fine no matter the state of the csrf setting.

When I have set:
    $config['csrf_protection'] = TRUE; My jqxhr requests always get the http 403 error (rejected request that implies a suspected hacking attempt). My basic question is to understand why this happens so I can correct it and run the csrf protection.

I don't know if this is related but I found that I only need to provide the controller and function to the jqxhr rather than the complete url. Most examples I've seen online provide embedded Php code to insert the base_url in front. Something in the system (CI?) seems to want to prepend the base_url  to the controller/function no matter what. If I insert it myself, it creates an unusable url with the base_url appearing twice.

If I use . . .
    var url= "C_library/updateTitle";
     $.post(url, { 'tID':tID, 'newTitle':newTitle }, function(data) { . .

. . . the request works if csrf is not running. If csrf protection is running, this would be a typical console error report:

XHRPOSThttp://localhost/MZlocal/C_library/updateTitle [HTTP/1.1 403 Forbidden 32ms]

Note that the url is correctly formed.

Also, probably not relevant but here's my .htaccess file - which works (eliminates "index.php" from the address bar).

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

csrf protection is an important feature of CI that I'd really like to understand better. Any help or hints as to where I should look is appreciated.

Full csrf config.php:

$config['csrf_protection'] = TRUE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();

Body:
In your Form data you must  pass  security token when CSRF is TRUE

<input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>" />


问:
works in ie9 and ff4 - not in ie7 or ie 8?
I wrote this script awhile back and have modified it to use css sprites to cut down on images.  Everything works perfect in ie9 and ff4, however, I noticed it will not show in ie7/ie8... It must be a css or js problem, but I certainly cannot see anything that would be preventing the older ie's from displaying the code...

I have included the entire contents below in a 'test' page which includes everything... if someone can point me out to why this is not working in ie7 or ie8 I would be very grateful!

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<style type="text/css">
#social16 {height:16px;font-size:13px; color:#0066ff; font-weight:bold;}
#sb16 {margin: 0px; padding:0px; height:16px; display: inline;line-height:16px;}
#sb16 li {list-style-type:none;float:left;padding:0 5px 0 0;}
#sb16 li a {background:url(social.png);background-repeat:no-repeat;display: block;height: 16px;width:16px;}
#sb16 li a.item0 {background-position:0px 0px;}
#sb16 li a.item1 {background-position:-16px 0px;}
#sb16 li a.item2 {background-position:-32px 0px;}
#sb16 li a.item3 {background-position:-48px 0px;}
#sb16 li a.item4 {background-position:-64px 0px;}
#sb16 li a.item5 {background-position:-80px 0px;}
#sb16 li a.item6 {background-position:-96px 0px;}
</style>
</head>
<body>
<div id="social16"></div>
<script type="text/javascript">
(function(){

var sites = [
        ['Send to Facebook', 'http://www.facebook.com/sharer.php?u={url}&t={title}'],
        ['Tweet This', 'http://twitter.com/share?text={title}&url={url}'],
        ['Send to StumbleUpon', 'http://www.stumbleupon.com/submit?url={url}&title={title}'],
        ['Digg This', 'http://digg.com/submit?phase=2&url={url}&title={title}'],
        ['Send to GoogleBuzz', 'http://www.google.com/buzz/post?message={title}&url={url}'],
        ['Send to Reddit', 'http://reddit.com/submit?url={url}&title={title}'],
        ['Email to Friends', 'mailto:?subject={title}&body={url}'],
    ];

var url = encodeURIComponent(location.href),
    url = url.replace( "#", "" ),
    title = encodeURIComponent(document.title),
    html = '<ul id="sb16"><li>Share this ... </li>';

for (var i = 0, len = sites.length; i < len; i++) {
    var site = sites[i],
    link = site[1].replace('{url}', url).replace('{title}', title);

    html += '<li><a class="item' + i + '" href="#" title="' + site[0] + '" onclick="window.open(\'' + link + '\')"></a></li>';
}

html += '</ul>';

document.getElementById("social16").innerHTML=(html);

})();
</script>
</body>
</html>
</code>```

答:
You have a comma after the last element of sites:

```<code>var sites = [
    //...
    ['Email to Friends', 'mailto:?subject={title}&body={url}'],
    // -----------------------------------------------------------^
];
</code>```

IE6 and IE7 don't like that. This usually shows up as a null at the end of the array and you end up with a null where you don't expect one.

ContentLicense: CC BY-SA 3.0

Body:
I wrote this script awhile back and have modified it to use css sprites to cut down on images.  Everything works perfect in ie9 and ff4, however, I noticed it will not show in ie7/ie8... It must be a css or js problem, but I certainly cannot see anything that would be preventing the older ie's from displaying the code...

I have included the entire contents below in a 'test' page which includes everything... if someone can point me out to why this is not working in ie7 or ie8 I would be very grateful!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

Body:
You have a comma after the last element of sites:

var sites = [
    //...
    ['Email to Friends', 'mailto:?subject={title}&amp;body={url}'],
    // -----------------------------------------------------------^
];

IE6 and IE7 don't like that. This usually shows up as a null at the end of the array and you end up with a null where you don't expect one.


问:
I want to limit the display of x and y axis in R
I am trying to Limit the x and y axis in R but dont know how to do so,I am using xlim and ylim but it is not working.

here is my code:

```<code>library(raster)
library(changepoint)
r <- raster("E:/Project_data/all_India_raster_stacked_image.tif")
set.seed(1)
m1=values(r)
m1.amoc=cpt.mean(m1)
cpts(m1.amoc)
m1.cusum=cpt.mean(m1,pen.value=1,penalty=manual,test.stat='CUSUM')
dev.new(width=10,height=10,unit='cm')
plot(m1.amoc,xlim(0,800),ylim(400000,1500000))
</code>```

Body:
I am trying to Limit the x and y axis in R but dont know how to do so,I am using xlim and ylim but it is not working.

here is my code:

library(raster)
library(changepoint)
r <- raster("E:/Project_data/all_India_raster_stacked_image.tif")
set.seed(1)
m1=values(r)
m1.amoc=cpt.mean(m1)
cpts(m1.amoc)
m1.cusum=cpt.mean(m1,pen.value=1,penalty=manual,test.stat='CUSUM')
dev.new(width=10,height=10,unit='cm')
plot(m1.amoc,xlim(0,800),ylim(400000,1500000))

Body: plot(m1.amoc,xlim=c(0,800), ylim=c(400000,1500000))


问:
how to configure http uri healthcheck for a ws balancer with Apache Httpd
i need to configure healthcheck for my ws load balancer within Apache httpd.
i am using mod_proxy_wstunnel for websocket tunneling and mod_balancer for load balancing between 2 servers.
i am using additionnaly mod_proxy_hcheck for verifying if the 2 servers are available.
the configuration is following:

```<code>Header add Set-Cookie "ROUTEID=.%{BALANCER_WORKER_ROUTE}e; path=/" env=BALANCER_ROUTE_CHANGED
ProxyHCExpr ok2 {%{REQUEST_STATUS} =~ /^[2]/}
    <Proxy balancer://trackingwsbalancer>
    BalancerMember  wss://{{ rpa_fqdn_tracking1 }}:8443 route=1 hcmethod=GET hcexpr=ok2 hcuri=/trackingproxy_advanced/actuator
    BalancerMember  wss://{{ rpa_fqdn_tracking2 }}:8443 route=2 hcmethod=GET hcexpr=ok2 hcuri=/trackingproxy_advanced/actuator
    ProxySet stickysession=ROUTEID
    ProxySet lbmethod=bybusyness
    </Proxy>
</code>```

the problem is that the healthcheck always fails because the request behind is:

```<code>wss ://{{ rpa_fqdn_tracking1 }}:8443/trackingproxy_advanced/actuator.
</code>```

and i want it to be

```<code>htpps ://{{ rpa_fqdn_tracking1 }}:8443/trackingproxy_advanced/actuator
</code>```

in order to be able to handle the response for healthcheck correctly with hcexpr

i will greatly appreciate any idea to configure the protocole for the uri healthcheck.

答:
The documentation of the mod_proxy_hcheck  module says that it performs a HTTP request.
 After inspecting the mod_proxy_hcheck.c( Apche 2.4.39), it seems that this case is not covered. The code doesn't check if the scheme is ws and does not replace it when it create the request.

It should be great to be able to add an absolute uri for the hckeck or replace automatically the protocol used if it's not http.

Body:
i need to configure healthcheck for my ws load balancer within Apache httpd.
i am using mod_proxy_wstunnel for websocket tunneling and mod_balancer for load balancing between 2 servers.
i am using additionnaly mod_proxy_hcheck for verifying if the 2 servers are available.
the configuration is following:

Header add Set-Cookie "ROUTEID=.%{BALANCER_WORKER_ROUTE}e; path=/" env=BALANCER_ROUTE_CHANGED
ProxyHCExpr ok2 {%{REQUEST_STATUS} =~ /^[2]/}
    <Proxy balancer://trackingwsbalancer>
    BalancerMember  wss://{{ rpa_fqdn_tracking1 }}:8443 route=1 hcmethod=GET hcexpr=ok2 hcuri=/trackingproxy_advanced/actuator
    BalancerMember  wss://{{ rpa_fqdn_tracking2 }}:8443 route=2 hcmethod=GET hcexpr=ok2 hcuri=/trackingproxy_advanced/actuator
    ProxySet stickysession=ROUTEID
    ProxySet lbmethod=bybusyness
    </Proxy>

the problem is that the healthcheck always fails because the request behind is:

wss ://{{ rpa_fqdn_tracking1 }}:8443/trackingproxy_advanced/actuator.

and i want it to be

htpps ://{{ rpa_fqdn_tracking1 }}:8443/trackingproxy_advanced/actuator

in order to be able to handle the response for healthcheck correctly with hcexpr

i will greatly appreciate any idea to configure the protocole for the uri healthcheck.


问:
JSON format to Data Frame in Python
I am reading API data from the cloud server in JSON format as shown here

How to write a code to store this data frame into the data frame in any database. How to convert JSON format to DataFrame?

The requirement output format is shown in table2

答:
Here is an example:

```<code>from requests import request
import json
import pandas as pd
response = request(url="http://api.open-notify.org/astros.json", method='get')# API source
data=json.loads(response.text)['people']# pick the 'people' data source from json
pd.DataFrame(data) # convert to pandas dataframe
</code>```

let me know if it works.

Title: JSON format to Data Frame in Python

Body:
Here is an example:

from requests import request
import json
import pandas as pd
response = request(url="http://api.open-notify.org/astros.json", method='get')# API source
data=json.loads(response.text)['people']# pick the 'people' data source from json
pd.DataFrame(data) # convert to pandas dataframe

let me know if it works.


问:
System.Data.SqlClient.SqlException: 'Incorrect syntax near '9'
I have two DateTimePickers (dateStart and dateStop) in a winform. I've set dateStart and dateSop's format like this:

```<code>    dateStart.Format = DateTimePickerFormat.Custom;
    dateStart.CustomFormat = "yyyy:MM:dd HH:mm:ss";
    dateStop.Format = DateTimePickerFormat.Custom;
    dateStop.CustomFormat = "yyyy:MM:dd HH:mm:ss";
</code>```

I want to count number of rows from my datebase's table between dateStart and dateStop.
My select string:

```<code>string stmt = "SELECT COUNT(*) FROM [dbo].[tbl_TagLogging] WHERE DateTime BETWEEN  " + Convert.ToString(dateStart.Value) + " AND " + Convert.ToString(dateStop.Value);
</code>```

And it's result:

This is how link DateStart and DateStop paramaters of my datebase with DateTimePickers.

```<code> cmd.Parameters.Add("@DataStart", SqlDbType.DateTime).Value = dateStart.Value;// new DateTime(dateStart.Value);
 cmd.Parameters.Add("@DataStop", SqlDbType.DateTime).Value = dateStop.Value;// new DateTime(2020, 02, 05, 13, 12, 25, 703);//2020, 02, 05, 13, 12, 25, 703   //2020, 02, 05, 13, 06, 50, 700
</code>```

The row counting works perfectly without WHERE clause.

```<code>count = (int)cmdCount.ExecuteScalar();//this is how I count the rows
</code>```

I'm getting here a 'System.Data.SqlClient.SqlException: Incorect syntax near 9'.

I kinda don't understand why if dateStart's format is  "yyyy:MM:dd HH:mm:ss", dateStart.value is returned in another format. On my UI, dateStart is displayed in the right format (the one from the code above). But I might have done something faulty in my stmt string.
Any thoughts on what is wrong?

EDIT 1 (my entire code):

```<code> private void button_Click(object sender, EventArgs e)
    {
        dateStart.Format = DateTimePickerFormat.Custom;
        dateStart.CustomFormat = "yyyy:MM:dd HH:mm:ss";
        dateStop.Format = DateTimePickerFormat.Custom;
        dateStop.CustomFormat = "yyyy:MM:dd HH:mm:ss";
        string stmt = "SELECT COUNT(*) FROM [dbo].[tbl_TagLogging] WHERE DateTime BETWEEN  @DataStart AND @DataStop";         // WHERE DateTime BETWEEN  " + Convert.ToString(dateStart.Value) + " AND " + Convert.ToString(dateStop.Value)
       // string stmt = "SELECT COUNT(*) FROM [dbo].[tbl_TagLogging] WHERE DateTime BETWEEN  '" + Convert.ToString(dateStart.Value) + "' AND '" + Convert.ToString(dateStop.Value) + "'";
        int count = 0;

        using (SqlConnection connection = new SqlConnection(@"Data Source=DESKTOP-JQSJAF8\SQLEXPRESS;Initial Catalog=TRTF_TagLogging;Integrated Security=True; MultipleActiveResultSets = true"))
        {
            using (SqlCommand cmd = new SqlCommand("PS_TagLogging", connection))// used for stored proc
            {
                using (SqlCommand cmdCount = new SqlCommand(stmt, connection))//used to count number of rows of my table
                {
                    //yyyy:MM:dd hh:mm:ss
                    connection.Open();
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@DataStart", SqlDbType.DateTime).Value = dateStart.Value;
                    cmd.Parameters.Add("@DataStop", SqlDbType.DateTime).Value = dateStop.Value;
                    var values = new List<double>();
                    var valData = new List<DateTime>();
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        // values.Add(reader.GetInt64(0));//reads the values of first column (ID) from DB
                        values.Add(reader.GetFloat(1));//reads the values of second column (Tag1) from DB
                        valData.Add(reader.GetDateTime(2));//reads the values of third column (DateTime) from DB
                    }

                    arrDate = valData.ToArray();
                    arrVal = values.ToArray();

                    count = (int)cmdCount.ExecuteScalar();
                    plot1.XAxes[0].ScaleDisplay.TextFormatting.Style = Iocomp.Types.TextFormatDoubleStyle.DateTime;
                    plot1.XAxes[0].ScaleRange.Span = 1.0 / 120.0 ; //30sec Span;

                    for (int i=0; i<count; i++)
                    {
                        plot1.Channels.Trace[0].AddXY(arrDate[i], arrVal[i]);
                    }

                    connection.Close();
                }
            }
        }
        MessageBox.Show("Nr. lines: " + count);
         Random().NextDouble() * 100);
    }
</code>```

答:
As already mentioned in the comments and proofed by your other command, you should use parameters. And here is how it should look in your case:

```<code>string stmt = "SELECT COUNT(*) FROM [dbo].[tbl_TagLogging] WHERE DateTime BETWEEN @DataStart AND @DataEnd";
using (var cmd = new SqlCommand(stmt))
{
    cmd.Parameters.Add("@DataStart", SqlDbType.DateTime).Value = dateStart.Value;
    cmd.Parameters.Add("@DataStop", SqlDbType.DateTime).Value = dateStop.Value;
    var reader = cmd.ExecuteReader();

    // Process the data from the reader.
}
</code>```

But maybe you should think about to completely drop these things and use Entity Framework (Core) and model your DBContext and just work with LINQ-to-SQL to retrieve data from your database.

Update

After you updated your question and posted the whole function, the problem is quite easy. You simply missed to add the parameters to your second query and added it only to the first one. So please update accordingly to something like this:

```<code>cmdCount.Parameters.Add("@DataStart", SqlDbType.DateTime).Value = dateStart.Value;
cmdCount.Parameters.Add("@DataStop", SqlDbType.DateTime).Value = dateStop.Value;
count = (int)cmdCount.ExecuteScalar();
</code>```

Nevertheless I hope this is not really your whole function, cause in that case requesting the count through this second query is completely useless. You use that value to iterate over the array you extracted from the first query. So my assumption would be that the variables arrDate.Length and arrVal.Length already contain the value that you need. So you should really check if these values (the length property of the array and the count result of your query) are the same and if not, why they differ and find the root cause for this issue. If they are the same, just use your local existing value and don't bother asking the SQL serverb for something you already know.

Body:
I have two DateTimePickers (dateStart and dateStop) in a winform. I've set dateStart and dateSop's format like this:

    dateStart.Format = DateTimePickerFormat.Custom;
    dateStart.CustomFormat = "yyyy:MM:dd HH:mm:ss";
    dateStop.Format = DateTimePickerFormat.Custom;
    dateStop.CustomFormat = "yyyy:MM:dd HH:mm:ss";

I want to count number of rows from my datebase's table between dateStart and dateStop.
My select string:

string stmt = "SELECT COUNT(*) FROM [dbo].[tbl_TagLogging] WHERE DateTime BETWEEN  " + Convert.ToString(dateStart.Value) + " AND " + Convert.ToString(dateStop.Value);

And it's result:

This is how link DateStart and DateStop paramaters of my datebase with DateTimePickers.

 cmd.Parameters.Add("@DataStart", SqlDbType.DateTime).Value = dateStart.Value;// new DateTime(dateStart.Value);
 cmd.Parameters.Add("@DataStop", SqlDbType.DateTime).Value = dateStop.Value;// new DateTime(2020, 02, 05, 13, 12, 25, 703);//2020, 02, 05, 13, 12, 25, 703   //2020, 02, 05, 13, 06, 50, 700

The row counting works perfectly without WHERE clause.

count = (int)cmdCount.ExecuteScalar();//this is how I count the rows

I'm getting here a 'System.Data.SqlClient.SqlException: Incorect syntax near 9'.

I kinda don't understand why if dateStart's format is  "yyyy:MM:dd HH:mm:ss", dateStart.value is returned in another format. On my UI, dateStart is displayed in the right format (the one from the code above). But I might have done something faulty in my stmt string.
Any thoughts on what is wrong?

EDIT 1 (my entire code):

 private void button_Click(object sender, EventArgs e)
    {
        dateStart.Format = DateTimePickerFormat.Custom;
        dateStart.CustomFormat = "yyyy:MM:dd HH:mm:ss";
        dateStop.Format = DateTimePickerFormat.Custom;
        dateStop.CustomFormat = "yyyy:MM:dd HH:mm:ss";
        string stmt = "SELECT COUNT(*) FROM [dbo].[tbl_TagLogging] WHERE DateTime BETWEEN  @DataStart AND @DataStop";         // WHERE DateTime BETWEEN  " + Convert.ToString(dateStart.Value) + " AND " + Convert.ToString(dateStop.Value)
       // string stmt = "SELECT COUNT(*) FROM [dbo].[tbl_TagLogging] WHERE DateTime BETWEEN  '" + Convert.ToString(dateStart.Value) + "' AND '" + Convert.ToString(dateStop.Value) + "'";
        int count = 0;

        using (SqlConnection connection = new SqlConnection(@"Data Source=DESKTOP-JQSJAF8\SQLEXPRESS;Initial Catalog=TRTF_TagLogging;Integrated Security=True; MultipleActiveResultSets = true"))
        {
            using (SqlCommand cmd = new SqlCommand("PS_TagLogging", connection))// used for stored proc
            {
                using (SqlCommand cmdCount = new SqlCommand(stmt, connection))//used to count number of rows of my table
                {
                    //yyyy:MM:dd hh:mm:ss
                    connection.Open();
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@DataStart", SqlDbType.DateTime).Value = dateStart.Value;
                    cmd.Parameters.Add("@DataStop", SqlDbType.DateTime).Value = dateStop.Value;
                    var values = new List<double>();
                    var valData = new List<DateTime>();
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        // values.Add(reader.GetInt64(0));//reads the values of first column (ID) from DB
                        values.Add(reader.GetFloat(1));//reads the values of second column (Tag1) from DB
                        valData.Add(reader.GetDateTime(2));//reads the values of third column (DateTime) from DB
                    }

                    arrDate = valData.ToArray();
                    arrVal = values.ToArray();

                    count = (int)cmdCount.ExecuteScalar();
                    plot1.XAxes[0].ScaleDisplay.TextFormatting.Style = Iocomp.Types.TextFormatDoubleStyle.DateTime;
                    plot1.XAxes[0].ScaleRange.Span = 1.0 / 120.0 ; //30sec Span;

                    for (int i=0; i<count; i++)
                    {
                        plot1.Channels.Trace[0].AddXY(arrDate[i], arrVal[i]);
                    }

                    connection.Close();
                }
            }
        }
        MessageBox.Show("Nr. lines: " + count);
         Random().NextDouble() * 100);
    }

Body:
As already mentioned in the comments and proofed by your other command, you should use parameters. And here is how it should look in your case:

string stmt = "SELECT COUNT(*) FROM [dbo].[tbl_TagLogging] WHERE DateTime BETWEEN @DataStart AND @DataEnd";
using (var cmd = new SqlCommand(stmt))
{
    cmd.Parameters.Add("@DataStart", SqlDbType.DateTime).Value = dateStart.Value;
    cmd.Parameters.Add("@DataStop", SqlDbType.DateTime).Value = dateStop.Value;
    var reader = cmd.ExecuteReader();

    // Process the data from the reader.
}

But maybe you should think about to completely drop these things and use Entity Framework (Core) and model your DBContext and just work with LINQ-to-SQL to retrieve data from your database.

Update

After you updated your question and posted the whole function, the problem is quite easy. You simply missed to add the parameters to your second query and added it only to the first one. So please update accordingly to something like this:

cmdCount.Parameters.Add("@DataStart", SqlDbType.DateTime).Value = dateStart.Value;
cmdCount.Parameters.Add("@DataStop", SqlDbType.DateTime).Value = dateStop.Value;
count = (int)cmdCount.ExecuteScalar();

Nevertheless I hope this is not really your whole function, cause in that case requesting the count through this second query is completely useless. You use that value to iterate over the array you extracted from the first query. So my assumption would be that the variables arrDate.Length and arrVal.Length already contain the value that you need. So you should really check if these values (the length property of the array and the count result of your query) are the same and if not, why they differ and find the root cause for this issue. If they are the same, just use your local existing value and don't bother asking the SQL serverb for something you already know.


问:
Google Firestore Setting Value Fails
I am writing from a Unity app - it is not an authentication issue as I have tried with an open db and a constrained one. The user is authenticated, I've checked the code at each step and I am seeing the expected values in all of the variables except the raw variable which is set to "{}" whereas initialUser as JSON is {"inventory": [], "saves": []}

```<code>        private void InitialiseUser(FirebaseUser user, Action<bool> callback) {
        LoadJsonAsset<UserData>("initialise/user", initialUser => {
            if (initialUser != null) {
                userDataRef.SetRawJsonValueAsync(JsonUtility.ToJson(initialUser)).ContinueWithOnMainThread(task => {
                    if (task.IsCompleted) {
                        userDataRef.GetValueAsync().ContinueWithOnMainThread(getTask => {
                            var raw = getTask.Result.GetRawJsonValue();
                            userSnapshot = getTask.Result;
                            callback(getTask.IsCompleted);
                        });
                    } else {
                        Debug.LogError("Unable to set initial user data");
                        callback(false);
                    }
                });
            } else {
                Debug.LogError("Unable to initialise user");
                callback(false);
            }
        });
    }
</code>```

Reducing the problem so that it is a little clearer:

```<code>        const string setRaw = "{\"inventory\":[],\"saves\":[]}";

        userDataRef.SetRawJsonValueAsync(setRaw).ContinueWithOnMainThread(setTask => {
            if (setTask.IsCompleted) {
                userDataRef.GetValueAsync().ContinueWithOnMainThread(getTask => {
                    var getRaw = getTask.Result.GetRawJsonValue();

                    Debug.Assert(getRaw == setRaw);
                });
            }
        });
</code>```

What I can see is that getRaw is set to "{}". It seems that if you have members that are empty arrays they are silently stripped out of the stored data and consequently the entire write silently fails.

If for example setRaw is set to "{\"inventory\":[\"test\"],\"saves\":[]}" then we get a saved record.

答:
So having answered my own question, I'll record it here for posterity.

The Firebase.Database.DatabaseReference.SetRawJsonValueAsync method will not write any members that point to an empty array, they are simply skipped and silently fail to be added to the database object. This is not mentioned in the documentation which states:

Set the data at this location to the given string json represenation.

Title: Google Firestore Setting Value Fails

Body:
I am writing from a Unity app - it is not an authentication issue as I have tried with an open db and a constrained one. The user is authenticated, I've checked the code at each step and I am seeing the expected values in all of the variables except the raw variable which is set to "{}" whereas initialUser as JSON is {"inventory": [], "saves": []}

        private void InitialiseUser(FirebaseUser user, Action<bool> callback) {
        LoadJsonAsset<UserData>("initialise/user", initialUser => {
            if (initialUser != null) {
                userDataRef.SetRawJsonValueAsync(JsonUtility.ToJson(initialUser)).ContinueWithOnMainThread(task => {
                    if (task.IsCompleted) {
                        userDataRef.GetValueAsync().ContinueWithOnMainThread(getTask => {
                            var raw = getTask.Result.GetRawJsonValue();
                            userSnapshot = getTask.Result;
                            callback(getTask.IsCompleted);
                        });
                    } else {
                        Debug.LogError("Unable to set initial user data");
                        callback(false);
                    }
                });
            } else {
                Debug.LogError("Unable to initialise user");
                callback(false);
            }
        });
    }

Reducing the problem so that it is a little clearer:

        const string setRaw = "{\"inventory\":[],\"saves\":[]}";

        userDataRef.SetRawJsonValueAsync(setRaw).ContinueWithOnMainThread(setTask => {
            if (setTask.IsCompleted) {
                userDataRef.GetValueAsync().ContinueWithOnMainThread(getTask => {
                    var getRaw = getTask.Result.GetRawJsonValue();

                    Debug.Assert(getRaw == setRaw);
                });
            }
        });

What I can see is that getRaw is set to "{}". It seems that if you have members that are empty arrays they are silently stripped out of the stored data and consequently the entire write silently fails.

If for example setRaw is set to "{\"inventory\":[\"test\"],\"saves\":[]}" then we get a saved record.


问:
How can I use a variable in a SqlDataSource SelectCommand?
So making a .Net site with VB and running off of a MySQL server.

Trying to use a variable within the connectionstring to only retrieve certain data.

I Currently have in the header:

```<code><script language="vbscript">
     Dim varSQLcommand as String

     varSQLcommand = "1"
</script>
</code>```

and the connection string of

```<code><asp:SqlDataSource ID="SqlDataSource1" runat="server"
    ConnectionString="<%$ ConnectionStrings:emergency systemsConnectionString3 %>"
    ProviderName="<%$ ConnectionStrings:emergency systemsConnectionString3.ProviderName %>"
    SelectCommand= "SELECT * from tbldisaster WHERE Disaster_ID = " & varSQLcommand & "" >
</asp:SqlDataSource>
</code>```

Going to replace varSQLcommand = "1" with varSQLcommand = Request.QueryString("ID") and make the url disasterdetails.aspx?ID={1}.

is this the Correct way to do what I want to do?

答:
You can use the SelectParameters to set custom variables in your SQL:

```<code>SelectCommand="SELECT * FROM tblDisaster WHERE Disaster_ID = @Disaster_ID">
    <SelectParameters>
        <asp:QueryStringParameter QueryStringField="ID" Name="Disaster_ID" />
    </SelectParameters>
</code>```

In this case, the filter criteria comes from the Query String (?id=123), so we use the QueryStringParameter, and bind it to parameter with name @Disaster_ID.  Then the query will pull the id value from the url and replace it where @Disaster_ID appears in the query.

Body:
So making a .Net site with VB and running off of a MySQL server.

Trying to use a variable within the connectionstring to only retrieve certain data.

I Currently have in the header:

and the connection string of

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
    ConnectionString="<%$ ConnectionStrings:emergency systemsConnectionString3 %>"
    ProviderName="<%$ ConnectionStrings:emergency systemsConnectionString3.ProviderName %>"
    SelectCommand= "SELECT * from tbldisaster WHERE Disaster_ID = " & varSQLcommand & "" >
</asp:SqlDataSource>

Going to replace varSQLcommand = "1" with varSQLcommand = Request.QueryString("ID") and make the url disasterdetails.aspx?ID={1}.

is this the Correct way to do what I want to do?

Body:
You can use the SelectParameters to set custom variables in your SQL:

SelectCommand="SELECT * FROM tblDisaster WHERE Disaster_ID = @Disaster_ID">
    <SelectParameters>
        <asp:QueryStringParameter QueryStringField="ID" Name="Disaster_ID" />
    </SelectParameters>

In this case, the filter criteria comes from the Query String (?id=123), so we use the QueryStringParameter, and bind it to parameter with name @Disaster_ID.  Then the query will pull the id value from the url and replace it where @Disaster_ID appears in the query.


问:
Navigating between two fragments on backpress
I am having trouble going back to previous fragment on backpress from current fragment.
I have Two fragments and i navigate to second fragment on click and when i try to click back from the second fragment, i want to go back to the previous fragment but instead the app exits on backpress. below is the code i am using..

Fragment1 calling second fragment

```<code>    UserFragment frag = new UserFragment()
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        frag.setArguments(bundle);
        transaction.addToBackStack("UserActivity");
             transaction.replace(android.R.id.content, frag, "UserActivity").addToBackStack(null);
transaction.commit();
</code>```

In second Fragment i have implemented an interface OnBackpress and over riding the below method

```<code>@Override
public void onBackPressed() {

    if (getFragmentManager().getBackStackEntryCount() != 0) {
        if(getFragmentManager().findFragmentByTag("UserActivity") != null){
            Log.e("UserActivity",getFragmentManager().findFragmentByTag("UserActivity").toString());
            getFragmentManager().popBackStack();
        };
    }

}
</code>```

But on back press the app exits. Instead i want to go back to previous fragment. What mistake am i doing? please help. thanks

答:
please change to add() instead of replace() in your code..

```<code>    UserFragment frag = new UserFragment()
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    frag.setArguments(bundle);
    transaction.addToBackStack("UserActivity");
    transaction.add(android.R.id.content, frag, "UserActivity").addToBackStack(null);
    transaction.commit();
</code>```

This will solve your problem.

Body:
I am having trouble going back to previous fragment on backpress from current fragment.
I have Two fragments and i navigate to second fragment on click and when i try to click back from the second fragment, i want to go back to the previous fragment but instead the app exits on backpress. below is the code i am using..

Fragment1 calling second fragment

    UserFragment frag = new UserFragment()
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        frag.setArguments(bundle);
        transaction.addToBackStack("UserActivity");
             transaction.replace(android.R.id.content, frag, "UserActivity").addToBackStack(null);
transaction.commit();

In second Fragment i have implemented an interface OnBackpress and over riding the below method

@Override
public void onBackPressed() {

    if (getFragmentManager().getBackStackEntryCount() != 0) {
        if(getFragmentManager().findFragmentByTag("UserActivity") != null){
            Log.e("UserActivity",getFragmentManager().findFragmentByTag("UserActivity").toString());
            getFragmentManager().popBackStack();
        };
    }

}

But on back press the app exits. Instead i want to go back to previous fragment. What mistake am i doing? please help. thanks

Body:
please change to add() instead of replace() in your code..

    UserFragment frag = new UserFragment()
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    frag.setArguments(bundle);
    transaction.addToBackStack("UserActivity");
    transaction.add(android.R.id.content, frag, "UserActivity").addToBackStack(null);
    transaction.commit();

This will solve your problem.


问:
Azure Storage SAS signature does not match, how can I generate SAS token?
I'm having some problems generating SAS token to download the file of Azure Storage. The following produces a URI that does not work. The error message I get back is Signature did not match, and I'm uncertain why.

Has anyone generated SAS tokens, and got the signature to match manually?

```<code>    static void Main(string[] args)
    {
        var sas = generateSAS
        (
            key,            // Azure portal very secret ^-^
            keyName,        // Azure portal, example: key1
            resourceUri,    // example: https://myaccount.blob.core.windows.net/emails/email.pdf
            resourcePath    // example: /blob/myaccount/emails/email.pdf
        );
    }

    private static string generateSAS(string key, string keyName, string uri, string path)
    {
        var permissions = "r";
        var startTime = DateTime.UtcNow;
        var endTime = DateTime.UtcNow.AddSeconds(60 * 2);
        var canonicalizedresource = path;
        var signedidentifier = keyName;
        var signedversion = "2012-02-12";

        var stringToSign = permissions + "\n" +
                           startTime.ToUniversalTime().ToString("u").Replace(" ", "T") + "\n" +
                           endTime.ToUniversalTime().ToString("u").Replace(" ", "T") + "\n" +
                           canonicalizedresource + "\n" +
                           signedidentifier + "\n" +
                           signedversion;

        HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));

        var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));

        return string.Format(CultureInfo.InvariantCulture, "{0}?sp={1}&st={2}&se={3}&spr={4}&sv={5}&sr={6}&si={7}&sig={8}",
            uri,
            permissions,
            startTime.ToUniversalTime().ToString("u").Replace(" ", "T"),
            endTime.ToUniversalTime().ToString("u").Replace(" ", "T"),
            "https",
            signedversion,
            "b",
            keyName,
            HttpUtility.UrlEncode(signature));
    }
</code>```

答:
Please try the code below, it generates a valid sas token for me:</p>

```<code>private static string generateSAS(string resourceUri, string account_name, string key)
{
    var accountName = account_name;
    var accountKey = key;
    var start = DateTime.UtcNow.AddHours(-2).ToString("yyyy-MM-ddTHH:mm:ssZ");
    var end = DateTime.UtcNow.AddHours(2).ToString("yyyy-MM-ddTHH:mm:ssZ");
    var permission = "rwdlac";
    var serviceType = "b";
    var resourceTypes = "sco";
    var protocol = "https";
    var serviceVersion = "2019-02-02";

    //here is the difference from your code.
    var stringToSign = string.Format("{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n{8}\n",accountName, permission,serviceType,resourceTypes,start,end,"",protocol,serviceVersion);

    HMACSHA256 hmac = new HMACSHA256(Convert.FromBase64String(accountKey));
    string signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
    var sasToken = string.Format("?sv={0}&ss={1}&srt={2}&sp={3}&se={4}&st={5}&spr={6}&sig={7}", serviceVersion,
        serviceType, resourceTypes, permission, end, start, protocol, HttpUtility.UrlEncode(signature));

    var urlToListTables = resourceUri + sasToken;

    return urlToListTables;
}
</code>```

Body:
I'm having some problems generating SAS token to download the file of Azure Storage. The following produces a URI that does not work. The error message I get back is Signature did not match, and I'm uncertain why.

Has anyone generated SAS tokens, and got the signature to match manually?

    static void Main(string[] args)
    {
        var sas = generateSAS
        (
            key,            // Azure portal very secret ^-^
            keyName,        // Azure portal, example: key1
            resourceUri,    // example: https://myaccount.blob.core.windows.net/emails/email.pdf
            resourcePath    // example: /blob/myaccount/emails/email.pdf
        );
    }

    private static string generateSAS(string key, string keyName, string uri, string path)
    {
        var permissions = "r";
        var startTime = DateTime.UtcNow;
        var endTime = DateTime.UtcNow.AddSeconds(60 * 2);
        var canonicalizedresource = path;
        var signedidentifier = keyName;
        var signedversion = "2012-02-12";

        var stringToSign = permissions + "\n" +
                           startTime.ToUniversalTime().ToString("u").Replace(" ", "T") + "\n" +
                           endTime.ToUniversalTime().ToString("u").Replace(" ", "T") + "\n" +
                           canonicalizedresource + "\n" +
                           signedidentifier + "\n" +
                           signedversion;

        HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));

        var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));

        return string.Format(CultureInfo.InvariantCulture, "{0}?sp={1}&st={2}&se={3}&spr={4}&sv={5}&sr={6}&si={7}&sig={8}",
            uri,
            permissions,
            startTime.ToUniversalTime().ToString("u").Replace(" ", "T"),
            endTime.ToUniversalTime().ToString("u").Replace(" ", "T"),
            "https",
            signedversion,
            "b",
            keyName,
            HttpUtility.UrlEncode(signature));
    }

Body:
Please try the code below, it generates a valid sas token for me:

private static string generateSAS(string resourceUri, string account_name, string key)
{
    var accountName = account_name;
    var accountKey = key;
    var start = DateTime.UtcNow.AddHours(-2).ToString("yyyy-MM-ddTHH:mm:ssZ");
    var end = DateTime.UtcNow.AddHours(2).ToString("yyyy-MM-ddTHH:mm:ssZ");
    var permission = "rwdlac";
    var serviceType = "b";
    var resourceTypes = "sco";
    var protocol = "https";
    var serviceVersion = "2019-02-02";

    //here is the difference from your code.
    var stringToSign = string.Format("{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n{8}\n",accountName, permission,serviceType,resourceTypes,start,end,"",protocol,serviceVersion);

    HMACSHA256 hmac = new HMACSHA256(Convert.FromBase64String(accountKey));
    string signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
    var sasToken = string.Format("?sv={0}&ss={1}&srt={2}&sp={3}&se={4}&st={5}&spr={6}&sig={7}", serviceVersion,
        serviceType, resourceTypes, permission, end, start, protocol, HttpUtility.UrlEncode(signature));

    var urlToListTables = resourceUri + sasToken;

    return urlToListTables;
}


问:
Hashmap. Find key(s) which have same values between two hashmaps
Lets consider we have two hashmaps as below:

```<code> HashMap<String, Integer> map1  = new HashMap<>();
 map1.put("vishal", 10);
 map1.put("sachin", 30);
 map1.put("vaibhav", 20);

 HashMap<String, Integer> map2  = new HashMap<>();
 map2.put("Raja", 10);
 map2.put("John", 30);
 map2.put("Krishna", 20);
</code>```

The "vaibhav" from map1 and "krishna" from map2 have the same values.

I need to find the keys from both the maps, which have the same values. In this case, "vaibhav" and "Krishna".

Thanks.

答:
This can be achieved through two for loops with a complexity of n*m, where n.m is the size of each map.

```<code>Map<String, String> map1 = new HashMap<>();
map1.put("santhosh", "1");
map1.put("raja", "2");
map1.put("arun", "3");

Map<String, String> map2 = new HashMap<>();
map2.put("kumar", "1");
map2.put("mani", "1");
map2.put("tony", "3");

for (Map.Entry<String, String> entry1 : map1.entrySet()) {
  String key1 = entry1.getKey();
  String value1 = entry1.getValue();

  for (Map.Entry<String, String> entry2 : map2.entrySet()) {
    String key2 = entry2.getKey();
    String value2 = entry2.getValue();

    if (value1 == value2) {
      System.out.println(key1 + " " + key2);
    }
    }
</code>```

Thanks.

Body:
Lets consider we have two hashmaps as below:

 HashMap<String, Integer> map1  = new HashMap<>();
 map1.put("vishal", 10);
 map1.put("sachin", 30);
 map1.put("vaibhav", 20);

 HashMap<String, Integer> map2  = new HashMap<>();
 map2.put("Raja", 10);
 map2.put("John", 30);
 map2.put("Krishna", 20);

The "vaibhav" from map1 and "krishna" from map2 have the same values.

I need to find the keys from both the maps, which have the same values. In this case, "vaibhav" and "Krishna".

Thanks.

Body:
This can be achieved through two for loops with a complexity of n*m, where n.m is the size of each map.

Map<String, String> map1 = new HashMap<>();
map1.put("santhosh", "1");
map1.put("raja", "2");
map1.put("arun", "3");

Map<String, String> map2 = new HashMap<>();
map2.put("kumar", "1");
map2.put("mani", "1");
map2.put("tony", "3");

for (Map.Entry<String, String> entry1 : map1.entrySet()) {
  String key1 = entry1.getKey();
  String value1 = entry1.getValue();

  for (Map.Entry<String, String> entry2 : map2.entrySet()) {
    String key2 = entry2.getKey();
    String value2 = entry2.getValue();

    if (value1 == value2) {
      System.out.println(key1 + " " + key2);
    }
    }

Thanks.


问:
Illegal String offset in php (Laravel 5.1)
In lang.php file has the following array.

```<code>"animal" => [
           "mammel"=>[
              "cat" => "Cat",
              "ele" => "Elephant",
              "dog" => "Dog"
            ]
        ]

$r_animal = str_ireplace($lm, trans('lang.animal.mammel')[strtolower(substr($lm, 0, 3))], $r_animal);
</code>```

In above line give the error as Illegal String offset 'ele' .

答:
To access the translations you would need something like trans('lang.animal.mammel.cat'), trans('lang.animal.mammel.ele') or trans('lang.animal.mammel.dog'). Assuming strtolower(substr($lm, 0, 3)) contains either "cat", "ele" or "dog" you could concatenate the required translation key like so:

```<code>$translationKey = 'lang.animal.mammel.' . strtolower(substr($lm, 0, 3));
$r_animal = str_ireplace($lm, trans($translationKey), $r_animal);
</code>```

Body:
In lang.php file has the following array.

"animal" => [
           "mammel"=>[
              "cat" => "Cat",
              "ele" => "Elephant",
              "dog" => "Dog"
            ]
        ]

$r_animal = str_ireplace($lm, trans('lang.animal.mammel')[strtolower(substr($lm, 0, 3))], $r_animal);

In above line give the error as Illegal String offset 'ele' .

Body:
To access the translations you would need something like trans('lang.animal.mammel.cat'), trans('lang.animal.mammel.ele') or trans('lang.animal.mammel.dog'). Assuming strtolower(substr($lm, 0, 3)) contains either "cat", "ele" or "dog" you could concatenate the required translation key like so:

$translationKey = 'lang.animal.mammel.' . strtolower(substr($lm, 0, 3));
$r_animal = str_ireplace($lm, trans($translationKey), $r_animal);


问:
AWS CodeDeploy hooks scripts execution location
I am currently using CodeDeploy for a NodeJS application of mine and I just have 1 burning question, is there a way to instruct say, my BeforeInstall script to run on the revision root instead of the root directory of my Linux OS?

For instance, the BeforeInstall hook script of mine may looks like this:

```<code>#!/bin/bash
echo "Current directory: "
echo $PWD
echo `ls`
# Do actual stuff here
</code>```

By looking at the log it seemed to me that the script is ran on / (OS root), how do I instruct it to run on the revision root? I know I can CD into /opt/codedeploy-agent/deployment-root/app-id/deployment-id but it just seemed like a hassle to me to retrieve the app id and deployment id every time.

答:
Use cd "$(dirname "${BASH_SOURCE[0]}")" to change directory to the script directory of this deployment.

Example: cd /opt/codedeploy-agent/deployment-root/940bf299-698b-4179-a49f-f221316c1776/d-K24U7DAD1/deployment-archive/scripts

Body:
I am currently using CodeDeploy for a NodeJS application of mine and I just have 1 burning question, is there a way to instruct say, my BeforeInstall script to run on the revision root instead of the root directory of my Linux OS?

For instance, the BeforeInstall hook script of mine may looks like this:

#!/bin/bash
echo "Current directory: "
echo $PWD
echo `ls`
# Do actual stuff here

By looking at the log it seemed to me that the script is ran on / (OS root), how do I instruct it to run on the revision root? I know I can CD into /opt/codedeploy-agent/deployment-root/app-id/deployment-id but it just seemed like a hassle to me to retrieve the app id and deployment id every time.


问:
How do I iterate of the object containing queries, and execute them all
I have an object that looks like this:

```<code>let queries = [
  {
    name: "checkUsers",
    query: 'select * from users where inactive = 1'
  },
  {
    name: "checkSubscriptions",
    query: 'select * from subscriptions where invalid = 1'
  }
]
</code>```

I am making an AWS Lambda function that will iterate these queries, and if any of them returns a value, I will send an email.

I have come up with this pseudo code:

```<code>for (let prop in queries) {

  const result = await mysqlConnector.runQuery(prop.query).catch(async error => {
    // handle error in query
  });

  if (result.length < 0){
    // send email
  }
}

return;
</code>```

I am wondering is this ideal approach? I need to iterate all the object queries.

答:
I don't see anything wrong with what you are trying to achieve but there are few changes you could do

Try to use Promise.all if you can. This will speed up the overall process as things will execute in parallel. It will depend on number of queries as well.

Try leverage executing multiple statements in one query. This way you will make one call and then you can add the logic to identify. Check here

Body:
I have an object that looks like this:

let queries = [
  {
    name: "checkUsers",
    query: 'select * from users where inactive = 1'
  },
  {
    name: "checkSubscriptions",
    query: 'select * from subscriptions where invalid = 1'
  }
]

I am making an AWS Lambda function that will iterate these queries, and if any of them returns a value, I will send an email.

I have come up with this pseudo code:

for (let prop in queries) {

  const result = await mysqlConnector.runQuery(prop.query).catch(async error => {
    // handle error in query
  });

  if (result.length < 0){
    // send email
  }
}

return;

I am wondering is this ideal approach? I need to iterate all the object queries.


问:
Is the PHP CURL api cleaner/faster/better than using streams for HTTP/HTTPS access?
I currently use pretty exclusively the PHP stream context functionality (see http://us2.php.net/manual/en/function.stream-context-create.php) to access HTTP resources and I've been able to successfully use it to do PUTs, DELETEs, POSTs, manage cookies and do just about everything I've needed to do. I originally started using it because I had SSL issues with earlier Debian PHP cURL builds (there was an OpenSSL double-initialization issue within the Apache process that errored out when trying to access SSL urls): those are probably fixed now but I've not had occasion to go back.

In discussions with a friend he contended that the cURL api is faster/better so I wanted to ask: is there any definite experience/knowledge about which option is superior, and in what ways?

答:
Streams are pretty neat in my experience. You probably know it already, but here's a post on streams with a twist in case not:

http://fabien.potencier.org/article/44/php-iterators-and-streams-are-awesome

Curl is nice and fast, and simple; but I honestly wouldn't prefer one or the other for performance reasons. I've never measured but I doubt it makes that much of a difference in comparison with the overhead of doing a remote request in the first place.


问:
Sample for Entity Framework 6 + Code First + Oracle 12c
I have a problem with a Visual Studio solution using Entity Framework 6 + Code First + Oracle 12c. I'm not sure it is properly configured, or if I missed something simple.

I tried to look for a sample project as a start, but was not able to find - google search, stackoverflow etc.

Is there a minimalistic sample project somewhere, which tries to create the database when runs?

Update: Just to make sure, I'm not asking anyone to create a sample for me. Before I'll do it, I want to make sure there is really no existing sample (which is strange for me, but very well might be the case).

答:
I spent days fixing this issue... Finally I solved it:

The table did not exist. I checked many times and refreshed, but the problem was not in the table itself, it was with the sequence. Every table in Oracle creates a sequence object to increase the id. So, if you delete the table make sure to drop the sequence as well, otherwise when you migrate again, it will give you ORA-00955: name is already used by an existing object.

So, the real problem is in the sequence, not in the table. But you cannot create new sequence because it already exists. It is not deleted when you delete the table, it should be deleted manually.

I hope this will help someone.


问:
get time from places local time
I am currently using

```<code>SimpleDateFormat localDateFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());
</code>```

to get the time of a place, which obviously returning the time in devices's current location, not of the location searched.

Is there any (easy) way to change the behaviour and get the time as the local time of the location searched?

答:
Please try this

```<code>val formatter = SimpleDateFormat("yyyyMMddHHmm")
formatter.timeZone = TimeZone.getTimeZone("GMT+7:00")
</code>```

And when you want to format it just use.

```<code>formatter.format(Date())
</code>```

Title: get time from places local time

Body:
I am currently using

SimpleDateFormat localDateFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());

to get the time of a place, which obviously returning the time in devices's current location, not of the location searched.

Is there any (easy) way to change the behaviour and get the time as the local time of the location searched?

Body:
Please try this

val formatter = SimpleDateFormat("yyyyMMddHHmm")
formatter.timeZone = TimeZone.getTimeZone("GMT+7:00")

And when you want to format it just use.

formatter.format(Date())


问:
EntityDbContext SaveChanges : What are the differences between these two codes?
In order to performance, exception capturing and etc., What are the differences between these two codes:

```<code>           int count = 0;
           foreach (var record in SomeDbEntityList)
            {
                count++;
                dbContext.SomeDbEntity.Add(record);
                if (count > 500)
                {
                  dbContext.SaveChanges();
                  count = 0;
                }
            }
            //LeftOver
            if (count > 0)
                dbContext.SaveChanges();
</code>```

The direct code:

```<code>            foreach (var record in SomeDbEntityList)
            {
                dbContext.SomeDbEntity.Add(record);
                dbContext.SaveChanges();
            }
</code>```

答:
The first code saves the new changes on the DB after 500 (or less)
records are entity, so 500 updates/inserts are made to the DB on the
same time.

Advantages: you don't go for every record in the DB.

Disadvantages: if any of these records have an error (issue), than none of the records will be updated.

The second code saves directly to the DB.

Please take a look at Unit of Work design pattern.

Body:
In order to performance, exception capturing and etc., What are the differences between these two codes:

           int count = 0;
           foreach (var record in SomeDbEntityList)
            {
                count++;
                dbContext.SomeDbEntity.Add(record);
                if (count > 500)
                {
                  dbContext.SaveChanges();
                  count = 0;
                }
            }
            //LeftOver
            if (count > 0)
                dbContext.SaveChanges();

The direct code:

            foreach (var record in SomeDbEntityList)
            {
                dbContext.SomeDbEntity.Add(record);
                dbContext.SaveChanges();
            }


问:
Add custom icon to drawer navigation
I am trying to add custom icon to my CustomDrawerComponent, but nothing happen...

App.js :

```<code>const navigationOptions = {
  headerTintColor: colors.white,
};

const drawerNavigationOption = ({ navigation }) => ({
  ...navigationOptions,
  headerLeft: (
    <TouchableOpacity onPress={() => navigation.toggleDrawer()}>
      <View>
        <Icon name="menu" size={24} color={colors.white} />
      </View>
    </TouchableOpacity>
  ),
});

const MapsStackNavigator = createStackNavigator({
  MapsNavigator: {
    screen: MapsScreen,
    navigationOptions: drawerNavigationOption,
  },
});

const AppDrawerNavigator = createDrawerNavigator(
  {
    Plans: MapsStackNavigator,
  },
  {
    contentComponent: CustomDrawerMenu,
    contentOptions: {
      inactiveTintColor: colors.doveGrey,
      activeTintColor: colors.doveGrey,
    },
  }
);
</code>```

My CustomDrawerMenu.js :

```<code>export default class CustomDrawerMenu extends Component {
  render() {
    return (
      <ScrollView
        contentContainerStyle={{
          flex: 1,
          flexDirection: "column",
          justifyContent: "space-between",
        }}
      >
        <SafeAreaView forceInset={{ top: "always", horizontal: "never" }}>
          {...}
          <DrawerItems {...this.props} />
        </SafeAreaView>
        {...}
      </ScrollView>
    );
  }
}
</code>```

My MapsScreen :

```<code>export default class MapsScreen extends React.Component {
  static navigationOptions = {
    drawerIcon: (
      <Image
        style={{ width: 24, height: 24 }}
        source={require("../../assets/icons/plan.png")}
      />
    ),
    title: "Plans",
  };

  render() {
    return (
      <Text>My map screen</Text>
    );
  }
}
</code>```

But absolutely nothing happened... I tried to add drawerIcon to my App.js > const navigationOptions but nothing happened aswell.

I do not really know where to place drawerIconm because I search on the doc, on some YouTubes video and when I reproduced the same, it does not work.

Thank you.

答:
In the new version of react-navigation(5.x)

You have to do :

1-

```<code>import { createDrawerNavigator } from '@react-navigation/drawer';
import { NavigationContainer } from '@react-navigation/native';
import Icon from 'react-native-vector-icons/Ionicons';
</code>```

2- Instead of using createDrawerNavigator you have to use Drawer.Navigator as below :

```<code><NavigationContainer>
    <Drawer.Navigator
        initialRouteName="Products">

        <Drawer.Screen name="Products" component={YOUR COMPONENT OR YOUR STACKNAVIGATOR} options={{
            drawerIcon: config => <Icon
                size={23}
                name={Platform.OS === 'android' ? 'md-list' : 'ios-list'}></Icon>
        }} />

        <Drawer.Screen name="Orders" component={YOUR COMPONENT OR YOUR STACKNAVIGATOR} options={{
            drawerIcon: config => <Icon
                size={23}
                name={Platform.OS === 'android' ? 'md-create' : 'ios-create'}></Icon>
        }} />

    </Drawer.Navigator>
</NavigationContainer>
</code>```

Title: Add custom icon to drawer navigation

Body:
I am trying to add custom icon to my CustomDrawerComponent, but nothing happen...

App.js :

const navigationOptions = {
  headerTintColor: colors.white,
};

const drawerNavigationOption = ({ navigation }) => ({
  ...navigationOptions,
  headerLeft: (
    <TouchableOpacity onPress={() => navigation.toggleDrawer()}>
      <View>
        <Icon name="menu" size={24} color={colors.white} />
      </View>
    </TouchableOpacity>
  ),
});

const MapsStackNavigator = createStackNavigator({
  MapsNavigator: {
    screen: MapsScreen,
    navigationOptions: drawerNavigationOption,
  },
});

const AppDrawerNavigator = createDrawerNavigator(
  {
    Plans: MapsStackNavigator,
  },
  {
    contentComponent: CustomDrawerMenu,
    contentOptions: {
      inactiveTintColor: colors.doveGrey,
      activeTintColor: colors.doveGrey,
    },
  }
);

My CustomDrawerMenu.js :

export default class CustomDrawerMenu extends Component {
  render() {
    return (
      <ScrollView
        contentContainerStyle={{
          flex: 1,
          flexDirection: "column",
          justifyContent: "space-between",
        }}
      >
        <SafeAreaView forceInset={{ top: "always", horizontal: "never" }}>
          {...}
          <DrawerItems {...this.props} />
        </SafeAreaView>
        {...}
      </ScrollView>
    );
  }
}

My MapsScreen :

export default class MapsScreen extends React.Component {
  static navigationOptions = {
    drawerIcon: (
      <Image
        style={{ width: 24, height: 24 }}
        source={require("../../assets/icons/plan.png")}
      />
    ),
    title: "Plans",
  };

  render() {
    return (
      <Text>My map screen</Text>
    );
  }
}

But absolutely nothing happened... I tried to add drawerIcon to my App.js > const navigationOptions but nothing happened aswell.

I do not really know where to place drawerIconm because I search on the doc, on some YouTubes video and when I reproduced the same, it does not work.

Thank you.

Body:
In the new version of react-navigation(5.x)

You have to do :

1-

import { createDrawerNavigator } from '@react-navigation/drawer';
import { NavigationContainer } from '@react-navigation/native';
import Icon from 'react-native-vector-icons/Ionicons';

2- Instead of using createDrawerNavigator you have to use Drawer.Navigator as below :

<NavigationContainer>
    <Drawer.Navigator
        initialRouteName="Products">

        <Drawer.Screen name="Products" component={YOUR COMPONENT OR YOUR STACKNAVIGATOR} options={{
            drawerIcon: config => <Icon
                size={23}
                name={Platform.OS === 'android' ? 'md-list' : 'ios-list'}></Icon>
        }} />

        <Drawer.Screen name="Orders" component={YOUR COMPONENT OR YOUR STACKNAVIGATOR} options={{
            drawerIcon: config => <Icon
                size={23}
                name={Platform.OS === 'android' ? 'md-create' : 'ios-create'}></Icon>
        }} />

    </Drawer.Navigator>
</NavigationContainer>


问:
SpringBoot : Expand Child Object in RestController Response
Good Morning Community,

I am new to SringBoot (and Java).

I can't succeed to do a simple task : Create a controller that return a Car and its Driver in json.

I have this response :

{"color":"red","driver":"example"}

I want :

{"color":"red","driver":{"name": "example"}}

Is it possible to do it without an ObjectMapper, I hope there is an annotation that do the trick.

Thank you for your time, have a nice day.

My Controller :

```<code>
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CarController {

    @GetMapping("/car/{driverName}")
    public Car cars(
            @PathVariable(value = "driverName") String driverName
    ) {
        driverName = "example";
        Driver driver = new Driver();
        driver.setName(driverName);
        Car car = new Car();
        car.setDriver(driver);
       return car;
    }
}
</code>```

My Car Class :

```<code>
import org.springframework.stereotype.Component;

import java.io.Serializable;

@Component
public class Car {

    public Driver driver;
    public String color ="red";

    public Car() {
    }

    public String getDriver() {
        return this.driver;
    }

    public String getColor() {
        return color;
    }

    public void setDriver(Driver driver) {
        this.driver = driver;
    }

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

My Driver Class :

```<code>
import org.springframework.stereotype.Component;

import java.io.Serializable;

@Component
public class Driver {

    public String name;

    public Driver() {
    }

    public String getName() {
        return this.name;
    }

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

答:
You have a problem in your Car class, the getDriver method returns a String but it should return the Driver object, try with:

```<code>import org.springframework.stereotype.Component;

import java.io.Serializable;

@Component
public class Car {

    public Driver driver;
    public String color ="red";

    public Car() {
    }

    public Driver getDriver() {
        return this.driver;
    }

    public String getColor() {
        return color;
    }

    public void setDriver(Driver driver) {
        this.driver = driver;
    }

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

Body:
Good Morning Community,

I am new to SringBoot (and Java).

I can't succeed to do a simple task : Create a controller that return a Car and its Driver in json.

I have this response :

{"color":"red","driver":"example"}

I want :

{"color":"red","driver":{"name": "example"}}

Is it possible to do it without an ObjectMapper, I hope there is an annotation that do the trick.

Thank you for your time, have a nice day.

My Controller :

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CarController {

    @GetMapping("/car/{driverName}")
    public Car cars(
            @PathVariable(value = "driverName") String driverName
    ) {
        driverName = "example";
        Driver driver = new Driver();
        driver.setName(driverName);
        Car car = new Car();
        car.setDriver(driver);
       return car;
    }
}

My Car Class :

import org.springframework.stereotype.Component;

import java.io.Serializable;

@Component
public class Car {

    public Driver driver;
    public String color ="red";

    public Car() {
    }

    public String getDriver() {
        return this.driver;
    }

    public String getColor() {
        return color;
    }

    public void setDriver(Driver driver) {
        this.driver = driver;
    }

    public void setColor(String color) {
        this.color = color;
    }
}

My Driver Class :

import org.springframework.stereotype.Component;

import java.io.Serializable;

@Component
public class Driver {

    public String name;

    public Driver() {
    }

    public String getName() {
        return this.name;
    }

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

Body:
You have a problem in your Car class, the getDriver method returns a String but it should return the Driver object, try with:

import org.springframework.stereotype.Component;

import java.io.Serializable;

@Component
public class Car {

    public Driver driver;
    public String color ="red";

    public Car() {
    }

    public Driver getDriver() {
        return this.driver;
    }

    public String getColor() {
        return color;
    }

    public void setDriver(Driver driver) {
        this.driver = driver;
    }

    public void setColor(String color) {
        this.color = color;
    }
}


问:
Matching string from one file to another file and append the values
I have two text files with 350 m+ rows. Content of two text files are as follows:

```<code>file1:
>15_48499991_ENSG00000074803_C_G_G
CCAATCGCTTTCAAGTTAGTGTG
>15_48499991_ENSG00000074803_C_G_G
CAATCGCTTTCAAGTTAGTGTGA
>15_48499991_ENSG00000074803_C_G_G
AATCGCTTTCAAGTTAGTGTGAT

</code>```

```<code>file2:
CCAATCGCTTTCAAGTTAGTGTG -14.48
CAATCGCTTTCAAGTTAGTGTGA -29.94
AATCGCTTTCAAGTTAGTGTGAT -20.58

</code>```

I would like to match the value of column 1 of file 2 and the string in file1 and append the value after > of file1 with file2 whenever there is a match.

The desired output is:

```<code>15_48499991_ENSG00000074803_C_G_G    CCAATCGCTTTCAAGTTAGTGTG    -14.48
15_48499991_ENSG00000074803_C_G_G    CAATCGCTTTCAAGTTAGTGTGA    -29.94
15_48499991_ENSG00000074803_C_G_G    AATCGCTTTCAAGTTAGTGTGAT    -20.58
</code>```

Any suggestions would be helpful here.

Thanks

答:
Try this:</p>

```<code>with open( 'file2' ) as fin :
    data = { i.strip().split() for i in fin }

with open( 'file1' ) as fin :
    for line in fin :
        if line.startswith('>') :
            print line[1:].strip(),
        else :
            stripped = line.strip()
            print stripped, data[stripped]
</code>```

Body:
I have two text files with 350 m+ rows. Content of two text files are as follows:

file1:
>15_48499991_ENSG00000074803_C_G_G
CCAATCGCTTTCAAGTTAGTGTG
>15_48499991_ENSG00000074803_C_G_G
CAATCGCTTTCAAGTTAGTGTGA
>15_48499991_ENSG00000074803_C_G_G
AATCGCTTTCAAGTTAGTGTGAT

file2:
CCAATCGCTTTCAAGTTAGTGTG -14.48
CAATCGCTTTCAAGTTAGTGTGA -29.94
AATCGCTTTCAAGTTAGTGTGAT -20.58

I would like to match the value of column 1 of file 2 and the string in file1 and append the value after > of file1 with file2 whenever there is a match.

The desired output is:

15_48499991_ENSG00000074803_C_G_G    CCAATCGCTTTCAAGTTAGTGTG    -14.48
15_48499991_ENSG00000074803_C_G_G    CAATCGCTTTCAAGTTAGTGTGA    -29.94
15_48499991_ENSG00000074803_C_G_G    AATCGCTTTCAAGTTAGTGTGAT    -20.58

Any suggestions would be helpful here.

Thanks

Body:
Try this:

with open( 'file2' ) as fin :
    data = { i.strip().split() for i in fin }

with open( 'file1' ) as fin :
    for line in fin :
        if line.startswith('>') :
            print line[1:].strip(),
        else :
            stripped = line.strip()
            print stripped, data[stripped]


问:
add two lists then sort = None(?)
Second list squared each item on list, xs. Running the code below, python gives me 'None'

```<code>xs = [12, 10, 32, 3, 66, 17, 42, 99, 20]
a = [b**2 for b in xs]
c = (a + xs).sort()
print(c, end=', ')
</code>```

Same list but different code--

```<code>xs = [12, 10, 32, 3, 66, 17, 42, 99, 20]
a = [b**2 for b in xs]
c = a + xs
c.sort()
print(c, end=', ')
</code>```

...python gives me my list(c), all sorted. I don't get it. Or is there a more pythonic way to do this?

Thanks!

答:
You use generator expressions and itertools to reduce the amount of temporary storage like this</p>

```<code>>>> import itertools
>>> xs = [12, 10, 32, 3, 66, 17, 42, 99, 20]
>>> a = (b**2 for b in xs)
>>> c = sorted(itertools.chain(a, xs))
>>> c
[3, 9, 10, 12, 17, 20, 32, 42, 66, 99, 100, 144, 289, 400, 1024, 1764, 4356, 9801]
</code>```

Title: add two lists then sort = None(?)

Body:
Second list squared each item on list, xs. Running the code below, python gives me 'None'

xs = [12, 10, 32, 3, 66, 17, 42, 99, 20]
a = [b**2 for b in xs]
c = (a + xs).sort()
print(c, end=', ')

Same list but different code--

xs = [12, 10, 32, 3, 66, 17, 42, 99, 20]
a = [b**2 for b in xs]
c = a + xs
c.sort()
print(c, end=', ')

...python gives me my list(c), all sorted. I don't get it. Or is there a more pythonic way to do this?

Thanks!

Body:
You use generator expressions and itertools to reduce the amount of temporary storage like this

>>> import itertools
>>> xs = [12, 10, 32, 3, 66, 17, 42, 99, 20]
>>> a = (b**2 for b in xs)
>>> c = sorted(itertools.chain(a, xs))
>>> c
[3, 9, 10, 12, 17, 20, 32, 42, 66, 99, 100, 144, 289, 400, 1024, 1764, 4356, 9801]


Title: Split a data frame by column using a list of vectors

Body:
I want to split this data frame df by column using a list of vectors ind as the column indices.

> df
    1  2  3  4  5  6  7  8  9  10
1   1 11 21 31 41 51 61 71 81  91
2   2 12 22 32 42 52 62 72 82  92
3   3 13 23 33 43 53 63 73 83  93
4   4 14 24 34 44 54 64 74 84  94
5   5 15 25 35 45 55 65 75 85  95
6   6 16 26 36 46 56 66 76 86  96
7   7 17 27 37 47 57 67 77 87  97
8   8 18 28 38 48 58 68 78 88  98
9   9 19 29 39 49 59 69 79 89  99
10 10 20 30 40 50 60 70 80 90 100

The combined length of the vectors are equal to the number of columns in the data frame.

> ind
[[1]]
[1] 1 4 9

[[2]]
[1] 2 5 10 7 3

[[3]]
[1]  8 6

The desired result should look like this:

$`1`
    1  4  9
1   1 31 81
2   2 32 82
3   3 33 83
4   4 34 84
5   5 35 85
6   6 36 86
7   7 37 87
8   8 38 88
9   9 39 89
10 10 40 90

$`2`
    2  5  10  7  3
1  11 41  91 61 21
2  12 42  92 62 22
3  13 43  93 63 23
4  14 44  94 64 24
5  15 45  95 65 25
6  16 46  96 66 26
7  17 47  97 67 27
8  18 48  98 68 28
9  19 49  99 69 29
10 20 50 100 70 30

$`3`
    8  6
1  71 51
2  72 52
3  73 53
4  74 54
5  75 55
6  76 56
7  77 57
8  78 58
9  79 59
10 80 60

Effectively the code generates sub matrices as data frames from the data frame df based on the vectors in the list ind

I have tried using split.defult without achieving the desired result.

split.default(V, rep(seq_along(ind), lengths(ind)))

Body:
One purrr option could be:

map(.x = ind, ~ df[, .x])

[[1]]
  X1 X4 X9
1  1 31 81
2  2 32 82
3  3 33 83

[[2]]
  X2 X5 X10 X7 X3
1 11 41  91 61 21
2 12 42  92 62 22
3 13 43  93 63 23

[[3]]
  X8 X6
1 71 51
2 72 52
3 73 53

With ind defined as:

ind <- list(c(1, 4, 9),
            c(2, 5, 10, 7, 3),
            c(8, 6))

An option for a list of dfs:

map(ind, ~ map(df_list, `[`, .))