问:
Angular 7 Service providedIn: 'root'
I'm very new to angular development so please forgive me if this is a very basic question

But I have a cart service which I have at the moment simply has a simple console log function

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class CartService {

  constructor( ) {}

  public addItem() {
    console.log('Hello');
  }
}```

and basically I cannot figure out how to use this service within a NG Module that I have installed, I have successfully used it in other components via the constructor but the ngmodule doesn't have this?

I get the fact that it's a singleton at the app-module level by using the providedIn: 'root' tag added in angular 6

but just can't figure out how to call cartService.addItem()?

Thanks if anyone can help!

答:
You can use Dependency Injection like this to call the service</p>

```<code>export class AppComponent {
  constructor(private cartService: CartService) {

  }

  doSomething() {
     this.cartService.addItem();
  }
}
</code>```

Title: Angular 7 Service providedIn: 'root'

Body:
I'm very new to angular development so please forgive me if this is a very basic question

But I have a cart service which I have at the moment simply has a simple console log function

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class CartService {

  constructor( ) {}

  public addItem() {
    console.log('Hello');
  }
}

and basically I cannot figure out how to use this service within a NG Module that I have installed, I have successfully used it in other components via the constructor but the ngmodule doesn't have this?

I get the fact that it's a singleton at the app-module level by using the providedIn: 'root' tag added in angular 6

but just can't figure out how to call cartService.addItem()?

Thanks if anyone can help!

Body:
You can use Dependency Injection like this to call the service

export class AppComponent {
  constructor(private cartService: CartService) {

  }

  doSomething() {
     this.cartService.addItem();
  }
}


来源: stackexchange

问:
Difference between (int ret = 0; !ret && ret !=0)
What the difference between:

```<code>1) !ret
2) ret != 0
</code>```

?

```<code>if (ret != 0 || stack[fd] == NULL || stack[fd][0] == '\0')
{
  if (!ret && *line)
    *line = NULL;
  return (ret);
}
</code>```

答:
In a boolean context in C, a value of zero is considered "false" and a non-zero value is considered "true". Hence if (ret) (if ret is true) is equivalent to if (ret != 0) (if ret is not false), and similarly if (!ret) (if ret is not true) is equivalent to if (ret == 0) (if ret is false).

(i.e., the meanings of !ret and ret != 0 are opposite, assuming the question is correct.)

ContentLicense: CC BY-SA 4.0

Body:
What the difference between:

1) !ret
2) ret != 0

?

if (ret != 0 || stack[fd] == NULL || stack[fd][0] == '\0')
{
  if (!ret && *line)
    *line = NULL;
  return (ret);
}


问:
Make match input and if-else
I have my script here

from tkinter import *
from tkinter import messagebox
import commands

db=''

def launch():
        # Database Check.
            if db.lower() == 'y':
                commands.db_download()
            else:
                db.lower() == 'n'

root = Tk()

checklabel = Label(root, text="Check for new databases? Y/N: ")
checkentree = Entry(root, textvariable=db)
checkbutton = Button(root, text="Go", command=launch)

checklabel.pack()
checkentree.pack()
checkbutton.pack()

root.mainloop()
```

And everything works except the matching part.
When I enter "y" or "n", or even anything else in the Entry box and click Go, nothing happens... Why isnt anything happening? And how could i make it work?

答:
There is 1 change you need to make and a couple that are a good idea to fix.

1st the "need" to change:

When using a textvaraible in a tkinter widget you must use one of the ObjectVars (IE: StringVar, IntVar and so on). Keep in mind also that you will need to use .get() on db as the get() method is how you grab a value from an ObjectVar.

To accomplish this change this:

```<code>db = ''

def launch():
    if db.lower() == 'y':
</code>```

To this:

```<code>db = tk.StringVar()
db.set('') # not actually required in this instance but still good to know how to set the value of a ObjectVar.

def launch():
    if db.get().lower() == 'y':
</code>```

As well as move your db tkinter code past the root or else the StringVar will throw this error AttributeError: 'NoneType' object has no attribute '_root' as you have not yet started the tk instance for the StringVar to latch onto.

That said you should also change how you import tkinter and maybe clean up your widget names and how you pack.

It is better to do import tkinter as tk over from tkinter import * because this helps prevent accidentally overwriting an import form other imports or your own variable/functions/class names. To work with this new import method you just need to use the prefix tk. for each method/widget use.

If you are not going to modify a widget down the road (IE: a permanent label, button or so on) you do not need to assign it to a variable and can simply use your geometry manager (in this case pack()) on the widget directly.

Lastly your if/else statement is not exactly correct. It will function but this line db.lower() == 'n' is not doing what you think it is doing. An else statement does not have any conditions to meet. It just is the last option in an if/elif/else statement that will run if none of the other conditions are met. That said if you have nothing you want to be done if none of the other conditions are met you can simple delete the else portion of your logic statement.

Take a look at the below code:

```<code>import tkinter as tk

def launch():
if db.get().lower() == 'y':
    print('commands.db_download()')
else:
    print('not y')

root = tk.Tk()
db = tk.StringVar()
db.set('')

tk.Label(root, text="Check for new databases? Y/N: ").pack()
tk.Entry(root, textvariable=db).pack()
tk.Button(root, text="Go", command=launch).pack()

root.mainloop()
</code>```

Title: Make match input and if-else

Body:
I have my script here

from tkinter import *
from tkinter import messagebox
import commands

db=''

def launch():
        # Database Check.
            if db.lower() == 'y':
                commands.db_download()
            else:
                db.lower() == 'n'

root = Tk()

checklabel = Label(root, text="Check for new databases? Y/N: ")
checkentree = Entry(root, textvariable=db)
checkbutton = Button(root, text="Go", command=launch)

checklabel.pack()
checkentree.pack()
checkbutton.pack()

root.mainloop()

And everything works except the matching part.
When I enter "y" or "n", or even anything else in the Entry box and click Go, nothing happens... Why isnt anything happening? And how could i make it work?

Body:
There is 1 change you need to make and a couple that are a good idea to fix.

1st the "need" to change:

When using a textvaraible in a tkinter widget you must use one of the ObjectVars (IE: StringVar, IntVar and so on). Keep in mind also that you will need to use .get() on db as the get() method is how you grab a value from an ObjectVar.

To accomplish this change this:

db = ''

def launch():
    if db.lower() == 'y':

To this:

db = tk.StringVar()
db.set('') # not actually required in this instance but still good to know how to set the value of a ObjectVar.

def launch():
    if db.get().lower() == 'y':

As well as move your db tkinter code past the root or else the StringVar will throw this error AttributeError: 'NoneType' object has no attribute '_root' as you have not yet started the tk instance for the StringVar to latch onto.

That said you should also change how you import tkinter and maybe clean up your widget names and how you pack.

It is better to do import tkinter as tk over from tkinter import * because this helps prevent accidentally overwriting an import form other imports or your own variable/functions/class names. To work with this new import method you just need to use the prefix tk. for each method/widget use.

If you are not going to modify a widget down the road (IE: a permanent label, button or so on) you do not need to assign it to a variable and can simply use your geometry manager (in this case pack()) on the widget directly.

Lastly your if/else statement is not exactly correct. It will function but this line db.lower() == 'n' is not doing what you think it is doing. An else statement does not have any conditions to meet. It just is the last option in an if/elif/else statement that will run if none of the other conditions are met. That said if you have nothing you want to be done if none of the other conditions are met you can simple delete the else portion of your logic statement.

Take a look at the below code:

import tkinter as tk

def launch():
if db.get().lower() == 'y':
    print('commands.db_download()')
else:
    print('not y')

root = tk.Tk()
db = tk.StringVar()
db.set('')

tk.Label(root, text="Check for new databases? Y/N: ").pack()
tk.Entry(root, textvariable=db).pack()
tk.Button(root, text="Go", command=launch).pack()

root.mainloop()


问:
Postgresql - Sort a character field with Special characters, numbers and alphabets
I have the following data in one of my Postgresql table.

```<code>name
-----------------
AdvertiserTest123
Advertiser ADV 833
:1Advertiser
02 Advertiser
MH Advertiser
</code>```

When I query as: Select * from adv_names order by name;

The output I get is

```<code>AdvertiserTest123
Advertiser ADV 833
:1Advertiser
02 Advertiser
MH Advertiser
</code>```

I'm expecting the order of sorting to be name with Specials Characters followed numbers and then alphabets. If I'm not wrong this is how it behaves in Sql Server.

I tried changing collation and tried ascii search. It doesn't work the way I am expecting.  Can anyone help on this?

Expected Output:

```<code>:1Advertiser
02 Advertiser
Advertiser ADV 833
AdvertiserTest123
MH Advertiser
</code>```

答:
The real question here is whether your expectation is reasonable. Sorting text values in SQL is determined by the collation. In PostgreSQL, you can change the collation when you run your query.

```<code>select * from adv_names order by "name" collate "POSIX";
</code>```

It boils down to this: in which collations are special characters ordered before numbers? I don't think any of the collations work that way, but I could be wrong. (I don't have to think much about collations where I work.)

To see which collations are available to you, run this.

```<code>select * from pg_collation;
</code>```

In a pinch, you can create your own collation.  See create collation. I'm not sure this will work for you. It depends on OS support and PostgreSQL build options.

Body:
I have the following data in one of my Postgresql table.

name
-----------------
AdvertiserTest123
Advertiser ADV 833
:1Advertiser
02 Advertiser
MH Advertiser

When I query as: Select * from adv_names order by name;

The output I get is

AdvertiserTest123
Advertiser ADV 833
:1Advertiser
02 Advertiser
MH Advertiser

I'm expecting the order of sorting to be name with Specials Characters followed numbers and then alphabets. If I'm not wrong this is how it behaves in Sql Server.

I tried changing collation and tried ascii search. It doesn't work the way I am expecting.  Can anyone help on this?

Expected Output:

:1Advertiser
02 Advertiser
Advertiser ADV 833
AdvertiserTest123
MH Advertiser

Body:
The real question here is whether your expectation is reasonable. Sorting text values in SQL is determined by the collation. In PostgreSQL, you can change the collation when you run your query.

select * from adv_names order by "name" collate "POSIX";

It boils down to this: in which collations are special characters ordered before numbers? I don't think any of the collations work that way, but I could be wrong. (I don't have to think much about collations where I work.)

To see which collations are available to you, run this.

select * from pg_collation;

In a pinch, you can create your own collation.  See create collation. I'm not sure this will work for you. It depends on OS support and PostgreSQL build options.


问:
Show IDs for the highest MAX values in a matrix
I have a matrix that's grouped by different company brands. Essentially, I'm showing the highest value spent by a customer for each company brand (I've used MAX in my expression to get those). I also want to show Customer IDs attributed to those MAX values. Does anybody know how to do that? Is there any expression?

Example:

Company Brand: Nike | Max value spent: £500 | Customer ID: ???

Thanks

答:
You can use subqueries to retrieve summed values in your SQL Query</p>

```<code>SELECT T1.CustomerID, T1.CompanyBrand,
    (SELECT Max(S1.ValueSpentField) FROM TableThatContainsValueSpent S1 WHERE T1.CustomerID = S1.CustomerID)
FROM Company T1
</code>```

Body:
You can use subqueries to retrieve summed values in your SQL Query

SELECT T1.CustomerID, T1.CompanyBrand,
    (SELECT Max(S1.ValueSpentField) FROM TableThatContainsValueSpent S1 WHERE T1.CustomerID = S1.CustomerID)
FROM Company T1


问:
haskell : calculated fields in custom data types
Is it possible to do something that is equivalent to having a field in a data type that is automatically calculated from other fields in the data type. For example:

```<code>data Grid = Grid
  { x :: Int
  , y :: Int
  , c = (x * y) :: Int
  }
</code>```

and then
myGrid = Grid 5 6

or does this have to be or can only be done with Class?

```<code>data Grid = Grid
  { x :: Int
  , y :: Int
  }

class Calculated a where
  c :: a -> Int

instance Calculated Grid where
  c g = x g * y g
</code>```

答:
If, for some reason, you want to pre-compute c and store it in the value, define a smart constructor.

```<code>data Grid = Grid {x :: Int, y :: Int, c :: Int}

mkGrid :: Int -> Int -> Grid
mkGrid x y = Grid x y (x * y)
</code>```

There is a stricter separation of data and functions in Haskell than in an OO language. data only defines a new type, not the operations on that type. Record syntax only provides projections of the form Grid -> x for some type x; it doesn't let you define anything more complicated.

Body:
Is it possible to do something that is equivalent to having a field in a data type that is automatically calculated from other fields in the data type. For example:

data Grid = Grid
  { x :: Int
  , y :: Int
  , c = (x * y) :: Int
  }

and then
myGrid = Grid 5 6

or does this have to be or can only be done with Class?

data Grid = Grid
  { x :: Int
  , y :: Int
  }

class Calculated a where
  c :: a -> Int

instance Calculated Grid where
  c g = x g * y g

Body:
If, for some reason, you want to pre-compute c and store it in the value, define a smart constructor.

data Grid = Grid {x :: Int, y :: Int, c :: Int}

mkGrid :: Int -> Int -> Grid
mkGrid x y = Grid x y (x * y)

There is a stricter separation of data and functions in Haskell than in an OO language. data only defines a new type, not the operations on that type. Record syntax only provides projections of the form Grid -> x for some type x; it doesn't let you define anything more complicated.


问:
Add different text to the last line of a string - C# LINQ
I want to take an input string and add " ' + " to the end of each line except the last line, on the last line I want to add " ' ; "

The following allows me to add " ' + " to every line:

```<code>string[] outputArr = outputRaw
  .Split(new string[] { Environment.NewLine }, StringSplitOptions.None)
  .Select((stringval, stringindex) => "'" + stringval + " ' + ")
  .ToArray();

this.Output = String.Join(Environment.NewLine, outputArr);
</code>```

Can this be adjusted to identify the last line and add different characters?

答:
You can just replace the new lines :</p>

```<code>this.Output = "'" + outputRaw.Replace(Environment.NewLine, " ' + " + Environment.NewLine + "'") + " ' ; ";
</code>```

Body:
I want to take an input string and add " ' + " to the end of each line except the last line, on the last line I want to add " ' ; "

The following allows me to add " ' + " to every line:

string[] outputArr = outputRaw
  .Split(new string[] { Environment.NewLine }, StringSplitOptions.None)
  .Select((stringval, stringindex) => "'" + stringval + " ' + ")
  .ToArray();

this.Output = String.Join(Environment.NewLine, outputArr);

Can this be adjusted to identify the last line and add different characters?

Body:
You can just replace the new lines :

this.Output = "'" + outputRaw.Replace(Environment.NewLine, " ' + " + Environment.NewLine + "'") + " ' ; ";


问:
How to create an upload folder for a web app in Kubernetes?
we're experimenting Kubernetes and thinking about migrating our webapp, currently hosted in a classic public cloud with vps and load balancing.

I'd like to know how to manage an upload folder (with write/read privileged) inside our dockerized app in which  files uploaded by our users are stored.

As we use lot of file uploading in our apps, would it be possible to have a persistent data storage in which the webapp can upload files in and manage them via webapp? Do I have to change the code of my app and save files to external object storages or there's a faster way to do it via local filesystem?

Thank you !

答:
I'm guessing that if you are running more than one pod, you'd want some sort of shared filesystem?  So all uploaded documents are available in one location instead of scattered around several persistent volumes?  If that's the case, you want some sort of distibuted file storage like Amazon S3.  Even better, you could use a Kubernetes NFS so your code thinks it is using local filesystem but it is backed by a distributed file store.

Take a look at this example: https://github.com/kubernetes/examples/tree/master/staging/volumes/nfs. The NFS can use a persistent volume from GKE, Azure, or AWS.


问:
How to save file in Preferences?
I have a list of files in external storage, what I need to do is to save these files's paths in Shared Preferences, so then, when the user starts the app, I can take that path and open those files.
I've tried with saving an string set, but it doesn't seems to work, what would I do?</p>

答: Files cannot be saved in the SharedPreferences. SharedPreferences are used to store simple values like String , Int , Double, Float etc. In any other case you will need to use some database or something. The only thing you can do with the SharedPreferences is to save the File's path as a string to access it later in the application.

Title: How to save file in Preferences?


问:
Creating Proportional Graphs in R
I'm looking to create a proportional bar graph in R. I have two variables, one is "drunk" and one is "housing“。I want to graph the proportional of individuals of each category of " housing" who fulfil "drunk".

The dataframe is something like follows:

Drunk: 0, 1, 0, 1, 1, 1, 1, 0
Housing: 1, 2, 1, 3, 1, 4, 1, 1

I want to know how to graph the proportion of each category of housing (1 through 4) which fulfils "1" for drunk.

png("Graphs/Analysis_Figure1.png")

analysis %>%

count(housing, drunk) %>%

group_by(housing) %>%

mutate(freq = n/sum(n)) %>%

ggplot(aes(x = housing, y = freq, fill = drunk)) +

geom_bar(stat="identity", position = 'dodge')

dev.off()

This gives me the proportions, but instead of only including "1" responses for drunk, I also get "0". Is there a way to only include 1?

This is an image I generated with STATA, which I hope to replicate inN R

This is what I get with R instead. I want to remove the "2 or less" (coded as "0" drunk responses

答:
You can use the filter() function from dplyr in your pipleline:

```<code>analysis %>%
filter(drunk == 1) %>%
count(housing, drunk) %>% ...
</code>```

Title: Creating Proportional Graphs in R

Body:
You can use the filter() function from dplyr in your pipleline:

analysis %>%
filter(drunk == 1) %>%
count(housing, drunk) %>% ...


问:
Is there a speed difference in MySQL operations?
I was discussing speed of MySQL statements and someone asked me: Between SELECT, INSERT, UPDATE, and DELETE, which is faster and why?

I didn't know the answer. Does anyone know if one is faster than the other, and if so, why? Or are they all generally the same speed?

答: I'm not sure about each command individually, but a lot of it depends on the actual statement.  Having indexes on a table require that indexes be modified on inserts, updates and deletes.  While an index may make selects faster, it slows down any data modification statements.  In addition to that, the complexity of the query, the datatype of the columns, any sql functions (like aggregates) all change the performance of a query.</p>

OwnerDisplayName: rocket

ContentLicense: CC BY-SA 2.5


问:
What are the differences between extern, abstract, and partial for methods in an abstract class?
I am writing an abstract class because I want to provide a few commonly used methods, require a few methods that will be too specific, and allow some methods to "extended".  After bumping into a compiler error I am wondering if anybody can explain the differences between the extern, abstract, and partial keywords.  What do they mean and when/where should I use them?

答:
extern is unlikely to be something you want to use.  It means that the method is implemented, but implemented externally - and typically used in interop scenarios where you're defining a method implelemented in external code.

abstract, on the other hand, means you're defining the API for the method, but not providing an implementation.  The subclass will have to provide the implementation for any methods or properties marked abstract, or be abstract itself.  If you want to make a base class and have a method or property that must be implemented by subclasses, you'll want to use abstract.

partial classes and methods are merely a compilation tool.  They allow you to use multiple files to define your type.  This is mostly used with automatically generated code (ie: a designer will put the designer generated code into a separate file defining a partial class, so you can 'fill in' the missing pieces without looking at the implementation details).  This is unlikely something you'll use directly for defining a class.

ContentLicense: CC BY-SA 3.0


问:
Continue executing method once event occurs in windows forms
I am developing a windows forms application that acts in a very similar fashion to a console. The functionality I am trying to implement should work in the same way as Console.ReadLine(), with a windows forms button in place of the user pressing the enter key. In the form, there is text box that displays the output text, and a text box that the user can input information to (shown in image).

Edit: What I would like to do is have the application get information from the input text box, then assign that information to a variable within the Start() function when the 'enter' button is pressed. The problem I am facing is doing this multiple times for the same function without it proceeding further in the function (i.e. displaying incorrect information in the output text box).

It's my understanding that I would need to use the click event from the 'enter' button, but not sure have to "pause" the function until the enter button is clicked.

```<code>public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void TextTop_Changed(object sender, EventArgs e)
    {

    }

    private void Enter_Clicked(object sender, EventArgs e)
    {
        textBottom.Text = string.Empty;
    }

    private void Start_Click(object sender, EventArgs e)
    {
        start();
    }

    public void textBoxInput(string message)
    {
        textTop.Text = message;
    }

    public void start()
    {
        textBottom.Text = "Enter name:";

        //need to wait here until enter button is clicked.

        string name = textTop.Text;//get input from top text box

        textBottom.Text = "Enter description:";

        //need to wait here until enter button is clicked again.

        string description = textTop.Text; //get input from top text box
    }
}
</code>```

答:
It looks to me like you are trying to simulate a console line application which executes in a sequential manner. As others have noted, Windows Forms don't work sequentially. Events are triggered instead.

I believe what you need to do is keep the state of your operations internally. Have a set of variables with form scope for this purpose:

```<code>public class Form1 : Form
{
    public const int STEP_INITIAL = 0;
    public const int STEP_GET_NAME = 1;
    public const int STEP_GET_DESCRIPTION = 2;
    public const int STEP_INFO_GATHERED = 3;

    private int _step = STEP_INITIAL;
    private string _name;
    private string _description;

}
</code>```

Your Start method can then check on the current state and do what it needs to do:

```<code>public void start()
{
    switch (_step)
    {
        case STEP_INITIAL:
            textBottom.Text = "Enter name:";
            _step = STEP_GET_NAME;
            break;
        case STEP_GET_NAME:
            _name = textTop.Text;
            if (string.IsNullOrWhiteSpace(_name))
                MessageBox.Show("Please enter a valid name!");
            else
            {
                textBottom.Text = "Enter description:";
                textTop.Clear();
                _step = STEP_GET_DESCRIPTION;
            }
            break;
        case STEP_GET_DESCRIPTION:
            _description = textTop.Text;
            if (string.IsNullOrWhiteSpace(_description))
                MessageBox.Show("Please enter a valid description!");
            else
            {
                //This is your final state, where they have entered all the information
                _step = STEP_INFO_GATHERED;
            }
            break;
    }
}
</code>```

There are [obviously] more elegant ways of doing this but this should point you in the right direction. Please check the syntax, I did this off the top of my head.

Lastly, this would be a lot easier if you just had two textboxes for name and description... :-)

Body:
I am developing a windows forms application that acts in a very similar fashion to a console. The functionality I am trying to implement should work in the same way as Console.ReadLine(), with a windows forms button in place of the user pressing the enter key. In the form, there is text box that displays the output text, and a text box that the user can input information to (shown in image).

Edit: What I would like to do is have the application get information from the input text box, then assign that information to a variable within the Start() function when the 'enter' button is pressed. The problem I am facing is doing this multiple times for the same function without it proceeding further in the function (i.e. displaying incorrect information in the output text box).

It's my understanding that I would need to use the click event from the 'enter' button, but not sure have to "pause" the function until the enter button is clicked.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void TextTop_Changed(object sender, EventArgs e)
    {

    }

    private void Enter_Clicked(object sender, EventArgs e)
    {
        textBottom.Text = string.Empty;
    }

    private void Start_Click(object sender, EventArgs e)
    {
        start();
    }

    public void textBoxInput(string message)
    {
        textTop.Text = message;
    }

    public void start()
    {
        textBottom.Text = "Enter name:";

        //need to wait here until enter button is clicked.

        string name = textTop.Text;//get input from top text box

        textBottom.Text = "Enter description:";

        //need to wait here until enter button is clicked again.

        string description = textTop.Text; //get input from top text box
    }
}

Body:
It looks to me like you are trying to simulate a console line application which executes in a sequential manner. As others have noted, Windows Forms don't work sequentially. Events are triggered instead.

I believe what you need to do is keep the state of your operations internally. Have a set of variables with form scope for this purpose:

public class Form1 : Form
{
    public const int STEP_INITIAL = 0;
    public const int STEP_GET_NAME = 1;
    public const int STEP_GET_DESCRIPTION = 2;
    public const int STEP_INFO_GATHERED = 3;

    private int _step = STEP_INITIAL;
    private string _name;
    private string _description;

}

Your Start method can then check on the current state and do what it needs to do:

public void start()
{
    switch (_step)
    {
        case STEP_INITIAL:
            textBottom.Text = "Enter name:";
            _step = STEP_GET_NAME;
            break;
        case STEP_GET_NAME:
            _name = textTop.Text;
            if (string.IsNullOrWhiteSpace(_name))
                MessageBox.Show("Please enter a valid name!");
            else
            {
                textBottom.Text = "Enter description:";
                textTop.Clear();
                _step = STEP_GET_DESCRIPTION;
            }
            break;
        case STEP_GET_DESCRIPTION:
            _description = textTop.Text;
            if (string.IsNullOrWhiteSpace(_description))
                MessageBox.Show("Please enter a valid description!");
            else
            {
                //This is your final state, where they have entered all the information
                _step = STEP_INFO_GATHERED;
            }
            break;
    }
}

There are [obviously] more elegant ways of doing this but this should point you in the right direction. Please check the syntax, I did this off the top of my head.

Lastly, this would be a lot easier if you just had two textboxes for name and description... :-)


问:
Flutter pubspec.yaml Android versionCode
My app before using Flutter had

```<code>android:versionCode="17"
android:versionName="17"
</code>```

In my Flutter application in pubspec.yaml, I have to set a version as x.y.z and I am trying set the new version to 19.0.0.
But when I try to install the application on my device that has a version with android:versionCode="17" installed, I get an error message saying that the version on device is bigger than version I am trying to install.

How do I fix this?

答:
The flutter.versionCode local property gets populated using the part after the + of the pubspec.yaml version.

This means that for Android, the pubspec.yaml version is parsed as follows:

```<code>version: {versionName}+{versionCode}
</code>```

The example from your questions would consequently look like this in order to work (in pubspec.yaml:

```<code>name: ...
version: 19.0.0+19

...
</code>```

As a side note, it is idiomatic for Dart to follow Semantic Versioning, although the + suffix does not work as it should when trying to build for Android with Flutter as I explained.

Body:
My app before using Flutter had

android:versionCode="17"
android:versionName="17"

In my Flutter application in pubspec.yaml, I have to set a version as x.y.z and I am trying set the new version to 19.0.0.
But when I try to install the application on my device that has a version with android:versionCode="17" installed, I get an error message saying that the version on device is bigger than version I am trying to install.

How do I fix this?

Body:
The flutter.versionCode local property gets populated using the part after the + of the pubspec.yaml version.

This means that for Android, the pubspec.yaml version is parsed as follows:

version: {versionName}+{versionCode}

The example from your questions would consequently look like this in order to work (in pubspec.yaml:

name: ...
version: 19.0.0+19

...

As a side note, it is idiomatic for Dart to follow Semantic Versioning, although the + suffix does not work as it should when trying to build for Android with Flutter as I explained.


问:
How to convert JSON to URL params string as per my expected value?
I am working on an angular project. For a method getting a response JSON to convert stringify and POST a body to an API is done. Now the problem is for another one function I should send this value as a URL parameter I tried some ways but didn't get expected result. Please find the below codes and help me out. Thanks

Here is my JSON format value

```<code>const bodyJSON = [{FullPackageIDs:[11,7],
                    PartialPkg:[
                        {PackageID:4,
                            FormsList:[
                                {Form_Name:"Form name One"},
                                {Form_Name:"Form name Two"}]},
                        {PackageID:6,
                            FormsList:[
                                {Form_Name:"Form name Three"},
                                {Form_Name:"Form name Four"},
                                {Form_Name:"Form name Five"}
                            ]
                        }
                    ]
                }]
</code>```

My expected URL string value like below

```<code>http://localhost:4200/DownloadPackage?FullPackageIDs[0]=11&FullPackageIDs[1]=7&PartialPkg[0].PackageID=4&PartialPkg[0].FormsList[0].Form_Name=Form name One&PartialPkg[0].FormsList[1].Form_Name=Form name Two&PartialPkg[1].PackageID=6&PartialPkg[0].FormsList[0].Form_Name=Form name Three&PartialPkg[1].FormsList[1].Form_Name=Form name Four&PartialPkg[2].FormsList[2].Form_Name=Form name Five
</code>```

I tried via forloop but didnt get expected result. Here is the code for what I tried.

```<code>for (let i = 0; i < getSelectedId.length; i++) {
  fullPackageParams = `${fullPackageParams}FullPackageIDs[${i}]=${getSelectedId[i]}&`;
  for (let j = 0; j < getPartialId.length; j++) {
    // const getPartialName = this.partialPackage.map(res => res[i].FormsList);
    const getPartialName = getPartialId[j].FormsList;

    partialPackageIDParams = `${partialPackageIDParams}PartialPkg[${j}].PackageID=${getPartialId[j].PackageID}&`;

    for (let index = 0; index < getPartialName.length; index++) {
      partialPackageNameParams = `PartialPkg[${index}].FormsList[${index}].Form_Name=${getPartialName[index].Form_Name}&`;
    }
  }
}
console.log('params for full packages', fullPackageParams + partialPackageIDParams + partialPackageNameParams);
</code>```

答:
even if it seems kinda strange to me that you need to pass all of those params using query, you can try this

it just uses ES6 map, reduce functions to create your query string

```<code>let URLQuery = bodyJSON.map(value => {
    const packageIDs = value.FullPackageIDs.map((v, i) => `FullPackageIDs[${i}]=${encodeURIComponent(v)}`);
    const partialPkgs = value.PartialPkg.map((v, i) => {
        const startKey = `PartialPkg[${i}]`;
        return [
            `${startKey}.PackageID=${v.PackageID}`
        ].concat(
            v.FormsList.map((v, i) => `${startKey}.FormsList[${i}].Form_Name=${encodeURIComponent(v.Form_Name)}`)
        );
    }).reduce((arr, v) => {
        return arr.concat(v)
    }, []);

    return packageIDs.concat(partialPkgs);
}).reduce((arr, v) => {
    return arr.concat(v);
}, []).join("&");

const fullURL = `https://example.com?${URLQuery}`;
</code>```

Body:
I am working on an angular project. For a method getting a response JSON to convert stringify and POST a body to an API is done. Now the problem is for another one function I should send this value as a URL parameter I tried some ways but didn't get expected result. Please find the below codes and help me out. Thanks

Here is my JSON format value

const bodyJSON = [{FullPackageIDs:[11,7],
                    PartialPkg:[
                        {PackageID:4,
                            FormsList:[
                                {Form_Name:"Form name One"},
                                {Form_Name:"Form name Two"}]},
                        {PackageID:6,
                            FormsList:[
                                {Form_Name:"Form name Three"},
                                {Form_Name:"Form name Four"},
                                {Form_Name:"Form name Five"}
                            ]
                        }
                    ]
                }]

My expected URL string value like below

http://localhost:4200/DownloadPackage?FullPackageIDs[0]=11&FullPackageIDs[1]=7&PartialPkg[0].PackageID=4&PartialPkg[0].FormsList[0].Form_Name=Form name One&PartialPkg[0].FormsList[1].Form_Name=Form name Two&PartialPkg[1].PackageID=6&PartialPkg[0].FormsList[0].Form_Name=Form name Three&PartialPkg[1].FormsList[1].Form_Name=Form name Four&PartialPkg[2].FormsList[2].Form_Name=Form name Five

I tried via forloop but didnt get expected result. Here is the code for what I tried.

for (let i = 0; i < getSelectedId.length; i++) {
  fullPackageParams = `${fullPackageParams}FullPackageIDs[${i}]=${getSelectedId[i]}&`;
  for (let j = 0; j < getPartialId.length; j++) {
    // const getPartialName = this.partialPackage.map(res => res[i].FormsList);
    const getPartialName = getPartialId[j].FormsList;

    partialPackageIDParams = `${partialPackageIDParams}PartialPkg[${j}].PackageID=${getPartialId[j].PackageID}&`;

    for (let index = 0; index < getPartialName.length; index++) {
      partialPackageNameParams = `PartialPkg[${index}].FormsList[${index}].Form_Name=${getPartialName[index].Form_Name}&`;
    }
  }
}
console.log('params for full packages', fullPackageParams + partialPackageIDParams + partialPackageNameParams);

Body:
even if it seems kinda strange to me that you need to pass all of those params using query, you can try this

it just uses ES6 map, reduce functions to create your query string

let URLQuery = bodyJSON.map(value => {
    const packageIDs = value.FullPackageIDs.map((v, i) => `FullPackageIDs[${i}]=${encodeURIComponent(v)}`);
    const partialPkgs = value.PartialPkg.map((v, i) => {
        const startKey = `PartialPkg[${i}]`;
        return [
            `${startKey}.PackageID=${v.PackageID}`
        ].concat(
            v.FormsList.map((v, i) => `${startKey}.FormsList[${i}].Form_Name=${encodeURIComponent(v.Form_Name)}`)
        );
    }).reduce((arr, v) => {
        return arr.concat(v)
    }, []);

    return packageIDs.concat(partialPkgs);
}).reduce((arr, v) => {
    return arr.concat(v);
}, []).join("&");

const fullURL = `https://example.com?${URLQuery}`;


问:
Laravel some questions (pagination, if - foreach)
I'm laravel newbie. I'm created simple code and I have some questions:
I think this code bad (it works, but I use @forelse($forums as $forum) and anywhere use $forum)

```<code>@extends('layouts.main')
@section('content')
@forelse($forums as $forum) <-- I don't like this line, it works but i think it's possible with if or something else
@forelse($topics as $topic)
{{ $topic->title }}<br>
@empty
Sorry but this forums empty.
@endforelse
@empty
Sorry but this forum not found
@endforelse
@stop
</code>```

And second question how to make pagination? I'm tried this:

```<code><?php

namespace App\Http\Controllers;
use DB;
use View;

class viewForum extends Controller
{
    public function showForum($fname, $fid)
    {
        return View::make('forum', [
            'forums'    => DB::table('forums')
                ->where('id', $fid)
                ->where('seo_name', $fname)
                ->select()
                ->get()
                ->simplePagination(5)
        ]);
    }
}
</code>```

But not work's, I'm tried tutorials..etc, how to? Thanks so much in advance ! :)

答:
for pagination i will suggest you use jquery datatable for proper pagination. Its quite okay and saves lots of time. see below the sample implementation:

```<code>//this preload the jquery library for datatable together with the print button
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.5.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.5.2/js/buttons.print.min.js"></script>

//this section call the document ready event making sure that datatable is loaded
<script>

 $(document).ready(function() {
    $('#').DataTable();
  } );

//this section display the datatable
  $(document).ready(function() {
      $('#mytable').DataTable( {
          dom: 'Bfrtip',
          "pageLength": 5, //here you can set the page row limit
          buttons: [
              {
                  extend: 'print',
                  customize: function ( win ) {
                      $(win.document.body)
                          .css( 'font-size', '10pt' )
                          .prepend(
                              ''
                          );

                      $(win.document.body).find( 'table' )
                          .addClass( 'compact' )
                          .css( 'font-size', 'inherit' );
                  }
              }
          ]
      } );
  } );
</script>

//you can display record on the datatable as shown below
<div class="table-responsive col-md-12">
 <table id="mytable" class="table table-bordered table-striped table-highlight">
                                            <thead>
                                              <tr bgcolor="#c7c7c7">
                                                <th>S/N</th>
                                                 <th>Name</th>
                                              </tr>
                                            </thead>

                                            <tbody>

                                              @php
                                              $i=1;
                                              @endphp
                                                @foreach($queryrecord as $list)

                                                   <tr>
                                                   <td>{{ $i++ }}</td>
                                                   <td>{{ $list->name }}</td>
                                                   </tr>
                                               @endforeach
                                                </tbody>

                                          </table>
                                           <hr />
                                        </div>
</code>```

Note: remember before displaying information on the datatable, you must have query your record from database.i'm using query builder here as sample

```<code>$data['queryrecord']=DB::table('tablename')->get();
</code>```

Body:
I'm laravel newbie. I'm created simple code and I have some questions:
I think this code bad (it works, but I use @forelse($forums as $forum) and anywhere use $forum)

@extends('layouts.main')
@section('content')
@forelse($forums as $forum) <-- I don't like this line, it works but i think it's possible with if or something else
@forelse($topics as $topic)
{{ $topic->title }}

@empty
Sorry but this forums empty.
@endforelse
@empty
Sorry but this forum not found
@endforelse
@stop

And second question how to make pagination? I'm tried this:

<?php

namespace App\Http\Controllers;
use DB;
use View;

class viewForum extends Controller
{
    public function showForum($fname, $fid)
    {
        return View::make('forum', [
            'forums'    => DB::table('forums')
                ->where('id', $fid)
                ->where('seo_name', $fname)
                ->select()
                ->get()
                ->simplePagination(5)
        ]);
    }
}

But not work's, I'm tried tutorials..etc, how to? Thanks so much in advance ! :)

Body:
for pagination i will suggest you use jquery datatable for proper pagination. Its quite okay and saves lots of time. see below the sample implementation:

//this preload the jquery library for datatable together with the print button
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.5.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.5.2/js/buttons.print.min.js"></script>

//this section call the document ready event making sure that datatable is loaded
<script>

 $(document).ready(function() {
    $('#').DataTable();
  } );

//this section display the datatable
  $(document).ready(function() {
      $('#mytable').DataTable( {
          dom: 'Bfrtip',
          "pageLength": 5, //here you can set the page row limit
          buttons: [
              {
                  extend: 'print',
                  customize: function ( win ) {
                      $(win.document.body)
                          .css( 'font-size', '10pt' )
                          .prepend(
                              ''
                          );

                      $(win.document.body).find( 'table' )
                          .addClass( 'compact' )
                          .css( 'font-size', 'inherit' );
                  }
              }
          ]
      } );
  } );
</script>

//you can display record on the datatable as shown below
<div class="table-responsive col-md-12">
 <table id="mytable" class="table table-bordered table-striped table-highlight">
                                            <thead>
                                              <tr bgcolor="#c7c7c7">
                                                <th>S/N</th>
                                                 <th>Name</th>
                                              </tr>
                                            </thead>

                                            <tbody>

                                              @php
                                              $i=1;
                                              @endphp
                                                @foreach($queryrecord as $list)

                                                   <tr>
                                                   <td>{{ $i++ }}</td>
                                                   <td>{{ $list->name }}</td>
                                                   </tr>
                                               @endforeach
                                                </tbody>

                                          </table>
                                           <hr />
                                        </div>

Note: remember before displaying information on the datatable, you must have query your record from database.i'm using query builder here as sample

$data['queryrecord']=DB::table('tablename')->get();


问:
Matching All Substrings in JSGF Grammar
I am using a jsgf format grammar with pocketsphinx. I want to be able to match/recognise a only a finite number of possible input sentences (i.e. a command and control type interface).

However, due to the nature of these “valid” sentences, and sentence fragment (sub-sentence) with three or more words is also a valid input.

For example, if the valid sentences are:

This is a valid sentence

So is this one

then the grammar should contain:

This is a

This is a valid

This is a valid sentence

is a valid

is a valid sentence

a valid sentence

So is this

So is this one

is this one

[Obviously, in this example, this grammar seems a bit bizarre, but it does make sense in the language/context I am using.]

Is there any way this can be done automatically using jsgf grammar syntax or any pocketsphinx / CMU Sphinx tool. Of course I could programmatically generate a grammar file given a set of valid full sentences, but this seems a bit long-winded and makes the grammar file long and difficult to edit directly (or even just to determine what the valid full sentences are).

The best I can come up with just using the rules of the jsgf format (that I know of) is the following. (For the example above:)

```<code><a> = this is a;
<valid> = (<a> | is a) valid;
<sentence> = (<valid> | a valid) sentence;

<this> = so is this;
<one> = (<this> | is this) one;
</code>```

(E.g. the rule  matches any sub-sentence of length three or more which ends with the word “valid”.)

This grammar contains exactly the valid strings listed above. Nevertheless, this grammar still needs to be generated programmatically from the set of valid full sentences, so I may as well list all sub-sentences explicitly. This format does however make it slightly easier to see directly from the jsgf file what the valid full sentences are.

Essentially, my question is: Is there a better way to achieve the above grammar with pocketsphinx?

答:
And it is not the task of the grammar to enforce complex contstrains in recognized speech. When you restrict things in the grammar, recognition becomes much slower and prone to mistakes because users do not follow the grammars as you envision. To build a proper application you need to use a free-form grammar that allows to recognize speech properly and build a post-processor for that. Post-processor can use regular expressions or even some custom code to verify the requirements you need.

This should work:

```<code> <sentence> = this | is  | a | valid | sentence | one | so;
</code>```

If you need something more advanced, you can build a bigram langauge model and convert it to fsg like in librispeech paper on Figure 1.

Also answered on Sourceforge Forum

Title: Matching All Substrings in JSGF Grammar

Body:
I am using a jsgf format grammar with pocketsphinx. I want to be able to match/recognise a only a finite number of possible input sentences (i.e. a command and control type interface).

However, due to the nature of these “valid” sentences, and sentence fragment (sub-sentence) with three or more words is also a valid input.

For example, if the valid sentences are:

This is a valid sentence

So is this one

then the grammar should contain:

This is a

This is a valid

This is a valid sentence

is a valid

is a valid sentence

a valid sentence

So is this

So is this one

is this one

[Obviously, in this example, this grammar seems a bit bizarre, but it does make sense in the language/context I am using.]

Is there any way this can be done automatically using jsgf grammar syntax or any pocketsphinx / CMU Sphinx tool. Of course I could programmatically generate a grammar file given a set of valid full sentences, but this seems a bit long-winded and makes the grammar file long and difficult to edit directly (or even just to determine what the valid full sentences are).

The best I can come up with just using the rules of the jsgf format (that I know of) is the following. (For the example above:)

 = this is a;
<valid> = ( | is a) valid;
<sentence> = (<valid> | a valid) sentence;

<this> = so is this;
<one> = (<this> | is this) one;

(E.g. the rule  matches any sub-sentence of length three or more which ends with the word “valid”.)

This grammar contains exactly the valid strings listed above. Nevertheless, this grammar still needs to be generated programmatically from the set of valid full sentences, so I may as well list all sub-sentences explicitly. This format does however make it slightly easier to see directly from the jsgf file what the valid full sentences are.

Essentially, my question is: Is there a better way to achieve the above grammar with pocketsphinx?

Body:
And it is not the task of the grammar to enforce complex contstrains in recognized speech. When you restrict things in the grammar, recognition becomes much slower and prone to mistakes because users do not follow the grammars as you envision. To build a proper application you need to use a free-form grammar that allows to recognize speech properly and build a post-processor for that. Post-processor can use regular expressions or even some custom code to verify the requirements you need.

This should work:

 <sentence> = this | is  | a | valid | sentence | one | so;

If you need something more advanced, you can build a bigram langauge model and convert it to fsg like in librispeech paper on Figure 1.

Also answered on Sourceforge Forum


问:
MySQL: any way to have a column defaults to auto-increment (or copy from an auto-increment field) but still allow other values to be inserted?
I'm building a Q&A site. I want to store both questions and answers in the same table:

```<code>CREATE TABLE Q_n_A (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    question_id INT NOT NULL,
    # type indicates whether the record is a question (1) or an answer (0)
    type BOOL,
    title VARCHAR(80),
    body VARCHAR(5000)
);
</code>```

When I insert a new question, I don't have a value of question_id for this new question. As such, I want to use the auto_incremented value of id as the value for question_id. So in this case I want question_id to either default to AUTO_INCREMENT or to copy from id.

When I insert an answer to an existing question, I already know what is the question_id for that answer. As such I want to specify a value for question_id at the insert.

Is there a way to do what I want here: default question_id to AUTO_INCREMENT (or copy from the AUTO_INCREMENT field id) but still allow non-default value of question_id to be specified?

Thanks.

答:
```<code>CREATE TABLE Q_n_A (
overall_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
parent_id INT default '0',
title VARCHAR(80),
body VARCHAR(5000)
);
</code>```

Now when someone ask simply insert no parent_id, resulting it to have parent_id = 0
When someone answers insert into parent_id the ovverall_id, via $_POST data or however your form is setup.

Making it easy to query the correct answers to the given question

Body:
I'm building a Q&A site. I want to store both questions and answers in the same table:

CREATE TABLE Q_n_A (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    question_id INT NOT NULL,
    # type indicates whether the record is a question (1) or an answer (0)
    type BOOL,
    title VARCHAR(80),
    body VARCHAR(5000)
);

When I insert a new question, I don't have a value of question_id for this new question. As such, I want to use the auto_incremented value of id as the value for question_id. So in this case I want question_id to either default to AUTO_INCREMENT or to copy from id.

When I insert an answer to an existing question, I already know what is the question_id for that answer. As such I want to specify a value for question_id at the insert.

Is there a way to do what I want here: default question_id to AUTO_INCREMENT (or copy from the AUTO_INCREMENT field id) but still allow non-default value of question_id to be specified?

Thanks.

Body:
CREATE TABLE Q_n_A (
overall_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
parent_id INT default '0',
title VARCHAR(80),
body VARCHAR(5000)
);

Now when someone ask simply insert no parent_id, resulting it to have parent_id = 0
When someone answers insert into parent_id the ovverall_id, via $_POST data or however your form is setup.

Making it easy to query the correct answers to the given question


问:
How to add new label to boxlayout from popup?
I have screen that has two boxlayouts. first one is empty. second one has button to open popup. In popup i have 2 textinputs and checkbox.  I want to add those textinputs as a labels to that boxlayout and checkbox as well.

I can add button to boxlayout if i have button on that screen. but once we go to popup i cant figure out how to do it.

Py.

```<code>from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.popup import Popup
from kivy.uix.button import Button
from kivy.uix.screenmanager import Screen, ScreenManager

class MyPopup(Popup):
    pass

class MainScreen(Screen):
    pass

class SecondScreen(Screen):
    def fire_popup(self):
        pops = MyPopup()
        pops.open()

class ScreenManagement(ScreenManager):
    def changescreen(self, value):

        try:
            if value !='main':
                self.current = value
        except:
            print('No Screen named'+ value)

class testiApp(App):
    def build(self):
        self.title = 'Hello'

    def add_more(self):
        addbutton = self.root.get_screen('Page2').ids.empty
        addbutton.add_widget(Button(text='Hello'))

    def remove(self):
        container = self.root.get_screen('Page2').ids.empty
        if len(container.children) > 0:
            container.remove_widget(container.children[0])

testiApp().run()

</code>```

Kv.

```<code>
<MyPopup>:
    id:pop
    size_hint: .4, .4
    auto_dismiss: False
    title: 'XXX!!'
    BoxLayout:
        orientation:'vertical'
        BoxLayout:
            orientation:'horizontal'
            Label:
                text:'X1'
            TextInput:
                id: X1

            Label:
                text:'X2'
            TextInput:
                id:X2

            CheckBox:
                id:X3

        BoxLayout:
            orientation:'horizontal'
            Button:
                text:'Add'
                on_release: app.add_more()
            Button:
                text: 'Close'
                on_press: pop.dismiss()

ScreenManagement:
    MainScreen:
        name:'Main'
    SecondScreen:
        name:'Page2'

<MainScreen>:
    name:'Main'
    BoxLayout:
        Button:
            text:'Next Page'
            on_release: app.root.current ='Page2'

<SecondScreen>:
    name:'Page2'

    BoxLayout:
        orientation:'vertical'
        BoxLayout:
            orientation:'vertical'
            Label:
                text:'Popup Test'
            ScrollView:
                GridLayout:
                    orientation: "vertical"
                    size_hint_y: None
                    height: self.minimum_height
                    row_default_height: 60
                    cols:1
                    id:empty
            BoxLayout:
                Button:
                    text:'Open Popup'
                    on_press: root.fire_popup()

                Button:
                    text:'Add'
                    on_release: app.add_more()

                Button:
                    text:'remove'
                    on_release: app.remove()
</code>```

答:
Question

I want to add those textinputs as a labels to that boxlayout and
  checkbox as well.

Solution

The solution involves enhancements to the kv file and Python script.

kv file

Implement the view for class rule, <Row>:

Pass the values of X1, X2, X3 to method add_more()

Optional: add attributes to ScrollView:

Snippets - kv file

```<code><Row>:
    x1: ''
    x2: ''
    x3: False

    Label:
        text: root.x1
    Label:
        text: root.x2
    CheckBox:
        active: root.x3

<MyPopup>:
    ...

        BoxLayout:
            orientation:'horizontal'
            Button:
                text:'Add'
                on_release: app.add_more(X1.text, X2.text, X3.active)
...

<SecondScreen>:
    ...

            ScrollView:
                bar_width: 10
                bar_color: 1, 0, 0, 1   # red
                bar_inactive_color: 0, 0, 1, 1   # blue
                effect_cls: "ScrollEffect"
                scroll_type: ['bars', 'content']
</code>```

py file

Declare a class Row() with inheritance of BoxLayout.

Declare class attributes for x1, x2, and x3 of type StringProperty and BooleanProperty

Implement a constructor to populate x1, x2, and x3

Modify method add_more() to accept x1, x2, and x3

Snippets - py file

```<code>class Row(BoxLayout):
    x1 = StringProperty('')
    x2 = StringProperty('')
    x3 = BooleanProperty(False)

    def __init__(self, x1, x2, x3, **kwargs):
        super(Row, self).__init__(**kwargs)
        self.x1 = x1
        self.x2 = x2
        self.x3 = x3

class testiApp(App):
    ...
    def add_more(self, x1, x2, x3):
        addbutton = self.root.get_screen('Page2').ids.empty
        addbutton.add_widget(Row(x1, x2, x3))
</code>```

Output

Body:
I have screen that has two boxlayouts. first one is empty. second one has button to open popup. In popup i have 2 textinputs and checkbox.  I want to add those textinputs as a labels to that boxlayout and checkbox as well.

I can add button to boxlayout if i have button on that screen. but once we go to popup i cant figure out how to do it.

Py.

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.popup import Popup
from kivy.uix.button import Button
from kivy.uix.screenmanager import Screen, ScreenManager

class MyPopup(Popup):
    pass

class MainScreen(Screen):
    pass

class SecondScreen(Screen):
    def fire_popup(self):
        pops = MyPopup()
        pops.open()

class ScreenManagement(ScreenManager):
    def changescreen(self, value):

        try:
            if value !='main':
                self.current = value
        except:
            print('No Screen named'+ value)

class testiApp(App):
    def build(self):
        self.title = 'Hello'

    def add_more(self):
        addbutton = self.root.get_screen('Page2').ids.empty
        addbutton.add_widget(Button(text='Hello'))

    def remove(self):
        container = self.root.get_screen('Page2').ids.empty
        if len(container.children) > 0:
            container.remove_widget(container.children[0])

testiApp().run()

Kv.

<MyPopup>:
    id:pop
    size_hint: .4, .4
    auto_dismiss: False
    title: 'XXX!!'
    BoxLayout:
        orientation:'vertical'
        BoxLayout:
            orientation:'horizontal'
            Label:
                text:'X1'
            TextInput:
                id: X1

            Label:
                text:'X2'
            TextInput:
                id:X2

            CheckBox:
                id:X3

        BoxLayout:
            orientation:'horizontal'
            Button:
                text:'Add'
                on_release: app.add_more()
            Button:
                text: 'Close'
                on_press: pop.dismiss()

ScreenManagement:
    MainScreen:
        name:'Main'
    SecondScreen:
        name:'Page2'

<MainScreen>:
    name:'Main'
    BoxLayout:
        Button:
            text:'Next Page'
            on_release: app.root.current ='Page2'

<SecondScreen>:
    name:'Page2'

    BoxLayout:
        orientation:'vertical'
        BoxLayout:
            orientation:'vertical'
            Label:
                text:'Popup Test'
            ScrollView:
                GridLayout:
                    orientation: "vertical"
                    size_hint_y: None
                    height: self.minimum_height
                    row_default_height: 60
                    cols:1
                    id:empty
            BoxLayout:
                Button:
                    text:'Open Popup'
                    on_press: root.fire_popup()

                Button:
                    text:'Add'
                    on_release: app.add_more()

                Button:
                    text:'remove'
                    on_release: app.remove()

Body:
Question

I want to add those textinputs as a labels to that boxlayout and
  checkbox as well.

Solution

The solution involves enhancements to the kv file and Python script.

kv file

Implement the view for class rule, <Row>:

Pass the values of X1, X2, X3 to method add_more()

Optional: add attributes to ScrollView:

Snippets - kv file

<Row>:
    x1: ''
    x2: ''
    x3: False

    Label:
        text: root.x1
    Label:
        text: root.x2
    CheckBox:
        active: root.x3

<MyPopup>:
    ...

        BoxLayout:
            orientation:'horizontal'
            Button:
                text:'Add'
                on_release: app.add_more(X1.text, X2.text, X3.active)
...

<SecondScreen>:
    ...

            ScrollView:
                bar_width: 10
                bar_color: 1, 0, 0, 1   # red
                bar_inactive_color: 0, 0, 1, 1   # blue
                effect_cls: "ScrollEffect"
                scroll_type: ['bars', 'content']

py file

Declare a class Row() with inheritance of BoxLayout.

Declare class attributes for x1, x2, and x3 of type StringProperty and BooleanProperty

Implement a constructor to populate x1, x2, and x3

Modify method add_more() to accept x1, x2, and x3

Snippets - py file

class Row(BoxLayout):
    x1 = StringProperty('')
    x2 = StringProperty('')
    x3 = BooleanProperty(False)

    def __init__(self, x1, x2, x3, **kwargs):
        super(Row, self).__init__(**kwargs)
        self.x1 = x1
        self.x2 = x2
        self.x3 = x3

class testiApp(App):
    ...
    def add_more(self, x1, x2, x3):
        addbutton = self.root.get_screen('Page2').ids.empty
        addbutton.add_widget(Row(x1, x2, x3))

Output


问:
Pick every ip address but one in particular
I need to create a regex which returns me every possible ip address so between 0.0.0.0 and 255.255.255.255 but one in particular which is 127.0.0.1

i played a little bit with regex but they are a little bit complex
i was doing something like that but even using regex101.com im not able to obtain the proper one.

```<code>^(?![0-9\.]+:)(?!127.0.0.1:)
</code>```

Body:
I need to create a regex which returns me every possible ip address so between 0.0.0.0 and 255.255.255.255 but one in particular which is 127.0.0.1

i played a little bit with regex but they are a little bit complex
i was doing something like that but even using regex101.com im not able to obtain the proper one.

^(?![0-9\.]+:)(?!127.0.0.1:)

Body:
This should work as well and do the validation of range.

^(?!127.0.0.1)((?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9]))$


问:
Airflow emr cluster termination being called before step completion
I am launching a cluster on EMR and submiting some steps on it using airflow.

What i want:

I want to terminate my cluster after all the steps added through EmrAddStepsOperator are complete

What i have tried:

I have tried using together EmrStepSensor and EmrTerminateJobFlowOperator, but my spark step gets cancelled and cluster terminates without completing all the steps

Anyone please suggest how to do it properly. here is my code

```<code>dag = DAG('emr_job_flow_automatic_steps_17',
         default_args=default_args,
         schedule_interval="@daily",
         max_active_runs=1,
         catchup=True,
)

upload_to_S3_task = PythonOperator(
   task_id='upload_to_S3',
   python_callable=upload_file_to_S3,
   op_kwargs={
       'filename': '/home/ab/projects/test.py',
       'key': 'test.py',
       'bucket_name': 'dep-buck',
   },
   dag=dag)

cluster_creator = EmrCreateJobFlowOperator(
   task_id='create_job_flow2',
   job_flow_overrides=JOB_FLOW_OVERRIDES,
   aws_conn_id='aws_default',
   emr_conn_id='emr_default',
   dag=dag
)

step_adder = EmrAddStepsOperator(
   task_id='add_steps',
   job_flow_id="{{ task_instance.xcom_pull('create_job_flow2', key='return_value') }}",
   aws_conn_id='aws_default',
   steps=step,
   dag=dag
)
step_checker = EmrStepSensor(
   task_id='watch_step',
   job_flow_id="{{ task_instance.xcom_pull('create_job_flow2', key='return_value') }}",
   step_id="{{ task_instance.xcom_pull('add_steps', key='return_value')[0] }}",
   aws_conn_id='aws_default',
   dag=dag
)

cluster_remover = EmrTerminateJobFlowOperator(
   task_id='remove_cluster',
   job_flow_id="{{ task_instance.xcom_pull('create_job_flow2', key='return_value') }}",
   aws_conn_id='aws_default',
   dag=dag
)

upload_to_S3_task >> cluster_creator >> step_adder >> step_checker >> cluster_remover
</code>```

Other Questions on stackoverflow:

There is one similar question on stackoverflow but it has not been answered properly (using EmrTerminateJobFlowOperator)

答:
So I managed to do it. The problem is that i was feeding EmrStepSensor all steps in as one stepadder, so as soon as one was finishing it was terminating the cluster.

The solution is to separate all steps and give the last step'id to the EmrStepSensor. Alternatively, i have separated only the last step with its separate step adder (step_adder_actual_step) from others and provided it to EmrStepSensor

```<code>step_adder_pre_step = EmrAddStepsOperator(
    task_id='pre_step',
    job_flow_id="{{ task_instance.xcom_pull('create_job_flow2', key='return_value') }}",
    aws_conn_id='aws_default',
    steps=pre_step,
    dag=dag
)

step_adder_actual_step = EmrAddStepsOperator(
    task_id='actual_step',
    job_flow_id="{{ task_instance.xcom_pull('create_job_flow2', key='return_value') }}",
    aws_conn_id='aws_default',
    steps=actual_step,
    dag=dag
)

step_checker = EmrStepSensor(
    task_id='watch_step',
    job_flow_id="{{ task_instance.xcom_pull('create_job_flow2', key='return_value') }}",
    step_id="{{ task_instance.xcom_pull('actual_step', key='return_value')[0] }}",
    aws_conn_id='aws_default',
    dag=dag
)

cluster_remover = EmrTerminateJobFlowOperator(
    task_id='remove_cluster',
    job_flow_id="{{ task_instance.xcom_pull('create_job_flow2', key='return_value') }}",
    aws_conn_id='aws_default',
    dag=dag
)

cluster_creator >> step_adder_pre_step >> step_adder_actual_step >> step_checker >> cluster_remover
</code>```

Body:
I am launching a cluster on EMR and submiting some steps on it using airflow.

What i want:

I want to terminate my cluster after all the steps added through EmrAddStepsOperator are complete

What i have tried:

I have tried using together EmrStepSensor and EmrTerminateJobFlowOperator, but my spark step gets cancelled and cluster terminates without completing all the steps

Anyone please suggest how to do it properly. here is my code

dag = DAG('emr_job_flow_automatic_steps_17',
         default_args=default_args,
         schedule_interval="@daily",
         max_active_runs=1,
         catchup=True,
)

upload_to_S3_task = PythonOperator(
   task_id='upload_to_S3',
   python_callable=upload_file_to_S3,
   op_kwargs={
       'filename': '/home/ab/projects/test.py',
       'key': 'test.py',
       'bucket_name': 'dep-buck',
   },
   dag=dag)

cluster_creator = EmrCreateJobFlowOperator(
   task_id='create_job_flow2',
   job_flow_overrides=JOB_FLOW_OVERRIDES,
   aws_conn_id='aws_default',
   emr_conn_id='emr_default',
   dag=dag
)

step_adder = EmrAddStepsOperator(
   task_id='add_steps',
   job_flow_id="{{ task_instance.xcom_pull('create_job_flow2', key='return_value') }}",
   aws_conn_id='aws_default',
   steps=step,
   dag=dag
)
step_checker = EmrStepSensor(
   task_id='watch_step',
   job_flow_id="{{ task_instance.xcom_pull('create_job_flow2', key='return_value') }}",
   step_id="{{ task_instance.xcom_pull('add_steps', key='return_value')[0] }}",
   aws_conn_id='aws_default',
   dag=dag
)

cluster_remover = EmrTerminateJobFlowOperator(
   task_id='remove_cluster',
   job_flow_id="{{ task_instance.xcom_pull('create_job_flow2', key='return_value') }}",
   aws_conn_id='aws_default',
   dag=dag
)

upload_to_S3_task >> cluster_creator >> step_adder >> step_checker >> cluster_remover

Other Questions on stackoverflow:

There is one similar question on stackoverflow but it has not been answered properly (using EmrTerminateJobFlowOperator)

Body:
So I managed to do it. The problem is that i was feeding EmrStepSensor all steps in as one stepadder, so as soon as one was finishing it was terminating the cluster.

The solution is to separate all steps and give the last step'id to the EmrStepSensor. Alternatively, i have separated only the last step with its separate step adder (step_adder_actual_step) from others and provided it to EmrStepSensor

step_adder_pre_step = EmrAddStepsOperator(
    task_id='pre_step',
    job_flow_id="{{ task_instance.xcom_pull('create_job_flow2', key='return_value') }}",
    aws_conn_id='aws_default',
    steps=pre_step,
    dag=dag
)

step_adder_actual_step = EmrAddStepsOperator(
    task_id='actual_step',
    job_flow_id="{{ task_instance.xcom_pull('create_job_flow2', key='return_value') }}",
    aws_conn_id='aws_default',
    steps=actual_step,
    dag=dag
)

step_checker = EmrStepSensor(
    task_id='watch_step',
    job_flow_id="{{ task_instance.xcom_pull('create_job_flow2', key='return_value') }}",
    step_id="{{ task_instance.xcom_pull('actual_step', key='return_value')[0] }}",
    aws_conn_id='aws_default',
    dag=dag
)

cluster_remover = EmrTerminateJobFlowOperator(
    task_id='remove_cluster',
    job_flow_id="{{ task_instance.xcom_pull('create_job_flow2', key='return_value') }}",
    aws_conn_id='aws_default',
    dag=dag
)

cluster_creator >> step_adder_pre_step >> step_adder_actual_step >> step_checker >> cluster_remover


问:
Numbering row in order by ID
Sorry if this post is not well organized, first time stack overflower...

I am trying to create a column to create a order within each IDs, but the twist is that if there is a gap year, order needs to start from the beginning.
Please check example and expected result below.

I wasn't able to find appropriate code for it.. I cannot think of anything :( Please help me! I appreciate alot!

答:
We can take the difference of 'Year' and the lag of 'Year', get the cumulative sum, use that in the group_by along with 'ID' and create the order as row_number()

```<code>library(dplyr)
df %>%
  group_by(ID, grp = cumsum(Year - lag(Year, default = Year[1]) > 1)) %>%
  mutate(order = row_number()) %>%
  ungroup %>%
  select(-grp)
# A tibble: 10 x 3
#   ID     Year order
#   <chr> <dbl> <int>
# 1 A      2007     1
# 2 A      2008     2
# 3 A      2009     3
# 4 A      2013     1
# 5 A      2014     2
# 6 A      2015     3
# 7 A      2016     4
# 8 B      2010     1
# 9 B      2012     1
#10 B      2013     2
</code>```

data

```<code>df <- structure(list(ID = c("A", "A", "A", "A", "A", "A", "A", "B",
"B", "B"), Year = c(2007, 2008, 2009, 2013, 2014, 2015, 2016,
2010, 2012, 2013)), class = "data.frame", row.names = c(NA, -10L
))
</code>```

Title: Numbering row in order by ID

Body:
We can take the difference of 'Year' and the lag of 'Year', get the cumulative sum, use that in the group_by along with 'ID' and create the order as row_number()

library(dplyr)
df %>%
  group_by(ID, grp = cumsum(Year - lag(Year, default = Year[1]) > 1)) %>%
  mutate(order = row_number()) %>%
  ungroup %>%
  select(-grp)
# A tibble: 10 x 3
#   ID     Year order
#   <chr> <dbl> <int>
# 1 A      2007     1
# 2 A      2008     2
# 3 A      2009     3
# 4 A      2013     1
# 5 A      2014     2
# 6 A      2015     3
# 7 A      2016     4
# 8 B      2010     1
# 9 B      2012     1
#10 B      2013     2

data

df <- structure(list(ID = c("A", "A", "A", "A", "A", "A", "A", "B",
"B", "B"), Year = c(2007, 2008, 2009, 2013, 2014, 2015, 2016,
2010, 2012, 2013)), class = "data.frame", row.names = c(NA, -10L
))


问:
How to consume a VSTS artifact DLL from another pipeline in my VSTS MSTest pipeline
I am trying to use a DLL artifact from a developers build pipeline in my VSTS MSTest build pipeline.  I need to reference this DLL but I get an error - Error CS0246: The type or namespace name 'Adv' could not be found (are you missing a using directive or an assembly reference?)

I am able to download the DLL's/Artifacts successfully to the agent using Download Build Artifacts option in my pipeline.

How can I get my build in the VSTS pipepline to use the downloaded DLL artifacts on the agent and get rid of this error?

答:
I found out you need to use the copy files option to get the DLL's where you want them.  I first tried \bin\debug but the problem there was the build creates these areas automatically and it overwrote my file copy.  I noticed in the build log it was considering looking here for the DLL's - C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.0.

I updated the copy files to copy there and the solution builds just fine now.


问:
Handling the Callback from animoto videos
I am using Animoto API to create all the images into video.

As per the animoto documentation I have used "
job = Animoto::Jobs::DirectingAndRendering.load(JSON.parse(request.body))"

for handling the call back from anomoto API but it is throwing error called

"uninitialized constant Animoto::Jobs"

Anybody has any idea about his. Please help me

答:
I don't know Animoto, but your error comes from a missing Ruby library defining Animoto::Jobs class.
This can be resolved by requiring the Ruby file defining this class, using require '<NameOfRubyFile>' before using it (usually at the top of your .rb file).

You can try the following:

Check the way Animoto's API is meant to be included. Some libraries will just need 1 require that will then include plenty of other files (ie. require 'animoto'). Other libraries will ask you to require each individual file manually (ie. require 'animoto/main'; require 'animoto/jobs'). I would say that Animoto documentation should tell.

Check the require lines used by other projects using Animoto::Jobs class.

If Animoto respects some Ruby standards, you can try blindly require 'animoto/jobs'

If you have access to Animoto's source code, try looking for the class definition among its files. The definition should look like class Jobs or class Animoto::Jobs. Grep this in the source files, and require the matching one.

Maybe a specialist of Animoto's library will be able to point you directly to the missing require.


问:
How to represent complex POST data in python for requests
I'm trying to automate a web form.  The payload when I actually run the query in Chrome looks like this on the inspect window...

```<code>    data: [{"property":"TimeQuick","value":"Active"},{"property":"TimeQuickDurationOptions","value":3},{"property":"TimeQuickStartDate","value":"05/15/2019 00:00:00"},{"property":"TimeQuickEndDate","value":"05/15/2019 23:59:59"},{"property":"ProviderCode","value":["FPL"]},{"property":"SellerCode","value":[""]},{"property":"Ref","value":""},{"property":"POR","value":["SOCO"]},{"property":"POD","value":["FPC"]},{"property":"Path","value":""},{"property":"ServiceIncrement","value":["DAILY"]},{"property":"TSClass","value":[""]},{"property":"TSType","value":[""]},{"property":"TSWindow","value":""},{"property":"TSPeriod","value":""},{"property":"TSSubClass","value":""},{"property":"Time","value":"Active"},{"property":"TimeDurationOptions","value":3},{"property":"TimeStartDate","value":"05/15/2019 00:00:00"},{"property":"TimeEndDate","value":"05/15/2019 23:59:59"},{"property":"ShowActiveData","value":true},{"property":"DaylightSavings","value":false}]
    sort: [{"property":"TOL","direction":"DESC","root":"data"}]
    pagingEnabled: 1
    page: 1
    limit: 50
</code>```

I tried to represent that as a python variable like this

```<code>    datareq = [
             ('data',
              {'property':'TimeQuick', 'value':'Active'},
              {"property":"TimeQuickDurationOptions","value":'3'},
              {"property":"TimeQuickStartDate","value":"05/15/2019 00:00:00"},
              {"property":"TimeQuickEndDate","value":"05/15/2019 23:59:59"},
              {"property":"ProviderCode","value":["FPL"]},
              {"property":"SellerCode","value":[""]},
              {"property":"Ref","value":""},
              {"property":"POR","value":["SOCO"]},
              {"property":"POD","value":["FPC"]},
              {"property":"Path","value":""},
              {"property":"ServiceIncrement","value":["DAILY"]},
              {"property":"TSClass","value":[""]},
              {"property":"TSType","value":[""]},
              {"property":"TSWindow","value":""},
              {"property":"TSPeriod","value":""},
              {"property":"TSSubClass","value":""},
              {"property":"Time","value":"Active"},
              {"property":"TimeDurationOptions","value":3},
              {"property":"TimeStartDate","value":"05/15/2019 00:00:00"},
              {"property":"TimeEndDate","value":"05/15/2019 23:59:59"},
              {"property":"ShowActiveData","value":'true'},
              {"property":"DaylightSavings","value":'false'}
              ),
             ('sort',
              {"property":"TOL","direction":"DESC","root":"data"}
              ),
             ('pagingEnabled', 1),
             ('limit', 50)

             ]
</code>```

When I ran s.post(myurl, data=datareq, cert=mycerts) I got the following error:

```<code>    Traceback (most recent call last):

      File "<ipython-input-78-37ee269ebbce>", line 1, in <module>
        logblah=s.post(myurl, data= datareq, cert=mycerts)

      File "C:\Users\me\AppData\Local\Continuum\anaconda3\Lib\python\requests\sessions.py", line 555, in post
        return self.request('POST', url, data=data, json=json, **kwargs)

      File "C:\Users\me\AppData\Local\Continuum\anaconda3\Lib\python\requests\sessions.py", line 494, in request
        prep = self.prepare_request(req)

      File "C:\Users\me\AppData\Local\Continuum\anaconda3\Lib\python\requests\sessions.py", line 437, in prepare_request
        hooks=merge_hooks(request.hooks, self.hooks),

      File "C:\Users\me\AppData\Local\Continuum\anaconda3\Lib\python\requests\models.py", line 308, in prepare
        self.prepare_body(data, files, json)

      File "C:\Users\me\AppData\Local\Continuum\anaconda3\Lib\python\requests\models.py", line 499, in prepare_body
        body = self._encode_params(data)

      File "C:\Users\me\AppData\Local\Continuum\anaconda3\Lib\python\requests\models.py", line 97, in _encode_params
        for k, vs in to_key_val_list(data):

    ValueError: too many values to unpack (expected 2)
</code>```

I'm assuming the problem is in the way I've structured my datareq variable.  What would be the proper way to make that POST?

Edit/Update:
I've tried each of Alex and Ivan's suggestions but neither work.  They each give me a cryptic message from the server that success=false.  If I try them with json=datareq instead of data=datareq then I get a response from the server with 0 results even though it should have many so it seems like that is getting closer but still not all the way.

答:
Below is the python representation of that data,

```<code>data = {
    "data": [
        {"property": "TimeQuick", "value": "Active"},
        {"property": "TimeQuickDurationOptions", "value": 3},
        {"property": "TimeQuickStartDate", "value": "05/15/2019 00:00:00"},
        {"property": "TimeQuickEndDate", "value": "05/15/2019 23:59:59"},
        {"property": "ProviderCode", "value": ["FPL"]},
        {"property": "SellerCode", "value": [""]},
        {"property": "Ref", "value": ""},
        {"property": "POR", "value": ["SOCO"]},
        {"property": "POD", "value": ["FPC"]},
        {"property": "Path", "value": ""},
        {"property": "ServiceIncrement", "value": ["DAILY"]},
        {"property": "TSClass", "value": [""]},
        {"property": "TSType", "value": [""]},
        {"property": "TSWindow", "value": ""},
        {"property": "TSPeriod", "value": ""},
        {"property": "TSSubClass", "value": ""},
        {"property": "Time", "value": "Active"},
        {"property": "TimeDurationOptions", "value": 3},
        {"property": "TimeStartDate", "value": "05/15/2019 00:00:00"},
        {"property": "TimeEndDate", "value": "05/15/2019 23:59:59"},
        {"property": "ShowActiveData", "value": True},
        {"property": "DaylightSavings", "value": False}],
    "sort": [
        {"property": "TOL", "direction": "DESC", "root": "data"}
    ],
    "pagingEnabled": 1,
    "page": 1,
    "limit": 50,
}
</code>```

you don't need to put any json objects to the request.post any valid python dictionary would do. The only thing you need to worry about is the schema of the json for the server to accept. The python dictionary is automatically turned into json when you put it to post method automatically by the library.

Body:
I'm trying to automate a web form.  The payload when I actually run the query in Chrome looks like this on the inspect window...

    data: [{"property":"TimeQuick","value":"Active"},{"property":"TimeQuickDurationOptions","value":3},{"property":"TimeQuickStartDate","value":"05/15/2019 00:00:00"},{"property":"TimeQuickEndDate","value":"05/15/2019 23:59:59"},{"property":"ProviderCode","value":["FPL"]},{"property":"SellerCode","value":[""]},{"property":"Ref","value":""},{"property":"POR","value":["SOCO"]},{"property":"POD","value":["FPC"]},{"property":"Path","value":""},{"property":"ServiceIncrement","value":["DAILY"]},{"property":"TSClass","value":[""]},{"property":"TSType","value":[""]},{"property":"TSWindow","value":""},{"property":"TSPeriod","value":""},{"property":"TSSubClass","value":""},{"property":"Time","value":"Active"},{"property":"TimeDurationOptions","value":3},{"property":"TimeStartDate","value":"05/15/2019 00:00:00"},{"property":"TimeEndDate","value":"05/15/2019 23:59:59"},{"property":"ShowActiveData","value":true},{"property":"DaylightSavings","value":false}]
    sort: [{"property":"TOL","direction":"DESC","root":"data"}]
    pagingEnabled: 1
    page: 1
    limit: 50

I tried to represent that as a python variable like this

    datareq = [
             ('data',
              {'property':'TimeQuick', 'value':'Active'},
              {"property":"TimeQuickDurationOptions","value":'3'},
              {"property":"TimeQuickStartDate","value":"05/15/2019 00:00:00"},
              {"property":"TimeQuickEndDate","value":"05/15/2019 23:59:59"},
              {"property":"ProviderCode","value":["FPL"]},
              {"property":"SellerCode","value":[""]},
              {"property":"Ref","value":""},
              {"property":"POR","value":["SOCO"]},
              {"property":"POD","value":["FPC"]},
              {"property":"Path","value":""},
              {"property":"ServiceIncrement","value":["DAILY"]},
              {"property":"TSClass","value":[""]},
              {"property":"TSType","value":[""]},
              {"property":"TSWindow","value":""},
              {"property":"TSPeriod","value":""},
              {"property":"TSSubClass","value":""},
              {"property":"Time","value":"Active"},
              {"property":"TimeDurationOptions","value":3},
              {"property":"TimeStartDate","value":"05/15/2019 00:00:00"},
              {"property":"TimeEndDate","value":"05/15/2019 23:59:59"},
              {"property":"ShowActiveData","value":'true'},
              {"property":"DaylightSavings","value":'false'}
              ),
             ('sort',
              {"property":"TOL","direction":"DESC","root":"data"}
              ),
             ('pagingEnabled', 1),
             ('limit', 50)

             ]

When I ran s.post(myurl, data=datareq, cert=mycerts) I got the following error:

    Traceback (most recent call last):

      File "<ipython-input-78-37ee269ebbce>", line 1, in <module>
        logblah=s.post(myurl, data= datareq, cert=mycerts)

      File "C:\Users\me\AppData\Local\Continuum\anaconda3\Lib\python\requests\sessions.py", line 555, in post
        return self.request('POST', url, data=data, json=json, **kwargs)

      File "C:\Users\me\AppData\Local\Continuum\anaconda3\Lib\python\requests\sessions.py", line 494, in request
        prep = self.prepare_request(req)

      File "C:\Users\me\AppData\Local\Continuum\anaconda3\Lib\python\requests\sessions.py", line 437, in prepare_request
        hooks=merge_hooks(request.hooks, self.hooks),

      File "C:\Users\me\AppData\Local\Continuum\anaconda3\Lib\python\requests\models.py", line 308, in prepare
        self.prepare_body(data, files, json)

      File "C:\Users\me\AppData\Local\Continuum\anaconda3\Lib\python\requests\models.py", line 499, in prepare_body
        body = self._encode_params(data)

      File "C:\Users\me\AppData\Local\Continuum\anaconda3\Lib\python\requests\models.py", line 97, in _encode_params
        for k, vs in to_key_val_list(data):

    ValueError: too many values to unpack (expected 2)

I'm assuming the problem is in the way I've structured my datareq variable.  What would be the proper way to make that POST?

Edit/Update:
I've tried each of Alex and Ivan's suggestions but neither work.  They each give me a cryptic message from the server that success=false.  If I try them with json=datareq instead of data=datareq then I get a response from the server with 0 results even though it should have many so it seems like that is getting closer but still not all the way.

Body:
Below is the python representation of that data,

data = {
    "data": [
        {"property": "TimeQuick", "value": "Active"},
        {"property": "TimeQuickDurationOptions", "value": 3},
        {"property": "TimeQuickStartDate", "value": "05/15/2019 00:00:00"},
        {"property": "TimeQuickEndDate", "value": "05/15/2019 23:59:59"},
        {"property": "ProviderCode", "value": ["FPL"]},
        {"property": "SellerCode", "value": [""]},
        {"property": "Ref", "value": ""},
        {"property": "POR", "value": ["SOCO"]},
        {"property": "POD", "value": ["FPC"]},
        {"property": "Path", "value": ""},
        {"property": "ServiceIncrement", "value": ["DAILY"]},
        {"property": "TSClass", "value": [""]},
        {"property": "TSType", "value": [""]},
        {"property": "TSWindow", "value": ""},
        {"property": "TSPeriod", "value": ""},
        {"property": "TSSubClass", "value": ""},
        {"property": "Time", "value": "Active"},
        {"property": "TimeDurationOptions", "value": 3},
        {"property": "TimeStartDate", "value": "05/15/2019 00:00:00"},
        {"property": "TimeEndDate", "value": "05/15/2019 23:59:59"},
        {"property": "ShowActiveData", "value": True},
        {"property": "DaylightSavings", "value": False}],
    "sort": [
        {"property": "TOL", "direction": "DESC", "root": "data"}
    ],
    "pagingEnabled": 1,
    "page": 1,
    "limit": 50,
}

you don't need to put any json objects to the request.post any valid python dictionary would do. The only thing you need to worry about is the schema of the json for the server to accept. The python dictionary is automatically turned into json when you put it to post method automatically by the library.


问:
Unable to download full html using Wget in batch script
I'm creating a database from digikey parts and using Wget in my batch script to retrieve the html. I'm unable to download the full html using a URL via keywords.

As an example, I'm able to download the the html into my "Test_Read_File.txt" using the URL "https://www.digikey.ca/product-detail/en/DF3-5P-2DSA-01/H3924-ND/560482" but unable if I use the URL "https://www.digikey.ca/products/en?keywords=DF3-5P-2DSA(01)". Both URLs will open the same page. I would use the first URL but am unable too because of the "560482" number at the end which changes for every component. My main program will call a .txt file with thousands of manufacturer part numbers and insert them one by one as a replacement for DF3-5P-2DSA(01). I don't think Agent is necessary in this case.

```<code>SET AGENT="Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64; Trident/8.0; .NET4.0C; .NET4.0E)"

Wget -U %AGENT% -O Test_Read_File.txt "https://www.digikey.ca/products/en?keywords=DF3-5P-2DSA(01)"
</code>```

答:
I ended up creating a python script (.py) that used selenium and created a call from my batch.</p>

```<code>from time import sleep
from bs4 import BeautifulSoup
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://www.digikey.com/products/en?keywords=EDH106M016A9BAA')

sleep(3)
source = driver.page_source
soup = BeautifulSoup(source)

saveFile = open('FILE-LOCATION','w',encoding='utf-8')
saveFile.write(str(soup))
saveFile.close()
driver.quit()
</code>```

Body:
I'm creating a database from digikey parts and using Wget in my batch script to retrieve the html. I'm unable to download the full html using a URL via keywords.

As an example, I'm able to download the the html into my "Test_Read_File.txt" using the URL "https://www.digikey.ca/product-detail/en/DF3-5P-2DSA-01/H3924-ND/560482" but unable if I use the URL "https://www.digikey.ca/products/en?keywords=DF3-5P-2DSA(01)". Both URLs will open the same page. I would use the first URL but am unable too because of the "560482" number at the end which changes for every component. My main program will call a .txt file with thousands of manufacturer part numbers and insert them one by one as a replacement for DF3-5P-2DSA(01). I don't think Agent is necessary in this case.

SET AGENT="Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64; Trident/8.0; .NET4.0C; .NET4.0E)"

Wget -U %AGENT% -O Test_Read_File.txt "https://www.digikey.ca/products/en?keywords=DF3-5P-2DSA(01)"

Body:
I ended up creating a python script (.py) that used selenium and created a call from my batch.

from time import sleep
from bs4 import BeautifulSoup
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://www.digikey.com/products/en?keywords=EDH106M016A9BAA')

sleep(3)
source = driver.page_source
soup = BeautifulSoup(source)

saveFile = open('FILE-LOCATION','w',encoding='utf-8')
saveFile.write(str(soup))
saveFile.close()
driver.quit()


问:
How to interpret an apache mod rewrite rule?
I am struggling to fully understand this rule and want to make sure that I am not guessing.

funny.cat.pictures.com is my silly attempt to hide the clients actual 4 part url . I found this rule in a conf file in sites-enabled. It was written by others before me.

```<code><Directory /var/www/active/vhost/funny.cat.pictures.com/html>
  <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_URI} ^/sites/
    RewriteCond %{REQUEST_URI} !^/sites/funny\.cat\.pictures\.com/
    RewriteCond %{REQUEST_URI} !^/sites/funny\-cat\.pictures\.com/
    RewriteCond %{REQUEST_URI} !^/sites/all/
    RewriteRule ^ - [F]
  </IfModule>
</code>```

Am I correct to say the meaning of this rule is:
if the uri has /sites/ but 1) does not have /sites/funny[. or -]pictures.com or 2) does not have /sites/all  then block that path as a forbidden path?

Do I understand this correctly?

I thank you for your time.

答:
With more testing confirmed that what I posed here as a question was correct.
This configuration comes handy in drupal multisite setups.
Given a site funny.cat.pictures.com all request to funny.cat.pictures.com/sites/funny.pictures.com/files/... or funny.cat.pictures.com/sites/funny-pictures.com/files/... will be allowed.
But apache will block a request to
funny.cat.pictures.com/sites/another.site.com/files/...</p>

Body:
I am struggling to fully understand this rule and want to make sure that I am not guessing.

funny.cat.pictures.com is my silly attempt to hide the clients actual 4 part url . I found this rule in a conf file in sites-enabled. It was written by others before me.

<Directory /var/www/active/vhost/funny.cat.pictures.com/html>
  <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_URI} ^/sites/
    RewriteCond %{REQUEST_URI} !^/sites/funny\.cat\.pictures\.com/
    RewriteCond %{REQUEST_URI} !^/sites/funny\-cat\.pictures\.com/
    RewriteCond %{REQUEST_URI} !^/sites/all/
    RewriteRule ^ - [F]
  </IfModule>

Am I correct to say the meaning of this rule is:
if the uri has /sites/ but 1) does not have /sites/funny[. or -]pictures.com or 2) does not have /sites/all  then block that path as a forbidden path?

Do I understand this correctly?

I thank you for your time.


问:
Run command after container start up
I'm trying to execute command after docker container start.

Here is my Dockerfile

```<code>FROM mysite:myport/mongo:3.6
EXPOSE 27017
ADD mongo.js /data/mongodb/scripts/
</code>```

here is my docker-compose.yml

```<code>mongo:
    image: test-mongo
    container_name: test-mongo
    hostname: mongo
    expose:
      - "27017"
    ports:
      - "27017:27017"
    command: mongo --eval load("/data/mongodb/scripts/mongo.js")
</code>```

docker-compose --no-ansi up returns me

```<code>Creating test-mongo ...
Creating test-mongo ... done
Attaching to test-mongo
test-mongo | MongoDB shell version v3.6.5
test-mongo | connecting to: mongodb://127.0.0.1:27017
test-mongo | 2018-06-09T15:46:50.229+0000 W NETWORK  [thread1] Failed to connect to 127.0.0.1:27017, in(checking socket for error after poll), rea
son: Connection refused
test-mongo | 2018-06-09T15:46:50.229+0000 E QUERY    [thread1] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed :
test-mongo | connect@src/mongo/shell/mongo.js:251:13
test-mongo | @(connect):1:6
test-mongo | exception: connect failed
test-mongo exited with code 1
</code>```

I don't uderstand how can I load my file after mongodb is started

答:
If all you're trying to do is initialize a new database, such as creating a new schema and adding a user, you can create an initialization script and load it into the container. From the Docker Hub documentation:

When a container is started for the first time it will execute files with extensions .sh and .js that are found in /docker-entrypoint-initdb.d. Files will be executed in alphabetical order. .js files will be executed by mongo using the database specified by the MONGO_INITDB_DATABASE variable, if it is present, or test otherwise. You may also switch databases within the .js script.

Title: Run command after container start up

Body:
I'm trying to execute command after docker container start.

Here is my Dockerfile

FROM mysite:myport/mongo:3.6
EXPOSE 27017
ADD mongo.js /data/mongodb/scripts/

here is my docker-compose.yml

mongo:
    image: test-mongo
    container_name: test-mongo
    hostname: mongo
    expose:
      - "27017"
    ports:
      - "27017:27017"
    command: mongo --eval load("/data/mongodb/scripts/mongo.js")

docker-compose --no-ansi up returns me

Creating test-mongo ...
Creating test-mongo ... done
Attaching to test-mongo
test-mongo | MongoDB shell version v3.6.5
test-mongo | connecting to: mongodb://127.0.0.1:27017
test-mongo | 2018-06-09T15:46:50.229+0000 W NETWORK  [thread1] Failed to connect to 127.0.0.1:27017, in(checking socket for error after poll), rea
son: Connection refused
test-mongo | 2018-06-09T15:46:50.229+0000 E QUERY    [thread1] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed :
test-mongo | connect@src/mongo/shell/mongo.js:251:13
test-mongo | @(connect):1:6
test-mongo | exception: connect failed
test-mongo exited with code 1

I don't uderstand how can I load my file after mongodb is started