问:
How to create a separate 'archive widget' only for my cpt 'portfolio'?
I am creating one custom wordpress theme for my portfolio, trying to do everything from scratch by using fields and meta-boxes and don't want to use any plugin.

I have created one cpt as below:

function codex_custom_init() {

     register_post_type(
        'Portfolio', array(
        'labels' => array('name' => __( 'Portfolio' ), 'singular_name' => __( 'Portfolio' ) ),
        'public' => true,
        'has_archive' => true,
        'supports' => array('title', 'editor', 'thumbnail', 'comments'),
        'menu_icon' => 'dashicons-sos',
        )
    );

    //register taxonomy for portfolio post tags
    register_taxonomy(
        'portfolio-tag', //taxonomy
        'portfolio', //post-type
        array(
            'hierarchical'  => false,
            'label'         => __( 'Portfolio Tags','taxonomy general name'),
            'singular_name' => __( 'Tag', 'taxonomy general name' ),
            'rewrite'       => true,
            'query_var'     => true
        )
    );

    // add categories for Portfolio

    register_taxonomy(
            'portfoliocategories',
            'portfolio',
            array(
                'labels' => array(
                    'name' => 'Portfolio Categories',
                    'add_new_item' => 'Add New Portfolio Category',
                    'new_item_name' => "New Portfolio Type"
                ),
                'show_ui' => true,
                'show_tagcloud' => false,
                'hierarchical' => true
            )
        );

    }
    add_action( 'init', 'codex_custom_init' );```
</div>
</div>
</p>

<p>I have created all the required pages and sidebars. I want to show archive widget on my 'archive portfolio page', a separate archive widget, which will have posts only related to portfolio.
Thanks for your concern.</p>

<p>How to edit and customize this for cpt:</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-html lang-html prettyprint-override"><code><?php
    wp_get_archives(
    apply_filters(
    'widget_archives_args',
    array(
        'type'   => 'monthly',
        'show_post_count' => $count,
        ),
        $instance
        )
        );
    ?></code>```

答:
Where you are showing your widget put your code inside this condition.</p>

```<code>if ( is_singular( 'yourcpt' ) ) {
    // conditional content/code

}
</code>```

Body:
I am creating one custom wordpress theme for my portfolio, trying to do everything from scratch by using fields and meta-boxes and don't want to use any plugin.

I have created one cpt as below:

function codex_custom_init() {

     register_post_type(
        'Portfolio', array(
        'labels' => array('name' => __( 'Portfolio' ), 'singular_name' => __( 'Portfolio' ) ),
        'public' => true,
        'has_archive' => true,
        'supports' => array('title', 'editor', 'thumbnail', 'comments'),
        'menu_icon' => 'dashicons-sos',
        )
    );

    //register taxonomy for portfolio post tags
    register_taxonomy(
        'portfolio-tag', //taxonomy
        'portfolio', //post-type
        array(
            'hierarchical'  => false,
            'label'         => __( 'Portfolio Tags','taxonomy general name'),
            'singular_name' => __( 'Tag', 'taxonomy general name' ),
            'rewrite'       => true,
            'query_var'     => true
        )
    );

    // add categories for Portfolio

    register_taxonomy(
            'portfoliocategories',
            'portfolio',
            array(
                'labels' => array(
                    'name' => 'Portfolio Categories',
                    'add_new_item' => 'Add New Portfolio Category',
                    'new_item_name' => "New Portfolio Type"
                ),
                'show_ui' => true,
                'show_tagcloud' => false,
                'hierarchical' => true
            )
        );

    }
    add_action( 'init', 'codex_custom_init' );

I have created all the required pages and sidebars. I want to show archive widget on my 'archive portfolio page', a separate archive widget, which will have posts only related to portfolio.
Thanks for your concern.

How to edit and customize this for cpt:

<?php
    wp_get_archives(
    apply_filters(
    'widget_archives_args',
    array(
        'type'   => 'monthly',
        'show_post_count' => $count,
        ),
        $instance
        )
        );
    ?>

Body:
Where you are showing your widget put your code inside this condition.

if ( is_singular( 'yourcpt' ) ) {
    // conditional content/code

}


来源: stackexchange

问:
SQL where last n records for each id meet a certain criteria
This question was the closest I have found to my problem but it still doesn't solve it.

I have a (simplified) table like:

```<code>ID  Value   Date
1   CCC     2013-09-06
1   CCC     2015-07-13
1   AAA     2015-10-15
1   AAA     2015-10-29
1   AAA     2015-11-17
1   AAA     2015-12-22
2   AAA     2019-11-01
3   BBB     2017-10-02
3   AAA     2017-12-21
3   AAA     2018-01-18
3   AAA     2018-02-20
3   AAA     2018-03-20
3   AAA     2018-05-16
3   AAA     2018-08-15
3   AAA     2018-11-14
</code>```

I'd like to have the IDs that have the value AAA on the last five entries by date.
In my example, the result would be

```<code>ID
--
3
</code>```

ID 1 does not meet the criteria because when ordered by date, one of the last four entries are not 'AAA'.

ID 2 does not meet the criteria because although it's last value is AAA, it does not even at least 5 entries (only 1)

I have tried dividing my problem in different steps, first identifiying all IDs that have at least 5 records, with a simple select TOP 5 ordered by date DESC.
I have also succeeded in finding all records that have at least five 'AAA' values, using COUNT, GROUP BY and HAVING.

But I have been unable to take into account if those records found are the last five by date.

I appreciate any help/tips.

答:
You can Use

```<code>Select * from
(Select Id,Date,ROW_NUMBER() Over(Order by Date DESC) As Rw From Temp) T
WHERE T.Rw=1 OR T.Rw=2
Order By Id
</code>```

Query to assign Rw column and use filter on this column.

ContentLicense: CC BY-SA 4.0

Body:
This question was the closest I have found to my problem but it still doesn't solve it.

I have a (simplified) table like:

ID  Value   Date
1   CCC     2013-09-06
1   CCC     2015-07-13
1   AAA     2015-10-15
1   AAA     2015-10-29
1   AAA     2015-11-17
1   AAA     2015-12-22
2   AAA     2019-11-01
3   BBB     2017-10-02
3   AAA     2017-12-21
3   AAA     2018-01-18
3   AAA     2018-02-20
3   AAA     2018-03-20
3   AAA     2018-05-16
3   AAA     2018-08-15
3   AAA     2018-11-14

I'd like to have the IDs that have the value AAA on the last five entries by date.
In my example, the result would be

ID
--
3

ID 1 does not meet the criteria because when ordered by date, one of the last four entries are not 'AAA'.

ID 2 does not meet the criteria because although it's last value is AAA, it does not even at least 5 entries (only 1)

I have tried dividing my problem in different steps, first identifiying all IDs that have at least 5 records, with a simple select TOP 5 ordered by date DESC.
I have also succeeded in finding all records that have at least five 'AAA' values, using COUNT, GROUP BY and HAVING.

But I have been unable to take into account if those records found are the last five by date.

I appreciate any help/tips.

Body:
You can Use

Select * from
(Select Id,Date,ROW_NUMBER() Over(Order by Date DESC) As Rw From Temp) T
WHERE T.Rw=1 OR T.Rw=2
Order By Id

Query to assign Rw column and use filter on this column.


问:
how to pass encrypted query string in asp.net
I need to pass values between asp.net pages. How do i encrypt those values in the URL?
Example : Response.Redirect("customerAdd.aspx?customerId=" + custId);</p>

答:
Assume that you have a url like:

```<code>www.example.com/customerAdd.aspx?customerId=custId&password=weak
</code>```

What you can do is to take the string "customerId=custId&password=weak", encrypt it with a key, encode the resulting cyphertext to base64 and now the URL becomes(something like):

```<code>www.example.com/customerAdd.aspx?s=KJADSN1234kNmnanjnads
</code>```

Remember to store the encryption key in the server side. Don't send it to the client side.

Now if you are using the same key for all encryption sessions, you can re-use the URL. i.e, you can send the URL to somebody else and they can visit the same page. But this scheme reduces the security of your encryption.

If you change the encryption key for each session, you get added security but the URL will not be valid after the session is closed.

OwnerDisplayName: Ksmps

ContentLicense: CC BY-SA 2.5

Body:
Assume that you have a url like:

www.example.com/customerAdd.aspx?customerId=custId&password=weak

What you can do is to take the string "customerId=custId&password=weak", encrypt it with a key, encode the resulting cyphertext to base64 and now the URL becomes(something like):

www.example.com/customerAdd.aspx?s=KJADSN1234kNmnanjnads

Remember to store the encryption key in the server side. Don't send it to the client side.

Now if you are using the same key for all encryption sessions, you can re-use the URL. i.e, you can send the URL to somebody else and they can visit the same page. But this scheme reduces the security of your encryption.

If you change the encryption key for each session, you get added security but the URL will not be valid after the session is closed.

OwnerDisplayName: Niyaz


问:
How do I put an href link in an IOS App (OpenGL)
My App is written in OpenGL and C++, I do not use XIB file for presentation. So how can I create an href link that the user clicks and takes them someone in the browser?</p>

答:
Okay I think I found it:</p>

```<code>NSURL *url = [NSURL URLWithString:@"http://www.iphonedevelopertips.com"];

[[UIApplication sharedApplication] openURL:url];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Okay I think I found it:

NSURL *url = [NSURL URLWithString:@"http://www.iphonedevelopertips.com"];

[[UIApplication sharedApplication] openURL:url];


问:
Pre-commit hook permission denied inside script
I have following pre-commit hook:

#!/bin/bash

set -e

result=''

for file in $(find rest/src/main/groovy/ru/naumen/modules -name '*.groovy' | sort); do
    filename=basename "$file"
    result+=echo "${filename//.groovy/}",
done

result+='smpUtils'

sed -i -r "s|modules = .*|modules = $result|g" rest/smpsync.ini

git add rest/smpsync.ini
```

<p>I'm getting <code>Permission denied</code> error on line 8</p>

<pre class="lang-sh prettyprint-override"><code>filename=basename "$file"
</code>```

And I'm not able to determine the reason of it.

Hook itself has execution rights (chmod +x .git/hooks/pre-commit)

Whole directories/files tree in ./rest/src/main/groovy/ru/naumen/modules has read/write rights and belongs to my user.

答:
Try instead:

```<code>filename="$(basename "$file")"
</code>```

In order to get the result of the command basename in your filename variable.

Body:
I have following pre-commit hook:

#!/bin/bash

set -e

result=''

for file in $(find rest/src/main/groovy/ru/naumen/modules -name '*.groovy' | sort); do
    filename=basename "$file"
    result+=echo "${filename//.groovy/}",
done

result+='smpUtils'

sed -i -r "s|modules = .*|modules = $result|g" rest/smpsync.ini

git add rest/smpsync.ini

I'm getting Permission denied error on line 8

filename=basename "$file"

And I'm not able to determine the reason of it.

Hook itself has execution rights (chmod +x .git/hooks/pre-commit)

Whole directories/files tree in ./rest/src/main/groovy/ru/naumen/modules has read/write rights and belongs to my user.

Body:
Try instead:

filename="$(basename "$file")"

In order to get the result of the command basename in your filename variable.


问:
PHP array_fill array with multiples of the same record
I have this function; I'm trying to fill the $records array with multiple entries of each $vendor. Only the first record goes in the $records array 12 times like I want it to. Now I would like to get the rest to do the same.

```<code>function vendors()
{
    $vendor = [
        "Chick-Fil-A #03971 Houston TX" => 3,
        "Uber Trip Help.Uber.Com TX" => 8,
        "Starbucks Store 05 Houston TX" => 3,
        "Shell Service S Houston TX" => 3,
        "Ralphs #0 1200 N Centr Houston TX" => 3,
        "Nails Van Nuys TX" => 3,
        "Postmates Ed3F9 to Httpspostmate CA" => 3,
        "Pico Beauty Supply and SA Houston TX" => 3,
        "Big Mamas & Papas 818-679-9976 TX" => 3,
        "CIT-GO Houston TX" => 3,
        "Dollar Tree Houston TX" => 3,
        "McDonald's M6310 O Houston TX" => 5,
        "Jamba Juice - Houston TX" => 3,
        "Cvs/Pharm 10445--125 N Glendale" => 3,
    ];
    $records = array();
    foreach ($vendor as $key => $value)
    {
        $times = $value * 4;
        $records = array_fill(0, $times, $key);
    }
    return $records;
}
</code>```

答:
Every time you call array_fill it overwrites what you did in the previous call.

If you don't absolutely need to use array_fill you could replace the foreach with something like this:

```<code>foreach ($vendor as $key => $value){
        $times = $value * 4;
        for($x=0; $x<$times; $x++){
          if(!isset($records[$x])){
            $records[$x]=[];
        }
          array_push($records[$x], $key);
        }
}
</code>```

Does that do what you are trying to do?

Body:
I have this function; I'm trying to fill the $records array with multiple entries of each $vendor. Only the first record goes in the $records array 12 times like I want it to. Now I would like to get the rest to do the same.

function vendors()
{
    $vendor = [
        "Chick-Fil-A #03971 Houston TX" => 3,
        "Uber Trip Help.Uber.Com TX" => 8,
        "Starbucks Store 05 Houston TX" => 3,
        "Shell Service S Houston TX" => 3,
        "Ralphs #0 1200 N Centr Houston TX" => 3,
        "Nails Van Nuys TX" => 3,
        "Postmates Ed3F9 to Httpspostmate CA" => 3,
        "Pico Beauty Supply and SA Houston TX" => 3,
        "Big Mamas & Papas 818-679-9976 TX" => 3,
        "CIT-GO Houston TX" => 3,
        "Dollar Tree Houston TX" => 3,
        "McDonald's M6310 O Houston TX" => 5,
        "Jamba Juice - Houston TX" => 3,
        "Cvs/Pharm 10445--125 N Glendale" => 3,
    ];
    $records = array();
    foreach ($vendor as $key => $value)
    {
        $times = $value * 4;
        $records = array_fill(0, $times, $key);
    }
    return $records;
}

Body:
Every time you call array_fill it overwrites what you did in the previous call.

If you don't absolutely need to use array_fill you could replace the foreach with something like this:

foreach ($vendor as $key => $value){
        $times = $value * 4;
        for($x=0; $x<$times; $x++){
          if(!isset($records[$x])){
            $records[$x]=[];
        }
          array_push($records[$x], $key);
        }
}

Does that do what you are trying to do?


问:
Upload app to playstore error related to permission
I am trying to upload my ReactNative app to play store but it gives below error -

Upload failed
  Your APK or Android App Bundle is using permissions that require a privacy policy: (android.permission.CAMERA, android.permission.READ_CONTACTS).

i am not using Camera and contacts in my app, and not declare permissions for same in manifest but after generating signed apk it gives error mention above.

Any help really appreciated, i am not able to upload app to play store.

Thanks in advance.

答:
It may be because of any third-party npm package which may include that permission so from my experience in this field You have to add the privacy policy regarding to that particular information it means if you ask get accounts permission in your app then you have to declare that with your privacy policy file we use that data i.e. email address or whatever with reasons.

Therefore need a privacy policy for the app If your app handles personal or sensitive user data

View Official Informations

Also can do this

```<code><uses-permission android:name="android.permission.YOUR_PERMISSION" tools:node="remove" />
</code>```

Body:
It may be because of any third-party npm package which may include that permission so from my experience in this field You have to add the privacy policy regarding to that particular information it means if you ask get accounts permission in your app then you have to declare that with your privacy policy file we use that data i.e. email address or whatever with reasons.

Therefore need a privacy policy for the app If your app handles personal or sensitive user data

View Official Informations

Also can do this

<uses-permission android:name="android.permission.YOUR_PERMISSION" tools:node="remove" />


问:
insert content of a file while changing values inside
```<code>$title = '';

function insert($file){
    global $title;
    $title = 'lorem';
    $cnt = file_get_contents(`abc.php`);
    echo $cnt;

    $title = ' ipsum';
    $cnt = file_get_contents(`abc.php`);
    echo $cnt;
}
</code>```

abc.php

```<code><div class='title'><?php echo $title; ?></div>
</code>```

So I need to insert abc.php while changing variables inside.

In the above (simplified) example I'm expecting lorem ipsum as the result, but I'm getting empty div .title

答:
As per your current flow it not working.

Try with str_replace in the current file and in abc.php file declare one keyword like #TITLE#

```<code>$title = '';

function insert($file){
    global $title;
    $title = 'lorem';
    $cnt = file_get_contents(`abc.php`);
    $cnt = str_replace("#TITLE#",$title,$cnt);
    echo $cnt;

    $title = ' ipsum';
    $cnt = file_get_contents(`abc.php`);
    $cnt = str_replace("#TITLE#",$title,$cnt);
    echo $cnt;
}
</code>```

abc.php

```<code><div class='title'>#TITLE#</div>
</code>```

Hope this work for you.

Body:
$title = '';

function insert($file){
    global $title;
    $title = 'lorem';
    $cnt = file_get_contents(`abc.php`);
    echo $cnt;

    $title = ' ipsum';
    $cnt = file_get_contents(`abc.php`);
    echo $cnt;
}

abc.php

<?php echo $title; ?>

So I need to insert abc.php while changing variables inside.

In the above (simplified) example I'm expecting lorem ipsum as the result, but I'm getting empty div .title

Body:
As per your current flow it not working.

Try with str_replace in the current file and in abc.php file declare one keyword like #TITLE#

$title = '';

function insert($file){
    global $title;
    $title = 'lorem';
    $cnt = file_get_contents(`abc.php`);
    $cnt = str_replace("#TITLE#",$title,$cnt);
    echo $cnt;

    $title = ' ipsum';
    $cnt = file_get_contents(`abc.php`);
    $cnt = str_replace("#TITLE#",$title,$cnt);
    echo $cnt;
}

abc.php

<div class='title'>#TITLE#</div>

Hope this work for you.


问:
How to calculate the percentage of different values in same column and group by month of current year?
I want to take the percentage of only SLA's in the sla_osla table and group them by all the months of current year

Here is my table

http://sqlfiddle.com/#!9/179518/2

I have tried the following query

```<code>    SELECT MONTH(service_date),((nums/(count(*)))*100) AS perc
      FROM orders CROSS JOIN (SELECT MONTH(service_date) AS months, COUNT(*) AS
   nums FROM orders WHERE YEAR(service_date) = year(CURRENT_DATE()) AND sla_osla =
  'sla'
     GROUP BY MONTH(CURRENT_DATE())) table1
     WHERE YEAR(service_date) = YEAR(current_date) AND sla_osla IN ('sla','osla')
     GROUP BY MONTH(service_date)
</code>```

I want output like this

```<code>month percentage

    1       75%
    2       50%
</code>```

答:
```<code>SELECT month(service_date) as dmonth,count(1)
  FROM orders where sla_osla='sla'
 group by dmonth
</code>```

Body:
I want to take the percentage of only SLA's in the sla_osla table and group them by all the months of current year

Here is my table

http://sqlfiddle.com/#!9/179518/2

I have tried the following query

    SELECT MONTH(service_date),((nums/(count(*)))*100) AS perc
      FROM orders CROSS JOIN (SELECT MONTH(service_date) AS months, COUNT(*) AS
   nums FROM orders WHERE YEAR(service_date) = year(CURRENT_DATE()) AND sla_osla =
  'sla'
     GROUP BY MONTH(CURRENT_DATE())) table1
     WHERE YEAR(service_date) = YEAR(current_date) AND sla_osla IN ('sla','osla')
     GROUP BY MONTH(service_date)

I want output like this

month percentage

    1       75%
    2       50%


问:
how to replace email domain name
Im trying to write a procedure that updates the domain of an email (example: converting Email123@gmail.com into Email123@hotmail.com when i pass 2 strings gmail.com and hotmail.com) while having a cursor in my procedure

```<code>create of replace procedure pr_update_email
(Old_Email Varchar2, New_Email Varchar2)
    As
    V_OldDomain Varchar2(50);
      Cursor C_Domains IS Select Email_Address
                From Customer
                where Email_Address Like '%@'||Old_Email;
          Begin
          Open C_Domains;
          Fetch C_Domains INTO V_OldDomain;
          While C_Domains %Found loop
                    Update Customer
                    Set Email_Address = regexp_replace(Email_Address, '^(.*@.*)'||Old_Email||'\1'||New_Email)
                    WHERE Email_Address LIKE V_OldDomain;
          Fetch C_Domains into New_Email;
          End Loop;
  Close C_Domains;
End pr_update_email;
/
Show Errors;
</code>```

getting errors:
 19/11    PL/SQL: SQL Statement ignored

19/32    PLS-00403: expression'NEW_EMAIL' cannot be used as an INTO-target of a
   SELECT/FETCH statement

答:
You can directly update without creating a Stored Procedure but by using Regexp_Replace() and Instr() Functions :

```<code>SQL> Update Customer
        Set Email_Address = Regexp_Replace(Email_Address,'(.*)@[gmail]+.(.*)','\1@hotmail.\2')
      Where Instr(Email_Address,'@gmail.') > 0;
SQL> Commit;
</code>```

If you want to create a generic structure in order to be able to use for such other cases also, then transfer the above Update statement as :

```<code>SQL> Create Or Replace Procedure pr_update_email(Old_Email Varchar2, New_Email Varchar2) As
Begin
    Update Customer
       Set Email_Address = Regexp_Replace(Email_Address,'(.*)@['||Old_Email||']+.(.*)','\1@'||New_Email||'.\2')
     Where Instr(Email_Address,'@'||Old_Email||'.')>0 ;

End;
/
SQL> Begin
   pr_update_email('gmail','hotmail');
End;
/
SQL> Commit;
</code>```

Title: how to replace email domain name

Body:
Im trying to write a procedure that updates the domain of an email (example: converting Email123@gmail.com into Email123@hotmail.com when i pass 2 strings gmail.com and hotmail.com) while having a cursor in my procedure

create of replace procedure pr_update_email
(Old_Email Varchar2, New_Email Varchar2)
    As
    V_OldDomain Varchar2(50);
      Cursor C_Domains IS Select Email_Address
                From Customer
                where Email_Address Like '%@'||Old_Email;
          Begin
          Open C_Domains;
          Fetch C_Domains INTO V_OldDomain;
          While C_Domains %Found loop
                    Update Customer
                    Set Email_Address = regexp_replace(Email_Address, '^(.*@.*)'||Old_Email||'\1'||New_Email)
                    WHERE Email_Address LIKE V_OldDomain;
          Fetch C_Domains into New_Email;
          End Loop;
  Close C_Domains;
End pr_update_email;
/
Show Errors;

getting errors:
 19/11    PL/SQL: SQL Statement ignored

19/32    PLS-00403: expression'NEW_EMAIL' cannot be used as an INTO-target of a
   SELECT/FETCH statement

Body:
You can directly update without creating a Stored Procedure but by using Regexp_Replace() and Instr() Functions :

SQL> Update Customer
        Set Email_Address = Regexp_Replace(Email_Address,'(.*)@[gmail]+.(.*)','\1@hotmail.\2')
      Where Instr(Email_Address,'@gmail.') > 0;
SQL> Commit;

If you want to create a generic structure in order to be able to use for such other cases also, then transfer the above Update statement as :

SQL> Create Or Replace Procedure pr_update_email(Old_Email Varchar2, New_Email Varchar2) As
Begin
    Update Customer
       Set Email_Address = Regexp_Replace(Email_Address,'(.*)@['||Old_Email||']+.(.*)','\1@'||New_Email||'.\2')
     Where Instr(Email_Address,'@'||Old_Email||'.')>0 ;

End;
/
SQL> Begin
   pr_update_email('gmail','hotmail');
End;
/
SQL> Commit;


问:
How can I write this in one line?
Hey So I'm working on a problem that asks me to manipulate a dictionary by grabbing all the keys and values and formatting them into a single string for every key/value pair. I have to do this in one line, or so I think, the problem is better explained in the image.

答:
I believe they would like you to write for country, pop in country_pop.items(): on line 7. However, you can do the entire thing in one line as well.

```<code>print('\n'.join([f'{key} has {value} people' for key, value in country_pop.items()]))
</code>```

Title: How can I write this in one line?

Body:
I believe they would like you to write for country, pop in country_pop.items(): on line 7. However, you can do the entire thing in one line as well.

print('\n'.join([f'{key} has {value} people' for key, value in country_pop.items()]))


问:
Restart a scenario from the task it fails automatically
I am using ODI , and I have a single mapping and a scenario for that , how can I restart the scenario from the same point after it fails due to some issue automatically.
For ex if I have around 100 rows and 90 gets inserted and after that server shuts down or some reason it stops how can I restart the scenario from the same point without having to start from the starting of the scenario and insert remaining 10 rows.</p>

答:
You can refer this to restart the session from where it failed.

ODI Session Restart - Scenarios & Load Plans


问:
How to escape the forward slash in the string in javascript? C# web api not recognizing the forward slash
How do i escape forward slash in javascript ?
string str= "[B]Hello How are you[/B]".
This is the string i want to pass from client side to c# web api.
C# web api  not recognizing forward slash in the string. - "[REM][TB]Hello How are you[%2FTB]" </p>

答:
You can try with below replace function to remove your escape sequences:</p>

```<code>str.replace(/\//g, "");
</code>```

Body:
You can try with below replace function to remove your escape sequences:

str.replace(/\//g, "");


问:
How to properly reuse a Provider in Flutter
So I have this ChangeNotifierProvider high in my widget tree as I am seeing many children widgets to listen to its value.

What I am currently doing is that I pass down the Provider.of(context) object from the parent widget into it's children via constructors whenever I am to reuse some values/functions on my children widgets. For example, everytime I create a Provider.of(context) object for my children widgets, it seems that it does not carry over the updated values I have on the Parent Provider but rather this one has my default null/0/'empty' ones like it has only been created. This lead me to pass down the initial Provider.of(context) object to each children that will use the updated values and functions of the ChangeNotifier.

This setup is working for me, however, when my Widget Tree has started being complex, I am constantly passing down values through each widget and to some that do not even use it at all just for its children to listen to the main provider.

I think what I may be doing now is anti-pattern of the Provider Architecture, I am hoping you guys can help me on a more optimized and efficient way of doing this.

Thank you very much!

P.S. There are some things in the documentation that I am not yet quite grasping properly.

Edits Below to include sample code and visualization:

provider_type.dart

```<code>class ProviderType extends ChangeNotifier{
    String valueA = '';
    String valueB = '';
}
</code>```

home.dart

```<code>import ..provider_type.dart
...
    Widget build(BuildContext context){
        return ChangeNotifierProvider<ProviderType>(
            create: (context) => ProviderType(),
            child: ScreenColumn();
        );
    }
...
</code>```

screen_column.dart

```<code>import ..screen_a.dart
import ..screen_b.dart
class ScreenColumn extends StatelessWidget{
    Widget build(BuildContext context){
        var providerType = Provider.of<ProviderType>(context);

        return Column(
            children: <Widget>[
                ScreenA(providerType: providerType),
                ScreenB(providerType: providerType),
            ],
        );
    }
}
</code>```

screen_a.dart

```<code>class ScreenA extends StatelessWidget{
    final ProviderType providerType;

    ScreenA({this.providerType});

    Widget build(BuildContext context){
        return Text(
            '${providerType.valueA}'
        );
    }
}
</code>```

screen_b.dart

```<code>import ..screen_c.dart
class ScreenB extends StatelessWidget{
    final ProviderType providerType;

    ScreenB({this.providerType});

    Widget build(BuildContext context){
        return ScreenC(providerType: providerType);
    }
}
</code>```

screen_c.dart

```<code>class ScreenC extends StatelessWidget{
    final ProviderType providerType;

    ScreenB({this.providerType});

    Widget build(BuildContext context){
        return Column(
        children: <Widget>[
            Text(
                '${providerType.valueA}'
            )
            Text(
                '${providerType.valueB}'
            )
            Text(
                '${providerType.valueC}'
            )
        ]
        );
    }
}
</code>```

Visualization

So what I am currently doing is to pass down the object providerType from ScreenColumn to Screens A, B, and C just so each of them have the same "Source of Values". Cause when I try to make different Provider.of objects and use them, they do not share the same updated values when I do some computation.

Is there something I can do to make this more efficient or is there a better way that I need to do?

答:
To those who may be wondering or are searching for answers to the same question, look at my sample code below that shows how you can reuse/share your Provider Values and Functions at any point in your widget tree as long as they are under your Parent Provider.

And yes, you can actually just create Provider.of Objects anywhere in
  your tree without passing down the initial Provider.of object that you
  have created.

```<code>import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class ProviderType extends ChangeNotifier {
  String value = DateTime.now().toString();

  changeValue() {
    value = DateTime.now().toString();
    notifyListeners();
  }
}

void main() => runApp(AppIndex());

class AppIndex extends StatelessWidget {
  const AppIndex({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<ProviderType>(
      create: (context) => ProviderType(),
      child: MaterialApp(
        home: Home(),
      ),
    );
  }
}

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var providerType = Provider.of<ProviderType>(context);

    return Scaffold(
      appBar: AppBar(
        title: Text('Sample App'),
      ),
      body: ScreenColumn(),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: () => providerType.changeValue(),
        label: Text('ChangeValue'),
      ),
    );
  }
}

class ScreenColumn extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
        child: Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: <Widget>[
        ScreenA(),
        ScreenB(),
        ScreenC(),
        ScreenC(),
      ],
    ));
  }
}

class ScreenA extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var providerType = Provider.of<ProviderType>(context);
    return Card(
      color: Colors.red,
      elevation: 8.0,
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Text(providerType.value),
      ),
    );
  }
}

class ScreenB extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var providerType = Provider.of<ProviderType>(context);
    return Card(
      color: Colors.blue,
      elevation: 8.0,
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Text(providerType.value),
            ScreenC(),
            ScreenC(),
          ],
        ),
      ),
    );
  }
}

class ScreenC extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // var providerType = Provider.of<ProviderType>(context);

    return Card(
      color: Colors.green,
      elevation: 8.0,
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Text('This is Screen B with no Provider.of Object'),
            ScreenD(),
            ScreenD(),
            ScreenD(),
          ],
        ),
      ),
    );
  }
}

class ScreenD extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var providerType = Provider.of<ProviderType>(context);
    return Card(
      color: Colors.yellow,
      elevation: 8.0,
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Text(
                'This is Screen D. A Provider.of object was created here without inheriting the Parent\'s Provider.of object.'),
            Text(providerType.value),
          ],
        ),
      ),
    );
  }
}
</code>```

Body:
So I have this ChangeNotifierProvider high in my widget tree as I am seeing many children widgets to listen to its value.

What I am currently doing is that I pass down the Provider.of(context) object from the parent widget into it's children via constructors whenever I am to reuse some values/functions on my children widgets. For example, everytime I create a Provider.of(context) object for my children widgets, it seems that it does not carry over the updated values I have on the Parent Provider but rather this one has my default null/0/'empty' ones like it has only been created. This lead me to pass down the initial Provider.of(context) object to each children that will use the updated values and functions of the ChangeNotifier.

This setup is working for me, however, when my Widget Tree has started being complex, I am constantly passing down values through each widget and to some that do not even use it at all just for its children to listen to the main provider.

I think what I may be doing now is anti-pattern of the Provider Architecture, I am hoping you guys can help me on a more optimized and efficient way of doing this.

Thank you very much!

P.S. There are some things in the documentation that I am not yet quite grasping properly.

Edits Below to include sample code and visualization:

provider_type.dart

class ProviderType extends ChangeNotifier{
    String valueA = '';
    String valueB = '';
}

home.dart

import ..provider_type.dart
...
    Widget build(BuildContext context){
        return ChangeNotifierProvider<ProviderType>(
            create: (context) => ProviderType(),
            child: ScreenColumn();
        );
    }
...

screen_column.dart

import ..screen_a.dart
import ..screen_b.dart
class ScreenColumn extends StatelessWidget{
    Widget build(BuildContext context){
        var providerType = Provider.of<ProviderType>(context);

        return Column(
            children: <Widget>[
                ScreenA(providerType: providerType),
                ScreenB(providerType: providerType),
            ],
        );
    }
}

screen_a.dart

class ScreenA extends StatelessWidget{
    final ProviderType providerType;

    ScreenA({this.providerType});

    Widget build(BuildContext context){
        return Text(
            '${providerType.valueA}'
        );
    }
}

screen_b.dart

import ..screen_c.dart
class ScreenB extends StatelessWidget{
    final ProviderType providerType;

    ScreenB({this.providerType});

    Widget build(BuildContext context){
        return ScreenC(providerType: providerType);
    }
}

screen_c.dart

class ScreenC extends StatelessWidget{
    final ProviderType providerType;

    ScreenB({this.providerType});

    Widget build(BuildContext context){
        return Column(
        children: <Widget>[
            Text(
                '${providerType.valueA}'
            )
            Text(
                '${providerType.valueB}'
            )
            Text(
                '${providerType.valueC}'
            )
        ]
        );
    }
}

Visualization

So what I am currently doing is to pass down the object providerType from ScreenColumn to Screens A, B, and C just so each of them have the same "Source of Values". Cause when I try to make different Provider.of objects and use them, they do not share the same updated values when I do some computation.

Is there something I can do to make this more efficient or is there a better way that I need to do?

Body:
To those who may be wondering or are searching for answers to the same question, look at my sample code below that shows how you can reuse/share your Provider Values and Functions at any point in your widget tree as long as they are under your Parent Provider.

And yes, you can actually just create Provider.of Objects anywhere in
  your tree without passing down the initial Provider.of object that you
  have created.

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class ProviderType extends ChangeNotifier {
  String value = DateTime.now().toString();

  changeValue() {
    value = DateTime.now().toString();
    notifyListeners();
  }
}

void main() => runApp(AppIndex());

class AppIndex extends StatelessWidget {
  const AppIndex({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<ProviderType>(
      create: (context) => ProviderType(),
      child: MaterialApp(
        home: Home(),
      ),
    );
  }
}

class Home extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var providerType = Provider.of<ProviderType>(context);

    return Scaffold(
      appBar: AppBar(
        title: Text('Sample App'),
      ),
      body: ScreenColumn(),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: () => providerType.changeValue(),
        label: Text('ChangeValue'),
      ),
    );
  }
}

class ScreenColumn extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
        child: Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: <Widget>[
        ScreenA(),
        ScreenB(),
        ScreenC(),
        ScreenC(),
      ],
    ));
  }
}

class ScreenA extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var providerType = Provider.of<ProviderType>(context);
    return Card(
      color: Colors.red,
      elevation: 8.0,
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Text(providerType.value),
      ),
    );
  }
}

class ScreenB extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var providerType = Provider.of<ProviderType>(context);
    return Card(
      color: Colors.blue,
      elevation: 8.0,
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Text(providerType.value),
            ScreenC(),
            ScreenC(),
          ],
        ),
      ),
    );
  }
}

class ScreenC extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // var providerType = Provider.of<ProviderType>(context);

    return Card(
      color: Colors.green,
      elevation: 8.0,
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Text('This is Screen B with no Provider.of Object'),
            ScreenD(),
            ScreenD(),
            ScreenD(),
          ],
        ),
      ),
    );
  }
}

class ScreenD extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var providerType = Provider.of<ProviderType>(context);
    return Card(
      color: Colors.yellow,
      elevation: 8.0,
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Text(
                'This is Screen D. A Provider.of object was created here without inheriting the Parent\'s Provider.of object.'),
            Text(providerType.value),
          ],
        ),
      ),
    );
  }
}


问:
Deleting an image from android device?
I want to delete an image that user selects through

ACTION_GET_CONTENT

I am successfully able to select image and show it in recycleview,
I am selecting image like this:

```<code>switch (requestCode) {
        case 42:
            if (resultCode == RESULT_OK) {
                Uri uri = data.getData();

                InputStream inputStream = null;
                try {
                    inputStream = getBaseContext().getContentResolver().openInputStream(uri);
                    Bitmap bm = BitmapFactory.decodeStream(inputStream);

                    int maxHeight = 1920;
                    int maxWidth = 1920;

                    float scale = Math.min(((float) maxHeight / bm.getWidth()), ((float) maxWidth / bm.getHeight()));

                    Matrix matrix = new Matrix();
                    matrix.postScale(scale, scale);

                    Bitmap bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);

                    saveImageToInternalStorage(bitmap, getFileName(uri));
                    bm.recycle();
                    bitmap.recycle();

                    finishActivity(42);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
    }
</code>```

Now I want to delete this image from users gallery but it should still be visible in the recyclerview

I get the photoPath as

```<code>content://com.android.providers.media.documents/document/image%3A5793
</code>```

答:
Try this</p>

```<code>File file = new File(photoPath);
file.delete();
</code>```

Title: Deleting an image from android device?

Body:
I want to delete an image that user selects through

ACTION_GET_CONTENT

I am successfully able to select image and show it in recycleview,
I am selecting image like this:

switch (requestCode) {
        case 42:
            if (resultCode == RESULT_OK) {
                Uri uri = data.getData();

                InputStream inputStream = null;
                try {
                    inputStream = getBaseContext().getContentResolver().openInputStream(uri);
                    Bitmap bm = BitmapFactory.decodeStream(inputStream);

                    int maxHeight = 1920;
                    int maxWidth = 1920;

                    float scale = Math.min(((float) maxHeight / bm.getWidth()), ((float) maxWidth / bm.getHeight()));

                    Matrix matrix = new Matrix();
                    matrix.postScale(scale, scale);

                    Bitmap bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);

                    saveImageToInternalStorage(bitmap, getFileName(uri));
                    bm.recycle();
                    bitmap.recycle();

                    finishActivity(42);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
    }

Now I want to delete this image from users gallery but it should still be visible in the recyclerview

I get the photoPath as

content://com.android.providers.media.documents/document/image%3A5793

Body:
Try this

File file = new File(photoPath);
file.delete();


问:
total of sales for each item in different columns with specific year

1. This is the normal code

```<code>SELECT A.customer_id,

        SUM(B.quantity*b.list_price) AS [ITEM SALES]

     -- ,

     --(SELECT SUM(quantity*list_price)

     -- FROM sales.order_items

     -- WHERE YEAR(order_date) = '2016') AS [TOTAL SALES 2016]

FROM sales.orders AS A

RIGHT JOIN sales.order_items AS B

ON A.order_id = B.order_id

GROUP BY A.customer_id

ORDER BY A.customer_id ASC
</code>```

RESULT // I need to display the TOTAL OF SALES IN 2016

```<code>1   30645.87
2   21653.85
3   26249.81
4   24198.88
5   19442.88
6   35857.86
7   7707.96
8   2603.95
9   26679.78
</code>```

答:
Most of the code you actually need to do your query is already there, you just need to reword it a bit, and use conditional aggregation:</p>

```<code>SELECT
    so.customer_id,
    SUM(soi.quantity*soi.list_price) AS [ITEM SALES],
    SUM(CASE WHEN YEAR(so.order_date) = 2016
             THEN soi.quantity*soi.list_price ELSE 0 END) AS [TOTAL SALES 2016]
FROM sales.orders AS so
LEFT JOIN sales.order_items AS soi
    ON so.order_id = soi.order_id
GROUP BY
    so.customer_id
ORDER BY
    so.customer_id;
</code>```

Body:
1. This is the normal code

SELECT A.customer_id,

        SUM(B.quantity*b.list_price) AS [ITEM SALES]

     -- ,

     --(SELECT SUM(quantity*list_price)

     -- FROM sales.order_items

     -- WHERE YEAR(order_date) = '2016') AS [TOTAL SALES 2016]

FROM sales.orders AS A

RIGHT JOIN sales.order_items AS B

ON A.order_id = B.order_id

GROUP BY A.customer_id

ORDER BY A.customer_id ASC

RESULT // I need to display the TOTAL OF SALES IN 2016

1   30645.87
2   21653.85
3   26249.81
4   24198.88
5   19442.88
6   35857.86
7   7707.96
8   2603.95
9   26679.78

Body:
Most of the code you actually need to do your query is already there, you just need to reword it a bit, and use conditional aggregation:

SELECT
    so.customer_id,
    SUM(soi.quantity*soi.list_price) AS [ITEM SALES],
    SUM(CASE WHEN YEAR(so.order_date) = 2016
             THEN soi.quantity*soi.list_price ELSE 0 END) AS [TOTAL SALES 2016]
FROM sales.orders AS so
LEFT JOIN sales.order_items AS soi
    ON so.order_id = soi.order_id
GROUP BY
    so.customer_id
ORDER BY
    so.customer_id;


问:
Different between ToString(),Convert.Tostring() and (string)variable in C#
Different between [ToString()],[Convert.Tostring()] and [(string)variable] in C#

答:
```<code>int A =0;
MessageBox.Show(A.ToString());
MessageBox.Show(Convert.ToString(A));
</code>```

Here both the methods are used to convert the string but the basic difference between them is: "Convert" function handles NULLS, while "i.ToString()" does not it will throw a NULL reference exception error. So as good coding practice using "convert" is always safe. (string)casting is only to convert string and objects.

Let's see another example:

```<code>    string s;
    object o = null;
    s = o.ToString();
    //returns a null reference exception for s.

    string s;
    object o = null;
    s = Convert.ToString(o);
    //returns an empty string for s and does not throw an exception.

 static void Main(string[] args)
        {
            try
            {
                string s;
                object o = null;
                s = (string)o;
                Console.WriteLine(s);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            Console.ReadKey();
        }
 //returns an empty string for s and does not throw an exception.
</code>```

Body:
int A =0;
MessageBox.Show(A.ToString());
MessageBox.Show(Convert.ToString(A));

Here both the methods are used to convert the string but the basic difference between them is: "Convert" function handles NULLS, while "i.ToString()" does not it will throw a NULL reference exception error. So as good coding practice using "convert" is always safe. (string)casting is only to convert string and objects.

Let's see another example:

    string s;
    object o = null;
    s = o.ToString();
    //returns a null reference exception for s.

    string s;
    object o = null;
    s = Convert.ToString(o);
    //returns an empty string for s and does not throw an exception.

 static void Main(string[] args)
        {
            try
            {
                string s;
                object o = null;
                s = (string)o;
                Console.WriteLine(s);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            Console.ReadKey();
        }
 //returns an empty string for s and does not throw an exception.


问:
Upload an Image from SD card to a Lamp Server
I am trying to upload an image from the android device to a LAMP server where i will handle the form through PHP.

i have an image view which has been set with the image path from the SD card

i want to upload this image on click of a button

答: You can upload things from Android through POST (and therefore, FILES). Simply send it up to your PHP as a POST (with the "upload" button being the submit), just like you would do a form on a webpage, then write a PHP script to handle saving the file.</p>


问:
Why am I getting a wrong result for adding two numbers in cuda?
Why am I getting a wrong result for adding two numbers in cuda?
I am getting 1 as an answer instead of 9. Can anybody tell me why? Does this have something to do with the pointers? I have used the following code:</p>

```<code>#include <iostream>
#include <cuda_runtime.h>
#include <cuda.h>

using namespace std;
__global__ void add(int *a, int *b, int *c)
{
*c = *a + *b;
}

int main(void) {
int a, b, c; // host copies of a, b, c
int *d_a, *d_b, *d_c; // device copies of a, b, c
int size = sizeof(int);

// Allocate space for device copies of a, b, c
cudaMalloc((void **)&d_a, size);
cudaMalloc((void **)&d_b, size);
cudaMalloc((void **)&d_c, size);

// Setup input values
a = 2;
b = 7;

cudaMemcpy(d_a, &a, size, cudaMemcpyHostToDevice);
cudaMemcpy(d_b, &b, size, cudaMemcpyHostToDevice);

// Launch add() kernel on GPU
add<<<1,1>>>(d_a, d_b, d_c);

// Copy result back to host
cudaMemcpy(&c, d_c, size, cudaMemcpyDeviceToHost);
cout << "answer is " << c <<endl;
// Cleanup
cudaFree(d_a); cudaFree(d_b); cudaFree(d_c);

//return 0;
}
</code>```

答:
Problem was with the persistence mode. The persistence mode was disabled. Doing this worked:</p>

```<code>$ sudo -i
# nvidia-smi -pm 1
</code>```

Body:
Why am I getting a wrong result for adding two numbers in cuda?
I am getting 1 as an answer instead of 9. Can anybody tell me why? Does this have something to do with the pointers? I have used the following code:

#include <iostream>
#include <cuda_runtime.h>
#include <cuda.h>

using namespace std;
__global__ void add(int *a, int *b, int *c)
{
*c = *a + *b;
}

int main(void) {
int a, b, c; // host copies of a, b, c
int *d_a, *d_b, *d_c; // device copies of a, b, c
int size = sizeof(int);

// Allocate space for device copies of a, b, c
cudaMalloc((void **)&d_a, size);
cudaMalloc((void **)&d_b, size);
cudaMalloc((void **)&d_c, size);

// Setup input values
a = 2;
b = 7;

cudaMemcpy(d_a, &a, size, cudaMemcpyHostToDevice);
cudaMemcpy(d_b, &b, size, cudaMemcpyHostToDevice);

// Launch add() kernel on GPU
add<<<1,1>>>(d_a, d_b, d_c);

// Copy result back to host
cudaMemcpy(&c, d_c, size, cudaMemcpyDeviceToHost);
cout << "answer is " << c <<endl;
// Cleanup
cudaFree(d_a); cudaFree(d_b); cudaFree(d_c);

//return 0;
}

Body:
Problem was with the persistence mode. The persistence mode was disabled. Doing this worked:

$ sudo -i
# nvidia-smi -pm 1


问:
Best practice to record large amount of hits into MySQL database
Well, this is the thing. Let's say that my future PHP CMS need to drive 500k visitors daily and I need to record them all in MySQL database (referrer, ip address, time etc.). This way I need to insert 300-500 rows per minute and update 50 more. The main problem is that script would call database every time I want to insert new row, which is every time someone hits a page.

My question, is there any way to locally cache incoming hits first (and what is the best solution for that apc, csv...?) and periodically send them to database every 10 minutes for example? Is this good solution and what is the best practice for this situation?

答:
A frequently used solution:

You could implement an counter in memcached which you increment on an visit, and push an update to the database for every 100 (or 1000) hits.


问:
How do I reverse a list or loop over it backwards?
How do I iterate over a list in reverse in Python?

See also: How can I get a reversed copy of a list (avoid a separate statement when chaining a method after .reverse)?

答:
There are 3 methods to get the reversed list:

Slicing Method 1:    reversed_array = array[-1::-1]

Slicing Method 2:
reversed_array2 = array[::-1]

Using the builtin function: reversed_array = array.reverse()

The third function actually reversed the list object in place. That means no copy of pristine data is maintained. This is a good approach if you don't want to maintain the old version. But doesn't seem to be a solution if you do want the pristine and reversed version.


问:
Using React to create a form, how could I get my err message to display on Submit (when the submit button is clicked)?
I am using React to create a form with two input text and would like to display an error message every time the user enters a non-numerical value as the age and clicks the submit button. The form apparently is doing most of what I want but it is not displaying the error message.

NB: I would love not to use the alert() syntax here if possible.

Thanks for your help.

class MyForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      username: '',
      age: null,
      errormessage: ''
    };
  }

 errorHandler = () => {
  let err = '';
  if (nam === "age") {
    if (val !="" && !Number(val)) {
      err = Your age must be a number;
    }
  }
  this.setState({errormessage: err});
 }

  myChangeHandler = (event) => {
    let nam = event.target.name;
    let val = event.target.value;
    this.setState({[nam]: val});
  }

  render() {
    return (
      <form onSubmit={this.errorHandler}>

Hello {this.state.username} {this.state.age}

Enter your name:

      <input
        type='text'
        name='username'
        onChange={this.myChangeHandler}
      />

Enter your age:

      <input
        type='text'
        name='age'
        onChange={this.myChangeHandler}
      />

      <input
        type='submit'
      />
      {this.state.errormessage}
      </form>
    );
  }
}
ReactDOM.render(<MyForm />, document.getElementById('root'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div></code>```

答:
I was able to able to refine the answer given by @Springy to get the code below.

Thank you @Springy

class MyForm extends React.Component {
  constructor(props) {
   super(props);
   this.state = {
     username: "",
     age: null,
     errormessage: ""
   };
  }

  errorHandler = e => {
    e.preventDefault();
    let err = "";
    let newAge = Number(this.state.age);
    if (isNaN(newAge)) {
      err = Your age must be a number;
    }
    this.setState({ errormessage: err });
  };

  handleUserAgeName = event => {
    this.setState({
      [event.target.name]:event.target.value
    });
  };

  render() {
    return (
      <form onSubmit={this.errorHandler}>

          Hello {this.state.username} {this.state.age}

Enter your name:

    <input
      type="text"
      name="username"
      defaultValue=""
      onChange={this.handleUserAgeName}
    />

Enter your age:

    <input
      type="text"
      name="age"
      defaultValue=""
      onChange={this.handleUserAgeName}
    />

    <input type="submit" />
    {this.state.errormessage}
  </form>
);
  }
}
ReactDOM.render(<MyForm />, document.getElementById("root"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div></code>```

Body:
I was able to able to refine the answer given by @Springy to get the code below.

Thank you @Springy

class MyForm extends React.Component {
  constructor(props) {
   super(props);
   this.state = {
     username: "",
     age: null,
     errormessage: ""
   };
  }

  errorHandler = e => {
    e.preventDefault();
    let err = "";
    let newAge = Number(this.state.age);
    if (isNaN(newAge)) {
      err = <strong>Your age must be a number</strong>;
    }
    this.setState({ errormessage: err });
  };

  handleUserAgeName = event => {
    this.setState({
      [event.target.name]:event.target.value
    });
  };

  render() {
    return (
      <form onSubmit={this.errorHandler}>
        <h1>
          Hello {this.state.username} {this.state.age}
        </h1>
    <p>Enter your name:</p>
    <input
      type="text"
      name="username"
      defaultValue=""
      onChange={this.handleUserAgeName}
    />
    <p>Enter your age:</p>
    <input
      type="text"
      name="age"
      defaultValue=""
      onChange={this.handleUserAgeName}
    />
    <br />
    <input type="submit" />
    {this.state.errormessage}
  </form>
);
  }
}
ReactDOM.render(<MyForm />, document.getElementById("root"));

<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>


问:
React lodash debounce always return null
I want to use lodash within class property but it always return me null for the value. I followed this Perform debounce in React.js (second answer and solution number 3)

my code:

```<code>// func
handleSearchInput = debounce(e => {
    console.log(e);
    e.persist();

    console.log(e.target);
}, 500);

// Render
<Input
    type="text"
    onKeyDown={this.handleSearchInput}
    placeholder="Search..."
/>
</code>```

all my console.log() always return me null. I want to get my input value.

Any solution?

答:
You can persist the synthetic event by using:

```<code>onClick(event) {
  event.persist();

   setTimeout(() => {
     consoloe.log(event);
   }, 1000);
}
</code>```

OR you can copy the event object:

```<code>onClick(event) {
 const eventClone = { ...event };

 setTimeout(() => {
     consoloe.log(eventClone);
 }, 1000);
}
</code>```

Body:
I want to use lodash within class property but it always return me null for the value. I followed this Perform debounce in React.js (second answer and solution number 3)

my code:

// func
handleSearchInput = debounce(e => {
    console.log(e);
    e.persist();

    console.log(e.target);
}, 500);

// Render
<Input
    type="text"
    onKeyDown={this.handleSearchInput}
    placeholder="Search..."
/>

all my console.log() always return me null. I want to get my input value.

Any solution?

Body:
You can persist the synthetic event by using:

onClick(event) {
  event.persist();

   setTimeout(() => {
     consoloe.log(event);
   }, 1000);
}

OR you can copy the event object:

onClick(event) {
 const eventClone = { ...event };

 setTimeout(() => {
     consoloe.log(eventClone);
 }, 1000);
}


问:
Android intent to open URL in same tab in google chrome
Google chrome opens URL in new tab when chrome app is killed.
Following code is being used.It open URL in same tab if chrome app is not killed otherwise it opens URL in new tab.

```<code>String urlString = "https://www.google.com/";
Intent intent1 = new Intent(Intent.ACTION_VIEW, Uri.parse(urlString));
intent1.putExtra(Browser.EXTRA_APPLICATION_ID, "com.android.chrome");
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent1.setPackage("com.android.chrome");
</code>```

The URL should be opened in chrome in a single tab.

答:
Use EXTRA_APPLICATION_ID with your intent to make sure that same browser tab is reused for your app. For example:

http://developer.android.com/reference/android/provider/Browser.html#

For Example

```<code>Context context = widget.getContext();
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());
</code>```

Body:
Google chrome opens URL in new tab when chrome app is killed.
Following code is being used.It open URL in same tab if chrome app is not killed otherwise it opens URL in new tab.

String urlString = "https://www.google.com/";
Intent intent1 = new Intent(Intent.ACTION_VIEW, Uri.parse(urlString));
intent1.putExtra(Browser.EXTRA_APPLICATION_ID, "com.android.chrome");
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent1.setPackage("com.android.chrome");

The URL should be opened in chrome in a single tab.

Body:
Use EXTRA_APPLICATION_ID with your intent to make sure that same browser tab is reused for your app. For example:

http://developer.android.com/reference/android/provider/Browser.html#

For Example

Context context = widget.getContext();
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());


问:
Can't push to bitbucket, Permission denied (publickey)
I am trying to push my project onto my bitbucket, been messing with this for about 4 days pouring through countless problem solving/pages/troubleshooting/tutorials. Im at a loss and very frustrated. I have done this before but on different computers...anyway here is the code/response that I'm getting

```<code>~/dev/sample_app git push -u origin --all
The authenticity of host 'bitbucket.org (131.103.20.168)' can't be established.
RSA key fingerprint is 81:7b:2c:f5:6f:18:2b:7c:4b:ec:aa:46:46:74:7c:40.
Are you sure you want to continue connecting (yes/no)?
Host key verification failed.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
~/dev/sample_app
</code>```

I am on a mac running 10.8.4.

So a little progress has been made, initially there was no .ssh folder so I created that way back in the beginning, there was no known_hosts file so I ran

```<code>ssh -T git@bitbucket.org
</code>```

I chose yes and this created a known_hosts file and when I tried to push again I got:

```<code>~/dev/sample_app git push -u origin --all
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

My .ssh folder is 700 and the keys inside are all 600.

答: In source tree select your project right click then you find an option "Convert to SSH"-> Repair -> login this solved for me

Body:
I am trying to push my project onto my bitbucket, been messing with this for about 4 days pouring through countless problem solving/pages/troubleshooting/tutorials. Im at a loss and very frustrated. I have done this before but on different computers...anyway here is the code/response that I'm getting

~/dev/sample_app git push -u origin --all
The authenticity of host 'bitbucket.org (131.103.20.168)' can't be established.
RSA key fingerprint is 81:7b:2c:f5:6f:18:2b:7c:4b:ec:aa:46:46:74:7c:40.
Are you sure you want to continue connecting (yes/no)?
Host key verification failed.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
~/dev/sample_app

I am on a mac running 10.8.4.

So a little progress has been made, initially there was no .ssh folder so I created that way back in the beginning, there was no known_hosts file so I ran

ssh -T git@bitbucket.org

I chose yes and this created a known_hosts file and when I tried to push again I got:

~/dev/sample_app git push -u origin --all
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

My .ssh folder is 700 and the keys inside are all 600.


问:
React Routing : toggle switch onclick dynamic routing
I am using a toggleswitch component in my react app. Within every event change of the toggle button, I want to change my routing, inside this component. Using react routing for the first time so I am pretty confused how can I handle it within the component.

If the state is true, I want to route it to "/", else i want it to "/videos". Here is my code :

```<code>import React, { Component } from "react";

class ToggleSwitch extends Component {
  constructor() {
    super();

    this.state = {
      toggleValue: false
    };

    this.changeToggleMenuValue = this.changeToggleMenuValue.bind(this);
  }

  changeToggleMenuValue(event) {
    this.setState({
      toggleValue: !this.state.toggleValue
    });
  }

  render() {
    return (
      <div className="onoffswitch">
        <input
          type="checkbox"
          name="onoffswitch"
          class="onoffswitch-checkbox"
          id="myonoffswitch"
          onClick={e => this.changeToggleMenuValue(e)}
        />
        <label class="onoffswitch-label" for="myonoffswitch">
          <span class="onoffswitch-inner"></span>
          <span class="onoffswitch-switch"></span>
        </label>
      </div>
    );
  }
}

export default ToggleSwitch;
</code>```

答:
This function should be work on your code:</p>

```<code>changeToggleMenuValue() {
    this.setState({
      toggleValue:
          this.state.toggleValue
             ? history.push('') // or history.push('/')
             : history.push('/videos');
    });
  }
</code>```

Body:
I am using a toggleswitch component in my react app. Within every event change of the toggle button, I want to change my routing, inside this component. Using react routing for the first time so I am pretty confused how can I handle it within the component.

If the state is true, I want to route it to "/", else i want it to "/videos". Here is my code :

import React, { Component } from "react";

class ToggleSwitch extends Component {
  constructor() {
    super();

    this.state = {
      toggleValue: false
    };

    this.changeToggleMenuValue = this.changeToggleMenuValue.bind(this);
  }

  changeToggleMenuValue(event) {
    this.setState({
      toggleValue: !this.state.toggleValue
    });
  }

  render() {
    return (

        <input
          type="checkbox"
          name="onoffswitch"
          class="onoffswitch-checkbox"
          id="myonoffswitch"
          onClick={e => this.changeToggleMenuValue(e)}
        />

    );
  }
}

export default ToggleSwitch;

Body:
This function should be work on your code:

changeToggleMenuValue() {
    this.setState({
      toggleValue:
          this.state.toggleValue
             ? history.push('') // or history.push('/')
             : history.push('/videos');
    });
  }


问:
Cartesian Product of PCollection with itself
Say I have a bounded PCollection p of type KV<String, Integer>. Assume p cannot fit in memory, and therefore cannot be a side input of a DoFn.

Example p:

```<code>("foo", 0)
("bar", 1)
("baz", 2)
</code>```

How can I take the cartesian product of p and itself?

For example, p x p may look as follows:

```<code>("foo+foo", [("foo", 0), ("foo", 0)])
("foo+bar", [("foo", 0), ("bar", 1)])
("foo+baz", [("foo", 0), ("baz", 2)])
("bar+foo", [("bar", 1), ("foo", 0)])
("bar+bar", [("bar", 1), ("bar", 1)])
("bar+baz", [("bar", 1), ("baz", 2)])
("baz+foo", [("baz", 2), ("foo", 0)])
("baz+bar", [("baz", 2), ("bar", 1)])
("baz+baz", [("baz", 2), ("baz", 2)])
</code>```

答:
As you've surmised, the easiest way to do this would be to have a DoFn that processes your PCollection as a main and side input.

If this doesn't work because the PCollection is too large to fit into memory, you could partition it into N disjoint PCollections, pass it through each of those, and then flatten the result. For example, you could write something like

```<code>class CrossProduct(beam.PTransform):
  def expand(self, pcoll):
    N = 10
    parts = pcoll | beam.Partition(lambda element, n: hash(element) % n, N)
    cross_parts = [
        pcoll | str(ix) >> beam.FlatMap(
            lambda x, side: [(x, s) for s in side],
            beam.pvalue.AsIter(part))
        for ix, part in enumerate(parts)]
    return cross_parts | beam.Flatten()

output = input | CrossProduct()
</code>```

Note, however, that unless the elements of your PCollection are particularly large, if the PCollection cannot fit into memory than its cross product may be prohibitively large to produce (and process).

Body:
Say I have a bounded PCollection p of type KV<String, Integer>. Assume p cannot fit in memory, and therefore cannot be a side input of a DoFn.

Example p:

("foo", 0)
("bar", 1)
("baz", 2)

How can I take the cartesian product of p and itself?

For example, p x p may look as follows:

("foo+foo", [("foo", 0), ("foo", 0)])
("foo+bar", [("foo", 0), ("bar", 1)])
("foo+baz", [("foo", 0), ("baz", 2)])
("bar+foo", [("bar", 1), ("foo", 0)])
("bar+bar", [("bar", 1), ("bar", 1)])
("bar+baz", [("bar", 1), ("baz", 2)])
("baz+foo", [("baz", 2), ("foo", 0)])
("baz+bar", [("baz", 2), ("bar", 1)])
("baz+baz", [("baz", 2), ("baz", 2)])

Body:
As you've surmised, the easiest way to do this would be to have a DoFn that processes your PCollection as a main and side input.

If this doesn't work because the PCollection is too large to fit into memory, you could partition it into N disjoint PCollections, pass it through each of those, and then flatten the result. For example, you could write something like

class CrossProduct(beam.PTransform):
  def expand(self, pcoll):
    N = 10
    parts = pcoll | beam.Partition(lambda element, n: hash(element) % n, N)
    cross_parts = [
        pcoll | str(ix) >> beam.FlatMap(
            lambda x, side: [(x, s) for s in side],
            beam.pvalue.AsIter(part))
        for ix, part in enumerate(parts)]
    return cross_parts | beam.Flatten()

output = input | CrossProduct()

Note, however, that unless the elements of your PCollection are particularly large, if the PCollection cannot fit into memory than its cross product may be prohibitively large to produce (and process).


答:
the base routing structure in react is like below:

1.Root Component:

basically you have a Root Component in your application, mainly the <App /> component

2.Inner Components:

inside of your <App /> component you render 2 type of components:

components that should render in your routes

components that are shared between your routes ( which means that they are visible in every route )

type 2 components would render on each route, because they are out of Switch, like code structure below:

```<code>function App(props) {

  return (
    <>

      <Header />

      <Switch>
       ...your routes
      </Switch>

      <SharedComponent_1 /> // may be a notif manager
      <SharedComponent_2 /> // may be a footer
      <SharedComponent_1 /> // other type of shared component

    </>

  )

}
</code>```

if you want to navigate from a route to another route inside of your component logic, you should ask your self two questions about your component:

is my component directly rendered by a <Route ... />?

is my component is just a simple sub component that rendered by another component which rendered by a <Router ... />

if your component has criteria of condition 1, then you already have history, match, location in your props and you can use history.push('/targetRoute') to navigate your user to another route.

however, if your component has criteras described in condition 2, you should wrap your component by a withRouter to get history, match and location into your props and user push function of history to navigate user around.

Title: React Routing : toggle switch onclick dynamic routing

Body:
the base routing structure in react is like below:

1.Root Component:

basically you have a Root Component in your application, mainly the <App /> component

2.Inner Components:

inside of your <App /> component you render 2 type of components:

components that should render in your routes

components that are shared between your routes ( which means that they are visible in every route )

type 2 components would render on each route, because they are out of Switch, like code structure below:

function App(props) {

  return (
    <>

      <Header />

      <Switch>
       ...your routes
      </Switch>

      <SharedComponent_1 /> // may be a notif manager
      <SharedComponent_2 /> // may be a footer
      <SharedComponent_1 /> // other type of shared component

    </>

  )

}

if you want to navigate from a route to another route inside of your component logic, you should ask your self two questions about your component:

is my component directly rendered by a <Route ... />?

is my component is just a simple sub component that rendered by another component which rendered by a <Router ... />

if your component has criteria of condition 1, then you already have history, match, location in your props and you can use history.push('/targetRoute') to navigate your user to another route.

however, if your component has criteras described in condition 2, you should wrap your component by a withRouter to get history, match and location into your props and user push function of history to navigate user around.


问:
Upload app to playstore error related to permission
I am trying to upload my ReactNative app to play store but it gives below error -

Upload failed
  Your APK or Android App Bundle is using permissions that require a privacy policy: (android.permission.CAMERA, android.permission.READ_CONTACTS).

i am not using Camera and contacts in my app, and not declare permissions for same in manifest but after generating signed apk it gives error mention above.

Any help really appreciated, i am not able to upload app to play store.

Thanks in advance.

答:
Generate the legal documents for your app
check out the link below for more information

https://www.iubenda.com/en/help/3744-how-to-add-android-and-ios-mobile-permissions-for-device-data#android


问:
How to show the only the upcoming 3 months in date pickers

<input id="datepicker" type="text">
```

<pre class="lang-js prettyprint-override"><code>$("#datepicker").datepicker({
  minDate: 0,
  beforeShowDay: function(d) {
    var day = d.getDate();
    return [day == 5 || day == 10 || day == 15 || day == 20 || day == 25];
  },
  beforeShow: function() {
    var dateTime = new Date();
    var hour = dateTime.getHours();
    var minute = dateTime.getMinutes();
    if (hour >= 18 && minute > 30) {
      $(this).datepicker("option", "minDate", "1");
    }
  }
});
</code>```

How to show the only the upcoming 3 months from current i.e feb, march and april in date pickers and enable 5, 10, 15, 20, 25 dates in every and disable the date after 6:30 PM

答:
you can disable all other date except upcoming three months.</p>

```<code>$("#datepicker").datepicker({
  maxDate: '+3M',
  numberOfMonths:3,
  minDate: 0,
  beforeShowDay: function(d) {
    var day = d.getDate();
    return [day == 5 || day == 10 || day == 15 || day == 20 || day == 25];
  },
  beforeShow: function() {
    var dateTime = new Date();
    var hour = dateTime.getHours();
    var minute = dateTime.getMinutes();
    if (hour >= 18 && minute > 30) {
      $(this).datepicker("option", "minDate", "1");
    }
  }
});
</code>```

Body:
<input id="datepicker" type="text">

$("#datepicker").datepicker({
  minDate: 0,
  beforeShowDay: function(d) {
    var day = d.getDate();
    return [day == 5 || day == 10 || day == 15 || day == 20 || day == 25];
  },
  beforeShow: function() {
    var dateTime = new Date();
    var hour = dateTime.getHours();
    var minute = dateTime.getMinutes();
    if (hour >= 18 && minute > 30) {
      $(this).datepicker("option", "minDate", "1");
    }
  }
});

How to show the only the upcoming 3 months from current i.e feb, march and april in date pickers and enable 5, 10, 15, 20, 25 dates in every and disable the date after 6:30 PM

Body:
you can disable all other date except upcoming three months.

$("#datepicker").datepicker({
  maxDate: '+3M',
  numberOfMonths:3,
  minDate: 0,
  beforeShowDay: function(d) {
    var day = d.getDate();
    return [day == 5 || day == 10 || day == 15 || day == 20 || day == 25];
  },
  beforeShow: function() {
    var dateTime = new Date();
    var hour = dateTime.getHours();
    var minute = dateTime.getMinutes();
    if (hour >= 18 && minute > 30) {
      $(this).datepicker("option", "minDate", "1");
    }
  }
});


问:
swift: auto logout after certain time
I am developing an app which is connected to a server through .net api.

What user logs in it generate an access token which is used to make network calls.

Requirement: After 20 mins of the generation of that access token, the
  token gets expired and the user have to log in again to continue using
  the app.

How can I achieve this feature that after 20 min the user will get logout from app and redirected to the home page.

If the user is using app even after 20 min from login? how to save the access token in app and remove it once user logout.

I have seen a couple of answers in Objective c but I want the answer in swift.

答:
Save your access token to the keychain, and timestamp it.

Write a function which gets you the API token from the keychain. Each time this function accesses the access token, it should check if its timestamp is older than 20 mins it should return nil, and then you shoudl take the user to the home screen.

Title: swift: auto logout after certain time


问:
Send and Extract zip file to azure VM using powershell
I am trying to send and extract the zip file to azure VM but unable make the connection to the remote Azure VM.

Code

```<code>$cred = Get-Credential
$SO = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck
$session = New-PSSession -ConnectionUri 'http://xx.xx.xxx.xxx:3389' -Credential $cred -SessionOption $SO

Send-File -Path C:\testArchive.zip -Destination C:\ -Session $session
Expand-Archive -Path C:\testArchive.zip -DestinationPath C:\ -Session $session
</code>```

Error

```<code>New-PSSession : [xx.xx.xxx.xxx] Connecting to remote server xx.xx.xxx.xxx
failed with the following error message : The client cannot connect to the
destination specified in the request. Verify that the service on the
destination is running and is accepting requests. Consult the logs and
documentation for the WS-Management service running on the destination, most
commonly IIS or WinRM. If the destination is the WinRM service, run the
following command on the destination to analyze and configure the WinRM
service: "winrm quickconfig". For more information, see the
about_Remote_Troubleshooting Help topic.
At line:4 char:12
+ $session = New-PSSession -ConnectionUri 'http://xx.xx.xxx.xxx:3389' - ...
+            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:Re
   moteRunspace) [New-PSSession], PSRemotingTransportException
    + FullyQualifiedErrorId : CannotConnect,PSSessionOpenFailed
</code>```

Below is the output when i run 'winrm quickconfig' command on azure VM

```<code>WinRM service is already running on this machine.
WinRM is already set up for remote management on this computer.
</code>```

When I run the 'Enter-PSSession -ComputerName LoadTestVm -Port 3389 -Credential qa-admin'

```<code>Enter-PSSession : Connecting to remote server LoadTestVm failed with the following error
message : The WinRM client cannot process the request because the server name cannot be
resolved. For more information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:1
+ Enter-PSSession -ComputerName LoadTestVm -Port 3389 -Credential qa-ad ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (LoadTestVm:String) [Enter-PSSession], PSRem
   otingTransportException
    + FullyQualifiedErrorId : CreateRemoteRunspaceFailed
</code>```

答:
This is not really a best practice risk management/Security-wise.

```<code><#
$username = 'qa-admin'
$pass = ConvertTo-SecureString -string 'xxxxxxxx' -AsPlainText -Force
#>
</code>```

This ...

```<code><#
$cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist $username, $pass
#>
</code>```

... there is a built-in cmdlet for this.

Never pass clear text passwords in a script. Either:

prompt for them

Read them from a secure pre-created file

Quickly and securely storing your credentials – PowerShell

Working with Passwords, Secure Strings and Credentials in Windows
  PowerShell

from Windows credential manager

CredentialManager 2.0

Accessing Windows Credentials Manager from PowerShell

How to Manage Secrets and Passwords with CredentialManager and
  PowerShell

```<code>$cred = Get-Credential -Credential $env:USERNAME
</code>```

This...

```<code>$session = New-PSSession -ConnectionUri 'http://xx.xx.xxx.xxx:3389' -Credential $cred -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck)
</code>```

...is not correct. You cannot do this. You need the results of the above to pass to the -SessionOption param.

```<code>Get-Help -Name New-PSSessionOption -Examples

<#
NAME
    New-PSSessionOption

SYNOPSIS
    Creates an object that contains advanced options for a PSSession.

Example 1: Create a default session option

    PS C:\>New-PSSessionOption
...

This command creates a session option object that has all of the default values.
Example 2: Configure a session by using a session option object

    PS C:\>$pso = New-PSSessionOption -Culture "fr-fr" -MaximumReceivedObjectSize 10MB
    PS C:\>New-PSSession -ComputerName Server01 -SessionOption $pso

...

Example 3: Start an interactive session

    PS C:\>Enter-PSSession -ComputerName Server01 -SessionOption (New-PSSessionOption -NoEncryption -NoCompression)

...
Example 4: Modify a session option object

    PS C:\>$a = New-PSSessionOption
...

PS C:\> $a.UICulture = (Get-UICulture)
PS C:\> $a.OpenTimeout = (New-Timespan -Minutes 4)
PS C:\> $a.MaximumConnectionRedirectionCount = 1
PS C:\> $a

...

Example 5: Create a preference variable

    PS C:\>$PSSessionOption = New-PSSessionOption -OpenTimeOut 120000

...

Example 6: Fulfill the requirements for a remote session configuration

    PS C:\>$skipCN = New-PSSessionOption -SkipCNCheck
    PS C:\>New-PSSession -ComputerName 171.09.21.207 -UseSSL -Credential Domain01\User01 -SessionOption $SkipCN

...

Example 7: Make arguments available to a remote session

    PS C:\>$team = @{Team="IT"; Use="Testing"}
    PS C:\>$TeamOption = New-PSSessionOption -ApplicationArguments $team
    PS C:\>$s = New-PSSession -ComputerName Server01 -SessionOption $TeamOption
    PS C:\>Invoke-Command -Session $s {$PSSenderInfo.SpplicationArguments}

...

    PS C:\>Invoke-Command -Session $s {if ($PSSenderInfo.ApplicationArguments.Use -ne "Testing") {.\logFiles.ps1} else {"Just testing."}}
...
#>
</code>```

So, yours is...

```<code>$SO       = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck
$session  = New-PSSession -ConnectionUri 'http://xx.xx.xxx.xxx:3389' -Credential $cred -SessionOption $SO

# Process other actions
Send-File -Path C:\testArchive.zip -Destination C:\ -Session $session
Expand-Archive -Path C:\testArchive.zip -DestinationPath C:\ -Session $session
</code>```

Body:
I am trying to send and extract the zip file to azure VM but unable make the connection to the remote Azure VM.

Code

$cred = Get-Credential
$SO = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck
$session = New-PSSession -ConnectionUri 'http://xx.xx.xxx.xxx:3389' -Credential $cred -SessionOption $SO

Send-File -Path C:\testArchive.zip -Destination C:\ -Session $session
Expand-Archive -Path C:\testArchive.zip -DestinationPath C:\ -Session $session

Error

New-PSSession : [xx.xx.xxx.xxx] Connecting to remote server xx.xx.xxx.xxx
failed with the following error message : The client cannot connect to the
destination specified in the request. Verify that the service on the
destination is running and is accepting requests. Consult the logs and
documentation for the WS-Management service running on the destination, most
commonly IIS or WinRM. If the destination is the WinRM service, run the
following command on the destination to analyze and configure the WinRM
service: "winrm quickconfig". For more information, see the
about_Remote_Troubleshooting Help topic.
At line:4 char:12
+ $session = New-PSSession -ConnectionUri 'http://xx.xx.xxx.xxx:3389' - ...
+            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (System.Manageme....RemoteRunspace:Re
   moteRunspace) [New-PSSession], PSRemotingTransportException
    + FullyQualifiedErrorId : CannotConnect,PSSessionOpenFailed

Below is the output when i run 'winrm quickconfig' command on azure VM

WinRM service is already running on this machine.
WinRM is already set up for remote management on this computer.

When I run the 'Enter-PSSession -ComputerName LoadTestVm -Port 3389 -Credential qa-admin'

Enter-PSSession : Connecting to remote server LoadTestVm failed with the following error
message : The WinRM client cannot process the request because the server name cannot be
resolved. For more information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:1
+ Enter-PSSession -ComputerName LoadTestVm -Port 3389 -Credential qa-ad ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (LoadTestVm:String) [Enter-PSSession], PSRem
   otingTransportException
    + FullyQualifiedErrorId : CreateRemoteRunspaceFailed

Body:
This is not really a best practice risk management/Security-wise.

<#
$username = 'qa-admin'
$pass = ConvertTo-SecureString -string 'xxxxxxxx' -AsPlainText -Force
#>

This ...

<#
$cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist $username, $pass
#>

... there is a built-in cmdlet for this.

Never pass clear text passwords in a script. Either:

prompt for them

Read them from a secure pre-created file

Quickly and securely storing your credentials – PowerShell

Working with Passwords, Secure Strings and Credentials in Windows
  PowerShell

from Windows credential manager

CredentialManager 2.0

Accessing Windows Credentials Manager from PowerShell

How to Manage Secrets and Passwords with CredentialManager and
  PowerShell

$cred = Get-Credential -Credential $env:USERNAME

This...

$session = New-PSSession -ConnectionUri 'http://xx.xx.xxx.xxx:3389' -Credential $cred -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck)

...is not correct. You cannot do this. You need the results of the above to pass to the -SessionOption param.

Get-Help -Name New-PSSessionOption -Examples

<#
NAME
    New-PSSessionOption

SYNOPSIS
    Creates an object that contains advanced options for a PSSession.

Example 1: Create a default session option

    PS C:\>New-PSSessionOption
...

This command creates a session option object that has all of the default values.
Example 2: Configure a session by using a session option object

    PS C:\>$pso = New-PSSessionOption -Culture "fr-fr" -MaximumReceivedObjectSize 10MB
    PS C:\>New-PSSession -ComputerName Server01 -SessionOption $pso

...

Example 3: Start an interactive session

    PS C:\>Enter-PSSession -ComputerName Server01 -SessionOption (New-PSSessionOption -NoEncryption -NoCompression)

...
Example 4: Modify a session option object

    PS C:\>$a = New-PSSessionOption
...

PS C:\> $a.UICulture = (Get-UICulture)
PS C:\> $a.OpenTimeout = (New-Timespan -Minutes 4)
PS C:\> $a.MaximumConnectionRedirectionCount = 1
PS C:\> $a

...

Example 5: Create a preference variable

    PS C:\>$PSSessionOption = New-PSSessionOption -OpenTimeOut 120000

...

Example 6: Fulfill the requirements for a remote session configuration

    PS C:\>$skipCN = New-PSSessionOption -SkipCNCheck
    PS C:\>New-PSSession -ComputerName 171.09.21.207 -UseSSL -Credential Domain01\User01 -SessionOption $SkipCN

...

Example 7: Make arguments available to a remote session

    PS C:\>$team = @{Team="IT"; Use="Testing"}
    PS C:\>$TeamOption = New-PSSessionOption -ApplicationArguments $team
    PS C:\>$s = New-PSSession -ComputerName Server01 -SessionOption $TeamOption
    PS C:\>Invoke-Command -Session $s {$PSSenderInfo.SpplicationArguments}

...

    PS C:\>Invoke-Command -Session $s {if ($PSSenderInfo.ApplicationArguments.Use -ne "Testing") {.\logFiles.ps1} else {"Just testing."}}
...
#>

So, yours is...

$SO       = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck
$session  = New-PSSession -ConnectionUri 'http://xx.xx.xxx.xxx:3389' -Credential $cred -SessionOption $SO

# Process other actions
Send-File -Path C:\testArchive.zip -Destination C:\ -Session $session
Expand-Archive -Path C:\testArchive.zip -DestinationPath C:\ -Session $session


问:
How to split images diagonally?
I have images like below. I would like to split them diagonally, probably using the centroid of the image or get the angle of the bounding rect/ellipse and cut along that.

The blue and green colors are to represent different contours, in practice, these will be binary thresholded, so all colors look the same.

I can cut the images horizontally or vertically using list slicing:

```<code>eg img_split=img[:50%,:]
</code>```

How do I do it diagonally in OpenCV Python/Numpy?

Images:

Split sample:

答:
If you just want to cut, you can use fillPoly function which helps you to cut any polygonal shape. In the code below, I just gave the polygonal points manually.

Note: If you want the program to detect those points, for the first image it is easy because the objects have different colors. But for the second image I dont know how to do.

Result:

Code:

Note: My environment is C++ based thats why I used it but it should be easy to convert.

```<code>#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/imgproc/imgproc.hpp"

using namespace cv;

int main()
{

    cv::Mat img = cv::imread("/ur/image/directory/image.png");
    imshow("original",img);

    cv::Point corners[1][4];
    corners[0][0] = Point( 0, 0 );
    corners[0][1] = Point( img.cols/2, img.rows/2 );
    corners[0][2] = Point( img.cols, img.rows );
    corners[0][3] = Point( img.cols, 0 );

    const Point* corner_list[1] = { corners[0] };

    int num_points = 4;
    int num_polygons = 1;
    int line_type = 8;

    cv::Mat mask = cv::Mat::zeros(img.rows, img.cols, CV_8UC1);
    cv::fillPoly( mask, corner_list, &num_points, num_polygons, cv::Scalar( 255, 255, 255 ),  line_type);
    cv::Mat result(img.size(), img.type(), cv::Scalar(255, 255, 255));
    img.copyTo(result, mask);

    imshow("Output",result);
    cv::waitKey(0);
    return 0;
}
</code>```

Title: How to split images diagonally?

Body:
I have images like below. I would like to split them diagonally, probably using the centroid of the image or get the angle of the bounding rect/ellipse and cut along that.

The blue and green colors are to represent different contours, in practice, these will be binary thresholded, so all colors look the same.

I can cut the images horizontally or vertically using list slicing:

eg img_split=img[:50%,:]

How do I do it diagonally in OpenCV Python/Numpy?

Images:

Split sample:

Body:
If you just want to cut, you can use fillPoly function which helps you to cut any polygonal shape. In the code below, I just gave the polygonal points manually.

Note: If you want the program to detect those points, for the first image it is easy because the objects have different colors. But for the second image I dont know how to do.

Result:

Code:

Note: My environment is C++ based thats why I used it but it should be easy to convert.

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/imgproc/imgproc.hpp"

using namespace cv;

int main()
{

    cv::Mat img = cv::imread("/ur/image/directory/image.png");
    imshow("original",img);

    cv::Point corners[1][4];
    corners[0][0] = Point( 0, 0 );
    corners[0][1] = Point( img.cols/2, img.rows/2 );
    corners[0][2] = Point( img.cols, img.rows );
    corners[0][3] = Point( img.cols, 0 );

    const Point* corner_list[1] = { corners[0] };

    int num_points = 4;
    int num_polygons = 1;
    int line_type = 8;

    cv::Mat mask = cv::Mat::zeros(img.rows, img.cols, CV_8UC1);
    cv::fillPoly( mask, corner_list, &num_points, num_polygons, cv::Scalar( 255, 255, 255 ),  line_type);
    cv::Mat result(img.size(), img.type(), cv::Scalar(255, 255, 255));
    img.copyTo(result, mask);

    imshow("Output",result);
    cv::waitKey(0);
    return 0;
}


问:
Trying to merge 2 dataframes but get ValueError
These are my two dataframes saved in two variables:

```<code>> print(df.head())
>
          club_name  tr_jan  tr_dec  year
    0  ADO Den Haag    1368    1422  2010
    1  ADO Den Haag    1455    1477  2011
    2  ADO Den Haag    1461    1443  2012
    3  ADO Den Haag    1437    1383  2013
    4  ADO Den Haag    1386    1422  2014
> print(rankingdf.head())
>
           club_name  ranking  year
    0    ADO Den Haag    12    2010
    1    ADO Den Haag    13    2011
    2    ADO Den Haag    11    2012
    3    ADO Den Haag    14    2013
    4    ADO Den Haag    17    2014
</code>```

I'm trying to merge these two using this code:

```<code>new_df = df.merge(ranking_df, on=['club_name', 'year'], how='left')
</code>```

The how='left' is added because I have less datapoints in my ranking_df than in my standard df.

The expected behaviour is as such:

```<code>> print(new_df.head())
>

      club_name  tr_jan  tr_dec  year    ranking
0  ADO Den Haag    1368    1422  2010    12
1  ADO Den Haag    1455    1477  2011    13
2  ADO Den Haag    1461    1443  2012    11
3  ADO Den Haag    1437    1383  2013    14
4  ADO Den Haag    1386    1422  2014    17
</code>```

But I get this error:

ValueError: You are trying to merge on object and int64 columns. If
  you wish to proceed you should use pd.concat

But I do not wish to use concat since I want to merge the trees not just add them on.

Another behaviour that's weird in my mind is that my code works if I save the first df to .csv and then load that .csv into a dataframe.

The code for that:

```<code>df = pd.DataFrame(data_points, columns=['club_name', 'tr_jan', 'tr_dec', 'year'])
df.to_csv('preliminary.csv')

df = pd.read_csv('preliminary.csv', index_col=0)

ranking_df = pd.DataFrame(rankings, columns=['club_name', 'ranking', 'year'])

new_df = df.merge(ranking_df, on=['club_name', 'year'], how='left')
</code>```

I think that it has to do with the index_col=0 parameter. But I have no idea to fix it without having to save it, it doesn't matter much but is kind of an annoyance that I have to do that.

答:
At first check the type of columns which you want to merge. You will see one of them is string where other one is int. Then convert it to int as following code:

```<code>df["something"] = df["something"].astype(int)

merged = df.merge[df1, on="something"]
</code>```

Body:
These are my two dataframes saved in two variables:

> print(df.head())
>
          club_name  tr_jan  tr_dec  year
    0  ADO Den Haag    1368    1422  2010
    1  ADO Den Haag    1455    1477  2011
    2  ADO Den Haag    1461    1443  2012
    3  ADO Den Haag    1437    1383  2013
    4  ADO Den Haag    1386    1422  2014
> print(rankingdf.head())
>
           club_name  ranking  year
    0    ADO Den Haag    12    2010
    1    ADO Den Haag    13    2011
    2    ADO Den Haag    11    2012
    3    ADO Den Haag    14    2013
    4    ADO Den Haag    17    2014

I'm trying to merge these two using this code:

new_df = df.merge(ranking_df, on=['club_name', 'year'], how='left')

The how='left' is added because I have less datapoints in my ranking_df than in my standard df.

The expected behaviour is as such:

> print(new_df.head())
>

      club_name  tr_jan  tr_dec  year    ranking
0  ADO Den Haag    1368    1422  2010    12
1  ADO Den Haag    1455    1477  2011    13
2  ADO Den Haag    1461    1443  2012    11
3  ADO Den Haag    1437    1383  2013    14
4  ADO Den Haag    1386    1422  2014    17

But I get this error:

ValueError: You are trying to merge on object and int64 columns. If
  you wish to proceed you should use pd.concat

But I do not wish to use concat since I want to merge the trees not just add them on.

Another behaviour that's weird in my mind is that my code works if I save the first df to .csv and then load that .csv into a dataframe.

The code for that:

df = pd.DataFrame(data_points, columns=['club_name', 'tr_jan', 'tr_dec', 'year'])
df.to_csv('preliminary.csv')

df = pd.read_csv('preliminary.csv', index_col=0)

ranking_df = pd.DataFrame(rankings, columns=['club_name', 'ranking', 'year'])

new_df = df.merge(ranking_df, on=['club_name', 'year'], how='left')

I think that it has to do with the index_col=0 parameter. But I have no idea to fix it without having to save it, it doesn't matter much but is kind of an annoyance that I have to do that.

Body:
At first check the type of columns which you want to merge. You will see one of them is string where other one is int. Then convert it to int as following code:

df["something"] = df["something"].astype(int)

merged = df.merge[df1, on="something"]