问:
Scraping content from infinite scroll website
I am trying to scrape the links in a webpage with infinite scrolling. I am able to fetch only the links on the first pane. How to proceed ahead so as to form a complete list of all the links. Here is what i have so far -

from bs4 import BeautifulSoup
import requests

html = "https://www.carwale.com/used/cars-for-sale/#sc=-1&so=-1&car=7&pn=8&lcr=168&ldr=0&lir=0"
html_content = requests.get(html).text
soup = BeautifulSoup(html_content, "lxml")
table = soup.find_all("div", {"class": "card-detail-block__data"})

y = []
for i in table:
    try:
        y.append(i.find("a", {"id":"linkToDetails"}).get('href'))
    except AttributeError:
        pass

z = [('carwale.com' + item) for item in y]
z
```

答:
You do not need BeautifulSoup to ninja HTML dom at all, as the website provides JSON responses that populated the HTML.  Requests alone can do the work. If you monitor "Network" from Chrome or Firefox Development tool, you will see that for each load, the browser sends a get request to an API. Using that we can get clean json data out.

Disclaimer: I have not checked if this site allows web scraping. Do double check their terms of use. I am assuming that you did that.

I used Pandas, to help in dealing with tabular data and also exporting data to CSV or whatever format you prefer: pip install pandas

import pandas as pd
from requests import Session

# Using Session and a header
req = Session()
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) '\
                         'AppleWebKit/537.36 (KHTML, like Gecko) '\
                         'Chrome/75.0.3770.80 Safari/537.36',
          'Content-Type': 'application/json;charset=UTF-8'}
# Add headers
req.headers.update(headers)

BASE_URL = 'https://www.carwale.com/webapi/classified/stockfilters/'

# Monitoring the updates on Network, the params changes in each load
#sc=-1&so=-1&car=7&pn=1
#sc=-1&so=-1&car=7&pn=2&lcr=24&ldr=0&lir=0
#sc=-1&so=-1&car=7&pn=3&lcr=48&ldr=0&lir=0
#sc=-1&so=-1&car=7&pn=4&lcr=72&ldr=0&lir=0

params = dict(sc=-1, so=-1, car=7, pn=4, lcr=72, ldr=0, lir=0)

r = req.get(BASE_URL, params=params) #just like requests.get

# Check if everything is okay
assert r.ok, 'We did not get 200'

# get json data
data = r.json()

# Put it in DataFrame
df = pd.DataFrame(data['ResultData'])

print(df.head())

# to go to another page create a function:

def scrap_carwale(params):
    r = req.get(BASE_URL, params=params)
    if not r.ok:
        raise ConnectionError('We did not get 200')
    data = r.json()

    return  pd.DataFrame(data['ResultData'])

# Just first 5 pages :)
for i in range(5):
    params['pn']+=1
    params['lcr']*=2

    dt = scrap_carwale(params)
    #append your data
    df = df.append(dt)

#print data sample
print(df.sample(10)

# Save data to csv or whatever format
df.to_csv('my_data.csv') #see df.to_?
```

This is the network

Response:

Sample of Results

Body:
You do not need BeautifulSoup to ninja HTML dom at all, as the website provides JSON responses that populated the HTML.  Requests alone can do the work. If you monitor "Network" from Chrome or Firefox Development tool, you will see that for each load, the browser sends a get request to an API. Using that we can get clean json data out.

Disclaimer: I have not checked if this site allows web scraping. Do double check their terms of use. I am assuming that you did that.

I used Pandas, to help in dealing with tabular data and also exporting data to CSV or whatever format you prefer: pip install pandas

import pandas as pd
from requests import Session

# Using Session and a header
req = Session()
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) '\
                         'AppleWebKit/537.36 (KHTML, like Gecko) '\
                         'Chrome/75.0.3770.80 Safari/537.36',
          'Content-Type': 'application/json;charset=UTF-8'}
# Add headers
req.headers.update(headers)

BASE_URL = 'https://www.carwale.com/webapi/classified/stockfilters/'

# Monitoring the updates on Network, the params changes in each load
#sc=-1&so=-1&car=7&pn=1
#sc=-1&so=-1&car=7&pn=2&lcr=24&ldr=0&lir=0
#sc=-1&so=-1&car=7&pn=3&lcr=48&ldr=0&lir=0
#sc=-1&so=-1&car=7&pn=4&lcr=72&ldr=0&lir=0

params = dict(sc=-1, so=-1, car=7, pn=4, lcr=72, ldr=0, lir=0)

r = req.get(BASE_URL, params=params) #just like requests.get

# Check if everything is okay
assert r.ok, 'We did not get 200'

# get json data
data = r.json()

# Put it in DataFrame
df = pd.DataFrame(data['ResultData'])

print(df.head())

# to go to another page create a function:

def scrap_carwale(params):
    r = req.get(BASE_URL, params=params)
    if not r.ok:
        raise ConnectionError('We did not get 200')
    data = r.json()

    return  pd.DataFrame(data['ResultData'])

# Just first 5 pages :)
for i in range(5):
    params['pn']+=1
    params['lcr']*=2

    dt = scrap_carwale(params)
    #append your data
    df = df.append(dt)

#print data sample
print(df.sample(10)

# Save data to csv or whatever format
df.to_csv('my_data.csv') #see df.to_?

This is the network

Response:

Sample of Results


来源: stackexchange

问:
ruby-debug and cucumber
I have a failing scenario in cucumber, and I'd like to debug my rails controller using ruby-debug. But if I add 'debugger' to the point where I want to break, it doesn't stop.

I tried adding require of ruby-debug and rubygems to the features/support/env.rb but then it says to me that it can't load ruby-debug, although ruby-debug is on the gem list and I can load it in irb.

So... what should I do to get it working?

Thanks!

答:
They key here is definitely getting ruby-debug loaded first.

If you're having problems with gems not loading, and the gem is definitely listed in your Gemfile, run cucumber like:

bundle exec cucumber ...

This is often necessary with bundler.

ContentLicense: CC BY-SA 2.5

Title: ruby-debug and cucumber

ContentLicense: CC BY-SA 3.0


问:
Numpy array is modified globally by the function without return
When I use the function that doesn't return anything, the input parameters remain globally unchanged.

For example:

```<code>def func(var):
    var += 1

a = 0

for i in range(3):
    func(a)
    print(a)
</code>```

logically results in

```<code>0
0
0
</code>```

By it doesn't seem to work the same when the input is numpy array:

```<code>import numpy as np

def func(var):
    var += 1

a = np.zeros(3)

for i in range(3):
    func(a)
    print(a)
</code>```

Output:

```<code>[1. 1. 1.]
[2. 2. 2.]
[3. 3. 3.]
</code>```

Thus, all modifications were applied to array globally, not inside the function. Why is it happening? And, more generally, are there any special rules on how to handle np arrays as functions input?

答:
In Python, any value passed to a function is passed by object reference. So, in the first case, where you pass a number to your function, var is set to a reference to the object that reresents the number 1. In Python, even numbers are objects. To icrement var in this case actually means to set it with a reference to the object that represents the number 1+1, which is the object that represents 2. Note that object that represents the number 1 is not changed. Within the function, it is replaced.

When you pass a numpy array to your function it is likewise passed in by object reference. Hence, var now holds a reference to your array a. Incrementing an array by arr += 1 means to add 1 to each of its elements. Hence, the actual content of the object that var references has to change. However, var still references the same object are incrementation.

Take a look at the following code:

```<code>import numpy as np

def func(vals):
    print('Before inc: ', id(vals))
    vals += 1
    print('After inc: ', id(vals))
</code>```

When you pass in a number literal, vals is set to a reference of the object representing the respective number. This object has a unique id, which you can return using the id function. After incrementation, vals is a reference to the object representing a number which is one greater the first one. You can verify that by calling id again after incrementation. So, the output of the above function is something like:

```<code>Before inc:  4351114480
After inc:  4351114512
</code>```

Note that there are two different objects. When now pass in an numpy array like, the resulting ids are the same:

```<code>a = np.zeros(3)
func(a)

Before inc:  4496241408
After inc:  4496241408
</code>```

If you want to modify an array inside of a function and don't want that the apply changes take effect outside of the function, you have to copy your array:

```<code>def func(vals):
    _vals = vals.copy()
    # doing stuff with `_vals` won't change the array passed to `vals`
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When I use the function that doesn't return anything, the input parameters remain globally unchanged.

For example:

def func(var):
    var += 1

a = 0

for i in range(3):
    func(a)
    print(a)

logically results in

0
0
0

By it doesn't seem to work the same when the input is numpy array:

import numpy as np

def func(var):
    var += 1

a = np.zeros(3)

for i in range(3):
    func(a)
    print(a)

Output:

[1. 1. 1.]
[2. 2. 2.]
[3. 3. 3.]

Thus, all modifications were applied to array globally, not inside the function. Why is it happening? And, more generally, are there any special rules on how to handle np arrays as functions input?

Body:
In Python, any value passed to a function is passed by object reference. So, in the first case, where you pass a number to your function, var is set to a reference to the object that reresents the number 1. In Python, even numbers are objects. To icrement var in this case actually means to set it with a reference to the object that represents the number 1+1, which is the object that represents 2. Note that object that represents the number 1 is not changed. Within the function, it is replaced.

When you pass a numpy array to your function it is likewise passed in by object reference. Hence, var now holds a reference to your array a. Incrementing an array by arr += 1 means to add 1 to each of its elements. Hence, the actual content of the object that var references has to change. However, var still references the same object are incrementation.

Take a look at the following code:

import numpy as np

def func(vals):
    print('Before inc: ', id(vals))
    vals += 1
    print('After inc: ', id(vals))

When you pass in a number literal, vals is set to a reference of the object representing the respective number. This object has a unique id, which you can return using the id function. After incrementation, vals is a reference to the object representing a number which is one greater the first one. You can verify that by calling id again after incrementation. So, the output of the above function is something like:

Before inc:  4351114480
After inc:  4351114512

Note that there are two different objects. When now pass in an numpy array like, the resulting ids are the same:

a = np.zeros(3)
func(a)

Before inc:  4496241408
After inc:  4496241408

If you want to modify an array inside of a function and don't want that the apply changes take effect outside of the function, you have to copy your array:

def func(vals):
    _vals = vals.copy()
    # doing stuff with `_vals` won't change the array passed to `vals`


问:
How to speed up multiple str.contains searches for millions of rows?
I have a dataframe of shop names that I'm trying to standardize. Small sample to test here:

```<code>import pandas as pd

df = pd.DataFrame({'store': pd.Series(['McDonalds', 'Lidls', 'Lidl New York 123', 'KFC', 'Lidi Berlin', 'Wallmart LA 90210', 'Aldi', 'London Lidl', 'Aldi627', 'mcdonaldsabc123', 'Mcdonald_s', 'McDonalds12345', 'McDonalds5555', 'McDonalds888', 'Aldi123', 'KFC-786', 'KFC-908', 'McDonalds511', 'GerALDInes Shop'],dtype='object',index=pd.RangeIndex(start=0, stop=19, step=1)), 'standard': pd.Series([pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan],dtype='float64',index=pd.RangeIndex(start=0, stop=19, step=1))}, index=pd.RangeIndex(start=0, stop=19, step=1))

                store  standard
0           McDonalds       NaN
1               Lidls       NaN
2   Lidl New York 123       NaN
3                 KFC       NaN
4         Lidi Berlin       NaN
5   Wallmart LA 90210       NaN
6                Aldi       NaN
7         London Lidl       NaN
8             Aldi627       NaN
9     mcdonaldsabc123       NaN
10         Mcdonald_s       NaN
11     McDonalds12345       NaN
12      McDonalds5555       NaN
13       McDonalds888       NaN
14            Aldi123       NaN
15            KFC-786       NaN
16            KFC-908       NaN
17       McDonalds511       NaN
18    GerALDInes Shop       NaN
</code>```

I set up a regex dictionary to search for a string, and insert a standardized version of the shop name into the column standard. This works fine for this small dataframe:

```<code># set up the dictionary
regex_dict = {
 "McDonalds": r'(mcdonalds|mcdonald_s)',
 "Lidl" : r'(lidl|lidi)',
 "Wallmart":r'wallmart',
 "KFC": r'KFC',
 "Aldi":r'(\baldi\b|\baldi\d+)'
}

# loop through dictionary, using str.replace
for regname, regex_formula in regex_dict.items():

    df.loc[df['store'].str.contains(regex_formula,na=False,flags=re.I), 'standard'] = regname

print(df)

                store   standard
0           McDonalds  McDonalds
1               Lidls       Lidl
2   Lidl New York 123       Lidl
3                 KFC        KFC
4         Lidi Berlin       Lidl
5   Wallmart LA 90210   Wallmart
6                Aldi       Aldi
7         London Lidl       Lidl
8             Aldi627       Aldi
9     mcdonaldsabc123  McDonalds
10         Mcdonald_s  McDonalds
11     McDonalds12345  McDonalds
12      McDonalds5555  McDonalds
13       McDonalds888  McDonalds
14            Aldi123       Aldi
15            KFC-786        KFC
16            KFC-908        KFC
17       McDonalds511  McDonalds
18    GerALDInes Shop        NaN
</code>```

The problem is I have about SIX million rows to standardize, with a regex dictionary much larger than the one shown here. (many different shop names with some mispellings etc.)

What I would like to do is at each loop, only use str.contains for rows that have not been standardized, and ignore the rows that have been standardized. The idea is to reduce the search space with each loop, therefore reducing the overall processing time.

I have tested indexing by the standard column, only performing str.contains on rows where standard is Nan, but it does not result in any real speedup. It still takes time to figure out which rows are Nan before applying str.contains.

Here is what I tried to reduce the processing time each loop:

```<code>for regname, regex_formula in regex_dict.items():

    # only apply str.contains to rows where standard == NAN
    df.loc[df['standard'].isnull() & df['store'].str.contains(regex_formula,na=False,flags=re.I), 'standard'] = regname
</code>```

This works .. but using this on my full 6 million rows makes no real difference in speed.

Is it even possible to speed this up on a dataframe of 6 million rows?

答:
I managed to reduced the time needed by 40% using this. Best I could do

I create an empty dataframe called fixed_df to append new standardized rows, then delete the same rows in the original dataframe at the end of each loop. The search space is reduced for each loop as each shop is standardized, and the fixed_df increases in size with each loop. In the end, fixed_df should have all the original rows, now standardized, and the original df should be empty.

```<code># create empty df to store new results
fixed_df = pd.DataFrame()

# loop through dictionary
for regname, regex_formula in regex_dict.items():

    # search for regex formula, add standardized name into standard column
    df.loc[df['term_location'].str.contains(regex_formula,na=False,flags=re.I), 'standard'] = regname

    # get index of where names were fixed
    ind = df[df['standard']==regname].index

    # append fixed data to new df
    fixed_df.append(df[df.index.isin(ind)].copy())

    # remove processed stuff from original df
    df = df[~df.index.isin(ind)].copy()
</code>```

Body:
I have a dataframe of shop names that I'm trying to standardize. Small sample to test here:

import pandas as pd

df = pd.DataFrame({'store': pd.Series(['McDonalds', 'Lidls', 'Lidl New York 123', 'KFC', 'Lidi Berlin', 'Wallmart LA 90210', 'Aldi', 'London Lidl', 'Aldi627', 'mcdonaldsabc123', 'Mcdonald_s', 'McDonalds12345', 'McDonalds5555', 'McDonalds888', 'Aldi123', 'KFC-786', 'KFC-908', 'McDonalds511', 'GerALDInes Shop'],dtype='object',index=pd.RangeIndex(start=0, stop=19, step=1)), 'standard': pd.Series([pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan, pd.np.nan],dtype='float64',index=pd.RangeIndex(start=0, stop=19, step=1))}, index=pd.RangeIndex(start=0, stop=19, step=1))

                store  standard
0           McDonalds       NaN
1               Lidls       NaN
2   Lidl New York 123       NaN
3                 KFC       NaN
4         Lidi Berlin       NaN
5   Wallmart LA 90210       NaN
6                Aldi       NaN
7         London Lidl       NaN
8             Aldi627       NaN
9     mcdonaldsabc123       NaN
10         Mcdonald_s       NaN
11     McDonalds12345       NaN
12      McDonalds5555       NaN
13       McDonalds888       NaN
14            Aldi123       NaN
15            KFC-786       NaN
16            KFC-908       NaN
17       McDonalds511       NaN
18    GerALDInes Shop       NaN

I set up a regex dictionary to search for a string, and insert a standardized version of the shop name into the column standard. This works fine for this small dataframe:

# set up the dictionary
regex_dict = {
 "McDonalds": r'(mcdonalds|mcdonald_s)',
 "Lidl" : r'(lidl|lidi)',
 "Wallmart":r'wallmart',
 "KFC": r'KFC',
 "Aldi":r'(\baldi\b|\baldi\d+)'
}

# loop through dictionary, using str.replace
for regname, regex_formula in regex_dict.items():

    df.loc[df['store'].str.contains(regex_formula,na=False,flags=re.I), 'standard'] = regname

print(df)

                store   standard
0           McDonalds  McDonalds
1               Lidls       Lidl
2   Lidl New York 123       Lidl
3                 KFC        KFC
4         Lidi Berlin       Lidl
5   Wallmart LA 90210   Wallmart
6                Aldi       Aldi
7         London Lidl       Lidl
8             Aldi627       Aldi
9     mcdonaldsabc123  McDonalds
10         Mcdonald_s  McDonalds
11     McDonalds12345  McDonalds
12      McDonalds5555  McDonalds
13       McDonalds888  McDonalds
14            Aldi123       Aldi
15            KFC-786        KFC
16            KFC-908        KFC
17       McDonalds511  McDonalds
18    GerALDInes Shop        NaN

The problem is I have about SIX million rows to standardize, with a regex dictionary much larger than the one shown here. (many different shop names with some mispellings etc.)

What I would like to do is at each loop, only use str.contains for rows that have not been standardized, and ignore the rows that have been standardized. The idea is to reduce the search space with each loop, therefore reducing the overall processing time.

I have tested indexing by the standard column, only performing str.contains on rows where standard is Nan, but it does not result in any real speedup. It still takes time to figure out which rows are Nan before applying str.contains.

Here is what I tried to reduce the processing time each loop:

for regname, regex_formula in regex_dict.items():

    # only apply str.contains to rows where standard == NAN
    df.loc[df['standard'].isnull() & df['store'].str.contains(regex_formula,na=False,flags=re.I), 'standard'] = regname

This works .. but using this on my full 6 million rows makes no real difference in speed.

Is it even possible to speed this up on a dataframe of 6 million rows?

Body:
I managed to reduced the time needed by 40% using this. Best I could do

I create an empty dataframe called fixed_df to append new standardized rows, then delete the same rows in the original dataframe at the end of each loop. The search space is reduced for each loop as each shop is standardized, and the fixed_df increases in size with each loop. In the end, fixed_df should have all the original rows, now standardized, and the original df should be empty.

# create empty df to store new results
fixed_df = pd.DataFrame()

# loop through dictionary
for regname, regex_formula in regex_dict.items():

    # search for regex formula, add standardized name into standard column
    df.loc[df['term_location'].str.contains(regex_formula,na=False,flags=re.I), 'standard'] = regname

    # get index of where names were fixed
    ind = df[df['standard']==regname].index

    # append fixed data to new df
    fixed_df.append(df[df.index.isin(ind)].copy())

    # remove processed stuff from original df
    df = df[~df.index.isin(ind)].copy()


问:
Can I declare TypeScript interfaces in a separated file and use it without ever importing it?
Right now I have to either declare interface right where I use it or import {ISomeInterface} from './somePlace'. Is there a way to just declare interfaces in something.interface.ts files and use those interfaces without importing them?

E.g. i'm not importing @types/node to use interfaces declared in the @types/node, right? I'd like to do it with custom interfaces too.

答:
You can declare the types globally. If you declare a ts or d.ts file, that does not export anything and does not use any import statement then your file will be treated add adding to the global scope. You can use import types if you need to access types from modules, using import('moduleName').Type.

You could also use declare global inside a file that does contain imports:

```<code>import { Type } from 'module'
declare global {
    interface GlobalInterface {
        o: Type
    }
}
</code>```

Body:
You can declare the types globally. If you declare a ts or d.ts file, that does not export anything and does not use any import statement then your file will be treated add adding to the global scope. You can use import types if you need to access types from modules, using import('moduleName').Type.

You could also use declare global inside a file that does contain imports:

import { Type } from 'module'
declare global {
    interface GlobalInterface {
        o: Type
    }
}


问:
Save data into an email:
Save data from edit texts, text views, spinner selections, and checkboxes from multiple activities into an email:

I am already using:

```<code>Intent EmailSend = new Intent(android.content.Intent.ACTION_SEND);
    EmailSend.setType("plain/text");
    EmailSend.putExtra(android.content.Intent.EXTRA_TEXT,
      "Pretext"+edittext.getText().toString());
</code>```

the put string is not working for items not listed in the .java
When I use the last line in that i get error saying -edittext cannot resolved-

and how to get data from checkbox & spinner

I will have 80 or so items to compile to this email over 8 activities

答:
I wrote a snippet to automate it a little:</p>

```<code>ViewGroup     root = (ViewGroup) ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
StringBuilder str  = new StringBuilder();

public void extractText(ViewGroup root, StringBuilder str){
    int count = root.getChildCount();
    for(int i = 0; i < count; i++) {
        View v = root.getChildAt(i);

        if(v instanceof Spinner) {
            str.append(i).append(" Spinner: ").append(((Spinner) v).getSelectedItem());
        } else if(v instanceof TextView) {
            str.append(i).append(" TextView: ").append(((TextView) v).getText());
        } else if(v instanceof CheckBox) {
            str.append(i).append(" Checkbox: ").append(((CheckBox) v).isChecked());
        }else if(v instanceof ViewGroup){
            extractText((ViewGroup)v, str);
        }
    }
}
</code>```

Title: Save data into an email:

Body:
Save data from edit texts, text views, spinner selections, and checkboxes from multiple activities into an email:

I am already using:

Intent EmailSend = new Intent(android.content.Intent.ACTION_SEND);
    EmailSend.setType("plain/text");
    EmailSend.putExtra(android.content.Intent.EXTRA_TEXT,
      "Pretext"+edittext.getText().toString());

the put string is not working for items not listed in the .java
When I use the last line in that i get error saying -edittext cannot resolved-

and how to get data from checkbox & spinner

I will have 80 or so items to compile to this email over 8 activities

Body:
I wrote a snippet to automate it a little:

ViewGroup     root = (ViewGroup) ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
StringBuilder str  = new StringBuilder();

public void extractText(ViewGroup root, StringBuilder str){
    int count = root.getChildCount();
    for(int i = 0; i < count; i++) {
        View v = root.getChildAt(i);

        if(v instanceof Spinner) {
            str.append(i).append(" Spinner: ").append(((Spinner) v).getSelectedItem());
        } else if(v instanceof TextView) {
            str.append(i).append(" TextView: ").append(((TextView) v).getText());
        } else if(v instanceof CheckBox) {
            str.append(i).append(" Checkbox: ").append(((CheckBox) v).isChecked());
        }else if(v instanceof ViewGroup){
            extractText((ViewGroup)v, str);
        }
    }
}


问:
COUNT DISTINCT WHERE JOIN in one query php mysql
I'm beginner in PHP,

How Making COUNT DISTINCT JOIN and Multiple WHERE in one query ?
for output to json

I tried

```<code><?php
require_once "../conn.php";
$query = "SELECT
COUNT(DISTINCT tbl_trx.idoutlet WHERE (tbl_trx.payone != 0)) as p1
COUNT(DISTINCT tbl_trx.idoutlet WHERE (tbl_trx.paytwo != 0)) as p2
COUNT(DISTINCT tbl_trx.idoutlet WHERE (tbl_trx.paythree != 0)) as p3
FROM tbl_outlet
INNER JOIN tbl_trx ON tbl_trx.idoutlet = tbl_outlet.id
WHERE id = $_GET[id]";
$sql = mysqli_query ($link,$query);
$ray = array();
while ($row = mysqli_fetch_array($sql)) {
  array_push($ray, array(
    "payone" => $row['p1'],
    "paytwo" => $row['p2'],
    "paythree" => $row['p3'],
  ));
}
echo json_encode($ray);
mysqli_close($link);
?>
</code>```

But Doesnt Work
Please Help

答:
You should avoid  php var is sql and use param and a case for filter </p>

```<code>select  count ( DISTINCT CASE WHEN tbl_trx.payone != 0 THEN tbl_trx.idoutlet ELSE NULL END) p1
, count ( DISTINCT CASE WHEN tbl_trx.paytwo != 0 THEN tbl_trx.idoutlet ELSE NULL END) p2
, count ( DISTINCT CASE WHEN tbl_trx.paythree != 0 THEN tbl_trx.idoutlet ELSE NULL END) p3
FROM tbl_outlet
INNER JOIN tbl_trx ON tbl_trx.idoutlet = tbl_outlet.id
WHERE id = :id
</code>```

Body:
I'm beginner in PHP,

How Making COUNT DISTINCT JOIN and Multiple WHERE in one query ?
for output to json

I tried

<?php
require_once "../conn.php";
$query = "SELECT
COUNT(DISTINCT tbl_trx.idoutlet WHERE (tbl_trx.payone != 0)) as p1
COUNT(DISTINCT tbl_trx.idoutlet WHERE (tbl_trx.paytwo != 0)) as p2
COUNT(DISTINCT tbl_trx.idoutlet WHERE (tbl_trx.paythree != 0)) as p3
FROM tbl_outlet
INNER JOIN tbl_trx ON tbl_trx.idoutlet = tbl_outlet.id
WHERE id = $_GET[id]";
$sql = mysqli_query ($link,$query);
$ray = array();
while ($row = mysqli_fetch_array($sql)) {
  array_push($ray, array(
    "payone" => $row['p1'],
    "paytwo" => $row['p2'],
    "paythree" => $row['p3'],
  ));
}
echo json_encode($ray);
mysqli_close($link);
?>

But Doesnt Work
Please Help

Body:
You should avoid  php var is sql and use param and a case for filter

select  count ( DISTINCT CASE WHEN tbl_trx.payone != 0 THEN tbl_trx.idoutlet ELSE NULL END) p1
, count ( DISTINCT CASE WHEN tbl_trx.paytwo != 0 THEN tbl_trx.idoutlet ELSE NULL END) p2
, count ( DISTINCT CASE WHEN tbl_trx.paythree != 0 THEN tbl_trx.idoutlet ELSE NULL END) p3
FROM tbl_outlet
INNER JOIN tbl_trx ON tbl_trx.idoutlet = tbl_outlet.id
WHERE id = :id


问:
Determinate if a rectangle fits into another
I'm using canvas to draw two rectangles one inside another (it's an interactive image crop view)

The trouble is that the blue rectangle can be also scaled and rotated (I'm using Matrix() on a bitmap to do this):

I can calculate the bounds without the rotation like this:

```<code>if( ( centerX - offsetX ) > ( greenRectangleWidth / 2f ) )
     // out of bounds
</code>```

But I'm completely lost how to calculate if the blue rectangle is still inside the green rectangle if the blue rectangle is rotated.. I think I could potentially solve this in two ways:

```<code>1. Read the pixel color of the edges of the blue square, if any of the edges will be outside the green square, the color will change. This seems like an unreliable way and I don't think I can even read 'pixel value' from canvas, then I would need to convert it to bitmap on each frame which will be very slow.

2. Calculate if any of the corners of the blue rectangle cross the edge of the green rectangle, but I'm not sure where to go from here.
</code>```

Any hints please how this could be solved most efficiently? Thank you!

答:
If both a blue and green rectangles are stored as Rect I would expect the line

if (!rectGreen.contains(rectBlue)){
  // blue is not inside the green
}

```

To work for both conditions - rotated and not rotated (I've not tested it)

See https://developer.android.com/reference/android/graphics/Rect.html#contains(android.graphics.Rect)

Body:
I'm using canvas to draw two rectangles one inside another (it's an interactive image crop view)

The trouble is that the blue rectangle can be also scaled and rotated (I'm using Matrix() on a bitmap to do this):

I can calculate the bounds without the rotation like this:

if( ( centerX - offsetX ) > ( greenRectangleWidth / 2f ) )
     // out of bounds

But I'm completely lost how to calculate if the blue rectangle is still inside the green rectangle if the blue rectangle is rotated.. I think I could potentially solve this in two ways:

1. Read the pixel color of the edges of the blue square, if any of the edges will be outside the green square, the color will change. This seems like an unreliable way and I don't think I can even read 'pixel value' from canvas, then I would need to convert it to bitmap on each frame which will be very slow.

2. Calculate if any of the corners of the blue rectangle cross the edge of the green rectangle, but I'm not sure where to go from here.

Any hints please how this could be solved most efficiently? Thank you!

Body:
If both a blue and green rectangles are stored as Rect I would expect the line

if (!rectGreen.contains(rectBlue)){
  // blue is not inside the green
}

To work for both conditions - rotated and not rotated (I've not tested it)

See https://developer.android.com/reference/android/graphics/Rect.html#contains(android.graphics.Rect)


问:
Unpacking unknown object from within DataFrame
Newbie here. I have a dataframe which contains an object I don't recognise, which I need to unpack and convert into a new separate dataframe, to form a new normalised structure.

A simplified version of the df is;

```<code>   trasaction_id   customer_details
0   1       <customer {id:'A123', name: 'Tina'} as x >
0   2       <customer {id:'B456', name: 'Tony'} as x >
0   3       <customer {id:'C789', name: 'Tim'} as x >

Name: customer_details, dtype: object
</code>```

I can't seem to access the dictionary within the object inside of the angle brackets. I've tried all sorts of things, if I try print(df['customer_details].__dict__ I get the following: {'_is_copy': None, '_data': SingleBlockManager.

I've even tried to do something hacky like this string manipulator, but I'm sure there's something basic I'm missing through being new to this.
'{' + df['customer_details'].apply(lambda st: st[st.find("{")+1:st.find("}")]) + '}'

Ultimately what I'm trying to achieve is to unnest these customer_details into a separate df linked by the transaction_id and store it in a simple normalised structure in an RDB. I believe in order to use a standard tool like json.dumps() etc I want it to look like this (with each element double quoted);

```<code>    transaction_id   customer_details
0    1        {id:'A123', name: 'Tina'}
0    2        {id:'B456', name: 'Tony'}
0    3        {id:'C789', name: 'Tim'}
</code>```

This is driving me mad. Thanks for your help!

答:
It seems you have object/class with properties id and name so you can try to get

```<code>{'id': st.id, 'name': st.name}
</code>```

which means

```<code>df['customer_details'] = df['customer_details'].apply(lambda x: {'id': x.id, 'name': x.name})
</code>```

or directly to separated columns

```<code>df['id']   = df['customer_details'].apply(lambda x: x.id)
df['name'] = df['customer_details'].apply(lambda x: x.name)
</code>```

Example code:

```<code>import pandas as pd

class customer:
    def __init__(self, id_, name):
        self.id = id_
        self.name = name
    def __str__(self):
        return '<customer {{id: {}, name: {}}} as x>'.format(self.id, self.name)

data = {
    'trasaction_id': [1,2,3],
    'customer_details': [
        customer('A123', 'Tina'),
        customer('B456', 'Tony'),
        customer('C789', 'Tim')
    ],
}

df = pd.DataFrame(data)
print(df)

# ---

df['id'] = df['customer_details'].apply(lambda x: x.id)
df['name'] = df['customer_details'].apply(lambda x: x.name)
print(df)

df['customer_details'] = df['customer_details'].apply(lambda x: {'id': x.id, 'name': x.name})
print(df)

#new_df = pd.DataFrame( df['customer_details'].to_list() )
</code>```

Result:

```<code>   trasaction_id                        customer_details
0              1  <customer {id: A123, name: Tina} as x>
1              2  <customer {id: B456, name: Tony} as x>
2              3   <customer {id: C789, name: Tim} as x>

   trasaction_id                        customer_details    id  name
0              1  <customer {id: A123, name: Tina} as x>  A123  Tina
1              2  <customer {id: B456, name: Tony} as x>  B456  Tony
2              3   <customer {id: C789, name: Tim} as x>  C789   Tim

   trasaction_id                customer_details    id  name
0              1  {'id': 'A123', 'name': 'Tina'}  A123  Tina
1              2  {'id': 'B456', 'name': 'Tony'}  B456  Tony
2              3   {'id': 'C789', 'name': 'Tim'}  C789   Tim
</code>```

EDIT: If you have strings then you can use regex to get values from string

```<code>import pandas as pd
import re

data = {
    'trasaction_id': [1,2,3],
    'customer_details': [
        "<customer {id:'A123', name: 'Tina'} as x >",
        "<customer {id:'B456', name: 'Tony'} as x >",
        "<customer {id:'C789', name: 'Tim'} as x >",
    ]
}

df = pd.DataFrame(data)
print(df)

# ---

df['id'] = df['customer_details'].apply(lambda x: re.search("id:'(.*)',", x)[1])
df['name'] = df['customer_details'].apply(lambda x: re.search("name: '(.*)'}", x)[1])
print(df)

def myfunc(x):
    r = re.search("id:'(.*)', name: '(.*)'}", x)
    return {'id': r[1], 'name': r[2]}

df['customer_details'] = df['customer_details'].apply(myfunc)
print(df)

#new_df = pd.DataFrame( df['customer_details'].to_list() )
</code>```

Body:
Newbie here. I have a dataframe which contains an object I don't recognise, which I need to unpack and convert into a new separate dataframe, to form a new normalised structure.

A simplified version of the df is;

   trasaction_id   customer_details
0   1       <customer {id:'A123', name: 'Tina'} as x >
0   2       <customer {id:'B456', name: 'Tony'} as x >
0   3       <customer {id:'C789', name: 'Tim'} as x >

Name: customer_details, dtype: object

I can't seem to access the dictionary within the object inside of the angle brackets. I've tried all sorts of things, if I try print(df['customer_details].__dict__ I get the following: {'_is_copy': None, '_data': SingleBlockManager.

I've even tried to do something hacky like this string manipulator, but I'm sure there's something basic I'm missing through being new to this.
'{' + df['customer_details'].apply(lambda st: st[st.find("{")+1:st.find("}")]) + '}'

Ultimately what I'm trying to achieve is to unnest these customer_details into a separate df linked by the transaction_id and store it in a simple normalised structure in an RDB. I believe in order to use a standard tool like json.dumps() etc I want it to look like this (with each element double quoted);

    transaction_id   customer_details
0    1        {id:'A123', name: 'Tina'}
0    2        {id:'B456', name: 'Tony'}
0    3        {id:'C789', name: 'Tim'}

This is driving me mad. Thanks for your help!

Body:
It seems you have object/class with properties id and name so you can try to get

{'id': st.id, 'name': st.name}

which means

df['customer_details'] = df['customer_details'].apply(lambda x: {'id': x.id, 'name': x.name})

or directly to separated columns

df['id']   = df['customer_details'].apply(lambda x: x.id)
df['name'] = df['customer_details'].apply(lambda x: x.name)

Example code:

import pandas as pd

class customer:
    def __init__(self, id_, name):
        self.id = id_
        self.name = name
    def __str__(self):
        return '<customer {{id: {}, name: {}}} as x>'.format(self.id, self.name)

data = {
    'trasaction_id': [1,2,3],
    'customer_details': [
        customer('A123', 'Tina'),
        customer('B456', 'Tony'),
        customer('C789', 'Tim')
    ],
}

df = pd.DataFrame(data)
print(df)

# ---

df['id'] = df['customer_details'].apply(lambda x: x.id)
df['name'] = df['customer_details'].apply(lambda x: x.name)
print(df)

df['customer_details'] = df['customer_details'].apply(lambda x: {'id': x.id, 'name': x.name})
print(df)

#new_df = pd.DataFrame( df['customer_details'].to_list() )

Result:

   trasaction_id                        customer_details
0              1  <customer {id: A123, name: Tina} as x>
1              2  <customer {id: B456, name: Tony} as x>
2              3   <customer {id: C789, name: Tim} as x>

   trasaction_id                        customer_details    id  name
0              1  <customer {id: A123, name: Tina} as x>  A123  Tina
1              2  <customer {id: B456, name: Tony} as x>  B456  Tony
2              3   <customer {id: C789, name: Tim} as x>  C789   Tim

   trasaction_id                customer_details    id  name
0              1  {'id': 'A123', 'name': 'Tina'}  A123  Tina
1              2  {'id': 'B456', 'name': 'Tony'}  B456  Tony
2              3   {'id': 'C789', 'name': 'Tim'}  C789   Tim

EDIT: If you have strings then you can use regex to get values from string

import pandas as pd
import re

data = {
    'trasaction_id': [1,2,3],
    'customer_details': [
        "<customer {id:'A123', name: 'Tina'} as x >",
        "<customer {id:'B456', name: 'Tony'} as x >",
        "<customer {id:'C789', name: 'Tim'} as x >",
    ]
}

df = pd.DataFrame(data)
print(df)

# ---

df['id'] = df['customer_details'].apply(lambda x: re.search("id:'(.*)',", x)[1])
df['name'] = df['customer_details'].apply(lambda x: re.search("name: '(.*)'}", x)[1])
print(df)

def myfunc(x):
    r = re.search("id:'(.*)', name: '(.*)'}", x)
    return {'id': r[1], 'name': r[2]}

df['customer_details'] = df['customer_details'].apply(myfunc)
print(df)

#new_df = pd.DataFrame( df['customer_details'].to_list() )


问:
JPA could not locate named parameter
I keep getting the following error: "could not locate named parameter [articleCommentId]" but it doesn't make sense to me because to me the named parameter is very much in place.

```<code>public ArticleCommentForDisplay getCommentByArticleCommentId(BigInteger articleCommentId) {

    String queryString = "select c.article_comment_id,  "
            + "       c.article_id,  "
            + "       c.parent_comment_id, "
            + "       p.nickname, "
            + "       c.title,  "
            + "       c.comment, "
            + "       c.person_id, "
            + "       c.confirmed_user, "
            + "       c.comment_depth, "
            + "       c.moderation_rank, "
            + "       c.moderation_reason, "
            + "       c.hide, "
            + "       c.hide_reason, "
            + "       c.session_id, "
            + "       c.confirmation_uuid, "
            + "       c.created_timestamp, "
            + "       c.created_by_id, "
            + "       c.updated_timestamp, "
            + "       c.updated_by_id, "
            + "       c.update_action, "
            + "       null as comment_path "
            + "from article_comment c "
            + "   join person p "
            + "       on p.person_id = c.person_id "
            + "where c.article_comment_id = :articleCommentId; ";

    Query query = em.createNativeQuery(queryString, "ArticleCommentMap");
    query.setParameter("articleCommentId", articleCommentId);

    List <ArticleCommentForDisplay> articleComments = new ArrayList<>();
    articleComments = query.getResultList();
    ArticleCommentForDisplay theComment = articleComments.get(0);

    return (theComment);

}
</code>```

Here is an extract of the stack trace with the relevant error:

```<code>Caused by: java.lang.IllegalArgumentException: org.hibernate.QueryParameterException: could not locate named parameter [articleCommentId]
    at org.hibernate.ejb.QueryImpl.setParameter(QueryImpl.java:379)
    at org.hibernate.ejb.QueryImpl.setParameter(QueryImpl.java:72)
    at com.extremelatitudesoftware.content.ArticleCommentFacade.getCommentByArticleCommentId(ArticleCommentFacade.java:293)
</code>```

答:
You can also use it like this

where c.article_comment_id = ?,
 and c.any_other_field = ?;
....
query.setParameter(1, articleCommentId)
query.setParameter(2, anyOtherValue)

it will take it by sequence.

And you can also give numbers like

where c.article_comment_id = ?1,
 and c.any_other_field = ?2;
....
query.setParameter(1, articleCommentId)
query.setParameter(2, anyOtherValue)

Title: JPA could not locate named parameter

Body:
I keep getting the following error: "could not locate named parameter [articleCommentId]" but it doesn't make sense to me because to me the named parameter is very much in place.

public ArticleCommentForDisplay getCommentByArticleCommentId(BigInteger articleCommentId) {

    String queryString = "select c.article_comment_id,  "
            + "       c.article_id,  "
            + "       c.parent_comment_id, "
            + "       p.nickname, "
            + "       c.title,  "
            + "       c.comment, "
            + "       c.person_id, "
            + "       c.confirmed_user, "
            + "       c.comment_depth, "
            + "       c.moderation_rank, "
            + "       c.moderation_reason, "
            + "       c.hide, "
            + "       c.hide_reason, "
            + "       c.session_id, "
            + "       c.confirmation_uuid, "
            + "       c.created_timestamp, "
            + "       c.created_by_id, "
            + "       c.updated_timestamp, "
            + "       c.updated_by_id, "
            + "       c.update_action, "
            + "       null as comment_path "
            + "from article_comment c "
            + "   join person p "
            + "       on p.person_id = c.person_id "
            + "where c.article_comment_id = :articleCommentId; ";

    Query query = em.createNativeQuery(queryString, "ArticleCommentMap");
    query.setParameter("articleCommentId", articleCommentId);

    List <ArticleCommentForDisplay> articleComments = new ArrayList<>();
    articleComments = query.getResultList();
    ArticleCommentForDisplay theComment = articleComments.get(0);

    return (theComment);

}

Here is an extract of the stack trace with the relevant error:

Caused by: java.lang.IllegalArgumentException: org.hibernate.QueryParameterException: could not locate named parameter [articleCommentId]
    at org.hibernate.ejb.QueryImpl.setParameter(QueryImpl.java:379)
    at org.hibernate.ejb.QueryImpl.setParameter(QueryImpl.java:72)
    at com.extremelatitudesoftware.content.ArticleCommentFacade.getCommentByArticleCommentId(ArticleCommentFacade.java:293)


问:
intersphinx link creation issues for local files across multiple projects
I have a few different Sphinx projects that I would like to refer to each other locally (no web server). I have separate code + build directories setup for the projects and was trying out intersphinx to solve this requirement.

My questions are:

Is there a better way of referring to two or more local projects within Sphinx?

Is there a way to strip out the second build in the path?

In my configuration file I have:

intersphinx_mapping = {
    'doc1': ('../build/doc1',None)
}
```
<p>so I get no issues in doing a make HTML, however when I look at the reference I've created with <code>:ref:'doc1 info <doc1:label1>'</code> I have in the HTML document:</p>
<p><code>file:///<root path>/build/**build**/doc1/html/doc.html#label1</code></p>
<p>So the issue is I get two "build" directory listings - it should of been:</p>
<p><code>file:///<root path>/build/doc1/html/doc.html#label1.</code></p>
<p>If I manually do this, it correctly pulls in the document.</p>
<p>I've also tried replacing <code>None</code> with <code>'../build/doc1'</code>.  If I drop the build from the mapping I do get an error in finding the <code>objects.inv</code> file for doc1.</p>
<p>I do not want to use absolute path since the end user getting this documentation may see it in another location and I want this to be cross platform...</p>
<p>My directory tree is essentially as follows:</p>
<pre class="lang-none prettyprint-override"><code>Makefile
build/doc1/html
build/doc2/html
doc1
doc2
</code>```

As a background, I'm trying this under Cygwin with Sphinx 1.7.5... I haven't tried Linux yet to see if I get the same behavior...

答:
You can set a different path for your target and for your inventory.
Maybe you can try something like:

intersphinx_mapping = {
    'doc1': ('../doc1', '../build/doc1/objects.inv')
}
```
<p>If you want to keep the <code>None</code>, it is also possible to have both:</p>
<pre class="lang-py prettyprint-override"><code>intersphinx_mapping = {
    'doc1': ('../doc1', (None, '../build/doc1/objects.inv'))
}
</code>```

Body:
I have a few different Sphinx projects that I would like to refer to each other locally (no web server). I have separate code + build directories setup for the projects and was trying out intersphinx to solve this requirement.

My questions are:

Is there a better way of referring to two or more local projects within Sphinx?

Is there a way to strip out the second build in the path?

In my configuration file I have:

intersphinx_mapping = {
    'doc1': ('../build/doc1',None)
}

so I get no issues in doing a make HTML, however when I look at the reference I've created with :ref:'doc1 info <doc1:label1>' I have in the HTML document:

file:///<root path>/build/**build**/doc1/html/doc.html#label1

So the issue is I get two "build" directory listings - it should of been:

file:///<root path>/build/doc1/html/doc.html#label1.

If I manually do this, it correctly pulls in the document.

I've also tried replacing None with '../build/doc1'.  If I drop the build from the mapping I do get an error in finding the objects.inv file for doc1.

I do not want to use absolute path since the end user getting this documentation may see it in another location and I want this to be cross platform...

My directory tree is essentially as follows:

Makefile
build/doc1/html
build/doc2/html
doc1
doc2

As a background, I'm trying this under Cygwin with Sphinx 1.7.5... I haven't tried Linux yet to see if I get the same behavior...

Body:
You can set a different path for your target and for your inventory.
Maybe you can try something like:

intersphinx_mapping = {
    'doc1': ('../doc1', '../build/doc1/objects.inv')
}

If you want to keep the None, it is also possible to have both:

intersphinx_mapping = {
    'doc1': ('../doc1', (None, '../build/doc1/objects.inv'))
}


问:
Julia - dataframe - Same column in a multiple input function with by()
I am trying to explore the capabilities of the DataFrames.jl module.
I ran into the following issue when trying to pass the same column into a multiple input variable in the by() function.

My base example is :

```<code>df = DataFrame(grp = rand(["a","b"], 100), x= rand(100), y = rand(100), z=rand(100))
by(df, :grp,result= (:x, :z) => ((x, y),) -> cov(x, y))
</code>```

Giving the following dataframe

```<code>2×2 DataFrame
│ Row │ grp    │ result     │
│     │ String │ Float64    │
├─────┼────────┼────────────┤
│ 1   │ a      │ -0.0111914 │
│ 2   │ b      │ -0.0184773 │
</code>```

Now lets assume that I am not necessarily working with cov() and that I would like to pass the same column x as both the x and y inputs of that function. In the case of cov() , it is a trivial one, but trying to be as generic as possible.

I have tried the following two possibilities

```<code>by(df, :grp,result= (:x) => ((x, y),) -> cov(x, y))
</code>```

Which gives the following error message :

```<code>ERROR: MethodError: no method matching cov(::Float64, ::Float64)
</code>```

The error in this case is expected and I imagine that method refers to the data provided to the function object

I have also tried the following

```<code>by(df, :grp,result= (:x,:x) => ((x, y),) -> cov(x, y))
</code>```

Which gives the following error message

```<code>ERROR: ArgumentError: Elements of Symbol[:x, :x] must be unique
</code>```

This time I understand the error message, but I don't understand why Symbol must be unique. I have checked ?Symbol but couldn't find more details on why or how to bypass this issue (limitation?).
Effectively this prevents me from passing the same column programatically for both inputs.

So what would be the way to address this issue and be able to pass the same column twice for a function with f(x,y) ?

PS: Ahead of questions or comments on in this case (x)->cov(x,x) will work. I am aware that it will. But lets say I have a function that will compute the cov() or other functions for the (selected) columns of a dataframe I would prefer not to have to handle special cases for the diagonal items.

答:
The error with

```<code>by(df, :grp,result= (:x) => ((x, y),) -> cov(x, y))
</code>```

is due to the following way Julia processess arguments:

```<code>julia> f((x,y),) = @show (x,y)
f (generic function with 1 method)

julia> f([1,2,3,4,5])
(x, y) = (1, 2)
(1, 2)
</code>```

so x gets a first element of the passed vector stored in column :x and :y gets the second value.

Note that if your df were shorter than 2 rows you would even get an error:

```<code>julia> by(first(df,2), :grp,result= (:x) => ((x, y),) -> println((x,y)))
ERROR: BoundsError: attempt to access 1-element view(::Array{Float64,1}, [1]) with eltype Float64 at index [2]
</code>```

Now moving to the duplicate column issue. The problem is that by passes to your function a NamedTuple, which you can check by running e.g. the following code:

```<code>julia> df = DataFrame(x=[:a,:b,:a,:b], y=1:4)
4×2 DataFrame
│ Row │ x      │ y     │
│     │ Symbol │ Int64 │
├─────┼────────┼───────┤
│ 1   │ a      │ 1     │
│ 2   │ b      │ 2     │
│ 3   │ a      │ 3     │
│ 4   │ b      │ 4     │

julia> by(df, :x, (:x, :y) => x -> @show typeof(x));
typeof(x) = NamedTuple{(:x, :y),Tuple{SubArray{Symbol,1,Array{Symbol,1},Tuple{Array{Int64,1}},false},SubArray{Int64,1,Array{Int64,1},Tuple{Array{Int64,1}},false}}}
typeof(x) = NamedTuple{(:x, :y),Tuple{SubArray{Symbol,1,Array{Symbol,1},Tuple{Array{Int64,1}},false},SubArray{Int64,1,Array{Int64,1},Tuple{Array{Int64,1}},false}}}
</code>```

and NamedTuple does not allow duplicate columns:

```<code>julia> (a=1,a=2)
ERROR: syntax: field name "a" repeated in named tuple
</code>```

Actually we are discussing in DataFrames.jl currently to switch from passing a NamedTuple to auto-splatting, see the following issue.

Body:
I am trying to explore the capabilities of the DataFrames.jl module.
I ran into the following issue when trying to pass the same column into a multiple input variable in the by() function.

My base example is :

df = DataFrame(grp = rand(["a","b"], 100), x= rand(100), y = rand(100), z=rand(100))
by(df, :grp,result= (:x, :z) => ((x, y),) -> cov(x, y))

Giving the following dataframe

2×2 DataFrame
│ Row │ grp    │ result     │
│     │ String │ Float64    │
├─────┼────────┼────────────┤
│ 1   │ a      │ -0.0111914 │
│ 2   │ b      │ -0.0184773 │

Now lets assume that I am not necessarily working with cov() and that I would like to pass the same column x as both the x and y inputs of that function. In the case of cov() , it is a trivial one, but trying to be as generic as possible.

I have tried the following two possibilities

by(df, :grp,result= (:x) => ((x, y),) -> cov(x, y))

Which gives the following error message :

ERROR: MethodError: no method matching cov(::Float64, ::Float64)

The error in this case is expected and I imagine that method refers to the data provided to the function object

I have also tried the following

by(df, :grp,result= (:x,:x) => ((x, y),) -> cov(x, y))

Which gives the following error message

ERROR: ArgumentError: Elements of Symbol[:x, :x] must be unique

This time I understand the error message, but I don't understand why Symbol must be unique. I have checked ?Symbol but couldn't find more details on why or how to bypass this issue (limitation?).
Effectively this prevents me from passing the same column programatically for both inputs.

So what would be the way to address this issue and be able to pass the same column twice for a function with f(x,y) ?

PS: Ahead of questions or comments on in this case (x)->cov(x,x) will work. I am aware that it will. But lets say I have a function that will compute the cov() or other functions for the (selected) columns of a dataframe I would prefer not to have to handle special cases for the diagonal items.

Body:
The error with

by(df, :grp,result= (:x) => ((x, y),) -> cov(x, y))

is due to the following way Julia processess arguments:

julia> f((x,y),) = @show (x,y)
f (generic function with 1 method)

julia> f([1,2,3,4,5])
(x, y) = (1, 2)
(1, 2)

so x gets a first element of the passed vector stored in column :x and :y gets the second value.

Note that if your df were shorter than 2 rows you would even get an error:

julia> by(first(df,2), :grp,result= (:x) => ((x, y),) -> println((x,y)))
ERROR: BoundsError: attempt to access 1-element view(::Array{Float64,1}, [1]) with eltype Float64 at index [2]

Now moving to the duplicate column issue. The problem is that by passes to your function a NamedTuple, which you can check by running e.g. the following code:

julia> df = DataFrame(x=[:a,:b,:a,:b], y=1:4)
4×2 DataFrame
│ Row │ x      │ y     │
│     │ Symbol │ Int64 │
├─────┼────────┼───────┤
│ 1   │ a      │ 1     │
│ 2   │ b      │ 2     │
│ 3   │ a      │ 3     │
│ 4   │ b      │ 4     │

julia> by(df, :x, (:x, :y) => x -> @show typeof(x));
typeof(x) = NamedTuple{(:x, :y),Tuple{SubArray{Symbol,1,Array{Symbol,1},Tuple{Array{Int64,1}},false},SubArray{Int64,1,Array{Int64,1},Tuple{Array{Int64,1}},false}}}
typeof(x) = NamedTuple{(:x, :y),Tuple{SubArray{Symbol,1,Array{Symbol,1},Tuple{Array{Int64,1}},false},SubArray{Int64,1,Array{Int64,1},Tuple{Array{Int64,1}},false}}}

and NamedTuple does not allow duplicate columns:

julia> (a=1,a=2)
ERROR: syntax: field name "a" repeated in named tuple

Actually we are discussing in DataFrames.jl currently to switch from passing a NamedTuple to auto-splatting, see the following issue.


问:
Array does not have indent or space in PyYAML
In the code below I created the net_plan_dict variable dictionary and converted it into a YAML format file.
Inside the dictionary I have a field called addresses which is an array of three elements.
After creating the YAML file, the three array elements were not placed under the addresses field :

```<code>import yaml

net_plan_dict = {
    'networking': {
        'addresses': ['192.168.1.1', '192.168.1.2', "192.168.1.3"],
        'gateway4': '192.168.121.1'
    }
}

with open("new.yaml", "w") as f:
    yaml.dump(net_plan_dict, f)

</code>```

Output of the above code is as follows (in the file below, the IPs are not below the address and have no space or indent).

new.yaml:

```<code>networking:
  addresses:
  - 192.168.1.1 <-------- does not have indent
  - 192.168.1.2
  - 192.168.1.3
  gateway4: 192.168.121.1

</code>```

but my goal is to get this output file (how to create this file, when ips are under addresses field):

```<code>networking:
  addresses:
    - 192.168.1.1
    - 192.168.1.2
    - 192.168.1.3
  gateway4: 192.168.121.1

</code>```

答:
PyYAML's dump() doesn't have the fine control to have a different indent for
the mappings (2 positions) and sequences (4 positions), nor can it offset the sequence indicator (-) within
the space of the (sequence) indent).

If you want that kind of control over your output you should use ruamel.yaml (disclaimer: I am the author of that package):

```<code>import sys
import ruamel.yaml

net_plan_dict = {
    'networking': {
        'addresses': ['192.168.1.1', '192.168.1.2', "192.168.1.3"],
        'gateway4': '192.168.121.1'
    }
}

yaml = ruamel.yaml.YAML()
yaml.indent(mapping=2, sequence=4, offset=2)
yaml.dump(net_plan_dict, sys.stdout)
</code>```

which gives:

```<code>networking:
  addresses:
    - 192.168.1.1
    - 192.168.1.2
    - 192.168.1.3
  gateway4: 192.168.121.1
</code>```

Body:
In the code below I created the net_plan_dict variable dictionary and converted it into a YAML format file.
Inside the dictionary I have a field called addresses which is an array of three elements.
After creating the YAML file, the three array elements were not placed under the addresses field :

import yaml

net_plan_dict = {
    'networking': {
        'addresses': ['192.168.1.1', '192.168.1.2', "192.168.1.3"],
        'gateway4': '192.168.121.1'
    }
}

with open("new.yaml", "w") as f:
    yaml.dump(net_plan_dict, f)

Output of the above code is as follows (in the file below, the IPs are not below the address and have no space or indent).

new.yaml:

networking:
  addresses:
  - 192.168.1.1 <-------- does not have indent
  - 192.168.1.2
  - 192.168.1.3
  gateway4: 192.168.121.1

but my goal is to get this output file (how to create this file, when ips are under addresses field):

networking:
  addresses:
    - 192.168.1.1
    - 192.168.1.2
    - 192.168.1.3
  gateway4: 192.168.121.1

Body:
PyYAML's dump() doesn't have the fine control to have a different indent for
the mappings (2 positions) and sequences (4 positions), nor can it offset the sequence indicator (-) within
the space of the (sequence) indent).

If you want that kind of control over your output you should use ruamel.yaml (disclaimer: I am the author of that package):

import sys
import ruamel.yaml

net_plan_dict = {
    'networking': {
        'addresses': ['192.168.1.1', '192.168.1.2', "192.168.1.3"],
        'gateway4': '192.168.121.1'
    }
}

yaml = ruamel.yaml.YAML()
yaml.indent(mapping=2, sequence=4, offset=2)
yaml.dump(net_plan_dict, sys.stdout)

which gives:

networking:
  addresses:
    - 192.168.1.1
    - 192.168.1.2
    - 192.168.1.3
  gateway4: 192.168.121.1


问:
Driver to simulate keypresses into another process
How can I simulate a key being pressed in a given process on Linux? Xorg isn't running, the inputs are handled by DirectFB</p>

答:
I'm not entirely sure what you are trying to accomplish here... more information about your goals would be very helpful.

To communicate between different processes you either need to use signals (or here) or that specific program's API (e.g., Xorg's development wiki).

OwnerDisplayName: Listito

OwnerDisplayName: kce


问:
certificate.php:5 Uncaught ReferenceError: TEstasdasd is not defined
my php code

```<code><?php
if (isset($_POST['submit'])) {
    $name = $_POST['name'];
    $address = $_POST['address'];
    $fname = $_POST['fname'];
    $mname = $_POST['mname'];
    $all_info = $name . "<br>" . $address . "<br>" . $fname . "<br>" . $fname;
    // echo $all_info;
}

// echo $name,$email,$message;

?>
</code>```

my js code

```<code><script>

const name = <?php echo $name ?>;
console.log(name);
alert(name);

</script>
</code>```

error

certificate.php:5 Uncaught ReferenceError: TEstasdasd is not defined

eror sources code

```<code><script>

const name = TEstasdasd;
console.log(name);
alert(name);

</script>
</code>```

I can't fix my bugs can anyone help me?

答:
const name = TEstasdasd; on this line you're getting error. Because you didn't define it anywhere and try to call that constant

Try as below.

```<code>const name = 'TEstasdasd';
</code>```

Body:
my php code

<?php
if (isset($_POST['submit'])) {
    $name = $_POST['name'];
    $address = $_POST['address'];
    $fname = $_POST['fname'];
    $mname = $_POST['mname'];
    $all_info = $name . "
" . $address . "
" . $fname . "
" . $fname;
    // echo $all_info;
}

// echo $name,$email,$message;

?>

my js code

error

certificate.php:5 Uncaught ReferenceError: TEstasdasd is not defined

eror sources code

I can't fix my bugs can anyone help me?

Body:
const name = TEstasdasd; on this line you're getting error. Because you didn't define it anywhere and try to call that constant

Try as below.

const name = 'TEstasdasd';


问:
Need support for face lock
I am trying to integrate face lock with a bio-metric manager but it is not working.
also, I need to check whether face locks feature support in the device or not.
let me know anyone integrates face lock for the custom app login.</p>

```<code>BiometricManager biometricManager = BiometricManager.from(MainActivity.this);
switch (biometricManager.canAuthenticate()) {
  case BiometricManager.BIOMETRIC_SUCCESS:
    Toast.makeText(MainActivity.this, "Face Id Setup Successfully", Toast.LENGTH_LONG).show();
    Log.d("Sohan", "App can authenticate using biometrics.");
    break;
  case BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE:
    Toast.makeText(MainActivity.this, "No biometric features available on this device.", Toast.LENGTH_LONG).show();
    Log.e("Sohan", "No biometric features available on this device.");
    break;
  case BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE:
    Toast.makeText(MainActivity.this, "Biometric features are currently unavailable.", Toast.LENGTH_LONG).show();
    Log.e("Sohan", "Biometric features are currently unavailable.");
    break;
  case BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED:
    Toast.makeText(MainActivity.this, "The user hasn't associated any biometric credentials with their account.", Toast.LENGTH_LONG).show();
    Log.e("Sohan", "The user hasn't associated any biometric credentials with their account.");
    break;
}
</code>```

答: you cant enable face lock only .if device enabled both finerprint and face. BiometricManager automatically call fingerprint first. if fingerprint not enabled BiometricManager takes face. these are the options available.</p>

Title: Need support for face lock

Body:
I am trying to integrate face lock with a bio-metric manager but it is not working.
also, I need to check whether face locks feature support in the device or not.
let me know anyone integrates face lock for the custom app login.

BiometricManager biometricManager = BiometricManager.from(MainActivity.this);
switch (biometricManager.canAuthenticate()) {
  case BiometricManager.BIOMETRIC_SUCCESS:
    Toast.makeText(MainActivity.this, "Face Id Setup Successfully", Toast.LENGTH_LONG).show();
    Log.d("Sohan", "App can authenticate using biometrics.");
    break;
  case BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE:
    Toast.makeText(MainActivity.this, "No biometric features available on this device.", Toast.LENGTH_LONG).show();
    Log.e("Sohan", "No biometric features available on this device.");
    break;
  case BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE:
    Toast.makeText(MainActivity.this, "Biometric features are currently unavailable.", Toast.LENGTH_LONG).show();
    Log.e("Sohan", "Biometric features are currently unavailable.");
    break;
  case BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED:
    Toast.makeText(MainActivity.this, "The user hasn't associated any biometric credentials with their account.", Toast.LENGTH_LONG).show();
    Log.e("Sohan", "The user hasn't associated any biometric credentials with their account.");
    break;
}


问:
How can i change the itemLayout in Adapter class
I try to get a key from the main class but it is Always getting null

```<code> Bundle bundle =new Bundle();
 String type = bundle.getString("theType");

if (type =="Check"){

    view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.item_note_check, parent, false);

}else if (type =="photo"){
    view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.item_note_photo, parent, false);
}else {view = LayoutInflater.from(parent.getContext())
         .inflate(R.layout.item_note, parent, false);
}
</code>```

to get kType from

```<code>public void onRadioButtonTypeClicked(View view) {
    // Is the button now checked?
    boolean checked = ((RadioButton) view).isChecked();
Bundle bundle = new Bundle();

   // Intent intent = new Intent();
    kType="photo";
    // Check which radio button was clicked
    switch(view.getId()) {
        case R.id.radioButtonSheet:
            if (checked)
                mImageNoteV.setImageResource(R.drawable.radio_button_note);
            kType= "note";
            bundle.putString("theType",kType);
         //   intent.putExtra("theType",kType);
            break;
        case R.id.radioButtonDone:
            if (checked)
                mImageNoteV.setImageResource(R.drawable.radio_button_check_box);
            kType="Check";
            bundle.putString("theType",kType);
        //   intent.putExtra("theType",kType);
            break;
        case R.id.radioButtonPicture:
            if (checked)
                mImageNoteV.setImageResource(R.drawable.radio_button_photo);
            kType = "photo";
            bundle.putString("theType",kType);
         //   intent.putExtra("theType",kType);
            break;
    }
</code>```

i try to set it in other class and get it again from it but does not work = null. is there good way to solve this

答:
For this, you need to initialize two class variables of type boolean in your activity like the following.

```<code>public static boolean defaultType = false;
public static boolean noteCheck = false;
</code>```

then do changes as per your requirement  (eg: 'noteCheck = true' represent kType="Check" and  'noteCheck = false' represent kType="Photo" and 'defaultType = true' represents kType="note")

```<code>// Check which radio button was clicked
switch(view.getId()) {
    case R.id.radioButtonSheet:
        if (checked)
            mImageNoteV.setImageResource(R.drawable.radio_button_note);
        defaultType= true;
        break;
    case R.id.radioButtonDone:
        if (checked)
            mImageNoteV.setImageResource(R.drawable.radio_button_check_box);
        noteCheck= true;
        break;
    case R.id.radioButtonPicture:
        if (checked)
            mImageNoteV.setImageResource(R.drawable.radio_button_photo);
        noteCheck = false;
        break;
}
</code>```

Then in your Adapter class call them by class name and set the layout as follows:

```<code>View view;
    if (defaultType){
        view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_note, parent, false);
    }else {
        view = LayoutInflater.from(context).inflate(noteCheck ? R.layout.item_note_check : R.layout.item_note_photo, parent, false);
    }
</code>```

Don't forget to call the variables by their class name as they are class variables.
The way worked for me, hope it helps you.

Body:
I try to get a key from the main class but it is Always getting null

 Bundle bundle =new Bundle();
 String type = bundle.getString("theType");

if (type =="Check"){

    view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.item_note_check, parent, false);

}else if (type =="photo"){
    view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.item_note_photo, parent, false);
}else {view = LayoutInflater.from(parent.getContext())
         .inflate(R.layout.item_note, parent, false);
}

to get kType from

public void onRadioButtonTypeClicked(View view) {
    // Is the button now checked?
    boolean checked = ((RadioButton) view).isChecked();
Bundle bundle = new Bundle();

   // Intent intent = new Intent();
    kType="photo";
    // Check which radio button was clicked
    switch(view.getId()) {
        case R.id.radioButtonSheet:
            if (checked)
                mImageNoteV.setImageResource(R.drawable.radio_button_note);
            kType= "note";
            bundle.putString("theType",kType);
         //   intent.putExtra("theType",kType);
            break;
        case R.id.radioButtonDone:
            if (checked)
                mImageNoteV.setImageResource(R.drawable.radio_button_check_box);
            kType="Check";
            bundle.putString("theType",kType);
        //   intent.putExtra("theType",kType);
            break;
        case R.id.radioButtonPicture:
            if (checked)
                mImageNoteV.setImageResource(R.drawable.radio_button_photo);
            kType = "photo";
            bundle.putString("theType",kType);
         //   intent.putExtra("theType",kType);
            break;
    }

i try to set it in other class and get it again from it but does not work = null. is there good way to solve this

Body:
For this, you need to initialize two class variables of type boolean in your activity like the following.

public static boolean defaultType = false;
public static boolean noteCheck = false;

then do changes as per your requirement  (eg: 'noteCheck = true' represent kType="Check" and  'noteCheck = false' represent kType="Photo" and 'defaultType = true' represents kType="note")

// Check which radio button was clicked
switch(view.getId()) {
    case R.id.radioButtonSheet:
        if (checked)
            mImageNoteV.setImageResource(R.drawable.radio_button_note);
        defaultType= true;
        break;
    case R.id.radioButtonDone:
        if (checked)
            mImageNoteV.setImageResource(R.drawable.radio_button_check_box);
        noteCheck= true;
        break;
    case R.id.radioButtonPicture:
        if (checked)
            mImageNoteV.setImageResource(R.drawable.radio_button_photo);
        noteCheck = false;
        break;
}

Then in your Adapter class call them by class name and set the layout as follows:

View view;
    if (defaultType){
        view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_note, parent, false);
    }else {
        view = LayoutInflater.from(context).inflate(noteCheck ? R.layout.item_note_check : R.layout.item_note_photo, parent, false);
    }

Don't forget to call the variables by their class name as they are class variables.
The way worked for me, hope it helps you.


问:
Set all items to a listview from a file .txt (ArrayList) what contains textview value [Android Java]
I want after a button onClick generate1() show all items from my Arraylist(.txt) contains Edittext value.

I am a beginner in android java programming.

This is my onClick Method generate1():

```<code>    public void generate1(View view) throws IOException {

        ArrayAdapter<String> adapter;
        ArrayList<String> ls = new ArrayList<>();
        EditText editText = (EditText) findViewById(R.id.editText);

        BufferedReader br = null;

        br = new BufferedReader(new InputStreamReader(getAssets().open("themen.txt")));
        String word;
        while ((word = br.readLine()) != null) {
            ls.add(word);
        }
        br.close();
        ListView listView = (ListView) findViewById(R.id.listView);
        adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,ls);
        listView.setAdapter(adapter);

        for (String e : ls){
           if (e.toLowerCase().contains(editText.getText().toString())){
              //???? some toDO ???? (if i do here System.out.println(e); its work, but i want the Items to a listview!!
           }
        }
    }
</code>```

答:
you should create two global ArrayList .first you named 'ls' for all results.second i call 'lsFiltered' for filtered results;
then...

change this

```<code>for (String e : ls){
       if (e.toLowerCase().contains(editText.getText().toString())){
          //???? some toDO ???? (if i do here System.out.println(e); its work, but i want the Items to a listview!!
       }
    }
</code>```

to this

```<code>for (int i = 0; i <ls.size() ; i++) {
        if (e.toLowerCase().contains(editText.getText().toString())){
            lsFiltered.add(ls.get(i));
        }
}
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,lsFiltered);
listView.setAdapter(adapter);
</code>```

Body:
I want after a button onClick generate1() show all items from my Arraylist(.txt) contains Edittext value.

I am a beginner in android java programming.

This is my onClick Method generate1():

    public void generate1(View view) throws IOException {

        ArrayAdapter<String> adapter;
        ArrayList<String> ls = new ArrayList<>();
        EditText editText = (EditText) findViewById(R.id.editText);

        BufferedReader br = null;

        br = new BufferedReader(new InputStreamReader(getAssets().open("themen.txt")));
        String word;
        while ((word = br.readLine()) != null) {
            ls.add(word);
        }
        br.close();
        ListView listView = (ListView) findViewById(R.id.listView);
        adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,ls);
        listView.setAdapter(adapter);

        for (String e : ls){
           if (e.toLowerCase().contains(editText.getText().toString())){
              //???? some toDO ???? (if i do here System.out.println(e); its work, but i want the Items to a listview!!
           }
        }
    }

Body:
you should create two global ArrayList .first you named 'ls' for all results.second i call 'lsFiltered' for filtered results;
then...

change this

for (String e : ls){
       if (e.toLowerCase().contains(editText.getText().toString())){
          //???? some toDO ???? (if i do here System.out.println(e); its work, but i want the Items to a listview!!
       }
    }

to this

for (int i = 0; i <ls.size() ; i++) {
        if (e.toLowerCase().contains(editText.getText().toString())){
            lsFiltered.add(ls.get(i));
        }
}
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,lsFiltered);
listView.setAdapter(adapter);


问:
Append from txt to worksheet - Powershell
I'm trying to build a script which takes the content of text file and appends it to the worksheet but it stops at the first match. I want it to go through the whole text file and append EVERY match to the worksheet.

Text file:

```<code>Node: ABC
Name: PC
Cluster: HS1
Node: XZZ
Name: CC
Cluster: HS2
Node: XYZ
Name: DD
Cluster: HS3

</code>```

How I want it to be

```<code>Node|Name|Cluster
ABC    PC   HS1
XZZ    CC   HS2
XYZ    DD   HS3
</code>```

I'm using the following code:

```<code>$WorkbookPath = "Destination Path"
$Patterns = "Name"
$Testbestand = get-content "Source Path"
$sheetName = "Sheet1"
$objExcel = New-Object -ComObject Excel.Application
$WorkBook = $objExcel.Workbooks.Open($WorkbookPath)
$WorkSheet = $WorkBook.sheets.item($sheetName)
$usedRange = $WorkSheet.usedRange
$lastCell = $usedRange.SpecialCells(11)
$newRow = $lastCell.row + 1
foreach ($Pattern in $Patterns){
$AlertValue = $Testbestand | Select-string -pattern $Pattern -list -quiet
$AlertValue = ($AlertValue -split " ")[-1]
$col = ($Worksheet.Columns.Find($pattern))
$WorkSheet.cells.item($newRow, $col.Column).value = $AlertValue
}#foreach pattern
$WorkBook.Save()
$objExcel.Quit()
</code>```

答:
You can convert the textfile you have to a proper CSV file and import that into Excel without much effort.

```<code># read the file as a single string including newlines
$content = Get-Content -Path 'TheInputFile' -Raw

# create a regex to parse the file
$regex = [regex] '(?i)Node:\s*(?<node>[^\r\n]*)\r?\nName:\s*(?<name>[^\r\n]*)\r?\nCluster:\s*(?<cluster>[^\r\n]*)'
$match = $regex.Match($content)

# collect the resulting PSObjects in variable $result
$result = while ($match.Success) {
    [PsCustomObject]@{
        'Node'    = $match.Groups['node'].Value
        'Name'    = $match.Groups['name'].Value
        'Cluster' = $match.Groups['cluster'].Value
    }
    $match = $match.NextMatch()
}

# output on screen
$result

# output to CSV file (if you like)
# $result | Export-Csv -Path 'TheOutputFile' -UseCulture -NoTypeInformation
</code>```

Result on screen:

```<code>Node Name Cluster
---- ---- -------
ABC  PC   HS1
XZZ  CC   HS2
XYZ  DD   HS3
</code>```

Update

You can use this $result array to insert the data into an Excel file.
Something like this:

```<code># first use the above code to parse the text file into an array of PSObjects.

# next, insert data from the $result array in the Excel
$WorkbookPath = "Destination Path"
$sheetName    = "Sheet1"
$objExcel     = New-Object -ComObject Excel.Application
$WorkBook     = $objExcel.Workbooks.Open($WorkbookPath)
$WorkSheet    = $WorkBook.sheets.item($sheetName)
$usedRange    = $WorkSheet.usedRange
$lastCell     = $usedRange.SpecialCells(11)

# determine the row and column positions
$row = $lastCell.row + 1
$colNode = ($Worksheet.Columns.Find("Node"))
$colName = ($Worksheet.Columns.Find("Name"))
$colCluster = ($Worksheet.Columns.Find("Cluster"))

# now loop through the parsed $result array
$result | ForEach-Object {
    $WorkSheet.cells.item($row, $colNode.Column).value = $_.Node
    $WorkSheet.cells.item($row, $colName.Column).value = $_.Name
    $WorkSheet.cells.item($row, $colCluster.Column).value = $_.Cluster
    $row++
}

$WorkBook.Save()
$objExcel.Quit()

# release COM objects from memory
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($WorkBook) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($objExcel) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
</code>```

Regex Details:

```<code>(?i)               Make the Match work case-insensitive
Node:              Match the characters “Node:” literally
\s                 Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
   *               Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
(?<node>           Match the regular expression below and capture its match into backreference with name “node”
   .               Match any single character that is not a line break character
      *            Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
)
\r                 Match a carriage return character
   ?               Between zero and one times, as many times as possible, giving back as needed (greedy)
\n                 Match a line feed character
Name:              Match the characters “Name:” literally
\s                 Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
   *               Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
(?<name>           Match the regular expression below and capture its match into backreference with name “name”
   .               Match any single character that is not a line break character
      *            Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
)
\r                 Match a carriage return character
   ?               Between zero and one times, as many times as possible, giving back as needed (greedy)
\n                 Match a line feed character
Cluster:           Match the characters “Cluster:” literally
\s                 Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
   *               Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
(?<cluster>        Match the regular expression below and capture its match into backreference with name “cluster”
   .               Match any single character that is not a line break character
      *            Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
)
</code>```

Body:
I'm trying to build a script which takes the content of text file and appends it to the worksheet but it stops at the first match. I want it to go through the whole text file and append EVERY match to the worksheet.

Text file:

Node: ABC
Name: PC
Cluster: HS1
Node: XZZ
Name: CC
Cluster: HS2
Node: XYZ
Name: DD
Cluster: HS3

How I want it to be

Node|Name|Cluster
ABC    PC   HS1
XZZ    CC   HS2
XYZ    DD   HS3

I'm using the following code:

$WorkbookPath = "Destination Path"
$Patterns = "Name"
$Testbestand = get-content "Source Path"
$sheetName = "Sheet1"
$objExcel = New-Object -ComObject Excel.Application
$WorkBook = $objExcel.Workbooks.Open($WorkbookPath)
$WorkSheet = $WorkBook.sheets.item($sheetName)
$usedRange = $WorkSheet.usedRange
$lastCell = $usedRange.SpecialCells(11)
$newRow = $lastCell.row + 1
foreach ($Pattern in $Patterns){
$AlertValue = $Testbestand | Select-string -pattern $Pattern -list -quiet
$AlertValue = ($AlertValue -split " ")[-1]
$col = ($Worksheet.Columns.Find($pattern))
$WorkSheet.cells.item($newRow, $col.Column).value = $AlertValue
}#foreach pattern
$WorkBook.Save()
$objExcel.Quit()

Body:
You can convert the textfile you have to a proper CSV file and import that into Excel without much effort.

# read the file as a single string including newlines
$content = Get-Content -Path 'TheInputFile' -Raw

# create a regex to parse the file
$regex = [regex] '(?i)Node:\s*(?<node>[^\r\n]*)\r?\nName:\s*(?<name>[^\r\n]*)\r?\nCluster:\s*(?<cluster>[^\r\n]*)'
$match = $regex.Match($content)

# collect the resulting PSObjects in variable $result
$result = while ($match.Success) {
    [PsCustomObject]@{
        'Node'    = $match.Groups['node'].Value
        'Name'    = $match.Groups['name'].Value
        'Cluster' = $match.Groups['cluster'].Value
    }
    $match = $match.NextMatch()
}

# output on screen
$result

# output to CSV file (if you like)
# $result | Export-Csv -Path 'TheOutputFile' -UseCulture -NoTypeInformation

Result on screen:

Node Name Cluster
---- ---- -------
ABC  PC   HS1
XZZ  CC   HS2
XYZ  DD   HS3

Update

You can use this $result array to insert the data into an Excel file.
Something like this:

# first use the above code to parse the text file into an array of PSObjects.

# next, insert data from the $result array in the Excel
$WorkbookPath = "Destination Path"
$sheetName    = "Sheet1"
$objExcel     = New-Object -ComObject Excel.Application
$WorkBook     = $objExcel.Workbooks.Open($WorkbookPath)
$WorkSheet    = $WorkBook.sheets.item($sheetName)
$usedRange    = $WorkSheet.usedRange
$lastCell     = $usedRange.SpecialCells(11)

# determine the row and column positions
$row = $lastCell.row + 1
$colNode = ($Worksheet.Columns.Find("Node"))
$colName = ($Worksheet.Columns.Find("Name"))
$colCluster = ($Worksheet.Columns.Find("Cluster"))

# now loop through the parsed $result array
$result | ForEach-Object {
    $WorkSheet.cells.item($row, $colNode.Column).value = $_.Node
    $WorkSheet.cells.item($row, $colName.Column).value = $_.Name
    $WorkSheet.cells.item($row, $colCluster.Column).value = $_.Cluster
    $row++
}

$WorkBook.Save()
$objExcel.Quit()

# release COM objects from memory
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($WorkBook) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($objExcel) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

Regex Details:

(?i)               Make the Match work case-insensitive
Node:              Match the characters “Node:” literally
\s                 Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
   *               Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
(?<node>           Match the regular expression below and capture its match into backreference with name “node”
   .               Match any single character that is not a line break character
      *            Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
)
\r                 Match a carriage return character
   ?               Between zero and one times, as many times as possible, giving back as needed (greedy)
\n                 Match a line feed character
Name:              Match the characters “Name:” literally
\s                 Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
   *               Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
(?<name>           Match the regular expression below and capture its match into backreference with name “name”
   .               Match any single character that is not a line break character
      *            Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
)
\r                 Match a carriage return character
   ?               Between zero and one times, as many times as possible, giving back as needed (greedy)
\n                 Match a line feed character
Cluster:           Match the characters “Cluster:” literally
\s                 Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
   *               Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
(?<cluster>        Match the regular expression below and capture its match into backreference with name “cluster”
   .               Match any single character that is not a line break character
      *            Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
)


问:
How to pass props from html div to the function component in react?
Don't know how to pass properties from html into react file.
This is the existing code,

```<code><html>
<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>

<body>

<div id="mydiv" parm="some info"></div>
<script type="text/babel" src="h2.js"></script>

</body>
</html>
</code>```

The react file, i'm manually sending props "parm={2}" for now.

```<code>const Hello = (props) => {
        console.log(props);
        return (<h2>h2 with function component {props.parm}</h2>);
}

ReactDOM.render(<Hello parm={2} />, document.getElementById('mydiv'));
</code>```

My Q is, how to pass parm from html to Hello() component ?
Pls note, i have to turn off CORS for local testing,
https://alfilatov.com/posts/run-chrome-without-cors/

答:
Sure, it's possible.

Note: I'm not sure what your use-case is. Maybe you are "sprinking" react into an existing project? If you are not, I'd suggest you take a look at the React docs as they might suggest a better way to achieve your outcome.

Anyway, here's an example that implements what you have asked. Notice your HTML param is logged to the console. You can then use it inside react.

https://codesandbox.io/s/params-to-react-from-html-lycqx?fontsize=14&hidenavigation=1&theme=dark

```<code>// here's how to get the value itself
const myParam = document
    .querySelector("#my_container") // get the html element, e.g. a div
    .getAttribute("myParam"); // get the value of the custom property on that element
</code>```

Hope it helps!

Body:
Don't know how to pass properties from html into react file.
This is the existing code,

The react file, i'm manually sending props "parm={2}" for now.

const Hello = (props) => {
        console.log(props);
        return (
h2 with function component {props.parm}
);
}

ReactDOM.render(<Hello parm={2} />, document.getElementById('mydiv'));

My Q is, how to pass parm from html to Hello() component ?
Pls note, i have to turn off CORS for local testing,
https://alfilatov.com/posts/run-chrome-without-cors/

Body:
Sure, it's possible.

Note: I'm not sure what your use-case is. Maybe you are "sprinking" react into an existing project? If you are not, I'd suggest you take a look at the React docs as they might suggest a better way to achieve your outcome.

Anyway, here's an example that implements what you have asked. Notice your HTML param is logged to the console. You can then use it inside react.

https://codesandbox.io/s/params-to-react-from-html-lycqx?fontsize=14&hidenavigation=1&theme=dark

// here's how to get the value itself
const myParam = document
    .querySelector("#my_container") // get the html element, e.g. a div
    .getAttribute("myParam"); // get the value of the custom property on that element

Hope it helps!


问:
Kotlin in Android - Suspend Functions in Room
I was looking at the sample at https://github.com/android/architecture-samples/tree/dev-dagger/app/src/main/java/com/example/android/architecture/blueprints/todoapp/data/source/local of the dev-dagger branch and in the TasksLocalDataSource.kt file they have the following method:

```<code>override suspend fun getTasks(): Result<List<Task>> = withContext(ioDispatcher) {
        return@withContext try {
            Success(tasksDao.getTasks())
        } catch (e: Exception) {
            Error(e)
        }
}
</code>```

By using withContext with an IO as dispatcher, they want the coroutine to run on an IO thread. But the Room request tasksDao.getTasks() inside the method is a suspend function. And in the codelab at https://codelabs.developers.google.com/codelabs/kotlin-coroutines/#8, they say that Room takes care of running the request (here: getTasks() ) on a background thread when it is a suspend function which is the case here.
So, isn't too much to use also a withContext(ioDispatcher) ? Could I not rewrite the method above also like the following way ? :

```<code>override suspend fun getTasks(): Result<List<Task>> {
         return Success(tasksDao.getTasks())
}
</code>```

答: Yes, this is exactly what you should write. There still appears to be a lot of legacy in the docs, from the time before they introduced suspendable Room calls. It is a waste both in terms of readability and performance to force a suspendable function call into the IO dispatcher.</p>

Body:
I was looking at the sample at https://github.com/android/architecture-samples/tree/dev-dagger/app/src/main/java/com/example/android/architecture/blueprints/todoapp/data/source/local of the dev-dagger branch and in the TasksLocalDataSource.kt file they have the following method:

override suspend fun getTasks(): Result<List<Task>> = withContext(ioDispatcher) {
        return@withContext try {
            Success(tasksDao.getTasks())
        } catch (e: Exception) {
            Error(e)
        }
}

By using withContext with an IO as dispatcher, they want the coroutine to run on an IO thread. But the Room request tasksDao.getTasks() inside the method is a suspend function. And in the codelab at https://codelabs.developers.google.com/codelabs/kotlin-coroutines/#8, they say that Room takes care of running the request (here: getTasks() ) on a background thread when it is a suspend function which is the case here.
So, isn't too much to use also a withContext(ioDispatcher) ? Could I not rewrite the method above also like the following way ? :

override suspend fun getTasks(): Result<List<Task>> {
         return Success(tasksDao.getTasks())
}