问:
select elements of a dataframe according to the category of a row or column in R
For each of the 4 genes(each gene is on column), i need to test whether its mean expression is equal for patients with stable and progressive disease and store the corresponding p-value. Someone can help me please ? the language is in R.
Here picture of my dataframe:

答:
Suppose this is your data frame:

```<code>df = data.frame(y=sample(c("progres.","stable"),100,replace=TRUE),matrix(rnorm(100*4),ncol=4))
colnames(df)[-1] = c("X1000_at","X1001_at","X1002_at","X1003_at")
</code>```

If you just need the p.value, you can do:

```<code>apply(df[,-1],2,function(i)t.test(i ~ df$y)[["p.value"]])
  X1000_at   X1001_at   X1002_at   X1003_at
0.14861795 0.11653459 0.01820033 0.41873270
</code>```

In the above, you iterate through the gene columns, t.test between groups demarcated by the y column and capture only the p value.

Body:
Suppose this is your data frame:

df = data.frame(y=sample(c("progres.","stable"),100,replace=TRUE),matrix(rnorm(100*4),ncol=4))
colnames(df)[-1] = c("X1000_at","X1001_at","X1002_at","X1003_at")

If you just need the p.value, you can do:

apply(df[,-1],2,function(i)t.test(i ~ df$y)[["p.value"]])
  X1000_at   X1001_at   X1002_at   X1003_at
0.14861795 0.11653459 0.01820033 0.41873270

In the above, you iterate through the gene columns, t.test between groups demarcated by the y column and capture only the p value.


来源: stackexchange

问:
Unable to delete git remote branch with a special character
Please, before mark this question as duplicated, read carefully.

If you list branches, it appears like this:

```<code>$git branch -a
  remotes/origin/feat/verify-<C3>email
</code>```

The branch name is:

```<code>origin/feat/verify-√email
</code>```

If you try to access the branch url from Github Dashboard:

```<code>The github page broke into a HTTP error 400
</code>```

If you try to delete the branch:

```<code>$ git push origin --delete feat/verify-√email
error: unable to delete 'feat/verify-√email': remote ref does not exist
error: failed to push some refs to 'https://mataide@github.com/mataide/proak-website.git'
</code>```

Delete by pattern:

```<code>git branch -d -r $(git branch --list origin/feat/ve* -r)
error: cannot lock ref 'refs/remotes/origin/feat/verify-?email': Unable to create '/Users/marcus/Documents/Workspace/proak-website/.git/refs/remotes/origin/feat/verify-?email.lock': Illegal byte sequence
error: Error deleting remote-tracking branch 'origin/feat/verify-?email'
</code>```

Same error if you try by the name: feat/verify-email.
Also doent work if you try to delete by tools like Sourcetree.

I just want to delete the branch, any help?

答:
The √ character that I cut and pasted from your posting is a Unicode character for square root: U+221A—see also https://en.wikipedia.org/wiki/Radical_symbol.  The one actually in the other Git appears to be a code-byte-C3 in some non-Unicode character set.  You'll need to get the other Git to remove that somehow.

The git push --delete is a good idea, but you have to send the exact byte sequence to that other Git.  It's not clear to me how to do that from whatever terminal session you're using.  If you're on MacOS, you could edit up a shell script file that has the right byte sequence: just run git branch -r > /tmp/script, open the file in a suitable editor (e.g., vim), delete all the irrelevant lines, and insert git push origin --delete in front of the remaining one with the bad name.  Then run the resulting script, e.g., sh /tmp/script.  With no human hands (or editor) touching the bytes on the line, the original byte code sequence should remain in place.

Using git branch -d -r will, even if it works, not really help, as the name will keep coming back as long as it exists in the other Git.  However, once you've gotten rid of the bad name on the other Git—which might require outside help, e.g., from the GitHub folks—a git fetch --prune may not be able to discard the remote-tracking name in your own repository either.  (Try it first though.)

Given that your OS won't let you create the lock file for that name, you'll need to manually remove the right entry, which will be a line in your .git/packed-refs file.  Use a text-file-only editor (not a rich-text editor) that can handle newline-terminated lines (not CRLF) and delete the line.

ContentLicense: CC BY-SA 4.0

Body:
Please, before mark this question as duplicated, read carefully.

If you list branches, it appears like this:

$git branch -a
  remotes/origin/feat/verify-<C3>email

The branch name is:

origin/feat/verify-√email

If you try to access the branch url from Github Dashboard:

The github page broke into a HTTP error 400

If you try to delete the branch:

$ git push origin --delete feat/verify-√email
error: unable to delete 'feat/verify-√email': remote ref does not exist
error: failed to push some refs to 'https://mataide@github.com/mataide/proak-website.git'

Delete by pattern:

git branch -d -r $(git branch --list origin/feat/ve* -r)
error: cannot lock ref 'refs/remotes/origin/feat/verify-?email': Unable to create '/Users/marcus/Documents/Workspace/proak-website/.git/refs/remotes/origin/feat/verify-?email.lock': Illegal byte sequence
error: Error deleting remote-tracking branch 'origin/feat/verify-?email'

Same error if you try by the name: feat/verify-email.
Also doent work if you try to delete by tools like Sourcetree.

I just want to delete the branch, any help?


问:
How to iterate over directories and subdirectories that contain images and save them as jpegs in Python
I am trying to write some Python code that will iterate over image files in several folders within a directory and if they have the .tif extension I need to open the file, convert it to RGB with a size of 2500 by 2500 and then save it as a jpeg.  The following code is not working.  What is the best way to do this in Python?  This keeps giving me an error that a file doesn't exist when I see the file in the folders:</p>

```<code>import os
from PIL import Image
for (dirname, dirs, files) in os.walk('S:/DAM/Test/Approved/'):
    for filename in files:
        if filename.endswith('.tif'):
           img = Image.open(filename).convert('RGB')
           imageResize = img.resize((2500, 2500))
           imageResize.save(filename.jpg)
</code>```

答:
You should provide the full path to open and save the images using the PIL library.

Assuming that you have a directory structure similar to:

```<code>.
└── scriptfolder
       -- your-script.py
       -- picture.tif
       imagefolder
           -- picture2.tif
           -- picture3.jpg
           imagefolder2
               --example.jpg
               --example2.tif
               --whatever.png
</code>```

The following script should work if you are using a Linux machine and the script is located on a top level directory relative to the images:

```<code># !/usr/bin/python3

from PIL import Image
import os

for root, dirs, files in os.walk(".", topdown = False):
   for name in files:
      if name.endswith('.tif'):
         filename = os.path.join(root, name)
         img = Image.open(filename).convert('RGB')
         imageResize = img.resize((2500,2500))
         imageResize.save(filename[:-4]+'.jpg','JPEG')
</code>```

EDIT

In a Windows Machine you can the following:

Install a clean version of Python 3 for Windows (e.g. https://www.python.org/downloads/release/python-376/)

Run the installer as an administrator and on the installation prompt make sure to mark adding the Python environment variable to the path and install pip.

Open a CMD as administrator and install the Pillow library with pip install Pillow

Open IDLE and create the following script: changing the ´path_to_images´ variable to the correct path where your images are stored.

```<code>from PIL import Image
import os

path_to_images = "D:\Images\Path-to-images"

for root, dirs, files in os.walk(path_to_images, topdown = False):
   for name in files:
      if name.endswith('.tif'):
         filename = os.path.join(root, name)
         print(filename)
         img = Image.open(filename).convert('RGB')
         imageResize = img.resize((2500,2500))
         imageResize.save(filename[:-4]+"toJPEG.jpg",'JPEG')

</code>```

Run the Module in IDLE with F5.

Body:
I am trying to write some Python code that will iterate over image files in several folders within a directory and if they have the .tif extension I need to open the file, convert it to RGB with a size of 2500 by 2500 and then save it as a jpeg.  The following code is not working.  What is the best way to do this in Python?  This keeps giving me an error that a file doesn't exist when I see the file in the folders:

import os
from PIL import Image
for (dirname, dirs, files) in os.walk('S:/DAM/Test/Approved/'):
    for filename in files:
        if filename.endswith('.tif'):
           img = Image.open(filename).convert('RGB')
           imageResize = img.resize((2500, 2500))
           imageResize.save(filename.jpg)

Body:
You should provide the full path to open and save the images using the PIL library.

Assuming that you have a directory structure similar to:

.
└── scriptfolder
       -- your-script.py
       -- picture.tif
       imagefolder
           -- picture2.tif
           -- picture3.jpg
           imagefolder2
               --example.jpg
               --example2.tif
               --whatever.png

The following script should work if you are using a Linux machine and the script is located on a top level directory relative to the images:

# !/usr/bin/python3

from PIL import Image
import os

for root, dirs, files in os.walk(".", topdown = False):
   for name in files:
      if name.endswith('.tif'):
         filename = os.path.join(root, name)
         img = Image.open(filename).convert('RGB')
         imageResize = img.resize((2500,2500))
         imageResize.save(filename[:-4]+'.jpg','JPEG')

EDIT

In a Windows Machine you can the following:

Install a clean version of Python 3 for Windows (e.g. https://www.python.org/downloads/release/python-376/)

Run the installer as an administrator and on the installation prompt make sure to mark adding the Python environment variable to the path and install pip.

Open a CMD as administrator and install the Pillow library with pip install Pillow

Open IDLE and create the following script: changing the ´path_to_images´ variable to the correct path where your images are stored.

from PIL import Image
import os

path_to_images = "D:\Images\Path-to-images"

for root, dirs, files in os.walk(path_to_images, topdown = False):
   for name in files:
      if name.endswith('.tif'):
         filename = os.path.join(root, name)
         print(filename)
         img = Image.open(filename).convert('RGB')
         imageResize = img.resize((2500,2500))
         imageResize.save(filename[:-4]+"toJPEG.jpg",'JPEG')

Run the Module in IDLE with F5.


问:
I need to find links that contain the same number and merge them all into the same cell
can someone help me speed up the process in excel. I need formula to find links that contain the same number and merge them all into the same cell. So far I've done it with the formula but it's a slow process for me when I have over 1000 links:
=TEXTJOIN( ", ";TRUE;B110:B114)

Thanks!

Textjoin

答:
I would use several columns.
Col B, extract the number from the strings with

```<code>=mid(A2,26,4)
</code>```

Column C formula

```<code>=If(B2=B1, "", D2)
</code>```

Column D

```<code>=IF(B2=B3, A2 & "," & D3, A2)
</code>```

Copy those all the way down and answers with be in C. Filter out the blanks if you want.

Body:
I would use several columns.
Col B, extract the number from the strings with

=mid(A2,26,4)

Column C formula

=If(B2=B1, "", D2)

Column D

=IF(B2=B3, A2 & "," & D3, A2)

Copy those all the way down and answers with be in C. Filter out the blanks if you want.


问:
How to calculate or manage streaming data in Pyspark
I wanna caculate data from streaming data and then sent to web page. For example: I will calculate sum of TotalSales column in streaming data. But it error at summary = dataStream.select('TotalSales').groupby().sum().toPandas() and this is my code.

```<code>import os
from pyspark.sql import SparkSession
from pyspark.sql.types import StructType
from pyspark.sql.functions import *

spark = SparkSession.builder.appName("Python Spark SQL basic example").config("spark.some.config.option", "some-value").getOrCreate()
schema = StructType().add("_c0", "integer").add("InvoiceNo", "string").add("Quantity","integer").add("InvoiceDate","date").add("UnitPrice","integer").add("CustomerID","double").add("TotalSales","integer")
INPUT_DIRECTORY = "C:/Users/HP/Desktop/test/jsonFile"
dataStream = spark.readStream.format("json").schema(schema).load(INPUT_DIRECTORY)
query = dataStream.writeStream.format("console").start()

summary = dataStream.select('TotalSales').groupby().sum().toPandas()
print(query.id)
query.awaitTermination();
</code>```

and this is error showed on command line.

```<code>Traceback (most recent call last):
  File "testStreaming.py", line 12, in <module>
    dataStream = dataStream.toPandas()
  File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\pyspark\sql\dataframe.py", line 2150, in toPandas
    pdf = pd.DataFrame.from_records(self.collect(), columns=self.columns)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\pyspark\sql\dataframe.py", line 534, in collect
    sock_info = self._jdf.collectToPython()
  File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\py4j\java_gateway.py", line 1257, in __call__
answer, self.gateway_client, self.target_id, self.name)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\pyspark\sql\utils.py", line 69, in deco
raise AnalysisException(s.split(': ', 1)[1], stackTrace)
pyspark.sql.utils.AnalysisException: 'Queries with streaming sources must be executed with writeStream.start();;\nFileSource[C:/Users/HP/Desktop/test/jsonFile]'
</code>```

Thank for your answering.

答:
why are you trying to create a a pandas Df

toPandas  will create a  DataFrame that is local to your driver node.  I am not sure what are you trying to achieve here .  Pandas DataFrame represents a fixed set of tuples, where as  structured stream  is a continuous stream  of data .

Now one possible sol to this problem is to complete the entire process that you  want to do and  send the output to a parquet/csv file  and use this parquet/csv etc  file to create a pandas DF .

```<code>summary = dataStream.select('TotalSales').groupby().sum()
query = dataStream.writeStream.format("parquet").outputMode("complete").start(outputPathDir)
query.awaitTermination()
</code>```

Body:
I wanna caculate data from streaming data and then sent to web page. For example: I will calculate sum of TotalSales column in streaming data. But it error at summary = dataStream.select('TotalSales').groupby().sum().toPandas() and this is my code.

import os
from pyspark.sql import SparkSession
from pyspark.sql.types import StructType
from pyspark.sql.functions import *

spark = SparkSession.builder.appName("Python Spark SQL basic example").config("spark.some.config.option", "some-value").getOrCreate()
schema = StructType().add("_c0", "integer").add("InvoiceNo", "string").add("Quantity","integer").add("InvoiceDate","date").add("UnitPrice","integer").add("CustomerID","double").add("TotalSales","integer")
INPUT_DIRECTORY = "C:/Users/HP/Desktop/test/jsonFile"
dataStream = spark.readStream.format("json").schema(schema).load(INPUT_DIRECTORY)
query = dataStream.writeStream.format("console").start()

summary = dataStream.select('TotalSales').groupby().sum().toPandas()
print(query.id)
query.awaitTermination();

and this is error showed on command line.

Traceback (most recent call last):
  File "testStreaming.py", line 12, in <module>
    dataStream = dataStream.toPandas()
  File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\pyspark\sql\dataframe.py", line 2150, in toPandas
    pdf = pd.DataFrame.from_records(self.collect(), columns=self.columns)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\pyspark\sql\dataframe.py", line 534, in collect
    sock_info = self._jdf.collectToPython()
  File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\py4j\java_gateway.py", line 1257, in __call__
answer, self.gateway_client, self.target_id, self.name)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\pyspark\sql\utils.py", line 69, in deco
raise AnalysisException(s.split(': ', 1)[1], stackTrace)
pyspark.sql.utils.AnalysisException: 'Queries with streaming sources must be executed with writeStream.start();;\nFileSource[C:/Users/HP/Desktop/test/jsonFile]'

Thank for your answering.

Body:
why are you trying to create a a pandas Df

toPandas  will create a  DataFrame that is local to your driver node.  I am not sure what are you trying to achieve here .  Pandas DataFrame represents a fixed set of tuples, where as  structured stream  is a continuous stream  of data .

Now one possible sol to this problem is to complete the entire process that you  want to do and  send the output to a parquet/csv file  and use this parquet/csv etc  file to create a pandas DF .

summary = dataStream.select('TotalSales').groupby().sum()
query = dataStream.writeStream.format("parquet").outputMode("complete").start(outputPathDir)
query.awaitTermination()


问:
How to unsecure /** URL pattern in spring-security
I'm trying to unsecure the /** pattern, but all my tries are in vain so far.

This is what I'm doing:

```<code><security:intercept-url pattern="/**" filters="none" />
</code>```

My configuration doesn't contain any more intercept-url definitions.

However after accessing any URL I still get redirected to the default entry point...

I debugged the spring security source and I can actually see the the filters being loaded for the URL I'm trying to access. (FilterChainProxy line: 154, the filters list is full)

Any insight into why this happens and how to unsecure /** would be very appreciated.

I'm using 3.0.5.RELEASE

EDIT:

Security configuration:

```<code> <security:http auto-config="false" use-expressions="true" entry-point-ref="loginUrlAuthenticationEntryPoint">
    <!-- dev --><security:intercept-url pattern="/**" filters="none" />

    <security:custom-filter position="FORM_LOGIN_FILTER" ref="absoluteUrlSsoFilter" />
</security:http>

<security:authentication-manager>
    <security:authentication-provider user-service-ref="ssoDetailsService" />
</security:authentication-manager>
</code>```

This is the relevant part, I could also give you the bean definitions, but I doubt the problem is there.

答:
at least in grails, you could set the security setting to IS_AUTHENTICATED_ANONYMOUSLY.  Since the grails spring security plugin is based on spring security, I bet this would work.

no need to play with filters or anything.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to unsecure the /** pattern, but all my tries are in vain so far.

This is what I'm doing:

<security:intercept-url pattern="/**" filters="none" />

My configuration doesn't contain any more intercept-url definitions.

However after accessing any URL I still get redirected to the default entry point...

I debugged the spring security source and I can actually see the the filters being loaded for the URL I'm trying to access. (FilterChainProxy line: 154, the filters list is full)

Any insight into why this happens and how to unsecure /** would be very appreciated.

I'm using 3.0.5.RELEASE

EDIT:

Security configuration:

 <security:http auto-config="false" use-expressions="true" entry-point-ref="loginUrlAuthenticationEntryPoint">
    <security:intercept-url pattern="/**" filters="none" />

    <security:custom-filter position="FORM_LOGIN_FILTER" ref="absoluteUrlSsoFilter" />
</security:http>

<security:authentication-manager>
    <security:authentication-provider user-service-ref="ssoDetailsService" />
</security:authentication-manager>

This is the relevant part, I could also give you the bean definitions, but I doubt the problem is there.


问:
Docusign - Authorization Code Grant - Redirect uri is not being performed when obtaining access token
The Problem: DocuSign seems to ignore the redirect_uri that's set in the HTTP header when obtaining an access token.

For context, I am using PHP and cURL. When I send the cURL request, the authorization succeeds because I do get the access token and refresh tokens. The only issue is that DocuSign does not perform a redirect after the authorization's success like it should.

Here's the PHP - cURL code taken from Postman that I'm also using in my code. I've shortened certain strings for conciseness. The redirect_uri param is in CURLOPT_POSTFIELDS:

```<code><?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://account-d.docusign.com/oauth/token",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "grant_type=authorization_code&code=eyJ0eXAiOiJ...UDa8uJ9A&redirect_uri=http%3A//localhost/docusign/getData.php",
  CURLOPT_HTTPHEADER => array(
    "Content-Type: application/x-www-form-urlencoded",
    "Authorization: Basic NTYxN...DkxMA==",
    "Cookie: __RequestVerificationToken=ARmOPr...tg0B0"
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;
?>
</code>```

I've closely followed this DocuSign doc regarding following the authorization code grant flow: https://developers.docusign.com/esign-rest-api/guides/authentication/oauth2-code-grant

Any help is greatly appreciated!

答:
The redirect URI is not used by the API in step 2 to redirect.
It is only used in step 1 to redirect the user to your URL after you logged in.
I'm not sure if the documentation suggested otherwise, we can fix it if it led to confusion. </p>

Body:
The Problem: DocuSign seems to ignore the redirect_uri that's set in the HTTP header when obtaining an access token.

For context, I am using PHP and cURL. When I send the cURL request, the authorization succeeds because I do get the access token and refresh tokens. The only issue is that DocuSign does not perform a redirect after the authorization's success like it should.

Here's the PHP - cURL code taken from Postman that I'm also using in my code. I've shortened certain strings for conciseness. The redirect_uri param is in CURLOPT_POSTFIELDS:

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://account-d.docusign.com/oauth/token",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "grant_type=authorization_code&code=eyJ0eXAiOiJ...UDa8uJ9A&redirect_uri=http%3A//localhost/docusign/getData.php",
  CURLOPT_HTTPHEADER => array(
    "Content-Type: application/x-www-form-urlencoded",
    "Authorization: Basic NTYxN...DkxMA==",
    "Cookie: __RequestVerificationToken=ARmOPr...tg0B0"
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;
?>

I've closely followed this DocuSign doc regarding following the authorization code grant flow: https://developers.docusign.com/esign-rest-api/guides/authentication/oauth2-code-grant

Any help is greatly appreciated!


问:
document.getElementById("app").innerHTML fails when using imports
First Js file (testtest.js):

```<code>let test = "<h1>hello</h1>";
module.exports = test;
</code>```

Second Js file:

```<code>const test = require('./testtest');
document.getElementById("app").innerHTML = "<h1>hello</h1>";
</code>```

When I try use document.getElementById("app").innerHTML when I am using import, it fails to show HTML but, if I comment the import line it works as expected.

Can you help what is problem solution?

答:
This looks like a combination of server side js and client js. Client side js doesn't use module.exports or require. Ofc you can use a bundler but based on the post I don't think you are.

file: testtest.js

let test = "
hello
";
export default test;
```

<p>second js file:</p>

```//this import must be top level
import test from "./testtest.js";
document.getElementById("app").innerHTML = test;
```

https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export

https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/import

Body:
First Js file (testtest.js):

let test = "
hello
";
module.exports = test;

Second Js file:

const test = require('./testtest');
document.getElementById("app").innerHTML = "
hello
";

When I try use document.getElementById("app").innerHTML when I am using import, it fails to show HTML but, if I comment the import line it works as expected.

Can you help what is problem solution?

Body:
This looks like a combination of server side js and client js. Client side js doesn't use module.exports or require. Ofc you can use a bundler but based on the post I don't think you are.

file: testtest.js

let test = "<h1>hello</h1>";
export default test;

second js file:

//this import must be top level
import test from "./testtest.js";
document.getElementById("app").innerHTML = test;

https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export

https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/import


问:
how to count the frequency of letters in text excluding whitespace and numbers?
Use a dictionary to count the frequency of letters in the input string. Only letters should be counted, not blank spaces, numbers, or punctuation. Upper case should be considered the same as lower case. For example, count_letters("This is a sentence.") should return {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}</p>

```<code>def count_letters(text):
      result = {}
      # Go through each letter in the text
      for letter in text:
        # Check if the letter needs to be counted or not
        if letter not in result:
          result[letter.lower()] = 1
        # Add or increment the value in the dictionary
        else:
          result[letter.lower()] += 1
      return result

    print(count_letters("AaBbCc"))
    # Should be {'a': 2, 'b': 2, 'c': 2}

    print(count_letters("Math is fun! 2+2=4"))
    # Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}

    print(count_letters("This is a sentence."))
    # Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}
</code>```

答:
```<code>def count_letters(text):
  result = {}
  # Go through each letter in the text
  for letter in text:
    # Check if the letter needs to be counted or not
    if letter.isalpha():
      if letter not in result:
        result[letter.lower()] = 1
      else:
        result[letter.lower()] +=1
    # Add or increment the value in the dictionary

  return result

print(count_letters("AaBbCc"))
# Should be {'a': 2, 'b': 2, 'c': 2}

print(count_letters("Math is fun! 2+2=4"))
# Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}
</code>```

Body:
Use a dictionary to count the frequency of letters in the input string. Only letters should be counted, not blank spaces, numbers, or punctuation. Upper case should be considered the same as lower case. For example, count_letters("This is a sentence.") should return {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}

def count_letters(text):
      result = {}
      # Go through each letter in the text
      for letter in text:
        # Check if the letter needs to be counted or not
        if letter not in result:
          result[letter.lower()] = 1
        # Add or increment the value in the dictionary
        else:
          result[letter.lower()] += 1
      return result

    print(count_letters("AaBbCc"))
    # Should be {'a': 2, 'b': 2, 'c': 2}

    print(count_letters("Math is fun! 2+2=4"))
    # Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}

    print(count_letters("This is a sentence."))
    # Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}


问:
Git ignore typechanges

TLDR

I want to be able to have two files change simultaneously in different projects.

Long version

I would like to use git to ONLY track content changes to my files, I do not care about so called typechange changes. Can I change my git configuration or edit my .gitignore file?

I have a file ~/proj/real_foo that has identical contents to the tracked ./foo but I want to be able to have both files change simultaneously in different projects.

Currently:

```<code>> ls
foo
> git status
On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean
> rm foo; ln -s ~/proj/real_foo ./foo
> git status
On branch master
Your branch is up to date with 'origin/master'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    typechange: foo

no changes added to commit (use "git add" and/or "git commit -a")
</code>```

Desired:

```<code>> ls
foo
> git status
On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean
> rm foo; ln -s ~/proj/real_foo ./foo
> git status
On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean
</code>```

答:
Git doesn't provide a way to ignore type changes.  This is a specific case of the more general case of ignoring changes to tracked files, to which the answer is, Git doesn't offer that as an option.  Trying to use one of the git update-index suggestions typically offered doesn't work, as the documentation states.

What you can do here is to ignore foo and provide some template for it that's copied over by your build system or a script if it doesn't exist.  Since a symlink exists, it will be preserved, while still making the code work on a fresh clone with a plain file.  You could also have your build system or script just symlink to the template file instead.

Title: Git ignore typechanges

Body:
TLDR

I want to be able to have two files change simultaneously in different projects.

Long version

I would like to use git to ONLY track content changes to my files, I do not care about so called typechange changes. Can I change my git configuration or edit my .gitignore file?

I have a file ~/proj/real_foo that has identical contents to the tracked ./foo but I want to be able to have both files change simultaneously in different projects.

Currently:

> ls
foo
> git status
On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean
> rm foo; ln -s ~/proj/real_foo ./foo
> git status
On branch master
Your branch is up to date with 'origin/master'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    typechange: foo

no changes added to commit (use "git add" and/or "git commit -a")

Desired:

> ls
foo
> git status
On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean
> rm foo; ln -s ~/proj/real_foo ./foo
> git status
On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean


问:
Using `RangeFull` syntax with strings and `Borrow`
I'm working on a pandas-like library for Rust, and one of the features I'd like to support is psuedo-slicing of indices (and series/frames later on) using the Rust range syntax (e.g. 0..=5, ..7, 4.., .., etc) using RangeBounds.

In addition, I'd like to support using references to the data contained in the index as bounds for the range, not just integers. So if an index has ["dog", "cat", "bird", "sheep"], I'd like to support a lookup of .loc_range(&"dog"..=&"bird") to return the 1st, 2nd, and 3rd items, for instance.

I've gotten to the point where primitive Copy types that I support as labels work perfectly, but I'm stuck on String. Not only does it feel weird to use "str" instead of &"str" (see code example below, comparing the char and the String usages, and probably worth a new SO question), but the naive .. call on the String version fails to compile at all! Instead, I have to specify the type parameters, as shown on the last line of code.

If this was an internal call, I'd just make the change and continue on. But I intend for this to be a user-facing function, and I'd hate to have users need to specify the type arguments for this edge case. Is there a way around this? More specifically, I'm looking to be able to not have to specify type vars for the TestIndex<String>::loc_range(..) case.

use std::fmt::Debug;
use std::hash::Hash;
use std::borrow::Borrow;
use std::ops::RangeBounds;

pub trait TestLabel: Debug + Clone + Sized + PartialEq +
                     Eq + Hash + PartialOrd + Ord {}

impl TestLabel for char {}
impl TestLabel for String {}

pub struct TestIndex<L: TestLabel>(Vec<L>);

impl<L: TestLabel> TestIndex<L> {
    pub fn loc_range<'a, R, Q: 'a>(&self, range: R) -> Option<Vec<usize>>
    where
        R: RangeBounds<&'a Q>,
        L: Borrow<Q>,
        Q: Hash + Eq + ?Sized,
    {
        // Actual code uses `IndexSet` and does a set lookup,
        // hence the use of `Borrow`.
        // This is just dummy code to get a minimum working example.
        None
    }

    pub fn test() {
        let i = TestIndex(vec!['a', 'b', 'c']);

        // OK!
        println!("{:?}", i.loc_range(&'a'..&'c'));
        println!("{:?}", i.loc_range(..&'c'));
        println!("{:?}", i.loc_range(&'a'..));
        println!("{:?}", i.loc_range(..));

        let i = TestIndex(vec![
            String::from("a"),
            String::from("b"),
            String::from("c"),
        ]);

        // Strange that no '&' is needed, but compiles
        println!("{:?}", i.loc_range("a".."c"));
        println!("{:?}", i.loc_range(.."c"));
        println!("{:?}", i.loc_range("a"..));

        // ERROR E0283
        // cannot resolve `std::string::String: std::borrow::Borrow<_>`
        println!("{:?}", i.loc_range(..));

        // Compiles, but feels very unergonomic!
        println!("{:?}", i.loc_range::<_, str>(..));
    }
}
```

NOTE: I posted this question on the Rust Discord, but also wanted to get some opinions and insights here on SO, especially since I can provide more context and background for the use case I have!

答:
I think you will need to make your own trait

Like so: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=f08dba83840f06bc69ffa203bf9838a4

(note: I didn't fill out all of the required implementations, you will need an implementation of LocRange<_> for each of the range types)
You can minimize the boiler-plate by going back through a function like

```<code>pub fn generic_loc_range_impl<'a, R, L, Q: 'a>(test_index: &TestIndex<L>, range: R) -> Option<Vec<usize>>
    where
        R: RangeBounds<&'a Q>,
        L: Borrow<Q> + TestLabel,
        Q: Hash + Eq + ?Sized,
{
    ...
}
</code>```

In each of the implementations, these implementations are just to remove the unnecessary type parameter for RangeFull which causes the inference failure.
In the RangeFull impl you can call it like generic_loc_range_impl::<RangeFull, L, L>(self, ..)

Body:
I'm working on a pandas-like library for Rust, and one of the features I'd like to support is psuedo-slicing of indices (and series/frames later on) using the Rust range syntax (e.g. 0..=5, ..7, 4.., .., etc) using RangeBounds.

In addition, I'd like to support using references to the data contained in the index as bounds for the range, not just integers. So if an index has ["dog", "cat", "bird", "sheep"], I'd like to support a lookup of .loc_range(&"dog"..=&"bird") to return the 1st, 2nd, and 3rd items, for instance.

I've gotten to the point where primitive Copy types that I support as labels work perfectly, but I'm stuck on String. Not only does it feel weird to use "str" instead of &"str" (see code example below, comparing the char and the String usages, and probably worth a new SO question), but the naive .. call on the String version fails to compile at all! Instead, I have to specify the type parameters, as shown on the last line of code.

If this was an internal call, I'd just make the change and continue on. But I intend for this to be a user-facing function, and I'd hate to have users need to specify the type arguments for this edge case. Is there a way around this? More specifically, I'm looking to be able to not have to specify type vars for the TestIndex<String>::loc_range(..) case.

use std::fmt::Debug;
use std::hash::Hash;
use std::borrow::Borrow;
use std::ops::RangeBounds;

pub trait TestLabel: Debug + Clone + Sized + PartialEq +
                     Eq + Hash + PartialOrd + Ord {}

impl TestLabel for char {}
impl TestLabel for String {}

pub struct TestIndex<L: TestLabel>(Vec<L>);

impl<L: TestLabel> TestIndex<L> {
    pub fn loc_range<'a, R, Q: 'a>(&self, range: R) -> Option<Vec<usize>>
    where
        R: RangeBounds<&'a Q>,
        L: Borrow<Q>,
        Q: Hash + Eq + ?Sized,
    {
        // Actual code uses `IndexSet` and does a set lookup,
        // hence the use of `Borrow`.
        // This is just dummy code to get a minimum working example.
        None
    }

    pub fn test() {
        let i = TestIndex(vec!['a', 'b', 'c']);

        // OK!
        println!("{:?}", i.loc_range(&'a'..&'c'));
        println!("{:?}", i.loc_range(..&'c'));
        println!("{:?}", i.loc_range(&'a'..));
        println!("{:?}", i.loc_range(..));

        let i = TestIndex(vec![
            String::from("a"),
            String::from("b"),
            String::from("c"),
        ]);

        // Strange that no '&' is needed, but compiles
        println!("{:?}", i.loc_range("a".."c"));
        println!("{:?}", i.loc_range(.."c"));
        println!("{:?}", i.loc_range("a"..));

        // ERROR E0283
        // cannot resolve `std::string::String: std::borrow::Borrow<_>`
        println!("{:?}", i.loc_range(..));

        // Compiles, but feels very unergonomic!
        println!("{:?}", i.loc_range::<_, str>(..));
    }
}

NOTE: I posted this question on the Rust Discord, but also wanted to get some opinions and insights here on SO, especially since I can provide more context and background for the use case I have!

Body:
I think you will need to make your own trait

Like so: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=f08dba83840f06bc69ffa203bf9838a4

(note: I didn't fill out all of the required implementations, you will need an implementation of LocRange<_> for each of the range types)
You can minimize the boiler-plate by going back through a function like

pub fn generic_loc_range_impl<'a, R, L, Q: 'a>(test_index: &TestIndex<L>, range: R) -> Option<Vec<usize>>
    where
        R: RangeBounds<&'a Q>,
        L: Borrow<Q> + TestLabel,
        Q: Hash + Eq + ?Sized,
{
    ...
}

In each of the implementations, these implementations are just to remove the unnecessary type parameter for RangeFull which causes the inference failure.
In the RangeFull impl you can call it like generic_loc_range_impl::<RangeFull, L, L>(self, ..)


问:
Parts of https://jenkins.io is down. How do I report it?
So https://www.jenkins.io/ has been down for at least most of the afternoon. The main page is accessible, but blog posts and plugins etc. aren't available. I get a 503 that looks like this:

I figured I'd try again later, but since it was still down I thought I'd better report it. So I went to their JIRA to report the issue at https://issues.jenkins-ci.org/, which seems to be up, but when trying to log in I get a 502 response, with the following error message:

I went to their GitHub, but they have issues disabled there. I'm running out of options, so I figured I'd ask here to see if there is someone that knows how to get in touch with someone that knows how to fix it. I found a few tweets about it, but no responses from anyone that seems to be able to do anything about it.

答:
After the issue was resolved and I was able to log in to JIRA, I found a way to report the issue and apparently a few people already did. If this happens again, you can go to https://github.com/jenkins-infra/jenkins.io/issues/ and report the issue there.

Another place to check is the jenkins-infra channel on freenode, as that's where they are discussing the issue during investigation.

In case you were curious, it seems like this outage was due to a problem with the Kubernetes cluster where it was hosted. I don't know any more details than that.

I hope this might help someone in the future.


问:
Error loading hostpolicy.dll while deploying .NET Core console app to Azure WebJobs
I have followed this tutorial to deploy a .NET Core console application to an Azure Web Service WebJob.

My app is running locally without any issue (with dotnet 1.0.0-preview2-003131) but when I try to run it from Azure console I have the following error :

Failed to load the dll from [D:\local\VirtualDirectory0\site\wwwroot\app_data\jobs\triggered\PopcornExportWebJob\hostpolicy.dll], HRESULT: 0x800700C1**

An error occurred while loading required library hostpolicy.dll from [D:\local\VirtualDirectory0\site\wwwroot\app_data\jobs\triggered\PopcornExportWebJob]

The version of Azure .Net is 1.0.0-rc4-004771  and the hostpolicy.dll file is the same than I use locally. In fact, when I download the zip of my deploy from Azure and when I run it locally, it is working fine. But it fails on Azure environment.

Also, here is my project.json:

```<code>{
      "publishOptions": {
        "include": [
          "run.cmd"
        ]
      },
      "buildOptions": {
        "emitEntryPoint": true,
        "copyToOutput": "appsettings.json"
      },
      "copyright": "bbougot",
      "dependencies": {
        "FubarCoder.RestSharp.Portable.Core": "4.0.7",
        "FubarCoder.RestSharp.Portable.HttpClient": "4.0.7",
        "Microsoft.ApplicationInsights.AspNetCore": "2.0.0",
        "Microsoft.Extensions.Configuration": "1.1.0",
        "Microsoft.Extensions.Configuration.Json": "1.1.0",
        "Microsoft.Extensions.DependencyInjection": "1.1.0",
        "Microsoft.Extensions.Logging": "1.1.0",
        "Microsoft.Extensions.Logging.Console": "1.1.0",
        "Microsoft.NETCore.App": "1.1.0",
        "MongoDB.Driver": "2.4.2",
        "StructureMap.Microsoft.DependencyInjection": "1.3.0"
      },
      "description": "Popcorn Api Exporter",
      "frameworks": {
        "netcoreapp1.1": {
          "imports": [
            "portable-net45+win8"
          ]
        }
      },
      "runtimes": {
        "win10-x64": {}
      },
      "scripts": {
        "postpublish": [ "7za.exe a -tzip PopcornExport.zip .\\bin\\Release\\PublishOutput\\*",
                         ".\\WAWSDeploy.exe .\\PopcornExport.zip .\\popcornexport.PublishSettings /t app_data\\jobs\\triggered\\PopcornExportWebJob /v /d" ]
      },
      "title": "PopcornExport",
      "version": "1.0.0-*"
    }
</code>```

I had to add the node runtimes (win10-x64 otherwise the app can't run locally). But, the Azure Web Service is running on Windows Server 2012. May it be an issue?

What did I miss?

答:
This error could happen if the bitness of your application doesn't match the bitness of your App Service (e.g. publishing a 64-bit deployment to an App Service running in 32-bit mode).

To solve this I had to change the bitness to the correct setting in Azure:

To match the bitness of my publish profile in VS:

Body:
I have followed this tutorial to deploy a .NET Core console application to an Azure Web Service WebJob.

My app is running locally without any issue (with dotnet 1.0.0-preview2-003131) but when I try to run it from Azure console I have the following error :

Failed to load the dll from [D:\local\VirtualDirectory0\site\wwwroot\app_data\jobs\triggered\PopcornExportWebJob\hostpolicy.dll], HRESULT: 0x800700C1**

An error occurred while loading required library hostpolicy.dll from [D:\local\VirtualDirectory0\site\wwwroot\app_data\jobs\triggered\PopcornExportWebJob]

The version of Azure .Net is 1.0.0-rc4-004771  and the hostpolicy.dll file is the same than I use locally. In fact, when I download the zip of my deploy from Azure and when I run it locally, it is working fine. But it fails on Azure environment.

Also, here is my project.json:

{
      "publishOptions": {
        "include": [
          "run.cmd"
        ]
      },
      "buildOptions": {
        "emitEntryPoint": true,
        "copyToOutput": "appsettings.json"
      },
      "copyright": "bbougot",
      "dependencies": {
        "FubarCoder.RestSharp.Portable.Core": "4.0.7",
        "FubarCoder.RestSharp.Portable.HttpClient": "4.0.7",
        "Microsoft.ApplicationInsights.AspNetCore": "2.0.0",
        "Microsoft.Extensions.Configuration": "1.1.0",
        "Microsoft.Extensions.Configuration.Json": "1.1.0",
        "Microsoft.Extensions.DependencyInjection": "1.1.0",
        "Microsoft.Extensions.Logging": "1.1.0",
        "Microsoft.Extensions.Logging.Console": "1.1.0",
        "Microsoft.NETCore.App": "1.1.0",
        "MongoDB.Driver": "2.4.2",
        "StructureMap.Microsoft.DependencyInjection": "1.3.0"
      },
      "description": "Popcorn Api Exporter",
      "frameworks": {
        "netcoreapp1.1": {
          "imports": [
            "portable-net45+win8"
          ]
        }
      },
      "runtimes": {
        "win10-x64": {}
      },
      "scripts": {
        "postpublish": [ "7za.exe a -tzip PopcornExport.zip .\\bin\\Release\\PublishOutput\\*",
                         ".\\WAWSDeploy.exe .\\PopcornExport.zip .\\popcornexport.PublishSettings /t app_data\\jobs\\triggered\\PopcornExportWebJob /v /d" ]
      },
      "title": "PopcornExport",
      "version": "1.0.0-*"
    }

I had to add the node runtimes (win10-x64 otherwise the app can't run locally). But, the Azure Web Service is running on Windows Server 2012. May it be an issue?

What did I miss?


问:
How to declare a Kotlin function with return type 'void' for a java caller?
I have a library that is completely written in Kotlin including its public API. Now a user of the library uses Java, the problem here is that Kotlin functions with return type Unit are not compiled to return type void. The effect is that the Java side has always to return Unit.INSTANCE for methods that are effectivly void. Can this be avoided somehow?

Example:

Kotlin interface

```<code>interface Foo{
  fun bar()
}
</code>```

Java implementation

```<code>class FooImpl implements Foo{
   // should be public void bar()
   public Unit bar(){
      return Unit.INSTANCE
      // ^^ implementations should not be forced to return anything
   }
}
</code>```

Is it possible to declare the Kotlin function differently so the compiler generates a void or Void method?

答:
example:</p>

```<code>override fun doInBackground(vararg params: Void?):Void{
    for (i in 0 until 10) {

        Thread.sleep(1000);
    }

    return null as Void;

}
</code>```

Body:
I have a library that is completely written in Kotlin including its public API. Now a user of the library uses Java, the problem here is that Kotlin functions with return type Unit are not compiled to return type void. The effect is that the Java side has always to return Unit.INSTANCE for methods that are effectivly void. Can this be avoided somehow?

Example:

Kotlin interface

interface Foo{
  fun bar()
}

Java implementation

class FooImpl implements Foo{
   // should be public void bar()
   public Unit bar(){
      return Unit.INSTANCE
      // ^^ implementations should not be forced to return anything
   }
}

Is it possible to declare the Kotlin function differently so the compiler generates a void or Void method?

Body:
example:

override fun doInBackground(vararg params: Void?):Void{
    for (i in 0 until 10) {

        Thread.sleep(1000);
    }

    return null as Void;

}


问:
How to format a phone number using PhoneNumberUtils?
How can I format a phone number using PhoneNumberUtils?

E.g.: 1234567890 → (123) 456-7890

答:
2020 working sulotion:</p>

```<code>TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

String countryIso = telephonyManager.getNetworkCountryIso().toUpperCase();              //important!!

phoneNumberTextView.setText(PhoneNumberUtils.formatNumber("3473214567", countryIso));
</code>```

Body:
2020 working sulotion:

TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

String countryIso = telephonyManager.getNetworkCountryIso().toUpperCase();              //important!!

phoneNumberTextView.setText(PhoneNumberUtils.formatNumber("3473214567", countryIso));


问:
Redirect output to new date file in shell script
I have a shell script which call a Perl script which can run more than 20 hours .So if the process starts at 06/01 sometime it will end next day at 06/02. Below code i am using to write the output

```<code>date=`date +%Y-%m-%d`
logfile="$log_filename.${date}.log"
nohup run.pl >> $logfile 2>&1 &
</code>```

So problem with this code i have having is it redirecting the output to the old date file even if the date change.

Is there any general solution that we pipe the stderr/stdout of the app to another program and it does the writes to a the rolling log file.

答: I'd write the data to a temporary file and rename it at the end of the run. I'd try to move all of the shell stuff into the Perl program so it can control choosing the file name and date format.</p>

Body:
I have a shell script which call a Perl script which can run more than 20 hours .So if the process starts at 06/01 sometime it will end next day at 06/02. Below code i am using to write the output

date=`date +%Y-%m-%d`
logfile="$log_filename.${date}.log"
nohup run.pl >> $logfile 2>&1 &

So problem with this code i have having is it redirecting the output to the old date file even if the date change.

Is there any general solution that we pipe the stderr/stdout of the app to another program and it does the writes to a the rolling log file.


问:
Navigator.push().then not calling a Function
This is my students list screen, which has an add student button and upon taping save on the form it pops back to the students list.

class _StudentListState extends State<StudentList> {
  var students = new List<Student>();

  _getStudents() {
    APIServices.fetchStudents().then((response) {
      setState(() {
        Iterable list = json.decode(response);
        students = list.map((model) => Student.fromJson(model)).toList();
      });
    });
  }

  @override
  void initState() {
    super.initState();
    _getStudents();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton:_buidFloatingButton(),
      appBar: _buildAppBar(context),
      bottomNavigationBar: BottomAppBar(
// ================== REFRESH BUTTON ============================
        child: FlatButton(
          child:Icon(Icons.refresh),
          onPressed: () {
            _getStudents();
          },
        ),
// =======================================================
      ),
// ================== ADD STUDENT BUTTON =======================
  Widget _buidFloatingButton() {
    return FloatingActionButton(
        child:Icon(Icons.person_add),
        onPressed: () {

            Navigator.push(context, MaterialPageRoute(builder: (context) => AddStudent())).then((value) {
              _getStudents();
            });

        },
      );
  }
// =======================================================
  }
}
```

<p>I'm trying to refresh the student list after the form pop with this code, as seen in above code:</p>

```Navigator.push(context, MaterialPageRoute(builder: (context) => AddStudent())).then((value) => () {
  _getStudents();
});
```

<p><img src="https://i.stack.imgur.com/5IiMY.png" alt="enter image description here">
<img src="https://i.stack.imgur.com/lxBlV.png" alt="enter image description here"></p>

<p>It's not refreshing the student list, but it will refresh if I tap the refresh button, both attempts are executing the same _getStudentes() function.</p>

<p>At the end of the save button I just do a:</p>

```Navigator.pop(context);
```

What am I missing?

Thanks.

答:
You are returning a function with (value) => () { ... }.

The shorthand syntax in JavaScript and Dart differs a little in that regard, let me explain:

// Expression that returns a function.
() {
  ...
}
// You could also assign it to a variable:
final foo = () { return 3; };
// Now, you can call foo:
final bar = foo();
```

<p>Thus, you are returning a function with <code>(value) => () { ... }</code>.</p>

<p>What you want to do instead is either of the following:</p>

<pre class="lang-dart prettyprint-override"><code>(value) => _getStudents()
// or
(value) {
  _getStudents();
}
</code>```

Learn more about functions in Dart.

Body:
This is my students list screen, which has an add student button and upon taping save on the form it pops back to the students list.

class _StudentListState extends State<StudentList> {
  var students = new List<Student>();

  _getStudents() {
    APIServices.fetchStudents().then((response) {
      setState(() {
        Iterable list = json.decode(response);
        students = list.map((model) => Student.fromJson(model)).toList();
      });
    });
  }

  @override
  void initState() {
    super.initState();
    _getStudents();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton:_buidFloatingButton(),
      appBar: _buildAppBar(context),
      bottomNavigationBar: BottomAppBar(
// ================== REFRESH BUTTON ============================
        child: FlatButton(
          child:Icon(Icons.refresh),
          onPressed: () {
            _getStudents();
          },
        ),
// =======================================================
      ),
// ================== ADD STUDENT BUTTON =======================
  Widget _buidFloatingButton() {
    return FloatingActionButton(
        child:Icon(Icons.person_add),
        onPressed: () {

            Navigator.push(context, MaterialPageRoute(builder: (context) => AddStudent())).then((value) {
              _getStudents();
            });

        },
      );
  }
// =======================================================
  }
}

I'm trying to refresh the student list after the form pop with this code, as seen in above code:

Navigator.push(context, MaterialPageRoute(builder: (context) => AddStudent())).then((value) => () {
  _getStudents();
});

It's not refreshing the student list, but it will refresh if I tap the refresh button, both attempts are executing the same _getStudentes() function.

At the end of the save button I just do a:

Navigator.pop(context);

What am I missing?

Thanks.

Body:
You are returning a function with (value) => () { ... }.

The shorthand syntax in JavaScript and Dart differs a little in that regard, let me explain:

// Expression that returns a function.
() {
  ...
}
// You could also assign it to a variable:
final foo = () { return 3; };
// Now, you can call foo:
final bar = foo();

Thus, you are returning a function with (value) => () { ... }.

What you want to do instead is either of the following:

(value) => _getStudents()
// or
(value) {
  _getStudents();
}

Learn more about functions in Dart.


问:
Inventory design approach (inheritance vs generics)
Greetings!
I am trying to decide on which is the best approach to implement a following scenario:

Vehicle and Part are both "entites" which can be an Item in an Inventory.
Vehicle has the usual VIN, Year, Make, Model, Type, etc, etc... while Part has PartNumber, QuantityOnHand, IsPartOfSet, Vendor...
When "stocked" in an Inventory as an Item, both have RetailPrice, PurchasePrice, PurchaseDate but at the same time they have a lot of other properties that are not in common
(e.g Vehicle has CurrentMileage, NewOrUsed, etc... etc.. while Part has TreshholdCount, LastCountDate, etc, etc..)
So as you can see both Part and Vehicle can be in Inventory, but they have very few properties that are share (more that they don't)...

With scenario above, I am trying to decide between several approaches:

Option 1 - Separate classes for everything (no inheritance)

Vehicle - common vehicle properties (VIN, year, make, model, etc, etc)

VehicleInventoryItem - has a reference to Vehicle and contains other inventory specific properties (pricing, warranties, status)

VehicleInventoryManager - singleton with business logic add, remove, notify, etc, etc

Part

PartInventoryItem

PartInventoryManager

I think this approach is most flexible while it suffers for some property repetition. Managers also can have very different methods...

Option 2 - Base class simple inheritance

Vehicle - same as option 1

Part - same as option 1

InventoryItem  - base class

VehicleInventoryItem - extends InventoryItem, references Vehicle

PartInventoryItem - extends InventoryItem, references Part

InventoryManager - all methods accept InventoryItem as parameters

With this approach, I am worried about InventoryManager being polluted with different operations needed for parts vs vehicles

Option 3 - Generics

Item - where T will be part or vehicle (I can even go more specific then, e.g. - VehicleItem : Item)

Inventory - holds reference to Item

InventoryManager - singleton that operates on T

In this approach, there is less classes but again I am worried about InventoryManager

Recap

Vehicle and Part share very few properties when "stocked" in Inventory.

Inventory management for Vehicle and Part will also be mostly different (parts are "reordered" when qty on hand is low, when vehicle is sold similar one may be purchased but it is unique)

In my scenario there will be no other objects/models that will be "stockable" (being in Inventory of any kind)

Questions

What does community think? Is there another approach (perhaps interfaces?)
If 2 domain objects share at least 1 property (e.g. PurchasePrice), should that warrant having some sort of inheritance (e.g. option 2 or 3)

答:
Maybe I'm missing something, but I don't understand your concern about "pollution" in the InventoryManager. If that's a concern, it would call for a separate class. Every other class you've described shares common functionality (at the very least, their identifiers), so inheritance would seem to be the order of the day.

I think, however, that you're going to want to use a mix of technologies. You'll use inheritance, with interfaces (for comparison, for example), and generics (for lists). One does not necessarily exclude the other.


问:
Why the truthmaker of OntoUML <<role>> must be a <<mediation>>?
The thesis Ontological foundations for structural conceptual models states that

"Every relationally dependent entity (role and role mixins) must be
  connected to an association end of a «mediation» relation."

(p.332). Why is a <<member of>> relation not enough to satisfy the relational dependance?

答:
There is indeed a pattern of roles and role mixins for members of collectives, however, the membership to the collective has a truthmaker of its own.

If you only use the «memberOf» relation you'll be hiding the relator of "membership" that makes it true that "the endurant plays the role of a member of some collective". In order to have the complete pattern, you should capture the relator and the «mediation» relation between the role and the relator.

Notice that this is a pattern specific to the case involving roles (e.g., employees, students, band members). You can still have cases where there may not be a relator as the truthmaker of the «memberOf» relation.

Take, for instance, the collective Forest whose members are instances of Tree. In this case, you would not be interested in capturing the "membership" between trees and forests and that is OK as Tree should not be a role, but a category, kind or subkind. (hint: the truthmaker here is something more "tricky")


问:
How to deploy container to gce by updating container image?
I setup my CD with following commands to deploy container to gce:

```<code>gcloud compute instances stop my-awesome-app
gcloud compute instances update my-awesome-app --no-shielded-integrity-monitoring
gcloud beta compute instances update-container my-awesome-app --container-image=docker.io/my-docker-hub-user/my-awesome-app:${IMAGE_TAG}
gcloud compute instances start my-awesome-app
</code>```

The instance will then stop, replace container image and start.

If I create new instance with the latest image, everything works fine.

If I deploy with my CD pipeline, the instance ALWAYS hang forever (after receiving start event, no new logging is coming), NEVER pulls the new image, and NEVER goes up and running.

Anyone can tell me what's the problem?

答:
I hope the document [1] is helpful for you from where you could have steps for updating a container on a VM in Google Cloud.

When you want to update a VM running a container, Compute Engine performs below two steps:

Updates container declaration on the instance. Compute Engine stores the updated container declaration in instance metadata under the gce-container-declaration metadata key.

Stops and restarts the instance to actuate the updated configuration, if the instance is running. If the instance is stopped, updates the container declaration and keeps the instance stopped. The VM instance downloads the new image and launches the container on VM start.

Please follow 1 to 5 steps as the document [1], Compute Engine saves the changes and restarts the instance automatically to make the update. After the VM restarts, it downloads the new image and starts the container with the updated configuration.

[1] https://cloud.google.com/compute/docs/containers/deploying-containers#updating_a_container_on_a_vm_instance

Body:
I setup my CD with following commands to deploy container to gce:

gcloud compute instances stop my-awesome-app
gcloud compute instances update my-awesome-app --no-shielded-integrity-monitoring
gcloud beta compute instances update-container my-awesome-app --container-image=docker.io/my-docker-hub-user/my-awesome-app:${IMAGE_TAG}
gcloud compute instances start my-awesome-app

The instance will then stop, replace container image and start.

If I create new instance with the latest image, everything works fine.

If I deploy with my CD pipeline, the instance ALWAYS hang forever (after receiving start event, no new logging is coming), NEVER pulls the new image, and NEVER goes up and running.

Anyone can tell me what's the problem?


问:
Main activity is not present in android studio
I would like some help/advice on an issue I have involving Android Studio.I'm using android studio and the java language to code however, whenever I try to create a bottom navigation activity in my project only the UI folder is present however the main activity isn't present on the left hand project menu and I was hoping you could help me with this issue, just to make you aware that the problem is not because of any errors in my code and I have tried cleaning and rebuilding my project, it also isnt in the UI folder.The clip i have attached to this email will display the issue.Thank you in advance.

Yours sincerely, UltraSavageGamer

my project menu

adding bottom navigation activity

bottom navigation activity added

main activity not present

答:
First you should make sure you can see the MainActivity.java in your explore folder (where you save your project). If it existes, you can change the view of Android Studio to see it like the picture below:

Change the view mode to "project files" or sth else to look for your MainActivity.


问:
Spring Boot runnable Jar file for production?
Is spring boot runnable jar file meant for production environments with any optimizations needed for production or it is meant for testing/prototyping and we should generate and deploy WAR files on app servers in the prod machines?</p>

答: It is perfectly suited for Prod envs. You can check https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html#server-properties to see how you can configure your server.</p>


问:
How to do conditional variables definition on Karate
I had written karate tests for one environment only (staging). Since the tests are successful on capturing bugs (thanks a lot Karate and Intuit team!), there is now request to run the tests on production.

Our tests are graphql-based where most of the requests are query. I wonder if it is possible for us to switch variables based on karate.env we passed on terminal?

Most of our requests look like this:

```<code>And def variables = {objectID:"1234566", cursor:"1", cursorType:PAGE, size:'10', objectType:USER}
And request { query: '#(query)', variables: '#(variables)' }
When method POST
Then status 200
</code>```

I had tried reading the conditional-logic page on github page but haven't yet found a success.

What I tried so far is:

```<code>* if (karate.env == 'staging') * def variables = {objectID:"1234566", cursor:"1", cursorType:PAGE, size:'10', objectType:USER}
</code>```

But to no success.

Any help will be greatly appreciated. Thanks a lot!

答:
We keep our graphql queries & variables in separate json files, but, we're attempting to solve the same issue.  Based on what Peter wrote I came up with this, though it will likely get cleaned up before deployment.</p>

```<code>Given def query = read('graphqlQuery.graphql')
    And def prodVariable = read('prod-variables.json')
    And def stageVariable = read('stage-variables.json')
    And def variables = karate.env == 'prod' ? prodV : stageV
    And path 'api/' + 'graphql'
    And request { query: '#(query)', variables: '#(variables)' }
    When method post
    Then status 200
</code>```

Body:
I had written karate tests for one environment only (staging). Since the tests are successful on capturing bugs (thanks a lot Karate and Intuit team!), there is now request to run the tests on production.

Our tests are graphql-based where most of the requests are query. I wonder if it is possible for us to switch variables based on karate.env we passed on terminal?

Most of our requests look like this:

And def variables = {objectID:"1234566", cursor:"1", cursorType:PAGE, size:'10', objectType:USER}
And request { query: '#(query)', variables: '#(variables)' }
When method POST
Then status 200

I had tried reading the conditional-logic page on github page but haven't yet found a success.

What I tried so far is:

* if (karate.env == 'staging') * def variables = {objectID:"1234566", cursor:"1", cursorType:PAGE, size:'10', objectType:USER}

But to no success.

Any help will be greatly appreciated. Thanks a lot!

Body:
We keep our graphql queries & variables in separate json files, but, we're attempting to solve the same issue.  Based on what Peter wrote I came up with this, though it will likely get cleaned up before deployment.

Given def query = read('graphqlQuery.graphql')
    And def prodVariable = read('prod-variables.json')
    And def stageVariable = read('stage-variables.json')
    And def variables = karate.env == 'prod' ? prodV : stageV
    And path 'api/' + 'graphql'
    And request { query: '#(query)', variables: '#(variables)' }
    When method post
    Then status 200


问:
To Convert CSV File to Hash Structure using TEXT::CSV_XS Module in perl
I've below code which is used to read a csv file and convert to hash. The Keys are dependent on the number of key columns that user need.

```<code>use warnings;
use strict;

my %hash;
my $KeyCols = 2;
while (<DATA>) {
    chomp;
    my @cols = split /,/, $_, $KeyCols+1;
    next unless @cols > $KeyCols;
    my $v = pop @cols;
    my $k = join '', @cols;
    $hash{$k} = $v;
}
</code>```

I need help in achieving the same logic using TEXT::CSV_XS package for efficiency. Please help.

答:
The real reason for using Text::CSV_XS is for correctness. It's not going to be faster than what you have, but it will work where yours will fail.

```<code>use Text::CSV_XS qw( );

my $csv = Text::CSV_XS->new({
    auto_diag => 2,
    binary    => 1,
});

my %hash;
while ( my $row = $csv->getline(\*DATA) ) {
   $hash{ $row->[0] . $row->[1] } = $row;
}
</code>```

Concatenating the fields together directly (without a separator) seems really odd.

The above makes the value an array of fields rather than CSV. If you want CSV as in the original, you will need to re-encode them into CSV.

```<code>my %hash;
while ( my $row = $csv->getline(\*DATA) ) {
   my ($k1, $k2) = splice(@$row, 0, 2);
   $csv->combine(@$row);
   $hash{ $k1 . $k2 } = $csv->string();
}
</code>```

Body:
I've below code which is used to read a csv file and convert to hash. The Keys are dependent on the number of key columns that user need.

use warnings;
use strict;

my %hash;
my $KeyCols = 2;
while (<DATA>) {
    chomp;
    my @cols = split /,/, $_, $KeyCols+1;
    next unless @cols > $KeyCols;
    my $v = pop @cols;
    my $k = join '', @cols;
    $hash{$k} = $v;
}

I need help in achieving the same logic using TEXT::CSV_XS package for efficiency. Please help.

Body:
The real reason for using Text::CSV_XS is for correctness. It's not going to be faster than what you have, but it will work where yours will fail.

use Text::CSV_XS qw( );

my $csv = Text::CSV_XS->new({
    auto_diag => 2,
    binary    => 1,
});

my %hash;
while ( my $row = $csv->getline(\*DATA) ) {
   $hash{ $row->[0] . $row->[1] } = $row;
}

Concatenating the fields together directly (without a separator) seems really odd.

The above makes the value an array of fields rather than CSV. If you want CSV as in the original, you will need to re-encode them into CSV.

my %hash;
while ( my $row = $csv->getline(\*DATA) ) {
   my ($k1, $k2) = splice(@$row, 0, 2);
   $csv->combine(@$row);
   $hash{ $k1 . $k2 } = $csv->string();
}


问:
Base10 encryption for a String
I am trying to find a way to obtain a base10 value for a String. This is easily achievable with the hash code function as shown. But I've noticed the values turns up sequential or close to it. Example below.

I am not dealing with a secure password or anything here, just wanting to be able to convert a String to base10 value and always get the same value when I do that.

May be bit over kill but looked at existing hashing options such as MessageDigest. But they are all Base64 (more or less) but none for Base10 which is expected considering that is not secure to begin with.

One possible option I am thinking is to use MessageDigest, get a base64 value and regex it to only extract out all the numbers. Meaning every time I encode via message digest and regex to get only Base10 values, I should always get same value.

My question is, is there a better way to do this? Instead of complicating it with encryptions which is not really needed in my case.

I just want to convert example as follows:

```<code>String s1 = "Sample00000000001";
// after encoding, getting Base10 value like -> 8725342728354

String s2 = "Sample00000000002";
// after encoding, getting Base10 value like -> 11576232138652 (random, not sequential even though only 1 character changed).
</code>```

Trying with Base64 from Java Util which produces results in sequence (or close) thus not what I want. Will still need to regex out the Base10 values from here.

```<code>public static void main(String[] args) {
    String salt = "Sample";
    String num = "00000000001";
    Base64.Encoder encoder = Base64.getEncoder();
    Base64.Decoder decoder = Base64.getDecoder();
    String value  = salt + num;
    String encoded = encoder.encodeToString(value.getBytes());
    String decoded = new String(decoder.decode(encoded));
    // 00000000001 gives U2FtcGxlMDAwMDAwMDAwMDE=
    // 00000000002 gives U2FtcGxlMDAwMDAwMDAwMDI=
}
</code>```

Using hashcode which again ends up sequential or close

```<code>public static void main(String[] args) {

    String salt = "Sample";
    String num = "00000000002";

    String v = salt+num;
    int hash = v.hashCode();
    System.out.println(hash);
}
</code>```

Last option I am looking at, using libraries like Bouncy castle or in built MessageDigest.

Assuming the encoding is done and I have assigned that to variable 'value' below. I could pull out only Base10 values from it via regex as follows.

```<code>String value = "HASDJHSDGF3423HIHGH234565BJB666";
long result =  Long.valueOf(value.replaceAll("\\D+",""));
System.out.println(result); // end up with 3423234565666 as expected.
</code>```

I am currently leaning towards this last option to possibly use MessageDigest but looking for advice / options for a better way to do this. Appreciate any help. Thanks.

答:
You can use the message digest to generate an array of bytes and then read them as integer:

   public static void main(String[] args) {

        String salt = "Sample";
        String num = "00000000002";
        String num2 = "00000000001";

        hash(salt, num);
        hash(salt, num2);
    }

    private static void hash(String salt, String num) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.reset();
            ByteBuffer bytes = ByteBuffer.wrap(digest.digest((num + digest).getBytes()));
            System.out.println(bytes.asIntBuffer().get());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
```

<p>Or you can use the <code>Random</code> class (same seed produce the same "random" value) (I'm not sure from a performance point of view about the implications)</p>

<pre class="lang-java prettyprint-override"><code>   private static void hash(String salt, String num) {
        System.out.println(new Random(num.hashCode() + salt.hashCode()).nextInt());
    }
</code>```

Title: Base10 encryption for a String

Body:
I am trying to find a way to obtain a base10 value for a String. This is easily achievable with the hash code function as shown. But I've noticed the values turns up sequential or close to it. Example below.

I am not dealing with a secure password or anything here, just wanting to be able to convert a String to base10 value and always get the same value when I do that.

May be bit over kill but looked at existing hashing options such as MessageDigest. But they are all Base64 (more or less) but none for Base10 which is expected considering that is not secure to begin with.

One possible option I am thinking is to use MessageDigest, get a base64 value and regex it to only extract out all the numbers. Meaning every time I encode via message digest and regex to get only Base10 values, I should always get same value.

My question is, is there a better way to do this? Instead of complicating it with encryptions which is not really needed in my case.

I just want to convert example as follows:

String s1 = "Sample00000000001";
// after encoding, getting Base10 value like -> 8725342728354

String s2 = "Sample00000000002";
// after encoding, getting Base10 value like -> 11576232138652 (random, not sequential even though only 1 character changed).

Trying with Base64 from Java Util which produces results in sequence (or close) thus not what I want. Will still need to regex out the Base10 values from here.

public static void main(String[] args) {
    String salt = "Sample";
    String num = "00000000001";
    Base64.Encoder encoder = Base64.getEncoder();
    Base64.Decoder decoder = Base64.getDecoder();
    String value  = salt + num;
    String encoded = encoder.encodeToString(value.getBytes());
    String decoded = new String(decoder.decode(encoded));
    // 00000000001 gives U2FtcGxlMDAwMDAwMDAwMDE=
    // 00000000002 gives U2FtcGxlMDAwMDAwMDAwMDI=
}

Using hashcode which again ends up sequential or close

public static void main(String[] args) {

    String salt = "Sample";
    String num = "00000000002";

    String v = salt+num;
    int hash = v.hashCode();
    System.out.println(hash);
}

Last option I am looking at, using libraries like Bouncy castle or in built MessageDigest.

Assuming the encoding is done and I have assigned that to variable 'value' below. I could pull out only Base10 values from it via regex as follows.

String value = "HASDJHSDGF3423HIHGH234565BJB666";
long result =  Long.valueOf(value.replaceAll("\\D+",""));
System.out.println(result); // end up with 3423234565666 as expected.

I am currently leaning towards this last option to possibly use MessageDigest but looking for advice / options for a better way to do this. Appreciate any help. Thanks.

Body:
You can use the message digest to generate an array of bytes and then read them as integer:

   public static void main(String[] args) {

        String salt = "Sample";
        String num = "00000000002";
        String num2 = "00000000001";

        hash(salt, num);
        hash(salt, num2);
    }

    private static void hash(String salt, String num) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.reset();
            ByteBuffer bytes = ByteBuffer.wrap(digest.digest((num + digest).getBytes()));
            System.out.println(bytes.asIntBuffer().get());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

Or you can use the Random class (same seed produce the same "random" value) (I'm not sure from a performance point of view about the implications)

   private static void hash(String salt, String num) {
        System.out.println(new Random(num.hashCode() + salt.hashCode()).nextInt());
    }


问:
How to take picture with webcam from excel?
I would like to take a picture using a webcam from excel macros, and I am a complete beginner when it comes to excel. I tried to follow other sources on the internet, but I can't even type in "Public Class Form1" without getting an error. What I did was I inserted a button into a spreadsheet, clicked "New," then replaced the sub data that comes with the button with code I found on the internet, and I just have tons of red lines throughout the code.

I looked at this post and its answers, but none of it works because, as I've said, excel doesn't want to work. If it's possible for you guys to give me more baby-step instructions (use this button and not that button, you gotta type "Public Class Form1" then pray to the gods for it to work instead of just pressing enter, stuff like that), that would help me greatly.

Visual Basic Connect to Webcam and Save Picture to File

Me not knowing how to terminate line. I tried &HD and &HA since that's a solution from microsoft, but that obviously didn't work.

答:
The answer is don't try to do the whole thing from excel. In excel, assign a macro to a button. The code in that macro will be:

```<code>Sub RunPython()

Dim objShell As Object
Dim PythonExe, PythonScript As String

    Set objShell = VBA.CreateObject("Wscript.Shell")

    PythonExe = """PATH TO PYTHON.EXE"""
    PythonScript = "PATH TO PYTHON CODE THAT NEEDS TO BE RUN"

    objShell.Run PythonExe & PythonScript

End Sub
</code>```

In Python 3, you, use the following code:

```<code>from cv2 import *

cam = VideoCapture(0)   # 0 -> index of camera
s, img = cam.read()
if s:    # frame captured without any errors
    namedWindow("cam-test", WINDOW_NORMAL)
    imshow("cam-test",img)
    waitKey(1000)
    destroyWindow("cam-test")
    imwrite("filename.jpg",img) #save image
</code>```

Credit:

Using Excel to use Python: https://stackoverflow.com/a/60658227/9582521

Using Python to use Webcam: https://stackoverflow.com/a/11094891/9582521

Body:
The answer is don't try to do the whole thing from excel. In excel, assign a macro to a button. The code in that macro will be:

Sub RunPython()

Dim objShell As Object
Dim PythonExe, PythonScript As String

    Set objShell = VBA.CreateObject("Wscript.Shell")

    PythonExe = """PATH TO PYTHON.EXE"""
    PythonScript = "PATH TO PYTHON CODE THAT NEEDS TO BE RUN"

    objShell.Run PythonExe & PythonScript

End Sub

In Python 3, you, use the following code:

from cv2 import *

cam = VideoCapture(0)   # 0 -> index of camera
s, img = cam.read()
if s:    # frame captured without any errors
    namedWindow("cam-test", WINDOW_NORMAL)
    imshow("cam-test",img)
    waitKey(1000)
    destroyWindow("cam-test")
    imwrite("filename.jpg",img) #save image

Credit:

Using Excel to use Python: https://stackoverflow.com/a/60658227/9582521

Using Python to use Webcam: https://stackoverflow.com/a/11094891/9582521


问:
mysql sum values from query
The mysql query looks like:

```<code>SELECT count(f.id) as total, m1.fname FROM members m1 INNER JOIN new f ON m1.id = f.id
</code>```

The result of that query:

```<code>   total | fname  |
  ------------------
    2    |  john
    3    |  mike
    5    |  july
</code>```

How can I sum values from column "total" using this mysql query?

答:
You should use sum() instead of count(). did you check sum?</p>

```<code>SELECT sum(f.id) as total, m1.fname FROM members m1 INNER JOIN new f ON m1.id = f.id
</code>```

Title: mysql sum values from query

Body:
The mysql query looks like:

SELECT count(f.id) as total, m1.fname FROM members m1 INNER JOIN new f ON m1.id = f.id

The result of that query:

   total | fname  |
  ------------------
    2    |  john
    3    |  mike
    5    |  july

How can I sum values from column "total" using this mysql query?

Body:
You should use sum() instead of count(). did you check sum?

SELECT sum(f.id) as total, m1.fname FROM members m1 INNER JOIN new f ON m1.id = f.id


问:
How to enable PyCharm autocompletion for imported library (Discord.py)
How do I enable method autocompletion for discord.py in PyCharm? Until now I've been doing it the hard way by looking at the documentation and I didn't even know that autocomplete for a library existed. So how do I enable it?</p>

答: The answer in my case was to first create a new interpreter as a new virtual environment, copy over all of the libraries I needed (there is an option to inherit all of the libraries from the previous interpreter while setting up the new one) and then follow method 3 from above. I hope this helps anyone in the future!</p>


问:
Get the number of columns between Column A and a certain Range in the sheet
I use this VBA to get the first column of Range("C2:E4"):

```<code>Sub Get_First_Column()
Sheet1.Range("C2:E4").Column
End Sub
</code>```

In this case the result is 3.

Now, I want to add the number of columns that is between the Column A and the Range("C2:E4").

In this case it would be 2 since Column A and Column B are between.
The result would be 5 in the end.

I could do this manually by just adding +2  behind the VBA.

However, the Range("C2:E4") could also change to another range. Therefore, I am looking for a flexible solution.

答:
This should work

```<code>Sub Get_First_Column()

    Debug.Print 2 * Sheet1.Range("C2:E4").Column - 1

End Sub
</code>```

if you're looking to a flexible solution then set your range and result separately, as below

```<code>Sub Get_First_Column()

Dim rng As Range
Dim x As Long

Set rng = Sheet1.Range("C2:E4")

    x = 2 * rng.Column - 1

    MsgBox x    'delete this line, for testing only

End Sub
</code>```

Body:
I use this VBA to get the first column of Range("C2:E4"):

Sub Get_First_Column()
Sheet1.Range("C2:E4").Column
End Sub

In this case the result is 3.

Now, I want to add the number of columns that is between the Column A and the Range("C2:E4").

In this case it would be 2 since Column A and Column B are between.
The result would be 5 in the end.

I could do this manually by just adding +2  behind the VBA.

However, the Range("C2:E4") could also change to another range. Therefore, I am looking for a flexible solution.

Body:
This should work

Sub Get_First_Column()

    Debug.Print 2 * Sheet1.Range("C2:E4").Column - 1

End Sub

if you're looking to a flexible solution then set your range and result separately, as below

Sub Get_First_Column()

Dim rng As Range
Dim x As Long

Set rng = Sheet1.Range("C2:E4")

    x = 2 * rng.Column - 1

    MsgBox x    'delete this line, for testing only

End Sub


问:
How to avoid duplicate legend labels in plotly or pass custom legend labels
How can I avoid duplicate legend labels in subplots? One way I would go about it in matplotlib would be to pass custom legend labels to an legend object. I couldn't find any documentation for an equivalent option in plotly. Any ideas?

```<code>traces = []

colors = {'Iris-setosa': 'rgb(31, 119, 180)',
          'Iris-versicolor': 'rgb(255, 127, 14)',
          'Iris-virginica': 'rgb(44, 160, 44)'}

for col in range(4):
    for key in colors:
        traces.append(Histogram(x=X[y==key, col],
                        opacity=0.75,
                        xaxis='x%s' %(col+1),
                        marker=Marker(color=colors[key]),
                        name=key
                        )
                     )

data = Data(traces)

layout = Layout(barmode='overlay',
                xaxis=XAxis(domain=[0, 0.25], title='sepal length (cm)'),
                xaxis2=XAxis(domain=[0.3, 0.5], title='sepal width (cm)'),
                xaxis3=XAxis(domain=[0.55, 0.75], title='petal length (cm)'),
                xaxis4=XAxis(domain=[0.8, 1], title='petal width (cm)'),
                yaxis=YAxis(title='count'),
                title='Distribution of the different Iris flower features')

fig = Figure(data=data, layout=layout)

py.iplot(fig)
</code>```

答:
This is a code snippet I came up with which avoids to set showlegend=False manually on each trace with a duplicate name.

```<code>names = set()
fig.for_each_trace(
    lambda trace:
        trace.update(showlegend=False)
        if (trace.name in names) else names.add(trace.name))
</code>```

fig.for_each_trace calls the passed function for each trace. The function keeps track of which legend names already occurred (via the set names, like @LucG proposed in a comment), and hides legend entries for duplicate (or triplicate, ...) names.

The code needs to be run after all traces have been added to the figure, and before it is shown.

Body:
How can I avoid duplicate legend labels in subplots? One way I would go about it in matplotlib would be to pass custom legend labels to an legend object. I couldn't find any documentation for an equivalent option in plotly. Any ideas?

traces = []

colors = {'Iris-setosa': 'rgb(31, 119, 180)',
          'Iris-versicolor': 'rgb(255, 127, 14)',
          'Iris-virginica': 'rgb(44, 160, 44)'}

for col in range(4):
    for key in colors:
        traces.append(Histogram(x=X[y==key, col],
                        opacity=0.75,
                        xaxis='x%s' %(col+1),
                        marker=Marker(color=colors[key]),
                        name=key
                        )
                     )

data = Data(traces)

layout = Layout(barmode='overlay',
                xaxis=XAxis(domain=[0, 0.25], title='sepal length (cm)'),
                xaxis2=XAxis(domain=[0.3, 0.5], title='sepal width (cm)'),
                xaxis3=XAxis(domain=[0.55, 0.75], title='petal length (cm)'),
                xaxis4=XAxis(domain=[0.8, 1], title='petal width (cm)'),
                yaxis=YAxis(title='count'),
                title='Distribution of the different Iris flower features')

fig = Figure(data=data, layout=layout)

py.iplot(fig)

Body:
This is a code snippet I came up with which avoids to set showlegend=False manually on each trace with a duplicate name.

names = set()
fig.for_each_trace(
    lambda trace:
        trace.update(showlegend=False)
        if (trace.name in names) else names.add(trace.name))

fig.for_each_trace calls the passed function for each trace. The function keeps track of which legend names already occurred (via the set names, like @LucG proposed in a comment), and hides legend entries for duplicate (or triplicate, ...) names.

The code needs to be run after all traces have been added to the figure, and before it is shown.


问:
categoryChoiceTree in prestashop module configuration page
I'm developing a prestashop module and I'm trying to show a category tree in my backoffice configuration page.

I'm trying to follow this instructions below but  I don't know exactly where to add this code.

It should be inside main module's php? or inside a separate .php file and call it from the main one (don't know how to do it either).

As much time I'm spending trying to figure out, how to implement the code in the link above, the more I think I'm losing my time.
I see that "use" files, and this JS, " /admin-dev/themes/new-theme/js/components/form/choice-tree.js " are not in any prestashop folders.

答:
Well, it is SOLVED!!!! Finally it was very simple, but you must get the correct info for you particular case.
@Robertino's answer might be the best implementation, I don't know, but it became impossible to solve for me,

I uses this code below, and called $categoryTree from the form input. This input must be type=> categories_select

Thanks for your time, and for the help of another post from this forum.

```<code>$root = Category::getRootCategory();

    //Generating the tree
    $tree = new HelperTreeCategories('categories_1'); //The string in param is the ID used by the generated tree
    $tree->setUseCheckBox(false)
        ->setAttribute('is_category_filter', $root->id)
        ->setRootCategory($root->id)
        ->setSelectedCategories(array((int)Configuration::get('CATEGORY_1'))) //if you wanted to be pre-carged
        ->setInputName('CATEGORY_1'); //Set the name of input. The option "name" of $fields_form doesn't seem to work with "categories_select" type
    $categoryTree = $tree->render();
</code>```

And the Form:

```<code>                    array(
                    'type'  => 'categories_select',
                    'label' => $this->l('Category'),
                    'desc' => $this->l('Select Category '),
                    'name'  => 'CATEGORY_1', //No ho podem treure si no, no passa la variable al configuration
                    'category_tree'  => $categoryTree, //This is the category_tree called in form.tpl
                    'required' => true
</code>```

Body:
Well, it is SOLVED!!!! Finally it was very simple, but you must get the correct info for you particular case.
@Robertino's answer might be the best implementation, I don't know, but it became impossible to solve for me,

I uses this code below, and called $categoryTree from the form input. This input must be type=> categories_select

Thanks for your time, and for the help of another post from this forum.

$root = Category::getRootCategory();

    //Generating the tree
    $tree = new HelperTreeCategories('categories_1'); //The string in param is the ID used by the generated tree
    $tree->setUseCheckBox(false)
        ->setAttribute('is_category_filter', $root->id)
        ->setRootCategory($root->id)
        ->setSelectedCategories(array((int)Configuration::get('CATEGORY_1'))) //if you wanted to be pre-carged
        ->setInputName('CATEGORY_1'); //Set the name of input. The option "name" of $fields_form doesn't seem to work with "categories_select" type
    $categoryTree = $tree->render();

And the Form:

                    array(
                    'type'  => 'categories_select',
                    'label' => $this->l('Category'),
                    'desc' => $this->l('Select Category '),
                    'name'  => 'CATEGORY_1', //No ho podem treure si no, no passa la variable al configuration
                    'category_tree'  => $categoryTree, //This is the category_tree called in form.tpl
                    'required' => true


问:
Avoiding Error 429 (quota exceeded) while working with Google Cloud Registry
I'm hitting 429 error in Google Container Registry, too many images are pulled simultaneously

```<code>Error: Status 429 trying to pull repository [...] "Quota Exceeded."
</code>```

There is a Kubernetes cluster with multiple nodes and pods implement Kubeflow steps. In the Google guide they suggest the following:

```<code>To avoid hitting the fixed quota limit, you can:
- Increase the number of IP addresses talking to Container Registry.
  Quotas are per IP address.
- Add retries that introduce a delay.
  For example, you could use exponential backoff.
</code>```

Questions:

How to increase the number of IP addresses talking to Container Registry?

How and where is it possible to add retries that introduce a delay? Pods are run as steps in the Kubeflow pipelines.

Update:

It was Spinnaker which produced many requests to GCR, so it was a different application that exceeded quota and caused issues

答:
It seems nothing can be done in terms of the Cloud Registry quota limits because those are fixed. According to Container Registry > Doc > Resources > Quotas and limits:

Any request sent to Container Registry has a 2 hour timeout limit.

The fixed rate limits per client IP address are:

50,000 HTTP requests every 10 minutes

1,000,000 HTTP requests per day

Google provides support for GKE, but Kubeflow itself is not supported by Google. This question should be addressed to the Kubeflow support.

A Kubeflow issue with breaching quota limits and a question about how to get container pulls to use more IP addresses can be registered on the project page on GitHub:
https://github.com/kubeflow/kubeflow/issues

Other support options are available here:
https://www.kubeflow.org/docs/other-guides/support/

If you use CLI, you may try to customize Kubeflow configuration file before deployment or split it into separate deployments to overcome Cloud Registry quota limits. This approach helps for some complicated deployments. An important thing here is to take care of dependencies. First run

```<code>kfctl build -v -f ${CONFIG_URI}
</code>```

make changes in the file ${KF_DIR}/kfctl_gcp_iap.yaml, and then run

```<code>kfctl apply -v -f ${CONFIG_URI}
</code>```

Body:
I'm hitting 429 error in Google Container Registry, too many images are pulled simultaneously

Error: Status 429 trying to pull repository [...] "Quota Exceeded."

There is a Kubernetes cluster with multiple nodes and pods implement Kubeflow steps. In the Google guide they suggest the following:

To avoid hitting the fixed quota limit, you can:
- Increase the number of IP addresses talking to Container Registry.
  Quotas are per IP address.
- Add retries that introduce a delay.
  For example, you could use exponential backoff.

Questions:

How to increase the number of IP addresses talking to Container Registry?

How and where is it possible to add retries that introduce a delay? Pods are run as steps in the Kubeflow pipelines.

Update:

It was Spinnaker which produced many requests to GCR, so it was a different application that exceeded quota and caused issues

Body:
It seems nothing can be done in terms of the Cloud Registry quota limits because those are fixed. According to Container Registry > Doc > Resources > Quotas and limits:

Any request sent to Container Registry has a 2 hour timeout limit.

The fixed rate limits per client IP address are:

50,000 HTTP requests every 10 minutes

1,000,000 HTTP requests per day

Google provides support for GKE, but Kubeflow itself is not supported by Google. This question should be addressed to the Kubeflow support.

A Kubeflow issue with breaching quota limits and a question about how to get container pulls to use more IP addresses can be registered on the project page on GitHub:
https://github.com/kubeflow/kubeflow/issues

Other support options are available here:
https://www.kubeflow.org/docs/other-guides/support/

If you use CLI, you may try to customize Kubeflow configuration file before deployment or split it into separate deployments to overcome Cloud Registry quota limits. This approach helps for some complicated deployments. An important thing here is to take care of dependencies. First run

kfctl build -v -f ${CONFIG_URI}

make changes in the file ${KF_DIR}/kfctl_gcp_iap.yaml, and then run

kfctl apply -v -f ${CONFIG_URI}