问:
Python 3: How to generate a table from a nested list as input
So, I've got the following nested list (which I've parsed from an Nmap XML output file). It's basically a list of IP addresses, and all their open ports:

```<code>[['192.168.23.78', ['53', '88', '135', '139', '389', '445', '3389']],
 ['192.168.27.243', ['135', '139', '445', '3389', '5800', '5900']],
 ['192.168.99.164', ['135', '139', '445', '3389', '5800', '5900']],
 ['192.168.228.211', ['80']],
 ['192.168.171.74', ['135', '139', '445', '3389', '5800', '5900']]]
</code>```

I would like to create a table from this data, where each first item (all IP addresses) are printed as rows. I then wish to iterate over each second item (a list of all ports per IP address), and count each unique port number. I wish this new counted unique list of ports to be printed as column headers of my table. My empty table should then roughly look like this:

```<code>                 53  80  88  135  139  389  445  3389  5800  5900
192.168.23.78
192.168.27.243
192.168.99.164
192.168.228.211
192.168.171.74
</code>```

And then I wish to place X's in each correct cell for each IP address that has a given open port, like so:

```<code>                 53  80  88  135  139  389  445  3389  5800  5900
192.168.23.78    X   X       X    X    X         X
192.168.27.243               X    X         X    X     X     X
192.168.99.164               X    X         X    X     X     X
192.168.228.211      X
192.168.171.74               X    X         X    X     X     X
</code>```

How would I do this with my data set?

I'm a total newbie, but I could likely figure out how to iterate over all the port numbers and get a unique port list. But I have absolutely not clue how to then plot X's on the table, in the correct cells

This is my code so far:

#!/usr/bin/env python

from pprint import pprint
import xml.etree.ElementTree as ET

def loopy(item):
    for port in host.findall('ports/port'):
        if port.get('protocol') == "tcp":
            portid = port.get('portid')
            for state in port.findall('state'):
                if state.get('state') == "open":
                    if item == "address":
                        list_addr.append(addr)
                        return
                    elif item == "portid":
                        list_portid.append(portid)

root = ET.parse('scan5.xml').getroot()
result = []
for host in root.findall('host'):
    list_portid = []
    list_addr = []
    address = host.find('address')
    addr = address.get('addr')
    loopy("address")
    loopy("portid")
    if list_addr:
        result.append([list_addr[0], list_portid])

pprint(result)
```

<p>My nested list is in now <code>result</code>, but I have no clue how to create a table from this.</p>

<p>So far my code only produces the raw list:</p>

```[['10.133.23.78', ['53', '88', '135', '139', '389', '445', '3389']],
 ['10.133.27.243', ['135', '139', '445', '3389', '5800', '5900']],
 ['10.133.99.164', ['135', '139', '445', '3389', '5800', '5900']],
 ['10.135.228.211', ['80']],
 ['10.133.171.74', ['135', '139', '445', '3389', '5800', '5900']]]
```

Body:
So, I've got the following nested list (which I've parsed from an Nmap XML output file). It's basically a list of IP addresses, and all their open ports:

[['192.168.23.78', ['53', '88', '135', '139', '389', '445', '3389']],
 ['192.168.27.243', ['135', '139', '445', '3389', '5800', '5900']],
 ['192.168.99.164', ['135', '139', '445', '3389', '5800', '5900']],
 ['192.168.228.211', ['80']],
 ['192.168.171.74', ['135', '139', '445', '3389', '5800', '5900']]]

I would like to create a table from this data, where each first item (all IP addresses) are printed as rows. I then wish to iterate over each second item (a list of all ports per IP address), and count each unique port number. I wish this new counted unique list of ports to be printed as column headers of my table. My empty table should then roughly look like this:

                 53  80  88  135  139  389  445  3389  5800  5900
192.168.23.78
192.168.27.243
192.168.99.164
192.168.228.211
192.168.171.74

And then I wish to place X's in each correct cell for each IP address that has a given open port, like so:

                 53  80  88  135  139  389  445  3389  5800  5900
192.168.23.78    X   X       X    X    X         X
192.168.27.243               X    X         X    X     X     X
192.168.99.164               X    X         X    X     X     X
192.168.228.211      X
192.168.171.74               X    X         X    X     X     X

How would I do this with my data set?

I'm a total newbie, but I could likely figure out how to iterate over all the port numbers and get a unique port list. But I have absolutely not clue how to then plot X's on the table, in the correct cells

This is my code so far:

#!/usr/bin/env python

from pprint import pprint
import xml.etree.ElementTree as ET

def loopy(item):
    for port in host.findall('ports/port'):
        if port.get('protocol') == "tcp":
            portid = port.get('portid')
            for state in port.findall('state'):
                if state.get('state') == "open":
                    if item == "address":
                        list_addr.append(addr)
                        return
                    elif item == "portid":
                        list_portid.append(portid)

root = ET.parse('scan5.xml').getroot()
result = []
for host in root.findall('host'):
    list_portid = []
    list_addr = []
    address = host.find('address')
    addr = address.get('addr')
    loopy("address")
    loopy("portid")
    if list_addr:
        result.append([list_addr[0], list_portid])

pprint(result)

My nested list is in now result, but I have no clue how to create a table from this.

So far my code only produces the raw list:

[['10.133.23.78', ['53', '88', '135', '139', '389', '445', '3389']],
 ['10.133.27.243', ['135', '139', '445', '3389', '5800', '5900']],
 ['10.133.99.164', ['135', '139', '445', '3389', '5800', '5900']],
 ['10.135.228.211', ['80']],
 ['10.133.171.74', ['135', '139', '445', '3389', '5800', '5900']]]

Body:
you can use install and use prettytable package to visualise pretty table

first pip install prettytable

then code

from prettytable import PrettyTable

data = [['192.168.23.78', ['53', '88', '135', '139', '389', '445', '3389']],
        ['192.168.27.243', ['135', '139', '445', '3389', '5800', '5900']],
        ['192.168.99.164', ['135', '139', '445', '3389', '5800', '5900']],
        ['192.168.228.211', ['80']],
        ['192.168.171.74', ['135', '139', '445', '3389', '5800', '5900']]]

ports = sorted(set([int(port) for _, open_ports in data for port in open_ports]))

my_table = PrettyTable()
header = ['ip']
header.extend(ports)
my_table.field_names = header
for ip_address, open_ports in data:
    row = [ip_address]
    row.extend('X' if str(port) in open_ports else '' for port in ports)
    my_table.add_row(row)

print(my_table)

output

+-----------------+----+----+----+-----+-----+-----+-----+------+------+------+
|        ip       | 53 | 80 | 88 | 135 | 139 | 389 | 445 | 3389 | 5800 | 5900 |
+-----------------+----+----+----+-----+-----+-----+-----+------+------+------+
|  192.168.23.78  | X  |    | X  |  X  |  X  |  X  |  X  |  X   |      |      |
|  192.168.27.243 |    |    |    |  X  |  X  |     |  X  |  X   |  X   |  X   |
|  192.168.99.164 |    |    |    |  X  |  X  |     |  X  |  X   |  X   |  X   |
| 192.168.228.211 |    | X  |    |     |     |     |     |      |      |      |
|  192.168.171.74 |    |    |    |  X  |  X  |     |  X  |  X   |  X   |  X   |
+-----------------+----+----+----+-----+-----+-----+-----+------+------+------+


来源: stackexchange

问:
Is it possible to access Microsoft Dynamics NAV Web service from NodeJS?
I am using node-soap lib to create a soap client.
On NAV side,
Credential Type is Windows. When I am trying to access NAV Soap Web Service from NodeJS, It is giving me Error:401 (Access Denied).
Here is the code what I am using in my application.

```<code>var soap = require("soap");
var url = "http://<url>"; // This is accessible from browser.

soap.createClient(url, function (err, client) {
        if (err) { console.log(err); }
        else {
            console.log(client.describe());
        }
    });
</code>```

答:
So I just went through this to integrate between our ERP software and NAV (actually known as Dynamics365 Business Central now) and figure I'll leave what I've done here to help people. So just FYI, I did this on NAV 14.0.

var soap = require('soap');
var url = 'http://localhost:7047/{INSTANCE}/WS/{COMPANY}/Codeunit/{CODEUNITNAME}';

var security = new soap['NTLMSecurity']({
  username: NAVUSERNAME,
  password: NAVUSERPASSWORD,
  domain: DOMAIN',
  negotiate: true
});

const wsdl_headers = {}, wsdl_options = {};
security.addHeaders(wsdl_headers);
security.addOptions(wsdl_options);

return soap.createClientAsync(url, { wsdl_headers, wsdl_options })
.then(
  (client) => {
    client.setSecurity(security)
    return client;
  }
).then((client) => {
  return client.FunctionNameAsync({params});
})```

This will authenticate both the wsdl request and the SOAP service you are trying to access. When I first tried this, I got the error Couldn't find NTLM in the message type2 comming from the server. This was because my installation of NAV had NTLM authentication OFF by default. I have no idea what authentication method it was expecting with this off. You can enable this through the server manager:

After that restart the instance and your authentication will hopefully work. Hope this helps someone else.

ContentLicense: CC BY-SA 3.0

Body:
I am using node-soap lib to create a soap client.
On NAV side,
Credential Type is Windows. When I am trying to access NAV Soap Web Service from NodeJS, It is giving me Error:401 (Access Denied).
Here is the code what I am using in my application.

var soap = require("soap");
var url = "http://<url>"; // This is accessible from browser.

soap.createClient(url, function (err, client) {
        if (err) { console.log(err); }
        else {
            console.log(client.describe());
        }
    });

Body:
So I just went through this to integrate between our ERP software and NAV (actually known as Dynamics365 Business Central now) and figure I'll leave what I've done here to help people. So just FYI, I did this on NAV 14.0.

var soap = require('soap');
var url = 'http://localhost:7047/{INSTANCE}/WS/{COMPANY}/Codeunit/{CODEUNITNAME}';

var security = new soap['NTLMSecurity']({
  username: NAVUSERNAME,
  password: NAVUSERPASSWORD,
  domain: DOMAIN',
  negotiate: true
});

const wsdl_headers = {}, wsdl_options = {};
security.addHeaders(wsdl_headers);
security.addOptions(wsdl_options);

return soap.createClientAsync(url, { wsdl_headers, wsdl_options })
.then(
  (client) => {
    client.setSecurity(security)
    return client;
  }
).then((client) => {
  return client.FunctionNameAsync({params});
})

This will authenticate both the wsdl request and the SOAP service you are trying to access. When I first tried this, I got the error Couldn't find NTLM in the message type2 comming from the server. This was because my installation of NAV had NTLM authentication OFF by default. I have no idea what authentication method it was expecting with this off. You can enable this through the server manager:

After that restart the instance and your authentication will hopefully work. Hope this helps someone else.

ContentLicense: CC BY-SA 4.0


问:
How to extract text from large text
I have Data which is in this format in FILE1.txt

```<code>@E/f1/w/ @H/abc/w/ @demo/file/wk/Fil0.fk
@E/f2/w/ @H/cdv/w/ @demo/file/wk/Fil1.fk
@E/f3/w/ @H/efg/w/ @demo/file/wk/Fil2.fk
@E/f4/w/ @H/mno/w/ @demo/file/wk/Fil3.fk
@E/f5/w/ @H/pqr/w/ @demo/file/wk/Fil4.fk
</code>```

I want to Print data to a File .... FILE2.txt in this Below Format

```<code>Fil0.fk
Fil1.fk
Fil2.fk
Fil3.fk
Fil4.fk
</code>```

答:
Welcome to StackOverflow.

I Assuming that you want to save the first and second columns in new files.

You have to create a bash like bellow in the path where the FILE1.txt exists, change it to an executable file with chmod +x <bash_file_name> command and run it by ./<bash_file_name>

```<code>#!/bin/bash

input="FILE1.txt"
while IFS= read -r line
do
    # Extract file name
    filename=`echo "$line" | awk '{print $3}' | cut -d'/' -f4`

    # Extract data
    clumnOne=`echo "$line" | awk '{print $1}'`
    clumnTwo=`echo "$line" | awk '{print $2}'`

    # Write to file
    echo "$clumnOne $clumnTwo" >> $filename
done < "$input"
</code>```

Title: How to extract text from large text

Body:
I have Data which is in this format in FILE1.txt

@E/f1/w/ @H/abc/w/ @demo/file/wk/Fil0.fk
@E/f2/w/ @H/cdv/w/ @demo/file/wk/Fil1.fk
@E/f3/w/ @H/efg/w/ @demo/file/wk/Fil2.fk
@E/f4/w/ @H/mno/w/ @demo/file/wk/Fil3.fk
@E/f5/w/ @H/pqr/w/ @demo/file/wk/Fil4.fk

I want to Print data to a File .... FILE2.txt in this Below Format

Fil0.fk
Fil1.fk
Fil2.fk
Fil3.fk
Fil4.fk

Body:
Welcome to StackOverflow.

I Assuming that you want to save the first and second columns in new files.

You have to create a bash like bellow in the path where the FILE1.txt exists, change it to an executable file with chmod +x <bash_file_name> command and run it by ./<bash_file_name>

#!/bin/bash

input="FILE1.txt"
while IFS= read -r line
do
    # Extract file name
    filename=`echo "$line" | awk '{print $3}' | cut -d'/' -f4`

    # Extract data
    clumnOne=`echo "$line" | awk '{print $1}'`
    clumnTwo=`echo "$line" | awk '{print $2}'`

    # Write to file
    echo "$clumnOne $clumnTwo" >> $filename
done < "$input"


问:
Having an anchor tag within an HTML button tag
I have an anchor tag  within a button tag description in HTML as below:

```<code><button type="submit" onClick="handleSubmit()">Desc....
   <a href="https://......." target="_blank">Click here for more details</a>
</button>
</code>```

Now when I click on the anchor text, the action "handleSubmit()" executes instead of going to my https:// link.So apparently, my  text is also being treated as a button instead of a hyperlink.

I tried adding the z-index property to my CSS for (z-index: 1) in order to make it independently clickable so it overlays on top of the button tag, but no joy!

But if I right-click on the  text, I do see the option of opening the https link in a new tab and it does so perfectly. Only when I click on it normally(left click), the button click handler executes as if its the button being clicked instead of the anchor tag.

How can I fix this? Any help would be much appreciated, thank you.

答:
I don't quite understand if you intend to use the function inside the onClick in any situation.
You can swap the wrapping of elements so that the button is inside the link; also you could move the link inside the onClick like this:

```<code>onClick="window.location.href='link'"
</code>```

Thought these can be a couple solutions, you need to clarify the exact behaviour you expect to obtain from your code.

Body:
I have an anchor tag  within a button tag description in HTML as below:

<button type="submit" onClick="handleSubmit()">Desc....
   Click here for more details
</button>

Now when I click on the anchor text, the action "handleSubmit()" executes instead of going to my https:// link.So apparently, my  text is also being treated as a button instead of a hyperlink.

I tried adding the z-index property to my CSS for (z-index: 1) in order to make it independently clickable so it overlays on top of the button tag, but no joy!

But if I right-click on the  text, I do see the option of opening the https link in a new tab and it does so perfectly. Only when I click on it normally(left click), the button click handler executes as if its the button being clicked instead of the anchor tag.

How can I fix this? Any help would be much appreciated, thank you.

Body:
I don't quite understand if you intend to use the function inside the onClick in any situation.
You can swap the wrapping of elements so that the button is inside the link; also you could move the link inside the onClick like this:

onClick="window.location.href='link'"

Thought these can be a couple solutions, you need to clarify the exact behaviour you expect to obtain from your code.


问:
Load Angular Material before own styles
We have an Angular project, with Material and we're having some issues with overriding styles.

For example, if we want to change the border-radius globally on <mat-card>, we currently need to add important to the styles:

```<code>.mat-card { border-radius: $some-var !important; }
</code>```

This seems to me to be caused by the material styles loading after our own custom styles. At least according to "traditional" CSS standards. So usually you could just change the load order around, and the last loaded styles would overwrite the previous.

Is there a way to achieve this? Or how are we supposed to style these kinds of elements, without adding !important all over?

答:
You are not really supposed to "style these kinds of elements" - that's not what Angular Material is about. But some customization can be done - and a guide is available: https://v6.material.angular.io/guide/customizing-component-styles.

You especially need to understand how style is encapsulated and dynamically applied. You can control when the global Angular Material style sheet is loaded in the "traditional" way, but you cannot control when all component style is applied because some of it is dynamic. If you hope to completely restyle everything - you should probably consider a different library as it is not always merely a matter of redefining class properties.

Title: Load Angular Material before own styles

Body:
We have an Angular project, with Material and we're having some issues with overriding styles.

For example, if we want to change the border-radius globally on <mat-card>, we currently need to add important to the styles:

.mat-card { border-radius: $some-var !important; }

This seems to me to be caused by the material styles loading after our own custom styles. At least according to "traditional" CSS standards. So usually you could just change the load order around, and the last loaded styles would overwrite the previous.

Is there a way to achieve this? Or how are we supposed to style these kinds of elements, without adding !important all over?


问:
How to return total number of records with TOP * select
I have over 300 000 rows, I would like to return total number of the records even if I pick only 20/50/100 records using TOP * statement.

Is it possible to filter select like

select top 50 * from table where rule1=rule1 and rule=rule2

Let's say that total number of records if database is 300 000 and select above would return 4 000 records. But physically it will return only 50 records, I need to know how manu is there in database using this where statement (it would return 4000).

Thanks

答: There are a lot of simple answers to this question, as other posters have pointed out.  There is also a lot of subtlety depending on your scenario.   There is a fairly in depth discussion of the issue @ Efficient way of getting @@rowcount from a query using row_number</p>


问:
How should the keychain option be used for altool?
I'm trying to use the @keychain option with the -p switch in altool in order to load my iTunes Connect password from the keychain:

altool --validate-app -f "${IPA}" -u "redacted" -p "@keychain:?????"
```

<p>I'm trying to figure out what I need to enter after <code>@keychain:</code>. Everything I try (path of the keychain file, name of the keychain entry, username in the keychain entry) produces the following error:</p>

<blockquote>
  <p>*** Error: The specified item could not be found in the keychain.</p>
</blockquote>

<p><code>altool</code> supplies the following info about the <code>-p</code> param:</p>

<pre class="lang-none prettyprint-override"><code>-p, --password  Password. Required if username specified.  Password is read from stdin if one is not supplied.
                May use @keychain: or @env: prefixes followed by the keychain or environment variable lookup name.
                e.g. -p @env:SECRET which would use the value in the SECRET environment variable.
</code>```

答:
Prerequisites:

You need an Apple developer account, obviously. That's AC_USERNAME.

You need a password for that account. If you can have two-factor authentication enabled, you need to create an app-specific password (beyond the scope of this answer). The password is AC_PASSWORD.

The keychain item is going to need a name that is references via altool's @keychain parameter. We call this ITEM_NAME.

In the instructions below, replace AC_USERNAME, AC_PASSWORD and ITEM_NAME with the values you need. Do not type these names verbatim.

Now:

Create a generic password in your keychain.

You can do so via Keychain Access.app File > New Password Item … . In the Keychain Item Name, enter the name you want for ITEM_NAME, the Account Name is your AC_USERNAME and the AC_PASSWORD goes into the Password field.

Or you can do it via the command line: security add-generic-password -a "AC_USERNAME" -w "AC_PASSWORD" -s "ITEM_NAME"

In the arguments to altool, you now pass -u AC_USERNAME -p "@keychain:ITEM_NAME" to make it fetch the password from the keychain.

The first time you run altool, you get a security confirmation dialog asking you whether to allow altool to read the password. Enter your keychain password and click on Always allow.

To prevent the security confirmation dialog from appearing, either click on Always allow or modify the appropriate keychain entry. This works like this:

Locate the path to altool by opening a shell and typing xcrun -find altool.

Either use this path as argument -T <path> when creating the password using the security add-generic-password command or:

Open Keychain Access.app.

Select the password entry, select the menu File > Get Info (or press Cmd+I or click the ⓘ icon).

In this dialog, select the Access Control tab and press the + button. A file selection dialog opens.

Open Finder and select the menu Go > Go to Folder… and paste the path to altool (the directory part, without altool itself, e.g. /Applications/Xcode.app/Contents/Developer/usr/bin/).

Drag altool to the open panel of Keychain Access and press the Add button.

Body:
I'm trying to use the @keychain option with the -p switch in altool in order to load my iTunes Connect password from the keychain:

altool --validate-app -f "${IPA}" -u "redacted" -p "@keychain:?????"

I'm trying to figure out what I need to enter after @keychain:. Everything I try (path of the keychain file, name of the keychain entry, username in the keychain entry) produces the following error:

*** Error: The specified item could not be found in the keychain.

altool supplies the following info about the -p param:

-p, --password  Password. Required if username specified.  Password is read from stdin if one is not supplied.
                May use @keychain: or @env: prefixes followed by the keychain or environment variable lookup name.
                e.g. -p @env:SECRET which would use the value in the SECRET environment variable.


问:
ReactJS Semantic UI dropdown onChange won't fire if the user selects the same item twice
I have a File menu that contains 3 options:

```<code>const fileOptions = [
  { key: 'open', icon: 'open folder outline', text: 'Open lesson', value: 'open' },
  { key: 'save', icon: 'save', text: 'Save lesson', value: 'save' },
  { key: 'delete', icon: 'delete', text: 'Delete lesson', value: 'delete' },
]
</code>```

Everything works fine but if I select for example "Save lesson" twice it will work the first time only (I'm using the onChange event). And that's because the value of the dropdown did not change. What event should I usr?

```<code>     <Button.Group color='teal'>
        <Dropdown

          className='button icon'
          floating
          options={fileOptions}
          trigger={<React.Fragment />}
          onChange={this.handleLessonMenu}
        />
      </Button.Group>
</code>```

答:
I kind of sorted the issue out by changing the code as follows:</p>

```<code>      <Dropdown
        text='File'
        fluid
      >
        <Dropdown.Menu >
          <Dropdown.Item text='Add section'
            onClick={this.addSection}
          />
          <Dropdown.Divider />
          <Dropdown.Item text='New lesson' />
          <Dropdown.Item text='Open lesson' description='ctrl + o' />
          <Dropdown.Item text='Save lesson' description='ctrl + s'
            onClick={this.handleSave}
          />
          <Dropdown.Divider />
          <Dropdown.Item text='Delete lesson' description='ctrl + d' />
        </Dropdown.Menu>
      </Dropdown>
</code>```

Body:
I have a File menu that contains 3 options:

const fileOptions = [
  { key: 'open', icon: 'open folder outline', text: 'Open lesson', value: 'open' },
  { key: 'save', icon: 'save', text: 'Save lesson', value: 'save' },
  { key: 'delete', icon: 'delete', text: 'Delete lesson', value: 'delete' },
]

Everything works fine but if I select for example "Save lesson" twice it will work the first time only (I'm using the onChange event). And that's because the value of the dropdown did not change. What event should I usr?

     <Button.Group color='teal'>
        <Dropdown

          className='button icon'
          floating
          options={fileOptions}
          trigger={<React.Fragment />}
          onChange={this.handleLessonMenu}
        />
      </Button.Group>

Body:
I kind of sorted the issue out by changing the code as follows:

      <Dropdown
        text='File'
        fluid
      >
        <Dropdown.Menu >
          <Dropdown.Item text='Add section'
            onClick={this.addSection}
          />
          <Dropdown.Divider />
          <Dropdown.Item text='New lesson' />
          <Dropdown.Item text='Open lesson' description='ctrl + o' />
          <Dropdown.Item text='Save lesson' description='ctrl + s'
            onClick={this.handleSave}
          />
          <Dropdown.Divider />
          <Dropdown.Item text='Delete lesson' description='ctrl + d' />
        </Dropdown.Menu>
      </Dropdown>


问:
Android Apps 64-bit Advice - Receiving Contradictory Information
Google requires all apps submitted after August 1 to have 64-bit and 32-bit .so files.  They have an article about how to package both sets of libraries in your .apk

I've been told that instead, we should create 2 apps, one with 32-bit libraries and one with 64-bit libraries, and submit them both with different version codes.  Will this even work?

My understanding is that a 32-bit-only app won't even be accepted after August 1, so how can I submit both?  If I submit the 64-bit one first, will the store be ok with then submitting a 32-bit-only one?

Even more confusing is that I was told to use version codes far apart to distinguish the 32-bit and 64-bit versions.  So today my version code is 32.  In August, I'd submit a 32-bit app with code 33 and a 64-bit one with code 1033.  And then, for another app, I would submit one with codes 34 and 1034.  That doesn't make sense to me, because my understanding is that you can never go backwards in version codes, they always increase in value.

Not that it matters in this context, bit it is Kony (a multi-platform app generator from JavaScript) that is telling us to do it this way.  This advice just doesn't sound right, and I don't want to find out the hard way on August 1 that it isn't going to work.

I've tried to find information on the Google developer site, but I don't see any indication that this strategy will work.

Any clarification would be appreciated.

答:
I found a document on the Android development site that answers everything.
https://developer.android.com/google/play/publishing/multiple-apks.html</p>


问:
Explain some code about dynamic connection string
So, I'm doing a website that does a lot of things and one of them is, doing a dynamic connection string... I already did it, but because I took the code from the internet, I'm kinda lost, so I was hoping that somebody could help and explain how it works and what each thing does...

Here's the code:

```<code>protected void Page_Load(object sender, EventArgs e)
        {
            AddUpdateConnectionString("ConString");
        }

            void AddUpdateConnectionString(string name)
            {

                bool isNew = false;
                string path = Server.MapPath("~/Web.Config");
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNodeList list = doc.DocumentElement.SelectNodes(string.Format("connectionStrings/add[@name='{0}']", name));
                XmlNode node;
                isNew = list.Count == 0;
                if (isNew)
                {
                    node = doc.CreateNode(XmlNodeType.Element, "add", null);
                    XmlAttribute attribute = doc.CreateAttribute("name");
                    attribute.Value = name;
                    node.Attributes.Append(attribute);

                    attribute = doc.CreateAttribute("connectionString");
                    attribute.Value = "";
                    node.Attributes.Append(attribute);

                    attribute = doc.CreateAttribute("providerName");
                    attribute.Value = "System.Data.SqlClient";
                    node.Attributes.Append(attribute);
                }
                else
                {
                    node = list[0];
                }
                string conString = node.Attributes["connectionString"].Value;
                SqlConnectionStringBuilder conStringBuilder = new SqlConnectionStringBuilder(conString);
                conStringBuilder.InitialCatalog = TxtBaseDeDados.Text;
                conStringBuilder.DataSource = TxtHost.Text;
                conStringBuilder.IntegratedSecurity = false;
                conStringBuilder.UserID = TxtUtilizador.Text;
                conStringBuilder.Password = TxtPalavraPasse.Text;
                node.Attributes["connectionString"].Value = conStringBuilder.ConnectionString;
                if (isNew)
                {
                    doc.DocumentElement.SelectNodes("connectionStrings")[0].AppendChild(node);
                }

                doc.Save(path);

            }

        protected void Button1_Click(object sender, EventArgs e)
        {
            AddUpdateConnectionString("ConString");
        }
</code>```

答:
If you are wanting to load a connection string from the web.config file I would encourange you to use the ConfigurationManager class like this:

```<code>ConfigurationManager.ConnectionStrings["WingtipToys"].ConnectionString
</code>```

WingtipToys would be stored like this in web.config

```<code><configuration>
<startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
  <add name="WingtipToys" connectionString="Data Source=(LocalDB)\v11.0;Initial Catalog=WingtipToys;Integrated Security=True;Pooling=False" />
</connectionStrings>
</code>```

Here is more info: https://learn.microsoft.com/en-us/dotnet/api/system.configuration.configurationmanager?view=netframework-4.8

Body:
So, I'm doing a website that does a lot of things and one of them is, doing a dynamic connection string... I already did it, but because I took the code from the internet, I'm kinda lost, so I was hoping that somebody could help and explain how it works and what each thing does...

Here's the code:

protected void Page_Load(object sender, EventArgs e)
        {
            AddUpdateConnectionString("ConString");
        }

            void AddUpdateConnectionString(string name)
            {

                bool isNew = false;
                string path = Server.MapPath("~/Web.Config");
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                XmlNodeList list = doc.DocumentElement.SelectNodes(string.Format("connectionStrings/add[@name='{0}']", name));
                XmlNode node;
                isNew = list.Count == 0;
                if (isNew)
                {
                    node = doc.CreateNode(XmlNodeType.Element, "add", null);
                    XmlAttribute attribute = doc.CreateAttribute("name");
                    attribute.Value = name;
                    node.Attributes.Append(attribute);

                    attribute = doc.CreateAttribute("connectionString");
                    attribute.Value = "";
                    node.Attributes.Append(attribute);

                    attribute = doc.CreateAttribute("providerName");
                    attribute.Value = "System.Data.SqlClient";
                    node.Attributes.Append(attribute);
                }
                else
                {
                    node = list[0];
                }
                string conString = node.Attributes["connectionString"].Value;
                SqlConnectionStringBuilder conStringBuilder = new SqlConnectionStringBuilder(conString);
                conStringBuilder.InitialCatalog = TxtBaseDeDados.Text;
                conStringBuilder.DataSource = TxtHost.Text;
                conStringBuilder.IntegratedSecurity = false;
                conStringBuilder.UserID = TxtUtilizador.Text;
                conStringBuilder.Password = TxtPalavraPasse.Text;
                node.Attributes["connectionString"].Value = conStringBuilder.ConnectionString;
                if (isNew)
                {
                    doc.DocumentElement.SelectNodes("connectionStrings")[0].AppendChild(node);
                }

                doc.Save(path);

            }

        protected void Button1_Click(object sender, EventArgs e)
        {
            AddUpdateConnectionString("ConString");
        }

Body:
If you are wanting to load a connection string from the web.config file I would encourange you to use the ConfigurationManager class like this:

ConfigurationManager.ConnectionStrings["WingtipToys"].ConnectionString

WingtipToys would be stored like this in web.config

<configuration>
<startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
  <add name="WingtipToys" connectionString="Data Source=(LocalDB)\v11.0;Initial Catalog=WingtipToys;Integrated Security=True;Pooling=False" />
</connectionStrings>

Here is more info: https://learn.microsoft.com/en-us/dotnet/api/system.configuration.configurationmanager?view=netframework-4.8


问:
Trouble Connecting to sql server Login failed. "The login is from an untrusted domain and cannot be used with Windows authentication"
I am trying to host a SQL server database, but whenever I try to connect to it I get this error:

The login is from an untrusted domain and cannot be used with Windows
  authentication

I am connecting through Matlab using the following command:

```<code>conn = database('Clinical_Data','DoyleLab07\Acc','','com.microsoft.sqlserver.jdbc.SQLServerDriver','jdbc:sqlserver://DOYLELAB07\SQLEXPRESS:54287;database=Clinical_Data;integratedSecurity=true;').
</code>```

Connecting to the database using matlab worked fine as long as I was using matlab on the computer which I was using to host the server. However, when I use another computer and the same Matlab command I get the error I showed above.

When I look under control panel\system. I notice that no domain is listed on my host PC or the PC I am using to connect to the host, but both computers are in the same workgroup. Would I be able to fix my problem by creating a domain and adding the foreign PC and the host to that domain? If so, how can this be accomplished?

Any suggestions will be very much appreciated.
Thank you for reading my post.

答: We now use a privileged account management solution that changes our passwords regularly.  I ended up receiving this error after my password was changed.  Closing and re-opening SSMS with the new password resolved my issue.</p>

Body:
I am trying to host a SQL server database, but whenever I try to connect to it I get this error:

The login is from an untrusted domain and cannot be used with Windows
  authentication

I am connecting through Matlab using the following command:

conn = database('Clinical_Data','DoyleLab07\Acc','','com.microsoft.sqlserver.jdbc.SQLServerDriver','jdbc:sqlserver://DOYLELAB07\SQLEXPRESS:54287;database=Clinical_Data;integratedSecurity=true;').

Connecting to the database using matlab worked fine as long as I was using matlab on the computer which I was using to host the server. However, when I use another computer and the same Matlab command I get the error I showed above.

When I look under control panel\system. I notice that no domain is listed on my host PC or the PC I am using to connect to the host, but both computers are in the same workgroup. Would I be able to fix my problem by creating a domain and adding the foreign PC and the host to that domain? If so, how can this be accomplished?

Any suggestions will be very much appreciated.
Thank you for reading my post.


问:
Cannot connect cluster mongo.db atlas
I'm currently trying to learn MEAN stack. The tutorial are about a task manager. Right now I'm trying to connect to mongodb atlas to retrieve sample data in database but they are not showing up http://localhost:3000/api/tasks

Here is my tasks.js file

```<code>var express = require('express');
var router = express.Router();
var mongojs = require('mongojs');
var db = mongojs('drivers',['tasks']);

router.get('/tasks', function(req, res, next){
    db.tasks.find(function(err, tasks){
        if(err){
            res.send(err);
        }
        res.json(tasks);
    });
});

module.exports = router;
</code>```

Here is my server.js file

```<code>var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var task = require('./routes/tasks');
var app = express();
var port = 3000;

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);

app.use(express.static(path.join(__dirname, 'client')));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

app.use('/', index);
app.use('/api', task);

app.listen(port, function(){
    console.log('Server started on port' +port);
});
</code>```

Here is my package.json file

```<code>{
  "name": "mytasklist",
  "version": "1.0.0",
  "description": "Task Manager",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "ejs": "^2.6.1",
    "express": "^4.17.1",
    "mongojs": "^2.6.0"
  }
}
</code>```

答: Problem solved, I pasted the wrong version for my nodejs driver.</p>

Title: Cannot connect cluster mongo.db atlas

Body:
I'm currently trying to learn MEAN stack. The tutorial are about a task manager. Right now I'm trying to connect to mongodb atlas to retrieve sample data in database but they are not showing up http://localhost:3000/api/tasks

Here is my tasks.js file

var express = require('express');
var router = express.Router();
var mongojs = require('mongojs');
var db = mongojs('drivers',['tasks']);

router.get('/tasks', function(req, res, next){
    db.tasks.find(function(err, tasks){
        if(err){
            res.send(err);
        }
        res.json(tasks);
    });
});

module.exports = router;

Here is my server.js file

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var task = require('./routes/tasks');
var app = express();
var port = 3000;

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);

app.use(express.static(path.join(__dirname, 'client')));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

app.use('/', index);
app.use('/api', task);

app.listen(port, function(){
    console.log('Server started on port' +port);
});

Here is my package.json file

{
  "name": "mytasklist",
  "version": "1.0.0",
  "description": "Task Manager",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "ejs": "^2.6.1",
    "express": "^4.17.1",
    "mongojs": "^2.6.0"
  }
}


问:
Capture the highest value for each computers from the SQL table
Need to pull the last step performed by each computer in a specific task sequence

Wrote one SQL query which pulls the status of the computer for a particular task sequence with all the steps it performed during the task sequence run. But it shows all the steps which the machine performed where my actual requirement is to get the last step for each machine.

```<code>Netbios_Name0   Step    ActionName  Last Status
Computer1   0     xyx             Failed
Computer1   1     xyz             Success
Computer1   2     yyy            Inprogres
Computer2   0     xzz             Waiting
Computer2   1     xxy             Failed
Computer3   0     xyz             Failed
Computer3   1     xxx            Accepted
Computer3   2     xzy             Failed
Computer3   3     xzz            Success
</code>```

```<code>Select Netbios_name0
,Step
,ActionName
,Laststatus
from [v_R_System] System
join [vSMS_TaskSequenceExecutionStatus] TaskSequence
On TaskSequence.ResourceID = System.ResourceID
where packageID like '%PackageID%'
</code>```

The expected out is like,

```<code>Netbios_Name0   Step    ActionName  Last Status
Computer1   2   yyy          Inprogres
Computer2   1   xxy           Failed
Computer3   3   xzz           Success
</code>```

答:
If you have window functions available...</p>

```<code>select Netbios_Name0,Step,ActionName,Last Status
from
  (
  select t1.*, row_number() over (partition by Netbios_name0 order by Step desc) as rn
  from MyTable t1
  ) x2
where x2.rn = 1
</code>```

Body:
Need to pull the last step performed by each computer in a specific task sequence

Wrote one SQL query which pulls the status of the computer for a particular task sequence with all the steps it performed during the task sequence run. But it shows all the steps which the machine performed where my actual requirement is to get the last step for each machine.

Netbios_Name0   Step    ActionName  Last Status
Computer1   0     xyx             Failed
Computer1   1     xyz             Success
Computer1   2     yyy            Inprogres
Computer2   0     xzz             Waiting
Computer2   1     xxy             Failed
Computer3   0     xyz             Failed
Computer3   1     xxx            Accepted
Computer3   2     xzy             Failed
Computer3   3     xzz            Success

Select Netbios_name0
,Step
,ActionName
,Laststatus
from [v_R_System] System
join [vSMS_TaskSequenceExecutionStatus] TaskSequence
On TaskSequence.ResourceID = System.ResourceID
where packageID like '%PackageID%'

The expected out is like,

Netbios_Name0   Step    ActionName  Last Status
Computer1   2   yyy          Inprogres
Computer2   1   xxy           Failed
Computer3   3   xzz           Success

Body:
If you have window functions available...

select Netbios_Name0,Step,ActionName,Last Status
from
  (
  select t1.*, row_number() over (partition by Netbios_name0 order by Step desc) as rn
  from MyTable t1
  ) x2
where x2.rn = 1


问:
I have a question about using github with collaborators
I guys, Id like to know some tips about git,
I've worked with collaborators in the same repository and Id like to know if when someone makes the code's push, the code that is already there will be changed adding only the changes and when the other persor make the other git-push the code will be the union of both pushes, or the code will be replaced by the last one pushed from the last person who made the git-push.</p>

答:
The second person making a push won't be able to, unless he/she forces the push (git push --force), assuming they are both pushing from and to the same branch.

The best practice would be for that second person to do first:

```<code>git pull --rebase
</code>```

That will replay unpushed commit on top of the update branch (with the commits from the first person). Possible merge conflicts will be resolved locally, in the second person's local Git repository.

Then a simple git push will add the new commits on top of the existing ones.

Body:
The second person making a push won't be able to, unless he/she forces the push (git push --force), assuming they are both pushing from and to the same branch.

The best practice would be for that second person to do first:

git pull --rebase

That will replay unpushed commit on top of the update branch (with the commits from the first person). Possible merge conflicts will be resolved locally, in the second person's local Git repository.

Then a simple git push will add the new commits on top of the existing ones.


问:
ng-select add new option with async search
I use the [@ng-select/ng-select][1] component many places in my software. It works well, it searches by a backend method as the user types and shows the results for selection.

Now I would like to let the user to create new items that are not on the list. How can I do this with an async list? productNames is an Observable.

```<code><ng-select [name]="'productname'+index$" [items]="productNames | async"
        [attr.id]="'productname'+index$"
        [(ngModel)]="detail.productNameNew"
        [typeahead]="productNameInput"
        (change)="productNameChanged($event, detail)"
        (keydown)="productNameKeyPress($event, detail)"
        [disabled]="currentSuggestion.acceptUser === null ? null : true"
        [clearable]="false">
    <ng-template ng-label-tmp let-item="item">
        {{item.productName}}
    </ng-template>
    <ng-template ng-option-tmp let-item="item">
        <div class="noproduct-item">
                <div class="noproduct-head">
                    <div class="productname">{{item.productName}}</div>
                    <div class="description">{{item.description}}</div>
                </div>
                <div class="noproduct-details">
                <div class="headid">
                    <span class='glyphicon glyphicon-send'></span>
                    {{item.suggestionHeadId}}
                </div>
                <div class="createduser">
                    <span class='glyphicon glyphicon-user'></span>
                    {{item.createUser?.name}}
                </div>
                <div class="createddate">
                    <span class='glyphicon glyphicon-calendar'></span>
                    {{item.createDate | date: 'yyyy.MM.dd.'}}
                </div>
            </div>
        </div>
    </ng-template>
</ng-select>
</code>```

答:
Add a second observable to capture the user added products and then use combineLatest to merge them.  Subscribing to the combined list will produce a new list that you can use in the ng-select.
https://stackblitz.com/edit/angular-rxjs-combinelatest</p>

Body:
I use the [@ng-select/ng-select][1] component many places in my software. It works well, it searches by a backend method as the user types and shows the results for selection.

Now I would like to let the user to create new items that are not on the list. How can I do this with an async list? productNames is an Observable.

<ng-select [name]="'productname'+index$" [items]="productNames | async"
        [attr.id]="'productname'+index$"
        [(ngModel)]="detail.productNameNew"
        [typeahead]="productNameInput"
        (change)="productNameChanged($event, detail)"
        (keydown)="productNameKeyPress($event, detail)"
        [disabled]="currentSuggestion.acceptUser === null ? null : true"
        [clearable]="false">
    <ng-template ng-label-tmp let-item="item">
        {{item.productName}}
    </ng-template>
    <ng-template ng-option-tmp let-item="item">

{{item.productName}}

{{item.description}}

                    {{item.suggestionHeadId}}

                    {{item.createUser?.name}}

                    {{item.createDate | date: 'yyyy.MM.dd.'}}

    </ng-template>
</ng-select>


问:
Problem with understanding a vector initialization
This might be a dumb question but there is something I can't quite understand. When using a vector, whenever I want to 'push_back' an element to a certain position I can do that only if I initialize the vector in a certain way.

For example when I use this initialization:

```<code>std::vector<int> Myvec;
int size = 0;
int x = 0;
std::cin >> size;

for(int i = 0; i < size; i++)
{
    std::cin >> x;
    Myvec[i].push_back(x);
}
</code>```

I receive the following error:
request for member 'push_back' in 'Myvec.std::vector<_Tp, _Alloc>::operator[] >(((std::vector::size_type)i))', which is of non-class type '__gnu_cxx::__alloc_traits >::value_type {aka int}'|

But when I use the following initialization it works:

```<code>int size = 0;
int x = 0;
std::cin >> size;
std::vector<int> Myvec[size];

for(int i = 0; i < size; i++)
{
    std::cin >> x;
    Myvec[i].push_back(x);
}
</code>```

I don't have any problem using it and can implement it in all sorts of tasks, but it's bugging me because I'm not sure why it is actually working. Thank you for your help in advance.

答:
You're not putting an element at position i in a vector.

You're putting an element at the back of the ith vector in an array of vectors! Worse, the array is empty, so the access is invalid.

If it weren't, though, you'd end up with i vectors each having one element. Not good!

Instead, you can make your vector be of a certain size:

```<code>MyVec.resize(SomeSize);
</code>```

…then assign the elements as if the vector were an array (which it kind of is):

```<code>MyVec[i] = thing;
</code>```

The key point here is that you don't have to push_back; you only do that when you want to push a new element to the back of the vector. You can access existing values with array-like [] syntax just fine.

Read more about vectors in your C++ book.

Body:
This might be a dumb question but there is something I can't quite understand. When using a vector, whenever I want to 'push_back' an element to a certain position I can do that only if I initialize the vector in a certain way.

For example when I use this initialization:

std::vector<int> Myvec;
int size = 0;
int x = 0;
std::cin >> size;

for(int i = 0; i < size; i++)
{
    std::cin >> x;
    Myvec[i].push_back(x);
}

I receive the following error:
request for member 'push_back' in 'Myvec.std::vector<_Tp, _Alloc>::operator[] >(((std::vector::size_type)i))', which is of non-class type '__gnu_cxx::__alloc_traits >::value_type {aka int}'|

But when I use the following initialization it works:

int size = 0;
int x = 0;
std::cin >> size;
std::vector<int> Myvec[size];

for(int i = 0; i < size; i++)
{
    std::cin >> x;
    Myvec[i].push_back(x);
}

I don't have any problem using it and can implement it in all sorts of tasks, but it's bugging me because I'm not sure why it is actually working. Thank you for your help in advance.

Body:
You're not putting an element at position i in a vector.

You're putting an element at the back of the ith vector in an array of vectors! Worse, the array is empty, so the access is invalid.

If it weren't, though, you'd end up with i vectors each having one element. Not good!

Instead, you can make your vector be of a certain size:

MyVec.resize(SomeSize);

…then assign the elements as if the vector were an array (which it kind of is):

MyVec[i] = thing;

The key point here is that you don't have to push_back; you only do that when you want to push a new element to the back of the vector. You can access existing values with array-like [] syntax just fine.

Read more about vectors in your C++ book.


问:
Animate Image transitions in Android
I have 4 ImageViews (Please see picture attached below)

The code for the 4 images are as such:

```<code><LinearLayout
    android:id="@id/LinearLayout_fromAddItemActivity_Priority"
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintBottom_toTopOf="@+id/FAB_fromAddItemActivity_AddItem"
    app:layout_constraintTop_toBottomOf="@+id/TextView_fromAddItemActivity_SubtitlePriority"
    app:layout_constraintVertical_chainStyle="packed">

<ImageView
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:onClick="setPriority"
        android:tag="@{Constant.ENUM_PRIORITY_P1}"
        android:contentDescription="@string/ContentDescription_fromAddItemActivity_Priority1Icon"
        app:srcCompat="@drawable/ic_priority_1"/>
<ImageView
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:onClick="setPriority"
        android:tag="@{Constant.ENUM_PRIORITY_P2}"
        android:contentDescription="@string/ContentDescription_fromAddItemActivity_Priority2Icon"
        app:srcCompat="@drawable/ic_priority_2"/>
<ImageView
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:onClick="setPriority"
        android:tag="@{Constant.ENUM_PRIORITY_P3}"
        android:contentDescription="@string/ContentDescription_fromAddItemActivity_Priority3Icon"
        app:srcCompat="@drawable/ic_priority_3"/>
<ImageView
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:onClick="setPriority"
        android:tag="@{Constant.ENUM_PRIORITY_P4}"
        android:contentDescription="@string/ContentDescription_fromAddItemActivity_Priority4Icon"
        app:srcCompat="@drawable/ic_priority_4"/>
</code>```

On clicking on either of these images, I want them to transition as shown in the picture below with the image clicked to be on top!

Anybody can help me with these, please?

(I don't know much about transitions and animations in Android, I just know how to transition between activities).

答:
you can use this function to move a view to the center horizontally  of your screen </p>

```<code>private fun moveViewToScreenCenter(view:View) {

 val dm = DisplayMetrics()
  getWindowManager().getDefaultDisplay().getMetrics(dm)
  val originalPos = IntArray(2)
  view.getLocationOnScreen(originalPos)
  val xDelta = (dm.widthPixels - view.getMeasuredWidth() - originalPos[0]) / 2
  val yDelta = originalPos[1]//because you want to centre it horizontally
  val animSet = AnimationSet(true)
  animSet.setFillAfter(true)
  animSet.setDuration(1000)
  animSet.setInterpolator(BounceInterpolator())
  val translate = TranslateAnimation(0, xDelta, 0, yDelta)
  animSet.addAnimation(translate)
  val scale = ScaleAnimation(1f, 2f, 1f, 2f, ScaleAnimation.RELATIVE_TO_PARENT, .5f, ScaleAnimation.RELATIVE_TO_PARENT, .5f)
  animSet.addAnimation(scale)
  view.startAnimation(animSet)
}
</code>```

Title: Animate Image transitions in Android

Body:
I have 4 ImageViews (Please see picture attached below)

The code for the 4 images are as such:

<LinearLayout
    android:id="@id/LinearLayout_fromAddItemActivity_Priority"
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintBottom_toTopOf="@+id/FAB_fromAddItemActivity_AddItem"
    app:layout_constraintTop_toBottomOf="@+id/TextView_fromAddItemActivity_SubtitlePriority"
    app:layout_constraintVertical_chainStyle="packed">

<ImageView
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:onClick="setPriority"
        android:tag="@{Constant.ENUM_PRIORITY_P1}"
        android:contentDescription="@string/ContentDescription_fromAddItemActivity_Priority1Icon"
        app:srcCompat="@drawable/ic_priority_1"/>
<ImageView
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:onClick="setPriority"
        android:tag="@{Constant.ENUM_PRIORITY_P2}"
        android:contentDescription="@string/ContentDescription_fromAddItemActivity_Priority2Icon"
        app:srcCompat="@drawable/ic_priority_2"/>
<ImageView
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:onClick="setPriority"
        android:tag="@{Constant.ENUM_PRIORITY_P3}"
        android:contentDescription="@string/ContentDescription_fromAddItemActivity_Priority3Icon"
        app:srcCompat="@drawable/ic_priority_3"/>
<ImageView
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:onClick="setPriority"
        android:tag="@{Constant.ENUM_PRIORITY_P4}"
        android:contentDescription="@string/ContentDescription_fromAddItemActivity_Priority4Icon"
        app:srcCompat="@drawable/ic_priority_4"/>

On clicking on either of these images, I want them to transition as shown in the picture below with the image clicked to be on top!

Anybody can help me with these, please?

(I don't know much about transitions and animations in Android, I just know how to transition between activities).

Body:
you can use this function to move a view to the center horizontally  of your screen

private fun moveViewToScreenCenter(view:View) {

 val dm = DisplayMetrics()
  getWindowManager().getDefaultDisplay().getMetrics(dm)
  val originalPos = IntArray(2)
  view.getLocationOnScreen(originalPos)
  val xDelta = (dm.widthPixels - view.getMeasuredWidth() - originalPos[0]) / 2
  val yDelta = originalPos[1]//because you want to centre it horizontally
  val animSet = AnimationSet(true)
  animSet.setFillAfter(true)
  animSet.setDuration(1000)
  animSet.setInterpolator(BounceInterpolator())
  val translate = TranslateAnimation(0, xDelta, 0, yDelta)
  animSet.addAnimation(translate)
  val scale = ScaleAnimation(1f, 2f, 1f, 2f, ScaleAnimation.RELATIVE_TO_PARENT, .5f, ScaleAnimation.RELATIVE_TO_PARENT, .5f)
  animSet.addAnimation(scale)
  view.startAnimation(animSet)
}


问:
How to apply mask behavior in primeng calendar (p-calendar)?
I am new to angular, in p-calendar I'm not able to apply masking behaviour. Example: If user enters 01012012, I want to change it to 01-01-2012. Thanks in advance.</p>

答:
Try this:

```<code> onKeyDate(event: any){
   event.target.value = event.target.value.replace(/^(\d{2})(\d{2})(\d{4})/, '$1-$2-$3');
  }
</code>```

in HTML:

```<code><input type="text" name="data" placeholder="Date:"(keyup)="onKeyDate($event)">
</code>```

Body:
Try this:

 onKeyDate(event: any){
   event.target.value = event.target.value.replace(/^(\d{2})(\d{2})(\d{4})/, '$1-$2-$3');
  }

in HTML:

<input type="text" name="data" placeholder="Date:"(keyup)="onKeyDate($event)">


问:
EntityFramework.SqlServer.dll not is getting added to the published folder only when I publish in RELEASE mode
I know there is a problem with EF6 EntityFramework.SqlServer and included  var type = typeof(System.Data.Entity.SqlServer.SqlProviderServices); in context constructor. It works fine when i do publish in DEBUG mode.

Getting the below error only when I publish in RELEASE mode. The reason is EntityFramework.SqlServer.dll missing in the published folder. But, bin folder has EntityFramework.SqlServer.dll for both debug and release mode.

Error:

The Entity Framework provider type
  'System.Data.Entity.SqlServer.SqlProviderServices,
  EntityFramework.SqlServer' registered in the application config file
  for the ADO.NET provider with invariant name 'System.Data.SqlClient'
  could not be loaded. Make sure that the assembly-qualified name is
  used and that the assembly is available to the running application.

Why is it missing only when I publish using RELEASE mode?

答:
I also had the same problem.

What happens is that this EntityFramework.SqlServer.dll is not referenced directly by your project, but internally byEntityFramework.dll.

Since we do not use any of this EntityFramework.SqlServer.dll in our code, the Roslyn compiler, applying some optimizations, understands that it does not need this component and then does not copy it to thebin folder and does not copy also for Publish.

What you need to do is create a reference to some object of this EntityFramework.SqlServer.dll anywhere in your code.

For example, I have a dependency injection container configuration class, where I configure my repositories and contexts, and I think it would be a good location. So I created a static property that I never use in any location, but it solves the problem:

using System.Data.Entity.SqlServer;

public class ContainerConfiguration
{
    // HACK: This code snippet ensures that the DLL (EntityFramework.SqlServer.dll)
    // not removed by compiler optimizer (csc.exe roslyn)
    public static SqlProviderServices EntitySqlServerHack => SqlProviderServices.Instance;

    public void ContainerConfiguration(IContainer container)
    {
        InternalConfigure(container, false);
    }
}
```


问:
Ruby on Rails -- commontator -- use avatar urls instead of paperclip avatar
So I'm using the commontator gem for comments in ruby and I wanna know how I can just use a simple url to display the avatar

My user.avatar is basically a string with a url.
Default:

```<code>config.user_avatar_proc = lambda { |user, view|
                                     view.commontator_gravatar_image_tag(
                                       user, 1, :s => 60, :d => 'mm') }
</code>```

I have tried:

```<code>config.user_avatar_proc = lambda { |user, view|
                                     view.image_tag(
                                       user.avatar) }
</code>```

Without any luck

答:
user.avatar is the paperclip object. Inside image tag, use
user.avatar.url(:thumb) (thumb or whatever sizes you have specified)</p>

Body:
So I'm using the commontator gem for comments in ruby and I wanna know how I can just use a simple url to display the avatar

My user.avatar is basically a string with a url.
Default:

config.user_avatar_proc = lambda { |user, view|
                                     view.commontator_gravatar_image_tag(
                                       user, 1, :s => 60, :d => 'mm') }

I have tried:

config.user_avatar_proc = lambda { |user, view|
                                     view.image_tag(
                                       user.avatar) }

Without any luck


问:
Jest raises a TypeError with Object.entries
I don't know what's wrong with jest/enzyme, but it crashes in some really frustrating ways.

```<code>import React from 'react';
import Timeline from './Timeline';
import { configure, mount, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });

const wrapper = mount(
    <Timeline/>
);

it('Should render the timeline component.', () => {
    expect(wrapper.find(Timeline)).toHaveLength(1);
});
</code>```

This simple test raises this error:

```<code>TypeError: Cannot convert undefined or null to object
        at Function.entries (<anonymous>)

      17 |                 <Row>
      18 |                     {
    > 19 |                         Object.entries(this.props.months).map((month) => {
         |                                ^
      20 |                             let onClick = () => {
      21 |                                 alert(month);
      22 |                             };

      at Timeline.entries [as render] (src/components/Dashboard/AReceber/Timeline.js:19:32)
      at finishClassComponent (node_modules/react-dom/cjs/react-dom.development.js:14741:31)
      at updateClassComponent (node_modules/react-dom/cjs/react-dom.development.js:14696:24)
      at beginWork (node_modules/react-dom/cjs/react-dom.development.js:15644:16)
      at performUnitOfWork (node_modules/react-dom/cjs/react-dom.development.js:19312:12)
      at workLoop (node_modules/react-dom/cjs/react-dom.development.js:19352:24)
      at renderRoot (node_modules/react-dom/cjs/react-dom.development.js:19435:7)
      at performWorkOnRoot (node_modules/react-dom/cjs/react-dom.development.js:20342:7)
      at requestWork (node_modules/react-dom/cjs/react-dom.development.js:20090:7)
      at scheduleWork (node_modules/react-dom/cjs/react-dom.development.js:19911:5)
      at scheduleRootUpdate (node_modules/react-dom/cjs/react-dom.development.js:20572:3)
      at updateContainerAtExpirationTime (node_modules/react-dom/cjs/react-dom.development.js:20600:10)
      at updateContainer (node_modules/react-dom/cjs/react-dom.development.js:20657:10)
      at ReactRoot.Object.<anonymous>.ReactRoot.render (node_modules/react-dom/cjs/react-dom.development.js:20953:3)
      at node_modules/react-dom/cjs/react-dom.development.js:21090:14
      at unbatchedUpdates (node_modules/react-dom/cjs/react-dom.development.js:20454:14)
      at legacyRenderSubtreeIntoContainer (node_modules/react-dom/cjs/react-dom.development.js:21086:5)
      at Object.render (node_modules/react-dom/cjs/react-dom.development.js:21155:12)
      at render (node_modules/enzyme-adapter-react-16/src/ReactSixteenAdapter.js:425:26)
      at fn (node_modules/enzyme-adapter-react-16/src/ReactSixteenAdapter.js:342:37)
      at Object.batchedUpdates$1 [as unstable_batchedUpdates] (node_modules/react-dom/cjs/react-dom.development.js:20439:12)
      at Object.act (node_modules/react-dom/cjs/react-dom-test-utils.development.js:1161:27)
      at act (node_modules/enzyme-adapter-react-16/src/ReactSixteenAdapter.js:342:13)
      at Object.wrapAct [as render] (node_modules/enzyme-adapter-react-16/src/ReactSixteenAdapter.js:411:16)
      at new ReactWrapper (node_modules/enzyme/build/ReactWrapper.js:134:16)
      at mount (node_modules/enzyme/build/mount.js:21:10)
      at Object.<anonymous> (src/components/Dashboard/AReceber/Timeline.test.js:10:17)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        4.698s
Ran all test suites related to changed files.
</code>```

Just because I use Object.entries:

```<code>import React, { Component } from 'react';
import { withStyles } from '@material-ui/core/styles';
import { Col, Row } from 'reactstrap';

import { buttons } from '../../General/styles';

class Timeline extends Component {

    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div className="timeline-fabs">
                <Row>
                    {
                        Object.entries(this.props.months).map((month) => {
                            let onClick = () => {
                                alert(month);
                            };
                            if (month[1]) {
                                return <Col xs={1}>
                                    <button onClick={onClick} className="timeline-button timeline-button-active">
                                        {month}
                                    </button>
                                </Col>
                            }
                            return <Col xs={1}>
                                <button onClick={onClick} className="timeline-button">
                                    {month}
                                </button>
                            </Col>
                        })
                    }
                </Row>
                <div className="timeline-line" />
            </div>
        )
    }
}

export default withStyles(buttons)(Timeline);
</code>```

It makes no sense and I don't know how to avoid it.

EDIT (Showing that the prop is not undefined):

```<code><Timeline months={{
    "Jan": this.mockService.getRandomBoolean(),
    "Fev": this.mockService.getRandomBoolean(),
    "Mar": this.mockService.getRandomBoolean(),
    "Abr": this.mockService.getRandomBoolean(),
    "Mai": this.mockService.getRandomBoolean(),
    "Jun": this.mockService.getRandomBoolean(),
    "Jul": this.mockService.getRandomBoolean(),
    "Ago": this.mockService.getRandomBoolean(),
    "Set": this.mockService.getRandomBoolean(),
    "Out": this.mockService.getRandomBoolean(),
    "Nov": this.mockService.getRandomBoolean(),
    "Dez": this.mockService.getRandomBoolean()
}} />
</code>```

答:
It turns out that @SrAxi (In the comments) was right. It starts as undefined for some reason and then it gets updated with the prop. I came up with an ugly solution:

```<code><Row>
    {
        Object.entries((() => {
            if (this.props.months) {
                return this.props.months
            }
            return {}
        })()).map((month) => {
            let onClick = () => {
                alert(month);
            };
            if (month[1]) {
                return <Col xs={1}>
                    <button onClick={onClick} className="timeline-button timeline-button-active">
                        {month}
                    </button>
                </Col>
            }
            return <Col xs={1}>
                <button onClick={onClick} className="timeline-button">
                    {month}
                </button>
            </Col>
        })
    }
</Row>
</code>```

It's ugly, but it works. I'll leave this answer for future sufferers.

Body:
I don't know what's wrong with jest/enzyme, but it crashes in some really frustrating ways.

import React from 'react';
import Timeline from './Timeline';
import { configure, mount, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });

const wrapper = mount(
    <Timeline/>
);

it('Should render the timeline component.', () => {
    expect(wrapper.find(Timeline)).toHaveLength(1);
});

This simple test raises this error:

TypeError: Cannot convert undefined or null to object
        at Function.entries (<anonymous>)

      17 |                 <Row>
      18 |                     {
    > 19 |                         Object.entries(this.props.months).map((month) => {
         |                                ^
      20 |                             let onClick = () => {
      21 |                                 alert(month);
      22 |                             };

      at Timeline.entries [as render] (src/components/Dashboard/AReceber/Timeline.js:19:32)
      at finishClassComponent (node_modules/react-dom/cjs/react-dom.development.js:14741:31)
      at updateClassComponent (node_modules/react-dom/cjs/react-dom.development.js:14696:24)
      at beginWork (node_modules/react-dom/cjs/react-dom.development.js:15644:16)
      at performUnitOfWork (node_modules/react-dom/cjs/react-dom.development.js:19312:12)
      at workLoop (node_modules/react-dom/cjs/react-dom.development.js:19352:24)
      at renderRoot (node_modules/react-dom/cjs/react-dom.development.js:19435:7)
      at performWorkOnRoot (node_modules/react-dom/cjs/react-dom.development.js:20342:7)
      at requestWork (node_modules/react-dom/cjs/react-dom.development.js:20090:7)
      at scheduleWork (node_modules/react-dom/cjs/react-dom.development.js:19911:5)
      at scheduleRootUpdate (node_modules/react-dom/cjs/react-dom.development.js:20572:3)
      at updateContainerAtExpirationTime (node_modules/react-dom/cjs/react-dom.development.js:20600:10)
      at updateContainer (node_modules/react-dom/cjs/react-dom.development.js:20657:10)
      at ReactRoot.Object.<anonymous>.ReactRoot.render (node_modules/react-dom/cjs/react-dom.development.js:20953:3)
      at node_modules/react-dom/cjs/react-dom.development.js:21090:14
      at unbatchedUpdates (node_modules/react-dom/cjs/react-dom.development.js:20454:14)
      at legacyRenderSubtreeIntoContainer (node_modules/react-dom/cjs/react-dom.development.js:21086:5)
      at Object.render (node_modules/react-dom/cjs/react-dom.development.js:21155:12)
      at render (node_modules/enzyme-adapter-react-16/src/ReactSixteenAdapter.js:425:26)
      at fn (node_modules/enzyme-adapter-react-16/src/ReactSixteenAdapter.js:342:37)
      at Object.batchedUpdates$1 [as unstable_batchedUpdates] (node_modules/react-dom/cjs/react-dom.development.js:20439:12)
      at Object.act (node_modules/react-dom/cjs/react-dom-test-utils.development.js:1161:27)
      at act (node_modules/enzyme-adapter-react-16/src/ReactSixteenAdapter.js:342:13)
      at Object.wrapAct [as render] (node_modules/enzyme-adapter-react-16/src/ReactSixteenAdapter.js:411:16)
      at new ReactWrapper (node_modules/enzyme/build/ReactWrapper.js:134:16)
      at mount (node_modules/enzyme/build/mount.js:21:10)
      at Object.<anonymous> (src/components/Dashboard/AReceber/Timeline.test.js:10:17)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        4.698s
Ran all test suites related to changed files.

Just because I use Object.entries:

import React, { Component } from 'react';
import { withStyles } from '@material-ui/core/styles';
import { Col, Row } from 'reactstrap';

import { buttons } from '../../General/styles';

class Timeline extends Component {

    constructor(props) {
        super(props);
    }

    render() {
        return (

                <Row>
                    {
                        Object.entries(this.props.months).map((month) => {
                            let onClick = () => {
                                alert(month);
                            };
                            if (month[1]) {
                                return <Col xs={1}>
                                    <button onClick={onClick} className="timeline-button timeline-button-active">
                                        {month}
                                    </button>
                                </Col>
                            }
                            return <Col xs={1}>
                                <button onClick={onClick} className="timeline-button">
                                    {month}
                                </button>
                            </Col>
                        })
                    }
                </Row>

        )
    }
}

export default withStyles(buttons)(Timeline);

It makes no sense and I don't know how to avoid it.

EDIT (Showing that the prop is not undefined):

<Timeline months={{
    "Jan": this.mockService.getRandomBoolean(),
    "Fev": this.mockService.getRandomBoolean(),
    "Mar": this.mockService.getRandomBoolean(),
    "Abr": this.mockService.getRandomBoolean(),
    "Mai": this.mockService.getRandomBoolean(),
    "Jun": this.mockService.getRandomBoolean(),
    "Jul": this.mockService.getRandomBoolean(),
    "Ago": this.mockService.getRandomBoolean(),
    "Set": this.mockService.getRandomBoolean(),
    "Out": this.mockService.getRandomBoolean(),
    "Nov": this.mockService.getRandomBoolean(),
    "Dez": this.mockService.getRandomBoolean()
}} />

Body:
It turns out that @SrAxi (In the comments) was right. It starts as undefined for some reason and then it gets updated with the prop. I came up with an ugly solution:

<Row>
    {
        Object.entries((() => {
            if (this.props.months) {
                return this.props.months
            }
            return {}
        })()).map((month) => {
            let onClick = () => {
                alert(month);
            };
            if (month[1]) {
                return <Col xs={1}>
                    <button onClick={onClick} className="timeline-button timeline-button-active">
                        {month}
                    </button>
                </Col>
            }
            return <Col xs={1}>
                <button onClick={onClick} className="timeline-button">
                    {month}
                </button>
            </Col>
        })
    }
</Row>

It's ugly, but it works. I'll leave this answer for future sufferers.


问:
How to trigger JAWS text-to-speech on button click?
My company is doing some ADA conformance revision. I need to have the button text read when the user interacts with it. Will that happen with aria-label or .. how do you do it?

答: A Screen Reader will announce the title of the button when it comes into tab focus, and let the user know that it's a button to begin with. As a base requirement though, a native <button> element should be used since the functionality is already built in. With that said, you don't need any other particular aria tags by default.


问:
Substring Regular Expression for occurence
I want to select part of the string which occurs after the first underline _ and before the second, third or whatever amount of underlines _ occur in a string.

For example I have strings such as:

```<code>75618_LORIK1_2_BABA_ODD_GENERIC
19_GENTRIT3_CC_DD_FF_BROWSERTC
75618_BETIM2
</code>```

Output should be:

```<code>LORIK1
GENTRIT3
BETIM2
</code>```

I cant seem to find some kind of expression of substring to get that part, I tried using:

```<code>SELECT SUBSTR(COLNAME, 0, INSTR(COLNAME, '_')-1) FROM DUAL;
</code>```

But it seems to get only the part before the first occurrence of '_'.

答:
Here's one way to do this with regular expressions.</p>

```<code>with
  test_data (str) as (
    select '75618_LORIK1_2_BABA_ODD_GENERIC' from dual union all
    select '19_GENTRIT3_CC_DD_FF_BROWSERTC'  from dual union all
    select '75618_BETIM2'                    from dual union all
    select 'NO UNDERLINES HERE'              from dual
  )
select str, regexp_substr(str, '[^_]*', 1, 3) as second_token
from   test_data
;

STR                             SECOND_TOKEN
------------------------------- -------------------------------
75618_LORIK1_2_BABA_ODD_GENERIC LORIK1
19_GENTRIT3_CC_DD_FF_BROWSERTC  GENTRIT3
75618_BETIM2                    BETIM2
NO UNDERLINES HERE
</code>```

Body:
I want to select part of the string which occurs after the first underline _ and before the second, third or whatever amount of underlines _ occur in a string.

For example I have strings such as:

75618_LORIK1_2_BABA_ODD_GENERIC
19_GENTRIT3_CC_DD_FF_BROWSERTC
75618_BETIM2

Output should be:

LORIK1
GENTRIT3
BETIM2

I cant seem to find some kind of expression of substring to get that part, I tried using:

SELECT SUBSTR(COLNAME, 0, INSTR(COLNAME, '_')-1) FROM DUAL;

But it seems to get only the part before the first occurrence of '_'.

Body:
Here's one way to do this with regular expressions.

with
  test_data (str) as (
    select '75618_LORIK1_2_BABA_ODD_GENERIC' from dual union all
    select '19_GENTRIT3_CC_DD_FF_BROWSERTC'  from dual union all
    select '75618_BETIM2'                    from dual union all
    select 'NO UNDERLINES HERE'              from dual
  )
select str, regexp_substr(str, '[^_]*', 1, 3) as second_token
from   test_data
;

STR                             SECOND_TOKEN
------------------------------- -------------------------------
75618_LORIK1_2_BABA_ODD_GENERIC LORIK1
19_GENTRIT3_CC_DD_FF_BROWSERTC  GENTRIT3
75618_BETIM2                    BETIM2
NO UNDERLINES HERE


问:
Where I can find passport keys in Laravel?
I generated a keys using the Laravel command php artisan passport:keys but I don't know where I can find it.

答:
The default path is storage folder.

There are two files with the following names:

```<code>oauth-private.key

oauth-public.key
</code>```

Laravel version: 5.8

Body:
The default path is storage folder.

There are two files with the following names:

oauth-private.key

oauth-public.key

Laravel version: 5.8


问:
How to update a column in one dataframe based on another dataframe?
I am needing to see how to update one column in a data frame where the employeeID matches that of another data frame.

For example:

```<code>df1 >

empID     salary
1         10000
2         15000
3         0

df2 >

empID     salary2
1         10000
2         15000
3         20000
</code>```

I am needing to see how to update it where df1$salary = 0, then update it where df1$empID = df2$empID.

I tried this but received "No such column: salary2" error :

```<code>df1$salary <- ifelse(df1$salary == 0,sqldf("UPDATE df1 SET salary = salary2 WHERE df1.empID = df2.empID"),df1$salary)
</code>```

答:
We could do

```<code>#find empID in df1 where salary is 0
inds <- df1$empID[df1$salary == 0]

#match empID with df2 and get respective salary and update df1
df1$salary[inds] <- df2$salary2[match(inds, df2$empID)]
df1
#  empID salary
#1     1  10000
#2     2  15000
#3     3  20000
</code>```

This should also work if you have multiple entries with 0 in df1.

We can do the same using ifelse like

```<code>ifelse(df1$salary == 0, df2$salary2[match(df1$empID, df2$empID)], df1$salary)
</code>```

Body:
I am needing to see how to update one column in a data frame where the employeeID matches that of another data frame.

For example:

df1 >

empID     salary
1         10000
2         15000
3         0

df2 >

empID     salary2
1         10000
2         15000
3         20000

I am needing to see how to update it where df1$salary = 0, then update it where df1$empID = df2$empID.

I tried this but received "No such column: salary2" error :

df1$salary <- ifelse(df1$salary == 0,sqldf("UPDATE df1 SET salary = salary2 WHERE df1.empID = df2.empID"),df1$salary)

Body:
We could do

#find empID in df1 where salary is 0
inds <- df1$empID[df1$salary == 0]

#match empID with df2 and get respective salary and update df1
df1$salary[inds] <- df2$salary2[match(inds, df2$empID)]
df1
#  empID salary
#1     1  10000
#2     2  15000
#3     3  20000

This should also work if you have multiple entries with 0 in df1.

We can do the same using ifelse like

ifelse(df1$salary == 0, df2$salary2[match(df1$empID, df2$empID)], df1$salary)


问:
Encoding is happening while sending parameter from Post request in Jmeter
I have a Post request in Jmeter in which, ViewState parameter is passing but value for that parameter is combination of alphabates, number, special characters . so while send that parameter request is encoding the special character for e.g. i have forward slash in paramter so while sending it is converting it to %2F and that leads in failing the request

Solution i have tried is:

uncheck URL Encode check box

UTF-8 in content encoding

for ViewState providing ${__urldecode('${viewState}')} value as Parameter value, which(viewState) i am fetching from previous response

used replace function in Parameter value

So what i am expecting is while sending Post request parameters should not get encoded.
Can someone please provide solution

答:
I am assuming that you are trying to correlate the variable in the body of the subsequent request(2nd Request).
Try sending the data in "Body Data" instead of parameters. So, it is your variable i.e ${viewState} in "Body Data"

I hope view state is not in the URL.
Hope this helps.


问:
R Loop code over several lists of dataframes
I have several lists of dataframes and I want to format the date in each single dataframe within all lists of dataframes. Here is an example code:

```<code>v1 = c("2000-05-01", "2000-05-02", "2000-05-03", "2000-05-04", "2000-05-05")
v2 = seq(2,20, length = 5)
v3 = seq(-2,7, length = 5)
v4 = seq(-6,3, length = 5)

df1 = data.frame(Date = v1, df1_Tmax = v2, df1_Tmean = v3, df1_Tmin = v4)
dfl1 <- list(df1, df1, df1, df1)
names(dfl1) = c("ABC_1", "DEF_1", "GHI_1", "JKL_1")

v1 = c("2000-05-01", "2000-05-02", "2000-05-03", "2000-05-04", "2000-05-05")
v2 = seq(3,21, length = 5)
v3 = seq(-3,8, length = 5)
v4 = seq(-7,4, length = 5)

df2 = data.frame(Date = v1, df2_Tmax = v2, df2_Tmean = v3, df2_Tmin = v4)
dfl2 <- list(df2, df2, df2, df2)
names(dfl2) = c("ABC_2", "DEF_2", "GHI_2", "JKL_2")

v1 = c("2000-05-01", "2000-05-02", "2000-05-03", "2000-05-04", "2000-05-05")
v2 = seq(4,22, length = 5)
v3 = seq(-4,9, length = 5)
v4 = seq(-8,5, length = 5)

df3 = data.frame(Date = v1, df3_Tmax = v2, df3_Tmean = v3, df3_Tmin = v4)
dfl3 <- list(df3, df3, df3, df3)
names(dfl3) = c("ABC_3", "DEF_3", "GHI_3", "JKL_3")

v1 = c("2000-05-01", "2000-05-02", "2000-05-03", "2000-05-04", "2000-05-05")
v2 = seq(2,20, length = 5)
v3 = seq(-2,8, length = 5)
v4 = seq(-6,3, length = 5)

abc = data.frame(Date = v1, ABC_Tmax = v2, ABC_Tmean = v3, ABC_Tmin = v4)

abclist <-list(abc, abc, abc, abc)

names(abclist) = c("ABC_abc", "DEF_abc", "GHI_abc", "JKL_abc")
</code>```

I know how to change the date-column manually:

```<code>dfl1$ABC_1$Date = as.Date(dfl1$ABC_1$Date,format="%Y-%m-%d")
class(dfl1$ABC_1$Date)
</code>```

But how can I do that for each single Date-Column in all of my lists of dataframes?

答:
Here is one option using get and assign

```<code>nms <- c('dfl1', 'dfl2', 'dfl3', 'abclist')
lapply(nms, function(x) assign(x,lapply(get(x),
                                 function(y) {y$Date1 <- as.Date(y$Date, format="%Y-%m-%d")
                                 return(y)}),
                        envir = .GlobalEnv))
</code>```

PS: Be careful with assign since it will change your global environment .GlobalEnv. Many R users will suggest the list solution over assign.

Body:
I have several lists of dataframes and I want to format the date in each single dataframe within all lists of dataframes. Here is an example code:

v1 = c("2000-05-01", "2000-05-02", "2000-05-03", "2000-05-04", "2000-05-05")
v2 = seq(2,20, length = 5)
v3 = seq(-2,7, length = 5)
v4 = seq(-6,3, length = 5)

df1 = data.frame(Date = v1, df1_Tmax = v2, df1_Tmean = v3, df1_Tmin = v4)
dfl1 <- list(df1, df1, df1, df1)
names(dfl1) = c("ABC_1", "DEF_1", "GHI_1", "JKL_1")

v1 = c("2000-05-01", "2000-05-02", "2000-05-03", "2000-05-04", "2000-05-05")
v2 = seq(3,21, length = 5)
v3 = seq(-3,8, length = 5)
v4 = seq(-7,4, length = 5)

df2 = data.frame(Date = v1, df2_Tmax = v2, df2_Tmean = v3, df2_Tmin = v4)
dfl2 <- list(df2, df2, df2, df2)
names(dfl2) = c("ABC_2", "DEF_2", "GHI_2", "JKL_2")

v1 = c("2000-05-01", "2000-05-02", "2000-05-03", "2000-05-04", "2000-05-05")
v2 = seq(4,22, length = 5)
v3 = seq(-4,9, length = 5)
v4 = seq(-8,5, length = 5)

df3 = data.frame(Date = v1, df3_Tmax = v2, df3_Tmean = v3, df3_Tmin = v4)
dfl3 <- list(df3, df3, df3, df3)
names(dfl3) = c("ABC_3", "DEF_3", "GHI_3", "JKL_3")

v1 = c("2000-05-01", "2000-05-02", "2000-05-03", "2000-05-04", "2000-05-05")
v2 = seq(2,20, length = 5)
v3 = seq(-2,8, length = 5)
v4 = seq(-6,3, length = 5)

abc = data.frame(Date = v1, ABC_Tmax = v2, ABC_Tmean = v3, ABC_Tmin = v4)

abclist <-list(abc, abc, abc, abc)

names(abclist) = c("ABC_abc", "DEF_abc", "GHI_abc", "JKL_abc")

I know how to change the date-column manually:

dfl1$ABC_1$Date = as.Date(dfl1$ABC_1$Date,format="%Y-%m-%d")
class(dfl1$ABC_1$Date)

But how can I do that for each single Date-Column in all of my lists of dataframes?

Body:
Here is one option using get and assign

nms <- c('dfl1', 'dfl2', 'dfl3', 'abclist')
lapply(nms, function(x) assign(x,lapply(get(x),
                                 function(y) {y$Date1 <- as.Date(y$Date, format="%Y-%m-%d")
                                 return(y)}),
                        envir = .GlobalEnv))

PS: Be careful with assign since it will change your global environment .GlobalEnv. Many R users will suggest the list solution over assign.


问:
Why is my Apps Script deletion loop running so slowly? Can I improve performance?
My company collects manufacturing data a few dozen times a day through Google Form responses. Right now the Sheet I'll be referencing is near 10,000 rows. Recently I frankensteined some Google Apps Script code (from other SO threads and forums) to delete rows from a large spreadsheet that are older than 7 days. During trials (on a copy of the Sheet) the script deleted 3-4 rows per second. Now, the code is deleting only one row every 7-8 seconds. I don't know why my code is running so slowly. Is there something wrong with my loop?

I've tried this code on a couple of other Sheets during development and it worked perfectly fine. When the script was first applied to the target Sheet it operated as expected. However, when I went to run it again a few days ago the script executed extremely slowly.

The function that deletes the rows is triggered by a custom menu option that is loaded once the Sheet is opened in the browser.

```<code>function onOpen() {
  SpreadsheetApp.getUi()
                .createMenu('Delete')
                .addItem('Delete Rows Older than 7 Days', 'deleteOldEntries')
                .addToUi();
}

function deleteOldEntries() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Form Responses 1");    //name of the sheet
  //var sheet = ss.getActiveSheet();
  var datarange = sheet.getDataRange();
  var lastrow = datarange.getLastRow();
  var values = datarange.getValues();   //get all data in a 2D array

  var currentDate = new Date();   //today
  var weekOld = Date.now() + -7*24*3600*1000;   //for dates longer than 7 days, change only the 7 to a higher number
  for (i=lastrow;i>=2;i--) {
    var tempDate = values[i-1][0];  //2D arrays are organized as [row][column]; arrays are 0 indexed so row1 = values[0] and col12 = [11]
    if ((tempDate!="") && (tempDate <= (weekOld)))
    {
      sheet.deleteRow(i);
    }
  }
}
</code>```

I expect the performance to at least be a few rows per second, but actual performance has slowed to 6-7 rows per minute. The script times out at 30 minutes, which is a preset time limit by Google (if I'm not mistaken).

Thanks in advance!

EDIT: Here is the partial Execution Transcript from the last run of the code (the whole execution transcript was quite long). Almost all entries from the last run, conducted this morning, seem to be just above 4 seconds.

```<code>[19-05-31 08:57:24:875 EDT] Sheet.deleteRow([5681]) [4.048 seconds]
[19-05-31 08:57:29:295 EDT] Sheet.deleteRow([5680]) [4.419 seconds]
[19-05-31 08:57:34:013 EDT] Sheet.deleteRow([5679]) [4.718 seconds]
[19-05-31 08:57:38:561 EDT] Sheet.deleteRow([5678]) [4.547 seconds]
[19-05-31 08:57:42:991 EDT] Sheet.deleteRow([5677]) [4.43 seconds]
[19-05-31 08:57:47:599 EDT] Sheet.deleteRow([5676]) [4.607 seconds]
[19-05-31 08:57:52:122 EDT] Sheet.deleteRow([5675]) [4.522 seconds]
[19-05-31 08:57:56:683 EDT] Sheet.deleteRow([5674]) [4.56 seconds]
[19-05-31 08:58:00:950 EDT] Sheet.deleteRow([5673]) [4.266 seconds]
[19-05-31 08:58:05:450 EDT] Sheet.deleteRow([5672]) [4.5 seconds]
[19-05-31 08:58:10:349 EDT] Sheet.deleteRow([5671]) [4.898 seconds]
[19-05-31 08:58:14:736 EDT] Sheet.deleteRow([5670]) [4.387 seconds]
[19-05-31 08:58:19:697 EDT] Sheet.deleteRow([5669]) [4.96 seconds]
[19-05-31 08:58:28:412 EDT] Sheet.deleteRow([5668]) [8.714 seconds]
[19-05-31 08:58:33:601 EDT] Sheet.deleteRow([5667]) [5.189 seconds]
[19-05-31 08:58:38:845 EDT] Sheet.deleteRow([5666]) [5.243 seconds]
[19-05-31 08:58:43:313 EDT] Sheet.deleteRow([5665]) [4.468 seconds]
[19-05-31 08:58:47:964 EDT] Sheet.deleteRow([5664]) [4.65 seconds]
[19-05-31 08:58:52:947 EDT] Sheet.deleteRow([5663]) [4.982 seconds]
[19-05-31 08:58:58:172 EDT] Sheet.deleteRow([5662]) [5.223 seconds]
[19-05-31 08:59:03:036 EDT] Sheet.deleteRow([5661]) [4.864 seconds]
[19-05-31 08:59:07:957 EDT] Sheet.deleteRow([5660]) [4.92 seconds]
[19-05-31 08:59:12:727 EDT] Sheet.deleteRow([5659]) [4.769 seconds]
[19-05-31 08:59:12:800 EDT] Execution failed: Exceeded maximum execution time [1,803.124 seconds total runtime]
</code>```

答:
You need to use batch operations: Batch up contiguous rows in the non-contiguous range. If you need to delete 1,2,3,4,6,7,8 rows, instead of making 8 delete calls, you can batch up [1-4] and [6-8] and make two delete calls.

Snippet:

```<code>  var thisBatch = 0;//added
  for (i=lastrow;i>=2;i--) {
    var tempDate = values[i-1][0];
    if ((tempDate!="") && (tempDate <= (weekOld)))
    {
        ++thisBatch;//increment this batch
    } else if(thisBatch){ // previous batch ended
        sheet.deleteRows(i+1, thisBatch); //delete next row and all of that batch
        thisBatch = 0;
    }
  }
 thisBatch ? sheet.deleteRows(i+1, thisBatch) : null;//to remove any batch after remaining after end of loop
</code>```

If that's still slow, you need to use Advanced Google services to access the sheets api and issue  Delete Dimension Request. Also trim your sheet by deleting all empty rows at the bottom of the sheet manually.

Body:
My company collects manufacturing data a few dozen times a day through Google Form responses. Right now the Sheet I'll be referencing is near 10,000 rows. Recently I frankensteined some Google Apps Script code (from other SO threads and forums) to delete rows from a large spreadsheet that are older than 7 days. During trials (on a copy of the Sheet) the script deleted 3-4 rows per second. Now, the code is deleting only one row every 7-8 seconds. I don't know why my code is running so slowly. Is there something wrong with my loop?

I've tried this code on a couple of other Sheets during development and it worked perfectly fine. When the script was first applied to the target Sheet it operated as expected. However, when I went to run it again a few days ago the script executed extremely slowly.

The function that deletes the rows is triggered by a custom menu option that is loaded once the Sheet is opened in the browser.

function onOpen() {
  SpreadsheetApp.getUi()
                .createMenu('Delete')
                .addItem('Delete Rows Older than 7 Days', 'deleteOldEntries')
                .addToUi();
}

function deleteOldEntries() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Form Responses 1");    //name of the sheet
  //var sheet = ss.getActiveSheet();
  var datarange = sheet.getDataRange();
  var lastrow = datarange.getLastRow();
  var values = datarange.getValues();   //get all data in a 2D array

  var currentDate = new Date();   //today
  var weekOld = Date.now() + -7*24*3600*1000;   //for dates longer than 7 days, change only the 7 to a higher number
  for (i=lastrow;i>=2;i--) {
    var tempDate = values[i-1][0];  //2D arrays are organized as [row][column]; arrays are 0 indexed so row1 = values[0] and col12 = [11]
    if ((tempDate!="") && (tempDate <= (weekOld)))
    {
      sheet.deleteRow(i);
    }
  }
}

I expect the performance to at least be a few rows per second, but actual performance has slowed to 6-7 rows per minute. The script times out at 30 minutes, which is a preset time limit by Google (if I'm not mistaken).

Thanks in advance!

EDIT: Here is the partial Execution Transcript from the last run of the code (the whole execution transcript was quite long). Almost all entries from the last run, conducted this morning, seem to be just above 4 seconds.

[19-05-31 08:57:24:875 EDT] Sheet.deleteRow([5681]) [4.048 seconds]
[19-05-31 08:57:29:295 EDT] Sheet.deleteRow([5680]) [4.419 seconds]
[19-05-31 08:57:34:013 EDT] Sheet.deleteRow([5679]) [4.718 seconds]
[19-05-31 08:57:38:561 EDT] Sheet.deleteRow([5678]) [4.547 seconds]
[19-05-31 08:57:42:991 EDT] Sheet.deleteRow([5677]) [4.43 seconds]
[19-05-31 08:57:47:599 EDT] Sheet.deleteRow([5676]) [4.607 seconds]
[19-05-31 08:57:52:122 EDT] Sheet.deleteRow([5675]) [4.522 seconds]
[19-05-31 08:57:56:683 EDT] Sheet.deleteRow([5674]) [4.56 seconds]
[19-05-31 08:58:00:950 EDT] Sheet.deleteRow([5673]) [4.266 seconds]
[19-05-31 08:58:05:450 EDT] Sheet.deleteRow([5672]) [4.5 seconds]
[19-05-31 08:58:10:349 EDT] Sheet.deleteRow([5671]) [4.898 seconds]
[19-05-31 08:58:14:736 EDT] Sheet.deleteRow([5670]) [4.387 seconds]
[19-05-31 08:58:19:697 EDT] Sheet.deleteRow([5669]) [4.96 seconds]
[19-05-31 08:58:28:412 EDT] Sheet.deleteRow([5668]) [8.714 seconds]
[19-05-31 08:58:33:601 EDT] Sheet.deleteRow([5667]) [5.189 seconds]
[19-05-31 08:58:38:845 EDT] Sheet.deleteRow([5666]) [5.243 seconds]
[19-05-31 08:58:43:313 EDT] Sheet.deleteRow([5665]) [4.468 seconds]
[19-05-31 08:58:47:964 EDT] Sheet.deleteRow([5664]) [4.65 seconds]
[19-05-31 08:58:52:947 EDT] Sheet.deleteRow([5663]) [4.982 seconds]
[19-05-31 08:58:58:172 EDT] Sheet.deleteRow([5662]) [5.223 seconds]
[19-05-31 08:59:03:036 EDT] Sheet.deleteRow([5661]) [4.864 seconds]
[19-05-31 08:59:07:957 EDT] Sheet.deleteRow([5660]) [4.92 seconds]
[19-05-31 08:59:12:727 EDT] Sheet.deleteRow([5659]) [4.769 seconds]
[19-05-31 08:59:12:800 EDT] Execution failed: Exceeded maximum execution time [1,803.124 seconds total runtime]

Body:
You need to use batch operations: Batch up contiguous rows in the non-contiguous range. If you need to delete 1,2,3,4,6,7,8 rows, instead of making 8 delete calls, you can batch up [1-4] and [6-8] and make two delete calls.

Snippet:

  var thisBatch = 0;//added
  for (i=lastrow;i>=2;i--) {
    var tempDate = values[i-1][0];
    if ((tempDate!="") && (tempDate <= (weekOld)))
    {
        ++thisBatch;//increment this batch
    } else if(thisBatch){ // previous batch ended
        sheet.deleteRows(i+1, thisBatch); //delete next row and all of that batch
        thisBatch = 0;
    }
  }
 thisBatch ? sheet.deleteRows(i+1, thisBatch) : null;//to remove any batch after remaining after end of loop

If that's still slow, you need to use Advanced Google services to access the sheets api and issue  Delete Dimension Request. Also trim your sheet by deleting all empty rows at the bottom of the sheet manually.


问:
Enum Case with Object
How can one get the object inside an emun case? Is it possible without a switch statement?</p>

```<code>enum ItemType {
    case person(Person)
    case dog(Dog)
    case cat(Cat)
}

var items = [ItemType]()

var dog = items[index] // Would like the actual dog object
</code>```

答:
You need to check that you have the right case (since items[index] might be a Cat or a Person, instead).

```<code>let item = items[index]
if case .dog(let dog) = item {
    // use `dog`
}
</code>```

If you plan on accessing this a lot, you could add a computed property on ItemType.

```<code>extension ItemType {
    var dog: Dog? {
        switch self {
        case .dog(let dog): return dog
        default: return nil
        }
    }
}
</code>```

Note that this is optional (since not every ItemType has a dog). But then you could say:

```<code>if let dog = items[index].dog { ... }
</code>```

Title: Enum Case with Object

Body:
How can one get the object inside an emun case? Is it possible without a switch statement?

enum ItemType {
    case person(Person)
    case dog(Dog)
    case cat(Cat)
}

var items = [ItemType]()

var dog = items[index] // Would like the actual dog object

Body:
You need to check that you have the right case (since items[index] might be a Cat or a Person, instead).

let item = items[index]
if case .dog(let dog) = item {
    // use `dog`
}

If you plan on accessing this a lot, you could add a computed property on ItemType.

extension ItemType {
    var dog: Dog? {
        switch self {
        case .dog(let dog): return dog
        default: return nil
        }
    }
}

Note that this is optional (since not every ItemType has a dog). But then you could say:

if let dog = items[index].dog { ... }