答:
I really recommend changing the type of the string variable to DateTime. It is WAY better to manipulate dates. However, if you want to stick with string for some reason, you could convert to date just in the time of sorting.

```<code>public class SortbyDate :IComparer<OilChange>
{
    public int Compare(OilChange x, OilChange y)
    {
        DateTime dateX = Convert.ToDateTime(x.ServiceDate);
        DateTime dateY = Convert.ToDateTime(y.ServiceDate);
        return dateX.CompareTo(dateY);
    }
}
</code>```

If your problem is just formatting the date, try:

```<code>string date = String.Format("{0:MM/dd/yyyy}", dateTimeValue);
</code>```

Read more here.

Title: Sort error - dates in Unity

Body:
I really recommend changing the type of the string variable to DateTime. It is WAY better to manipulate dates. However, if you want to stick with string for some reason, you could convert to date just in the time of sorting.

public class SortbyDate :IComparer<OilChange>
{
    public int Compare(OilChange x, OilChange y)
    {
        DateTime dateX = Convert.ToDateTime(x.ServiceDate);
        DateTime dateY = Convert.ToDateTime(y.ServiceDate);
        return dateX.CompareTo(dateY);
    }
}

If your problem is just formatting the date, try:

string date = String.Format("{0:MM/dd/yyyy}", dateTimeValue);

Read more here.


来源: stackexchange

问:
Why does splitting a string return a (bad) value across multiple lines in my Rails API application, but not the console?
I have a GrapeSwaggerRails API application that takes a two dates and a comma-delimited string of category IDs. It should query the database for Records with a created_at within the two given dates and a category_id that matches one of the IDs passed to it. I'm not having any trouble with the dates, so I'll skip that for now. But let's say I want Records with categories matching 8, 2, or 1. In the code, it looks like "8,2,1". In the URL, it gets appended as &categories=%228%2C2%2C1%22.

Anyway, I figured one decent way of getting this to do what I want would be to convert that string into an array of integers like this: categories = params[:categories].split(',').map(&:to_i)

But given "8,2,1", the output is this (ignore the comment):

```<code>0 # <-- ?????
2
1
</code>```

Very strange. In the definition of the API, params[:categories] looks like this: "8,2,1". But params[:categories].split(',') becomes the following:

```<code>"8
2
1"
</code>```

That's a bit odd, isn't it? Running the map method on that turns it into that nonsense higher up, converting the "8 to a 0 for reasons I'm hoping to find out here. I know I could probably come at this problem from a different angle and sidestep the issue, but I'd rather try to get to the root of what's going wrong, so I can learn something from it. For reference, here's what the Rails console does when I put (as far as I can tell) the same data into it:

```<code>>> "8,2,1".split(',')
#=> ["8", "2", "1"]
</code>```

map then works as expected.

```<code>>> "8,2,1".split(',').map(&:to_i)
#=> [8, 2, 1]
</code>```

So my question is twofold. What's going wrong with this split function? Why does it behave differently in the console?

答:
Because params[:categories] is actually

```<code>'"8,2,1"' # <- the outer ''s are just for illustration of a string.
</code>```

If you pass &categories=8%2C2%2C1 it should work as expected.

ContentLicense: CC BY-SA 3.0

Body:
I have a GrapeSwaggerRails API application that takes a two dates and a comma-delimited string of category IDs. It should query the database for Records with a created_at within the two given dates and a category_id that matches one of the IDs passed to it. I'm not having any trouble with the dates, so I'll skip that for now. But let's say I want Records with categories matching 8, 2, or 1. In the code, it looks like "8,2,1". In the URL, it gets appended as &categories=%228%2C2%2C1%22.

Anyway, I figured one decent way of getting this to do what I want would be to convert that string into an array of integers like this: categories = params[:categories].split(',').map(&:to_i)

But given "8,2,1", the output is this (ignore the comment):

0 # <-- ?????
2
1

Very strange. In the definition of the API, params[:categories] looks like this: "8,2,1". But params[:categories].split(',') becomes the following:

"8
2
1"

That's a bit odd, isn't it? Running the map method on that turns it into that nonsense higher up, converting the "8 to a 0 for reasons I'm hoping to find out here. I know I could probably come at this problem from a different angle and sidestep the issue, but I'd rather try to get to the root of what's going wrong, so I can learn something from it. For reference, here's what the Rails console does when I put (as far as I can tell) the same data into it:

>> "8,2,1".split(',')
#=> ["8", "2", "1"]

map then works as expected.

>> "8,2,1".split(',').map(&:to_i)
#=> [8, 2, 1]

So my question is twofold. What's going wrong with this split function? Why does it behave differently in the console?

Body:
Because params[:categories] is actually

'"8,2,1"' # <- the outer ''s are just for illustration of a string.

If you pass &categories=8%2C2%2C1 it should work as expected.


问:
Doubles are contaminating my BigDecimal math
I'm writing a Mandelbrot Set explorer. I need as much precision as possible so I can zoom in as far as possible.

I noticed an unfortunate side-effect of mixing doubles and BigDecimals: they "contaminate" the type returned:

```<code>(type (* 1M 2))
=> java.math.BigDecimal

(type (* 1M 2.0))
=> java.lang.Double
</code>```

I expected the opposite. BigDecimals, being potentially more precise, should contaminate the doubles.

Besides manually calling bigdec on every number that may come in contact with a BigDecimal, is there a way of preventing the auto-downgrade to double when doing math on doubles and BigDecimals?

Body:
I'm writing a Mandelbrot Set explorer. I need as much precision as possible so I can zoom in as far as possible.

I noticed an unfortunate side-effect of mixing doubles and BigDecimals: they "contaminate" the type returned:

(type (* 1M 2))
=> java.math.BigDecimal

(type (* 1M 2.0))
=> java.lang.Double

I expected the opposite. BigDecimals, being potentially more precise, should contaminate the doubles.

Besides manually calling bigdec on every number that may come in contact with a BigDecimal, is there a way of preventing the auto-downgrade to double when doing math on doubles and BigDecimals?

Body:
This isn't actually a bug, even though it at least looks wrong. To more clearly show how this leads to wrong looking answers compare these expressions:

user>  (* 2.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001M 1.0)
2.0
user>  (* 2.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001M 1.0M)
2.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010M

For the time being you will likely need to, as you suggest, make sure you only use big decimals in your program. It will likely be limited to the IO functions and any constants you introduce need the M on the end. Adding preconditions to functions will likely help catch some cases as well.


问:
Can't center
 nested inside of 2 divs and a section
I'm trying to center my paragraphs, but having the worst time of trying to do it:

.centerLoginForm {
  display: flex;
  justify-content: center;
}

.mainContent {
  position: relative;
  color: white;
  width: 60%;
  padding: 1.5% 2.5% 0 2.5%;
  margin-top: 5%;
  background-color: black;
  border-radius: 5% 5% 5% 5%;
}

.underHead,
.underHead p {
  margin: 0;
  padding: 0;
  border: 0;
  outline: 0;
}

.underHead {
  width: 70%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='centerLoginForm'>
  <section class='mainContent'>
    <h1>Welcome to the BYU Idaho Radio Intranet!</h1>
    <div class='underHead'>
      <p>Computers and computer networks are a funny thing. We interact with them mostly through the internet, which is just a whole bunch of interconnected computers around the world. Well this is an <i>intranet</i>: a local network just like the internet,
        only with fewer connected computers.</p>

      <p>The purpose of this intranet is to guide through troubleshooting, monitoring critical systems, and station documentation. This site is easy to navigate and you should find all the things you are looking for just by following the navigation links.</p>

      <p>This was built to be a living, breathing application. Some dude originally built this, but he welcomes support, ideas, and if somebody wanted to chip in on developing, he would love that too! So please, if you have ideas, thoughts, or skills, share
        them! Engineering unfortunately is having fewer and fewer people enter into its field, and needs as many bright minds as it can take and you have a bright mind!</p>
    </div>
  </section>
</div></code>```

As you can see, the text inside of the
 tags is is following it's natural position, instead of following what I have in my class .underHead. I've tried text-align, content-align, justify-content, and I just can't figure out a way to center that content.

答:
I think this is what you are looking to do:

.centerLoginForm {
  display: flex;
  justify-content: center;
}

.mainContent {
  position: relative;
  color: white;
  width: 60%;
  padding: 1.5% 2.5% 0 2.5%;
  margin-top: 5%;
  background-color: black;
  border-radius: 5% 5% 5% 5%;
}

.underHead {
  display: block;
  margin: auto;
  width: 70%;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='centerLoginForm'>
  <section class='mainContent'>
    <h1>Welcome to the BYU Idaho Radio Intranet!</h1>
    <div class='underHead'>
      <p>Computers and computer networks are a funny thing. We interact with them mostly through the internet, which is just a whole bunch of interconnected computers around the world. Well this is an <i>intranet</i>: a local network just like the internet,
        only with fewer connected computers.</p>

      <p>The purpose of this intranet is to guide through troubleshooting, monitoring critical systems, and station documentation. This site is easy to navigate and you should find all the things you are looking for just by following the navigation links.</p>

      <p>This was built to be a living, breathing application. Some dude originally built this, but he welcomes support, ideas, and if somebody wanted to chip in on developing, he would love that too! So please, if you have ideas, thoughts, or skills, share
        them! Engineering unfortunately is having fewer and fewer people enter into its field, and needs as many bright minds as it can take and you have a bright mind!</p>
    </div>
  </section>

</div></code>```

Title: Can't center <p> nested inside of 2 divs and a section

Body:
I'm trying to center my paragraphs, but having the worst time of trying to do it:

.centerLoginForm {
  display: flex;
  justify-content: center;
}

.mainContent {
  position: relative;
  color: white;
  width: 60%;
  padding: 1.5% 2.5% 0 2.5%;
  margin-top: 5%;
  background-color: black;
  border-radius: 5% 5% 5% 5%;
}

.underHead,
.underHead p {
  margin: 0;
  padding: 0;
  border: 0;
  outline: 0;
}

.underHead {
  width: 70%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
}

Welcome to the BYU Idaho Radio Intranet!

Computers and computer networks are a funny thing. We interact with them mostly through the internet, which is just a whole bunch of interconnected computers around the world. Well this is an intranet: a local network just like the internet,
        only with fewer connected computers.

The purpose of this intranet is to guide through troubleshooting, monitoring critical systems, and station documentation. This site is easy to navigate and you should find all the things you are looking for just by following the navigation links.

This was built to be a living, breathing application. Some dude originally built this, but he welcomes support, ideas, and if somebody wanted to chip in on developing, he would love that too! So please, if you have ideas, thoughts, or skills, share
        them! Engineering unfortunately is having fewer and fewer people enter into its field, and needs as many bright minds as it can take and you have a bright mind!

As you can see, the text inside of the
 tags is is following it's natural position, instead of following what I have in my class .underHead. I've tried text-align, content-align, justify-content, and I just can't figure out a way to center that content.

Body:
I think this is what you are looking to do:

.centerLoginForm {
  display: flex;
  justify-content: center;
}

.mainContent {
  position: relative;
  color: white;
  width: 60%;
  padding: 1.5% 2.5% 0 2.5%;
  margin-top: 5%;
  background-color: black;
  border-radius: 5% 5% 5% 5%;
}

.underHead {
  display: block;
  margin: auto;
  width: 70%;
  text-align: center;
}

<div class='centerLoginForm'>
  <section class='mainContent'>
    <h1>Welcome to the BYU Idaho Radio Intranet!</h1>
    <div class='underHead'>
      <p>Computers and computer networks are a funny thing. We interact with them mostly through the internet, which is just a whole bunch of interconnected computers around the world. Well this is an <i>intranet</i>: a local network just like the internet,
        only with fewer connected computers.</p>

      <p>The purpose of this intranet is to guide through troubleshooting, monitoring critical systems, and station documentation. This site is easy to navigate and you should find all the things you are looking for just by following the navigation links.</p>

      <p>This was built to be a living, breathing application. Some dude originally built this, but he welcomes support, ideas, and if somebody wanted to chip in on developing, he would love that too! So please, if you have ideas, thoughts, or skills, share
        them! Engineering unfortunately is having fewer and fewer people enter into its field, and needs as many bright minds as it can take and you have a bright mind!</p>
    </div>
  </section>

</div>


问:
Python ctypes usage passing pointers
I am trying to call functions from a C library in python 2.7. I am rather confused by most tutorials or information I've found so far.

The C function takes in 3 doubles (labeled h, k, l) and 2 pointers to a double (*p, *q) to iteratively solve the two doubles, initialized with 0.0 for simplicity. The function returns nothing, it just uses the pointers to modify the values of p and q.

My current code reads:

```<code>import ctypes
path = '/foo/bar.so'
_lib = ctypes.CDLL(path)
_lib.solve.argtypes = (ctypes.c_double, ctypes.c_double, ctypes.c_double, ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double))

def py_solve(h, k, l):
    global _lib
    p, q = ctypes.c_double(0.0), ctypes.c_double(0.0)
    _lib.solve(ctypes.c_double(h), ctypes.c_double(k), ctypes.c_double(l), ctypes.POINTER(p), ctypes.POINTER(q))
    return float(p), float(q)
</code>```

I get:

```<code>'TypeError: must be a ctypes type'
</code>```

on the line calling _lib.solve(...) in my py_solve function. Maybe this would be simpler by using ctypes' byref() function but I am unsure how to do that as well. Any help is appreciated, thanks.

答:
The function ctypes.POINTER takes an argument that is a ctypes type.  When you use it in the line

```<code>_lib.solve.argtypes = (ctypes.c_double, ctypes.c_double, ctypes.c_double, ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double))
</code>```

that's exactly what you're doing, since ctypes.c_double is a type.

When later you call it like this:

```<code>ctypes.POINTER(p)
</code>```

the argument isn't a type but an instance of a type - an already initialized variable of type ctypes.c_double.

All you need to do is to create a pointer to the already initialized variables p and q.  Just replace ctypes.POINTER(p) with ctypes.byref(p).

Title: Python ctypes usage passing pointers

Body:
I am trying to call functions from a C library in python 2.7. I am rather confused by most tutorials or information I've found so far.

The C function takes in 3 doubles (labeled h, k, l) and 2 pointers to a double (*p, *q) to iteratively solve the two doubles, initialized with 0.0 for simplicity. The function returns nothing, it just uses the pointers to modify the values of p and q.

My current code reads:

import ctypes
path = '/foo/bar.so'
_lib = ctypes.CDLL(path)
_lib.solve.argtypes = (ctypes.c_double, ctypes.c_double, ctypes.c_double, ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double))

def py_solve(h, k, l):
    global _lib
    p, q = ctypes.c_double(0.0), ctypes.c_double(0.0)
    _lib.solve(ctypes.c_double(h), ctypes.c_double(k), ctypes.c_double(l), ctypes.POINTER(p), ctypes.POINTER(q))
    return float(p), float(q)

I get:

'TypeError: must be a ctypes type'

on the line calling _lib.solve(...) in my py_solve function. Maybe this would be simpler by using ctypes' byref() function but I am unsure how to do that as well. Any help is appreciated, thanks.

Body:
The function ctypes.POINTER takes an argument that is a ctypes type.  When you use it in the line

_lib.solve.argtypes = (ctypes.c_double, ctypes.c_double, ctypes.c_double, ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double))

that's exactly what you're doing, since ctypes.c_double is a type.

When later you call it like this:

ctypes.POINTER(p)

the argument isn't a type but an instance of a type - an already initialized variable of type ctypes.c_double.

All you need to do is to create a pointer to the already initialized variables p and q.  Just replace ctypes.POINTER(p) with ctypes.byref(p).


问:
Robot framework: how can I get current instance of selenium webdriver to write my own keywords?
I have a maven-powered Robot-framework project in java that uses selenium 3.4.0 dependency, robotframework 3.0.2 dependency, markusbernhardt's selenium2library version 1.4.0.8, and robotframework-maven-plugin version 1.4.7.

My robot tests live in the src/main/test/robotframework/acceptance folder, while in src/main/java/mypackage I created a Customized.java file to set a system property for the browser driver path (I then import this library in my tests:

```<code>*** Settings ***
Library             Selenium2Library
Library             mypackage.Customized
</code>```

This works perfectly. But now I'd like to implement my own keywords to extend Selenium2Library. But I'm not sure how to obtain the current WebDriver instance that is running.

I mean, if I weren't using Robot and just plain Selenium, I'd do something like this:

```<code>WebDriver driver=new ChromeDriver();
driver.doSomething();
</code>```

However, in this case I don't want to instantiate a new WebDriver but instead get the one that is currently running (which Robot automatically instantiated). How can I do that?

I've so far created a Selenium2Library object and set it with the value returned by Selenium2Library.getLibraryInstance(); but that's not giving me access to selenium's methods (e.g.: getCurrentUrl() is not listed).

答:
Actually, I found a solution, but I'm not sure it's the right approach:

```<code>public class Customized {

    private static Selenium2Library s;
    private BrowserManagement b;
    private WebDriver driver;

    public Customized() throws ScriptException {
        try {
            Customized.s = (Selenium2Library) Selenium2Library.getLibraryInstance();
        } catch (javax.script.ScriptException e) {
            e.printStackTrace();
        }
        b = s.getBrowserManagement();
        driver=b.getCurrentWebDriver();
    }
}
</code>```

Now the selenium methods are available from the driver object. However, there might be a better way to do it, as there's this message in the javax.script.ScriptException exception: "Access restriction: The type 'ScriptException' is not API (restriction on required library 'C:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar')"

Body:
I have a maven-powered Robot-framework project in java that uses selenium 3.4.0 dependency, robotframework 3.0.2 dependency, markusbernhardt's selenium2library version 1.4.0.8, and robotframework-maven-plugin version 1.4.7.

My robot tests live in the src/main/test/robotframework/acceptance folder, while in src/main/java/mypackage I created a Customized.java file to set a system property for the browser driver path (I then import this library in my tests:

*** Settings ***
Library             Selenium2Library
Library             mypackage.Customized

This works perfectly. But now I'd like to implement my own keywords to extend Selenium2Library. But I'm not sure how to obtain the current WebDriver instance that is running.

I mean, if I weren't using Robot and just plain Selenium, I'd do something like this:

WebDriver driver=new ChromeDriver();
driver.doSomething();

However, in this case I don't want to instantiate a new WebDriver but instead get the one that is currently running (which Robot automatically instantiated). How can I do that?

I've so far created a Selenium2Library object and set it with the value returned by Selenium2Library.getLibraryInstance(); but that's not giving me access to selenium's methods (e.g.: getCurrentUrl() is not listed).

Body:
Actually, I found a solution, but I'm not sure it's the right approach:

public class Customized {

    private static Selenium2Library s;
    private BrowserManagement b;
    private WebDriver driver;

    public Customized() throws ScriptException {
        try {
            Customized.s = (Selenium2Library) Selenium2Library.getLibraryInstance();
        } catch (javax.script.ScriptException e) {
            e.printStackTrace();
        }
        b = s.getBrowserManagement();
        driver=b.getCurrentWebDriver();
    }
}

Now the selenium methods are available from the driver object. However, there might be a better way to do it, as there's this message in the javax.script.ScriptException exception: "Access restriction: The type 'ScriptException' is not API (restriction on required library 'C:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar')"


问:
Java print writer wraps around
I am using a Java PrintWriter to write a Scala HashMap to file. This is the code I am using:

```<code>def writeToFileAsMapUsingPrintWriter(data: mutable.HashMap[String, Int], outputFilename: String, outputDirectoryPath: String): Unit = {
val myfile = new File (outputDirectoryPath, outputFilename);
val printWriter = new PrintWriter(myfile);
for ((k, v) <- data) {
  printWriter.println(s"$k->$v")
}
printWriter.close ();}
</code>```

Now the problem is this PrintWriter wraps some lines around to the next newline in the output file.
Eg:

CC PRP VBP JJ1 to get JJ2 IN
->821065
2000 DT RBS JJ1 IN the hundred of JJ2 year->10521306
PRP be JJ1 TO VB JJ2 IN
->10521307
DT world POS JJ1 marketer , MD lead JJ2 effort->10521308

This becomes a problem because when I read this file back, I go line by line, and I encounter lines without an id, as above. And the interesting part is it occurs only for the same lines always. There are longer lines than that, but they don't wrap around.

I tried running the PrintWriter separately for just with these 5 lines in a HashMap, then it prints these lines in the same line i.e without wrapping around. Its only when I feed it my 11GB hash map that this occurs. I also tried replacing the println with a print, but didn't make a difference.

printWriter.print(s"$k->$v\n")

I can maybe go in with an sed command and fix these lines in the file, but that will fix only these 2, and wont fix others. Plus it is just a temporary fix.

Sounds like some kind of memory issue to me. Has anyone encountered this before?

Meanwhile, I will try out more trial and error methods. So next I am going to replace the PrintWriter with a BufferedWriter, using the flush() command as given here etc.

Just that it takes 12 hours to run my program once, so the turn around time is huge. Hence asking just in case if anyone has encountered this before.

答:
How sure are you that your keys don't actually contain newlines? That can sometimes be hard to spot. My guess is this might resolve it:

```<code>printWriter.println(s"${k.trim()}->$v")
</code>```

I am very skeptical that there is any sort of memory issue or other bug with the JVM or Java standard library.

Title: Java print writer wraps around

Body:
I am using a Java PrintWriter to write a Scala HashMap to file. This is the code I am using:

def writeToFileAsMapUsingPrintWriter(data: mutable.HashMap[String, Int], outputFilename: String, outputDirectoryPath: String): Unit = {
val myfile = new File (outputDirectoryPath, outputFilename);
val printWriter = new PrintWriter(myfile);
for ((k, v) <- data) {
  printWriter.println(s"$k->$v")
}
printWriter.close ();}

Now the problem is this PrintWriter wraps some lines around to the next newline in the output file.
Eg:

CC PRP VBP JJ1 to get JJ2 IN
->821065
2000 DT RBS JJ1 IN the hundred of JJ2 year->10521306
PRP be JJ1 TO VB JJ2 IN
->10521307
DT world POS JJ1 marketer , MD lead JJ2 effort->10521308

This becomes a problem because when I read this file back, I go line by line, and I encounter lines without an id, as above. And the interesting part is it occurs only for the same lines always. There are longer lines than that, but they don't wrap around.

I tried running the PrintWriter separately for just with these 5 lines in a HashMap, then it prints these lines in the same line i.e without wrapping around. Its only when I feed it my 11GB hash map that this occurs. I also tried replacing the println with a print, but didn't make a difference.

printWriter.print(s"$k->$v\n")

I can maybe go in with an sed command and fix these lines in the file, but that will fix only these 2, and wont fix others. Plus it is just a temporary fix.

Sounds like some kind of memory issue to me. Has anyone encountered this before?

Meanwhile, I will try out more trial and error methods. So next I am going to replace the PrintWriter with a BufferedWriter, using the flush() command as given here etc.

Just that it takes 12 hours to run my program once, so the turn around time is huge. Hence asking just in case if anyone has encountered this before.

Body:
How sure are you that your keys don't actually contain newlines? That can sometimes be hard to spot. My guess is this might resolve it:

printWriter.println(s"${k.trim()}->$v")

I am very skeptical that there is any sort of memory issue or other bug with the JVM or Java standard library.


问:
Integer Array inside if/Elif Statement
I currently have the following code, which appends lines of a text file to respective lists if they begin with a certain number.

Is there a way I can and use a numerical array and loop to save some lines of code? The number just needs to stop at 9.

Thank you.

```<code>for number in f:
if number.startswith('1'):
        startsw1.append(number)
elif number.startswith('2'):
        startsw2.append(number)
elif number.startswith('3'):
        startsw3.append(number)
elif number.startswith('4'):
        startsw4.append(number)
elif number.startswith('5'):
        startsw5.append(number)
elif number.startswith('6'):
    startsw6.append(number)
elif number.startswith('7'):
    startsw7.append(number)
elif number.startswith('8'):
        startsw8.append(number)
elif number.startswith('9'):
    startsw9.append(number)
</code>```

答:
You can just have a single list, with nested lists with the index indicating the starting digit.

```<code>startsw = [[] for i in range(0,11)]

f = ['122','423','42341','635']
for number in f:
    startsw[int(number[0])].append(number)
</code>```

Output:

```<code>[[], ['122'], [], [], ['423', '42341'], [], ['635'], [], [], [], []]
</code>```

Title: Integer Array inside if/Elif Statement

Body:
I currently have the following code, which appends lines of a text file to respective lists if they begin with a certain number.

Is there a way I can and use a numerical array and loop to save some lines of code? The number just needs to stop at 9.

Thank you.

for number in f:
if number.startswith('1'):
        startsw1.append(number)
elif number.startswith('2'):
        startsw2.append(number)
elif number.startswith('3'):
        startsw3.append(number)
elif number.startswith('4'):
        startsw4.append(number)
elif number.startswith('5'):
        startsw5.append(number)
elif number.startswith('6'):
    startsw6.append(number)
elif number.startswith('7'):
    startsw7.append(number)
elif number.startswith('8'):
        startsw8.append(number)
elif number.startswith('9'):
    startsw9.append(number)

Body:
You can just have a single list, with nested lists with the index indicating the starting digit.

startsw = [[] for i in range(0,11)]

f = ['122','423','42341','635']
for number in f:
    startsw[int(number[0])].append(number)

Output:

[[], ['122'], [], [], ['423', '42341'], [], ['635'], [], [], [], []]


问:
Horizontal alignment, with text at top of image?
Hia!
I have the text at the side of the image I want. As seen below.

https://image.ibb.co/bWWO0F/Capture.jpg

Yet, I am struggling to get the text at the TOP of the image, like my amazing drawing here...

https://image.ibb.co/ksgZ7v/Capture1.jpg

How may I do this?

Here is my HTML...

```<code><div>
    <img style="vertical-align:middle" width="350" class="img-circle" align="top" src="image.jpg">
    <p>Works.</p>
</div>
</code>```

答:
Use flexbox.

.flexbox {
  display: flex;
  border: 1px solid;
  padding: 15px;
}

.img-circle {
  border-radius: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flexbox">
  <img style="vertical-align:middle" width="350" class="img-circle" align="top" src="http://placehold.it/350x350">
  <p>Works.</p>
</div></code>```

Body:
Hia!
I have the text at the side of the image I want. As seen below.

https://image.ibb.co/bWWO0F/Capture.jpg

Yet, I am struggling to get the text at the TOP of the image, like my amazing drawing here...

https://image.ibb.co/ksgZ7v/Capture1.jpg

How may I do this?

Here is my HTML...

Works.

Body:
Use flexbox.

.flexbox {
  display: flex;
  border: 1px solid;
  padding: 15px;
}

.img-circle {
  border-radius: 100%;
}

<div class="flexbox">
  <img style="vertical-align:middle" width="350" class="img-circle" align="top" src="http://placehold.it/350x350">
  <p>Works.</p>
</div>


答:
If you have to fill your lists in the global stack, you can use globals() to grab references to your lists and then just append to them:

```<code>for number in f:
    globals()["startsw" + number[0]].append(number)
</code>```

This assumes you've already created startsw1, startsw2, startsw3 ... startsw9 lists in the global namespace and that all elements in f are strings and have their first character as a number.

However, it's much better to just use a dedicated dict to store your number lists:

```<code> starts_dict = {i+1: [] for i in range(9)}
 for number in f:
     starts_dict[number[0]].append(number)
</code>```

Title: Integer Array inside if/Elif Statement

Body:
If you have to fill your lists in the global stack, you can use globals() to grab references to your lists and then just append to them:

for number in f:
    globals()["startsw" + number[0]].append(number)

This assumes you've already created startsw1, startsw2, startsw3 ... startsw9 lists in the global namespace and that all elements in f are strings and have their first character as a number.

However, it's much better to just use a dedicated dict to store your number lists:

 starts_dict = {i+1: [] for i in range(9)}
 for number in f:
     starts_dict[number[0]].append(number)


问:
SQLite3 with C++ retrieve ID and store to another table
Good evening people,
I am building a database using SQLite3 and C++ and I want to insert into table "Subs" as a foreign key, the ID which is the primary key for table "Programs". The table Programs has two columns, Id and programCode. I have the programCode in a variable so my approach is to get the Id from the programCode, store it into a variable and then store this in the table Subs. My problem is that I don't know how to get the result from query and store it into a variable. This is my code:

```<code>sqlite3_stmt *sql;
rc = sqlite3_prepare_v2(db, "SELECT Id FROM Programs WHERE  programCode=?", -1, &sql, 0);
sqlite3_bind_text(sql, 1, _program.c_str(), -1,  SQLITE_TRANSIENT);
int step = sqlite3_step(sql);

if(step == SQLITE_ROW) {
   printf("%d\n", sqlite3_column_int(sql, 0));
}
</code>```

The _program variable holds the programCode value.
Printf prints nothing and I expected to see the result of the query so I can use this  to store it into  an integer.
Any help would be highly appreciated.

答: Thanks to @CL for giving me this piece of information. I checked my csv where I retrieve the information for the database and the programCode had a "space" before the text so that is why there was no matching row. Thanks @CL!

Body:
Good evening people,
I am building a database using SQLite3 and C++ and I want to insert into table "Subs" as a foreign key, the ID which is the primary key for table "Programs". The table Programs has two columns, Id and programCode. I have the programCode in a variable so my approach is to get the Id from the programCode, store it into a variable and then store this in the table Subs. My problem is that I don't know how to get the result from query and store it into a variable. This is my code:

sqlite3_stmt *sql;
rc = sqlite3_prepare_v2(db, "SELECT Id FROM Programs WHERE  programCode=?", -1, &sql, 0);
sqlite3_bind_text(sql, 1, _program.c_str(), -1,  SQLITE_TRANSIENT);
int step = sqlite3_step(sql);

if(step == SQLITE_ROW) {
   printf("%d\n", sqlite3_column_int(sql, 0));
}

The _program variable holds the programCode value.
Printf prints nothing and I expected to see the result of the query so I can use this  to store it into  an integer.
Any help would be highly appreciated.


问:
How to customize tab bar with icons?
Can someone explain to me what I should add exactly to this code from this website:

```<code>III. To change tab icon use TabLayout.Tab#setIcon method. You can get TabLayout.Tab object via TabLayout#getTabAt method, which accept tab index as parameter.

...
//after initialization TabLayout and ViewPager
TabLayout.Tab tabCall = tabLayout.getTabAt(ITEM_CALL);
tabCall.setIcon(R.drawable.selector_call);

//repeat this code for all your tabs
...
</code>```

Because I get tabLayout and ITEM_CALL in red!

答:
You need to first create the selector xml files, and place them in your drawable folder, and those selector files need to reference valid drawables for the selected and non-selected states.

Then, just set the tab icons in onCreate() of the Activity.

Here is what your Activity should look like in order to show three tabs, with each tab showing only an icon:

```<code>public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);

        viewPager.setAdapter(new TabPagerAdapter(getSupportFragmentManager()));

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        tabLayout.setupWithViewPager(viewPager);

        TabLayout.Tab tabCall = tabLayout.getTabAt(0);
        tabCall.setIcon(R.drawable.selector_call);

        TabLayout.Tab tabHeart = tabLayout.getTabAt(1);
        tabHeart.setIcon(R.drawable.selector_heart);

        TabLayout.Tab tabContacts = tabLayout.getTabAt(2);
        tabContacts.setIcon(R.drawable.selector_contacts);
    }

    class TabPagerAdapter extends FragmentPagerAdapter {

        public TabPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return 3;
        }

        @Override
        public Fragment getItem(int position) {

            switch (position) {
                case 0:
                    return new CallFragment();
                case 1:
                    return new HeartFragment();
                case 2:
                    return new ContactsFragment();
            }

            return null;
        }
    }
}
</code>```

Each tab needs its own selector xml file, here is an example of what the selector for the third tab should look like:

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:state_selected="true"
        android:drawable="@drawable/contacts_selected" />

    <item
        android:state_selected="false"
        android:drawable="@drawable/contacts_unselected" />

</selector>
```

Title: How to customize tab bar with icons?

Body:
Can someone explain to me what I should add exactly to this code from this website:

III. To change tab icon use TabLayout.Tab#setIcon method. You can get TabLayout.Tab object via TabLayout#getTabAt method, which accept tab index as parameter.

...
//after initialization TabLayout and ViewPager
TabLayout.Tab tabCall = tabLayout.getTabAt(ITEM_CALL);
tabCall.setIcon(R.drawable.selector_call);

//repeat this code for all your tabs
...

Because I get tabLayout and ITEM_CALL in red!

Body:
You need to first create the selector xml files, and place them in your drawable folder, and those selector files need to reference valid drawables for the selected and non-selected states.

Then, just set the tab icons in onCreate() of the Activity.

Here is what your Activity should look like in order to show three tabs, with each tab showing only an icon:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);

        viewPager.setAdapter(new TabPagerAdapter(getSupportFragmentManager()));

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        tabLayout.setupWithViewPager(viewPager);

        TabLayout.Tab tabCall = tabLayout.getTabAt(0);
        tabCall.setIcon(R.drawable.selector_call);

        TabLayout.Tab tabHeart = tabLayout.getTabAt(1);
        tabHeart.setIcon(R.drawable.selector_heart);

        TabLayout.Tab tabContacts = tabLayout.getTabAt(2);
        tabContacts.setIcon(R.drawable.selector_contacts);
    }

    class TabPagerAdapter extends FragmentPagerAdapter {

        public TabPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return 3;
        }

        @Override
        public Fragment getItem(int position) {

            switch (position) {
                case 0:
                    return new CallFragment();
                case 1:
                    return new HeartFragment();
                case 2:
                    return new ContactsFragment();
            }

            return null;
        }
    }
}

Each tab needs its own selector xml file, here is an example of what the selector for the third tab should look like:

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:state_selected="true"
        android:drawable="@drawable/contacts_selected" />

    <item
        android:state_selected="false"
        android:drawable="@drawable/contacts_unselected" />

</selector>


问:
Docker: cannot open port from container to host
I'm using Docker for Mac. I have a container that run a server, for example my server is run on port 5000. I have exposed this port on Dockerfile

When my container is running, I connect to this container and check and if this server is working or not by running below command and see that it returns data (a bunch of html and javascript)

```<code>wget -d localhost:5000
</code>```

Notes, I start this container and also publish port outside by command:

```<code>docker run -d -p 5000:5000 <docker_image_name>
</code>```

But at docker host (is my mac and running El Capitan), I open chrome and go to address localhost:5000. It doesn't work. Just a little note, if I go to any arbitrary port such as localhost:4000 I see error message from chrome such as:

```<code>This site can’t be reached
localhost refused to connect.
</code>```

But error message for localhost:5000 is:

```<code>The localhost page isn’t working
localhost didn’t send any data.
</code>```

So it seems I have configured work "a little" but something wrong. Please tell me how to fix this.

答:
I had this problem using Docker for Mac, trying to run an Angular2 app.

I fixed the issue by changing the start script in package.json to

"scripts": {
    "start": "ng serve --host 0.0.0.0"
}
```

Previously start was only ng serve.

Body:
I'm using Docker for Mac. I have a container that run a server, for example my server is run on port 5000. I have exposed this port on Dockerfile

When my container is running, I connect to this container and check and if this server is working or not by running below command and see that it returns data (a bunch of html and javascript)

wget -d localhost:5000

Notes, I start this container and also publish port outside by command:

docker run -d -p 5000:5000 <docker_image_name>

But at docker host (is my mac and running El Capitan), I open chrome and go to address localhost:5000. It doesn't work. Just a little note, if I go to any arbitrary port such as localhost:4000 I see error message from chrome such as:

This site can’t be reached
localhost refused to connect.

But error message for localhost:5000 is:

The localhost page isn’t working
localhost didn’t send any data.

So it seems I have configured work "a little" but something wrong. Please tell me how to fix this.

Body:
I had this problem using Docker for Mac, trying to run an Angular2 app.

I fixed the issue by changing the start script in package.json to

"scripts": {
    "start": "ng serve --host 0.0.0.0"
}

Previously start was only ng serve.

ContentLicense: CC BY-SA 4.0


问:
Trouble working with 3 ax objects on the same subplot
The Code:

```<code>import matplotlib.pyplot as plt
import pandas as pd
from numpy import arange
%matplotlib inline

avg_discount = pd.read_json('{"Date":{"0":1498694400000,"1":1498780800000,"2":1498867200000,"3":1498953600000,"4":1499040000000},"Discount":{"0":0.2136567047,"1":0.2186422586,"2":0.2171303955,"3":0.2273395644,"4":0.2285249182}}')
auth_counts = pd.read_json('{"index":{"0":"False","1":"True"},"authorized":{"0":155,"1":22}}')
violation_counts = pd.read_json('{"index":{"0":"False","1":"True"},"violations":{"0":55,"1":7}}')

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1, label='1')
ax2 = ax1.twinx() #tried .twiny() but didn't work as desired
ax3 = fig.add_subplot(1,1,1, label='2', frame_on=False)
bar_positions = arange(2) + 0.75
ax1.bar(bar_positions, auth_counts['authorized'],0.5, color='#b0c4de')
ax1.xaxis.tick_top()
tick_positions = range(1,3)
ax1.set_xticks(tick_positions)
ax1.set_xticklabels(['Unauthorized','Authorized'])
ax2.bar(bar_positions, [55,7], 0.5)
ax2.set_ylim([1,160])
ax2.tick_params(axis='both', top='off', right='off', labelright='off')
ax3.plot(avg_discount['Date'], avg_discount['Discount'], color='r', marker='o')
ax3.tick_params(axis='both', left='off', top='off', right='off',labelleft='off')
ax3.set_xticklabels([val.day for val in avg_discount['Date']], rotation=90)
plt.show()
</code>```

Result:

Data Explained:
- ax1 represents two different groups and their counts. ax2 represents of those two groups who has performed a certain action. ax3 adds a trend line of a statistic that defines the action taken by the members of these groups.

The Problem:
- The x axis and the correlated data points are not lined up for the line plot, ax3. Also, I'd like to neatly show the date, but settled for showing the day. Any suggestions on how to better represent this data would be appreciated.
- While I managed to get both bar charts to overlap, they are no longer neatly spaced out. I can only assume this is because matplotlib is trying to find an xlimit that satisfies all 3 charts, but when I edit the xlimit for all 3 to 10, ax3 says the limit is out of range.

Expected output:
- The output I'm looking for should look somewhat similar to the output of just the first bar chart. With the 2nd barchart overlaying on the 1st and the line plotted across the figure.

答:
You may set the bar positions to some integer number, e.g. 0 and 1, which makes it easier to handle the spacings. If the bar is center-aligned align="center" and has a width of 0.8, it extents from -0.4 to 0.4, or from 0.6 to 1.4. Setting the xlim to [-1,2] leaves enough space around the bars. Of course you may chose other values to your liking.

To format the date axes, you may use matplotlib dates locators and formatters (also see the dates example).

```<code>import matplotlib.pyplot as plt
import matplotlib.dates
import pandas as pd
from numpy import arange
#%matplotlib inline

avg_discount = pd.read_json('{"Date":{"0":1498694400000,"1":1498780800000,"2":1498867200000,"3":1498953600000,"4":1499040000000},"Discount":{"0":0.2136567047,"1":0.2186422586,"2":0.2171303955,"3":0.2273395644,"4":0.2285249182}}')
auth_counts = pd.read_json('{"index":{"0":"False","1":"True"},"authorized":{"0":155,"1":22}}')
violation_counts = pd.read_json('{"index":{"0":"False","1":"True"},"violations":{"0":55,"1":7}}')

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1, label='1')
ax2 = ax1.twinx()
ax3 = fig.add_subplot(1,1,1, label='2', frame_on=False)

bar_positions = arange(2)
ax1.bar(bar_positions, auth_counts['authorized'],0.8, color='#b0c4de', align="center")
ax1.xaxis.tick_top()
tick_positions = range(1,3)
ax1.set_xticks(bar_positions)
ax1.set_xticklabels(['Unauthorized','Authorized'])
ax2.bar(bar_positions, [55,7], 0.8, align="center")
ax2.set_ylim([1,160])
ax2.set_xlim([-1,2]) # set xlim manually, if wanted

ax2.tick_params(axis='both', top='off', right='off', labelright='off')
ax3.plot(avg_discount['Date'], avg_discount['Discount'], color='r', marker='o')
ax3.tick_params(axis='both', left='off', top='off', right='off',labelleft='off')
plt.setp(ax3.get_xticklabels(), rotation=60, ha="right")
ax3.xaxis.set_major_locator(matplotlib.dates.DayLocator())
ax3.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%Y-%m-%d"))

plt.show()
</code>```

Body:
The Code:

import matplotlib.pyplot as plt
import pandas as pd
from numpy import arange
%matplotlib inline

avg_discount = pd.read_json('{"Date":{"0":1498694400000,"1":1498780800000,"2":1498867200000,"3":1498953600000,"4":1499040000000},"Discount":{"0":0.2136567047,"1":0.2186422586,"2":0.2171303955,"3":0.2273395644,"4":0.2285249182}}')
auth_counts = pd.read_json('{"index":{"0":"False","1":"True"},"authorized":{"0":155,"1":22}}')
violation_counts = pd.read_json('{"index":{"0":"False","1":"True"},"violations":{"0":55,"1":7}}')

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1, label='1')
ax2 = ax1.twinx() #tried .twiny() but didn't work as desired
ax3 = fig.add_subplot(1,1,1, label='2', frame_on=False)
bar_positions = arange(2) + 0.75
ax1.bar(bar_positions, auth_counts['authorized'],0.5, color='#b0c4de')
ax1.xaxis.tick_top()
tick_positions = range(1,3)
ax1.set_xticks(tick_positions)
ax1.set_xticklabels(['Unauthorized','Authorized'])
ax2.bar(bar_positions, [55,7], 0.5)
ax2.set_ylim([1,160])
ax2.tick_params(axis='both', top='off', right='off', labelright='off')
ax3.plot(avg_discount['Date'], avg_discount['Discount'], color='r', marker='o')
ax3.tick_params(axis='both', left='off', top='off', right='off',labelleft='off')
ax3.set_xticklabels([val.day for val in avg_discount['Date']], rotation=90)
plt.show()

Result:

Data Explained:
- ax1 represents two different groups and their counts. ax2 represents of those two groups who has performed a certain action. ax3 adds a trend line of a statistic that defines the action taken by the members of these groups.

The Problem:
- The x axis and the correlated data points are not lined up for the line plot, ax3. Also, I'd like to neatly show the date, but settled for showing the day. Any suggestions on how to better represent this data would be appreciated.
- While I managed to get both bar charts to overlap, they are no longer neatly spaced out. I can only assume this is because matplotlib is trying to find an xlimit that satisfies all 3 charts, but when I edit the xlimit for all 3 to 10, ax3 says the limit is out of range.

Expected output:
- The output I'm looking for should look somewhat similar to the output of just the first bar chart. With the 2nd barchart overlaying on the 1st and the line plotted across the figure.

Body:
You may set the bar positions to some integer number, e.g. 0 and 1, which makes it easier to handle the spacings. If the bar is center-aligned align="center" and has a width of 0.8, it extents from -0.4 to 0.4, or from 0.6 to 1.4. Setting the xlim to [-1,2] leaves enough space around the bars. Of course you may chose other values to your liking.

To format the date axes, you may use matplotlib dates locators and formatters (also see the dates example).

import matplotlib.pyplot as plt
import matplotlib.dates
import pandas as pd
from numpy import arange
#%matplotlib inline

avg_discount = pd.read_json('{"Date":{"0":1498694400000,"1":1498780800000,"2":1498867200000,"3":1498953600000,"4":1499040000000},"Discount":{"0":0.2136567047,"1":0.2186422586,"2":0.2171303955,"3":0.2273395644,"4":0.2285249182}}')
auth_counts = pd.read_json('{"index":{"0":"False","1":"True"},"authorized":{"0":155,"1":22}}')
violation_counts = pd.read_json('{"index":{"0":"False","1":"True"},"violations":{"0":55,"1":7}}')

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1, label='1')
ax2 = ax1.twinx()
ax3 = fig.add_subplot(1,1,1, label='2', frame_on=False)

bar_positions = arange(2)
ax1.bar(bar_positions, auth_counts['authorized'],0.8, color='#b0c4de', align="center")
ax1.xaxis.tick_top()
tick_positions = range(1,3)
ax1.set_xticks(bar_positions)
ax1.set_xticklabels(['Unauthorized','Authorized'])
ax2.bar(bar_positions, [55,7], 0.8, align="center")
ax2.set_ylim([1,160])
ax2.set_xlim([-1,2]) # set xlim manually, if wanted

ax2.tick_params(axis='both', top='off', right='off', labelright='off')
ax3.plot(avg_discount['Date'], avg_discount['Discount'], color='r', marker='o')
ax3.tick_params(axis='both', left='off', top='off', right='off',labelleft='off')
plt.setp(ax3.get_xticklabels(), rotation=60, ha="right")
ax3.xaxis.set_major_locator(matplotlib.dates.DayLocator())
ax3.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%Y-%m-%d"))

plt.show()


问:
How to verify that my terminal's postgres connection is to the same data as Intellij?
I am using intellij with postgres, and highlight sql commands to run them.

I also have postgres running in my terminal, and I am getting different results from the same query when run in intellij vs. when run in the terminal.

Here is the command run from Intellij:

The result shows one entry present:

However, running the same command in the terminal shows no table entries present.

Intellij and the terminal are connecting to the same database and port as shown by Intellij's connection settings

and by the result of \conninfo run in the terminal.

Furthermore, the schema matches as shown by Intellij's connection settings (shown above) and by the result of the terminal's \d+ visitor_sign_in command

Why does this same command give different results when run in Intellij vs. when run in the terminal?

答:
Based on your most recent comment ("yes running select * from pg_stat_activity; does show 'idle in transaction'."), here is what I believe is happening.

You have two connections, A and B.

A starts a transaction, inserts data, and then selects from that table. The table shows data (the data that was just inserted).

B connects, and selects from the same table. Since A has not committed, B does not see that data. In order for the data inserted by A to be visible to any other connections, you need A to commit its transaction.

Now, I don't know why IntelliJ is not offering you the opportunity to commit your transaction, but that lack of commit is the cause of your visibility problem.


问:
What does FastCGI: comm with server mean?
I'm getting this error in a PHP (Drupal) application:

```<code>(104)Connection reset by peer: FastCGI: comm with server "/opt/php-5.2.5/bin/php-cgi" aborted: read failed
</code>```

It is often followed  by this error:

```<code>FastCGI: incomplete headers (0 bytes) received from server "/opt/php-5.2.5/bin/php-cgi"
</code>```

The basic Apache configuration for PHP looks like this:

```<code>   FastCgiServer /opt/php-5.2.5/bin/php-cgi -initial-env PHP_FCGI_CHILDREN=32
   ScriptAlias /fcgi-bin/php-5.2.5 /opt/php-5.2.5/bin/php-cgi
   <Location /fcgi-bin/php-5.2.5>
     Options +ExecCGI
     SetHandler fastcgi-script
     SetOutputFilter INCLUDES
   </Location>
   # send php5.2-fastcgi handler to our scriptalias
   Action php-5.2.5-fastcgi /fcgi-bin/php-5.2.5
</code>```

Now, my basic question is, what are the general causes of the "comm with server" error? In this particular case, the error appears intermittently, but certain pages generate it more often than others. I'd like to know what to look for when debugging my code.

答:
I had the same problem but in python and i resolved changing the extention of my script to .py</p>

```<code>#.htaccess file
AddHandler fastcgi-script .py
</code>```

OwnerDisplayName: Aaron Longwell

ContentLicense: CC BY-SA 2.5

Body:
I'm getting this error in a PHP (Drupal) application:

(104)Connection reset by peer: FastCGI: comm with server "/opt/php-5.2.5/bin/php-cgi" aborted: read failed

It is often followed  by this error:

FastCGI: incomplete headers (0 bytes) received from server "/opt/php-5.2.5/bin/php-cgi"

The basic Apache configuration for PHP looks like this:

   FastCgiServer /opt/php-5.2.5/bin/php-cgi -initial-env PHP_FCGI_CHILDREN=32
   ScriptAlias /fcgi-bin/php-5.2.5 /opt/php-5.2.5/bin/php-cgi
   <Location /fcgi-bin/php-5.2.5>
     Options +ExecCGI
     SetHandler fastcgi-script
     SetOutputFilter INCLUDES
   </Location>
   # send php5.2-fastcgi handler to our scriptalias
   Action php-5.2.5-fastcgi /fcgi-bin/php-5.2.5

Now, my basic question is, what are the general causes of the "comm with server" error? In this particular case, the error appears intermittently, but certain pages generate it more often than others. I'd like to know what to look for when debugging my code.

Body:
I had the same problem but in python and i resolved changing the extention of my script to .py

#.htaccess file
AddHandler fastcgi-script .py


问:
How to end a dialog and start an another dialog?
```<code>var bot = new builder.UniversalBot(connector, [
function (session, args, next) {
    if (!session.userData.name) {
        session.beginDialog('profile');
    } else {
        next();
    }
},
function (session, results) {
    session.send('Hello %s!', session.userData.name);
}]);bot.dialog('profile', [
function (session) {
    builder.Prompts.text(session, 'Hi! What is your name?');
},
function (session, results) {
    session.userData.name = results.response;
    session.endDialog();
}]);
</code>```

The above code is taken from the Microsoft bot framework documentation. Here, I cant understand the purpose of the session.endDialog(). After running this code, it asks for username and gets the input and replies back with "hello user input". What happens is, it keeps looping again and again.
I want to start the qnamaker dialog after getting the user name and it should continue with the qnamaker  and should not get back to the first function where user name is asked.

答:
session.endDialog() will end the current dialog (in your example code, it would end the profile dialog), and returns control to the dialog that called it, so (in your example) control would return to the default dialog that launches after the wake word is sent.

The example code that you took from the Microsoft site is just meant to show a basic example, so of course it just has those few dialogs. For the QnA bot you want to build, instead of simply echoing the name back to the user, you would want to start your QnA functionality/dialog in that function, which could include starting another dialog, depending on how you want to architect it.

Body:
var bot = new builder.UniversalBot(connector, [
function (session, args, next) {
    if (!session.userData.name) {
        session.beginDialog('profile');
    } else {
        next();
    }
},
function (session, results) {
    session.send('Hello %s!', session.userData.name);
}]);bot.dialog('profile', [
function (session) {
    builder.Prompts.text(session, 'Hi! What is your name?');
},
function (session, results) {
    session.userData.name = results.response;
    session.endDialog();
}]);

The above code is taken from the Microsoft bot framework documentation. Here, I cant understand the purpose of the session.endDialog(). After running this code, it asks for username and gets the input and replies back with "hello user input". What happens is, it keeps looping again and again.
I want to start the qnamaker dialog after getting the user name and it should continue with the qnamaker  and should not get back to the first function where user name is asked.


问:
Is it possible to have more than one URL in the webRequest target
Is it possible to have more than one target in the urls argument in the webRequest. How?

This is an example that did not work and gave me this error:

```<code>The webRequest.addListener filter doesn't overlap with host permissions.
</code>```

****UPDATED****:

This is the example code main.js:

```<code>myArray=["yahoo.com", "google.co.uk"];
patterns=[];
for (var x=0; x<myArray.length; x++)
{
    var aURL="\"https://*."+myArray[x]+"/*\""
    patterns.push(aURL);
}//end for

console.log("the array: "+patterns);

function logURL(requestDetails)
{
    console.log("inside logURL");
    console.log("*******************************");
    console.log("Loading: " + requestDetails.url);
    console.log("*******************************");
}//end logUTL

browser.webRequest.onBeforeRequest.addListener(
  logURL,
  {urls: patterns,
   types: ["main_frame"]}
);
</code>```

This is the manifest:

```<code>{
    "manifest_version": 2,
    "name": "test",
    "version": "1.0",
    "description": "",
    "background": {
    "scripts": ["main.js"]
    },

    "icons": {
    "64": "icons/myicon.png"
    },

    "permissions":[
    "<all_urls>",
    "activeTab",
    "tabs",
    "activeTab",
    "webRequest"
    ]
}
</code>```

答:
Any reason to add double quotes?</p>

```<code>-var aURL="\"https://*." + myArray[x] + "/*\""
+var aURL="https://*." + myArray[x] + "/*"
</code>```

Body:
Is it possible to have more than one target in the urls argument in the webRequest. How?

This is an example that did not work and gave me this error:

The webRequest.addListener filter doesn't overlap with host permissions.

****UPDATED****:

This is the example code main.js:

myArray=["yahoo.com", "google.co.uk"];
patterns=[];
for (var x=0; x<myArray.length; x++)
{
    var aURL="\"https://*."+myArray[x]+"/*\""
    patterns.push(aURL);
}//end for

console.log("the array: "+patterns);

function logURL(requestDetails)
{
    console.log("inside logURL");
    console.log("*******************************");
    console.log("Loading: " + requestDetails.url);
    console.log("*******************************");
}//end logUTL

browser.webRequest.onBeforeRequest.addListener(
  logURL,
  {urls: patterns,
   types: ["main_frame"]}
);

This is the manifest:

{
    "manifest_version": 2,
    "name": "test",
    "version": "1.0",
    "description": "",
    "background": {
    "scripts": ["main.js"]
    },

    "icons": {
    "64": "icons/myicon.png"
    },

    "permissions":[
    "<all_urls>",
    "activeTab",
    "tabs",
    "activeTab",
    "webRequest"
    ]
}

Body:
Any reason to add double quotes?

-var aURL="\"https://*." + myArray[x] + "/*\""
+var aURL="https://*." + myArray[x] + "/*"


问:
SenderView and making fields read only
Given this workflow:

Our user selects some documents (pdf forms that we fill with data on our servers using iTextSharp) in our software

We use the REST API to generate a sender view and navigate them to it

The documents may have editable PDF form fields on them that the sender will fill in.

When the user is on an iPad and for whatever reason doesn't have a bluetooth or other keyboard handy and has to use the GUI keyboard (our users are on the road a lot) they don't have a command key so can't make use of the keyboard shortcuts in the sender view to easily select all fields and mark them read-only.

Desired result: upon sending all non-signature related fields become read-only.

The end result we desire is that after the sender fills in any fields, all non-signature related fields that are left become read-only so that any signers cannot make changes. On desktop or with a connected keyboard, keyboard shortcuts, etc. make this trivial for the user to accomplish on short documents. However, on longer documents or in cases where a connected keyboard is not available, this is not trivial and is actually a bad user experience.

Is there any setting that I've overlooked that would do this automatically? Any particular way of forming the envelope that would accomplish it automatically? When we create the envelope we do assign the signature fields to the appropriate signer using composite/inline templates and tabs collections. That part is working fine currently. We are now trying to add the ability for the sender to preview the document, fill in missing data and send while disallowing signers from editing.

答:
Before uploading the PDF to DocuSign, set the Form fields on your PDF as readonly. See this answer for doing this using iTextSharp.

When the envelope is created, DocuSign will transform those Fields as readonly for the Signer.

Sender should still be able to edit the read only fields in the sending experience.

Title: SenderView and making fields read only


问:
How to stop .+ at the first instance of a character and not the last with regular expressions in perl?
I want to replace:

```<code>'''<font size="3"><font color="blue"> SUMMER/WINTER CONFIGURATION FILES</font></font>'''
</code>```

With:

```<code>='''<font color="blue"> SUMMER/WINTER CONFIGURATION FILES</font>'''=
</code>```

Now my existing code is:

```<code>$html =~ s/\n(.+)<font size=\".+?\">(.+)<\/font>(.+)\n/\n=$1$2$3=\n/gm
</code>```

However this ends up with this as the result:

```<code>=''' SUMMER/WINTER CONFIGURATION FILES</font>'''=
</code>```

Now I can see what is happening, it is matching <font size ="..... all the way up to the end of the  which is not what I want, I want it to stop at the first instance of " not the last, I thought that is what putting the ? mark there would do, however I've tried .+ .+? .* and .*? with the same result each time.

Anyone got any ideas what I am doing wrong?

答: You could change .+ to [^"]+ (instead of "match anything", "match anything that isn't a ""...

Body:
I want to replace:

''' SUMMER/WINTER CONFIGURATION FILES'''

With:

=''' SUMMER/WINTER CONFIGURATION FILES'''=

Now my existing code is:

$html =~ s/\n(.+)(.+)<\/font>(.+)\n/\n=$1$2$3=\n/gm

However this ends up with this as the result:

=''' SUMMER/WINTER CONFIGURATION FILES'''=

Now I can see what is happening, it is matching <font size ="..... all the way up to the end of the  which is not what I want, I want it to stop at the first instance of " not the last, I thought that is what putting the ? mark there would do, however I've tried .+ .+? .* and .*? with the same result each time.

Anyone got any ideas what I am doing wrong?


问:
How can I get list of adapter types in VMWare by vSphere client API
I want to create a virtual machine on ESXi 6.0 by configured adapter type.
Basically, these 3 (E1000, Vmxnet2, VMXNET3) are listing while creating the virtual machine, but I can't find any API in java.
I am importing below packages:

```<code>import com.vmware.vim25.VirtualEthernetCard;
import com.vmware.vim25.VirtualEthernetCardNetworkBackingInfo;
import com.vmware.vim25.VirtualHardware;
import com.vmware.vim25.VirtualMachineConfigInfo;
import com.vmware.vim25.VirtualMachineConfigSpec;
import com.vmware.vim25.VirtualMachineNetworkInfo;

 ArrayList<HostSystem> hosts = OperationHelper.GetAllHostReferene();
 ArrayList<String> networkNames = new ArrayList<String>();
 Network[] nws = null;
    for(HostSystem host : hosts) {
        Datastore[] dts = host.getDatastores();
        for(Datastore d : dts){
            if(d.getName().equals(m_datastore)) {
                log.info("Found host for datastore");
                nws = host.getNetworks();
              for(Network n : nws){
                 networkNames.add(n.getName());
              }
           }
       }
   }
</code>```

I get Network interface card list by above code. But I am not able to get adapter types.
Please help out.

答:
Each VM network adapter inherits from VirtualEthernetCard. For example:

VirtualEthernetCard <|-- VirtualVmxnet <|-- VirtualVmxnet3 <|-- VirtualVmxnet3Vrdma

You should be passing instances of these classes to the list of VM devices when calling ReconfigureVM().

Body:
I want to create a virtual machine on ESXi 6.0 by configured adapter type.
Basically, these 3 (E1000, Vmxnet2, VMXNET3) are listing while creating the virtual machine, but I can't find any API in java.
I am importing below packages:

import com.vmware.vim25.VirtualEthernetCard;
import com.vmware.vim25.VirtualEthernetCardNetworkBackingInfo;
import com.vmware.vim25.VirtualHardware;
import com.vmware.vim25.VirtualMachineConfigInfo;
import com.vmware.vim25.VirtualMachineConfigSpec;
import com.vmware.vim25.VirtualMachineNetworkInfo;

 ArrayList<HostSystem> hosts = OperationHelper.GetAllHostReferene();
 ArrayList<String> networkNames = new ArrayList<String>();
 Network[] nws = null;
    for(HostSystem host : hosts) {
        Datastore[] dts = host.getDatastores();
        for(Datastore d : dts){
            if(d.getName().equals(m_datastore)) {
                log.info("Found host for datastore");
                nws = host.getNetworks();
              for(Network n : nws){
                 networkNames.add(n.getName());
              }
           }
       }
   }

I get Network interface card list by above code. But I am not able to get adapter types.
Please help out.


问:
Split and sort string array swift 3
I'm looking for the most efficient way to go about this. Say there's an array of objects, mapped out in alphabetical order by names:

```<code>let objectArray = [AnyObject]()
let abcNameObjectArray = ["Amy", "Bernadette", "Brian", "Chris", "Candice"]
</code>```

How would I access all the values in this array that have "A" , "B", or "C" based on the first character of each String value in abcNameObject array, in alphabetical order? I'm trying to unload data and return a specific number of rows in the UITableView's cellForRowAt method and numberOfRowsInSection method based on the number of friends one might have in alphabetical order.
The goal is to split the array into a SET of arrays to populate a table view like the Contacts app and ALSO ACCESS the values for a given section. Perhaps utilizing a dictionary might be better to solve this?

答:
A Set is not a good choice for the data source for a table view. A Dictionary is not a good choice either. Both are unordered collections, and a table view's data source needs a definite order. I suggest breaking the source array into an array of arrays, where each sub-array contains all the words that begin with a specific letter, sorted in alphabetical order. The code do that might look like this:

```<code>import UIKit

let strings = ["arf",
               "woofing",
               "flounder",
               "Manbaby",
               "Dogs",
               "baseballs",
               "Suet",
               "Cards",
               "Tiny-fingered, cheeto-faced, ferret-wearing sh*tgibbon",
               "apple",
               "Acorn",
               "Achy-breaky heart",
               "songbirds",
               "Aces"]

let aValue = "a".unicodeScalars.first!.value
let zValue = "z".unicodeScalars.first!.value

var result = [[String]]()
for value in aValue...zValue {
  let aChar = Character(UnicodeScalar(value)!)
  let thisArray = strings
    .filter{$0.lowercased().characters.first! == aChar}
    .sorted{$0.caseInsensitiveCompare($1) == .orderedAscending}
  if !thisArray.isEmpty {
    result.append(thisArray)
  }
}

result.forEach{print($0)}
</code>```

That yields the following output:

```<code>["Aces", "Achy-breaky heart", "Acorn", "apple", "arf"]
["baseballs"]
["Cards"]
["Dogs"]
["flounder"]
["Manbaby"]
["songbirds", "Suet"]
["Tiny-fingered, cheeto-faced, ferret-wearing sh*tgibbon"]
["woofing"]
</code>```

If you want an array with an entry for every letter, even when there are no words beginning with that letter, get rid of the if !thisArray.isEmpty test.

Title: Split and sort string array swift 3

Body:
I'm looking for the most efficient way to go about this. Say there's an array of objects, mapped out in alphabetical order by names:

let objectArray = [AnyObject]()
let abcNameObjectArray = ["Amy", "Bernadette", "Brian", "Chris", "Candice"]

How would I access all the values in this array that have "A" , "B", or "C" based on the first character of each String value in abcNameObject array, in alphabetical order? I'm trying to unload data and return a specific number of rows in the UITableView's cellForRowAt method and numberOfRowsInSection method based on the number of friends one might have in alphabetical order.
The goal is to split the array into a SET of arrays to populate a table view like the Contacts app and ALSO ACCESS the values for a given section. Perhaps utilizing a dictionary might be better to solve this?

Body:
A Set is not a good choice for the data source for a table view. A Dictionary is not a good choice either. Both are unordered collections, and a table view's data source needs a definite order. I suggest breaking the source array into an array of arrays, where each sub-array contains all the words that begin with a specific letter, sorted in alphabetical order. The code do that might look like this:

import UIKit

let strings = ["arf",
               "woofing",
               "flounder",
               "Manbaby",
               "Dogs",
               "baseballs",
               "Suet",
               "Cards",
               "Tiny-fingered, cheeto-faced, ferret-wearing sh*tgibbon",
               "apple",
               "Acorn",
               "Achy-breaky heart",
               "songbirds",
               "Aces"]

let aValue = "a".unicodeScalars.first!.value
let zValue = "z".unicodeScalars.first!.value

var result = [[String]]()
for value in aValue...zValue {
  let aChar = Character(UnicodeScalar(value)!)
  let thisArray = strings
    .filter{$0.lowercased().characters.first! == aChar}
    .sorted{$0.caseInsensitiveCompare($1) == .orderedAscending}
  if !thisArray.isEmpty {
    result.append(thisArray)
  }
}

result.forEach{print($0)}

That yields the following output:

["Aces", "Achy-breaky heart", "Acorn", "apple", "arf"]
["baseballs"]
["Cards"]
["Dogs"]
["flounder"]
["Manbaby"]
["songbirds", "Suet"]
["Tiny-fingered, cheeto-faced, ferret-wearing sh*tgibbon"]
["woofing"]

If you want an array with an entry for every letter, even when there are no words beginning with that letter, get rid of the if !thisArray.isEmpty test.


问:
Cloning infrastructure from one region to another: AWS CloudFormation
I have existing infrastructure in us-east-1 region which needed to be cloned exactly to us-east-2 region. Used AWS CloudFormer to generate the JSON template from existing us-east-1 region, replaced all the us-east-1 with us-east-2 and started creating the stack but getting errors saying "Resource creation cancelled", specifically for all the EC2 instances

A snapshot of the template (only EC2 instance):

```<code>"instancei071dd59b": {
      "Type": "AWS::EC2::Instance",
      "Properties": {
        "DisableApiTermination": "false",
        "InstanceInitiatedShutdownBehavior": "stop",
        "ImageId": "ami-1a41b377",
        "InstanceType": "t2.medium",
        "KeyName": "MyServer",
        "Monitoring": "false",
        "Tags": [
          {
            "Key": "MyServer OS",
            "Value": "Windows Server"
          },
          {
            "Key": "Name",
            "Value": "MyServer_WEB_TEST_2"
          }
        ],
        "Volumes": [
          {
            "Device": "xvdb",
            "VolumeId": {
              "Ref": "volumevol9124b841"
            }
          }
        ],
        "NetworkInterfaces": [
          {
            "DeleteOnTermination": "true",
            "DeviceIndex": 0,
            "SubnetId": {
              "Ref": "subnet24031c0f"
            },
            "PrivateIpAddresses": [
              {
                "PrivateIpAddress": "172.31.53.184",
                "Primary": "true"
              }
            ],
            "GroupSet": [
              {
                "Ref": "sgMyServerWEB"
              }
            ],
            "AssociatePublicIpAddress": "true"
          }
        ]
      }
    },
"volumevol9124b841": {
      "Type": "AWS::EC2::Volume",
      "Properties": {
        "AvailabilityZone": "us-east-2b",
        "Size": "30",
        "SnapshotId": "snap-95288b92",
        "VolumeType": "gp2"
      }
    }
</code>```

答:
For collecting AMI ID in different region, I'd recommend to use the image name instead the AMI ID as the key.

To build resources to be placed in different regions, definitely is better to use CloudFormation. In this case you can use the lambda cli2cloudformation (https://github.com/lucioveloso/cli2cloudformation).

Using it, you can get the AMI ID across all regions and whatever other information that you are able to get using CLI.

To collect the AMI ID, create a lambda with cli2cloudformation and inside your template, create a custom resource as bellow:

```<code>"imageIdNameBased": {
    "Type": "Custom::cli2cfnLambda",
    "Properties": {
      "ServiceToken": "arn:aws:lambda:eu-west-1:123456789012:function:cli2cfnLambda",
      "CliCommandCreate": "ec2 describe-images --filters 'Name=name,Values=amzn-ami-hvm-2017.03.0.20170417-x86_64-gp2' --query 'Images[0]'"
    }
}
</code>```

In this case, I'm getting the AMI ID to the Image named 'amzn-ami-hvm-2017.03.0.20170417-x86_64-gp2'. You can change to your image name.

After that, you can retrieve it in any point of your CloudFormation stack.

```<code>"Fn::GetAtt" : ["imageIdNameBased", "ImageId"]
</code>```

Body:
I have existing infrastructure in us-east-1 region which needed to be cloned exactly to us-east-2 region. Used AWS CloudFormer to generate the JSON template from existing us-east-1 region, replaced all the us-east-1 with us-east-2 and started creating the stack but getting errors saying "Resource creation cancelled", specifically for all the EC2 instances

A snapshot of the template (only EC2 instance):

"instancei071dd59b": {
      "Type": "AWS::EC2::Instance",
      "Properties": {
        "DisableApiTermination": "false",
        "InstanceInitiatedShutdownBehavior": "stop",
        "ImageId": "ami-1a41b377",
        "InstanceType": "t2.medium",
        "KeyName": "MyServer",
        "Monitoring": "false",
        "Tags": [
          {
            "Key": "MyServer OS",
            "Value": "Windows Server"
          },
          {
            "Key": "Name",
            "Value": "MyServer_WEB_TEST_2"
          }
        ],
        "Volumes": [
          {
            "Device": "xvdb",
            "VolumeId": {
              "Ref": "volumevol9124b841"
            }
          }
        ],
        "NetworkInterfaces": [
          {
            "DeleteOnTermination": "true",
            "DeviceIndex": 0,
            "SubnetId": {
              "Ref": "subnet24031c0f"
            },
            "PrivateIpAddresses": [
              {
                "PrivateIpAddress": "172.31.53.184",
                "Primary": "true"
              }
            ],
            "GroupSet": [
              {
                "Ref": "sgMyServerWEB"
              }
            ],
            "AssociatePublicIpAddress": "true"
          }
        ]
      }
    },
"volumevol9124b841": {
      "Type": "AWS::EC2::Volume",
      "Properties": {
        "AvailabilityZone": "us-east-2b",
        "Size": "30",
        "SnapshotId": "snap-95288b92",
        "VolumeType": "gp2"
      }
    }

Body:
For collecting AMI ID in different region, I'd recommend to use the image name instead the AMI ID as the key.

To build resources to be placed in different regions, definitely is better to use CloudFormation. In this case you can use the lambda cli2cloudformation (https://github.com/lucioveloso/cli2cloudformation).

Using it, you can get the AMI ID across all regions and whatever other information that you are able to get using CLI.

To collect the AMI ID, create a lambda with cli2cloudformation and inside your template, create a custom resource as bellow:

"imageIdNameBased": {
    "Type": "Custom::cli2cfnLambda",
    "Properties": {
      "ServiceToken": "arn:aws:lambda:eu-west-1:123456789012:function:cli2cfnLambda",
      "CliCommandCreate": "ec2 describe-images --filters 'Name=name,Values=amzn-ami-hvm-2017.03.0.20170417-x86_64-gp2' --query 'Images[0]'"
    }
}

In this case, I'm getting the AMI ID to the Image named 'amzn-ami-hvm-2017.03.0.20170417-x86_64-gp2'. You can change to your image name.

After that, you can retrieve it in any point of your CloudFormation stack.

"Fn::GetAtt" : ["imageIdNameBased", "ImageId"]


问:
Error using Vlookup and Table as range for data pull macro
```<code>Private Sub Search_Click()
    On Error GoTo MyErrorHandler:

Dim PartNumber As String
Dim det As String

PartNumber = PartNumberIN.Text ' take part input from textbox

det = "Part Number: " & Application.WorksheetFunction.VLookup(PartNumber, Application.WorksheetFunction.Offset(Table1, 0, 2), 3, False)
det = det & vbNewLine & "Part Description: " & Application.WorksheetFunction.VLookup(PartNumber, Application.WorksheetFunction.Offset(Table1, 0, 4), 5, False)
det = det & vbNewLine & "CV or VA: " & Application.WorksheetFunction.VLookup(PartNumber, Application.WorksheetFunction.Offset(Table1, 0, 1), 2, False)
det = det & vbNewLine & "Direct Ship?: " & Application.WorksheetFunction.VLookup(PartNumber, Application.WorksheetFunction.Offset(Table1, 0, 3), 4, False)
det = det & vbNewLine & "Storage Container: " & Application.WorksheetFunction.VLookup(PartNumber, Application.WorksheetFunction.Offset(Table1, 0, 6), 7, False)
det = det & vbNewLine & "SAP Location: " & Application.WorksheetFunction.VLookup(PartNumber, Application.WorksheetFunction.Offset(Table1, 0, 13), 14, False)
det = det & vbNewLine & "Physical Location: " & Application.WorksheetFunction.VLookup(PartNumber, Application.WorksheetFunction.Offset(Table1, 0, 14), 15, False)
MsgBox "Part Details : " & vbNewLine & det
Exit Sub

MyErrorHandler:
If Err.Number = 1004 Then
    MsgBox "Part not present in table."
ElseIf Err.Number = 13 Then
    MsgBox "You have entered an invalid value"
ElseIf Err.Number = 429 Then
    MsgBox "You're toast"
End If
</code>```

The message box should display:
Part Number: (DATA PULLED)
CV or VA: ""
Direct Ship: ""

and so forth.

The data is pulled from a table on a separate sheet than the macro button.
The button simply opens the userform.

Looking for help. The reason the table is used as a range is that this data will be updated regularly, and a named dynamic range does not work.

答:
A bit simplified: I'm not following your use of Offset here, so you may need to adjust some of the column numbers...</p>

```<code>Private Sub Search_Click()

    Dim PartNumber As String
    Dim det As String, m, rng

    'get the table's data range
    Set rng = ThisWorkbook.Sheets("Sheet1").ListObjects("table1").DataBodyRange
    'Debug.Print rng.Address
    PartNumber = PartNumberIN.Text ' take part input from textbox

    'locate the row if there's a match in the first column
    m = Application.Match(PartNumber, rng.Columns(1), 0)
    If Not IsError(m) Then
        'got a match, so construct the message
        With rng.Rows(m)
            det = "Part Number: " & PartNumber
            det = det & vbNewLine & .Cells(5).Value
            'etc...
            MsgBox "Part Details : " & vbNewLine & det
        End With
    Else
        'no match
        MsgBox "Part not present in table."
    End If

End Sub
</code>```

Body:
Private Sub Search_Click()
    On Error GoTo MyErrorHandler:

Dim PartNumber As String
Dim det As String

PartNumber = PartNumberIN.Text ' take part input from textbox

det = "Part Number: " & Application.WorksheetFunction.VLookup(PartNumber, Application.WorksheetFunction.Offset(Table1, 0, 2), 3, False)
det = det & vbNewLine & "Part Description: " & Application.WorksheetFunction.VLookup(PartNumber, Application.WorksheetFunction.Offset(Table1, 0, 4), 5, False)
det = det & vbNewLine & "CV or VA: " & Application.WorksheetFunction.VLookup(PartNumber, Application.WorksheetFunction.Offset(Table1, 0, 1), 2, False)
det = det & vbNewLine & "Direct Ship?: " & Application.WorksheetFunction.VLookup(PartNumber, Application.WorksheetFunction.Offset(Table1, 0, 3), 4, False)
det = det & vbNewLine & "Storage Container: " & Application.WorksheetFunction.VLookup(PartNumber, Application.WorksheetFunction.Offset(Table1, 0, 6), 7, False)
det = det & vbNewLine & "SAP Location: " & Application.WorksheetFunction.VLookup(PartNumber, Application.WorksheetFunction.Offset(Table1, 0, 13), 14, False)
det = det & vbNewLine & "Physical Location: " & Application.WorksheetFunction.VLookup(PartNumber, Application.WorksheetFunction.Offset(Table1, 0, 14), 15, False)
MsgBox "Part Details : " & vbNewLine & det
Exit Sub

MyErrorHandler:
If Err.Number = 1004 Then
    MsgBox "Part not present in table."
ElseIf Err.Number = 13 Then
    MsgBox "You have entered an invalid value"
ElseIf Err.Number = 429 Then
    MsgBox "You're toast"
End If

The message box should display:
Part Number: (DATA PULLED)
CV or VA: ""
Direct Ship: ""

and so forth.

The data is pulled from a table on a separate sheet than the macro button.
The button simply opens the userform.

Looking for help. The reason the table is used as a range is that this data will be updated regularly, and a named dynamic range does not work.

Body:
A bit simplified: I'm not following your use of Offset here, so you may need to adjust some of the column numbers...

Private Sub Search_Click()

    Dim PartNumber As String
    Dim det As String, m, rng

    'get the table's data range
    Set rng = ThisWorkbook.Sheets("Sheet1").ListObjects("table1").DataBodyRange
    'Debug.Print rng.Address
    PartNumber = PartNumberIN.Text ' take part input from textbox

    'locate the row if there's a match in the first column
    m = Application.Match(PartNumber, rng.Columns(1), 0)
    If Not IsError(m) Then
        'got a match, so construct the message
        With rng.Rows(m)
            det = "Part Number: " & PartNumber
            det = det & vbNewLine & .Cells(5).Value
            'etc...
            MsgBox "Part Details : " & vbNewLine & det
        End With
    Else
        'no match
        MsgBox "Part not present in table."
    End If

End Sub


问:
Chaining promise in loops
I'm facing a complicated promise chain and it looks like the results doesn't wait for the end of the promise.

```<code>return Promise.all([
  Radar.newRadar(1),
  Radar.newRadar(2),
  Radar.newRadar(3)
])
.then( newRadarIds => {
    let RadarNotes = [];
  return Promise.all([
     _.map(newRadarIds, (radar_id) =>{
      return Promise.all([
        Radar.init(radar_id)
      ])
      .then( kpis => {
        return Promise.all([
          Radar.addKpis(radar_id.radar_id, ...)
        ])
        .then( radarAddKpi => {
          RadarNotes.push({
            year : radar_id.year,
            data : kpis[0].data});
            console.log('in map')
          // return {
          //   year : radar_id.year,
          //   data : kpis[0].data}
        })
        .catch( err => {
          console.error(err);
        })
      })

    }) //end map
  ])
  .then(result => {
    console.log('her222e')
    res.json(result)
  })
  .catch (err => {
    console.error(err);
  })
  })
.catch( error => {
  console.error(error);
})
</code>```

I get the output 'here' before the 'in map'. The goal is to fill an array and send it to the client with a res.json call.

What am I missing ?

答:
The culprit is

```<code>return Promise.all([
  _.map(newRadarIds, (radar_id) =>{
    return // a promise
  }) //end map
])
</code>```

which calls Promise.all on an array of arrays of promises. Which wont be awaited. You will want to drop the array literal and pass the result of the map - the array of promises - directly to Promise.all.

Also calling Promise.all([ … ]) with a single-element array (Radar.init, Radar.addKpis) is pretty superfluous (and potentially harmful if you don't expect the result to be an array). Just chain the then directly to the promise you have.

Finally, your result will consist of undefined entries, as your promises don't resolve with anything. You would need to send the RadarNotes explicitly. But better than pushing to that array is to fulfill your promises with each result, so that Promise.all can construct the promise for the array of all results:

```<code>return Promise.all([
  Radar.newRadar(1),
  Radar.newRadar(2),
  Radar.newRadar(3)
])
.then(newRadarIds =>
  Promise.all(_.map(newRadarIds, radar_id =>
    Radar.init(radar_id)
    .then(kpi =>
      Radar.addKpis(radar_id.radar_id, ...)
      .then(radarAddKpi =>
        ({
          year : radar_id.year,
          data : kpi.data
        })
      )
    )
  ))
)
.then(result => {
  res.json(result)
})
.catch (err => {
  console.error(err);
})
</code>```

Title: Chaining promise in loops

Body:
I'm facing a complicated promise chain and it looks like the results doesn't wait for the end of the promise.

return Promise.all([
  Radar.newRadar(1),
  Radar.newRadar(2),
  Radar.newRadar(3)
])
.then( newRadarIds => {
    let RadarNotes = [];
  return Promise.all([
     _.map(newRadarIds, (radar_id) =>{
      return Promise.all([
        Radar.init(radar_id)
      ])
      .then( kpis => {
        return Promise.all([
          Radar.addKpis(radar_id.radar_id, ...)
        ])
        .then( radarAddKpi => {
          RadarNotes.push({
            year : radar_id.year,
            data : kpis[0].data});
            console.log('in map')
          // return {
          //   year : radar_id.year,
          //   data : kpis[0].data}
        })
        .catch( err => {
          console.error(err);
        })
      })

    }) //end map
  ])
  .then(result => {
    console.log('her222e')
    res.json(result)
  })
  .catch (err => {
    console.error(err);
  })
  })
.catch( error => {
  console.error(error);
})

I get the output 'here' before the 'in map'. The goal is to fill an array and send it to the client with a res.json call.

What am I missing ?

Body:
The culprit is

return Promise.all([
  _.map(newRadarIds, (radar_id) =>{
    return // a promise
  }) //end map
])

which calls Promise.all on an array of arrays of promises. Which wont be awaited. You will want to drop the array literal and pass the result of the map - the array of promises - directly to Promise.all.

Also calling Promise.all([ … ]) with a single-element array (Radar.init, Radar.addKpis) is pretty superfluous (and potentially harmful if you don't expect the result to be an array). Just chain the then directly to the promise you have.

Finally, your result will consist of undefined entries, as your promises don't resolve with anything. You would need to send the RadarNotes explicitly. But better than pushing to that array is to fulfill your promises with each result, so that Promise.all can construct the promise for the array of all results:

return Promise.all([
  Radar.newRadar(1),
  Radar.newRadar(2),
  Radar.newRadar(3)
])
.then(newRadarIds =>
  Promise.all(_.map(newRadarIds, radar_id =>
    Radar.init(radar_id)
    .then(kpi =>
      Radar.addKpis(radar_id.radar_id, ...)
      .then(radarAddKpi =>
        ({
          year : radar_id.year,
          data : kpi.data
        })
      )
    )
  ))
)
.then(result => {
  res.json(result)
})
.catch (err => {
  console.error(err);
})


问:
iOS Safari position:fixed doesn't work at all
position:fixed doesn't work on mobile safari browser. I've tried two devices, iPhone7 and 5s with latest Safari versions. I'm losing my mind. No internet trick I've already found could help me. I found one site where my iPhone actually showed me fixed navigation bar. But when I copied that site's source code into my code, my iphone refused to show navbar as fixed element.

```<code>.fixed {
  position:fixed;
  width:100%;
  z-index:1;
  top: 0;
  overflow: hidden;
}
</code>```

Also, these devices don't support any kind of scroll detection, neither window.pageYOffset nor window.parent.pageYOffset nor document.documentElement.scrollTop. All shows 0.
Please, help me. I cant stand this anymore

答:
Try adding the following CSS

```<code>nav{
  -ms-transform: translate3d(0,0,0);
  -webkit-transform: translate3d(0,0,0);
  transform: translate3d(0,0,0);
}
</code>```

If that doesn't work, try this instead

```<code>nav{
  -ms-transform: translateZ(0);
  -webkit-transform: translateZ(0);
  transform: translateZ(0);
}
</code>```

Please let me know if it helps

Body:
position:fixed doesn't work on mobile safari browser. I've tried two devices, iPhone7 and 5s with latest Safari versions. I'm losing my mind. No internet trick I've already found could help me. I found one site where my iPhone actually showed me fixed navigation bar. But when I copied that site's source code into my code, my iphone refused to show navbar as fixed element.

.fixed {
  position:fixed;
  width:100%;
  z-index:1;
  top: 0;
  overflow: hidden;
}

Also, these devices don't support any kind of scroll detection, neither window.pageYOffset nor window.parent.pageYOffset nor document.documentElement.scrollTop. All shows 0.
Please, help me. I cant stand this anymore

Body:
Try adding the following CSS

nav{
  -ms-transform: translate3d(0,0,0);
  -webkit-transform: translate3d(0,0,0);
  transform: translate3d(0,0,0);
}

If that doesn't work, try this instead

nav{
  -ms-transform: translateZ(0);
  -webkit-transform: translateZ(0);
  transform: translateZ(0);
}

Please let me know if it helps


问:
How to reference data with different key in c++
I am new to C++ and need to store a data set. The data set looks like the following

```<code>id | time | value
01 |   1  |   1
01 |   2  |   0
01 |   3  |   1
01 |   4  |   0
01 |   5  |   1
02 |   1  |   2
02 |   2  |   3
02 |   3  |   7
02 |   4  |   9
02 |   5  |   5
</code>```

I would like to be able to search the data either by id or by time, i.e.

```<code>GetValueByID(data, '01')
# id | time | value
# 01 |   1  |   1
# 01 |   2  |   0
# 01 |   3  |   1
# 01 |   4  |   0
# 01 |   5  |   1

GetValueByID(data, '2')
# id | time | value
# 01 |   2  |   0
# 02 |   2  |   3
</code>```

What would be the most memory efficient way of doing this?
Thank you!

答:
The most memory efficient method is to create a class with ID, Time and Value members, then use a std::vector of the class.

For run-time efficiency, you want to create an index table or std::map containing the search key field and the index of the item in the vector.  Create one map for ID and another for the Time field.  This is a common approach with database tables.

Edit 1: Duplicate keys

You use std::map if the key fields are unique.  Use an unordered map when keys are not unique.

Body:
I am new to C++ and need to store a data set. The data set looks like the following

id | time | value
01 |   1  |   1
01 |   2  |   0
01 |   3  |   1
01 |   4  |   0
01 |   5  |   1
02 |   1  |   2
02 |   2  |   3
02 |   3  |   7
02 |   4  |   9
02 |   5  |   5

I would like to be able to search the data either by id or by time, i.e.

GetValueByID(data, '01')
# id | time | value
# 01 |   1  |   1
# 01 |   2  |   0
# 01 |   3  |   1
# 01 |   4  |   0
# 01 |   5  |   1

GetValueByID(data, '2')
# id | time | value
# 01 |   2  |   0
# 02 |   2  |   3

What would be the most memory efficient way of doing this?
Thank you!


问:
Integer Array inside if/Elif Statement
I currently have the following code, which appends lines of a text file to respective lists if they begin with a certain number.

Is there a way I can and use a numerical array and loop to save some lines of code? The number just needs to stop at 9.

Thank you.

```<code>for number in f:
if number.startswith('1'):
        startsw1.append(number)
elif number.startswith('2'):
        startsw2.append(number)
elif number.startswith('3'):
        startsw3.append(number)
elif number.startswith('4'):
        startsw4.append(number)
elif number.startswith('5'):
        startsw5.append(number)
elif number.startswith('6'):
    startsw6.append(number)
elif number.startswith('7'):
    startsw7.append(number)
elif number.startswith('8'):
        startsw8.append(number)
elif number.startswith('9'):
    startsw9.append(number)
</code>```

答:
I realize that you requested to use a list to hold your lists, but I think that using a dictionary will be more natural. The way that you use the code will end up being identical, but if for some reason in the future you need to support more than just indexing by integers then you won't have to change anything.

A default dictionary is the most natural solution.

```<code>from collections import defaultdict
starts_with = defaultdict(list)
for number in f:
    # Probably should have some error handling in case the first
    # character cannot be converted to an int.
    starts_with[int(number[0])].append(number)
</code>```

The nice thing here is that you don't have to preallocate your starts_with object like you would have to with a list. You can even simply store the keys as strings (i.e. '1') instead of ints if you wish.

Please note that this assumes that you will use this starts_with dictionary instead of nine different list variables startsw1..startsw9, which in the long run will end up being easier to maintain.

Title: Integer Array inside if/Elif Statement

Body:
I currently have the following code, which appends lines of a text file to respective lists if they begin with a certain number.

Is there a way I can and use a numerical array and loop to save some lines of code? The number just needs to stop at 9.

Thank you.

for number in f:
if number.startswith('1'):
        startsw1.append(number)
elif number.startswith('2'):
        startsw2.append(number)
elif number.startswith('3'):
        startsw3.append(number)
elif number.startswith('4'):
        startsw4.append(number)
elif number.startswith('5'):
        startsw5.append(number)
elif number.startswith('6'):
    startsw6.append(number)
elif number.startswith('7'):
    startsw7.append(number)
elif number.startswith('8'):
        startsw8.append(number)
elif number.startswith('9'):
    startsw9.append(number)

Body:
I realize that you requested to use a list to hold your lists, but I think that using a dictionary will be more natural. The way that you use the code will end up being identical, but if for some reason in the future you need to support more than just indexing by integers then you won't have to change anything.

A default dictionary is the most natural solution.

from collections import defaultdict
starts_with = defaultdict(list)
for number in f:
    # Probably should have some error handling in case the first
    # character cannot be converted to an int.
    starts_with[int(number[0])].append(number)

The nice thing here is that you don't have to preallocate your starts_with object like you would have to with a list. You can even simply store the keys as strings (i.e. '1') instead of ints if you wish.

Please note that this assumes that you will use this starts_with dictionary instead of nine different list variables startsw1..startsw9, which in the long run will end up being easier to maintain.


问:
bootstrap position fixed doesn't work with one column
I started making my new layout with bootstrap grid system i actually made rows and columns First row is my headerrow i embed the column in the header section
i made a class in css and i put the position:fixed thing into it. then i added the class to the column. The class contains red background etc it works but the position:fixed doesnt work when i try to scroll down its just stays there. position:fixed; is outlined in chrome :/ why?

http://kephost.com/images/2017/07/07/riiiii.jpg

答:
Because position: fixed has overrided by bootstrap's default position. col-xx-xx has a position: relative rule.

You do not need to add your class "headerUpper" to the bootstrap column. You should add it to it parents element. Like following code:

```<code><div class="headerUpper">
    <div class="row">
        <div class="col-sm-12">
        ...
        </div>
    </div>
</div>
</code>```

You also can use bootstrap's affix feature for fixed element - http://getbootstrap.com/javascript/#affix.

Body:
Because position: fixed has overrided by bootstrap's default position. col-xx-xx has a position: relative rule.

You do not need to add your class "headerUpper" to the bootstrap column. You should add it to it parents element. Like following code:

<div class="headerUpper">
    <div class="row">
        <div class="col-sm-12">
        ...
        </div>
    </div>
</div>

You also can use bootstrap's affix feature for fixed element - http://getbootstrap.com/javascript/#affix.