问:
How to Reverse Chart.js Label Order?
I'm using  a lot of pie  and doughnut charts  with two data values  in a
project. It really annoys me that since the chart slices starts from the
top going clockwise, the labels end up looking reversed: on the opposite
side of the data it represents.

Is there an easy way to reverse the label order, or reverse the chart to
run counter-clockwise?

```<code>new Chart(context, {
  type: 'doughnut',
  data: {
    labels: [ 'Blue', 'Red' ],
    datasets: [
      {
        data: [7, 3],
        backgroundColor: [
          'rgba(54, 162, 235, 0.7)',
          'rgba(208, 54, 100, 0.7)',
        ],
      },
    ]
  }
});
</code>```

答:
Try giving it rotation via options in the Chart object.

```<code>new Chart(context, {
type: 'doughnut',
data: {
labels: [ 'Blue', 'Red' ],
datasets: [{
          data: [7, 3],
          backgroundColor: [
          'rgba(54, 162, 235, 0.7)',
          'rgba(208, 54, 100, 0.7)',
          ],
      }]
     },
  options: {rotation: (0.5 * Math.PI)}
});
</code>```

Fiddle: https://jsfiddle.net/zdh7591r/

Title: How to Reverse Chart.js Label Order?

Body:
I'm using  a lot of pie  and doughnut charts  with two data values  in a
project. It really annoys me that since the chart slices starts from the
top going clockwise, the labels end up looking reversed: on the opposite
side of the data it represents.

Is there an easy way to reverse the label order, or reverse the chart to
run counter-clockwise?

new Chart(context, {
  type: 'doughnut',
  data: {
    labels: [ 'Blue', 'Red' ],
    datasets: [
      {
        data: [7, 3],
        backgroundColor: [
          'rgba(54, 162, 235, 0.7)',
          'rgba(208, 54, 100, 0.7)',
        ],
      },
    ]
  }
});

Body:
Try giving it rotation via options in the Chart object.

new Chart(context, {
type: 'doughnut',
data: {
labels: [ 'Blue', 'Red' ],
datasets: [{
          data: [7, 3],
          backgroundColor: [
          'rgba(54, 162, 235, 0.7)',
          'rgba(208, 54, 100, 0.7)',
          ],
      }]
     },
  options: {rotation: (0.5 * Math.PI)}
});

Fiddle: https://jsfiddle.net/zdh7591r/


来源: stackexchange

问:
conda is not recognized as an internal or external command, operable program or batch file
I was updating pandas (on windows 7) using:

```<code>conda update pandas
</code>```

accidentally I closed the command window while updating.
Now I can't start spyder and if I type conda in the command window I get:

```<code>"conda is not recognized as an internal or external command operable program or batch file"
</code>```

if I type spyder --show=console I get

```<code>from PyQt5.Qtwidgets import *
importerror: DLL load failed: The specific module could not be found
</code>```

Any idea how to solve this?

答: Search pip in your system and set the location to your system environment variable. For example, for default setting, you may add following path: C:\ProgramData\Anaconda3\Scripts</p>

ContentLicense: CC BY-SA 3.0

Body:
I was updating pandas (on windows 7) using:

conda update pandas

accidentally I closed the command window while updating.
Now I can't start spyder and if I type conda in the command window I get:

"conda is not recognized as an internal or external command operable program or batch file"

if I type spyder --show=console I get

from PyQt5.Qtwidgets import *
importerror: DLL load failed: The specific module could not be found

Any idea how to solve this?


问:
How can I automate sending and receiving TCP traffic using netcat in Bash?
I'm trying to create some test network traffic by sending TCP traffic using netcat.

The issue is that the netcat command to receive TCP data doesn't end on its own, which makes perfect sense.

I'm wondering how I can have a script that continues running to the send portion of the TCP traffic.  Something similar to:

```<code>#!/bin/bash

#Prepare to receive traffic
nc -vv -l -p 5000 > receiveData.txt

#Send traffic
nc -nvv localhost 5000 < sendData.txt
</code>```

Obviously the script will never get to the #Send traffic line because the receive traffic never ends.  I've been looking at methods for running functions in bash asynchronously, but nothing I've read seems to solve this problem.

答:
How about just running receive traffic process in the background so that the other commands can be executed to?</p>

```<code># Prepare to receive traffic
# Running this process in the background so that the sending TCP traffic
# happens

nc -vv -l -p 5000 > receiveData.txt &

#Send traffic
nc -nvv localhost 5000 < sendData.txt
</code>```

Body:
I'm trying to create some test network traffic by sending TCP traffic using netcat.

The issue is that the netcat command to receive TCP data doesn't end on its own, which makes perfect sense.

I'm wondering how I can have a script that continues running to the send portion of the TCP traffic.  Something similar to:

#!/bin/bash

#Prepare to receive traffic
nc -vv -l -p 5000 > receiveData.txt

#Send traffic
nc -nvv localhost 5000 < sendData.txt

Obviously the script will never get to the #Send traffic line because the receive traffic never ends.  I've been looking at methods for running functions in bash asynchronously, but nothing I've read seems to solve this problem.

Body:
How about just running receive traffic process in the background so that the other commands can be executed to?

# Prepare to receive traffic
# Running this process in the background so that the sending TCP traffic
# happens

nc -vv -l -p 5000 > receiveData.txt &

#Send traffic
nc -nvv localhost 5000 < sendData.txt


问:
Operation time limit
is there a way to time limit the oparations in python, eg:</p>

```<code>try:
    cmds.file( file, o=1, pmt=0 )
except:
    print "Sorry, run out of time"
    pass
</code>```

答:
If you're on Mac or a Unix-based system, you can use signal.SIGALRM to forcibly time out functions that take too long, so your code would look like:

```<code>import signal

class TimeoutException(Exception):   # custom exception
    pass

def timeout_handler(signum, frame):   # raises exception when signal sent
    raise TimeoutException

# Makes it so that when SIGALRM signal sent, it calls the function timeout_handler, which raises your exception
signal.signal(signal.SIGALRM, timeout_handler)

# Start the timer. Once 5 seconds are over, a SIGALRM signal is sent.
signal.alarm(5)
try:
    cmds.file( file, o=1, pmt=0 )
except TimeoutException:
    print "Sorry, run out of time" # you don't need pass because that's in the exception definition
</code>```

Basically, you're creating a custom exception that's raised when the after the time limit is up (i.e., the SIGALRM is sent). You can of course tweak the time limit.

Title: Operation time limit

Body:
is there a way to time limit the oparations in python, eg:

try:
    cmds.file( file, o=1, pmt=0 )
except:
    print "Sorry, run out of time"
    pass

Body:
If you're on Mac or a Unix-based system, you can use signal.SIGALRM to forcibly time out functions that take too long, so your code would look like:

import signal

class TimeoutException(Exception):   # custom exception
    pass

def timeout_handler(signum, frame):   # raises exception when signal sent
    raise TimeoutException

# Makes it so that when SIGALRM signal sent, it calls the function timeout_handler, which raises your exception
signal.signal(signal.SIGALRM, timeout_handler)

# Start the timer. Once 5 seconds are over, a SIGALRM signal is sent.
signal.alarm(5)
try:
    cmds.file( file, o=1, pmt=0 )
except TimeoutException:
    print "Sorry, run out of time" # you don't need pass because that's in the exception definition

Basically, you're creating a custom exception that's raised when the after the time limit is up (i.e., the SIGALRM is sent). You can of course tweak the time limit.


问:
Padding 1D NumPy array with zeros to form 2D array
I have a numpy array:

```<code>arr=np.array([0,1,0,0.5])
</code>```

I need to form a new array from it as follows, such that every zero elements is repeated thrice and every non-zero element has 2 preceding zeroes, followed by the non-zero number. In short, every element is repeated thrice, zero as it is and non-zero has 2 preceding 0 and then the number itself. It is as follows:

```<code>([0,1,0,0.5])=0,0,0, [for index 0]
              0,0,1 [for index 1]
              0,0,0 [for index 2, which again has a zero] and
              0,0,0.5
</code>```

final output should be:

```<code>new_arr=[0,0,0,0,0,1,0,0,0,0,0,0.5]
</code>```

np.repeat() repeats all the array elements n number of times, but i dont want that exactly. How should this be done? Thanks for the help.

ContentLicense: CC BY-SA 4.0

Body:
I have a numpy array:

arr=np.array([0,1,0,0.5])

I need to form a new array from it as follows, such that every zero elements is repeated thrice and every non-zero element has 2 preceding zeroes, followed by the non-zero number. In short, every element is repeated thrice, zero as it is and non-zero has 2 preceding 0 and then the number itself. It is as follows:

([0,1,0,0.5])=0,0,0, [for index 0]
              0,0,1 [for index 1]
              0,0,0 [for index 2, which again has a zero] and
              0,0,0.5

final output should be:

new_arr=[0,0,0,0,0,1,0,0,0,0,0,0.5]

np.repeat() repeats all the array elements n number of times, but i dont want that exactly. How should this be done? Thanks for the help.

Body:
A quick reshape followed by a call to np.pad will do it:

np.pad(arr.reshape(-1, 1), ((0, 0), (2, 0)), 'constant')

Output:

array([[ 0. ,  0. ,  0. ],
       [ 0. ,  0. ,  1. ],
       [ 0. ,  0. ,  0. ],
       [ 0. ,  0. ,  0.5]])

You'll want to flatten it back again. That's simply done by calling .reshape(-1, ).

>>> np.pad(arr.reshape(-1, 1), ((0, 0), (2, 0)), 'constant').reshape(-1, )
array([ 0. ,  0. ,  0. ,  0. ,  0. ,  1. ,  0. ,  0. ,  0. ,  0. ,  0. ,
    0.5])


问:
Copy Row A1 from Sheet 1 into Row A1 Sheet 2
I basically just need to know how to copy a header from sheet one that goes from A1-O1 into sheet two, three, four, five and so on...they all have the same header. Sheet one is on the right and sheet two is left and increases to the left. I tried this which I found on some website but it says object required. The error is Runtime Error 424</p>

```<code>mainworkBook.Sheets(“Sheet1”).Rows(1).EntireRow.Copy
mainworkBook.Sheets(“Sheet2”).Range(“A1”).Select
mainworkBook.Sheets(“Sheet2”).Paste
</code>```

答:
You can do something like this instead of using Select:

```<code>For Each Sheet In ThisWorkbook.Sheets
    ThisWorkbook.Sheets("ALL_DATA").Rows(1).Copy Destination:=Worksheets(Sheet.Name).Range("A1")
Next
</code>```

This will loop through each sheet in your workbook, take the range you provided (row 1 from Sheet1), and paste it to each sheet by referencing the Name property of each Sheet you are looping through.

The error may have been from the workbook variable, as that is the only thing that is unclear.

I would also recommend looking into this post: How to avoid using Select in Excel VBA macros as it is tremendously helpful in avoiding Select/Activate when possible, which is a common occurrence among those who learn VBA through recording Macros.

Let me know if it works for you.

Body:
I basically just need to know how to copy a header from sheet one that goes from A1-O1 into sheet two, three, four, five and so on...they all have the same header. Sheet one is on the right and sheet two is left and increases to the left. I tried this which I found on some website but it says object required. The error is Runtime Error 424

mainworkBook.Sheets(“Sheet1”).Rows(1).EntireRow.Copy
mainworkBook.Sheets(“Sheet2”).Range(“A1”).Select
mainworkBook.Sheets(“Sheet2”).Paste

Body:
You can do something like this instead of using Select:

For Each Sheet In ThisWorkbook.Sheets
    ThisWorkbook.Sheets("ALL_DATA").Rows(1).Copy Destination:=Worksheets(Sheet.Name).Range("A1")
Next

This will loop through each sheet in your workbook, take the range you provided (row 1 from Sheet1), and paste it to each sheet by referencing the Name property of each Sheet you are looping through.

The error may have been from the workbook variable, as that is the only thing that is unclear.

I would also recommend looking into this post: How to avoid using Select in Excel VBA macros as it is tremendously helpful in avoiding Select/Activate when possible, which is a common occurrence among those who learn VBA through recording Macros.

Let me know if it works for you.


问:
ERROR: no library trees found in 'lib.loc' when deploying Shiny App
I got this error when I tried to deploy my App using https://www.shinyapps.io/.

ERROR: no library trees found in 'lib.loc'

Any idea why? I found several threads about it but the explanation are not very clear to me.

These are the locations of my packages:

```<code>library("plyr", lib.loc="C:/Users/Ktanizar/Documents/R/win-library/3.4")

library("cluster", lib.loc="C:/Program Files/R/R-3.4.1/library")

library("xlsx", lib.loc="C:/Users/Ktanizar/Documents/R/win-library/3.4")

library("seriation", lib.loc="C:/Users/Ktanizar/Documents/R/win-library/3.4")

library("data.tree", lib.loc="C:/Users/Ktanizar/Documents/R/win-library/3.4")

library("DT", lib.loc="C:/Users/Ktanizar/Documents/R/win-library/3.4")

library("shinythemes", lib.loc="C:/Users/Ktanizar/Documents/R/win-library/3.4")

library("clipr", lib.loc="C:/Users/Ktanizar/Documents/R/win-library/3.4")
</code>```

Here is the result when I run .libPaths()
[1]
"C:/Users/KTanizar/Documents/R/win-library/3.4"
    "C:/Program Files/R/R-3.4.1/library"

Here is the path of rsconnect

rsconnect::deployApp('C:/Users/Ketty Noonan/Desktop/Innovation Projects/0 Market Structure/5 Innovation/1 R scripts and notes/R_Shiny/2 Deploy')

Any ideas are greatly appreciated.

答:
It works now with the following codes:

```<code>if(!require("plyr"))
  install.packages("plyr")
if(!require("cluster"))
  install.packages("cluster")
if(!require("xlsx"))
  install.packages("xlsx")
if(!require("seriation"))
  install.packages("seriation")
if(!require("data.tree"))
  install.packages("data.tree")
if(!require("DT"))
  install.packages("DT")
if(!require("shinythemes"))
  install.packages("shinythemes")
if(!require("clipr"))
  install.packages("clipr")
</code>```

and when I changed the following code

```<code>fluidPage(theme = "bootstrap.css",
</code>```

from the following

```<code>fluidPage(theme = shinytheme("spacelab"),
</code>```

Hope this helps someone and thank you, Jarko.

Body:
I got this error when I tried to deploy my App using https://www.shinyapps.io/.

ERROR: no library trees found in 'lib.loc'

Any idea why? I found several threads about it but the explanation are not very clear to me.

These are the locations of my packages:

library("plyr", lib.loc="C:/Users/Ktanizar/Documents/R/win-library/3.4")

library("cluster", lib.loc="C:/Program Files/R/R-3.4.1/library")

library("xlsx", lib.loc="C:/Users/Ktanizar/Documents/R/win-library/3.4")

library("seriation", lib.loc="C:/Users/Ktanizar/Documents/R/win-library/3.4")

library("data.tree", lib.loc="C:/Users/Ktanizar/Documents/R/win-library/3.4")

library("DT", lib.loc="C:/Users/Ktanizar/Documents/R/win-library/3.4")

library("shinythemes", lib.loc="C:/Users/Ktanizar/Documents/R/win-library/3.4")

library("clipr", lib.loc="C:/Users/Ktanizar/Documents/R/win-library/3.4")

Here is the result when I run .libPaths()
[1]
"C:/Users/KTanizar/Documents/R/win-library/3.4"
    "C:/Program Files/R/R-3.4.1/library"

Here is the path of rsconnect

rsconnect::deployApp('C:/Users/Ketty Noonan/Desktop/Innovation Projects/0 Market Structure/5 Innovation/1 R scripts and notes/R_Shiny/2 Deploy')

Any ideas are greatly appreciated.

Body:
It works now with the following codes:

if(!require("plyr"))
  install.packages("plyr")
if(!require("cluster"))
  install.packages("cluster")
if(!require("xlsx"))
  install.packages("xlsx")
if(!require("seriation"))
  install.packages("seriation")
if(!require("data.tree"))
  install.packages("data.tree")
if(!require("DT"))
  install.packages("DT")
if(!require("shinythemes"))
  install.packages("shinythemes")
if(!require("clipr"))
  install.packages("clipr")

and when I changed the following code

fluidPage(theme = "bootstrap.css",

from the following

fluidPage(theme = shinytheme("spacelab"),

Hope this helps someone and thank you, Jarko.


问:
openui5 can't find <template:repeat> in xml view
According to:sap documentation: repeat I should be able to use a repeat tag to loop over my data.
I added the template namespace xmlns:template="http://schemas.sap.com/sapui5/extension/sap.ui.core.template/1" but when I try to run my code it gives the following error:

Uncaught Error: failed to load 'http://schemas/sap/com/openui5/extension/sap/ui/core/template/1/repeat.js' from webjars/openui5/1.42.6/

I can't change my openui5 version.
I work in Eclipse with an openui5 front-end and a Java services back-end.

答:
This error looks like UI5 is trying to load the pre-processor directives as if they were controls. Because controls are not yet loaded during pre-processing, I guess that this happens during view control tree instantiation. This in turn indicates that the template instructions were still present in the XML view at the moment when the control tree was built.

Are you sure you actually have "activated" XML pre-processing before instantiating your view? Check out the XML pre-processing documentation (more specifically, the "calling the preprocessor" example).

Actually, now that I am reading your question again, I think you want to use XML pre-processing instructions for building the UI based on your data.  This should not be the case, you should use XML pre-processing / templateing only for building the views based on your meta-data (i.e. only once, the first time the view is shown).

For adapting your views based on your data, you should use data binding instead. More specifically, you should use aggregation binding to emulate a loop.


问:
%in% does not returns atomic result
In this operation, x is a tbl_df, and outliers is a data.frame.
But id returns a logical, not a tbl_df.

What am i doing wrong?

```<code>x <- as_tibble(c(rep(2,10),50,64,80))
boxplot1 <-
  ggplot (data=x, aes_string (x = factor(0), y = "x" )) +
  geom_boxplot (fill = "lightgreen", outlier.fill = "darkgreen") +
  stat_boxplot(geom ='errorbar', color = "grey") +
  coord_flip () +
  ggtitle (paste0 ("x", ", with outliers"))
outliers <- data.frame (unlist (ggplot_build(boxplot1)$data[[1]][6],use.names = F),stringsAsFactors=FALSE)
id <- x %in% outliers
</code>```

I expected a tbl_df with the same length that x. Indeed, id <- match(outliers,x) returns a numeric of length outliers, but id <- match(x,outliers) does not return a numeric of length x

答: the solution was put id in brakets id <- x[[1]] %in% outliers[[1]], but I do not understand why.

Title: %in% does not returns atomic result

Body:
In this operation, x is a tbl_df, and outliers is a data.frame.
But id returns a logical, not a tbl_df.

What am i doing wrong?

x <- as_tibble(c(rep(2,10),50,64,80))
boxplot1 <-
  ggplot (data=x, aes_string (x = factor(0), y = "x" )) +
  geom_boxplot (fill = "lightgreen", outlier.fill = "darkgreen") +
  stat_boxplot(geom ='errorbar', color = "grey") +
  coord_flip () +
  ggtitle (paste0 ("x", ", with outliers"))
outliers <- data.frame (unlist (ggplot_build(boxplot1)$data[[1]][6],use.names = F),stringsAsFactors=FALSE)
id <- x %in% outliers

I expected a tbl_df with the same length that x. Indeed, id <- match(outliers,x) returns a numeric of length outliers, but id <- match(x,outliers) does not return a numeric of length x


问:
Custom blocks not working in Drupal 8
I'm building a module with custom block in Drupal 8 beta 9. When I create a block in my module I'm placing it in src\Plugin\Block directory. The block show in 'Block structure' list, but when I press link to add it, nothing happens.
I reviewed my code 10 times, tried to put my files into core module's directories (only for test obviously), tried to put some core block files to my directory, to copy-paste code. None of this works. Here is a code of my block file: </p>

```<code><?php
/**
 * @file
 * Contains \Drupal\internetdevels\Plugin\Block\TestBlock.
 */

namespace Drupal\internetdevels\Plugin\Block;
use Drupal\Core\Block\BlockBase;

/**
 * Provides 'my custom' block.
 *
 * @Block(
 *   id = "my_custom_block",
 *   admin_label = @Translation("My Custom Block"),
 *   category = @Translation("System"),
 * )
 */
class TestBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    return array('#markup' => 'hello world');
  }

}
</code>```

答:
```<code>class TestBlock extends BlockBase {

/*
** {@inheritdoc}
*/

public function build() {
   return array(
     '#markup' => $this->t('Welcome page!'),
   );
   }
}
</code>```

Use the following link to create new custom bloc programatically.

Title: Custom blocks not working in Drupal 8

Body:
I'm building a module with custom block in Drupal 8 beta 9. When I create a block in my module I'm placing it in src\Plugin\Block directory. The block show in 'Block structure' list, but when I press link to add it, nothing happens.
I reviewed my code 10 times, tried to put my files into core module's directories (only for test obviously), tried to put some core block files to my directory, to copy-paste code. None of this works. Here is a code of my block file:

<?php
/**
 * @file
 * Contains \Drupal\internetdevels\Plugin\Block\TestBlock.
 */

namespace Drupal\internetdevels\Plugin\Block;
use Drupal\Core\Block\BlockBase;

/**
 * Provides 'my custom' block.
 *
 * @Block(
 *   id = "my_custom_block",
 *   admin_label = @Translation("My Custom Block"),
 *   category = @Translation("System"),
 * )
 */
class TestBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    return array('#markup' => 'hello world');
  }

}

Body:
class TestBlock extends BlockBase {

/*
** {@inheritdoc}
*/

public function build() {
   return array(
     '#markup' => $this->t('Welcome page!'),
   );
   }
}

Use the following link to create new custom bloc programatically.


问:
Virtually turn vector of struct into vector of struct members
I have a function that takes a vector-like input. To simplify things, let's use this print_in_order function:

```<code>#include <iostream>
#include <vector>

template <typename vectorlike>
void print_in_order(std::vector<int> const & order,
                    vectorlike const & printme) {
    for (int i : order)
        std::cout << printme[i] << std::endl;
}

int main() {
    std::vector<int> printme = {100, 200, 300};
    std::vector<int> order = {2,0,1};
    print_in_order(order, printme);
}
</code>```

Now I have a vector<Elem> and want to print a single integer member, Elem.a, for each Elem in the vector. I could do this by creating a new vector<int> (copying a for all Elems) and pass this to the print function - however, I feel like there must be a way to pass a "virtual" vector that, when operator[] is used on it, returns this only the member a. Note that I don't want to change the print_in_order function to access the member, it should remain general.

Is this possible, maybe with a lambda expression?
Full code below.

```<code>#include <iostream>
#include <vector>

struct Elem {
    int a,b;
    Elem(int a, int b) : a(a),b(b) {}
};

template <typename vectorlike>
void print_in_order(std::vector<int> const & order,
                    vectorlike const & printme) {
    for (int i : order)
        std::cout << printme[i] << std::endl;
}

int main() {
    std::vector<Elem> printme = {Elem(1,100), Elem(2,200), Elem(3,300)};
    std::vector<int> order = {2,0,1};

    // how to do this?
    virtual_vector X(printme) // behaves like a std::vector<Elem.a>
    print_in_order(order, X);
}
</code>```

答:
It's not really possible to directly do what you want. Instead you might want to take a hint from the standard algorithm library, for example std::for_each where you take an extra argument that is a function-like object that you call for each element. Then you could easily pass a lambda function that prints only the wanted element.

Perhaps something like

```<code>template<typename vectorlike, typename functionlike>
void print_in_order(std::vector<int> const & order,
                vectorlike const & printme,
                functionlike func) {
    for (int i : order)
        func(printme[i]);
}
</code>```

Then call it like

```<code>print_in_order(order, printme, [](Elem const& elem) {
    std::cout << elem.a;
});
</code>```

Since C++ have function overloading you can still keep the old print_in_order function for plain vectors.

Body:
I have a function that takes a vector-like input. To simplify things, let's use this print_in_order function:

#include <iostream>
#include <vector>

template <typename vectorlike>
void print_in_order(std::vector<int> const & order,
                    vectorlike const & printme) {
    for (int i : order)
        std::cout << printme[i] << std::endl;
}

int main() {
    std::vector<int> printme = {100, 200, 300};
    std::vector<int> order = {2,0,1};
    print_in_order(order, printme);
}

Now I have a vector<Elem> and want to print a single integer member, Elem.a, for each Elem in the vector. I could do this by creating a new vector<int> (copying a for all Elems) and pass this to the print function - however, I feel like there must be a way to pass a "virtual" vector that, when operator[] is used on it, returns this only the member a. Note that I don't want to change the print_in_order function to access the member, it should remain general.

Is this possible, maybe with a lambda expression?
Full code below.

#include <iostream>
#include <vector>

struct Elem {
    int a,b;
    Elem(int a, int b) : a(a),b(b) {}
};

template <typename vectorlike>
void print_in_order(std::vector<int> const & order,
                    vectorlike const & printme) {
    for (int i : order)
        std::cout << printme[i] << std::endl;
}

int main() {
    std::vector<Elem> printme = {Elem(1,100), Elem(2,200), Elem(3,300)};
    std::vector<int> order = {2,0,1};

    // how to do this?
    virtual_vector X(printme) // behaves like a std::vector<Elem.a>
    print_in_order(order, X);
}

Body:
It's not really possible to directly do what you want. Instead you might want to take a hint from the standard algorithm library, for example std::for_each where you take an extra argument that is a function-like object that you call for each element. Then you could easily pass a lambda function that prints only the wanted element.

Perhaps something like

template<typename vectorlike, typename functionlike>
void print_in_order(std::vector<int> const & order,
                vectorlike const & printme,
                functionlike func) {
    for (int i : order)
        func(printme[i]);
}

Then call it like

print_in_order(order, printme, [](Elem const& elem) {
    std::cout << elem.a;
});

Since C++ have function overloading you can still keep the old print_in_order function for plain vectors.


问:
MySQL: Number of subsequent occurrences
I have a table with four columns: id, from, to, msg.

The rows can look like this:

```<code>1 - foo - bar - hello
2 - foo - bar - zup?
3 - bar - foo - hi
4 - bar - foo - going okay
5 - bar - foo - you?
</code>```

Now I wanna know how many times "bar" has tried to "talk" to "foo" without response. Like I wanna count the number of occurrences since "foo" was on the sending end.

In this example, before the next entry, it should return 3.

Is this possible in pure (My)SQL?

I'm using php on the server side.

Thanks for any tips and advice! =)

答:
```<code>var1 = select id from table where fromname = "user1" and toname = "user2" order by id desc limit 1
var2 = select id from table where fromname = "user2" and toname = "user1" order by id desc limit 1

return var2-var1;
</code>```

ContentLicense: CC BY-SA 2.5

Title: MySQL: Number of subsequent occurrences

Body:
I have a table with four columns: id, from, to, msg.

The rows can look like this:

1 - foo - bar - hello
2 - foo - bar - zup?
3 - bar - foo - hi
4 - bar - foo - going okay
5 - bar - foo - you?

Now I wanna know how many times "bar" has tried to "talk" to "foo" without response. Like I wanna count the number of occurrences since "foo" was on the sending end.

In this example, before the next entry, it should return 3.

Is this possible in pure (My)SQL?

I'm using php on the server side.

Thanks for any tips and advice! =)


问:
Robot framework not picking up keyword implementation
I'm trying to set up robot on top of an Eclipse Maven-Selenium-TestNG java project I created, but it doesn't seem to be picking up default keywords (I haven't even tried adding my own yet).

I started by creating a maven project and adding to pom.xml the dependencies for selenium 3.4, testNG 6.8 and robot 3.0.2, then also added robot plugin 1.4.7. Finally, updated the project so maven downloads all the needed stuff.

To test selenium (without robot) I created a textNG class in src>test>java, added a system property pointing to the chromedriver.exe file in my system and added a simple test that just opens the browser and navigates to google. It worked, so now I want to use robot on top of that.

This is my pom.xml file:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.demo.automation</groupId>
  <artifactId>automated_tests</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>3.4.0</version>
    </dependency>
    <dependency>
      <groupId>org.testng</groupId>
      <artifactId>testng</artifactId>
      <version>6.8</version>
      <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.robotframework</groupId>
        <artifactId>robotframework</artifactId>
        <version>3.0.2</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.robotframework</groupId>
        <artifactId>robotframework-maven-plugin</artifactId>
        <version>1.4.7</version>
        <executions>
          <execution>
            <goals>
              <goal>run</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>
</code>```

I created a file in src/test/robotframework/acceptance, with the following contents:

```<code>*** Settings ***
Test Set Up  Start Selenium Server
Test Tear Down  Stop Selenium Server

*** Test Cases ***
Visit google
  Open Browser  https://www.google.com  chrome
  Close Browser
</code>```

However, when I run as maven install, I get:

Setup failed: No keyword with name 'Start Selenium Server' found.

Also teardown failed: No keyword with name 'Stop Selenium Server'
  found.

So why is it that robot is not finding the keywords implementation? And how do I add implementations of my own keywords?

答:
I actually found out I was missing a maven dependency:

```<code><dependency>
  <groupId>com.github.markusbernhardt</groupId>
  <artifactId>robotframework-selenium2library-java</artifactId>
  <version>1.4.0.8</version>
</dependency>
</code>```

Also, I don't need to use Start Selenium Server and Stop Selenium Server because they're deprecated.
After that, I was able to run my test by creating a custom keyword to set browser path (I'm using chromedriver):

I created a .java file within src/main/java/demo and added a method that sets up the property:

```<code>package demo;

public class Setup {
    public void driverPath() {
        System.setProperty("webdriver.chrome.driver", "C:\\path\\to\\chromedriver.exe");
    }
}
</code>```

Then, I created src/test/robotframework/acceptance/Resource.robot file and imported my library:

```<code>*** Settings ***
Library  Selenium2Library
Library  demo.Setup
</code>```

Also created a src/test/robotframework/acceptance/__init__.robot file and used the keyword I created (Browser Setup):

```<code>*** Settings ***
Test Setup  Driver Path
Test Teardown  Close All Browsers
Test Timeout  2 minute 30 seconds
</code>```

In my test, I invoked Resource.robot:

```<code>*** Settings ***
Resource  Resource.robot

*** Test Cases ***
Visit google
  Open Browser  https://www.google.com  chrome
</code>```

Body:
I'm trying to set up robot on top of an Eclipse Maven-Selenium-TestNG java project I created, but it doesn't seem to be picking up default keywords (I haven't even tried adding my own yet).

I started by creating a maven project and adding to pom.xml the dependencies for selenium 3.4, testNG 6.8 and robot 3.0.2, then also added robot plugin 1.4.7. Finally, updated the project so maven downloads all the needed stuff.

To test selenium (without robot) I created a textNG class in src>test>java, added a system property pointing to the chromedriver.exe file in my system and added a simple test that just opens the browser and navigates to google. It worked, so now I want to use robot on top of that.

This is my pom.xml file:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.demo.automation</groupId>
  <artifactId>automated_tests</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <dependencies>
    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>3.4.0</version>
    </dependency>
    <dependency>
      <groupId>org.testng</groupId>
      <artifactId>testng</artifactId>
      <version>6.8</version>
      <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.robotframework</groupId>
        <artifactId>robotframework</artifactId>
        <version>3.0.2</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.robotframework</groupId>
        <artifactId>robotframework-maven-plugin</artifactId>
        <version>1.4.7</version>
        <executions>
          <execution>
            <goals>
              <goal>run</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

I created a file in src/test/robotframework/acceptance, with the following contents:

*** Settings ***
Test Set Up  Start Selenium Server
Test Tear Down  Stop Selenium Server

*** Test Cases ***
Visit google
  Open Browser  https://www.google.com  chrome
  Close Browser

However, when I run as maven install, I get:

Setup failed: No keyword with name 'Start Selenium Server' found.

Also teardown failed: No keyword with name 'Stop Selenium Server'
  found.

So why is it that robot is not finding the keywords implementation? And how do I add implementations of my own keywords?

Body:
I actually found out I was missing a maven dependency:

<dependency>
  <groupId>com.github.markusbernhardt</groupId>
  <artifactId>robotframework-selenium2library-java</artifactId>
  <version>1.4.0.8</version>
</dependency>

Also, I don't need to use Start Selenium Server and Stop Selenium Server because they're deprecated.
After that, I was able to run my test by creating a custom keyword to set browser path (I'm using chromedriver):

I created a .java file within src/main/java/demo and added a method that sets up the property:

package demo;

public class Setup {
    public void driverPath() {
        System.setProperty("webdriver.chrome.driver", "C:\\path\\to\\chromedriver.exe");
    }
}

Then, I created src/test/robotframework/acceptance/Resource.robot file and imported my library:

*** Settings ***
Library  Selenium2Library
Library  demo.Setup

Also created a src/test/robotframework/acceptance/__init__.robot file and used the keyword I created (Browser Setup):

*** Settings ***
Test Setup  Driver Path
Test Teardown  Close All Browsers
Test Timeout  2 minute 30 seconds

In my test, I invoked Resource.robot:

*** Settings ***
Resource  Resource.robot

*** Test Cases ***
Visit google
  Open Browser  https://www.google.com  chrome


问:
Extract text from HTML while preserving block-level element newlines

Background

Most questions about extracting text from HTML (i.e., stripping the tags) use:

```<code>jQuery( htmlString ).text();
</code>```

While this abstracts browser inconsistencies (such as innerText vs. textContent), the function call also ignores the semantic meaning of block-level elements (such as li).

Problem

Preserving newlines of block-level elements (i.e., the semantic intent) across various browsers entails no small effort, as Mike Wilcox describes.

A seemingly simpler solution would be to emulate pasting HTML content into a <textarea>, which strips HTML while preserving block-level element newlines. However, JavaScript-based inserts do not trigger the same HTML-to-text routines that browsers employ when users paste content into a <textarea>.

I also tried integrating Mike Wilcox's JavaScript code. The code works in Chromium, but not in Firefox.

Question

What is the simplest cross-browser way to extract text from HTML while preserving semantic newlines for block-level elements using jQuery (or vanilla JavaScript)?

Example

Consider:

Select and copy this entire question.

Open the textarea example page.

Paste the content into the textarea.

The textarea preserves the newlines for ordered lists, headings, preformatted text, and so forth. That is the result I would like to achieve.

To further clarify, given any HTML content, such as:

```<code>   <h1>Header</h1>
   <p>Paragraph</p>
   <ul>
     <li>First</li>
     <li>Second</li>
   </ul>
   <dl>
     <dt>Term</dt>
       <dd>Definition</dd>
   </dl>
   <div>Div with <span>span</span>.<br />After the <a href="...">break</a>.</div>
</code>```

How would you produce:

```
  Header
  Paragraph

    First
    Second

  Term
    Definition

  Div with span.
  After the break.
```

Note: Neither indentation nor non-normalized whitespace are relevant.

答:
I would like to suggest a little edit from the code of svidgen:

function getText(n, isInnerNode) {
  var rv = '';
  if (n.nodeType == 3) {
      rv = n.nodeValue;
  } else {
      var partial = "";
      var d = getComputedStyle(n).getPropertyValue('display');
      if (isInnerNode && d.match(/^block/) || d.match(/list/) || n.tagName == 'BR') {
          partial += "\n";
      }

      for (var i = 0; i < n.childNodes.length; i++) {
          partial += getText(n.childNodes[i], true);
      }
      rv = partial;
  }
  return rv;
 };```
</div>
</div>
</p>

<p>I just added the line break before the for loop, in this way we have a newline before the block, and also a variable to avoid the newline for the root element.</p>

<p>The code should be invocated: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>getText(document.getElementById("divElement"))</code>```

Body:
Background

Most questions about extracting text from HTML (i.e., stripping the tags) use:

jQuery( htmlString ).text();

While this abstracts browser inconsistencies (such as innerText vs. textContent), the function call also ignores the semantic meaning of block-level elements (such as li).

Problem

Preserving newlines of block-level elements (i.e., the semantic intent) across various browsers entails no small effort, as Mike Wilcox describes.

A seemingly simpler solution would be to emulate pasting HTML content into a <textarea>, which strips HTML while preserving block-level element newlines. However, JavaScript-based inserts do not trigger the same HTML-to-text routines that browsers employ when users paste content into a <textarea>.

I also tried integrating Mike Wilcox's JavaScript code. The code works in Chromium, but not in Firefox.

Question

What is the simplest cross-browser way to extract text from HTML while preserving semantic newlines for block-level elements using jQuery (or vanilla JavaScript)?

Example

Consider:

Select and copy this entire question.

Open the textarea example page.

Paste the content into the textarea.

The textarea preserves the newlines for ordered lists, headings, preformatted text, and so forth. That is the result I would like to achieve.

To further clarify, given any HTML content, such as:

Header

Paragraph

First

Second

Term

Definition

Div with span.
After the break.

How would you produce:

  Header
  Paragraph

    First
    Second

  Term
    Definition

  Div with span.
  After the break.

Note: Neither indentation nor non-normalized whitespace are relevant.

Body:
I would like to suggest a little edit from the code of svidgen:

function getText(n, isInnerNode) {
  var rv = '';
  if (n.nodeType == 3) {
      rv = n.nodeValue;
  } else {
      var partial = "";
      var d = getComputedStyle(n).getPropertyValue('display');
      if (isInnerNode && d.match(/^block/) || d.match(/list/) || n.tagName == 'BR') {
          partial += "\n";
      }

      for (var i = 0; i < n.childNodes.length; i++) {
          partial += getText(n.childNodes[i], true);
      }
      rv = partial;
  }
  return rv;
 };

I just added the line break before the for loop, in this way we have a newline before the block, and also a variable to avoid the newline for the root element.

The code should be invocated:

getText(document.getElementById("divElement"))


问:
I am currently learning Python on codeacademy and I cant figure out what is wrong with this code
I'm currently learning python on codeacademy, I'm trying to do the following in the last function of this code:

Define a function called get_class_average that has one argument students.

You can expect students to be a list containing your three students.
First, make an empty list called results.

For each student item in the class list, calculate get_average(student) and then call results.append() with that result.

Finally, return the result of calling average() with results.
But I keep getting this error anytime i try to run the code.

"Oops, try again. get_class_average([alice]) returned 80.55 instead of 91.15 as expected"

```<code>lloyd = {
    "name": "Lloyd",
    "homework": [90.0, 97.0, 75.0, 92.0],
    "quizzes": [88.0, 40.0, 94.0],
    "tests": [75.0, 90.0]
}
alice = {
    "name": "Alice",
    "homework": [100.0, 92.0, 98.0, 100.0],
    "quizzes": [82.0, 83.0, 91.0],
    "tests": [89.0, 97.0]
}
tyler = {
    "name": "Tyler",
    "homework": [0.0, 87.0, 75.0, 22.0],
    "quizzes": [0.0, 75.0, 78.0],
    "tests": [100.0, 100.0]
}

# Add your function below!
def average(numbers):
    total = sum(numbers)
    total = float(total)
    return total / len(numbers)

def get_average(student):
    homework = average(student["homework"])
    quizzes = average(student["quizzes"])
    tests = average(student["tests"])
    return 0.1 * homework + 0.3 * quizzes + 0.6 * tests

def get_letter_grade(score):
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    elif score >= 60:
        return "D"
    else:
        return "F"

def get_class_average(students):
    students = [lloyd, alice, tyler]
    results = []
    for student in students:
        results.append(get_average(student))
        return average(results)
        print get_class_average(students)
        print get_letter_grade(get_class_average)
</code>```

答:
First: after return "F" you have a very inconsistent indentation. Move everything one tab left except for the first line (student =...)

Second: in the first line of get_class_average you erase students passed to function and write a new array. Either initialize students outside and pass them to function, or pass nothing and construct the array inside.

First is better.

Body:
I'm currently learning python on codeacademy, I'm trying to do the following in the last function of this code:

Define a function called get_class_average that has one argument students.

You can expect students to be a list containing your three students.
First, make an empty list called results.

For each student item in the class list, calculate get_average(student) and then call results.append() with that result.

Finally, return the result of calling average() with results.
But I keep getting this error anytime i try to run the code.

"Oops, try again. get_class_average([alice]) returned 80.55 instead of 91.15 as expected"

lloyd = {
    "name": "Lloyd",
    "homework": [90.0, 97.0, 75.0, 92.0],
    "quizzes": [88.0, 40.0, 94.0],
    "tests": [75.0, 90.0]
}
alice = {
    "name": "Alice",
    "homework": [100.0, 92.0, 98.0, 100.0],
    "quizzes": [82.0, 83.0, 91.0],
    "tests": [89.0, 97.0]
}
tyler = {
    "name": "Tyler",
    "homework": [0.0, 87.0, 75.0, 22.0],
    "quizzes": [0.0, 75.0, 78.0],
    "tests": [100.0, 100.0]
}

# Add your function below!
def average(numbers):
    total = sum(numbers)
    total = float(total)
    return total / len(numbers)

def get_average(student):
    homework = average(student["homework"])
    quizzes = average(student["quizzes"])
    tests = average(student["tests"])
    return 0.1 * homework + 0.3 * quizzes + 0.6 * tests

def get_letter_grade(score):
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    elif score >= 60:
        return "D"
    else:
        return "F"

def get_class_average(students):
    students = [lloyd, alice, tyler]
    results = []
    for student in students:
        results.append(get_average(student))
        return average(results)
        print get_class_average(students)
        print get_letter_grade(get_class_average)


问:
Matplotlib dates in datetime format
I am plotting a candlestick chart (ohlc+volume) and unfortunately I can't figure out how to display the date in datetime format. Several approaches did not work.

```<code>import matplotlib.pyplot as plt
from matplotlib.finance import candlestick_ohlc
from matplotlib import style
import pandas as pd

style.use('classic')

def graph(candlestick_list):
    df = pd.DataFrame(candlestick_list)
    ohlc = df[['date', 'open', 'high', 'low', 'close']]

    ax1 = plt.subplot2grid((6,1), (0,0), rowspan=5, colspan=1)
    ax2 = plt.subplot2grid((6,1), (5,0), rowspan=5, colspan=1, sharex=ax1)
    candlestick_ohlc(ax1, ohlc.values, width=0.5, colorup='g', colordown='r')
    ax2.bar(df['date'], df['volume'])
    plt.show()
</code>```

Unfortunately the following approaches didn't work for me:

df['date'] = pd.to_datetime(df['date'], unit='s')

TypeError: unsupported operand type(s) for -: 'Timestamp' and 'float'

or this one:

```<code>import matplotlib.dates as mdates
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
</code>```

ValueError: year 4095909 is out of range

Does anybody have an idea?
Many thanks in advance!

PS: the following list can be used to test the code

```<code>candlestick_list = [{'date': 1496332800, 'high': 215.3209, 'low': 200.3, 'open': 211.18, 'close': 206.47999999, 'volume': 2432435.9201853, 'quoteVolume': 11813.26856836, 'weightedAverage': 205.90710404}, {'date': 1496340000, 'high': 212.0001, 'low': 205.75400533, 'open': 206.47999992, 'close': 207.85, 'volume': 1301024.6514137, 'quoteVolume': 6250.47612412, 'weightedAverage': 208.14808753}, {'date': 1496347200, 'high': 212.44999999, 'low': 206.9813717, 'open': 208.49981874, 'close': 209.99811003, 'volume': 1062083.1773221, 'quoteVolume': 5056.26107738, 'weightedAverage': 210.05307302}, {'date': 1496354400, 'high': 213.20999999, 'low': 209.61231001, 'open': 210, 'close': 211.44, 'volume': 705968.23009208, 'quoteVolume': 3335.35026592, 'weightedAverage': 211.66239639}, {'date': 1496361600, 'high': 219, 'low': 210.81410968, 'open': 211.43999994, 'close': 215.41715998, 'volume': 972040.25543603, 'quoteVolume': 4500.001815, 'weightedAverage': 216.00885852}]
</code>```

答:
Try converting the dates into Matplotlib format. Often, Matplotlib will recognize and auto-convert dates from DataFrames, but there are many odd cases. Generally when things don't work, do your own conversion manually.

```<code>import matplotlib.pyplot as plt
from matplotlib.finance import candlestick_ohlc
from matplotlib import style
import pandas as pd
import matplotlib.dates as mdates

def graph(candlestick_list):
    df = pd.DataFrame(candlestick_list)
    df['date'] = pd.to_datetime(df['date'], unit='s')
    df['mdate'] = [mdates.date2num(d) for d in df['date']]

    ohlc = df[['mdate', 'open', 'high', 'low', 'close']]

    ax1 = plt.subplot2grid((6,1), (0,0), rowspan=5, colspan=1)
    ax2 = plt.subplot2grid((6,1), (5,0), rowspan=5, colspan=1, sharex=ax1)
    candlestick_ohlc(ax1, ohlc.values, width=0.05, colorup='g', colordown='r')
    ax2.bar(df['mdate'], df['volume'])
    ax2.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
    plt.xticks(rotation=60)
    plt.show()
</code>```

Documentation for date2num(). Note I added a separate mdate column. Useful for debugging, and if you need to also use regular Pandas dates for other purposes. Here in this limited, within-a-function context, probably overkill to keep several date representations around.
I also thinned the width of your OHLC bars, and rotated the date ticks so I could see them better. YMMV on such styling tweaks.

Finally, if the use of a list comprehension offends your sensibilties because "it's not vectorized," you can do the conversion to matplotlib style dates in one go with:

```<code>df['mdate'] = mdates.date2num(df.date.dt.to_pydatetime())
</code>```

Title: Matplotlib dates in datetime format

Body:
I am plotting a candlestick chart (ohlc+volume) and unfortunately I can't figure out how to display the date in datetime format. Several approaches did not work.

import matplotlib.pyplot as plt
from matplotlib.finance import candlestick_ohlc
from matplotlib import style
import pandas as pd

style.use('classic')

def graph(candlestick_list):
    df = pd.DataFrame(candlestick_list)
    ohlc = df[['date', 'open', 'high', 'low', 'close']]

    ax1 = plt.subplot2grid((6,1), (0,0), rowspan=5, colspan=1)
    ax2 = plt.subplot2grid((6,1), (5,0), rowspan=5, colspan=1, sharex=ax1)
    candlestick_ohlc(ax1, ohlc.values, width=0.5, colorup='g', colordown='r')
    ax2.bar(df['date'], df['volume'])
    plt.show()

Unfortunately the following approaches didn't work for me:

df['date'] = pd.to_datetime(df['date'], unit='s')

TypeError: unsupported operand type(s) for -: 'Timestamp' and 'float'

or this one:

import matplotlib.dates as mdates
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))

ValueError: year 4095909 is out of range

Does anybody have an idea?
Many thanks in advance!

PS: the following list can be used to test the code

candlestick_list = [{'date': 1496332800, 'high': 215.3209, 'low': 200.3, 'open': 211.18, 'close': 206.47999999, 'volume': 2432435.9201853, 'quoteVolume': 11813.26856836, 'weightedAverage': 205.90710404}, {'date': 1496340000, 'high': 212.0001, 'low': 205.75400533, 'open': 206.47999992, 'close': 207.85, 'volume': 1301024.6514137, 'quoteVolume': 6250.47612412, 'weightedAverage': 208.14808753}, {'date': 1496347200, 'high': 212.44999999, 'low': 206.9813717, 'open': 208.49981874, 'close': 209.99811003, 'volume': 1062083.1773221, 'quoteVolume': 5056.26107738, 'weightedAverage': 210.05307302}, {'date': 1496354400, 'high': 213.20999999, 'low': 209.61231001, 'open': 210, 'close': 211.44, 'volume': 705968.23009208, 'quoteVolume': 3335.35026592, 'weightedAverage': 211.66239639}, {'date': 1496361600, 'high': 219, 'low': 210.81410968, 'open': 211.43999994, 'close': 215.41715998, 'volume': 972040.25543603, 'quoteVolume': 4500.001815, 'weightedAverage': 216.00885852}]

Body:
Try converting the dates into Matplotlib format. Often, Matplotlib will recognize and auto-convert dates from DataFrames, but there are many odd cases. Generally when things don't work, do your own conversion manually.

import matplotlib.pyplot as plt
from matplotlib.finance import candlestick_ohlc
from matplotlib import style
import pandas as pd
import matplotlib.dates as mdates

def graph(candlestick_list):
    df = pd.DataFrame(candlestick_list)
    df['date'] = pd.to_datetime(df['date'], unit='s')
    df['mdate'] = [mdates.date2num(d) for d in df['date']]

    ohlc = df[['mdate', 'open', 'high', 'low', 'close']]

    ax1 = plt.subplot2grid((6,1), (0,0), rowspan=5, colspan=1)
    ax2 = plt.subplot2grid((6,1), (5,0), rowspan=5, colspan=1, sharex=ax1)
    candlestick_ohlc(ax1, ohlc.values, width=0.05, colorup='g', colordown='r')
    ax2.bar(df['mdate'], df['volume'])
    ax2.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
    plt.xticks(rotation=60)
    plt.show()

Documentation for date2num(). Note I added a separate mdate column. Useful for debugging, and if you need to also use regular Pandas dates for other purposes. Here in this limited, within-a-function context, probably overkill to keep several date representations around.
I also thinned the width of your OHLC bars, and rotated the date ticks so I could see them better. YMMV on such styling tweaks.

Finally, if the use of a list comprehension offends your sensibilties because "it's not vectorized," you can do the conversion to matplotlib style dates in one go with:

df['mdate'] = mdates.date2num(df.date.dt.to_pydatetime())


问:
Get coords of the intersection of the line in the plane
I have a canvas with this params:
width = 400, height = 400

and have a line passing through the point cursor[x1,y1] at an angle Q (in degree)

I need get all coords of the intersection of the line in the plane and write it to array. Now i use this equation: y - y1 = k * (x - x1)

to check all point I use this code:

var rad = Q * Math.PI/180;

```<code>for (ctrY = 0; ctrY < 400; ctrY += 1) {
    for (ctrX = 0; ctrX < 400; ctrX += 1) {

        if ( (ctrY - cursor.y) ===
              ~~(Math.tan(rad) * (ctrX - cursor.x)) ) {

            z.push([ctrX, ctrY]);
        }

    }
}
</code>```

For example when 0 < Q < 90 and cursor[x1,y1] = [200,200] z.length = 0 and it's not correct.

Where i'm wrong? Maybe there is a more convenient algorithm?

P.S. Sorry for my english

答:
Seems you need line rastering algorithm. Consider Bresenham algorithm.

You can also look at DDA algorithm

Body:
I have a canvas with this params:
width = 400, height = 400

and have a line passing through the point cursor[x1,y1] at an angle Q (in degree)

I need get all coords of the intersection of the line in the plane and write it to array. Now i use this equation: y - y1 = k * (x - x1)

to check all point I use this code:

var rad = Q * Math.PI/180;

for (ctrY = 0; ctrY < 400; ctrY += 1) {
    for (ctrX = 0; ctrX < 400; ctrX += 1) {

        if ( (ctrY - cursor.y) ===
              ~~(Math.tan(rad) * (ctrX - cursor.x)) ) {

            z.push([ctrX, ctrY]);
        }

    }
}

For example when 0 < Q < 90 and cursor[x1,y1] = [200,200] z.length = 0 and it's not correct.

Where i'm wrong? Maybe there is a more convenient algorithm?

P.S. Sorry for my english


问:
bootstrap column height different
What I want to achieve using the grid system of Bootstrap 3 is the following:
Image what I imagine.
However, what I get with the normal row and col is the following:
This is what I get.

Is there a ways how I can make the first element of the second row fit exactly the first element of the first row by keeping the different heights and preferably by keeping the order of the elements.

答:
Something like this?

https://codepen.io/anon/pen/RgBqNr

```<code> <div class="row">
      <div class="col-xs-6">
        <div style="background: red">
          Hello<br/><br/><br/>
        </div>
        <div style="background: blue">
          Hello<br/><br/><br/>
          Again<br/><br/><br/>
        </div>
      </div>
      <div class="col-xs-6">
        <div style="background: cyan">
          Hello<br/><br/><br/>
          Again<br/><br/><br/>
        </div>
        <div style="background: red">
          Hello<br/><br/><br/>
        </div>
        <div style="background: blue">
          Hello<br/><br/><br/>
          Again<br/><br/><br/>
        </div>
      </div>
    </div><!--/row-->
</code>```

Title: bootstrap column height different

Body:
Something like this?

https://codepen.io/anon/pen/RgBqNr

 <div class="row">
      <div class="col-xs-6">
        <div style="background: red">
          Hello<br/><br/><br/>
        </div>
        <div style="background: blue">
          Hello<br/><br/><br/>
          Again<br/><br/><br/>
        </div>
      </div>
      <div class="col-xs-6">
        <div style="background: cyan">
          Hello<br/><br/><br/>
          Again<br/><br/><br/>
        </div>
        <div style="background: red">
          Hello<br/><br/><br/>
        </div>
        <div style="background: blue">
          Hello<br/><br/><br/>
          Again<br/><br/><br/>
        </div>
      </div>
    </div><!--/row-->


问:
_kCFStreamErrorCodeKey=-2102 only with wifi of some ISPs
I use below code to send a file to the server:

```<code>NSString *urlString = [NSString stringWithFormat:@"%@%@",[LIUtility sharedUtility].uploadConnectionURL,BR_SERVER_UPLOAD_ADDRESS_FILE];

self.request =[[NSMutableURLRequest alloc] init];
[self.request setURL:[NSURL URLWithString:urlString]];
[self.request setHTTPMethod:@"POST"];

PKMultipartInputStream *body = [[PKMultipartInputStream alloc] init];

NSString *requestString =[self getRequestStringForRange:range andExtension:fileName];
NSData *requestData = [requestString dataUsingEncoding:NSUTF8StringEncoding];

NSString *jsonLengthString = [NSString stringWithFormat:@"%04lu",(unsigned long)requestData.length];
NSData *jsonLengthData = [jsonLengthString dataUsingEncoding:NSUTF8StringEncoding];

[body addPartWithName:@"jsonLength" data:jsonLengthData];
[body addPartWithName:@"json" data:requestData];
[body addPartWithName:@"separator" string:@"\r\n"];
[body addPartWithName:@"fileData" filename:fileName stream:dataStream streamLength:streamSize];

[self.request setHTTPBodyStream:body];
[self.request setTimeoutInterval:60];
NSString *contentType = LI_CONNECTION_CONTENTTYPE;
[self.request addValue:contentType forHTTPHeaderField: @"Content-Type"];

self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self];
_responseData = [NSMutableData data];
[self.connection start];
</code>```

The file is uploading with 3G/4G.The code also works when device is connected to wifi of some ADSL ISPs but in some other ISPs the code do not work and I get below error:

Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSErrorFailingURLStringKey=http://example.net, _kCFStreamErrorCodeKey=-2102, NSErrorFailingURLKey=http:/example.net:80/au, NSLocalizedDescription=The request timed out., _kCFStreamErrorDomainKey=4, NSUnderlyingError=0x16a40410 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "The request timed out." UserInfo={_kCFStreamErrorCodeKey=-2102, NSErrorFailingURLStringKey=http://example.net, NSErrorFailingURLKey=http://example.net, NSLocalizedDescription=The request timed out., _kCFStreamErrorDomainKey=4}}}

Does anyone have any idea about what is the problem?

答: If you are running an enterprise version of application, check with your server admin to see if your Cert is up to date and compatible with your firewall server. Mine isn't.</p>

Body:
I use below code to send a file to the server:

NSString *urlString = [NSString stringWithFormat:@"%@%@",[LIUtility sharedUtility].uploadConnectionURL,BR_SERVER_UPLOAD_ADDRESS_FILE];

self.request =[[NSMutableURLRequest alloc] init];
[self.request setURL:[NSURL URLWithString:urlString]];
[self.request setHTTPMethod:@"POST"];

PKMultipartInputStream *body = [[PKMultipartInputStream alloc] init];

NSString *requestString =[self getRequestStringForRange:range andExtension:fileName];
NSData *requestData = [requestString dataUsingEncoding:NSUTF8StringEncoding];

NSString *jsonLengthString = [NSString stringWithFormat:@"%04lu",(unsigned long)requestData.length];
NSData *jsonLengthData = [jsonLengthString dataUsingEncoding:NSUTF8StringEncoding];

[body addPartWithName:@"jsonLength" data:jsonLengthData];
[body addPartWithName:@"json" data:requestData];
[body addPartWithName:@"separator" string:@"\r\n"];
[body addPartWithName:@"fileData" filename:fileName stream:dataStream streamLength:streamSize];

[self.request setHTTPBodyStream:body];
[self.request setTimeoutInterval:60];
NSString *contentType = LI_CONNECTION_CONTENTTYPE;
[self.request addValue:contentType forHTTPHeaderField: @"Content-Type"];

self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self];
_responseData = [NSMutableData data];
[self.connection start];

The file is uploading with 3G/4G.The code also works when device is connected to wifi of some ADSL ISPs but in some other ISPs the code do not work and I get below error:

Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSErrorFailingURLStringKey=http://example.net, _kCFStreamErrorCodeKey=-2102, NSErrorFailingURLKey=http:/example.net:80/au, NSLocalizedDescription=The request timed out., _kCFStreamErrorDomainKey=4, NSUnderlyingError=0x16a40410 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "The request timed out." UserInfo={_kCFStreamErrorCodeKey=-2102, NSErrorFailingURLStringKey=http://example.net, NSErrorFailingURLKey=http://example.net, NSLocalizedDescription=The request timed out., _kCFStreamErrorDomainKey=4}}}

Does anyone have any idea about what is the problem?


问:
React-native - How to begin StackNavigator on certain level
I have only one screen and call itself.

```<code>module.exports = StackNavigator({
    Parent: { screen: PickCategory },
})
</code>```

Currently, i navigate to screen level i want on componentWillMount.
But i can see the transition, it's ugly and annoying.

I wanna load StackNavigator with specified level without animation.
Is it posible?

答:
Put your screen level want on the first param in StackNavigator.

```<code>const TideTable = StackNavigator({
Home: { screen: YourScreenLevelYouWantToDisplayFirst},
Second: { screen: NextScreen},
Third: { screen: TheNextOne},
</code>```

});

Body:
I have only one screen and call itself.

module.exports = StackNavigator({
    Parent: { screen: PickCategory },
})

Currently, i navigate to screen level i want on componentWillMount.
But i can see the transition, it's ugly and annoying.

I wanna load StackNavigator with specified level without animation.
Is it posible?

Body:
Put your screen level want on the first param in StackNavigator.

const TideTable = StackNavigator({
Home: { screen: YourScreenLevelYouWantToDisplayFirst},
Second: { screen: NextScreen},
Third: { screen: TheNextOne},

});


问:
How to cancel incomplete task on ExecutorService
I have submitted two tasks, task1 & task2 to the ExecutorService. Task2 needs 5 seconds to complete, and task1 need 10 seconds.

How can I stop the task(s) submitted (ie: task1) when task2 completes and continues the rest of logic?

Here's my code so far:

```<code>public class mt_poc {
    public static void action_1 () throws InterruptedException {
        System.out.println("action_1 invoke " );
        Thread.sleep(10000);
        action_2 ();
        System.out.println("action_1 done" );
    }

    public static void action_2() throws InterruptedException {
        System.out.println("action_2 invoke " );
        Thread.sleep(5000);
        System.out.println("action_2 done " );
    }

    public static void main(String[] args) {
        System.out.println("TEST");
        Runnable task1 = new Runnable() {
            public void run() {
                try {
                    action_1 ();
                }
                catch(InterruptedException e) {
                    System.out.println("action_1 invoke interrupted");
                }
                System.out.println("action_1 invoke run is over" );
                }
            };

        Runnable task2 = new Runnable() {
            public void run() {
                try {
                    action_2 ();
                }
                catch(InterruptedException e) {
                   System.out.println("action_2 invoke interrupted");
                }
                System.out.println("action_2 invoke run is over" );
                }
            };

        ExecutorService executor = Executors.newFixedThreadPool(2);

        try {
            executor.submit(task1);
            executor.submit(task2);
            // cancel uncomplete task
            executor.shutdown();
            executor.awaitTermination(5, TimeUnit.SECONDS);
            // continues the rest of logic
        } catch (InterruptedException e) {
                e.printStackTrace();
        }

        System.out.println("Shutdown executor");
    }
}
</code>```

答:
you can use shutdownNow() method

Attempts to stop all actively executing tasks, halts the processing of
  waiting tasks, and returns a list of the tasks that were awaiting
  execution.

for full documentation:

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html

shutdown() method will wait for all the threads to finish before closing the executor

Body:
I have submitted two tasks, task1 & task2 to the ExecutorService. Task2 needs 5 seconds to complete, and task1 need 10 seconds.

How can I stop the task(s) submitted (ie: task1) when task2 completes and continues the rest of logic?

Here's my code so far:

public class mt_poc {
    public static void action_1 () throws InterruptedException {
        System.out.println("action_1 invoke " );
        Thread.sleep(10000);
        action_2 ();
        System.out.println("action_1 done" );
    }

    public static void action_2() throws InterruptedException {
        System.out.println("action_2 invoke " );
        Thread.sleep(5000);
        System.out.println("action_2 done " );
    }

    public static void main(String[] args) {
        System.out.println("TEST");
        Runnable task1 = new Runnable() {
            public void run() {
                try {
                    action_1 ();
                }
                catch(InterruptedException e) {
                    System.out.println("action_1 invoke interrupted");
                }
                System.out.println("action_1 invoke run is over" );
                }
            };

        Runnable task2 = new Runnable() {
            public void run() {
                try {
                    action_2 ();
                }
                catch(InterruptedException e) {
                   System.out.println("action_2 invoke interrupted");
                }
                System.out.println("action_2 invoke run is over" );
                }
            };

        ExecutorService executor = Executors.newFixedThreadPool(2);

        try {
            executor.submit(task1);
            executor.submit(task2);
            // cancel uncomplete task
            executor.shutdown();
            executor.awaitTermination(5, TimeUnit.SECONDS);
            // continues the rest of logic
        } catch (InterruptedException e) {
                e.printStackTrace();
        }

        System.out.println("Shutdown executor");
    }
}


问:
Handle Exception in ResponsesEntity java
I wonder how to handle exception in ResponsesEntity.
When it receive wrong url, it supposes to go to the catch block and display the log. But I keep getting error message in console. The try-catch not working as it not display log message.

```<code>@GetMapping("abc/{Id}")
    public ResponseEntity info(@PathVariable("Id") String id) {
        HttpEntity httpEntity = new HttpEntity(buildHttpHeaders());
        String theUrl = url + "/xxx/transactions/" +id;
        ResponseEntity<TDto> responseEntity = restTemplate.exchange(theUrl, HttpMethod.GET, httpEntity, TDto.class);
        TDto tdto = responseEntity.getBody();
        Tran tran = new Tran();
        try {
              tran.setDate(new Date());
              tran.saveAndFlush(tran); // save to database
        }catch(Exception e)
        {
            log.info("Log: "+e);
        }
        return responseEntity;
    }
</code>```

Error

```<code>org.springframework.web.client.HttpClientErrorException: 404 Not Found
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:63)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:531)
    at com.rh.tranglo.controller.ApiController.retrieveTransactionInfo(ApiController.java:41)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
</code>```

Is there a way to handle exception by displaying the log in catch block?

答:
If your catch block is not catching the exception then it means, you are wrapping the wrong code inside the try block. To know which code is actually throwing an exception I suggest you place break points in your code and run it through a debugger. I'm not familiar with what you want to achieve but looking at it I'm guessing the statement you are supposed to wrap inside the try block is this

```<code>ResponseEntity<TDto> responseEntity = restTemplate.exchange(theUrl, HttpMethod.GET, httpEntity, TDto.class);
</code>```

Also if you look at the log again more carefully you'll see something that will help you. The exception is originating from your code but the top exceptions are just spring exceptions. I think if you follow the log message and go down you'll see the line in your code that is throwing the exception.

Update

I think I understand your problem now. But your question is not properly asked. You have a controller that is mapped to a specific URL say /hello but when testing you pass /hi and you expected your controller method to catch the not found exception. Sorry spring does not work that way.

When a controller is mapped to a URL, the controller code will only be executed if the URL used in the call matches the URL the controller is mapped to. So in your case when you make a GET with another URL other than which your controller is mapped to, the code in the controller will never be executed. That's why you don't enter the catch block you put. Spring code is responsible for throwing the 404 exception not your code.

Note I'll be able to help you more when I properly understand your problem. It will do a lot of good if you could share the full stacktrace.

Body:
I wonder how to handle exception in ResponsesEntity.
When it receive wrong url, it supposes to go to the catch block and display the log. But I keep getting error message in console. The try-catch not working as it not display log message.

@GetMapping("abc/{Id}")
    public ResponseEntity info(@PathVariable("Id") String id) {
        HttpEntity httpEntity = new HttpEntity(buildHttpHeaders());
        String theUrl = url + "/xxx/transactions/" +id;
        ResponseEntity<TDto> responseEntity = restTemplate.exchange(theUrl, HttpMethod.GET, httpEntity, TDto.class);
        TDto tdto = responseEntity.getBody();
        Tran tran = new Tran();
        try {
              tran.setDate(new Date());
              tran.saveAndFlush(tran); // save to database
        }catch(Exception e)
        {
            log.info("Log: "+e);
        }
        return responseEntity;
    }

Error

org.springframework.web.client.HttpClientErrorException: 404 Not Found
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:63)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:531)
    at com.rh.tranglo.controller.ApiController.retrieveTransactionInfo(ApiController.java:41)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)

Is there a way to handle exception by displaying the log in catch block?

Body:
If your catch block is not catching the exception then it means, you are wrapping the wrong code inside the try block. To know which code is actually throwing an exception I suggest you place break points in your code and run it through a debugger. I'm not familiar with what you want to achieve but looking at it I'm guessing the statement you are supposed to wrap inside the try block is this

ResponseEntity<TDto> responseEntity = restTemplate.exchange(theUrl, HttpMethod.GET, httpEntity, TDto.class);

Also if you look at the log again more carefully you'll see something that will help you. The exception is originating from your code but the top exceptions are just spring exceptions. I think if you follow the log message and go down you'll see the line in your code that is throwing the exception.

Update

I think I understand your problem now. But your question is not properly asked. You have a controller that is mapped to a specific URL say /hello but when testing you pass /hi and you expected your controller method to catch the not found exception. Sorry spring does not work that way.

When a controller is mapped to a URL, the controller code will only be executed if the URL used in the call matches the URL the controller is mapped to. So in your case when you make a GET with another URL other than which your controller is mapped to, the code in the controller will never be executed. That's why you don't enter the catch block you put. Spring code is responsible for throwing the 404 exception not your code.

Note I'll be able to help you more when I properly understand your problem. It will do a lot of good if you could share the full stacktrace.


问:
UIImageView resizing to eliminate blank space IOS
My UIImageView is in aspect fit mode which leaves blank space beneath the actual image.

The blue space is what I want to eliminate so the imageView wraps the image (if only I had wrap content). Seemed like an easy task but I soon realized that the image is in aspect fit so the image view changes the width and height of the image but then I would have to make a calculation on the image view based on that altered image which would make a never ending loop of shrinking the image.

I just want to remove the blank space to make it look more concise. Full project at GitHub: https://github.com/sak6lab/Closet-Space

答:
I filed a radar recently for this as I believe it is broken behaviour.

Currently, the best way I have found to fix this is to add an aspect ratio constraint to the image view based on the aspect ratio of the image. (You'll have to update the constraint when the image changes though).

Something like...

```<code>imageView.widthAnchor.constraint(equalTo: imageView.heightAnchor, multiplier: image.size.width / image.size.height).isActive = true
</code>```

You could wrap this into a UIImageView subclass maybe. Override the didSet of the image property or even just add a new function.

Be careful though as you need to make sure you only create one constraint and on subsequent passes you update the already existing constraint.

Body:
I filed a radar recently for this as I believe it is broken behaviour.

Currently, the best way I have found to fix this is to add an aspect ratio constraint to the image view based on the aspect ratio of the image. (You'll have to update the constraint when the image changes though).

Something like...

imageView.widthAnchor.constraint(equalTo: imageView.heightAnchor, multiplier: image.size.width / image.size.height).isActive = true

You could wrap this into a UIImageView subclass maybe. Override the didSet of the image property or even just add a new function.

Be careful though as you need to make sure you only create one constraint and on subsequent passes you update the already existing constraint.


问:
How to Reverse Chart.js Label Order?
I'm using  a lot of pie  and doughnut charts  with two data values  in a
project. It really annoys me that since the chart slices starts from the
top going clockwise, the labels end up looking reversed: on the opposite
side of the data it represents.

Is there an easy way to reverse the label order, or reverse the chart to
run counter-clockwise?

```<code>new Chart(context, {
  type: 'doughnut',
  data: {
    labels: [ 'Blue', 'Red' ],
    datasets: [
      {
        data: [7, 3],
        backgroundColor: [
          'rgba(54, 162, 235, 0.7)',
          'rgba(208, 54, 100, 0.7)',
        ],
      },
    ]
  }
});
</code>```

答:
I think what you are looking for is the reverse option under legend which will show datasets in reverse order

http://www.chartjs.org/docs/latest/configuration/legend.html?h=reverse

Title: How to Reverse Chart.js Label Order?

Body:
I'm using  a lot of pie  and doughnut charts  with two data values  in a
project. It really annoys me that since the chart slices starts from the
top going clockwise, the labels end up looking reversed: on the opposite
side of the data it represents.

Is there an easy way to reverse the label order, or reverse the chart to
run counter-clockwise?

new Chart(context, {
  type: 'doughnut',
  data: {
    labels: [ 'Blue', 'Red' ],
    datasets: [
      {
        data: [7, 3],
        backgroundColor: [
          'rgba(54, 162, 235, 0.7)',
          'rgba(208, 54, 100, 0.7)',
        ],
      },
    ]
  }
});


问:
Accessing object in iframe using VBA
To the point:

I have successfully used VBA to do the following:

Login to a website using getElementsByName

Select parameters for the report that will be generated (using getelementsby...)

generating the report after selecting parameters which renders the resulting dataset into an iframe on the same page

Important to note - The website is client-side

The above was the simple part, the difficult part is as below:

clicking on a gif image within the iframe that exports the dataset to a csv

I have tried the following:

```<code>Dim idoc As HTMLDocument
Dim iframe As HTMLFrameElement
Dim iframe2 As HTMLDocument

Set idoc = objIE.document
Set iframe = idoc.all("iframename")
Set iframe2 = iframe.contentDocument

    Do Until InStr(1, objIE.document.all("iframename").contentDocument.innerHTML, "img.gif", vbTextCompare) = 0
        DoEvents
    Loop
</code>```

To give some context to the logic above -

I accessed the main frame

i accessed the iframe by its name element

i accessed the content within the iframe

I attempted to find the gif image that needs to be clicked to export to csv

It is at this line that it trips up saying "Object doesn't support this property or method"

Also tried accessing the iframe gif by the a element and href attribute but this totally failed. I also tried grabbing the image from its source URL but all this does it take me to the page the image is from.

note: the iframe does not have an ID and strangely the gif image does not have an "onclick" element/event

Final consideration - attempted scraping the iframe using R

accessing the HTML node of the iframe was simple, however trying to access the attributes of the iframe and subsequently the nodes of the table proved unsuccessful. All it returned was "Character(0)"

```<code>library(rvest)
library(magrittr)

Blah <-read_html("web address redacted") %>%
  html_nodes("#iframe")%>%
  html_nodes("#img")%>%
  html_attr("#src")%>%
  #read_html()%>%
  head()
Blah
</code>```

As soon as a i include read_html the following error returns on the script:

Error in if (grepl("<|>", x)) { : argument is of length zero

I suspect this is referring to the Character(0)

Appreciate any guidance here!

Many Thanks,

HTML

```<code><div align="center">
    <table id="table1" style="border-collapse: collapse" width="700" cellspacing="0" cellpadding="0" border="0">
        <tbody>
            <tr>
                <td colspan="6">  </td>
            </tr>
            <tr>
                <td colspan="6">
                    <a href="href redacted">
                        <img src="img.gif" width="38" height="38" border="0" align="right">
                    </a>
                    <strong>x - </strong>
                </td>
            </tr>
        </tbody>
    </table>
</div>
</code>```

答:
It is sometimes tricky with iframes. Based on html you provided I have created this example. Which works locally, but would it work for you as well?

To get to the IFrame the frames collection can be used. Hope you know the name of the IFrame?

```<code>Dim iframeDoc As MSHTML.HTMLDocument
Set iframeDoc = doc.frames("iframename").document
</code>```

Then to go the the image we can use querySelector method e.g. like this:

```<code>Dim img As MSHTML.HTMLImg
Set img = iframeDoc.querySelector("div table[id='table1'] tbody tr td a[href^='https://stackoverflow.com'] img")
</code>```

The selector a[href^='https://stackoverflow.com'] selects anchor which has an href attribute which starts with given text. The ^ denotes the beginning.

Then when we have the image just a simple call to click on its parent which is the desired anchor. HTH

Complete example:

```<code>Option Explicit

' Add reference to Microsoft Internet Controls (SHDocVw)
' Add reference to Microsoft HTML Object Library

Sub Demo()

    Dim ie As SHDocVw.InternetExplorer
    Dim doc As MSHTML.HTMLDocument
    Dim url As String

    url = "file:///C:/Users/dusek/Documents/My Web Sites/mainpage.html"
    Set ie = New SHDocVw.InternetExplorer
    ie.Visible = True
    ie.navigate url

    While ie.Busy Or ie.readyState <> READYSTATE_COMPLETE
        DoEvents
    Wend

    Set doc = ie.document

    Dim iframeDoc As MSHTML.HTMLDocument
    Set iframeDoc = doc.frames("iframename").document
    If iframeDoc Is Nothing Then
        MsgBox "IFrame with name 'iframename' was not found."
        ie.Quit
        Exit Sub
    End If

    Dim img As MSHTML.HTMLImg
    Set img = iframeDoc.querySelector("div table[id='table1'] tbody tr td a[href^='https://stackoverflow.com'] img")
    If img Is Nothing Then
        MsgBox "Image element within iframe was not found."
        ie.Quit
        Exit Sub
    Else
        img.parentElement.Click
    End If

    ie.Quit
End Sub
</code>```

Main page HTML used

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<!-- saved from url=(0016)http://localhost -->
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>x -</title>
</head>

<body>
<iframe name="iframename" src="iframe1.html">
</iframe>
</body>

</html>
</code>```

IFrame HTML used (saved as file iframe1.html

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<!-- saved from url=(0016)http://localhost -->
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 2</title>
</head>

<body>
<div align="center">
    <table id="table1" style="border-collapse: collapse" width="700" cellspacing="0" cellpadding="0" border="0">
        <tbody>
            <tr>
                <td colspan="6">  </td>
            </tr>
            <tr>
                <td colspan="6">
                    <a href="https://stackoverflow.com/questions/44902558/accessing-object-in-iframe-using-vba">
                        <img src="img.gif" width="38" height="38" border="0" align="right">
                    </a>
                    <strong>x - </strong>
                </td>
            </tr>
        </tbody>
    </table>
</div>

</body>

</html>
</code>```

BTW, The frame may be referenced by it's index also doc.frames(0).document. Thanks to Paulo Bueno.

Title: Accessing object in iframe using VBA

Body:
To the point:

I have successfully used VBA to do the following:

Login to a website using getElementsByName

Select parameters for the report that will be generated (using getelementsby...)

generating the report after selecting parameters which renders the resulting dataset into an iframe on the same page

Important to note - The website is client-side

The above was the simple part, the difficult part is as below:

clicking on a gif image within the iframe that exports the dataset to a csv

I have tried the following:

Dim idoc As HTMLDocument
Dim iframe As HTMLFrameElement
Dim iframe2 As HTMLDocument

Set idoc = objIE.document
Set iframe = idoc.all("iframename")
Set iframe2 = iframe.contentDocument

    Do Until InStr(1, objIE.document.all("iframename").contentDocument.innerHTML, "img.gif", vbTextCompare) = 0
        DoEvents
    Loop

To give some context to the logic above -

I accessed the main frame

i accessed the iframe by its name element

i accessed the content within the iframe

I attempted to find the gif image that needs to be clicked to export to csv

It is at this line that it trips up saying "Object doesn't support this property or method"

Also tried accessing the iframe gif by the a element and href attribute but this totally failed. I also tried grabbing the image from its source URL but all this does it take me to the page the image is from.

note: the iframe does not have an ID and strangely the gif image does not have an "onclick" element/event

Final consideration - attempted scraping the iframe using R

accessing the HTML node of the iframe was simple, however trying to access the attributes of the iframe and subsequently the nodes of the table proved unsuccessful. All it returned was "Character(0)"

library(rvest)
library(magrittr)

Blah <-read_html("web address redacted") %>%
  html_nodes("#iframe")%>%
  html_nodes("#img")%>%
  html_attr("#src")%>%
  #read_html()%>%
  head()
Blah

As soon as a i include read_html the following error returns on the script:

Error in if (grepl("<|>", x)) { : argument is of length zero

I suspect this is referring to the Character(0)

Appreciate any guidance here!

Many Thanks,

HTML

                    x -

Body:
It is sometimes tricky with iframes. Based on html you provided I have created this example. Which works locally, but would it work for you as well?

To get to the IFrame the frames collection can be used. Hope you know the name of the IFrame?

Dim iframeDoc As MSHTML.HTMLDocument
Set iframeDoc = doc.frames("iframename").document

Then to go the the image we can use querySelector method e.g. like this:

Dim img As MSHTML.HTMLImg
Set img = iframeDoc.querySelector("div table[id='table1'] tbody tr td a[href^='https://stackoverflow.com'] img")

The selector a[href^='https://stackoverflow.com'] selects anchor which has an href attribute which starts with given text. The ^ denotes the beginning.

Then when we have the image just a simple call to click on its parent which is the desired anchor. HTH

Complete example:

Option Explicit

' Add reference to Microsoft Internet Controls (SHDocVw)
' Add reference to Microsoft HTML Object Library

Sub Demo()

    Dim ie As SHDocVw.InternetExplorer
    Dim doc As MSHTML.HTMLDocument
    Dim url As String

    url = "file:///C:/Users/dusek/Documents/My Web Sites/mainpage.html"
    Set ie = New SHDocVw.InternetExplorer
    ie.Visible = True
    ie.navigate url

    While ie.Busy Or ie.readyState <> READYSTATE_COMPLETE
        DoEvents
    Wend

    Set doc = ie.document

    Dim iframeDoc As MSHTML.HTMLDocument
    Set iframeDoc = doc.frames("iframename").document
    If iframeDoc Is Nothing Then
        MsgBox "IFrame with name 'iframename' was not found."
        ie.Quit
        Exit Sub
    End If

    Dim img As MSHTML.HTMLImg
    Set img = iframeDoc.querySelector("div table[id='table1'] tbody tr td a[href^='https://stackoverflow.com'] img")
    If img Is Nothing Then
        MsgBox "Image element within iframe was not found."
        ie.Quit
        Exit Sub
    Else
        img.parentElement.Click
    End If

    ie.Quit
End Sub

Main page HTML used

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<!-- saved from url=(0016)http://localhost -->
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>x -</title>
</head>

<body>
<iframe name="iframename" src="iframe1.html">
</iframe>
</body>

</html>

IFrame HTML used (saved as file iframe1.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<!-- saved from url=(0016)http://localhost -->
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 2</title>
</head>

<body>
<div align="center">
    <table id="table1" style="border-collapse: collapse" width="700" cellspacing="0" cellpadding="0" border="0">
        <tbody>
            <tr>
                <td colspan="6"> &nbsp;</td>
            </tr>
            <tr>
                <td colspan="6">
                    <a href="https://stackoverflow.com/questions/44902558/accessing-object-in-iframe-using-vba">
                        <img src="img.gif" width="38" height="38" border="0" align="right">
                    </a>
                    <strong>x - </strong>
                </td>
            </tr>
        </tbody>
    </table>
</div>

</body>

</html>

BTW, The frame may be referenced by it's index also doc.frames(0).document. Thanks to Paulo Bueno.


问:
Copy Row A1 from Sheet 1 into Row A1 Sheet 2
I basically just need to know how to copy a header from sheet one that goes from A1-O1 into sheet two, three, four, five and so on...they all have the same header. Sheet one is on the right and sheet two is left and increases to the left. I tried this which I found on some website but it says object required. The error is Runtime Error 424</p>

```<code>mainworkBook.Sheets(“Sheet1”).Rows(1).EntireRow.Copy
mainworkBook.Sheets(“Sheet2”).Range(“A1”).Select
mainworkBook.Sheets(“Sheet2”).Paste
</code>```

答:
This is an excellent place to use a loop.  For each sheet in the workbook, paste the same header.

```<code>Sub forEachWs()
    Dim ws As Worksheet
    For Each ws In ActiveWorkbook.Worksheets
        Call pasteContents(ws)
    Next
End Sub

Sub pasteContents(ws as Worksheet)
     ** Your code goes here
End Sub
</code>```

EDIT: The ** section could be as such:

```<code>Sub pasteContents(ws as Worksheet)
     ActiveWorkbook.Sheets(“Sheet1”).Rows(1).EntireRow.Copy
     ActiveWorkbook.Sheets(ws).Range(“A1”).Select
     ActiveWorkbook.Sheets(ws).Paste
End Sub
</code>```

Or it could also be...

```<code>Sub pasteContents(ws as Worksheet)
     ActiveWorkbook.Sheets("Sheet1").Rows(1).Copy Destination:=Worksheets(ws).Range("A1")
End Sub
</code>```

Body:
I basically just need to know how to copy a header from sheet one that goes from A1-O1 into sheet two, three, four, five and so on...they all have the same header. Sheet one is on the right and sheet two is left and increases to the left. I tried this which I found on some website but it says object required. The error is Runtime Error 424

mainworkBook.Sheets(“Sheet1”).Rows(1).EntireRow.Copy
mainworkBook.Sheets(“Sheet2”).Range(“A1”).Select
mainworkBook.Sheets(“Sheet2”).Paste

Body:
This is an excellent place to use a loop.  For each sheet in the workbook, paste the same header.

Sub forEachWs()
    Dim ws As Worksheet
    For Each ws In ActiveWorkbook.Worksheets
        Call pasteContents(ws)
    Next
End Sub

Sub pasteContents(ws as Worksheet)
     ** Your code goes here
End Sub

EDIT: The ** section could be as such:

Sub pasteContents(ws as Worksheet)
     ActiveWorkbook.Sheets(“Sheet1”).Rows(1).EntireRow.Copy
     ActiveWorkbook.Sheets(ws).Range(“A1”).Select
     ActiveWorkbook.Sheets(ws).Paste
End Sub

Or it could also be...

Sub pasteContents(ws as Worksheet)
     ActiveWorkbook.Sheets("Sheet1").Rows(1).Copy Destination:=Worksheets(ws).Range("A1")
End Sub


问:
Compiling and executing c program in bash script not working because the compiled program is not found
I only recently started programming. I have a shell script which contains a c-program. At the end of the script, the c-program is ran using the commands

```<code>gcc stadist.c -lm
a.out < XXXXX | sort -n -k3 > YYYYY
rm a.out
rm stadist.c
rm XXXXX
</code>```

Running this script gives a.out: not found. The file YYYYY is created but it is empty. How can i solve this problem. I am on Linux ubuntu 16.04 LTS.

答:
The shell cannot find a.out because it isn't looking in the current directory.  That is best practice.  (ie, do not add . to PATH).  Just do:

```<code>gcc stadist.c -lm &&
./a.out < XXXXX | sort -n -k3 > YYYYY
rm a.out
rm stadist.c
rm XXXXX
</code>```

Note that I added && after the invocation of gcc so that the script does not attempt to run a.out if the compilation fails.  You'll probably want to add more robust error checking.

Body:
I only recently started programming. I have a shell script which contains a c-program. At the end of the script, the c-program is ran using the commands

gcc stadist.c -lm
a.out < XXXXX | sort -n -k3 > YYYYY
rm a.out
rm stadist.c
rm XXXXX

Running this script gives a.out: not found. The file YYYYY is created but it is empty. How can i solve this problem. I am on Linux ubuntu 16.04 LTS.

Body:
The shell cannot find a.out because it isn't looking in the current directory.  That is best practice.  (ie, do not add . to PATH).  Just do:

gcc stadist.c -lm &&
./a.out < XXXXX | sort -n -k3 > YYYYY
rm a.out
rm stadist.c
rm XXXXX

Note that I added && after the invocation of gcc so that the script does not attempt to run a.out if the compilation fails.  You'll probably want to add more robust error checking.


问:
GZip Compression For JQuery Without Server Access
all. I am required to build a website with each page under 130kb. I know that JQuery 1.4.4 is ~28kb when it's g-zipped, but it's 77kb minified, which is just too much for this particular assignment. I have already built the entire site using JQuery in one implementation or another on each page, so scrapping it would mean days of wasted time.

With that in mind,

1) Can I add content headers to a javascript file to add "Content-Encoding: gzip" without modifying config files on the server end? I'm uploading them to the university server, but I don't have access to the configuration. From the response header, the server is: Apache/1.3.26 (UnitedLinux) mod_ssl/2.8.10 OpenSSL/0.9.6g PHP/4.2.2 mod_perl/1.27

2) From the phpinfo file, I know that ZLIB compression is enabled, but "zlib.output_compression" is not.

3) I realize this can be done using .htaccess. However, I'd like to do it any other way, if possible, since I don't want the school thinking I'm trying to modify their server configuration.

4) Will XHR's setrequestheader method work here, or is that only good for asynchronous files?

I know this is short notice and all, but my Final presentation is tomorrow, and I'll lose a ton of points if my site is over the size limit. Any help would be much appreciated!

答: Use http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js, which is GZIPed.</p>