问:
Pass Reference in Class
I am totally confused. In this example which is part of my class, I have:

```<code>public:
        typedef DoubleLinkedNode<DataType> Node;
private:
            const DataType* fValue;
            Node* fNext;
            Node* fPrevious;
            DoubleLinkedNode(): fValue((const DataType*)0){
                fNext = (Node*)0;
                fPrevious = (Node*)0;
            }
</code>```

Which means fValue is a const DataType* , now I want to apply/define data type like string or int to fValue by this part:

```<code>    DoubleLinkedNode( const DataType& aValue ){

        std::cout << "  --  "  << aValue << std::endl;
    }
</code>```

I am confused , what exactly I must write there and why? How can I define aValue to my fValue ?!
(note: The std::cout << "  --  "  << aValue << std::endl; is just for test)

答:
I'm not quite sure what you're trying to do here, but if you want to construct DoubleLinkedNode with fValue pointing to the address of aValue (which was passed to the constructor by reference) you need to define your constructor this way:

```<code>DoubleLinkedNode( const DataType& aValue ) : fValue(&aValue) {
        std::cout << "  --  "  << aValue << std::endl;
}
</code>```

Note that it's not 100% safe to do this, since you can accidentally call this constructor with an rvalue reference (to simplify things: a reference to an object that gets destroyed right after the function call). For instance, the following code will not raise a compilation error:

```<code>std::string s = "Hello ";
DoubleLinkedNode<std::string> node = DoubleLinkedNode<std::string>(s + "World");
</code>```

even though s + "World" is a temporary value which will be promptly destroyed after the constructor call, and now fValue will point to an invalid memory location. This is very bad, since you won't get any warning during compilation, but you will get some very hard-to-debug behavior at runtime.

Therefore, it might be better to make a constructor that expects pointers instead of references:

```<code>DoubleLinkedNode( const DataType* aValue ) : fValue(aValue) {
        std::cout << "  --  "  << aValue << std::endl;
}
</code>```

Title: Pass Reference in Class

Body:
I am totally confused. In this example which is part of my class, I have:

public:
        typedef DoubleLinkedNode<DataType> Node;
private:
            const DataType* fValue;
            Node* fNext;
            Node* fPrevious;
            DoubleLinkedNode(): fValue((const DataType*)0){
                fNext = (Node*)0;
                fPrevious = (Node*)0;
            }

Which means fValue is a const DataType* , now I want to apply/define data type like string or int to fValue by this part:

    DoubleLinkedNode( const DataType& aValue ){

        std::cout << "  --  "  << aValue << std::endl;
    }

I am confused , what exactly I must write there and why? How can I define aValue to my fValue ?!
(note: The std::cout << "  --  "  << aValue << std::endl; is just for test)

Body:
I'm not quite sure what you're trying to do here, but if you want to construct DoubleLinkedNode with fValue pointing to the address of aValue (which was passed to the constructor by reference) you need to define your constructor this way:

DoubleLinkedNode( const DataType& aValue ) : fValue(&aValue) {
        std::cout << "  --  "  << aValue << std::endl;
}

Note that it's not 100% safe to do this, since you can accidentally call this constructor with an rvalue reference (to simplify things: a reference to an object that gets destroyed right after the function call). For instance, the following code will not raise a compilation error:

std::string s = "Hello ";
DoubleLinkedNode<std::string> node = DoubleLinkedNode<std::string>(s + "World");

even though s + "World" is a temporary value which will be promptly destroyed after the constructor call, and now fValue will point to an invalid memory location. This is very bad, since you won't get any warning during compilation, but you will get some very hard-to-debug behavior at runtime.

Therefore, it might be better to make a constructor that expects pointers instead of references:

DoubleLinkedNode( const DataType* aValue ) : fValue(aValue) {
        std::cout << "  --  "  << aValue << std::endl;
}


来源: stackexchange

问:
What is the meaning of OneMinuteRate in JMX?
I am trying to calculate the Read/second and Write/Second in my Cassandra 2.1 cluster. After searching and reading, I came to know about JMX bean

org.apache.cassandra.metrics:type=ClientRequest,scope=Write,name=Latency

Here I can see oneMinuteRate. I have started a brand new cluster and started collected these metrics from 0.
When I started my first record, I can see

```<code>Count = 1
OneMinuteRate = 0.01599111...
</code>```

Does it mean that my write/s is 0.0159911?
Or does it mean that based on 1 minute data, my write latency is 0.01599 where Write Latency refers to the response time for writing a record?

Please help me understand the value.

Thanks.

答:
OneMinuteRate, FiveMinuteRate, and FifteenMinuteRate are exponential moving averages, meaning they are not simply dividing readings against time, instead, as the name implies they take an exponential series of averages as below:

result(t) = (1 - w) * result(t - 1) + (w) * event_this_period

where w is the weighting factor, t is the ticking time, in other words, simply they take 20% or the new reading and 80% of old readings, it's the same way UNIX systems measure CPU loads.

however, if this applies to requests that the server receives, below is a chart from one request to a server, measures taken by dropwizard.

as you can see, from one request a curve is drawn by time, it's really useful to determine trends, but not sure if they are great to monitor live traffic and especially critical one.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to calculate the Read/second and Write/Second in my Cassandra 2.1 cluster. After searching and reading, I came to know about JMX bean

org.apache.cassandra.metrics:type=ClientRequest,scope=Write,name=Latency

Here I can see oneMinuteRate. I have started a brand new cluster and started collected these metrics from 0.
When I started my first record, I can see

Count = 1
OneMinuteRate = 0.01599111...

Does it mean that my write/s is 0.0159911?
Or does it mean that based on 1 minute data, my write latency is 0.01599 where Write Latency refers to the response time for writing a record?

Please help me understand the value.

Thanks.

ContentLicense: CC BY-SA 4.0


问:
List of List of Numbers with a Bounded wildcard type
If I have this,

```<code>Collection<? extends Number> c = new ArrayList<>();
c.add(new Integer(1)); // Compile time error
</code>```

Since we don't know what the element type of c stands for, we cannot add integers to it.

But if I do like,

```<code>List<List<? extends Number>> history = new ArrayList<>();

List<Integer> integers = new ArrayList<>();
integers.add(new Integer(1));

List<Double> doubles = new ArrayList<>();
doubles.add(new Double(2));

history.add(integers); // This is allowed
history.add(doubles);  // This is allowed
</code>```

Why the addition in the 2nd example is allowed?

答:
```<code>Collection<? extends ...>
c.add(...);
</code>```

A collection with a lower bound cannot be added to.

```<code>List<List<...>> history;
history.add(...);      // Allowed
</code>```

The outer list has a concrete type. The ? extends wildcard is inside the inner list, but it's irrelevant since you're adding to the outer list. I've replaced the wildcard with ... since it doesn't matter what it is when you're calling history.add().

If the outer list had a wildcard bound then adding would fail.

```<code>List<? extends List<...>> history;
history.add(...);      // NOT allowed
</code>```

Body:
If I have this,

Collection<? extends Number> c = new ArrayList<>();
c.add(new Integer(1)); // Compile time error

Since we don't know what the element type of c stands for, we cannot add integers to it.

But if I do like,

List<List<? extends Number>> history = new ArrayList<>();

List<Integer> integers = new ArrayList<>();
integers.add(new Integer(1));

List<Double> doubles = new ArrayList<>();
doubles.add(new Double(2));

history.add(integers); // This is allowed
history.add(doubles);  // This is allowed

Why the addition in the 2nd example is allowed?

Body:
Collection<? extends ...>
c.add(...);

A collection with a lower bound cannot be added to.

List<List<...>> history;
history.add(...);      // Allowed

The outer list has a concrete type. The ? extends wildcard is inside the inner list, but it's irrelevant since you're adding to the outer list. I've replaced the wildcard with ... since it doesn't matter what it is when you're calling history.add().

If the outer list had a wildcard bound then adding would fail.

List<? extends List<...>> history;
history.add(...);      // NOT allowed


问:
Python print ascii character in string instead of value
I have a string "hello[ World]" and I want to convert it to "hello[World]"

I tried something like this:

```<code> a.encode("utf-8").decode("ascii")
</code>```

I got back same string as input.

答:
Try this:

```<code>import html
html.unescape("LASIX [FUROSEMIDE]")
</code>```

This produces:

```<code>'LASIX [FUROSEMIDE]'
</code>```

Body:
I have a string "hello[ World]" and I want to convert it to "hello[World]"

I tried something like this:

 a.encode("utf-8").decode("ascii")

I got back same string as input.

Body:
Try this:

import html
html.unescape("LASIX &#91;FUROSEMIDE&#93;")

This produces:

'LASIX [FUROSEMIDE]'


问:
Silverlight Simple and Complex Properties
I was asked recently in an interview to give an example of a simple property and a complex property in Silverlight.  I think they were asking about dependency properties and attached properties but I'm not sure.  I've never heard the term Silverlight Simple Property or Silverlight Complex Property and googling hasn't helped.  Are these common terms that I've just missed up until now?  If so, what do they refer to?</p>

答: maybe simple properties are of type string, int, bool, etc. where complex properties are custom classes (or struct) like Company { string companyName; }</p>


问:
Extract messages programmatically with PyBabel
Right now, I’m extracting messages using

```<code>pybabel extract -F babel.cfg -o messages.pot .
</code>```

This walks through all my Python files and extracts messages correctly.  However, I call this through subprocess.call(), which is pretty ugly, given PyBbel is also written in Python.

I took a look into PyBabel, and it uses setuptools comands to do its work. I could copy the extract_messages.run() method to my Python script, but it doesn’t feel too elegant.  Is there a better way to do it?  There are tons of articles on how to create new setuptools commands, but no one writes about invoking them…

答:
Maybe this is what you are looking for: How do i run the python 'sdist' command from within a python automated script without using subprocess?

I'm going to show a few alternatives to run the Babel Python code, without creating a new subprocess, from higher to lower level.

This is kind of a hack, taken from the answers linked above:

```<code>from setuptools.dist import Distribution
from babel.messages.frontend import extract_messages

dist = Distribution({'name': 'my-project', 'version': '1.0.0'}) # etc.
dist.script_name = 'setup.py'
cmd = extract_messages(dist)
cmd.ensure_finalized()
cmd.run()  # TODO: error handling
</code>```

pylabel script actually does something like this:

```<code>from babel.messages.frontend import main

sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())
</code>```

But you can avoid sending the commands over the sys.argv and actually call the CommandInterface python code from babel.

This is my favorite way to call it:

```<code>from babel.messages.frontend import CommandLineInterface

CommandLineInterface().run(['pybabel','extract','-F','babel.cfg','-k','lazy_gettext','-o','messages.pot','sample_project'])
CommandLineInterface().run(['pybabel','init','-i','messages.pot','-d','translations','-l','en'])
CommandLineInterface().run(['pybabel','compile','-d','translations'])
CommandLineInterface().run(['pybabel','update','-d','translations'])
</code>```

That's the closest you can get to the low level code, unless you want to start copy/pasting and customizing the python code. Again, this is a 100% python solution, and it doesn't call a new process.

Good luck

Body:
Right now, I’m extracting messages using

pybabel extract -F babel.cfg -o messages.pot .

This walks through all my Python files and extracts messages correctly.  However, I call this through subprocess.call(), which is pretty ugly, given PyBbel is also written in Python.

I took a look into PyBabel, and it uses setuptools comands to do its work. I could copy the extract_messages.run() method to my Python script, but it doesn’t feel too elegant.  Is there a better way to do it?  There are tons of articles on how to create new setuptools commands, but no one writes about invoking them…

Body:
Maybe this is what you are looking for: How do i run the python 'sdist' command from within a python automated script without using subprocess?

I'm going to show a few alternatives to run the Babel Python code, without creating a new subprocess, from higher to lower level.

This is kind of a hack, taken from the answers linked above:

from setuptools.dist import Distribution
from babel.messages.frontend import extract_messages

dist = Distribution({'name': 'my-project', 'version': '1.0.0'}) # etc.
dist.script_name = 'setup.py'
cmd = extract_messages(dist)
cmd.ensure_finalized()
cmd.run()  # TODO: error handling

pylabel script actually does something like this:

from babel.messages.frontend import main

sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())

But you can avoid sending the commands over the sys.argv and actually call the CommandInterface python code from babel.

This is my favorite way to call it:

from babel.messages.frontend import CommandLineInterface

CommandLineInterface().run(['pybabel','extract','-F','babel.cfg','-k','lazy_gettext','-o','messages.pot','sample_project'])
CommandLineInterface().run(['pybabel','init','-i','messages.pot','-d','translations','-l','en'])
CommandLineInterface().run(['pybabel','compile','-d','translations'])
CommandLineInterface().run(['pybabel','update','-d','translations'])

That's the closest you can get to the low level code, unless you want to start copy/pasting and customizing the python code. Again, this is a 100% python solution, and it doesn't call a new process.

Good luck


问:
Unique regex replacement with capture
I have a text (html code) with many images like:

I need the src value to be replaced by a unique identification like CID:# where # is this unique value. I don't know if the src values will be all different, maybe some of them can be equal.

Bellow is the code with the regular expression to match the images. Now, how to make the replacement?

PS: I need to store in a array the relation between the unique code created and the string that was replaced. For instance, i need to know that the 345 id is relative to the url "img/xxx.jpg".

```<code>preg_match_all('/<img src=[",\']([^>,^\',^"]*)[",\']([^>]*)/', $html, $matches);

$url_image = array();
$attr_image = array();
$cid = array();

foreach ($matches[1] as $i => $img){

    $url_image[$i] = $matches[2][$i];
    $attr_image[$i] = $matches[3][$i];

    //How to replace the src value with the value of $cid?
    $cid[$contador] = "CID:".date('YmdHms').'.'.time().$i;
}
</code>```

答:
Here is the solution used:</p>

```<code>preg_match_all('/<img src=[",\']([^>,^\',^"]*)[",\']([^>]*)/', $html, $matches);

$url_image = array();
$attr_image = array();
$cid = array();

foreach ($matches[1] as $i => $img){

    $url_image[$i] = $matches[1][$i];
    $attr_image[$i] = $matches[2][$i];

    $cid[$i] = "CID:".date('YmdHms').'.'.time().$i;
    $tag_img = str_replace("/", "\/", $img);

    //Replace each specific occurrence
    $html = preg_replace('/'.$tag_img.'/', $cid[$i], $html, 1);
}
</code>```

Title: Unique regex replacement with capture

Body:
I have a text (html code) with many images like:

I need the src value to be replaced by a unique identification like CID:# where # is this unique value. I don't know if the src values will be all different, maybe some of them can be equal.

Bellow is the code with the regular expression to match the images. Now, how to make the replacement?

PS: I need to store in a array the relation between the unique code created and the string that was replaced. For instance, i need to know that the 345 id is relative to the url "img/xxx.jpg".

preg_match_all('/,^\',^"]*)[",\']([^>]*)/', $html, $matches);

$url_image = array();
$attr_image = array();
$cid = array();

foreach ($matches[1] as $i => $img){

    $url_image[$i] = $matches[2][$i];
    $attr_image[$i] = $matches[3][$i];

    //How to replace the src value with the value of $cid?
    $cid[$contador] = "CID:".date('YmdHms').'.'.time().$i;
}

Body:
Here is the solution used:

preg_match_all('/<img src=[",\']([^>,^\',^"]*)[",\']([^>]*)/', $html, $matches);

$url_image = array();
$attr_image = array();
$cid = array();

foreach ($matches[1] as $i => $img){

    $url_image[$i] = $matches[1][$i];
    $attr_image[$i] = $matches[2][$i];

    $cid[$i] = "CID:".date('YmdHms').'.'.time().$i;
    $tag_img = str_replace("/", "\/", $img);

    //Replace each specific occurrence
    $html = preg_replace('/'.$tag_img.'/', $cid[$i], $html, 1);
}


问:
How to merge 2 tables with user and timestamp in python
I need to merge 2 tables of millions of records. The common fields are user and timestamp. The problem is that the timestamp is different in both tables, so I need to create a new variable or establish a range of 5 seconds to find a perfect coincidence between tables 1 and 2.

I am trying to use lookup or function y.  I am not an expert, so I really need your help.

I know that it seems easy for an expert. Thank you very much!!!

答:
Might I suggest pandas merge_asof function:

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.merge_asof.html

I believe the argument direction='nearest' might solve your problem.


问:
Pandas resample and interpolate an irregular time series using a list of other irregular times
I have data collected from 2 different sensors which operate asynchronously at non-uniform intervals. I want to get data from sensor 1 interpolated to the timestamps from sensor 2.
I have found a round about way of doing this with Pandas involving first creating a combined time series, interpolating it and then combining the interpolated one with the 2nd sensor's time series to only bring out the intersecting times.
Is there a more Pythonic (or Pandaic) way to do this more efficiently.  Here is a sample code which uses the method I describe above:</p>

```<code>import numpy as np
from matplotlib import pyplot as plt
import datetime
import pandas as pd

rand_secs = np.sort(np.random.randint(1, high=60,size=10))
times = [pd.datetime(2019, 5, 23,9, x) for x in rand_secs]
frame1 = pd.DataFrame(index = times,
                      data = np.sin(rand_secs/60*2*np.pi))
ax1 = frame1.plot(marker='+')
plt.xlim(pd.datetime(2019, 5, 23,9, 0), pd.datetime(2019, 5, 23,9, 59))
plt.ylim(-1.1,1.1)

times2 = [pd.datetime(2019, 5, 23,9, x) for x in np.sort(np.random.randint(1, high=60,size=10))]
frame2 = pd.DataFrame(index = times2)

frame12_combined = pd.merge(frame1, frame2, how='outer',left_index=True, right_index=True)
frame12_interp = frame12_combined.interpolate(method='index') #Linear is not Correct

frame1_resampled = pd.merge(frame2, frame12_interp, how='left',left_index=True, right_index=True)
frame1_resampled.plot(ax=ax1,style='o' )
ax1.legend(['Original time series', 'Resampled time series'])
</code>```

答:
Using Pandas we can do the following:

You can use union from pandas.Index along with reindex from pandas.DataFrame, this will eliminate all the merging:

```<code>ax1 = frame1.plot(marker='+')
frame1_r = frame1.reindex(frame1.index.union(frame2.index))\
                 .interpolate(method='index')\
                 .reindex(frame2.index)
frame1_r.plot(ax=ax1, style='o')
</code>```

Output:

Body:
I have data collected from 2 different sensors which operate asynchronously at non-uniform intervals. I want to get data from sensor 1 interpolated to the timestamps from sensor 2.
I have found a round about way of doing this with Pandas involving first creating a combined time series, interpolating it and then combining the interpolated one with the 2nd sensor's time series to only bring out the intersecting times.
Is there a more Pythonic (or Pandaic) way to do this more efficiently.  Here is a sample code which uses the method I describe above:

import numpy as np
from matplotlib import pyplot as plt
import datetime
import pandas as pd

rand_secs = np.sort(np.random.randint(1, high=60,size=10))
times = [pd.datetime(2019, 5, 23,9, x) for x in rand_secs]
frame1 = pd.DataFrame(index = times,
                      data = np.sin(rand_secs/60*2*np.pi))
ax1 = frame1.plot(marker='+')
plt.xlim(pd.datetime(2019, 5, 23,9, 0), pd.datetime(2019, 5, 23,9, 59))
plt.ylim(-1.1,1.1)

times2 = [pd.datetime(2019, 5, 23,9, x) for x in np.sort(np.random.randint(1, high=60,size=10))]
frame2 = pd.DataFrame(index = times2)

frame12_combined = pd.merge(frame1, frame2, how='outer',left_index=True, right_index=True)
frame12_interp = frame12_combined.interpolate(method='index') #Linear is not Correct

frame1_resampled = pd.merge(frame2, frame12_interp, how='left',left_index=True, right_index=True)
frame1_resampled.plot(ax=ax1,style='o' )
ax1.legend(['Original time series', 'Resampled time series'])

Body:
Using Pandas we can do the following:

You can use union from pandas.Index along with reindex from pandas.DataFrame, this will eliminate all the merging:

ax1 = frame1.plot(marker='+')
frame1_r = frame1.reindex(frame1.index.union(frame2.index))\
                 .interpolate(method='index')\
                 .reindex(frame2.index)
frame1_r.plot(ax=ax1, style='o')

Output:


问:
How to reduce Apk (.apk) size in android studio
When i run my app size of apk will 21 MB. even i enabled proguard. i use android studio to run project. in project files src folder has 8.62 MB size and lib folder size is 400 KB size. so how i reduce size of .apk file.
Actually .apk file is 8 mb before some days with same images but after paypal integration my app size will increases to 21 mb.
size of build folder is 127 MB.

build.gradle(module app) is:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"
    useLibrary 'org.apache.http.legacy'
    defaultConfig {
        applicationId "com.oi.food"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    packagingOptions{
        exclude 'AndroidManifest.xml'
    } }

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile files('libs/httpmime-4.1.1.jar')
    compile files('libs/apache-mime4j-0.6.jar')
    compile 'com.squareup.picasso:picasso:2.3.2'
    compile 'com.android.support:design:23.1.1'
    compile 'com.android.support:recyclerview-v7:23.1.1'
    compile 'com.paypal.sdk:paypal-android-sdk:2.14.1' }
</code>```

答: I think you should build your APK as (APK bundle), Google promotes that for APK size issues. I've used the option for my projects and it did actually decrease the size of my APK.</p>

Body:
When i run my app size of apk will 21 MB. even i enabled proguard. i use android studio to run project. in project files src folder has 8.62 MB size and lib folder size is 400 KB size. so how i reduce size of .apk file.
Actually .apk file is 8 mb before some days with same images but after paypal integration my app size will increases to 21 mb.
size of build folder is 127 MB.

build.gradle(module app) is:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"
    useLibrary 'org.apache.http.legacy'
    defaultConfig {
        applicationId "com.oi.food"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    packagingOptions{
        exclude 'AndroidManifest.xml'
    } }

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile files('libs/httpmime-4.1.1.jar')
    compile files('libs/apache-mime4j-0.6.jar')
    compile 'com.squareup.picasso:picasso:2.3.2'
    compile 'com.android.support:design:23.1.1'
    compile 'com.android.support:recyclerview-v7:23.1.1'
    compile 'com.paypal.sdk:paypal-android-sdk:2.14.1' }


问:
How to fix "ord() expected a character, but string of length 0 found" error in Python
My program must encode input messages using a Caesar Cipher. I tried to split my string to many letters by putting "/" between them. Then everything, in fact, worked(as I think). Eventually, when a message gets closer to chr(ord(ch)+ 2) an error pops out. How can I fix with this? </p>

```<code>def main():

    print("This program will encode your messages using a Caesar Cipher")

    message = input("Enter the message: ")

    load = ("")

    codedMessage = ("")

    for i in message:

        load = load + i + "/"

        ''.join(load)

    for ch in load.split("/"):

        codedMessage = codedMessage + chr(ord(ch)+ 2)

    print("The coded message is:", codedMessage)

main()
</code>```

答:
You must do this:</p>

```<code>print("This program will encode your messages using a Caesar Cipher")

message = input("Enter the message: ")

codedMessage = ""

for ch in message:
    codedMessage = codedMessage + chr(ord(ch) + 2)

print("The coded message is:", codedMessage)
</code>```

Body:
My program must encode input messages using a Caesar Cipher. I tried to split my string to many letters by putting "/" between them. Then everything, in fact, worked(as I think). Eventually, when a message gets closer to chr(ord(ch)+ 2) an error pops out. How can I fix with this?

def main():

    print("This program will encode your messages using a Caesar Cipher")

    message = input("Enter the message: ")

    load = ("")

    codedMessage = ("")

    for i in message:

        load = load + i + "/"

        ''.join(load)

    for ch in load.split("/"):

        codedMessage = codedMessage + chr(ord(ch)+ 2)

    print("The coded message is:", codedMessage)

main()

Body:
You must do this:

print("This program will encode your messages using a Caesar Cipher")

message = input("Enter the message: ")

codedMessage = ""

for ch in message:
    codedMessage = codedMessage + chr(ord(ch) + 2)

print("The coded message is:", codedMessage)


问:
How can I find the MAC address of a specific device via Windows batch file?
I'm trying to write a script that will compare the MAC address of Local Area Connection to the MAC address in software licenses to see if one of the licenses matches the machines.  The part that has me stuck right now is pulling the MAC address of a specific device "Local Area Connection".

I have tried using search features such as:

```<code>ipconfig /all | findstr^ /C:"Local Area Connection"^ /C:"Physical Address" > C:\temp\macaddress.txt
for /f "tokens=1,2 delims=:" %%i in (C:\temp\macaddress.txt) do @echo The MAC Address of %%i is %%j
pause
</code>```

I really don't need the echo in the above attempt, but I use it for debugging.

But still the above statement puts text into a file like this:

"Physical Address. . . . . . . . . : 00-37-10-D1-98-2C

Ethernet adapter Local Area Connection:

Physical Address. . . . . . . . . : 5D-26-0A-11-11-15"
(quotes added by me to show the beginning and end of text file)

From that, I'm not sure how to pull the MAC address that comes after Ethernet adapter Local Area Connection, especially when they're not on the same line.

I need to do this with a batch file in Windows XP Professional.  Thank you.

答:
This old script should work.

It searches first for the correct adapter, and then it waits until a line containing the string "Physical".
The :Normalize function is for removing < Carriage Return> in the output of ipconfig at XP systems, as microsoft doesn't know exactly that a line should end with CR/LF not with LF/CR.

```<code>@echo off
SETLOCAL EnableDelayedExpansion EnableExtensions

rem call :GetIP ip_WLAN "Drahtlos"
rem echo ---
set OS_Version=XP
call :GetIP result  "Ethernet adapter" "Physical"

echo mac=%result%

goto :eof

::::::::::::::::::::::::::::
:GetIP <resultVar> <AdapterName>
:: resultVar    return variable for the searched value
:: AdapterName  part of the adapter name
setlocal
set /a found=0
if "%OS_Version%"=="Win7" set ipText=IPv4
if "%OS_Version%"=="Vista" set ipText=IPv4
if "%OS_Version%"=="XP" set ipText=IP-
if "%~3"=="" (
    set searchText=!ipText!
) ELSE (
    set "searchText=%~3"
)
for /F "tokens=1,* delims=:" %%a IN ('ipconfig /all') DO (
  call :Normalize first "%%a.dummy"
  call :Normalize post "%%b.dummy"

  if "!post!"=="_" (
    if "!first:%~2=!" NEQ "!first!" (
        set /a found=1
        rem echo adapter found "!first!"
    ) ELSE (
        if "!first!" NEQ "_" (
            set /a found=0
            rem echo - !first! !post!
        )
    )
  )

  if !found! EQU 1 (
    rem echo try "!first!"
    if "!first:%searchText%=!" NEQ "!first!" (
        set ipAddr=!post:_=!
        set ipAddr=!ipAddr: =!
        rem echo IP found !post! for adapter
    )
  )
)

(
  endlocal
  set %~1=%ipAddr%
  goto :eof
)

:Normalize
set %~1=_%~n2
goto :eof
</code>```

Body:
I'm trying to write a script that will compare the MAC address of Local Area Connection to the MAC address in software licenses to see if one of the licenses matches the machines.  The part that has me stuck right now is pulling the MAC address of a specific device "Local Area Connection".

I have tried using search features such as:

ipconfig /all | findstr^ /C:"Local Area Connection"^ /C:"Physical Address" > C:\temp\macaddress.txt
for /f "tokens=1,2 delims=:" %%i in (C:\temp\macaddress.txt) do @echo The MAC Address of %%i is %%j
pause

I really don't need the echo in the above attempt, but I use it for debugging.

But still the above statement puts text into a file like this:

"Physical Address. . . . . . . . . : 00-37-10-D1-98-2C

Ethernet adapter Local Area Connection:

Physical Address. . . . . . . . . : 5D-26-0A-11-11-15"
(quotes added by me to show the beginning and end of text file)

From that, I'm not sure how to pull the MAC address that comes after Ethernet adapter Local Area Connection, especially when they're not on the same line.

I need to do this with a batch file in Windows XP Professional.  Thank you.

Body:
This old script should work.

It searches first for the correct adapter, and then it waits until a line containing the string "Physical".
The :Normalize function is for removing < Carriage Return> in the output of ipconfig at XP systems, as microsoft doesn't know exactly that a line should end with CR/LF not with LF/CR.

@echo off
SETLOCAL EnableDelayedExpansion EnableExtensions

rem call :GetIP ip_WLAN "Drahtlos"
rem echo ---
set OS_Version=XP
call :GetIP result  "Ethernet adapter" "Physical"

echo mac=%result%

goto :eof

::::::::::::::::::::::::::::
:GetIP <resultVar> <AdapterName>
:: resultVar    return variable for the searched value
:: AdapterName  part of the adapter name
setlocal
set /a found=0
if "%OS_Version%"=="Win7" set ipText=IPv4
if "%OS_Version%"=="Vista" set ipText=IPv4
if "%OS_Version%"=="XP" set ipText=IP-
if "%~3"=="" (
    set searchText=!ipText!
) ELSE (
    set "searchText=%~3"
)
for /F "tokens=1,* delims=:" %%a IN ('ipconfig /all') DO (
  call :Normalize first "%%a.dummy"
  call :Normalize post "%%b.dummy"

  if "!post!"=="_" (
    if "!first:%~2=!" NEQ "!first!" (
        set /a found=1
        rem echo adapter found "!first!"
    ) ELSE (
        if "!first!" NEQ "_" (
            set /a found=0
            rem echo - !first! !post!
        )
    )
  )

  if !found! EQU 1 (
    rem echo try "!first!"
    if "!first:%searchText%=!" NEQ "!first!" (
        set ipAddr=!post:_=!
        set ipAddr=!ipAddr: =!
        rem echo IP found !post! for adapter
    )
  )
)

(
  endlocal
  set %~1=%ipAddr%
  goto :eof
)

:Normalize
set %~1=_%~n2
goto :eof


问:
Build a slider based on the data returned from API call
Need to build a slider (carousel) which should be based on the data returned from the API call. There are 3 values which I need to pull. image, title and description.

It must be a picture, heading, and description (on each slide, pulled from JSON).

jQuery

```<code>var myJSON = 'apiCall';
$.getJSON('myJSON, { get_param: 'value' }, function(data) {
    $.each(data, function(index, element) {
        $('body').append($('<img>', {
        }));
    });
});
</code>```

HTML

```<code>   <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
             <ol class="carousel-indicators">
               <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
    <li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
  </ol>
  <div class="carousel-inner">
    <div class="carousel-item active">
      <img class="d-block w-80" src="..." alt="First slide">
        <div class="carousel-caption d-none d-md-block">
         <h5></h5>
         <p></p>
        </div>
    </div>
    <div class="carousel-item">
      <img class="d-block w-80" src="..." alt="Second slide">
        <div class="carousel-caption d-none d-md-block">
         <h5></h5>
         <p></p>
        </div>
  </div>
    </div>
    <div class="carousel-item">
      <img class="d-block w-80" src="..." alt="Third slide">
       <div class="carousel-caption d-none d-md-block">
         <h5></h5>
         <p></p>
       </div>
    </div>
  </div>
  <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
  </a>
  <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
</div>
</code>```

答:
$.get('apiCall')
      .then(function(response) {
          var $carousel = $('#carouselExampleIndicators');
          var $carouselInner = $carousel.find('.carousel-inner');

          response.data.forEach(function(item, i) {
            var template = '';

            if(i === 0) {
              template = '
';
            } else {
              template = '
';
            }

            template += '';
            template += '
';
            template += '
' + item.title_a + '
';
            template += '
' + item.category + '
';
            template += '
';
            template += '
';

            $carouselInner.append(template);
          })

          $carousel.carousel();
      })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
  <div class="carousel-inner">

  </div>

   <span class="carousel-control-prev-icon" aria-hidden="true"></span>
   <span class="sr-only">Previous</span>

   <span class="carousel-control-next-icon" aria-hidden="true"></span>
   <span class="sr-only">Next</span>

 </div></code>```

Hey, here is the example with jQuery and ES5 js. I suggest you using https://handlebarsjs.com/ for templating html. It will look nicer.

Body:
Need to build a slider (carousel) which should be based on the data returned from the API call. There are 3 values which I need to pull. image, title and description.

It must be a picture, heading, and description (on each slide, pulled from JSON).

jQuery

var myJSON = 'apiCall';
$.getJSON('myJSON, { get_param: 'value' }, function(data) {
    $.each(data, function(index, element) {
        $('body').append($('', {
        }));
    });
});

HTML

    Previous

    Next

Body:
$.get('apiCall')
      .then(function(response) {
          var $carousel = $('#carouselExampleIndicators');
          var $carouselInner = $carousel.find('.carousel-inner');

          response.data.forEach(function(item, i) {
            var template = '';

            if(i === 0) {
              template = '<div class="carousel-item active">';
            } else {
              template = '<div class="carousel-item">';
            }

            template += '<img class="d-block w-80" src="' + item.image + '" alt="Second slide">';
            template += '<div class="carousel-caption">';
            template += '<h5>' + item.title_a + '</h5>';
            template += '<p>' + item.category + '</p>';
            template += '</div>';
            template += '</div>';

            $carouselInner.append(template);
          })

          $carousel.carousel();
      })

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
  <div class="carousel-inner">

  </div>
  <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
   <span class="carousel-control-prev-icon" aria-hidden="true"></span>
   <span class="sr-only">Previous</span>
  </a>
  <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
   <span class="carousel-control-next-icon" aria-hidden="true"></span>
   <span class="sr-only">Next</span>
  </a>
 </div>

Hey, here is the example with jQuery and ES5 js. I suggest you using https://handlebarsjs.com/ for templating html. It will look nicer.


问:
URL routing in Django
I am prrety new in URLs and Django and got some questions.

For now I have 2 HTML templates which are routing correctly: home.html and ladder.html .

What do I have to do to go from my ladder.html(ladder/) back to my home.html("") if I click to home again nothing is happening.
And as second when I am on ladder and click ladder again it adds another ladder/ to the URL and Im getting a router error , how can I resolve this ?

Thanks for the help.

I will show the code of my navbar wher my href attributes are so u can understand what I mean and my urls.py

My hrefs:

```<code><div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="">Home<span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="ladder/">Ladders</a>
</code>```

My urls.py:

```<code>from django.contrib import admin
from django.urls import path
from pages.views import home_view,ladder_view
from django.contrib.staticfiles.urls import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns = [
    path('', home_view),
    path('admin/', admin.site.urls),
    path('ladder/',ladder_view),

]
</code>```

答:
The path for home is /, so you can write this as:

```<code><a class="nav-link" href=<b>"/"</b>>Home<span class="sr-only">(current)</span></a></code>```

But that being said hardcoding URLs is not a good idea. You should give your URLs a name, and use the {% url ... %} [Django-doc] template tag, like:

```<code># app/urls.py

from django.contrib import admin
from django.urls import path
from pages.views import home_view,ladder_view
from django.contrib.staticfiles.urls import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns = [
    path('', home_view<b>, name='home'</b>),
    path('admin/', admin.site.urls),
    path('ladder/',ladder_view<b>, name='ladder'</b>),
]</code>```

In the template you can then write this as:

```<code><li class="nav-item active">
    <a class="nav-link" href="<b>{% url 'home' %}</b>">Home<span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
    <a class="nav-link" href="<b>{% url 'ladder' %}</b>">Ladders</a>
</li></code>```

If you later for example change the path, or move that view to another app, then the URLs will change, since Django "calculates" the URLs when rendering the template. The Django documentation has a topic named Naming url patterns [Django-doc] on that.

Title: URL routing in Django

Body:
I am prrety new in URLs and Django and got some questions.

For now I have 2 HTML templates which are routing correctly: home.html and ladder.html .

What do I have to do to go from my ladder.html(ladder/) back to my home.html("") if I click to home again nothing is happening.
And as second when I am on ladder and click ladder again it adds another ladder/ to the URL and Im getting a router error , how can I resolve this ?

Thanks for the help.

I will show the code of my navbar wher my href attributes are so u can understand what I mean and my urls.py

My hrefs:

        Home(current)

        Ladders

My urls.py:

from django.contrib import admin
from django.urls import path
from pages.views import home_view,ladder_view
from django.contrib.staticfiles.urls import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns = [
    path('', home_view),
    path('admin/', admin.site.urls),
    path('ladder/',ladder_view),

]

Body:
The path for home is /, so you can write this as:

<a class="nav-link" href="/">Home<span class="sr-only">(current)</span></a>

But that being said hardcoding URLs is not a good idea. You should give your URLs a name, and use the {% url ... %} [Django-doc] template tag, like:

# app/urls.py

from django.contrib import admin
from django.urls import path
from pages.views import home_view,ladder_view
from django.contrib.staticfiles.urls import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns = [
    path('', home_view, name='home'),
    path('admin/', admin.site.urls),
    path('ladder/',ladder_view, name='ladder'),
]

In the template you can then write this as:

<li class="nav-item active">
    <a class="nav-link" href="{% url 'home' %}">Home<span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
    <a class="nav-link" href="{% url 'ladder' %}">Ladders</a>
</li>

If you later for example change the path, or move that view to another app, then the URLs will change, since Django "calculates" the URLs when rendering the template. The Django documentation has a topic named Naming url patterns [Django-doc] on that.


问:
Does inline determine internal linkage?
I'm trying to extern an inline function. How I thought it should work:

```<code>//a.cpp
inline void f(int) {}
//b.cpp
extern void f(int);
int main() { f(4); }
</code>```

But getting link error. Then by reading this ("1) It must be declared inline in every translation unit."). What I've tried:

```<code>//a.cpp
inline void f(int) {}
//b.cpp
extern inline void f(int);
int main() { f(4); }
</code>```

Still getting link error. But now, trying something that I don't know what I'm doing:

```<code>//a.cpp
extern inline void f(int) {}
//b.cpp
extern inline void f(int);
int main() { f(4); }
</code>```

It works. What's happening here? Before adding extern to everything, f in a.cpp had internal linkage?

I'm using MSVC 2017 (v141) with /permissive- and /std:c++17

答:
I'm trying to extern an inline function.

There is no reason to use extern with a function. See storage duration - linkage. Functions have external linkage by default; in order to not have external linkage, something special needs to be done (i.e. put it in an anonymous namespace or declare it static). So the normal use of an inline function already exhibits external linkage with no need for the extern keyword.

How I thought it should work:

```<code>//a.cpp
inline void f(int) {}
//b.cpp
extern void f(int);
int main() { f(4); }
</code>```

Then by reading this ("1) It must be declared inline in every translation unit.").

That reference is correct, but look up a bit more where it says "The definition of an inline function [...] must be present in the translation unit where it is accessed [...]." Your example has a declaration of f in b.cpp, but not a definition. If you are going to call f from b.cpp, you need the full definition in that translation unit, as in:

```<code>inline void f(int) {}
</code>```

(This is the same code that exists in a.cpp.) If you leave off the curly braces, then you have a declaration but not a definition, making it illegal to call f from that translation unit.

Basically, it is a real pain to define an inline function outside a header file, unless you give it internal linkage. That's because each source file that uses the inline function would need its own copy of the function body, meaning that if you change the function, you need to make that change in multiple files. Oof. Don't do it. Define each of your inline functions in a header file. If you think you want to define one in a source file, you probably misunderstand what "inline" means.

What does "inline" mean?

As far as the compiler is concerned, the inline keyword means (almost) nothing. It is just a flag on a function definition that gets propagated into the object code so that the linker sees it. The compiler processes the function just as it would any other function. The function may be called normally, or calls to it might be inlined – just like any other function.

The one case where the compiler might do something with the inline flag is when a function is declared inline, is used, but lacks a definition. This is an error that can be caught before the linker takes over. It does not have to be caught by the compiler, but it can be. (If not caught by the compiler, it would be caught by the linker.)

Moving on to the linking stage. When the linker sees the inline flag, it suspends the one-definition rule for that function. The linker will expect to see a definition of the function in each translation unit that still uses the function after the compiler's optimizations. It gets to choose any one of those definitions to serve as the final implementation. Hence the reason that all definitions must match.

And that's about it. The inline keyword basically means that the function definition is in a header file. It tells the linker to not complain when that definition appears in multiple translation units, because that is expected.

Going back to the question, it looks like the intent was to declare an inline function whose definition would appear in only one translation unit. In other words, the function would be flagged as defined in multiple translation units, but the definition would be in only one. Kind of inconsistent there, if not outright contradictory.

Title: Does inline determine internal linkage?

Body:
I'm trying to extern an inline function. How I thought it should work:

//a.cpp
inline void f(int) {}
//b.cpp
extern void f(int);
int main() { f(4); }

But getting link error. Then by reading this ("1) It must be declared inline in every translation unit."). What I've tried:

//a.cpp
inline void f(int) {}
//b.cpp
extern inline void f(int);
int main() { f(4); }

Still getting link error. But now, trying something that I don't know what I'm doing:

//a.cpp
extern inline void f(int) {}
//b.cpp
extern inline void f(int);
int main() { f(4); }

It works. What's happening here? Before adding extern to everything, f in a.cpp had internal linkage?

I'm using MSVC 2017 (v141) with /permissive- and /std:c++17

Body:
I'm trying to extern an inline function.

There is no reason to use extern with a function. See storage duration - linkage. Functions have external linkage by default; in order to not have external linkage, something special needs to be done (i.e. put it in an anonymous namespace or declare it static). So the normal use of an inline function already exhibits external linkage with no need for the extern keyword.

How I thought it should work:

//a.cpp
inline void f(int) {}
//b.cpp
extern void f(int);
int main() { f(4); }

Then by reading this ("1) It must be declared inline in every translation unit.").

That reference is correct, but look up a bit more where it says "The definition of an inline function [...] must be present in the translation unit where it is accessed [...]." Your example has a declaration of f in b.cpp, but not a definition. If you are going to call f from b.cpp, you need the full definition in that translation unit, as in:

inline void f(int) {}

(This is the same code that exists in a.cpp.) If you leave off the curly braces, then you have a declaration but not a definition, making it illegal to call f from that translation unit.

Basically, it is a real pain to define an inline function outside a header file, unless you give it internal linkage. That's because each source file that uses the inline function would need its own copy of the function body, meaning that if you change the function, you need to make that change in multiple files. Oof. Don't do it. Define each of your inline functions in a header file. If you think you want to define one in a source file, you probably misunderstand what "inline" means.

What does "inline" mean?

As far as the compiler is concerned, the inline keyword means (almost) nothing. It is just a flag on a function definition that gets propagated into the object code so that the linker sees it. The compiler processes the function just as it would any other function. The function may be called normally, or calls to it might be inlined – just like any other function.

The one case where the compiler might do something with the inline flag is when a function is declared inline, is used, but lacks a definition. This is an error that can be caught before the linker takes over. It does not have to be caught by the compiler, but it can be. (If not caught by the compiler, it would be caught by the linker.)

Moving on to the linking stage. When the linker sees the inline flag, it suspends the one-definition rule for that function. The linker will expect to see a definition of the function in each translation unit that still uses the function after the compiler's optimizations. It gets to choose any one of those definitions to serve as the final implementation. Hence the reason that all definitions must match.

And that's about it. The inline keyword basically means that the function definition is in a header file. It tells the linker to not complain when that definition appears in multiple translation units, because that is expected.

Going back to the question, it looks like the intent was to declare an inline function whose definition would appear in only one translation unit. In other words, the function would be flagged as defined in multiple translation units, but the definition would be in only one. Kind of inconsistent there, if not outright contradictory.


问:
Changing loglevel in appsettings.json won't get applied to NLog
I am using NLog with dotnet core app configured like described here. https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-2

In nlog.config if I set minLevel to Error and launch my app I can see on logger that logDebug is disabled.

If I restore back to trace then all levels are set to true (error, trace, debug, info, warning)

and if I put this into config file (appsettings.json)

```<code>"Logging": {
        "LogLevel": {
            "Default": "Error",
            "Microsoft": "Information"
        }
    }
</code>```

then nothing happens, all logger levels are still set to true, what might be wrong ?

答:
As Snakefoot mentioned,

this is the config of Microsoft Extension Logging.

When using NLog + Injected .NET Core loggers (using Microsoft Extension Logging), the flow is as follows:

ILogger<MyClass> → LoggerFactory in Microsoft Extension Logging → LogFactory in NLog.

To configure NLog, you should update the NLog <rules> in your nlog.config, e.g.

(also possible from code, see docs)

<rules>
   <logger name="*" minlevel="debug" />
</rules>
```

Please note that you won't see debug logs if the minlevel is "debug" in NLog and "error"
the appsettings.json

note 2:
When using  NLog direct, e.g. the NLog.LogManager.GetCurrentClassLogger(), you only need to configure NLog and the appsettings.json config isn't used for those logs.

Body:
I am using NLog with dotnet core app configured like described here. https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-2

In nlog.config if I set minLevel to Error and launch my app I can see on logger that logDebug is disabled.

If I restore back to trace then all levels are set to true (error, trace, debug, info, warning)

and if I put this into config file (appsettings.json)

"Logging": {
        "LogLevel": {
            "Default": "Error",
            "Microsoft": "Information"
        }
    }

then nothing happens, all logger levels are still set to true, what might be wrong ?

Body:
As Snakefoot mentioned,

this is the config of Microsoft Extension Logging.

When using NLog + Injected .NET Core loggers (using Microsoft Extension Logging), the flow is as follows:

ILogger<MyClass> → LoggerFactory in Microsoft Extension Logging → LogFactory in NLog.

To configure NLog, you should update the NLog <rules> in your nlog.config, e.g.

(also possible from code, see docs)

<rules>
   <logger name="*" minlevel="debug" />
</rules>

Please note that you won't see debug logs if the minlevel is "debug" in NLog and "error"
the appsettings.json

note 2:
When using  NLog direct, e.g. the NLog.LogManager.GetCurrentClassLogger(), you only need to configure NLog and the appsettings.json config isn't used for those logs.


问:
Display single QStandardItem
I have a model using QStandardItemModel and it consists of a single column QStandardItem. I was wondering if there are any widgets in Pyside that i can use to display a single QStandardItem in something like a QLineEdit?

I want to display a single QStandardItem like so:

If users wish to see all the items they can later open a separate dialog displaying all of them like this using a QListView which i already have...

答:
There is no widget that shows the information of an item of a model, but you can build a widget based on a delegate and the model:

from PySide import QtCore, QtGui

class ItemView(QtGui.QWidget):
    def __init__(self, parent=None):
        super(ItemView, self).__init__(parent)
        self.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
        self.m_index = QtCore.QModelIndex()
        self.m_model = None
        self.m_icon_size = QtCore.QSize()
        self.m_text_elide_mode = QtCore.Qt.ElideRight
        self.m_wrap_item_text = False

        self.m_delegate = QtGui.QStyledItemDelegate(self)

    def model(self):
        return self.m_model

    def setModel(self, model):
        self.m_model = model
        self.update()

    def setItemDelegate(self, delegate):
        if delegate is None:
            return
        if self.m_delegate.parent() == self:
            self.m_delegate.deleteLater()
        self.m_delegate = delegate
        self.m_delegate.sizeHintChanged.connect(self.update)

    def delegate(self):
        return self.m_delegate

    def index(self):
        return self.m_index

    def setIndex(self, index):
        if index.isValid() and index.model() == self.model():
            self.m_index = index
            self.update()

    def textElideMode(self):
        return self.m_text_elide_mode

    def setTextElideMode(self, mode):
        self.m_text_elide_mode = mode
        self.update()

    def wordWrap(self):
        return self.m_wrap_item_text

    def setWordWrap(self, on):
        self.m_wrap_item_text = on
        self.update()

    def iconSize(self):
        return self.m_icon_size

    def setIconSize(self, size):
        self.m_icon_size = size
        self.update()

    def viewOptions(self):
        option = QtGui.QStyleOptionViewItem()
        option.init(self)
        option.state &= ~QtGui.QStyle.State_MouseOver
        option.font = self.font()
        if not self.hasFocus():
            option.state &= ~QtGui.QStyle.State_Active
        option.state &= ~QtGui.QStyle.State_HasFocus
        if self.m_icon_size.isValid():
            option.decorationSize = self.m_icon_size
        else:
            pm = self.style().pixelMetric(
                QtGui.QStyle.PM_SmallIconSize, None, self
            )
            option.decorationSize = QtCore.QSize(pm, pm)
        option.decorationPosition = QtGui.QStyleOptionViewItem.Left
        option.decorationAlignment = QtCore.Qt.AlignVCenter
        option.textElideMode = self.m_text_elide_mode
        option.rect = QtCore.QRect()
        option.showDecorationSelected = self.style().styleHint(
            QtGui.QStyle.SH_ItemView_ShowDecorationSelected, None, self
        )
        if self.m_wrap_item_text:
            option.features = QtGui.QStyleOptionViewItem.WrapText
        option.locale = self.locale()
        option.locale.setNumberOptions(QtCore.QLocale.OmitGroupSeparator)
        option.Widget = self
        return option

    def paintEvent(self, event):
        if self.m_model is None or not self.m_index.isValid():
            return

        painter = QtGui.QPainter(self)
        option = self.viewOptions()
        option.rect = self.rect()
        cg = QtGui.QPalette.ColorGroup()
        if (
            self.m_model.flags(self.m_index) & QtCore.Qt.ItemIsEnabled
            == QtCore.Qt.NoItemFlags
        ):
            option.state &= ~QtGui.QStyle.State_Enabled
            cg = QtGui.QPalette.Disabled
        else:
            cg = QtGui.QPalette.Normal
        option.palette.setCurrentColorGroup(cg)
        if self.hasFocus():
            option.state |= QtGui.QStyle.State_HasFocus

        self.m_delegate.paint(painter, option, self.m_index)

    def sizeHint(self):
        option = self.viewOptions()
        size = self.m_delegate.sizeHint(option, self.m_index)
        return size

if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)

    view = QtGui.QListView()
    model = QtGui.QStandardItemModel(view)
    view.setModel(model)

    icons = [
        "SP_TitleBarMinButton",
        "SP_TitleBarMenuButton",
        "SP_TitleBarMaxButton",
        "SP_TitleBarCloseButton",
        "SP_TitleBarNormalButton",
        "SP_TitleBarShadeButton",
        "SP_TitleBarUnshadeButton",
        "SP_TitleBarContextHelpButton",
        "SP_MessageBoxInformation",
        "SP_MessageBoxWarning",
        "SP_MessageBoxCritical",
        "SP_MessageBoxQuestion",
        "SP_DesktopIcon",
        "SP_TrashIcon",
        "SP_ComputerIcon",
        "SP_DriveFDIcon",
        "SP_DriveHDIcon",
        "SP_DriveCDIcon",
        "SP_DriveDVDIcon",
        "SP_DriveNetIcon",
        "SP_DirHomeIcon",
        "SP_DirOpenIcon",
        "SP_DirClosedIcon",
        "SP_DirIcon",
        "SP_DirLinkIcon",
        "SP_FileIcon",
        "SP_FileLinkIcon",
        "SP_FileDialogStart",
        "SP_FileDialogEnd",
        "SP_FileDialogToParent",
        "SP_FileDialogNewFolder",
        "SP_FileDialogDetailedView",
        "SP_FileDialogInfoView",
        "SP_FileDialogContentsView",
        "SP_FileDialogListView",
        "SP_FileDialogBack",
        "SP_DockWidgetCloseButton",
        "SP_ToolBarHorizontalExtensionButton",
        "SP_ToolBarVerticalExtensionButton",
        "SP_DialogOkButton",
        "SP_DialogCancelButton",
        "SP_DialogHelpButton",
        "SP_DialogOpenButton",
        "SP_DialogSaveButton",
        "SP_DialogCloseButton",
        "SP_DialogApplyButton",
        "SP_DialogResetButton",
        "SP_DialogDiscardButton",
        "SP_DialogYesButton",
        "SP_DialogNoButton",
        "SP_ArrowUp",
        "SP_ArrowDown",
        "SP_ArrowLeft",
        "SP_ArrowRight",
        "SP_ArrowBack",
        "SP_ArrowForward",
        "SP_CommandLink",
        "SP_VistaShield",
        "SP_BrowserReload",
        "SP_BrowserStop",
        "SP_MediaPlay",
        "SP_MediaStop",
        "SP_MediaPause",
        "SP_MediaSkipForward",
        "SP_MediaSkipBackward",
        "SP_MediaSeekForward",
        "SP_MediaSeekBackward",
        "SP_MediaVolume",
        "SP_MediaVolumeMuted",
        "SP_CustomBase",
    ]
    for icon_name in icons:
        icon = QtGui.QApplication.style().standardIcon(
            getattr(QtGui.QStyle, icon_name)
        )
        it = QtGui.QStandardItem(icon, icon_name)
        model.appendRow(it)

    item_view = ItemView()
    item_view.setModel(model)

    view.selectionModel().currentChanged.connect(item_view.setIndex)
    view.setCurrentIndex(model.index(0, 0))

    w = QtGui.QWidget()
    lay = QtGui.QVBoxLayout(w)
    lay.addWidget(view)
    lay.addWidget(item_view)
    w.show()
    sys.exit(app.exec_())
```

Title: Display single QStandardItem


问:
How to fix Null Point Exception in Google Or-Tools solution?
When i create test for Google Or-Tools and send my distance matrix, solution the solution is always null.

When i use default distance matrix from here https://developers.google.com/optimization/routing/vrp
but when i use my custom distanceMatrix array Assigment solution is always null.

Where is mistake?

Full test class

```<code>import com.google.ortools.constraintsolver.*;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.logging.Logger;

@RunWith(SpringRunner.class)
@SpringBootTest
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class OrToolsTests {

    private static final Logger logger = Logger.getLogger(OrToolsTests.class.getName());

    static {
        System.loadLibrary("jniortools");
    }

    @Test
    public void b_googleOrTools() throws Exception {
        // Instantiate the data problem.
        final DataModel data = new DataModel();

        // Create Routing Index Manager
        RoutingIndexManager manager =
                new RoutingIndexManager(data.data.length, data.vehicleNumber, data.depot);

        // Create Routing Model.
        RoutingModel routing = new RoutingModel(manager);

        // Create and register a transit callback.
        final int transitCallbackIndex =
                routing.registerTransitCallback((long fromIndex, long toIndex) -> {
                    // Convert from routing variable Index to user NodeIndex.
                    int fromNode = manager.indexToNode(fromIndex);
                    int toNode = manager.indexToNode(toIndex);
                    return data.data[fromNode][toNode];
                });

        // Define cost of each arc.
        routing.setArcCostEvaluatorOfAllVehicles(transitCallbackIndex);

        // Add Distance constraint.
        routing.addDimension(transitCallbackIndex, 0, 3000,
                true, // start cumul to zero
                "Distance");
        RoutingDimension distanceDimension = routing.getMutableDimension("Distance");
        distanceDimension.setGlobalSpanCostCoefficient(100);

        // Setting first solution heuristic.
        RoutingSearchParameters searchParameters =
                main.defaultRoutingSearchParameters()
                        .toBuilder()
                        .setFirstSolutionStrategy(FirstSolutionStrategy.Value.PATH_CHEAPEST_ARC)
                        .build();

        // Solve the problem.
        Assignment solution = routing.solveWithParameters(searchParameters);

        // Print solution on console.
        printSolution(data, routing, manager, solution);
    }

    private void printSolution(
            DataModel data, RoutingModel routing, RoutingIndexManager manager, Assignment solution) {
        // Inspect solution.
        long maxRouteDistance = 0;
        for (int i = 0; i < data.vehicleNumber; ++i) {
            long index = routing.start(i);
            logger.info("Route for Vehicle " + i + ":");
            long routeDistance = 0;
            String route = "";
            while (!routing.isEnd(index)) {
                route += manager.indexToNode(index) + " -> ";
                long previousIndex = index;
                index = solution.value(routing.nextVar(index));
                routeDistance += routing.getArcCostForVehicle(previousIndex, index, i);
            }
            logger.info(route + manager.indexToNode(index));
            logger.info("Distance of the route: " + routeDistance + "m");
            maxRouteDistance = Math.max(routeDistance, maxRouteDistance);
        }
        logger.info("Maximum of the route distances: " + maxRouteDistance + "m");
    }

    class DataModel {
        public final long[][] data = {
                {0, 58305, 41338, 16599, 22834, 36364, 24979, 9797, 22023, 5880, 21282, 39248},
                {58147, 0, 82634, 49102, 39605, 93558, 72909, 49687, 67379, 55889, 76274, 22047},
                {41663, 81167, 0, 47046, 58798, 56366, 18071, 41586, 60532, 36117, 49432, 74933},
                {15666, 49990, 53000, 0, 7358, 51077, 30428, 13558, 34534, 13408, 33793, 30933},
                {22151, 39552, 59486, 7391, 0, 57563, 36914, 20043, 41019, 19893, 40278, 24535},
                {36164, 93036, 56237, 51331, 57566, 0, 37419, 44529, 44381, 41822, 17567, 73980},
                {25224, 72585, 18046, 30880, 37115, 37483, 0, 25147, 44093, 19678, 30549, 53529},
                {9218, 49544, 41424, 13485, 19719, 44630, 25065, 0, 28086, 5966, 27345, 30488},
                {22816, 72597, 60379, 34430, 40665, 44423, 44020, 27629, 0, 24921, 27138, 57079},
                {6858, 56163, 36826, 14458, 20693, 42270, 20467, 6781, 25726, 0, 24985, 37107},
                {22678, 75998, 49002, 34292, 40527, 17284, 30184, 27490, 27342, 24783, 0, 56941},
                {38986, 22165, 76018, 29941, 24347, 74398, 53749, 30526, 57854, 36728, 57113, 0}};
        public final int vehicleNumber = 4;
        public final int depot = 0;
    }
}
</code>```

答: From what I understand, you add a dimension with a max cumul of 3000, while the distance matrix has a lot of inter-node distances above 10k.</p>

Body:
When i create test for Google Or-Tools and send my distance matrix, solution the solution is always null.

When i use default distance matrix from here https://developers.google.com/optimization/routing/vrp
but when i use my custom distanceMatrix array Assigment solution is always null.

Where is mistake?

Full test class

import com.google.ortools.constraintsolver.*;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.logging.Logger;

@RunWith(SpringRunner.class)
@SpringBootTest
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class OrToolsTests {

    private static final Logger logger = Logger.getLogger(OrToolsTests.class.getName());

    static {
        System.loadLibrary("jniortools");
    }

    @Test
    public void b_googleOrTools() throws Exception {
        // Instantiate the data problem.
        final DataModel data = new DataModel();

        // Create Routing Index Manager
        RoutingIndexManager manager =
                new RoutingIndexManager(data.data.length, data.vehicleNumber, data.depot);

        // Create Routing Model.
        RoutingModel routing = new RoutingModel(manager);

        // Create and register a transit callback.
        final int transitCallbackIndex =
                routing.registerTransitCallback((long fromIndex, long toIndex) -> {
                    // Convert from routing variable Index to user NodeIndex.
                    int fromNode = manager.indexToNode(fromIndex);
                    int toNode = manager.indexToNode(toIndex);
                    return data.data[fromNode][toNode];
                });

        // Define cost of each arc.
        routing.setArcCostEvaluatorOfAllVehicles(transitCallbackIndex);

        // Add Distance constraint.
        routing.addDimension(transitCallbackIndex, 0, 3000,
                true, // start cumul to zero
                "Distance");
        RoutingDimension distanceDimension = routing.getMutableDimension("Distance");
        distanceDimension.setGlobalSpanCostCoefficient(100);

        // Setting first solution heuristic.
        RoutingSearchParameters searchParameters =
                main.defaultRoutingSearchParameters()
                        .toBuilder()
                        .setFirstSolutionStrategy(FirstSolutionStrategy.Value.PATH_CHEAPEST_ARC)
                        .build();

        // Solve the problem.
        Assignment solution = routing.solveWithParameters(searchParameters);

        // Print solution on console.
        printSolution(data, routing, manager, solution);
    }

    private void printSolution(
            DataModel data, RoutingModel routing, RoutingIndexManager manager, Assignment solution) {
        // Inspect solution.
        long maxRouteDistance = 0;
        for (int i = 0; i < data.vehicleNumber; ++i) {
            long index = routing.start(i);
            logger.info("Route for Vehicle " + i + ":");
            long routeDistance = 0;
            String route = "";
            while (!routing.isEnd(index)) {
                route += manager.indexToNode(index) + " -> ";
                long previousIndex = index;
                index = solution.value(routing.nextVar(index));
                routeDistance += routing.getArcCostForVehicle(previousIndex, index, i);
            }
            logger.info(route + manager.indexToNode(index));
            logger.info("Distance of the route: " + routeDistance + "m");
            maxRouteDistance = Math.max(routeDistance, maxRouteDistance);
        }
        logger.info("Maximum of the route distances: " + maxRouteDistance + "m");
    }

    class DataModel {
        public final long[][] data = {
                {0, 58305, 41338, 16599, 22834, 36364, 24979, 9797, 22023, 5880, 21282, 39248},
                {58147, 0, 82634, 49102, 39605, 93558, 72909, 49687, 67379, 55889, 76274, 22047},
                {41663, 81167, 0, 47046, 58798, 56366, 18071, 41586, 60532, 36117, 49432, 74933},
                {15666, 49990, 53000, 0, 7358, 51077, 30428, 13558, 34534, 13408, 33793, 30933},
                {22151, 39552, 59486, 7391, 0, 57563, 36914, 20043, 41019, 19893, 40278, 24535},
                {36164, 93036, 56237, 51331, 57566, 0, 37419, 44529, 44381, 41822, 17567, 73980},
                {25224, 72585, 18046, 30880, 37115, 37483, 0, 25147, 44093, 19678, 30549, 53529},
                {9218, 49544, 41424, 13485, 19719, 44630, 25065, 0, 28086, 5966, 27345, 30488},
                {22816, 72597, 60379, 34430, 40665, 44423, 44020, 27629, 0, 24921, 27138, 57079},
                {6858, 56163, 36826, 14458, 20693, 42270, 20467, 6781, 25726, 0, 24985, 37107},
                {22678, 75998, 49002, 34292, 40527, 17284, 30184, 27490, 27342, 24783, 0, 56941},
                {38986, 22165, 76018, 29941, 24347, 74398, 53749, 30526, 57854, 36728, 57113, 0}};
        public final int vehicleNumber = 4;
        public final int depot = 0;
    }
}


问:
No such file or directory #include <QDebug>
Why I got an error:

I use Qt Creator. Version Qt 5.9.7 for Desktop

Output::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

```<code>23:02:13: Uruchamianie "/usr/bin/make"
g++ -c -pipe -g -std=gnu++11 -Wall -W -fPIC -DQT_QML_DEBUG -I../Kurs_STL_cpp0x -I. -I../../anaconda3/mkspecs/linux-g++ -o main.o ../Kurs_STL_cpp0x/main.cpp
../Kurs_STL_cpp0x/main.cpp:4:10: fatal error: Debug: No such file or directory
 #include <Debug>
          ^~~~~~~
compilation terminated.
Makefile:627: recipe for target 'main.o' failed
make: *** [main.o] Error 1
23:02:13: Proces "/usr/bin/make" zakończył się kodem wyjściowym 2.
Błąd budowania / instalowania projektu Kurs_STL_cpp0x (zestaw narzędzi: Desktop)
Podczas wykonywania kroku "Make"
23:02:13: Czas trwania: 00:00.
</code>```

答:
When you select a non-Qt project, the generated *.pro file is configured to disable Qt (and you will not be able to include Qt files).

In *.pro file, remove the line CONFIG -= qt to enable Qt.

After that, you may need to include the different Qt modules (widgets, quick, etc.) by adding them to the env variable QT (the module core and gui should be enabled by default).

For example, to use the Qt Widgets and Qt Quick, you have to add QT += widgets quick

You can also disable useless modules by adding a line like QT -= gui

Body:
Why I got an error:

I use Qt Creator. Version Qt 5.9.7 for Desktop

Output::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

23:02:13: Uruchamianie "/usr/bin/make"
g++ -c -pipe -g -std=gnu++11 -Wall -W -fPIC -DQT_QML_DEBUG -I../Kurs_STL_cpp0x -I. -I../../anaconda3/mkspecs/linux-g++ -o main.o ../Kurs_STL_cpp0x/main.cpp
../Kurs_STL_cpp0x/main.cpp:4:10: fatal error: Debug: No such file or directory
 #include <Debug>
          ^~~~~~~
compilation terminated.
Makefile:627: recipe for target 'main.o' failed
make: *** [main.o] Error 1
23:02:13: Proces "/usr/bin/make" zakończył się kodem wyjściowym 2.
Błąd budowania / instalowania projektu Kurs_STL_cpp0x (zestaw narzędzi: Desktop)
Podczas wykonywania kroku "Make"
23:02:13: Czas trwania: 00:00.


问:
Does Gwt 2.1 Entity Proxy support transparent call to lazy loaded entity relations?
Well, I have read the document about Entity Proxy http://code.google.com/webtoolkit/doc/latest/DevGuideRequestFactory.html . As far as I understood Entity Proxy does not support transparently calling of lazy loaded entity relations. Such as, I have Employee entity, and this entity has supervisor field whose type is Employee, and this field fetch type is lazy.. When I have queried an employee, can I call its getSupervisor method at GWT layer?.. What I expect EmployeeProxy calls transparently getSupervisor method of Employee entity on the server.. Is this the case?.  </p>

答: There is the gilead project that might do what you intend.</p>

ContentLicense: CC BY-SA 2.5


问:
How Can I Organize and Reduce The Amount of Classes in My Application
I guess this is more of a Design Pattern question than coding question. So here we go... I have an android application that contain many classes and activities. I have classes grouped inside directory according to their function eg: DownloadTask, ScanTask inside the AsyncTask directory. Then I have all all activities inside the activity directory and so on. But I notice that a lot of my code is repeated. For example, I have 3 Activities PingActivity, NetstatActivity, WhoisActivity that basically look entriely the same from the  point of view of the code. The only difference is the command their using eg: ping host for PingActivity, netstat -ant for NetstatActivity and so on.. they all instanciate the views from an xml layout that looks very similar since all I have is EditText, button, and TextView. And the classes Call AsyncTask to perform the background process separate from the main thread. With the exception of WhoisActivity which use rest api service to query for domain name. So my question is how can I simplify my design? can I use one single class and pass the command or api depending what menu option the user selected? how can I do that? thanks</p>

答:
Just a few suggestions, in my humble opinion...

Reducing the number of classes should never be a goal by itself.

Multiple pieces of code that look the same, may actually do different things in terms of logic, and may evolve in very different ways in the future (DRY is about knowledge, not code).

Always design with SOLID in mind, when you say "can I use one single class and pass the command or api", that sounds worse for the Single-Responsibility and the Open-Closed principles.

Having said that, if there are pieces of code that look (and actually are) equal, try to factor them out into services that get injected in your classes. Just do not try to reduce complexity by putting all the code that looks similar in a class/method with a few parameters and some if-else/switch blocks, because in long term that's usually much worse than having a lot of small and organised classes.


问:
How to properly scale/rotate images in pyqtgraph?
I have implemented pyqtgraph inside QGraphicsView in PyQt5. When I display the image the following way, it is stretched out and expands in the same aspect ratio as the screen. How do I fix this?

```<code>image = pg.ImageItem(asarray(Image.open('pic.png')) )
self.graphicsView.addItem(image)
image.rotate(270)
</code>```

EDIT: found out how to rotate image, so I updated question with the solution. Now I am just trying to scale it properly.

答:
I used np.rot90() instead, it's much faster and cythonable

image = pg.ImageItem(np.rot90(np.asarray(Image.open('pic.png'))))
```

Body:
I have implemented pyqtgraph inside QGraphicsView in PyQt5. When I display the image the following way, it is stretched out and expands in the same aspect ratio as the screen. How do I fix this?

image = pg.ImageItem(asarray(Image.open('pic.png')) )
self.graphicsView.addItem(image)
image.rotate(270)

EDIT: found out how to rotate image, so I updated question with the solution. Now I am just trying to scale it properly.


问:
Multiple ifs within list comprehension
I've used a list comprehension which is supposed to store keys and values in itemDict variable considering the fact that some items if present in item['keys'] will not be included in itemDict. I've used multiple if conditions to make that possible.

This is what I've tried with:

```<code>itemDict = {item['keys']:item['value'] for item in soup.select('input[keys]') if '$cmdPrint' not in item['name'] and 'btnView' not in item['name'] and 'btnMyDoc' not in item['key']}
</code>```

How can I rewrite those conditions to make it concise?

答:
You could use a check function and use all builtin. Also reformat the comprehension for readability.

```<code>def check(item):
    return all(('$cmdPrint' not in item['name'],
           'btnView' not in item['name'],
           'btnMyDoc' not in item['key']))

itemDict = {item['keys']:item['value']
            for item in soup.select('input[keys]')
            if check(item)}
</code>```

Or use it in the comprehension, but that's one long comprehension.

```<code>itemDict = {item['keys']:item['value']
            for item in soup.select('input[keys]')
            if all(('$cmdPrint' not in item['name'],
                    'btnView' not in item['name'],
                    'btnMyDoc' not in item['key']))}
</code>```

Or just use a regular for loop:

```<code>itemDict = {}
for item in soup.select('input[keys]')
    if check(item):
        itemDict[item['keys']] = item['value']
</code>```

Title: Multiple ifs within list comprehension

Body:
I've used a list comprehension which is supposed to store keys and values in itemDict variable considering the fact that some items if present in item['keys'] will not be included in itemDict. I've used multiple if conditions to make that possible.

This is what I've tried with:

itemDict = {item['keys']:item['value'] for item in soup.select('input[keys]') if '$cmdPrint' not in item['name'] and 'btnView' not in item['name'] and 'btnMyDoc' not in item['key']}

How can I rewrite those conditions to make it concise?

Body:
You could use a check function and use all builtin. Also reformat the comprehension for readability.

def check(item):
    return all(('$cmdPrint' not in item['name'],
           'btnView' not in item['name'],
           'btnMyDoc' not in item['key']))

itemDict = {item['keys']:item['value']
            for item in soup.select('input[keys]')
            if check(item)}

Or use it in the comprehension, but that's one long comprehension.

itemDict = {item['keys']:item['value']
            for item in soup.select('input[keys]')
            if all(('$cmdPrint' not in item['name'],
                    'btnView' not in item['name'],
                    'btnMyDoc' not in item['key']))}

Or just use a regular for loop:

itemDict = {}
for item in soup.select('input[keys]')
    if check(item):
        itemDict[item['keys']] = item['value']


问:
sql trouble, need to combine 2 runnable code
i have 2 runnable code but i need to combine these 2 codes into 1

```<code>SELECT `doc`.`date`,`doc`.`no`,`def`.`name`,`i`.`type`
FROM `documents` as `doc`
    RIGHT JOIN `items` as `i` ON `i`.`document_id` = `doc`.`id`
    RIGHT JOIN `definitions` as `def` ON `doc`.`type_id` = `def`.`id`
WHERE `doc`.`id`= 2
</code>```

this is the first code that i have

```<code>SELECT `alacak`,`ödeme`,(`alacak` - `ödeme`) as `bakiye`
FROM (SELECT (SELECT IFNULL(SUM( `quantity` * `price` * `d`.`currency_value` / 100 ), 0) AS `alacak` FROM `items` as `i`
        RIGHT JOIN `documents` as `d` ON `d`.`id` = `i`.`document_id` WHERE `d`.`type_group` = 'sales') as `alacak`,
        (SELECT IFNULL(SUM( `quantity` * `price` * `d`.`currency_value` / 100 ), 0) AS `ödeme` FROM `items` as `i`
        RIGHT JOIN `documents` as `d` ON `d`.`id` = `i`.`document_id` WHERE `d`.`type_group` = 'purchases') as `ödeme`) as  `table
</code>```

and this is the second

i need to combine these 2 codes and receive 1 working codes.

答:
You can get an overall idea of joining both scripts into one from the below script. But you need to adjust/decide which column is required in the selection part as they are also need to add in the GROUP BY clause and the result will change-</p>

```<code>SELECT `doc`.`date`,`doc`.`no`,`def`.`name`,`i`.`type`,
IFNULL(SUM( CASE WHEN  `d`.`type_group` = 'sales' THEN (`quantity` * `price` * `d`.`currency_value`) / 100 ELSE 0 END ), 0) AS `alacak` ,
IFNULL(SUM( CASE WHEN  `d`.`type_group` = 'purchases' THEN (`quantity` * `price` * `d`.`currency_value`) / 100 ELSE 0 END ) , 0) AS  `ödeme` ,

IFNULL(SUM( CASE WHEN  `d`.`type_group` = 'sales' THEN (`quantity` * `price` * `d`.`currency_value`) / 100 ELSE 0 END ), 0)
-
IFNULL(SUM( CASE WHEN  `d`.`type_group` = 'purchases' THEN (`quantity` * `price` * `d`.`currency_value`) / 100 ELSE 0 END ) , 0)
as `bakiye`
FROM `items` as `i`
RIGHT JOIN `documents` as `d` ON `d`.`id` = `i`.`document_id`
RIGHT JOIN `definitions` as `def` ON `doc`.`type_id` = `def`.`id`
WHERE `d`.`id`= 2
GROUP BY `d`.`date`,`d`.`no`,`def`.`name`,`i`.`type`
</code>```

Body:
i have 2 runnable code but i need to combine these 2 codes into 1

SELECT `doc`.`date`,`doc`.`no`,`def`.`name`,`i`.`type`
FROM `documents` as `doc`
    RIGHT JOIN `items` as `i` ON `i`.`document_id` = `doc`.`id`
    RIGHT JOIN `definitions` as `def` ON `doc`.`type_id` = `def`.`id`
WHERE `doc`.`id`= 2

this is the first code that i have

SELECT `alacak`,`ödeme`,(`alacak` - `ödeme`) as `bakiye`
FROM (SELECT (SELECT IFNULL(SUM( `quantity` * `price` * `d`.`currency_value` / 100 ), 0) AS `alacak` FROM `items` as `i`
        RIGHT JOIN `documents` as `d` ON `d`.`id` = `i`.`document_id` WHERE `d`.`type_group` = 'sales') as `alacak`,
        (SELECT IFNULL(SUM( `quantity` * `price` * `d`.`currency_value` / 100 ), 0) AS `ödeme` FROM `items` as `i`
        RIGHT JOIN `documents` as `d` ON `d`.`id` = `i`.`document_id` WHERE `d`.`type_group` = 'purchases') as `ödeme`) as  `table

and this is the second

i need to combine these 2 codes and receive 1 working codes.

Body:
You can get an overall idea of joining both scripts into one from the below script. But you need to adjust/decide which column is required in the selection part as they are also need to add in the GROUP BY clause and the result will change-

SELECT `doc`.`date`,`doc`.`no`,`def`.`name`,`i`.`type`,
IFNULL(SUM( CASE WHEN  `d`.`type_group` = 'sales' THEN (`quantity` * `price` * `d`.`currency_value`) / 100 ELSE 0 END ), 0) AS `alacak` ,
IFNULL(SUM( CASE WHEN  `d`.`type_group` = 'purchases' THEN (`quantity` * `price` * `d`.`currency_value`) / 100 ELSE 0 END ) , 0) AS  `ödeme` ,

IFNULL(SUM( CASE WHEN  `d`.`type_group` = 'sales' THEN (`quantity` * `price` * `d`.`currency_value`) / 100 ELSE 0 END ), 0)
-
IFNULL(SUM( CASE WHEN  `d`.`type_group` = 'purchases' THEN (`quantity` * `price` * `d`.`currency_value`) / 100 ELSE 0 END ) , 0)
as `bakiye`
FROM `items` as `i`
RIGHT JOIN `documents` as `d` ON `d`.`id` = `i`.`document_id`
RIGHT JOIN `definitions` as `def` ON `doc`.`type_id` = `def`.`id`
WHERE `d`.`id`= 2
GROUP BY `d`.`date`,`d`.`no`,`def`.`name`,`i`.`type`


问:
Remove Element from JDOM document using removeContent()
Given the following scenario, where the xml, Geography.xml looks like -

```<code><Geography xmlns:ns="some valid namespace">
    <Country>
        <Region>
            <State>
                <City>
                    <Name></Name>
                    <Population></Population>
                </City>
            </State>
            </Region>
        </Country>
    </Geography>
</code>```

and the following sample java code -

```<code>InputStream is = new FileInputStream("C:\\Geography.xml");
SAXBuilder saxBuilder = new SAXBuilder();
Document doc = saxBuilder.build(is);

XPath xpath = XPath.newInstance("/*/Country/Region/State/City");
Element el = (Element) xpath.selectSingleNode(doc);
boolean b = doc.removeContent(el);
</code>```

The removeContent() method doesn't remove the Element City from the content list of the doc. The value of b is false

I don't understand why is it not removing the Element, I even tried to delete the Name & Population elements from the xml just to see if that was the issue but apparently its not.

Another way I tried, I don't know why I know its not essentially different, still just for the sake, was to use Parent -

```<code>Parent p = el.getParent();
boolean s = p.removeContent(new Element("City"));
</code>```

What might the problem? and a possible solution? and if anyone can share the real behaviour of the method removeContent(), I suspect it has to do with the parent-child relationship.

答:
If you want to remove the City element, get its parent and call removeContent:

```<code>    XPath xpath = XPath.newInstance("/*/Country/Region/State/City");
    Element el = (Element) xpath.selectSingleNode(doc);
    el.getParent().removeContent(el);
</code>```

The reason why doc.removeContent(el) does not work is because el is not a child of doc.

Check the javadocs for details. There are a number of overloaded removeContent methods there.

Body:
Given the following scenario, where the xml, Geography.xml looks like -

<Geography xmlns:ns="some valid namespace">
    <Country>
        <Region>
            <State>
                <City>
                    <Name></Name>
                    <Population></Population>
                </City>
            </State>
            </Region>
        </Country>
    </Geography>

and the following sample java code -

InputStream is = new FileInputStream("C:\\Geography.xml");
SAXBuilder saxBuilder = new SAXBuilder();
Document doc = saxBuilder.build(is);

XPath xpath = XPath.newInstance("/*/Country/Region/State/City");
Element el = (Element) xpath.selectSingleNode(doc);
boolean b = doc.removeContent(el);

The removeContent() method doesn't remove the Element City from the content list of the doc. The value of b is false

I don't understand why is it not removing the Element, I even tried to delete the Name & Population elements from the xml just to see if that was the issue but apparently its not.

Another way I tried, I don't know why I know its not essentially different, still just for the sake, was to use Parent -

Parent p = el.getParent();
boolean s = p.removeContent(new Element("City"));

What might the problem? and a possible solution? and if anyone can share the real behaviour of the method removeContent(), I suspect it has to do with the parent-child relationship.

Body:
If you want to remove the City element, get its parent and call removeContent:

    XPath xpath = XPath.newInstance("/*/Country/Region/State/City");
    Element el = (Element) xpath.selectSingleNode(doc);
    el.getParent().removeContent(el);

The reason why doc.removeContent(el) does not work is because el is not a child of doc.

Check the javadocs for details. There are a number of overloaded removeContent methods there.


问:
Translating Nucleotides Triplets
I am trying to split a string of nucleotides in a way that allows me to find the outlier in the center of the nucleotide sequence, and turn it into a triplet by adding "n" to fill in the gaps.

I have tried splitting by number of characters, but the problem is that it happens from left to right, and I have been trying to find a way to do it right to left. So what I have done is find the length of the sequence, which in this one example is 52. Then, I take that length number and divide it by 3, to find the number of potential triplets that there will be. Then, I divide by 2 to know (obviously rounding) how many groups of 3 there will be roughly on each side of the outlier. Ideally, I want one more triplet on the left hand side than on the right hand side. The outlier would remain in the middle (either as one nucleotide, or two). For example:

```<code>nucleobases <- 'TGTGCCAGCAGTTTAAGGTAGATAGCGGGATTCCTACAATGAGCAGTTCTTC'
nucleolength <- nchar("TGTGCCAGCAGTTTAAGGTAGATAGCGGGATTCCTACAATGAGCAGTTCTTC")
num1 <- round(nucleolength/6)*3

firstsplit <- gsub("(.{27})", "\\1 ", nucleobases) #This works for the first half

secondsplit <- gsub("(.{24})", "\\1 ", firstsplit, rev) #This works, but not in the ideal way that it is supposed to.
</code>```

I do not have any trouble translating the sequences into amino acids, which is my end goal. What I want is to add "n" in the places where it belongs in the sequence (on the outlier) so the ends of the sequences become the correct amino acids. This is ultimately what I would like:

```<code>#original sequence: TGTGCCAGCAGTTTAAGGTAGATAGCGGGATTCCTACAATGAGCAGTTCTTC
#split up in the correct places: TGTGCCAGCAGTTTAAGGTAGATAGCG G GATTCCTACAATGAGCAGTTCTTC
#"N" fills in the outlier: TGTGCCAGCAGTTTAAGGTAGATAGCG GNN GATTCCTACAATGAGCAGTTCTTC
#Gaps are then eliminated and sequence is translated: TGTGCCAGCAGTTTAAGGTAGATAGCGGNNGATTCCTACAATGAGCAGTTCTTC
#Translated sequence: CASSLR-IAXDSYNEQFF
</code>```

If anyone has an idea of how to do this in an efficient way possible, it would be great to know! Also, something to keep in mind is that this is not the only sequence. There are other sequences with different lengths (47, 46, 35, etc.). To reiterate, the grouped sequence on the left should be longer than the right, with the outlier in the middle. Please keep in mind that the groups should be a multiple of 3 (since they are codons), all except for the outlier. Thank you!!

答:
It's possible to use sub, as well:

```<code>dna <- 'TGTGCCAGCAGTTTAAGGTAGATAGCGGGATTCCTACAATGAGCAGTTCTTC'

fillorf <- function(dna){
  nout <- nchar(dna) %% 3
  if(nout){
    nleft <- (nchar(dna) %/% 6 + 1) * 3 + nout
    dna <- sub(
      paste('(^.{', nleft, '})(.+$)', sep = ''),
      paste('\\1', substr('NN', 1, 3 - nout), '\\2', sep = ''),
      dna
    )
  }
  return(dna)
}

# > fillorf(dna)
# [1] "TGTGCCAGCAGTTTAAGGTAGATAGCGGNNGATTCCTACAATGAGCAGTTCTTC"
</code>```

Title: Translating Nucleotides Triplets

Body:
I am trying to split a string of nucleotides in a way that allows me to find the outlier in the center of the nucleotide sequence, and turn it into a triplet by adding "n" to fill in the gaps.

I have tried splitting by number of characters, but the problem is that it happens from left to right, and I have been trying to find a way to do it right to left. So what I have done is find the length of the sequence, which in this one example is 52. Then, I take that length number and divide it by 3, to find the number of potential triplets that there will be. Then, I divide by 2 to know (obviously rounding) how many groups of 3 there will be roughly on each side of the outlier. Ideally, I want one more triplet on the left hand side than on the right hand side. The outlier would remain in the middle (either as one nucleotide, or two). For example:

nucleobases <- 'TGTGCCAGCAGTTTAAGGTAGATAGCGGGATTCCTACAATGAGCAGTTCTTC'
nucleolength <- nchar("TGTGCCAGCAGTTTAAGGTAGATAGCGGGATTCCTACAATGAGCAGTTCTTC")
num1 <- round(nucleolength/6)*3

firstsplit <- gsub("(.{27})", "\\1 ", nucleobases) #This works for the first half

secondsplit <- gsub("(.{24})", "\\1 ", firstsplit, rev) #This works, but not in the ideal way that it is supposed to.

I do not have any trouble translating the sequences into amino acids, which is my end goal. What I want is to add "n" in the places where it belongs in the sequence (on the outlier) so the ends of the sequences become the correct amino acids. This is ultimately what I would like:

#original sequence: TGTGCCAGCAGTTTAAGGTAGATAGCGGGATTCCTACAATGAGCAGTTCTTC
#split up in the correct places: TGTGCCAGCAGTTTAAGGTAGATAGCG G GATTCCTACAATGAGCAGTTCTTC
#"N" fills in the outlier: TGTGCCAGCAGTTTAAGGTAGATAGCG GNN GATTCCTACAATGAGCAGTTCTTC
#Gaps are then eliminated and sequence is translated: TGTGCCAGCAGTTTAAGGTAGATAGCGGNNGATTCCTACAATGAGCAGTTCTTC
#Translated sequence: CASSLR-IAXDSYNEQFF

If anyone has an idea of how to do this in an efficient way possible, it would be great to know! Also, something to keep in mind is that this is not the only sequence. There are other sequences with different lengths (47, 46, 35, etc.). To reiterate, the grouped sequence on the left should be longer than the right, with the outlier in the middle. Please keep in mind that the groups should be a multiple of 3 (since they are codons), all except for the outlier. Thank you!!

Body:
It's possible to use sub, as well:

dna <- 'TGTGCCAGCAGTTTAAGGTAGATAGCGGGATTCCTACAATGAGCAGTTCTTC'

fillorf <- function(dna){
  nout <- nchar(dna) %% 3
  if(nout){
    nleft <- (nchar(dna) %/% 6 + 1) * 3 + nout
    dna <- sub(
      paste('(^.{', nleft, '})(.+$)', sep = ''),
      paste('\\1', substr('NN', 1, 3 - nout), '\\2', sep = ''),
      dna
    )
  }
  return(dna)
}

# > fillorf(dna)
# [1] "TGTGCCAGCAGTTTAAGGTAGATAGCGGNNGATTCCTACAATGAGCAGTTCTTC"


问:
How do I use BeautifulSoup4 to get ALL text before
 tag into a pandas data frame
I'm trying to extract postcode and suburbs of sydney as dataframe by scraping a website

I've located the corresponding tag in beautifulsup but am not able to finish the process

import requests
from bs4 import BeautifulSoup

url = 'https://data.mongabay.com/igapo/australia/postcodes/sydney-numeric.html'
res = requests.get(url)
soup = BeautifulSoup(res.text,'html5lib')

table = soup.find_all('table')[10]

rows = table.find_all('td')[2]

for br in rows.find_all("br"):
    br.replace_with("\n")

parsedText = rows.get_text()

```

<p>I'm expecting a dataframe such as:</p>

<pre class="lang-py prettyprint-override"><code>postcode suburbs
2000 Australia Square Post Office
2000 Circular Quay
2000 Clarence Street Post Office
...
</code>```

thank you for your help

答:
You did pretty much all the work! You just have to read it in correctly.

```<code>from io import StringIO
import re

pd.read_csv(StringIO(parsedText), sep= r'(?<=\d) ', header = None, engine = 'python')
</code>```

So we need to use StringIO to make your text readable by pd.read_csv, then we can do some regex to define our separator.

r'(?<=\d) ' looks for a space (notice the space after ')' ) if there is a digit preceding it.

Title: How do I use BeautifulSoup4 to get ALL text before <br> tag into a pandas data frame

Body:
I'm trying to extract postcode and suburbs of sydney as dataframe by scraping a website

I've located the corresponding tag in beautifulsup but am not able to finish the process

import requests
from bs4 import BeautifulSoup

url = 'https://data.mongabay.com/igapo/australia/postcodes/sydney-numeric.html'
res = requests.get(url)
soup = BeautifulSoup(res.text,'html5lib')

table = soup.find_all('table')[10]

rows = table.find_all('td')[2]

for br in rows.find_all("br"):
    br.replace_with("\n")

parsedText = rows.get_text()

I'm expecting a dataframe such as:

postcode suburbs
2000 Australia Square Post Office
2000 Circular Quay
2000 Clarence Street Post Office
...

thank you for your help

Body:
You did pretty much all the work! You just have to read it in correctly.

from io import StringIO
import re

pd.read_csv(StringIO(parsedText), sep= r'(?<=\d) ', header = None, engine = 'python')

So we need to use StringIO to make your text readable by pd.read_csv, then we can do some regex to define our separator.

r'(?<=\d) ' looks for a space (notice the space after ')' ) if there is a digit preceding it.