问:
Remove label from node using patch
I'd like to remove a label from node using strategic merge patch.
Here is what I used to remove label:

```<code>kubectl patch node xxx --type='strategic' -p '{"metadata":{"labels":{"$patch": "delete", "node-role.kubernetes.io/master":""}}}'
xxx patched
</code>```

It succeeded but there are two issues here:

It removed all labels but not only the label I specified.

When I tried to patch it again on same node, it reported error:

```<code>kubectl patch node xxx --type='strategic' -p '{"metadata":{"labels":{"$patch": "delete", "node-role.kubernetes.io/master":""}}}'
The Node "xxx" is invalid: metadata.labels: Invalid value: "$patch": name part must consist of alphanumeric characters, '-', '_' or '.', and must start and end with an alphanumeric character (e.g. 'MyName',  or 'my.name',  or '123-abc', regex used for validation is '([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9]')
</code>```

How should I only remove one label I specified?
The patch with delete operation is not idempotent? I don't quite understand the error it reported when I tried to delete the label again.

答:
Check the REST API that kubectl internally calls to remove a label from a node

```<code>kubectl label nodes kind-control-plane abc- -v=10

I0602 09:21:04.717687   37243 request.go:1068] Request Body: {"metadata":{"labels":{"abc":null}}}
I0602 09:21:04.717784   37243 round_trippers.go:423] curl -k -v -XPATCH  -H "User-Agent: kubectl/v1.18.0 (darwin/amd64) kubernetes/9e99141" -H "Accept: application/json" -H "Content-Type: application/merge-patch+json" 'https://127.0.0.1:32768/api/v1/nodes/kind-control-plane'
</code>```

Then call the same API from client library

Title: Remove label from node using patch

Body:
I'd like to remove a label from node using strategic merge patch.
Here is what I used to remove label:

kubectl patch node xxx --type='strategic' -p '{"metadata":{"labels":{"$patch": "delete", "node-role.kubernetes.io/master":""}}}'
xxx patched

It succeeded but there are two issues here:

It removed all labels but not only the label I specified.

When I tried to patch it again on same node, it reported error:

kubectl patch node xxx --type='strategic' -p '{"metadata":{"labels":{"$patch": "delete", "node-role.kubernetes.io/master":""}}}'
The Node "xxx" is invalid: metadata.labels: Invalid value: "$patch": name part must consist of alphanumeric characters, '-', '_' or '.', and must start and end with an alphanumeric character (e.g. 'MyName',  or 'my.name',  or '123-abc', regex used for validation is '([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9]')

How should I only remove one label I specified?
The patch with delete operation is not idempotent? I don't quite understand the error it reported when I tried to delete the label again.

Body:
Check the REST API that kubectl internally calls to remove a label from a node

kubectl label nodes kind-control-plane abc- -v=10

I0602 09:21:04.717687   37243 request.go:1068] Request Body: {"metadata":{"labels":{"abc":null}}}
I0602 09:21:04.717784   37243 round_trippers.go:423] curl -k -v -XPATCH  -H "User-Agent: kubectl/v1.18.0 (darwin/amd64) kubernetes/9e99141" -H "Accept: application/json" -H "Content-Type: application/merge-patch+json" 'https://127.0.0.1:32768/api/v1/nodes/kind-control-plane'

Then call the same API from client library


来源: stackexchange

问:
Executing collection group queries in a specific FireStore collection
I have a database structure as follows (simplified for purposes of this question):

```<code>Collection: item_A
    -> Document: params = {someParameter: "value"}
    -> Document: user_01
        -> Sub-collection: orders
            -> Document: order_AA = {type: "A1", address: {pincode: "000000", city:"Paris"}
            -> Document: order_AB = {type: "A2", address: {pincode: "111111", city:"London"}
            ...
    -> Document: user_02
        -> Sub-collection: orders
            -> Document: order_AC = {type: "A1", address: {pincode: "222222", city:"Berlin"}
            -> Document: order_AD = {type: "A1", address: {pincode: "333333", city:"Paris"}
            ...

Collection: item_B
    -> Document: params = {someParameter: "value"}
    -> Document: user_01
        -> Sub-collection: orders
            -> Document: order_BA = {type: "B1", address: {pincode: "000000", city:"Paris"}
            -> Document: order_BB = {type: "B2", address: {pincode: "111111", city:"London"}
            ...
    -> Document: user_02
        -> Sub-collection: orders
            -> Document: order_BC = {type: "B1", address: {pincode: "222222", city:"Berlin"}
            -> Document: order_BD = {type: "B2", address: {pincode: "333333", city:"Paris"}
            ...
</code>```

What I want to do:
Obtain a list of all the orders across all users for a user-specified collection (item).
(please note that the number of "user" documents is variable over time, and also the number of "order" documents within the sub-collection. The number of "items" is constant ~10, so I wish to avoid to manually code for handling each of them)

In more words...
The user shall input the item type (e.g. item_A or item_B).
Additionally the user can specify the required city (e.g. Paris).
Now I want to query FireStore to find all the orders of that particular item type with the matching city.

How can I do this in the shortest steps (fewest queries)?

Can I use "collection group queries" for this? I have tried toying with this, but I am not sure I understand how. How can I restrict the query to run on a specified collection (e.g. item_A) and not all the available collections (item_A, item_B). Do I need to rename the sub-collections differently for each item (e.g. orders_item_A) to make use of collection group queries selectively?

答:
Update: it turns out that querying a specific path may be possible after all, thanks to how FieldPath.documentId() is indexed for collection group indexes. Check @samthecodingman's answer here: https://stackoverflow.com/a/68049847

Collection group queries currently run on all collections of specific name. They cannot run on just the collections of a name in a specific path.

So you you want to run them on the orders under item_A, you will have to give those subcollections a unique name, like item_A_orders.

ContentLicense: CC BY-SA 4.0

Body:
I have a database structure as follows (simplified for purposes of this question):

Collection: item_A
    -> Document: params = {someParameter: "value"}
    -> Document: user_01
        -> Sub-collection: orders
            -> Document: order_AA = {type: "A1", address: {pincode: "000000", city:"Paris"}
            -> Document: order_AB = {type: "A2", address: {pincode: "111111", city:"London"}
            ...
    -> Document: user_02
        -> Sub-collection: orders
            -> Document: order_AC = {type: "A1", address: {pincode: "222222", city:"Berlin"}
            -> Document: order_AD = {type: "A1", address: {pincode: "333333", city:"Paris"}
            ...

Collection: item_B
    -> Document: params = {someParameter: "value"}
    -> Document: user_01
        -> Sub-collection: orders
            -> Document: order_BA = {type: "B1", address: {pincode: "000000", city:"Paris"}
            -> Document: order_BB = {type: "B2", address: {pincode: "111111", city:"London"}
            ...
    -> Document: user_02
        -> Sub-collection: orders
            -> Document: order_BC = {type: "B1", address: {pincode: "222222", city:"Berlin"}
            -> Document: order_BD = {type: "B2", address: {pincode: "333333", city:"Paris"}
            ...

What I want to do:
Obtain a list of all the orders across all users for a user-specified collection (item).
(please note that the number of "user" documents is variable over time, and also the number of "order" documents within the sub-collection. The number of "items" is constant ~10, so I wish to avoid to manually code for handling each of them)

In more words...
The user shall input the item type (e.g. item_A or item_B).
Additionally the user can specify the required city (e.g. Paris).
Now I want to query FireStore to find all the orders of that particular item type with the matching city.

How can I do this in the shortest steps (fewest queries)?

Can I use "collection group queries" for this? I have tried toying with this, but I am not sure I understand how. How can I restrict the query to run on a specified collection (e.g. item_A) and not all the available collections (item_A, item_B). Do I need to rename the sub-collections differently for each item (e.g. orders_item_A) to make use of collection group queries selectively?


问:
telerik mvc grid access cell data to enable columns.Command
I can't seem to find a way to reference the value in a column in the grid, in my case it is the StatusId.  Based on the cell value in this row, for the StatusId, I need to return a true or false to the method ".Visible(???)".  It would be nice to find the answer in the documentation online but I haven't been able to.  I find it hard to believe that I would be the first person who ever needed this functionality.

I would be most appreciative of any assistance since no one in the telerik forums know.

```<code>.Columns(columns => {
    columns.Command(commands => {
    commands.Edit().ButtonType(ButtonType);
    commands.Delete().ButtonType(ButtonType);
}).Width(90).Visible(???);
</code>```

Thanks!
AZee

答: Above solution doesnt work with Ajax Binding ....For example if I want to show a perticular Cell's text Color in Red .." i.e. Cell_Text="In Error", when the Grid loads for the 1st time then this solution becomes applicable but when I apply some Ajax Actions on the said Grid like Filtering , then my Cell_Text again changes back to its normal text color .... Do you have any other codes for my perticular scenario</p>

ContentLicense: CC BY-SA 2.5

Body:
I can't seem to find a way to reference the value in a column in the grid, in my case it is the StatusId.  Based on the cell value in this row, for the StatusId, I need to return a true or false to the method ".Visible(???)".  It would be nice to find the answer in the documentation online but I haven't been able to.  I find it hard to believe that I would be the first person who ever needed this functionality.

I would be most appreciative of any assistance since no one in the telerik forums know.

.Columns(columns => {
    columns.Command(commands => {
    commands.Edit().ButtonType(ButtonType);
    commands.Delete().ButtonType(ButtonType);
}).Width(90).Visible(???);

Thanks!
AZee

ContentLicense: CC BY-SA 3.0


问:
Clear rules of AWS security group for a particular port
How to remove all rules for a given port using the "aws ec2"?</p>

```<code>aws ec2 revoke-security-group-ingress --group-name MySecurityGroup --protocol tcp --port 22 **--ALL-IP**
</code>```

答:
revoke-security-group-ingress in version 2 gives us to specify multiple IP CIDRS. See below solution written in PHP which I am trying to clean in multiple region and multiple prots.

To specify multiple rules in a single command use the --ip-permissions option https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/revoke-security-group-ingress.html

```<code>$cleanports = [22,5984];
$sgids = [["sgid"=>"sg1","region"=>"us-east-1"],["sgid"=>"sg1","region"=>"us-east-1"]];
foreach($sgids as $sgidDetail){
    $iprules = json_decode(shell_exec("/usr/bin/aws ec2 describe-security-groups --group-ids {$sgidDetail['sgid']} --region {$sgidDetail['region']} --query 'SecurityGroups[*].IpPermissions'"), true)[0];

    foreach ($iprules as $key => $ips) {
        if(!empty($ips['FromPort']) && !empty($ips['ToPort']) && in_array($ips['FromPort'], $cleanports) && in_array($ips['ToPort'], $cleanports)){
            echo "\n\n";
            echo shell_exec("/usr/bin/aws ec2 revoke-security-group-ingress --group-id {$sgidDetail['sgid']} --region {$sgidDetail['region']} --ip-permissions '".json_encode($ips)."'");
        }
    }
}
</code>```

Body:
How to remove all rules for a given port using the "aws ec2"?

aws ec2 revoke-security-group-ingress --group-name MySecurityGroup --protocol tcp --port 22 **--ALL-IP**

Body:
revoke-security-group-ingress in version 2 gives us to specify multiple IP CIDRS. See below solution written in PHP which I am trying to clean in multiple region and multiple prots.

To specify multiple rules in a single command use the --ip-permissions option https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/revoke-security-group-ingress.html

$cleanports = [22,5984];
$sgids = [["sgid"=>"sg1","region"=>"us-east-1"],["sgid"=>"sg1","region"=>"us-east-1"]];
foreach($sgids as $sgidDetail){
    $iprules = json_decode(shell_exec("/usr/bin/aws ec2 describe-security-groups --group-ids {$sgidDetail['sgid']} --region {$sgidDetail['region']} --query 'SecurityGroups[*].IpPermissions'"), true)[0];

    foreach ($iprules as $key => $ips) {
        if(!empty($ips['FromPort']) && !empty($ips['ToPort']) && in_array($ips['FromPort'], $cleanports) && in_array($ips['ToPort'], $cleanports)){
            echo "\n\n";
            echo shell_exec("/usr/bin/aws ec2 revoke-security-group-ingress --group-id {$sgidDetail['sgid']} --region {$sgidDetail['region']} --ip-permissions '".json_encode($ips)."'");
        }
    }
}


问:
How can i rerender Pinterest's Pin It button?
I'm trying to create and manipulate the Pin It button after page load. When i change the button properties with js, it should be rerendered to get the functionality of pinning dynamically loaded images. So, does Pinterest have any method like Facebook's B.XFBML.parse() function?

Thanks...

答:
As of June 2020, Pinterest updated the pin js code to v2. That's why data-pin-build might not work on

Now it works on pinit_v2.js

Body:
As of June 2020, Pinterest updated the pin js code to v2. That's why data-pin-build might not work on
<script defer="defer" src="//assets.pinterest.com/js/pinit.js" data-pin-build="parsePins"></script>

Now it works on pinit_v2.js
<script async defer src="//assets.pinterest.com/js/pinit_v2.js" data-pin-build="parsePins"></script>


问:
gzip -t in a loop and run script
I have several *.gz files in a folder, and I want to run a python script on them. However, I have been getting errors. These errors are associated with corrupted gz files.

I want run my python script ONLY in gz files correctly compressed. I have tried the following:

```<code>for i in *.gz;
do
    if gzip -t $i
    then
        python myscript.py
    else
        echo 'file is corrupt'
    fi
done;
</code>```

But my script is being run also in corrupted gz files (and through a lot of errors).

Alternatively, Can I modified the python script to read only non-corrupted gz files?

The top of my current script is:

```<code>for tf in glob.glob('*.gz'):
    tar = tarfile.open(tf)
    tar.extractall()
    tar.close()
    files = [file for file in glob.glob('*.txt')] ..
</code>```

If I open the gz files, I would like to keep it (cause I know gunzip will delete the original gz file while decompressing).

Thanks in advance

答:
Use:

```<code>gunzip -t $i
</code>```

instead, to check for corruption:

```<code>for i in *.gz;
do
    if gunzip -t $i
    then
        python myscript.py
    else
        echo 'file is corrupt'
    fi
done;
</code>```

the default for gunzip is to decompress.

-t tests the file for integrity.

To do this all with bash:

```<code>for i in *.gz;
do
    if gunzip -t $i
    then
        gzip -d $1 # -d decompress
    else
        echo 'file is corrupt'
    fi
done;
</code>```

gunzip keeps the origin files when you pass the -k option to it, -k for keep input files

Title: gzip -t in a loop and run script

Body:
I have several *.gz files in a folder, and I want to run a python script on them. However, I have been getting errors. These errors are associated with corrupted gz files.

I want run my python script ONLY in gz files correctly compressed. I have tried the following:

for i in *.gz;
do
    if gzip -t $i
    then
        python myscript.py
    else
        echo 'file is corrupt'
    fi
done;

But my script is being run also in corrupted gz files (and through a lot of errors).

Alternatively, Can I modified the python script to read only non-corrupted gz files?

The top of my current script is:

for tf in glob.glob('*.gz'):
    tar = tarfile.open(tf)
    tar.extractall()
    tar.close()
    files = [file for file in glob.glob('*.txt')] ..

If I open the gz files, I would like to keep it (cause I know gunzip will delete the original gz file while decompressing).

Thanks in advance

Body:
Use:

gunzip -t $i

instead, to check for corruption:

for i in *.gz;
do
    if gunzip -t $i
    then
        python myscript.py
    else
        echo 'file is corrupt'
    fi
done;

the default for gunzip is to decompress.

-t tests the file for integrity.

To do this all with bash:

for i in *.gz;
do
    if gunzip -t $i
    then
        gzip -d $1 # -d decompress
    else
        echo 'file is corrupt'
    fi
done;

gunzip keeps the origin files when you pass the -k option to it, -k for keep input files


问:
how to make it so the space inbetween buttons can't be highlighted
html:

<button id='automoney' onclick='minusTen()'></button>
<button id='automoney2' onclick='minusHundred()'></button>
<button id='automoney3' onclick='minusFiveHundred()'></button>
<button id='automoney4' onclick='minusThousand()'></button>
<button id='automoney5' onclick='minusFifteenHundred()'></button>
<button id='automoney6' onclick='minusThreeThousand()'></button>```

the space between the buttons can be highlighted. if there is a way to do it using CSS, that would be preferable, if not, that's fine too

thanks in advance

答:
Try wrapping buttons into flex div to remove spaces.

div {
  display: flex;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
    <button id='automoney' onclick='minusTen()'></button>
    <button id='automoney2' onclick='minusHundred()'></button>
    <button id='automoney3' onclick='minusFiveHundred()'></button>
    <button id='automoney4' onclick='minusThousand()'></button>
    <button id='automoney5' onclick='minusFifteenHundred()'></button>
    <button id='automoney6' onclick='minusThreeThousand()'></button>
</div></code>```

Body:
html:

<button id='automoney' onclick='minusTen()'></button>
<button id='automoney2' onclick='minusHundred()'></button>
<button id='automoney3' onclick='minusFiveHundred()'></button>
<button id='automoney4' onclick='minusThousand()'></button>
<button id='automoney5' onclick='minusFifteenHundred()'></button>
<button id='automoney6' onclick='minusThreeThousand()'></button>

the space between the buttons can be highlighted. if there is a way to do it using CSS, that would be preferable, if not, that's fine too

thanks in advance

Body:
Try wrapping buttons into flex div to remove spaces.

div {
  display: flex;
}

<div>
    <button id='automoney' onclick='minusTen()'></button>
    <button id='automoney2' onclick='minusHundred()'></button>
    <button id='automoney3' onclick='minusFiveHundred()'></button>
    <button id='automoney4' onclick='minusThousand()'></button>
    <button id='automoney5' onclick='minusFifteenHundred()'></button>
    <button id='automoney6' onclick='minusThreeThousand()'></button>
</div>


问:
How do I check mobile data connection and set up an event for it?
I want to check the mobile data connection and if it turns on or off, I will define an event for it.
When the data cell is turned on, display the mobile data icon,
When the mobile data is turned off, the mobile data icon will also be hidden!</p>

答:
Determine whether you have an internet connection

```<code>ConnectivityManager cm =
        (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
                      activeNetwork.isConnectedOrConnecting();
</code>```

Determine the type of internet connection

```<code>ConnectivityManager cm =
        (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
boolean isMetered = cm.isActiveNetworkMetered();
</code>```

For more information click here.

Body:
Determine whether you have an internet connection

ConnectivityManager cm =
        (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
                      activeNetwork.isConnectedOrConnecting();

Determine the type of internet connection

ConnectivityManager cm =
        (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
boolean isMetered = cm.isActiveNetworkMetered();

For more information click here.


问:
Change appended td by condition inside loop
I am appending rows and columns to a table using javascript. But I need one of the classname inside the td to somethings else based on the condition inside a `$.post() response.

I did this:

```<code>let arr = ['Hermione', 'Ron', 'Harry']

arr.forEach(d=>{
    $('#the_table>tbody').append(`
                <tr id='tr_${d}'>
                    <td'>${d}</td>
                    <td><i id='change' class='no'></i></td>
                </tr>
            `);
});

const myfunc = () => {
$.post(api, json_object,
    function(data, status) {
        if (data.value === 'started') {
        setTimeout(myfunc, 5000);
    } else {
        $('#change').removeClass('no').addClass('yes');
        }
}, 'json');
            }
myfunc();
</code>```

When I do this, it is only changing the value for the first value (Hermione). But in the console.log, I can see that the data.value is not started so it should've changed to yes.

Hoe can I change it to yes for each of the rows once the condition has been passed

答:
The problem is that You are using the same id name for identifying many differents rows .
Each ID  must be unique . So if you have many elements to manipulate it is better to identify them by their classname instead . Change the the the attribute ID to CLASS as illustrated below .

```<code> // I have only change the attribute id to class
 let arr = ['Hermione', 'Ron', 'Harry']

 arr.forEach(d=>{
 $('#the_table>tbody').append(`
     <tr id='tr_${d}'>
       <td'>${d}</td>
       <td><i class='change' class='no'></i></td>// now their identified by class name
            </tr>
        `);
  });

 const myfunc = () => {
 $.post(api, json_object,
     function(data, status) {
         if (data.value === 'started') {
             setTimeout(myfunc, 5000);
         } else {
            $('.change').removeClass('no').addClass('yes');
         }
     }, 'json');
 }

 myfunc();
</code>```

Body:
I am appending rows and columns to a table using javascript. But I need one of the classname inside the td to somethings else based on the condition inside a `$.post() response.

I did this:

let arr = ['Hermione', 'Ron', 'Harry']

arr.forEach(d=>{
    $('#the_table>tbody').append(`

                    ${d}

            `);
});

const myfunc = () => {
$.post(api, json_object,
    function(data, status) {
        if (data.value === 'started') {
        setTimeout(myfunc, 5000);
    } else {
        $('#change').removeClass('no').addClass('yes');
        }
}, 'json');
            }
myfunc();

When I do this, it is only changing the value for the first value (Hermione). But in the console.log, I can see that the data.value is not started so it should've changed to yes.

Hoe can I change it to yes for each of the rows once the condition has been passed

Body:
The problem is that You are using the same id name for identifying many differents rows .
Each ID  must be unique . So if you have many elements to manipulate it is better to identify them by their classname instead . Change the the the attribute ID to CLASS as illustrated below .

 // I have only change the attribute id to class
 let arr = ['Hermione', 'Ron', 'Harry']

 arr.forEach(d=>{
 $('#the_table>tbody').append(`
     <tr id='tr_${d}'>
       <td'>${d}</td>
       <td><i class='change' class='no'></i></td>// now their identified by class name
            </tr>
        `);
  });

 const myfunc = () => {
 $.post(api, json_object,
     function(data, status) {
         if (data.value === 'started') {
             setTimeout(myfunc, 5000);
         } else {
            $('.change').removeClass('no').addClass('yes');
         }
     }, 'json');
 }

 myfunc();


问:
Using pandas dataframes, how to read through a column to find "True" statement and then proceed to create a new dataframe
Below I have 4 columns in my dataframe. I am interested in going through the entire "Greater_than_50" column. Upon reaching a "True" flag, I then want to take the associated  "Discharge" and "Resistance" values to make a new dataframe which contains only those values found to be "True".

```<code>time           Discharge          Resistance  Greater_than_50
-------------------------------------------------------------
0                  0.000                 NaN              NaN
1                  0.005              76.373             True
2                  0.010             -48.174            False
3                  0.016             -37.012            False
4                  0.021             -27.808            False
5                  0.026             -24.674            False
6                  0.031             -20.464            False
7                  0.037             100.114            True
...                  ...                 ...              ...
</code>```

I would like the new dataframe to look something like this:

```<code>Discharge          Resistance
------------------------------
0.005              76.373
0.037             100.114
...                   ...

</code>```

答:
```<code>df['Greater_than_50'] = [val.strip() for val in df['Greater_than_50'].astype(str)]

# columns to keep
col_mask = ['Discharge', 'Resistance']

df_new = df.loc[df['Greater_than_50'] == 'True'][col_mask]
</code>```

This is how I tested it:

```<code>'''
time    Discharge   Resistance  Greater_than_50
0   0.000   NaN NaN
1   0.005   76.373  True
2   0.010   -48.174 False
3   0.016   -37.012 False
4   0.021   -27.808 False
5   0.026   -24.674 False
6   0.031   -20.464 False
7   0.037   100.114 True
'''

import pandas as pd

df = pd.read_clipboard()

print(df)
</code>```

Original df:

```<code>   time  Discharge  Resistance Greater_than_50
0     0      0.000         NaN             NaN
1     1      0.005      76.373            True
2     2      0.010     -48.174           False
3     3      0.016     -37.012           False
4     4      0.021     -27.808           False
5     5      0.026     -24.674           False
6     6      0.031     -20.464           False
7     7      0.037     100.114            True
</code>```

.

```<code>df['Greater_than_50'] = [val.strip() for val in df['Greater_than_50'].astype(str)]

# columns to keep
col_mask = ['Discharge', 'Resistance']

df_new = df.loc[df['Greater_than_50'] == 'True'][col_mask]
print(df_new)
</code>```

Output:

```<code>   Discharge  Resistance
1      0.005      76.373
7      0.037     100.114
</code>```

Just replace whatever columns you want to keep in the 'col_mask'.

Body:
Below I have 4 columns in my dataframe. I am interested in going through the entire "Greater_than_50" column. Upon reaching a "True" flag, I then want to take the associated  "Discharge" and "Resistance" values to make a new dataframe which contains only those values found to be "True".

time           Discharge          Resistance  Greater_than_50
-------------------------------------------------------------
0                  0.000                 NaN              NaN
1                  0.005              76.373             True
2                  0.010             -48.174            False
3                  0.016             -37.012            False
4                  0.021             -27.808            False
5                  0.026             -24.674            False
6                  0.031             -20.464            False
7                  0.037             100.114            True
...                  ...                 ...              ...

I would like the new dataframe to look something like this:

Discharge          Resistance
------------------------------
0.005              76.373
0.037             100.114
...                   ...

Body:
df['Greater_than_50'] = [val.strip() for val in df['Greater_than_50'].astype(str)]

# columns to keep
col_mask = ['Discharge', 'Resistance']

df_new = df.loc[df['Greater_than_50'] == 'True'][col_mask]

This is how I tested it:

'''
time    Discharge   Resistance  Greater_than_50
0   0.000   NaN NaN
1   0.005   76.373  True
2   0.010   -48.174 False
3   0.016   -37.012 False
4   0.021   -27.808 False
5   0.026   -24.674 False
6   0.031   -20.464 False
7   0.037   100.114 True
'''

import pandas as pd

df = pd.read_clipboard()

print(df)

Original df:

   time  Discharge  Resistance Greater_than_50
0     0      0.000         NaN             NaN
1     1      0.005      76.373            True
2     2      0.010     -48.174           False
3     3      0.016     -37.012           False
4     4      0.021     -27.808           False
5     5      0.026     -24.674           False
6     6      0.031     -20.464           False
7     7      0.037     100.114            True

.

df['Greater_than_50'] = [val.strip() for val in df['Greater_than_50'].astype(str)]

# columns to keep
col_mask = ['Discharge', 'Resistance']

df_new = df.loc[df['Greater_than_50'] == 'True'][col_mask]
print(df_new)

Output:

   Discharge  Resistance
1      0.005      76.373
7      0.037     100.114

Just replace whatever columns you want to keep in the 'col_mask'.


问:
How to create multiple varibles with multiple values
I'm making a game where the user has to stop people from hacking into their company's database/security.

Currently, I have a variable int threats; that I can assign a value to. This doesn't work because I need to have multiple threats that have their own type, like DDos or Malware, and they also need names, like $DDoSThreat%.

This has been killing me for weeks, all help would be appreciated.

答:
You could've used std::vector<> for storing multiple struct types using a single variable.

Look at the following:

```<code>#include <iostream>
#include <vector>

struct Malware {
    std::string name;
    bool danger;
};

void getMalwareDetails(Malware); // parameter: struct

int main(void) {
    std::vector<Malware> malware; // HERE'S WHAT I'M TALKING ABOUT
    Malware mTemp; // for temporary
    char ask;

    do {
        std::cout << "Malware name and is that danger (1/0)? : ";
        std::cin >> mTemp.name >> mTemp.danger;

        malware.push_back(mTemp); // adds the info to struct

        std::cout << "Add more? (Y/n): ";
        std::cin >> ask;

    } while (ask == 'Y' || ask == 'y');

    for (int i = 0; i < malware.size(); i++)
        getMalwareDetails(malware[i]); // get the struct info

    return 0;
}

void getMalwareDetails(Malware m) {
    std::cout << "Name: " << m.name << " Danger?: " << m.danger << std::endl;
}
</code>```

Create a struct, use std::vector<STRUCT_NAME>, add the struct values to the vector variable on each iteration then finally display them. Similarly, you may use one more struct for DDos.

Sample Output

```<code>Malware name and is that danger? : $DDoSThreat% 1 // --- INPUT
Add more? (Y/n): y
Malware name and is that danger? : Trojan 1
Add more? (Y/n): y
Malware name and is that danger? : Google 0
Add more? (Y/n): n
Name: $DDoSThreat% Danger?: 1 // --- OUTPUT
Name: Trojan Danger?: 1
Name: Google Danger?: 0
</code>```

Body:
You could've used std::vector<> for storing multiple struct types using a single variable.

Look at the following:

#include <iostream>
#include <vector>

struct Malware {
    std::string name;
    bool danger;
};

void getMalwareDetails(Malware); // parameter: struct

int main(void) {
    std::vector<Malware> malware; // HERE'S WHAT I'M TALKING ABOUT
    Malware mTemp; // for temporary
    char ask;

    do {
        std::cout << "Malware name and is that danger (1/0)? : ";
        std::cin >> mTemp.name >> mTemp.danger;

        malware.push_back(mTemp); // adds the info to struct

        std::cout << "Add more? (Y/n): ";
        std::cin >> ask;

    } while (ask == 'Y' || ask == 'y');

    for (int i = 0; i < malware.size(); i++)
        getMalwareDetails(malware[i]); // get the struct info

    return 0;
}

void getMalwareDetails(Malware m) {
    std::cout << "Name: " << m.name << " Danger?: " << m.danger << std::endl;
}

Create a struct, use std::vector<STRUCT_NAME>, add the struct values to the vector variable on each iteration then finally display them. Similarly, you may use one more struct for DDos.

Sample Output

Malware name and is that danger? : $DDoSThreat% 1 // --- INPUT
Add more? (Y/n): y
Malware name and is that danger? : Trojan 1
Add more? (Y/n): y
Malware name and is that danger? : Google 0
Add more? (Y/n): n
Name: $DDoSThreat% Danger?: 1 // --- OUTPUT
Name: Trojan Danger?: 1
Name: Google Danger?: 0


问:
Mock abstract class default behaviour with Rhino
I'm pretty new to mocking so this might be something I'm just not picking up on yet, but I can't find a good example anywhere.

I'm trying to assert that by default, any class that inherits from my abstract class will instantiate a collection in the constructor.  Here's the abstract class:

```<code>public abstract class DataCollectionWorkflow : SequentialWorkflowActivity
{
        private readonly DataSet _output = new DataSet();
        private List<DataCollectionParameter> _params = null;

        public DataCollectionWorkflow()
        {
            _params = new List<DataCollectionParameter>();
        }

        public virtual IList<DataCollectionParameter> Parameters
        {
            get { return _params; }
            set { _params = (List<DataCollectionParameter>)value; }
        }
}
</code>```

How do I mock this with Rhino?  If I do a GenerateMock<DataCollectionWorkflow> (or a stub), the constructor runs and the mock's private field "_params" gets initialized, but the mock's "Parameters" property is simply null.

Obviously the generated mock subclass is overriding the property implementation.  Is there some way of excluding the Parameters property from being re-implemented?

Thanks.

答:
Okay, I figured it out.  Chalk me up as another casualty to the intricacies of Rhino.  This kind of thing makes me want to move to a simpler framework, maybe I'll check out MoQ.

So the answer is using PartialMocks.  I had briefly toyed with generating a partial mock, but when I ran the debugger over it I noticed that the properties weren't even null, they were throwing weird exceptions, so I didn't look much deeper.  I was using the short form AAA type of syntax.

Turns out if I simply put the mock into playback mode, the test works - the properties are used as is (as they should be with a partial mock).

So here's the answer:

```<code>[Test]
public void ShouldCreateParameterListInConstructor()
{
      var mockRepository = new MockRepository();
      var mock = mockRepository.PartialMock<DataCollectionWorkflow>();
      using ( mockRepository.Record() )
      {

      }
      using (mockRepository.Playback())
      {
           Assert.That(mock.Parameters, Is.Not.Null, "DataCollectionWorkflow base class didn't create new param collection");
      }
}
</code>```

I realize that this is a stateful test but it's actually a simpler prelude to some behavioural testing that involves the property in question, so I wanted this case as prerequisite.  Hope it helps someone.

OwnerDisplayName: womp

Body:
I'm pretty new to mocking so this might be something I'm just not picking up on yet, but I can't find a good example anywhere.

I'm trying to assert that by default, any class that inherits from my abstract class will instantiate a collection in the constructor.  Here's the abstract class:

public abstract class DataCollectionWorkflow : SequentialWorkflowActivity
{
        private readonly DataSet _output = new DataSet();
        private List<DataCollectionParameter> _params = null;

        public DataCollectionWorkflow()
        {
            _params = new List<DataCollectionParameter>();
        }

        public virtual IList<DataCollectionParameter> Parameters
        {
            get { return _params; }
            set { _params = (List<DataCollectionParameter>)value; }
        }
}

How do I mock this with Rhino?  If I do a GenerateMock<DataCollectionWorkflow> (or a stub), the constructor runs and the mock's private field "_params" gets initialized, but the mock's "Parameters" property is simply null.

Obviously the generated mock subclass is overriding the property implementation.  Is there some way of excluding the Parameters property from being re-implemented?

Thanks.

Body:
Okay, I figured it out.  Chalk me up as another casualty to the intricacies of Rhino.  This kind of thing makes me want to move to a simpler framework, maybe I'll check out MoQ.

So the answer is using PartialMocks.  I had briefly toyed with generating a partial mock, but when I ran the debugger over it I noticed that the properties weren't even null, they were throwing weird exceptions, so I didn't look much deeper.  I was using the short form AAA type of syntax.

Turns out if I simply put the mock into playback mode, the test works - the properties are used as is (as they should be with a partial mock).

So here's the answer:

[Test]
public void ShouldCreateParameterListInConstructor()
{
      var mockRepository = new MockRepository();
      var mock = mockRepository.PartialMock<DataCollectionWorkflow>();
      using ( mockRepository.Record() )
      {

      }
      using (mockRepository.Playback())
      {
           Assert.That(mock.Parameters, Is.Not.Null, "DataCollectionWorkflow base class didn't create new param collection");
      }
}

I realize that this is a stateful test but it's actually a simpler prelude to some behavioural testing that involves the property in question, so I wanted this case as prerequisite.  Hope it helps someone.


问:
set parameter which is null in @NamedQuery (JPA QL 1.0)
I am writing a JPA QL named query that would search for documents. This should be done in only one query and I cannot switch to native SQL (that's non functional requirement).
The query I wrote looks as follows:

```<code>query = "select doc from Doc doc " +
" join doc.Csts cst " +
" where cst.cstFrstNm like :FrstNm " +
" and cst.cstLastNm like :LastNm " +
" and doc.resId = :id ";
</code>```

This query is parametrized using following instructions:

```<code>query.setParameter("FrstNm ", firstName + '%');
query.setParameter("LastNm ", lastName + '%');
query.setParameter("id", resId);
</code>```

firstName, lastName, resId in the above code are my search criteria and they are all Strings and they can be null. When one of them is null, it shouldn't be taken into consideration when the query is invoked.

For instance:

Let's say that: firstName = "John", lastName = "Doe" and resId is null, then the query should return all the entries from Doc table that are for user John Doe, no matter what is their resId.

I was trying to put additional OR and AND conditions into query that'd check if resId is null but it didn't work. I'm testing it on HSQLDB.

Is it any way to modify this JPA query to handle null values?

答:
You may need to build the query dynamically to satisfy your parameters. For instance:

```<code>public List<Employee> findEmployees(String name, String deptName, String projectName, String city) {
  StringBuffer query = new StringBuffer();
  query.append("SELECT DISTINCT e ");
  query.append("FROM Employee e LEFT JOIN e.projects p ");
  query.append("WHERE ");
  List<String> criteria = new ArrayList<String>();
  if (name != null) { criteria.add("e.name = :name"); }
  if (deptName != null) { criteria.add("e.dept.name = :dept"); }
  if (projectName != null) { criteria.add("p.name = :project"); }
  if (city != null) { criteria.add("e.address.city = :city"); }
  if (criteria.size() == 0) {
     throw new RuntimeException("no criteria");
  }
  for (int i = 0; i < criteria.size(); i++) {
    if (i > 0) { query.append(" AND "); }
       query.append(criteria.get(i));
  }
  Query q = em.createQuery(query.toString());
  if (name != null) { q.setParameter("name", name); }
  if (deptName != null) { q.setParameter("dept", deptName); }
  if (projectName != null) { q.setParameter("project", projectName); }
  if (city != null) { q.setParameter("city", city); }
  return (List<Employee>)q.getResultList();
}
</code>```

You migt also like to consider Criteria API if you are using JPA 2.0 for this kind of task.

Body:
I am writing a JPA QL named query that would search for documents. This should be done in only one query and I cannot switch to native SQL (that's non functional requirement).
The query I wrote looks as follows:

query = "select doc from Doc doc " +
" join doc.Csts cst " +
" where cst.cstFrstNm like :FrstNm " +
" and cst.cstLastNm like :LastNm " +
" and doc.resId = :id ";

This query is parametrized using following instructions:

query.setParameter("FrstNm ", firstName + '%');
query.setParameter("LastNm ", lastName + '%');
query.setParameter("id", resId);

firstName, lastName, resId in the above code are my search criteria and they are all Strings and they can be null. When one of them is null, it shouldn't be taken into consideration when the query is invoked.

For instance:

Let's say that: firstName = "John", lastName = "Doe" and resId is null, then the query should return all the entries from Doc table that are for user John Doe, no matter what is their resId.

I was trying to put additional OR and AND conditions into query that'd check if resId is null but it didn't work. I'm testing it on HSQLDB.

Is it any way to modify this JPA query to handle null values?

Body:
You may need to build the query dynamically to satisfy your parameters. For instance:

public List<Employee> findEmployees(String name, String deptName, String projectName, String city) {
  StringBuffer query = new StringBuffer();
  query.append("SELECT DISTINCT e ");
  query.append("FROM Employee e LEFT JOIN e.projects p ");
  query.append("WHERE ");
  List<String> criteria = new ArrayList<String>();
  if (name != null) { criteria.add("e.name = :name"); }
  if (deptName != null) { criteria.add("e.dept.name = :dept"); }
  if (projectName != null) { criteria.add("p.name = :project"); }
  if (city != null) { criteria.add("e.address.city = :city"); }
  if (criteria.size() == 0) {
     throw new RuntimeException("no criteria");
  }
  for (int i = 0; i < criteria.size(); i++) {
    if (i > 0) { query.append(" AND "); }
       query.append(criteria.get(i));
  }
  Query q = em.createQuery(query.toString());
  if (name != null) { q.setParameter("name", name); }
  if (deptName != null) { q.setParameter("dept", deptName); }
  if (projectName != null) { q.setParameter("project", projectName); }
  if (city != null) { q.setParameter("city", city); }
  return (List<Employee>)q.getResultList();
}

You migt also like to consider Criteria API if you are using JPA 2.0 for this kind of task.


问:
How to draw a line in line chart for single value in Charts.JS
I need to plot a single value in line chart. Currently i am using charts.JS library for line graph purpose.

The data will be varied some times i'll get the single data inside the data set at that time i need to plot the single value in the line chart.

I had tried with the charts.js annotation plugin but it didn't meet my requirements. which is like it wis  overlapping the plotted point in the graph area.

My code

```<code>createLineChart() {
   this.lineChart = new Chart(this.lineCanvas.nativeElement, {
      type: "line",

      data: {
        labels:[],

        datasets: [
          {
            fill: false,

            backgroundColor: "#0168FF",
            borderColor: "#0168FF",
            pointBackgroundColor: "white", // wite point fill
            pointBorderWidth: 1, // point border width
            lineTension: 0,
            pointBorderColor: "blue",
            pointRadius: 4,
          },
        ],
      },
      options: {
        scales: {
          yAxes: [
            {
              ticks: {
                padding: 20,
                beginAtZero: true,
                min: 0,

                stepSize: 100,
              },
              gridLines: {
                drawBorder: false,
              },
            },
          ],
          xAxes: [
            {
             // offset: true,
              ticks: {
                display: false,
               //beginAtZero: true,
               min: 0,

              },
              gridLines: {
                zeroLineColor: "transparent",
                drawBorder: false,
                display: false,
              },
              //offset:true,
            },
          ],
          legend: {
            display: false,
          },
          tooltips: {
            enabled: false,
          },
        },
          drawTime: "afterDraw", // (default)
        } as ChartOptions,
       // plugins: [ChartAnnotation]
      },
    });
  }
</code>```

To plot the data dynamically:

```<code>generateRandomDataSet(size) {
    let yaxisArr = [];
    let xaxisArr = [];
    let random_data:any = this.getRandomData(size)
    let maxYTickVal = Math.max.apply(Math, random_data.map((val) => {return val.yaxis}));
    let maxVal = Math.ceil((maxYTickVal+1) / 10) * 10

    for(let data of random_data) {
      yaxisArr.push(data.yaxis)
      xaxisArr.push(data.xaxis)
    }

    this.lineChart.data.datasets[0].data = yaxisArr
    this.lineChart.config.data.labels = []
    this.lineChart.config.data.labels = xaxisArr
    this.lineChart.config.options.scales.yAxes[0].ticks.max =maxVal
    this.lineChart.config.options.scales.yAxes[0].ticks.stepSize = maxVal/2

    this.lineChart.update()
  }
</code>```

What i required

What i am getting

Thankyou.

答:
There exists different approaches to solve this problem.

According to the answer I gave to a similar question, you can define an animation.onComplete function to draw the line.

In a comment on before mentioned answer, Lakshmansundeep suggested an approach where he defines the same data value three times but makes sure, pointRadius for the leading and ending data point is zero.

```<code>datasets: [{
  data: [120, 120, 120],
  ...
  pointRadius: [0, 4, 0],
  pointHoverRadius: [0, 4, 0],
}],
</code>```

For the second approach, please have a look at the code below.

new Chart('line-chart', {
  type: "line",
  data: {
    labels: [null, 'A', null],
    datasets: [{
      data: [120, 120, 120],
      fill: false,
      backgroundColor: "#0168FF",
      borderColor: "#0168FF",
      pointBackgroundColor: "white",
      pointBorderWidth: 1,
      lineTension: 0,
      pointBorderColor: "blue",
      pointRadius: [0, 4, 0],
      pointHoverRadius: [0, 4, 0],
    }],
  },
  options: {
    legend: {
      display: false
    },
    tooltips: {
      enabled: false
    },
    scales: {
      yAxes: [{
        ticks: {
          padding: 20,
          min: 0,
          stepSize: 100
        },
        gridLines: {
          drawBorder: false
        }
      }],
      xAxes: [{
        ticks: {
          display: false
        },
        gridLines: {
          zeroLineColor: "transparent",
          drawBorder: false,
          display: false
        }
      }]
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="line-chart" height="80"></canvas></code>```

Body:
I need to plot a single value in line chart. Currently i am using charts.JS library for line graph purpose.

The data will be varied some times i'll get the single data inside the data set at that time i need to plot the single value in the line chart.

I had tried with the charts.js annotation plugin but it didn't meet my requirements. which is like it wis  overlapping the plotted point in the graph area.

My code

createLineChart() {
   this.lineChart = new Chart(this.lineCanvas.nativeElement, {
      type: "line",

      data: {
        labels:[],

        datasets: [
          {
            fill: false,

            backgroundColor: "#0168FF",
            borderColor: "#0168FF",
            pointBackgroundColor: "white", // wite point fill
            pointBorderWidth: 1, // point border width
            lineTension: 0,
            pointBorderColor: "blue",
            pointRadius: 4,
          },
        ],
      },
      options: {
        scales: {
          yAxes: [
            {
              ticks: {
                padding: 20,
                beginAtZero: true,
                min: 0,

                stepSize: 100,
              },
              gridLines: {
                drawBorder: false,
              },
            },
          ],
          xAxes: [
            {
             // offset: true,
              ticks: {
                display: false,
               //beginAtZero: true,
               min: 0,

              },
              gridLines: {
                zeroLineColor: "transparent",
                drawBorder: false,
                display: false,
              },
              //offset:true,
            },
          ],
          legend: {
            display: false,
          },
          tooltips: {
            enabled: false,
          },
        },
          drawTime: "afterDraw", // (default)
        } as ChartOptions,
       // plugins: [ChartAnnotation]
      },
    });
  }

To plot the data dynamically:

generateRandomDataSet(size) {
    let yaxisArr = [];
    let xaxisArr = [];
    let random_data:any = this.getRandomData(size)
    let maxYTickVal = Math.max.apply(Math, random_data.map((val) => {return val.yaxis}));
    let maxVal = Math.ceil((maxYTickVal+1) / 10) * 10

    for(let data of random_data) {
      yaxisArr.push(data.yaxis)
      xaxisArr.push(data.xaxis)
    }

    this.lineChart.data.datasets[0].data = yaxisArr
    this.lineChart.config.data.labels = []
    this.lineChart.config.data.labels = xaxisArr
    this.lineChart.config.options.scales.yAxes[0].ticks.max =maxVal
    this.lineChart.config.options.scales.yAxes[0].ticks.stepSize = maxVal/2

    this.lineChart.update()
  }

What i required

What i am getting

Thankyou.

Body:
There exists different approaches to solve this problem.

According to the answer I gave to a similar question, you can define an animation.onComplete function to draw the line.

In a comment on before mentioned answer, Lakshmansundeep suggested an approach where he defines the same data value three times but makes sure, pointRadius for the leading and ending data point is zero.

datasets: [{
  data: [120, 120, 120],
  ...
  pointRadius: [0, 4, 0],
  pointHoverRadius: [0, 4, 0],
}],

For the second approach, please have a look at the code below.

new Chart('line-chart', {
  type: "line",
  data: {
    labels: [null, 'A', null],
    datasets: [{
      data: [120, 120, 120],
      fill: false,
      backgroundColor: "#0168FF",
      borderColor: "#0168FF",
      pointBackgroundColor: "white",
      pointBorderWidth: 1,
      lineTension: 0,
      pointBorderColor: "blue",
      pointRadius: [0, 4, 0],
      pointHoverRadius: [0, 4, 0],
    }],
  },
  options: {
    legend: {
      display: false
    },
    tooltips: {
      enabled: false
    },
    scales: {
      yAxes: [{
        ticks: {
          padding: 20,
          min: 0,
          stepSize: 100
        },
        gridLines: {
          drawBorder: false
        }
      }],
      xAxes: [{
        ticks: {
          display: false
        },
        gridLines: {
          zeroLineColor: "transparent",
          drawBorder: false,
          display: false
        }
      }]
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="line-chart" height="80"></canvas>


问:
Should I make the method virtual or abstract?
I have an abstract class that does its own internal validation. It has another method that allows subclasses to do additional validation checks. Currently, I've made the method abstract.

```<code>protected abstract bool ValidateFurther();
</code>```

However, I'm seeing quite a number of subclasses being forced to override it just to return true. I'm considering to make the method virtual.

```<code>protected virtual bool ValidateFurther() => true;
</code>```

Is it bad to assume that validation is going to be fine in the abstract class? I'm worried that subclasses may not notice it and ended up not overriding it even when it is needed. Which is the more suitable approach here?

答:
abstract method means you just want to define the behavior to be followed, and let sub classes do the implementation.

virtual method means you defined an method with initial implementation, but allow to be override.

So maybe you can explain you context more, then we can discuss it!

Body:
I have an abstract class that does its own internal validation. It has another method that allows subclasses to do additional validation checks. Currently, I've made the method abstract.

protected abstract bool ValidateFurther();

However, I'm seeing quite a number of subclasses being forced to override it just to return true. I'm considering to make the method virtual.

protected virtual bool ValidateFurther() => true;

Is it bad to assume that validation is going to be fine in the abstract class? I'm worried that subclasses may not notice it and ended up not overriding it even when it is needed. Which is the more suitable approach here?


答:
Add css flex property to your div or float it and remove all white spaces, then add margin to the buttons to add space that is not delectable.

div {
  display: flex;
}
button {
  margin: 0 3px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
    <button id='automoney' onclick='minusTen()'></button>
    <button id='automoney2' onclick='minusHundred()'></button>
    <button id='automoney3' onclick='minusFiveHundred()'></button>
    <button id='automoney4' onclick='minusThousand()'></button>
    <button id='automoney5' onclick='minusFifteenHundred()'></button>
    <button id='automoney6' onclick='minusThreeThousand()'></button>
</div></code>```

Title: how to make it so the space inbetween buttons can't be highlighted

Body:
Add css flex property to your div or float it and remove all white spaces, then add margin to the buttons to add space that is not delectable.

div {
  display: flex;
}
button {
  margin: 0 3px;
}

<div>
    <button id='automoney' onclick='minusTen()'></button>
    <button id='automoney2' onclick='minusHundred()'></button>
    <button id='automoney3' onclick='minusFiveHundred()'></button>
    <button id='automoney4' onclick='minusThousand()'></button>
    <button id='automoney5' onclick='minusFifteenHundred()'></button>
    <button id='automoney6' onclick='minusThreeThousand()'></button>
</div>


问:
Adding new.line in future price?
I've spent the whole day trying to figure this out.. so here I am.

1.
I want to make a script to plot lines and text like this:
https://gyazo.com/250560130c661044d2c37106b9a367fe

I got the lines for historical price figured out, but for future, I'm starting to think it's not possible with lines? I have tried so much.

2.
Is it possible to put text on vertical line directly in line.new? Or make a label.new and rotate it 90 degrees?

3.
How could I get the texts to be at the same level above/below the bars? Right now I use low[30]

//@version=4
study("TEST nr 032",overlay=true)
fromHour = 00
t1 = timestamp("GMT-4", year, month, dayofmonth, fromHour, 00, 00)
t2 = t1
timeIsOk = (time >= t1) and (time <= t2)

if timeIsOk and dayofweek == dayofweek.monday
    line.new(bar_index, low * .9999, bar_index, high * 1.0001, xloc.bar_index, extend.both, color.blue, line.style_solid, 1)
    var label1 = label.new(bar_index, low[30], text="Monday", style=label.style_none)
    label.set_x(label1, 0)
    label.set_xloc(label1, time, xloc.bar_time)

if timeIsOk and dayofweek == dayofweek.tuesday
    line.new(bar_index, low * .9999, bar_index, high * 1.0001, xloc.bar_index, extend.both, color.blue, line.style_solid, 1)
    var label2 = label.new(bar_index, low[30], text="Tuesday", style=label.style_none)
    label.set_x(label2, 0)
    label.set_xloc(label2, time, xloc.bar_time)

if timeIsOk and dayofweek == dayofweek.wednesday
    line.new(bar_index, low * .9999, bar_index, high * 1.0001, xloc.bar_index, extend.both, color.blue, line.style_solid, 1)
    var label3 = label.new(bar_index, low[30], text="Wednesday", style=label.style_none)
    label.set_x(label3, 0)
    label.set_xloc(label3, time, xloc.bar_time)

if timeIsOk and dayofweek == dayofweek.thursday
    line.new(bar_index, low * .9999, bar_index, high * 1.0001, xloc.bar_index, extend.both, color.blue, line.style_solid, 1)
    var label4 = label.new(bar_index, low[30], text="Tursday", style=label.style_none)
    label.set_x(label4, 0)
    label.set_xloc(label4, time, xloc.bar_time)

if timeIsOk and dayofweek == dayofweek.friday
    line.new(bar_index, low * .9999, bar_index, high * 1.0001, xloc.bar_index, extend.both, color.blue, line.style_solid, 1)
    var label5 = label.new(bar_index, low[30], text="Friday", style=label.style_none)
    label.set_x(label5, 0)
    label.set_xloc(label5, time, xloc.bar_time)

fromHour2 = 18
t3 = timestamp("GMT-4", year, month, dayofmonth, fromHour2, 00, 00)
t4 = t3
timeIsOk2 = (time >= t3) and (time <= t4)

if timeIsOk2 and dayofweek == dayofweek.sunday
    line.new(bar_index, low * .9999, bar_index, high * 1.0001, xloc.bar_index, extend.both, color.red, line.style_solid, 1)
    var label7 = label.new(bar_index, low[30], text="Sunday", style=label.style_none)
    label.set_x(label7, 0)
    label.set_xloc(label7, time, xloc.bar_time)```

Thank you so much for your time, I really apperience it.

答:
This should get you on your way. If you have questions on the code, just ask.

What we are doing is keeping 2 sets of lines and drawings: one for the bar where the daily condition is detected and one for the future, one week ahead.

Text can't be rotated in Pine, so we need to print it one letter per line. The text is printed one bar past the line, but when you zoom in/out, its position will vary relative to the line. Can't do much about that.

```<code>//@version=4
study("TEST nr 032",overlay=true)
fromHour = 00
t1 = timestamp("GMT-4", year, month, dayofmonth, fromHour, 00, 00)
t2 = t1
timeIsOk = (time >= t1) and (time <= t2)

// ————— Calculates the chart's normal time between bars.
f_chartTimeInterval() =>
    var _timeDelta = 10e15
    // Maintain the smallest interbar time value in the dataset, which should correspond to the chart's interval.
    _timeDelta := min(time - nz(time[1]), _timeDelta)

// ————— Calculates a time offset (+/-) which is a multiple of the chart's interval for use with drawing functions.
f_timeAtIntervalMultiple(_mult) =>
    // _mult ("series int"): +/- number of time intervals in the future/past to be calculated.
    int(time + f_chartTimeInterval() * _mult)

// ————— Calculates a +/- time offset from the current bar's time.
f_timeFromBar(_qty, _units) =>
    // _qty   : the +/- number of units of offset required. A "series float" can be used but it will cast to a "series int".
    // _units : string containing one of the 6 allowed time units (the `f_chartTimeUnits()` can be used to supply the current chart's resolution).
    _year   = year        + (_units == "years"   ? int(_qty) : 0)
    _month  = month       + (_units == "months"  ? int(_qty) : 0)
    _day    = dayofmonth  + (_units == "days"    ? int(_qty) : 0)
    _hour   = hour        + (_units == "hours"   ? int(_qty) : 0)
    _minute = minute      + (_units == "minutes" ? int(_qty) : 0)
    _second = second      + (_units == "seconds" ? int(_qty) : 0)
    timestamp(_year, _month, _day, _hour, _minute, _second)

// ————— Draws a text label.
f_drawText(_label, _x, _y, _t, _c) =>
    if na(_label)
        label.new(_x, _y, text = _t, xloc = xloc.bar_time, textcolor = _c, style = label.style_none)
    else
        label.set_xy(_label, _x, _y)
        _label

// ————— Draws a line.
f_drawLine(_line, _x, _c) =>
    if na(_line)
        line.new(_x, low * .9999, _x, high * 1.0001, xloc.bar_time, extend.both, _c, line.style_solid, 1)
    else
        line.set_xy1(_line, _x, low * .9999)
        line.set_xy2(_line, _x, high * 1.0001)
        _line

// ————— Processes one day of lines and labels.
f_doOneDay(_y, _day, _txtColor, _lineColor) =>
    timeInOneWeek = f_timeFromBar(7, "days")
    var line _lineCurrent = f_drawLine(line(na), time, _lineColor)
    var line _lineFuture  = f_drawLine(line(na), time, _lineColor)
    _lineCurrent := f_drawLine(_lineCurrent, time, _lineColor)
    _lineFuture  := f_drawLine(_lineFuture, timeInOneWeek, _lineColor)
    var label _labelCurrent = f_drawText(label(na), time, _y, _day, _txtColor)
    var label _labelFuture  = f_drawText(label(na), time, _y, _day, _txtColor)
    _labelCurrent := f_drawText(_labelCurrent, int(time + f_chartTimeInterval()), _y, _day, _txtColor)
    _labelFuture  := f_drawText(_labelFuture, int(timeInOneWeek + f_chartTimeInterval()), _y, _day, _txtColor)

y         = highest(close, 500)[1]
textColor = color.gray
lineColor = color.blue
txtMon    = "M\no\nn\nd\na\ny"
txtTue    = "T\nu\ne\ns\nd\na\ny"
txtWed    = "W\ne\nd\nn\ne\ns\nd\na\ny"
txtThu    = "T\nh\nu\nr\ns\nd\na\ny"
txtFri    = "F\nr\ni\nd\na\ny"
txtSun    = "S\nu\nn\nd\na\ny"

if timeIsOk and dayofweek == dayofweek.monday
    f_doOneDay(y, txtMon, textColor, lineColor)
else if timeIsOk and dayofweek == dayofweek.tuesday
    f_doOneDay(y, txtTue, textColor, lineColor)
else if timeIsOk and dayofweek == dayofweek.wednesday
    f_doOneDay(y, txtWed, textColor, lineColor)
else if timeIsOk and dayofweek == dayofweek.thursday
    f_doOneDay(y, txtThu, textColor, lineColor)
else if timeIsOk and dayofweek == dayofweek.friday
    f_doOneDay(y, txtFri, textColor, lineColor)

fromHour2 = 18
t3 = timestamp("GMT-4", year, month, dayofmonth, fromHour2, 00, 00)
t4 = t3
timeIsOk2 = (time >= t3) and (time <= t4)

if timeIsOk2 and dayofweek == dayofweek.sunday
    f_doOneDay(y, txtSun, color.red, color.red)
</code>```

Title: Adding new.line in future price?

Body:
I've spent the whole day trying to figure this out.. so here I am.

1.
I want to make a script to plot lines and text like this:
https://gyazo.com/250560130c661044d2c37106b9a367fe

I got the lines for historical price figured out, but for future, I'm starting to think it's not possible with lines? I have tried so much.

2.
Is it possible to put text on vertical line directly in line.new? Or make a label.new and rotate it 90 degrees?

3.
How could I get the texts to be at the same level above/below the bars? Right now I use low[30]

//@version=4
study("TEST nr 032",overlay=true)
fromHour = 00
t1 = timestamp("GMT-4", year, month, dayofmonth, fromHour, 00, 00)
t2 = t1
timeIsOk = (time >= t1) and (time <= t2)

if timeIsOk and dayofweek == dayofweek.monday
    line.new(bar_index, low * .9999, bar_index, high * 1.0001, xloc.bar_index, extend.both, color.blue, line.style_solid, 1)
    var label1 = label.new(bar_index, low[30], text="Monday", style=label.style_none)
    label.set_x(label1, 0)
    label.set_xloc(label1, time, xloc.bar_time)

if timeIsOk and dayofweek == dayofweek.tuesday
    line.new(bar_index, low * .9999, bar_index, high * 1.0001, xloc.bar_index, extend.both, color.blue, line.style_solid, 1)
    var label2 = label.new(bar_index, low[30], text="Tuesday", style=label.style_none)
    label.set_x(label2, 0)
    label.set_xloc(label2, time, xloc.bar_time)

if timeIsOk and dayofweek == dayofweek.wednesday
    line.new(bar_index, low * .9999, bar_index, high * 1.0001, xloc.bar_index, extend.both, color.blue, line.style_solid, 1)
    var label3 = label.new(bar_index, low[30], text="Wednesday", style=label.style_none)
    label.set_x(label3, 0)
    label.set_xloc(label3, time, xloc.bar_time)

if timeIsOk and dayofweek == dayofweek.thursday
    line.new(bar_index, low * .9999, bar_index, high * 1.0001, xloc.bar_index, extend.both, color.blue, line.style_solid, 1)
    var label4 = label.new(bar_index, low[30], text="Tursday", style=label.style_none)
    label.set_x(label4, 0)
    label.set_xloc(label4, time, xloc.bar_time)

if timeIsOk and dayofweek == dayofweek.friday
    line.new(bar_index, low * .9999, bar_index, high * 1.0001, xloc.bar_index, extend.both, color.blue, line.style_solid, 1)
    var label5 = label.new(bar_index, low[30], text="Friday", style=label.style_none)
    label.set_x(label5, 0)
    label.set_xloc(label5, time, xloc.bar_time)

fromHour2 = 18
t3 = timestamp("GMT-4", year, month, dayofmonth, fromHour2, 00, 00)
t4 = t3
timeIsOk2 = (time >= t3) and (time <= t4)

if timeIsOk2 and dayofweek == dayofweek.sunday
    line.new(bar_index, low * .9999, bar_index, high * 1.0001, xloc.bar_index, extend.both, color.red, line.style_solid, 1)
    var label7 = label.new(bar_index, low[30], text="Sunday", style=label.style_none)
    label.set_x(label7, 0)
    label.set_xloc(label7, time, xloc.bar_time)

Thank you so much for your time, I really apperience it.

Body:
This should get you on your way. If you have questions on the code, just ask.

What we are doing is keeping 2 sets of lines and drawings: one for the bar where the daily condition is detected and one for the future, one week ahead.

Text can't be rotated in Pine, so we need to print it one letter per line. The text is printed one bar past the line, but when you zoom in/out, its position will vary relative to the line. Can't do much about that.

//@version=4
study("TEST nr 032",overlay=true)
fromHour = 00
t1 = timestamp("GMT-4", year, month, dayofmonth, fromHour, 00, 00)
t2 = t1
timeIsOk = (time >= t1) and (time <= t2)

// ————— Calculates the chart's normal time between bars.
f_chartTimeInterval() =>
    var _timeDelta = 10e15
    // Maintain the smallest interbar time value in the dataset, which should correspond to the chart's interval.
    _timeDelta := min(time - nz(time[1]), _timeDelta)

// ————— Calculates a time offset (+/-) which is a multiple of the chart's interval for use with drawing functions.
f_timeAtIntervalMultiple(_mult) =>
    // _mult ("series int"): +/- number of time intervals in the future/past to be calculated.
    int(time + f_chartTimeInterval() * _mult)

// ————— Calculates a +/- time offset from the current bar's time.
f_timeFromBar(_qty, _units) =>
    // _qty   : the +/- number of units of offset required. A "series float" can be used but it will cast to a "series int".
    // _units : string containing one of the 6 allowed time units (the `f_chartTimeUnits()` can be used to supply the current chart's resolution).
    _year   = year        + (_units == "years"   ? int(_qty) : 0)
    _month  = month       + (_units == "months"  ? int(_qty) : 0)
    _day    = dayofmonth  + (_units == "days"    ? int(_qty) : 0)
    _hour   = hour        + (_units == "hours"   ? int(_qty) : 0)
    _minute = minute      + (_units == "minutes" ? int(_qty) : 0)
    _second = second      + (_units == "seconds" ? int(_qty) : 0)
    timestamp(_year, _month, _day, _hour, _minute, _second)

// ————— Draws a text label.
f_drawText(_label, _x, _y, _t, _c) =>
    if na(_label)
        label.new(_x, _y, text = _t, xloc = xloc.bar_time, textcolor = _c, style = label.style_none)
    else
        label.set_xy(_label, _x, _y)
        _label

// ————— Draws a line.
f_drawLine(_line, _x, _c) =>
    if na(_line)
        line.new(_x, low * .9999, _x, high * 1.0001, xloc.bar_time, extend.both, _c, line.style_solid, 1)
    else
        line.set_xy1(_line, _x, low * .9999)
        line.set_xy2(_line, _x, high * 1.0001)
        _line

// ————— Processes one day of lines and labels.
f_doOneDay(_y, _day, _txtColor, _lineColor) =>
    timeInOneWeek = f_timeFromBar(7, "days")
    var line _lineCurrent = f_drawLine(line(na), time, _lineColor)
    var line _lineFuture  = f_drawLine(line(na), time, _lineColor)
    _lineCurrent := f_drawLine(_lineCurrent, time, _lineColor)
    _lineFuture  := f_drawLine(_lineFuture, timeInOneWeek, _lineColor)
    var label _labelCurrent = f_drawText(label(na), time, _y, _day, _txtColor)
    var label _labelFuture  = f_drawText(label(na), time, _y, _day, _txtColor)
    _labelCurrent := f_drawText(_labelCurrent, int(time + f_chartTimeInterval()), _y, _day, _txtColor)
    _labelFuture  := f_drawText(_labelFuture, int(timeInOneWeek + f_chartTimeInterval()), _y, _day, _txtColor)

y         = highest(close, 500)[1]
textColor = color.gray
lineColor = color.blue
txtMon    = "M\no\nn\nd\na\ny"
txtTue    = "T\nu\ne\ns\nd\na\ny"
txtWed    = "W\ne\nd\nn\ne\ns\nd\na\ny"
txtThu    = "T\nh\nu\nr\ns\nd\na\ny"
txtFri    = "F\nr\ni\nd\na\ny"
txtSun    = "S\nu\nn\nd\na\ny"

if timeIsOk and dayofweek == dayofweek.monday
    f_doOneDay(y, txtMon, textColor, lineColor)
else if timeIsOk and dayofweek == dayofweek.tuesday
    f_doOneDay(y, txtTue, textColor, lineColor)
else if timeIsOk and dayofweek == dayofweek.wednesday
    f_doOneDay(y, txtWed, textColor, lineColor)
else if timeIsOk and dayofweek == dayofweek.thursday
    f_doOneDay(y, txtThu, textColor, lineColor)
else if timeIsOk and dayofweek == dayofweek.friday
    f_doOneDay(y, txtFri, textColor, lineColor)

fromHour2 = 18
t3 = timestamp("GMT-4", year, month, dayofmonth, fromHour2, 00, 00)
t4 = t3
timeIsOk2 = (time >= t3) and (time <= t4)

if timeIsOk2 and dayofweek == dayofweek.sunday
    f_doOneDay(y, txtSun, color.red, color.red)


问:
Why doesn't Chrome recognize my progressive web app?
I made a progressive web app with a nodejs backend. When I deploy it on my server, chrome does not recognize the app as a PWA. All other browsers do (firefox, opera...). This means I don't get the "download" prompt or the full screen view of my app.

It was working perfectly when it was deployed on heroku. I bought hosting and now it doesn't work. The main difference is that the app now runs on port 8443 because port 433 is used by a webserver. I looked on google and found that chrome only recognizes PWAs if they run on port 433. I asked the helpdesk and they told me to use a .htaccess file. I have not worked with one before and it does not seem to fix my problem. It automatically redirects to port 8443 but Chrome still does not recognize it as a PWA. This is the .htaccess I use:

```<code>SetEnvIf Request_URI "^(.*)" PORT=8443

RewriteEngine On
RewriteBase /

# CORS
Header add Access-Control-Allow-Origin "*"

# HTTPS
RewriteCond %{HTTPS} !=on
RewriteCond %{ENV:HTTPS} !=on
RewriteRule ^(.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# PORT
RewriteCond %{SERVER_PORT} !^%{ENV:PORT}$
RewriteRule ^(.*) https://%{HTTP_HOST}:%{ENV:PORT}%{REQUEST_URI} [L,R=301]

# RPROXY
# RewriteRule ^(.*) http://localhost:${ENV:PORT}/$1 [P]
</code>```

I was wondering if the problem really occurs because the app runs on 8443 or if there is something else I don't know.

thanks!

答: I haven't tested this, but maybe using vhost and reverse proxy, so you can still serve your app on port 433 but reverse proxy the requests to your node server running on a different port.</p>

Body:
I made a progressive web app with a nodejs backend. When I deploy it on my server, chrome does not recognize the app as a PWA. All other browsers do (firefox, opera...). This means I don't get the "download" prompt or the full screen view of my app.

It was working perfectly when it was deployed on heroku. I bought hosting and now it doesn't work. The main difference is that the app now runs on port 8443 because port 433 is used by a webserver. I looked on google and found that chrome only recognizes PWAs if they run on port 433. I asked the helpdesk and they told me to use a .htaccess file. I have not worked with one before and it does not seem to fix my problem. It automatically redirects to port 8443 but Chrome still does not recognize it as a PWA. This is the .htaccess I use:

SetEnvIf Request_URI "^(.*)" PORT=8443

RewriteEngine On
RewriteBase /

# CORS
Header add Access-Control-Allow-Origin "*"

# HTTPS
RewriteCond %{HTTPS} !=on
RewriteCond %{ENV:HTTPS} !=on
RewriteRule ^(.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# PORT
RewriteCond %{SERVER_PORT} !^%{ENV:PORT}$
RewriteRule ^(.*) https://%{HTTP_HOST}:%{ENV:PORT}%{REQUEST_URI} [L,R=301]

# RPROXY
# RewriteRule ^(.*) http://localhost:${ENV:PORT}/$1 [P]

I was wondering if the problem really occurs because the app runs on 8443 or if there is something else I don't know.

thanks!


问:
Is it possible to use Mockito in Kotlin?
The problem I'm facing is that Matchers.anyObject() returns null. When used to mock method that only accepts non-nullable types it causes a "Should not be null" exception to be thrown.

```<code>`when`(mockedBackend.login(anyObject())).thenAnswer { invocationOnMock -> someResponse }
</code>```

Mocked method:

```<code>public open fun login(userCredentials: UserCredentials): Response
</code>```

答:
it just need to return a nonnull result when you use Mockito.any();

```<code>Mockito.any() ?: 0
Mockito.any() ?: HashMap<Int,Int>()
Mockito.any() ?: {}
</code>```

...

Body:
The problem I'm facing is that Matchers.anyObject() returns null. When used to mock method that only accepts non-nullable types it causes a "Should not be null" exception to be thrown.

`when`(mockedBackend.login(anyObject())).thenAnswer { invocationOnMock -> someResponse }

Mocked method:

public open fun login(userCredentials: UserCredentials): Response

Body:
it just need to return a nonnull result when you use Mockito.any();

Mockito.any() ?: 0
Mockito.any() ?: HashMap<Int,Int>()
Mockito.any() ?: {}

...


问:
How do I solve this Javascript/CSS problem?
I want the smaller div box to show up in the larger div.

However, when I drag and drop it, this is what it looks like:

Why isn't the small box's border properly showing in the larger box? I have modified the drop function so that it copies the 2nd div instead of dropping it.

```<code><html>
    <head>
        <script>
            function remove(id){
                //var el = document.getElementById("r1").outerHTML = "";
                var element = document.getElementById(id);
                element.parentNode.parentNode.removeChild(element.parentNode);
                console.log('Removed')
            }

            function allowDrop(ev) {
                ev.preventDefault();
            }

            function drag(ev) {
                ev.dataTransfer.setData("text", ev.target.id);
            }

            function drop(ev) {
                ev.preventDefault();
                var data = ev.dataTransfer.getData("text");
                var nodeCopy = document.getElementById(data).cloneNode(true);
                nodeCopy.id = 'something';
                ev.target.appendChild(nodeCopy);
            }
        </script>
    </head>
    <body>
        <p>Drag the W3Schools image into the rectangle:</p>
        <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
        <br>
        <div id = "drag1" draggable="true" ondragstart="drag(event)" height="50px" width="50px">
            <span id="yo" class="fa fa-close cross" onclick="remove(this.id);"></span>
        </div>
    </body>
</html>
</code>```

答:
height="50px" width="50px" doesn't work with the div. It is specific to few tags.

You can set the styles in the following ways for div.

Add CSS styling with class. (Preferred solution)

Add In-line styling for the div, like this. style="width: 100px"

Added the code snippet for your reference.

function remove(id){
    //var el = document.getElementById("r1").outerHTML = "";
    var element = document.getElementById(id);
    element.parentNode.parentNode.removeChild(element.parentNode);
    console.log('Removed')
}

function allowDrop(ev) {
    ev.preventDefault();
}

function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    var nodeCopy = document.getElementById(data).cloneNode(true);
    nodeCopy.id = 'something';
    ev.target.appendChild(nodeCopy);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box{
    border: 1px solid black;
}

.big{
    width: 120px;
    height: 50px;
}

.small{
    width: 80px;
    height: 30px;
}</code>```

Drag the W3Schools image into the rectangle:

    x

    ```

Body:
I want the smaller div box to show up in the larger div.

However, when I drag and drop it, this is what it looks like:

Why isn't the small box's border properly showing in the larger box? I have modified the drop function so that it copies the 2nd div instead of dropping it.

Drag the W3Schools image into the rectangle:

Body:
height="50px" width="50px" doesn't work with the div. It is specific to few tags.

You can set the styles in the following ways for div.

Add CSS styling with class. (Preferred solution)

Add In-line styling for the div, like this. style="width: 100px"

Added the code snippet for your reference.

function remove(id){
    //var el = document.getElementById("r1").outerHTML = "";
    var element = document.getElementById(id);
    element.parentNode.parentNode.removeChild(element.parentNode);
    console.log('Removed')
}

function allowDrop(ev) {
    ev.preventDefault();
}

function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    var nodeCopy = document.getElementById(data).cloneNode(true);
    nodeCopy.id = 'something';
    ev.target.appendChild(nodeCopy);
}

.box{
    border: 1px solid black;
}

.big{
    width: 120px;
    height: 50px;
}

.small{
    width: 80px;
    height: 30px;
}

<p>Drag the W3Schools image into the rectangle:</p>

<div id="div1" class="big box" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br>
<div id="drag1" class="small box" draggable="true" ondragstart="drag(event)">
    <span id="yo" class="" onclick="remove(this.id);">x</span>
</div>


问:
I can't edit a memory address in C
I don't really know how to phrase the title, what I want is to edit the string in one pointer from another overlapping pointer.

What I want to obtain in this code what  is 1abcd abcd but what I get instead is 123 abcd

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

int main() {

    char* x = (char*)malloc(4);
    x = "123";
    char*  y = (char*) x+1;
    y = "abcd";
    printf("%s %s",x,y);

}
</code>```

答:
The issue is that you assign to y, then you assign to y again.

```<code>char *y = x+1;  // first assignment
y = "abcd";              // second assignment
</code>```

y = "abcd"; isn't a copy. It's assigning a pointer to the const char[5] string abcd to y.

Similar problem here.

```<code>char *x = malloc(4);
x = "123";
</code>```

x is first assigned to the memory from malloc, but then overwritten by the const char[4] 123. The malloc memory is leaked.

If you want to copy into the memory pointed to by x you need to use strcpy. However, x only has 4 bytes. You'll need more.

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

int main() {
    // Allocate memory
    char *x = malloc(6);

    // Copy "123" the heap memory pointed to by x.
    strcpy(x, "123");

    // Assign a pointer to x+1 to y.
    char *y = x+1;

    // Copy "abcd" to the heap memory pointed to by y.
    strcpy(y, "abcd");

    // x='1abcd' y='abcd'
    printf("x='%s' y='%s'\n",x,y);
}
</code>```

Note that strcpy is not safe to use when the length of the source and destination strings are not known.

Title: I can't edit a memory address in C

Body:
I don't really know how to phrase the title, what I want is to edit the string in one pointer from another overlapping pointer.

What I want to obtain in this code what  is 1abcd abcd but what I get instead is 123 abcd

#include <stdio.h>

int main() {

    char* x = (char*)malloc(4);
    x = "123";
    char*  y = (char*) x+1;
    y = "abcd";
    printf("%s %s",x,y);

}

Body:
The issue is that you assign to y, then you assign to y again.

char *y = x+1;  // first assignment
y = "abcd";              // second assignment

y = "abcd"; isn't a copy. It's assigning a pointer to the const char[5] string abcd to y.

Similar problem here.

char *x = malloc(4);
x = "123";

x is first assigned to the memory from malloc, but then overwritten by the const char[4] 123. The malloc memory is leaked.

If you want to copy into the memory pointed to by x you need to use strcpy. However, x only has 4 bytes. You'll need more.

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

int main() {
    // Allocate memory
    char *x = malloc(6);

    // Copy "123" the heap memory pointed to by x.
    strcpy(x, "123");

    // Assign a pointer to x+1 to y.
    char *y = x+1;

    // Copy "abcd" to the heap memory pointed to by y.
    strcpy(y, "abcd");

    // x='1abcd' y='abcd'
    printf("x='%s' y='%s'\n",x,y);
}

Note that strcpy is not safe to use when the length of the source and destination strings are not known.


问:
Verifying that the user inputs and integer C++
My C++ program needs to ask the user to input two values. In order to avoid non-integer values, I wanted to create a loop like this:

```<code>#include <iostream>
using namespace std;

int main(){
     int x,y;

     while ((typeof(x)!=int){
         cin>>x;
         cin>>y;
     }
     return 0;
}
</code>```

However, it does not work. Does anyone know how to do it?

答:
You can't evaluate any datatype directly as an expression.

Use std::cin.good() (returns boolean) for verification if the number(s) entered were integer.

```<code>int val1, val2;

std::cout << "Input two integers: ";
std::cin >> val1 >> val2;

while (!std::cin.good()) {
    std::cin.clear();
    std::cin.ignore(INT_MAX, '\n');

    std::cout << "Incorrect! Input two integers: ";
    std::cin >> val1 >> val2;
}

std::cout << val1 << ' ' << val2;
</code>```

Sample Output

```<code>Input two integers: 33 h
Incorrect! Input two integers: l h
Incorrect! Input two integers: 1 2
1 2
</code>```

Body:
My C++ program needs to ask the user to input two values. In order to avoid non-integer values, I wanted to create a loop like this:

#include <iostream>
using namespace std;

int main(){
     int x,y;

     while ((typeof(x)!=int){
         cin>>x;
         cin>>y;
     }
     return 0;
}

However, it does not work. Does anyone know how to do it?

Body:
You can't evaluate any datatype directly as an expression.

Use std::cin.good() (returns boolean) for verification if the number(s) entered were integer.

int val1, val2;

std::cout << "Input two integers: ";
std::cin >> val1 >> val2;

while (!std::cin.good()) {
    std::cin.clear();
    std::cin.ignore(INT_MAX, '\n');

    std::cout << "Incorrect! Input two integers: ";
    std::cin >> val1 >> val2;
}

std::cout << val1 << ' ' << val2;

Sample Output

Input two integers: 33 h
Incorrect! Input two integers: l h
Incorrect! Input two integers: 1 2
1 2


问:
Gracefully stopping an std::thread?
I have a worker std::thread and I want its main loop to check if some other thread tells it to stop looping and exit.

What is a good cross platform way to do this? Does boost provide some event object for it?

Is using just a bool considered thread-safe?

答: std::mutex and it's relatives are the core mechanisms.  std::lock_guard and unique_lock build on this, and std::condition_variable are good for this purpose.</p>

Title: Gracefully stopping an std::thread?


问:
Empty EditText value displayed in AlertDialog
I am new in Android development and I got a problem. I have 2 EditText fields of login and password and 1 Button. When I click on the Button, I am getting AlertDialog with message "Logged in as " but I need it to be "Logged in as *value entered into "login" EditText".
The EditText value is always empty. It's just a simple implementation, but it doesn't work.
What am I doing wrong here?

Here is the code:

```<code>public class FirstFragment extends Fragment {
    EditText loginText;
    EditText passwText;
    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {
        View view2 = inflater.inflate(R.layout.fragment_first, null, false);

        loginText = (EditText)view2.findViewById(R.id.loginText);
        passwText = (EditText)view2.findViewById(R.id.passText);
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first, container, false);
    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        view.findViewById(R.id.button_first).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick( View view) {
                handleLoginDialog();
            }
        });
    }

    private void handleLoginDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        //View view2 = getLayoutInflater().inflate(R.layout.fragment_first, null, false);

        String st = loginText.getText().toString();

        if (loginText != null && passwText != null){
            builder.setMessage("Logged in as " + st);
        }
        else
            builder.setMessage("Login or password was not entered!" );
        builder.show();
    }
}
</code>```

答:
I want to start the answer with what you did:

You inflated 2 same layouts as :

View view2 = inflater.inflate(R.layout.fragment_first, null, false);

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

Let's call this second inflation as view1 which is the original view that was inflated for the Fragment and also is the one that is returned in the onViewCreated() method.

Then, you set the set the onClickListener for button_first of view1.

Then, inside the handleDialogLogin() method, you try to get the text value of EditText fields that you created with view2 object.

That's where it went wrong. Because, during app usage, you insert the text in EditText fields of view1 but you are asking for text value of EditText fields of view2 which will obviously be empty.

The correct and clean approach is here :

```<code>public class FirstFragment extends Fragment {
    EditText loginText;
    EditText passwText;
    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {
        // just inflate the layout for this fragment as it is not correct
        // place for declaring and initializing views
        return inflater.inflate(R.layout.fragment_first, container, false);
    }

    // this is the best place for declaring and initializing views
    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // declare and initialize your EditText here
        loginText = (EditText)view.findViewById(R.id.loginText);
        passwText = (EditText)view.findViewById(R.id.passText);
        view.findViewById(R.id.button_first).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick( View view) {
                handleLoginDialog();
            }
        });
    }

    private void handleLoginDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());

        String st = loginText.getText().toString().trim();
        String pt = passText.getText().toString().trim();

        if (st.isEmpty() && pt.isEmpty())
           builder.setMessage("Login or password was not entered!" );
        else
           builder.setMessage("Logged in as " + st);
        builder.show();
    }
}
</code>```

Body:
I am new in Android development and I got a problem. I have 2 EditText fields of login and password and 1 Button. When I click on the Button, I am getting AlertDialog with message "Logged in as " but I need it to be "Logged in as *value entered into "login" EditText".
The EditText value is always empty. It's just a simple implementation, but it doesn't work.
What am I doing wrong here?

Here is the code:

public class FirstFragment extends Fragment {
    EditText loginText;
    EditText passwText;
    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {
        View view2 = inflater.inflate(R.layout.fragment_first, null, false);

        loginText = (EditText)view2.findViewById(R.id.loginText);
        passwText = (EditText)view2.findViewById(R.id.passText);
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first, container, false);
    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        view.findViewById(R.id.button_first).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick( View view) {
                handleLoginDialog();
            }
        });
    }

    private void handleLoginDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        //View view2 = getLayoutInflater().inflate(R.layout.fragment_first, null, false);

        String st = loginText.getText().toString();

        if (loginText != null && passwText != null){
            builder.setMessage("Logged in as " + st);
        }
        else
            builder.setMessage("Login or password was not entered!" );
        builder.show();
    }
}

Body:
I want to start the answer with what you did:

You inflated 2 same layouts as :

View view2 = inflater.inflate(R.layout.fragment_first, null, false);

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

Let's call this second inflation as view1 which is the original view that was inflated for the Fragment and also is the one that is returned in the onViewCreated() method.

Then, you set the set the onClickListener for button_first of view1.

Then, inside the handleDialogLogin() method, you try to get the text value of EditText fields that you created with view2 object.

That's where it went wrong. Because, during app usage, you insert the text in EditText fields of view1 but you are asking for text value of EditText fields of view2 which will obviously be empty.

The correct and clean approach is here :

public class FirstFragment extends Fragment {
    EditText loginText;
    EditText passwText;
    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {
        // just inflate the layout for this fragment as it is not correct
        // place for declaring and initializing views
        return inflater.inflate(R.layout.fragment_first, container, false);
    }

    // this is the best place for declaring and initializing views
    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // declare and initialize your EditText here
        loginText = (EditText)view.findViewById(R.id.loginText);
        passwText = (EditText)view.findViewById(R.id.passText);
        view.findViewById(R.id.button_first).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick( View view) {
                handleLoginDialog();
            }
        });
    }

    private void handleLoginDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());

        String st = loginText.getText().toString().trim();
        String pt = passText.getText().toString().trim();

        if (st.isEmpty() && pt.isEmpty())
           builder.setMessage("Login or password was not entered!" );
        else
           builder.setMessage("Logged in as " + st);
        builder.show();
    }
}