问:
Key value pairs in C# Params
I'm looking for a way to have a function such as:

```<code>myFunction({"Key", value}, {"Key2", value});
</code>```

I'm sure there's something with anonymous types that would be pretty easy, but I'm not seeing it.

The only solution I can think of is to have a params KeyValuePair<String, object>[] pairs parameter, but that ends up being something similar to:

```<code>myFunction(new KeyValuePair<String, object>("Key", value),
           new KeyValuePair<String, object>("Key2", value));
</code>```

Which is, admittedly, much uglier.

EDIT:

To clarify, I'm writing a Message class to pass between 2 different systems.  It contains a ushort specifying the the Message Type, and a dictionary of string to object for "Data" associated with the message.  I'd like to be able to pass all this information in the constructor, so I am able to do this:

```<code>Agent.SendMessage(new Message(MessageTypes.SomethingHappened, "A", x, "B", y, "C", z));
</code>```

or similar syntax.

答:
Since C# 7.0, you can use value tuples. C# 7.0 not only introduces a new type but a simplified syntax for tuple types and for tuple values. A tuple type is simply written as a list of types surrounded by braces:

```<code>(string, int, double)
</code>```

The corresponding elements are named Item1, Item2, Item2. You can also specify optional aliases. These aliases are only syntactic sugar (a trick of the C# compiler); the tuples are still based on the invariant (but generic)  System.ValueTuple<T1, T2, ...> struct.

```<code>(string name, int count, double magnitude)
</code>```

Tuple values have a similar syntax, except that you specify expressions instead of types

```<code>("test", 7, x + 5.91)
</code>```

or with the aliases

```<code>(name: "test", count: 7, magnitude: x + 5.91)
</code>```

Example with params array:

```<code>public static void MyFunction(params (string Key, object Value)[] pairs)
{
    foreach (var pair in pairs) {
        Console.WriteLine($"{pair.Key} = {pair.Value}");
    }
}
</code>```

It is also possible to deconstruct a tuple like this

```<code>var (key, value) = pair;
Console.WriteLine($"{key} = {value}");
</code>```

This extracts the items of the tuple in two separate variables key and value.

Now, you can call MyFunction with a varying number of arguments easily:

MyFunction(("a", 1), ("b", 2), ("c", 3));

It allows us to do things like

```<code>DrawLine((0, 0), (10, 0), (10, 10), (0, 10), (0, 0));
</code>```

See: New Features in C# 7.0

Title: Key value pairs in C# Params

Body:
I'm looking for a way to have a function such as:

myFunction({"Key", value}, {"Key2", value});

I'm sure there's something with anonymous types that would be pretty easy, but I'm not seeing it.

The only solution I can think of is to have a params KeyValuePair<String, object>[] pairs parameter, but that ends up being something similar to:

myFunction(new KeyValuePair<String, object>("Key", value),
           new KeyValuePair<String, object>("Key2", value));

Which is, admittedly, much uglier.

EDIT:

To clarify, I'm writing a Message class to pass between 2 different systems.  It contains a ushort specifying the the Message Type, and a dictionary of string to object for "Data" associated with the message.  I'd like to be able to pass all this information in the constructor, so I am able to do this:

Agent.SendMessage(new Message(MessageTypes.SomethingHappened, "A", x, "B", y, "C", z));

or similar syntax.

Body:
Since C# 7.0, you can use value tuples. C# 7.0 not only introduces a new type but a simplified syntax for tuple types and for tuple values. A tuple type is simply written as a list of types surrounded by braces:

(string, int, double)

The corresponding elements are named Item1, Item2, Item2. You can also specify optional aliases. These aliases are only syntactic sugar (a trick of the C# compiler); the tuples are still based on the invariant (but generic)  System.ValueTuple<T1, T2, ...> struct.

(string name, int count, double magnitude)

Tuple values have a similar syntax, except that you specify expressions instead of types

("test", 7, x + 5.91)

or with the aliases

(name: "test", count: 7, magnitude: x + 5.91)

Example with params array:

public static void MyFunction(params (string Key, object Value)[] pairs)
{
    foreach (var pair in pairs) {
        Console.WriteLine($"{pair.Key} = {pair.Value}");
    }
}

It is also possible to deconstruct a tuple like this

var (key, value) = pair;
Console.WriteLine($"{key} = {value}");

This extracts the items of the tuple in two separate variables key and value.

Now, you can call MyFunction with a varying number of arguments easily:

MyFunction(("a", 1), ("b", 2), ("c", 3));

It allows us to do things like

DrawLine((0, 0), (10, 0), (10, 10), (0, 10), (0, 0));

See: New Features in C# 7.0


来源: stackexchange

问:
Placing methods in foreach loop c#
not sure if the title is really correct, but this is the issue...

I have a foreach loop populating a pushpin collection. I need to do some 'work' on one of the XML elements (Latitude). the 'work' is commented out. The problem is I cant see where to put these tasks/variables anywhere. wherever I place it I get a varity of errors. I can go into more detail of that if needed, but wondering if there is a better way of doing this. Its preey self explanitory below what im trying to do but let me know if you need more explanation. Any suggestions welcome.

```<code>  public void OnOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
    {
        var document = XDocument.Load(e.Result);
        if (document.Root == null)
            return;
         var events = from ev in document.Descendants("item")

                      .Where(ev => ev.Element("category") != null)

                     select new
                     {

                         Title = (ev.Element("title").Value),
                         Description = (ev.Element("description").Value),
                         Category = (ev.Element("category").Value),
                         Latitude = (ev.Element("link").Value),

                      };

         ObservableCollection<Eng> pushPinCollection = new ObservableCollection<Eng>();

        foreach (var ev in events)
         {

             Eng PushPin = new Eng
               (ev.Title, ev.Description, ev.Category)

           // Lat1 = (ev.Latitude),
            //  var items = Lat1.Split('?')[1].Split('&').Select(i => i.Split  ('=')).ToDictionary(o => o[0], o => o[1]);
            //  var lon = items["lon"];
            //  var lat = items["lat"];
            //  var lat1 = Convert.ToDouble(lat);
            //  var lon1 = Convert.ToDouble(lon);
             {

        //Location value below is System.Device.location.Geocoordinate Eng Location
                  Location = new GeoCoordinate(lat1, lon1),
                  Title = ev.Title,
                  Description = ev.Description,
                  Category = ev.Category

             };
            pushPinCollection.Add(PushPin);
         }
         pushPins = pushPinCollection;
         mapItems.ItemsSource = PushPins;

       }
</code>```

答:
You can't insert any code between the end of the call to the Constructor, and the initializer. There are several ways to address this:

```<code>Eng pushPin = new Eng(...);  // note the semicolon

// calculations to get lat1 and lon1

pushPin.Location = new GeoCoordinate(lat1, lon1); // Location must have a public Set
</code>```

or

```<code>// calculations for lat1 and lon 1

Eng PushPin = new Eng(ev.Title, ev.Description, ev.Category)
                  {
                      Location = new GeoCoordinate(lat1, lon1);
                  }
</code>```

or if you have a constructor that takes the GeoCoordinate:

```<code> Eng PushPin = new Eng(ev.Title, ev.Description, ev.Category, new GeoCoordinate(lat1, lon1));
</code>```

ContentLicense: CC BY-SA 2.5

Title: Placing methods in foreach loop c#

Body:
not sure if the title is really correct, but this is the issue...

I have a foreach loop populating a pushpin collection. I need to do some 'work' on one of the XML elements (Latitude). the 'work' is commented out. The problem is I cant see where to put these tasks/variables anywhere. wherever I place it I get a varity of errors. I can go into more detail of that if needed, but wondering if there is a better way of doing this. Its preey self explanitory below what im trying to do but let me know if you need more explanation. Any suggestions welcome.

  public void OnOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
    {
        var document = XDocument.Load(e.Result);
        if (document.Root == null)
            return;
         var events = from ev in document.Descendants("item")

                      .Where(ev => ev.Element("category") != null)

                     select new
                     {

                         Title = (ev.Element("title").Value),
                         Description = (ev.Element("description").Value),
                         Category = (ev.Element("category").Value),
                         Latitude = (ev.Element("link").Value),

                      };

         ObservableCollection<Eng> pushPinCollection = new ObservableCollection<Eng>();

        foreach (var ev in events)
         {

             Eng PushPin = new Eng
               (ev.Title, ev.Description, ev.Category)

           // Lat1 = (ev.Latitude),
            //  var items = Lat1.Split('?')[1].Split('&').Select(i => i.Split  ('=')).ToDictionary(o => o[0], o => o[1]);
            //  var lon = items["lon"];
            //  var lat = items["lat"];
            //  var lat1 = Convert.ToDouble(lat);
            //  var lon1 = Convert.ToDouble(lon);
             {

        //Location value below is System.Device.location.Geocoordinate Eng Location
                  Location = new GeoCoordinate(lat1, lon1),
                  Title = ev.Title,
                  Description = ev.Description,
                  Category = ev.Category

             };
            pushPinCollection.Add(PushPin);
         }
         pushPins = pushPinCollection;
         mapItems.ItemsSource = PushPins;

       }

Body:
You can't insert any code between the end of the call to the Constructor, and the initializer. There are several ways to address this:

Eng pushPin = new Eng(...);  // note the semicolon

// calculations to get lat1 and lon1

pushPin.Location = new GeoCoordinate(lat1, lon1); // Location must have a public Set

or

// calculations for lat1 and lon 1

Eng PushPin = new Eng(ev.Title, ev.Description, ev.Category)
                  {
                      Location = new GeoCoordinate(lat1, lon1);
                  }

or if you have a constructor that takes the GeoCoordinate:

 Eng PushPin = new Eng(ev.Title, ev.Description, ev.Category, new GeoCoordinate(lat1, lon1));


问:
superclass has no null constructors but no arguments were given without spring integration
```<code>java.lang.IllegalArgumentException: Superclass has no null constructors but no arguments were given
    at net.sf.cglib.proxy.Enhancer.emitConstructors(Enhancer.java:721)
    at net.sf.cglib.proxy.Enhancer.generateClass(Enhancer.java:499)
    at net.sf.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
    at net.sf.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
    at net.sf.cglib.proxy.Enhancer.createHelper(Enhancer.java:377)
    at net.sf.cglib.proxy.Enhancer.create(Enhancer.java:285)
    at net.thucydides.core.steps.StepFactory.createProxyStepLibrary(StepFactory.java:155)
    at net.thucydides.core.steps.StepFactory.instantiateNewStepLibraryFor(StepFactory.java:109)
    at net.thucydides.core.steps.StepFactory.instantiateNewStepLibraryFor(StepFactory.java:101)
    at net.thucydides.core.steps.StepFactory.getStepLibraryFor(StepFactory.java:67)
    at net.thucydides.core.steps.StepAnnotations.instantiateAnyUnitiaializedSteps(StepAnnotations.java:50)
    at net.thucydides.core.steps.StepAnnotations.instanciateScenarioStepFields(StepAnnotations.java:41)
    at net.thucydides.core.steps.StepAnnotations.injectScenarioStepsInto(StepAnnotations.java:23)
    at net.thucydides.jbehave.ThucydidesStepFactory.createInstanceOfType(ThucydidesStepFactory.java:80)
    at org.jbehave.core.steps.StepCreator.stepsInstance(StepCreator.java:82)
    at org.jbehave.core.steps.StepCreator$ParameterisedStep.perform(StepCreator.java:550)
    at org.jbehave.core.embedder.StoryRunner$FineSoFar.run(StoryRunner.java:499)
    at org.jbehave.core.embedder.StoryRunner.runStepsWhileKeepingState(StoryRunner.java:479)
    at org.jbehave.core.embedder.StoryRunner.runScenarioSteps(StoryRunner.java:443)
    at org.jbehave.core.embedder.StoryRunner.runCancellable(StoryRunner.java:305)
    at org.jbehave.core.embedder.StoryRunner.run(StoryRunner.java:219)
    at org.jbehave.core.embedder.StoryRunner.run(StoryRunner.java:180)
    at org.jbehave.core.embedder.StoryManager$EnqueuedStory.call(StoryManager.java:229)
    at org.jbehave.core.embedder.StoryManager$EnqueuedStory.call(StoryManager.java:201)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
</code>```

答:
You have a class that is calling the constructor of his implemented class by using super(), with no arguments in it.

Your super class doesn't have a constructor without any arguments.

Example:

```<code>public class Cat implements Animal {
    public Cat() {
        super();
    }
}

public class Animal {
    final String name;
    public Animal(String name) {
        this.name = name;
    }
}
</code>```

The super() in the Cat class will call a constructor with no arguments of the Animal class. The Animal class doesn't have such a constructor and thus will throw an error like yours.

This can also be caused if you are letting a framework like Spring, try to autowire an object, that doesn't have a no-argument constructor.

Please share the class the is throwing the error.

ContentLicense: CC BY-SA 3.0

Body:
You have a class that is calling the constructor of his implemented class by using super(), with no arguments in it.

Your super class doesn't have a constructor without any arguments.

Example:

public class Cat implements Animal {
    public Cat() {
        super();
    }
}

public class Animal {
    final String name;
    public Animal(String name) {
        this.name = name;
    }
}

The super() in the Cat class will call a constructor with no arguments of the Animal class. The Animal class doesn't have such a constructor and thus will throw an error like yours.

This can also be caused if you are letting a framework like Spring, try to autowire an object, that doesn't have a no-argument constructor.

Please share the class the is throwing the error.


问:
CUDD: Access BDD childs
I'm working with CUDD C++ interface.

I'm finding not much information about this library.

How can I get the two children of a BDD?

For example:

```<code>Cudd mgr;
BDD x = mgr.bddVar();
BDD y = mgr.bddVar();
BDD f = x * y;
</code>```

Now, with f, I want to get its then child and else child.
The documentation says that DdNode has this children but I don't know how to access them.

Thank you.

答:
You can access the then and else children of a Cudd BDD node as follows:

```<code>DdNode *t = Cudd_T(f.getNode());
DdNode *e = Cudd_E(f.getNode());
</code>```

This gives DdNode pointer, which is the data structure used to refer to BDDs when using the plain C interface. You can get C++ objects again by:

```<code>BDD tb = BDD(mgr,t);
</code>```

Note that the above only works if f is not a complemented node. Otherwise, you have to run the result of calling "getNode" function through the Cudd_Regular function. Note that this inverts the meaning of the BDD.

You could also treat the BDDs like as if CuDD did not use inverted nodes. For this case, you would get then- and else-successors as follows:

```<code>BDD t;
BDD e;
if (Cudd_IsComplement(f.getNode())) {
    t = !BDD(manager,Cudd_Regular(Cudd_T(f.getNode())));
    e = !BDD(manager,Cudd_Regular(Cudd_E(f.getNode())));
} else {
    t = BDD(manager,Cudd_T(f.getNode()));
    e = BDD(manager,Cudd_E(f.getNode()));
}
</code>```

Title: CUDD: Access BDD childs

Body:
I'm working with CUDD C++ interface.

I'm finding not much information about this library.

How can I get the two children of a BDD?

For example:

Cudd mgr;
BDD x = mgr.bddVar();
BDD y = mgr.bddVar();
BDD f = x * y;

Now, with f, I want to get its then child and else child.
The documentation says that DdNode has this children but I don't know how to access them.

Thank you.

Body:
You can access the then and else children of a Cudd BDD node as follows:

DdNode *t = Cudd_T(f.getNode());
DdNode *e = Cudd_E(f.getNode());

This gives DdNode pointer, which is the data structure used to refer to BDDs when using the plain C interface. You can get C++ objects again by:

BDD tb = BDD(mgr,t);

Note that the above only works if f is not a complemented node. Otherwise, you have to run the result of calling "getNode" function through the Cudd_Regular function. Note that this inverts the meaning of the BDD.

You could also treat the BDDs like as if CuDD did not use inverted nodes. For this case, you would get then- and else-successors as follows:

BDD t;
BDD e;
if (Cudd_IsComplement(f.getNode())) {
    t = !BDD(manager,Cudd_Regular(Cudd_T(f.getNode())));
    e = !BDD(manager,Cudd_Regular(Cudd_E(f.getNode())));
} else {
    t = BDD(manager,Cudd_T(f.getNode()));
    e = BDD(manager,Cudd_E(f.getNode()));
}


问:
Regex using the AND NOT operator
I'm looking for a regular expression that I find in the text, the words "ata de audiência" OR "termo de audiência", and find "inconcilia" AND "reclamante" AND "reclamada", and do NOT find the word "sentença"

```<code>if(re.search(r'ata de audiência' or r'termo de audiência') and r'inconcilia' and r'reclamada' and r'reclamante' and not r'sentença', content.read())):
            key_content = True
</code>```

I tried to do it this way.. i can find the words, but when I use the  "AND NOT" operator, the regular expression does not work

ps: there are words in portuguese

答:
The code in the question is not complete enough to comment in detail but the first issue is misunderstanding that argument you've passed to re.search().

The following code is a boolean expression:

```<code>r'ata de audiência' or r'termo de audiência'
</code>```

Python interprets this as "use the first string, if not None or not empty, or else the second".

On the console:

```<code>>>> r'ata de audiência' or r'termo de audiência'
'ata de audiência'
</code>```

Likewise with and and not:

```<code>>>> r'inconcilia' and r'reclamada'
'reclamada'

>>> r'inconcilia' and r'reclamada' and r'reclamante' and not r'sentença'
False
</code>```

You need to provide a small standalone example. Often the act of preparing that example will get you a long way to answering the problem.

Title: Regex using the AND NOT operator

Body:
I'm looking for a regular expression that I find in the text, the words "ata de audiência" OR "termo de audiência", and find "inconcilia" AND "reclamante" AND "reclamada", and do NOT find the word "sentença"

if(re.search(r'ata de audiência' or r'termo de audiência') and r'inconcilia' and r'reclamada' and r'reclamante' and not r'sentença', content.read())):
            key_content = True

I tried to do it this way.. i can find the words, but when I use the  "AND NOT" operator, the regular expression does not work

ps: there are words in portuguese

Body:
The code in the question is not complete enough to comment in detail but the first issue is misunderstanding that argument you've passed to re.search().

The following code is a boolean expression:

r'ata de audiência' or r'termo de audiência'

Python interprets this as "use the first string, if not None or not empty, or else the second".

On the console:

>>> r'ata de audiência' or r'termo de audiência'
'ata de audiência'

Likewise with and and not:

>>> r'inconcilia' and r'reclamada'
'reclamada'

>>> r'inconcilia' and r'reclamada' and r'reclamante' and not r'sentença'
False

You need to provide a small standalone example. Often the act of preparing that example will get you a long way to answering the problem.


问:
Is it possible to delete running container automatically after 1 day?
I have created my own linux container and its in running state. I want to delete the running container after one day automatically.

Is there anyway to delete the container automatically?

If it's possible, Where do I have to add script/code in my Dockerfile?

答:
There's no built in feature that does this explicitly. However you can hack up a solution in several places.

Inside the container, you can have an entrypoint that runs:

```<code>#!/bin/sh
( sleep 86400 && kill 1 && sleep 10 && kill -9 1 )&
exec "$@"
</code>```

That runs a subshell in the background that will sleep for a day, send a SIGTERM, give the process 10 seconds to gracefully exit, and then send a SIGKILL. The exec at the end then runs your CMD as pid 1.

You can hijack the healthcheck to kill pid 1 after a day. You can either work with timeouts on the when the healthcheck runs, or look at the process start time with a ps command if you need a regular healthcheck for other purposes.

Outside of the container, you can run a script, possibly in cron, that checks the output of docker ps, greps for "Up .* days", and selectively runs a docker rm -f on matching lines. I'd recommend scripting this up using the --format option for docker ps and using labels on containers to limit which containers you perform this action.

Body:
There's no built in feature that does this explicitly. However you can hack up a solution in several places.

Inside the container, you can have an entrypoint that runs:

#!/bin/sh
( sleep 86400 && kill 1 && sleep 10 && kill -9 1 )&
exec "$@"

That runs a subshell in the background that will sleep for a day, send a SIGTERM, give the process 10 seconds to gracefully exit, and then send a SIGKILL. The exec at the end then runs your CMD as pid 1.

You can hijack the healthcheck to kill pid 1 after a day. You can either work with timeouts on the when the healthcheck runs, or look at the process start time with a ps command if you need a regular healthcheck for other purposes.

Outside of the container, you can run a script, possibly in cron, that checks the output of docker ps, greps for "Up .* days", and selectively runs a docker rm -f on matching lines. I'd recommend scripting this up using the --format option for docker ps and using labels on containers to limit which containers you perform this action.


问:
Should you declare methods using overloads or optional parameters in C# 4.0?
I was watching Anders' talk about C# 4.0 and sneak preview of C# 5.0, and it got me thinking about when optional parameters are available in C# what is going to be the recommended way to declare methods that do not need all parameters specified?

For example something like the FileStream class has about fifteen different constructors which can be divided into logical 'families' e.g. the ones below from a string, the ones from an IntPtr and the ones from a SafeFileHandle.

```<code>FileStream(string,FileMode);
FileStream(string,FileMode,FileAccess);
FileStream(string,FileMode,FileAccess,FileShare);
FileStream(string,FileMode,FileAccess,FileShare,int);
FileStream(string,FileMode,FileAccess,FileShare,int,bool);
</code>```

It seems to me that this type of pattern could be simplified by having three constructors instead, and using optional parameters for the ones that can be defaulted, which would make the different families of constructors more distinct [note: I know this change will not be made in the BCL, I'm talking hypothetically for this type of situation].

What do you think? From C# 4.0 will it make more sense to make closely related groups of constructors and methods a single method with optional parameters, or is there a good reason to stick with the traditional many-overload mechanism?

答:
To add a no-brainer when to use an overload instead of optionals:

Whenever you have a number of parameters that only make sense together, do not introduce optionals on them.

Or more generally, whenever your method signatures enable usage patterns which don't make sense, restrict the number of permutations of possible calls. E.g., by using overloads instead of optionals (this rule also holds true when you have several parameters of the same datatype, by the way; here, devices like factory methods or custom data types can help).

Example:

```<code>enum Match {
    Regex,
    Wildcard,
    ContainsString,
}

// Don't: This way, Enumerate() can be called in a way
//         which does not make sense:
IEnumerable<string> Enumerate(string searchPattern = null,
                              Match match = Match.Regex,
                              SearchOption searchOption = SearchOption.TopDirectoryOnly);

// Better: Provide only overloads which cannot be mis-used:
IEnumerable<string> Enumerate(SearchOption searchOption = SearchOption.TopDirectoryOnly);
IEnumerable<string> Enumerate(string searchPattern, Match match,
                              SearchOption searchOption = SearchOption.TopDirectoryOnly);
</code>```

OwnerDisplayName: Greg Beech

Body:
I was watching Anders' talk about C# 4.0 and sneak preview of C# 5.0, and it got me thinking about when optional parameters are available in C# what is going to be the recommended way to declare methods that do not need all parameters specified?

For example something like the FileStream class has about fifteen different constructors which can be divided into logical 'families' e.g. the ones below from a string, the ones from an IntPtr and the ones from a SafeFileHandle.

FileStream(string,FileMode);
FileStream(string,FileMode,FileAccess);
FileStream(string,FileMode,FileAccess,FileShare);
FileStream(string,FileMode,FileAccess,FileShare,int);
FileStream(string,FileMode,FileAccess,FileShare,int,bool);

It seems to me that this type of pattern could be simplified by having three constructors instead, and using optional parameters for the ones that can be defaulted, which would make the different families of constructors more distinct [note: I know this change will not be made in the BCL, I'm talking hypothetically for this type of situation].

What do you think? From C# 4.0 will it make more sense to make closely related groups of constructors and methods a single method with optional parameters, or is there a good reason to stick with the traditional many-overload mechanism?

Body:
To add a no-brainer when to use an overload instead of optionals:

Whenever you have a number of parameters that only make sense together, do not introduce optionals on them.

Or more generally, whenever your method signatures enable usage patterns which don't make sense, restrict the number of permutations of possible calls. E.g., by using overloads instead of optionals (this rule also holds true when you have several parameters of the same datatype, by the way; here, devices like factory methods or custom data types can help).

Example:

enum Match {
    Regex,
    Wildcard,
    ContainsString,
}

// Don't: This way, Enumerate() can be called in a way
//         which does not make sense:
IEnumerable<string> Enumerate(string searchPattern = null,
                              Match match = Match.Regex,
                              SearchOption searchOption = SearchOption.TopDirectoryOnly);

// Better: Provide only overloads which cannot be mis-used:
IEnumerable<string> Enumerate(SearchOption searchOption = SearchOption.TopDirectoryOnly);
IEnumerable<string> Enumerate(string searchPattern, Match match,
                              SearchOption searchOption = SearchOption.TopDirectoryOnly);


问:
Handling an empty UITableView. Print a friendly message
I have a UITableView that in some cases it is legal to be empty. So instead of showing the
background image of the app, I would prefer to print a friendly message in the screen, such as:

This list is now empty

What is the simplest way to do it?

答:
So for a safer solution:

```<code>extension UITableView {
func setEmptyMessage(_ message: String) {
    guard self.numberOfRows() == 0 else {
        return
    }
    let messageLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height))
    messageLabel.text = message
    messageLabel.textColor = .black
    messageLabel.numberOfLines = 0;
    messageLabel.textAlignment = .center;
    messageLabel.font = UIFont.systemFont(ofSize: 14.0, weight: UIFontWeightMedium)
    messageLabel.sizeToFit()

    self.backgroundView = messageLabel;
    self.separatorStyle = .none;
}

func restore() {
    self.backgroundView = nil
    self.separatorStyle = .singleLine
}

public func numberOfRows() -> Int {
    var section = 0
    var rowCount = 0
    while section < numberOfSections {
        rowCount += numberOfRows(inSection: section)
        section += 1
    }
    return rowCount
  }
}
</code>```

and for UICollectionView as well:

```<code>extension UICollectionView {
func setEmptyMessage(_ message: String) {
    guard self.numberOfItems() == 0 else {
        return
    }

    let messageLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height))
    messageLabel.text = message
    messageLabel.textColor = .black
    messageLabel.numberOfLines = 0;
    messageLabel.textAlignment = .center;
    messageLabel.font = UIFont.systemFont(ofSize: 18.0, weight: UIFontWeightSemibold)
    messageLabel.sizeToFit()
    self.backgroundView = messageLabel;
}

func restore() {
    self.backgroundView = nil
}

public func numberOfItems() -> Int {
    var section = 0
    var itemsCount = 0
    while section < self.numberOfSections {
        itemsCount += numberOfItems(inSection: section)
        section += 1
    }
    return itemsCount
  }
}
</code>```

More Generic Solution:

```<code>    protocol EmptyMessageViewType {
      mutating func setEmptyMessage(_ message: String)
      mutating func restore()
    }

    protocol ListViewType: EmptyMessageViewType where Self: UIView {
      var backgroundView: UIView? { get set }
    }

    extension UITableView: ListViewType {}
    extension UICollectionView: ListViewType {}

    extension ListViewType {
      mutating func setEmptyMessage(_ message: String) {
        let messageLabel = UILabel(frame: CGRect(x: 0,
                                                 y: 0,
                                                 width: self.bounds.size.width,
                                                 height: self.bounds.size.height))
        messageLabel.text = message
        messageLabel.textColor = .black
        messageLabel.numberOfLines = 0
        messageLabel.textAlignment = .center
        messageLabel.font = UIFont(name: "TrebuchetMS", size: 16)
        messageLabel.sizeToFit()

        backgroundView = messageLabel
    }

     mutating func restore() {
        backgroundView = nil
     }
}
</code>```

Body:
So for a safer solution:

extension UITableView {
func setEmptyMessage(_ message: String) {
    guard self.numberOfRows() == 0 else {
        return
    }
    let messageLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height))
    messageLabel.text = message
    messageLabel.textColor = .black
    messageLabel.numberOfLines = 0;
    messageLabel.textAlignment = .center;
    messageLabel.font = UIFont.systemFont(ofSize: 14.0, weight: UIFontWeightMedium)
    messageLabel.sizeToFit()

    self.backgroundView = messageLabel;
    self.separatorStyle = .none;
}

func restore() {
    self.backgroundView = nil
    self.separatorStyle = .singleLine
}

public func numberOfRows() -> Int {
    var section = 0
    var rowCount = 0
    while section < numberOfSections {
        rowCount += numberOfRows(inSection: section)
        section += 1
    }
    return rowCount
  }
}

and for UICollectionView as well:

extension UICollectionView {
func setEmptyMessage(_ message: String) {
    guard self.numberOfItems() == 0 else {
        return
    }

    let messageLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height))
    messageLabel.text = message
    messageLabel.textColor = .black
    messageLabel.numberOfLines = 0;
    messageLabel.textAlignment = .center;
    messageLabel.font = UIFont.systemFont(ofSize: 18.0, weight: UIFontWeightSemibold)
    messageLabel.sizeToFit()
    self.backgroundView = messageLabel;
}

func restore() {
    self.backgroundView = nil
}

public func numberOfItems() -> Int {
    var section = 0
    var itemsCount = 0
    while section < self.numberOfSections {
        itemsCount += numberOfItems(inSection: section)
        section += 1
    }
    return itemsCount
  }
}

More Generic Solution:

    protocol EmptyMessageViewType {
      mutating func setEmptyMessage(_ message: String)
      mutating func restore()
    }

    protocol ListViewType: EmptyMessageViewType where Self: UIView {
      var backgroundView: UIView? { get set }
    }

    extension UITableView: ListViewType {}
    extension UICollectionView: ListViewType {}

    extension ListViewType {
      mutating func setEmptyMessage(_ message: String) {
        let messageLabel = UILabel(frame: CGRect(x: 0,
                                                 y: 0,
                                                 width: self.bounds.size.width,
                                                 height: self.bounds.size.height))
        messageLabel.text = message
        messageLabel.textColor = .black
        messageLabel.numberOfLines = 0
        messageLabel.textAlignment = .center
        messageLabel.font = UIFont(name: "TrebuchetMS", size: 16)
        messageLabel.sizeToFit()

        backgroundView = messageLabel
    }

     mutating func restore() {
        backgroundView = nil
     }
}

ContentLicense: CC BY-SA 4.0


问:
SignalR sticky sessions with F5 and Citrix
we have a web application (angular) that needs to interact with a winform application. we do that via SignalR.
the browser and winform are deployed on a citrix server.
There is a webfarm of IIS servers and on those we have the webapi services and also the signalR Hubs.

all network activity goes via F5 loadbalancer.

the problem we are facing - is how to make sure the web applicaion running on chrome, and the windows forms application connect both to the same SignalR Hub Server.

we cannot use stickey sessions based on Origin IP as all users are using the citrix infrastructure, so all have the same origin IP.
using a cookie - i am not sure that the cookie is shared between the browser and the winform app. and anyways cookie in a websocket scenario isnt working (right ?)

is the only solution using a backplane ? (not using dotnet core at the moment)

答:
Override or Change source Signalr

Private Task ProcessNegotiationRequest-->

```<code>   string connectionId = !string.IsNullOrEmpty(context.Request.QueryString["ConnId"]) ? context.Request.QueryString["ConnId"]: connectionId = Guid.NewGuid().ToString("d");
</code>```

And send conId in querystring

Body:
Override or Change source Signalr

Private Task ProcessNegotiationRequest-->

   string connectionId = !string.IsNullOrEmpty(context.Request.QueryString["ConnId"]) ? context.Request.QueryString["ConnId"]: connectionId = Guid.NewGuid().ToString("d");

And send conId in querystring


问:
When you program in as3, do you usually use classes?
I want other programmers' opinions on this.  When you program in as3, do you usually use classes?  Why?</p>

答:
i do.
 because it's a great way to create reusable and well organized code


问:
Given a word get the meaning using WordNet API
I am currently using the wordnet search to get the meaning of words. However, I have a really long list of words and thus, would like to see the possibility of automating it.

For example given the individual word goat I want to get the meaning of it provide by wordnet.

I see questions about getting root word, hyponyms etc, but I could not find a proper solution on how to retrieve the meaning given a word.

Please let me know the possible options of doing it!

答:
Here is how to get definition

```<code>from nltk.corpus import wordnet
syns = wordnet.synsets("goat")
print(syns[0].definition())
</code>```

Output

```<code>any of numerous agile ruminants related to sheep but having a beard and straight horns
</code>```

Body:
Here is how to get definition

from nltk.corpus import wordnet
syns = wordnet.synsets("goat")
print(syns[0].definition())

Output

any of numerous agile ruminants related to sheep but having a beard and straight horns


问:
Angular 4: http interceptor emit events to other components?
I have a usual http intercetor, that makes a call to a certain API and if it receives a 403 response, must emit an event.

Interceptor:

```<code>@Injectable
export class CustomHttpInterceptor implements HttpInterceptor {
  @Output() notify: EventEmitter<boolean> = new EventEmitter<boolean>();

  constructor() {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (req.body.status === 403) {
      this.notify.emit(true);
    }
    return next.handle(req);
  }

}
</code>```

And then I have a navi.component.html that would listen for this event:

```<code><md-toolbar (notify)="onNotify($event)">
  <a routerLink="/home">
      <img src="assets/images/logo.png" class="md-card-image p-navi-logo" alt="image caption"></a>
  <span class="spacer"></span>

  <div fxLayout="row" fxShow="false" fxShow.gt-sm>
    <development *ngIf="isLoggedIn"></development>
    <guide-menu></guide-menu>
    <documentation-menu></documentation-menu>
    <administration *ngIf="isAdmin"></administration>
    <about></about>
  </div>
...
</code>```

top-navi.component.ts

```<code>public onNotify(result: boolean):void {
    console.log('notification received: ' + result);
    this.isLoggedIn = result;
  }
</code>```

The problem is that the top-navi-component never gets the event and doesn't log anything. What am I doing wrong?

答:
Try like this to emit value follow below steps

create new service file or if you have existing service file use that

sample.service.ts

```<code>@Injectable()
export class SampleService {
    notify: Subject<boolean> = new Subject<boolean>();
    onNotify(event) {
            this.notify.next(true);
    }
}
</code>```

Interceptor:

```<code>@Injectable()
export class CustomHttpInterceptor implements HttpInterceptor {

    constructor(private sampleService: SampleService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (req.body.status === 403) {
            this.sampleService.onNotify(true)
        }
        return next.handle(req);
    }

}
</code>```

and navi.component.html

```<code><md-toolbar>
    <a routerLink="/home">
        <img src="assets/images/logo.png" class="md-card-image p-navi-logo" alt="image caption">
    </a>
    <span class="spacer"></span>
    <div fxLayout="row" fxShow="false" fxShow.gt-sm>
        <development *ngIf="isLoggedIn"></development>
        <guide-menu></guide-menu>
        <documentation-menu></documentation-menu>
        <administration *ngIf="isAdmin"></administration>
        <about></about>
    </div>
</md-toolbar>
</code>```

finally top-navi.component.ts

```<code>export class TopNaviComponent {

    constructor(private sampleService: SampleService) {

        this.sampleService.notify.subscribe((result) => {
            console.log('result', result)
        })

    }
}
</code>```

Body:
I have a usual http intercetor, that makes a call to a certain API and if it receives a 403 response, must emit an event.

Interceptor:

@Injectable
export class CustomHttpInterceptor implements HttpInterceptor {
  @Output() notify: EventEmitter<boolean> = new EventEmitter<boolean>();

  constructor() {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (req.body.status === 403) {
      this.notify.emit(true);
    }
    return next.handle(req);
  }

}

And then I have a navi.component.html that would listen for this event:

<md-toolbar (notify)="onNotify($event)">

    <development *ngIf="isLoggedIn"></development>
    <guide-menu></guide-menu>
    <documentation-menu></documentation-menu>
    <administration *ngIf="isAdmin"></administration>
    <about></about>

...

top-navi.component.ts

public onNotify(result: boolean):void {
    console.log('notification received: ' + result);
    this.isLoggedIn = result;
  }

The problem is that the top-navi-component never gets the event and doesn't log anything. What am I doing wrong?

Body:
Try like this to emit value follow below steps

create new service file or if you have existing service file use that

sample.service.ts

@Injectable()
export class SampleService {
    notify: Subject<boolean> = new Subject<boolean>();
    onNotify(event) {
            this.notify.next(true);
    }
}

Interceptor:

@Injectable()
export class CustomHttpInterceptor implements HttpInterceptor {

    constructor(private sampleService: SampleService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (req.body.status === 403) {
            this.sampleService.onNotify(true)
        }
        return next.handle(req);
    }

}

and navi.component.html

<md-toolbar>
    <a routerLink="/home">
        <img src="assets/images/logo.png" class="md-card-image p-navi-logo" alt="image caption">
    </a>
    <span class="spacer"></span>
    <div fxLayout="row" fxShow="false" fxShow.gt-sm>
        <development *ngIf="isLoggedIn"></development>
        <guide-menu></guide-menu>
        <documentation-menu></documentation-menu>
        <administration *ngIf="isAdmin"></administration>
        <about></about>
    </div>
</md-toolbar>

finally top-navi.component.ts

export class TopNaviComponent {

    constructor(private sampleService: SampleService) {

        this.sampleService.notify.subscribe((result) => {
            console.log('result', result)
        })

    }
}


问:
Reduce a list down to a field with runtime parameter
Is it possible to configure Automapper so it can map from a collection to a single instance based on a run-time parameter?

In our application our entities have labels for each language.
Depending on the preference of the current user, a single value should be shown.

```<code>DepartmentEntity
  Labels: Label[]
    Value: string
    Culture: CultureInfo

DepartmentViewModel
  Label: string
</code>```

Given I know the current user culture when I map my entities, could I configure Automapper so it can map from DepartmentEntity to DepartmentViewModel?

Something like

```<code>var department = Mapper.Map<DepartmentEntity, DepartmentViewModel>(user.Culture);
</code>```

Other answers like this one seem to want to pass a parameter to use as target value straight up.
I want to use it as a way to reduce a list to a single field.

答:
You can do it the same as the answer you mentioned:

```<code>var department = Mapper.Map<DepartmentEntity, DepartmentViewModel>(departmentEntity,
  opt => opt.AfterMap((src, dest) => dest.Label = src.Labels.FirstOrDefault(x=>
                                       x.CultureInfo.Name == user.Culture.Name)?.Value));
</code>```

Keep in mind that you have to make the ignore call when defining the map.

UPDATE

You are correct and after some more research it's actually possible and fairly easy to achieve this with Automapper. The feature I got it from this SO answer.

```<code>cfg.CreateMap<DepartmentEntity, DepartmentViewModel>().ForMember(x => x.Label, opt =>
opt.ResolveUsing((src, dest, member, context) =>
                  src.Labels.FirstOrDefault(x=> x.Culture.Name ==
                           context.Items["userCulture"].ToString())?.Value));
</code>```

And when converting objects use

```<code>var userCulture = new CultureInfo("en-US");
var department = Mapper.Map<DepartmentViewModel>(depEntity,
            opt => opt.Items["userCulture"] = userCulture.Name);
</code>```

Body:
Is it possible to configure Automapper so it can map from a collection to a single instance based on a run-time parameter?

In our application our entities have labels for each language.
Depending on the preference of the current user, a single value should be shown.

DepartmentEntity
  Labels: Label[]
    Value: string
    Culture: CultureInfo

DepartmentViewModel
  Label: string

Given I know the current user culture when I map my entities, could I configure Automapper so it can map from DepartmentEntity to DepartmentViewModel?

Something like

var department = Mapper.Map<DepartmentEntity, DepartmentViewModel>(user.Culture);

Other answers like this one seem to want to pass a parameter to use as target value straight up.
I want to use it as a way to reduce a list to a single field.

Body:
You can do it the same as the answer you mentioned:

var department = Mapper.Map<DepartmentEntity, DepartmentViewModel>(departmentEntity,
  opt => opt.AfterMap((src, dest) => dest.Label = src.Labels.FirstOrDefault(x=>
                                       x.CultureInfo.Name == user.Culture.Name)?.Value));

Keep in mind that you have to make the ignore call when defining the map.

UPDATE

You are correct and after some more research it's actually possible and fairly easy to achieve this with Automapper. The feature I got it from this SO answer.

cfg.CreateMap<DepartmentEntity, DepartmentViewModel>().ForMember(x => x.Label, opt =>
opt.ResolveUsing((src, dest, member, context) =>
                  src.Labels.FirstOrDefault(x=> x.Culture.Name ==
                           context.Items["userCulture"].ToString())?.Value));

And when converting objects use

var userCulture = new CultureInfo("en-US");
var department = Mapper.Map<DepartmentViewModel>(depEntity,
            opt => opt.Items["userCulture"] = userCulture.Name);


问:
Creating and Verifying JWT signature using public/private key in Spring boot security
I would like to know the process of creation and verification of JWT signature using public and private keys in spring boot security.

I am trying to validate JWT token using HMAC algorithm. I am building JWT with hardcoded secret "MYSECRET".

```<code>Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setAudience(audience)
                .setIssuedAt(createdDate)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, "MYSECRET")
                .compact()
</code>```

For parsing the code is as follows

```<code>Jwts.parser()
                .setSigningKey("MYSECRET")
                .parseClaimsJws(token)
                .getBody();
</code>```

Instead of using signing key as "MYSECRET", I would like to make use of public and private keys

答:
Generate JKS Java KeyStore File

Let’s first generate the keys – and more specifically a .jks file – using the command line tool keytool:

keytool -genkeypair -alias mytest
                      -keyalg RSA
                      -keypass mypass
                      -keystore mytest.jks
                      -storepass mypass

Export your public key

keytool -list -rfc --keystore mytest.jks | openssl x509 -inform pem
  -pubkey

Using your key to sign token in your Authorization Server.

```<code>@Bean
public JwtAccessTokenConverter accessTokenConverter(){

    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    KeyStoreKeyFactory keyStoreKeyFactory =
      new KeyStoreKeyFactory(new ClassPathResource("mytest.jks"), "mypass".toCharArray());
    converter.setKeyPair(keyStoreKeyFactory.getKeyPair("mytest"));
    return converter;
}
</code>```

Finally using your public key in your resource server.

```<code>@Bean
public JwtAccessTokenConverter accessTokenConverter() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    Resource resource = new ClassPathResource("public.txt");
    String publicKey = null;
    try {
        publicKey = IOUtils.toString(resource.getInputStream());
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
    converter.setVerifierKey(publicKey);
    return converter;
}
</code>```

Body:
I would like to know the process of creation and verification of JWT signature using public and private keys in spring boot security.

I am trying to validate JWT token using HMAC algorithm. I am building JWT with hardcoded secret "MYSECRET".

Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setAudience(audience)
                .setIssuedAt(createdDate)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, "MYSECRET")
                .compact()

For parsing the code is as follows

Jwts.parser()
                .setSigningKey("MYSECRET")
                .parseClaimsJws(token)
                .getBody();

Instead of using signing key as "MYSECRET", I would like to make use of public and private keys

Body:
Generate JKS Java KeyStore File

Let’s first generate the keys – and more specifically a .jks file – using the command line tool keytool:

keytool -genkeypair -alias mytest
                      -keyalg RSA
                      -keypass mypass
                      -keystore mytest.jks
                      -storepass mypass

Export your public key

keytool -list -rfc --keystore mytest.jks | openssl x509 -inform pem
  -pubkey

Using your key to sign token in your Authorization Server.

@Bean
public JwtAccessTokenConverter accessTokenConverter(){

    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    KeyStoreKeyFactory keyStoreKeyFactory =
      new KeyStoreKeyFactory(new ClassPathResource("mytest.jks"), "mypass".toCharArray());
    converter.setKeyPair(keyStoreKeyFactory.getKeyPair("mytest"));
    return converter;
}

Finally using your public key in your resource server.

@Bean
public JwtAccessTokenConverter accessTokenConverter() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    Resource resource = new ClassPathResource("public.txt");
    String publicKey = null;
    try {
        publicKey = IOUtils.toString(resource.getInputStream());
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
    converter.setVerifierKey(publicKey);
    return converter;
}


问:
Probable template specialization within a class
I encountered code like the following:

```<code>class XX
{
public:
    template<typename TT> struct YY;

    template<typename TT, typename UU> struct YY<std::pair<TT, UU>>
    {
        std::size_t operator()(std::pair<TT, UU> const& val) const
        {
            // content omitted for brevity
        }
    };
};
</code>```

Basically, I am confused and need help in understanding this code.

Specifically, is the first YY declaration a forward declaration? Is the second YY declaration a partial template specialization? Why does the second YY declaration have two template arguments (TT and UU), while the first YY declaration only have one template argument (TT)? Why does the first YY declaration have no definition?

(The code compiles with no problem.)

答:
Specifically, is the first YY declaration a forward declaration?

Yes. This renders any instantiation YY<T> an incomplete type except...

Is the second YY declaration a partial template specialization?

... if there is a template specialization for a certain type or class of types (like pointers) that provides a full definition. In this particular case, this is indeed a partial specialization, applying for all YY<T> with T being a pair type with TT and UU.

Why does the second YY declaration have two template arguments (TT and UU), while the first YY declaration only have one template argument (TT)?

The author of the code didn't want to impose any conditions on the pair's types, they shall be arbitrary. By writing such a specialization, you basically promote all YY instantiations taking a std::pair to be a template with two arguments.

Why does the first YY declaration have no definition?

Because it may not be needed. All you need to create specializations is a declaration. If you actually defined YY there, you would have gotten a "default" instantiation that always gets instantiated when no specialization is apt. If you want the compilation to fail if you chose a type where there is no specialization, you can do it like that. Alternatively (and probably better), you actually would define the template, containing a static_assert(!std::is_same_v<T, T>) or something like that together with a more meaningful message than something like "cannot create object of incomplete type".

Body:
I encountered code like the following:

class XX
{
public:
    template<typename TT> struct YY;

    template<typename TT, typename UU> struct YY<std::pair<TT, UU>>
    {
        std::size_t operator()(std::pair<TT, UU> const& val) const
        {
            // content omitted for brevity
        }
    };
};

Basically, I am confused and need help in understanding this code.

Specifically, is the first YY declaration a forward declaration? Is the second YY declaration a partial template specialization? Why does the second YY declaration have two template arguments (TT and UU), while the first YY declaration only have one template argument (TT)? Why does the first YY declaration have no definition?

(The code compiles with no problem.)


问:
Showing on console: Slow network is detected. Fallback font will be used while loading
what can I do in this case?
I'm seeing this on my console when ran on the browser the AngularJS App:

Slow network is detected. Fallback font will be used while loading: /bootstrap/dist/fonts/glyphicons-halflings-regular.woff2

I also see the fonts changing while loading.

答:
Setting the following chrome flag to  Unknown will prevent that message appearing on dev-console :

```<code>chrome://flags/#force-effective-connection-type
</code>```

ᴛᴇꜱᴛᴇᴅ ᴏɴ

Google Chrome

Version 63.0.3239.84

Body:
Setting the following chrome flag to  Unknown will prevent that message appearing on dev-console :

chrome://flags/#force-effective-connection-type

ᴛᴇꜱᴛᴇᴅ ᴏɴ

Google Chrome

Version 63.0.3239.84


问:
After parsing a Nodejs response. The JSON response results array is outputing as just object. How do I get to to display the objects
Here I call the module. Then ask for the response. then I use JSON.parse the body of the response but the output looks like this.

```<code>{ response:
   { status: 'ok',
     userTier: 'developer',
     total: 240,
     startIndex: 1,
     pageSize: 1,
     currentPage: 1,
     pages: 240,
     orderBy: 'newest',
     results: [ [Object] ] } }
</code>```

I want to be able to see the Objects

```<code>    {
    "response": {
        "status": "ok",
        "userTier": "developer",
        "total": 240,
        "startIndex": 1,
        "pageSize": 1,
        "currentPage": 1,
        "pages": 240,
        "orderBy": "newest",
        "results": [{
            "id": "sustainable-business/2017/jun/13/battery-storage-and-rooftop-solar-could-mean-new-life-post-grid-for-consumers",
            "type": "article",
            "sectionId": "sustainable-business",
            "sectionName": "Guardian Sustainable Business",
            "webPublicationDate": "2017-06-12T23:51:00Z",
            "webTitle": "Battery storage and rooftop solar could mean new life post-grid for consumers",
            "webUrl": "https://www.theguardian.com/sustainable-business/2017/jun/13/battery-storage-and-rooftop-solar-could-mean-new-life-post-grid-for-consumers",
            "apiUrl": "https://content.guardianapis.com/sustainable-business/2017/jun/13/battery-storage-and-rooftop-solar-could-mean-new-life-post-grid-for-consumers",
            "isHosted": false
        }]
    }
}
</code>```

this is the code

function prettyJSON(data) {
 return JSON.stringify(data,null,"   ");
}

api.custom.search({fromDate:"2017-06-12",
     toDate:"2017-06-12",
     orderBy:"newest",
     //showFields:"all",
     pageSize: 2})
 .then(function(response){
  var reqBody = response.body.toString();
  reqBody = JSON.parse(reqBody);
  console.log(reqBody);

 })

  .catch(function(err){
  console.log(err);
 }); ```

答:
I believe a console log will not output nested objects so your response is probably fine you just cannot see it in your console.

If you want to inspect it you can either use a debugger and inspect your variable there or use util.inspect()

See this answer

Edit: The console in Chrome will show the nested objects but node's console does not extend objects by default - thanks to Jeremy Thille for his comment

Body:
Here I call the module. Then ask for the response. then I use JSON.parse the body of the response but the output looks like this.

{ response:
   { status: 'ok',
     userTier: 'developer',
     total: 240,
     startIndex: 1,
     pageSize: 1,
     currentPage: 1,
     pages: 240,
     orderBy: 'newest',
     results: [ [Object] ] } }

I want to be able to see the Objects

    {
    "response": {
        "status": "ok",
        "userTier": "developer",
        "total": 240,
        "startIndex": 1,
        "pageSize": 1,
        "currentPage": 1,
        "pages": 240,
        "orderBy": "newest",
        "results": [{
            "id": "sustainable-business/2017/jun/13/battery-storage-and-rooftop-solar-could-mean-new-life-post-grid-for-consumers",
            "type": "article",
            "sectionId": "sustainable-business",
            "sectionName": "Guardian Sustainable Business",
            "webPublicationDate": "2017-06-12T23:51:00Z",
            "webTitle": "Battery storage and rooftop solar could mean new life post-grid for consumers",
            "webUrl": "https://www.theguardian.com/sustainable-business/2017/jun/13/battery-storage-and-rooftop-solar-could-mean-new-life-post-grid-for-consumers",
            "apiUrl": "https://content.guardianapis.com/sustainable-business/2017/jun/13/battery-storage-and-rooftop-solar-could-mean-new-life-post-grid-for-consumers",
            "isHosted": false
        }]
    }
}

this is the code

function prettyJSON(data) {
 return JSON.stringify(data,null,"   ");
}

api.custom.search({fromDate:"2017-06-12",
     toDate:"2017-06-12",
     orderBy:"newest",
     //showFields:"all",
     pageSize: 2})
 .then(function(response){
  var reqBody = response.body.toString();
  reqBody = JSON.parse(reqBody);
  console.log(reqBody);

 })

  .catch(function(err){
  console.log(err);
 });


问:
How to select the parent's parent in CSS?
```<code><div id="maincontent">
    <div id="content">
        <div id="admin"></div>
    </div>
</div>
</code>```

Is it possible to have a rule that would match #maincontent only if #admin exists using just CSS?

It's just I have a background colour in the control panel but don't want it there for visitors.

答:
No not with CSS. Alternatively you may use a CSS class hen viewing for admin. So for an admin

```<code><div id="maincontent" class="adminBackground">
    <div id="content">
        <div id="admin"></div>
    </div>
</div>
</code>```

And for normal visitors (notice that the class="adminBackground" attribute is removed):

```<code><div id="maincontent">
    <div id="content">
        <div id="admin"></div>
    </div>
</div>
</code>```

Then define a role for that class "adminBackground":

```<code>.adminBackground {
     background: #AAAAAA;
}
</code>```

Body:
No not with CSS. Alternatively you may use a CSS class hen viewing for admin. So for an admin

<div id="maincontent" class="adminBackground">
    <div id="content">
        <div id="admin"></div>
    </div>
</div>

And for normal visitors (notice that the class="adminBackground" attribute is removed):

<div id="maincontent">
    <div id="content">
        <div id="admin"></div>
    </div>
</div>

Then define a role for that class "adminBackground":

.adminBackground {
     background: #AAAAAA;
}


问:
Create one list of numbers by combining numbers from three lists of uneven length
I'm trying to create a list of id's, where the numbers are made up of three different lists: the first part of the number should be from the list pers:

```<code>pers = list(range(1,12))
</code>```

The second part should be a combination of the person id, and the number 1 or 2 (not necessarily a list, as it is just two numbers), like this:

```<code>ids = [11, 12, 21, 22, 31, 32, 41, 42, 51, 52, 61, 62, 71, 72, 81, 82, 91,
       92, 101, 102, 111, 112]
</code>```

The third part should be a combination of the above and the values in the list reps:

```<code>reps = list(range(1,13))
</code>```

like this:

```<code>ids = [111, 112, 113, 114, 115, 116, 117, 118, 119, 1110, 1111, 1112,
       121, 122, 123, 124, 125, 126, 127, 128, 129, 1210, 1211, 1212 ...]
</code>```

and so on, all the way up to 11212 (person 11, condition 2,  repetition 12). In total around 2250 items in the list.

I've tried various itertools functions, or nested for loops, lists of lists and tips in this post, but none seem to yield what I need.

Body:
I'm trying to create a list of id's, where the numbers are made up of three different lists: the first part of the number should be from the list pers:

pers = list(range(1,12))

The second part should be a combination of the person id, and the number 1 or 2 (not necessarily a list, as it is just two numbers), like this:

ids = [11, 12, 21, 22, 31, 32, 41, 42, 51, 52, 61, 62, 71, 72, 81, 82, 91,
       92, 101, 102, 111, 112]

The third part should be a combination of the above and the values in the list reps:

reps = list(range(1,13))

like this:

ids = [111, 112, 113, 114, 115, 116, 117, 118, 119, 1110, 1111, 1112,
       121, 122, 123, 124, 125, 126, 127, 128, 129, 1210, 1211, 1212 ...]

and so on, all the way up to 11212 (person 11, condition 2,  repetition 12). In total around 2250 items in the list.

I've tried various itertools functions, or nested for loops, lists of lists and tips in this post, but none seem to yield what I need.

Body:
You can do a triple loop list comprehension:

pers = range(1, 12)
cond = [1, 2]
reps = range(1, 13)

ids = ["{}{}{}".format(a, b, c) for a in pers for b in cond for c in reps]
# ['111', '112', '113', '114', '115', '116', '117', '118', '119', '1110', '1111', '1112',
#  '121', '122', '123', '124', '125', '126', '127', '128', '129', '1210', '1211', '1212',
#  '211', '212', '213', '214', '215', '216', '217', '218', '219', '2110', ...]

Or, if you need them as integers:

ids = [int("{}{}{}".format(a, b, c)) for a in pers for b in cond for c in reps]


问:
Change datatype from string to integer in MongoDB PHP
I have a set of documents where some of product_id are stored in string

```<code>[
  {
    "_id": ObjectId("foobar1"),
    "product_id": "1"
  },
  {
    "_id": ObjectId("foobar2"),
    "product_id": 2
  }
]
</code>```

Is there any way to convert product_id to integer for all the documents using MongoDB PHP ?

答:
this may help you...

```<code>db.collection.find().forEach(function(product) {
    product.product_id= new NumberInt(product.product_id);
    db.collection.save(product);
});
</code>```

OR using UPDATE

```<code>db.collection.find().forEach(function(data) {
    db.collection.update({_id:data._id},{$set:{product_id:parseInt(data.product_id)}});
})
</code>```

Body:
I have a set of documents where some of product_id are stored in string

[
  {
    "_id": ObjectId("foobar1"),
    "product_id": "1"
  },
  {
    "_id": ObjectId("foobar2"),
    "product_id": 2
  }
]

Is there any way to convert product_id to integer for all the documents using MongoDB PHP ?

Body:
this may help you...

db.collection.find().forEach(function(product) {
    product.product_id= new NumberInt(product.product_id);
    db.collection.save(product);
});

OR using UPDATE

db.collection.find().forEach(function(data) {
    db.collection.update({_id:data._id},{$set:{product_id:parseInt(data.product_id)}});
})


问:
How to open just a single jquery dialog within a PHP while loop
I have a HTML table, where rows are shown within a while loop.
In each row I have a , and within each of those I place a .

```<code><table>
 <tr>
  <th class="text-left highlight">presso</th>
 </tr>
<?php
while...
?>
<div class="myClass" title="info" style="display: none;">
bla bla bla
</div>
 <tr>
  <td class="text-left">
   <img src="img/i.png" class="myImg" /><?php echo $while_loop_result;?>
  </td>
 </tr>
<?php
}
?>
</table>
</code>```

Please notice the class myClass for the div and myImg for the img.

Now, I want to click on the  in each table row, and open a jquery dialog which corresponds to that specific row.

```<code><script type="text/javascript">
$(function() {
$('.myClass').dialog(
{
      autoOpen: false,
      maxWidth:300,
      maxHeight: 300,
      width: 300,
      height: 300,
      modal: true,
      show: {
      effect: "blind",
      duration: 1200
      },
      hide: {
      effect: "drop",
      duration: 1200
      }
    }
);
$('.myClass').dialog('close');
$(".myImg").click(
 function (e) {
   $('.myClass').dialog('open');
 });
})
</script>
</code>```

The script above opens all the dialog windows. If the table has five rows, by clicking on any of the five images, all the five dialog popups open.

How can I open just the one I clicked on?

答:
Well its obvious if you refer to a class you all the classes will be opened. You need to assign separate ids to every element. The workaround for this should be similar to this.

```<code>     $sql = "Your query string";
    $results = mysqli_query($conn, $sql);

    if (mysqli_num_rows($results) > 0) {
        // output data of each row
$i=1;
        while($row = mysqli_fetch_assoc($results)) {
echo '<div class="myClass" id="expand-'.$i.'" title="info" style="display: none;">
bla bla bla
</div>
 <tr>
  <td class="text-left">
   <img src="img/i.png" class="myImg" id="'.$i.'"/>'.$row["somedatabasefield"].'
  </td>
 </tr>';
$i=$i+1;
}

}
</code>```

Now when you have generated all the tds and divs we will see the jquery code accordingly. It should something like this. I haven't checked this on my own but this will give an idea what to do exactly.

```<code><script type="text/javascript">
$(function() {
$('.myClass').dialog(
{
      autoOpen: false,
      maxWidth:300,
      maxHeight: 300,
      width: 300,
      height: 300,
      modal: true,
      show: {
      effect: "blind",
      duration: 1200
      },
      hide: {
      effect: "drop",
      duration: 1200
      }
    }
);
$('.myClass').dialog('close');
$(".myImg").click(
 function (e) {
   $('#expand-'+this.id).dialog('open');
 });
})
</script>
</code>```

As you can see only one change in jquery is needed in this workaround.

Body:
I have a HTML table, where rows are shown within a while loop.
In each row I have a , and within each of those I place a .

  presso

<?php
while...
?>

bla bla bla

   <?php echo $while_loop_result;?>

<?php
}
?>

Please notice the class myClass for the div and myImg for the img.

Now, I want to click on the  in each table row, and open a jquery dialog which corresponds to that specific row.

The script above opens all the dialog windows. If the table has five rows, by clicking on any of the five images, all the five dialog popups open.

How can I open just the one I clicked on?

Body:
Well its obvious if you refer to a class you all the classes will be opened. You need to assign separate ids to every element. The workaround for this should be similar to this.

     $sql = "Your query string";
    $results = mysqli_query($conn, $sql);

    if (mysqli_num_rows($results) > 0) {
        // output data of each row
$i=1;
        while($row = mysqli_fetch_assoc($results)) {
echo '<div class="myClass" id="expand-'.$i.'" title="info" style="display: none;">
bla bla bla
</div>
 <tr>
  <td class="text-left">
   <img src="img/i.png" class="myImg" id="'.$i.'"/>'.$row["somedatabasefield"].'
  </td>
 </tr>';
$i=$i+1;
}

}

Now when you have generated all the tds and divs we will see the jquery code accordingly. It should something like this. I haven't checked this on my own but this will give an idea what to do exactly.

<script type="text/javascript">
$(function() {
$('.myClass').dialog(
{
      autoOpen: false,
      maxWidth:300,
      maxHeight: 300,
      width: 300,
      height: 300,
      modal: true,
      show: {
      effect: "blind",
      duration: 1200
      },
      hide: {
      effect: "drop",
      duration: 1200
      }
    }
);
$('.myClass').dialog('close');
$(".myImg").click(
 function (e) {
   $('#expand-'+this.id).dialog('open');
 });
})
</script>

As you can see only one change in jquery is needed in this workaround.


问:
Terraform - Enumerating Instances
Terraform question here: I am trying to deploy a set of instances on Azure and I am enumerating them when deployed.

```<code>resource "azurerm_virtual_machine" "kafka" {   name
= "kafka${count.index}"   #name                             = "${var.kafka_cluster_prefix}-kafka-${count.index}"   location
= "${azurerm_resource_group.rg.location}"   resource_group_name              = "${azurerm_resource_group.rg.name}"   #availability_set_id              = "${azurerm_availability_set.kafka.id}"   network_interface_ids            = ["${element(azurerm_network_interface.broker_nic.*.id, count.index)}"]   vm_size                          = "${var.broker_vm_size}"   delete_os_disk_on_termination    = true   delete_data_disks_on_termination = true   count
= "${var.broker_instance_count}"

  tags {
    displayName = "${var.kafka_cluster_prefix}-kafka VM Creation"
    ssh_user    = "${var.admin_username}"
    ssh_ip      = "${element(azurerm_network_interface.broker_nic.*.private_ip_address, count.index)}"
    role        = "${var.kafka_role_tag}"   }
</code>```

However, my instances are starting count from '0' (i.e., broker0, broker1, broker2).

Question: Is it possible to start counting from '1' and not '0' ?

Thanks again,

答:
No - that's how arrays work in any sensible programming language, they always start at 0.

But you have math operations available to you, so why don't you just do a "${count.index + 1}" - that will let Terraform iterate over as it expects, and you get to name your resources how you wish.

Title: Terraform - Enumerating Instances

Body:
Terraform question here: I am trying to deploy a set of instances on Azure and I am enumerating them when deployed.

resource "azurerm_virtual_machine" "kafka" {   name
= "kafka${count.index}"   #name                             = "${var.kafka_cluster_prefix}-kafka-${count.index}"   location
= "${azurerm_resource_group.rg.location}"   resource_group_name              = "${azurerm_resource_group.rg.name}"   #availability_set_id              = "${azurerm_availability_set.kafka.id}"   network_interface_ids            = ["${element(azurerm_network_interface.broker_nic.*.id, count.index)}"]   vm_size                          = "${var.broker_vm_size}"   delete_os_disk_on_termination    = true   delete_data_disks_on_termination = true   count
= "${var.broker_instance_count}"

  tags {
    displayName = "${var.kafka_cluster_prefix}-kafka VM Creation"
    ssh_user    = "${var.admin_username}"
    ssh_ip      = "${element(azurerm_network_interface.broker_nic.*.private_ip_address, count.index)}"
    role        = "${var.kafka_role_tag}"   }

However, my instances are starting count from '0' (i.e., broker0, broker1, broker2).

Question: Is it possible to start counting from '1' and not '0' ?

Thanks again,


答:
Better and simpler approach would be doing it in the MongoShell itself, the below javascript function will does the job of converting all product_id from String to integer.

This will work if all the product_id string can be converted to an integer, say the possible values of product_id can be "1", "34343", "23", ....

```<code>db.collection.find({product_id: {$exists : true}}).forEach(
    function(obj) {
        obj.product_id = new NumberInt( obj.product_id );
        db.collection.save(obj);
    }
);
</code>```

Title: Change datatype from string to integer in MongoDB PHP

Body:
Better and simpler approach would be doing it in the MongoShell itself, the below javascript function will does the job of converting all product_id from String to integer.

This will work if all the product_id string can be converted to an integer, say the possible values of product_id can be "1", "34343", "23", ....

db.collection.find({product_id: {$exists : true}}).forEach(
    function(obj) {
        obj.product_id = new NumberInt( obj.product_id );
        db.collection.save(obj);
    }
);


问:
How to position views near the screen edges using Constraint Layout?
I am trying to change my GridLayout to the ConstraintLayout.

My grid looks like this:

```<code><android.support.v7.widget.GridLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">

<com.app.widget.CircularColorProgressView
    android:id="@+id/progress_stage_asset"

    android:layout_width="@dimen/circular_color_progress_size_small"
    android:layout_height="@dimen/circular_color_progress_size_small"

    app:layout_gravity="center_horizontal"
    app:layout_column="0"
    app:layout_row="0"

    app:hideText="true"
    app:skipStartColor="true"/>

<TextView
    android:id="@+id/progress_text_stage_asset"

    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="@dimen/margin_small"

    app:layout_gravity="center_horizontal"
    app:layout_column="0"
    app:layout_row="1"

    style="@style/AppWidget.Text.Emphasized"
    android:gravity="center"
    android:textColor="@color/circular_progress_middle_color"
    android:text="text text text" />

<com.app.widget.CircularColorProgressView
    android:id="@+id/progress_stage_sync"

    android:layout_width="@dimen/circular_color_progress_size_small"
    android:layout_height="@dimen/circular_color_progress_size_small"

    app:layout_gravity="center_horizontal"
    app:layout_column="2"
    app:layout_row="0"

    app:hideText="true"
    app:skipStartColor="true"/>

<TextView
    android:id="@+id/progress_text_stage_sync"

    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="@dimen/margin_small"

    app:layout_gravity="center_horizontal"
    app:layout_column="2"
    app:layout_row="1"

    style="@style/AppWidget.Text.Emphasized"
    android:gravity="center"
    android:textColor="@color/circular_progress_middle_color"
    android:text="text text text" />

<com.app.widget.CircularColorProgressView
    android:id="@+id/progress_stage_completed"

    android:layout_width="@dimen/circular_color_progress_size_medium"
    android:layout_height="@dimen/circular_color_progress_size_medium"

    app:layout_gravity="center_horizontal"
    app:layout_column="0"
    app:layout_row="3"

    app:hideText="true"
    app:skipStartColor="true"/>

<TextView
    android:id="@+id/progress_text_stage_completed"

    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="@dimen/margin_small"

    app:layout_gravity="center_horizontal"
    app:layout_column="0"
    app:layout_row="4"

    style="@style/AppWidget.Text.Emphasized"
    android:gravity="center"
    android:textColor="@color/circular_progress_middle_color"
    android:text="@string/msg_in_store_commissioning_stage_completed" />

<View
    android:layout_width="0dp"
    android:layout_height="0dp"

    app:layout_column="1"
    app:layout_row="2"
    app:layout_columnWeight="1"
    app:layout_rowWeight="1"/>

<com.app.widget.CircularColorProgressView
    android:id="@+id/progress_stage_params"

    android:layout_width="@dimen/circular_color_progress_size_small"
    android:layout_height="@dimen/circular_color_progress_size_small"

    app:layout_gravity="center"
    app:layout_column="2"
    app:layout_row="3"

    app:hideText="true"
    app:skipStartColor="true"/>

</android.support.v7.widget.GridLayout>
</code>```

And it produces the output like this:

I am new to ConstraintLayout. Is there an easy way to accomplish the same behaviour using Constraint Layout? I guess it will be more efficient and clean.

Using RelativeLayout will be just to align left, right, bottom etc.
Using LinearLayout will be just to put some empty view in between those Circular views and add the specific weights to them.

But how it can be easly done with ConstraintLayout?

UPDATE:
Here is what i tried with ConstraintLayout so far:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<com.app.widget.CircularColorProgressView
    android:id="@+id/progress_stage_asset"
    android:layout_width="@dimen/circular_color_progress_size_small"
    android:layout_height="@dimen/circular_color_progress_size_small"
    android:layout_marginStart="16dp"
    app:hideText="true"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:skipStartColor="true" />

<TextView
    android:id="@+id/progress_text_stage_asset"

    style="@style/AppWidget.Text.Emphasized"
    android:layout_width="wrap_content"

    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginTop="12dp"

    android:gravity="center"
    android:text="text text text"
    android:textColor="@color/circular_progress_middle_color"
    app:layout_column="0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/progress_stage_asset"
    app:layout_gravity="center_horizontal"
    app:layout_row="1" />

<com.app.widget.CircularColorProgressView
    android:id="@+id/progress_stage_sync"
    android:layout_width="@dimen/circular_color_progress_size_small"
    android:layout_height="@dimen/circular_color_progress_size_small"
    android:layout_marginEnd="16dp"

    app:hideText="true"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:skipStartColor="true" />

<TextView
    android:id="@+id/progress_text_stage_sync"
    style="@style/AppWidget.Text.Emphasized"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginTop="@dimen/margin_small"
    android:gravity="center"
    android:text="text text text"
    android:textColor="@color/circular_progress_middle_color"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/progress_stage_sync"
    app:layout_gravity="center_horizontal" />

<com.app.widget.CircularColorProgressView
    android:id="@+id/progress_stage_completed"

    android:layout_width="@dimen/circular_color_progress_size_medium"
    android:layout_height="@dimen/circular_color_progress_size_medium"

    android:layout_marginBottom="48dp"

    app:hideText="true"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_gravity="center_horizontal"
    app:skipStartColor="true" />

<TextView
    android:id="@+id/progress_text_stage_completed"

    style="@style/AppWidget.Text.Emphasized"
    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_marginStart="3dp"
    android:layout_marginTop="@dimen/margin_small"
    android:gravity="center"
    android:text="@string/msg_in_store_commissioning_stage_completed"
    android:textColor="@color/circular_progress_middle_color"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/progress_stage_completed"
    app:layout_gravity="center_horizontal" />

<com.app.widget.CircularColorProgressView
    android:layout_width="@dimen/circular_color_progress_size_small"
    android:layout_height="@dimen/circular_color_progress_size_small"
    android:layout_marginBottom="80dp"
    android:layout_marginEnd="16dp"
    app:hideText="true"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:skipStartColor="true" />
</code>```

It produces pretty similiar to the Grid:

答:
Try this:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/gridLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ProgressBar
        android:id="@+id/progress_stage_asset"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
         />

    <TextView
        android:id="@+id/progress_text_stage_asset"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text text text"
        android:textColor="@android:color/black"
        app:layout_constraintLeft_toLeftOf="@+id/progress_stage_asset"
        app:layout_constraintRight_toRightOf="@+id/progress_stage_asset"
        app:layout_constraintTop_toBottomOf="@+id/progress_stage_asset" />

    <ProgressBar
        android:id="@+id/progress_stage_sync"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintRight_toRightOf="parent"
         />

    <TextView
        android:id="@+id/progress_text_stage_sync"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text text text"
        app:layout_constraintLeft_toLeftOf="@id/progress_stage_sync"
        app:layout_constraintLeft_toRightOf="@+id/progress_stage_sync"
        app:layout_constraintTop_toBottomOf="@+id/progress_stage_sync"/>

    <ProgressBar
        android:id="@+id/progress_stage_completed"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintBottom_toTopOf="@+id/progress_text_stage_completed"
        />

    <TextView
        android:id="@+id/progress_text_stage_completed"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello"
        android:textColor="@android:color/black"
        app:layout_constraintLeft_toLeftOf="@+id/progress_stage_completed"
        app:layout_constraintRight_toRightOf="@+id/progress_stage_completed"
        app:layout_constraintBottom_toBottomOf="parent"/>

    <View
        android:id="@+id/view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <ProgressBar
        android:id="@+id/progress_stage_params"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="20dp"
       />

</android.support.constraint.ConstraintLayout>
</code>```

Body:
I am trying to change my GridLayout to the ConstraintLayout.

My grid looks like this:

<android.support.v7.widget.GridLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">

<com.app.widget.CircularColorProgressView
    android:id="@+id/progress_stage_asset"

    android:layout_width="@dimen/circular_color_progress_size_small"
    android:layout_height="@dimen/circular_color_progress_size_small"

    app:layout_gravity="center_horizontal"
    app:layout_column="0"
    app:layout_row="0"

    app:hideText="true"
    app:skipStartColor="true"/>

<TextView
    android:id="@+id/progress_text_stage_asset"

    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="@dimen/margin_small"

    app:layout_gravity="center_horizontal"
    app:layout_column="0"
    app:layout_row="1"

    style="@style/AppWidget.Text.Emphasized"
    android:gravity="center"
    android:textColor="@color/circular_progress_middle_color"
    android:text="text text text" />

<com.app.widget.CircularColorProgressView
    android:id="@+id/progress_stage_sync"

    android:layout_width="@dimen/circular_color_progress_size_small"
    android:layout_height="@dimen/circular_color_progress_size_small"

    app:layout_gravity="center_horizontal"
    app:layout_column="2"
    app:layout_row="0"

    app:hideText="true"
    app:skipStartColor="true"/>

<TextView
    android:id="@+id/progress_text_stage_sync"

    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="@dimen/margin_small"

    app:layout_gravity="center_horizontal"
    app:layout_column="2"
    app:layout_row="1"

    style="@style/AppWidget.Text.Emphasized"
    android:gravity="center"
    android:textColor="@color/circular_progress_middle_color"
    android:text="text text text" />

<com.app.widget.CircularColorProgressView
    android:id="@+id/progress_stage_completed"

    android:layout_width="@dimen/circular_color_progress_size_medium"
    android:layout_height="@dimen/circular_color_progress_size_medium"

    app:layout_gravity="center_horizontal"
    app:layout_column="0"
    app:layout_row="3"

    app:hideText="true"
    app:skipStartColor="true"/>

<TextView
    android:id="@+id/progress_text_stage_completed"

    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="@dimen/margin_small"

    app:layout_gravity="center_horizontal"
    app:layout_column="0"
    app:layout_row="4"

    style="@style/AppWidget.Text.Emphasized"
    android:gravity="center"
    android:textColor="@color/circular_progress_middle_color"
    android:text="@string/msg_in_store_commissioning_stage_completed" />

<View
    android:layout_width="0dp"
    android:layout_height="0dp"

    app:layout_column="1"
    app:layout_row="2"
    app:layout_columnWeight="1"
    app:layout_rowWeight="1"/>

<com.app.widget.CircularColorProgressView
    android:id="@+id/progress_stage_params"

    android:layout_width="@dimen/circular_color_progress_size_small"
    android:layout_height="@dimen/circular_color_progress_size_small"

    app:layout_gravity="center"
    app:layout_column="2"
    app:layout_row="3"

    app:hideText="true"
    app:skipStartColor="true"/>

</android.support.v7.widget.GridLayout>

And it produces the output like this:

I am new to ConstraintLayout. Is there an easy way to accomplish the same behaviour using Constraint Layout? I guess it will be more efficient and clean.

Using RelativeLayout will be just to align left, right, bottom etc.
Using LinearLayout will be just to put some empty view in between those Circular views and add the specific weights to them.

But how it can be easly done with ConstraintLayout?

UPDATE:
Here is what i tried with ConstraintLayout so far:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<com.app.widget.CircularColorProgressView
    android:id="@+id/progress_stage_asset"
    android:layout_width="@dimen/circular_color_progress_size_small"
    android:layout_height="@dimen/circular_color_progress_size_small"
    android:layout_marginStart="16dp"
    app:hideText="true"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:skipStartColor="true" />

<TextView
    android:id="@+id/progress_text_stage_asset"

    style="@style/AppWidget.Text.Emphasized"
    android:layout_width="wrap_content"

    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginTop="12dp"

    android:gravity="center"
    android:text="text text text"
    android:textColor="@color/circular_progress_middle_color"
    app:layout_column="0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/progress_stage_asset"
    app:layout_gravity="center_horizontal"
    app:layout_row="1" />

<com.app.widget.CircularColorProgressView
    android:id="@+id/progress_stage_sync"
    android:layout_width="@dimen/circular_color_progress_size_small"
    android:layout_height="@dimen/circular_color_progress_size_small"
    android:layout_marginEnd="16dp"

    app:hideText="true"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:skipStartColor="true" />

<TextView
    android:id="@+id/progress_text_stage_sync"
    style="@style/AppWidget.Text.Emphasized"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginTop="@dimen/margin_small"
    android:gravity="center"
    android:text="text text text"
    android:textColor="@color/circular_progress_middle_color"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/progress_stage_sync"
    app:layout_gravity="center_horizontal" />

<com.app.widget.CircularColorProgressView
    android:id="@+id/progress_stage_completed"

    android:layout_width="@dimen/circular_color_progress_size_medium"
    android:layout_height="@dimen/circular_color_progress_size_medium"

    android:layout_marginBottom="48dp"

    app:hideText="true"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_gravity="center_horizontal"
    app:skipStartColor="true" />

<TextView
    android:id="@+id/progress_text_stage_completed"

    style="@style/AppWidget.Text.Emphasized"
    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_marginStart="3dp"
    android:layout_marginTop="@dimen/margin_small"
    android:gravity="center"
    android:text="@string/msg_in_store_commissioning_stage_completed"
    android:textColor="@color/circular_progress_middle_color"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/progress_stage_completed"
    app:layout_gravity="center_horizontal" />

<com.app.widget.CircularColorProgressView
    android:layout_width="@dimen/circular_color_progress_size_small"
    android:layout_height="@dimen/circular_color_progress_size_small"
    android:layout_marginBottom="80dp"
    android:layout_marginEnd="16dp"
    app:hideText="true"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:skipStartColor="true" />

It produces pretty similiar to the Grid:

Body:
Try this:

    <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/gridLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ProgressBar
        android:id="@+id/progress_stage_asset"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
         />

    <TextView
        android:id="@+id/progress_text_stage_asset"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text text text"
        android:textColor="@android:color/black"
        app:layout_constraintLeft_toLeftOf="@+id/progress_stage_asset"
        app:layout_constraintRight_toRightOf="@+id/progress_stage_asset"
        app:layout_constraintTop_toBottomOf="@+id/progress_stage_asset" />

    <ProgressBar
        android:id="@+id/progress_stage_sync"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintRight_toRightOf="parent"
         />

    <TextView
        android:id="@+id/progress_text_stage_sync"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text text text"
        app:layout_constraintLeft_toLeftOf="@id/progress_stage_sync"
        app:layout_constraintLeft_toRightOf="@+id/progress_stage_sync"
        app:layout_constraintTop_toBottomOf="@+id/progress_stage_sync"/>

    <ProgressBar
        android:id="@+id/progress_stage_completed"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintBottom_toTopOf="@+id/progress_text_stage_completed"
        />

    <TextView
        android:id="@+id/progress_text_stage_completed"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello"
        android:textColor="@android:color/black"
        app:layout_constraintLeft_toLeftOf="@+id/progress_stage_completed"
        app:layout_constraintRight_toRightOf="@+id/progress_stage_completed"
        app:layout_constraintBottom_toBottomOf="parent"/>

    <View
        android:id="@+id/view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <ProgressBar
        android:id="@+id/progress_stage_params"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="20dp"
       />

</android.support.constraint.ConstraintLayout>


问:
Restore and Backup with Entity Framework
I use C#, .net 4, Entity Framework and SQL Server 2008 R2 in a project.

I have no familiarity with backup and restore from database by Entity Framework. Please help me to write restore and backup code in Entity Framework

答:
This should get you going on the restore side:

```<code>void LoadDB(
    System.Data.Entity.DbContext context,
    string backup_filename,
    string orig_mdf, // the original LogicalName name of the data (also called the MDF) file within the backup file
    string orig_ldf, // the original LogicalName name of the log (also called the LDF) file within the backup file
    string new_database_name
)
{
    var database_dir = System.IO.Path.GetTempPath();
    var temp_mdf = $"{database_dir}{new_database_name}.mdf";
    var temp_ldf = $"{database_dir}{new_database_name}.ldf";
    var query = @"RESTORE DATABASE @new_database_name FROM DISK = @backup_filename
        WITH MOVE @orig_mdf TO @temp_mdf,
        MOVE @orig_ldf TO  @temp_ldf,
        REPLACE;";
    context.Database.ExecuteSqlCommand(
        // Do not use a transaction for this query so we can load without getting an exception:
        // "cannot perform a backup or restore operation within a transaction"
        TransactionalBehavior.DoNotEnsureTransaction,
        query,
        new[] {
        new SqlParameter("@backup_filename", backup_filename),
        new SqlParameter("@database_dir", database_dir),
        new SqlParameter("@new_database_name", new_database_name),
        new SqlParameter("@orig_mdf", orig_mdf),
        new SqlParameter("@orig_ldf", orig_ldf),
        new SqlParameter("@temp_mdf", temp_mdf),
        new SqlParameter("@temp_ldf", temp_ldf),
        }
    );
}
</code>```

If you don't know them beforehand, the MDF and LDF LogicalName values can be obtained manually or programmatically from a query like this one:

```<code>RESTORE FILELISTONLY FROM DISK @backup_filename
</code>```

Body:
This should get you going on the restore side:

void LoadDB(
    System.Data.Entity.DbContext context,
    string backup_filename,
    string orig_mdf, // the original LogicalName name of the data (also called the MDF) file within the backup file
    string orig_ldf, // the original LogicalName name of the log (also called the LDF) file within the backup file
    string new_database_name
)
{
    var database_dir = System.IO.Path.GetTempPath();
    var temp_mdf = $"{database_dir}{new_database_name}.mdf";
    var temp_ldf = $"{database_dir}{new_database_name}.ldf";
    var query = @"RESTORE DATABASE @new_database_name FROM DISK = @backup_filename
        WITH MOVE @orig_mdf TO @temp_mdf,
        MOVE @orig_ldf TO  @temp_ldf,
        REPLACE;";
    context.Database.ExecuteSqlCommand(
        // Do not use a transaction for this query so we can load without getting an exception:
        // "cannot perform a backup or restore operation within a transaction"
        TransactionalBehavior.DoNotEnsureTransaction,
        query,
        new[] {
        new SqlParameter("@backup_filename", backup_filename),
        new SqlParameter("@database_dir", database_dir),
        new SqlParameter("@new_database_name", new_database_name),
        new SqlParameter("@orig_mdf", orig_mdf),
        new SqlParameter("@orig_ldf", orig_ldf),
        new SqlParameter("@temp_mdf", temp_mdf),
        new SqlParameter("@temp_ldf", temp_ldf),
        }
    );
}

If you don't know them beforehand, the MDF and LDF LogicalName values can be obtained manually or programmatically from a query like this one:

RESTORE FILELISTONLY FROM DISK @backup_filename