问:
Why this c program fall into infinity loop?
```<code>#include <stdio.h>

int main()
{
  int sum=0;
  char s[10];

  while(scanf("%[^\n]s", s)!=EOF)
  {
    printf("%s", s);

  }

  return 0;
}
</code>```

This while loop fall into infinity loop for any string input.

答:
Given

```<code>while(scanf("%[^\n]s", s)!=EOF)
{
   printf("%s", s);
}
</code>```

you ask "Why this c program fall into infinity loop?"

Therefore, you have to understand how scanf() works. scanf() uses your format string to parse input from stdin, which is a stream that delivers character by character.

Assume you have the following in stdin:

foo\n
bar\n
<<EOF>>
```

<p>Now your format string has this conversion <code>%[^\n]</code> which means "match anything but newline and copy into a char buffer". The <code>s</code> following it is just a literal <code>s</code> because it doesn't have a <code>%</code> in front of it ... so it would match a literal <code>s</code> if there was one. In other words, it doesn't matter here.</p>

<p>Now, calling your <code>scanf()</code> the first time, it WILL match <code>foo</code> and consume it. it returns <code>1</code> because it matched one element. After that, <code>stdin</code> looks like this:</p>

<pre class="lang-none prettyprint-override"><code>\n
bar\n
<<EOF>>
</code>```

Note the unmatched newline is still there. Your next call again starts with a format string to match anything but newline, but the next character is a newline. scanf() matches nothing and therefore returns 0. It cannot return EOF because, as you can see, EOF is not reached yet. Here is your infinite loop.

So, you have to fix your format string. First, remove the s that never matches anything. It doesn't really hurt here, but it's still wrong. Then, you can take advantage of the whitespace matching of scanf(). Whitespace is either space, tab or newline. If your format string contains whitespace, scanf() will match as much whitespace as is there (this can be none as well). Therefore, an easy fix would be to just start your format string with a space, this will "eat" the left-over newline:

```<code>while(scanf(" %[^\n]", s)!=EOF)
{
   printf("%s", s);
}
</code>```

Now this is still dangerous code, because [^\n] matches any amount of characters as long as there is no newline, but your buffer has only room for 9 character plus terminating 0. So you MUST tell scanf() not to match more than that limit, and this can be done by putting the number between the % and the conversion specification:

```<code>while(scanf(" %9[^\n]", s)!=EOF)
{
   printf("%s", s);
}
</code>```

This code will do what you want in a safe manner, but assume you wanted to match something more specific, e.g. numbers, and you get some unexpected input: By waiting for EOF, you'd have your infinite loop again, because there is input that doesn't match, and so you can never reach EOF (as above with the unmatched newline). Therefore, always check for the number of successful matches instead. Here you expect exactly one match, so the loop should look like this:

```<code>while (scanf(" %9[^\n]", s) == 1)
{
   printf("%s", s);
}
</code>```

In practice, for reading whole lines, you don't need scanf(), just using fgets() would be easier. Your code could look as simple as this (the newlines will be read into s as well):

```<code>while (fgets(s, 10, stdin))
{
    printf("%s", s);
}
</code>```

Note the second parameter 10 here: fgets() automatically accounts for the terminating 0 character, so you just give it the size of your buffer.

Just a final hint: this could be even simpler without using printf() when there's no formatting to do:

```<code>while (fgets(s, 10, stdin))
{
    fputs(s, stdout);
}
</code>```

Body:
#include <stdio.h>

int main()
{
  int sum=0;
  char s[10];

  while(scanf("%[^\n]s", s)!=EOF)
  {
    printf("%s", s);

  }

  return 0;
}

This while loop fall into infinity loop for any string input.

Body:
Given

while(scanf("%[^\n]s", s)!=EOF)
{
   printf("%s", s);
}

you ask "Why this c program fall into infinity loop?"

Therefore, you have to understand how scanf() works. scanf() uses your format string to parse input from stdin, which is a stream that delivers character by character.

Assume you have the following in stdin:

foo\n
bar\n
<<EOF>>

Now your format string has this conversion %[^\n] which means "match anything but newline and copy into a char buffer". The s following it is just a literal s because it doesn't have a % in front of it ... so it would match a literal s if there was one. In other words, it doesn't matter here.

Now, calling your scanf() the first time, it WILL match foo and consume it. it returns 1 because it matched one element. After that, stdin looks like this:

\n
bar\n
<<EOF>>

Note the unmatched newline is still there. Your next call again starts with a format string to match anything but newline, but the next character is a newline. scanf() matches nothing and therefore returns 0. It cannot return EOF because, as you can see, EOF is not reached yet. Here is your infinite loop.

So, you have to fix your format string. First, remove the s that never matches anything. It doesn't really hurt here, but it's still wrong. Then, you can take advantage of the whitespace matching of scanf(). Whitespace is either space, tab or newline. If your format string contains whitespace, scanf() will match as much whitespace as is there (this can be none as well). Therefore, an easy fix would be to just start your format string with a space, this will "eat" the left-over newline:

while(scanf(" %[^\n]", s)!=EOF)
{
   printf("%s", s);
}

Now this is still dangerous code, because [^\n] matches any amount of characters as long as there is no newline, but your buffer has only room for 9 character plus terminating 0. So you MUST tell scanf() not to match more than that limit, and this can be done by putting the number between the % and the conversion specification:

while(scanf(" %9[^\n]", s)!=EOF)
{
   printf("%s", s);
}

This code will do what you want in a safe manner, but assume you wanted to match something more specific, e.g. numbers, and you get some unexpected input: By waiting for EOF, you'd have your infinite loop again, because there is input that doesn't match, and so you can never reach EOF (as above with the unmatched newline). Therefore, always check for the number of successful matches instead. Here you expect exactly one match, so the loop should look like this:

while (scanf(" %9[^\n]", s) == 1)
{
   printf("%s", s);
}

In practice, for reading whole lines, you don't need scanf(), just using fgets() would be easier. Your code could look as simple as this (the newlines will be read into s as well):

while (fgets(s, 10, stdin))
{
    printf("%s", s);
}

Note the second parameter 10 here: fgets() automatically accounts for the terminating 0 character, so you just give it the size of your buffer.

Just a final hint: this could be even simpler without using printf() when there's no formatting to do:

while (fgets(s, 10, stdin))
{
    fputs(s, stdout);
}


来源: stackexchange

问:
Error when starting up cxf client for xsd containing xmldsig
We're currently developing a webservive containing a 3rd party XSD. This 3rd party XSD contains a digital signature (importing the http://www.w3.org/2000/09/xmldsig# XSD).

The architecture has 2 major functionalities:

our Webservice accepts messages as per the 3rd party XSD contract

we forward some of these messages to another (also 3rd party)
webservice via a small client

1) works perfectly, there are no issues involving the signature here.

2) is the odd one. As long as the signature-element

```<code><xs:element ref="sig:Signature" minOccurs="0" maxOccurs="1"/>
</code>```

is present, the software will not startup, and instead crash with this errormessage:

Caused by: org.springframework.beans.BeanInstantiationException:
  Failed to instantiate [net.eucaris.services.GenericServiceSoap]:
  Factory method 'genericServiceSoap' threw exception; nested exception
  is java.lang.IllegalArgumentException: can't parse argument number:
  ''{0}''   at
  org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
  [spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]    at
  org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
  [spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]    ... 38 more Caused by:
  java.lang.IllegalArgumentException: can't parse argument number:
  ''{0}''     at
  java.text.MessageFormat.makeFormat(MessageFormat.java:1429)
  [rt.jar:1.8.0_131]    at
  java.text.MessageFormat.applyPattern(MessageFormat.java:479)
  [rt.jar:1.8.0_131]    at
  java.text.MessageFormat.(MessageFormat.java:362)
  [rt.jar:1.8.0_131]    at
  java.text.MessageFormat.format(MessageFormat.java:840)
  [rt.jar:1.8.0_131]    at
  com.sun.xml.bind.v2.model.impl.Messages.format(Messages.java:132)
  [jaxb-impl-2.2.11.jar:2.2.11]

I traced it down to the generated files, to be precise the porttype-interface:

```<code>@WebService(targetNamespace = "http://services.eucaris.net/", name = "GenericServiceSoap")
@XmlSeeAlso({org.w3._2000._09.xmldsig_.ObjectFactory.class, ObjectFactory.class})
public interface GenericServiceSoap {
...
</code>```

As long as the xmldsig-ObjectFactory is referenced here, the system crashes. Once its out, everything works fine (well, until someone sends a signature, which then cannot be recognized).

Digging deeper (ie, debugging) leads me to this information:

The exception is thrown in this piece of code (java.text.MessageFormat, from line 1415, jdk 1.8.131)

```<code> private void makeFormat(int position, int offsetNumber,
                            StringBuilder[] textSegments)
    {
        String[] segments = new String[textSegments.length];
        for (int i = 0; i < textSegments.length; i++) {
            StringBuilder oneseg = textSegments[i];
            segments[i] = (oneseg != null) ? oneseg.toString() : "";
        }

        // get the argument number
        int argumentNumber;
        try {
            argumentNumber = Integer.parseInt(segments[SEG_INDEX]); // always unlocalized!
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("can't parse argument number: "
                                               + segments[SEG_INDEX], e);
        }
</code>```

The method parameters are 73, 0, and a StringBuilder containing this data:

[Es ist keine ObjectFactory mit @XmlElementDecl für das Element ',
  ''{0}'', null, null]

This indicates, that somehow, somewhere, this StringBuffer is filled wrong, as the method clearly expects a number. ''{0}'' kinda looks like a placeholder. In itself, the application tries to raise an error or at least a warning, considering the content of the message.

More info:

We're using CXF 3.1.11 with Spring 4.3.8. We're generating code from the wsdl and xsd files. The client is created via

```<code>@Bean
public GenericServiceSoap genericServiceSoap() {
    final JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
    factory.setAddress(http://example.com);
    factory.setServiceClass(GenericServiceSoap.class);
    factory.setInInterceptors(createInInterceptors());
    factory.setOutInterceptors(createOutInterceptors());
    return (GenericServiceSoap) factory.create();
}
</code>```

The signature generates this piece of code, which looks fine to me:

```<code>@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SignatureType", propOrder = {
    "signedInfo",
    "signatureValue",
    "keyInfo",
    "objects"
})
@XmlRootElement(name = "Signature")
public class Signature implements Serializable
{

    private final static Long serialVersionUID = 5363422069410258353L;
    @XmlElement(name = "SignedInfo", required = true)
    @NotNull
    protected SignedInfo signedInfo;
    @XmlElement(name = "SignatureValue", required = true)
    @NotNull
    protected SignatureValue signatureValue;
    @XmlElement(name = "KeyInfo")
    protected KeyInfo keyInfo;
    @XmlElement(name = "Object")
    protected List<org.w3._2000._09.xmldsig_.Object> objects;
    @XmlAttribute(name = "Id")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlID
    @XmlSchemaType(name = "ID")
    @Pattern(regexp = "[\\i-[:]][\\c-[:]]*")
    protected String id;
    // getters/setters omitted
</code>```

I just don't get how or why this happens. Or am I running into a bug here?

答:
The main problem was an instance of

com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException: 1
  counts of IllegalAnnotationExceptions Two classes have the same XML
  type name "xxx". Use @XmlType.name and @XmlType.namespace

That problem was solved.

As to why this error was mangled deep inside of the framework instead of clearly given out, I have no clue. I've seen the error before, once it was known it was clear what to do. Maybe there is a bug somewhere in there, who knows.

ContentLicense: CC BY-SA 3.0

Body:
We're currently developing a webservive containing a 3rd party XSD. This 3rd party XSD contains a digital signature (importing the http://www.w3.org/2000/09/xmldsig# XSD).

The architecture has 2 major functionalities:

our Webservice accepts messages as per the 3rd party XSD contract

we forward some of these messages to another (also 3rd party)
webservice via a small client

1) works perfectly, there are no issues involving the signature here.

2) is the odd one. As long as the signature-element

<xs:element ref="sig:Signature" minOccurs="0" maxOccurs="1"/>

is present, the software will not startup, and instead crash with this errormessage:

Caused by: org.springframework.beans.BeanInstantiationException:
  Failed to instantiate [net.eucaris.services.GenericServiceSoap]:
  Factory method 'genericServiceSoap' threw exception; nested exception
  is java.lang.IllegalArgumentException: can't parse argument number:
  ''{0}''   at
  org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
  [spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]    at
  org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
  [spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]    ... 38 more Caused by:
  java.lang.IllegalArgumentException: can't parse argument number:
  ''{0}''     at
  java.text.MessageFormat.makeFormat(MessageFormat.java:1429)
  [rt.jar:1.8.0_131]    at
  java.text.MessageFormat.applyPattern(MessageFormat.java:479)
  [rt.jar:1.8.0_131]    at
  java.text.MessageFormat.(MessageFormat.java:362)
  [rt.jar:1.8.0_131]    at
  java.text.MessageFormat.format(MessageFormat.java:840)
  [rt.jar:1.8.0_131]    at
  com.sun.xml.bind.v2.model.impl.Messages.format(Messages.java:132)
  [jaxb-impl-2.2.11.jar:2.2.11]

I traced it down to the generated files, to be precise the porttype-interface:

@WebService(targetNamespace = "http://services.eucaris.net/", name = "GenericServiceSoap")
@XmlSeeAlso({org.w3._2000._09.xmldsig_.ObjectFactory.class, ObjectFactory.class})
public interface GenericServiceSoap {
...

As long as the xmldsig-ObjectFactory is referenced here, the system crashes. Once its out, everything works fine (well, until someone sends a signature, which then cannot be recognized).

Digging deeper (ie, debugging) leads me to this information:

The exception is thrown in this piece of code (java.text.MessageFormat, from line 1415, jdk 1.8.131)

 private void makeFormat(int position, int offsetNumber,
                            StringBuilder[] textSegments)
    {
        String[] segments = new String[textSegments.length];
        for (int i = 0; i < textSegments.length; i++) {
            StringBuilder oneseg = textSegments[i];
            segments[i] = (oneseg != null) ? oneseg.toString() : "";
        }

        // get the argument number
        int argumentNumber;
        try {
            argumentNumber = Integer.parseInt(segments[SEG_INDEX]); // always unlocalized!
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("can't parse argument number: "
                                               + segments[SEG_INDEX], e);
        }

The method parameters are 73, 0, and a StringBuilder containing this data:

[Es ist keine ObjectFactory mit @XmlElementDecl für das Element ',
  ''{0}'', null, null]

This indicates, that somehow, somewhere, this StringBuffer is filled wrong, as the method clearly expects a number. ''{0}'' kinda looks like a placeholder. In itself, the application tries to raise an error or at least a warning, considering the content of the message.

More info:

We're using CXF 3.1.11 with Spring 4.3.8. We're generating code from the wsdl and xsd files. The client is created via

@Bean
public GenericServiceSoap genericServiceSoap() {
    final JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
    factory.setAddress(http://example.com);
    factory.setServiceClass(GenericServiceSoap.class);
    factory.setInInterceptors(createInInterceptors());
    factory.setOutInterceptors(createOutInterceptors());
    return (GenericServiceSoap) factory.create();
}

The signature generates this piece of code, which looks fine to me:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SignatureType", propOrder = {
    "signedInfo",
    "signatureValue",
    "keyInfo",
    "objects"
})
@XmlRootElement(name = "Signature")
public class Signature implements Serializable
{

    private final static Long serialVersionUID = 5363422069410258353L;
    @XmlElement(name = "SignedInfo", required = true)
    @NotNull
    protected SignedInfo signedInfo;
    @XmlElement(name = "SignatureValue", required = true)
    @NotNull
    protected SignatureValue signatureValue;
    @XmlElement(name = "KeyInfo")
    protected KeyInfo keyInfo;
    @XmlElement(name = "Object")
    protected List<org.w3._2000._09.xmldsig_.Object> objects;
    @XmlAttribute(name = "Id")
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlID
    @XmlSchemaType(name = "ID")
    @Pattern(regexp = "[\\i-[:]][\\c-[:]]*")
    protected String id;
    // getters/setters omitted

I just don't get how or why this happens. Or am I running into a bug here?


问:
Rails Active Record method to ensure query returns single record?
Is there something in Active Record that ensures that your query does NOT return more than one record?

This is what the basic functionality would be (apologies--this isn't real code but just enough to give the idea of what I'm looking for):

```<code>Foo.where(:thing => 'this_should_be_uniq').single

def single(records)
  if records.length > 1
    raise # or maybe return nil or something like that
  else
    return records.first
  end
end
</code>```

Essentially, this would be a safeguard against accidentally assuming (incorrectly) that your query will always return a single record.

Thanks!

答:
I cannot find such method in ActiveRecord::FinderMethods.

As alternative solution, you can write it shorter using tap method in the case of raising the exception if more than two records exists:

Foo.where(:thing => 'this_should_be_uniq').tap { |r| raise "ERROR" if r.count > 1 }.first

Considering isolation from other operations, the following code is proper:

Foo.where(:thing => 'this_should_be_uniq').to_a.tap { |r| raise "ERROR" if r.size > 1 }[0]

Body:
Is there something in Active Record that ensures that your query does NOT return more than one record?

This is what the basic functionality would be (apologies--this isn't real code but just enough to give the idea of what I'm looking for):

Foo.where(:thing => 'this_should_be_uniq').single

def single(records)
  if records.length > 1
    raise # or maybe return nil or something like that
  else
    return records.first
  end
end

Essentially, this would be a safeguard against accidentally assuming (incorrectly) that your query will always return a single record.

Thanks!


问:
iOS Swift POST param and body
I'm trying to POST a key parameter and a JSON dictionary body to an API but for some reason it won't work.

Here's my work so far.

```<code>@IBAction func POST(_ sender: Any) {
    let url = URL(string: "http://apilink.com/updateProfile&=param")!
    let jsonObject = ["FName":"Tarik",
                      "LName":"Salama"]
    let jsonData = try! JSONSerialization.data(withJSONObject: jsonObject, options: [])

    var request = URLRequest(url: url)
    request.httpMethod = "post"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    request.httpBody = jsonData

    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
        if let error = error {
            print("error:", error)
            return
        }

        do {
            guard let data = data else { return }
            guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject] else { return }
            print("json:", json)
        } catch {
            print("error:", error)
        }
    }

    task.resume()
}
</code>```

I get this error when I click the POST button:

error: Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

What am I doing wrong?
I tried changing some stuff around after I checked some other threads like putting the parameter and the data dictionary into a key:value dictionary but the API responded and said that the data is invalid which means the whole thing was sent in an incorrect format.
Note: I'm not allowed to use 3rd party libraries like Alamofire and the API link is working fine as shown in the screenshot.

答:
you can check the problem by printing the response data

```<code>do {
            guard let data = data else { return }
            print(String(data: data, encoding: .utf8) ?? "No Conversion") //Print Here
            guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject] else { return }
            print("json:", json)
        } catch {
            print("error:", error)
        }
</code>```

look at the 'Print Here' line. I believe the response is not a valid json so when you try to parse the data to JSOn it always ends up in catch block.

Title: iOS Swift POST param and body

Body:
I'm trying to POST a key parameter and a JSON dictionary body to an API but for some reason it won't work.

Here's my work so far.

@IBAction func POST(_ sender: Any) {
    let url = URL(string: "http://apilink.com/updateProfile&=param")!
    let jsonObject = ["FName":"Tarik",
                      "LName":"Salama"]
    let jsonData = try! JSONSerialization.data(withJSONObject: jsonObject, options: [])

    var request = URLRequest(url: url)
    request.httpMethod = "post"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    request.httpBody = jsonData

    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
        if let error = error {
            print("error:", error)
            return
        }

        do {
            guard let data = data else { return }
            guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject] else { return }
            print("json:", json)
        } catch {
            print("error:", error)
        }
    }

    task.resume()
}

I get this error when I click the POST button:

error: Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

What am I doing wrong?
I tried changing some stuff around after I checked some other threads like putting the parameter and the data dictionary into a key:value dictionary but the API responded and said that the data is invalid which means the whole thing was sent in an incorrect format.
Note: I'm not allowed to use 3rd party libraries like Alamofire and the API link is working fine as shown in the screenshot.

Body:
you can check the problem by printing the response data

do {
            guard let data = data else { return }
            print(String(data: data, encoding: .utf8) ?? "No Conversion") //Print Here
            guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: AnyObject] else { return }
            print("json:", json)
        } catch {
            print("error:", error)
        }

look at the 'Print Here' line. I believe the response is not a valid json so when you try to parse the data to JSOn it always ends up in catch block.


问:
Why can I not click on this element in this code?
Actions action = new Actions(driver);
IWebElement we = driver.FindElement(By.XPath(".//*[@class='ms-crm-CommandBar-Button ms-crm-Menu-Label']"));

action.MoveToElement(driver.FindElement(By.XPath(".//*[@class='ms-crm-CommandBar-Button ms-crm-Menu-Label-Hovered']"))).Click().Build().Perform();

expect element as followings:

            New

            Create a new Lead record.

Note that this class "ms-crm-CommandBar-Button ms-crm-Menu-Label" turns to be "ms-crm-CommandBar-Button ms-crm-Menu-Label-Hovered" when mouseover.

Many thanks.

答:
In hover case first you need to moveTo That element after that you can click on it. </p>

```<code>Actions actions = new Actions(driver);
action.moveToElement(mainMenu).moveToElement(driver.findElement(By.xpath("ur element"))).click().build().perform();
</code>```

Body:
In hover case first you need to moveTo That element after that you can click on it.

Actions actions = new Actions(driver);
action.moveToElement(mainMenu).moveToElement(driver.findElement(By.xpath("ur element"))).click().build().perform();


问:
Flatten a nested object in MongoDB and rename
Suppose I have documents like this

```<code>{
    "id" : "1415166669",
    "color" : {
        "14" : "Silver"
    },
    "name":"Random Name"
}
</code>```

where the key inside color can change, i.e Next Document may look like this

```<code>{
    "id" : "1415126969",
    "color" : {
        "11" : "Gold"
    },
    "name":"Random Name 2"
}
</code>```

I want to flatten and rename them so that my documents have a similar structure as follows:

```<code>{
    "id" : "1415126969",
    "color"  : "Gold"
    "name":"Random Name 2"
}
</code>```

and

```<code>{
    "id" : "1415166669",
    "color" : "Silver"
    "name":"Random Name"
}
</code>```

I tried using the aggregation pipeline but I am not sure how to proceed further.
Also can anyone suggest a way using Robomongo, that would be nice as well.

答:
I would run a simple JavaScript loop for this, since it's going to be quite quick and easy to code. It can also be applied to the same collection:

```<code>var ops = [];

db.collection.find().forEach(function(doc) {
  let color;
  Object.keys(doc.color).forEach(function(key) {
    color = doc.color[key];
  });
  ops = [
    ...ops,
    { "updateOne": {
      "filter": { "_id": doc._id },
      "update": { "$set": { "color": color } }
    }}
  ];
  if ( ops.length >= 500 ) {
    db.collection.bulkWrite(ops);
     ops = [];
  }
})

if ( ops.length > 0 ) {
  db.collection.bulkWrite(ops);
   ops = [];
}
</code>```

So you basically traverse the "keys" of the object and get the value, which later we write back to the document with $set

Alternately, since MongoDB 3.4 you can run an aggregation statement using $objectToArray in order to access the keys. But you really only should do this where the collection has millions of documents. The requirements of $out means the result is in new collection, and not the current one being updated:

```<code>db.collecion.aggregate([
  { "$addFields": {
    "color": {
     "$arrayElemAt": [
       { "$map": {
         "input": { "$objectToArray": "$color" },
         "as": "c",
         "in": "$$c.v"
       }},
       0
     ]
    }
  }},
  { "$out": "newcollection" }
])
</code>```

This works because $objectToArray turns your structure like this:

```<code>"color": { "11": "Gold" }
</code>```

Into this:

```<code>"color": [{ "k": "11", "v": "Gold" }]
</code>```

So we can then use the $map operator in order to extract the "color.v" path value and $arrayElemAt to turn this into a singular value rather than an array.

Generally speaking such conversions would be a lot more complex for aggregation pipeline statements than for what you can achieve simply by manipulating the document structure in code and then writing back to the target collection.

Given the existing documents:

```<code>{
        "_id" : ObjectId("59389951fc04695e84e7f4ae"),
        "id" : "1415166669",
        "color" : {
                "14" : "Silver"
        },
        "name" : "Random Name"
}
{
        "_id" : ObjectId("59389a75fc04695e84e7f4af"),
        "id" : "1415126969",
        "color" : {
                "11" : "Gold"
        },
        "name" : "Random Name 2"
}
</code>```

Output from both methods is:

```<code>{
        "_id" : ObjectId("59389951fc04695e84e7f4ae"),
        "id" : "1415166669",
        "color" : "Silver",
        "name" : "Random Name"
}
{
        "_id" : ObjectId("59389a75fc04695e84e7f4af"),
        "id" : "1415126969",
        "color" : "Gold",
        "name" : "Random Name 2"
}
</code>```

Body:
Suppose I have documents like this

{
    "id" : "1415166669",
    "color" : {
        "14" : "Silver"
    },
    "name":"Random Name"
}

where the key inside color can change, i.e Next Document may look like this

{
    "id" : "1415126969",
    "color" : {
        "11" : "Gold"
    },
    "name":"Random Name 2"
}

I want to flatten and rename them so that my documents have a similar structure as follows:

{
    "id" : "1415126969",
    "color"  : "Gold"
    "name":"Random Name 2"
}

and

{
    "id" : "1415166669",
    "color" : "Silver"
    "name":"Random Name"
}

I tried using the aggregation pipeline but I am not sure how to proceed further.
Also can anyone suggest a way using Robomongo, that would be nice as well.

Body:
I would run a simple JavaScript loop for this, since it's going to be quite quick and easy to code. It can also be applied to the same collection:

var ops = [];

db.collection.find().forEach(function(doc) {
  let color;
  Object.keys(doc.color).forEach(function(key) {
    color = doc.color[key];
  });
  ops = [
    ...ops,
    { "updateOne": {
      "filter": { "_id": doc._id },
      "update": { "$set": { "color": color } }
    }}
  ];
  if ( ops.length >= 500 ) {
    db.collection.bulkWrite(ops);
     ops = [];
  }
})

if ( ops.length > 0 ) {
  db.collection.bulkWrite(ops);
   ops = [];
}

So you basically traverse the "keys" of the object and get the value, which later we write back to the document with $set

Alternately, since MongoDB 3.4 you can run an aggregation statement using $objectToArray in order to access the keys. But you really only should do this where the collection has millions of documents. The requirements of $out means the result is in new collection, and not the current one being updated:

db.collecion.aggregate([
  { "$addFields": {
    "color": {
     "$arrayElemAt": [
       { "$map": {
         "input": { "$objectToArray": "$color" },
         "as": "c",
         "in": "$$c.v"
       }},
       0
     ]
    }
  }},
  { "$out": "newcollection" }
])

This works because $objectToArray turns your structure like this:

"color": { "11": "Gold" }

Into this:

"color": [{ "k": "11", "v": "Gold" }]

So we can then use the $map operator in order to extract the "color.v" path value and $arrayElemAt to turn this into a singular value rather than an array.

Generally speaking such conversions would be a lot more complex for aggregation pipeline statements than for what you can achieve simply by manipulating the document structure in code and then writing back to the target collection.

Given the existing documents:

{
        "_id" : ObjectId("59389951fc04695e84e7f4ae"),
        "id" : "1415166669",
        "color" : {
                "14" : "Silver"
        },
        "name" : "Random Name"
}
{
        "_id" : ObjectId("59389a75fc04695e84e7f4af"),
        "id" : "1415126969",
        "color" : {
                "11" : "Gold"
        },
        "name" : "Random Name 2"
}

Output from both methods is:

{
        "_id" : ObjectId("59389951fc04695e84e7f4ae"),
        "id" : "1415166669",
        "color" : "Silver",
        "name" : "Random Name"
}
{
        "_id" : ObjectId("59389a75fc04695e84e7f4af"),
        "id" : "1415126969",
        "color" : "Gold",
        "name" : "Random Name 2"
}


问:
Cannot Load Graph using Highcharts
I am using highcharts to display the graph dynamically . But my graph is not loaded . It throws the following error .

```<code>Error: Highcharts error #14: www.highcharts.com/errors/14
</code>```

I am trying the following code . In this code i passing the series data in the variables  left and right . But my Graph is not loading . If i pass the variables as static Graph is Loaded.

```<code>    var left = [];
   var right = [];

 if(($('#love').val() != '') && ($('#architectural').val() != '')){

 var rights = [[  $('#love').val() , $('#love').val() ] ,      [$('#architectural').val() ,$('#architectural').val() ]];

}

if(($('#righty').val() != '') && ($('#lefty').val() != '')){

if($('#righty').val() == 5){

   var second1 = (1 +','+ $('#right1').val() );

}else if($('#righty').val() == 4 ){

    var second1 = (2 +','+ $('#right1').val());

}else if($('#righty').val() == 3 ){

   var second1 = (3 +','+ $('#right1').val());

 }else if($('#righty').val() == 2 ){

   var second1 = (4 +','+ $('#right1').val());

 }else{

    var second1 = (5 +','+ $('#right1').val());

 }

 if($('#lefty').val() == 5){

  var first1 = ( $('#condition').val() +','+ 1 );

  }else if($('#lefty').val() == 4 ){

  var first1 = ($('#condition').val() +','+ 2);

}else if($('#lefty').val() == 3 ){

  var first1 = ($('#condition').val() +','+ 3);

}else if($('#lefty').val() == 2 ){

 var first1 = ($('#condition').val() +','+ 4);

}else{

 var first1 = ($('#condition').val() +','+ 5);

}

var lefts = [[  second1 ] , [ first1 ] ];

 }

 //var left = [[4,7],[9,2]];
 //var right = [[2,2],[4,4]];

     left.push(lefts);
      right.push(rights);

  Highcharts.chart('container', {

 title:{
    text:''
 },

 tooltip: { enabled: false },

 exporting: { enabled: false },

 credits: {enabled: false},

 plotOptions: {
    series: {
        pointStart: 1
    }
 },

xAxis: {
    max: 10,
    min: 1,
    tickInterval: 1
},

 yAxis: {
    max: 10,
    min: 1,
    tickInterval: 1,

  plotLines: [{
  color: 'black',
  value: 5.5,
  width: 2

  }],

},

  series: [{
    showInLegend: false,
    data: left
  },
 {
   showInLegend: false,
    data: right
  }],
 });

      }

  }
</code>```

I am getting the following  graph :

答:
The reason of the issue is use strings instead of numbers.

Use

```<code>parseFloat($('#love').val())
</code>```

instead of

```<code>$('#love').val()
</code>```

and all other val()

Title: Cannot Load Graph using Highcharts

Body:
I am using highcharts to display the graph dynamically . But my graph is not loaded . It throws the following error .

Error: Highcharts error #14: www.highcharts.com/errors/14

I am trying the following code . In this code i passing the series data in the variables  left and right . But my Graph is not loading . If i pass the variables as static Graph is Loaded.

    var left = [];
   var right = [];

 if(($('#love').val() != '') && ($('#architectural').val() != '')){

 var rights = [[  $('#love').val() , $('#love').val() ] ,      [$('#architectural').val() ,$('#architectural').val() ]];

}

if(($('#righty').val() != '') && ($('#lefty').val() != '')){

if($('#righty').val() == 5){

   var second1 = (1 +','+ $('#right1').val() );

}else if($('#righty').val() == 4 ){

    var second1 = (2 +','+ $('#right1').val());

}else if($('#righty').val() == 3 ){

   var second1 = (3 +','+ $('#right1').val());

 }else if($('#righty').val() == 2 ){

   var second1 = (4 +','+ $('#right1').val());

 }else{

    var second1 = (5 +','+ $('#right1').val());

 }

 if($('#lefty').val() == 5){

  var first1 = ( $('#condition').val() +','+ 1 );

  }else if($('#lefty').val() == 4 ){

  var first1 = ($('#condition').val() +','+ 2);

}else if($('#lefty').val() == 3 ){

  var first1 = ($('#condition').val() +','+ 3);

}else if($('#lefty').val() == 2 ){

 var first1 = ($('#condition').val() +','+ 4);

}else{

 var first1 = ($('#condition').val() +','+ 5);

}

var lefts = [[  second1 ] , [ first1 ] ];

 }

 //var left = [[4,7],[9,2]];
 //var right = [[2,2],[4,4]];

     left.push(lefts);
      right.push(rights);

  Highcharts.chart('container', {

 title:{
    text:''
 },

 tooltip: { enabled: false },

 exporting: { enabled: false },

 credits: {enabled: false},

 plotOptions: {
    series: {
        pointStart: 1
    }
 },

xAxis: {
    max: 10,
    min: 1,
    tickInterval: 1
},

 yAxis: {
    max: 10,
    min: 1,
    tickInterval: 1,

  plotLines: [{
  color: 'black',
  value: 5.5,
  width: 2

  }],

},

  series: [{
    showInLegend: false,
    data: left
  },
 {
   showInLegend: false,
    data: right
  }],
 });

      }

  }

I am getting the following  graph :

Body:
The reason of the issue is use strings instead of numbers.

Use

parseFloat($('#love').val())

instead of

$('#love').val()

and all other val()


问:
sqlite3 in c++ not acknowledging my primary key
I am currently building a project of a database in sqlite3.
I've already made a function that inserts the table

```<code>t_users(username TEXT primarykey not null, password TEXT not null, email TEXT not null)
</code>```

a new row.
the problem is the function doesn't acknowledge my primary key, and it lets me add two rows with the same username.
this is my main:

```<code>#include "Database.h"
int main()
{
    DataBase db;
    bool answer = db.addNewUser("user4", "1234", "user4@gmail.com");
    return 0;
}
</code>```

and this is my addNewUser functions:

```<code>bool DataBase::addNewUser(string username, string password, string email)
{
    //not a really relevant part:
    username.insert(0, "'");
    username += "'";
    password.insert(0, "'");
    password += "'";
    email.insert(0, "'");
    email += "'";

    //this is probably the relevant part:
    char* zErrMsg;
    int rv;
    rv = sqlite3_exec(_db, ("INSERT INTO t_users(username, password, email)
    VALUES(" + username + ',' + password + ',' + email + ");").c_str(), NULL, 0, &zErrMsg);
    if (rv != SQLITE3_OK) //checking for errors that might have occured
    {
        return false;
    }
    return true;
}
</code>```

答:
That table does not have a primary key.

The first column has the name username and the type TEXT primarykey.

To get a primary key, spell it correctly as PRIMARY KEY.

Body:
I am currently building a project of a database in sqlite3.
I've already made a function that inserts the table

t_users(username TEXT primarykey not null, password TEXT not null, email TEXT not null)

a new row.
the problem is the function doesn't acknowledge my primary key, and it lets me add two rows with the same username.
this is my main:

#include "Database.h"
int main()
{
    DataBase db;
    bool answer = db.addNewUser("user4", "1234", "user4@gmail.com");
    return 0;
}

and this is my addNewUser functions:

bool DataBase::addNewUser(string username, string password, string email)
{
    //not a really relevant part:
    username.insert(0, "'");
    username += "'";
    password.insert(0, "'");
    password += "'";
    email.insert(0, "'");
    email += "'";

    //this is probably the relevant part:
    char* zErrMsg;
    int rv;
    rv = sqlite3_exec(_db, ("INSERT INTO t_users(username, password, email)
    VALUES(" + username + ',' + password + ',' + email + ");").c_str(), NULL, 0, &zErrMsg);
    if (rv != SQLITE3_OK) //checking for errors that might have occured
    {
        return false;
    }
    return true;
}


问:
Python dictionary, lists ,join and Interpreter
join in python joins the list elements and keys in dictionaries right?.

Whenever I use join to join a list the output is in the same order as the list. I know it not ordered and the output clearly differed when i gave the same in a file and in the interpreter.

My question is how interpreter remembers that and gives the same output everytime for that order. Is it in some sort of cache or??

```<code>>>> x = ['a','b','c']
>>> ','.join(x)
'a,b,c'
>>> x = ['c','b','a']
>>> ','.join(x)
'c,b,a'
</code>```

using a dict

```<code>>>> z = {'a':3,'b':1,'c':4,'d':2}
>>> ','.join(z)
'b,d,a,c'
>>> z = {'a':3,'d':1,'c':4,'b':2}
>>> ','.join(z)
'c,d,a,b'
</code>```

So I concluded that it varies each time but when I give the same dictionary with a specific order after several instructions it still displays the output in some order which is the same everytime in the interpreter!

```<code>>>> z = {'foo':3,'bar':1,'egg':4,'spam':2}
>>> ','.join(z)
'egg,bar,foo,spam'
>>> z = {'bar':3,'foo':1,'egg':4,'spam':2}
>>> ','.join(z)
'egg,bar,foo,spam'
>>> z = {'bar':3,'foo':1,'spam':4,'egg':2}
>>> ','.join(z)
'spam,bar,foo,egg'
>>> z = {'foo':3,'bar':1,'egg':4,'spam':2}
>>> ','.join(z)
'egg,bar,foo,spam'
</code>```

I maybe missing something out but how does the interpreter remember it. Clear explanations would help greatly.

NOTE: As seen in the comments mentioned by chris_rands
I quote 'the dict iteration is fixed within an interpreter session because the environmental variable PYTHONHASHSEED is fixed'

is more along the lines of the answer I am looking for. Explanations would be great!.

答:
You can use sortedcontainers, and then join

```<code>from sortedcontainers import SortedDict
z={'egg': 4, 'foo': 3, 'bar': 1, 'spam': 2}
','.join(SortedDict(z))
#'bar,egg,foo,spam'
</code>```

in natural case :

```<code>','.join(dict(SortedDict(z)))   #or   ','.join(z)
#'egg,foo,bar,spam'
</code>```

Body:
join in python joins the list elements and keys in dictionaries right?.

Whenever I use join to join a list the output is in the same order as the list. I know it not ordered and the output clearly differed when i gave the same in a file and in the interpreter.

My question is how interpreter remembers that and gives the same output everytime for that order. Is it in some sort of cache or??

>>> x = ['a','b','c']
>>> ','.join(x)
'a,b,c'
>>> x = ['c','b','a']
>>> ','.join(x)
'c,b,a'

using a dict

>>> z = {'a':3,'b':1,'c':4,'d':2}
>>> ','.join(z)
'b,d,a,c'
>>> z = {'a':3,'d':1,'c':4,'b':2}
>>> ','.join(z)
'c,d,a,b'

So I concluded that it varies each time but when I give the same dictionary with a specific order after several instructions it still displays the output in some order which is the same everytime in the interpreter!

>>> z = {'foo':3,'bar':1,'egg':4,'spam':2}
>>> ','.join(z)
'egg,bar,foo,spam'
>>> z = {'bar':3,'foo':1,'egg':4,'spam':2}
>>> ','.join(z)
'egg,bar,foo,spam'
>>> z = {'bar':3,'foo':1,'spam':4,'egg':2}
>>> ','.join(z)
'spam,bar,foo,egg'
>>> z = {'foo':3,'bar':1,'egg':4,'spam':2}
>>> ','.join(z)
'egg,bar,foo,spam'

I maybe missing something out but how does the interpreter remember it. Clear explanations would help greatly.

NOTE: As seen in the comments mentioned by chris_rands
I quote 'the dict iteration is fixed within an interpreter session because the environmental variable PYTHONHASHSEED is fixed'

is more along the lines of the answer I am looking for. Explanations would be great!.

Body:
You can use sortedcontainers, and then join

from sortedcontainers import SortedDict
z={'egg': 4, 'foo': 3, 'bar': 1, 'spam': 2}
','.join(SortedDict(z))
#'bar,egg,foo,spam'

in natural case :

','.join(dict(SortedDict(z)))   #or   ','.join(z)
#'egg,foo,bar,spam'


问:
How to find how many web pages Nutch crawled?
At the end of a Nutch crawl, is it possible to find or determine how many web pages Nutch actually crawled? </p>

答:
You can use readdb

```<code>bin/nutch readdb crawl/crawldb -stats
</code>```

Example : bin/nutch readdb crawl/dabfolder/crawldb -stats

Output will be like :

```<code>Statistics for CrawlDb: crawl/dabfolder/crawldb/
TOTAL urls: 563390
shortest fetch interval:    30 days, 00:00:00
avg fetch interval: 30 days, 00:43:49
longest fetch interval: 45 days, 00:00:00
earliest fetch time:    Fri Jun 02 11:57:00 IST 2017
avg of fetch times: Sun Jun 04 14:46:00 IST 2017
latest fetch time:  Mon Jul 17 11:54:00 IST 2017
retry 0:    560279
retry 1:    3111
min score:  0.0
avg score:  0.1028828
max score:  195.854
status 1 (db_unfetched):    524278
status 2 (db_fetched):  17615
status 3 (db_gone): 1143
status 4 (db_redir_temp):   8428
status 5 (db_redir_perm):   11800
status 7 (db_duplicate):    126
CrawlDb statistics: done
</code>```

Body:
You can use readdb

bin/nutch readdb crawl/crawldb -stats

Example : bin/nutch readdb crawl/dabfolder/crawldb -stats

Output will be like :

Statistics for CrawlDb: crawl/dabfolder/crawldb/
TOTAL urls: 563390
shortest fetch interval:    30 days, 00:00:00
avg fetch interval: 30 days, 00:43:49
longest fetch interval: 45 days, 00:00:00
earliest fetch time:    Fri Jun 02 11:57:00 IST 2017
avg of fetch times: Sun Jun 04 14:46:00 IST 2017
latest fetch time:  Mon Jul 17 11:54:00 IST 2017
retry 0:    560279
retry 1:    3111
min score:  0.0
avg score:  0.1028828
max score:  195.854
status 1 (db_unfetched):    524278
status 2 (db_fetched):  17615
status 3 (db_gone): 1143
status 4 (db_redir_temp):   8428
status 5 (db_redir_perm):   11800
status 7 (db_duplicate):    126
CrawlDb statistics: done


问:
JQUERY: How to reduce code if i have multiple fields that i control validation
For example i have 3 function that i control the keydown of each field; at the end i control the same so i want to put the 3 fields with code 1 time only.</p>

```<code>ens_q_frio.keydown(function (event) {

    if (event.shiftKey == true) {
        event.preventDefault();
    }

    if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46 || event.keyCode == 190) {

    } else {
        event.preventDefault();
    }

    if ($(this).val().indexOf('.') !== -1 && event.keyCode == 190)
        event.preventDefault();
});

ens_q_cal.keydown(function (event) {

    if (event.shiftKey == true) {
        event.preventDefault();
    }

    if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46 || event.keyCode == 190) {

    } else {
        event.preventDefault();
    }

    if ($(this).val().indexOf('.') !== -1 && event.keyCode == 190)
        event.preventDefault();
});

ens_t_frio.keydown(function (event) {

    if (event.shiftKey == true) {
        event.preventDefault();
    }

    if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46 || event.keyCode == 190) {

    } else {
        event.preventDefault();
    }

    if ($(this).val().indexOf('.') !== -1 && event.keyCode == 190)
        event.preventDefault();
});
</code>```

答:
you can put it in a function and have it on each event handler.

$(function(){
  $("#ens_q_frio").keydown(function(event){
     KeyDownEvent("ens_q_frio", event);
  });

  $("#ens_q_cal").keydown(function(event){
    KeyDownEvent("ens_q_cal", event);
  });

   $("#ens_t_frio").keydown(function(event){
    KeyDownEvent("ens_t_frio", event);
   });
})

function KeyDownEvent(txtBox, event){
  if (event.shiftKey == true) {
    event.preventDefault();
  }

  if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46 || event.keyCode == 190) {

  }
  else {
    event.preventDefault();
  }

  if($("#" + txtBox).val().indexOf('.') !== -1 && event.keyCode == 190)
    event.preventDefault();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="ens_q_frio"/>
<input type="text" id="ens_q_cal"/>
<input type="text" id="ens_t_frio"/></code>```

Body:
For example i have 3 function that i control the keydown of each field; at the end i control the same so i want to put the 3 fields with code 1 time only.

ens_q_frio.keydown(function (event) {

    if (event.shiftKey == true) {
        event.preventDefault();
    }

    if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46 || event.keyCode == 190) {

    } else {
        event.preventDefault();
    }

    if ($(this).val().indexOf('.') !== -1 && event.keyCode == 190)
        event.preventDefault();
});

ens_q_cal.keydown(function (event) {

    if (event.shiftKey == true) {
        event.preventDefault();
    }

    if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46 || event.keyCode == 190) {

    } else {
        event.preventDefault();
    }

    if ($(this).val().indexOf('.') !== -1 && event.keyCode == 190)
        event.preventDefault();
});

ens_t_frio.keydown(function (event) {

    if (event.shiftKey == true) {
        event.preventDefault();
    }

    if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46 || event.keyCode == 190) {

    } else {
        event.preventDefault();
    }

    if ($(this).val().indexOf('.') !== -1 && event.keyCode == 190)
        event.preventDefault();
});

Body:
you can put it in a function and have it on each event handler.

$(function(){
  $("#ens_q_frio").keydown(function(event){
     KeyDownEvent("ens_q_frio", event);
  });

  $("#ens_q_cal").keydown(function(event){
    KeyDownEvent("ens_q_cal", event);
  });

   $("#ens_t_frio").keydown(function(event){
    KeyDownEvent("ens_t_frio", event);
   });
})

function KeyDownEvent(txtBox, event){
  if (event.shiftKey == true) {
    event.preventDefault();
  }

  if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46 || event.keyCode == 190) {

  }
  else {
    event.preventDefault();
  }

  if($("#" + txtBox).val().indexOf('.') !== -1 && event.keyCode == 190)
    event.preventDefault();
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="ens_q_frio"/>
<input type="text" id="ens_q_cal"/>
<input type="text" id="ens_t_frio"/>


问:
Focus on textbox after a keyevent
What I am trying to achieve is  :

On Alt it should show a span which would tell user that if c is pressed now, the textbox will be on focus

Or on Alt + c it should focus. (this works)

Issue :
When Alt is pressed span shows, and when c is followed nothing happens. But if I press c after I click somewhere on the page it sets the focus. Why is that? And how do i fix this?

Below is what I have.

var lastKey;
$(document).on("keydown", function(e) {
  e.stopPropagation();
  if (e.altKey) {
    $(".shortcut").fadeIn("slow");
    if (e.keyCode == 67) { // c
      console.log("filter should open");
      $(".shortcut").fadeOut("slow");
      $("#item").focus()
      e.preventDefault();
      return false;
    }

  }
  if (lastKey && e.keyCode == 67) { // c
    $(".shortcut").fadeOut("slow");
    $("#item").focus()
    e.preventDefault();
    lastKey = false;
    return false;
  }
  lastKey = true;
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.shortcut {
  display: none;
}

.inputgroup-shortcut {
  position: absolute;
  //top: 25%;
  padding: 3px 5px;
  background: #428bca;
  border-radius: 4px;
  color: white;
  line-height: 1.0;
  font-size: 9px;
  font-weight: bold;
  left: 0px;
  z-index: 100;
}</code>```

c
<input type="text" id="item" />```

答:
You need to add e.preventDefault() to prevent alt key from performing it's default action in the browser i.e to show the menu bar in the browser.

var lastKey;
$(document).on("keydown", function(e) {
  e.stopPropagation();
  if (e.altKey) {
    $(".shortcut").fadeIn("slow");
    e.preventDefault();
    if (e.keyCode == 67) { // c
      console.log("filter should open");
      $(".shortcut").fadeOut("slow");
      $("#item").focus()
      e.preventDefault();
      return false;
    }

  }
  if (lastKey && e.keyCode == 67) { // c
    $(".shortcut").fadeOut("slow");
    $("#item").focus()
    e.preventDefault();
    lastKey = false;
    return false;
  }
  lastKey = true;
});
```

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var lastKey;
$(document).on("keydown", function(e) {
  e.stopPropagation();
  if (e.altKey) {
    $(".shortcut").fadeIn("slow");
    e.preventDefault();
    if (e.keyCode == 67) { // c
      console.log("filter should open");
      $(".shortcut").fadeOut("slow");
      $("#item").focus()
      e.preventDefault();
      return false;
    }

  }
  if (lastKey && e.keyCode == 67) { // c
    $(".shortcut").fadeOut("slow");
    $("#item").focus()
    e.preventDefault();
    lastKey = false;
    return false;
  }
  lastKey = true;
});</code>```

.shortcut {
  display: none;
}

.inputgroup-shortcut {
  position: absolute;
  //top: 25%;
  padding: 3px 5px;
  background: #428bca;
  border-radius: 4px;
  color: white;
  line-height: 1.0;
  font-size: 9px;
  font-weight: bold;
  left: 0px;
  z-index: 100;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="shortcut inputgroup-shortcut">c</span>
<input type="text" id="item" /></code>```

Title: Focus on textbox after a keyevent

Body:
What I am trying to achieve is  :

On Alt it should show a span which would tell user that if c is pressed now, the textbox will be on focus

Or on Alt + c it should focus. (this works)

Issue :
When Alt is pressed span shows, and when c is followed nothing happens. But if I press c after I click somewhere on the page it sets the focus. Why is that? And how do i fix this?

Below is what I have.

var lastKey;
$(document).on("keydown", function(e) {
  e.stopPropagation();
  if (e.altKey) {
    $(".shortcut").fadeIn("slow");
    if (e.keyCode == 67) { // c
      console.log("filter should open");
      $(".shortcut").fadeOut("slow");
      $("#item").focus()
      e.preventDefault();
      return false;
    }

  }
  if (lastKey && e.keyCode == 67) { // c
    $(".shortcut").fadeOut("slow");
    $("#item").focus()
    e.preventDefault();
    lastKey = false;
    return false;
  }
  lastKey = true;
});

.shortcut {
  display: none;
}

.inputgroup-shortcut {
  position: absolute;
  //top: 25%;
  padding: 3px 5px;
  background: #428bca;
  border-radius: 4px;
  color: white;
  line-height: 1.0;
  font-size: 9px;
  font-weight: bold;
  left: 0px;
  z-index: 100;
}

c
<input type="text" id="item" />

Body:
You need to add e.preventDefault() to prevent alt key from performing it's default action in the browser i.e to show the menu bar in the browser.

var lastKey;
$(document).on("keydown", function(e) {
  e.stopPropagation();
  if (e.altKey) {
    $(".shortcut").fadeIn("slow");
    e.preventDefault();
    if (e.keyCode == 67) { // c
      console.log("filter should open");
      $(".shortcut").fadeOut("slow");
      $("#item").focus()
      e.preventDefault();
      return false;
    }

  }
  if (lastKey && e.keyCode == 67) { // c
    $(".shortcut").fadeOut("slow");
    $("#item").focus()
    e.preventDefault();
    lastKey = false;
    return false;
  }
  lastKey = true;
});

var lastKey;
$(document).on("keydown", function(e) {
  e.stopPropagation();
  if (e.altKey) {
    $(".shortcut").fadeIn("slow");
    e.preventDefault();
    if (e.keyCode == 67) { // c
      console.log("filter should open");
      $(".shortcut").fadeOut("slow");
      $("#item").focus()
      e.preventDefault();
      return false;
    }

  }
  if (lastKey && e.keyCode == 67) { // c
    $(".shortcut").fadeOut("slow");
    $("#item").focus()
    e.preventDefault();
    lastKey = false;
    return false;
  }
  lastKey = true;
});

.shortcut {
  display: none;
}

.inputgroup-shortcut {
  position: absolute;
  //top: 25%;
  padding: 3px 5px;
  background: #428bca;
  border-radius: 4px;
  color: white;
  line-height: 1.0;
  font-size: 9px;
  font-weight: bold;
  left: 0px;
  z-index: 100;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="shortcut inputgroup-shortcut">c</span>
<input type="text" id="item" />

ContentLicense: CC BY-SA 4.0


问:
Angular Radio Buttons Multiple Forms
I'm having a hell of a time with Radio buttons. Happy Tuesday.

I have multiple names, a form for each name, and the ability to select a name as a "primary name". Each name can be edited and submitted independently. When a name is selected as "primary" (1) the others are set to 0.

In the function updatePrimary(), I have it setting the correct name's primary_name value to 1, and the rest to 0. But the other radio buttons are not un-selecting their radio buttons (well there should only be one other selected anyway).

Like this :

```<code><ng-include src="'app/names/__edit.html'" ng-repeat="name in names track by $index"></ng-include>

<!-- __edit.html -->
<form name="names[$index]">
    <input name="primary_name" class="form-control" type="radio" ng-click="updatePrimary($index)" ng-model="name.primary_name" ng-value="name.primary_name" ng-checked="<% name.primary_name == 1 %>"/>
</form>
</code>```

What I don't understand is where I'm binding name.primary_name to the button, giving it the condition to be checked (== 1), then why when I update the model is the display not updating? Just to reiterate, it's correct in the model, this is a UI / binding issue.

Another thing to note - I have a button to save, that's enabled when the form is dirty. Selecting the radio button does not trigger this. The button is as such :

```<code><button class="name-save" ng-disabled="names[$index].$pristine" ng-click="save($index)">Save</button>
</code>```

答:
Try this :

```<code><ng-include src="'app/names/__edit.html'" ng-repeat="name in names track by $index"></ng-include>

<!-- __edit.html -->
<form name="names[$index]">
<input id="radio_{{$index}}" name="primary_name" class="form-control" type="radio" ng-click="updatePrimary($index)" ng-model="name.primary_name" ng-value="name.primary_name" ng-checked="<% name.primary_name == 1 %>"/>
</code>```

Using a dynamic id on the radio input fields should solve the problem.

Also keep in mind that ng-repeat does not work on forms. Forms will not get repeated. You have to use ng-form to repeat forms.

Title: Angular Radio Buttons Multiple Forms

Body:
I'm having a hell of a time with Radio buttons. Happy Tuesday.

I have multiple names, a form for each name, and the ability to select a name as a "primary name". Each name can be edited and submitted independently. When a name is selected as "primary" (1) the others are set to 0.

In the function updatePrimary(), I have it setting the correct name's primary_name value to 1, and the rest to 0. But the other radio buttons are not un-selecting their radio buttons (well there should only be one other selected anyway).

Like this :

<ng-include src="'app/names/__edit.html'" ng-repeat="name in names track by $index"></ng-include>

<form name="names[$index]">
    <input name="primary_name" class="form-control" type="radio" ng-click="updatePrimary($index)" ng-model="name.primary_name" ng-value="name.primary_name" ng-checked="<% name.primary_name == 1 %>"/>
</form>

What I don't understand is where I'm binding name.primary_name to the button, giving it the condition to be checked (== 1), then why when I update the model is the display not updating? Just to reiterate, it's correct in the model, this is a UI / binding issue.

Another thing to note - I have a button to save, that's enabled when the form is dirty. Selecting the radio button does not trigger this. The button is as such :

<button class="name-save" ng-disabled="names[$index].$pristine" ng-click="save($index)">Save</button>

Body:
Try this :

<ng-include src="'app/names/__edit.html'" ng-repeat="name in names track by $index"></ng-include>

<!-- __edit.html -->
<form name="names[$index]">
<input id="radio_{{$index}}" name="primary_name" class="form-control" type="radio" ng-click="updatePrimary($index)" ng-model="name.primary_name" ng-value="name.primary_name" ng-checked="<% name.primary_name == 1 %>"/>

Using a dynamic id on the radio input fields should solve the problem.

Also keep in mind that ng-repeat does not work on forms. Forms will not get repeated. You have to use ng-form to repeat forms.


问:
Do VLookup IF condition is met
I'm trying to get a VLookup to run on specific rows within my spreadsheet. The sheet is generated automatically, so manually entering the VLookup into specific rows is an issue because the ones I am needing change from time to time.

I have a test IF statement (shown below) that works perfectly fine.

```<code>=IF(LEFT(A3,6)="200301","Yes","No")
</code>```

Here is my VLookup that works too.

```<code>=L4*IFERROR(VLOOKUP($I4,INDIRECT("data!weights"),2,FALSE),0)
</code>```

I am trying to get the VLookup to run in the 'Value_If_True' section of the IF statement.

Thanks in advance

答:
If I understand your question, you literally have to put the 2nd formula in the "Yes" part of your 1st formula.

```<code>=IF(LEFT(A3,6)="200301",L4*IFERROR(VLOOKUP($I4,INDIRECT("data!weights"),2,FALSE),0),"No")
</code>```

Title: Do VLookup IF condition is met

Body:
I'm trying to get a VLookup to run on specific rows within my spreadsheet. The sheet is generated automatically, so manually entering the VLookup into specific rows is an issue because the ones I am needing change from time to time.

I have a test IF statement (shown below) that works perfectly fine.

=IF(LEFT(A3,6)="200301","Yes","No")

Here is my VLookup that works too.

=L4*IFERROR(VLOOKUP($I4,INDIRECT("data!weights"),2,FALSE),0)

I am trying to get the VLookup to run in the 'Value_If_True' section of the IF statement.

Thanks in advance

Body:
If I understand your question, you literally have to put the 2nd formula in the "Yes" part of your 1st formula.

=IF(LEFT(A3,6)="200301",L4*IFERROR(VLOOKUP($I4,INDIRECT("data!weights"),2,FALSE),0),"No")


问:
Position of All Matching Elements in List
I'm trying to write a function in Common Lisp similar to the built in position function, that returns a list of the positions of all elements in the haystack that match the needle, as opposed to just the first. I've come up with a few possible solutions (for example recursively searching for the next element using a cdr-from function on the position and adding the result to the previous position) but none of the approaches I've come up with so far seem particularly elegant.

Can anyone suggest what would be the best way of approaching this, as I'm currently struggling.

答:
Here's another (not necessarily better) way to do it.</p>

```<code>(defun get-positions (needle haystack)
  (let ((result nil))
    (dotimes (i (length haystack))
      (if (eq (nth i haystack) needle)
          (push i result)))
    (nreverse result)))
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Here's another (not necessarily better) way to do it.

(defun get-positions (needle haystack)
  (let ((result nil))
    (dotimes (i (length haystack))
      (if (eq (nth i haystack) needle)
          (push i result)))
    (nreverse result)))


问:
Aggregate functions with EF repository
Lets say that I have a products catalog MVC web application that utilizes EF 6.0 where all CRUD operations are handled by repositories. Now, one of the views has to show a List of Categories along with some aggregate information about Products from that Category, I mean that next to Category name column should appear three columns with total count of products from that category, along with minimum and maximum prices of products.

```<code>public class Product
{
    public string   Name    { get; set; }
    public decimal  Price   { get; set; }
    public int      CategoryId             { get; set; }
    public virtual  Category    Category   { get; set; }
}

public class Category
{
    public string   Name    { get; set; }
    public virtual  ICollection<Product>   Products   { get; set; }
}
</code>```

Then if I have a repository of Bakery products

```<code>unitOfWork.ProductRepository.Insert(new Product(){Name="Doughnut", Price=4.0, CategoryId=1});
unitOfWork.ProductRepository.Insert(new Product(){Name="Apple Pie", Price=7.0, CategoryId=1});
unitOfWork.ProductRepository.Insert(new Product(){Name="Meat Pie", Price=9.0, CategoryId=1});
</code>```

I need the view to show

```<code>#  Category        Total Products        Min Price        Max Price
1  Bakery products 3                     4                9
</code>```

I don't believe that it is a bright idea to handle out of the repository the query, since it ruins all the idea of using repositories, and AFAIK it's widely recognized as a bad practice.

Some queries that utilize the DbContext directly could be written but I wanted to know how this type of tasks is handled in real world applications?
Maybe a new view model is required and then another read-only repository should be added that will get this data? Something like this?

```<code>public class CategoryStatsVM
{
    public string   Name    { get; set; }
    public virtual  ICollection<Product>   Products   { get; set; }
    public int      Count   { get; set; }
    public decimal  MinPrice    { get; set; }
    public decimal  MaxPrice    { get; set; }
}
</code>```

答:
You can use the Aggregate function like this to get the UserLogs last logging of transaction file</p>

```<code>UsersLogs.Where(i => i.Id== _id).Max(x => x.transId)
</code>```

Title: Aggregate functions with EF repository

Body:
Lets say that I have a products catalog MVC web application that utilizes EF 6.0 where all CRUD operations are handled by repositories. Now, one of the views has to show a List of Categories along with some aggregate information about Products from that Category, I mean that next to Category name column should appear three columns with total count of products from that category, along with minimum and maximum prices of products.

public class Product
{
    public string   Name    { get; set; }
    public decimal  Price   { get; set; }
    public int      CategoryId             { get; set; }
    public virtual  Category    Category   { get; set; }
}

public class Category
{
    public string   Name    { get; set; }
    public virtual  ICollection<Product>   Products   { get; set; }
}

Then if I have a repository of Bakery products

unitOfWork.ProductRepository.Insert(new Product(){Name="Doughnut", Price=4.0, CategoryId=1});
unitOfWork.ProductRepository.Insert(new Product(){Name="Apple Pie", Price=7.0, CategoryId=1});
unitOfWork.ProductRepository.Insert(new Product(){Name="Meat Pie", Price=9.0, CategoryId=1});

I need the view to show

#  Category        Total Products        Min Price        Max Price
1  Bakery products 3                     4                9

I don't believe that it is a bright idea to handle out of the repository the query, since it ruins all the idea of using repositories, and AFAIK it's widely recognized as a bad practice.

Some queries that utilize the DbContext directly could be written but I wanted to know how this type of tasks is handled in real world applications?
Maybe a new view model is required and then another read-only repository should be added that will get this data? Something like this?

public class CategoryStatsVM
{
    public string   Name    { get; set; }
    public virtual  ICollection<Product>   Products   { get; set; }
    public int      Count   { get; set; }
    public decimal  MinPrice    { get; set; }
    public decimal  MaxPrice    { get; set; }
}

Body:
You can use the Aggregate function like this to get the UserLogs last logging of transaction file

UsersLogs.Where(i => i.Id== _id).Max(x => x.transId)


问:
Sending a system exclusive message using CoreMIDI
I'm working on a MacOS app where I'm utilizing MIDI. What I'd like to do is send s SysEx message to a MIDI device. Now, I've done this once in Java, but never in Swift.

And since the coremidi library is almost totally new to me, i have no idea how this would work. What I've figured out so far is that I have to compose a MIDISysexSendRequest, and I've come this far:

```<code>let SysEx = MIDISysexSendRequest(destination: self.endpointRef, data: UnsafePointer<UInt8>, bytesToSend: 8, complete: complete, reserved: (UInt8, UInt8, UInt8), completionProc: completionProc, completionRefCon: nil)
</code>```

In this, there are a few things that confuse me:

In what way am i supposed to compose the data variable? I know what bytes i want to send, just not how to format this for Swift

What is reserved supposed to be?

I couldn't find any examples or reference on these that i could use. Could someone help me/

Thanks in advance.

答:
Reserved means you can't use it, as in: "reserved for internal use"

```<code>struct MIDISysexSendRequest
{
    MIDIEndpointRef     destination;
    const Byte *        data;
    UInt32              bytesToSend;
    Boolean             complete;
    Byte                reserved[3];
    MIDICompletionProc  completionProc;
    void * __nullable   completionRefCon;
};

/*!
    @struct         MIDISysexSendRequest
    @abstract       A request to transmit a system-exclusive event.

    @field          destination
                        The endpoint to which the event is to be sent.
    @field          data
                        Initially, a pointer to the sys-ex event to be sent.
                        MIDISendSysex will advance this pointer as bytes are
                        sent.
    @field          bytesToSend
                        Initially, the number of bytes to be sent.  MIDISendSysex
                        will decrement this counter as bytes are sent.
    @field          complete
                        The client may set this to true at any time to abort
                        transmission.  The implementation sets this to true when
                        all bytes have been sent.
    @field          completionProc
                        Called when all bytes have been sent, or after the client
                        has set complete to true.
    @field          completionRefCon
                        Passed as a refCon to completionProc.

    @discussion
        This represents a request to send a single system-exclusive MIDI event to
        a MIDI destination asynchronously.
*/
</code>```

Notice how the reserved variable doesn't even show up in the header.

A quick google shows many projects written in swift that use MIDI. Browse through some of these to see working examples.

The first one I looked at seemed perfect for seeing how things are done. It even has quite a few .java files, so it might be easier for you to see how it relates to swift (or how to connect them).

Take a look here: MIDI in Swift

In the CoreMIDI framework there is a file called "MIDIServices.h" (finder will find it for you).  It has a LOT of information regarding MIDI.

Best of luck!!

Body:
I'm working on a MacOS app where I'm utilizing MIDI. What I'd like to do is send s SysEx message to a MIDI device. Now, I've done this once in Java, but never in Swift.

And since the coremidi library is almost totally new to me, i have no idea how this would work. What I've figured out so far is that I have to compose a MIDISysexSendRequest, and I've come this far:

let SysEx = MIDISysexSendRequest(destination: self.endpointRef, data: UnsafePointer<UInt8>, bytesToSend: 8, complete: complete, reserved: (UInt8, UInt8, UInt8), completionProc: completionProc, completionRefCon: nil)

In this, there are a few things that confuse me:

In what way am i supposed to compose the data variable? I know what bytes i want to send, just not how to format this for Swift

What is reserved supposed to be?

I couldn't find any examples or reference on these that i could use. Could someone help me/

Thanks in advance.

Body:
Reserved means you can't use it, as in: "reserved for internal use"

struct MIDISysexSendRequest
{
    MIDIEndpointRef     destination;
    const Byte *        data;
    UInt32              bytesToSend;
    Boolean             complete;
    Byte                reserved[3];
    MIDICompletionProc  completionProc;
    void * __nullable   completionRefCon;
};

/*!
    @struct         MIDISysexSendRequest
    @abstract       A request to transmit a system-exclusive event.

    @field          destination
                        The endpoint to which the event is to be sent.
    @field          data
                        Initially, a pointer to the sys-ex event to be sent.
                        MIDISendSysex will advance this pointer as bytes are
                        sent.
    @field          bytesToSend
                        Initially, the number of bytes to be sent.  MIDISendSysex
                        will decrement this counter as bytes are sent.
    @field          complete
                        The client may set this to true at any time to abort
                        transmission.  The implementation sets this to true when
                        all bytes have been sent.
    @field          completionProc
                        Called when all bytes have been sent, or after the client
                        has set complete to true.
    @field          completionRefCon
                        Passed as a refCon to completionProc.

    @discussion
        This represents a request to send a single system-exclusive MIDI event to
        a MIDI destination asynchronously.
*/

Notice how the reserved variable doesn't even show up in the header.

A quick google shows many projects written in swift that use MIDI. Browse through some of these to see working examples.

The first one I looked at seemed perfect for seeing how things are done. It even has quite a few .java files, so it might be easier for you to see how it relates to swift (or how to connect them).

Take a look here: MIDI in Swift

In the CoreMIDI framework there is a file called "MIDIServices.h" (finder will find it for you).  It has a LOT of information regarding MIDI.

Best of luck!!


问:
CSS/HTML5: How to adjust div tag height equal to browser window's current height?
I want the height of my div tag exactly equal to the height of the browser's window. So if you resize the browser the  should adjust automatically.
So what should I set my height equal to in CSS.

I have tried

```<code>.class {
  height: 100%;
}
</code>```

Doesn't work.

em, rem, vh, wh apparently only work with the font.

If I however, hard-code the body tag to some amount of pixels, then the percentage works for the children tags but this is not dynamic.

What I want: Just as I am viewing this stack page in my browser. I wish when I resize the browser I still get the same amount of page viewership, only resized for the new size (responsive).

Thanks.

答:
You need to add

```<code>html, body {
  width: 100%;
  margin: 0;
}
</code>```

to set a height reference for the DIV (any DIV is a child of another element, a DIV without another container is a child of body, which is a child of html)

Body:
I want the height of my div tag exactly equal to the height of the browser's window. So if you resize the browser the  should adjust automatically.
So what should I set my height equal to in CSS.

I have tried

.class {
  height: 100%;
}

Doesn't work.

em, rem, vh, wh apparently only work with the font.

If I however, hard-code the body tag to some amount of pixels, then the percentage works for the children tags but this is not dynamic.

What I want: Just as I am viewing this stack page in my browser. I wish when I resize the browser I still get the same amount of page viewership, only resized for the new size (responsive).

Thanks.

Body:
You need to add

html, body {
  width: 100%;
  margin: 0;
}

to set a height reference for the DIV (any DIV is a child of another element, a DIV without another container is a child of body, which is a child of html)


问:
IllegalStateException: Activity has been destroyed - when app is trying to show DialogFragment once more time
I have found a lot of similar questions on the stackoverflow but their solutions don't work in my case. They are connected with onSaveInstanceState method and the Support Library especially.

I have Activity which runs on one event this code:

```<code>MyDialogFragment.showMyDialog(name, this, this);
</code>```

name parameter is the String object. Second parameter (this) is the just Activity class object and the third one (also this) is the simple interface. This my Activity implements this interface. showMyDialog() is of course static method. This is it body:

```<code>MyDialogFragment fragment = new MyDialogFragment(listener, "Hello " + name);
fragment.show(activity.getFragmentManager(), "myDialog");
</code>```

This is working good at the first try. But at the second I am getting this exception:

```<code>E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.myapp, PID: 20759
java.lang.IllegalStateException: Activity has been destroyed
        at android.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1345)
        at android.app.BackStackRecord.commitInternal(BackStackRecord.java:597)
        at android.app.BackStackRecord.commit(BackStackRecord.java:575)
        at android.app.DialogFragment.show(DialogFragment.java:230)
        at com.example.myapp.view.dialog.MyDialogFragment.showMyDialog(MyDialogFragment.java:41)
        at com.example.myapp.MyActivity.showMyDialog(MyActivity.java:208)
        at com.example.myapp.MyActivity.onEvent(MyActivity.java:232)
        at com.example.myapp.MyActivity.handleMessage(MyActivity.java:89)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5017)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
        at dalvik.system.NativeStart.main(Native Method)
</code>```

In general this is the steps to reproduce my exception:

Enter Activity - event is received so MyDialogFragment is shown.

Dismiss dialog by negative button.

Enter Activity once more time - MyDialogFragment is shown again.

Type some code to the EditText.

At this moment validation take some time. Connecting with server etc. And the negative result is returned. So it is need to show MyDialogFragment once more. But at this moment I am getting exception.

However, when I skip the second point and start to typing wrong code for validation, MyDialogFragment will be shown without any issue. Strange behaviour.

I have tried with non-static method, setRetainInstance(true) and also commitAllowingStateLoss. But there was no difference.

答:
I had the same error while I was trying to add a SupportMapFragment within a DialogFragment. I could fix this error by using getChildFramentManager() instead of getFragmentManager(), as suggested by the API when using nested fragments:

```<code>public class GpsDialogFragment extends DialogFragment {
    private SupportMapFragment mapFragment;
    private static final String MAP_FRAGMENT_TAG = "MAP_FRAGMENT";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.gps_postition_dialog, container, false);
        // ...

        // dynamically create the map fragment (https://stackoverflow.com/questions/14083950)
        FragmentManager fragmentManager = getChildFragmentManager();
        mapFragment = (SupportMapFragment) fragmentManager.findFragmentByTag(MAP_FRAGMENT_TAG);
        if (mapFragment == null) {
            if (!getActivity().isFinishing()) {
                mapFragment = new SupportMapFragment();
                FragmentTransaction ft = fragmentManager.beginTransaction();
                ft.add(R.id.mapFrame, mapFragment, MAP_FRAGMENT_TAG);
                ft.commit();
                fragmentManager.executePendingTransactions();
            }
        }

        return view;
    }

    // ...

    @Override
    public void onPause() {
        if (mapFragment != null)
            getChildFragmentManager().beginTransaction().remove(mapFragment).commit();
        super.onPause();
    }
}
</code>```

Body:
I have found a lot of similar questions on the stackoverflow but their solutions don't work in my case. They are connected with onSaveInstanceState method and the Support Library especially.

I have Activity which runs on one event this code:

MyDialogFragment.showMyDialog(name, this, this);

name parameter is the String object. Second parameter (this) is the just Activity class object and the third one (also this) is the simple interface. This my Activity implements this interface. showMyDialog() is of course static method. This is it body:

MyDialogFragment fragment = new MyDialogFragment(listener, "Hello " + name);
fragment.show(activity.getFragmentManager(), "myDialog");

This is working good at the first try. But at the second I am getting this exception:

E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.myapp, PID: 20759
java.lang.IllegalStateException: Activity has been destroyed
        at android.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1345)
        at android.app.BackStackRecord.commitInternal(BackStackRecord.java:597)
        at android.app.BackStackRecord.commit(BackStackRecord.java:575)
        at android.app.DialogFragment.show(DialogFragment.java:230)
        at com.example.myapp.view.dialog.MyDialogFragment.showMyDialog(MyDialogFragment.java:41)
        at com.example.myapp.MyActivity.showMyDialog(MyActivity.java:208)
        at com.example.myapp.MyActivity.onEvent(MyActivity.java:232)
        at com.example.myapp.MyActivity.handleMessage(MyActivity.java:89)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5017)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
        at dalvik.system.NativeStart.main(Native Method)

In general this is the steps to reproduce my exception:

Enter Activity - event is received so MyDialogFragment is shown.

Dismiss dialog by negative button.

Enter Activity once more time - MyDialogFragment is shown again.

Type some code to the EditText.

At this moment validation take some time. Connecting with server etc. And the negative result is returned. So it is need to show MyDialogFragment once more. But at this moment I am getting exception.

However, when I skip the second point and start to typing wrong code for validation, MyDialogFragment will be shown without any issue. Strange behaviour.

I have tried with non-static method, setRetainInstance(true) and also commitAllowingStateLoss. But there was no difference.

Body:
I had the same error while I was trying to add a SupportMapFragment within a DialogFragment. I could fix this error by using getChildFramentManager() instead of getFragmentManager(), as suggested by the API when using nested fragments:

public class GpsDialogFragment extends DialogFragment {
    private SupportMapFragment mapFragment;
    private static final String MAP_FRAGMENT_TAG = "MAP_FRAGMENT";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.gps_postition_dialog, container, false);
        // ...

        // dynamically create the map fragment (https://stackoverflow.com/questions/14083950)
        FragmentManager fragmentManager = getChildFragmentManager();
        mapFragment = (SupportMapFragment) fragmentManager.findFragmentByTag(MAP_FRAGMENT_TAG);
        if (mapFragment == null) {
            if (!getActivity().isFinishing()) {
                mapFragment = new SupportMapFragment();
                FragmentTransaction ft = fragmentManager.beginTransaction();
                ft.add(R.id.mapFrame, mapFragment, MAP_FRAGMENT_TAG);
                ft.commit();
                fragmentManager.executePendingTransactions();
            }
        }

        return view;
    }

    // ...

    @Override
    public void onPause() {
        if (mapFragment != null)
            getChildFragmentManager().beginTransaction().remove(mapFragment).commit();
        super.onPause();
    }
}


问:
I want to read and confirm data from a dictionary
I want to write a simple login script for existing users, I've created a dictionary for it but my code doesn't work.

I've tried the following:

```<code>d = {'apple':'red','green':'lettuce','yellow':'lemon','orange':'orange'}
print "Please enter your username: "
user_name = raw_input()
print "Please enter your password: "
password = raw_input
for user_name,password in d:
    if user_name in d and password in d:
        print "great"
    else:
        print "Password incorrect!"
</code>```

The code doesn't work, I always get incorrect password.

答:
You will get an error in line : "for user_name,password in d:"

Python ValueError: too many values to unpack

Correct code will be :

```<code>d = {'apple':'red','green':'lettuce','yellow':'lemon','orange':'orange'}
print "Please enter your username: "
user_name = raw_input()
print "Please enter your password: "
password = raw_input()
for user,passw in d.iteritems():
    if user == user_name and password == passw :
         print "great"
         exit(0)
print "Password incorrect!"
</code>```

Body:
I want to write a simple login script for existing users, I've created a dictionary for it but my code doesn't work.

I've tried the following:

d = {'apple':'red','green':'lettuce','yellow':'lemon','orange':'orange'}
print "Please enter your username: "
user_name = raw_input()
print "Please enter your password: "
password = raw_input
for user_name,password in d:
    if user_name in d and password in d:
        print "great"
    else:
        print "Password incorrect!"

The code doesn't work, I always get incorrect password.

Body:
You will get an error in line : "for user_name,password in d:"

Python ValueError: too many values to unpack

Correct code will be :

d = {'apple':'red','green':'lettuce','yellow':'lemon','orange':'orange'}
print "Please enter your username: "
user_name = raw_input()
print "Please enter your password: "
password = raw_input()
for user,passw in d.iteritems():
    if user == user_name and password == passw :
         print "great"
         exit(0)
print "Password incorrect!"


问:
readystate never reaching 4
In the code below I try to post some data to a table and then retrieve several records from the table afterwards. For testing purposes I have only included a dummy query in the php, which returns a valid xml.

But the Javascript readystate only reach readystate 1 (twice). As the php seems to be working fine I suspect I have scripted the javascript incorrectly. Is it a problem with the "request" variable?

$(document).ready(function() {
  $('form').submit(function(event) { //Trigger on form submit
    $('#name + .throw_error').empty(); //Clear the messages first

    var name = $('input[name=name]').val();
    var request = !window.XMLHttpRequest ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest;
    request.onreadystatechange = function() {

      if (request.readyState == 4 && request.status == 200) {
        var xml = request.responseXML;
        var dynamiclist = '';
        document.getElementById("myLink").innerHTML = '';
        var posts = xml.documentElement.getElementsByTagName("post");
        for (var i = 0; i < posts.length; i++) {
          var Msg = posts[i].getAttribute("Msg");
          alert("test");
          var dynamiclist = dynamiclist + '

' + Msg + '

';
          document.getElementById("myLink").innerHTML = dynamiclist;
        };
      };
    };
    request.open('POST', 'process.php', true);
    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    request.send('name=' + name);
  });
});```

答:
Try preventing the default form event from firing:

$('form').submit(function(event) {
        event.preventDefault();

This prevents the form element from reloading the browser window.

Title: readystate never reaching 4


问:
Woocommerce Tax_query with LIKE terms
I want to query all the products by "color" attribute. But some of my product's color attribute is set like this "01 blue", "02 blue", "01 black" and so on. What I want to do is to load products by color that is likely the given color. Sample color is blue, so it will get all products with 01 blue, 02 blue color attribute.

I have these codes but it is not working:

```<code>$args = array(
              'post_type' => 'product',
              'posts_per_page' => 12,
              'tax_query' => array(
                  array(
                      'taxonomy' => 'pa_product-color',
                      'field' => 'slug',
                      'terms' => 'featured-product',
                      'compare' => 'LIKE'
                  )
              )
             );
</code>```

答:
```<code>$args = array(
    'post_type' => 'product',
    'posts_per_page' => 12,
    'tax_query' => array(
        array(
            'taxonomy' => 'pa_product-color',
            'field' => 'slug',
            'terms' => 'blue',
            'compare' => 'LIKE'
        )
    )
);
</code>```

This should get you the products with the color blue.

Title: Woocommerce Tax_query with LIKE terms

Body:
I want to query all the products by "color" attribute. But some of my product's color attribute is set like this "01 blue", "02 blue", "01 black" and so on. What I want to do is to load products by color that is likely the given color. Sample color is blue, so it will get all products with 01 blue, 02 blue color attribute.

I have these codes but it is not working:

$args = array(
              'post_type' => 'product',
              'posts_per_page' => 12,
              'tax_query' => array(
                  array(
                      'taxonomy' => 'pa_product-color',
                      'field' => 'slug',
                      'terms' => 'featured-product',
                      'compare' => 'LIKE'
                  )
              )
             );

Body:
$args = array(
    'post_type' => 'product',
    'posts_per_page' => 12,
    'tax_query' => array(
        array(
            'taxonomy' => 'pa_product-color',
            'field' => 'slug',
            'terms' => 'blue',
            'compare' => 'LIKE'
        )
    )
);

This should get you the products with the color blue.


问:
How do you count the elements of an array in java
Say i have the array

```<code>int theArray = new int[20];
</code>```

The length of the array is 20 but the count is 0. How can i get the count?

答:
What I think you may want is an ArrayList<Integer> instead of an array.  This will allow you do to:

```<code>ArrayList<Integer> arr = new ArrayList<Integer>(20);
System.out.println(arr.size());
</code>```

The output will be 0.

Then, you can add things to the list, and it will keep track of the count for you.  (It will also grow the size of the backing storage as you need as well.)

Body:
Say i have the array

int theArray = new int[20];

The length of the array is 20 but the count is 0. How can i get the count?

Body:
What I think you may want is an ArrayList<Integer> instead of an array.  This will allow you do to:

ArrayList<Integer> arr = new ArrayList<Integer>(20);
System.out.println(arr.size());

The output will be 0.

Then, you can add things to the list, and it will keep track of the count for you.  (It will also grow the size of the backing storage as you need as well.)