问:
Only extract those words from a list that include no repeating letters, using regex
I have a large word list file with one word per line. I would like to filter out the words with repeating alphabets.

```<code>INPUT:
  abducts
  abe
  abeam
  abel
  abele

OUTPUT:
  abducts
  abe
  abel
</code>```

I'd like to do this using Regex (grep or perl or python). Is that possible?

答:
Simple Stuff

Despite the inaccurate protestation that this is impossible with a regex, it certainly is.

While @cjm justly states that it is a lot easier to negate a positive match than  it is to express a negative one as a single pattern, the model for doing so is sufficiently well-known that it becomes a mere matter of plugging things into that model. Given that:

```
    /X/
```

matches something, then the way to express the condition

```
    ! /X/
```

in a single, positively-matching pattern is to write it as

```
    /\A (?: (?! X ) . ) * \z /sx
```

Therefore, given that the positive pattern is

```
    / (\pL) .* \1 /sxi
```

the corresponding negative needs must be

```
    /\A (?: (?! (\pL) .* \1  ) . ) * \z /sxi
```

by way of simple substitution for X.

Real-World Concerns

That said, there are extenuating concerns that may sometimes require more work. For example, while \pL describes any code point having the GeneralCategory=Letter property, it does not consider what to do with words like red‐violet–colored, ’Tisn’t, or fiancée — the latter of which is different in otherwise-equivalent NFD vs NFC forms.

You therefore must first run it through full decomposition, so that a string like "r\x{E9}sume\x{301}" would correctly detect the duplicate “letter é’s” — that is, all canonically equivalent grapheme cluster units.

To account for such as these, you must at a bare minimum first run your string through an NFD decomposition, and then afterwards also use grapheme clusters via \X instead of arbitrary code points via ..

So for English, you would want something that followed along these lines for the positive match, with the corresponding negative match per the substitution give above:

```
    NFD($string) =~ m{
        (?<ELEMENT>
           (?= [\p{Alphabetic}\p{Dash}\p{Quotation_Mark}] ) \X
        )
        \X *
        \k<ELEMENT>
    }xi
```

But even with that there still remain certain outstanding issues unresolved, such as for example whether \N{EN DASH} and \N{HYPHEN} should be considered equivalent elements or different ones.

That’s because properly written,  hyphenating two elements like red‐violet and colored to form the single compound word red‐violet–colored, where at least one of the pair already contains a hyphen, requires that one employ an EN DASH as the separator instead of a mere HYPHEN.

Normally the EN DASH is reserved for compounds of like nature, such as a time–space trade‐off. People using typewriter‐English don’t even do that, though, using that super‐massively overloaded legacy code point, HYPHEN-MINUS, for both: red-violet-colored.

It just depends whether your text came from some 19th‐century manual typewriter — or whether it represents English text properly rendered under modern typesetting rules. :)

Conscientious Case Insensitivity

You will note I am here considering letter that differ in case alone to be the same one. That’s because I use the /i regex switch, ᴀᴋᴀ the (?i) pattern modifier.

That’s rather like saying that they are the same as collation strength 1 — but not quite, because Perl uses only case folding (albeit full case folding not simple) for its case insensitive matches, not some higher collation strength than the tertiary level as might be preferred.

Full equivalence at the primary collation strength is a significantly stronger statement, but one that may well be needed to fully solve the problem in the general case. However, that requires a lot more work than the problem necessarily requires in many specific instances. In short, it is overkill for many specific cases that actually arise, no matter how much it might be needed for the hypothetical general case.

This is made even more difficult because, although you can for example do this:

```
    my $collator = new Unicode::Collate::Locale::
                       level => 1,
                       locale => "de__phonebook",
                       normalization => undef,
                    ;

    if ($collator->cmp("müß", "MUESS") == 0) { ... }
```

and expect to get the right answer — and you do, hurray! — this sort of robust string comparison is not easily extended to regex matches.

Yet. :)

Summary

The choice of whether to under‐engineer — or to over‐engineer — a solution will vary according to individual circumstances, which no one can decide for you.

I like CJM’s solution that negates a positive match, myself, although it’s somewhat cavalier about what it considers a duplicate letter.  Notice:

```
    while ("de__phonebook" =~ /(?=((\w).*?\2))/g) {
        print "The letter <$2> is duplicated in the substring <$1>.\n";
    }
```

produces:

```
    The letter <e> is duplicated in the substring <e__phone>.
    The letter <_> is duplicated in the substring <__>.
    The letter <o> is duplicated in the substring <onebo>.
    The letter <o> is duplicated in the substring <oo>.
```

That shows why when you need to match a letter, you should alwasy use \pL ᴀᴋᴀ \p{Letter} instead of \w, which actually matches [\p{alpha}\p{GC=Mark}\p{NT=De}\p{GC=Pc}].

Of course, when you need to match an alphabetic, you need to use \p{alpha} ᴀᴋᴀ\p{Alphabetic}, which isn’t at all the same as a mere letter — contrary to popular misunderstanding. :)

Body:
I have a large word list file with one word per line. I would like to filter out the words with repeating alphabets.

INPUT:
  abducts
  abe
  abeam
  abel
  abele

OUTPUT:
  abducts
  abe
  abel

I'd like to do this using Regex (grep or perl or python). Is that possible?

Body:
Simple Stuff

Despite the inaccurate protestation that this is impossible with a regex, it certainly is.

While @cjm justly states that it is a lot easier to negate a positive match than  it is to express a negative one as a single pattern, the model for doing so is sufficiently well-known that it becomes a mere matter of plugging things into that model. Given that:

    /X/

matches something, then the way to express the condition

    ! /X/

in a single, positively-matching pattern is to write it as

    /\A (?: (?! X ) . ) * \z /sx

Therefore, given that the positive pattern is

    / (\pL) .* \1 /sxi

the corresponding negative needs must be

    /\A (?: (?! (\pL) .* \1  ) . ) * \z /sxi

by way of simple substitution for X.

Real-World Concerns

That said, there are extenuating concerns that may sometimes require more work. For example, while \pL describes any code point having the GeneralCategory=Letter property, it does not consider what to do with words like red‐violet–colored, ’Tisn’t, or fiancée — the latter of which is different in otherwise-equivalent NFD vs NFC forms.

You therefore must first run it through full decomposition, so that a string like "r\x{E9}sume\x{301}" would correctly detect the duplicate “letter é’s” — that is, all canonically equivalent grapheme cluster units.

To account for such as these, you must at a bare minimum first run your string through an NFD decomposition, and then afterwards also use grapheme clusters via \X instead of arbitrary code points via ..

So for English, you would want something that followed along these lines for the positive match, with the corresponding negative match per the substitution give above:

    NFD($string) =~ m{
        (?<ELEMENT>
           (?= [\p{Alphabetic}\p{Dash}\p{Quotation_Mark}] ) \X
        )
        \X *
        \k<ELEMENT>
    }xi

But even with that there still remain certain outstanding issues unresolved, such as for example whether \N{EN DASH} and \N{HYPHEN} should be considered equivalent elements or different ones.

That’s because properly written,  hyphenating two elements like red‐violet and colored to form the single compound word red‐violet–colored, where at least one of the pair already contains a hyphen, requires that one employ an EN DASH as the separator instead of a mere HYPHEN.

Normally the EN DASH is reserved for compounds of like nature, such as a time–space trade‐off. People using typewriter‐English don’t even do that, though, using that super‐massively overloaded legacy code point, HYPHEN-MINUS, for both: red-violet-colored.

It just depends whether your text came from some 19th‐century manual typewriter — or whether it represents English text properly rendered under modern typesetting rules. :)

Conscientious Case Insensitivity

You will note I am here considering letter that differ in case alone to be the same one. That’s because I use the /i regex switch, ᴀᴋᴀ the (?i) pattern modifier.

That’s rather like saying that they are the same as collation strength 1 — but not quite, because Perl uses only case folding (albeit full case folding not simple) for its case insensitive matches, not some higher collation strength than the tertiary level as might be preferred.

Full equivalence at the primary collation strength is a significantly stronger statement, but one that may well be needed to fully solve the problem in the general case. However, that requires a lot more work than the problem necessarily requires in many specific instances. In short, it is overkill for many specific cases that actually arise, no matter how much it might be needed for the hypothetical general case.

This is made even more difficult because, although you can for example do this:

    my $collator = new Unicode::Collate::Locale::
                       level => 1,
                       locale => "de__phonebook",
                       normalization => undef,
                    ;

    if ($collator->cmp("müß", "MUESS") == 0) { ... }

and expect to get the right answer — and you do, hurray! — this sort of robust string comparison is not easily extended to regex matches.

Yet. :)

Summary

The choice of whether to under‐engineer — or to over‐engineer — a solution will vary according to individual circumstances, which no one can decide for you.

I like CJM’s solution that negates a positive match, myself, although it’s somewhat cavalier about what it considers a duplicate letter.  Notice:

    while ("de__phonebook" =~ /(?=((\w).*?\2))/g) {
        print "The letter <$2> is duplicated in the substring <$1>.\n";
    }

produces:

    The letter <e> is duplicated in the substring <e__phone>.
    The letter <_> is duplicated in the substring <__>.
    The letter <o> is duplicated in the substring <onebo>.
    The letter <o> is duplicated in the substring <oo>.

That shows why when you need to match a letter, you should alwasy use \pL ᴀᴋᴀ \p{Letter} instead of \w, which actually matches [\p{alpha}\p{GC=Mark}\p{NT=De}\p{GC=Pc}].

Of course, when you need to match an alphabetic, you need to use \p{alpha} ᴀᴋᴀ\p{Alphabetic}, which isn’t at all the same as a mere letter — contrary to popular misunderstanding. :)


来源: stackexchange

问:
Python | Reading JSON files and applying simple algorithm on each iteratively into a dataframe
we have a large json file that takes too long to be read with pd.read_json.

What we want to do initially is :

```<code># Load the file
df_view = pd.read_json('/path/to/file', lines=True)

# Create a new feature using the above dataframe
df_nb_view = df_view[['userid','itemid']]
df_nb_view = df_nb_view.groupby('userid').count()
df_nb_view.rename(index=str, columns = {"itemid":'item_viewed'}, inplace=True)
</code>```

So I've divided the dataset into subsets of it in one folder, and would like to read iteratively into it so as to do the work above on each subset, and concatenating the result at each step.

Hope this is clear enough.

I started out with this so as to read each file into one final df, but not sure how to create the new features in the process.

```<code>files = []
for file in os.listdir("/path/to/folder"):
    if file.endswith(".json"):
        files.append(os.path.join("/path/to/folder", file))

for file in files:
    with codecs.open(file,'r','utf-8') as f:
        df_view = json.load(f, encoding='utf-b')
</code>```

Thanks a lot in advance.

答:
If I understand correctly, you want to read and process in file chunks.
If so, create a final result dataframe and append to it in each iteration</p>

```<code>final_df = pd.DataFrame()

for filename in files:
    df_view = pd.read_json(filename, lines=True)
    df_nb_view = df_view[['userid','itemid']]
    df_nb_view = df_nb_view.groupby('userid').count()
    df_nb_view.rename(index=str, columns = {"itemid":'item_viewed'}, inplace=True)

    final_df.append(df_nb_view)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
we have a large json file that takes too long to be read with pd.read_json.

What we want to do initially is :

# Load the file
df_view = pd.read_json('/path/to/file', lines=True)

# Create a new feature using the above dataframe
df_nb_view = df_view[['userid','itemid']]
df_nb_view = df_nb_view.groupby('userid').count()
df_nb_view.rename(index=str, columns = {"itemid":'item_viewed'}, inplace=True)

So I've divided the dataset into subsets of it in one folder, and would like to read iteratively into it so as to do the work above on each subset, and concatenating the result at each step.

Hope this is clear enough.

I started out with this so as to read each file into one final df, but not sure how to create the new features in the process.

files = []
for file in os.listdir("/path/to/folder"):
    if file.endswith(".json"):
        files.append(os.path.join("/path/to/folder", file))

for file in files:
    with codecs.open(file,'r','utf-8') as f:
        df_view = json.load(f, encoding='utf-b')

Thanks a lot in advance.

Body:
If I understand correctly, you want to read and process in file chunks.
If so, create a final result dataframe and append to it in each iteration

final_df = pd.DataFrame()

for filename in files:
    df_view = pd.read_json(filename, lines=True)
    df_nb_view = df_view[['userid','itemid']]
    df_nb_view = df_nb_view.groupby('userid').count()
    df_nb_view.rename(index=str, columns = {"itemid":'item_viewed'}, inplace=True)

    final_df.append(df_nb_view)


问:
React.js - passing props to children from hoc
I have been trying to pass some props from my HOC to children. the HOC wraps react router switch and route. The props are missing in the child component. I make use of React.CloneElement to add the props to the children but do not seem to work

```<code><BrowserRouter>
<Layout>
        <React.Suspense fallback={loading()}>
          <Switch>
            <Route exact path="/" component={Login} />
            <Route path="/dashboard" component={Home} />
            <Route path="/tickets" component={Tickets} />

          </Switch>
        </React.Suspense>
      </Layout>
    </BrowserRouter>
</code>```

this is the HOC(layout)

```<code>class Layout extends React.Component {
   .....

    render() {
        const children = this.props.children && React.cloneElement(this.props.children, { data: 'ok' })
...
</code>```

the child component do no get the data prop, I get just this

```<code>{history: {…}, location: {…}, match: {…}, staticContext: undefined}
</code>```

答:
A working HOC example that injects a data prop into the base component.

/* HOC */
const withData = Base => () => <Base data="ok" />

/* Component */
class Router extends React.Component {
  render() {
    return this.props.data;
  }
}

const RouterWithData = withData(Router); // export default withData(Router);

ReactDOM.render(<RouterWithData />, document.getElementById('root'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div></code>```

Body:
I have been trying to pass some props from my HOC to children. the HOC wraps react router switch and route. The props are missing in the child component. I make use of React.CloneElement to add the props to the children but do not seem to work

<BrowserRouter>
<Layout>
        <React.Suspense fallback={loading()}>
          <Switch>
            <Route exact path="/" component={Login} />
            <Route path="/dashboard" component={Home} />
            <Route path="/tickets" component={Tickets} />

          </Switch>
        </React.Suspense>
      </Layout>
    </BrowserRouter>

this is the HOC(layout)

class Layout extends React.Component {
   .....

    render() {
        const children = this.props.children && React.cloneElement(this.props.children, { data: 'ok' })
...

the child component do no get the data prop, I get just this

{history: {…}, location: {…}, match: {…}, staticContext: undefined}

Body:
A working HOC example that injects a data prop into the base component.

/* HOC */
const withData = Base => () => <Base data="ok" />

/* Component */
class Router extends React.Component {
  render() {
    return this.props.data;
  }
}

const RouterWithData = withData(Router); // export default withData(Router);

ReactDOM.render(<RouterWithData />, document.getElementById('root'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>


问:
How to check if a string contains a substring from an array and split it
I have an array of string like:

```<code>var matchCodFisc = ["C.F.", "CF", "Cod.Fisc.", "C.F"]
</code>```

and I want to check if in my string
(e.g. var myString= "Cod.Fisc.FGDTFR34L16G643W") exists that substring (in this case "Cod.Fisc").
If I found the substring I want to split my string in two parts like ["Cod.Fisc", "FGDTFR34L16G643W"]. How can I do that using JavaScript?

答:
You could find the string and take the rest. Maybe it is better to sort the pattern array by length descending, because it finds the longest string first.

var matchCodFisc = ["C.F.", "CF", "Cod.Fisc.", "C.F"],
    string = "Cod.Fisc.FGDTFR34L16G643W",
    found = matchCodFisc
        .sort((a, b) => b.length - a.length)
        .find(s => string.startsWith(s)),
    result = [found, string.slice(found.length)];

console.log(result);```

Body:
I have an array of string like:

var matchCodFisc = ["C.F.", "CF", "Cod.Fisc.", "C.F"]

and I want to check if in my string
(e.g. var myString= "Cod.Fisc.FGDTFR34L16G643W") exists that substring (in this case "Cod.Fisc").
If I found the substring I want to split my string in two parts like ["Cod.Fisc", "FGDTFR34L16G643W"]. How can I do that using JavaScript?


问:
Data structure to store key - value pair where the value can be modified in objective-C
I want to have a data structure where corresponding to each key I have a value(Int) associated where the value can be modified like some value can be added to it.

Can NSMutableDictionary work ?

If yes then how ?

答:
You can do it like this:

```<code>NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:[NSNumber numberWithInt:42] forKey:@"key1"];

int myNumber = [[dict objectForKey:@"key1"] intValue];
myNumber = myNumber + 10;

dict[@"key1"] = [NSNumber numberWithInt:myNumber];
NSLog(@"%@", dict);
</code>```

The output of the given code is:

```<code>{
    key1 = 52;
}
</code>```

Body:
You can do it like this:

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:[NSNumber numberWithInt:42] forKey:@"key1"];

int myNumber = [[dict objectForKey:@"key1"] intValue];
myNumber = myNumber + 10;

dict[@"key1"] = [NSNumber numberWithInt:myNumber];
NSLog(@"%@", dict);

The output of the given code is:

{
    key1 = 52;
}


问:
How to show the each levels with different color in sunburst chart?
I have created a sunburst chart with the help of the Anychart library. Now I want to fill different colors on each level. Like blue color background in all slice of level-1. all data is coming dynamically from SQL. How I can do this?Sample image of what I want</p>

答: Colors of the children in Sunburst chart are inherited from the parent. It means the only way to achieve what you want is to set them for each point in the data. Please check this sample: https://playground.anychart.com/997YGRTI</p>


问:
Merge Rows of Dataframe based on condition
I have a csv file with only one column "notes". I want to merge rows of data-frame based on some condition.

Input_data={'notes':
            ['aaa','bbb','*','hello','**','my name','is xyz',
             '(1)','this is','temp','name',
             '(2)','BTW','how to','solve this',
             '(3)','with python','I don’t want this to be added ',
             'I don’t want this to be added ']}

df_in = pd.DataFrame(Input_data)
```

<p>Input looks like this </p>

<p><img src="https://i.stack.imgur.com/CWOAt.png" alt="Sample input"></p>

<p>Output</p>

<pre class="lang-py prettyprint-override"><code>output_Data={'notes':
             ['aaa','bbb','*hello','**my name is xyz',
              '(1) this is temp name',
              '(2) BTW how to solve this',
              '(3) with python','I don’t want this to be added ',
              'I don’t want this to be added ']}
df_out=pd.DataFrame(output_Data)
</code>```

I want to merge the rows with the above row which have either "*" or "(number)" in it. So the output will look like

Other rows which can not be merged should be left.
Also, in case of last row as there is no proper way to know up-to what range we can merge lets say just add only one next row
I solved this but its very long. Any simpler way

```<code>df=pd.DataFrame(Input_data)
notes=[];temp=[];flag='';value='';c=0;chk_star='yes'
for i,row in df.iterrows():
    row[0]=str(row[0])
    if '*' in row[0].strip()[:5] and chk_star=='yes':
        value=row[0].strip()
        temp=temp+[value]
        value=''
        continue

    if '(' in row[0].strip()[:5]:
        chk_star='no'
        temp=temp+[value]
        value='';c=0
        flag='continue'
        value=row[0].strip()
    if flag=='continue' and '(' not in row[0][:5] :
        value=value+row[0]
        c=c+1
    if c>4:
        temp=temp+[value]
        print "111",value,temp
        break
if '' in temp:
    temp.remove('')
df=pd.DataFrame({'notes':temp})
</code>```

答:
You can use a mask to avoid the for loop :

```<code>df = pd.DataFrame({'row':['aaa','bbb','*','hello','**','my name','is xyz',
         '(1)','this is ','temp ','name',
         '(2)','BTW ','how to ','solve this',
         '(3)','with python ','I don’t want this to be added ',
         'I don’t want this to be added ']})

special = ['*', '**']
for i in range(11):
    special.append('({})'.format(i))

# We find the indexes where we will have to merge
index_to_merge = df[df['row'].isin(special)].index.values
for idx, val in enumerate(index_to_merge):
    if idx != len(index_to_merge)-1:
        df.loc[val, 'row'] += ' ' + df.loc[val+1:index_to_merge[idx+1]-1, 'row'].values.sum()
    else:
        df.loc[index, 'row'] += ' ' + df.loc[index+1:, 'row'].values.sum()

# We delete the rows that we just used to merge
df.drop([x for x in np.array(range(len(df))) if x not in index_to_merge])
</code>```

Out :

```<code>        row
2   * hello
4   ** my nameis xyz
7   (1) this is temp name
11  (2) BTW how to solve this
15  (3) with python I don’t want this to be added ..
</code>```

You could also convert your column into a numpy array and use numpy functions to simplify what you did. First you can use the np.where and np.isin to find the indexes where you will have to merge. That way you don't have to iterate on your whole array using a for loop.

Then you can do the mergures on the corresponding indexes. Finally, you can delete the values that have been merged. Here is what it could look like :

```<code>list_to_merge = np.array(['aaa','bbb','*','hello','**','my name','is xyz',
             '(1)','this is','temp','name',
             '(2)','BTW','how to','solve this',
             '(3)','with python','I don’t want this to be added ',
             'I don’t want this to be added '])
special = ['*', '**']
for i in range(11):
    special.append('({})'.format(i))

ix = np.isin(list_to_merge, special)
rows_to_merge = np.where(ix)[0]

# We merge the rows
for index_to_merge in np.where(ix)[0]:
    # Check if there we are not trying to merge with an out of bounds value
    if index_to_merge!=len(list_to_merge)-1:
        list_to_merge[index_to_merge] = list_to_merge[index_to_merge] + ' ' + list_to_merge[index_to_merge+1]

# We delete the rows that have just been used to merge:
rows_to_delete = rows_to_merge +1
list_to_merge = np.delete(list_to_merge, rows_to_delete)
</code>```

Out :

```<code>['aaa', 'bbb', '* hello', '** my name', 'is xyz', '(1) this is',
       'temp', 'name', '(2) BTW', 'how to', 'solve this',
       '(3) with python', 'I don’t want this to be added ',
       'I don’t want this to be added ']
</code>```

Body:
I have a csv file with only one column "notes". I want to merge rows of data-frame based on some condition.

Input_data={'notes':
            ['aaa','bbb','*','hello','**','my name','is xyz',
             '(1)','this is','temp','name',
             '(2)','BTW','how to','solve this',
             '(3)','with python','I don’t want this to be added ',
             'I don’t want this to be added ']}

df_in = pd.DataFrame(Input_data)

Input looks like this

Output

output_Data={'notes':
             ['aaa','bbb','*hello','**my name is xyz',
              '(1) this is temp name',
              '(2) BTW how to solve this',
              '(3) with python','I don’t want this to be added ',
              'I don’t want this to be added ']}
df_out=pd.DataFrame(output_Data)

I want to merge the rows with the above row which have either "*" or "(number)" in it. So the output will look like

Other rows which can not be merged should be left.
Also, in case of last row as there is no proper way to know up-to what range we can merge lets say just add only one next row
I solved this but its very long. Any simpler way

df=pd.DataFrame(Input_data)
notes=[];temp=[];flag='';value='';c=0;chk_star='yes'
for i,row in df.iterrows():
    row[0]=str(row[0])
    if '*' in row[0].strip()[:5] and chk_star=='yes':
        value=row[0].strip()
        temp=temp+[value]
        value=''
        continue

    if '(' in row[0].strip()[:5]:
        chk_star='no'
        temp=temp+[value]
        value='';c=0
        flag='continue'
        value=row[0].strip()
    if flag=='continue' and '(' not in row[0][:5] :
        value=value+row[0]
        c=c+1
    if c>4:
        temp=temp+[value]
        print "111",value,temp
        break
if '' in temp:
    temp.remove('')
df=pd.DataFrame({'notes':temp})

Body:
You can use a mask to avoid the for loop :

df = pd.DataFrame({'row':['aaa','bbb','*','hello','**','my name','is xyz',
         '(1)','this is ','temp ','name',
         '(2)','BTW ','how to ','solve this',
         '(3)','with python ','I don’t want this to be added ',
         'I don’t want this to be added ']})

special = ['*', '**']
for i in range(11):
    special.append('({})'.format(i))

# We find the indexes where we will have to merge
index_to_merge = df[df['row'].isin(special)].index.values
for idx, val in enumerate(index_to_merge):
    if idx != len(index_to_merge)-1:
        df.loc[val, 'row'] += ' ' + df.loc[val+1:index_to_merge[idx+1]-1, 'row'].values.sum()
    else:
        df.loc[index, 'row'] += ' ' + df.loc[index+1:, 'row'].values.sum()

# We delete the rows that we just used to merge
df.drop([x for x in np.array(range(len(df))) if x not in index_to_merge])

Out :

        row
2   * hello
4   ** my nameis xyz
7   (1) this is temp name
11  (2) BTW how to solve this
15  (3) with python I don’t want this to be added ..

You could also convert your column into a numpy array and use numpy functions to simplify what you did. First you can use the np.where and np.isin to find the indexes where you will have to merge. That way you don't have to iterate on your whole array using a for loop.

Then you can do the mergures on the corresponding indexes. Finally, you can delete the values that have been merged. Here is what it could look like :

list_to_merge = np.array(['aaa','bbb','*','hello','**','my name','is xyz',
             '(1)','this is','temp','name',
             '(2)','BTW','how to','solve this',
             '(3)','with python','I don’t want this to be added ',
             'I don’t want this to be added '])
special = ['*', '**']
for i in range(11):
    special.append('({})'.format(i))

ix = np.isin(list_to_merge, special)
rows_to_merge = np.where(ix)[0]

# We merge the rows
for index_to_merge in np.where(ix)[0]:
    # Check if there we are not trying to merge with an out of bounds value
    if index_to_merge!=len(list_to_merge)-1:
        list_to_merge[index_to_merge] = list_to_merge[index_to_merge] + ' ' + list_to_merge[index_to_merge+1]

# We delete the rows that have just been used to merge:
rows_to_delete = rows_to_merge +1
list_to_merge = np.delete(list_to_merge, rows_to_delete)

Out :

['aaa', 'bbb', '* hello', '** my name', 'is xyz', '(1) this is',
       'temp', 'name', '(2) BTW', 'how to', 'solve this',
       '(3) with python', 'I don’t want this to be added ',
       'I don’t want this to be added ']


问:
Convert Encryption Java code into Go code
I have following java code that does encryption and decryption using RSA Public and Private keys.

I wrote similar code in GO to do the same.

But when I try to decrypt a string using Go code that was encrypted in Java code, I see error:
crypto/rsa: decryption error

public class EncryptDecryptUtil {

    private static final String MODE = "RSA/None/OAEPWithSHA256AndMGF1Padding";
    private static EncryptDecryptUtil single_instance = null;

    public static EncryptDecryptUtil getInstance()
    {
        if (single_instance == null)
            single_instance = new EncryptDecryptUtil();
        return single_instance;
    }

    public static String encryptText(String text, String keyStr) throws Exception {
        String resultText = null;
        try {
            Security.addProvider(new BouncyCastleProvider());
            Key publicKey = getRSAPublicFromPemFormat(keyStr);
            Cipher cipher = Cipher.getInstance(MODE, "BC");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            resultText = new String(Base64.getUrlEncoder().encodeToString(cipher.doFinal(text.getBytes())));
        } catch (IOException | GeneralSecurityException e) {
            e.printStackTrace();
        }
        return resultText;
    }

    public static String decryptText(String text, String keyStr) throws Exception {
        String resultText = null;
        try {
            Security.addProvider(new BouncyCastleProvider());
            Key privateKey = getRSAPrivateFromPemFormat(keyStr);
            Cipher cipher = Cipher.getInstance(MODE, "BC");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            resultText = new String(cipher.doFinal(Base64.getUrlDecoder().decode(text.getBytes())));

        } catch (IOException | GeneralSecurityException e) {
            e.printStackTrace();
        }
        return resultText;
    }

    private static PrivateKey getRSAPrivateFromPemFormat(String keyStr) throws Exception {
        return (PrivateKey) getKeyFromPEMString(keyStr, data -> new PKCS8EncodedKeySpec(data), (kf, spec) -> {
            try {
                return kf.generatePrivate(spec);
            } catch (InvalidKeySpecException e) {
                System.out.println("Cannot generate PrivateKey from String : " + keyStr + e);
                return null;
            }
        });
    }

    private static PublicKey getRSAPublicFromPemFormat(String keyStr) throws Exception {
        return (PublicKey) getKeyFromPEMString(keyStr, data -> new X509EncodedKeySpec(data), (kf, spec) -> {
            try {
                return kf.generatePublic(spec);
            } catch (InvalidKeySpecException e) {
                System.out.println("Cannot generate PublicKey from String : " + keyStr + e);
                return null;
            }
        });
    }

    private static Key getKeyFromPEMString(String key, Function<byte[], EncodedKeySpec> buildSpec,
                                         BiFunction<KeyFactory, EncodedKeySpec, ? extends Key> getKey) throws Exception {
        try {
            // Read PEM Format
            PemReader pemReader = new PemReader(new StringReader(key));
            PemObject pemObject = pemReader.readPemObject();
            pemReader.close();

            KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
            return getKey.apply(kf, buildSpec.apply(pemObject.getContent()));
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }

}

```

<pre class="lang-golang prettyprint-override"><code>package encryption

import (
    "crypto/rand"
    "crypto/rsa"
    "crypto/sha512"
    "crypto/x509"
    "encoding/base64"
    "encoding/pem"
    "fmt"
    "io/ioutil"
    "log"
)

// Encrypt encrypts string with public key
func Encrypt(msg string, publicKeyFilePath string) (string, error) {
    pubKey, err := ReadPublicKey(publicKeyFilePath)
    if err != nil {
        return "", err
    }
    encrypted, err := encrypt([]byte(msg), pubKey)
    if err != nil {
        return "", err
    }
    base64Encoded := base64.URLEncoding.WithPadding(61).EncodeToString(encrypted)
    return base64Encoded, nil
}

// Decrypt decrypts string with private key
func Decrypt(msg string, privateKeyFilePath string) (string, error) {
    privKey, err := ReadPrivateKey(privateKeyFilePath)
    if err != nil {
        return "", err
    }
    base64Decoded, err := base64.URLEncoding.WithPadding(61).DecodeString(msg)
    if err != nil {
        return "", err
    }
    decrypted, err := decrypt(base64Decoded, privKey)
    if err != nil {
        return "", err
    }
    return string(decrypted), nil
}

// GenerateKeyPair generates a new key pair
func GenerateKeyPair(bits int) (*rsa.PrivateKey, *rsa.PublicKey, error) {
    privkey, err := rsa.GenerateKey(rand.Reader, bits)
    if err != nil {
        return nil, nil, fmt.Errorf("Error generating Key Pair: %s", err)
    }
    return privkey, &privkey.PublicKey, nil
}

// ReadPublicKey reads public key from a file
func ReadPublicKey(publicKeyFile string) (*rsa.PublicKey, error) {
    pubPemData, err := ioutil.ReadFile(publicKeyFile)
    if err != nil {
        return nil, fmt.Errorf("Error [%s] reading public key from file: %s", err, publicKeyFile)
    }
    return BytesToPublicKey(pubPemData)
}

// ReadPrivateKey reads private key from a file
func ReadPrivateKey(privateKeyFile string) (*rsa.PrivateKey, error) {
    privKeyData, err := ioutil.ReadFile(privateKeyFile)
    if err != nil {
        return nil, fmt.Errorf("Error [%s] reading private key from file: %s", err, privateKeyFile)
    }
    return BytesToPrivateKey(privKeyData)
}

// PrivateKeyToBytes private key to bytes
func PrivateKeyToBytes(priv *rsa.PrivateKey) []byte {
    privBytes := pem.EncodeToMemory(
        &pem.Block{
            Type:  "RSA PRIVATE KEY",
            Bytes: x509.MarshalPKCS1PrivateKey(priv),
        },
    )

    return privBytes
}

// PublicKeyToBytes public key to bytes
func PublicKeyToBytes(pub *rsa.PublicKey) ([]byte, error) {
    pubASN1, err := x509.MarshalPKIXPublicKey(pub)
    if err != nil {
        return nil, fmt.Errorf("Error converting PublicKey to Bytes: %s", err)

    }

    pubBytes := pem.EncodeToMemory(&pem.Block{
        Type:  "RSA PUBLIC KEY",
        Bytes: pubASN1,
    })

    return pubBytes, nil
}

// BytesToPrivateKey bytes to private key
func BytesToPrivateKey(priv []byte) (*rsa.PrivateKey, error) {
    block, _ := pem.Decode(priv)

    enc := x509.IsEncryptedPEMBlock(block)
    b := block.Bytes
    var err error
    if enc {
        log.Println("is encrypted pem block")
        b, err = x509.DecryptPEMBlock(block, nil)
        if err != nil {
            return nil, fmt.Errorf("Error decrypting PEM Block: %s", err)
        }
    }
    key, err := x509.ParsePKCS1PrivateKey(b)
    if err != nil {
        return nil, fmt.Errorf("Error parsing PKCS1 Private Key: %s", err)
    }
    return key, nil
}

// BytesToPublicKey bytes to public key
func BytesToPublicKey(pub []byte) (*rsa.PublicKey, error) {
    block, _ := pem.Decode(pub)

    enc := x509.IsEncryptedPEMBlock(block)
    b := block.Bytes
    var err error
    if enc {
        log.Println("is encrypted pem block")
        b, err = x509.DecryptPEMBlock(block, nil)
        if err != nil {
            return nil, fmt.Errorf("Error decrypting PEM Block: %s", err)
        }
    }
    ifc, err := x509.ParsePKIXPublicKey(b)
    if err != nil {
        return nil, fmt.Errorf("Error parsing PKCS1 Public Key: %s", err)
    }
    key, ok := ifc.(*rsa.PublicKey)
    if !ok {
        return nil, fmt.Errorf("Error converting to Public Key: %s", err)
    }
    return key, nil
}

// encrypt encrypts data with public key
func encrypt(msg []byte, pub *rsa.PublicKey) ([]byte, error) {
    hash := sha512.New()
    ciphertext, err := rsa.EncryptOAEP(hash, rand.Reader, pub, msg, nil)
    if err != nil {
        return nil, fmt.Errorf("Error encrypting: %s", err)
    }
    return ciphertext, nil
}

// Decrypt decrypts data with private key
func decrypt(ciphertext []byte, priv *rsa.PrivateKey) ([]byte, error) {
    hash := sha512.New()
    plaintext, err := rsa.DecryptOAEP(hash, rand.Reader, priv, ciphertext, nil)
    if err != nil {
        return nil, fmt.Errorf("Error decrypting: %s", err)
    }
    return plaintext, nil
}

</code>```

How to make sure that value encrypted using java code is decrypted properly by Go code.

答:
Based on comments from @Michael, I changed go code to use sha256.New() instead of sha512.New() and that solved the issue. (Good catch!)
I am now able to encrypt in Java and decrypt in Go.</p>

Body:
I have following java code that does encryption and decryption using RSA Public and Private keys.

I wrote similar code in GO to do the same.

But when I try to decrypt a string using Go code that was encrypted in Java code, I see error:
crypto/rsa: decryption error

public class EncryptDecryptUtil {

    private static final String MODE = "RSA/None/OAEPWithSHA256AndMGF1Padding";
    private static EncryptDecryptUtil single_instance = null;

    public static EncryptDecryptUtil getInstance()
    {
        if (single_instance == null)
            single_instance = new EncryptDecryptUtil();
        return single_instance;
    }

    public static String encryptText(String text, String keyStr) throws Exception {
        String resultText = null;
        try {
            Security.addProvider(new BouncyCastleProvider());
            Key publicKey = getRSAPublicFromPemFormat(keyStr);
            Cipher cipher = Cipher.getInstance(MODE, "BC");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            resultText = new String(Base64.getUrlEncoder().encodeToString(cipher.doFinal(text.getBytes())));
        } catch (IOException | GeneralSecurityException e) {
            e.printStackTrace();
        }
        return resultText;
    }

    public static String decryptText(String text, String keyStr) throws Exception {
        String resultText = null;
        try {
            Security.addProvider(new BouncyCastleProvider());
            Key privateKey = getRSAPrivateFromPemFormat(keyStr);
            Cipher cipher = Cipher.getInstance(MODE, "BC");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            resultText = new String(cipher.doFinal(Base64.getUrlDecoder().decode(text.getBytes())));

        } catch (IOException | GeneralSecurityException e) {
            e.printStackTrace();
        }
        return resultText;
    }

    private static PrivateKey getRSAPrivateFromPemFormat(String keyStr) throws Exception {
        return (PrivateKey) getKeyFromPEMString(keyStr, data -> new PKCS8EncodedKeySpec(data), (kf, spec) -> {
            try {
                return kf.generatePrivate(spec);
            } catch (InvalidKeySpecException e) {
                System.out.println("Cannot generate PrivateKey from String : " + keyStr + e);
                return null;
            }
        });
    }

    private static PublicKey getRSAPublicFromPemFormat(String keyStr) throws Exception {
        return (PublicKey) getKeyFromPEMString(keyStr, data -> new X509EncodedKeySpec(data), (kf, spec) -> {
            try {
                return kf.generatePublic(spec);
            } catch (InvalidKeySpecException e) {
                System.out.println("Cannot generate PublicKey from String : " + keyStr + e);
                return null;
            }
        });
    }

    private static Key getKeyFromPEMString(String key, Function<byte[], EncodedKeySpec> buildSpec,
                                         BiFunction<KeyFactory, EncodedKeySpec, ? extends Key> getKey) throws Exception {
        try {
            // Read PEM Format
            PemReader pemReader = new PemReader(new StringReader(key));
            PemObject pemObject = pemReader.readPemObject();
            pemReader.close();

            KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
            return getKey.apply(kf, buildSpec.apply(pemObject.getContent()));
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }

}

package encryption

import (
    "crypto/rand"
    "crypto/rsa"
    "crypto/sha512"
    "crypto/x509"
    "encoding/base64"
    "encoding/pem"
    "fmt"
    "io/ioutil"
    "log"
)

// Encrypt encrypts string with public key
func Encrypt(msg string, publicKeyFilePath string) (string, error) {
    pubKey, err := ReadPublicKey(publicKeyFilePath)
    if err != nil {
        return "", err
    }
    encrypted, err := encrypt([]byte(msg), pubKey)
    if err != nil {
        return "", err
    }
    base64Encoded := base64.URLEncoding.WithPadding(61).EncodeToString(encrypted)
    return base64Encoded, nil
}

// Decrypt decrypts string with private key
func Decrypt(msg string, privateKeyFilePath string) (string, error) {
    privKey, err := ReadPrivateKey(privateKeyFilePath)
    if err != nil {
        return "", err
    }
    base64Decoded, err := base64.URLEncoding.WithPadding(61).DecodeString(msg)
    if err != nil {
        return "", err
    }
    decrypted, err := decrypt(base64Decoded, privKey)
    if err != nil {
        return "", err
    }
    return string(decrypted), nil
}

// GenerateKeyPair generates a new key pair
func GenerateKeyPair(bits int) (*rsa.PrivateKey, *rsa.PublicKey, error) {
    privkey, err := rsa.GenerateKey(rand.Reader, bits)
    if err != nil {
        return nil, nil, fmt.Errorf("Error generating Key Pair: %s", err)
    }
    return privkey, &privkey.PublicKey, nil
}

// ReadPublicKey reads public key from a file
func ReadPublicKey(publicKeyFile string) (*rsa.PublicKey, error) {
    pubPemData, err := ioutil.ReadFile(publicKeyFile)
    if err != nil {
        return nil, fmt.Errorf("Error [%s] reading public key from file: %s", err, publicKeyFile)
    }
    return BytesToPublicKey(pubPemData)
}

// ReadPrivateKey reads private key from a file
func ReadPrivateKey(privateKeyFile string) (*rsa.PrivateKey, error) {
    privKeyData, err := ioutil.ReadFile(privateKeyFile)
    if err != nil {
        return nil, fmt.Errorf("Error [%s] reading private key from file: %s", err, privateKeyFile)
    }
    return BytesToPrivateKey(privKeyData)
}

// PrivateKeyToBytes private key to bytes
func PrivateKeyToBytes(priv *rsa.PrivateKey) []byte {
    privBytes := pem.EncodeToMemory(
        &pem.Block{
            Type:  "RSA PRIVATE KEY",
            Bytes: x509.MarshalPKCS1PrivateKey(priv),
        },
    )

    return privBytes
}

// PublicKeyToBytes public key to bytes
func PublicKeyToBytes(pub *rsa.PublicKey) ([]byte, error) {
    pubASN1, err := x509.MarshalPKIXPublicKey(pub)
    if err != nil {
        return nil, fmt.Errorf("Error converting PublicKey to Bytes: %s", err)

    }

    pubBytes := pem.EncodeToMemory(&pem.Block{
        Type:  "RSA PUBLIC KEY",
        Bytes: pubASN1,
    })

    return pubBytes, nil
}

// BytesToPrivateKey bytes to private key
func BytesToPrivateKey(priv []byte) (*rsa.PrivateKey, error) {
    block, _ := pem.Decode(priv)

    enc := x509.IsEncryptedPEMBlock(block)
    b := block.Bytes
    var err error
    if enc {
        log.Println("is encrypted pem block")
        b, err = x509.DecryptPEMBlock(block, nil)
        if err != nil {
            return nil, fmt.Errorf("Error decrypting PEM Block: %s", err)
        }
    }
    key, err := x509.ParsePKCS1PrivateKey(b)
    if err != nil {
        return nil, fmt.Errorf("Error parsing PKCS1 Private Key: %s", err)
    }
    return key, nil
}

// BytesToPublicKey bytes to public key
func BytesToPublicKey(pub []byte) (*rsa.PublicKey, error) {
    block, _ := pem.Decode(pub)

    enc := x509.IsEncryptedPEMBlock(block)
    b := block.Bytes
    var err error
    if enc {
        log.Println("is encrypted pem block")
        b, err = x509.DecryptPEMBlock(block, nil)
        if err != nil {
            return nil, fmt.Errorf("Error decrypting PEM Block: %s", err)
        }
    }
    ifc, err := x509.ParsePKIXPublicKey(b)
    if err != nil {
        return nil, fmt.Errorf("Error parsing PKCS1 Public Key: %s", err)
    }
    key, ok := ifc.(*rsa.PublicKey)
    if !ok {
        return nil, fmt.Errorf("Error converting to Public Key: %s", err)
    }
    return key, nil
}

// encrypt encrypts data with public key
func encrypt(msg []byte, pub *rsa.PublicKey) ([]byte, error) {
    hash := sha512.New()
    ciphertext, err := rsa.EncryptOAEP(hash, rand.Reader, pub, msg, nil)
    if err != nil {
        return nil, fmt.Errorf("Error encrypting: %s", err)
    }
    return ciphertext, nil
}

// Decrypt decrypts data with private key
func decrypt(ciphertext []byte, priv *rsa.PrivateKey) ([]byte, error) {
    hash := sha512.New()
    plaintext, err := rsa.DecryptOAEP(hash, rand.Reader, priv, ciphertext, nil)
    if err != nil {
        return nil, fmt.Errorf("Error decrypting: %s", err)
    }
    return plaintext, nil
}

How to make sure that value encrypted using java code is decrypted properly by Go code.


问:
Doesn't take the result from View to ViewModel MVVM light
My ViewModel Doesn't take the value from model

I create the model

```<code>public class UserModel : INotifyPropertyChanged
{
    private string firstName;

    public string Firstname
    {
        get => firstName;
        set
        {
            firstName = value;
            NotifyPropertyChanged("Firstname");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(string propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
</code>```

my view model

```<code>UserModel user = new UserModel();
public UserModel User
{
    get => user;
    set => Set(ref user, value);
}
</code>```

and in model I bind with this line User.FirstName

```<code><TextBox x:Name="FirstName" Style="{StaticResource FirstNameBox}" Grid.Column="2" Grid.Row="2" >
    <TextBox.Text>
        <Binding  Mode="TwoWay" Path="User.FirstName" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <DataErrorValidationRule ValidatesOnTargetUpdated="False"/>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</code>```

but I take null. take example frome this answer mvvm calculated fields

答:
The binding paths are case-sensitive. You should bind to User.Firstname or change the name of the property to FirstName:

```<code>public string FirstName
{
    get => firstName;
    set
    {
        firstName = value;
        NotifyPropertyChanged("Firstname");
    }
}
</code>```

Body:
My ViewModel Doesn't take the value from model

I create the model

public class UserModel : INotifyPropertyChanged
{
    private string firstName;

    public string Firstname
    {
        get => firstName;
        set
        {
            firstName = value;
            NotifyPropertyChanged("Firstname");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(string propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

my view model

UserModel user = new UserModel();
public UserModel User
{
    get => user;
    set => Set(ref user, value);
}

and in model I bind with this line User.FirstName

<TextBox x:Name="FirstName" Style="{StaticResource FirstNameBox}" Grid.Column="2" Grid.Row="2" >
    <TextBox.Text>
        <Binding  Mode="TwoWay" Path="User.FirstName" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <DataErrorValidationRule ValidatesOnTargetUpdated="False"/>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>

but I take null. take example frome this answer mvvm calculated fields

Body:
The binding paths are case-sensitive. You should bind to User.Firstname or change the name of the property to FirstName:

public string FirstName
{
    get => firstName;
    set
    {
        firstName = value;
        NotifyPropertyChanged("Firstname");
    }
}


问:
How to send BCC via MFMailComposeViewController in iPhone SDK?
One part of my app sends an e-mail with an attachment. I'm using the MFMailComposeViewController class, and all is well.

I just would like to know if I can send a stealth BCC message to myself, just for statistics purposes to keep track of how many messages have been sent.

Thank you!

UPDATE: the user tc didn't understand what I was trying to accomplish. I DON'T WANT TO INVADE USER'S PRIVACY. I just need to keep track of EVENTS ON MY APP. I didn't make myself clear on what I needed.

答: You can track if an email was sent successfully without sending yourself a bcc of the message. Check the didFinishWithResult delegate method.

ContentLicense: CC BY-SA 3.0


问:
Can I create (an how to) a single html link to a mobile app, that sends the user to itunes or gplay based on device?
as for the title.

I have to place a simple link to an app on a website. The app has 2 versions, ios and android, so I should put 2 links, one to itunes and the other to gplay. ok.

Is there a way to create a single link that will send the user to the proper store?

答:
Firebase dynamic links is one way. I would like to recommend Branch.io, they do the same but more efficiently and the links that are generated don't look like spam. I did a huge study comparing both and found Branch to be better.

One cool thing, they even handle desktop deep linking i.e. they enable users to send the app link as an SMS from a custom designed page that gets loaded if they click the link on a desktop machine.


答:
You can use find, includes and split

First find the matching value from matchChodFisc using find and includes

Create a regex pattern based on value of found

Split using regex we built and fillter empty values

var matchCodFisc = ["C.F.", "CF", "Cod.Fisc.", "C.F"]
var myString= "Cod.Fisc.FGDTFR34L16G643W"

let found = matchCodFisc.find(val=> myString.includes(val))
let regex = new RegExp(`(${found})`, 'gi')

let splited = myString.split(regex).filter(Boolean)

console.log(splited)```

Title: How to check if a string contains a substring from an array and split it


问:
Ng-Zorro You Have Arrived
I added the NG-Zorro library to my project and now every page that I open within my App just has the NG-Zorro logo and the text "You have Arrived".

Just wondering how to get rid of the logo/text so that I can see my pages ?

I've looked through the documentation here, and the getting started shows that that's what's meant to happen. But it doesn't state how to get rid of the messaging.

答:
You will have to manually restore the changes from your Local History or Version Control. This was a problem with the first version(s) of ng-zorro

PS: The new versions of ng-zorro does not replace the main view if it is not the default.

Title: Ng-Zorro You Have Arrived


问:
Carbon Design Systems React UI Shell component is not working
I am trying to use the Carbon Design's UI Shell component.
I followed this blog to install all libraries, dependencies, etc.

Below is my code:

```<code>import {UIShell} from 'carbon-components-react';
import React from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
return (
<div className="App">
  <header className="App-header">
    <img src={logo} className="App-logo" alt="logo" />
    <p>
      Edit <code>src/App.js</code> and save to reload.
    </p>
    <a
      className="App-link"
      href="https://reactjs.org"
      target="_blank"
      rel="noopener noreferrer"
    >
      Learn React
    </a>
    <UIShell>UIShell Placeholder</UIShell>

  </header>
 </div>
 );
 }

 export default App;
</code>```

When I run this code, I get:

```<code> "Failed to compile: ./src/App.js Attempted import error: 'UIShell' is not exported from 'carbon-components-react'."
</code>```

According to the repository, UIShell is a component of carbon-components-react.
    Why am I getting this error?

答:
If you look in ./node_modules/carbon-components-react/lib/index.js, you will see that, although UIShell is defined in .../lib/components/, it's not exported.

So the question is actually... how can we access the UIShell components from the carbon-components-react component library when it's not exported?

I have found that that it's possible to import the UIShell component library explicitly:

```<code>import {...} from 'carbon-components-react/es/components/UIShell'
</code>```

Or, if you are not using ESM, I think that you could require the components via the following:

```<code>require('carbon-components-react/lib/components/UIShell')
</code>```

Body:
I am trying to use the Carbon Design's UI Shell component.
I followed this blog to install all libraries, dependencies, etc.

Below is my code:

import {UIShell} from 'carbon-components-react';
import React from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
return (

      Edit src/App.js and save to reload.

      Learn React

    <UIShell>UIShell Placeholder</UIShell>

 );
 }

 export default App;

When I run this code, I get:

 "Failed to compile: ./src/App.js Attempted import error: 'UIShell' is not exported from 'carbon-components-react'."

According to the repository, UIShell is a component of carbon-components-react.
    Why am I getting this error?

Body:
If you look in ./node_modules/carbon-components-react/lib/index.js, you will see that, although UIShell is defined in .../lib/components/, it's not exported.

So the question is actually... how can we access the UIShell components from the carbon-components-react component library when it's not exported?

I have found that that it's possible to import the UIShell component library explicitly:

import {...} from 'carbon-components-react/es/components/UIShell'

Or, if you are not using ESM, I think that you could require the components via the following:

require('carbon-components-react/lib/components/UIShell')


问:
Spring webflow prevent GET method in transition
I am using spring webflow 2.3.1.RELEASE in my project.

The customer's security team raised and issue witch is "It is possible to change the http method from POST to GET and the application accepts the change and continues working."

So I need to prevent this change and make my transitions accept only POST method. Or throw exception if I get any request parameter other than execution in the url.

How can I do this?

答:
I solved the problem using interceptors of the FlowHandlerMapping.

I've created a class and named it MethodInterceptor, implementend org.springframework.web.context.request.WebRequestInterceptor.

in the "public void preHandle(WebRequest request) throws Exception" method, I checked the request method, if it was get, I checked the request parameters to be either empty or contain only the execution parameter. If the condition didn't meet, I threw an exception.


问:
DBCP and Hibernate on Spring, doesn't re-open dead connections, why?
I'm using Hibernate and DBCP to manage mySQL connections, all in a Spring project.

Everything is working fine. The only problem is that if the app stays still for a long time, it will throw a an exception because the connection is dead (same thing if I restart mySQLd when the application is up). It's not big deal because the user will get the exception page (or the custom one) and a reload will solve the problem. But I'd like to solve it. Here is part of the exception:

```<code>com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:
</code>```

** BEGIN NESTED EXCEPTION **

java.io.EOFException
MESSAGE: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.

STACKTRACE:

java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.

I googled around and I found that with mysql I should set the dbcp.BasicDataSource property testOnBorrow to true, which I've done in my servlet-context.xml:

```<code><bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://${mySQL.host}/${mySQL.db}" />
    <property name="username" value="${mySQL.user}" />
    <property name="password" value="${mySQL.pass}" />
    <property name="testOnBorrow" value="true"></property>
</bean>
</code>```

But the problem persists. Any clues?

Solution! I used:

```<code><bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://${mySQL.host}/${mySQL.db}" />
    <property name="username" value="${mySQL.user}" />
    <property name="password" value="${mySQL.pass}" />
    <property name="testOnBorrow" value="true"></property>
    <property name="validationQuery" value="SELECT 1"></property>
</bean>
</code>```

答:
If you set testOnBorrow you must also set validationQuery -

validationQuery - The SQL query that will be used to
  validate connections from this pool
  before returning them to the caller.
  If specified, this query MUST be an
  SQL SELECT statement that returns at
  least one row.

I have also set timeBetweenEvictionRunsMillis so the dead connections will be evicted from the pool.

Body:
I'm using Hibernate and DBCP to manage mySQL connections, all in a Spring project.

Everything is working fine. The only problem is that if the app stays still for a long time, it will throw a an exception because the connection is dead (same thing if I restart mySQLd when the application is up). It's not big deal because the user will get the exception page (or the custom one) and a reload will solve the problem. But I'd like to solve it. Here is part of the exception:

com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:

** BEGIN NESTED EXCEPTION **

java.io.EOFException
MESSAGE: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.

STACKTRACE:

java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.

I googled around and I found that with mysql I should set the dbcp.BasicDataSource property testOnBorrow to true, which I've done in my servlet-context.xml:

<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://${mySQL.host}/${mySQL.db}" />
    <property name="username" value="${mySQL.user}" />
    <property name="password" value="${mySQL.pass}" />
    <property name="testOnBorrow" value="true"></property>
</bean>

But the problem persists. Any clues?

Solution! I used:

<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://${mySQL.host}/${mySQL.db}" />
    <property name="username" value="${mySQL.user}" />
    <property name="password" value="${mySQL.pass}" />
    <property name="testOnBorrow" value="true"></property>
    <property name="validationQuery" value="SELECT 1"></property>
</bean>


问:
How to send token in cookie, from server request angular universal?
I need to send from my server side to API in request headers "Cookie: token"
In angular universal, for servers Http request methods I use axios. when I try to change headers using Interceptor I have an error "Refused to set unsafe header 'Cookie'" if I send a static cookie like third arguments of axios post all work fine but I have some troubles to dynamically insert token there.

request.servise.ts

```<code>    import { RequestBody } from './models/request-body.model';
    import axios from 'axios';
    import {AxiosInstance} from 'axios';

    export class Request {
        http: AxiosInstance = axios;
        constructor() {}
        async test(): Promise<any> {
        const  params = {
                param1: 1,
                param2: 2,
                param3: 3,
            }
            try {
            return this.basicRequest('https://some-request.url', params);
            } catch (e) {
            console.error('Unknown exception: ', e);
            return null;
            }
        }

        private basicRequest(url, params) {
            const request = new RequestBody('2.0', 'someMethod', Math.floor(Math.random() * (9999999 - 1000000)) + 1000000, params);
            return this.http.post(url, request);
        }
    }
</code>```

projects.ts (sever router controller)

```<code>      import {Router} from 'express';
      import {Request} from '../../shared/request.service';

      const router: Router = Router();

      router.get('/test', async function(req, res, next){

        const request = new Request();
        try {
          const projects = (await request.test()).data.result.records;
          res.json(projects);
        } catch (e) {
          console.error(e);
        }
      });

      export const ProjectsController: Router = router;
</code>```

答:
By default, angular universal does not transfert cookieswhen using HttpClient. So, you need to do it manually, but you'll get the error you mentionned.

A possible workaround, suggested in that universal github issue, is to bypass xhr2's default security behaviour for unsafe headers

server.ts

```<code>import * as xhr2 from 'xhr2';
xhr2.prototype._restrictedHeaders = {};
</code>```

Body:
I need to send from my server side to API in request headers "Cookie: token"
In angular universal, for servers Http request methods I use axios. when I try to change headers using Interceptor I have an error "Refused to set unsafe header 'Cookie'" if I send a static cookie like third arguments of axios post all work fine but I have some troubles to dynamically insert token there.

request.servise.ts

    import { RequestBody } from './models/request-body.model';
    import axios from 'axios';
    import {AxiosInstance} from 'axios';

    export class Request {
        http: AxiosInstance = axios;
        constructor() {}
        async test(): Promise<any> {
        const  params = {
                param1: 1,
                param2: 2,
                param3: 3,
            }
            try {
            return this.basicRequest('https://some-request.url', params);
            } catch (e) {
            console.error('Unknown exception: ', e);
            return null;
            }
        }

        private basicRequest(url, params) {
            const request = new RequestBody('2.0', 'someMethod', Math.floor(Math.random() * (9999999 - 1000000)) + 1000000, params);
            return this.http.post(url, request);
        }
    }

projects.ts (sever router controller)

      import {Router} from 'express';
      import {Request} from '../../shared/request.service';

      const router: Router = Router();

      router.get('/test', async function(req, res, next){

        const request = new Request();
        try {
          const projects = (await request.test()).data.result.records;
          res.json(projects);
        } catch (e) {
          console.error(e);
        }
      });

      export const ProjectsController: Router = router;

Body:
By default, angular universal does not transfert cookieswhen using HttpClient. So, you need to do it manually, but you'll get the error you mentionned.

A possible workaround, suggested in that universal github issue, is to bypass xhr2's default security behaviour for unsafe headers

server.ts

import * as xhr2 from 'xhr2';
xhr2.prototype._restrictedHeaders = {};


问:
Is there a way to auto-generate models for OrmLite using .net core?
I am making the assumption that the T4 templates still are not supported in .Net Core.  Based on the articles I've read, I do not see any way to make them work.  I have a large database schema that I'd like to procedurally generate my models from.  Is there an alternative method for generating the models for ServiceStack's OrmLite or is there a hacky way to get the T4 to run on .Net Core?</p>

答: T4 Templates do work in .NET core. T4Executer adds support to run them on every build (before or after build event). </p>


问:
Is the login screen an entity or boundary class?
I'm developing a student response system and the facilitator has to login. On analysis stage I have identified classes including login class. The problem is if I model login screen as entity class or boundary class.</p>

答:
The terms 'boundary class' and 'entity class' are not defined by UML, but there are several methods, like RUP, which define those terms.

A screen is always a boundary class.


问:
UIGesturerecognizer is not working on UIView
When I am tapping on UIView but Gesture is not working.

```<code>override func viewDidLoad() {
        super.viewDidLoad()

        let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
        viewForSHadow.isUserInteractionEnabled = true
        viewForSHadow.addGestureRecognizer(tap)

        // Do any additional setup after loading the view.
    }

func handleTap(_sender: UITapGestureRecognizer) {
        print("---------View Tapped--------")
        viewForSHadow.isHidden = true
        viewForAlert.isHidden = true
    }

</code>```

I just want to perform this action on UIView tap.

答:
You have to implement as follows:</p>

```<code>    class ViewController: UIViewController, UIGestureRecognizerDelegate {

...

    override func viewDidLoad() {
        super.viewDidLoad()
        let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap(_sender:)))
        viewForSHadow.isUserInteractionEnabled = true
        viewForSHadow.addGestureRecognizer(tap)
    }

    @objc func handleTap(_sender: UITapGestureRecognizer) {
        print("---------View Tapped--------")
        viewForSHadow.isHidden = true
        viewForAlert.isHidden = true
    }
...

}
</code>```

Body:
When I am tapping on UIView but Gesture is not working.

override func viewDidLoad() {
        super.viewDidLoad()

        let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
        viewForSHadow.isUserInteractionEnabled = true
        viewForSHadow.addGestureRecognizer(tap)

        // Do any additional setup after loading the view.
    }

func handleTap(_sender: UITapGestureRecognizer) {
        print("---------View Tapped--------")
        viewForSHadow.isHidden = true
        viewForAlert.isHidden = true
    }

I just want to perform this action on UIView tap.

Body:
You have to implement as follows:

    class ViewController: UIViewController, UIGestureRecognizerDelegate {

...

    override func viewDidLoad() {
        super.viewDidLoad()
        let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap(_sender:)))
        viewForSHadow.isUserInteractionEnabled = true
        viewForSHadow.addGestureRecognizer(tap)
    }

    @objc func handleTap(_sender: UITapGestureRecognizer) {
        print("---------View Tapped--------")
        viewForSHadow.isHidden = true
        viewForAlert.isHidden = true
    }
...

}


问:
Should I assume sender can be null?
Should I assume a sender (of a CLR event handler) or a d (of a dependency event handler) be null and write some code for the case? Or can I simply mark them as [NotNull] and ignore warnings?

I'm using VS2019 + ReShaper to build a C# project. When "Value Analysis Mode" of R# is set to "Pessimistic (an entity is assumed when it doesn't have explicit NotNull attribute)", it warns sender and d can be null.

//// R# warns sender can be null.
private void OnSomethingHappened(object sender, EventArgs e) {
    //// Should I throw an Exception when sender is null?
    //// Or can I simply mark sender as [NotNull]?
}

//// R# warns d can be null.
private static void (DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    //// Should I throw an Exception when d is null?
    //// Or can I simply mark d as [NotNull]?
}
```

答:
Everyone recommend me that I check an object be null. So, IMO, this would be the best practice in case I'd like to utilize sender (or d) in the method.

```<code>    private void OnSomethingHappened([CanBeNull]object sender, EventArgs e) {
        if (!(sender is MyClass mc)) throw new ArgumentException();

        mc.DoSomething();
    }
</code>```

EDIT:
Now I prefer this:

```<code>    private void OnSomethingHappened([CanBeNull]object sender, EventArgs e) {
        var mc = sender as MyClass ?? throw new ArgumentException();

        mc.DoSomething();
    }
</code>```

Title: Should I assume sender can be null?

Body:
Everyone recommend me that I check an object be null. So, IMO, this would be the best practice in case I'd like to utilize sender (or d) in the method.

    private void OnSomethingHappened([CanBeNull]object sender, EventArgs e) {
        if (!(sender is MyClass mc)) throw new ArgumentException();

        mc.DoSomething();
    }

EDIT:
Now I prefer this:

    private void OnSomethingHappened([CanBeNull]object sender, EventArgs e) {
        var mc = sender as MyClass ?? throw new ArgumentException();

        mc.DoSomething();
    }


问:
How to check if a string contains a substring from an array and split it
I have an array of string like:

```<code>var matchCodFisc = ["C.F.", "CF", "Cod.Fisc.", "C.F"]
</code>```

and I want to check if in my string
(e.g. var myString= "Cod.Fisc.FGDTFR34L16G643W") exists that substring (in this case "Cod.Fisc").
If I found the substring I want to split my string in two parts like ["Cod.Fisc", "FGDTFR34L16G643W"]. How can I do that using JavaScript?

答:
You could do with Array#findIndex method using Str.includes()

var matchCodFisc = ["C.F.", "CF", "Cod.Fisc.", "C.F"]
var myString = "Cod.Fisc.FGDTFR34L16G643W";
var resindex = matchCodFisc.findIndex(a => myString.includes(a));

console.log([
  matchCodFisc[resindex],
  myString.split(matchCodFisc[resindex])[1]
])```


问:
Intellij idea cannot resolve anything in maven
I just imported a project with pom.xml, but the IDE didn't resolve anything in maven dependencies.

Anything defined in pom.xml dependencies when import in code raise an error cannot resolve symbol xxxxx

But mvn install will work, I try import the dependencies in Project Settings/Libraries in .jar files, then it works, but could the ide resolve libraries defined in pom.xml? i don't want to do that everytime.

Additionnal info:

IDEA version: 12.0.3, OS : windows 7, reimport does not work, maven version : 3.0.4, maven dependencies does not exists under Exernal Libraries.

There are no exceptions in idea.log...

答:
Using default maven (which comes with IntelliJ) also could create this problem. So configure the maven which you have installed.

This can be done from:
File -> Settings -> Build, Execution, Deployment -> Maven

Update following settings according to your maven installation:

Maven home directory =

User settings file =

Local repository =


问:
How can I include the jboss-client.jar present in the Wildfly bin/client folder to my maven project?
I have a maven project to which I have to add a external jar jboss-client.jar which is located in Jboss Wildfly 10 bin folder(bin/client). There is no version specified in the jar name.

When I add the jar manually in build path-it works fine.

However, since this is a maven project, I require a better way of doing this.

Note: The project works with only this jar and not other versions specified in pom.xml which I tried downloading.

Also, if I try to specify the external dependency in pom.xml, it asks for version of the dependency. However, I cannot specify the same as it is not mentioned in the jar.

My ultimate aim is to deploy this project in Jboss Wildfly 10.

Is there any other alternate way, I can add the jar?

答:
You can use maven to install third party library in local.
https://maven.apache.org/guides/mini/guide-3rd-party-jars-local.html

Using below command you can install.

mvn install:install-file -Dfile=path-to-file/jboss-client.jar -DgroupId=org.jboss -DartifactId=jboss-client -Dversion=1.0


问:
Why method that calls another one which throws RuntimeException needs return statement?
Why unreachable statement is not identified by javac ?</p>

```<code>public int directThrow(){
     throw new RuntimeException();
    //Compiles fine
}

public int indirectThrow(){
    directThrow();
    // Missing Return Statement error
}
</code>```

答:
Counter question: What if directThrow() was somehow altered that it doesn't throw an exception? How should the code then handle that?

To illustrate this problem, here's an example:

```<code>class Foo {
    int throwSomething() {
        throw new RuntimeException();
    }
}

class Bar extends Foo{
    int throwSomething() {
        return 1; // hahaaa, we don't throw but return normally
    }
}
</code>```

See? The subclass overrides the base method, and returns something, how should the code now handle that:

```<code>int indirectThrowing(Foo foo) {
    foo.throwSomething();
}
</code>```

If we pass new Foo() it will throw as expected, but if we pass new Bar() it will just return 1. And thus it will not fail.

To overcome this problem, you must write a return statement. Or if you want to reuse what you already have, you can also write:

```<code>return directThrow();
</code>```

Because directThrow() has a return type int, and thus you just pass the argument upwards.

Note, some languages like Kotlin handle this with a Nothing (sometimes called also Never) return type. To indicate to the compiler that a method can never return normally.

Body:
Why unreachable statement is not identified by javac ?

public int directThrow(){
     throw new RuntimeException();
    //Compiles fine
}

public int indirectThrow(){
    directThrow();
    // Missing Return Statement error
}

Body:
Counter question: What if directThrow() was somehow altered that it doesn't throw an exception? How should the code then handle that?

To illustrate this problem, here's an example:

class Foo {
    int throwSomething() {
        throw new RuntimeException();
    }
}

class Bar extends Foo{
    int throwSomething() {
        return 1; // hahaaa, we don't throw but return normally
    }
}

See? The subclass overrides the base method, and returns something, how should the code now handle that:

int indirectThrowing(Foo foo) {
    foo.throwSomething();
}

If we pass new Foo() it will throw as expected, but if we pass new Bar() it will just return 1. And thus it will not fail.

To overcome this problem, you must write a return statement. Or if you want to reuse what you already have, you can also write:

return directThrow();

Because directThrow() has a return type int, and thus you just pass the argument upwards.

Note, some languages like Kotlin handle this with a Nothing (sometimes called also Never) return type. To indicate to the compiler that a method can never return normally.


问:
How to make a countdown timer in Android?
I have two EditTexts in XML. In one EditText, the user can put a number as minutes and in another EditText, a number as seconds. After clicking the finish button, the seconds EditText should start to countdown and update its text every second.

Additionally, how can I keep it updating until it gets to zero minutes and zero seconds?

答:
```<code>public class Scan extends AppCompatActivity {
int minute;
long min;
TextView tv_timer;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_scan2);
    tv_timer=findViewById(R.id.tv_timer);
    minute=Integer.parseInt("Your time in string form like 10");
    min= minute*60*1000;
    counter(min);
}
private void counter(long min) {
    CountDownTimer timer = new CountDownTimer(min, 1000) {
        public void onTick(long millisUntilFinished) {
            int seconds = (int) (millisUntilFinished / 1000) % 60;
            int minutes = (int) ((millisUntilFinished / (1000 * 60)) % 60);
            int hours = (int) ((millisUntilFinished / (1000 * 60 * 60)) % 24);
            tv_timer.setText(String.format("%d:%d:%d", hours, minutes, seconds));
        }
        public void onFinish() {
            Toast.makeText(getApplicationContext(), "Your time has been completed",
                    Toast.LENGTH_LONG).show();
        }
    };
    timer.start();
}
</code>```

<p>}</p>

Body:
public class Scan extends AppCompatActivity {
int minute;
long min;
TextView tv_timer;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_scan2);
    tv_timer=findViewById(R.id.tv_timer);
    minute=Integer.parseInt("Your time in string form like 10");
    min= minute*60*1000;
    counter(min);
}
private void counter(long min) {
    CountDownTimer timer = new CountDownTimer(min, 1000) {
        public void onTick(long millisUntilFinished) {
            int seconds = (int) (millisUntilFinished / 1000) % 60;
            int minutes = (int) ((millisUntilFinished / (1000 * 60)) % 60);
            int hours = (int) ((millisUntilFinished / (1000 * 60 * 60)) % 24);
            tv_timer.setText(String.format("%d:%d:%d", hours, minutes, seconds));
        }
        public void onFinish() {
            Toast.makeText(getApplicationContext(), "Your time has been completed",
                    Toast.LENGTH_LONG).show();
        }
    };
    timer.start();
}

}


问:
Python unittest.mock: patched class method called but assertion fails
I'm trying to mock several components of a utility class. While assert_called() is ok for one method it fails for an other but I am sure that both are called. I'm running Python 3.7.3 on Windows 10.

I have stripped down my scenario to the essentials.
The utility class (util.py):

class api:

    @staticmethod
    def send(data):
        print("sending %s" % data)

    class logger:

        @staticmethod
        def info(s):
            print("INFO: %s" % s)

        @staticmethod
        def error(s):
            print("ERROR: %s" % s)
```

<p>The  unit test variant that works fine:</p>

<pre class="lang-py prettyprint-override"><code>import unittest
from unittest.mock import patch
from util import api

def do_something():
    api.logger.info("doing something")
    api.send("some data")

@patch("util.api.logger")
class Test(unittest.TestCase):

    def test_do_something(self, mock_logger):
        do_something()
        mock_logger.info.assert_called()
</code>```

The one that fails:

import unittest
from unittest.mock import patch
from util import api

def do_something():
    api.logger.info("doing something")
    api.send("some data")

@patch("util.api")
class Test(unittest.TestCase):

    def test_do_something(self, mock_api):
        do_something()
        mock_api.send.assert_called()
```

<p>When running the tests I am getting both <code>print()</code> outputs:</p>

```INFO: doing something
sending some data
```

<p>so I'm sure that both methods are called.</p>

<p>Very likely I'm making some stupid dummy mistake because I'm really new to python...</p>

<p>Some more background:</p>

<p>In my stripped down scenario <code>do_something()</code> is just a stand-in for a set of functions that are the object of my test and that in my real scenario are actually defined in a separate python file. In the production environment it runs in the context of a framework that provides the utility class api. In my test environment <code>util.py</code> itself is a mock of the production api. The py file to be tested (instead of <code>def do_something(): ...</code>) is loaded like so: </p>

```path = os.getcwd() + "<local path to py file to be tested>"
globals().update({ **runpy.run_path(path, init_globals=globals()), **globals() })
```

Therefore, I can't modify the do_something() code in the test scenario.

答:
Finally got it after having found this SO question - I wasn't aware that you can also patch individual functions/class methods (not mentioned in the unittest.mock.patch reference). So this works:</p>

```<code>import unittest
from unittest.mock import patch
from util import api

def do_something():
    api.logger.info("doing something")
    api.send("some data")

@patch("util.api.send")
@patch("util.api.logger")
class Test(unittest.TestCase):

    def test_do_something(self, mock_logger, mock_send):
        do_something()
        mock_send.assert_called()
        mock_logger.info.assert_called()
</code>```

Body:
I'm trying to mock several components of a utility class. While assert_called() is ok for one method it fails for an other but I am sure that both are called. I'm running Python 3.7.3 on Windows 10.

I have stripped down my scenario to the essentials.
The utility class (util.py):

class api:

    @staticmethod
    def send(data):
        print("sending %s" % data)

    class logger:

        @staticmethod
        def info(s):
            print("INFO: %s" % s)

        @staticmethod
        def error(s):
            print("ERROR: %s" % s)

The  unit test variant that works fine:

import unittest
from unittest.mock import patch
from util import api

def do_something():
    api.logger.info("doing something")
    api.send("some data")

@patch("util.api.logger")
class Test(unittest.TestCase):

    def test_do_something(self, mock_logger):
        do_something()
        mock_logger.info.assert_called()

The one that fails:

import unittest
from unittest.mock import patch
from util import api

def do_something():
    api.logger.info("doing something")
    api.send("some data")

@patch("util.api")
class Test(unittest.TestCase):

    def test_do_something(self, mock_api):
        do_something()
        mock_api.send.assert_called()

When running the tests I am getting both print() outputs:

INFO: doing something
sending some data

so I'm sure that both methods are called.

Very likely I'm making some stupid dummy mistake because I'm really new to python...

Some more background:

In my stripped down scenario do_something() is just a stand-in for a set of functions that are the object of my test and that in my real scenario are actually defined in a separate python file. In the production environment it runs in the context of a framework that provides the utility class api. In my test environment util.py itself is a mock of the production api. The py file to be tested (instead of def do_something(): ...) is loaded like so:

path = os.getcwd() + "<local path to py file to be tested>"
globals().update({ **runpy.run_path(path, init_globals=globals()), **globals() })

Therefore, I can't modify the do_something() code in the test scenario.

Body:
Finally got it after having found this SO question - I wasn't aware that you can also patch individual functions/class methods (not mentioned in the unittest.mock.patch reference). So this works:

import unittest
from unittest.mock import patch
from util import api

def do_something():
    api.logger.info("doing something")
    api.send("some data")

@patch("util.api.send")
@patch("util.api.logger")
class Test(unittest.TestCase):

    def test_do_something(self, mock_logger, mock_send):
        do_something()
        mock_send.assert_called()
        mock_logger.info.assert_called()


问:
Zoom extension to multilayer boundaries of several KML
I have a web page that uses openlayers 5 and has several layers, each one of them extracts the data of one kml. How can I zoom in and show all kmls on the screen

 var vector1 = new ol.layer.Vector({
    source: new ol.source.Vector({
      url: 'vector1.kml',
      format: new ol.format.KML({
        extractStyles: true
      })
    }),
    style: styleFunction
  });
  var vector2 = new ol.layer.Vector({
    source: new ol.source.Vector({
      url: 'vector2.kml',
      format: new ol.format.KML({
        extractStyles: true
      })
    }),
    style: styleFunction
  });

var raster = new ol.layer.Tile({ // TileLayer
    source: new ol.source.Stamen({
      layer: 'toner'
    })
  });

  var view = new ol.View({
    center: [0, 0],
    zoom: 1  // 14
  });

  var Layers =  [raster,vector1,vector2,vector3,vector4];
  var map = new ol.Map({
    layers: Layers,
    target: 'map',
    view: view
  });
```

I have a web page that uses openlayers 5 and has several layers, each one of them extracts the data of one kml. How can I zoom in and show all kmls on the screen

答:
It's not going to be very efficient because the sources will load asynchronously in a random order and there is no event to indicate all features have been added, each feature fires an event, but building and fitting an extent as they load will get there eventually </p>

```<code>var Layers = [raster,vector1,vector2,vector3,vector4];
var extent = ol.extent.createEmpty();
Layers.slice(1).forEach(function(layer){
  layer.getSource().on('addfeature',function(){
    ol.extent.extend(extent, layer.getSource().getExtent());
    map.getView().fit(extent, { size: map.getSize() });
  });
});
</code>```

Body:
I have a web page that uses openlayers 5 and has several layers, each one of them extracts the data of one kml. How can I zoom in and show all kmls on the screen

 var vector1 = new ol.layer.Vector({
    source: new ol.source.Vector({
      url: 'vector1.kml',
      format: new ol.format.KML({
        extractStyles: true
      })
    }),
    style: styleFunction
  });
  var vector2 = new ol.layer.Vector({
    source: new ol.source.Vector({
      url: 'vector2.kml',
      format: new ol.format.KML({
        extractStyles: true
      })
    }),
    style: styleFunction
  });

var raster = new ol.layer.Tile({ // TileLayer
    source: new ol.source.Stamen({
      layer: 'toner'
    })
  });

  var view = new ol.View({
    center: [0, 0],
    zoom: 1  // 14
  });

  var Layers =  [raster,vector1,vector2,vector3,vector4];
  var map = new ol.Map({
    layers: Layers,
    target: 'map',
    view: view
  });

I have a web page that uses openlayers 5 and has several layers, each one of them extracts the data of one kml. How can I zoom in and show all kmls on the screen

Body:
It's not going to be very efficient because the sources will load asynchronously in a random order and there is no event to indicate all features have been added, each feature fires an event, but building and fitting an extent as they load will get there eventually

var Layers = [raster,vector1,vector2,vector3,vector4];
var extent = ol.extent.createEmpty();
Layers.slice(1).forEach(function(layer){
  layer.getSource().on('addfeature',function(){
    ol.extent.extend(extent, layer.getSource().getExtent());
    map.getView().fit(extent, { size: map.getSize() });
  });
});


问:
How can I get all possible combinations of element in set? (power set)
I have a array of number:

```<code>$numbers = array(1,2,3);
</code>```

The order does not mean anything.  If the numbers given were 1, 2 and 3, then I would want to receive this as a result:

```<code>1
2
3
1 2
1 3
2 3
1 2 3
</code>```

How can I achieve that?

答:
May be I found it on a old SO post or Github gist.

```<code><?php
function uniqueCombination($in, $minLength = 1, $max = 2000) {
    $count = count($in);
    $members = pow(2, $count);
    $return = array();
    for($i = 0; $i < $members; $i ++) {
        $b = sprintf("%0" . $count . "b", $i);
        $out = array();
        for($j = 0; $j < $count; $j ++) {
            $b{$j} == '1' and $out[] = $in[$j];
        }
        count($out) >= $minLength && count($out) <= $max and $return[] = $out;
        }
    return $return;
}

$numbers = array(1,2,3);
$return = uniqueCombination($numbers);
sort($return);
print_r(array_map(function($v){ return implode(" ", $v); }, $return));
?>
</code>```

Output:

```<code>Array (
   [0] => 1
   [1] => 2
   [2] => 3
   [3] => 1 2
   [4] => 1 3
   [5] => 2 3
   [6] => 1 2 3
)
</code>```

DEMO: https://3v4l.org/lec2F

Body:
I have a array of number:

$numbers = array(1,2,3);

The order does not mean anything.  If the numbers given were 1, 2 and 3, then I would want to receive this as a result:

1
2
3
1 2
1 3
2 3
1 2 3

How can I achieve that?

Body:
May be I found it on a old SO post or Github gist.

<?php
function uniqueCombination($in, $minLength = 1, $max = 2000) {
    $count = count($in);
    $members = pow(2, $count);
    $return = array();
    for($i = 0; $i < $members; $i ++) {
        $b = sprintf("%0" . $count . "b", $i);
        $out = array();
        for($j = 0; $j < $count; $j ++) {
            $b{$j} == '1' and $out[] = $in[$j];
        }
        count($out) >= $minLength && count($out) <= $max and $return[] = $out;
        }
    return $return;
}

$numbers = array(1,2,3);
$return = uniqueCombination($numbers);
sort($return);
print_r(array_map(function($v){ return implode(" ", $v); }, $return));
?>

Output:

Array (
   [0] => 1
   [1] => 2
   [2] => 3
   [3] => 1 2
   [4] => 1 3
   [5] => 2 3
   [6] => 1 2 3
)

DEMO: https://3v4l.org/lec2F


问:
Getting SSL handshake error while Enabling SSL in KAFKA
I’m getting SSL handshake failed when I start producer to push data, did below settings:

```<code>1. Followed steps as per
    https://docs.confluent.io/2.0.0/kafka/ssl.html to create keystore
2.  Started zookeeper with default settings
3.  Made below changes in kafka server properties:
    a.  listeners=SSL://hostName:9092
    b.  ssl.keystore.location =/home/kafka_2.12-
       2.2.0/kafka.server.keystore.jks
    c.  ssl.keystore.password =keystore
    d.  ssl.key.password =keystore
    e.  ssl.truststore.location =/home/kafka_2.12-
       2.2.0/kafka.server.truststore.jks
    f.  ssl.truststore.password =keystore
    g.  ssl.endpoint.identification.algorithm=HTTPS
    h.  advertised.listeners=SSL://hostName:9092
    i.  inter.broker.listener.name=SSL
    j.  listener.security.protocol.map=SSL:SSL
</code>```

After doing above steps, I was able to start kafka server and server got started.

```<code>Command bin/zookeeper-shell.sh localhost:2181 <<< "get /brokers/ids/0" gave below output that means broker id 0 was up and listening  on
SSL://hostName:9092
Connecting to localhost:2181
Welcome to ZooKeeper!
JLine support is disabled
WATCHER::
WatchedEvent state:SyncConnected type:None path:null
{"listener_security_protocol_map":{"SSL":"SSL"},"endpoints":
["SSL://hostName:9092"]
 ,"jmx_port":-1,"host":null,"timestamp":"1559106754150"
 ,"port":-1,"version":4}
cZxid = 0x425
ctime = Wed May 29 10:42:34 IST 2019
mZxid = 0x425
mtime = Wed May 29 10:42:34 IST 2019
pZxid = 0x425
cversion = 0
dataVersion = 1
aclVersion = 0
ephemeralOwner = 0x1004d6fe052000a
dataLength = 159
numChildren = 0
</code>```

But when I’m starting kafka producer to push data, I’m getting SSL handshake error on kafka server console

To start producer
    bin/kafka-console-producer.sh --broker-list hostName:9092 --topic test3

```<code>[2019-05-29 10:45:57,808] INFO [SocketServer brokerId=0] Failed
authentication with /101.101.101.101 (SSL handshake failed)
(org.apache.kafka.common.network.Selector)
[2019-05-29 10:45:58,143] INFO [SocketServer brokerId=0] Failed
authentication with /101.101.101.101 (SSL handshake failed)
(org.apache.kafka.common.network.Selector)
[2019-05-29 10:45:58,728] INFO [SocketServer brokerId=0] Failed
authentication with /101.101.101.101 (SSL handshake failed)
(org.apache.kafka.common.network.Selector)
[2019-05-29 10:45:59,613] INFO [SocketServer brokerId=0] Failed
authentication with /101.101.101.101 (SSL handshake failed)
(org.apache.kafka.common.network.Selector)
[2019-05-29 10:46:00,600] INFO [SocketServer brokerId=0] Failed
authentication with /101.101.101.101 (SSL handshake failed)
(org.apache.kafka.common.network.Selector)
[2019-05-29 10:46:01,688] INFO [SocketServer brokerId=0] Failed
authentication with /101.101.101.101 (SSL handshake failed)
(org.apache.kafka.common.network.Selector)
[2019-05-29 10:46:02,928] INFO [SocketServer brokerId=0] Failed
authentication with /101.101.101.101 (SSL handshake failed)
(org.apache.kafka.common.network.Selector)
</code>```

Note: Kafka broker server and producer are on same host

Expecting Producer should push data to broker which is running on same localhost.
Consumer from another node should be able to consume.
Data should be encrypted as we are enabling SSL

答:
was using single way handshaking.
Now got this issue resolved by implementing two way handshaking</p>

Body:
I’m getting SSL handshake failed when I start producer to push data, did below settings:

1. Followed steps as per
    https://docs.confluent.io/2.0.0/kafka/ssl.html to create keystore
2.  Started zookeeper with default settings
3.  Made below changes in kafka server properties:
    a.  listeners=SSL://hostName:9092
    b.  ssl.keystore.location =/home/kafka_2.12-
       2.2.0/kafka.server.keystore.jks
    c.  ssl.keystore.password =keystore
    d.  ssl.key.password =keystore
    e.  ssl.truststore.location =/home/kafka_2.12-
       2.2.0/kafka.server.truststore.jks
    f.  ssl.truststore.password =keystore
    g.  ssl.endpoint.identification.algorithm=HTTPS
    h.  advertised.listeners=SSL://hostName:9092
    i.  inter.broker.listener.name=SSL
    j.  listener.security.protocol.map=SSL:SSL

After doing above steps, I was able to start kafka server and server got started.

Command bin/zookeeper-shell.sh localhost:2181 <<< "get /brokers/ids/0" gave below output that means broker id 0 was up and listening  on
SSL://hostName:9092
Connecting to localhost:2181
Welcome to ZooKeeper!
JLine support is disabled
WATCHER::
WatchedEvent state:SyncConnected type:None path:null
{"listener_security_protocol_map":{"SSL":"SSL"},"endpoints":
["SSL://hostName:9092"]
 ,"jmx_port":-1,"host":null,"timestamp":"1559106754150"
 ,"port":-1,"version":4}
cZxid = 0x425
ctime = Wed May 29 10:42:34 IST 2019
mZxid = 0x425
mtime = Wed May 29 10:42:34 IST 2019
pZxid = 0x425
cversion = 0
dataVersion = 1
aclVersion = 0
ephemeralOwner = 0x1004d6fe052000a
dataLength = 159
numChildren = 0

But when I’m starting kafka producer to push data, I’m getting SSL handshake error on kafka server console

To start producer
    bin/kafka-console-producer.sh --broker-list hostName:9092 --topic test3

[2019-05-29 10:45:57,808] INFO [SocketServer brokerId=0] Failed
authentication with /101.101.101.101 (SSL handshake failed)
(org.apache.kafka.common.network.Selector)
[2019-05-29 10:45:58,143] INFO [SocketServer brokerId=0] Failed
authentication with /101.101.101.101 (SSL handshake failed)
(org.apache.kafka.common.network.Selector)
[2019-05-29 10:45:58,728] INFO [SocketServer brokerId=0] Failed
authentication with /101.101.101.101 (SSL handshake failed)
(org.apache.kafka.common.network.Selector)
[2019-05-29 10:45:59,613] INFO [SocketServer brokerId=0] Failed
authentication with /101.101.101.101 (SSL handshake failed)
(org.apache.kafka.common.network.Selector)
[2019-05-29 10:46:00,600] INFO [SocketServer brokerId=0] Failed
authentication with /101.101.101.101 (SSL handshake failed)
(org.apache.kafka.common.network.Selector)
[2019-05-29 10:46:01,688] INFO [SocketServer brokerId=0] Failed
authentication with /101.101.101.101 (SSL handshake failed)
(org.apache.kafka.common.network.Selector)
[2019-05-29 10:46:02,928] INFO [SocketServer brokerId=0] Failed
authentication with /101.101.101.101 (SSL handshake failed)
(org.apache.kafka.common.network.Selector)

Note: Kafka broker server and producer are on same host

Expecting Producer should push data to broker which is running on same localhost.
Consumer from another node should be able to consume.
Data should be encrypted as we are enabling SSL