问:
How to implement a tagging plugin for jQuery
Goal: To implement a jQuery plugin for my rails app (or write one myself, if necessary) that creates a "box" around text after a delimiter is typed.

Example: With tagging on SO, the user begins typing a tag, then selects one from the drop-down list provided. The input field recognizes that a tag has been selected, puts a space and then is ready for the next tag. Similarly, I am attempting to use this plugin to put a box around the previously entered tag before moving to to accept the next tag/input.

The instructions in the README.txt seem simple enough, however I have been receiving a

$(".tagbox").tagbox is not a function

error when debugging my app with firebug.

Here is what I have in my application.js:

```<code>$(document).ready( function(){

    $('.tagbox').tagbox({
        separator: /\[,]/  // specifying comma separation for <code>tags</code>
    });

});
</code>```

And here is my _form.html.erb:

```<code><% form_for @tag do |f| %>
  <%= f.error_messages %>
  <p>
    <%= f.label :name %><br />
    <%= text_field :tag, :name, { :method => :get, :class => "tagbox" } %>
  </p>

  <p><%= f.submit "Submit" %></p>
<% end %>
</code>```

I have omitted some other code (namely the implementation of an autocomplete plugin) existing within my _form.html.erb and application.js for sake of readability. The inclusion or exclusion of this omitted code does not affect the performance of this plugin.

I have included all of the necessary files for the tagbox plugin (as well as application.js after all other included JS files) within the javascript_include_tag in my application.html.erb file.

I'm pretty much confused as to why I'd be getting this "not a function" error when jquery.tagbox.js clearly defines the function and is included in the head of my html page in question. I've been struggling with this plugin for longer than I'd like to admit, so any help would really be appreciated. And, of course, I'm open to any other plugins or from-scratch suggestions you may have in mind..

This tagbox plugin does not seem to have a wealth of documentation or any currently working examples.

Also to note, I'm trying to avoid using jrails.

Thanks for your time

答:
Heres another tagBox plugin I wrote with some additional features:

http://www.geektantra.com/2011/05/jquery-tagbox-plugin/

Just see if it can help.

Body:
Goal: To implement a jQuery plugin for my rails app (or write one myself, if necessary) that creates a "box" around text after a delimiter is typed.

Example: With tagging on SO, the user begins typing a tag, then selects one from the drop-down list provided. The input field recognizes that a tag has been selected, puts a space and then is ready for the next tag. Similarly, I am attempting to use this plugin to put a box around the previously entered tag before moving to to accept the next tag/input.

The instructions in the README.txt seem simple enough, however I have been receiving a

$(".tagbox").tagbox is not a function

error when debugging my app with firebug.

Here is what I have in my application.js:

$(document).ready( function(){

    $('.tagbox').tagbox({
        separator: /\[,]/  // specifying comma separation for tags
    });

});

And here is my _form.html.erb:

<% form_for @tag do |f| %>
  <%= f.error_messages %>

    <%= f.label :name %>

    <%= text_field :tag, :name, { :method => :get, :class => "tagbox" } %>

<%= f.submit "Submit" %>

<% end %>

I have omitted some other code (namely the implementation of an autocomplete plugin) existing within my _form.html.erb and application.js for sake of readability. The inclusion or exclusion of this omitted code does not affect the performance of this plugin.

I have included all of the necessary files for the tagbox plugin (as well as application.js after all other included JS files) within the javascript_include_tag in my application.html.erb file.

I'm pretty much confused as to why I'd be getting this "not a function" error when jquery.tagbox.js clearly defines the function and is included in the head of my html page in question. I've been struggling with this plugin for longer than I'd like to admit, so any help would really be appreciated. And, of course, I'm open to any other plugins or from-scratch suggestions you may have in mind..

This tagbox plugin does not seem to have a wealth of documentation or any currently working examples.

Also to note, I'm trying to avoid using jrails.

Thanks for your time


来源: stackexchange

问:
IsCA certificate setting in Go x509 package
When creating an intermediate root certificate, do you set the "IsCA" property of the certificate template? What exactly does this property do?

I'm creating a certificate chain for an application.  In this application I need to use intermediate certificates to sign some client certificates.  I've found some guides on creating Root CA certificates and they indicate to set IsCA = true when creating the certificate template, but I cannot find any information on creating intermediate roots.  Does the IsCA property still need to be set?  Are there any other changes to the certificate template when creating an intermediate certificate vs. a root certificate?

答:
You must set the cA basic constraint for intermediate certificates. This bool indicates that a certificate can be used to verify other certificate signatures.

A certificate without cA set to true is a leaf certificate.

Here is the relevant portion of the "basic constraints" section of RFC 5280:

The cA boolean indicates whether the certified public key may be used
to verify certificate signatures.  If the cA boolean is not asserted,
then the keyCertSign bit in the key usage extension MUST NOT be
asserted.  If the basic constraints extension is not present in a
version 3 certificate, or the extension is present but the cA boolean
is not asserted, then the certified public key MUST NOT be used to
verify certificate signatures.

ContentLicense: CC BY-SA 4.0


问:
Python Pandas Dataframe: length of index does not match - df['column'] = ndarray
I have a pandas Dataframe containing EOD financial data (OHLC) for analysis.

I'm using https://github.com/cirla/tulipy library to generate technical indicator values, that have a certain timeperiod as option. For Example. ADX with timeperiod=5 shows ADX for last 5 days.

Because of this timeperiod, the generated array with indicator values is always shorter in length than the Dataframe. Because the prices of first 5 days are used to generate ADX for day 6..

```<code>    pdi14, mdi14 = ti.di(
    high=highData, low=lowData, close=closeData, period=14)

    df['mdi_14'] = mdi14
    df['pdi_14'] = pdi14
    >> ValueError: Length of values does not match length of index
</code>```

Unfortunately, unlike TA-LIB for example, this tulip library does not provide NaN-values for these first couple of empty days...

Is there an easy way to prepend these NaN to the ndarray?
Or insert into df at a certain index & have it create NaN for the rows before it automatically?

Thanks in advance, I've been researching for days!

答:
The C version of the tulip library includes a start function for each indicator (reference: https://tulipindicators.org/usage) that can be used to determine the output length of an indicator given a set of input options. Unfortunately, it does not appear that the python bindings library, tulipy, includes this functionality. Instead you have to resort to dynamically reassigning your index values to align the output with the original DataFrame.

Here is an example that uses the price series from the tulipy docs:

```<code>#Create the dataframe with close prices
prices = pd.DataFrame(data={81.59, 81.06, 82.87, 83, 83.61, 83.15, 82.84, 83.99, 84.55,
 84.36, 85.53, 86.54, 86.89, 87.77, 87.29}, columns=['close'])

#Compute the technical indicator using tulipy and save the result in a DataFrame
bbands = pd.DataFrame(data=np.transpose(ti.bbands(real = prices['close'].to_numpy(), period = 5, stddev = 2)))

#Dynamically realign the index; note from the tulip library documentation that the price/volume data is expected be ordered "oldest to newest (index 0 is oldest)"
bbands.index += prices.index.max() - bbands.index.max()

#Put the indicator values with the original DataFrame
prices[['BBANDS_5_2_low', 'BBANDS_5_2_mid', 'BBANDS_5_2_up']] = bbands
prices.head(15)

close   BBANDS_5_2_low  BBANDS_5_2_mid  BBANDS_5_2_up
0   81.06   NaN NaN NaN
1   81.59   NaN NaN NaN
2   82.87   NaN NaN NaN
3   83.00   NaN NaN NaN
4   83.61   80.530042   82.426  84.321958
5   83.15   81.494061   82.844  84.193939
6   82.84   82.533343   83.094  83.654657
7   83.99   82.471983   83.318  84.164017
8   84.55   82.417750   83.628  84.838250
9   84.36   82.435203   83.778  85.120797
10  85.53   82.511331   84.254  85.996669
11  86.54   83.142618   84.994  86.845382
12  86.89   83.536488   85.574  87.611512
13  87.77   83.870324   86.218  88.565676
14  87.29   85.288871   86.804  88.319129
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a pandas Dataframe containing EOD financial data (OHLC) for analysis.

I'm using https://github.com/cirla/tulipy library to generate technical indicator values, that have a certain timeperiod as option. For Example. ADX with timeperiod=5 shows ADX for last 5 days.

Because of this timeperiod, the generated array with indicator values is always shorter in length than the Dataframe. Because the prices of first 5 days are used to generate ADX for day 6..

    pdi14, mdi14 = ti.di(
    high=highData, low=lowData, close=closeData, period=14)

    df['mdi_14'] = mdi14
    df['pdi_14'] = pdi14
    >> ValueError: Length of values does not match length of index

Unfortunately, unlike TA-LIB for example, this tulip library does not provide NaN-values for these first couple of empty days...

Is there an easy way to prepend these NaN to the ndarray?
Or insert into df at a certain index & have it create NaN for the rows before it automatically?

Thanks in advance, I've been researching for days!

Body:
The C version of the tulip library includes a start function for each indicator (reference: https://tulipindicators.org/usage) that can be used to determine the output length of an indicator given a set of input options. Unfortunately, it does not appear that the python bindings library, tulipy, includes this functionality. Instead you have to resort to dynamically reassigning your index values to align the output with the original DataFrame.

Here is an example that uses the price series from the tulipy docs:

#Create the dataframe with close prices
prices = pd.DataFrame(data={81.59, 81.06, 82.87, 83, 83.61, 83.15, 82.84, 83.99, 84.55,
 84.36, 85.53, 86.54, 86.89, 87.77, 87.29}, columns=['close'])

#Compute the technical indicator using tulipy and save the result in a DataFrame
bbands = pd.DataFrame(data=np.transpose(ti.bbands(real = prices['close'].to_numpy(), period = 5, stddev = 2)))

#Dynamically realign the index; note from the tulip library documentation that the price/volume data is expected be ordered "oldest to newest (index 0 is oldest)"
bbands.index += prices.index.max() - bbands.index.max()

#Put the indicator values with the original DataFrame
prices[['BBANDS_5_2_low', 'BBANDS_5_2_mid', 'BBANDS_5_2_up']] = bbands
prices.head(15)

close   BBANDS_5_2_low  BBANDS_5_2_mid  BBANDS_5_2_up
0   81.06   NaN NaN NaN
1   81.59   NaN NaN NaN
2   82.87   NaN NaN NaN
3   83.00   NaN NaN NaN
4   83.61   80.530042   82.426  84.321958
5   83.15   81.494061   82.844  84.193939
6   82.84   82.533343   83.094  83.654657
7   83.99   82.471983   83.318  84.164017
8   84.55   82.417750   83.628  84.838250
9   84.36   82.435203   83.778  85.120797
10  85.53   82.511331   84.254  85.996669
11  86.54   83.142618   84.994  86.845382
12  86.89   83.536488   85.574  87.611512
13  87.77   83.870324   86.218  88.565676
14  87.29   85.288871   86.804  88.319129


问:
Python: how to net two dict entries and take the net of a number and the key of the larger value?
I have the following dictionaries which contain one entry each

```<code>a = {'long':10}
b = {'short':5}
</code>```

I would like to net the two dictionaries to get

```<code>c = {'long': 5}
</code>```

where the value 5 is the result of the larger number minus the smaller number, and the key is the key of the larger number.

Thank you

答:
This question may be an XY problem, but I'll assume you know what you are asking.  Keep in mind, the solution may not fully address your actual issue.

Assumptions

The code reflects these assumptions:

There are two dicts

Each dict is a singleton with one key-value pair

The values are integers

The resulting dict is also singleton

The resulting key comes from the dict with the larger value

The resulting value equals the larger minus the smaller values

Code

```<code>def d_net(a, b):
    """Return the net diff between two singleton dicts."""
    cmp_vals = lambda d: tuple(d.values())
    diff = lambda x: x[0] - x[1]

    d_max = max([a, b], key=cmp_vals)
    d_min = min([a, b], key=cmp_vals)

    key = list(d_max.keys())[0]
    vals = list(zip(d_max.values(), d_min.values()))[0]

    return {key: diff(vals)}
</code>```

Demo

```<code>d_net({"long": 10}, {"short": 5})
# {'long': 5}
</code>```

```<code>d_net({"long": 10}, {"short": 7})
# {'long': 3}
</code>```

```<code>d_net({"long": 10}, {"short": 10})
# {'long': 0}
</code>```

```<code>d_net({"long": -10}, {"short": -3})
# {'short': 7}
</code>```

Body:
I have the following dictionaries which contain one entry each

a = {'long':10}
b = {'short':5}

I would like to net the two dictionaries to get

c = {'long': 5}

where the value 5 is the result of the larger number minus the smaller number, and the key is the key of the larger number.

Thank you

Body:
This question may be an XY problem, but I'll assume you know what you are asking.  Keep in mind, the solution may not fully address your actual issue.

Assumptions

The code reflects these assumptions:

There are two dicts

Each dict is a singleton with one key-value pair

The values are integers

The resulting dict is also singleton

The resulting key comes from the dict with the larger value

The resulting value equals the larger minus the smaller values

Code

def d_net(a, b):
    """Return the net diff between two singleton dicts."""
    cmp_vals = lambda d: tuple(d.values())
    diff = lambda x: x[0] - x[1]

    d_max = max([a, b], key=cmp_vals)
    d_min = min([a, b], key=cmp_vals)

    key = list(d_max.keys())[0]
    vals = list(zip(d_max.values(), d_min.values()))[0]

    return {key: diff(vals)}

Demo

d_net({"long": 10}, {"short": 5})
# {'long': 5}

d_net({"long": 10}, {"short": 7})
# {'long': 3}

d_net({"long": 10}, {"short": 10})
# {'long': 0}

d_net({"long": -10}, {"short": -3})
# {'short': 7}


问:
React-window, how to prevent rerendering list on state change?
This my code sandbox example:
https://codesandbox.io/s/react-hooks-counter-demo-kevxp?file=/src/index.js

My problem is:
The list will always rerendering on every state change inside the page so the scroll will always back to the top. I want to know why this happen, and how to prevent this behaviour even the state of the list have changes then keep the last scroll position of the list

答:
Every time App renders, you are creating a brand new definition for the Example component. It may do the same thing as the old one, but it's a new component. So react compares the element from one render with the element of the next render and sees that they have different component types. Thus, thus it is forced to unmount the old one and mount the new one, just as it would if you changed something from a
 to a . The new one begins scrolled to 0.

The solution to this is to create Example only once, outside of App.

```<code>const Example = props => (
  <List
    className="List"
    height={80}
    itemCount={props.propsAbc.length}
    itemSize={20}
    width={300}
    itemData={{
      dataAbc: props.propsAbc
    }}
  >
    {({ index, style, data }) => (
      <div className={index % 2 ? "ListItemOdd" : "ListItemEven"} style={style}>
        {data.dataAbc[index]}
      </div>
    )}
  </List>
);

function App() {
  const [count, setCount] = useState(0);
  let [dataArray, setDataArray] = useState([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

  return (
    <div className="App">
      <h1>Scroll down the blue box, then click the button</h1>
      <h2>You clicked {count} times!</h2>

      <button onClick={() => setCount(count - 1)}>Decrement</button>
      <button onClick={() => setCount(count + 1)}>Increment</button>

      <div
        style={{ maxHeight: "80px", overflow: "äuto", background: "lightblue" }}
      >
        <Example propsAbc={dataArray} />
      </div>
    </div>
  );
}
</code>```

https://codesandbox.io/s/react-hooks-counter-demo-qcjgj

Body:
Every time App renders, you are creating a brand new definition for the Example component. It may do the same thing as the old one, but it's a new component. So react compares the element from one render with the element of the next render and sees that they have different component types. Thus, thus it is forced to unmount the old one and mount the new one, just as it would if you changed something from a <div> to a <span>. The new one begins scrolled to 0.

The solution to this is to create Example only once, outside of App.

const Example = props => (
  <List
    className="List"
    height={80}
    itemCount={props.propsAbc.length}
    itemSize={20}
    width={300}
    itemData={{
      dataAbc: props.propsAbc
    }}
  >
    {({ index, style, data }) => (
      <div className={index % 2 ? "ListItemOdd" : "ListItemEven"} style={style}>
        {data.dataAbc[index]}
      </div>
    )}
  </List>
);

function App() {
  const [count, setCount] = useState(0);
  let [dataArray, setDataArray] = useState([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

  return (
    <div className="App">
      <h1>Scroll down the blue box, then click the button</h1>
      <h2>You clicked {count} times!</h2>

      <button onClick={() => setCount(count - 1)}>Decrement</button>
      <button onClick={() => setCount(count + 1)}>Increment</button>

      <div
        style={{ maxHeight: "80px", overflow: "äuto", background: "lightblue" }}
      >
        <Example propsAbc={dataArray} />
      </div>
    </div>
  );
}

https://codesandbox.io/s/react-hooks-counter-demo-qcjgj


问:
Running a Python script by double-clicking desktop icon on Mac OS
I am very new to programming. I am trying to create a desktop icon that, when clicked on, will run my Python script on Mac OS.

The first line of my code involves input from the user. How can I create a desktop icon of my Python script, that when clicked, allows the user to enter the input in order to cause the Python script to start?

I have tried Pyinstaller; however, when I enter:

```<code>pyinstaller "myprogram".py
</code>```

into the Mac terminal, I receive a "dist" file that includes Python script with an ".exe" file extension. However, when I click on this extension, I receive this response in the terminal window:

```<code>logout
Saving session...
...copying shared history...
...saving history...truncating history
files...
...completed.
</code>```

I would like the Python script to run in order to have a user type their input in order to have the program run. Any help would be greatly appreciated.

答:
Also, I just went through a bundle of issues in a similar vein. If the problem persists after you delete and rerun pyinstaller with proper syntax, check out this page, I have a rather large answer all the way at the bottom, and there are other angles on the same issue there as well.

https://github.com/pyinstaller/pyinstaller/issues/3820

Body:
I am very new to programming. I am trying to create a desktop icon that, when clicked on, will run my Python script on Mac OS.

The first line of my code involves input from the user. How can I create a desktop icon of my Python script, that when clicked, allows the user to enter the input in order to cause the Python script to start?

I have tried Pyinstaller; however, when I enter:

pyinstaller "myprogram".py

into the Mac terminal, I receive a "dist" file that includes Python script with an ".exe" file extension. However, when I click on this extension, I receive this response in the terminal window:

logout
Saving session...
...copying shared history...
...saving history...truncating history
files...
...completed.

I would like the Python script to run in order to have a user type their input in order to have the program run. Any help would be greatly appreciated.


问:
How to sort a dictionary by relative word frequency in two txt files
I’m trying to write some code to read two separate text files, filter out common words, calculate frequency of words in each file, and finally output in order of relative frequency between the two lists. Therefore ideal output is words relatively more frequent in file 1 should appear at the top of the list, the words relatively more frequent in file 2 should appear at the bottom of the list, and those words that appear in both should be in the middle. For example:

```<code>word, freq file 1, freq file 2
Cat 5,0
Dog 4,0
Mouse 2,2
Carrot 1,4
Lettuce 0,5

</code>```

My code currently outputs the words in order of their frequency in file 1, but I cant figure out how to arrange the list so that it the words more common in file 2 appear at the bottom of the list. I get that I need to subtract the frequency of words in file 1 from the frequency of same words in file 2, but I cant figure out how to operate on the tuple in the dictionary...

Please help!

```<code>import re

f1=open('file1.txt','r', encoding="utf-8") #file 1
f2=open('file2.txt','r', encoding="utf-8") #file 2

file_list = [f1, f2] # This will hold all the files

num_files = len(file_list)

stopwords = ["a", "and", "the", "i", "of", "this", "it", "but", "is", "in", "im", "my", "to", "for", "as", "on", "helpful", "comment", "report", "stars", "reviewed", "united", "kingdom", "was", "with", "-", "it", "not", "about", "which", "so", "at", "out", "abuse", "than","any", "if", "be", "can", "its", "customer", "dont", "just", "other", "too", "only", "people", "found", "helpful", "have", "wasnt", "purchase", "do", "only", "bought", "etc", "verified", "", "wasnt", "thanks", "thanx", "could", "think", "your", "thing", "much", "ive", "you", "they", "vine", "had", "more", "that"]

frequencies = {} # One dictionary to hold the frequencies

for i, f in enumerate(file_list):   # Loop over the files, keeping an index i
    for line in f:                                      # Get the lines of that file
        for word in line.split():           # Get the words of that file
            word = re.sub(r'[^\w\s]','',word) # Strip punctuation
            word = word.lower()                     # Make lowercase
            if not word in stopwords:           # Remove stopwords
                    if not word.isdigit():      # Ignore digits
                        if not word in frequencies:
                            frequencies[word] = [0 for _ in range(num_files)] # make a list of 0's for any word not seen yet -- one 0 for each file

                        frequencies[word][i] += 1   # Increment the frequency count for that word and file

frequency_sorted = sorted(frequencies, key=frequencies.get, reverse=True)
for r in frequency_sorted:
    print (r, frequencies[r])

</code>```

答:
You overcomplicate things. This should help you:

```<code>import strings
from collections import Counter

def get_freqs( name ) :
    with open(name) as fin :
        text = fin.read().lower()

    words = ''.join( i if i in strings.ascii_letters else ' ' for i in text )
    words = [w for w in words.split() if len(w) > 0]
    return Counter( words )

freqs1 = get_freqs( 'file1.txt' )
freqs2 = get_freqs( 'file2.txt' )

all_words = set(freqs1.keys()) | set(freqs2.keys())  # - set(stop_words) ?
freqs_sorted = sorted( (freqs1[w], freqs2[w], w) for w in all_words )
</code>```

If you worry about the stopwords, you may change all_words = set(freqs1.keys()) | set(freqs2.keys()) into all_words = set(freqs1.keys()) | set(freqs2.keys()) - set(stop_words) or something similar.

Body:
I’m trying to write some code to read two separate text files, filter out common words, calculate frequency of words in each file, and finally output in order of relative frequency between the two lists. Therefore ideal output is words relatively more frequent in file 1 should appear at the top of the list, the words relatively more frequent in file 2 should appear at the bottom of the list, and those words that appear in both should be in the middle. For example:

word, freq file 1, freq file 2
Cat 5,0
Dog 4,0
Mouse 2,2
Carrot 1,4
Lettuce 0,5

My code currently outputs the words in order of their frequency in file 1, but I cant figure out how to arrange the list so that it the words more common in file 2 appear at the bottom of the list. I get that I need to subtract the frequency of words in file 1 from the frequency of same words in file 2, but I cant figure out how to operate on the tuple in the dictionary...

Please help!

import re

f1=open('file1.txt','r', encoding="utf-8") #file 1
f2=open('file2.txt','r', encoding="utf-8") #file 2

file_list = [f1, f2] # This will hold all the files

num_files = len(file_list)

stopwords = ["a", "and", "the", "i", "of", "this", "it", "but", "is", "in", "im", "my", "to", "for", "as", "on", "helpful", "comment", "report", "stars", "reviewed", "united", "kingdom", "was", "with", "-", "it", "not", "about", "which", "so", "at", "out", "abuse", "than","any", "if", "be", "can", "its", "customer", "dont", "just", "other", "too", "only", "people", "found", "helpful", "have", "wasnt", "purchase", "do", "only", "bought", "etc", "verified", "", "wasnt", "thanks", "thanx", "could", "think", "your", "thing", "much", "ive", "you", "they", "vine", "had", "more", "that"]

frequencies = {} # One dictionary to hold the frequencies

for i, f in enumerate(file_list):   # Loop over the files, keeping an index i
    for line in f:                                      # Get the lines of that file
        for word in line.split():           # Get the words of that file
            word = re.sub(r'[^\w\s]','',word) # Strip punctuation
            word = word.lower()                     # Make lowercase
            if not word in stopwords:           # Remove stopwords
                    if not word.isdigit():      # Ignore digits
                        if not word in frequencies:
                            frequencies[word] = [0 for _ in range(num_files)] # make a list of 0's for any word not seen yet -- one 0 for each file

                        frequencies[word][i] += 1   # Increment the frequency count for that word and file

frequency_sorted = sorted(frequencies, key=frequencies.get, reverse=True)
for r in frequency_sorted:
    print (r, frequencies[r])

Body:
You overcomplicate things. This should help you:

import strings
from collections import Counter

def get_freqs( name ) :
    with open(name) as fin :
        text = fin.read().lower()

    words = ''.join( i if i in strings.ascii_letters else ' ' for i in text )
    words = [w for w in words.split() if len(w) > 0]
    return Counter( words )

freqs1 = get_freqs( 'file1.txt' )
freqs2 = get_freqs( 'file2.txt' )

all_words = set(freqs1.keys()) | set(freqs2.keys())  # - set(stop_words) ?
freqs_sorted = sorted( (freqs1[w], freqs2[w], w) for w in all_words )

If you worry about the stopwords, you may change all_words = set(freqs1.keys()) | set(freqs2.keys()) into all_words = set(freqs1.keys()) | set(freqs2.keys()) - set(stop_words) or something similar.


问:
Firebase FCM with google plus cordova plugin conflict - IOS
I am using

```<code>"cordova-plugin-fcm-with-dependecy-updated": "^2.4.0",
"cordova-plugin-googleplus": "^8.0.0",
</code>```

I have added IOS platform

```<code>"cordova-ios": "^5.0.1",
</code>```

and when I try to build it in XCode it fails with below error.

```<code>Undefined symbols for architecture x86_64:
"_OBJC_CLASS_$_GSDK_GTMLogger", referenced from:
  objc-class-ref in GoogleIPhoneUtilities(GIPReachability.o)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

Note: I have tried everything mentioned in this question.
Firebase Undefined symbols for architecture x86_64

Build works if I remove any one of the plugins.

答:
With this version it has worked perfectly.

```<code>"cordova-plugin-googleplus": "^7.0.1"
</code>```

It should also be taken into account that sometimes it is necessary to add REVERSED_CLIENT_ID

Xcode -> info -> URL Types (add this)

Body:
I am using

"cordova-plugin-fcm-with-dependecy-updated": "^2.4.0",
"cordova-plugin-googleplus": "^8.0.0",

I have added IOS platform

"cordova-ios": "^5.0.1",

and when I try to build it in XCode it fails with below error.

Undefined symbols for architecture x86_64:
"_OBJC_CLASS_$_GSDK_GTMLogger", referenced from:
  objc-class-ref in GoogleIPhoneUtilities(GIPReachability.o)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Note: I have tried everything mentioned in this question.
Firebase Undefined symbols for architecture x86_64

Build works if I remove any one of the plugins.

Body:
With this version it has worked perfectly.

"cordova-plugin-googleplus": "^7.0.1"

It should also be taken into account that sometimes it is necessary to add REVERSED_CLIENT_ID

Xcode -> info -> URL Types (add this)


问:
How can I know the size of a file using a recursive program?
I have to make a program that measures the size of a given directory by using recursivity. I need to use the OS module. When I used

```<code>os.path.getsize()
</code>```

The response was 0 bytes, which makes no sense.

答:
You need to mention the path in the argument of a getsize function.
So it would look like:

```<code>os.path.getsize(<path_of_file>)
</code>```

If you are doing that already and interested in the size of a folder, you can add size of the files in the folder iteratively.

```<code>sum(os.path.getsize(f) for f in os.listdir(<path_of_the_folder>) if os.path.isfile(f))
</code>```

Body:
I have to make a program that measures the size of a given directory by using recursivity. I need to use the OS module. When I used

os.path.getsize()

The response was 0 bytes, which makes no sense.

Body:
You need to mention the path in the argument of a getsize function.
So it would look like:

os.path.getsize(<path_of_file>)

If you are doing that already and interested in the size of a folder, you can add size of the files in the folder iteratively.

sum(os.path.getsize(f) for f in os.listdir(<path_of_the_folder>) if os.path.isfile(f))


问:
How to restart a Tidal agent using APIs
I am new to Tidal and have to automate the agent restart process using API.
From the architecture stand point, I understand the agents are running on the nodes, so when the tidal master is not able to reach agent, it sends an error message with agent name that is not running. How can I use this information to restart the agent ? Is there any API to restart an agent ?

Thanks!

答: OK, so apparently there is no API to restart Tidal agent. This has to be done through command by logging into the target machine where the agent is running. </p>

Title: How to restart a Tidal agent using APIs


问:
Images not displaying in Angular
A lowly teacher here trying to sort an app out for my school so please go easy!
I'm trying to get a student image to display in my Angular app and this doesn't work in my student-details.component.ts:

```<code><img src="./images/11451.png" alt="Test" width="84"
     height="120">
</code>```

If I use URLs then it displays fine so I'm thinking it's a problem with the file structure. Could anybody help please? I'm using ng serve -o to see the app if that makes a difference on localhost:4200

答:
The recommended practice is to put your images in the assets folder,

If you add images in the assets/images folder, then this line of code should work in your templates

```<code>src
|__assests
   |__images
      |__myimage.png
</code>```

and access it as

```<code><img alt="My image name" src="./assets/images/myimage.png">
</code>```

Title: Images not displaying in Angular

Body:
A lowly teacher here trying to sort an app out for my school so please go easy!
I'm trying to get a student image to display in my Angular app and this doesn't work in my student-details.component.ts:

If I use URLs then it displays fine so I'm thinking it's a problem with the file structure. Could anybody help please? I'm using ng serve -o to see the app if that makes a difference on localhost:4200

Body:
The recommended practice is to put your images in the assets folder,

If you add images in the assets/images folder, then this line of code should work in your templates

src
|__assests
   |__images
      |__myimage.png

and access it as

<img alt="My image name" src="./assets/images/myimage.png">


问:
How do I mention a role with Discord.js?
I am making a bot and I am trying to Ping a certain role.  Here is the relevant code:

```<code>let msga = msg.author;
msg.channel.send("@NES Found one!! " + msga);
</code>```

@NES is the role I am trying to ping/mention.

答:
The currently accepted answer is incorrect. You ping a user with <@id>, not a role.

As stated in this Github issue, for roles, you have to use <@&id> and the role has to be pingable.

So, the correct code for the question would be something like:

msg.channel.send("<@&" + roleId + "> Found one!! " + msga);
```
<p>Or, using fancy formatted strings:</p>
<pre class="lang-js prettyprint-override"><code>msg.channel.send(`<@&${roleId}> Found one!! ${msga}`);
</code>```

Body:
I am making a bot and I am trying to Ping a certain role.  Here is the relevant code:

let msga = msg.author;
msg.channel.send("@NES Found one!! " + msga);

@NES is the role I am trying to ping/mention.

Body:
The currently accepted answer is incorrect. You ping a user with <@id>, not a role.

As stated in this Github issue, for roles, you have to use <@&id> and the role has to be pingable.

So, the correct code for the question would be something like:

msg.channel.send("<@&" + roleId + "> Found one!! " + msga);

Or, using fancy formatted strings:

msg.channel.send(`<@&${roleId}> Found one!! ${msga}`);


问:
Perl Regex: Need help on a way to split string into groups matching a pattern
I need to split this string to an array:

```<code>$string = "9583526578','9583636523','9673522574','9183556528','9983023378";
</code>```

Here's how I want my array to look like after splitting:

```<code>@foo = [
           [9583526578, 9583636523],
           [9673522574, 9183556528],
           [9983023378]
       ]
</code>```

As you might have noticed, I need to split this string into groups of n (2 in this example) but still consider remainder if it doesn't match with n.

How can this be done in Perl?

I've done my research and experimentations but can't seem to get it right after a couple of hours.

Thanks for your time! :)

答: First split on "','" to give you an array, then group the elements as desired.</p>

Body:
I need to split this string to an array:

$string = "9583526578','9583636523','9673522574','9183556528','9983023378";

Here's how I want my array to look like after splitting:

@foo = [
           [9583526578, 9583636523],
           [9673522574, 9183556528],
           [9983023378]
       ]

As you might have noticed, I need to split this string into groups of n (2 in this example) but still consider remainder if it doesn't match with n.

How can this be done in Perl?

I've done my research and experimentations but can't seem to get it right after a couple of hours.

Thanks for your time! :)


问:
Hardlinks in linux command line input
Hard links cannot span physical devices. Exactly this statement I read while understanding the concept of hard link in Linux. Can anyone help me to understand this ?</p>

答:
A filename, is a pointer to an inode.

So if you're not on the same drive, it's impossible to link a file, because the inodes belongs to a specific disk

Title: Hardlinks in linux command line input


问:
splitting txt based on ':' but excluding the timestamp in python
```<code>05-23 14:14:53.275  A:B:C
</code>```

in the above case i am trying to split the txt based on  : using line.split(':') and following o/p should come as

```<code>['05-23 14:14:53.275','A','B','C']
</code>```

but instead The o/p came is
['05-23 14','14','53.275','A','B','C']

it is also splitting the timestamp.
how do i exclude that from splitting

答:
You are also splitting on the last space. An easy solution is to split on the last space and then split the second group:</p>

```<code>s = '05-23 14:14:53.275 A:B:C'
front, back = s.rsplit(maxsplit=1)
[front] + back.split(':')

# ['05-23 14:14:53.275', 'A', 'B', 'C']
</code>```

Body:
05-23 14:14:53.275  A:B:C

in the above case i am trying to split the txt based on  : using line.split(':') and following o/p should come as

['05-23 14:14:53.275','A','B','C']

but instead The o/p came is
['05-23 14','14','53.275','A','B','C']

it is also splitting the timestamp.
how do i exclude that from splitting

Body:
You are also splitting on the last space. An easy solution is to split on the last space and then split the second group:

s = '05-23 14:14:53.275 A:B:C'
front, back = s.rsplit(maxsplit=1)
[front] + back.split(':')

# ['05-23 14:14:53.275', 'A', 'B', 'C']


问:
Can someone give a good math/stats explanation as to what the parameter var_smoothing does for GaussianNB in scikit learn?
I am aware of this parameter var_smoothing and how to tune it, but I'd like an explanation from a math/stats aspect that explains what tuning it actually does - I haven't been able to find any good ones online.</p>

答:
A Gaussian curve can serve as a "low pass" filter, allowing only the samples close to its mean to "pass." In the context of Naive Bayes, assuming a Gaussian distribution is essentially giving more weights to the samples closer to the distribution mean. This might or might not be appropriate depending if what you want to predict follows a normal distribution.

The variable, var_smoothing, artificially adds a user-defined value to the distribution's variance (whose default value is derived from the training data set). This essentially widens (or "smooths") the curve and accounts for more samples that are further away from the distribution mean.


问:
How to use Font Awesome icon in android application?
I want to use Font Awesome's icon set in my android application. I have some TextView to set those icons. I don't want to use any png image. My Textview is like this ->

```<code><TextView
    android:id="@+id/userLogin"
    android:text="Login Now"
    android:clickable="true"
    android:onClick="login"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
</code>```

No, I want to put a icon before the text Login Now. How to do that ?

答:
If anyone wants to assign font value programmatically then this is how I did.
Create an assets folder if it's not there and put ttf file in the folder</p>

```<code>Typeface type = Typeface.createFromAsset(getContext().getAssets(), "fonts/fa_solid_900.ttf");
tvHeart.setTypeface(type);
tvHeart.setText(Html.fromHtml(""));
</code>```

Body:
I want to use Font Awesome's icon set in my android application. I have some TextView to set those icons. I don't want to use any png image. My Textview is like this ->

<TextView
    android:id="@+id/userLogin"
    android:text="Login Now"
    android:clickable="true"
    android:onClick="login"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

No, I want to put a icon before the text Login Now. How to do that ?

Body:
If anyone wants to assign font value programmatically then this is how I did.
Create an assets folder if it's not there and put ttf file in the folder

Typeface type = Typeface.createFromAsset(getContext().getAssets(), "fonts/fa_solid_900.ttf");
tvHeart.setTypeface(type);
tvHeart.setText(Html.fromHtml("&#xf004;"));


答:
I would suggest you use regex to split this.

([-:\s\d.]*)\s([\w:]*)

Try it in some regex online to see how it is split. Once you get your regex right, you cna use the groups to select which part you want  and work on that.

```<code>import re

str = '05-23 14:14:53.275  A:B:C'
regex = '([-:\s\d.]*)\s([\w:]*)'
groups = re.compile(regex).match(str).groups()
timestamp = groups[0]
restofthestring = groups[1]

# Now you can split the second part using split
splits = restofthestring.split(':')
</code>```

Title: splitting txt based on ':' but excluding the timestamp in python

Body:
I would suggest you use regex to split this.

([-:\s\d.]*)\s([\w:]*)

Try it in some regex online to see how it is split. Once you get your regex right, you cna use the groups to select which part you want  and work on that.

import re

str = '05-23 14:14:53.275  A:B:C'
regex = '([-:\s\d.]*)\s([\w:]*)'
groups = re.compile(regex).match(str).groups()
timestamp = groups[0]
restofthestring = groups[1]

# Now you can split the second part using split
splits = restofthestring.split(':')


答:
Split the line on whitespaces once, starting from the right:

```<code>parts = line.rsplit(maxsplit=1)
</code>```

Combine the first two parts and the last one split by the colons:

```<code>parts[:1] + parts[-1].rsplit(":")
['05-23 14:14:53.275', 'A', 'B', 'C']
</code>```

Body:
Split the line on whitespaces once, starting from the right:

parts = line.rsplit(maxsplit=1)

Combine the first two parts and the last one split by the colons:

parts[:1] + parts[-1].rsplit(":")
['05-23 14:14:53.275', 'A', 'B', 'C']


问:
replace a word from string in list C# LINQ
I have list in which i'm getting URL like:

I want to replace "URL//" with actual URL like any URL. why i'm doing this, because, the URL will be dependent on environment website is being accessed for. like for stage, it will use stage's url and so on.

I have tried:

```<code>ProductReviews.Items.ToList().ForEach(x => x.AvatarUrl.Replace("URL", serverImageUrl));
</code>```

but as per my understanding it requires full string value as "URL". Please help me

答:
You don't use LINQ to perform modifications to your data collection. If you want to modify the collection, use a normal foreach loop

```<code>foreach(var pr in ProductReviews)
  pr.AvatarUrl = pr.AvatarUrl.Replace("URL", serverImageUrl);
</code>```

Remember: "LINQ is for querying, not modifying"

If you want to replace URL using LINQ you do it as part of a query that returns a enumeration of new objects that represent your replacements:

```<code>ProductReviews.Select(pr => new { Review = pr, ReplacedUrl = pr.AvatarUrl.Replace("URL", serverImageUrl) } );
</code>```

This will give you an enumerable of new objects that has the original and the replaced url. It's easier to include the original, assuming you need all the fields, as a single field but you could also list out the things you want:

```<code>ProductReviews.Select(pr => new {
   pr.Id,
   pr.CustomerId,
   AvatarUrl = pr.AvatarUrl.Replace("URL", serverImageUrl)
} );
</code>```

Or you can use an automapper to map your db objects to your client side objects and save a bit of this laborious typing

Body:
I have list in which i'm getting URL like:

I want to replace "URL//" with actual URL like any URL. why i'm doing this, because, the URL will be dependent on environment website is being accessed for. like for stage, it will use stage's url and so on.

I have tried:

ProductReviews.Items.ToList().ForEach(x => x.AvatarUrl.Replace("URL", serverImageUrl));

but as per my understanding it requires full string value as "URL". Please help me

Body:
You don't use LINQ to perform modifications to your data collection. If you want to modify the collection, use a normal foreach loop

foreach(var pr in ProductReviews)
  pr.AvatarUrl = pr.AvatarUrl.Replace("URL", serverImageUrl);

Remember: "LINQ is for querying, not modifying"

If you want to replace URL using LINQ you do it as part of a query that returns a enumeration of new objects that represent your replacements:

ProductReviews.Select(pr => new { Review = pr, ReplacedUrl = pr.AvatarUrl.Replace("URL", serverImageUrl) } );

This will give you an enumerable of new objects that has the original and the replaced url. It's easier to include the original, assuming you need all the fields, as a single field but you could also list out the things you want:

ProductReviews.Select(pr => new {
   pr.Id,
   pr.CustomerId,
   AvatarUrl = pr.AvatarUrl.Replace("URL", serverImageUrl)
} );

Or you can use an automapper to map your db objects to your client side objects and save a bit of this laborious typing


问:
Make a custom type post featured
I made a custom post type with CPT UI. On the listing page (wp-admin/edit.php?post_type=promotions), I don't see the little star button to make the post featured as with default posts.

How do I add that button ?

Coming from Drupal and struggling. Help me out :)

答: There is no such option in WordPress to make a post features this way. You can make a post featured by creating a category featured Like(Featured Promotion in your case) and then add your promotions to that category. </p>

Title: Make a custom type post featured


答:
I don't think it's a react window problem.

A react component re-renders because there's a state change. In this case, the state change is caused by setCount (when you click the increment button), which re-renders the entire component including Example.

If Example is its own component, the scroll position won't get refreshed, because it no longer depends on the count state.

A working sample here:
https://codesandbox.io/s/react-hooks-counter-demo-hbek7?file=/src/index.js

Title: React-window, how to prevent rerendering list on state change?

Body:
This my code sandbox example:
https://codesandbox.io/s/react-hooks-counter-demo-kevxp?file=/src/index.js

My problem is:
The list will always rerendering on every state change inside the page so the scroll will always back to the top. I want to know why this happen, and how to prevent this behaviour even the state of the list have changes then keep the last scroll position of the list


问:
BASH: Best way to set variable from array
Bash 4 on Linux ~

I have an array of possible values. I must restrict user input to these values.

```<code>Arr=(hello kitty goodbye quick fox)
</code>```

User supplies value as argument to script:

```<code>bash myscript.sh -b var
</code>```

Currently, I'm trying the following:

```<code>function func_exists () {
_var="$1"
for i in ${Arr[@]}
do
    if [ "$i" == "$_var" ]
    then
        echo hooray for "$_var"
        return 1
    fi
done
    return 0
}

func_exists $var
if [ $? -ne 1 ];then
    echo "Not a permitted value."
    func_help
    exit $E_OPTERROR
fi
</code>```

Seems to work fine, are there better methods for testing user input against an array of allowed values?

UPDATE: I like John K's answer ...can someone clarify the use of $@? I understand that this represents all positional parameters -- so we shift the first param off the stack and $@ now represents all remaining params, those being the passed array ...is that correct? I hate blindly using code without understanding ...even if it works!

答:
```<code>function func_exists () {
  case "$1"
  in
    hello)
    kitty)
    goodbye)
    quick)
    fox)
      return 1;;
    *)
      return 0;;
  esac
}
</code>```

Body:
Bash 4 on Linux ~

I have an array of possible values. I must restrict user input to these values.

Arr=(hello kitty goodbye quick fox)

User supplies value as argument to script:

bash myscript.sh -b var

Currently, I'm trying the following:

function func_exists () {
_var="$1"
for i in ${Arr[@]}
do
    if [ "$i" == "$_var" ]
    then
        echo hooray for "$_var"
        return 1
    fi
done
    return 0
}

func_exists $var
if [ $? -ne 1 ];then
    echo "Not a permitted value."
    func_help
    exit $E_OPTERROR
fi

Seems to work fine, are there better methods for testing user input against an array of allowed values?

UPDATE: I like John K's answer ...can someone clarify the use of $@? I understand that this represents all positional parameters -- so we shift the first param off the stack and $@ now represents all remaining params, those being the passed array ...is that correct? I hate blindly using code without understanding ...even if it works!


答:
```<code>ProductReviews.Items.ToList().ForEach(x => x.AvatarUrl = x.AvatarUrl.Replace("URL", serverImageUrl));
</code>```

Title: replace a word from string in list C# LINQ


问:
make laravel homestead site public without using third party services
I want to access my laravel homestead site from anywhere in the world without using third party services.I would like to know how I can do that.please help me</p>

答:
You might use ngrok, which is already part of Homestead, to make your site or APIs public.

I recommend deploying on laravel forge using the optimal package. It's quite affordable.

Or alternatively you might play with laravel vapor.


问:
How to use a read/write stream between two Python asyncio coroutines?
How can I use asyncio to implement a pipe between two coroutines, one that reads from a stream and the other that writes into it?

Suppose we have this existing code, two simple scripts. One that produces to stdout:

```<code># produce.py

import asyncio
import random
import sys

async def produce(stdout):
    for i in range(10000):
        await asyncio.sleep(random.randint(0, 3))
        print(i, file=stdout, flush=True)

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(produce(sys.stdout))
    loop.close()
</code>```

And the other that reads from stdin:

```<code># consume.py

async def consume(loop, stdin):
    reader = asyncio.StreamReader(loop=loop)
    reader_protocol = asyncio.StreamReaderProtocol(reader)
    await loop.connect_read_pipe(lambda: reader_protocol, stdin)

    while True:
        line = await reader.readline()
        if not line:
            break
        print(int(line) ** 2)

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(consume(loop, sys.stdin))
    loop.close()
</code>```

Obviously, since our two pieces can run individually from the command-line, we could use the subprocess module with shell pipes (produce | consume).

But we would like to implement the equivalent of a Unix pipe in Python, i.e. connect the streams of those two existing functions.

Something like this won't work:

```<code>pipe = io.BytesIO()

await asyncio.gather(produce(pipe),
                     consume(loop, pipe))
</code>```

If the two functions would manipulate generators, we could write something like this (python 3.6):

```<code>async def produce():
    for i in range(10000):
        await asyncio.sleep(random.randint(0, 3))
        yield str(i)

async def consume(generator):
    async for value in generator:
        print(int(value) ** 2)

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(consume(produce()))
    loop.close()
</code>```

Is there some parts of the asyncio API that would allow that ?

Thanks!

答:
The original post says "Something like this won't work." I'm not sure if this statement is indented to mean "the following code did not work" or "I do not want a solution of this style."

I will note that the following code does work:

```<code>r, w = os.pipe()
read_pipe = os.fdopen(r, 'r')
write_pipe = os.fdopen(w, 'w')

await asyncio.gather(produce(write_pipe), consume(loop, read_pipe))
</code>```

Body:
How can I use asyncio to implement a pipe between two coroutines, one that reads from a stream and the other that writes into it?

Suppose we have this existing code, two simple scripts. One that produces to stdout:

# produce.py

import asyncio
import random
import sys

async def produce(stdout):
    for i in range(10000):
        await asyncio.sleep(random.randint(0, 3))
        print(i, file=stdout, flush=True)

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(produce(sys.stdout))
    loop.close()

And the other that reads from stdin:

# consume.py

async def consume(loop, stdin):
    reader = asyncio.StreamReader(loop=loop)
    reader_protocol = asyncio.StreamReaderProtocol(reader)
    await loop.connect_read_pipe(lambda: reader_protocol, stdin)

    while True:
        line = await reader.readline()
        if not line:
            break
        print(int(line) ** 2)

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(consume(loop, sys.stdin))
    loop.close()

Obviously, since our two pieces can run individually from the command-line, we could use the subprocess module with shell pipes (produce | consume).

But we would like to implement the equivalent of a Unix pipe in Python, i.e. connect the streams of those two existing functions.

Something like this won't work:

pipe = io.BytesIO()

await asyncio.gather(produce(pipe),
                     consume(loop, pipe))

If the two functions would manipulate generators, we could write something like this (python 3.6):

async def produce():
    for i in range(10000):
        await asyncio.sleep(random.randint(0, 3))
        yield str(i)

async def consume(generator):
    async for value in generator:
        print(int(value) ** 2)

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(consume(produce()))
    loop.close()

Is there some parts of the asyncio API that would allow that ?

Thanks!

Body:
The original post says "Something like this won't work." I'm not sure if this statement is indented to mean "the following code did not work" or "I do not want a solution of this style."

I will note that the following code does work:

r, w = os.pipe()
read_pipe = os.fdopen(r, 'r')
write_pipe = os.fdopen(w, 'w')

await asyncio.gather(produce(write_pipe), consume(loop, read_pipe))


问:
Image Co-Ordinate System Design
I'm diving into something without sufficient background, but I feel like there may be simple solutions that don't require me to have in depth knowledge of the topic.

What I am trying to do is have an image co-ordinate system. Basically the user will supply an image, like a house plan. They can then click on points in the image and create markers (like google maps). The next time they retrieve the map, all the markers they added before are there and they can add new ones.

I need to identify the points these markers are located on so I can store that information. I also need to be able to create a layer on the image that contains the markers and renders them in the exact locations they were placed.

I imagine the easiest way to do this is to use pixel co-ordinates...the rub here is that the image won't be a fixed size since there is a web application and an IPad application, so the co-ordinate system needs to work as long as the image is in the same size ratio.

The server size is .NET and as mentioned there is an IPad app, so the solution needs to be viable given that tech stack.

Any ideas?

答: My suggestion is don't try to figure out the correlation between the actual image and the coordinates.  The only thing I would do is use the resolution of the image, aka 800x600 and use that for your grid.  Then overlay your markers using that grid on the image.  The points you'd remember would just be X and Y values and maybe a tag name/id.</p>

Title: Image Co-Ordinate System Design


问:
Pass foreign key in Golang gin
Here is my code snippet I'm trying to pass language_id along with book create call somehow I'm getting an error

```<code>func Create(c *gin.Context) {
    dbb := c.MustGet("db").(*gorm.DB)
    book := Models.BookModel{
        Title:  c.PostForm("title"),
        Author: c.PostForm("author"),
        LanguageID: c.PostForm("language_id"),
    }

    dbb.Save(&book)
    c.JSON(http.StatusCreated, gin.H{"status": http.StatusCreated, "message": "Book created successfully!", "bookId": book.ID})
}
</code>```

error is
Cannot use 'c.PostForm("language_id")' (type string) as type int
any help that would be great thanks!

答:
The problem is the LanguageID is an int type and you wanna pass a string value to it, you should parse it to int like:

```<code>func Create(c *gin.Context) {
dbb := c.MustGet("db").(*gorm.DB)

languageID, err := strconv.Atoi(c.PostForm("language_id"))
 if err != nil {
    fmt.Println(err)
    return
}

book := Models.BookModel{
    Title:  c.PostForm("title"),
    Author: c.PostForm("author"),
    LanguageID: languageID,
}

dbb.Save(&book)
c.JSON(http.StatusCreated, gin.H{"status": http.StatusCreated, "message": "Book created successfully!", "bookId": book.ID})
}
</code>```

Title: Pass foreign key in Golang gin

Body:
Here is my code snippet I'm trying to pass language_id along with book create call somehow I'm getting an error

func Create(c *gin.Context) {
    dbb := c.MustGet("db").(*gorm.DB)
    book := Models.BookModel{
        Title:  c.PostForm("title"),
        Author: c.PostForm("author"),
        LanguageID: c.PostForm("language_id"),
    }

    dbb.Save(&book)
    c.JSON(http.StatusCreated, gin.H{"status": http.StatusCreated, "message": "Book created successfully!", "bookId": book.ID})
}

error is
Cannot use 'c.PostForm("language_id")' (type string) as type int
any help that would be great thanks!

Body:
The problem is the LanguageID is an int type and you wanna pass a string value to it, you should parse it to int like:

func Create(c *gin.Context) {
dbb := c.MustGet("db").(*gorm.DB)

languageID, err := strconv.Atoi(c.PostForm("language_id"))
 if err != nil {
    fmt.Println(err)
    return
}

book := Models.BookModel{
    Title:  c.PostForm("title"),
    Author: c.PostForm("author"),
    LanguageID: languageID,
}

dbb.Save(&book)
c.JSON(http.StatusCreated, gin.H{"status": http.StatusCreated, "message": "Book created successfully!", "bookId": book.ID})
}


问:
Filtering empty partitions in RDD
Is there a way to filter empty partitions in RDD? I have some empty partitions after partitioning and I can't use them in action method.

I use Apache Spark in Scala

答:
This is my sample data

```<code>  val sc = spark.sparkContext
  val myDataFrame = spark.range(20).toDF("mycol").repartition($"mycol")
  myDataFrame.show(false)

</code>```

Output :

```<code>+-----+
|mycol|
+-----+
|19   |
|0    |
|7    |
|6    |
|9    |
|17   |
|5    |
|1    |
|10   |
|3    |
|12   |
|8    |
|11   |
|2    |
|4    |
|13   |
|18   |
|14   |
|15   |
|16   |
+-----+
</code>```

In the above code when you do repartition on column then 200 paritions will be created since spark.sql.shuffle.partitions = 200 in that many are not used or empty partitions since data is just 10 numbers (we are trying to fit 20 numbers in to 200 partitions means.... most of the partitions are empty.... :-))

1) Prepare a long accumulator variable to quickly count non empty partitions.

2) Add all non empty partitions in to accumulator variable like below example.

```<code> val nonEmptyPartitions = sc.longAccumulator("nonEmptyPartitions")
 myDataFrame.foreachPartition(partition =>
    if (partition.length > 0) nonEmptyPartitions.add(1))
</code>```

drop non empty partitions (means coalesce them... less shuffle/ minimum shuffle ).

print them.

```<code>
val finalDf = myDataFrame.coalesce(nonEmptyPartitions.value.toInt)
println(s"nonEmptyPart : ${nonEmptyPartitions.value.toInt}")
println(s"df.rdd.partitions.length :  ${myDataFrame.rdd.getNumPartitions}")
println(s"finalDf.rdd.partitions.length  :  ${finalDf.rdd.getNumPartitions}")

</code>```

print them ...

Result :

```<code>nonEmptyPart : 20
df.rdd.partitions.length :  200
finalDf.rdd.partitions.length  :  20
</code>```

Proof that all non empty partitions are dropped...

```<code>  myDataFrame.withColumn("partitionId", org.apache.spark.sql.functions.spark_partition_id)
.groupBy("partitionId")
.count
.show

</code>```

Result printed partition wise record count :

```<code> +-----------+-----+
|partitionId|count|
+-----------+-----+
|128        |1    |
|190        |1    |
|140        |1    |
|164        |1    |
|5          |1    |
|154        |1    |
|112        |1    |
|107        |1    |
|4          |1    |
|49         |1    |
|69         |1    |
|77         |1    |
|45         |1    |
|121        |1    |
|143        |1    |
|58         |1    |
|11         |1    |
|150        |1    |
|68         |1    |
|116        |1    |
+-----------+-----+
</code>```

Note :

Usage spark_partition_id is for demo/debug purpose only not for production purpose.

I reduced 200 partitions (due to repartition on column ) to 20 non empty partitions.

Conclusion :

Finally you got rid of extra empty partitions which doesnt have any data and avoided un necessary schedule to dummy tasks on empty partitions.

Title: Filtering empty partitions in RDD

Body:
This is my sample data

  val sc = spark.sparkContext
  val myDataFrame = spark.range(20).toDF("mycol").repartition($"mycol")
  myDataFrame.show(false)

Output :

+-----+
|mycol|
+-----+
|19   |
|0    |
|7    |
|6    |
|9    |
|17   |
|5    |
|1    |
|10   |
|3    |
|12   |
|8    |
|11   |
|2    |
|4    |
|13   |
|18   |
|14   |
|15   |
|16   |
+-----+

In the above code when you do repartition on column then 200 paritions will be created since spark.sql.shuffle.partitions = 200 in that many are not used or empty partitions since data is just 10 numbers (we are trying to fit 20 numbers in to 200 partitions means.... most of the partitions are empty.... :-))

1) Prepare a long accumulator variable to quickly count non empty partitions.

2) Add all non empty partitions in to accumulator variable like below example.

 val nonEmptyPartitions = sc.longAccumulator("nonEmptyPartitions")
 myDataFrame.foreachPartition(partition =>
    if (partition.length > 0) nonEmptyPartitions.add(1))

drop non empty partitions (means coalesce them... less shuffle/ minimum shuffle ).

print them.

val finalDf = myDataFrame.coalesce(nonEmptyPartitions.value.toInt)
println(s"nonEmptyPart : ${nonEmptyPartitions.value.toInt}")
println(s"df.rdd.partitions.length :  ${myDataFrame.rdd.getNumPartitions}")
println(s"finalDf.rdd.partitions.length  :  ${finalDf.rdd.getNumPartitions}")

print them ...

Result :

nonEmptyPart : 20
df.rdd.partitions.length :  200
finalDf.rdd.partitions.length  :  20

Proof that all non empty partitions are dropped...

  myDataFrame.withColumn("partitionId", org.apache.spark.sql.functions.spark_partition_id)
.groupBy("partitionId")
.count
.show

Result printed partition wise record count :

 +-----------+-----+
|partitionId|count|
+-----------+-----+
|128        |1    |
|190        |1    |
|140        |1    |
|164        |1    |
|5          |1    |
|154        |1    |
|112        |1    |
|107        |1    |
|4          |1    |
|49         |1    |
|69         |1    |
|77         |1    |
|45         |1    |
|121        |1    |
|143        |1    |
|58         |1    |
|11         |1    |
|150        |1    |
|68         |1    |
|116        |1    |
+-----------+-----+

Note :

Usage spark_partition_id is for demo/debug purpose only not for production purpose.

I reduced 200 partitions (due to repartition on column ) to 20 non empty partitions.

Conclusion :

Finally you got rid of extra empty partitions which doesnt have any data and avoided un necessary schedule to dummy tasks on empty partitions.


问:
Function runs repeatedly for no apparent reason
I'm writing a program that is supposed to average integers together, and also check if a number is negative when it is input. Everything seems to work, until it's time to return a value, then it appears to run my function repeatedly and I have no idea why. I would google my issue, but I don't even know what to look up.</p>

```<code>#include <stdio.h>
double averageOrNegative(int sum, int counter);
int main(){
    int  sum = 0, counter = 0;
    double number = averageOrNegative(sum,counter);
    return 0;
}
double averageOrNegative(int sum, int counter){//the sum and counter are declared outside the function so they don't get reset when I call it again
    int input = 0;
    double result = 0;
    char yesORno = ' ';
    printf("\nPlease input a number \n");
    scanf("%d", &input);
        if(input >= 0){
            counter++;
            sum = sum + input;
            printf("\ndo you want to input another number, press y for yes\n");
            scanf(" %c", &yesORno);
                if(yesORno == 'y'){
                    averageOrNegative(sum, counter);//this prompts for another number by calling the function again
                }else{
                    result = sum/counter;//this averages the numbers together and returns the result
                }
        }else{
            result = input;//if the number was negative, it becomes the return value
        }
    printf("\n%d", sum);
    printf("    %d", counter);
    printf("\nthis is being run\n");//these 4 lines are only here to test
    printf("\n%f", result);
    return result;
}
</code>```

答:
Your function runs repeatedly because it is recursive (it calls itself) and all those printf are being executed every time the function is called.
If you want to print only the end result, do it in main like this:
printf("%f\n", number);

I'm not sure what are you trying to do here, but if what you want is to print the partial average every time you introduce a number, then you should do the printing before calling the function recursively. Otherwise you will get all the printing when you finish entering numbers.

My last advice to you is that you should mind about structure and organization in your code. It seems messy.

Body:
I'm writing a program that is supposed to average integers together, and also check if a number is negative when it is input. Everything seems to work, until it's time to return a value, then it appears to run my function repeatedly and I have no idea why. I would google my issue, but I don't even know what to look up.

#include <stdio.h>
double averageOrNegative(int sum, int counter);
int main(){
    int  sum = 0, counter = 0;
    double number = averageOrNegative(sum,counter);
    return 0;
}
double averageOrNegative(int sum, int counter){//the sum and counter are declared outside the function so they don't get reset when I call it again
    int input = 0;
    double result = 0;
    char yesORno = ' ';
    printf("\nPlease input a number \n");
    scanf("%d", &input);
        if(input >= 0){
            counter++;
            sum = sum + input;
            printf("\ndo you want to input another number, press y for yes\n");
            scanf(" %c", &yesORno);
                if(yesORno == 'y'){
                    averageOrNegative(sum, counter);//this prompts for another number by calling the function again
                }else{
                    result = sum/counter;//this averages the numbers together and returns the result
                }
        }else{
            result = input;//if the number was negative, it becomes the return value
        }
    printf("\n%d", sum);
    printf("    %d", counter);
    printf("\nthis is being run\n");//these 4 lines are only here to test
    printf("\n%f", result);
    return result;
}


问:
Installation app blocked by play protect - How can i know where is the problem?
Installation app blocked by play protect. How can i know where is the problem? I don't know why i didn't stealing user data or something like that</p>

答: You must have downloaded that app from other sources like some websites. They aren't verified as safe, so play protect blocks them.</p>


问:
For XSS protection, do I need to escape before populating for edit
I have an infected text that I'm testing with.

In display mode, I get the data from the database and display it on the page, and I get the XSS as expected.

In edit mode, I use the same form I used for initial entry and I populate the value from the database into the input fields (textarea in this case), but I'm not getting the XSS. Is this normal? Are form fields data not susceptible to XSS because the text is being displayed inside the form field? so no need for the XSS protection I use in normal display?

By the way, the specific XSS I'm testing with is this. I got it from the cheat sheet for XSS on hackers, the fisrt one.

```<code>';alert(String.fromCharCode(88,83,83))//";alert(String.fromCharCode(88,83,83))//\";alert(String.fromCharCode(88,83,83))//--></SCRIPT>">'><SCRIPT>alert(String.fromCharCode(88,83,83))</SCRIPT>
</code>```

答:
An example.</p>

```<code></TEXTAREA><SCRIPT>alert(String.fromCharCode(88,83,83))</SCRIPT>
</code>```

Body:
I have an infected text that I'm testing with.

In display mode, I get the data from the database and display it on the page, and I get the XSS as expected.

In edit mode, I use the same form I used for initial entry and I populate the value from the database into the input fields (textarea in this case), but I'm not getting the XSS. Is this normal? Are form fields data not susceptible to XSS because the text is being displayed inside the form field? so no need for the XSS protection I use in normal display?

By the way, the specific XSS I'm testing with is this. I got it from the cheat sheet for XSS on hackers, the fisrt one.

';alert(String.fromCharCode(88,83,83))//";alert(String.fromCharCode(88,83,83))//\";alert(String.fromCharCode(88,83,83))//--></SCRIPT>">'>

Body:
An example.

</TEXTAREA><SCRIPT>alert(String.fromCharCode(88,83,83))</SCRIPT>


问:
Installation did not succeed. The application could not be installed. Installation failed due to: 'device offline'
In android studio 3.6.3

This error indicates when I click on the Run button to install the program on the emulator.

Installation did not succeed. The application could not be installed.
  Installation failed due to: 'device offline'

答:
After a lot of searching, I found out that the adb had a problem and the emulator was turned off incorrectly.
I entered these commands in the cmd and the above error was fixed.

```<code>adb kill-server

adb start-server

adb connect [192.168.162.101]:5555

adb devices
List of devices attached [192.168.162.101]:5555  device
</code>```

NOTE

This IP is 192.168.162.101, which has an emulator itself. If you want to run the emulator manually, you must get your emulator IP and replace it with 192.168.162.101, otherwise it should automatically follow. Implement the first two commands of the emulator on the adb

Body:
After a lot of searching, I found out that the adb had a problem and the emulator was turned off incorrectly.
I entered these commands in the cmd and the above error was fixed.

adb kill-server

adb start-server

adb connect [192.168.162.101]:5555

adb devices
List of devices attached [192.168.162.101]:5555  device

NOTE

This IP is 192.168.162.101, which has an emulator itself. If you want to run the emulator manually, you must get your emulator IP and replace it with 192.168.162.101, otherwise it should automatically follow. Implement the first two commands of the emulator on the adb


问:
PgAdmin4 unable to query or view data
I have a very basic PostgreSql table. Despite the simple table schema, I cannot query it via PgAdmin4.

The View Data option is unresponsive; Query Tool option becomes unresponsive after a few attempts in opening and closing the panel. When the Query Tool is eventually (somehow) launched, a trivial SQL statement like

SELECT * FROM test_table

will spin forever and never display.

The diagram above shows the exact same table, which is okay under PgAdmin3.

The table was created empty. Then added with a row. But it threw errors about not having a Primary Key. Which also threw errors when I tried to set a Primary Key. So I used TeamPostgreSql to set a Primary Key. So all is good under PgAdmin3 now. Hence I'm really curious about what's going on with PgAdmin4?

答:
You can remove pgadmin4, then reinstall it. It worked for me. I used Ubuntu 18.04.
Here is my command on terminal:

sudo apt autoremove pgadmin4

sudo apt install pgadmin4 pgadmin4-apache2 -y

Title: PgAdmin4 unable to query or view data


问:
Migrate Cloud Firestore project to another Cloud Firestore project
I need to change my Project Id because the firebase auth link to verify is showing the project id on the link, and the name of the project has changed due to a rebrand. Based on the info i have found, it seems unlikely possible to change the Project Id. I was thinking of migrating all the data from the old database to the new one with the new Project Id. Is there a way to do that?</p>

答:
Firebase has a documentation page dedicated to moving Firestore data from one project to another:

Move data between projects | Firebase

To move your authentication user accounts, you can use this method:

Transfer registered users from one firebase app to another – StackOverflow.

If you're using cloud functions and have environment configurations, you can transfer them by running the following command:

```<code>firebase functions:config:clone --from OLD_PROJECT_ID --project NEW_PROJECT_ID
</code>```

Then you can deploy your cloud functions to the new project by changing your project in your .firebaserc to your new project ID and then running:

```<code>firebase deploy --only functions
</code>```

Body:
Firebase has a documentation page dedicated to moving Firestore data from one project to another:

Move data between projects | Firebase

To move your authentication user accounts, you can use this method:

Transfer registered users from one firebase app to another – StackOverflow.

If you're using cloud functions and have environment configurations, you can transfer them by running the following command:

firebase functions:config:clone --from OLD_PROJECT_ID --project NEW_PROJECT_ID

Then you can deploy your cloud functions to the new project by changing your project in your .firebaserc to your new project ID and then running:

firebase deploy --only functions


答:
I've found the better solution. If you want to conquer this problem follow these steps below:

Open Play store
Go to menu then click Play protect.
Uncheck Scan device for security threats.

May this will help you

Title: Installation app blocked by play protect - How can i know where is the problem?

Body: Installation app blocked by play protect. How can i know where is the problem? I don't know why i didn't stealing user data or something like that


问:
Js style password working or password not working
I have this js styling but it seems to not work. I don't know what is wrong

```<code>
            <div id="SignUp-Password">
              <div id="SignUp-LG-Password">Password:</div>
              <input
                size="42"
                        type="Password"
                maxlength="42"
                        name="SignUp-Input-Password"
                        id="SignUp-Input-Password">
              <input    id="SignUp-CheckBox-Password"
                                    type="checkbox"
                                    name="SignUp-CheckBox-Password">
              <div id="SignUp-Password-Show">Show</div>
              <span id="SignUp-Password-Match/Notmatch"/>
            </div>

            <div id="SignUp-Password-Repeat">
                <div id="SignUp-LG-Password-Repeat">Password Repeat:</div>
              <input
                size="42"
                        type="text"
                maxlength="42"
                        name="SignUp-Input-Password-Repeat"
                        id="SignUp-Input-Password-Repeat">
                    <div id="SignUp-Password-Strong"></div>
              <div class="registrationFormAlert" id="divCheckPasswordMatch"></div>
            </div>
</code>```

java

```<code>
    function checkPasswordMatch() {
        var password = $("#SignUp-Input-Password").val();
        var confirmPassword = $("#SignUp-Input-Password-Repeat").val();

        if (password != confirmPassword)
            $("#divCheckPasswordMatch").html("Passwords do not match!").style.color = "red";
        else
            $("#divCheckPasswordMatch").html("Passwords match.").style.color = "green";
    }

    $(document).ready(function () {
       $("#SignUp-Input-Password-Repeat").keyup(checkPasswordMatch);
    });
</code>```

I would think this is easy for you but I need some help with javascript.
you can also see this http://jsfiddle.net/fLqujmp3/

答:
Your syntaxt to set style incorrect, change to

```<code>$("#divCheckPasswordMatch").css("color","red");
</code>```

If you want to use javascript, change it to

```<code>document.getElementById("divCheckPasswordMatch").style.color = "red";
</code>```

function checkPasswordMatch() {
        var password = $("#SignUp-Input-Password").val();
        var confirmPassword = $("#SignUp-Input-Password-Repeat").val();

        if (password != confirmPassword){
            $("#divCheckPasswordMatch").html("Passwords do not match!");
            document.getElementById("divCheckPasswordMatch").style.color = "red";
            //$("#divCheckPasswordMatch").css("color","red");
            }
        else{
            $("#divCheckPasswordMatch").html("Passwords match.")
             $("#divCheckPasswordMatch").css("color","green");
             }
    }

    $(document).ready(function () {
       $("#SignUp-Input-Password-Repeat").keyup(checkPasswordMatch);
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="SignUp-Password">
              <div id="SignUp-LG-Password">Password:</div>
              <input
                size="42"
                        type="Password"
                maxlength="42"
                        name="SignUp-Input-Password"
                        id="SignUp-Input-Password">
              <input    id="SignUp-CheckBox-Password"
                                    type="checkbox"
                                    name="SignUp-CheckBox-Password">
              <div id="SignUp-Password-Show">Show</div>
              <span id="SignUp-Password-Match/Notmatch"/>
            </div>

            <div id="SignUp-Password-Repeat">
                <div id="SignUp-LG-Password-Repeat">Password Repeat:</div>
              <input
                size="42"
                        type="text"
                maxlength="42"
                        name="SignUp-Input-Password-Repeat"
                        id="SignUp-Input-Password-Repeat">
                    <div id="SignUp-Password-Strong"></div>
              <div class="registrationFormAlert" id="divCheckPasswordMatch"></div>
            </div></code>```

Body:
I have this js styling but it seems to not work. I don't know what is wrong

Password:

              <input
                size="42"
                        type="Password"
                maxlength="42"
                        name="SignUp-Input-Password"
                        id="SignUp-Input-Password">
              <input    id="SignUp-CheckBox-Password"
                                    type="checkbox"
                                    name="SignUp-CheckBox-Password">

Show

Password Repeat:

              <input
                size="42"
                        type="text"
                maxlength="42"
                        name="SignUp-Input-Password-Repeat"
                        id="SignUp-Input-Password-Repeat">

java

    function checkPasswordMatch() {
        var password = $("#SignUp-Input-Password").val();
        var confirmPassword = $("#SignUp-Input-Password-Repeat").val();

        if (password != confirmPassword)
            $("#divCheckPasswordMatch").html("Passwords do not match!").style.color = "red";
        else
            $("#divCheckPasswordMatch").html("Passwords match.").style.color = "green";
    }

    $(document).ready(function () {
       $("#SignUp-Input-Password-Repeat").keyup(checkPasswordMatch);
    });

I would think this is easy for you but I need some help with javascript.
you can also see this http://jsfiddle.net/fLqujmp3/

Body:
Your syntaxt to set style incorrect, change to

$("#divCheckPasswordMatch").css("color","red");

If you want to use javascript, change it to

document.getElementById("divCheckPasswordMatch").style.color = "red";

function checkPasswordMatch() {
        var password = $("#SignUp-Input-Password").val();
        var confirmPassword = $("#SignUp-Input-Password-Repeat").val();

        if (password != confirmPassword){
            $("#divCheckPasswordMatch").html("Passwords do not match!");
            document.getElementById("divCheckPasswordMatch").style.color = "red";
            //$("#divCheckPasswordMatch").css("color","red");
            }
        else{
            $("#divCheckPasswordMatch").html("Passwords match.")
             $("#divCheckPasswordMatch").css("color","green");
             }
    }

    $(document).ready(function () {
       $("#SignUp-Input-Password-Repeat").keyup(checkPasswordMatch);
    });

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="SignUp-Password">
              <div id="SignUp-LG-Password">Password:</div>
              <input
                size="42"
                        type="Password"
                maxlength="42"
                        name="SignUp-Input-Password"
                        id="SignUp-Input-Password">
              <input    id="SignUp-CheckBox-Password"
                                    type="checkbox"
                                    name="SignUp-CheckBox-Password">
              <div id="SignUp-Password-Show">Show</div>
              <span id="SignUp-Password-Match/Notmatch"/>
            </div>

            <div id="SignUp-Password-Repeat">
                <div id="SignUp-LG-Password-Repeat">Password Repeat:</div>
              <input
                size="42"
                        type="text"
                maxlength="42"
                        name="SignUp-Input-Password-Repeat"
                        id="SignUp-Input-Password-Repeat">
                    <div id="SignUp-Password-Strong"></div>
              <div class="registrationFormAlert" id="divCheckPasswordMatch"></div>
            </div>


问:
How to exclude comma(,) in the output
How to exclude "," from the below output while printing.

```<code>[root@test ~]# echo "list joblog job=host1"|bconsole| awk -F"|" '/host1/ {print $3,$6,$8}'

 host1   I          417,680,874
 host1   I       18,466,159,904
 host1   I        8,040,571,252
[root@test ~]#
</code>```

Since "," is not a field separator in my requirement, not able to find the possible way to print the output like below:

Expected output -:

```<code> host1   I          417680874
 host1   I       18466159904
 host1   I        8040571252
</code>```

Request you to provide an help here.

答:
With GNU awk replace

```<code>print $3,$6,$8
</code>```

with

```<code>gsub(",","",$8); print $3,$6,$8
</code>```

to replace all , in $8 with nothing.

Title: How to exclude comma(,) in the output

Body:
How to exclude "," from the below output while printing.

[root@test ~]# echo "list joblog job=host1"|bconsole| awk -F"|" '/host1/ {print $3,$6,$8}'

 host1   I          417,680,874
 host1   I       18,466,159,904
 host1   I        8,040,571,252
[root@test ~]#

Since "," is not a field separator in my requirement, not able to find the possible way to print the output like below:

Expected output -:

 host1   I          417680874
 host1   I       18466159904
 host1   I        8040571252

Request you to provide an help here.

Body:
With GNU awk replace

print $3,$6,$8

with

gsub(",","",$8); print $3,$6,$8

to replace all , in $8 with nothing.


问:
How to fix "This relative module was not found: * ./src/main.js in multi..." error when trying to npm run serve
When trying to run the application with npm run serve (on iOS), I am getting the following error:

This relative module was not found:

./src/main.js in multi (webpack)-dev-server/client?http://10.0.0.5:8081/sockjs-node ./node_modules/@vue/cli-service/node_modules/webpack/hot/dev-server.js ./src/main.js

Please bear with me, I am new to this.

I have tried a bunch of random stuff like checking for misspelling issues, reinstalling webpack, updating node, and nothing. I have no clue of what this error is about so I am not sure where to look at.

The main.js file looks like this:

```<code>import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store/store'
import './registerServiceWorker'
import * as VueGoogleMaps from "vue2-google-maps"
import VeeValidate from 'vee-validate'
import BootstrapVue from 'bootstrap-vue'

Vue.use(VueGoogleMaps, {
    load: {
        key: "AIzaSyCGiy39IZbj8oxvO4HHqSVjP5RmLSHl7mY",
        libraries: "places" // necessary for places input
    }
});

Vue.use(VeeValidate);
Vue.use(BootstrapVue);

Vue.config.productionTip = false;

new Vue({
    router,
    store,
    beforeCreate() {
        this.$store.commit('initialiseStore');
        this.$store.dispatch('commons/initialize');
    },
    render: h => h(App)
}).$mount('#app')
</code>```

I expect the live web server to display, but I am getting this compilation error and it is failing.

答:
I faced a similar issue after and spent hours searching.

The issue occurred in my project when I tried to install vuetify using command vue add vuetify. Apparently, the in automatically changes the app entry property in webpack.config automatically.

You can either change the filename itself to main.js or change the webpack config through vue.config.js (by reading the vue cli documentation regararding webpack config).

You can check your webpack.config by using the command vue inspect.

 ],
 entry: {
   app: [
    './src/main.js'
   ]
 }
}
```

Body:
When trying to run the application with npm run serve (on iOS), I am getting the following error:

This relative module was not found:

./src/main.js in multi (webpack)-dev-server/client?http://10.0.0.5:8081/sockjs-node ./node_modules/@vue/cli-service/node_modules/webpack/hot/dev-server.js ./src/main.js

Please bear with me, I am new to this.

I have tried a bunch of random stuff like checking for misspelling issues, reinstalling webpack, updating node, and nothing. I have no clue of what this error is about so I am not sure where to look at.

The main.js file looks like this:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store/store'
import './registerServiceWorker'
import * as VueGoogleMaps from "vue2-google-maps"
import VeeValidate from 'vee-validate'
import BootstrapVue from 'bootstrap-vue'

Vue.use(VueGoogleMaps, {
    load: {
        key: "AIzaSyCGiy39IZbj8oxvO4HHqSVjP5RmLSHl7mY",
        libraries: "places" // necessary for places input
    }
});

Vue.use(VeeValidate);
Vue.use(BootstrapVue);

Vue.config.productionTip = false;

new Vue({
    router,
    store,
    beforeCreate() {
        this.$store.commit('initialiseStore');
        this.$store.dispatch('commons/initialize');
    },
    render: h => h(App)
}).$mount('#app')

I expect the live web server to display, but I am getting this compilation error and it is failing.


问:
How to make it so that data doesn't get lost when refreshed in javascript?
I am making a to do list, and to do items are being lost (as expected) when page is refreshed. How do I stop it from clearing the items when the page is refreshed???????

Html:

```<code>        <div class="row">
                <input id="userInput" type="text" placeholder="New item..." maxlength="190"autofocus>
                <button id="enter">Add</button>
        </div>

        <div class="row" id="items">
            <div class="listItems col-12">
                <ul class="col-12 offset-0 col-sm-8 offset-sm-2">
                </ul>
            </div>
        </div>
    </div>
</code>```

JS:

```<code>    function createListElement() {
        var li = document.createElement("li");
        li.appendChild(document.createTextNode(input.value));
        ul.appendChild(li);
        function crossOut() {
            li.classList.toggle("done");
        }
        li.addEventListener("click",crossOut);

        var dBtn = document.createElement("button");
        dBtn.appendChild(document.createTextNode("X"));
        li.appendChild(dBtn);
        dBtn.addEventListener("click", deleteListItem);

        function deleteListItem(){
            li.classList.add("delete");
        }
}

    //enter works
    function addListAfterKeypress(event) {
        if (inputLength() > 0 && event.which ===13) {
            createListElement();
        }
    }

    input.addEventListener("keypress", addListAfterKeypress);
</code>```

答:
You can't get your tasks if you refreshed the page without storing them somewhere,

so I recommend you to use local storage as a starting for you

the whole idea here is when you press enter to submit a task you need to make an array to push each task and at the same time update your local storage with that array

and then you need to make an event listener ('DOMContentLoaded') so if you refresh your page then you retrieve tasks from local storage and append them to dom

I hope this answer clarify your issue

// select elements
const input = document.getElementById('userInput');
const ul = document.querySelector('ul');

function createListElement() {
    var li = document.createElement("li");
    li.appendChild(document.createTextNode(input.value));
    ul.appendChild(li);

    // update array with storage
    let arr = getTasks();
    // push li text to array
    arr.push(li.textContent);
    // update localStorage
    localStorage.setItem('tasks', JSON.stringify(arr));

    function crossOut() {
        li.classList.toggle("done");
    }
    li.addEventListener("click", crossOut);

    var dBtn = document.createElement("button");
    dBtn.appendChild(document.createTextNode("X"));
    li.appendChild(dBtn);
    dBtn.addEventListener("click", deleteListItem);

    function deleteListItem() {
        li.classList.add("delete");
    }
}

//enter works
function addListAfterKeypress(event) {
    if (input.value.length > 0 && event.which === 13) {
        createListElement();
        // wipe out input
        input.value = '';
    }
}

input.addEventListener("keypress", addListAfterKeypress);

// check localStorage
function getTasks() {
    let tasks;
    if (localStorage.getItem('tasks') === null) {
        tasks = [];
    } else {
        tasks = JSON.parse(localStorage.getItem('tasks'));
    }
    return tasks;
}

// on dom loading append tasks
window.addEventListener('DOMContentLoaded', () => {
    // get tasks from storage
    let arr = getTasks();

    // loop through tasks
    let foo = '';
    arr.forEach(item => {
        foo += `

${item}<button>X</button>

                    `;
    });

    // append tasks to dom
    ul.innerHTML = foo;

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div class="row">
        <input id="userInput" type="text" placeholder="New item..." maxlength="190" autofocus>
        <button id="enter">Add</button>
    </div>

    <div class="row" id="items">
        <div class="listItems col-12">
            <ul class="col-12 offset-0 col-sm-8 offset-sm-2">
            </ul>
        </div>
    </div>
    </div></code>```

Body:
I am making a to do list, and to do items are being lost (as expected) when page is refreshed. How do I stop it from clearing the items when the page is refreshed???????

Html:

                <input id="userInput" type="text" placeholder="New item..." maxlength="190"autofocus>
                <button id="enter">Add</button>

JS:

    function createListElement() {
        var li = document.createElement("li");
        li.appendChild(document.createTextNode(input.value));
        ul.appendChild(li);
        function crossOut() {
            li.classList.toggle("done");
        }
        li.addEventListener("click",crossOut);

        var dBtn = document.createElement("button");
        dBtn.appendChild(document.createTextNode("X"));
        li.appendChild(dBtn);
        dBtn.addEventListener("click", deleteListItem);

        function deleteListItem(){
            li.classList.add("delete");
        }
}

    //enter works
    function addListAfterKeypress(event) {
        if (inputLength() > 0 && event.which ===13) {
            createListElement();
        }
    }

    input.addEventListener("keypress", addListAfterKeypress);

Body:
You can't get your tasks if you refreshed the page without storing them somewhere,

so I recommend you to use local storage as a starting for you

the whole idea here is when you press enter to submit a task you need to make an array to push each task and at the same time update your local storage with that array

and then you need to make an event listener ('DOMContentLoaded') so if you refresh your page then you retrieve tasks from local storage and append them to dom

I hope this answer clarify your issue

// select elements
const input = document.getElementById('userInput');
const ul = document.querySelector('ul');

function createListElement() {
    var li = document.createElement("li");
    li.appendChild(document.createTextNode(input.value));
    ul.appendChild(li);

    // update array with storage
    let arr = getTasks();
    // push li text to array
    arr.push(li.textContent);
    // update localStorage
    localStorage.setItem('tasks', JSON.stringify(arr));

    function crossOut() {
        li.classList.toggle("done");
    }
    li.addEventListener("click", crossOut);

    var dBtn = document.createElement("button");
    dBtn.appendChild(document.createTextNode("X"));
    li.appendChild(dBtn);
    dBtn.addEventListener("click", deleteListItem);

    function deleteListItem() {
        li.classList.add("delete");
    }
}

//enter works
function addListAfterKeypress(event) {
    if (input.value.length > 0 && event.which === 13) {
        createListElement();
        // wipe out input
        input.value = '';
    }
}

input.addEventListener("keypress", addListAfterKeypress);

// check localStorage
function getTasks() {
    let tasks;
    if (localStorage.getItem('tasks') === null) {
        tasks = [];
    } else {
        tasks = JSON.parse(localStorage.getItem('tasks'));
    }
    return tasks;
}

// on dom loading append tasks
window.addEventListener('DOMContentLoaded', () => {
    // get tasks from storage
    let arr = getTasks();

    // loop through tasks
    let foo = '';
    arr.forEach(item => {
        foo += `
                    <li>${item}<button>X</button></li>
                    `;
    });

    // append tasks to dom
    ul.innerHTML = foo;

});

    <div class="row">
        <input id="userInput" type="text" placeholder="New item..." maxlength="190" autofocus>
        <button id="enter">Add</button>
    </div>

    <div class="row" id="items">
        <div class="listItems col-12">
            <ul class="col-12 offset-0 col-sm-8 offset-sm-2">
            </ul>
        </div>
    </div>
    </div>


问:
Angular routing not working when deployed statically with Node
I am building my angular project and inserting the build output into a public folder in the root of my node project.

In my app.js file, I have the following code:

```<code>...
app.use(express.static(path.join(__dirname, 'public')));
...
app.get('*', (req, res) => {
     res.send(path.join(__dirname, 'public/index.html'));
});
</code>```

When deploying the project, this works perfectly; when I load the page, the index.html is rendered and navigating through the page works.

However, when I enter a url like for example '/admin', which is defined in my angular routing, I get a not found error.

How can this be solved?

答:
Hope this will solve ur issue
Create .htaccess file in root folder and pass</p>

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]

RewriteRule ^(.*) /index.html [NC,L]
</code>```

Body:
I am building my angular project and inserting the build output into a public folder in the root of my node project.

In my app.js file, I have the following code:

...
app.use(express.static(path.join(__dirname, 'public')));
...
app.get('*', (req, res) => {
     res.send(path.join(__dirname, 'public/index.html'));
});

When deploying the project, this works perfectly; when I load the page, the index.html is rendered and navigating through the page works.

However, when I enter a url like for example '/admin', which is defined in my angular routing, I get a not found error.

How can this be solved?

Body:
Hope this will solve ur issue
Create .htaccess file in root folder and pass

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]

RewriteRule ^(.*) /index.html [NC,L]


问:
Perl Regex: Need help on a way to split string into groups matching a pattern
I need to split this string to an array:

```<code>$string = "9583526578','9583636523','9673522574','9183556528','9983023378";
</code>```

Here's how I want my array to look like after splitting:

```<code>@foo = [
           [9583526578, 9583636523],
           [9673522574, 9183556528],
           [9983023378]
       ]
</code>```

As you might have noticed, I need to split this string into groups of n (2 in this example) but still consider remainder if it doesn't match with n.

How can this be done in Perl?

I've done my research and experimentations but can't seem to get it right after a couple of hours.

Thanks for your time! :)

答: I would recommend using regex to retrieve the numbers using '([0-9]+)' and just manually building @foo.  Or as @MRAB suggested, split is even more straight-forward.  Any reason you are aiming at Regex for this?</p>

Body:
I need to split this string to an array:

$string = "9583526578','9583636523','9673522574','9183556528','9983023378";

Here's how I want my array to look like after splitting:

@foo = [
           [9583526578, 9583636523],
           [9673522574, 9183556528],
           [9983023378]
       ]

As you might have noticed, I need to split this string into groups of n (2 in this example) but still consider remainder if it doesn't match with n.

How can this be done in Perl?

I've done my research and experimentations but can't seem to get it right after a couple of hours.

Thanks for your time! :)


问:
How to specify a particular conda environment to run pytest code against?
I have created some tests in Tests.py using py.test framework.

And I am using the following bash command to run in terminal:

py.test --junitxml result_Tests.xml Tests.py

But in this case py.test is picking the default python installation.

How do I specify a conda environment name to py.test so that it runs on that specific conda environment?

I could not find any specific py.test switches in their docs.

答:
This is pretty obvious and probably not what you're looking for, but - assuming 'python' is the conda environment's -  using

```<code>python -m pytest
</code>```

seems to work.

Body:
This is pretty obvious and probably not what you're looking for, but - assuming 'python' is the conda environment's -  using

python -m pytest

seems to work.