问:
How to change an ImageButton image after a while?
How can i change an ImageButton image after a specified amount of time without touching it, in Android Studio?

Thanks!

答:
Hey use this example with Thread: </p>

```<code>  public class MainActivity extends AppCompatActivity {

        private ImageButton button;
        private boolean flagChange = false;
        private Activity mActivity;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);

            mActivity = this;
            button = findViewById(R.id.button1);

            //thread
            new Thread(new Runnable() {
                @Override
                public void run() {

                    //always run background
                    while(true){

                        SystemClock.sleep(2000);//2 seconds sleep

                        //update Android UI on Main Thread
                        mActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (!flagChange) {
                                    button.setImageResource(R.drawable.ic_launcher_background);
                                    flagChange = true;
                                }else{
                                    button.setImageResource(R.drawable.ic_drop);
                                    flagChange = false;
                                }
                            }
                        });

                    }
                }
            }).start(); //start thread
}
</code>```

Body:
Hey use this example with Thread:

  public class MainActivity extends AppCompatActivity {

        private ImageButton button;
        private boolean flagChange = false;
        private Activity mActivity;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);

            mActivity = this;
            button = findViewById(R.id.button1);

            //thread
            new Thread(new Runnable() {
                @Override
                public void run() {

                    //always run background
                    while(true){

                        SystemClock.sleep(2000);//2 seconds sleep

                        //update Android UI on Main Thread
                        mActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (!flagChange) {
                                    button.setImageResource(R.drawable.ic_launcher_background);
                                    flagChange = true;
                                }else{
                                    button.setImageResource(R.drawable.ic_drop);
                                    flagChange = false;
                                }
                            }
                        });

                    }
                }
            }).start(); //start thread
}


来源: stackexchange

问:
MYSQL entries from one table that appear most often in another table
I have 2 tables, authors and books

authors contains the unique id authorId

books also contains this as a foreign key

I need to know the authors with the most number of books. If 2 or more authors are tied for the greatest number of books, I need to show both authors

I have been able to achieve this by first getting the maximum count

```<code>SELECT @maxCount := (MAX(counter)) FROM (SELECT count(*) AS counter FROM books GROUP BY authorId) AS counts;
</code>```

and then using it to get the Ids with that count as part of my author selection

```<code>SELECT *
FROM authors
WHERE authorId IN (
    SELECT authorId
    FROM books
    GROUP BY authorId
    HAVING COUNT(*) = @maxCount
);
</code>```

I've been told that I am not allowed to use variables and that what I've done is horribly inefficient if the tables grow very large.

Am I missing something obvious here? Is there a way to do this in a single statement without a variable (or temp table), and without having to select/group the entire books table twice?

答:
```<code>SELECT author, COUNT(*)
FROM authors
JOIN books
ON authors.authorId=books.AuthorId
GROUP BY author
ORDER BY COUNT(*) DESC
</code>```

Will give you a list ordered by the number of books for each author. I don't have an instance nearby to test, and tend to steer clear of embedded variables but expect something like....

```<code>SELECT *
FROM (
  SELECT author
  , @maxcount:=IF(COUNT(*)>@maxcount,COUNT(*), @maxcount)
  , COUNT(*) AS cnt
  FROM authors
  JOIN books
  ON authors.authorId=books.AuthorId
  GROUP BY author
  ORDER BY COUNT(*) DESC
) ilv
WHERE cnt=@maxcount;
</code>```

Performance still sucks with large datasets (even with the right indexes). If you have to run this query frequently with >100,000 records, then you might consider denormalizing your data.

ContentLicense: CC BY-SA 3.0

Body:
I have 2 tables, authors and books

authors contains the unique id authorId

books also contains this as a foreign key

I need to know the authors with the most number of books. If 2 or more authors are tied for the greatest number of books, I need to show both authors

I have been able to achieve this by first getting the maximum count

SELECT @maxCount := (MAX(counter)) FROM (SELECT count(*) AS counter FROM books GROUP BY authorId) AS counts;

and then using it to get the Ids with that count as part of my author selection

SELECT *
FROM authors
WHERE authorId IN (
    SELECT authorId
    FROM books
    GROUP BY authorId
    HAVING COUNT(*) = @maxCount
);

I've been told that I am not allowed to use variables and that what I've done is horribly inefficient if the tables grow very large.

Am I missing something obvious here? Is there a way to do this in a single statement without a variable (or temp table), and without having to select/group the entire books table twice?

Body:
SELECT author, COUNT(*)
FROM authors
JOIN books
ON authors.authorId=books.AuthorId
GROUP BY author
ORDER BY COUNT(*) DESC

Will give you a list ordered by the number of books for each author. I don't have an instance nearby to test, and tend to steer clear of embedded variables but expect something like....

SELECT *
FROM (
  SELECT author
  , @maxcount:=IF(COUNT(*)>@maxcount,COUNT(*), @maxcount)
  , COUNT(*) AS cnt
  FROM authors
  JOIN books
  ON authors.authorId=books.AuthorId
  GROUP BY author
  ORDER BY COUNT(*) DESC
) ilv
WHERE cnt=@maxcount;

Performance still sucks with large datasets (even with the right indexes). If you have to run this query frequently with >100,000 records, then you might consider denormalizing your data.


问:
Linq to select property from XML
This is my first day working with XML in the context of XPath, XQuery, and Linq, and I can't get any of them to work for me.

My goal is to extract values for AgentGUID and PublicKey in a XML blob.  The Linq query I'm using is below.

```<code>        IEnumerable<string> publicKey =
            from item in xDoc.Descendants("PublicKey")
            select (string)item.????;
</code>```

Here is the XML I'm trying to select from:

```<code><AgentRegister xmlns="sampleURI">
server
<Servername>server</Servername>
<AgentGUID>1da3a4cf-73f2-4ee2-b8c1-cef428ad4b21</AgentGUID>
<PublicKey><RSAKeyValue><Modulus>5fuiFE74EKYUxFbSsAgeYQwyGzulQ+L1auBD1J/1gupF2s2NugpgZ6vqsi4o//vKdrKz7uhwDWeRUB5TR7hljNfOsJKbTV0sg4HywF93cyYDnfKz+2wCSxiZxAIWV8SMiui2QuD0LjbgPNGR/bBsY4GIl3eWbngjJjNEzVZq5RE=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue></PublicKey>
<ApprovedByGUID><RSAKeyValue><Modulus>5fuiFE74EKYUxFbSsAgeYQwyGzulQ+L1auBD1J/1gupF2s2NugpgZ6vqsi4o//vKdrKz7uhwDWeRUB5TR7hljNfOsJKbTV0sg4HywF93cyYDnfKz+2wCSxiZxAIWV8SMiui2QuD0LjbgPNGR/bBsY4GIl3eWbngjJjNEzVZq5RE=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue></ApprovedByGUID>
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
<Reference URI="">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" /></Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<DigestValue>2HuOAQAAxOTWz2JSq9+bJnWM8m8=</DigestValue></Reference>
</SignedInfo>
<SignatureValue>yGKq/p/JQCWSJtVKeRp4E5kHeFWVaoMFd/TbrYIm6k3nYBgr57gcEZjzvrLNsmKKaoaWspSqMzTDnrhER5AkfMi+4nhW0C6+vghNYU/jrEqT35Ov/B3aH1M41q07p3OXZc8dA1lzJ6Zh0zpx6Vd7faTfvuPqgIKmNOe07xGyP2Q=</SignatureValue>
<KeyInfo><KeyValue><RSAKeyValue>
<Modulus>5fuiFE74EKYUxFbSsAgeYQwyGzulQ+L1auBD1J/1gupF2s2NugpgZ6vqsi4o//vKdrKz7uhwDWeRUB5TR7hljNfOsJKbTV0sg4HywF93cyYDnfKz+2wCSxiZxAIWV8SMiui2QuD0LjbgPNGR/bBsY4GIl3eWbngjJjNEzVZq5RE=</Modulus>
<Exponent>AQAB</Exponent></RSAKeyValue></KeyValue></KeyInfo>
</Signature>
</AgentRegister>
</code>```

How do I extract the mentioned values from this document?

答:
I would do it using XDocument but without LINQ, if you don't expect the general structure of the document to change.

```<code>var publicKey = (string)xDoc.Root.Element("PublicKey");
var agentGuid = (Guid)xDoc.Root.Element("AgentGUID");
</code>```

If you know there's only one instance of a given tag, it's less trouble to just go get that instance than to call a method that selects all tags with a given name, and then extract a single value from the resulting IEnumerable<>.

However, your original code was almost right.

```<code>    IEnumerable<string> publicKeys =
        from item in xDoc.Descendants("PublicKey")
        select (string)item;
</code>```

But then you'd have to follow that up with:

```<code>    string publicKey = publicKeys.First();
</code>```

The XElement type defines custom conversion operators for many different primitive types. It has a Value property that returns a string, so you could use that and not have any cast at all if a string is what you want - but often it's more convenient to just cast an XElement containing a value directly to the data type you want.

Update

If you need an XmlDocument you can convert an XDocument like this...

```<code>var doc = new XmlDocument();
doc.Load(xDoc.CreateReader());
</code>```

However, it's probably more efficient to just use an XmlDocument to begin with, even if it's less convenient. One way to get the same values from an XmlDocument is like this:

```<code>var publicKey = doc.GetElementsByTagName("PublicKey")[0].InnerText;
var agentGuid = new Guid(doc.GetElementsByTagName("AgentGUID")[0].InnerText);
</code>```

ContentLicense: CC BY-SA 2.5

Title: Linq to select property from XML

Body:
This is my first day working with XML in the context of XPath, XQuery, and Linq, and I can't get any of them to work for me.

My goal is to extract values for AgentGUID and PublicKey in a XML blob.  The Linq query I'm using is below.

        IEnumerable<string> publicKey =
            from item in xDoc.Descendants("PublicKey")
            select (string)item.????;

Here is the XML I'm trying to select from:

<AgentRegister xmlns="sampleURI">
server
<Servername>server</Servername>
<AgentGUID>1da3a4cf-73f2-4ee2-b8c1-cef428ad4b21</AgentGUID>
<PublicKey><RSAKeyValue><Modulus>5fuiFE74EKYUxFbSsAgeYQwyGzulQ+L1auBD1J/1gupF2s2NugpgZ6vqsi4o//vKdrKz7uhwDWeRUB5TR7hljNfOsJKbTV0sg4HywF93cyYDnfKz+2wCSxiZxAIWV8SMiui2QuD0LjbgPNGR/bBsY4GIl3eWbngjJjNEzVZq5RE=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue></PublicKey>
<ApprovedByGUID><RSAKeyValue><Modulus>5fuiFE74EKYUxFbSsAgeYQwyGzulQ+L1auBD1J/1gupF2s2NugpgZ6vqsi4o//vKdrKz7uhwDWeRUB5TR7hljNfOsJKbTV0sg4HywF93cyYDnfKz+2wCSxiZxAIWV8SMiui2QuD0LjbgPNGR/bBsY4GIl3eWbngjJjNEzVZq5RE=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue></ApprovedByGUID>
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
<Reference URI="">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" /></Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<DigestValue>2HuOAQAAxOTWz2JSq9+bJnWM8m8=</DigestValue></Reference>
</SignedInfo>
<SignatureValue>yGKq/p/JQCWSJtVKeRp4E5kHeFWVaoMFd/TbrYIm6k3nYBgr57gcEZjzvrLNsmKKaoaWspSqMzTDnrhER5AkfMi+4nhW0C6+vghNYU/jrEqT35Ov/B3aH1M41q07p3OXZc8dA1lzJ6Zh0zpx6Vd7faTfvuPqgIKmNOe07xGyP2Q=</SignatureValue>
<KeyInfo><KeyValue><RSAKeyValue>
<Modulus>5fuiFE74EKYUxFbSsAgeYQwyGzulQ+L1auBD1J/1gupF2s2NugpgZ6vqsi4o//vKdrKz7uhwDWeRUB5TR7hljNfOsJKbTV0sg4HywF93cyYDnfKz+2wCSxiZxAIWV8SMiui2QuD0LjbgPNGR/bBsY4GIl3eWbngjJjNEzVZq5RE=</Modulus>
<Exponent>AQAB</Exponent></RSAKeyValue></KeyValue></KeyInfo>
</Signature>
</AgentRegister>

How do I extract the mentioned values from this document?

Body:
I would do it using XDocument but without LINQ, if you don't expect the general structure of the document to change.

var publicKey = (string)xDoc.Root.Element("PublicKey");
var agentGuid = (Guid)xDoc.Root.Element("AgentGUID");

If you know there's only one instance of a given tag, it's less trouble to just go get that instance than to call a method that selects all tags with a given name, and then extract a single value from the resulting IEnumerable<>.

However, your original code was almost right.

    IEnumerable<string> publicKeys =
        from item in xDoc.Descendants("PublicKey")
        select (string)item;

But then you'd have to follow that up with:

    string publicKey = publicKeys.First();

The XElement type defines custom conversion operators for many different primitive types. It has a Value property that returns a string, so you could use that and not have any cast at all if a string is what you want - but often it's more convenient to just cast an XElement containing a value directly to the data type you want.

Update

If you need an XmlDocument you can convert an XDocument like this...

var doc = new XmlDocument();
doc.Load(xDoc.CreateReader());

However, it's probably more efficient to just use an XmlDocument to begin with, even if it's less convenient. One way to get the same values from an XmlDocument is like this:

var publicKey = doc.GetElementsByTagName("PublicKey")[0].InnerText;
var agentGuid = new Guid(doc.GetElementsByTagName("AgentGUID")[0].InnerText);


问:
dictionary with assigned value raises referenced before assignment error
I need to write a code that is supposed to put items from a dictionary in a list and sort them either after the key or the value. This is the code I came up with:

```<code>import copy
dict_ip_attempts = {"180.237.210.112": 9, "180.237.210.54": 5,
                     "180.237.210.13": 2, "180.237.210.30": 5}

d=copy.deepcopy(dict_ip_attempts)
ip_adress=[]
for key in dict_ip_attempts:
    var=key.split(".")
    ip_adress.append(int("".join(var)))

ip_adress.sort()

def sortip_adress():
    output=[0]*(len(ip_adress))
    for key in dict_ip_attempts:
        var=key.split(".")
        for i in range(len(ip_adress)):
            if int("".join(var)) == ip_adress[i]:
                output[i]=((key, dict_ip_attempts[key]))
    return output

def sortattempts():
    output=[]
    for key in dict_ip_attempts:
        if dict_ip_attempts[key]==min(dict_ip_attempts.values()):
            output.append((key, dict_ip_attempts[key]))
            dict_ip_attempts.pop(key)
    dict_ip_attempts=copy.deepcoy(d)
    return output

print("The dictionary sorted after the ip_adresses is:", sortip_adress())
print("The dictionary sorted after the attempts is:", sortattempts())
</code>```

The function sortip_adress() works just fine, but the sortattempts() function doesn't. When python reaches line 30 it prints: UnboundLocalError: local variable 'dict_ip_attempts' referenced before assignment

line 30 is this one:

```<code>for key in dict_ip_attempts:
</code>```

I don't understand why I get this error, since I defined dict_ip_attempts in line 2. Can someone explain it to me please?

答: Add global dict_ip_attempts as a line just under both of your function declarations since it is a global variable. Also popping a value from a dictionary in a for key in dictionary loop is a bad idea (as Wondercricket mentioned). It shouldn't be necessary, but if you need to empty the dictionary just do it after the loop is done with dict_ip_attempts = {}

Body:
I need to write a code that is supposed to put items from a dictionary in a list and sort them either after the key or the value. This is the code I came up with:

import copy
dict_ip_attempts = {"180.237.210.112": 9, "180.237.210.54": 5,
                     "180.237.210.13": 2, "180.237.210.30": 5}

d=copy.deepcopy(dict_ip_attempts)
ip_adress=[]
for key in dict_ip_attempts:
    var=key.split(".")
    ip_adress.append(int("".join(var)))

ip_adress.sort()

def sortip_adress():
    output=[0]*(len(ip_adress))
    for key in dict_ip_attempts:
        var=key.split(".")
        for i in range(len(ip_adress)):
            if int("".join(var)) == ip_adress[i]:
                output[i]=((key, dict_ip_attempts[key]))
    return output

def sortattempts():
    output=[]
    for key in dict_ip_attempts:
        if dict_ip_attempts[key]==min(dict_ip_attempts.values()):
            output.append((key, dict_ip_attempts[key]))
            dict_ip_attempts.pop(key)
    dict_ip_attempts=copy.deepcoy(d)
    return output

print("The dictionary sorted after the ip_adresses is:", sortip_adress())
print("The dictionary sorted after the attempts is:", sortattempts())

The function sortip_adress() works just fine, but the sortattempts() function doesn't. When python reaches line 30 it prints: UnboundLocalError: local variable 'dict_ip_attempts' referenced before assignment

line 30 is this one:

for key in dict_ip_attempts:

I don't understand why I get this error, since I defined dict_ip_attempts in line 2. Can someone explain it to me please?


问:
How to Return Counts of Values in Pandas
I have a dataframe that contains a unqiue IP, and a Severity rating based on a scan result classifier, as shown:

My objective: for each unique IP, how do I return a count for each Severity level?  The goal is to ultimately create a table that lists each IPs totals for each level of Severity.

I already know how to get hits for the Totals column. That is as simple as:

```<code>df_IP_counts = df['IP'].value_counts()

or

df_Severity_counts =df.Severity.value_counts()
</code>```

But how to separate each individual IP's counts for CRITICAL, HIGH, MODERATE, and LOW is giving me trouble at the moment.

Thank you.

答:
You could call groupby + count -

```<code>result = df.groupby(['IP', 'Severity']).Severity.count().unstack()
</code>```

To get the total count, you can call sum on the values and use assign/concat/inplace assignment to add it to the result dataframe -

```<code>result['Total'] = result.values.sum(axis=1)
</code>```

Body:
I have a dataframe that contains a unqiue IP, and a Severity rating based on a scan result classifier, as shown:

My objective: for each unique IP, how do I return a count for each Severity level?  The goal is to ultimately create a table that lists each IPs totals for each level of Severity.

I already know how to get hits for the Totals column. That is as simple as:

df_IP_counts = df['IP'].value_counts()

or

df_Severity_counts =df.Severity.value_counts()

But how to separate each individual IP's counts for CRITICAL, HIGH, MODERATE, and LOW is giving me trouble at the moment.

Thank you.

Body:
You could call groupby + count -

result = df.groupby(['IP', 'Severity']).Severity.count().unstack()

To get the total count, you can call sum on the values and use assign/concat/inplace assignment to add it to the result dataframe -

result['Total'] = result.values.sum(axis=1)


问:
Speed up CoreNLP Sentiment Analysis
Can anybody think of a way to speed up my CoreNLP Sentiment Analysis (below)?

I initialize the CoreNLP pipeline once on server startup:

```<code>// Initialize the CoreNLP text processing pipeline
public static Properties props = new Properties();
public static StanfordCoreNLP pipeline;

// Set text processing pipeline's annotators
props.setProperty("annotators", "tokenize, ssplit, pos, parse, sentiment");
// Use Shift-Reduce Constituency Parsing (O(n),
// http://nlp.stanford.edu/software/srparser.shtml) vs CoreNLP's default
// Probabilistic Context-Free Grammar Parsing (O(n^3))
props.setProperty("parse.model", "edu/stanford/nlp/models/srparser/englishSR.ser.gz");
pipeline = new StanfordCoreNLP(props);
</code>```

Then I call the pipeline from my Controller:

```<code>String text = 'A sample string.'
Annotation annotation = pipeline.process(text);
List<CoreMap> sentences = annotation.get(CoreAnnotations.SentencesAnnotation.class);
for (CoreMap sentence : sentences) {
    Tree tree = sentence.get(SentimentCoreAnnotations.SentimentAnnotatedTree.class);
    int sentiment = RNNCoreAnnotations.getPredictedClass(tree);
    ...
}
</code>```

I've profiled the code -- the line Annotation annotation = pipeline.process(text), which is CoreNLP's main processing call, is very slow. A request with 100 calls to my controller takes an average of 1.07 seconds. The annotation is taking ~7ms per call. I need to reduce that to ~2ms.

I can't remove any of the annotators because sentiment relies on all of them. I'm already using the Shift-Reduce Constituency Parser because it is much faster than the default Context-Free Grammar Parser.

Are there any other parameters I can tune to significantly speed this up?

答:
Having the same issue. I've also tried the SR Beam, which was even slower than the PCFG! Based on Stanford benchmarks, SR Beam should be much faster than PCFG, and only slightly slower than SR.

I guess other than using the SR parser instead of the PCFG, the only remaining way to improve the speed might be playing with the tokenizer options...

Title: Speed up CoreNLP Sentiment Analysis

Body:
Can anybody think of a way to speed up my CoreNLP Sentiment Analysis (below)?

I initialize the CoreNLP pipeline once on server startup:

// Initialize the CoreNLP text processing pipeline
public static Properties props = new Properties();
public static StanfordCoreNLP pipeline;

// Set text processing pipeline's annotators
props.setProperty("annotators", "tokenize, ssplit, pos, parse, sentiment");
// Use Shift-Reduce Constituency Parsing (O(n),
// http://nlp.stanford.edu/software/srparser.shtml) vs CoreNLP's default
// Probabilistic Context-Free Grammar Parsing (O(n^3))
props.setProperty("parse.model", "edu/stanford/nlp/models/srparser/englishSR.ser.gz");
pipeline = new StanfordCoreNLP(props);

Then I call the pipeline from my Controller:

String text = 'A sample string.'
Annotation annotation = pipeline.process(text);
List<CoreMap> sentences = annotation.get(CoreAnnotations.SentencesAnnotation.class);
for (CoreMap sentence : sentences) {
    Tree tree = sentence.get(SentimentCoreAnnotations.SentimentAnnotatedTree.class);
    int sentiment = RNNCoreAnnotations.getPredictedClass(tree);
    ...
}

I've profiled the code -- the line Annotation annotation = pipeline.process(text), which is CoreNLP's main processing call, is very slow. A request with 100 calls to my controller takes an average of 1.07 seconds. The annotation is taking ~7ms per call. I need to reduce that to ~2ms.

I can't remove any of the annotators because sentiment relies on all of them. I'm already using the Shift-Reduce Constituency Parser because it is much faster than the default Context-Free Grammar Parser.

Are there any other parameters I can tune to significantly speed this up?


问:
Curl command with option -d issue
Trying to send some data via API call (curl) but having issue with the format of the curl command:

```<code>serviceMsg="$(cat /tmp/response_time)"
perfData=$(/bin/echo "${serviceMsg}" | /bin/sed 's/,//g')

        StatusCode=0

curl -k -s -v -u user:password -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/process-check-result?service=ExternalURL!ResponseTime' -d "{ \"exit_status\": $StatusCode, \"plugin_output\": \"${perfData}\", \"performance_data\": [ ${perfData} ]}"
</code>```

Here is the error I am getting:

```<code>* Connection #0 to host localhost left intact
{
    "error": 400.0,
    "status": "Invalid request body: Error: lexical error: invalid character inside string.\n                                        { \"exit_status\": 0, \"plugin_ou\n                     (right here) ------^\n\n"
}
</code>```

what I am missing ?

答:
Don't hand-code JSON: use jq to generate it for you:

```<code>perfData=$(sed 's/,//g' /tmp/response_time)

json=$(jq -n --arg sc "$StatusCode" --arg pd "$perfData" \
        '{exit_status: $sc, plugin_output: $pd, performance_data: [ $pd ]}')

url='https://localhost:5665/v1/actions/process-check-result?service=ExternalURL!ResponseTime'

curl -ksv -u user:password -H 'Accept: application/json' -X POST -d "$json" "$url"
</code>```

Title: Curl command with option -d issue

Body:
Trying to send some data via API call (curl) but having issue with the format of the curl command:

serviceMsg="$(cat /tmp/response_time)"
perfData=$(/bin/echo "${serviceMsg}" | /bin/sed 's/,//g')

        StatusCode=0

curl -k -s -v -u user:password -H 'Accept: application/json' -X POST 'https://localhost:5665/v1/actions/process-check-result?service=ExternalURL!ResponseTime' -d "{ \"exit_status\": $StatusCode, \"plugin_output\": \"${perfData}\", \"performance_data\": [ ${perfData} ]}"

Here is the error I am getting:

* Connection #0 to host localhost left intact
{
    "error": 400.0,
    "status": "Invalid request body: Error: lexical error: invalid character inside string.\n                                        { \"exit_status\": 0, \"plugin_ou\n                     (right here) ------^\n\n"
}

what I am missing ?

Body:
Don't hand-code JSON: use jq to generate it for you:

perfData=$(sed 's/,//g' /tmp/response_time)

json=$(jq -n --arg sc "$StatusCode" --arg pd "$perfData" \
        '{exit_status: $sc, plugin_output: $pd, performance_data: [ $pd ]}')

url='https://localhost:5665/v1/actions/process-check-result?service=ExternalURL!ResponseTime'

curl -ksv -u user:password -H 'Accept: application/json' -X POST -d "$json" "$url"


问:
Get text before the last br in div jquery
Hi Guys i have this in html

```<code><div class="flexmls_connect__sr_address">
  <div class="flexmls_connect__ld_price">$9,000,000</div>
  Km. 16.5 Carr. Barra de Navidad, Villa Armonia Estate
  <br>
  Puerto Vallarta, JA
  <br>MLS# 11187
  <br>//NEED THIS NUMBER---- >5 beds  |  //AND THIS NUMBER---- >8 baths  |  11836 sqft
  <br>
</div>
</code>```

and this in jquery

```<code>    var baths = $(res).find('.flexmls_connect__sr_address').before('br').last().contents().filter(function() {
        return this.nodeType == 3;
    }).text();
</code>```

I need obtain the beds and baths, and for clearify not is my html code i obtain from a very old API and i cant change the HTML, i neee that values with only jquery or javascript. not neccesary with my answer all methos are welcome i only try many of theme and the last is get text before last tag br but any help is great, thanks :D

答:
before() is a dom insertion method. Can do something like the following

var specs = $('.flexmls_connect__sr_address').contents().filter(function() {
    return this.nodeType == 3 && $(this).text().indexOf('beds')>-1;
}).text().split('|').reduce(function(a,c){
    if(c.indexOf('beds')>-1){
        a.beds = /\d+/.exec(c)[0]
    }else if(c.indexOf('baths')>-1){
        a.baths = /\d+/.exec(c)[0]
    }
    return a
},{});

console.log(specs);
console.log('Property has ', specs.baths, ' baths and ', specs.beds, ' beds');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="flexmls_connect__sr_address">
  <div class="flexmls_connect__ld_price">$9,000,000</div>
  Km. 16.5 Carr. Barra de Navidad, Villa Armonia Estate
  <br>
  Puerto Vallarta, JA
  <br>MLS# 11187
  <br>5 beds  |  8 baths  |  11836 sqft
  <br>
</div></code>```

Body:
Hi Guys i have this in html

$9,000,000

  Km. 16.5 Carr. Barra de Navidad, Villa Armonia Estate

  Puerto Vallarta, JA

MLS# 11187

//NEED THIS NUMBER---- >5 beds  |  //AND THIS NUMBER---- >8 baths  |  11836 sqft

and this in jquery

    var baths = $(res).find('.flexmls_connect__sr_address').before('br').last().contents().filter(function() {
        return this.nodeType == 3;
    }).text();

I need obtain the beds and baths, and for clearify not is my html code i obtain from a very old API and i cant change the HTML, i neee that values with only jquery or javascript. not neccesary with my answer all methos are welcome i only try many of theme and the last is get text before last tag br but any help is great, thanks :D

Body:
before() is a dom insertion method. Can do something like the following

var specs = $('.flexmls_connect__sr_address').contents().filter(function() {
    return this.nodeType == 3 && $(this).text().indexOf('beds')>-1;
}).text().split('|').reduce(function(a,c){
    if(c.indexOf('beds')>-1){
        a.beds = /\d+/.exec(c)[0]
    }else if(c.indexOf('baths')>-1){
        a.baths = /\d+/.exec(c)[0]
    }
    return a
},{});

console.log(specs);
console.log('Property has ', specs.baths, ' baths and ', specs.beds, ' beds');

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="flexmls_connect__sr_address">
  <div class="flexmls_connect__ld_price">$9,000,000</div>
  Km. 16.5 Carr. Barra de Navidad, Villa Armonia Estate
  <br>
  Puerto Vallarta, JA
  <br>MLS# 11187
  <br>5 beds &nbsp;|&nbsp; 8 baths &nbsp;|&nbsp; 11836 sqft
  <br>
</div>


问:
Add a default value to form submission in Laravel
In my controller I've got the destination columns and the origin fields for specific data entered in my create function. However, I've got a few default values in here, like below:

```<code>    $shipment->shipment_billing_status = 1;
    $shipment->created_by = $user_id;
    $shipment->cn_billtoName = request('cn_billtoName');
</code>```

As you can see $shipment->shipment_billing_status default value should always be 1. However, in extreme cases, I would like a user to be able to choose (if they need to) between two checkboxes, titled "No Settle" and "No Charge", or their values being 2 and 3.

So in those extreme cases, I want a record to absolutely go to 1 if the "No Settle" or "No Charge" checkboxes aren't selected.

答:
Go to your shipment model and add this line

$table->integer('Billing_status')->default(1);```
</div>
</div>
</p>

<p>Refresh your migration.</p>

<p>Add this to your view</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="form-group">
        {!! Form::label('Billing_status','Status:') !!}
        {!! Form::select('Billing_status',[1=>'shipment_billing_status',2=>'No Settle', 3=>No chare],null,['class'=>'form-control']) !!}

    </div></code>```

This will default shipment_billing_status to 1, if none is selected.
I hope this answers your question.
@Matthew did you try this?

Body:
In my controller I've got the destination columns and the origin fields for specific data entered in my create function. However, I've got a few default values in here, like below:

    $shipment->shipment_billing_status = 1;
    $shipment->created_by = $user_id;
    $shipment->cn_billtoName = request('cn_billtoName');

As you can see $shipment->shipment_billing_status default value should always be 1. However, in extreme cases, I would like a user to be able to choose (if they need to) between two checkboxes, titled "No Settle" and "No Charge", or their values being 2 and 3.

So in those extreme cases, I want a record to absolutely go to 1 if the "No Settle" or "No Charge" checkboxes aren't selected.

Body:
Go to your shipment model and add this line

$table->integer('Billing_status')->default(1);

Refresh your migration.

Add this to your view

<div class="form-group">
        {!! Form::label('Billing_status','Status:') !!}
        {!! Form::select('Billing_status',[1=>'shipment_billing_status',2=>'No Settle', 3=>No chare],null,['class'=>'form-control']) !!}

    </div>

This will default shipment_billing_status to 1, if none is selected.
I hope this answers your question.
@Matthew did you try this?


问:
How to find strings within a text file in JAVA
I'd like to just see an example with some explanation.
What string functions do I use to compare the objects and does it compare each character or the actual word without any additional letters to it?

Thanks

答:
I tried doing something very similar to this question for a project awhile ago.  There are numerous ways to do this in Java, but I used the Scanner class and the File class.

```<code>public static void main(String[] args)
{
    Scanner input = new Scanner(System.in);      //Just a normal scanner

    System.out.println("Please enter in the pathname to the file you want to view.");
    String pathname = input.nextLine();          //Pathname to text file
    File book = new File(pathname);              //Creating a new file using the pathname

    if(book.canRead() == false)                  //If Java cant read the file, this will pop up
    {
        System.out.println("Your file cannot be read");
    }
    else if(book.canRead() == true)              //If Java can read the file, then this asks for the word to search for
    {
        System.out.println("Please enter in the word you wish to search for.");
        wordToSearchFor = input.nextLine();

        wordCounter(book);                        //Calls the method
  }

  System.out.println(wordToSearchFor.toLowerCase() + " appeared " + numOfOccurrences + " times in " + pathname);

}
</code>```

This is the main method where you use the File class to create a file based off  of a pathname that you give it EX - C:\Users\alex\Downloads\mobydick.txt
I then check to see if you can read the file, and if you can, then I call a method to analyze the book itself

```<code>import java.io.*;
import java.util.Scanner;

public class TextReader
{
    private static int numOfOccurrences;         //Counter to keep track of the number of occurances
    private static String wordToSearchFor;       //String field so both methods can access it

    /*
    * This method takes in the file of the book so the scanner can look at it
    * and then does all of the calculating to see if the desired word appears,
    * and how many times it does appear if it does appear
    */

    public static void wordCounter(File bookInput)
    {
        try
        {
            Scanner bookAnalyzer = new Scanner(bookInput);     //Scanner for the book

            while(bookAnalyzer.hasNext())                      //While the scanner has something to look at next
            {
                String wordInLine = bookAnalyzer.next();        //Create a string for the next word

                wordInLine = wordInLine.toLowerCase();          //Make it lowercase
                String wordToSearchForLowerCase = wordToSearchFor.toLowerCase();
                String wordToSearchForLowerCasePeriod = wordToSearchForLowerCase + ".";

                if(wordInLine.indexOf(wordToSearchForLowerCase) != -1 && wordInLine.length() == wordToSearchFor.length())
                {
                    numOfOccurrences++;
                }
                else if(wordInLine.indexOf(wordToSearchForLowerCasePeriod) != -1 && wordInLine.length() == wordToSearchForLowerCasePeriod.length())
                {
                    numOfOccurrences++;
                }
            }
        }

        catch(FileNotFoundException e)               //Self explanitory
        {
            System.out.println("The error is FileNotFoundException - " + e);
            System.out.println("This should be impossible to get to because error checking is done before this step.");
        }
    }
</code>```

Scanners in Java can be take a File object to analyze, which is the fist thing I do in this method.  I then use a while loop and ask the Scanner if there is a word that follows the current word.  As long as there is a word, this will continue to run.  I then create a String of the current word that the scanner is on to use as a reference to compare against.  I then use a method that comes with the String class to make everything lowercase because uppercase and lowercase letters matter.

The first if statement in this method checks if the current word that the scanner has matches what you are searching for using the indexOf method from the String class, which takes some string and looks to see if it exists in another string.  The if statement comparison also makes sure that the desired word length is the same as the word length in the book in case you are looking up "the" and it doesnt mark "then" as a word since it contains "the".  The second if statement does the same thing, just with your desired word with a period at the end.  If you wanted to go the extra mile, you could also check for exclamation points, question marks, commas, and so forth, but I decided to just check for periods.

Every time one of these if statements is correct, I increment a variable by one, and after the scanner runs out of words to search for, I print out the total number of times that certain word appears in a text file.

Body:
I tried doing something very similar to this question for a project awhile ago.  There are numerous ways to do this in Java, but I used the Scanner class and the File class.

public static void main(String[] args)
{
    Scanner input = new Scanner(System.in);      //Just a normal scanner

    System.out.println("Please enter in the pathname to the file you want to view.");
    String pathname = input.nextLine();          //Pathname to text file
    File book = new File(pathname);              //Creating a new file using the pathname

    if(book.canRead() == false)                  //If Java cant read the file, this will pop up
    {
        System.out.println("Your file cannot be read");
    }
    else if(book.canRead() == true)              //If Java can read the file, then this asks for the word to search for
    {
        System.out.println("Please enter in the word you wish to search for.");
        wordToSearchFor = input.nextLine();

        wordCounter(book);                        //Calls the method
  }

  System.out.println(wordToSearchFor.toLowerCase() + " appeared " + numOfOccurrences + " times in " + pathname);

}

This is the main method where you use the File class to create a file based off  of a pathname that you give it EX - C:\Users\alex\Downloads\mobydick.txt
I then check to see if you can read the file, and if you can, then I call a method to analyze the book itself

import java.io.*;
import java.util.Scanner;

public class TextReader
{
    private static int numOfOccurrences;         //Counter to keep track of the number of occurances
    private static String wordToSearchFor;       //String field so both methods can access it

    /*
    * This method takes in the file of the book so the scanner can look at it
    * and then does all of the calculating to see if the desired word appears,
    * and how many times it does appear if it does appear
    */

    public static void wordCounter(File bookInput)
    {
        try
        {
            Scanner bookAnalyzer = new Scanner(bookInput);     //Scanner for the book

            while(bookAnalyzer.hasNext())                      //While the scanner has something to look at next
            {
                String wordInLine = bookAnalyzer.next();        //Create a string for the next word

                wordInLine = wordInLine.toLowerCase();          //Make it lowercase
                String wordToSearchForLowerCase = wordToSearchFor.toLowerCase();
                String wordToSearchForLowerCasePeriod = wordToSearchForLowerCase + ".";

                if(wordInLine.indexOf(wordToSearchForLowerCase) != -1 && wordInLine.length() == wordToSearchFor.length())
                {
                    numOfOccurrences++;
                }
                else if(wordInLine.indexOf(wordToSearchForLowerCasePeriod) != -1 && wordInLine.length() == wordToSearchForLowerCasePeriod.length())
                {
                    numOfOccurrences++;
                }
            }
        }

        catch(FileNotFoundException e)               //Self explanitory
        {
            System.out.println("The error is FileNotFoundException - " + e);
            System.out.println("This should be impossible to get to because error checking is done before this step.");
        }
    }

Scanners in Java can be take a File object to analyze, which is the fist thing I do in this method.  I then use a while loop and ask the Scanner if there is a word that follows the current word.  As long as there is a word, this will continue to run.  I then create a String of the current word that the scanner is on to use as a reference to compare against.  I then use a method that comes with the String class to make everything lowercase because uppercase and lowercase letters matter.

The first if statement in this method checks if the current word that the scanner has matches what you are searching for using the indexOf method from the String class, which takes some string and looks to see if it exists in another string.  The if statement comparison also makes sure that the desired word length is the same as the word length in the book in case you are looking up "the" and it doesnt mark "then" as a word since it contains "the".  The second if statement does the same thing, just with your desired word with a period at the end.  If you wanted to go the extra mile, you could also check for exclamation points, question marks, commas, and so forth, but I decided to just check for periods.

Every time one of these if statements is correct, I increment a variable by one, and after the scanner runs out of words to search for, I print out the total number of times that certain word appears in a text file.


问:
How to see documentation of inbuilt functions on Jupyter Notebook?
I recently researched about finding documentation of any inbuilt python library's function within a cell of Jupyter Notebook. Any suggestion how I can access the documentation?. I know keyboard shortcut which is shift + tab, and with 4 times shift + tab, whole documentation with example pops up. I am just wondering the usual way, apart from shortcut.

答:
The documentation comes from the docstring in the Python code.

You can see it by calling help, and the __doc__ attribute returns the string.

Taking the built-in filter as example:

```<code># Displays the documentation for filter function
help(filter)
# Obtains the string of the documentation.
docstring = filter.__doc__
</code>```

Body:
The documentation comes from the docstring in the Python code.

You can see it by calling help, and the __doc__ attribute returns the string.

Taking the built-in filter as example:

# Displays the documentation for filter function
help(filter)
# Obtains the string of the documentation.
docstring = filter.__doc__


答:
If you HTML follows the same format as in the example then you can achieve your goal by selecting the inner HTML of each div.flexmls_connect__sr_address block, and using split() at each
.  The text you need is always going to be the second last item in that list, and this in turn can be split() at each  |  like so...

```<code>$('.flexmls_connect__sr_address').each(function() {
    // get innerHTML and split into array
    var block = $(this).html().split('<br>');

    // split second-last line into array
    var line = block[block.length - 2].split(' | ');

    // report to console
    console.log(' beds:',line[0].trim());
    console.log('baths:',line[1].trim());
    console.log(' sqft:',line[2].trim());
    console.log('----');
});
</code>```

As mentioned elsewhere, you can then use regular expressions to grab just the number from each item in line as needed. I.E..

```<code>var beds = line[0].replace(/\D+/g, "");
</code>```

Hope that helps. :)

Title: Get text before the last br in div jquery

Body:
If you HTML follows the same format as in the example then you can achieve your goal by selecting the inner HTML of each div.flexmls_connect__sr_address block, and using split() at each <br>.  The text you need is always going to be the second last item in that list, and this in turn can be split() at each &nbsp;|&nbsp; like so...

$('.flexmls_connect__sr_address').each(function() {
    // get innerHTML and split into array
    var block = $(this).html().split('<br>');

    // split second-last line into array
    var line = block[block.length - 2].split('&nbsp;|&nbsp;');

    // report to console
    console.log(' beds:',line[0].trim());
    console.log('baths:',line[1].trim());
    console.log(' sqft:',line[2].trim());
    console.log('----');
});

As mentioned elsewhere, you can then use regular expressions to grab just the number from each item in line as needed. I.E..

var beds = line[0].replace(/\D+/g, "");

Hope that helps. :)


问:
TeamCity - how to get currently running builds via REST API?
Does anyone know how to use the TeamCity REST API to find out which builds are currently running, and how far through they are (elapsed time vs estimated time)?</p>

答:
I did a little digging and a post on JetBrain's site stating that support for the running:true was actually added for TC6. TeamCity 5.X REST documentation just links to a different page which doesn't specify what was supported in TC5 and what is new to TC6.

EDIT: Hey Matt, I posted a question inquiring about REST documentation specific to TC 5.X. I know it would be very handy for me to know what exactly what I can do with REST for the version of TeamCity I am using and thought it may interest you as well!

ContentLicense: CC BY-SA 4.0


问:
Difficulty calling method from Hang Fire
I have a controller method which is responsible for scheduling appointments. I'm looking to schedule a task to remind the user via SMS (twilio) 5 minutes before their appointment to login to the service.

Here is my method call:

```<code>private SMSNotifier sms = new SMSNotifier();
 BackgroundJob.Schedule( () => sms.SendPatientUpcomingApptNotificationTest(appointment), appointment.Start.AddMinutes(-5));
</code>```

and here is my class:

```<code>public SMSNotifier()
    {
        var accountSid = ConfigurationManager.AppSettings["TwilioSid"];
        // Your Auth Token from twilio.com/console
        var authToken = ConfigurationManager.AppSettings["TwilioToken"]; ;

        TwilioClient.Init(accountSid, authToken);
    }

    public void SendPatientUpcomingApptNotificationTest(Appointment appt)
    {

            var message = MessageResource.Create(
        to: new PhoneNumber("+xxxxxxxxxx"),
        from: new PhoneNumber("+xxxxxxxxxx"),
        body: string.Format("Hello {0} {1}! You have an upcoming web based video appointment with xxxxxxxxxx. Please login to the website to be seen. Your appointment time is: {2} Thank you - xxxxxxxx", "xxxxxxx", "xxxxxxxx", appt.Start));

    }
}
</code>```

I keep getting this error:

```<code>Server Error in '/' Application.

Self referencing loop detected for property 'User' with type 'System.Data.Entity.DynamicProxies.AspNetUser_80E6332CC002F8FCF589159A68E74A0922BEE992586B9FE280D950E149CCC7EB'. Path 'Patient.ActiveSessions[0]'.
</code>```

But I just don't understand why. I don't reference a User object anywhere.

I should mention I obviously googled that error:

JSON.NET Error Self referencing loop detected for type

Self referencing loop detected - Getting back data from WebApi to the browser

∞

None of this provided any progress. I still have the same error.

What do you guys think?

I definitely think it has to do with the way I'm trying to schedule the 'SendPatientUpcomingApptNotificationTest' method. I can do a Console.WriteLine and it queues the job fine.

IE:

```<code>  BackgroundJob.Schedule( () => Console.WriteLine("TestSchedule"), appointment.Start.AddMinutes(-5));
</code>```

Works perfectly

答:
It sounds like it's running into this error when trying to serialize your appointment object.

When you schedule a background job, Hangfire saves info about the method you are calling and its arguments to its job store. If you're passing a complex object as an argument to the method, it attempts to serialize the whole object graph to json.

The recommended approach is to keep your job arguments small and simple. For example, pass an appointmentId to the job instead of the whole appointment:

```<code>BackgroundJob.Schedule( () => sms.SendPatientUpcomingApptNotificationTest(appointmentId), ...);
</code>```

Then you would retrieve the actual appointment within the job.

Body:
I have a controller method which is responsible for scheduling appointments. I'm looking to schedule a task to remind the user via SMS (twilio) 5 minutes before their appointment to login to the service.

Here is my method call:

private SMSNotifier sms = new SMSNotifier();
 BackgroundJob.Schedule( () => sms.SendPatientUpcomingApptNotificationTest(appointment), appointment.Start.AddMinutes(-5));

and here is my class:

public SMSNotifier()
    {
        var accountSid = ConfigurationManager.AppSettings["TwilioSid"];
        // Your Auth Token from twilio.com/console
        var authToken = ConfigurationManager.AppSettings["TwilioToken"]; ;

        TwilioClient.Init(accountSid, authToken);
    }

    public void SendPatientUpcomingApptNotificationTest(Appointment appt)
    {

            var message = MessageResource.Create(
        to: new PhoneNumber("+xxxxxxxxxx"),
        from: new PhoneNumber("+xxxxxxxxxx"),
        body: string.Format("Hello {0} {1}! You have an upcoming web based video appointment with xxxxxxxxxx. Please login to the website to be seen. Your appointment time is: {2} Thank you - xxxxxxxx", "xxxxxxx", "xxxxxxxx", appt.Start));

    }
}

I keep getting this error:

Server Error in '/' Application.

Self referencing loop detected for property 'User' with type 'System.Data.Entity.DynamicProxies.AspNetUser_80E6332CC002F8FCF589159A68E74A0922BEE992586B9FE280D950E149CCC7EB'. Path 'Patient.ActiveSessions[0]'.

But I just don't understand why. I don't reference a User object anywhere.

I should mention I obviously googled that error:

JSON.NET Error Self referencing loop detected for type

Self referencing loop detected - Getting back data from WebApi to the browser

∞

None of this provided any progress. I still have the same error.

What do you guys think?

I definitely think it has to do with the way I'm trying to schedule the 'SendPatientUpcomingApptNotificationTest' method. I can do a Console.WriteLine and it queues the job fine.

IE:

  BackgroundJob.Schedule( () => Console.WriteLine("TestSchedule"), appointment.Start.AddMinutes(-5));

Works perfectly

Body:
It sounds like it's running into this error when trying to serialize your appointment object.

When you schedule a background job, Hangfire saves info about the method you are calling and its arguments to its job store. If you're passing a complex object as an argument to the method, it attempts to serialize the whole object graph to json.

The recommended approach is to keep your job arguments small and simple. For example, pass an appointmentId to the job instead of the whole appointment:

BackgroundJob.Schedule( () => sms.SendPatientUpcomingApptNotificationTest(appointmentId), ...);

Then you would retrieve the actual appointment within the job.


问:
C# Open an excel spreadsheet and read the header column into a string
Hi I am fairly new using Excel spreadsheet in C#. I want to be able to open an excel spread sheet and then read the Header column and save it to a string.

e.g. if my headers are Name, Address, City, State in the Excel spreadsheet

I want the output in a string result = "Name, Address, City, State"

答:
There are numerous libraries out there for parsing Office Documents, but your best bet is to use the OpenXml library as it is both Free and supported by Microsoft:

https://github.com/OfficeDev/Open-XML-SDK
https://www.nuget.org/packages/DocumentFormat.OpenXml

Here is a tutorial for using the library to read Cells in Excel:  https://msdn.microsoft.com/en-us/library/office/hh298534.aspx


问:
Write chat message to Offic 365 Team User
Can I write chat messages to teams users with an api(not channels in teams)?
I would like to forward messages from web based email client to users directly into teams chat with an user and not forward the email.

Best regards
Christoph

答:
This discusses how to start a 1:1 conversation with a user: https://learn.microsoft.com/en-us/microsoftteams/platform/scenarios/bots-personal-conversations#starting-a-11-conversation.

The Featured sample apps for Node.js and C# show how to do it.


问:
How to do Incremental MapReduce in Apache Spark
In CouchDB and system designs like Incoop, there's a concept called "Incremental MapReduce" where results from previous executions of a MapReduce algorithm are saved and used to skip over sections of input data that haven't been changed.

Say I have 1 million rows divided into 20 partitions. If I run a simple MapReduce over this data, I could cache/store the result of reducing each separate partition, before they're combined and reduced again to produce the final result. If I only change data in the 19th partition then I only need to run the map & reduce steps on the changed section of the data, and then combine the new result with the saved reduce results from the unchanged partitions to get an updated result. Using this sort of catching I'd be able to skip almost 95% of the work for re-running a MapReduce job on this hypothetical dataset.

Is there any good way to apply this pattern to Spark? I know I could write my own tool for splitting up input data into partitions, checking if I've already processed those partitions before, loading them from a cache if I have, and then running the final reduce to join all the partitions together. However, I suspect that there's an easier way to approach this.

I've experimented with checkpointing in Spark Streaming, and that is able to store results between restarts, which is almost what I'm looking for, but I want to do this outside of a streaming job.

RDD caching/persisting/checkpointing almost looks like something I could build off of - it makes it easy to keep intermediate computations around and reference them later, but I think cached RDDs are always removed once the SparkContext is stopped, even if they're persisted to disk. So caching wouldn't work for storing results between restarts. Also, I'm not sure if/how checkpointed RDDs are supposed to be loaded when a new SparkContext is started... They seem to be stored under a UUID in the checkpoint directory that's specific to a single instance of the SparkContext.

答:
Both use cases suggested by the article (incremental logs processing and incremental query processing) can be generally solved by Spark Streaming.

The idea is that you have incremental updates coming in using DStreams abstraction. Then, you can process new data, and join it with previous calculation either using time window based processing or using arbitrary stateful operations as part of Structured Stream Processing. Results of the calculation can be later dumped to some sort of external sink like database or file system, or they can be exposed as an SQL table.

If you're not building an online data processing system, regular Spark can be used as well. It's just a matter of how incremental updates get into the process, and how intermediate state is saved. For example, incremental updates can appear under some path on a distributed file system, while intermediate state containing previous computation joined with new data computation can be dumped, again, to the same file system.


问:
Unable to use the web link from the second layout
So I have a simple program that has an image and a button. When the button is clicked, an alert dialog box is opened with a web link.

My problem is getting the web link to work without crashing the app (giving a null object reference error).

I've looked through Layoutinflaters and Fragments, but can't seem to make the program do what I want.

```<code>package com.test.test;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ImageView mShowDialog = findViewById(R.id.btnShowDialog);
    mShowDialog.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
            View mView = getLayoutInflater().inflate(R.layout.info_popup, null);

            mBuilder.setView(mView);
            AlertDialog dialog = mBuilder.create();
            dialog.show();

            //link is null
            TextView link = findViewById(R.id.linkText);
            //Crashes the app before it starts
            link.setMovementMethod(LinkMovementMethod.getInstance());
        }
    });
}
}
</code>```

I believe the error stems from this code, but will provide the xml files on request.

Any help would be greatly appreciated.

答:
A better option would be to link in the XML. You do not appear to be setting it in code, so the above is all unnecessary. Here is an example.

```<code><TextView
                android:id="@+id/lnkHelpInfo"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:gravity="center"
                android:layout_marginTop="25dp"
                android:linksClickable="true"
                android:layout_marginStart="10dp"
                android:layout_marginEnd="10dp"
                android:autoLink="web"
                android:text="https://www.google.com"/>
</code>```

If you prefer to do this in code because you want the text to show something different, then using the linkmethod doesn't really provide you any value. Just make your text underline and blue. Then handle in code.

```<code>Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(myIntent);
</code>```

Body:
So I have a simple program that has an image and a button. When the button is clicked, an alert dialog box is opened with a web link.

My problem is getting the web link to work without crashing the app (giving a null object reference error).

I've looked through Layoutinflaters and Fragments, but can't seem to make the program do what I want.

package com.test.test;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ImageView mShowDialog = findViewById(R.id.btnShowDialog);
    mShowDialog.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
            View mView = getLayoutInflater().inflate(R.layout.info_popup, null);

            mBuilder.setView(mView);
            AlertDialog dialog = mBuilder.create();
            dialog.show();

            //link is null
            TextView link = findViewById(R.id.linkText);
            //Crashes the app before it starts
            link.setMovementMethod(LinkMovementMethod.getInstance());
        }
    });
}
}

I believe the error stems from this code, but will provide the xml files on request.

Any help would be greatly appreciated.

Body:
A better option would be to link in the XML. You do not appear to be setting it in code, so the above is all unnecessary. Here is an example.

<TextView
                android:id="@+id/lnkHelpInfo"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:gravity="center"
                android:layout_marginTop="25dp"
                android:linksClickable="true"
                android:layout_marginStart="10dp"
                android:layout_marginEnd="10dp"
                android:autoLink="web"
                android:text="https://www.google.com"/>

If you prefer to do this in code because you want the text to show something different, then using the linkmethod doesn't really provide you any value. Just make your text underline and blue. Then handle in code.

Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(myIntent);


问:
Understanding how mutable variables behave across different scopes
Newbie to Python here. While practicing working with lists on Codingbat, I realized there are behaviors I don't understand concerning lists and how mutable variables behave. Sample below is derived from a few Codingbat problems to frame my questions...

In getManipulatedNewList(), newnums is destroyed because it goes out of scope (this is correct?), so that's why bobo gets None that first time.

I'm now assuming the only way to ensure I get an actual copy of a list is to create it outside a function--so deepcopying must happen outside the function that manipulates a list, within the same scope where the new list will be used. Correct?

Then what is being passed in the last function below (whatIsThisDoing()--I'm obviously creating a new list with the 1st and last elements of parameter "nums", which I then return immediately. Bobo gets assigned that new list successfully (otherwise arr[0] = 999 would have changed the 1st value in bobo as well).

Why does that work, but getManipulatedNewList() destroys newnums?

Is there any way to pass newnums the same way that anonymous list is returned, so it doesn't get destroyed?

(Or what am I misunderstanding here, please :)

```<code>import copy

def getManipulatedNewList(nums):
    # Create new list
    newnums = copy.deepcopy(nums)

    # For example only; assume many, more complex list manipulations
    # occur here
    newnums = newnums.reverse()

    # Return the newly-created list reference (doesn't work.)
    return newnums

def manipulateList(nums):
    # For example only; assume many, more complex list modifs
    # occur here
    nums = nums.reverse()

    # Nothing to return

def whatIsThisDoing(nums):
    # This actually returns something!
    # Why, though? It's creating the new list in this function too.
    return [nums[0], nums[-1]]

if __name__ == '__main__':
    arr = [1,2,3]
    print(arr)
    print("---")

    bobo = getManipulatedNewList(arr)
    print(arr)  # Shouldn't be touched, as expected
    print(bobo) # newnums was destroyed so bobo is None
    print("---")

    # Is this the only good solution to working with mutable vars?
    bobo = copy.deepcopy(arr)
    manipulateList(bobo)
    print(bobo)

    # Why does this work?
    bobo = whatIsThisDoing(arr)
    print(bobo)
    print("---")

    arr[0] = 999
    print(bobo) # bobo[0] isn't changed, so it's not referencing arr[0]
</code>```

答: No. The reason you get None is because that is what is returned from reverse; that method works in place. The issue has been nothing to do with scope, and the rest of your misunderstandings stem from that.

Body:
Newbie to Python here. While practicing working with lists on Codingbat, I realized there are behaviors I don't understand concerning lists and how mutable variables behave. Sample below is derived from a few Codingbat problems to frame my questions...

In getManipulatedNewList(), newnums is destroyed because it goes out of scope (this is correct?), so that's why bobo gets None that first time.

I'm now assuming the only way to ensure I get an actual copy of a list is to create it outside a function--so deepcopying must happen outside the function that manipulates a list, within the same scope where the new list will be used. Correct?

Then what is being passed in the last function below (whatIsThisDoing()--I'm obviously creating a new list with the 1st and last elements of parameter "nums", which I then return immediately. Bobo gets assigned that new list successfully (otherwise arr[0] = 999 would have changed the 1st value in bobo as well).

Why does that work, but getManipulatedNewList() destroys newnums?

Is there any way to pass newnums the same way that anonymous list is returned, so it doesn't get destroyed?

(Or what am I misunderstanding here, please :)

import copy

def getManipulatedNewList(nums):
    # Create new list
    newnums = copy.deepcopy(nums)

    # For example only; assume many, more complex list manipulations
    # occur here
    newnums = newnums.reverse()

    # Return the newly-created list reference (doesn't work.)
    return newnums

def manipulateList(nums):
    # For example only; assume many, more complex list modifs
    # occur here
    nums = nums.reverse()

    # Nothing to return

def whatIsThisDoing(nums):
    # This actually returns something!
    # Why, though? It's creating the new list in this function too.
    return [nums[0], nums[-1]]

if __name__ == '__main__':
    arr = [1,2,3]
    print(arr)
    print("---")

    bobo = getManipulatedNewList(arr)
    print(arr)  # Shouldn't be touched, as expected
    print(bobo) # newnums was destroyed so bobo is None
    print("---")

    # Is this the only good solution to working with mutable vars?
    bobo = copy.deepcopy(arr)
    manipulateList(bobo)
    print(bobo)

    # Why does this work?
    bobo = whatIsThisDoing(arr)
    print(bobo)
    print("---")

    arr[0] = 999
    print(bobo) # bobo[0] isn't changed, so it's not referencing arr[0]


问:
SO_ATTACH_REUSEPORT_CBPF socket option unexpected behavior
I am trying use a port from two applications and have each of them receive the packet from a different set of IP addresses. In order to achieve this, I use the SO_REUSEPORT and SO_ATTACH_REUSEPORT_CBPF  socket options. My code is as follows:

```<code>parentfd = socket(AF_INET, SOCK_STREAM, 0);
if (parentfd < 0)
  error( "ERROR opening socket");

struct sock_filter code[]={
  { 0x28, 0, 0, 0x0000000c },
  { 0x15, 0, 3, 0x00000800 },
  { 0x20, 0, 0, 0x0000001a },
  { 0x15, 2, 0, 0xc0a8ff01 },
  { 0x6, 0, 0, 0x00000000 },
  { 0x6, 0, 0, 0x00040000 },
  { 0x6, 0, 0, 0x00000001 },
};

struct sock_fprog bpf = {
  .len = ARRAY_SIZE(code),
  .filter = code,
};

if (setsockopt(parentfd, SOL_SOCKET, SO_REUSEPORT, (const void *)&optval,sizeof(optval)))
  error("ERROR setting SO_REUSEPORT");

if (setsockopt(parentfd, SOL_SOCKET, SO_ATTACH_REUSEPORT_CBPF, (const void *)&bpf, sizeof(bpf)))
  error("ERROR setting SO_ATTACH_REUSEPORT_CBPF);
</code>```

I also have a different process that listens to the same port using only the SO_REUSEPORT flag. From a machine with IP 192.168.255.1 I am running echo 1234 | ncat 192.168.255.150 1234. Based on my filter I would expect all traffic from that IP address to be received by the second process. However, it is all received by the first. When I change the filter to a simple:

struct sock_filter code[]={
  { 0x6, 0, 0, 0x00000001 },
};

It works as expected and all packets are received by the second process. Any idea why this might be happening?

答:
I found out what the problem was. The filter is applied to all packets, even the TCP handshake packets. Also, the base pointer points to the first byte of the packet payload, not headers. Hence, when it executes

```<code>ldh[12]
</code>```

it gets out of the limits of the packet (SYN packet has 0 bytes of payload) and the default behavior is to return 0.

Body:
I am trying use a port from two applications and have each of them receive the packet from a different set of IP addresses. In order to achieve this, I use the SO_REUSEPORT and SO_ATTACH_REUSEPORT_CBPF  socket options. My code is as follows:

parentfd = socket(AF_INET, SOCK_STREAM, 0);
if (parentfd < 0)
  error( "ERROR opening socket");

struct sock_filter code[]={
  { 0x28, 0, 0, 0x0000000c },
  { 0x15, 0, 3, 0x00000800 },
  { 0x20, 0, 0, 0x0000001a },
  { 0x15, 2, 0, 0xc0a8ff01 },
  { 0x6, 0, 0, 0x00000000 },
  { 0x6, 0, 0, 0x00040000 },
  { 0x6, 0, 0, 0x00000001 },
};

struct sock_fprog bpf = {
  .len = ARRAY_SIZE(code),
  .filter = code,
};

if (setsockopt(parentfd, SOL_SOCKET, SO_REUSEPORT, (const void *)&optval,sizeof(optval)))
  error("ERROR setting SO_REUSEPORT");

if (setsockopt(parentfd, SOL_SOCKET, SO_ATTACH_REUSEPORT_CBPF, (const void *)&bpf, sizeof(bpf)))
  error("ERROR setting SO_ATTACH_REUSEPORT_CBPF);

I also have a different process that listens to the same port using only the SO_REUSEPORT flag. From a machine with IP 192.168.255.1 I am running echo 1234 | ncat 192.168.255.150 1234. Based on my filter I would expect all traffic from that IP address to be received by the second process. However, it is all received by the first. When I change the filter to a simple:

struct sock_filter code[]={
  { 0x6, 0, 0, 0x00000001 },
};

It works as expected and all packets are received by the second process. Any idea why this might be happening?

Body:
I found out what the problem was. The filter is applied to all packets, even the TCP handshake packets. Also, the base pointer points to the first byte of the packet payload, not headers. Hence, when it executes

ldh[12]

it gets out of the limits of the packet (SYN packet has 0 bytes of payload) and the default behavior is to return 0.


答:
Try this (assuming the information is available after the 3rd "break" tag in div."flexmls_connect__sr_address" :

```<code>document.getElementsByClassName('flexmls_connect__sr_address')[0].getElementsByTagName("br")[2].nextSibling.data.split("|");
</code>```

Here's the response that you would get ["5 beds  ", " 8 baths  ", "  11836 sqft↵  "]

Body:
Try this (assuming the information is available after the 3rd "break" tag in div."flexmls_connect__sr_address" :

document.getElementsByClassName('flexmls_connect__sr_address')[0].getElementsByTagName("br")[2].nextSibling.data.split("|");

Here's the response that you would get ["5 beds  ", " 8 baths  ", "  11836 sqft↵  "]


问:
How to apply an operation to all members of a collection using each element
I would like to apply an operation to each element of a collection, for each element of the collection. I'm looking for something that operates similar to the following:

```<code>result = []
for i in X:
  for j != i in X:
    if j % i == 0 (or whatever condition here)
      result += j
</code>```

I can figure out the part of applying an operation to each element in the collection, but how do I make it use each element in the collection operate against the iterand?

So, for example, if I have 2 3 5 8 How would I get something like 4; ; ;?

答:
I'm guessing you are you trying to solve the problem for Part 2 of Day 3 on adventofcode? If not then I may have interpreted your question incorrectly.

The key is to think whole-array-at-a-time, not item-at-a-time so let's ignore the for i in X:

```<code>   ]jnei=: ~:/~ 2 3 5 8                NB. for j != i in X:
0 1 1 1
1 0 1 1
1 1 0 1
1 1 1 0

   ]dividesExactly=: 0 = |~/~ 2 3 5 8  NB. if j % i == 0
1 0 0 0
0 1 0 0
0 0 1 0
1 0 0 1

   mask=: jnei *. dividesExactly       NB. both conditions
0 0 0 0
0 0 0 0
0 0 0 0
1 0 0 0

   %/~ 2 3 5 8                         NB. divisions to choose from
  1 0.666667 0.4  0.25
1.5        1 0.6 0.375
2.5  1.66667   1 0.625
4  2.66667 1.6     1

   mask * %/~ 2 3 5 8                  NB. evenly divided, off-diagonals
0 0 0 0
0 0 0 0
0 0 0 0
4 0 0 0

   +/ , mask * %/~ 2 3 5 9             NB. ravel and sum to return 4
4
</code>```

I would likely code this as follows:

```<code>   +/ , (%/~ * ~:/~ *. 0 = |~/~) 2 3 5 8
4
</code>```

Body:
I would like to apply an operation to each element of a collection, for each element of the collection. I'm looking for something that operates similar to the following:

result = []
for i in X:
  for j != i in X:
    if j % i == 0 (or whatever condition here)
      result += j

I can figure out the part of applying an operation to each element in the collection, but how do I make it use each element in the collection operate against the iterand?

So, for example, if I have 2 3 5 8 How would I get something like 4; ; ;?

Body:
I'm guessing you are you trying to solve the problem for Part 2 of Day 3 on adventofcode? If not then I may have interpreted your question incorrectly.

The key is to think whole-array-at-a-time, not item-at-a-time so let's ignore the for i in X:

   ]jnei=: ~:/~ 2 3 5 8                NB. for j != i in X:
0 1 1 1
1 0 1 1
1 1 0 1
1 1 1 0

   ]dividesExactly=: 0 = |~/~ 2 3 5 8  NB. if j % i == 0
1 0 0 0
0 1 0 0
0 0 1 0
1 0 0 1

   mask=: jnei *. dividesExactly       NB. both conditions
0 0 0 0
0 0 0 0
0 0 0 0
1 0 0 0

   %/~ 2 3 5 8                         NB. divisions to choose from
  1 0.666667 0.4  0.25
1.5        1 0.6 0.375
2.5  1.66667   1 0.625
4  2.66667 1.6     1

   mask * %/~ 2 3 5 8                  NB. evenly divided, off-diagonals
0 0 0 0
0 0 0 0
0 0 0 0
4 0 0 0

   +/ , mask * %/~ 2 3 5 9             NB. ravel and sum to return 4
4

I would likely code this as follows:

   +/ , (%/~ * ~:/~ *. 0 = |~/~) 2 3 5 8
4


问:
Amazon API Gateway in front of ELB and ECS Cluster
I'm trying to put an Amazon API Gateway in front of an Application Load Balancer, which balances traffic to my ECS Cluster, where all my microservices are deployed. The motivation to use the API Gateway is to use a custom authorizer through a lambda function.

System diagram

In Amazon words (https://aws.amazon.com/api-gateway/faqs/): "Proxy requests to backend operations also need to be publicly accessible on the Internet". This forces me to make the ELB public (internet-facing) instead of internal. Then, I need a way to ensure that only the API Gateway is able to access the ELB outside the VPC.

My first idea was to use a Client Certificate in the API Gatway, but the ELB doesn't seem to support it.

Any ideas would be highly appreciated!

答:
Looks like this support has now been added. Haven't tested, YMMV:

https://aws.amazon.com/about-aws/whats-new/2017/11/amazon-api-gateway-supports-endpoint-integrations-with-private-vpcs/


问:
Fastest way to check if a string matches a regexp in ruby?
What is the fastest way to check if a string matches a regular expression in Ruby?

My problem is that I have to "egrep" through a huge list of strings to find which are the ones that match a regexp that is given at runtime. I only care about whether the string matches the regexp, not where it matches, nor what the content of the matching groups is. I hope this assumption can be used to reduce the amount of time my code spend matching regexps.

I load the regexp with

```<code>pattern = Regexp.new(ptx).freeze
</code>```

I have found that string =~ pattern is slightly faster than string.match(pattern).

Are there other tricks or shortcuts that can used to make this test even faster?

Body:
What is the fastest way to check if a string matches a regular expression in Ruby?

My problem is that I have to "egrep" through a huge list of strings to find which are the ones that match a regexp that is given at runtime. I only care about whether the string matches the regexp, not where it matches, nor what the content of the matching groups is. I hope this assumption can be used to reduce the amount of time my code spend matching regexps.

I load the regexp with

pattern = Regexp.new(ptx).freeze

I have found that string =~ pattern is slightly faster than string.match(pattern).

Are there other tricks or shortcuts that can used to make this test even faster?

Body:
To complete Wiktor Stribiżew and Dougui answers I would say that /regex/.match?("string") about as fast as "string".match?(/regex/).

Ruby 2.4.0 (10 000 000 ~2 sec)

2.4.0 > require 'benchmark'
 => true
2.4.0 > Benchmark.measure{ 10000000.times { /^CVE-[0-9]{4}-[0-9]{4,}$/.match?("CVE-2018-1589") } }
 => #<Benchmark::Tms:0x005563da1b1c80 @label="", @real=2.2060338060000504, @cstime=0.0, @cutime=0.0, @stime=0.04000000000000001, @utime=2.17, @total=2.21>
2.4.0 > Benchmark.measure{ 10000000.times { "CVE-2018-1589".match?(/^CVE-[0-9]{4}-[0-9]{4,}$/) } }
 => #<Benchmark::Tms:0x005563da139eb0 @label="", @real=2.260814556000696, @cstime=0.0, @cutime=0.0, @stime=0.010000000000000009, @utime=2.2500000000000004, @total=2.2600000000000007>

Ruby 2.6.2 (100 000 000 ~20 sec)

irb(main):001:0> require 'benchmark'
=> true
irb(main):005:0> Benchmark.measure{ 100000000.times { /^CVE-[0-9]{4}-[0-9]{4,}$/.match?("CVE-2018-1589") } }
=> #<Benchmark::Tms:0x0000562bc83e3768 @label="", @real=24.60139879199778, @cstime=0.0, @cutime=0.0, @stime=0.010000999999999996, @utime=24.565644999999996, @total=24.575645999999995>
irb(main):004:0> Benchmark.measure{ 100000000.times { "CVE-2018-1589".match?(/^CVE-[0-9]{4}-[0-9]{4,}$/) } }
=> #<Benchmark::Tms:0x0000562bc846aee8 @label="", @real=24.634255946999474, @cstime=0.0, @cutime=0.0, @stime=0.010046, @utime=24.598276, @total=24.608321999999998>

Note: times varies, sometimes /regex/.match?("string") is faster and sometimes "string".match?(/regex/), the differences maybe only due to the machine activity.


问:
Declarative pipeline send email
i need to send a mail notification using jenkins (if it is a success build or someting went wrong)

Right now i have something like that:

```<code>pipeline {
    agent any

...Some stages ...

post {
        success {
            mail to:"someone@hotmail.com", subject:"SUCCESS: ${currentBuild.fullDisplayName}", body: "Yay, we passed."
        }
        failure {
            mail to:"someone@hotmail.com", subject:"FAILURE: ${currentBuild.fullDisplayName}", body: "Boo, we failed."
        }
    }
}
</code>```

But when i execute i get the following error:

```<code>java.net.ConnectException: Connection refused: connect
Caused: javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
  nested exception is:
    java.net.ConnectException: Connection refused: connect
</code>```

I guess i cannot send on the port 25 i need to send it on the port 465.. am i wrong?But i dont know how can i do this.

In most of the examples they use plugins to the jenkins, but i can only use code (declarative pipeline)

suggestions?

答:
Jenkins default email server attempts to run through your localhost on port 25. That error message indicates, as you have guessed, that you need to change the email settings.

To do so, go to Manage Jenkins -> Configure System -> Email Notifcation or Extended Email Notification

As an aside, unless you have an email server running locally (and I'd be surprised if that was the case), changing the local port number won't work. You would need to point it to an external server. Here is a setting page for having Jenkins use the Google SMTP server, for instance

Title: Declarative pipeline send email

Body:
i need to send a mail notification using jenkins (if it is a success build or someting went wrong)

Right now i have something like that:

pipeline {
    agent any

...Some stages ...

post {
        success {
            mail to:"someone@hotmail.com", subject:"SUCCESS: ${currentBuild.fullDisplayName}", body: "Yay, we passed."
        }
        failure {
            mail to:"someone@hotmail.com", subject:"FAILURE: ${currentBuild.fullDisplayName}", body: "Boo, we failed."
        }
    }
}

But when i execute i get the following error:

java.net.ConnectException: Connection refused: connect
Caused: javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
  nested exception is:
    java.net.ConnectException: Connection refused: connect

I guess i cannot send on the port 25 i need to send it on the port 465.. am i wrong?But i dont know how can i do this.

In most of the examples they use plugins to the jenkins, but i can only use code (declarative pipeline)

suggestions?


问:
Can't make executable file with Pyinstaller 3.3 and Python 3.6
I can't get to make an .exe file using Pyinstaller 3.3 and python 3.6, on Windows 10 64bits.

I know all the dependencies are installed because i can run my script without any problems, from the command line.

I checked Pyinstaller page and they say python 3.6 is now supported.

```<code>E:\Fichier\Programming\Python>pyinstaller CheckNewEpisodes.py
371 INFO: PyInstaller: 3.3
372 INFO: Python: 3.6.1
372 INFO: Platform: Windows-10-10.0.15063-SP0
374 INFO: wrote E:\Fichier\Programming\Python\CheckNewEpisodes.spec
376 INFO: UPX is not available.
377 INFO: Extending PYTHONPATH with paths
['E:\\Fichier\\Programming\\Python', 'E:\\Fichier\\Programming\\Python']
377 INFO: checking Analysis
378 INFO: Building Analysis because out00-Analysis.toc is non existent
378 INFO: Initializing module dependency graph...
380 INFO: Initializing module graph hooks...
382 INFO: Analyzing base_library.zip ...
Traceback (most recent call last):
  File "<string>", line 41, in <module>
  File "<string>", line 13, in walk_packages
  File "c:\users\del\appdata\local\programs\python\python36\lib\pkgutil.py", line 127, in iter_modules
    for name, ispkg in iter_importer_modules(i, prefix):
  File "c:\users\del\appdata\local\programs\python\python36\lib\pkgutil.py", line 146, in _iter_file_finder_modules
    import inspect
  File "c:\users\del\appdata\local\programs\python\python36\lib\inspect.py", line 40, in <module>
    import linecache
  File "c:\users\del\appdata\local\programs\python\python36\lib\linecache.py", line 11, in <module>
    import tokenize
  File "c:\users\del\appdata\local\programs\python\python36\lib\tokenize.py", line 33, in <module>
    import re
  File "c:\users\del\appdata\local\programs\python\python36\lib\re.py", line 142, in <module>
    class RegexFlag(enum.IntFlag):
AttributeError: module 'enum' has no attribute 'IntFlag'
Traceback (most recent call last):
  File "<string>", line 41, in <module>
  File "<string>", line 13, in walk_packages
  File "c:\users\del\appdata\local\programs\python\python36\lib\pkgutil.py", line 127, in iter_modules
    for name, ispkg in iter_importer_modules(i, prefix):
  File "c:\users\del\appdata\local\programs\python\python36\lib\pkgutil.py", line 146, in _iter_file_finder_modules
    import inspect
  File "c:\users\del\appdata\local\programs\python\python36\lib\inspect.py", line 40, in <module>
    import linecache
  File "c:\users\del\appdata\local\programs\python\python36\lib\linecache.py", line 11, in <module>
    import tokenize
  File "c:\users\del\appdata\local\programs\python\python36\lib\tokenize.py", line 33, in <module>
    import re
  File "c:\users\del\appdata\local\programs\python\python36\lib\re.py", line 142, in <module>
    class RegexFlag(enum.IntFlag):
AttributeError: module 'enum' has no attribute 'IntFlag'
4277 INFO: running Analysis out00-Analysis.toc
4280 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable
  required by c:\users\del\appdata\local\programs\python\python36\python.exe
4346 WARNING: lib not found: api-ms-win-crt-locale-l1-1-0.dll dependency of c:\users\del\appdata\local\programs\python\python36\python.exe
5519 WARNING: lib not found: api-ms-win-crt-runtime-l1-1-0.dll dependency of c:\users\del\appdata\local\programs\python\python36\VCRUNTIME140.dll

5767 WARNING: lib not found: api-ms-win-crt-stdio-l1-1-0.dll dependency of c:\users\del\appdata\local\programs\python\python36\VCRUNTIME140.dll
5773 INFO: Caching module hooks...
5781 INFO: Analyzing E:\Fichier\Programming\Python\CheckNewEpisodes.py
6041 INFO: Processing pre-safe import module hook   urllib3.packages.six.moves
Traceback (most recent call last):
  File "<string>", line 2, in <module>
  File "c:\users\del\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\hooks\pre_safe_import_module\hook-urllib3.packages.six.moves.py", line 31, in pre_safe_import_module
    for real_module_name, six_module_name in real_to_six_module_name.items():
AttributeError: 'str' object has no attribute 'items'
</code>```

I had to truncate the error log, hope this is enough to get an idea about where the problem is.

答:
You need to make sure any files/data that your script uses is also being packed in with the exe, otherwise when pyinstaller trying to validate that your script works while building it, it will cause an error because the script will not work.

If you can post some of your code that uses the "items" then maybe we can try to help you figure out what you are missing.

In the meantime make sure pyinstaller is including whatever dependencies are needed by including them in the spec file. You can do that as show  HERE

Body:
I can't get to make an .exe file using Pyinstaller 3.3 and python 3.6, on Windows 10 64bits.

I know all the dependencies are installed because i can run my script without any problems, from the command line.

I checked Pyinstaller page and they say python 3.6 is now supported.

E:\Fichier\Programming\Python>pyinstaller CheckNewEpisodes.py
371 INFO: PyInstaller: 3.3
372 INFO: Python: 3.6.1
372 INFO: Platform: Windows-10-10.0.15063-SP0
374 INFO: wrote E:\Fichier\Programming\Python\CheckNewEpisodes.spec
376 INFO: UPX is not available.
377 INFO: Extending PYTHONPATH with paths
['E:\\Fichier\\Programming\\Python', 'E:\\Fichier\\Programming\\Python']
377 INFO: checking Analysis
378 INFO: Building Analysis because out00-Analysis.toc is non existent
378 INFO: Initializing module dependency graph...
380 INFO: Initializing module graph hooks...
382 INFO: Analyzing base_library.zip ...
Traceback (most recent call last):
  File "<string>", line 41, in <module>
  File "<string>", line 13, in walk_packages
  File "c:\users\del\appdata\local\programs\python\python36\lib\pkgutil.py", line 127, in iter_modules
    for name, ispkg in iter_importer_modules(i, prefix):
  File "c:\users\del\appdata\local\programs\python\python36\lib\pkgutil.py", line 146, in _iter_file_finder_modules
    import inspect
  File "c:\users\del\appdata\local\programs\python\python36\lib\inspect.py", line 40, in <module>
    import linecache
  File "c:\users\del\appdata\local\programs\python\python36\lib\linecache.py", line 11, in <module>
    import tokenize
  File "c:\users\del\appdata\local\programs\python\python36\lib\tokenize.py", line 33, in <module>
    import re
  File "c:\users\del\appdata\local\programs\python\python36\lib\re.py", line 142, in <module>
    class RegexFlag(enum.IntFlag):
AttributeError: module 'enum' has no attribute 'IntFlag'
Traceback (most recent call last):
  File "<string>", line 41, in <module>
  File "<string>", line 13, in walk_packages
  File "c:\users\del\appdata\local\programs\python\python36\lib\pkgutil.py", line 127, in iter_modules
    for name, ispkg in iter_importer_modules(i, prefix):
  File "c:\users\del\appdata\local\programs\python\python36\lib\pkgutil.py", line 146, in _iter_file_finder_modules
    import inspect
  File "c:\users\del\appdata\local\programs\python\python36\lib\inspect.py", line 40, in <module>
    import linecache
  File "c:\users\del\appdata\local\programs\python\python36\lib\linecache.py", line 11, in <module>
    import tokenize
  File "c:\users\del\appdata\local\programs\python\python36\lib\tokenize.py", line 33, in <module>
    import re
  File "c:\users\del\appdata\local\programs\python\python36\lib\re.py", line 142, in <module>
    class RegexFlag(enum.IntFlag):
AttributeError: module 'enum' has no attribute 'IntFlag'
4277 INFO: running Analysis out00-Analysis.toc
4280 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable
  required by c:\users\del\appdata\local\programs\python\python36\python.exe
4346 WARNING: lib not found: api-ms-win-crt-locale-l1-1-0.dll dependency of c:\users\del\appdata\local\programs\python\python36\python.exe
5519 WARNING: lib not found: api-ms-win-crt-runtime-l1-1-0.dll dependency of c:\users\del\appdata\local\programs\python\python36\VCRUNTIME140.dll

5767 WARNING: lib not found: api-ms-win-crt-stdio-l1-1-0.dll dependency of c:\users\del\appdata\local\programs\python\python36\VCRUNTIME140.dll
5773 INFO: Caching module hooks...
5781 INFO: Analyzing E:\Fichier\Programming\Python\CheckNewEpisodes.py
6041 INFO: Processing pre-safe import module hook   urllib3.packages.six.moves
Traceback (most recent call last):
  File "<string>", line 2, in <module>
  File "c:\users\del\appdata\local\programs\python\python36\lib\site-packages\PyInstaller\hooks\pre_safe_import_module\hook-urllib3.packages.six.moves.py", line 31, in pre_safe_import_module
    for real_module_name, six_module_name in real_to_six_module_name.items():
AttributeError: 'str' object has no attribute 'items'

I had to truncate the error log, hope this is enough to get an idea about where the problem is.


答:
I would recommend using the SpreadsheetLight library (http://spreadsheetlight.com/). There are other libraries out there as well, and I would recommend investigating those as well. But I have used SpreadsheetLight on numerous occasions, and it seems to be reliable. It's free and simple. You can do something like this:</p>

```<code>        SLDocument sl = new SLDocument("ExistingSpreadsheet.xlsx", "Sheet1");
        var name = sl.GetCellValueAsString("A1");
        var address = sl.GetCellValueAsString("B1");
        var city = sl.GetCellValueAsString("C1");
        var state = sl.GetCellValueAsString("D1");
        var result = string.Format("{0}, {1}, {2}, {3}", name, address, city, state);
</code>```

Title: C# Open an excel spreadsheet and read the header column into a string

Body:
Hi I am fairly new using Excel spreadsheet in C#. I want to be able to open an excel spread sheet and then read the Header column and save it to a string.

e.g. if my headers are Name, Address, City, State in the Excel spreadsheet

I want the output in a string result = "Name, Address, City, State"

Body:
I would recommend using the SpreadsheetLight library (http://spreadsheetlight.com/). There are other libraries out there as well, and I would recommend investigating those as well. But I have used SpreadsheetLight on numerous occasions, and it seems to be reliable. It's free and simple. You can do something like this:

        SLDocument sl = new SLDocument("ExistingSpreadsheet.xlsx", "Sheet1");
        var name = sl.GetCellValueAsString("A1");
        var address = sl.GetCellValueAsString("B1");
        var city = sl.GetCellValueAsString("C1");
        var state = sl.GetCellValueAsString("D1");
        var result = string.Format("{0}, {1}, {2}, {3}", name, address, city, state);


问:
SDO_GEOMETRY not accepting variables
I'm trying to display the distance between to locations, however, when using l_lng and l_lat variables that are processed from a postcode a user enters, I'm getting the following error - ORA-13032: Invalid NULL SDO_GEOMETRY object

It's not a problem with the UPDATE as when I input latitude and longitude values, the distance is calculated. Also, when displaying the latitude and longitude values held in the l_lng and l_lat variables, they are also correct.

```<code>DECLARE

  l_lat VARCHAR2(100);
  l_lng VARCHAR2(100);
  l_postcode VARCHAR2(8) := :P2_POSTCODE;

BEGIN

    brian.GEOCODE_GM_XML (:P2_POSTCODE, l_lat, l_lng);

    UPDATE RESTAURANTS
    SET DISTANCE =     (SELECT SDO_GEOM.SDO_DISTANCE(
                            restaurants.location,
                            SDO_GEOMETRY(2001, 4326, SDO_POINT_TYPE(l_lng, l_lat, null), null, null),
                            0.005, 'unit=mile') distance
                       FROM restaurants WHERE restaurants.restaurant_id = 36);
    htp.p(l_lat);
    htp.p(l_lng);

END;
</code>```

Is there any mistake I'm making?

答:
Change variable declarations for l_lat and l_lng from varchar2
to number.

I presume the restaurants.distance column is of type number.

Verify that the geometries have valid fields. To specify a NULL
geometry, specify the whole SDO_GEOMETRY as
NULL instead of setting each field to NULL.  It seems you may have  some values are NULL at the same time for both l_lat and
l_lng of SDO_POINT_TYPE.

Title: SDO_GEOMETRY not accepting variables

Body:
I'm trying to display the distance between to locations, however, when using l_lng and l_lat variables that are processed from a postcode a user enters, I'm getting the following error - ORA-13032: Invalid NULL SDO_GEOMETRY object

It's not a problem with the UPDATE as when I input latitude and longitude values, the distance is calculated. Also, when displaying the latitude and longitude values held in the l_lng and l_lat variables, they are also correct.

DECLARE

  l_lat VARCHAR2(100);
  l_lng VARCHAR2(100);
  l_postcode VARCHAR2(8) := :P2_POSTCODE;

BEGIN

    brian.GEOCODE_GM_XML (:P2_POSTCODE, l_lat, l_lng);

    UPDATE RESTAURANTS
    SET DISTANCE =     (SELECT SDO_GEOM.SDO_DISTANCE(
                            restaurants.location,
                            SDO_GEOMETRY(2001, 4326, SDO_POINT_TYPE(l_lng, l_lat, null), null, null),
                            0.005, 'unit=mile') distance
                       FROM restaurants WHERE restaurants.restaurant_id = 36);
    htp.p(l_lat);
    htp.p(l_lng);

END;

Is there any mistake I'm making?