问:
Jupyter notebook markdown without mouse click
For markdown there is a shortcut like typing a number(1,2,3,4..) in command mode (Esc) and then giving an Enter

The thing is that your cursor gets before the "###" (if you used 3) where you also need to click the End key to be able to write.

Is there a way to overcome the last action as it is very annoying.

答: What you already have is a one click solution, which is going to be hard to beat. The only improvement I can think of is to override the functionality that's inserting the markdown headings for you. You could extend it to also place the cell in edit mode and move the cursor to the end. This would be placed in your custom.js file, which you place here: ~/.jupyter/custom/custom.js.


来源: stackexchange

问:
How initialize dataset table that is not in a database?
I created a table in dataset that is not in a database, I need to set data to this table and bind data to a combobox, how can I do this?

```<code>        DataRowView drv = statusBindingSource.AddNew() as DataRowView;
        drv.Row["Value"] = 1;
        drv.Row["Name"] = "Active";
        statusBindingSource.EndEdit();

        statusBindingSource.Add(drv);
</code>```

I cannot add external objects to this list.

答:
The new DataTable is created, filled with data and bound to the combo box. I did not include a DataSet or BindingSource.</p>

```<code>    private void Form1_Load(object sender, EventArgs e)
    {
        CreateDataTable();
        cbo1.SelectedIndex = -1;
    }

    private void CreateDataTable()
    {
        //Create new DataTable
        DataTable dt = new DataTable();
        //Add colums with column name and datatype
        dt.Columns.Add("Value", Type.GetType("System.Int32"));
        dt.Columns.Add("Name", Type.GetType("System.String"));
        //Add data
        object[] data = { 1, "Active" };
        dt.Rows.Add(data);
        object[] data2 = { 2, "Passive" };
        dt.Rows.Add(data2);
        //Bind to combo box
        cbo1.DataSource = dt;
        cbo1.DisplayMember = "Name";
        cbo1.ValueMember = "Value";
    }

    private void Cbo1_SelectionChangeCommitted(object sender, EventArgs e)
    {
        MessageBox.Show($"The display member is {((DataRowView)cbo1.SelectedItem)["Name"]}, The value member is {cbo1.SelectedValue}");
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I created a table in dataset that is not in a database, I need to set data to this table and bind data to a combobox, how can I do this?

        DataRowView drv = statusBindingSource.AddNew() as DataRowView;
        drv.Row["Value"] = 1;
        drv.Row["Name"] = "Active";
        statusBindingSource.EndEdit();

        statusBindingSource.Add(drv);

I cannot add external objects to this list.

Body:
The new DataTable is created, filled with data and bound to the combo box. I did not include a DataSet or BindingSource.

    private void Form1_Load(object sender, EventArgs e)
    {
        CreateDataTable();
        cbo1.SelectedIndex = -1;
    }

    private void CreateDataTable()
    {
        //Create new DataTable
        DataTable dt = new DataTable();
        //Add colums with column name and datatype
        dt.Columns.Add("Value", Type.GetType("System.Int32"));
        dt.Columns.Add("Name", Type.GetType("System.String"));
        //Add data
        object[] data = { 1, "Active" };
        dt.Rows.Add(data);
        object[] data2 = { 2, "Passive" };
        dt.Rows.Add(data2);
        //Bind to combo box
        cbo1.DataSource = dt;
        cbo1.DisplayMember = "Name";
        cbo1.ValueMember = "Value";
    }

    private void Cbo1_SelectionChangeCommitted(object sender, EventArgs e)
    {
        MessageBox.Show($"The display member is {((DataRowView)cbo1.SelectedItem)["Name"]}, The value member is {cbo1.SelectedValue}");
    }


问:
What is the return value of request.args?
I am using request module of flask and trying to fetch arguments in the url by using request.args by using

```<code>req_args = { k:v[0] for k,v in dict(request.args).items() }
</code>```

The v in the above code line turns out to be a list, whereas on my friends laptop it turns out to be a string.
Why is it so?

答:
request.args type is ImmutableMultiDict, it is an immutable version of MultiDict. Here is the link you can click for more information about ImmutableMultiDict

http://flask.pocoo.org/docs/1.0/api/#flask.Request.args

Body:
I am using request module of flask and trying to fetch arguments in the url by using request.args by using

req_args = { k:v[0] for k,v in dict(request.args).items() }

The v in the above code line turns out to be a list, whereas on my friends laptop it turns out to be a string.
Why is it so?


问:
How can I make a button with children in it in Xamarin?
I am very new to Xamarin for mobile. How can I make a box with percentage dimensions such that it contains a square picture on its left, text on its right, and the entire entity is subject to touch like a button? Even better, with the children on the right side to be vertically stacked. The specific configuration as asked is entirely arbitrary, simply a reference example. </p>

答:
There are many ways this could be done, here is one via a Grid that I added a TapGestureRecognizer to it:

Example:

```<code><Grid BackgroundColor="Gray">
    <Grid.GestureRecognizers>
        <TapGestureRecognizer Tapped="Handle_Tapped" />
    </Grid.GestureRecognizers>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="2*" />
        <ColumnDefinition Width="1*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Image Source="deli.jpg" Margin="5,5,5,5" Aspect="AspectFill" Grid.Row="0" Grid.RowSpan="2" Grid.Column="0" />
    <StackLayout BackgroundColor="Black" Orientation="Vertical" Grid.Row="0" Grid.RowSpan="2" Grid.Column="1" VerticalOptions="CenterAndExpand">
        <Label Text="Cured" TextColor="White" HorizontalOptions="CenterAndExpand" VerticalTextAlignment="Center"  />
        <Label Text="Meat" TextColor="White" HorizontalOptions="CenterAndExpand" VerticalTextAlignment="Center" />
        <Label Text="(View More)" TextColor="White" HorizontalOptions="CenterAndExpand" VerticalTextAlignment="Center" />
    </StackLayout>
</Grid>
</code>```

Output:

Body:
There are many ways this could be done, here is one via a Grid that I added a TapGestureRecognizer to it:

Example:

<Grid BackgroundColor="Gray">
    <Grid.GestureRecognizers>
        <TapGestureRecognizer Tapped="Handle_Tapped" />
    </Grid.GestureRecognizers>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="2*" />
        <ColumnDefinition Width="1*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Image Source="deli.jpg" Margin="5,5,5,5" Aspect="AspectFill" Grid.Row="0" Grid.RowSpan="2" Grid.Column="0" />
    <StackLayout BackgroundColor="Black" Orientation="Vertical" Grid.Row="0" Grid.RowSpan="2" Grid.Column="1" VerticalOptions="CenterAndExpand">
        <Label Text="Cured" TextColor="White" HorizontalOptions="CenterAndExpand" VerticalTextAlignment="Center"  />
        <Label Text="Meat" TextColor="White" HorizontalOptions="CenterAndExpand" VerticalTextAlignment="Center" />
        <Label Text="(View More)" TextColor="White" HorizontalOptions="CenterAndExpand" VerticalTextAlignment="Center" />
    </StackLayout>
</Grid>

Output:


问:
How can I increase the speed of string generating in my code?
By searching I could find the following solution to generate all the combination of a given string and calculate their hash values. Now I can  generate 10000000 strings and hash values in 21 seconds. However, I need a faster method. </p>

```<code>import itertools
import hashlib
import time

def pow():
    global cnt
    authdata = "eTSlASZYlLNgKJuYeIQvGVbiAcLEEOVgAQPzSrtCOIwQxQHyFHcfjgRQJBJDlojx";
    l = 'abcdefghij'
    result = itertools.product(*([l] * 7))
    for each in result:
        cnt = cnt + 1
        suffix = ''.join(each)
        authdataSuffix = authdata + suffix
        hashValue = hashlib.sha1(authdataSuffix.encode('utf-8')).hexdigest()
        if  hashValue.startswith("0"*8):
            print (hashValue)

cnt = 0
start = time.time()
pow()
end = time.time()
print(cnt)
print(end - start)
</code>```

答:
Some remarks for improvements:

Do not use global variables

Use timeit for meaningful measurements

Use Python 3

I think you can use permutations from itertools, which is faster in generating, but also produces less data

Make everything possible constant

Body:
By searching I could find the following solution to generate all the combination of a given string and calculate their hash values. Now I can  generate 10000000 strings and hash values in 21 seconds. However, I need a faster method.

import itertools
import hashlib
import time

def pow():
    global cnt
    authdata = "eTSlASZYlLNgKJuYeIQvGVbiAcLEEOVgAQPzSrtCOIwQxQHyFHcfjgRQJBJDlojx";
    l = 'abcdefghij'
    result = itertools.product(*([l] * 7))
    for each in result:
        cnt = cnt + 1
        suffix = ''.join(each)
        authdataSuffix = authdata + suffix
        hashValue = hashlib.sha1(authdataSuffix.encode('utf-8')).hexdigest()
        if  hashValue.startswith("0"*8):
            print (hashValue)

cnt = 0
start = time.time()
pow()
end = time.time()
print(cnt)
print(end - start)


问:
How do I put an image over another image?
I'd like to put a logo on my background, but it keeps sliding off when I zoom out and in.

.top {
  height: 563px;
  width: 1000px;
  display: block;
  margin-left: auto;
  margin-right: auto;
}

.logo {
  position: absolute;
  top: 20px;
  left: 800px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="toplogo">
  <img src="css/elefant.png" class="top">
  <img src="css/logo.png" class="logo">
</div></code>```

答:
Maybe this will fix your zoom issue:(use on a full page (not responsive))
(You can add "@media only screen and (max-width 767px){ new CSS here }" to the CSS for making this responsive

<!DOCTYPE html>

  <title>
    Disable Double-Tap to Zoom
  </title>

  <meta meta name="viewport" content="width=device-width, user-scalable=no" />

WHAT DO WE DO?

Lecture

READ MORE

Captivity

READ MORE

Protest

READ MORE

```

Body:
Maybe this will fix your zoom issue:(use on a full page (not responsive))
(You can add "@media only screen and (max-width 767px){ new CSS here }" to the CSS for making this responsive

<!DOCTYPE html>
<html>

<head>
  <title>
    Disable Double-Tap to Zoom
  </title>

  <meta meta name="viewport" content="width=device-width, user-scalable=no" />

  <style>
    .top {
      position: absolute;
      left: 0%;
      top: 0%;
      z-index: -1;
    }

    .logo {
      position: absolute;
      left: 0%;
      top: 3%;
      z-index: 0;
    }

    h1.pos_what {
      display: flex;
      justify-content: center;
      font-size: 30px;
    }

    .inlet {
      padding: 5px;
    }

    img {
      max-width: 100%;
      height: auto;
    }

    h3 {
      font-size: 2.8rem;
      margin-block-start: 0em !important;
      margin-block-end: 0em !important;
      text-align: center;
    }

    .wrapper {
      display: flex;
      flex-direction: row;
      flex-wrap: no-wrap;
      justify-content: center;
      text-align: center;
    }

    .middlecaptivity,
    .middlelecture,
    .middleprotest {
      border-style: solid;
      margin-top: 20px;
      padding: 10px;
      font: bold;
      font-size: 20px;
      border-width: 1px;
    }
  </style>
</head>

<body>

  <div>
    <img src="https://dummyimage.com/400x400/666666/0011ff.png" class="top">
    <img src="https://www.crossmodal-learning.org/4034886/cml-logo-200x200-527600dd4d55892300f5b82bd80fc0918e4c070e.png" class="logo">
  </div>

  <h1 class="pos_what">WHAT DO WE DO?</h1>

  <div class="wrapper">
    <div class="inlet">
      <img src="https://dummyimage.com/400x400/666666/0011ff.png">
      <h3>Lecture</h3>
      <div class="middlelecture" onclick="location.href='lecture.html';" style="cursor:pointer;">READ MORE</div>
    </div>
    <div class="inlet">
      <img src="https://dummyimage.com/400x400/666666/0011ff.png">

      <h3>Captivity</h3>
      <div class="middlecaptivity" onclick="location.href='captivity.html';" style="cursor:pointer;">READ MORE</div>
    </div>
    <div class="inlet">
      <img src="https://dummyimage.com/400x400/666666/0011ff.png">
      <h3>Protest</h3>
      <div class="middleprotest" onclick="location.href='protest.html';" style="cursor:pointer;">READ MORE</div>
    </div>
  </div>
</body>


问:
Trying to get a variable from other python functions to work with tkinter button commands
trying to call variables from other functions but instead of grabbing only the functions it runs the function, which I dont want unless i push the button to let it which requires the variables.

Tried many things like creating global variables but it leads to them giving me errors as theyre not defined even when defining them.

```<code>import docx

#getfile method

def getfile():
    f1 = filedialog.askopenfilename(filetypes=[("Word Files", "*.docx")]) #<-- selects word files
    return f1

# admins screen after login

def home_page():
    global home_screen
    f1=getfile()#<-- these functions are used instead of grabbing the variable
    scan4yellow=scan_for_text()#<-- these functions are used instead of grabbing the variable
    home_screen = Toplevel(login_screen)
    home_screen.title("Home Page")
    home_screen.geometry("800x600")
    b1 = Button(home_screen, text="Select File", bg="white", command=getfile)
    l1 = Label(home_screen, bg="white", width="20")
    b2 = Button(home_screen, text="Scan File", width=8, bg="white", command=scan_for_text)
    b3 = Button(home_screen, text="Logout", width=8, bg="white", command=logout)
    b4 = Button(home_screen, text="Quit", width=8, bg="white", command=quit)
    l2 = Label(home_screen, text=f1, bg="white") #<-- should take the filepath selected in `f1` and show it
    l3 = Label(home_screen, text=scan4yellow, bg="white")
    return l2

def scan_for_text():
    #scan4yellow = scan_for_text()
    ##reads in the specific docx you want
    document = docx.Document(l2) #<--- reads in the filepath selected
    ##makes it so it is an element that is actually editable and usable
    rs = document._element.xpath("//w:r")
    ##microsoft words schema so it knows what the xml is like and the parametres
    WPML_URI = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
    ##bits and pieces to help find the highlighted pieces of text
    ##then leads onto if statements finding out the highlighted texts colour
    tag_rPr = WPML_URI + 'rPr'
    tag_highlight = WPML_URI + 'highlight'
    tag_val = WPML_URI + 'val'
    tag_t = WPML_URI + 't'
    for word in rs:
        for rPr in word.findall(tag_rPr):
            high = rPr.findall(tag_highlight)
            for hi in high:
                if hi.attrib[tag_val] == 'yellow':
                    scan4yellow = (word.find(tag_t).text.encode('utf-8').lower())
                    #return scan4yellow```
```

答:
Where you think your are "grabbing the variable", you are calling the function. One option is to create global variable 'f1' in 'getfile() and scan4yellow in scan_for_text(). Something like this should work.

```<code>#getfile method

def getfile():
    global f1 # Make the global variable f1 here
    f1 = filedialog.askopenfilename(filetypes=[("Word Files", "*.docx")]) #<-- selects word files
    l2 = Label(home_screen, text=f1, bg="white").grid(row=1, column=1, sticky='W') #<-- should take the filepath selected in `f1` and show it

# admins screen after login

def home_page():
    global home_screen
    home_screen = Toplevel(login_screen)
    home_screen.title("Home Page")
    home_screen.geometry("800x600")
    b1 = Button(home_screen, text="Select File", bg="white", command=getfile)
    b1.grid(row=1, column=0, sticky='W')
    l1 = Label(home_screen, bg="white", width="20")
    l1.grid(row=2, column=0, sticky='W')
    b2 = Button(home_screen, text="Scan File", width=8, bg="white", command=scan_for_text)
    b2.grid(row=3, column=0, sticky='W')
    b3 = Button(home_screen, text="Logout", width=8, bg="white", command=logout)
    b3.grid(row=4, column=0, sticky='W')
    b4 = Button(home_screen, text="Quit", width=8, bg="white", command=quit)
    b4.grid(row=5, column=0, sticky='W')

def scan_for_text():
    ##reads in the specific docx you want
    document = docx.Document(f1) # Change this to f1
    ##makes it so it is an element that is actually editable and usable
    rs = document._element.xpath("//w:r")
    ##microsoft words schema so it knows what the xml is like and the parametres
    WPML_URI = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
    ##bits and pieces to help find the highlighted pieces of text
    ##then leads onto if statements finding out the highlighted texts colour
    tag_rPr = WPML_URI + 'rPr'
    tag_highlight = WPML_URI + 'highlight'
    tag_val = WPML_URI + 'val'
    tag_t = WPML_URI + 't'
    for word in rs:
        for rPr in word.findall(tag_rPr):
            high = rPr.findall(tag_highlight)
            for hi in high:
                if hi.attrib[tag_val] == 'yellow':
                    global scan4yellow # Make the global variable here
                    scan4yellow = (word.find(tag_t).text.encode('utf-8').lower())
                    l3 = Label(home_screen, text=scan4yellow, bg="white").grid(row=7, column=0, sticky='W')
</code>```

Body:
trying to call variables from other functions but instead of grabbing only the functions it runs the function, which I dont want unless i push the button to let it which requires the variables.

Tried many things like creating global variables but it leads to them giving me errors as theyre not defined even when defining them.

import docx

#getfile method

def getfile():
    f1 = filedialog.askopenfilename(filetypes=[("Word Files", "*.docx")]) #<-- selects word files
    return f1

# admins screen after login

def home_page():
    global home_screen
    f1=getfile()#<-- these functions are used instead of grabbing the variable
    scan4yellow=scan_for_text()#<-- these functions are used instead of grabbing the variable
    home_screen = Toplevel(login_screen)
    home_screen.title("Home Page")
    home_screen.geometry("800x600")
    b1 = Button(home_screen, text="Select File", bg="white", command=getfile)
    l1 = Label(home_screen, bg="white", width="20")
    b2 = Button(home_screen, text="Scan File", width=8, bg="white", command=scan_for_text)
    b3 = Button(home_screen, text="Logout", width=8, bg="white", command=logout)
    b4 = Button(home_screen, text="Quit", width=8, bg="white", command=quit)
    l2 = Label(home_screen, text=f1, bg="white") #<-- should take the filepath selected in `f1` and show it
    l3 = Label(home_screen, text=scan4yellow, bg="white")
    return l2

def scan_for_text():
    #scan4yellow = scan_for_text()
    ##reads in the specific docx you want
    document = docx.Document(l2) #<--- reads in the filepath selected
    ##makes it so it is an element that is actually editable and usable
    rs = document._element.xpath("//w:r")
    ##microsoft words schema so it knows what the xml is like and the parametres
    WPML_URI = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
    ##bits and pieces to help find the highlighted pieces of text
    ##then leads onto if statements finding out the highlighted texts colour
    tag_rPr = WPML_URI + 'rPr'
    tag_highlight = WPML_URI + 'highlight'
    tag_val = WPML_URI + 'val'
    tag_t = WPML_URI + 't'
    for word in rs:
        for rPr in word.findall(tag_rPr):
            high = rPr.findall(tag_highlight)
            for hi in high:
                if hi.attrib[tag_val] == 'yellow':
                    scan4yellow = (word.find(tag_t).text.encode('utf-8').lower())
                    #return scan4yellow```

Body:
Where you think your are "grabbing the variable", you are calling the function. One option is to create global variable 'f1' in 'getfile() and scan4yellow in scan_for_text(). Something like this should work.

#getfile method

def getfile():
    global f1 # Make the global variable f1 here
    f1 = filedialog.askopenfilename(filetypes=[("Word Files", "*.docx")]) #<-- selects word files
    l2 = Label(home_screen, text=f1, bg="white").grid(row=1, column=1, sticky='W') #<-- should take the filepath selected in `f1` and show it

# admins screen after login

def home_page():
    global home_screen
    home_screen = Toplevel(login_screen)
    home_screen.title("Home Page")
    home_screen.geometry("800x600")
    b1 = Button(home_screen, text="Select File", bg="white", command=getfile)
    b1.grid(row=1, column=0, sticky='W')
    l1 = Label(home_screen, bg="white", width="20")
    l1.grid(row=2, column=0, sticky='W')
    b2 = Button(home_screen, text="Scan File", width=8, bg="white", command=scan_for_text)
    b2.grid(row=3, column=0, sticky='W')
    b3 = Button(home_screen, text="Logout", width=8, bg="white", command=logout)
    b3.grid(row=4, column=0, sticky='W')
    b4 = Button(home_screen, text="Quit", width=8, bg="white", command=quit)
    b4.grid(row=5, column=0, sticky='W')

def scan_for_text():
    ##reads in the specific docx you want
    document = docx.Document(f1) # Change this to f1
    ##makes it so it is an element that is actually editable and usable
    rs = document._element.xpath("//w:r")
    ##microsoft words schema so it knows what the xml is like and the parametres
    WPML_URI = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
    ##bits and pieces to help find the highlighted pieces of text
    ##then leads onto if statements finding out the highlighted texts colour
    tag_rPr = WPML_URI + 'rPr'
    tag_highlight = WPML_URI + 'highlight'
    tag_val = WPML_URI + 'val'
    tag_t = WPML_URI + 't'
    for word in rs:
        for rPr in word.findall(tag_rPr):
            high = rPr.findall(tag_highlight)
            for hi in high:
                if hi.attrib[tag_val] == 'yellow':
                    global scan4yellow # Make the global variable here
                    scan4yellow = (word.find(tag_t).text.encode('utf-8').lower())
                    l3 = Label(home_screen, text=scan4yellow, bg="white").grid(row=7, column=0, sticky='W')


问:
How to understand Python list comprehension when using 'and' or 'or' in derivation formula?
Using 'and' or 'or' in list comprehension, but the results were unexcepted.why?

> [print(i) and print(i) for i in range(1)]
0

> [print(i) or print(i) for i in range(1)]
0
0
```

答:
This has nothing to do with list-comprehension:

```<code>>>> print(0) and print(0)
0
>>> print(0) or print(0)
0
0
</code>```

This is the normal behavior of boolean operators in Python:

The expression x and y first evaluates x; if x is false, its value is returned

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

(See https://en.wikipedia.org/wiki/Short-circuit_evaluation).

If you know that print(0) returns None:

```<code>>>> print(0) is None
0
True
</code>```

And that:

the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers

You have your answer:

and case: evaluate print(0) (prints 0 as side effect), that is false and return its value (None)

or case: evaluate print(0) (prints 0), that is false and then evaluate the second print(0) (prints 0) return its value (None).

Body:
This has nothing to do with list-comprehension:

>>> print(0) and print(0)
0
>>> print(0) or print(0)
0
0

This is the normal behavior of boolean operators in Python:

The expression x and y first evaluates x; if x is false, its value is returned

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

(See https://en.wikipedia.org/wiki/Short-circuit_evaluation).

If you know that print(0) returns None:

>>> print(0) is None
0
True

And that:

the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers

You have your answer:

and case: evaluate print(0) (prints 0 as side effect), that is false and return its value (None)

or case: evaluate print(0) (prints 0), that is false and then evaluate the second print(0) (prints 0) return its value (None).


问:
genymotion stays on black screen when loading emulator
When i start a new virtual device with genymotion sometimes it will get stuck on the black screen and not load. Sometimes it will work especially just after a restart, otherwise it will hang on the black screen and become unusable.

答:
You need to check 4 different things:

proxy connections to be off( Gennymotion/setting/Network)

SDK be set( Gennymotion/ABD/SDK)

Graphic card driver be successfully installed

Virtual box installed and working correctly

Try again please. hope you will fix it easily.

ContentLicense: CC BY-SA 3.0


问:
Drawing multiple Tables with one Stage
One question currently I am working on a team size seletion screen, So far I did it with checkboxes for team one is finished. Now next to that I wanted to draw another table with the same stage, I don't want to draw with a new Stage in order to save ressources. So my question is it Possible to draw multible tables with one stage next to each other? This is what I currently tried but it didn't work.

So I tried to give a second Table to the constructor something like:

```<code>stage.addActor(table,table2)
</code>```

which did not work.

My second try was something like

```<code>stage.addActor(table);
stage.addActor(table2);
</code>```

which did not work either.

```<code>public class TeamSelectScreen implements Screen {

    public SEPGame game;
    public SpriteBatch menuBatch;
    public AssetManager assetManager;
    public Viewport viewport;
    public Stage stage;
    public MenuScreen menuScreen;
    public ButtonGroup<CheckBox> teamSelect;
    public CheckBox Tank1;
    public CheckBox Tank2;
    public CheckBox Tank3;
    public CheckBox Tank4;
    public CheckBox Tank5;

    public TeamSelectScreen(SEPGame game) {
        game = new SEPGame();
        menuBatch = new SpriteBatch();
        assetManager = new AssetManager();
        viewport = new FitViewport(SEPGame.WORLD_PIXEL_WIDTH, SEPGame.WORLD_PIXEL_HEIGHT);
        menuScreen = new MenuScreen(game);
        menuScreen.dispose();

        stage = new Stage(viewport, menuBatch);

        Gdx.input.setInputProcessor(stage);
        assetManager.load(Assetdescriptor.backGround);
        assetManager.load(Assetdescriptor.buttonNotePressed);
        assetManager.load(Assetdescriptor.buttonPressed);
        assetManager.load(Assetdescriptor.skinUI);
        assetManager.finishLoading();

    }

    public void setupScreen() {
        TextureAtlas menuUi = assetManager.get(Assetdescriptor.backGround);
        Skin uiSkin = assetManager.get(Assetdescriptor.skinUI);
        TextureRegion backGroundRegion = menuUi.findRegion(Regionnames.backGround);
        Table table = new Table();
        Table table2 = new Table();
        Label title = new Label("Team Auswahl", uiSkin);

        Tank1 = new CheckBox("Tank 1 Player", uiSkin);
        Tank2 = new CheckBox("Tank 2 Player", uiSkin);
        Tank3 = new CheckBox("Tank 3 Ki", uiSkin);
        Tank4 = new CheckBox("Tank 4 Ki", uiSkin);
        Tank5 = new CheckBox("Tank 5 Ki", uiSkin);

        ChangeListener teamSizeChanger = new ChangeListener() {
            @Override
            public void changed(ChangeEvent event, Actor actor) {

            }
        };

        Tank1.addListener(teamSizeChanger);
        Tank2.addListener(teamSizeChanger);
        Tank3.addListener(teamSizeChanger);
        Tank4.addListener(teamSizeChanger);
        Tank5.addListener(teamSizeChanger);

        Table checkTable = new Table();
        checkTable.defaults().pad(5);
        checkTable.add(Tank1).row();
        checkTable.add(Tank2).row();
        checkTable.add(Tank3).row();
        checkTable.add(Tank4).row();
        checkTable.add(Tank5).row();

        Table checkTable2 = new Table();
        Table checkTable3 = new Table();
        Table checkTable4 = new Table();
        Table checkTable5 = new Table();

        // Team 1
        table.add(checkTable);
        table.padRight(1200);
        table.setFillParent(true);
        table.pack();
        table.setBackground(new TextureRegionDrawable(backGroundRegion));

        // Team 2
        table2.add(checkTable2);
        table2.padRight(1000);
        table.setFillParent(true);
        table.pack();

        // Add 2 Tables?
        stage.addActor(table);
        stage.addActor(table2);

    }

    @Override
    public void show() {

    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(1, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        menuScreen.dispose();
        setupScreen();
        stage.draw();
    }
}
</code>```

答:
You're calling table.setFillParent(true) twice but never table2.setFillParent(true).

Another option would be adding a Stack with fill parent to the stage and then adding the two tables to the stack:

Stack stack = Stack(table, table2)
stack.setFillParent(true)
stage.addActor(stack)
```

Title: Drawing multiple Tables with one Stage

Body:
One question currently I am working on a team size seletion screen, So far I did it with checkboxes for team one is finished. Now next to that I wanted to draw another table with the same stage, I don't want to draw with a new Stage in order to save ressources. So my question is it Possible to draw multible tables with one stage next to each other? This is what I currently tried but it didn't work.

So I tried to give a second Table to the constructor something like:

stage.addActor(table,table2)

which did not work.

My second try was something like

stage.addActor(table);
stage.addActor(table2);

which did not work either.

public class TeamSelectScreen implements Screen {

    public SEPGame game;
    public SpriteBatch menuBatch;
    public AssetManager assetManager;
    public Viewport viewport;
    public Stage stage;
    public MenuScreen menuScreen;
    public ButtonGroup<CheckBox> teamSelect;
    public CheckBox Tank1;
    public CheckBox Tank2;
    public CheckBox Tank3;
    public CheckBox Tank4;
    public CheckBox Tank5;

    public TeamSelectScreen(SEPGame game) {
        game = new SEPGame();
        menuBatch = new SpriteBatch();
        assetManager = new AssetManager();
        viewport = new FitViewport(SEPGame.WORLD_PIXEL_WIDTH, SEPGame.WORLD_PIXEL_HEIGHT);
        menuScreen = new MenuScreen(game);
        menuScreen.dispose();

        stage = new Stage(viewport, menuBatch);

        Gdx.input.setInputProcessor(stage);
        assetManager.load(Assetdescriptor.backGround);
        assetManager.load(Assetdescriptor.buttonNotePressed);
        assetManager.load(Assetdescriptor.buttonPressed);
        assetManager.load(Assetdescriptor.skinUI);
        assetManager.finishLoading();

    }

    public void setupScreen() {
        TextureAtlas menuUi = assetManager.get(Assetdescriptor.backGround);
        Skin uiSkin = assetManager.get(Assetdescriptor.skinUI);
        TextureRegion backGroundRegion = menuUi.findRegion(Regionnames.backGround);
        Table table = new Table();
        Table table2 = new Table();
        Label title = new Label("Team Auswahl", uiSkin);

        Tank1 = new CheckBox("Tank 1 Player", uiSkin);
        Tank2 = new CheckBox("Tank 2 Player", uiSkin);
        Tank3 = new CheckBox("Tank 3 Ki", uiSkin);
        Tank4 = new CheckBox("Tank 4 Ki", uiSkin);
        Tank5 = new CheckBox("Tank 5 Ki", uiSkin);

        ChangeListener teamSizeChanger = new ChangeListener() {
            @Override
            public void changed(ChangeEvent event, Actor actor) {

            }
        };

        Tank1.addListener(teamSizeChanger);
        Tank2.addListener(teamSizeChanger);
        Tank3.addListener(teamSizeChanger);
        Tank4.addListener(teamSizeChanger);
        Tank5.addListener(teamSizeChanger);

        Table checkTable = new Table();
        checkTable.defaults().pad(5);
        checkTable.add(Tank1).row();
        checkTable.add(Tank2).row();
        checkTable.add(Tank3).row();
        checkTable.add(Tank4).row();
        checkTable.add(Tank5).row();

        Table checkTable2 = new Table();
        Table checkTable3 = new Table();
        Table checkTable4 = new Table();
        Table checkTable5 = new Table();

        // Team 1
        table.add(checkTable);
        table.padRight(1200);
        table.setFillParent(true);
        table.pack();
        table.setBackground(new TextureRegionDrawable(backGroundRegion));

        // Team 2
        table2.add(checkTable2);
        table2.padRight(1000);
        table.setFillParent(true);
        table.pack();

        // Add 2 Tables?
        stage.addActor(table);
        stage.addActor(table2);

    }

    @Override
    public void show() {

    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(1, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        menuScreen.dispose();
        setupScreen();
        stage.draw();
    }
}


问:
String split of delimited values in 2 columns simultaneously - R
I'm looking for an elegant way to split and convert semicolon-separated values from two columns into rows. Data looks like as:

```<code>1        A0A024R442;E7ETB3;Q9ULA0;E7EMB6           443;465;447;382
2 A0A024R442;E7ETB3;Q9ULA0;E7EMB6;C9JBE1       323;345;327;262;309
</code>```

The required output is:

```<code>A0A024R442        443
    E7ETB3        465
    Q9ULA0        447
  ...................
    C9JBE1        309
</code>```

The number of elements in columns is always equal per row as depicted above. I have tried the strsplit() function but I think I can't split delimited values on multiple columns simultaneously (please correct me if I'm wrong).

I would appreciate any suggestion.

答:
Here is a data.table option

```<code>library(data.table)
DT <- fread(text, header = FALSE)

out <- DT[, lapply(.SD, tstrsplit, split = ";", fixed = TRUE), by = 1:nrow(DT)]
out[, nrow := NULL][]
#           V1  V2
#1: A0A024R442 443
#2:     E7ETB3 465
#3:     Q9ULA0 447
#4:     E7EMB6 382
#5: A0A024R442 323
#6:     E7ETB3 345
#7:     Q9ULA0 327
#8:     E7EMB6 262
#9:     C9JBE1 309
</code>```

Or in baseR using strsplit instead

```<code>DF <- read.table(text = text, stringsAsFactors = FALSE, header = FALSE)
as.data.frame(lapply(DF, function(x) unlist(strsplit(x, split = ";", fixed = TRUE))))
</code>```

data

```<code>text = "A0A024R442;E7ETB3;Q9ULA0;E7EMB6           443;465;447;382
A0A024R442;E7ETB3;Q9ULA0;E7EMB6;C9JBE1       323;345;327;262;309"
</code>```

Body:
I'm looking for an elegant way to split and convert semicolon-separated values from two columns into rows. Data looks like as:

1        A0A024R442;E7ETB3;Q9ULA0;E7EMB6           443;465;447;382
2 A0A024R442;E7ETB3;Q9ULA0;E7EMB6;C9JBE1       323;345;327;262;309

The required output is:

A0A024R442        443
    E7ETB3        465
    Q9ULA0        447
  ...................
    C9JBE1        309

The number of elements in columns is always equal per row as depicted above. I have tried the strsplit() function but I think I can't split delimited values on multiple columns simultaneously (please correct me if I'm wrong).

I would appreciate any suggestion.

Body:
Here is a data.table option

library(data.table)
DT <- fread(text, header = FALSE)

out <- DT[, lapply(.SD, tstrsplit, split = ";", fixed = TRUE), by = 1:nrow(DT)]
out[, nrow := NULL][]
#           V1  V2
#1: A0A024R442 443
#2:     E7ETB3 465
#3:     Q9ULA0 447
#4:     E7EMB6 382
#5: A0A024R442 323
#6:     E7ETB3 345
#7:     Q9ULA0 327
#8:     E7EMB6 262
#9:     C9JBE1 309

Or in baseR using strsplit instead

DF <- read.table(text = text, stringsAsFactors = FALSE, header = FALSE)
as.data.frame(lapply(DF, function(x) unlist(strsplit(x, split = ";", fixed = TRUE))))

data

text = "A0A024R442;E7ETB3;Q9ULA0;E7EMB6           443;465;447;382
A0A024R442;E7ETB3;Q9ULA0;E7EMB6;C9JBE1       323;345;327;262;309"


问:
List Divider for Collapsible Content? Possible?
Is there a way to have a content divider for Collapsible Content, not a list, in jQuery Mobile?</p>

答:
You can put anything inside a collapsible block, so it can be a grid with any proportions or a listview.

If you want a divider on the clickable part of the collapsible, then you'll have to hack it yourself with some CSS


问:
Finding the elements in list such that elements should not have similar numbers
Consider a list = [23,52,44,32,78]
23,52,32 all these elements have at least one digit common so the set i want to filter is [44,78] as they don't have any common numbers.

Another example: [52,12,255,211,223,123,64,87,999] would be filtered as [64,87,999]

My current idea is to convert all the numbers into list like [2,3],[5,2]... and take a intersection of those but i couldn't understand how to compare all these sub-lists and filter out the desired numbers.

```<code>def convert_into_sublist(i):
    sublist = [int(x) for x in str(i)]

def intersection(l1, l2):
    l3 = [value for value in l1 if value in l2]
    if(len(l3)==0):
        return 1
</code>```

答:
You can use Counter to find non-common digits:

```<code>from collections import Counter
from itertools import chain
from operator import itemgetter

lst = [23, 52, 44, 32, 78]

sets = [set(str(i)) for i in lst]
# [{'3', '2'}, {'5', '2'}, {'4'}, {'3', '2'}, {'7', '8'}]

c = Counter(chain.from_iterable(sets))
# Counter({'2': 3, '3': 2, '5': 1, '4': 1, '7': 1, '8': 1})

new_lst = []
for num, set_ in zip(lst, sets):
    counts = itemgetter(*set_)(c)
    if counts == 1 or set(counts) == {1}:
        new_lst.append(num)

print(new_lst)
# [44, 78]
</code>```

Body:
Consider a list = [23,52,44,32,78]
23,52,32 all these elements have at least one digit common so the set i want to filter is [44,78] as they don't have any common numbers.

Another example: [52,12,255,211,223,123,64,87,999] would be filtered as [64,87,999]

My current idea is to convert all the numbers into list like [2,3],[5,2]... and take a intersection of those but i couldn't understand how to compare all these sub-lists and filter out the desired numbers.

def convert_into_sublist(i):
    sublist = [int(x) for x in str(i)]

def intersection(l1, l2):
    l3 = [value for value in l1 if value in l2]
    if(len(l3)==0):
        return 1

Body:
You can use Counter to find non-common digits:

from collections import Counter
from itertools import chain
from operator import itemgetter

lst = [23, 52, 44, 32, 78]

sets = [set(str(i)) for i in lst]
# [{'3', '2'}, {'5', '2'}, {'4'}, {'3', '2'}, {'7', '8'}]

c = Counter(chain.from_iterable(sets))
# Counter({'2': 3, '3': 2, '5': 1, '4': 1, '7': 1, '8': 1})

new_lst = []
for num, set_ in zip(lst, sets):
    counts = itemgetter(*set_)(c)
    if counts == 1 or set(counts) == {1}:
        new_lst.append(num)

print(new_lst)
# [44, 78]


问:
How to find fontAwsome icon's name
I'm trying to use font-awesome icons in a react native app, therefore I installed it and imported it using react-native-vector-icons :

```<code>import Icon from "react-native-vector-icons/FontAwesome";
.....
<Icon name="map-pin" />
</code>```

however I don't know where to find the name of the icons, I browsed in the font awesome web site, found some icons, but when I tried to use them, it doesn't work
 for example in their website  this icon's name is  abacus, however, when I use it in my app, I get a warning and the icon doesn't display.

答:
As you said, you can get the names from the official FontAwesome Webiste, but you need to be careful. There are regular icons and pro icons. The pro icons are marked with a small blue banner on the right top. By default, only the free/regular icons are available in the react-native-vector-icons package.

Regular Icon:

Pro Icon

As you can see, the abacus icon is a pro icon and therefore not available in the free tier.

Title: How to find fontAwsome icon's name

Body:
I'm trying to use font-awesome icons in a react native app, therefore I installed it and imported it using react-native-vector-icons :

import Icon from "react-native-vector-icons/FontAwesome";
.....
<Icon name="map-pin" />

however I don't know where to find the name of the icons, I browsed in the font awesome web site, found some icons, but when I tried to use them, it doesn't work
 for example in their website  this icon's name is  abacus, however, when I use it in my app, I get a warning and the icon doesn't display.


问:
what is FlinkZooKeeperQuorumPeer for in flink?
in bin/flink-console.sh, FlinkZooKeeperQuorumPeer is listed as one of the service that flink that can run. What is FlinkZooKeeperQuorumPeer for? In which flink needs to use zookeeper and run a standalone service for it?  If it is for job manager high availability, why don't we put as part of job manager? </p>

```<code>   (zookeeper)

CLASS_TO_RUN=org.apache.flink.runtime.zookeeper.FlinkZooKeeperQuorumPeer
;;
</code>```

答: As the documentation states FlinkZooKeeperQuorumPeer is a simple wrapper for ZooKeeper's QuorumPeer. QuorumPeer is the class that is responsible for managing the quorum protocol, which is used for leader election mechanism. The Zookeeper's election mechanism is used in case of JobManager High Availability mode set to zookeeper. Basically, in this mode You will have multiple JobManagers running, but only one of them will be marked as a leader  and it will be really the only one responsible for scheduling the jobs. If the leader for some reason dies or becomes unresponsive then the election is performed using Zookepeer's election mechanism and new leader is elected. More on High Availability in found here. And more on the Zookeepers election itself here.

Body:
in bin/flink-console.sh, FlinkZooKeeperQuorumPeer is listed as one of the service that flink that can run. What is FlinkZooKeeperQuorumPeer for? In which flink needs to use zookeeper and run a standalone service for it?  If it is for job manager high availability, why don't we put as part of job manager?

   (zookeeper)

CLASS_TO_RUN=org.apache.flink.runtime.zookeeper.FlinkZooKeeperQuorumPeer
;;


问:
Removing altered stopwords
Background:

1) I have the following code to remove stopwords using the nltk package:

```<code>import nltk
from nltk.corpus import stopwords
from nltk.tokenize import sent_tokenize
from nltk.tokenize import word_tokenize

your_string = "The dog does not bark at the tree when it sees a squirrel"
tokens = word_tokenize(your_string)
lower_tokens = [t.lower() for t in tokens]
filtered_words = [word for word in lower_tokens if word not in stopwords.words('english')]
</code>```

2) This code works to remove stopwords such as the as seen here:

```<code>['dog', 'barks', 'tree', 'sees', 'squirrel']
</code>```

3) I altered the stopwords to keep the word not with the following code:

```<code>to_remove = ['not']
new_stopwords = set(stopwords.words('english')).difference(to_remove)
</code>```

Problem:

4) But when I use new_stopwords with the following code:

```<code>your_string = "The dog does not bark at the tree when it sees a squirrel"
tokens = word_tokenize(your_string)
lower_tokens = [t.lower() for t in tokens]
filtered_words = [word for word in lower_tokens if word not in new_stopwords.words('english')]
</code>```

5) I get the following error because new_stopwords is a set:

```<code>AttributeError: 'set' object has no attribute 'words'
</code>```

Question:

6) How do I use the newly defined new_stopwords to get the desired output:

```<code>['dog', 'not','barks', 'tree', 'sees', 'squirrel']
</code>```

答:
You're very close, but your read of the error message is faulty: The problem isn't that "new_stopwords is a set", as you say, but that a "set doesn't have the attribute words"

Which, it doesn't. new_stopwords is a set, which means you can use it directly in the list comprehension:

```<code>filtered_words = [word for word in lower_tokens if word not in new_stopwords]
</code>```

You could also save yourself the trouble of making a modified list of stop words and just use two conditions:

```<code>keep_list = ['not']
filtered_words = [word for word in lower_tokens if (word not in stopwords.words("english")) or (word in keep_list)]
</code>```

Title: Removing altered stopwords

Body:
Background:

1) I have the following code to remove stopwords using the nltk package:

import nltk
from nltk.corpus import stopwords
from nltk.tokenize import sent_tokenize
from nltk.tokenize import word_tokenize

your_string = "The dog does not bark at the tree when it sees a squirrel"
tokens = word_tokenize(your_string)
lower_tokens = [t.lower() for t in tokens]
filtered_words = [word for word in lower_tokens if word not in stopwords.words('english')]

2) This code works to remove stopwords such as the as seen here:

['dog', 'barks', 'tree', 'sees', 'squirrel']

3) I altered the stopwords to keep the word not with the following code:

to_remove = ['not']
new_stopwords = set(stopwords.words('english')).difference(to_remove)

Problem:

4) But when I use new_stopwords with the following code:

your_string = "The dog does not bark at the tree when it sees a squirrel"
tokens = word_tokenize(your_string)
lower_tokens = [t.lower() for t in tokens]
filtered_words = [word for word in lower_tokens if word not in new_stopwords.words('english')]

5) I get the following error because new_stopwords is a set:

AttributeError: 'set' object has no attribute 'words'

Question:

6) How do I use the newly defined new_stopwords to get the desired output:

['dog', 'not','barks', 'tree', 'sees', 'squirrel']

Body:
You're very close, but your read of the error message is faulty: The problem isn't that "new_stopwords is a set", as you say, but that a "set doesn't have the attribute words"

Which, it doesn't. new_stopwords is a set, which means you can use it directly in the list comprehension:

filtered_words = [word for word in lower_tokens if word not in new_stopwords]

You could also save yourself the trouble of making a modified list of stop words and just use two conditions:

keep_list = ['not']
filtered_words = [word for word in lower_tokens if (word not in stopwords.words("english")) or (word in keep_list)]


问:
How do I get a snakemake rule to execute M times to generate MxN files?
I'm converting a bioinformatics pipeline into snakemake and have a script which loops over M files (where M=22 for each non-sex chromosome).

Each file essentially contains N label columns that I want as individual files. The python script does this reliably, my issue is that if I provide the snakefile with wildcards for the output (both chromosomes and labels) it will run the script MxN times whilst I only want it to run M times.

I can circumvent the problem by only looking for one label file per chromosome but this isn't keeping with the spirit of snakemake and the next step in the pipeline requires input from all label files.

I've already tried using the checkpoint feature (which as I understand, reevaluates the DAG after each rule is executed) to check the output, understand that N files have been generated and skip N jobs. But this crashes and I get this error. But because I know my labels beforehand, as I understand I shouldn't need checkpoint/dynamic - I just don't know exactly what I do need.

Is it possible to disable a wildcard from generating jobs and just check that the output is returned?

LABELS = ['A', 'B', 'C', 'D']
CHROMOSOMES = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]

rule all:
    input:
        "out/final.txt"

rule split_files:
    '''
    Splits the chromosome files by label.
    '''
    input:
        "per_chromosome/myfile.{chromosome}.txt"
    output:
        "per_label/myfile.{label}.{chromosome}.txt"
    script:
        "scripts/split_files_snake.py"

rule make_out_file:
    '''
    Makes the final output file by checking each of label.chromosome files one-by-one
    '''
    input:
        expand("per_label/myfile.{label}.{chromosome}",
            label=LABELS,
            chromosome=CHROMOSOMES)
    output:
        "out/final.txt"
    script:
        "scripts/make_out_file_snake.py"
```

答:
If you wish to avoid the scropt being run N times, you can specify all your output files without a wildcard in the output:

```<code>    output:
        "per_label/myfile.A.{chromosome}.txt",
        "per_label/myfile.B.{chromosome}.txt",
        "per_label/myfile.C.{chromosome}.txt",
        "per_label/myfile.D.{chromosome}.txt"
</code>```

To make the code more generic you can use the expand function but pay special attention to the braces in the format string:

```<code>    output:
        expand("per_label/myfile.{label}.{{chromosome}}.txt", label=LABELS)
</code>```

Body:
If you wish to avoid the scropt being run N times, you can specify all your output files without a wildcard in the output:

    output:
        "per_label/myfile.A.{chromosome}.txt",
        "per_label/myfile.B.{chromosome}.txt",
        "per_label/myfile.C.{chromosome}.txt",
        "per_label/myfile.D.{chromosome}.txt"

To make the code more generic you can use the expand function but pay special attention to the braces in the format string:

    output:
        expand("per_label/myfile.{label}.{{chromosome}}.txt", label=LABELS)


问:
jQuery 1.5.X Cross domain
I would like to know if jQuery 1.5.X truly has cross-domain. I was unable to find sufficient documentation on the site and my own cross-domain tests did not work either. I am not talking about JSONP but any regular call (xml, html, json).

I do not see how jQuery can circumvent browser restrictions without use of Adobe Flash/proxy etc.

答:
If the browser supports CORS you can directly use jQuery's AJAX methods to send a cross-domain AJAX request.

Unfortunately IE uses a different method which is not supported by jQuery (yet?).

Title: jQuery 1.5.X Cross domain


问:
Call more than one function 'onClick'
Here is my situation:

```<code><button onClick={this.changeTimerStatus.bind(this)}>makeTimerCliccable</button>

<button onClick={this.state.hasBeenFinished ? this.confirmHandler : (this.state.hasDest == false || this.state.hasDest == undefined ? this.takeTaskHandler : this.finishHandler)}>
</code>```

I have two buttons, but I'd like to have just the second one. Also, I'd like to execute this.changeTimerStatus.bind(this) (the function on the first button) together with this.confirmHandler or this.takeTaskHandler when they're running. How can I solve this?

答:
This should do it for you. Also here is a sandbox so you can see it in action: https://codesandbox.io/s/hardcore-bassi-2lwbu

```<code>    <button
      onClick={
        this.state.hasBeenFinished
          ? () => {
              this.changeTimerStatus();
              this.confirmHandler();
            }
          : !this.state.hasDest
          ? () => {
              this.changeTimerStatus();
              this.takeTaskHandler();
            }
          : this.finishHandler
      }
    >
       Click
    </button>
</code>```

As fellow posters have mentioned, you can move all this logic into a single event-handler like so and pair it with the event-listener

```<code>handleClick = () => {
   this.state.hasBeenFinished
       ? () => {
           this.changeTimerStatus();
           this.confirmHandler();
         }
       : !this.state.hasDest
       ? () => {
           this.changeTimerStatus();
           this.takeTaskHandler();
          }
       : this.finishHandler
}
</code>```

Then in the button:

```<code><button onClick={this.handleClick}>Click</button>
</code>```

The benefits of doing this are:

Prevents unnecessary re-renders caused by using anonymous
functions as event-handlers during render.

Cleans up your mark-up so its easier to read the logic behind
your component.

Title: Call more than one function 'onClick'

Body:
Here is my situation:

<button onClick={this.changeTimerStatus.bind(this)}>makeTimerCliccable</button>

<button onClick={this.state.hasBeenFinished ? this.confirmHandler : (this.state.hasDest == false || this.state.hasDest == undefined ? this.takeTaskHandler : this.finishHandler)}>

I have two buttons, but I'd like to have just the second one. Also, I'd like to execute this.changeTimerStatus.bind(this) (the function on the first button) together with this.confirmHandler or this.takeTaskHandler when they're running. How can I solve this?

Body:
This should do it for you. Also here is a sandbox so you can see it in action: https://codesandbox.io/s/hardcore-bassi-2lwbu

    <button
      onClick={
        this.state.hasBeenFinished
          ? () => {
              this.changeTimerStatus();
              this.confirmHandler();
            }
          : !this.state.hasDest
          ? () => {
              this.changeTimerStatus();
              this.takeTaskHandler();
            }
          : this.finishHandler
      }
    >
       Click
    </button>

As fellow posters have mentioned, you can move all this logic into a single event-handler like so and pair it with the event-listener

handleClick = () => {
   this.state.hasBeenFinished
       ? () => {
           this.changeTimerStatus();
           this.confirmHandler();
         }
       : !this.state.hasDest
       ? () => {
           this.changeTimerStatus();
           this.takeTaskHandler();
          }
       : this.finishHandler
}

Then in the button:

<button onClick={this.handleClick}>Click</button>

The benefits of doing this are:

Prevents unnecessary re-renders caused by using anonymous
functions as event-handlers during render.

Cleans up your mark-up so its easier to read the logic behind
your component.


问:
How to make If Statement inside foreach in ASP.Net view page in my case?
I am trying to display 4 columns in a single row. So after every 4 data there will be one opening
 and at the end closing

```<code>@{
    int i = 1;
}
@{
    foreach (var item in ViewBag.Prod)
    {
        if (i <= 4)
        {
            if (i == 1)
            {
                <div class="row mobile-bg-pic" id="sale-pic">  //OPENING div
                  }

                    <div class="col-6 col-md-3 col-nopadding">
                        <div class="card" data-itmid="@item.ProductID">
                            <img class="card-img-top" src="~/@(item.ImageLocation)/@(item.ImageName)" alt="Card image cap">
                            <div class="card-body">
                                <div class="card-title"><a>@item.Name</a></div>
                                <div class="card-text card-price">RM @item.Price <del class="without-offer-price"> RM @(item.FakePrice)</del><span class="discount">@(item.Discount)% offer</span></div>
                            </div>
                        </div>
                    </div>
                    if (i == 1)
                    {
                </div>    //ENDING div
                i++;
            }
            else if (i <= 3)
            {
                i++;
            }
            if (i == 4)
            {
                i = 0;
            }
        }

    }
}
</code>```

but it doesn't work as I expected it to. Actual rendered html code in the browser is below:

```<code><div class="row mobile-bg-pic" id="sale-pic">
        }

            <div class="col-6 col-md-3 col-nopadding">
                    <div class="card" data-itmid="5ddc742f-df82-43d7-ab3d-073c7dfdb587">
                        <img class="card-img-top loading" src="~/Content/images/Batch17/22-D.jpg" alt="Card image cap" data-was-processed="true">
                        <div class="card-body">
                            <div class="card-title"><a>Diamond songket</a></div>
                            <div class="card-text card-price">US 45 <del class="without-offer-price"> RM 65</del><span class="discount">20% offer</span></div>
                        </div>
                    </div>
                </div>
        if (i == 1)
        {
            </div>
</code>```

I see this stackoverflow link, But I don't understand. But this is the one I want

答:
This is how you could approach this. You must note that your loop for ensuring that only 4 records in ViewBag.Prod are printed must be dependent on how many records are available within that list.

So first Check How many records are within the list:

```<code>var RecordsCount = ViewBag.Prod.Count;
</code>```

Now you know the number of records available, so 4 records must be printed as columns in a row. I am assuming that you may have a dynamic number of records:

So you could try:

```<code>int i = 0; //iterator for the records available
while(i < RecordsCount)
{

   <div class="row mobile-bg-pic" id="sale-pic">  //OPENING div
    //iterator for 4 records interval
    for(int n = 0; n < 4; n++)
    {
       //Type your Html Column here, retrieve your list index using this notation:
       ViewBag.Prod[i+n]
      //Your must note that [i+n] keeps the value of i alive.
      //e.g when i = 0, then results for [0 + n] = 0, 1, 2, 3 - these are your index values
      //now for the second round, e.g when i = 4, indexes will be: [4 + n] = 4, 5, 6, 7
      //So you can use that to loop through the records in cycles of 4 items
    }
    </div>    //ENDING div

    //At this point, 4 records has been displayed
    //update the iterator
    i += 4;

}
</code>```

Body:
I am trying to display 4 columns in a single row. So after every 4 data there will be one opening
 and at the end closing

@{
    int i = 1;
}
@{
    foreach (var item in ViewBag.Prod)
    {
        if (i <= 4)
        {
            if (i == 1)
            {

  //OPENING div
                  }

@item.Name

RM @item.Price  RM @(item.FakePrice)@(item.Discount)% offer

                    if (i == 1)
                    {

    //ENDING div
                i++;
            }
            else if (i <= 3)
            {
                i++;
            }
            if (i == 4)
            {
                i = 0;
            }
        }

    }
}

but it doesn't work as I expected it to. Actual rendered html code in the browser is below:

        }

Diamond songket

US 45  RM 6520% offer

        if (i == 1)
        {

I see this stackoverflow link, But I don't understand. But this is the one I want

Body:
This is how you could approach this. You must note that your loop for ensuring that only 4 records in ViewBag.Prod are printed must be dependent on how many records are available within that list.

So first Check How many records are within the list:

var RecordsCount = ViewBag.Prod.Count;

Now you know the number of records available, so 4 records must be printed as columns in a row. I am assuming that you may have a dynamic number of records:

So you could try:

int i = 0; //iterator for the records available
while(i < RecordsCount)
{

   <div class="row mobile-bg-pic" id="sale-pic">  //OPENING div
    //iterator for 4 records interval
    for(int n = 0; n < 4; n++)
    {
       //Type your Html Column here, retrieve your list index using this notation:
       ViewBag.Prod[i+n]
      //Your must note that [i+n] keeps the value of i alive.
      //e.g when i = 0, then results for [0 + n] = 0, 1, 2, 3 - these are your index values
      //now for the second round, e.g when i = 4, indexes will be: [4 + n] = 4, 5, 6, 7
      //So you can use that to loop through the records in cycles of 4 items
    }
    </div>    //ENDING div

    //At this point, 4 records has been displayed
    //update the iterator
    i += 4;

}


问:
Check if image:tag combination already exists on docker hub
As part of a bash script, I want to check if a particularly docker image:tag combination exists on docker hub. Also, it will be a private repository.

i.e. the pseudocode would be like:

```<code>tag = something
if image:tag already exists on docker hub:
    Do nothing
else
    Build and push docker image with that tag
</code>```

答:
To build on morty's answer, notice that docker supports setting the experimental flag using environment variable:

DOCKER_CLI_EXPERIMENTAL Enable experimental features for the cli (e.g. enabled or disabled)

The snippet therefore becomes:

```<code>tag=something
if DOCKER_CLI_EXPERIMENTAL=enabled docker manifest inspect $image:$tag >/dev/null; then
    Do nothing
else
    Build and push docker image with that tag
fi
</code>```

Body:
As part of a bash script, I want to check if a particularly docker image:tag combination exists on docker hub. Also, it will be a private repository.

i.e. the pseudocode would be like:

tag = something
if image:tag already exists on docker hub:
    Do nothing
else
    Build and push docker image with that tag

Body:
To build on morty's answer, notice that docker supports setting the experimental flag using environment variable:

DOCKER_CLI_EXPERIMENTAL Enable experimental features for the cli (e.g. enabled or disabled)

The snippet therefore becomes:

tag=something
if DOCKER_CLI_EXPERIMENTAL=enabled docker manifest inspect $image:$tag >/dev/null; then
    Do nothing
else
    Build and push docker image with that tag
fi


问:
Is train_test_split necessary for binary classification? And why are there 4 outcomes?
Why are there 4 outcomes to train_test_split in sklearn? Why is there y_test, if the testing data has no y_data?</p>

答: The reason you get 4 outcomes is because you get: train_features, test_features, train_labels and test_labels (X_train, X_test, y_train, y_test). So it not just splits the dataset into train and test set, but also the labels. (so 2 + 2 = 4 outcomes).


问:
Why there is a sorting mechanism in std::map?
I want to use std::map as a key/value pair and I want to keep the order in which these key/values pairs have been inserted.
When I print my values, the order rearranged somehow. Below is my code

```<code>string removeDuplicates(string& s)
{
    // string& s = "asdasdasd"
    map<char, int> duplicates;
    for (int i = 0; i < s.length(); i++) {
        duplicates[s[i]]++;
    }
    map<char, int>::iterator itr = duplicates.begin();
    string result;
    while (itr != duplicates.end())
    {
        result += itr->first;
        itr++;
    }
    return result;
}
</code>```

I inserted "asdasd" and I expected "asd" but the result was "ads"

答:
After going through Spencer updated answer i don't think we require map altogether provided our objective is only to remove duplicates from string. Here is my solution with only std::string</p>

```<code>string removeDuplicatesKeepingOriginalOrder(string const& s)
{
    string result;
    for(std::size_t i=0;i<s.size();i++)
    {
        if(result.find(s[i]) == std::string::npos)
        {
            result.push_back(s[i]);
        }
    }
    return result;
}
</code>```

Body:
I want to use std::map as a key/value pair and I want to keep the order in which these key/values pairs have been inserted.
When I print my values, the order rearranged somehow. Below is my code

string removeDuplicates(string& s)
{
    // string& s = "asdasdasd"
    map<char, int> duplicates;
    for (int i = 0; i < s.length(); i++) {
        duplicates[s[i]]++;
    }
    map<char, int>::iterator itr = duplicates.begin();
    string result;
    while (itr != duplicates.end())
    {
        result += itr->first;
        itr++;
    }
    return result;
}

I inserted "asdasd" and I expected "asd" but the result was "ads"

Body:
After going through Spencer updated answer i don't think we require map altogether provided our objective is only to remove duplicates from string. Here is my solution with only std::string

string removeDuplicatesKeepingOriginalOrder(string const& s)
{
    string result;
    for(std::size_t i=0;i<s.size();i++)
    {
        if(result.find(s[i]) == std::string::npos)
        {
            result.push_back(s[i]);
        }
    }
    return result;
}


问:
Can anyone help me out in aligning the layout in flutter?
Below is the screenshot with incorrect layout:

As you can see above, a column inside a row is pushing other children down.

I have removed the column from the row and the layout was displaying as expected. However, I need that column to be part of the row.

```<code>class TitleSection extends StatelessWidget{
  @override
    Widget build(BuildContext context) {
      // TODO: implement build
      return Container(
        padding: EdgeInsets.all(32),
        child: Row(
          children: <Widget>[
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text("Kratos",style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 20
                  )),
                  Text("The God Of War",
                    style: TextStyle(
                      color: Colors.grey[500]
                    ),
                  ),
                ],
              ),
            ),
            Icon(
              Icons.star,
              color: Colors.red,
            ),
            Text("143")
          ],
        )
      );
    }
</code>```

}

答:
Rather than wrapping your Column with Expanded which will occupy as much space as possible use Flexible, also wrap you other widgets inside a Column so you can easily lay them out :

```<code> class TitleSection extends StatelessWidget{
    @override
    Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(32),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Flexible(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text("Kratos",style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 20
                )),
                Text("The God Of War",
                  style: TextStyle(
                      color: Colors.grey[500]
                  ),
                ),
              ],
            ),
          ),
          Flexible(
            child: Column(
              children: <Widget>[
                Row(
                  children: <Widget>[
                    Icon(
                      Icons.star,
                      color: Colors.red,
                    ),
                    Text("143")
                  ],
                ),
              ],
            ),
          ),
        ],
      )
    );
  }
}
</code>```

Body:
Below is the screenshot with incorrect layout:

As you can see above, a column inside a row is pushing other children down.

I have removed the column from the row and the layout was displaying as expected. However, I need that column to be part of the row.

class TitleSection extends StatelessWidget{
  @override
    Widget build(BuildContext context) {
      // TODO: implement build
      return Container(
        padding: EdgeInsets.all(32),
        child: Row(
          children: <Widget>[
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text("Kratos",style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 20
                  )),
                  Text("The God Of War",
                    style: TextStyle(
                      color: Colors.grey[500]
                    ),
                  ),
                ],
              ),
            ),
            Icon(
              Icons.star,
              color: Colors.red,
            ),
            Text("143")
          ],
        )
      );
    }

}

Body:
Rather than wrapping your Column with Expanded which will occupy as much space as possible use Flexible, also wrap you other widgets inside a Column so you can easily lay them out :

 class TitleSection extends StatelessWidget{
    @override
    Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(32),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Flexible(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text("Kratos",style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 20
                )),
                Text("The God Of War",
                  style: TextStyle(
                      color: Colors.grey[500]
                  ),
                ),
              ],
            ),
          ),
          Flexible(
            child: Column(
              children: <Widget>[
                Row(
                  children: <Widget>[
                    Icon(
                      Icons.star,
                      color: Colors.red,
                    ),
                    Text("143")
                  ],
                ),
              ],
            ),
          ),
        ],
      )
    );
  }
}


问:
Get location in a more precise way with Angular
I am using the services of google maps, using the function

```<code>navigator.geolocation.getCurrentPosition
</code>```

only that sometimes gives me the exact location, other times it gives me another location very far from mine, however in the maps web page When you press the button that your location gives you, it is always accurate.
Do you know how to do it like google? I mean to make it precise, since I need this functionality for a user registry, and I must obtain its exact coordinates.

Sorry if the translation is bad, I'm using the google translator.

答:
If you are using Angular try to use this method I made it and used it in all my projects and it works well <br /> </p>

```<code>function getCurrentPosition(): Observable<Position> {
  return Observable.create((observer: Observer<Position>) => {
      navigator.geolocation.getCurrentPosition(
        (position: Position) => {
          observer.next(position);
          observer.complete();
        },
        (error: PositionError) => {
          console.log('Geolocation service: ' + error.message);
          observer.error(error);
        }
      );
    });

}
</code>```

Body:
I am using the services of google maps, using the function

navigator.geolocation.getCurrentPosition

only that sometimes gives me the exact location, other times it gives me another location very far from mine, however in the maps web page When you press the button that your location gives you, it is always accurate.
Do you know how to do it like google? I mean to make it precise, since I need this functionality for a user registry, and I must obtain its exact coordinates.

Sorry if the translation is bad, I'm using the google translator.

Body:
If you are using Angular try to use this method I made it and used it in all my projects and it works well

function getCurrentPosition(): Observable<Position> {
  return Observable.create((observer: Observer<Position>) => {
      navigator.geolocation.getCurrentPosition(
        (position: Position) => {
          observer.next(position);
          observer.complete();
        },
        (error: PositionError) => {
          console.log('Geolocation service: ' + error.message);
          observer.error(error);
        }
      );
    });

}


问:
Retrieve index of a List<> item based in C# using Linq
It is a pretty simple question, I have a list of an object that has a Field Named "ID".

How can I retrieve the Index of an object in the list if I know the ID?

Example:

```<code>CUSTOM_OBJECTS test = new CUSTOM_OBJECTS{ID=50};
List<CUSTOM_OBJECTS> List = new List<CUSTOM_OBJECTS>();
List.Add(test);
</code>```

I would like to retrieve the index of the object with ID = 50 in the list, which would be 0 in this example.

答:
```<code>CUSTOM_OBJECT singleObject = list.Single(co => co.ID == 50)
</code>```

You can also use the methods SingleOrDefault, First, or FirstOrDefault.

Body:
It is a pretty simple question, I have a list of an object that has a Field Named "ID".

How can I retrieve the Index of an object in the list if I know the ID?

Example:

CUSTOM_OBJECTS test = new CUSTOM_OBJECTS{ID=50};
List<CUSTOM_OBJECTS> List = new List<CUSTOM_OBJECTS>();
List.Add(test);

I would like to retrieve the index of the object with ID = 50 in the list, which would be 0 in this example.

Body:
CUSTOM_OBJECT singleObject = list.Single(co => co.ID == 50)

You can also use the methods SingleOrDefault, First, or FirstOrDefault.


问:
Which Calendar values corresponds to the last hour/minute of the day?
I am using the Calendar object. The timestamp formatting I am using uses year, day, hour, and minute. However there are cases where I need to set these to extreme values for a given day.

I can set a Calendar to the first possible time of the day by setting Calendar.HOUR and Calendar.MINUTE to 0 (I think).

What is the correct value for the last minute of the day? Calendar.HOUR set to 23 and Calendar.MINUTE set to 59?

答:
java.time

The terrible Calendar and GregorianCalendar were supplanted years ago by the modern java.time classes defined in JSR 310.

To get the first moment of the day, start with a date-only, a LocalDate.

```<code>LocalDate ld = LocalDate.of( 2019 , Month.JANUARY , 23 ) ;
</code>```

To consider the time-of-day, we must have a time zone. Days do not always start at 00:00:00. On some dates in some zones, the day may start at a time such as 01:00:00. So let java.time determine the first moment of the day for the time zone of interest.

```<code>ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdtFirstMoment = ld.atStartOfDay( z ) ;
</code>```

As for the last moment of the day, that is problematic. The fraction of the last second of the last minute of the last hour is infinitely divisible. It could be something like 23:59:59.999 or 23:59:59.999999 or 23:59:59.999999999.

Generally it is better to work with spans of time defined as Half-Open. This means the beginning is inclusive while the ending is exclusive. For example, when we say the students’ lunch break is noon to 1 PM, we mean they should have their tushies in their seats before the bell strikes. So lunch starts at 12:00:00.0 and runs up to, but does not include, 13:00:00.0. Similarly, a week starts on a Monday and runs up to, but does not include, the following Monday.

```<code>ZonedDateTime zdtFirstMomentNextDay = zdtFirstMoment.plusDays( 1 ) ;
</code>```

If you insist on getting the last minute of the day, subtract a minute from the first moment.

```<code>ZonedDateTime zdtLastMinute = zdtFirstMomentNextDay.minusMinutes( 1 ) ;
</code>```

A day is not always 24 hours. It can be 23, 23.5, 25, or other numbers of hours long. To calculate the elapsed time, use Duration.

```<code>Duration d = Duration.between( zdtFirstMoment , zdtFirstMomentNextDay ) ;
</code>```

To represent this span-of-time as a pair of moments attached to the timeline, add the ThreeTen-Extra library to your project. Then use its Interval class. Adjust each ZonedDateTime to UTC by extracting an Instant object. Instant represents a moment in UTC.

```<code>Interval interval = Interval.of(
    zdtFirstMoment.toInstant() ,
    zdtFirstMomentNextDay.toInstant()
) ;
</code>```

If you must have a Calendar object, convert from ZonedDateTime using the new conversion methods added to the old classes. In this case, GregorianCalendar.from().

```<code>Calendar c = GregorianCalendar.from( zdtFirstMomentNextDay ) ;
</code>```

Body:
java.time

The terrible Calendar and GregorianCalendar were supplanted years ago by the modern java.time classes defined in JSR 310.

To get the first moment of the day, start with a date-only, a LocalDate.

LocalDate ld = LocalDate.of( 2019 , Month.JANUARY , 23 ) ;

To consider the time-of-day, we must have a time zone. Days do not always start at 00:00:00. On some dates in some zones, the day may start at a time such as 01:00:00. So let java.time determine the first moment of the day for the time zone of interest.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdtFirstMoment = ld.atStartOfDay( z ) ;

As for the last moment of the day, that is problematic. The fraction of the last second of the last minute of the last hour is infinitely divisible. It could be something like 23:59:59.999 or 23:59:59.999999 or 23:59:59.999999999.

Generally it is better to work with spans of time defined as Half-Open. This means the beginning is inclusive while the ending is exclusive. For example, when we say the students’ lunch break is noon to 1 PM, we mean they should have their tushies in their seats before the bell strikes. So lunch starts at 12:00:00.0 and runs up to, but does not include, 13:00:00.0. Similarly, a week starts on a Monday and runs up to, but does not include, the following Monday.

ZonedDateTime zdtFirstMomentNextDay = zdtFirstMoment.plusDays( 1 ) ;

If you insist on getting the last minute of the day, subtract a minute from the first moment.

ZonedDateTime zdtLastMinute = zdtFirstMomentNextDay.minusMinutes( 1 ) ;

A day is not always 24 hours. It can be 23, 23.5, 25, or other numbers of hours long. To calculate the elapsed time, use Duration.

Duration d = Duration.between( zdtFirstMoment , zdtFirstMomentNextDay ) ;

To represent this span-of-time as a pair of moments attached to the timeline, add the ThreeTen-Extra library to your project. Then use its Interval class. Adjust each ZonedDateTime to UTC by extracting an Instant object. Instant represents a moment in UTC.

Interval interval = Interval.of(
    zdtFirstMoment.toInstant() ,
    zdtFirstMomentNextDay.toInstant()
) ;

If you must have a Calendar object, convert from ZonedDateTime using the new conversion methods added to the old classes. In this case, GregorianCalendar.from().

Calendar c = GregorianCalendar.from( zdtFirstMomentNextDay ) ;


问:
How to write a repeat element to each row in scrapy
I am testing my hand at scraping with scrapy. Thrilled with progress so far, I have an issue where the data model of the source website doesn't seem to align with my current scrapy output.

Source provides Categories, Type, and URL data - each category contains multiple types, and each type has a URL.

I am looking to get an output maintaining the nesting of the data where each row associates the category, type, and URL grouping.

Both XLM and CSV outputs provide unique categories but hold all subsequent type and url data in columns for each category row.

Source/example site:

Half-Cents and Cents

Liberty Cap Half Cent (1793-1797)

Draped Bust Half Cent (1800-1808)

Classic Head Half Cent (1809-1836)

Two and Three Cents

Two Cent (1864-1873)

Three Cent Silver (1851-1873)

Three Cent Nickel (1865-1889)

```

<p>Working spider scraping all necessary data, but not formatted as needed:</p>

<pre class="lang-py prettyprint-override"><code>import scrapy

class PCGSSpider(scrapy.Spider):
    name = "pcgs_spider"
    custom_settings = {
        'FEED_FORMAT': 'xml',
        'FEED_URI': 'pcgsspider.xml'
    }
    start_urls = ['abovesample.html']

    def parse(self, response):
        SET_SELECTOR = '.box'
        for pcgs in response.css(SET_SELECTOR):

            CAT_SELECTOR = 'h3 ::text'
            TYPE_SELECTOR = './/ul/li/a/text()'
            URL_SELECTOR = './/ul/li/a/@href'
            yield {
                    'categories': pcgs.css(CAT_SELECTOR).extract(),
                    'types': pcgs.xpath(TYPE_SELECTOR).extract(),
                    'type_url': pcgs.xpath(URL_SELECTOR).extract(),
            }
</code>```

And the XML showing the right data, but not nested with each URL with its TYPE, and TYPE with its CATEGORY

-<item>
-<categories>
    <value>Half-Cents and Cents</value>
</categories>
-<types>
    <value>Liberty Cap Half Cent (1793-1797)</value>
    <value>Draped Bust Half Cent (1800-1808)</value>
    <value>Classic Head Half Cent (1809-1836)</value>
</types>
-<type_url>
    <value>/auctionprices/category/lincoln-cent-wheat-reverse-1909-1958/46</value>
    <value>/auctionprices/category/lincoln-cent-modern-1959-date/47</value>
    <value>/auctionprices/category/lincoln-cent-modern-1959-date/47</value>
</type_url>
</item>
```

Very new to this all so pardon any ignorance - it seems some level of iteration would resolve the problem, though it isn't clear to me if within my spider is the best place to resolve as the data and core of the structure is complete.

答:
You have to use extract_first() method instead of extract() on the categories field.Sample of what I got from scraping PCGS:

```<code><items>
<item><categories>Half-Cents and Cents</categories><types>Liberty Cap Half Cent (1793-1797)</types><type_url>/auctionprices/category/liberty-cap-half-cent-1793-1797/34</type_url></item>
<item><categories>Two and Three Cents</categories><types>Two Cent (1864-1873)</types><type_url>/auctionprices/category/two-cent-1864-1873/670</type_url></item>
<item><categories>Nickels</categories><types>Shield Nickel (1866-1883)</types><type_url>/auctionprices/category/shield-nickel-1866-1883/81</type_url></item>
</items>
</code>```

Hope that's what you were looking for.

Body:
I am testing my hand at scraping with scrapy. Thrilled with progress so far, I have an issue where the data model of the source website doesn't seem to align with my current scrapy output.

Source provides Categories, Type, and URL data - each category contains multiple types, and each type has a URL.

I am looking to get an output maintaining the nesting of the data where each row associates the category, type, and URL grouping.

Both XLM and CSV outputs provide unique categories but hold all subsequent type and url data in columns for each category row.

Source/example site:

Half-Cents and Cents

Liberty Cap Half Cent (1793-1797)

Draped Bust Half Cent (1800-1808)

Classic Head Half Cent (1809-1836)

Two and Three Cents

Two Cent (1864-1873)

Three Cent Silver (1851-1873)

Three Cent Nickel (1865-1889)

Working spider scraping all necessary data, but not formatted as needed:

import scrapy

class PCGSSpider(scrapy.Spider):
    name = "pcgs_spider"
    custom_settings = {
        'FEED_FORMAT': 'xml',
        'FEED_URI': 'pcgsspider.xml'
    }
    start_urls = ['abovesample.html']

    def parse(self, response):
        SET_SELECTOR = '.box'
        for pcgs in response.css(SET_SELECTOR):

            CAT_SELECTOR = 'h3 ::text'
            TYPE_SELECTOR = './/ul/li/a/text()'
            URL_SELECTOR = './/ul/li/a/@href'
            yield {
                    'categories': pcgs.css(CAT_SELECTOR).extract(),
                    'types': pcgs.xpath(TYPE_SELECTOR).extract(),
                    'type_url': pcgs.xpath(URL_SELECTOR).extract(),
            }

And the XML showing the right data, but not nested with each URL with its TYPE, and TYPE with its CATEGORY

-<item>
-<categories>
    <value>Half-Cents and Cents</value>
</categories>
-<types>
    <value>Liberty Cap Half Cent (1793-1797)</value>
    <value>Draped Bust Half Cent (1800-1808)</value>
    <value>Classic Head Half Cent (1809-1836)</value>
</types>
-<type_url>
    <value>/auctionprices/category/lincoln-cent-wheat-reverse-1909-1958/46</value>
    <value>/auctionprices/category/lincoln-cent-modern-1959-date/47</value>
    <value>/auctionprices/category/lincoln-cent-modern-1959-date/47</value>
</type_url>
</item>

Very new to this all so pardon any ignorance - it seems some level of iteration would resolve the problem, though it isn't clear to me if within my spider is the best place to resolve as the data and core of the structure is complete.

Body:
You have to use extract_first() method instead of extract() on the categories field.Sample of what I got from scraping PCGS:

<items>
<item><categories>Half-Cents and Cents</categories><types>Liberty Cap Half Cent (1793-1797)</types><type_url>/auctionprices/category/liberty-cap-half-cent-1793-1797/34</type_url></item>
<item><categories>Two and Three Cents</categories><types>Two Cent (1864-1873)</types><type_url>/auctionprices/category/two-cent-1864-1873/670</type_url></item>
<item><categories>Nickels</categories><types>Shield Nickel (1866-1883)</types><type_url>/auctionprices/category/shield-nickel-1866-1883/81</type_url></item>
</items>

Hope that's what you were looking for.


问:
why the overwrite doesn't have the output?
```<code>function rate_preprocess_rate_template_emotion(&$variables) {
  extract($variables);
  $buttons = array();
  foreach ($links as $link) {
    $button = theme('rate_button', $link['text'], $link['href'], 'rate-emotion-btn');
    $button .= $link['votes'];
    $buttons[] = $button;
  }
  $variables['buttons'] = $buttons;

  $info = array();
........
</code>```

now i want to add
around the . i put this code in my theme template.php.but it doesn't output the span tags.

```<code>function mytheme_preprocess_rate_template_emotion(&$variables) {
$link['votes']='<br/><span class="pollunm">'.$link['votes'].' </span>';
}
</code>```

答:
This is not a solution. Just the step for you to debug.

First make sure that function mytheme_preprocess_rate_template_emotion(&$variables) is getting called by putting a dpm(install devel module) in the function.

And inside function rate_preprocess_rate_template_emotion(&$variables) they are using foreach ($links as $link). So make sure that whether you want to do it for all links are just one link.

Within function mytheme_preprocess_rate_template_emotion(&$variables) put a dpm($variables); and find out which are the variables available to you and what are their values. It might help you.

Body:
function rate_preprocess_rate_template_emotion(&$variables) {
  extract($variables);
  $buttons = array();
  foreach ($links as $link) {
    $button = theme('rate_button', $link['text'], $link['href'], 'rate-emotion-btn');
    $button .= $link['votes'];
    $buttons[] = $button;
  }
  $variables['buttons'] = $buttons;

  $info = array();
........

now i want to add
around the . i put this code in my theme template.php.but it doesn't output the span tags.

function mytheme_preprocess_rate_template_emotion(&$variables) {
$link['votes']='
'.$link['votes'].' ';
}


问:
Mongodb 4.0.4 installation error in Linux
I am using 16.04.1-Ubuntu SMP i686 athlon i686 GNU/Linux (LINUX Mint)

I followed [offical documentation][1], but end up in errors.

installation using LATEST VERSION OF MongoDB

```<code>$ sudo apt-get install -y mongodb-org
</code>```

Errors

```<code>Package mongodb-org is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'mongodb-org' has no installation candidate
</code>```

Installation using Specific release of Mongodb

```<code>$sudo apt-get install -y mongodb-org=4.0.4 mongodb-org-server=4.0.4 mongodb-org-shell=4.0.4 mongodb-org-mongos=4.0.4 mongodb-org-tools=4.0.4
</code>```

Error

```<code>E: Version '4.0.4' for 'mongodb-org' was not found
E: Version '4.0.4' for 'mongodb-org-server' was not found
E: Version '4.0.4' for 'mongodb-org-shell' was not found
E: Version '4.0.4' for 'mongodb-org-mongos' was not found
E: Version '4.0.4' for 'mongodb-org-tools' was not found
</code>```

Note : the above installation is done after executing these codes

```<code>$sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4
$echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/4.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.0.list
$sudo apt-get update
</code>```

答:
You state:

```<code>I am using 16.04.1-Ubuntu SMP i686 athlon **i686** GNU/Linux (LINUX Mint)
</code>```

Your system is 32bit.

Yet you are trying to install amd64 (64bit) sources/packages:

```<code>$echo "deb [ **arch=amd64** ] https://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/4.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.0.list
</code>```

This won't work.

Solution: Install Ubuntu 64bit.

Body:
I am using 16.04.1-Ubuntu SMP i686 athlon i686 GNU/Linux (LINUX Mint)

I followed [offical documentation][1], but end up in errors.

installation using LATEST VERSION OF MongoDB

$ sudo apt-get install -y mongodb-org

Errors

Package mongodb-org is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'mongodb-org' has no installation candidate

Installation using Specific release of Mongodb

$sudo apt-get install -y mongodb-org=4.0.4 mongodb-org-server=4.0.4 mongodb-org-shell=4.0.4 mongodb-org-mongos=4.0.4 mongodb-org-tools=4.0.4

Error

E: Version '4.0.4' for 'mongodb-org' was not found
E: Version '4.0.4' for 'mongodb-org-server' was not found
E: Version '4.0.4' for 'mongodb-org-shell' was not found
E: Version '4.0.4' for 'mongodb-org-mongos' was not found
E: Version '4.0.4' for 'mongodb-org-tools' was not found

Note : the above installation is done after executing these codes

$sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4
$echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/4.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.0.list
$sudo apt-get update

Body:
You state:

I am using 16.04.1-Ubuntu SMP i686 athlon **i686** GNU/Linux (LINUX Mint)

Your system is 32bit.

Yet you are trying to install amd64 (64bit) sources/packages:

$echo "deb [ **arch=amd64** ] https://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/4.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.0.list

This won't work.

Solution: Install Ubuntu 64bit.


问:
How to get R function to return multiple values of parameters
I would like that my function would produce values for different values of one of my parameters (in this case CC), so that I can easily turn this into a dataframe.

Here is the code I am using:

```<code>ub_duration <- function(age, cc = c(12, 18, 24), cc_lag, dur,
                        extended) {
    dur = if (age < 30){
        if (cc < 15) return(150)
        if (cc >= 15 & cc < 24) return(210)
        if (cc >= 24) return(330)
    }
    dur = if (age >= 30 & age < 40){
        if (cc < 15) return(180)
        if (cc >= 15 & cc < 24) return(330)
        if (cc >= 24) return(420)
    }
    dur = if (age >= 50){
        if (cc < 15) return(270)
        if (cc >= 15 & cc < 24) return(480)
        if (cc >= 24) return(540)
    }
    return(dur)
}
</code>```

When I call the function, this is what  get

```<code>> ub_duration(25,c(12, 18, 24),0)
[1] 150
Warning message:
In if (cc < 15) return(150) :
the condition has length > 1 and only the first element will be used
</code>```

Body:
I would like that my function would produce values for different values of one of my parameters (in this case CC), so that I can easily turn this into a dataframe.

Here is the code I am using:

ub_duration <- function(age, cc = c(12, 18, 24), cc_lag, dur,
                        extended) {
    dur = if (age < 30){
        if (cc < 15) return(150)
        if (cc >= 15 & cc < 24) return(210)
        if (cc >= 24) return(330)
    }
    dur = if (age >= 30 & age < 40){
        if (cc < 15) return(180)
        if (cc >= 15 & cc < 24) return(330)
        if (cc >= 24) return(420)
    }
    dur = if (age >= 50){
        if (cc < 15) return(270)
        if (cc >= 15 & cc < 24) return(480)
        if (cc >= 24) return(540)
    }
    return(dur)
}

When I call the function, this is what  get

> ub_duration(25,c(12, 18, 24),0)
[1] 150
Warning message:
In if (cc < 15) return(150) :
the condition has length > 1 and only the first element will be used

Body:
ub_duration1 = function(age,cc){
    cc_cat = findInterval(cc,c(15,24))+1
    age_cat =findInterval(age,c(30,40,50))+1
    cc = cbind(c(150,210,330),c(180,330,420),NA,c(270,480,540))
    cc[cc_cat,age_cat]
}

ub_duration(25,c(12, 18, 24))
[1] 150 210 330


问:
input output file handling and rearranging data
I am new to Tcl I want to read data from a file lets say text.txt and content of the file is

```<code>Name     Delay  Trans  Load
----------------------------
AND1_2X  1.50ns  0.1  1.25ff
AND1_3X  1.75ns  0.2  1.98ff
AND2_3X  2.37ns  0.3  2.27ff
AND2_4X  1.82ns  0.5  2.54ff
NAND1_2X 2.14ns  0.2  1.69ff
NAND2_3X 2.48ns  0.3  2.11ff
</code>```

now I want to read data and rearrange as with spaces

```<code>Name     Trans   Load  Delay
-----------------------------
AND1_2X  0.1  1.25ff  1.50ns
AND1_3X  0.2  1.98ff  1075ns
AND2_3X  0.3  2.27ff  2.37ns
AND2_4X  0.5  2.54ff  1.82ns
NAND1_2X 0.2  1.69ff  2.14ns
NAND2_3X 0.3  2.11ff  2.48ns
</code>```

I have tried the code and I am getting the output as

```<code>Name Trans  Load Delay -----------------------------     AND1_2X 0.1  1.25ff 1.50ns AND1_3X 0.2  1.98ff 1.75ns AND2_3X 0.3  2.27ff 2.37ns AND2_4X 0.5  2.54ff 1.82ns NAND1_2X 0.2  1.69ff 2.14ns NAND2_3X 0.3  2.11ff 2.48ns
</code>```

the code is

```<code>set fp [open "file1.txt" r+]
set l1 {}
while { [gets $fp data] >= 0 } {
 set data1 [split $data "\n"]
puts [lindex $data 0]

 foreach line $data1 {
 set cline [regsub " +" $line " "]
 set dat1 [split $cline]
 puts $dat1
 puts [lindex $dat1 5]
 lappend l1 [lindex $dat1  0]
 lappend l1 [lindex $dat1  3]
lappend l1 [lindex $dat1  4]

 lappend l1 [lindex $dat1  5]
 lappend l1 [lindex $dat1  1]
}
}
puts $l1
set x [join $l1]
set fp1 [open "input.txt" w+]
puts $fp1 $x
close $fp1
 close $fp
</code>```

答:
The first problem you've got is that you've got your final join wrong: you need to tell it to join with newlines instead of the default (single spaces):

```<code>set x [join $l1 "\n"]
</code>```

Secondly, when you're producing a fixed-width line like:

```AND1_2X  0.1  1.25ff  1.50ns```

You should use the format command to do it. If you know C's printf() you should find it intuitive. Otherwise, use something like this:

```<code># First, this is how to pick out the fields, assuming they're always present
set fieldData [regexp -all -inline {\S+} $line]

# Let's get some good names instead of using loads of lindex calls
lassign $fieldData name delay trans load

# Now let's transform that into the output line
lappend l1 [format "%-8s %3s  %5s  %6s" $name $trans $load $delay]
</code>```

In particular, the %3s means “format this field” (from $trans in the code above) “in a right-aligned string field three characters wide”, and the %-8s means “format this field in a left-aligned string field eight characters wide”. This sort of thing is great for fixed width output.

If you're dealing with fixed width input with occasional missing fields, you need scan (which is sort of the inverse of format).

Finally, definitely special-case the header lines. That's hugely easier!

Body:
I am new to Tcl I want to read data from a file lets say text.txt and content of the file is

Name     Delay  Trans  Load
----------------------------
AND1_2X  1.50ns  0.1  1.25ff
AND1_3X  1.75ns  0.2  1.98ff
AND2_3X  2.37ns  0.3  2.27ff
AND2_4X  1.82ns  0.5  2.54ff
NAND1_2X 2.14ns  0.2  1.69ff
NAND2_3X 2.48ns  0.3  2.11ff

now I want to read data and rearrange as with spaces

Name     Trans   Load  Delay
-----------------------------
AND1_2X  0.1  1.25ff  1.50ns
AND1_3X  0.2  1.98ff  1075ns
AND2_3X  0.3  2.27ff  2.37ns
AND2_4X  0.5  2.54ff  1.82ns
NAND1_2X 0.2  1.69ff  2.14ns
NAND2_3X 0.3  2.11ff  2.48ns

I have tried the code and I am getting the output as

Name Trans  Load Delay -----------------------------     AND1_2X 0.1  1.25ff 1.50ns AND1_3X 0.2  1.98ff 1.75ns AND2_3X 0.3  2.27ff 2.37ns AND2_4X 0.5  2.54ff 1.82ns NAND1_2X 0.2  1.69ff 2.14ns NAND2_3X 0.3  2.11ff 2.48ns

the code is

set fp [open "file1.txt" r+]
set l1 {}
while { [gets $fp data] >= 0 } {
 set data1 [split $data "\n"]
puts [lindex $data 0]

 foreach line $data1 {
 set cline [regsub " +" $line " "]
 set dat1 [split $cline]
 puts $dat1
 puts [lindex $dat1 5]
 lappend l1 [lindex $dat1  0]
 lappend l1 [lindex $dat1  3]
lappend l1 [lindex $dat1  4]

 lappend l1 [lindex $dat1  5]
 lappend l1 [lindex $dat1  1]
}
}
puts $l1
set x [join $l1]
set fp1 [open "input.txt" w+]
puts $fp1 $x
close $fp1
 close $fp

Body:
The first problem you've got is that you've got your final join wrong: you need to tell it to join with newlines instead of the default (single spaces):

set x [join $l1 "\n"]

Secondly, when you're producing a fixed-width line like:

AND1_2X  0.1  1.25ff  1.50ns

You should use the format command to do it. If you know C's printf() you should find it intuitive. Otherwise, use something like this:

# First, this is how to pick out the fields, assuming they're always present
set fieldData [regexp -all -inline {\S+} $line]

# Let's get some good names instead of using loads of lindex calls
lassign $fieldData name delay trans load

# Now let's transform that into the output line
lappend l1 [format "%-8s %3s  %5s  %6s" $name $trans $load $delay]

In particular, the %3s means “format this field” (from $trans in the code above) “in a right-aligned string field three characters wide”, and the %-8s means “format this field in a left-aligned string field eight characters wide”. This sort of thing is great for fixed width output.

If you're dealing with fixed width input with occasional missing fields, you need scan (which is sort of the inverse of format).

Finally, definitely special-case the header lines. That's hugely easier!