问:
Why is matrix subtraction much slower than dot product in numpy?
Let's say we have a vector and a matrix:

```<code>X = np.random.random((1, 384)).astype('float32')
Y = np.random.random((500000, 384)).astype('float32')
</code>```

Why is np.dot(X, Y.T) much faster than X - Y?

```<code>In [8]: %timeit np.dot(X, Y.T)
10 loops, best of 3: 42.4 ms per loop

In [9]: %timeit X - Y
1 loop, best of 3: 501 ms per loop
</code>```

What can I do to make subtraction like this as faster as dot product?

答:
The size of the output matters, because the output has to be written to memory, and writing a large array takes time. The shape of dot(X, Y.T)  is (1, 500000). The shape of X-Y is (500000, 384).

In my test, most of the time taken by X-Y was allocating an array for the output. Compare:

```<code>%timeit X - Y
1 loop, best of 3: 449 ms per loop
</code>```

with pre-allocated space Z = np.zeros_like(Y),

```<code>%timeit np.subtract(X, Y, out=Z)
10 loops, best of 3: 181 ms per loop
</code>```

So, if you have to do this kind of subtraction repeatedly, having a pre-allocated array of suitable shape and type will save more than half of the execution time.

I don't think that subtraction in your case can be made as fast as multiplication. The amount of arithmetics to do is about the same: each entry of X meets 500000 entries of Y either way. The fact that the results are combined when you do multiplication (the summation step) only helps, as the CPU does it quickly with the numbers it already has lying around, and as a result it has only one number to send back. So: about the same amount of work, but the amount of memory-writing is 384 times more for the case of subtraction.

Here is a proof that subtraction is faster when the output size is the same for both (square matrices):

```<code>X = np.random.random((1000, 1000)).astype('float32')
Y = np.random.random((1000, 1000)).astype('float32')

%timeit np.dot(X, Y.T)
100 loops, best of 3: 28.7 ms per loop

%timeit X - Y
1000 loops, best of 3: 579 µs per loop
</code>```

Body:
Let's say we have a vector and a matrix:

X = np.random.random((1, 384)).astype('float32')
Y = np.random.random((500000, 384)).astype('float32')

Why is np.dot(X, Y.T) much faster than X - Y?

In [8]: %timeit np.dot(X, Y.T)
10 loops, best of 3: 42.4 ms per loop

In [9]: %timeit X - Y
1 loop, best of 3: 501 ms per loop

What can I do to make subtraction like this as faster as dot product?

Body:
The size of the output matters, because the output has to be written to memory, and writing a large array takes time. The shape of dot(X, Y.T)  is (1, 500000). The shape of X-Y is (500000, 384).

In my test, most of the time taken by X-Y was allocating an array for the output. Compare:

%timeit X - Y
1 loop, best of 3: 449 ms per loop

with pre-allocated space Z = np.zeros_like(Y),

%timeit np.subtract(X, Y, out=Z)
10 loops, best of 3: 181 ms per loop

So, if you have to do this kind of subtraction repeatedly, having a pre-allocated array of suitable shape and type will save more than half of the execution time.

I don't think that subtraction in your case can be made as fast as multiplication. The amount of arithmetics to do is about the same: each entry of X meets 500000 entries of Y either way. The fact that the results are combined when you do multiplication (the summation step) only helps, as the CPU does it quickly with the numbers it already has lying around, and as a result it has only one number to send back. So: about the same amount of work, but the amount of memory-writing is 384 times more for the case of subtraction.

Here is a proof that subtraction is faster when the output size is the same for both (square matrices):

X = np.random.random((1000, 1000)).astype('float32')
Y = np.random.random((1000, 1000)).astype('float32')

%timeit np.dot(X, Y.T)
100 loops, best of 3: 28.7 ms per loop

%timeit X - Y
1000 loops, best of 3: 579 µs per loop


来源: stackexchange

问:
Scala throws an exception when I try to launch it on ubuntu
I am trying to launch scala on Ubuntu 16.04.3. I installed java and scala but when I type scala in the terminal, all of a sudden it throws an exception.

Step 1: Installating Java and Scala

First, I Installed Java by following these steps described in How to install java:

```<code> - $sudo apt-get update
 - $sudo apt-get install default-jre
 - $sudo apt-get install default-jdk
 - $sudo add-apt-repository ppa:webupd8team/java
 - $sudo apt-get update
 - $sudo apt-get install oracle-java9-installer
</code>```

When I type $java -version I get:

```<code>java version "9.0.1"
Java(TM) SE Runtime Environment (build 9.0.1+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.1+11, mixed mode)
</code>```

Second, I installed scala by using the following command $sudo apt-get install scala

Step 2: Running scala

From the console when I type $scala I get the following exception:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: javax/script/Compilable
    at scala.tools.nsc.interpreter.ILoop.createInterpreter(ILoop.scala:126)
    at scala.tools.nsc.interpreter.ILoop$$anonfun$process$1.apply$mcZ$sp(ILoop.scala:908)
    at scala.tools.nsc.interpreter.ILoop$$anonfun$process$1.apply(ILoop.scala:906)
    at scala.tools.nsc.interpreter.ILoop$$anonfun$process$1.apply(ILoop.scala:906)
    at scala.reflect.internal.util.ScalaClassLoader$.savingContextLoader(ScalaClassLoader.scala:97)
    at scala.tools.nsc.interpreter.ILoop.process(ILoop.scala:906)
    at scala.tools.nsc.MainGenericRunner.runTarget$1(MainGenericRunner.scala:74)
    at scala.tools.nsc.MainGenericRunner.run$1(MainGenericRunner.scala:87)
    at scala.tools.nsc.MainGenericRunner.process(MainGenericRunner.scala:98)
    at scala.tools.nsc.MainGenericRunner$.main(MainGenericRunner.scala:103)
    at scala.tools.nsc.MainGenericRunner.main(MainGenericRunner.scala)
</code>```

答:
It seems that there are various issues with Scala in combination with Java9
( see here for example ).

The upcoming release Scala 2.12.4 is supposed to fix some of these.

At this point in time, the "best" option is probably to not install Java9, but to go with Java8. See here for guidance how to do that.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to launch scala on Ubuntu 16.04.3. I installed java and scala but when I type scala in the terminal, all of a sudden it throws an exception.

Step 1: Installating Java and Scala

First, I Installed Java by following these steps described in How to install java:

 - $sudo apt-get update
 - $sudo apt-get install default-jre
 - $sudo apt-get install default-jdk
 - $sudo add-apt-repository ppa:webupd8team/java
 - $sudo apt-get update
 - $sudo apt-get install oracle-java9-installer

When I type $java -version I get:

java version "9.0.1"
Java(TM) SE Runtime Environment (build 9.0.1+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.1+11, mixed mode)

Second, I installed scala by using the following command $sudo apt-get install scala

Step 2: Running scala

From the console when I type $scala I get the following exception:

Exception in thread "main" java.lang.NoClassDefFoundError: javax/script/Compilable
    at scala.tools.nsc.interpreter.ILoop.createInterpreter(ILoop.scala:126)
    at scala.tools.nsc.interpreter.ILoop$$anonfun$process$1.apply$mcZ$sp(ILoop.scala:908)
    at scala.tools.nsc.interpreter.ILoop$$anonfun$process$1.apply(ILoop.scala:906)
    at scala.tools.nsc.interpreter.ILoop$$anonfun$process$1.apply(ILoop.scala:906)
    at scala.reflect.internal.util.ScalaClassLoader$.savingContextLoader(ScalaClassLoader.scala:97)
    at scala.tools.nsc.interpreter.ILoop.process(ILoop.scala:906)
    at scala.tools.nsc.MainGenericRunner.runTarget$1(MainGenericRunner.scala:74)
    at scala.tools.nsc.MainGenericRunner.run$1(MainGenericRunner.scala:87)
    at scala.tools.nsc.MainGenericRunner.process(MainGenericRunner.scala:98)
    at scala.tools.nsc.MainGenericRunner$.main(MainGenericRunner.scala:103)
    at scala.tools.nsc.MainGenericRunner.main(MainGenericRunner.scala)


问:
python - converting objects to float in list of lists
I'm trying to make a program in Python 3 where user gives multiple values in one input separated by space and these values are added to a list in form of a list, thus creating a list of lists. But I just cant convert these values to float.

This is the "base" of the code:

```<code>lst = []
ln = input()
values = ln.split(" ")
lst.extend([values])
while ln != "":
    ln = input()
    values = ln.split(" ")
    lst.extend([values])
</code>```

Which would give me list like this

```<code>[['1', '2'], ['3', '4']]
</code>```

So the problem is that I cannot convert these strings to floats. One of the ways I've tried is

```<code>for i in lst:
    for j in i:
        j = float(j)
</code>```

Which just gives me "ValueError: could not convert string to float:". I've also tried mapping but that doesn't work either.

答:
The most straight forward approach is to convert the strings in your sub-lists to floats before appending the sub-lists to your final list. That means use

```<code>values = list(map(float, ln.split(" ")))
</code>```

Alternatively, you can post-process your list of lists like this:

```<code>>>> lst = [['1', '2', '3'], ['4', '5', '6']]
>>> lst = [list(map(float, sublist)) for sublist in lst]
>>> lst
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]
</code>```

... which also has a nested list-comprehension version:

```<code>>>> [[float(x) for x  in sublist] for sublist in lst]
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]
</code>```

... which if you are new to Python might want to write as

```<code>>>> lst = [['1', '2', '3'], ['4', '5', '6']]
>>> result = []
>>>
>>> for sublist in lst:
...     float_sublist = []
...     for x in sublist:
...         float_sublist.append(float(x))
...     result.append(float_sublist)
...
>>> result
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]
</code>```

In addition, but unrelated, use lst.append(values) instead of lst.extend([values]). The effect is the same, but the latter one looks weird and goes against the intended use-case for extend - appending objects from an iterable one by one, which you suppress by wrapping your iterable values in another iterable by passing [values].

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to make a program in Python 3 where user gives multiple values in one input separated by space and these values are added to a list in form of a list, thus creating a list of lists. But I just cant convert these values to float.

This is the "base" of the code:

lst = []
ln = input()
values = ln.split(" ")
lst.extend([values])
while ln != "":
    ln = input()
    values = ln.split(" ")
    lst.extend([values])

Which would give me list like this

[['1', '2'], ['3', '4']]

So the problem is that I cannot convert these strings to floats. One of the ways I've tried is

for i in lst:
    for j in i:
        j = float(j)

Which just gives me "ValueError: could not convert string to float:". I've also tried mapping but that doesn't work either.

Body:
The most straight forward approach is to convert the strings in your sub-lists to floats before appending the sub-lists to your final list. That means use

values = list(map(float, ln.split(" ")))

Alternatively, you can post-process your list of lists like this:

>>> lst = [['1', '2', '3'], ['4', '5', '6']]
>>> lst = [list(map(float, sublist)) for sublist in lst]
>>> lst
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]

... which also has a nested list-comprehension version:

>>> [[float(x) for x  in sublist] for sublist in lst]
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]

... which if you are new to Python might want to write as

>>> lst = [['1', '2', '3'], ['4', '5', '6']]
>>> result = []
>>>
>>> for sublist in lst:
...     float_sublist = []
...     for x in sublist:
...         float_sublist.append(float(x))
...     result.append(float_sublist)
...
>>> result
[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]

In addition, but unrelated, use lst.append(values) instead of lst.extend([values]). The effect is the same, but the latter one looks weird and goes against the intended use-case for extend - appending objects from an iterable one by one, which you suppress by wrapping your iterable values in another iterable by passing [values].


问:
How to implement thread pool that will automatically shutdown at end of execution?
I'm writing a Java client which could theoretically be used in a different environment: Java main(), in a servlet container, or via dependency injection.

The client implements internal connection thread pooling.

The problem with this approach is that users of the client that are unaware of the fact that an internal thread pool is implemented will see his or her application "hang" on shutdown.  My users need to know to send a shutdown() message to the library.

I'm wondering if any other alternative approach could be taken that would, on one hand, allow me to start a thread pool for my connections; and, on the other hand, catch some event, perhaps a JVM event, that indicates the JVM is going down, which will allow me to call my shutdown() implementation.

答:
Although you can add hooks, as was previous suggested, the problem you're still likely to have is the thread-pool still having active threads.

I believe that if you mark your individual threads as "daemons" (via Thread.setDaemon method) then the JVM will not keep alive if only daemon threads are left.

From the JavaDoc:

Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads.

Using this, if your primary non-daemon thread is terminated, the JVM won't "hang-up" because of the other thread running, and this trigger your shutdown hooks without having to explicitly send terminate instructions to the various threads.

ContentLicense: CC BY-SA 2.5


问:
Index renaming fails with curl
I try to rename my index with the intruction enter link description here
and I run the intructions in this way:

```<code>    curl -XPOST '<ip>:9200/ -H 'Content-Type: application/json' -d'
    {
       "source": {
         "index": "app_access_446"
       },
       "dest": {
         "index": "app_access_447"
       }
    }
    '
</code>```

But I get this response

```<code>   {"error":{"root_cause":[{"type":"illegal_argument_exception","reason":"invalid version format: -H CONTENT-TYPE: HTTP/1.1"}],"type":"illegal_argument_exception","reason":"invalid version format: -H CONTENT-TYPE: HTTP/1.1"},"status":400}curl: (3) [globbing] nested braces not supported at pos 36
</code>```

What I am doing wrong?

greetings niesel

答:
```<code>curl -XPOST '<ip>:9200/_reindex' -H 'Content-Type: application/json' -d'
{
   "source": {
     "index": "app_access_446"
   },
   "dest": {
     "index": "app_access_447"
   }
}
'
</code>```

Title: Index renaming fails with curl

Body:
I try to rename my index with the intruction enter link description here
and I run the intructions in this way:

    curl -XPOST '<ip>:9200/ -H 'Content-Type: application/json' -d'
    {
       "source": {
         "index": "app_access_446"
       },
       "dest": {
         "index": "app_access_447"
       }
    }
    '

But I get this response

   {"error":{"root_cause":[{"type":"illegal_argument_exception","reason":"invalid version format: -H CONTENT-TYPE: HTTP/1.1"}],"type":"illegal_argument_exception","reason":"invalid version format: -H CONTENT-TYPE: HTTP/1.1"},"status":400}curl: (3) [globbing] nested braces not supported at pos 36

What I am doing wrong?

greetings niesel


问:
Swift 3 macOS, set default button style
When I create a new NSButton, how can I set it's style to the Default one?

```<code>let (nomplusbut) = NSButton(frame: CGRect(x: 200, y: iy, width: 300, height: 40))
(nomplusbut).title = "Pfad öffnen..."
(nomplusbut).target = (self, action: #selector(buttonAction)) as AnyObject?
(nomplusbut).isBordered = true
(nomplusbut).setButtonType(NSMomentaryPushInButton)

arraybut.append(nomplusbut)

print(array[array.count - 1].stringValue)
self.view.addSubview(arraybut[arraybut.count - 1])
</code>```

Style I want to have:

Current Style:

答:
You should change the button's bezelStyle to rounded, e.g.:

```<code>nomplusbut.bezelStyle = .rounded
</code>```

Title: Swift 3 macOS, set default button style

Body:
When I create a new NSButton, how can I set it's style to the Default one?

let (nomplusbut) = NSButton(frame: CGRect(x: 200, y: iy, width: 300, height: 40))
(nomplusbut).title = "Pfad öffnen..."
(nomplusbut).target = (self, action: #selector(buttonAction)) as AnyObject?
(nomplusbut).isBordered = true
(nomplusbut).setButtonType(NSMomentaryPushInButton)

arraybut.append(nomplusbut)

print(array[array.count - 1].stringValue)
self.view.addSubview(arraybut[arraybut.count - 1])

Style I want to have:

Current Style:

Body:
You should change the button's bezelStyle to rounded, e.g.:

nomplusbut.bezelStyle = .rounded


问:
Azure SQL Data Migration Assistant is Stuck on “Migrate Data”
I am in the process of using the Data Migration Assistant to move a local DB to Aszure SQL.  The schema transfer went well, and 243 of the 246 tables all were able to transfer their data with no errors.

However, the transfer has been running for 13+ hours, and over the last three hours, three of the tables have not budged on their percent complete.  One is at 92.3%, one is at 93.9%, and the last is at 98.5%.

Some questions:

At this point, can I safely assume that this is a failed transfer, at least of these three tables?

I don't see a "stop" button.  If I wanted to, how would I abort this process?

If I were to abort the process, is there some way to manually finish the transfer of data from just these three tables?

答:
A Microsoft Engineer examined the logs you shared with us and found the following error:

Dma.exe Information: 0 : 'Exception type: System.IO.IOException
      Message:
          There is not enough space on the disk.

It seems like workstation that DMA is running on doesn’t have enough disk space to do schema extract.

The following is the explanation the Microsoft engineer shared with us about why DMA requires disk space:

The Extract service connects to a database, reads all of its objects
  and their properties, and then creates an in-memory model of the
  database. Similar to how the Build service validates the defined
  objects, the Extract service also checks for consistency and
  containment. The validation done here will also result in failures if
  you have a view that refers to a non-existent table same as with
  T-SQL! Additionally, unsupported or uncontained objects are blocked
  because these objects are not yet allowed in SQL Azure or the DAC
  in-memory model. Finally, once the in-memory model is complete and
  validated, a DACPAC is written to disk. Looking at the stack it’s a
  well-known Windows exception on not enough disk space.


问:
CUDA installation on Windows
I installed CUDA Toolkit 3.2, CUDA SDK and MS Visual Studio  2008 (not necessarily in this order) on my Windows 7 that does not have an nvidia graphics card.
But when I try running my CUDA code, the CUDA keywords are'nt identified.
I am a beginner. Pls tell me what I am doing wrong here.

Thanks

答:
You should be able to build the SDK samples with your setup, but you won't be able to run since you do not have a CUDA capable GPU. Emulation is no longer supported, so you have a couple of options available:

gpuocelot

PGI CUDA x86

Check out this stackoverflow post for details of syntax highlighting and more in VS2008.

Incidentally, if you installed the Toolkit before VS2008 then the rules files will not have been copied to the VS directories (clearly, since they didn't exist). You can find them and instructions in the CUDA Toolkit in the extras directory.

Title: CUDA installation on Windows


问:
How do I properly format this table?

I'm trying to properly format a table so that it prints out values below each column, beginning with the first character of that column. I've had success formatting three columns, but I'm unable to figure out how to format the K Count and LM Count columns so that they are printed out in a neat fashion.

What are some corrections I can make to the while loop portion of the code so that the K count and LM count columns are printed out neatly?

```<code>void printTable(const vector<int>& z, const vector<long>& x, const
vector<long>& y,
const vector<int>& a, const vector<int>& b)
{
ostringstream ss;
ss << "\n\n\n" << setw(10) << left << "Digits" << "Input Numbers       "
    << setw(11) << right << "K Output   " << setw(6)
    << right << "K Count     " << setw(10) << right << "LM Output   " << setw(6)
    << right << "LM Count" << endl;

int i = 0, n = 0;
while (i < 5)
{
    string q = to_string(z[2*n]) + " x " + to_string(z[abs(2*n + 1)]);
    string r = to_string(x[i]);
    string s = to_string(a[i]);
    string t = to_string(y[i]);
    string u = to_string(b[i]);

    ss << setw(10) << left << (i+1) <<  q
        << setw(16) << right << r
        << setw(11) << right << s
        << setw(12) << right << t
        << setw(10) << right << u << endl;

    i++;
    n++;
}

string r = ss.str();
cout << r;
}
</code>```

答:
You're printing the following:

- Digits left aligned over 10 chars

- Directly followed by the input number without specifying the width

- K output right aligned over 16 chars

You should instead specify the width of the input numbers as well.

Try this:

```<code>ss << setw(10) << left  << (i+1) <<
      setw(16) << left  << q <<
      setw(10) << right << s <<
      setw(12) << right << t <<
...
</code>```

The exact width of each column may not be correct. Try it out yourself.

Title: How do I properly format this table?

Body:
I'm trying to properly format a table so that it prints out values below each column, beginning with the first character of that column. I've had success formatting three columns, but I'm unable to figure out how to format the K Count and LM Count columns so that they are printed out in a neat fashion.

What are some corrections I can make to the while loop portion of the code so that the K count and LM count columns are printed out neatly?

void printTable(const vector<int>& z, const vector<long>& x, const
vector<long>& y,
const vector<int>& a, const vector<int>& b)
{
ostringstream ss;
ss << "\n\n\n" << setw(10) << left << "Digits" << "Input Numbers       "
    << setw(11) << right << "K Output   " << setw(6)
    << right << "K Count     " << setw(10) << right << "LM Output   " << setw(6)
    << right << "LM Count" << endl;

int i = 0, n = 0;
while (i < 5)
{
    string q = to_string(z[2*n]) + " x " + to_string(z[abs(2*n + 1)]);
    string r = to_string(x[i]);
    string s = to_string(a[i]);
    string t = to_string(y[i]);
    string u = to_string(b[i]);

    ss << setw(10) << left << (i+1) <<  q
        << setw(16) << right << r
        << setw(11) << right << s
        << setw(12) << right << t
        << setw(10) << right << u << endl;

    i++;
    n++;
}

string r = ss.str();
cout << r;
}

Body:
You're printing the following:

- Digits left aligned over 10 chars

- Directly followed by the input number without specifying the width

- K output right aligned over 16 chars

You should instead specify the width of the input numbers as well.

Try this:

ss << setw(10) << left  << (i+1) <<
      setw(16) << left  << q <<
      setw(10) << right << s <<
      setw(12) << right << t <<
...

The exact width of each column may not be correct. Try it out yourself.


问:
Horizontal line with different colours
How I can modify this code to have different colors for lines (for example Black, red, green)

```<code>library(ggplot2)

    lt <- data.frame(yint = c(200, 250, 210, 215, 279, 280),
                     grp  = factor(c(1, 1, 2, 2, 3, 3),
                                   levels = 1:3,
                                   labels = c("Group 1", "Group 2", "Group 3")))

    ggplot(mtcars, aes(mpg, disp)) +
          geom_point(aes(colour=factor(vs),
          fill = factor(vs)), shape=21, size = 4) +
          scale_fill_manual(values=c("blue", "pink")) +
          scale_colour_manual(values=c("black", "black"))+
          geom_hline(data = lt,
                     mapping = aes(yintercept = yint, linetype = grp))
</code>```

I tried to use this function buT I got the error

```<code>ggplot(DataSet, aes(AGE, RESULT)) +
      geom_point(aes(colour=PATIENT.SEX,
      fill = PATIENT.SEX), shape=21, size = 1.4) +
      scale_fill_manual(values=c("hotpink", "skyblue2")) +
      scale_colour_manual(values=c("hotpink", "skyblue2"))+
      ylab("Potassium (mmol/L) ")+xlab("Age (month) ")+ggtitle("Alberta observations")+theme_bw()+
      theme(plot.title = element_text(lineheight=.8, face="bold",size=13))+
      theme(axis.text=element_text(size=12),axis.title=element_text(size=12,face="bold"))+
      theme(panel.border = element_blank(), panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"))+
      geom_hline(data = lt,
                 mapping = aes(yintercept = yint,linetype = RI),colour
=c("blue","blue", "red", "red", "black","black" ))
</code>```

答:
One "brute force" option available starting in the current development version of ggplot2, 2.2.1.9000, is to set colors outside of aes.  The colors you give either has to be length 1 (all colors the same) or the same length as the dataset used in that layer.

In your example you have 6 rows in your dataset to make 6 horizontal lines so I give 6 colors.

If using this method you have to be careful to get the colors matched up with the appropriate row in the dataset.  In your real use case you could consider adding the colors to the dataset to keep organized.

```<code>ggplot(mtcars, aes(mpg, disp)) +
     geom_point(aes(colour=factor(vs),
                    fill = factor(vs)), shape=21, size = 4) +
     scale_fill_manual(values=c("blue", "pink")) +
     scale_colour_manual(values=c("black", "black"))+
     geom_hline(data = lt,
                mapping = aes(yintercept = yint, linetype = grp),
                color = c("black", "black", "red", "red", "green", "green") )
</code>```

If you want to put the colors on the linetype legend, you can use guide_legend and override.aes to set legend colors.

```<code>ggplot(mtcars, aes(mpg, disp)) +
     geom_point(aes(colour=factor(vs),
                    fill = factor(vs)), shape=21, size = 4) +
     scale_fill_manual(values=c("blue", "pink")) +
     scale_colour_manual(values=c("black", "black"))+
     geom_hline(data = lt,
                mapping = aes(yintercept = yint, linetype = grp),
                color = c("black", "black", "red", "red", "green", "green") ) +
     guides(linetype = guide_legend(override.aes = list(color = c("black", "red", "green") ) ) )
</code>```

Title: Horizontal line with different colours

Body:
How I can modify this code to have different colors for lines (for example Black, red, green)

library(ggplot2)

    lt <- data.frame(yint = c(200, 250, 210, 215, 279, 280),
                     grp  = factor(c(1, 1, 2, 2, 3, 3),
                                   levels = 1:3,
                                   labels = c("Group 1", "Group 2", "Group 3")))

    ggplot(mtcars, aes(mpg, disp)) +
          geom_point(aes(colour=factor(vs),
          fill = factor(vs)), shape=21, size = 4) +
          scale_fill_manual(values=c("blue", "pink")) +
          scale_colour_manual(values=c("black", "black"))+
          geom_hline(data = lt,
                     mapping = aes(yintercept = yint, linetype = grp))

I tried to use this function buT I got the error

ggplot(DataSet, aes(AGE, RESULT)) +
      geom_point(aes(colour=PATIENT.SEX,
      fill = PATIENT.SEX), shape=21, size = 1.4) +
      scale_fill_manual(values=c("hotpink", "skyblue2")) +
      scale_colour_manual(values=c("hotpink", "skyblue2"))+
      ylab("Potassium (mmol/L) ")+xlab("Age (month) ")+ggtitle("Alberta observations")+theme_bw()+
      theme(plot.title = element_text(lineheight=.8, face="bold",size=13))+
      theme(axis.text=element_text(size=12),axis.title=element_text(size=12,face="bold"))+
      theme(panel.border = element_blank(), panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(), axis.line = element_line(colour = "black"))+
      geom_hline(data = lt,
                 mapping = aes(yintercept = yint,linetype = RI),colour
=c("blue","blue", "red", "red", "black","black" ))

Body:
One "brute force" option available starting in the current development version of ggplot2, 2.2.1.9000, is to set colors outside of aes.  The colors you give either has to be length 1 (all colors the same) or the same length as the dataset used in that layer.

In your example you have 6 rows in your dataset to make 6 horizontal lines so I give 6 colors.

If using this method you have to be careful to get the colors matched up with the appropriate row in the dataset.  In your real use case you could consider adding the colors to the dataset to keep organized.

ggplot(mtcars, aes(mpg, disp)) +
     geom_point(aes(colour=factor(vs),
                    fill = factor(vs)), shape=21, size = 4) +
     scale_fill_manual(values=c("blue", "pink")) +
     scale_colour_manual(values=c("black", "black"))+
     geom_hline(data = lt,
                mapping = aes(yintercept = yint, linetype = grp),
                color = c("black", "black", "red", "red", "green", "green") )

If you want to put the colors on the linetype legend, you can use guide_legend and override.aes to set legend colors.

ggplot(mtcars, aes(mpg, disp)) +
     geom_point(aes(colour=factor(vs),
                    fill = factor(vs)), shape=21, size = 4) +
     scale_fill_manual(values=c("blue", "pink")) +
     scale_colour_manual(values=c("black", "black"))+
     geom_hline(data = lt,
                mapping = aes(yintercept = yint, linetype = grp),
                color = c("black", "black", "red", "red", "green", "green") ) +
     guides(linetype = guide_legend(override.aes = list(color = c("black", "red", "green") ) ) )


问:
Why isn't F# able to resolve overload between Async<> and Async<Result<>>?
I want to understand the F# overload resolution a little better in a specific context.

I'm writing a simple asyncResult workflow/computation expression to make error handling in the style of railway-oriented programming easier to use when combined with async workflows. I do this by overloading the Bind method on the workflow builder. This is fairly standard and used in all guides I've seen (and is also used in e.g. Chessie/ErrorHandling.fs).

I have one overload that accepts an Async<_> and one that accepts a Result<_,_>. Now, ideally, I'd like a third overload that accepts Async<Result<_,_>>. However, when I try to use let! or do! with an expression that returns Async<'a>, F# complains that a unique overload could not be determined, because both Async<_> and Async<Result<_,_>> fits, which of course they do (though one fits more specifically than the other). The only way I seem to be able to do this, is to do like Chessie (link above) and define a wrapper type:

```<code>type AsyncResult<'a, 'b> = AR of Async<Result<'a, 'b>>
</code>```

This again requires me to wrap all calls to methods that return Async<Result<_,_>> in this new type:

```<code>asyncResult {
  let! foo = funcReturningResultInsideAsync() |> AR
  ...
}
</code>```

AFAIK, C# will select the most specific overload. If F# did the same, this would not be a problem.

Why can't F# select the most specific overload?

Can anything be done to avoid the wrapper type in this specific situation?

Edit: As requested in the comments, here's non-compiling code that shows what I ideally would like, but doesn't work.

```<code>module AsyncResult =

  let liftAsync x =
    async { return x }

  let pure (value: 'a) : Async<Result<'a, 'b>> =
    async { return Ok value }

  let returnFrom (value: Async<Result<'a, 'b>>) : Async<Result<'a, 'b>> =
    value

  let bind (binder: 'a -> Async<Result<'b, 'c>>) (asyncResult: Async<Result<'a, 'c>>) : Async<Result<'b, 'c>> =
    async {
      let! result = asyncResult
      match result with
      | Ok x -> return! binder x
      | Error x -> return! Error x |> liftAsync
    }

  let bindResult (binder: 'a -> Async<Result<'b, 'c>>) (result: Result<'a, 'c>) : Async<Result<'b, 'c>> =
    bind binder (liftAsync result)

  let bindAsync (binder: 'a -> Async<Result<'b, 'c>>) (asnc: Async<'a>) : Async<Result<'b, 'c>> =
    bind binder (Async.map Ok asnc)

  type AsyncResultBuilder() =

    member __.Return value = pure value
    member __.ReturnFrom value = returnFrom value
    member __.Bind (asyncResult, binder) = bind binder asyncResult
    member __.Bind (result, binder) = bindResult binder result
    member __.Bind (async, binder) = bindAsync binder async

  let asyncResult = AsyncResultBuilder()

  // Usage

  let functionReturningAsync () =
    async { return 2 }

  let errorHandlingFunction () =
    asyncResult {
      // Error: A unique overload for method 'Bind' could not be determined ...
      do! functionReturningAsync()
    }
</code>```

答:
(this ought to be a comment, but it didn't fit)

The general philosophical position of F# is that it's inherently bad to have things "magically" happen behind the scenes. Everything should be written out explicitly, and this is aided by a lighter syntax.

This position is (partly) why F# doesn't have automatic sub/supertype coercions, and this is also why F# is so picky about overload resolution. If F# accepted multiple equally valid overloads, then you wouldn't be able to tell what's going on just by looking at the code. And this is, in fact, exactly what happens in C#: for one example, I can't even remember anymore how many times I had to fix bugs related to IQueryable/IEnumerable extension method confusion leading to pulling the whole database from the database server.

I can't say definitively that there isn't some trick to achieve what you're after, but I strongly advise against it.

Body:
I want to understand the F# overload resolution a little better in a specific context.

I'm writing a simple asyncResult workflow/computation expression to make error handling in the style of railway-oriented programming easier to use when combined with async workflows. I do this by overloading the Bind method on the workflow builder. This is fairly standard and used in all guides I've seen (and is also used in e.g. Chessie/ErrorHandling.fs).

I have one overload that accepts an Async<_> and one that accepts a Result<_,_>. Now, ideally, I'd like a third overload that accepts Async<Result<_,_>>. However, when I try to use let! or do! with an expression that returns Async<'a>, F# complains that a unique overload could not be determined, because both Async<_> and Async<Result<_,_>> fits, which of course they do (though one fits more specifically than the other). The only way I seem to be able to do this, is to do like Chessie (link above) and define a wrapper type:

type AsyncResult<'a, 'b> = AR of Async<Result<'a, 'b>>

This again requires me to wrap all calls to methods that return Async<Result<_,_>> in this new type:

asyncResult {
  let! foo = funcReturningResultInsideAsync() |> AR
  ...
}

AFAIK, C# will select the most specific overload. If F# did the same, this would not be a problem.

Why can't F# select the most specific overload?

Can anything be done to avoid the wrapper type in this specific situation?

Edit: As requested in the comments, here's non-compiling code that shows what I ideally would like, but doesn't work.

module AsyncResult =

  let liftAsync x =
    async { return x }

  let pure (value: 'a) : Async<Result<'a, 'b>> =
    async { return Ok value }

  let returnFrom (value: Async<Result<'a, 'b>>) : Async<Result<'a, 'b>> =
    value

  let bind (binder: 'a -> Async<Result<'b, 'c>>) (asyncResult: Async<Result<'a, 'c>>) : Async<Result<'b, 'c>> =
    async {
      let! result = asyncResult
      match result with
      | Ok x -> return! binder x
      | Error x -> return! Error x |> liftAsync
    }

  let bindResult (binder: 'a -> Async<Result<'b, 'c>>) (result: Result<'a, 'c>) : Async<Result<'b, 'c>> =
    bind binder (liftAsync result)

  let bindAsync (binder: 'a -> Async<Result<'b, 'c>>) (asnc: Async<'a>) : Async<Result<'b, 'c>> =
    bind binder (Async.map Ok asnc)

  type AsyncResultBuilder() =

    member __.Return value = pure value
    member __.ReturnFrom value = returnFrom value
    member __.Bind (asyncResult, binder) = bind binder asyncResult
    member __.Bind (result, binder) = bindResult binder result
    member __.Bind (async, binder) = bindAsync binder async

  let asyncResult = AsyncResultBuilder()

  // Usage

  let functionReturningAsync () =
    async { return 2 }

  let errorHandlingFunction () =
    asyncResult {
      // Error: A unique overload for method 'Bind' could not be determined ...
      do! functionReturningAsync()
    }


问:
Flask admin s3 SSL error
I'm trying to use a couple different implementations of uploading files to S3 from Flask Admin. In both situations I'm getting an SSL error. I've tried a few things that I've found such as adding this to config:

```<code>    S3_USE_HTTPS = False
</code>```

I also updated the certifi package which I saw recommended on another thread. I can't solve this error. Any idea why I'm getting this?

Error msg below:

```<code>> File
> "/Users/kevin/dev/allstarrma/flask-env/lib/python3.6/site-packages/boto/connection.py",
> line 1071, in make_request
>     retry_handler=retry_handler)   File "/Users/kevin/dev/allstarrma/flask-env/lib/python3.6/site-packages/boto/connection.py",
> line 1030, in _mexe
>     raise ex   File "/Users/kevin/dev/allstarrma/flask-env/lib/python3.6/site-packages/boto/connection.py",
> line 943, in _mexe
>     request.body, request.headers)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py",
> line 1239, in request
>     self._send_request(method, url, body, headers, encode_chunked)   File
> "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py",
> line 1285, in _send_request
>     self.endheaders(body, encode_chunked=encode_chunked)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py",
> line 1234, in endheaders
>     self._send_output(message_body, encode_chunked=encode_chunked)   File
> "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py",
> line 1026, in _send_output
>     self.send(msg)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py",
> line 964, in send
>     self.connect()   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py",
> line 1400, in connect
>     server_hostname=server_hostname)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py",
> line 407, in wrap_socket
>     _context=self, _session=session)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py",
> line 814, in __init__
>     self.do_handshake()   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py",
> line 1068, in do_handshake
>     self._sslobj.do_handshake()   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py",
> line 689, in do_handshake
>     self._sslobj.do_handshake() ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)
</code>```

答:
information about default https verification can be found:
https://www.python.org/dev/peps/pep-0476/

There is also great article from Red Hat.
https://access.redhat.com/articles/2039753 Right now it's open, but in case of being behind pay-wall I decided to write key points.

As said in comment you can invoke your python scripts with PYTHONHTTPSVERIFY=0 /path/to/script.py

You can also configure - default behaviour in file /etc/python/cert-verification.cfg and change

```<code>[https]
verify=platform_default
</code>```

to

```<code>[https]
verify=disable
</code>```

If you are using up to date python 2.7 you can also use in order to dynamically disable cert verification.

```<code>import ssl
ssl._https_verify_certificates(0)
</code>```

Unfortunately for Python > 3.4 (I tried 3.4.5 and 3.6.3) I wasn't able to find similar function. Same result in documentation https://docs.python.org/3/library/ssl.html.

Title: Flask admin s3 SSL error

Body:
I'm trying to use a couple different implementations of uploading files to S3 from Flask Admin. In both situations I'm getting an SSL error. I've tried a few things that I've found such as adding this to config:

    S3_USE_HTTPS = False

I also updated the certifi package which I saw recommended on another thread. I can't solve this error. Any idea why I'm getting this?

Error msg below:

> File
> "/Users/kevin/dev/allstarrma/flask-env/lib/python3.6/site-packages/boto/connection.py",
> line 1071, in make_request
>     retry_handler=retry_handler)   File "/Users/kevin/dev/allstarrma/flask-env/lib/python3.6/site-packages/boto/connection.py",
> line 1030, in _mexe
>     raise ex   File "/Users/kevin/dev/allstarrma/flask-env/lib/python3.6/site-packages/boto/connection.py",
> line 943, in _mexe
>     request.body, request.headers)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py",
> line 1239, in request
>     self._send_request(method, url, body, headers, encode_chunked)   File
> "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py",
> line 1285, in _send_request
>     self.endheaders(body, encode_chunked=encode_chunked)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py",
> line 1234, in endheaders
>     self._send_output(message_body, encode_chunked=encode_chunked)   File
> "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py",
> line 1026, in _send_output
>     self.send(msg)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py",
> line 964, in send
>     self.connect()   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/http/client.py",
> line 1400, in connect
>     server_hostname=server_hostname)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py",
> line 407, in wrap_socket
>     _context=self, _session=session)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py",
> line 814, in __init__
>     self.do_handshake()   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py",
> line 1068, in do_handshake
>     self._sslobj.do_handshake()   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ssl.py",
> line 689, in do_handshake
>     self._sslobj.do_handshake() ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)

Body:
information about default https verification can be found:
https://www.python.org/dev/peps/pep-0476/

There is also great article from Red Hat.
https://access.redhat.com/articles/2039753 Right now it's open, but in case of being behind pay-wall I decided to write key points.

As said in comment you can invoke your python scripts with PYTHONHTTPSVERIFY=0 /path/to/script.py

You can also configure - default behaviour in file /etc/python/cert-verification.cfg and change

[https]
verify=platform_default

to

[https]
verify=disable

If you are using up to date python 2.7 you can also use in order to dynamically disable cert verification.

import ssl
ssl._https_verify_certificates(0)

Unfortunately for Python > 3.4 (I tried 3.4.5 and 3.6.3) I wasn't able to find similar function. Same result in documentation https://docs.python.org/3/library/ssl.html.


问:
How can I write an array of strings into a file.txt using system calls write() and open()
I want to write a predefined array of strings to a file.txt, like so:

```<code>#include <unistd.h>
#include <fcntl.h>

int main(int argc, char *argv[])
{
    char *somestr[] = {"haha\n", "aww\n", "hmm\n", "hello\n", "there\n"};
    int filedesc = open("testfile.txt", O_WRONLY | O_APPEND | O_CREAT);
    for (int i = 0; i < 5; ++i) {
        write(filedesc, somestr[i], 24);
    }
    return 0;
}
</code>```

This will create testfile.txt. Expected file content:

```<code>haha
aww
hmm
hello
there
</code>```

But when I tried, it gives a weird result. Actual content:

haha
  \00aww
  \00hmm
  \00hello
  \00there
  \00aww
  \00hmm
  \00hello
  \00there
  \00testfihmm
  \00hello
  \00there
  \00testfile.txhello
  \00there
  \00testfile.txt\00\00there
  \00testfile.txt\00\00;4\00\00\00

答:
You are assuming that all the strings are 24 characters in length. This is incorrect. You are reading outside the bounds and writing this to file.

Instead use the correct length.

i.e.

```<code>write(filedesc, somestr[i], strlen(somestr[i]));
</code>```

Of course add the appropriate include file - this can be found on the manual page for strlen

Body:
I want to write a predefined array of strings to a file.txt, like so:

#include <unistd.h>
#include <fcntl.h>

int main(int argc, char *argv[])
{
    char *somestr[] = {"haha\n", "aww\n", "hmm\n", "hello\n", "there\n"};
    int filedesc = open("testfile.txt", O_WRONLY | O_APPEND | O_CREAT);
    for (int i = 0; i < 5; ++i) {
        write(filedesc, somestr[i], 24);
    }
    return 0;
}

This will create testfile.txt. Expected file content:

haha
aww
hmm
hello
there

But when I tried, it gives a weird result. Actual content:

haha
  \00aww
  \00hmm
  \00hello
  \00there
  \00aww
  \00hmm
  \00hello
  \00there
  \00testfihmm
  \00hello
  \00there
  \00testfile.txhello
  \00there
  \00testfile.txt\00\00there
  \00testfile.txt\00\00;4\00\00\00

Body:
You are assuming that all the strings are 24 characters in length. This is incorrect. You are reading outside the bounds and writing this to file.

Instead use the correct length.

i.e.

write(filedesc, somestr[i], strlen(somestr[i]));

Of course add the appropriate include file - this can be found on the manual page for strlen


问:
Is not accessible in current context
I have the following code

```<code>public abstract class BaseAdapter<T, V extends BaseAdapter.ViewHolder> extends ArrayAdapter<T> {
    public BaseAdapter(Context context, int resource, Collection<T> collection) {
        // typical constructor logic
    }

    // some other custom defined methods

    public static class ViewHolder {
        // custom defined logic
    }
}

public class ModelAdapter extends BaseAdapter<Model, ModelAdapter.ModelViewHolder> {
    public ModelAdapter(Context context, int resource, Collection<Model> collection) {
       super(context, resource, collection);
       // typical constructor logic
    }

    public static class ModelViewHolder extends ViewHolder {
        // custom defined logic
    }
}
</code>```

The BaseAdapter and ModelAdapter are in separated files. The problem is that I have a compilation error when trying to define the ModelAdapter:
ModelViewHolder is not accessible in current context

I don't really understand this error and can't figure out what I am doing wrong. Can somebody explain to me this problem or a link that may clarify this situation?

答: I faced this issue before, I'm not sure why that happened, but I resolved it by making the not-accessible inner class a stand-alone class (not inner means in a separate file).

Title: Is not accessible in current context

Body:
I have the following code

public abstract class BaseAdapter<T, V extends BaseAdapter.ViewHolder> extends ArrayAdapter<T> {
    public BaseAdapter(Context context, int resource, Collection<T> collection) {
        // typical constructor logic
    }

    // some other custom defined methods

    public static class ViewHolder {
        // custom defined logic
    }
}

public class ModelAdapter extends BaseAdapter<Model, ModelAdapter.ModelViewHolder> {
    public ModelAdapter(Context context, int resource, Collection<Model> collection) {
       super(context, resource, collection);
       // typical constructor logic
    }

    public static class ModelViewHolder extends ViewHolder {
        // custom defined logic
    }
}

The BaseAdapter and ModelAdapter are in separated files. The problem is that I have a compilation error when trying to define the ModelAdapter:
ModelViewHolder is not accessible in current context

I don't really understand this error and can't figure out what I am doing wrong. Can somebody explain to me this problem or a link that may clarify this situation?


问:
Uncaught ReferenceError: cordova is not defined
This is my HelloPlugin.js file.

```<code>var HelloPlugin = {
  callNativeFunction: function(success,fail,resultType) {
    return cordova.exec(success, fail, "HelloPlugin", "nativeAction", [resultType]);
  }
};
</code>```

I am getting the following exception:

```<code>: Uncaught ReferenceError: cordova is not defined at file:///android_asset/www/HelloPlugin.js:3
</code>```

Thank you in advance.

答:
I had a similar issue in iOS. The solution was to install cordova-plugin-file-transfer2:

```<code>cordova plugin add cordova-plugin-file-transfer
</code>```

Body:
This is my HelloPlugin.js file.

var HelloPlugin = {
  callNativeFunction: function(success,fail,resultType) {
    return cordova.exec(success, fail, "HelloPlugin", "nativeAction", [resultType]);
  }
};

I am getting the following exception:

: Uncaught ReferenceError: cordova is not defined at file:///android_asset/www/HelloPlugin.js:3

Thank you in advance.

Body:
I had a similar issue in iOS. The solution was to install cordova-plugin-file-transfer2:

cordova plugin add cordova-plugin-file-transfer


问:
Triggering an event from enter key
I am trying to create a UserForm that has a single data input of one Text box. and several Labels. The user will be scanning barcodes into the text box. The scan will trigger a series of macros to gather data from various sources and output the relevant information through updating the labels.

I have created a similar process in an Excel sheet and use a Change by Val trigger. In this instance, because only the single cell was unlocked the focus stayed on that cell, and hitting enter (or the carriage return from the barcode scanner) updated the cells value and triggered the series of Macros.

In this case I wanted to do the same thing so I expected I could use the AfterUpdate event trigger. The issue I am running into is that because the text box is the only actionable thing on the form the focus never leaves the textbox and therefore doesn't update.

So I changed direction and tried to use a KeyPress event trigger, but it does not seem to work for me.

```<code>Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    If KeyAscii = 13 Then MsgBox "successful"
End Sub
</code>```

I have also replaced 13 with vbKeyReturn

As I understand it any time anyone hits Enter while the cursor is active in the textbox there should be a msgbox that says successful pop up. But that is not happening.

I have verified MultipleLine is set to false. I have tried setting EnterKeyBehavior to both True and False without change.

I know in theory I could just make one of the labels an index stop and kick focus back to the text box when it has focus and that would essentially count as an update. Then I could use the update trigger as originally planned. But that seems to be a very sloppy work around and I know I should be able to trigger by the key stroke.

答:
Switching to the KeyDown event for the object works fine for me:

```<code>Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    If KeyCode = 13 Then
        Debug.Print "Made it here"
    End If
End Sub
</code>```

When I launch my form type and hit enter, my Immediate pane shows "Made it here" as expected.

Title: Triggering an event from enter key

Body:
I am trying to create a UserForm that has a single data input of one Text box. and several Labels. The user will be scanning barcodes into the text box. The scan will trigger a series of macros to gather data from various sources and output the relevant information through updating the labels.

I have created a similar process in an Excel sheet and use a Change by Val trigger. In this instance, because only the single cell was unlocked the focus stayed on that cell, and hitting enter (or the carriage return from the barcode scanner) updated the cells value and triggered the series of Macros.

In this case I wanted to do the same thing so I expected I could use the AfterUpdate event trigger. The issue I am running into is that because the text box is the only actionable thing on the form the focus never leaves the textbox and therefore doesn't update.

So I changed direction and tried to use a KeyPress event trigger, but it does not seem to work for me.

Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    If KeyAscii = 13 Then MsgBox "successful"
End Sub

I have also replaced 13 with vbKeyReturn

As I understand it any time anyone hits Enter while the cursor is active in the textbox there should be a msgbox that says successful pop up. But that is not happening.

I have verified MultipleLine is set to false. I have tried setting EnterKeyBehavior to both True and False without change.

I know in theory I could just make one of the labels an index stop and kick focus back to the text box when it has focus and that would essentially count as an update. Then I could use the update trigger as originally planned. But that seems to be a very sloppy work around and I know I should be able to trigger by the key stroke.

Body:
Switching to the KeyDown event for the object works fine for me:

Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    If KeyCode = 13 Then
        Debug.Print "Made it here"
    End If
End Sub

When I launch my form type and hit enter, my Immediate pane shows "Made it here" as expected.


答:
How about using this:</p>

```<code>Private Sub TextBox1_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = 13 Then MsgBox "successful"
End Sub
</code>```

Title: Triggering an event from enter key

Body:
How about using this:

Private Sub TextBox1_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
If KeyCode = 13 Then MsgBox "successful"
End Sub


问:
Load a jsp page every 20 secs after 1st page load
I am trying to autosubmit a form upon 1st load and then refresh every 20 secs. I have tried below but it keeps loading the page all the time. is that correct implementation or how I can achieve that.</p>

``` window.onload=function(){
    var auto = setTimeout(function(){ submitform(); }, 100);

    function submitform(){
      document.forms["frm1"].submit();
    }

    function autoRefresh(){
       clearTimeout(auto);
       auto = setTimeout(function(){ autoRefresh(); }, 20000);
    }
}  ```

答:
You must use setInterval() instead :

```<code>setInterval(function(){
    //Refresh code here
    //location.reload();
}, 20000);
</code>```

So the code inside will be triggered every 20 second.

Body:
I am trying to autosubmit a form upon 1st load and then refresh every 20 secs. I have tried below but it keeps loading the page all the time. is that correct implementation or how I can achieve that.

 window.onload=function(){
    var auto = setTimeout(function(){ submitform(); }, 100);

    function submitform(){
      document.forms["frm1"].submit();
    }

    function autoRefresh(){
       clearTimeout(auto);
       auto = setTimeout(function(){ autoRefresh(); }, 20000);
    }
}

Body:
You must use setInterval() instead :

setInterval(function(){
    //Refresh code here
    //location.reload();
}, 20000);

So the code inside will be triggered every 20 second.


问:
How to get proportions of polygons by class
I've 2 issues when classifying my image to get the proportion

1: i've classified my image into three classes (1,2,3) and i'm trying to use pkextractogr from pktools to get the proportions of each class using a vector polygon. The code below will run but will only output proportion for class 3. It will output a new file and in the attribute table there will be a column for class 1 and class 2 but they will be blank. If i try use it for just one class the output will either be 100% or 0% for the specified class. I've tried doing this on the command line and also in qgis (using pktools as a plugin).

2: When i use qgis the ogr tells me that the data source is invalid but i can't figure out why as both files are in the same projection.

data source invalid

pkextractogr -i classified_image.tif -s polygon.shp -o classified_proportion.shp -polygon -r proportion -c 1 -c 2 -c 3

Does anyone have a solution to either problem? im using fedora 26 and qgis 2.18.14

答: The version of pktools i was using 2.8.7 had a bug, i downloaded 2.8.7.3 which has resolved the problem</p>


问:
Python page count down print (len(elem_href1-(number)))
How do I create a page count down for python for each page it navigates to.  I have included my attempts below.  How do I get desired result?

I am using (len(elem_href1) so I can try and create page count down so easily informed of where my script is progressing. Trying to do that - a value each loop.

```<code>driver = webdriver.Chrome()

driver.get('https://stackoverflow.com/questions')
elements = driver.find_elements_by_css_selector("#questions .question-hyperlink")
elem_href1 = [element.get_attribute("href") for element in elements]
print(elem_href1)
print (len(elem_href1))
shuffle(elem_href1)
for link in elem_href1:#(2)
    driver.get(link)
    print(len(link))
    import numbers

    #number = number -= 1
    #print (len(elem_href1-(number)))

print (len(elem_href1)) gives total number of pages to navigate to.

print(len(link)) gives random number due to shuffle.
</code>```

Current output:

```<code>15
83
101
112
72
107
106
84
</code>```

Desired:

```<code>50 #When at page 50
49 #when at page 49..
48 #when at page 48..
42 #Counting down...
..
</code>```

Maybe then:

```<code>    number = number -= 1
    print (len(elem_href1-(number)))
#SyntaxError: invalid syntax
</code>```

Or:

```<code>count = len(elem_href1)
def countdownList(l):  # 3. prints number of files left to process
    global count
    count = count - 1
    print(count, " pages left to go.")
    if count == 0:
</code>```

Output:

```<code>    15
   43
</code>```

Any ideas how this might be achieved

答:
For me it seems that len(link) has nothing related to shuffle. It looks like it just prints length of the string of current link.

If you want to see a number of 'pages left to go' you can just do:

```<code>for i, e in enumerate(elem_href1):
    print(len(elem_href1) - i)
</code>```

or

```<code>left_to_go = len(elem_href1)

print(left_to_go)

for e in elem_href1:
    left_to_go -= 1
    print(left_to_go)
</code>```

Body:
How do I create a page count down for python for each page it navigates to.  I have included my attempts below.  How do I get desired result?

I am using (len(elem_href1) so I can try and create page count down so easily informed of where my script is progressing. Trying to do that - a value each loop.

driver = webdriver.Chrome()

driver.get('https://stackoverflow.com/questions')
elements = driver.find_elements_by_css_selector("#questions .question-hyperlink")
elem_href1 = [element.get_attribute("href") for element in elements]
print(elem_href1)
print (len(elem_href1))
shuffle(elem_href1)
for link in elem_href1:#(2)
    driver.get(link)
    print(len(link))
    import numbers

    #number = number -= 1
    #print (len(elem_href1-(number)))

print (len(elem_href1)) gives total number of pages to navigate to.

print(len(link)) gives random number due to shuffle.

Current output:

15
83
101
112
72
107
106
84

Desired:

50 #When at page 50
49 #when at page 49..
48 #when at page 48..
42 #Counting down...
..

Maybe then:

    number = number -= 1
    print (len(elem_href1-(number)))
#SyntaxError: invalid syntax

Or:

count = len(elem_href1)
def countdownList(l):  # 3. prints number of files left to process
    global count
    count = count - 1
    print(count, " pages left to go.")
    if count == 0:

Output:

    15
   43

Any ideas how this might be achieved

Body:
For me it seems that len(link) has nothing related to shuffle. It looks like it just prints length of the string of current link.

If you want to see a number of 'pages left to go' you can just do:

for i, e in enumerate(elem_href1):
    print(len(elem_href1) - i)

or

left_to_go = len(elem_href1)

print(left_to_go)

for e in elem_href1:
    left_to_go -= 1
    print(left_to_go)


问:
Xcode 9 performance issue
Have anyone tried out the new Color Asset Catalogue feature in Xcode 9. For me every time I edit something on this like adding or editing a colour asset,  I have to wait for 10-15 seconds while Xcode shows the coloured progress and does not allow any interaction.

At the same time being highly annoying, it is also highly counter-productive. I also found IB to be generally too slow after updating to Xcode 9.

Are these known issues ? Is there a solution to this?

答:
i asked apple about the hangs and crashes that keep on occurring on Xcode 9, and they replied:

First, quit Xcode. And then temporarily move aside
  UserInterfaceState.xcuserstate so that new user state is created.

It can be found here

path_to/$WORKSPACE.xcworkspace/xcuserdata/$USER.xcuserdatad/UserInterfaceState.xcuserstate

(if it is an .xcodeproject, it will be deep in the project.xcworkspace
  directory).

this worked for me with autocomplete problems and switching between files. hope it helps you out as well.

Title: Xcode 9 performance issue


问:
constructor() and super () react
I am learning from scratch react jsx. I have no previous learning of java or html language.

I've been searching what is it for the constructor() and super(). This are components? Anyone can explain me everything about this 2 things.

答:
These are clearly explained on the Mozilla Developer Network for JavaScript

The constructor method is a special method for creating and initializing an object created with a class. There can only be one special method with the name "constructor" in a class. A SyntaxError will be thrown if the class contains more than one occurrence of a constructor method.

The super keyword is used to access and call functions on an object's parent.
The super.prop and super[expr] expressions are valid in any method definition in both classes and object literals.

Title: constructor() and super () react


问:
Python: how to increment number and store in variable every time function runs
(I'm a beginner in Python, just so you know)

What I'm trying to do: I want to keep count of how many times a user choose a wrong option and if it exceeds a number of times, he fails.

My approach was to store the count in a variable within a function and check with if/else statement if the number of times is exceeded.

Part of the code:

```<code>    choice = int(input("> "))

if choice == 1:
    print("This is the wrong hall.")
    increment()
elif choice == 2:
    print("This is the wrong hall.")
    increment()
elif choice == 3:
    hall_passage()
else:
    end("You failed")

COUNT = 0
def increment():
    global COUNT
    COUNT += 1

increment()

print(COUNT)
</code>```

The increment part is from this thread and read using global scope is not a good practice.

The part I don't really understand is how you store count in a variable and it remembers the last value every time the function runs.

What is the best way to do this?

答:
Adapting this answer you could utilize the functions own __dict__. Note: if you didn't come across the @ syntax yet search for "python", "decorator":

```<code>import functools as ft

def show_me(f):
    @ft.wraps(f)
    def wrapper(*args, **kwds):
        return f(f, *args, **kwds)
    return wrapper

@show_me
def f(me, x):
    if x < 0:
        try:
            me.count += 1
        except AttributeError:
            me.count = 1
        print(me.count, 'failures')

f(0)
f(-1)
f(1)
f(-2)
</code>```

Output:

```<code>1 failures
2 failures
</code>```

Body:
(I'm a beginner in Python, just so you know)

What I'm trying to do: I want to keep count of how many times a user choose a wrong option and if it exceeds a number of times, he fails.

My approach was to store the count in a variable within a function and check with if/else statement if the number of times is exceeded.

Part of the code:

    choice = int(input("> "))

if choice == 1:
    print("This is the wrong hall.")
    increment()
elif choice == 2:
    print("This is the wrong hall.")
    increment()
elif choice == 3:
    hall_passage()
else:
    end("You failed")

COUNT = 0
def increment():
    global COUNT
    COUNT += 1

increment()

print(COUNT)

The increment part is from this thread and read using global scope is not a good practice.

The part I don't really understand is how you store count in a variable and it remembers the last value every time the function runs.

What is the best way to do this?

Body:
Adapting this answer you could utilize the functions own __dict__. Note: if you didn't come across the @ syntax yet search for "python", "decorator":

import functools as ft

def show_me(f):
    @ft.wraps(f)
    def wrapper(*args, **kwds):
        return f(f, *args, **kwds)
    return wrapper

@show_me
def f(me, x):
    if x < 0:
        try:
            me.count += 1
        except AttributeError:
            me.count = 1
        print(me.count, 'failures')

f(0)
f(-1)
f(1)
f(-2)

Output:

1 failures
2 failures


问:
Realtime database interaction iOS
I am creating an app where a I want a user notified in app whenever anyone they are following posts a picture. So lets say user A follows user B, when user B posts a picture it appears in realtime on user A's screen. My question is: Is this kind of thing done using push notifications? As in make a request to get the image when notification is received or is it better to be using sockets or queues?</p>

答:
This is one of the most common use cases for push notifications. Your iOS app asks the user for permission to send notifications, and then registers with Apple to receive push notifications. Apple provides a "token" that is a unique identifier for that notification subscription, which your app will then need to send to your server. When it is time to notify the user about a new photo, or whatever, your server uses Apple's APNS services to send the notification, using the token to identify the recipient.

So, the app and the server use multiple Apple-provided APIs to create the communication channel, and then you are free to add whatever logic you want to determine the timing and content of the notifications.

Before trying to implement anything, I'd suggest reading through the entirety of the Apple's Remote Notifications Programming Guide to a solid understanding of how all the pieces of this technology fit together.

Are there other technologies you could use? Maybe. For iOS apps, Firebase is essentially a more platform-independent wrapper that is built on top of the Apple notification system described above; under the hood, it is still using APNS and requires some of the same initial steps to configure your app. Socket-type technologies could be ok for limited use cases but aren't the correct approach for general purpose notification delivery, due to restrictions with running the app in the background (among other reasons).

Title: Realtime database interaction iOS


问:
How do I rotate the whole web page 90, 180 or 270 degrees?
I want to rotate the whole web page 90, 180 or 280 degrees.

Solution how to rotate 90 degrees is given in answer
Rotate all html element (whole page) 90 degree with CSS? . If I change 90 degrees to 270 degrees web page rotates "out of the screen" or is not centered to the screen. I would like to rotate the page like I rotate my monitor. My page starts from top left.

How to edit this code to properly work with 180 and 270 degrees?

```<code>.wrapper{
    transform: rotate(90deg);
    transform-origin:bottom left;

    position:absolute;
    top:-100vw;

    height:100vw;
    width:100vh;

    background-color:#000;
    color:#fff;

    overflow:auto;
}
</code>```

答:
transform-origin is the CSS property responsible for this. It determins the point the element is rotated around of. If you change the transform-origin and rotate the element, the position of the element can change depending on what value you use. You can change the value of transform-origin to the result you need.

Here's an example of two different transform-origins (hover on them):

.wrapper {
  margin-left: 50px;
  color: white;
  transform-origin: bottom left;
  height: 100px;
  width: 100px;
  background-color: #000;
  color: #fff;
  overflow: auto;
  padding: 10px;
}

.wrapper:hover {
  transition-duration: 0.3s;
  transform: rotate(90deg);
}

.spacerM {
  display: block;
  width: 100%;
  clear: both;
  height: 30px;
}

.correct {
  transform-origin: center;
  background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">Transform-Origin Bottom Left</div>
<div class="spacerM"></div>
<div class="wrapper correct">Transform-Origin Center</div></code>```

Body:
I want to rotate the whole web page 90, 180 or 280 degrees.

Solution how to rotate 90 degrees is given in answer
Rotate all html element (whole page) 90 degree with CSS? . If I change 90 degrees to 270 degrees web page rotates "out of the screen" or is not centered to the screen. I would like to rotate the page like I rotate my monitor. My page starts from top left.

How to edit this code to properly work with 180 and 270 degrees?

.wrapper{
    transform: rotate(90deg);
    transform-origin:bottom left;

    position:absolute;
    top:-100vw;

    height:100vw;
    width:100vh;

    background-color:#000;
    color:#fff;

    overflow:auto;
}

Body:
transform-origin is the CSS property responsible for this. It determins the point the element is rotated around of. If you change the transform-origin and rotate the element, the position of the element can change depending on what value you use. You can change the value of transform-origin to the result you need.

Here's an example of two different transform-origins (hover on them):

.wrapper {
  margin-left: 50px;
  color: white;
  transform-origin: bottom left;
  height: 100px;
  width: 100px;
  background-color: #000;
  color: #fff;
  overflow: auto;
  padding: 10px;
}

.wrapper:hover {
  transition-duration: 0.3s;
  transform: rotate(90deg);
}

.spacerM {
  display: block;
  width: 100%;
  clear: both;
  height: 30px;
}

.correct {
  transform-origin: center;
  background: red;
}

<div class="wrapper">Transform-Origin Bottom Left</div>
<div class="spacerM"></div>
<div class="wrapper correct">Transform-Origin Center</div>


问:
How to increase memory in windows form application (Memory Stream)
After implementing these codes below, I got the "Out of Memory" error. I am really new to this and would like to ask how and where do i increase the memory space of the program.

```<code>using (SqlCommand cmd = new SqlCommand("select Background from Employee where EmployeeName = @Name", con))
            {
                cmd.Parameters.AddWithValue("@Name", txt_name.Text);
                con.Open();
                var dt = new DataTable();

                using (SqlDataReader dr = cmd.ExecuteReader())
                {
                    dt.Load(dr); // fill DataTable from reader
                }

                if (dt.Rows.Count > 0 && dt.Rows[0]["Background"] != DBNull.Value)
                {
                    using (MemoryStream ms = new MemoryStream((byte[])dt.Rows[0]["Background"]))
                    {
                        this.BackgroundImage = new Bitmap(ms);
                    }
                    // do another stuff
                }
                else
                {
                    // do another stuff
                }
            }con.Close();
</code>```

Any help you would greatly appreciated

答:
```<code>using (SqlCommand cmd = new SqlCommand("select Background from Employee where EmployeeName = @Name", con))
        {
            cmd.Parameters.AddWithValue("@Name", txt_name.Text);
            con.Open();
            var dt = new DataTable();

            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                dt.Load(dr); // fill DataTable from reader
            }

            if (dt.Rows.Count > 0 && dt.Rows[0]["Background"] != DBNull.Value)
            {
                using (MemoryStream ms = new MemoryStream((byte[])dt.Rows[0]["Background"]))
                {
                    this.BackgroundImage = new Bitmap(ms);
                }
                // do another stuff
            }
            else
            {
                // do another stuff
            }
        }con.Close();
</code>```

Credit to Kalyan

Body:
After implementing these codes below, I got the "Out of Memory" error. I am really new to this and would like to ask how and where do i increase the memory space of the program.

using (SqlCommand cmd = new SqlCommand("select Background from Employee where EmployeeName = @Name", con))
            {
                cmd.Parameters.AddWithValue("@Name", txt_name.Text);
                con.Open();
                var dt = new DataTable();

                using (SqlDataReader dr = cmd.ExecuteReader())
                {
                    dt.Load(dr); // fill DataTable from reader
                }

                if (dt.Rows.Count > 0 && dt.Rows[0]["Background"] != DBNull.Value)
                {
                    using (MemoryStream ms = new MemoryStream((byte[])dt.Rows[0]["Background"]))
                    {
                        this.BackgroundImage = new Bitmap(ms);
                    }
                    // do another stuff
                }
                else
                {
                    // do another stuff
                }
            }con.Close();

Any help you would greatly appreciated

Body:
using (SqlCommand cmd = new SqlCommand("select Background from Employee where EmployeeName = @Name", con))
        {
            cmd.Parameters.AddWithValue("@Name", txt_name.Text);
            con.Open();
            var dt = new DataTable();

            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                dt.Load(dr); // fill DataTable from reader
            }

            if (dt.Rows.Count > 0 && dt.Rows[0]["Background"] != DBNull.Value)
            {
                using (MemoryStream ms = new MemoryStream((byte[])dt.Rows[0]["Background"]))
                {
                    this.BackgroundImage = new Bitmap(ms);
                }
                // do another stuff
            }
            else
            {
                // do another stuff
            }
        }con.Close();

Credit to Kalyan


问:
How to retrieve/read an image from MongoDB's GridFS in Python?
```<code>with cv2.imread("Desktop/foo.jpg") as img:
    b = fs.put(img, filename="foo")
</code>```

I use the above block of code to save an image. The issue is, how do I get it back and read it through some common library like PIL in Python3?

答:
gridfs.GridFS.find_one allows to find a file that was saved to GridFS using a filename.

This method returns an instance grid_file.GridOut that can be read.

```<code>file = fs.find_one({'filename': 'foo'})
image = file.read()
</code>```

Body:
with cv2.imread("Desktop/foo.jpg") as img:
    b = fs.put(img, filename="foo")

I use the above block of code to save an image. The issue is, how do I get it back and read it through some common library like PIL in Python3?

Body:
gridfs.GridFS.find_one allows to find a file that was saved to GridFS using a filename.

This method returns an instance grid_file.GridOut that can be read.

file = fs.find_one({'filename': 'foo'})
image = file.read()


问:
Show div's based on a randomly shuffled array using javascript/jquery
Essentially I'm trying to write a Javascript/Jquery script which will show/hide a number of div's one at a time in an order determined by a randomly shuffled series of numbers.

I've managed to get the scripts to shuffle the numbers and cycle through the divs working but I'm not sure how to combine the two.

The script so far looks like this

```<code>$(document).ready(function() {

    function shuffle(arra1) {
        var ctr = arra1.length, temp, index;

        // While there are elements in the array
        while (ctr > 0) {
            // Pick a random index
            index = Math.floor(Math.random() * ctr);
            // Decrease ctr by 1
            ctr--;
            // And swap the last element with it
            temp = arra1[ctr];
            arra1[ctr] = arra1[index];
            arra1[index] = temp;
        }

        return arra1;
    }

    var myArray = [0, 1, 2, 3, 4, 5];
    console.log(shuffle(myArray));

    var divs = $('div[id^="random"]').hide(),
        i = 0;

    (function cycle() {
        divs.eq(i).fadeIn(400)
                  .delay(1000)
                  .fadeOut(400, cycle);

        i = ++i % divs.length;
    })();
});
</code>```

The div's that I'm trying to cycle through in the HTML look Like this

```<code><div id="random-divs">
    <div id="random0">Div 0</div>
    <div id="random1">Div 1</div>
    <div id="random2">Div 2</div>
    <div id="random3">Div 3</div>
    <div id="random4">Div 4</div>
    <div id="random5">Div 5</div>
</div>
</code>```

If anyone could point me in the right direction I'd greatly appreciate it.

答:
$(document).ready(function() {

    function shuffle(arra1) {
        var ctr = arra1.length, temp, index;

        // While there are elements in the array
        while (ctr > 0) {
            // Pick a random index
            index = Math.floor(Math.random() * ctr);
            // Decrease ctr by 1
            ctr--;
            // And swap the last element with it
            temp = arra1[ctr];
            arra1[ctr] = arra1[index];
            arra1[index] = temp;
        }

        return arra1;
    }

    var myArray = [0, 1, 2, 3, 4, 5];
    var shuffledArray = shuffle(myArray);
    console.log(shuffledArray);
    var divs = $('div[id^="random"]');

    (function cycle() {
        var i = shuffledArray.shift();
        if(i === undefined){
          return
        }
        divs.eq(i).fadeIn(400)
                  .delay(1000)
                  .fadeOut(400, cycle);

    })();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="random-divs">
    <div style='display:none;' id="random0">Div 0</div>
    <div style='display:none;' id="random1">Div 1</div>
    <div style='display:none;' id="random2">Div 2</div>
    <div style='display:none;' id="random3">Div 3</div>
    <div style='display:none;' id="random4">Div 4</div>
    <div style='display:none;' id="random5">Div 5</div>
</div></code>```

Body:
Essentially I'm trying to write a Javascript/Jquery script which will show/hide a number of div's one at a time in an order determined by a randomly shuffled series of numbers.

I've managed to get the scripts to shuffle the numbers and cycle through the divs working but I'm not sure how to combine the two.

The script so far looks like this

$(document).ready(function() {

    function shuffle(arra1) {
        var ctr = arra1.length, temp, index;

        // While there are elements in the array
        while (ctr > 0) {
            // Pick a random index
            index = Math.floor(Math.random() * ctr);
            // Decrease ctr by 1
            ctr--;
            // And swap the last element with it
            temp = arra1[ctr];
            arra1[ctr] = arra1[index];
            arra1[index] = temp;
        }

        return arra1;
    }

    var myArray = [0, 1, 2, 3, 4, 5];
    console.log(shuffle(myArray));

    var divs = $('div[id^="random"]').hide(),
        i = 0;

    (function cycle() {
        divs.eq(i).fadeIn(400)
                  .delay(1000)
                  .fadeOut(400, cycle);

        i = ++i % divs.length;
    })();
});

The div's that I'm trying to cycle through in the HTML look Like this

Div 0

Div 1

Div 2

Div 3

Div 4

Div 5

If anyone could point me in the right direction I'd greatly appreciate it.

Body:
$(document).ready(function() {

    function shuffle(arra1) {
        var ctr = arra1.length, temp, index;

        // While there are elements in the array
        while (ctr > 0) {
            // Pick a random index
            index = Math.floor(Math.random() * ctr);
            // Decrease ctr by 1
            ctr--;
            // And swap the last element with it
            temp = arra1[ctr];
            arra1[ctr] = arra1[index];
            arra1[index] = temp;
        }

        return arra1;
    }

    var myArray = [0, 1, 2, 3, 4, 5];
    var shuffledArray = shuffle(myArray);
    console.log(shuffledArray);
    var divs = $('div[id^="random"]');

    (function cycle() {
        var i = shuffledArray.shift();
        if(i === undefined){
          return
        }
        divs.eq(i).fadeIn(400)
                  .delay(1000)
                  .fadeOut(400, cycle);

    })();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="random-divs">
    <div style='display:none;' id="random0">Div 0</div>
    <div style='display:none;' id="random1">Div 1</div>
    <div style='display:none;' id="random2">Div 2</div>
    <div style='display:none;' id="random3">Div 3</div>
    <div style='display:none;' id="random4">Div 4</div>
    <div style='display:none;' id="random5">Div 5</div>
</div>


问:
Which option to choose for designing this API endpoint
Let's imagine we have an API endpoint: /cars/1 and this returns basic information about the car (id, name, description).

But we can also request GET /cars/1?info=extra and this will also return extra information about the car (price, stock). And this extra information is stored in our Database as another table, which has a One To One relationship with the Car.

If it helps, our backend is a Java Spring Boot application.

There are many ways to return the data. Would you return same objects in both requests, with the corresponding extra parameters as null in the ?info=extra request? Or would you return different objects for each one of the requests?

For me returning all the nulls when requesting the "basic" info has the advantage of using the same Class to map both requests, by only changing the @Query in the JPA Repository, making it easier to maintain.

Returning all the nulls also has the disadvantage of returning a lot of useless values that the user didn't even requested. It also makes the API more difficult to read (someone can think that all of those values are actually null and they might not). Speaking of classes, we would have a MappedSuperClass Car and two other classes CarBasic and CarExtra, both extending Car, each one of them with the corresponding getters to create the output JSON.

Option 1:

/cars/1

```<code>{
    id: 1,
    name: "Honda Civic",
    description: "The best car of Honda"
}
</code>```

/cars/1?info=extra

```<code>{
    id: 1,
    name: "Honda Civic",
    description: "The best car of Honda",
    extraInfo: {
    {
        price: 25000,
        stock: 24
    }
}
</code>```

Option 2:

/cars/1

```<code>{
    id: 1,
    name: "Honda Civic",
    description: "The best car of Honda",
    extraInfo: null
}
</code>```

/cars/1?info=extra

```<code>{
    id: 1,
    name: "Honda Civic",
    description: "The best car of Honda",
    extraInfo: {
    {
        price: 25000,
        stock: 24
    }
}
</code>```

Option 3:

/cars/1

```<code>{
    id: 1,
    name: "Honda Civic",
    description: "The best car of Honda"
}
</code>```

/cars/1?info=extra

```<code>{
    id: 1,
    name: "Honda Civic",
    description: "The best car of Honda",
    price: 25000,
    stock: 24
}
</code>```

What do you think?

答:
However not really a StackOverflow type of question, a very interesting one nonetheless.

Personally I would prefer option 3.

In terms of code you could even extend your normal Car class with a model with your extra fields.

Body:
Let's imagine we have an API endpoint: /cars/1 and this returns basic information about the car (id, name, description).

But we can also request GET /cars/1?info=extra and this will also return extra information about the car (price, stock). And this extra information is stored in our Database as another table, which has a One To One relationship with the Car.

If it helps, our backend is a Java Spring Boot application.

There are many ways to return the data. Would you return same objects in both requests, with the corresponding extra parameters as null in the ?info=extra request? Or would you return different objects for each one of the requests?

For me returning all the nulls when requesting the "basic" info has the advantage of using the same Class to map both requests, by only changing the @Query in the JPA Repository, making it easier to maintain.

Returning all the nulls also has the disadvantage of returning a lot of useless values that the user didn't even requested. It also makes the API more difficult to read (someone can think that all of those values are actually null and they might not). Speaking of classes, we would have a MappedSuperClass Car and two other classes CarBasic and CarExtra, both extending Car, each one of them with the corresponding getters to create the output JSON.

Option 1:

/cars/1

{
    id: 1,
    name: "Honda Civic",
    description: "The best car of Honda"
}

/cars/1?info=extra

{
    id: 1,
    name: "Honda Civic",
    description: "The best car of Honda",
    extraInfo: {
    {
        price: 25000,
        stock: 24
    }
}

Option 2:

/cars/1

{
    id: 1,
    name: "Honda Civic",
    description: "The best car of Honda",
    extraInfo: null
}

/cars/1?info=extra

{
    id: 1,
    name: "Honda Civic",
    description: "The best car of Honda",
    extraInfo: {
    {
        price: 25000,
        stock: 24
    }
}

Option 3:

/cars/1

{
    id: 1,
    name: "Honda Civic",
    description: "The best car of Honda"
}

/cars/1?info=extra

{
    id: 1,
    name: "Honda Civic",
    description: "The best car of Honda",
    price: 25000,
    stock: 24
}

What do you think?


问:
Shuffling the items in a ListBox
I have a system that contains integers in a ListBox. I have included a 'Shuffle' Button, which should shuffle the stored items in the ListBox into a random order, when clicked by the user.

However, the code I am using is not working for this. Has anyone got any suggestions on how to generate a shuffle button to randomize the data within a ListBox?

答:
This line

```<code>buttonShuffle.ObjectCollection list = listBoxAddedIntegers.Items;
</code>```

makes no sense.  The compiler will be trying to create a variable called list of type buttonShuffle.ObjectCollection, which I'm assuming is not a valid type.

I think what you need to do is make list a List<int> (or var), and then populate buttonShuffle.ObjectCollection from list at the end of your method, using whatever method is appropriate for that operation (Add, AddRange, etc)

Title: Shuffling the items in a ListBox

Body:
This line

buttonShuffle.ObjectCollection list = listBoxAddedIntegers.Items;

makes no sense.  The compiler will be trying to create a variable called list of type buttonShuffle.ObjectCollection, which I'm assuming is not a valid type.

I think what you need to do is make list a List<int> (or var), and then populate buttonShuffle.ObjectCollection from list at the end of your method, using whatever method is appropriate for that operation (Add, AddRange, etc)


问:
How to do a full oracle database export or import yet exclude one tablespace
I'm working on creating a scheduled task to do a weekly refresh of an Oracle 11g database from production to test. I want to do a full export / import with the exception of one tablespace named PERFSTAT which we use in production with stats pack, but don't really need in test.

Here is my current export command

```<code>EXPDP system/password@instance FULL=Y DIRECTORY=TRPROD_EXPORT DUMPFILE=TRPROD_FULL_EXPORT.DMP LOGFILE=TRPROD_FULL_EXPORT.LOG COMPRESSION=all
</code>```

When I tested the import, i got the following error

```<code>ORA-01119: error in creating database file 'G:\ORACLE\ORADATA\TRPROD\PERFSTAT01.DBF'
ORA-27038: created file already exists
OSD-04010: <create> option specified, file already exists
Failing sql is:
CREATE TABLESPACE "PERFSTAT" DATAFILE 'G:\ORACLE\ORADATA\TRPROD\PERFSTAT01.DBF' SIZE 209715200 AUTOEXTEND ON NEXT 10485760 MAXSIZE 2146435072 LOGGING ONLINE PERMANENT BLOCKSIZE 8192 EXTENT MANAGEMENT LOCAL AUTOALLOCATE DEFAULT NOCOMPRESS  SEGMENT SPAC
</code>```

I've tried adding EXCLUDE=TABLESPACE:"='PERFSTAT'" to the EXPDP command to try and exclude that tablespace, but I gave me a syntax error, so I'm wondering what the correct way to do a full refresh of our test database would be yet exclude this one specific tablespace?

答:
You can create a parameter file as shown below.

```<code>[oracle@oratestprod fra]$ cat test.par
DIRECTORY=TRPROD_EXPORT
FULL=Y
DUMPFILE=TRPROD_FULL_EXPORT.DMP
LOGFILE=TRPROD_FULL_EXPORT.LOG
COMPRESSION=all
exclude=tablespace:"IN ('PERFSTAT')"
</code>```

And run as shown below.

```<code>[oracle@oratestprod fra]$ expdp system parfile=test.par
</code>```

Body:
I'm working on creating a scheduled task to do a weekly refresh of an Oracle 11g database from production to test. I want to do a full export / import with the exception of one tablespace named PERFSTAT which we use in production with stats pack, but don't really need in test.

Here is my current export command

EXPDP system/password@instance FULL=Y DIRECTORY=TRPROD_EXPORT DUMPFILE=TRPROD_FULL_EXPORT.DMP LOGFILE=TRPROD_FULL_EXPORT.LOG COMPRESSION=all

When I tested the import, i got the following error

ORA-01119: error in creating database file 'G:\ORACLE\ORADATA\TRPROD\PERFSTAT01.DBF'
ORA-27038: created file already exists
OSD-04010: <create> option specified, file already exists
Failing sql is:
CREATE TABLESPACE "PERFSTAT" DATAFILE 'G:\ORACLE\ORADATA\TRPROD\PERFSTAT01.DBF' SIZE 209715200 AUTOEXTEND ON NEXT 10485760 MAXSIZE 2146435072 LOGGING ONLINE PERMANENT BLOCKSIZE 8192 EXTENT MANAGEMENT LOCAL AUTOALLOCATE DEFAULT NOCOMPRESS  SEGMENT SPAC

I've tried adding EXCLUDE=TABLESPACE:"='PERFSTAT'" to the EXPDP command to try and exclude that tablespace, but I gave me a syntax error, so I'm wondering what the correct way to do a full refresh of our test database would be yet exclude this one specific tablespace?

Body:
You can create a parameter file as shown below.

[oracle@oratestprod fra]$ cat test.par
DIRECTORY=TRPROD_EXPORT
FULL=Y
DUMPFILE=TRPROD_FULL_EXPORT.DMP
LOGFILE=TRPROD_FULL_EXPORT.LOG
COMPRESSION=all
exclude=tablespace:"IN ('PERFSTAT')"

And run as shown below.

[oracle@oratestprod fra]$ expdp system parfile=test.par


问:
How do I .map() a new array of values from an array and an object?
```<code>let a1 = [1, 3, 5];
let a2 = {1: "a", 2: "b", 3: "c", 4: "d", 5: 2,}

// pass a function to map

const map1 = a1.map(? => ?);
console.log(map1);

// expected output: Array ["a", "c", 2]
</code>```

I want the number in the array 1, 3, 5 to map to the values on the keys of a2

What should "? => ?" be for the desired result?

Edited

My question is after reading the documentation Array.prototype.map() in MDN.

My question is (not how to solve this) but to learn about the callback function in .map():

```<code>let a1 = [1, 3, 5];
let a2 = {1: "a", 2: "b", 3: "c", 4: "d", 5: 2,}

// pass a function to map

const map1 = a1.map(a2, e => a2.value);
console.log(map1);

// expected output: Array ["a", "c", 2]
</code>```

Here I wanted e in a1 to match a2 and return a2 in the map function, but it's clearly wrong but after Googling for examples I guess I just had to make a question about it and try not cause too much confusion.

Body:
let a1 = [1, 3, 5];
let a2 = {1: "a", 2: "b", 3: "c", 4: "d", 5: 2,}

// pass a function to map

const map1 = a1.map(? => ?);
console.log(map1);

// expected output: Array ["a", "c", 2]

I want the number in the array 1, 3, 5 to map to the values on the keys of a2

What should "? => ?" be for the desired result?

Edited

My question is after reading the documentation Array.prototype.map() in MDN.

My question is (not how to solve this) but to learn about the callback function in .map():

let a1 = [1, 3, 5];
let a2 = {1: "a", 2: "b", 3: "c", 4: "d", 5: 2,}

// pass a function to map

const map1 = a1.map(a2, e => a2.value);
console.log(map1);

// expected output: Array ["a", "c", 2]

Here I wanted e in a1 to match a2 and return a2 in the map function, but it's clearly wrong but after Googling for examples I guess I just had to make a question about it and try not cause too much confusion.

Body:
Simply get the property from the object.

let a1 = [1, 3, 5];
let a2 = {1: "a", 2: "b", 3: "c", 4: "d", 5: 2,}

// pass a function to map
const map1 = a1.map(k => a2[k]);
// -----------------^^^^^^^^^^----
console.log(map1);


问:
ES6 support in VSCode isnt working
Ive seen other questions regarding this issue - Is there a way to turn on ES6/ES7 syntax support in vscode? - but this has now been addressed by Microsoft and implemented in VSCode.

However, I have downloaded the latest version of VSCode, and cloned the example es6 repo from GitHub, and it seems to not be working

答: If you're using eslint with npm, you may need the .eslintrc file in the root folder of your project. See my answer to this question and the docs for the ESLint VSCode extension.</p>

Title: ES6 support in VSCode isnt working


问:
Compilation fails in VS2010 for C++ programs building fine in Linux
My C++ project builds and runs fine on Linux. Now I am trying to compile it in VS2010. I get many errors seemingly from cmath library like the following one.

```<code>Error   1   error C2061: syntax error : identifier 'acosf'  c:\program files\microsoft visual studio 10.0\vc\include\cmath  19  1   MyPROJ
</code>```

Also I get many file operations related compilation errors like:

```<code>Error   1   error C3861: 'lseek': identifier not found  g:\project\file.cc  274 1   MyPROJ

Error   2   error C3861: 'write': identifier not found  g:\project\file.cc  275 1   MyPROJ
</code>```

How to eliminate these errors.

答: You can't port linux programs on windows without changing the sources a bit because they use different headers</p>

Body:
My C++ project builds and runs fine on Linux. Now I am trying to compile it in VS2010. I get many errors seemingly from cmath library like the following one.

Error   1   error C2061: syntax error : identifier 'acosf'  c:\program files\microsoft visual studio 10.0\vc\include\cmath  19  1   MyPROJ

Also I get many file operations related compilation errors like:

Error   1   error C3861: 'lseek': identifier not found  g:\project\file.cc  274 1   MyPROJ

Error   2   error C3861: 'write': identifier not found  g:\project\file.cc  275 1   MyPROJ

How to eliminate these errors.