问:
Web-scraping in R
I am practicing my web scraping coding in R and I cannot pass one phase no matter what website I try.

For example,

https://www.thecompleteuniversityguide.co.uk/league-tables/rankings?s=Music

My goal is to extract all 77 schools' name (Oxford to London Metropolitan)

So I tried...

```<code>library(rvest)
url_college <- "https://www.thecompleteuniversityguide.co.uk/league-tables/rankings?s=Music"
college <- read_html(url_college)
info <- html_nodes(college, css = '.league-table-institution-name')
info %>% html_nodes('.league-table-institution-name') %>% html_text()
</code>```

From F12, I could find out that all schools' name is under class '.league-table-institution-name'... and that's why I wrote that in html_nodes...

What have I done wrong?

答:
You appear to be running html_nodes() twice: first on college, an xml_document (which is correct) and then on info, a character vector, which is not correct.

Try this instead:

```<code>url_college %>%
  read_html() %>%
  html_nodes('.league-table-institution-name') %>%
  html_text()
</code>```

and then you'll need an additional step to clean up the school names; this one was suggested:

```<code>%>%
  str_replace_all("(^[^a-zA-Z]+)|([^a-zA-Z]+$)", "")
</code>```

Title: Web-scraping in R

Body:
I am practicing my web scraping coding in R and I cannot pass one phase no matter what website I try.

For example,

https://www.thecompleteuniversityguide.co.uk/league-tables/rankings?s=Music

My goal is to extract all 77 schools' name (Oxford to London Metropolitan)

So I tried...

library(rvest)
url_college <- "https://www.thecompleteuniversityguide.co.uk/league-tables/rankings?s=Music"
college <- read_html(url_college)
info <- html_nodes(college, css = '.league-table-institution-name')
info %>% html_nodes('.league-table-institution-name') %>% html_text()

From F12, I could find out that all schools' name is under class '.league-table-institution-name'... and that's why I wrote that in html_nodes...

What have I done wrong?

Body:
You appear to be running html_nodes() twice: first on college, an xml_document (which is correct) and then on info, a character vector, which is not correct.

Try this instead:

url_college %>%
  read_html() %>%
  html_nodes('.league-table-institution-name') %>%
  html_text()

and then you'll need an additional step to clean up the school names; this one was suggested:

%>%
  str_replace_all("(^[^a-zA-Z]+)|([^a-zA-Z]+$)", "")


来源: stackexchange

问:
C - Why do I keep printing out the Memory Address instead of the value in the array
I am having trouble printing out the values stored in the array. It seems to be printing out the memory address instead. Here is my code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void getMatrix(int x, int y);
void printMatrix(int arr[], int x, int y);
int product(int arr1[], int arr2[]);

int main(void){

 //Variables that will store matrix size
 int m, n, o, p;

 //Prompt user for size of Matrix A
 printf("Enter the rows and columns of Matrix A with space in between: ");

 //Read input
 scanf("%d %d", &m, &n);

 //Prompt user for the size of Matrix B
 printf("Enter the rows and columns of Matrix B with space in between: ");

 //Read input
 scanf("%d %d", &o, &p);

 //Seed RND Generator
 srand(time(NULL));

 //Check input
 if(n != o){
  while(n != o){
   printf("Matrix Sizes are not valid. Please enter valid sizes for the Matrices: ");
   scanf("%d %d %d %d", &m, &n, &o, &p);
  }
 }

 //Function Calls
 printf("Matrix 1:\n");
 getMatrix(m, n);
 printf("\nMatrix 2:\n");
 getMatrix(o, p);
}

void getMatrix(int x, int y){

 //Counter
 int c;

 //Size Declaration
 int size = x * y;

 //Array Declaration
 int arr[size];

 for(c = 0; c < size; c++){
  arr[c] = rand()%10;
 }

 printMatrix(arr[size], x, y);
}

void printMatrix(int arr[], int x, int y){

 //Counters
 int i, j;

 for(i = 0; i < y; i++){
  printf("\n");
  for(j = 0; j < x; j++){
   printf("%d ", arr[j]);
  }
 }
}
</code>```

So basically this code is supposed to take in input and create a variable length array and its supposed to store random numbers in a 1 dimensional array and then they have to be printed out in the form of a 2d array or a matrix. I feel there might be something wrong with the parameters of the printMatrix function or when passing the array obtained in the getMatrix function. Any help would be appreciated, thank you.

EDIT: Thank you all for the help. I didn't even think about using this as a solution. But it works now and prints out the numbers that it is supposed to. Thanks again

答:
What you are doing in the following line:

```<code>printMatrix(arr[size], x, y);
</code>```

Is invoking undefined behavior. Since you have declared your array to be arr[size], the counter of your array must range from 0 to size - 1.

When you are trying to pass arr[size], rather than passing the whole array (which, judging form the program, is what you want it to do), you pass arr at element size, which is one index out of bounds.

Going into a bit more technical explaination of why this happens, the memory space that is right after the block allocated for arr must be empty, so you don't get segmentation fault, and instead, you get the address of that out-of-bound element. However, if it was filled up, then that would have caused a segmentation fault, and would have resulted in a runtime error.

To pass arr, you need to remove the index specifier:

```<code>printMatrix(arr, x, y);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am having trouble printing out the values stored in the array. It seems to be printing out the memory address instead. Here is my code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void getMatrix(int x, int y);
void printMatrix(int arr[], int x, int y);
int product(int arr1[], int arr2[]);

int main(void){

 //Variables that will store matrix size
 int m, n, o, p;

 //Prompt user for size of Matrix A
 printf("Enter the rows and columns of Matrix A with space in between: ");

 //Read input
 scanf("%d %d", &m, &n);

 //Prompt user for the size of Matrix B
 printf("Enter the rows and columns of Matrix B with space in between: ");

 //Read input
 scanf("%d %d", &o, &p);

 //Seed RND Generator
 srand(time(NULL));

 //Check input
 if(n != o){
  while(n != o){
   printf("Matrix Sizes are not valid. Please enter valid sizes for the Matrices: ");
   scanf("%d %d %d %d", &m, &n, &o, &p);
  }
 }

 //Function Calls
 printf("Matrix 1:\n");
 getMatrix(m, n);
 printf("\nMatrix 2:\n");
 getMatrix(o, p);
}

void getMatrix(int x, int y){

 //Counter
 int c;

 //Size Declaration
 int size = x * y;

 //Array Declaration
 int arr[size];

 for(c = 0; c < size; c++){
  arr[c] = rand()%10;
 }

 printMatrix(arr[size], x, y);
}

void printMatrix(int arr[], int x, int y){

 //Counters
 int i, j;

 for(i = 0; i < y; i++){
  printf("\n");
  for(j = 0; j < x; j++){
   printf("%d ", arr[j]);
  }
 }
}

So basically this code is supposed to take in input and create a variable length array and its supposed to store random numbers in a 1 dimensional array and then they have to be printed out in the form of a 2d array or a matrix. I feel there might be something wrong with the parameters of the printMatrix function or when passing the array obtained in the getMatrix function. Any help would be appreciated, thank you.

EDIT: Thank you all for the help. I didn't even think about using this as a solution. But it works now and prints out the numbers that it is supposed to. Thanks again

Body:
What you are doing in the following line:

printMatrix(arr[size], x, y);

Is invoking undefined behavior. Since you have declared your array to be arr[size], the counter of your array must range from 0 to size - 1.

When you are trying to pass arr[size], rather than passing the whole array (which, judging form the program, is what you want it to do), you pass arr at element size, which is one index out of bounds.

Going into a bit more technical explaination of why this happens, the memory space that is right after the block allocated for arr must be empty, so you don't get segmentation fault, and instead, you get the address of that out-of-bound element. However, if it was filled up, then that would have caused a segmentation fault, and would have resulted in a runtime error.

To pass arr, you need to remove the index specifier:

printMatrix(arr, x, y);


问:
How to call Dictionary<K, V>.TryGetValue() where K : Predicate<T>, V : enum
I have Dictionary<Predicate<double>, SomeEnum>:

```<code>var dic = new Dictionary<Predicate<double>, SomeEnum>
{
    { (d) => d < 10, SomeEnum.Foo },
    { (d) => d > 90, SomeEnum.Bar }
};
</code>```

I want to call TryGetValue(K, out V) against it like this:

```<code>dic.TryGetValue(99)
</code>```

and receive

```<code>SomeStruct.Bar
</code>```

But first param for TryGetValue() is Predicate<T>, not just T. How can I do what I want?

I found only a dirty workaround:

```<code>var kpv = dic.FirstOrDefault(p => p.Key(99));
if (kpv.Key != null)
    var result = kpv.Value;
</code>```

Are there other ways?

Or how to implement my idea properly? - declare a key not as a constant but like a segment.

答:
There are a couple of things wrong here:

Predicate<double> is not an appropriate type to use as a TKey.  The key for a dictionary is supposed to identify a value, not calculate a value.

This wouldn't make any sense using lambdas either.  Because they are anonymous, you wouldn't get any equivalence, and won't be able use a dictionary.

See this code sample for an illustration:

```<code>Predicate<double> fn_1 = d => d == 34.0d;
Predicate<double> fn_2 = d => d == 34.0d;

// Note: There are not equal
if (fn_1 == fn_2)
    Console.WriteLine("These are Equal?");
</code>```

If anything, you could use a list of delegates and execute each one to find the ones that match, but at that point you must expect multiple results.  If you only want to get a single result, then you have to consider which order the predicates are stored within your list.

Don't misuse KeyValuePair as a hack for not having Tuple<T1,T2>.  It would be fairly easy to create a class that has both a Predicate and a SomeStruct.  Look:

```<code>public class MySegment
{
     public Predicate<double> Predicate {get;set;}
     public SomeStruct Result {get;set;}
}
</code>```

To go through a sequence of predicates, and find the matching ones would look like this:

```<code>...
List<MySegment> list = new List<MySegment>();
...
list.Add(new MySegment { Predicate = d => d < 10, Result = SomeStruct.Foo });
list.Add(new MySegment { Predicate = d => d > 90, Result = SomeStruct.Bar });

...

public IEnumerable<SomeStruct> GetResults(double input)
{
    foreach (var item in list)
        if (item.Predicate(input))
             yield return item.Result;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have Dictionary<Predicate<double>, SomeEnum>:

var dic = new Dictionary<Predicate<double>, SomeEnum>
{
    { (d) => d < 10, SomeEnum.Foo },
    { (d) => d > 90, SomeEnum.Bar }
};

I want to call TryGetValue(K, out V) against it like this:

dic.TryGetValue(99)

and receive

SomeStruct.Bar

But first param for TryGetValue() is Predicate<T>, not just T. How can I do what I want?

I found only a dirty workaround:

var kpv = dic.FirstOrDefault(p => p.Key(99));
if (kpv.Key != null)
    var result = kpv.Value;

Are there other ways?

Or how to implement my idea properly? - declare a key not as a constant but like a segment.

Body:
There are a couple of things wrong here:

Predicate<double> is not an appropriate type to use as a TKey.  The key for a dictionary is supposed to identify a value, not calculate a value.

This wouldn't make any sense using lambdas either.  Because they are anonymous, you wouldn't get any equivalence, and won't be able use a dictionary.

See this code sample for an illustration:

Predicate<double> fn_1 = d => d == 34.0d;
Predicate<double> fn_2 = d => d == 34.0d;

// Note: There are not equal
if (fn_1 == fn_2)
    Console.WriteLine("These are Equal?");

If anything, you could use a list of delegates and execute each one to find the ones that match, but at that point you must expect multiple results.  If you only want to get a single result, then you have to consider which order the predicates are stored within your list.

Don't misuse KeyValuePair as a hack for not having Tuple<T1,T2>.  It would be fairly easy to create a class that has both a Predicate and a SomeStruct.  Look:

public class MySegment
{
     public Predicate<double> Predicate {get;set;}
     public SomeStruct Result {get;set;}
}

To go through a sequence of predicates, and find the matching ones would look like this:

...
List<MySegment> list = new List<MySegment>();
...
list.Add(new MySegment { Predicate = d => d < 10, Result = SomeStruct.Foo });
list.Add(new MySegment { Predicate = d => d > 90, Result = SomeStruct.Bar });

...

public IEnumerable<SomeStruct> GetResults(double input)
{
    foreach (var item in list)
        if (item.Predicate(input))
             yield return item.Result;
}


问:
What is "semantic segmentation" compared to "segmentation" and "scene labeling"?
Is semantic segmentation just a Pleonasm or is there a difference between "semantic segmentation" and "segmentation"? Is there a difference to "scene labeling" or "scene parsing"?

What is the difference between pixel-level and pixelwise segmentation?

(Side-question: When you have this kind of pixel-wise annotation, do you get object detection for free or is there still something to do?)

Please give a source for your definitions.

Sources which use "semantic segmentation"

Jonathan Long, Evan Shelhamer, Trevor Darrell: Fully Convolutional Networks for Semantic Segmentation. CVPR, 2015 and PAMI, 2016

Hong, Seunghoon, Hyeonwoo Noh, and Bohyung Han: "Decoupled Deep Neural Network for Semi-supervised Semantic Segmentation." arXiv preprint arXiv:1506.04924, 2015.

V. Lempitsky, A. Vedaldi, and A. Zisserman: A pylon model for semantic segmentation. In Advances in Neural Information Processing Systems, 2011.

Sources which use "scene labeling"

Clement Farabet, Camille Couprie, Laurent Najman, Yann LeCun: Learning Hierarchical Features
for Scene Labeling. In Pattern Analysis and Machine Intelligence, 2013.

Source which use "pixel-level"

Pinheiro, Pedro O., and Ronan Collobert: "From Image-level to Pixel-level Labeling with Convolutional Networks." Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, 2015. (see http://arxiv.org/abs/1411.6228)

Source which use "pixelwise"

Li, Hongsheng, Rui Zhao, and Xiaogang Wang: "Highly efficient forward and backward propagation of convolutional neural networks for pixelwise classification." arXiv preprint arXiv:1412.4526, 2014.

Google Ngrams

"Semantic segmentation" seems to be more used recently than "scene labeling"

答:
The previous answers are really great, I would like to point out a few more additions:

Object Segmentation

one of the reasons that this has fallen out of favor in the research community is because it is problematically vague. Object segmentation used to simply mean finding a single or small number of objects in an image and draw a boundary around them, and for most purposes you can still assume it means this. However, it also began to be used to mean segmentation of blobs that might be objects, segmentation of objects from the background (more commonly now called background subtraction or background segmentation or foreground detection), and even in some cases used interchangeably with object recognition using bounding boxes (this quickly stopped with the advent of deep neural network approaches to object recognition, but beforehand object recognition could also mean simply labeling an entire image with the object in it).

What makes "segmentation" "semantic"?

Simpy, each segment, or in the case of deep methods each pixel, is given a class label based on a category. Segmentation in general is just the division of the image by some rule. Meanshift segmentation, for example, from a very high level divide the data according to the changes in the energy of the image. Graph cut based segmentation is similarly not learned but directly derived from the properties of each image separate from the rest.  More recent (neural network based) methods use pixels that are labeled to learn to identify the local features which are associated with specific classes, and then classify each pixel based on which class has the highest confidence for that pixel. In this way, "pixel-labeling" is actually more honest name for the task, and the "segmentation" component is emergent.

Instance Segmentation

Arguably the most difficult, relevant, and original meaning of Object Segmentation, "instance segmentation" means the segmentation of the individual objects within a scene, regardless of if they are the same type. However, one of the reason this is so difficult is because from a vision perspective (and in some ways a philosophical one) what makes an "object" instance is not entirely clear. Are body parts objects? Should such "part-objects" be segmented at all by an instance segmentation algorithm? Should they be only segmented if they are seen separate from the whole? What about compound objects should two things clearly adjoined but separable be one object or two (is a rock glued to the top of a stick an ax, a hammer, or just a stick and a rock unless properly made?). Also, it isn't clear how to distinguish instances. Is a will a separate instance from the other walls it is attached to? What order should instances be counted in? As they appear? Proximity to the viewpoint? In spite of these difficulties, segmentation of objects is still a big deal because as humans we interact with objects all the time regardless of their "class label" (using random objects around you as paper weights, sitting on things that are not chairs), and so some dataset do attempt to get at this problem, but the main reason there isn't much attention given to the problem yet is because it isn't well enough defined.

Scene Parsing/Scene labeling

Scene Parsing is the strictly segmentation approach to scene labeling, which also has some vagueness problems of its own. Historically, scene labeling meant to divide the entire "scene" (image) up into segments and give them all a class label. However, it was also used to mean giving class labels to areas of the image without explicitly segmenting them. With respect to segmentation, "semantic segmentation" does not imply dividing the entire scene. For semantic segmentation, the algorithm is intended to segment only the objects it knows, and will be penalized by its loss function for labeling pixels that don't have any label. For example the MS-COCO dataset is a dataset for semantic segmentation where only some objects are segmented.


问:
Spring Boot JPA bootstrapping the database
When using Spring Boot JPA (Hibernate), what is the best way to bootstrap the database with some seed data (MySQL in this case)? For example in Grails you can use the bootstrap.groovy file to accomplish this. I couldn't feel out a real consensus out there on what the best way to go about this is as in best practices.

答:
You can use Liquibase or Flyway approach.

Or the following Spring Boot properties:

spring.datasource.data= # Data (DML) script resource references.

spring.datasource.schema= # Schema (DDL) script resource references.

Another solution would be to create your own Bootstrap bean and run it before app started, see how the Spring Boot runs Flyway or Liquibase as a reference.

Database initialization documentation


问:
How to map a domain to another domain's subfolder?
I have a very fast web server (IIS6, ASP.NET) that I want to use for several sites. Now, I already have a domain that maps directly to the IP address of the server, but how can I get another domain to map to a subfolder (i.e., a separate ASP.NET application) on that same computer? Is it theoretically possible? (note: only port 80 is open, I cannot open other ones.)

Accepted answer: shown below. I actually followed the tutorial and got it working. Hooray! Thanks, everyone! :)

答:
Sure, you could do it with domain host headers. Just create a new web site and chose a different host header (e.g. www.example.com) and let it point to the desired folder. You can create hundreds of web sites on a single server, if you like.

Here is a tutorial how to do this.

Open IIS Manager

On the left side, expand your computer name, then click "Web Sites", right click in the right side, put your mouse over "New" and select "Web Site..."

Click Next in the dialog, then put in a description of the new web site you are creating (can be anything)

Click Next again and go to the last text box and put in what you want the new Host Header to be

Now put in the path to your new site and make sure you keep "Allow anonymous access" checked

Check "Run scripts" (for ASP.NET execution) if it's not already checked.

Click Finish on the next dialog and you're done!

OwnerDisplayName: Dmitri Nesteruk

LastEditorDisplayName: Dmitri Nesteruk

OwnerDisplayName: splattne

LastEditorDisplayName: splattne


问:
Internal links still point to development subdomain?
I moved a wordpress site from a subdirectory http://www.development.example.com to the root public_html directory.
I have updated the site & home urls to http://www.example.com and verified in phpMyAdmin in the control panel. The header links to other pages work as expected but my internal jump links on the home page such as http://www.example.com/#about still point to the subdomain link http://www.development.example.com/#about. Is there another place in the admin dashboard or directly in the database that I can check for necessary url changes to resolve this?

答:
You might try a couple things.

1.) Add the following to your wp-config.php file:

```<code>define('WP_HOME','http://yourdomain.com');
define('WP_SITEURL','http://yourdomain.com');
</code>```

2.) If you have (SSH) access to WP CLI, you can run this in your site root:

```<code>wp search-replace oldomain.com newdomain.com
</code>```

3.) Try the Better Search Replace plugin.

Body:
You might try a couple things.

1.) Add the following to your wp-config.php file:

define('WP_HOME','http://yourdomain.com');
define('WP_SITEURL','http://yourdomain.com');

2.) If you have (SSH) access to WP CLI, you can run this in your site root:

wp search-replace oldomain.com newdomain.com

3.) Try the Better Search Replace plugin.


问:
Boostrap Select with ajax sending parameters
I am new to jquery and found this great plugin: https://silviomoreto.github.io/bootstrap-select/

My page has 2 selects using ajax:
First looks for product and its code;
Second select looks for stock quantity for each unit of the selected product.
I realized the bellow code is not parsing the product code to second ajax call.

HTM:

```<code><div class="form-inline">
<select id="select_1" name = "codprod_1" class="selectpicker with-ajax" data-live-search="true">
</select>
</div>  <table class="table table-bordered table-striped" id="tabela">
<thead>
<tr>
<th>
ITEM
</th>
<th>
PRODUTO
</th>
<th>
LOTE
</th>
<th>
QTDE
</th>
<th>
VALIDADE
</th>
</tr>
</thead>
<tbody>
<tr>
<td align=center><b>1</b></td>
<td align=left>
<div class="form-inline">
<select id="select_1" name = "codprod_1" class="selectpicker with-ajax" data-live-search="true">
</select>
</div>
</td>
<input type=hidden name="descprod_1" id="descprod_1" value="">
<td align=left>
<div class="form-inline">
<select id="Lote_1" name = "Lote_1" class="selectpicker with-ajax2" data-live-search="true">
</select>
</div>
   </td>
<td align=center>
<input type=text class="form-control" id="qtde_1" name="qtde_1" value="" size=5 maxlength=5></td>
<td align=center><input type=text class="form-control" name="val_1" value="" size=7 maxlength=7></td>
</tr>
<tr>
<td align=center><b>2</b></td>
<td align=left>
<div class="form-inline">
<select id="select_2" name = "codprod_2" class="selectpicker with-ajax" data-live-search="true">
</select>
</div>
</td>
<input type=hidden name="descprod_2" id="descprod_2" value="">
<td align=left>
<div class="form-inline">
<select id="Lote_2" name = "Lote_2" class="selectpicker with-ajax2" data-live-search="true">
</select>
</div>
   </td>
<td align=center>
<input type=text class="form-control" id="qtde_2" name="qtde_2" value="" size=5 maxlength=5></td>
<td align=center><input type=text class="form-control" name="val_2" value="" size=7 maxlength=7></td>
</tr>
<tr>
<td align=center colspan="3">TOTAL</td>
<td align=center><div id="QtdTotal">0</div></td>
<td align=center> </div></td>
</tr>
</table>
</code>```

Javascript:

```<code><script language="Javascript">
var options = {
     ajax          : {
     url     : 'ajax_ConsultaProduto.asp',
     type    : 'POST',
     dataType: 'json',
     // Use "{{{q}}}" as a placeholder and Ajax Bootstrap Select will
     // automatically replace it with the value of the search query.
     data    : {
         q: '{{{q}}}'
     }
       },
      locale        : {
      emptyTitle: 'Código ou descrição do produto'
      },
      log           : 0,
    preprocessData: function (data) {
        var i, l = data.length, array = [];
        if (l) {
        for (i = 0; i < l; i++) {
            array.push($.extend(true, data[i], {
            text : data[i].descricao,
            value: data[i].codigo,
            data : {
                subtext: data[i].sigla
            }
            }));
        }
        }
        // You must always return a valid array when processing data. The
        // data argument passed is a clone and cannot be modified directly.
      return array;
      }
  };

var options2 = {
     ajax          : {
     url     : 'ajax_ConsultaLote.asp',
     type    : 'POST',
     dataType: 'json',
     // Use "{{{q}}}" as a placeholder and Ajax Bootstrap Select will
     // automatically replace it with the value of the search query.
     data    : {
         q: '{{{q}}}', p: document.getElementById('item').value
     }
       },
      locale        : {
      emptyTitle: 'Lote do Produto'
      },
      log           : 0,
    preprocessData: function (data) {
        var i, l = data.length, array = [];
        if (l) {
        for (i = 0; i < l; i++) {
            array.push($.extend(true, data[i], {
            text : data[i].descricao,
            value: data[i].codigo,
            data : {
                subtext: data[i].sigla
            }
            }));
        }
        }
        // You must always return a valid array when processing data. The
        // data argument passed is a clone and cannot be modified directly.
      return array;
      }
  };

$('.selectpicker').selectpicker().filter('.with-ajax').ajaxSelectPicker(options);
$('.selectpicker').selectpicker().filter('.with-ajax2').ajaxSelectPicker(options2);
</code>```

The parameter is p: document.getElementById('item').value as you can see. I suppose this command runs once the page is loaded. How can I parse the first selected value to the second ajax call>

答:
Just got the answer ...
Use refresh before calling the ajax...</p>

```<code>$('.selectpicker').selectpicker('refresh');
</code>```

Body:
I am new to jquery and found this great plugin: https://silviomoreto.github.io/bootstrap-select/

My page has 2 selects using ajax:
First looks for product and its code;
Second select looks for stock quantity for each unit of the selected product.
I realized the bellow code is not parsing the product code to second ajax call.

HTM:

<select id="select_1" name = "codprod_1" class="selectpicker with-ajax" data-live-search="true">
</select>

ITEM

PRODUTO

LOTE

QTDE

VALIDADE

1

<select id="select_1" name = "codprod_1" class="selectpicker with-ajax" data-live-search="true">
</select>

<input type=hidden name="descprod_1" id="descprod_1" value="">

<select id="Lote_1" name = "Lote_1" class="selectpicker with-ajax2" data-live-search="true">
</select>

<input type=text class="form-control" id="qtde_1" name="qtde_1" value="" size=5 maxlength=5>
<input type=text class="form-control" name="val_1" value="" size=7 maxlength=7>

2

<select id="select_2" name = "codprod_2" class="selectpicker with-ajax" data-live-search="true">
</select>

<input type=hidden name="descprod_2" id="descprod_2" value="">

<select id="Lote_2" name = "Lote_2" class="selectpicker with-ajax2" data-live-search="true">
</select>

<input type=text class="form-control" id="qtde_2" name="qtde_2" value="" size=5 maxlength=5>
<input type=text class="form-control" name="val_2" value="" size=7 maxlength=7>

TOTAL

0

Javascript:

Body:
Just got the answer ...
Use refresh before calling the ajax...

$('.selectpicker').selectpicker('refresh');


问:
Brand new to LC3
I am trying to write a program that will accept a user input and print the binary form of that input.  I am using the getc trap for the input.  I know that the getc input will be stored in R0 so I am thinking in need to use a BRzp then AND each bit to output either 1 or 0.  Can someone tell me if im thinking in the right direction.

PS I have to output the binary code in a string.

答:
A couple of things.

I am using the getc trap for the input.

If you are using GETC in order get a character, you should put a PUTC right after if you want to have the input echoed on the screen.

I am thinking in need to use a BRzp

BR is a conditional branch. Unless you want the PC to branch to a different part of your code, you shouldn't be using it.

then AND each bit

AND is a boolean algebra function. 0101 AND 0011 would be 0001.

PUTC or PUTS (for strings) are used in order to display an ASCII character to the console.

Before you tackle any coding in LC3, I would recommend you read up on what each psudo-code and psudo-op does and how LC3 functions before tackling your problem.

This slide is a good starting point. It shows you basically everything you need to know before coding in Assembly: https://classes.soe.ucsc.edu/cmpe012/Winter09/lectures/06_LC3_Assembly.pdf

Appendix from the Intro to Computing Systems textbook: http://highered.mheducation.com/sites/dl/free/0072467509/104691/pat67509_appa.pdf

Title: Brand new to LC3


问:
GridView is empty when passing in Array of images
I'm using picasso to load images into a grid view. The image URLS are retrieved from a database using the following code. This works as the URLS are outputted to the Android Monitor correctly.

```<code>private void getImages(){
        String BASE_URL = IMAGES_URL + userDetails.getUID();

        JsonObjectRequest jsonObjReq = new JsonObjectRequest(
                Request.Method.GET,BASE_URL, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try{
                            JSONArray listArray = response.getJSONArray("images");
                            images = new String[listArray.length()];
                            for(int i = 0; i <= listArray.length();i++)
                            {
                                JSONObject row = listArray.getJSONObject(i);

                                String name = row.getString("image_url");

                                images[i] = name;
                                Log.d(TAG, images[i]);

                            }
                            gridview.setAdapter(new ImageAdapter(getActivity(), images));

                        } catch (JSONException e)
                        {

                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d(TAG, "Error: " + error.getMessage());

            }
        });

        VolleyRequestQueue.getInstance(getActivity()).addToRequestQueue(jsonObjReq);
    }
</code>```

The code for my adapter is:

```<code>public class ImageAdapter extends BaseAdapter {
    private Context mContext;
    private String[] imageUrls;

    public ImageAdapter(Context c, String[] imageUrls) {
        mContext = c;
        this.imageUrls = imageUrls;
    }

    public int getCount() {
        return imageUrls.length;
    }

    public Object getItem(int position) {
        return null;
    }

    public long getItemId(int position) {
        return 0;
    }

    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {
            // if it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(200, 200));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
        } else {
            imageView = (ImageView) convertView;
        }

        Picasso picasso = Picasso.with(mContext);
        picasso.setIndicatorsEnabled(true);
        picasso.setLoggingEnabled(true);

        Picasso
                .with(mContext)
                .load("http://178.62.121.73" + imageUrls[position])
                .into(imageView);
        return imageView;
    }

}
</code>```

However, nothing is loaded on my activity. If i move the setadapter into my OnViewCreated, below where the code for downloading the image URLS is, i get a nullpointerexception on the images array, even though it has been successfully populated.

答: Did you check the size of ImageArray?if it is 0, I suppose the problems  is in 'reponse' variable which is your JSON parse result.</p>

Body:
I'm using picasso to load images into a grid view. The image URLS are retrieved from a database using the following code. This works as the URLS are outputted to the Android Monitor correctly.

private void getImages(){
        String BASE_URL = IMAGES_URL + userDetails.getUID();

        JsonObjectRequest jsonObjReq = new JsonObjectRequest(
                Request.Method.GET,BASE_URL, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try{
                            JSONArray listArray = response.getJSONArray("images");
                            images = new String[listArray.length()];
                            for(int i = 0; i <= listArray.length();i++)
                            {
                                JSONObject row = listArray.getJSONObject(i);

                                String name = row.getString("image_url");

                                images[i] = name;
                                Log.d(TAG, images[i]);

                            }
                            gridview.setAdapter(new ImageAdapter(getActivity(), images));

                        } catch (JSONException e)
                        {

                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d(TAG, "Error: " + error.getMessage());

            }
        });

        VolleyRequestQueue.getInstance(getActivity()).addToRequestQueue(jsonObjReq);
    }

The code for my adapter is:

public class ImageAdapter extends BaseAdapter {
    private Context mContext;
    private String[] imageUrls;

    public ImageAdapter(Context c, String[] imageUrls) {
        mContext = c;
        this.imageUrls = imageUrls;
    }

    public int getCount() {
        return imageUrls.length;
    }

    public Object getItem(int position) {
        return null;
    }

    public long getItemId(int position) {
        return 0;
    }

    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {
            // if it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(200, 200));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
        } else {
            imageView = (ImageView) convertView;
        }

        Picasso picasso = Picasso.with(mContext);
        picasso.setIndicatorsEnabled(true);
        picasso.setLoggingEnabled(true);

        Picasso
                .with(mContext)
                .load("http://178.62.121.73" + imageUrls[position])
                .into(imageView);
        return imageView;
    }

}

However, nothing is loaded on my activity. If i move the setadapter into my OnViewCreated, below where the code for downloading the image URLS is, i get a nullpointerexception on the images array, even though it has been successfully populated.


问:
Nearest completed quarter
Is there a C# function which will give me the last day of the most recently finished Quarter given a date?

For example,

```<code>var lastDayOfLastQuarter = SomeFunction(jan 3, 2010);
</code>```

would set lastDayOfLastQuarter = Dec 31, 2009

答: You can use a simple switch statement to check which quarter the given date falls and return the last day of that quarter.</p>

Title: Nearest completed quarter

Body:
Is there a C# function which will give me the last day of the most recently finished Quarter given a date?

For example,

var lastDayOfLastQuarter = SomeFunction(jan 3, 2010);

would set lastDayOfLastQuarter = Dec 31, 2009


问:
Replacing icon with image
I am using this template: https://startbootstrap.com/template-overviews/grayscale/ and am trying to replace the icon, which uses the i tag, with my own logo. I can't seem to find out how to use the i tag with my own image. I tried replacing it with an img tag, but the styling gets messed up. This is the line of html that is causing the issue:

```<code><a class="navbar-brand page-scroll" href="#page-top">
<i class="fa fa-play-circle"></i> <span  class="light">Start</span>  Bootstrap
            </a>
</code>```

I don't know what css, if any, to include since there is a lot relating to the specific class. Any help appreciated.

答:
Edit: UncaughtTypeError's comment is the way to go.

That is because the .fa-play-circle CSS class is affecting the "play icon" using the following CSS (found in font-awesome.min.css):

```<code>.fa-play-circle:before {
    content: "\f144";
}
</code>```

So, it isn't really an image as much as it is a glyph loaded before the  tag.

Title: Replacing icon with image

Body:
I am using this template: https://startbootstrap.com/template-overviews/grayscale/ and am trying to replace the icon, which uses the i tag, with my own logo. I can't seem to find out how to use the i tag with my own image. I tried replacing it with an img tag, but the styling gets messed up. This is the line of html that is causing the issue:

 Start  Bootstrap

I don't know what css, if any, to include since there is a lot relating to the specific class. Any help appreciated.

Body:
Edit: UncaughtTypeError's comment is the way to go.

That is because the .fa-play-circle CSS class is affecting the "play icon" using the following CSS (found in font-awesome.min.css):

.fa-play-circle:before {
    content: "\f144";
}

So, it isn't really an image as much as it is a glyph loaded before the  tag.


问:
SHA1withRSA verify in python?
I want to rewrite the code of Java to Python.The code is used to verify data through a .cer file.

```<code>public static boolean verifyByRSA(String certPath, byte[] aPlainData,
        byte[] aSignature) {
    boolean tResult = false;
    try {
        InputStream inStream = new FileInputStream(certPath);
        CertificateFactory tCertFactory = CertificateFactory
                .getInstance("X.509");
        Certificate tCertificate = tCertFactory
                .generateCertificate(inStream);

        Signature tSign = Signature.getInstance("SHA1withRSA", "BC");
        tSign.initVerify(tCertificate);

        tSign.update(aPlainData);
        tResult = tSign.verify(aSignature);

    } catch (Exception e) {
        e.printStackTrace();
    }
    return tResult;
}
</code>```

The .cer file is like:

-----BEGIN CERTIFICATE-----
MIIDhzCCAm+gAwIBAgIGASYISh96MA0GCSqGSIb3DQEBBQUAMF8xCzAJBgNVBAYTAkNOMSkwJwYDVQQKDCBBbGxpbnBheSBOZXR3b3JrIFNlcnZpY2VzIENvLkx0ZDElMCMGA1UECwwcQWxsaW5wYXkgUHJpbWFyeSBDZXJ0aWZpY2F0ZTAeFw0xMDAxMDcxMDE3NDBaFw0zMDAxMDIxMDE3NDBaMGQxCzAJBgNVBAYTAkNOMSkwJwYDVQQKDCBBbGxpbnBheSBOZXR3b3JrIFNlcnZpY2VzIENvLkx0ZDEqMCgGA1UECwwhQWxsaW5wYXkgRGlnaXRhbCBTaWduIENlcnRpZmljYXRlMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDEv2q2/xN5PF0dLn1vhIaVlyWsvJFVFxWgH7sQBObzYbZXOOVzoQpmXuSFOrF0/ol4Okd/2OGfdXUUFSUZfzAQOT1Wmjupec7z2V6l4/PT7aOg6t/MJwU9aW9Iw+AFzM1vnLOXdTlWVLZbtB7IiJ/HhfwBDkyvhp1zNYoAPrwC5QIDAQABo4HHMIHEMB0GA1UdDgQWBBQlWQA//YbuEdfE1yP+PpnokDO8WDCBjgYDVR0jBIGGMIGDgBSBWR3Bvx8To7TrecKhCM4smeabN6FjpGEwXzELMAkGA1UEBhMCQ04xKTAnBgNVBAoMIEFsbGlucGF5IE5ldHdvcmsgU2VydmljZXMgQ28uTHRkMSUwIwYDVQQLDBxBbGxpbnBheSBQcmltYXJ5IENlcnRpZmljYXRlggYBJghKHowwEgYDVR0TAQH/BAgwBgEB/wIBADANBgkqhkiG9w0BAQUFAAOCAQEATzT9GuAmAXLSWpoGc0F7Km7DPMWvSAkq8ckJLftF0/lB3JTR6QT5rsTnQHCdRU7SJX+eLNwhJQdRg34dPJAI2z/HpgGu7tW7pdsHjCjlVae3I64h2OzYBGXdtdRyPmyXfBOgXUfqtH0Fg+1QqsRmcRugywjZH8ZQAVYm0TkVJmdBknPp60bJ2gE/nj0w6VaSL6HMAQ+A7AVne3NDreBXepMHgiFqiqMHrZFBQCgTSR1UwZoT8hwXaaUgwf2h9l/D2QOGCD8G3sRKfMsH3clkehXbprWPNk3uww7dCT0pGz845AyKzCmRK60Z/NOgMG5X+f+JmugsS/bKYwjetXHg9Q==
-----END CERTIFICATE-----

I have tried

```<code>from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA

key = RSA.importKey(open(cer_path).read())
signer = PKCS1_v1_5.new(key)
digest = SHA.new()
digest.update(str_to_sign)
if signer.verify(digest, base64.decodestring(signature)):
    return True
return False
</code>```

But can't get the right result.What does the java code means?

答:
The importKey function supports the following:

X.509 subjectPublicKeyInfo DER SEQUENCE (binary or PEM encoding)

PKCS#1 RSAPublicKey DER SEQUENCE (binary or PEM encoding)

OpenSSH (textual public key only)

Now only the first and second are part of an X.509 certificate.

You need a library to parse X.509 certificates, such as the cryptography package.

As a stopgap measure you can get the RSAPublicKey object in your Java code and call getEncoded. This will return a DER SEQUENCE with a subjectPublicKeyInfo that can be imported in Python crypto (the first supported format by the importKey function).

Title: SHA1withRSA verify in python?

Body:
I want to rewrite the code of Java to Python.The code is used to verify data through a .cer file.

public static boolean verifyByRSA(String certPath, byte[] aPlainData,
        byte[] aSignature) {
    boolean tResult = false;
    try {
        InputStream inStream = new FileInputStream(certPath);
        CertificateFactory tCertFactory = CertificateFactory
                .getInstance("X.509");
        Certificate tCertificate = tCertFactory
                .generateCertificate(inStream);

        Signature tSign = Signature.getInstance("SHA1withRSA", "BC");
        tSign.initVerify(tCertificate);

        tSign.update(aPlainData);
        tResult = tSign.verify(aSignature);

    } catch (Exception e) {
        e.printStackTrace();
    }
    return tResult;
}

The .cer file is like:

-----BEGIN CERTIFICATE-----
MIIDhzCCAm+gAwIBAgIGASYISh96MA0GCSqGSIb3DQEBBQUAMF8xCzAJBgNVBAYTAkNOMSkwJwYDVQQKDCBBbGxpbnBheSBOZXR3b3JrIFNlcnZpY2VzIENvLkx0ZDElMCMGA1UECwwcQWxsaW5wYXkgUHJpbWFyeSBDZXJ0aWZpY2F0ZTAeFw0xMDAxMDcxMDE3NDBaFw0zMDAxMDIxMDE3NDBaMGQxCzAJBgNVBAYTAkNOMSkwJwYDVQQKDCBBbGxpbnBheSBOZXR3b3JrIFNlcnZpY2VzIENvLkx0ZDEqMCgGA1UECwwhQWxsaW5wYXkgRGlnaXRhbCBTaWduIENlcnRpZmljYXRlMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDEv2q2/xN5PF0dLn1vhIaVlyWsvJFVFxWgH7sQBObzYbZXOOVzoQpmXuSFOrF0/ol4Okd/2OGfdXUUFSUZfzAQOT1Wmjupec7z2V6l4/PT7aOg6t/MJwU9aW9Iw+AFzM1vnLOXdTlWVLZbtB7IiJ/HhfwBDkyvhp1zNYoAPrwC5QIDAQABo4HHMIHEMB0GA1UdDgQWBBQlWQA//YbuEdfE1yP+PpnokDO8WDCBjgYDVR0jBIGGMIGDgBSBWR3Bvx8To7TrecKhCM4smeabN6FjpGEwXzELMAkGA1UEBhMCQ04xKTAnBgNVBAoMIEFsbGlucGF5IE5ldHdvcmsgU2VydmljZXMgQ28uTHRkMSUwIwYDVQQLDBxBbGxpbnBheSBQcmltYXJ5IENlcnRpZmljYXRlggYBJghKHowwEgYDVR0TAQH/BAgwBgEB/wIBADANBgkqhkiG9w0BAQUFAAOCAQEATzT9GuAmAXLSWpoGc0F7Km7DPMWvSAkq8ckJLftF0/lB3JTR6QT5rsTnQHCdRU7SJX+eLNwhJQdRg34dPJAI2z/HpgGu7tW7pdsHjCjlVae3I64h2OzYBGXdtdRyPmyXfBOgXUfqtH0Fg+1QqsRmcRugywjZH8ZQAVYm0TkVJmdBknPp60bJ2gE/nj0w6VaSL6HMAQ+A7AVne3NDreBXepMHgiFqiqMHrZFBQCgTSR1UwZoT8hwXaaUgwf2h9l/D2QOGCD8G3sRKfMsH3clkehXbprWPNk3uww7dCT0pGz845AyKzCmRK60Z/NOgMG5X+f+JmugsS/bKYwjetXHg9Q==
-----END CERTIFICATE-----

I have tried

from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA

key = RSA.importKey(open(cer_path).read())
signer = PKCS1_v1_5.new(key)
digest = SHA.new()
digest.update(str_to_sign)
if signer.verify(digest, base64.decodestring(signature)):
    return True
return False

But can't get the right result.What does the java code means?


问:
Reactjs pass variables from one component to another
I have a component like this:

```<code>class LoginPage extends React.Component{
  constructor(props)  {
    super(props);
    this.state = {submit:''};
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(e) {
    alert('username and password were submitted: ' + this.props.userName + ' and ' + this.props.password);
    e.prevenDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <GetUsername/>
        <GetPassword/>
        <button type="submit">Login</button>
       </form>
    )
  }
}
</code>```

The GetUsername and GetPassword components get username and password from user input. My question is that is there anyway I can pass the username and password from these 2 components to the handleSubmit method of the LoginPage component above, so the alert pops up can show correctly?

答:
To achieve what you are looking for, you would need the login form to have its own state which would include the username and password. It would have instance methods that would update those fields. It would pass those functions down to the relevant child components and whenever they change they would call this.props.onChange with the appropriate value. The parent component would then update its appropriate state. Here is an example.

```<code>class LoginPage extends React.Component{
  constructor(props)  {
    super(props);
    this.state = {
      submit:'',
      password: '',
      userName: ''

    };
    this.handleSubmit = this.handleSubmit.bind(this);
    this.onUserNameChange = this.onUserNameChange.bind(this);
    this.onPasswordChange = this.onPasswordChange.bind(this);
  }

  onUserNameChange(userName) {
    this.setState({
      userName: userName
    })
  }

  onPasswordChange(password) {
    this.setState({
      password: password
    })
  }

  handleSubmit(e) {
    alert('username and password were submitted: ' + this.state.userName + ' and ' + this.state.password);
    e.prevenDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <GetUsername onChange={onUserNameChange}/>
        <GetPassword onChange={onPasswordChange}/>
        <button type="submit">Login</button>
       </form>
    )
  }
}
</code>```

this may require some tweaking and as stated before you would need to make sure that you are ingesting the this.props.onChange appropriately in your GetUsername and GetPassword components so they call that function and pass the appropriate argument in.

Body:
I have a component like this:

class LoginPage extends React.Component{
  constructor(props)  {
    super(props);
    this.state = {submit:''};
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(e) {
    alert('username and password were submitted: ' + this.props.userName + ' and ' + this.props.password);
    e.prevenDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <GetUsername/>
        <GetPassword/>
        <button type="submit">Login</button>
       </form>
    )
  }
}

The GetUsername and GetPassword components get username and password from user input. My question is that is there anyway I can pass the username and password from these 2 components to the handleSubmit method of the LoginPage component above, so the alert pops up can show correctly?

Body:
To achieve what you are looking for, you would need the login form to have its own state which would include the username and password. It would have instance methods that would update those fields. It would pass those functions down to the relevant child components and whenever they change they would call this.props.onChange with the appropriate value. The parent component would then update its appropriate state. Here is an example.

class LoginPage extends React.Component{
  constructor(props)  {
    super(props);
    this.state = {
      submit:'',
      password: '',
      userName: ''

    };
    this.handleSubmit = this.handleSubmit.bind(this);
    this.onUserNameChange = this.onUserNameChange.bind(this);
    this.onPasswordChange = this.onPasswordChange.bind(this);
  }

  onUserNameChange(userName) {
    this.setState({
      userName: userName
    })
  }

  onPasswordChange(password) {
    this.setState({
      password: password
    })
  }

  handleSubmit(e) {
    alert('username and password were submitted: ' + this.state.userName + ' and ' + this.state.password);
    e.prevenDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <GetUsername onChange={onUserNameChange}/>
        <GetPassword onChange={onPasswordChange}/>
        <button type="submit">Login</button>
       </form>
    )
  }
}

this may require some tweaking and as stated before you would need to make sure that you are ingesting the this.props.onChange appropriately in your GetUsername and GetPassword components so they call that function and pass the appropriate argument in.


问:
Get all strings between two other strings in html document in PHP
I'm creating some kind of crawler/proxy at the moment. It can navigate a website and still remain on my website while browsing. But I thought about while loading the website, get all the links and data at the same time.

So the website contains many "
"(without the space) which again contains a lot of other stuff.

Here is 1 example of many on the website:

```<code><tr>
    <td class="vertTh">
        <center>
            <a href="/s/browse/other.php">Other</a>
            <br>
            <a href="/s/browse/documents.php">Document</a>
        </center>
    </td>
    <td>
        <div class="Name">
            <a href="/s/database/Document_Title_Info" class="Link">Document Title Info</a>
        </div>
        <a href="http://example.com/source/to/document/which%20can%20be%20very%20long%20and%20have%20weird%20characters" title="Source">
            <img src="/static/img/icon-source.png" alt="Source">
        </a>
        <font class="Desc">Uploaded 03-24 14:02, Size 267.35 KB, ULed by <a class="Desc" href="/s/user/username/" title="Browse username">username</a></font>
    </td>
    <td align="right">67</td>
    <td align="right">9</td>
</tr>
</code>```

Users browse the proxy site, and while they do, it catches info from the original website.
I figured out how to get a string between two words, but I don't know how to make this to a "foreach" code or something else.

So let's say I want to get the source link. Then I would do something like this:

```<code>$url = $_GET['url'];
$str = file_get_contents('https://database.com/' . $url);

$source = 'http://example.com/source/to/' . getStringBetween($str,'example.com/source/to/','" title="Source">'); // Output looking like this: http://example.com/source/to/document/which%20can%20be%20very%20long%20and%20have%20weird%20characters

function getStringBetween($str,$from,$to)
{
    $sub = substr($str, strpos($str,$from)+strlen($from),strlen($str));
    return substr($sub,0,strpos($sub,$to));
}
</code>```

But I can't just do this, because there are multiple of these strings. So I'm wondering if there is any kind of way I can get Source, name and size on all of these strings?

答:
You might want to use preg_match_all so that you get a list of many matches. Then you can loop over it.

http://php.net/manual/en/function.preg-match-all.php

```<code>$html = '<tr>
    <td class="vertTh">
        <center>
            <a href="/s/browse/other.php">Other</a>
            <br>
            <a href="/s/browse/documents.php">Document</a>
        </center>
    </td>
    <td>
        <div class="Name">
            <a href="/s/database/Document_Title_Info" class="Link">Document Title Info</a>
        </div>
        <a href="http://another-example.com/source/to/document/which%20can%20be%20very%20long%20and%20have%20weird%20characters" title="Source">
            <img src="/static/img/icon-source.png" alt="Source">
        </a>
        <a href="http://example.com/source/to/document/which%20can%20be%20very%20long%20and%20have%20weird%20characters" title="Source">
            <img src="/static/img/icon-source.png" alt="Source">
        </a>
        <font class="Desc">Uploaded 03-24 14:02, Size 267.35 KB, ULed by <a class="Desc" href="/s/user/username/" title="Browse username">username</a></font>
    </td>
    <td align="right">67</td>
    <td align="right">9</td>
</tr>';

// use | as delimiter for pattern to make it a little cleaner
preg_match_all('|href="(http://.+?)" title="Source"|', $html, $matches);
// loop over $matches
var_dump($matches);

foreach ($matches[1] as $match) {
    // $match == http://example.com/source/to/document/which%20can%20be%20very%20long%20and%20have%20weird%20characters
}
</code>```

You can try this example at... http://phpfiddle.org/ or run it in a .php file locally. Good luck.

FYI: I added an extra anchor tag to illustrate finding another source.

Body:
I'm creating some kind of crawler/proxy at the moment. It can navigate a website and still remain on my website while browsing. But I thought about while loading the website, get all the links and data at the same time.

So the website contains many "
"(without the space) which again contains a lot of other stuff.

Here is 1 example of many on the website:

            Other

            Document

            Document Title Info

        Uploaded 03-24 14:02, Size 267.35 KB, ULed by username

    67
    9

Users browse the proxy site, and while they do, it catches info from the original website.
I figured out how to get a string between two words, but I don't know how to make this to a "foreach" code or something else.

So let's say I want to get the source link. Then I would do something like this:

$url = $_GET['url'];
$str = file_get_contents('https://database.com/' . $url);

$source = 'http://example.com/source/to/' . getStringBetween($str,'example.com/source/to/','" title="Source">'); // Output looking like this: http://example.com/source/to/document/which%20can%20be%20very%20long%20and%20have%20weird%20characters

function getStringBetween($str,$from,$to)
{
    $sub = substr($str, strpos($str,$from)+strlen($from),strlen($str));
    return substr($sub,0,strpos($sub,$to));
}

But I can't just do this, because there are multiple of these strings. So I'm wondering if there is any kind of way I can get Source, name and size on all of these strings?

Body:
You might want to use preg_match_all so that you get a list of many matches. Then you can loop over it.

http://php.net/manual/en/function.preg-match-all.php

$html = '<tr>
    <td class="vertTh">
        <center>
            <a href="/s/browse/other.php">Other</a>
            <br>
            <a href="/s/browse/documents.php">Document</a>
        </center>
    </td>
    <td>
        <div class="Name">
            <a href="/s/database/Document_Title_Info" class="Link">Document Title Info</a>
        </div>
        <a href="http://another-example.com/source/to/document/which%20can%20be%20very%20long%20and%20have%20weird%20characters" title="Source">
            <img src="/static/img/icon-source.png" alt="Source">
        </a>
        <a href="http://example.com/source/to/document/which%20can%20be%20very%20long%20and%20have%20weird%20characters" title="Source">
            <img src="/static/img/icon-source.png" alt="Source">
        </a>
        <font class="Desc">Uploaded 03-24&nbsp;14:02, Size 267.35&nbsp;KB, ULed by <a class="Desc" href="/s/user/username/" title="Browse username">username</a></font>
    </td>
    <td align="right">67</td>
    <td align="right">9</td>
</tr>';

// use | as delimiter for pattern to make it a little cleaner
preg_match_all('|href="(http://.+?)" title="Source"|', $html, $matches);
// loop over $matches
var_dump($matches);

foreach ($matches[1] as $match) {
    // $match == http://example.com/source/to/document/which%20can%20be%20very%20long%20and%20have%20weird%20characters
}

You can try this example at... http://phpfiddle.org/ or run it in a .php file locally. Good luck.

FYI: I added an extra anchor tag to illustrate finding another source.


问:
C while(false) loop
I was looking at a lexical analyzer code and i came across this:

```<code>while ("false")
{
    c = fgetc(f);
    switch (state)
    ...
</code>```

I tested it and the code works, it produces correct results. Why does the loop run if there is false condition? Shouldnt the loop never run?

答:
The while control structure only accepts Boolean parameters.

If it doesn't get Boolean parameters, the parameter is evaluated to a Boolean. In this case, "false" is a string, and it evaluates to a true value. Only 0and falseactually mean false.

Title: C while(false) loop

Body:
I was looking at a lexical analyzer code and i came across this:

while ("false")
{
    c = fgetc(f);
    switch (state)
    ...

I tested it and the code works, it produces correct results. Why does the loop run if there is false condition? Shouldnt the loop never run?


问:
ADB unable to start or find devices after sudo adb devices
I am currently trying to get a docker container to connect to my android devices over ADB. ADB is able to see that a device is connected but is unable to get the required permissions to access the desired device.

Normally I would fix this very quickly by running a simple adb kill-server followed by a sudo adb-devices. Unfortunately a sudo adb devices does not recognize that any device is attached. If i try to do a adb devices any time after the sudo command was executed I run into the following error:

```<code>* daemon not running. starting it now on port 5037 *
cannot bind 'local:5037'
ADB server didn't ACK
* failed to start daemon *
error: cannot connect to daemon
</code>```

After this point even if I run another kill-server I receive the same error on adb devices requests. In order to get past this I have to manually delete the socket /tmp/5037 generated by the request.

At this point my main goal is just to get access to the ADB device I am attempting to test with. Is there some step that I am missing that might be causing this weird behavior?

For reference:

usb debugging is enabled and I am able to adb into the device from
the box with the docker container running on it.

I do make sure to run an adb kill-server on the box with the
container in it before running adb start server inside the container.

device as listed by lsusb:

```<code>Bus 001 Device 012: ID 0c2e:0ba1 android_device_name
</code>```

99-android.rules entry in /etc/udev/:

```<code>SUBSYSTEM=="usb", ATTR{idVendor}=="0c2e", GROUP="plugdev" MODE="0666"
SUBSYSTEM=="usb",ATTR{idVendor}=="0c2e",SYMLINK+="android_adb"
SUBSYSTEM=="usb",ATTR{idVendor}=="0c2e",SYMLINK+="android_fastboot"
</code>```

my adb_usb.ini

```<code>0x067e
0x0c2e
0x05c6
</code>```

答:
You need to enable USB debugging in your phone. On your phone go to

Settings

General

Developer Options

USB debugging

In Android 4.2 and higher versions, the Developer Options menu and USB Debugging option have been hidden. In former 4.X versions of Android, USB Debugging option is under Developer Options menu.
First, you need to enable "Developer Options Menu".

Click Menu button to enter into App drawer.
Go to "Settings".
Scroll down to the bottom and tap "About phone" or "About tablet",
Scroll down to the bottom of the "About phone" and locate the "Build Number" field.

Tap the Build number field seven times to enable Developer Options. Tap a few times and you'll see a countdown that reads "You are now 3 steps away from being a developer."
When you are done, you'll see the message "You are now a developer!".
Tap the Back button and you'll see the Developer options menu under System on your Settings screen.
Now, you can enable USB Debugging mode.

Go to Settings>Developer Options>USB Debugging. Tap the USB Debugging checkbox.

Body:
I am currently trying to get a docker container to connect to my android devices over ADB. ADB is able to see that a device is connected but is unable to get the required permissions to access the desired device.

Normally I would fix this very quickly by running a simple adb kill-server followed by a sudo adb-devices. Unfortunately a sudo adb devices does not recognize that any device is attached. If i try to do a adb devices any time after the sudo command was executed I run into the following error:

* daemon not running. starting it now on port 5037 *
cannot bind 'local:5037'
ADB server didn't ACK
* failed to start daemon *
error: cannot connect to daemon

After this point even if I run another kill-server I receive the same error on adb devices requests. In order to get past this I have to manually delete the socket /tmp/5037 generated by the request.

At this point my main goal is just to get access to the ADB device I am attempting to test with. Is there some step that I am missing that might be causing this weird behavior?

For reference:

usb debugging is enabled and I am able to adb into the device from
the box with the docker container running on it.

I do make sure to run an adb kill-server on the box with the
container in it before running adb start server inside the container.

device as listed by lsusb:

Bus 001 Device 012: ID 0c2e:0ba1 android_device_name

99-android.rules entry in /etc/udev/:

SUBSYSTEM=="usb", ATTR{idVendor}=="0c2e", GROUP="plugdev" MODE="0666"
SUBSYSTEM=="usb",ATTR{idVendor}=="0c2e",SYMLINK+="android_adb"
SUBSYSTEM=="usb",ATTR{idVendor}=="0c2e",SYMLINK+="android_fastboot"

my adb_usb.ini

0x067e
0x0c2e
0x05c6


问:
Tensorflow not showing "Successfully opened so & so CUDA libraries locally"
I configured tensorflow to work with CUDA support on my GPU (GeForce 840M) but the programs are running quite slow in compare to what my CPU used to earlier. Also, I do not get any kind of message that the so and so CUDA library was successfully opened when I run the program. Instead, this is what I get in logs when I run any tensorflow program:

```<code>python Neuralnet.py
Successfully downloaded train-images-idx3-ubyte.gz 9912422 bytes.
Extracting /tmp/data/train-images-idx3-ubyte.gz
Successfully downloaded train-labels-idx1-ubyte.gz 28881 bytes.
Extracting /tmp/data/train-labels-idx1-ubyte.gz
Successfully downloaded t10k-images-idx3-ubyte.gz 1648877 bytes.
Extracting /tmp/data/t10k-images-idx3-ubyte.gz
Successfully downloaded t10k-labels-idx1-ubyte.gz 4542 bytes.
Extracting /tmp/data/t10k-labels-idx1-ubyte.gz
2017-03-28 07:53:57.979382: W tensorflow/core/platform/cpu_feature_guard.cc:45]
    The TensorFlow library wasn't compiled to use SSE4.1 instructions,
    but these are available on your machine and could speed up CPU computations.
2017-03-28 07:53:57.979413: W tensorflow/core/platform/cpu_feature_guard.cc:45]
    The TensorFlow library wasn't compiled to use SSE4.2 instructions,
    but these are available on your machine and could speed up CPU computations.
2017-03-28 07:53:57.979431: W tensorflow/core/platform/cpu_feature_guard.cc:45]
    The TensorFlow library wasn't compiled to use AVX instructions,
    but these are available on your machine and could speed up CPU computations.
2017-03-28 07:53:57.979438: W tensorflow/core/platform/cpu_feature_guard.cc:45]
    The TensorFlow library wasn't compiled to use AVX2 instructions,
    but these are available on your machine and could speed up CPU computations.
2017-03-28 07:53:57.979447: W tensorflow/core/platform/cpu_feature_guard.cc:45]
    The TensorFlow library wasn't compiled to use FMA instructions,
    but these are available on your machine and could speed up CPU computations.
2017-03-28 07:53:58.233876: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:901]
    successful NUMA node read from SysFS had negative value (-1),
    but there must be at least one NUMA node, so returning NUMA node zero
2017-03-28 07:53:58.234333: I tensorflow/core/common_runtime/gpu/gpu_device.cc:887]
Found device 0 with properties:
name: GeForce 840M
major: 5 minor: 0 memoryClockRate (GHz) 1.124
pciBusID 0000:08:00.0
Total memory: 1.96GiB
Free memory: 1.75GiB
2017-03-28 07:53:58.234362: I tensorflow/core/common_runtime/gpu/gpu_device.cc:908] DMA: 0
2017-03-28 07:53:58.234372: I tensorflow/core/common_runtime/gpu/gpu_device.cc:918] 0:   Y
2017-03-28 07:53:58.234388: I tensorflow/core/common_runtime/gpu/gpu_device.cc:977]
Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce 840M, pci bus id: 0000:08:00.0)
('Epoch', 0, 'completed out of', 15, 'loss:', 115374329.04653475)
</code>```

And so on the program started runnning but it didn't ran any faster according to my expectations. I installed CUDA from the official documentation, but I did not reset the git master head since it was creating issues and I used the same optimization flags provided bazel build -c opt --config=cuda //tensorflow/tools/pip_package:build_pip_package when building through bazel.

答:
Did you use nvidia-smi to tell whether you have the right cuda drivers installed and that your gpu is visible to the system?

In TF you can set the log_device_placement option to understand if any ops are being assigned to the GPU.

Body:
I configured tensorflow to work with CUDA support on my GPU (GeForce 840M) but the programs are running quite slow in compare to what my CPU used to earlier. Also, I do not get any kind of message that the so and so CUDA library was successfully opened when I run the program. Instead, this is what I get in logs when I run any tensorflow program:

python Neuralnet.py
Successfully downloaded train-images-idx3-ubyte.gz 9912422 bytes.
Extracting /tmp/data/train-images-idx3-ubyte.gz
Successfully downloaded train-labels-idx1-ubyte.gz 28881 bytes.
Extracting /tmp/data/train-labels-idx1-ubyte.gz
Successfully downloaded t10k-images-idx3-ubyte.gz 1648877 bytes.
Extracting /tmp/data/t10k-images-idx3-ubyte.gz
Successfully downloaded t10k-labels-idx1-ubyte.gz 4542 bytes.
Extracting /tmp/data/t10k-labels-idx1-ubyte.gz
2017-03-28 07:53:57.979382: W tensorflow/core/platform/cpu_feature_guard.cc:45]
    The TensorFlow library wasn't compiled to use SSE4.1 instructions,
    but these are available on your machine and could speed up CPU computations.
2017-03-28 07:53:57.979413: W tensorflow/core/platform/cpu_feature_guard.cc:45]
    The TensorFlow library wasn't compiled to use SSE4.2 instructions,
    but these are available on your machine and could speed up CPU computations.
2017-03-28 07:53:57.979431: W tensorflow/core/platform/cpu_feature_guard.cc:45]
    The TensorFlow library wasn't compiled to use AVX instructions,
    but these are available on your machine and could speed up CPU computations.
2017-03-28 07:53:57.979438: W tensorflow/core/platform/cpu_feature_guard.cc:45]
    The TensorFlow library wasn't compiled to use AVX2 instructions,
    but these are available on your machine and could speed up CPU computations.
2017-03-28 07:53:57.979447: W tensorflow/core/platform/cpu_feature_guard.cc:45]
    The TensorFlow library wasn't compiled to use FMA instructions,
    but these are available on your machine and could speed up CPU computations.
2017-03-28 07:53:58.233876: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:901]
    successful NUMA node read from SysFS had negative value (-1),
    but there must be at least one NUMA node, so returning NUMA node zero
2017-03-28 07:53:58.234333: I tensorflow/core/common_runtime/gpu/gpu_device.cc:887]
Found device 0 with properties:
name: GeForce 840M
major: 5 minor: 0 memoryClockRate (GHz) 1.124
pciBusID 0000:08:00.0
Total memory: 1.96GiB
Free memory: 1.75GiB
2017-03-28 07:53:58.234362: I tensorflow/core/common_runtime/gpu/gpu_device.cc:908] DMA: 0
2017-03-28 07:53:58.234372: I tensorflow/core/common_runtime/gpu/gpu_device.cc:918] 0:   Y
2017-03-28 07:53:58.234388: I tensorflow/core/common_runtime/gpu/gpu_device.cc:977]
Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce 840M, pci bus id: 0000:08:00.0)
('Epoch', 0, 'completed out of', 15, 'loss:', 115374329.04653475)

And so on the program started runnning but it didn't ran any faster according to my expectations. I installed CUDA from the official documentation, but I did not reset the git master head since it was creating issues and I used the same optimization flags provided bazel build -c opt --config=cuda //tensorflow/tools/pip_package:build_pip_package when building through bazel.


问:
Why Doesn't My Code Work When Converting From ES5 To ES6 Syntax?
I'm new to React and working my way through how to use 'props' and 'state' in online course. Online course uses ES5, but my IDE is set up for ES6. I've gotten through converting most examples just fine. But the following is baffling. The example works fine, but my ES6 conversion doesn't--the page renders blank. I looked through "Questions that may already have your answer", but nothing reveals my omission(s)/mistake(s). I was validated on other changes syntactically though. :)

My conversion in 'App.js' file

```<code>import React, { Component } from 'react';

let green = '#39D1B4';
let yellow = '#FFD712';

class Toggle extends Component {

  getInitialState() {
    return {color: green};
  }

  changeColor(){
    let newColor = this.state.color === green ? yellow : green;
    this.setState({color: newColor});
  }

  render() {
    return (
      <div style={{background: this.state.color}}>
        <h1>
          Change My Color
        </h1>
        <button onClick={this.changeColor}>
          Change Color
        </button>
      </div>
    );
  }
}

export default Toggle;
</code>```

My conversion in 'index.js' file

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import Toggle from './App';

ReactDOM.render(
  <Toggle />,
  document.getElementById('root')
);
</code>```

'index.html' file

```<code><!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Call 'this.setState' From Another Function</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>
</code>```

$ npm start says:

Compiled successfully!

The app is running at:

http://localhost:3000/

Note that the development build is not optimized.
To create a production build, use npm run build.

Yes, I got the following from the Console:

```<code>Warning: getInitialState was defined on Toggle, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?
printWarning @ warning.js:36
App.js:20Uncaught TypeError: Cannot read property 'color' of null
    at Toggle.render (App.js:20)
    at ReactCompositeComponent.js:796
    at measureLifeCyclePerf (ReactCompositeComponent.js:75)
    at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (ReactCompositeComponent.js:795)
    at ReactCompositeComponentWrapper._renderValidatedComponent (ReactCompositeComponent.js:822)
    at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:362)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:258)
    at Object.mountComponent (ReactReconciler.js:46)
    at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:371)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:258)
content.js:4186 Uncaught TypeError: Cannot read property 'indexOf' of null
    at content.js:4186
</code>```

Looks like everything works fine after adding a constructor, binding the method and fixing the onClick syntax. Direction is appreciated. Thanks.

答:
Three things:

There is no getInitialState in ES6-style React components. Set the state in the constructor of Toggle:

```<code>constructor(props)
{
    super(props);
    this.state = { color: green };
}
</code>```

React does not automatically bind component methods to this in ES6-style components. So, when you do onClick={this.changeColor}, and the onClick callback is triggered, this will be null, causing another error. Fix this by binding this.changeColor to this in the constructor:

```<code>constructor(props)
{
    super(props);
    this.state = { color: green };
    this.changeColor = this.changeColor.bind(this);
}
</code>```

Alternatively, use an ES6-style arrow function for onClick: onClick={() => this.changeColor()}

Your index.html doesn't include your script. This may just be a copy-paste error in your question, but make sure you include your script:

```<code><script src="index.js"></script>
</code>```

Body:
I'm new to React and working my way through how to use 'props' and 'state' in online course. Online course uses ES5, but my IDE is set up for ES6. I've gotten through converting most examples just fine. But the following is baffling. The example works fine, but my ES6 conversion doesn't--the page renders blank. I looked through "Questions that may already have your answer", but nothing reveals my omission(s)/mistake(s). I was validated on other changes syntactically though. :)

My conversion in 'App.js' file

import React, { Component } from 'react';

let green = '#39D1B4';
let yellow = '#FFD712';

class Toggle extends Component {

  getInitialState() {
    return {color: green};
  }

  changeColor(){
    let newColor = this.state.color === green ? yellow : green;
    this.setState({color: newColor});
  }

  render() {
    return (

          Change My Color

        <button onClick={this.changeColor}>
          Change Color
        </button>

    );
  }
}

export default Toggle;

My conversion in 'index.js' file

import React from 'react';
import ReactDOM from 'react-dom';
import Toggle from './App';

ReactDOM.render(
  <Toggle />,
  document.getElementById('root')
);

'index.html' file

<!doctype html>

    <meta charset="utf-8">
    <title>Call 'this.setState' From Another Function</title>

$ npm start says:

Compiled successfully!

The app is running at:

http://localhost:3000/

Note that the development build is not optimized.
To create a production build, use npm run build.

Yes, I got the following from the Console:

Warning: getInitialState was defined on Toggle, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?
printWarning @ warning.js:36
App.js:20Uncaught TypeError: Cannot read property 'color' of null
    at Toggle.render (App.js:20)
    at ReactCompositeComponent.js:796
    at measureLifeCyclePerf (ReactCompositeComponent.js:75)
    at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (ReactCompositeComponent.js:795)
    at ReactCompositeComponentWrapper._renderValidatedComponent (ReactCompositeComponent.js:822)
    at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:362)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:258)
    at Object.mountComponent (ReactReconciler.js:46)
    at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:371)
    at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:258)
content.js:4186 Uncaught TypeError: Cannot read property 'indexOf' of null
    at content.js:4186

Looks like everything works fine after adding a constructor, binding the method and fixing the onClick syntax. Direction is appreciated. Thanks.

Body:
Three things:

There is no getInitialState in ES6-style React components. Set the state in the constructor of Toggle:

constructor(props)
{
    super(props);
    this.state = { color: green };
}

React does not automatically bind component methods to this in ES6-style components. So, when you do onClick={this.changeColor}, and the onClick callback is triggered, this will be null, causing another error. Fix this by binding this.changeColor to this in the constructor:

constructor(props)
{
    super(props);
    this.state = { color: green };
    this.changeColor = this.changeColor.bind(this);
}

Alternatively, use an ES6-style arrow function for onClick: onClick={() => this.changeColor()}

Your index.html doesn't include your script. This may just be a copy-paste error in your question, but make sure you include your script:

<script src="index.js"></script>


问:
Rails 5.0.2, Capistrano Stopped Deploying
I've been successfully deploying with Capistrano for several months. After some updates, it stopped working.

Recently we added Spina CMS but have already deployed a version that is live. We did remove a Capistrano Lock awhile back.

If I run:

```<code>cap production deploy
(Backtrace restricted to imported tasks)
cap aborted!
Don't know how to build task 'start' (see --tasks)

Tasks: TOP => production
(See full trace by running task with --trace)
</code>```

I then ran:

```<code>Daves-MBP-2:enduur dave$ cap production deploy --trace
** Invoke production (first_time)
** Execute production
** Invoke load:defaults (first_time)
** Execute load:defaults
cap aborted!
Don't know how to build task 'start' (see --tasks)
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/task_manager.rb:58:in `[]'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/task.rb:361:in `[]'
/usr/local/rvm/gems/ruby-2.3.1/gems/capistrano-3.8.0/lib/capistrano/dsl/task_enhancements.rb:7:in `before'
config/deploy.rb:48:in `block in <top (required)>'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/task_manager.rb:205:in `in_namespace'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/dsl_definition.rb:140:in `namespace'
config/deploy.rb:39:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.3.1/gems/capistrano-3.8.0/lib/capistrano/setup.rb:27:in `load'
/usr/local/rvm/gems/ruby-2.3.1/gems/capistrano-3.8.0/lib/capistrano/setup.rb:27:in `block (3 levels) in <top (required)>'
/usr/local/rvm/gems/ruby-2.3.1/gems/capistrano-3.8.0/lib/capistrano/configuration/variables.rb:32:in `untrusted!'
/usr/local/rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/delegate.rb:83:in `method_missing'
/usr/local/rvm/gems/ruby-2.3.1/gems/capistrano-3.8.0/lib/capistrano/setup.rb:26:in `block (2 levels) in <top (required)>'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/task.rb:250:in `block in execute'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/task.rb:250:in `each'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/task.rb:250:in `execute'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/task.rb:194:in `block in invoke_with_call_chain'
/usr/local/rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/monitor.rb:214:in `mon_synchronize'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/task.rb:187:in `invoke_with_call_chain'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/task.rb:180:in `invoke'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/application.rb:152:in `invoke_task'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/application.rb:108:in `block (2 levels) in top_level'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/application.rb:108:in `each'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/application.rb:108:in `block in top_level'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/application.rb:117:in `run_with_threads'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/application.rb:102:in `top_level'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/application.rb:80:in `block in run'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/application.rb:178:in `standard_exception_handling'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/application.rb:77:in `run'
/usr/local/rvm/gems/ruby-2.3.1/gems/capistrano-3.8.0/lib/capistrano/application.rb:14:in `run'
/usr/local/rvm/gems/ruby-2.3.1/gems/capistrano-3.8.0/bin/cap:3:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.3.1/bin/cap:23:in `load'
/usr/local/rvm/gems/ruby-2.3.1/bin/cap:23:in `<main>'
/usr/local/rvm/gems/ruby-2.3.1/bin/ruby_executable_hooks:15:in `eval'
/usr/local/rvm/gems/ruby-2.3.1/bin/ruby_executable_hooks:15:in `<main>'
Tasks: TOP => production
</code>```

My Gemfile

```<code>source 'https://rubygems.org'

gem 'rails', '~> 5.0.2'

gem 'sqlite3'

group :development do
    gem 'capistrano',         require: false
    gem 'capistrano-rvm',     require: false
    gem 'capistrano-rails',   require: false
    gem 'capistrano-bundler', require: false
    gem 'capistrano3-puma',   require: false
end
gem 'puma', '~> 3.0'

gem 'sass-rails', '~> 5.0'

gem 'uglifier', '>= 1.3.0'

gem 'coffee-rails', '~> 4.2'

gem "font-awesome-rails"

gem 'mail_form'

# Use jquery as the JavaScript library
gem 'jquery-rails'
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platform: :mri
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console'
  gem 'listen', '~> 3.0.5'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
gem 'globalize', git: 'https://github.com/globalize/globalize'
gem 'spina', git: 'https://github.com/denkGroot/Spina'
gem 'spina-articles', git: 'https://github.com/kinnrot/spina-articles.git'
gem 'will_paginate', '~> 3.1.0'
gem 'fog'
gem 'pg'
gem "wysiwyg-rails"
</code>```

It seems the issue the Puma task inside the Deploy file.

Here is my capfile:

```<code># Load DSL and set up stages
require "capistrano/setup"
require "capistrano/deploy"
require 'capistrano/rails'
require 'capistrano/bundler'
require 'capistrano/rvm'
require 'capistrano/puma'

# Include tasks from other gems included in your Gemfile
#
# For documentation on these, see for example:
#
#   https://github.com/capistrano/rvm
#   https://github.com/capistrano/rbenv
#   https://github.com/capistrano/chruby
#   https://github.com/capistrano/bundler
#   https://github.com/capistrano/rails
#   https://github.com/capistrano/passenger
#
# require 'capistrano/rvm'
# require 'capistrano/rbenv'
# require 'capistrano/chruby'
# require 'capistrano/bundler'
# require 'capistrano/rails/assets'
# require 'capistrano/rails/migrations'
# require 'capistrano/passenger'

# Load custom tasks from `lib/capistrano/tasks` if you have any defined
Dir.glob("lib/capistrano/tasks/*.rake").each { |r| import r }
</code>```

Here is my Deploy file:

```<code># config valid only for current version of Capistrano

server 'IP', port: 22, roles: [:web, :app, :db], primary: true

set :application, 'APP'
set :repo_url, 'URL'
set :user,            'XX'
set :puma_threads,    [4, 16]
set :puma_workers,    0

# Don't change these unless you know what you're doing
set :pty,             true
set :use_sudo,        false
set :stage,           :production
set :deploy_via,      :remote_cache
set :deploy_to,       "/home/#{fetch(:user)}/apps/#{fetch(:application)}"
set :puma_bind,       "unix://#{shared_path}/tmp/sockets/#{fetch(:application)}-puma.sock"
set :puma_state,      "#{shared_path}/tmp/pids/puma.state"
set :puma_pid,        "#{shared_path}/tmp/pids/puma.pid"
set :puma_access_log, "#{release_path}/log/puma.error.log"
set :puma_error_log,  "#{release_path}/log/puma.access.log"
set :ssh_options,     { forward_agent: true, user: fetch(:user), keys: %w(~/.ssh/id_rsa.pub) }
set :puma_preload_app, true
set :puma_worker_timeout, nil
set :puma_init_active_record, true  # Change to false when not using ActiveRecord

## Defaults:
# set :scm,           :git
# set :branch,        :master
# set :format,        :pretty
# set :log_level,     :debug
# set :keep_releases, 5

## Linked Files & Directories (Default None):
# set :linked_files, %w{config/database.yml}
# set :linked_dirs,  %w{bin log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system}

namespace :puma do
  desc 'Create Directories for Puma Pids and Socket'
  task :make_dirs do
    on roles(:app) do
      execute "mkdir #{shared_path}/tmp/sockets -p"
      execute "mkdir #{shared_path}/tmp/pids -p"
    end
  end

  before :start, :make_dirs
end

namespace :deploy do
  desc "Make sure local git is in sync with remote."
  task :check_revision do
    on roles(:app) do
      unless `git rev-parse HEAD` == `git rev-parse origin/master`
        puts "WARNING: HEAD is not the same as origin/master"
        puts "Run `git push` to sync changes."
        exit
      end
    end
  end

  desc 'Initial Deploy'
  task :initial do
    on roles(:app) do
      before 'deploy:restart', 'puma:start'
      invoke 'deploy'
    end
  end

  desc 'Restart application'
  task :restart do
    on roles(:app), in: :sequence, wait: 5 do
      invoke 'puma:restart'
    end
  end

  before :starting,     :check_revision
  after  :finishing,    :compile_assets
  after  :finishing,    :cleanup
  after  :finishing,    :restart
end
</code>```

答:
Looks like it was a Capistrano-puma issue
https://github.com/seuros/capistrano-puma/issues/213

Changing the require line in my Capfile to the following worked:

```<code>require 'capistrano/puma'
install_plugin Capistrano::Puma
install_plugin Capistrano::Puma::Workers
</code>```

Body:
I've been successfully deploying with Capistrano for several months. After some updates, it stopped working.

Recently we added Spina CMS but have already deployed a version that is live. We did remove a Capistrano Lock awhile back.

If I run:

cap production deploy
(Backtrace restricted to imported tasks)
cap aborted!
Don't know how to build task 'start' (see --tasks)

Tasks: TOP => production
(See full trace by running task with --trace)

I then ran:

Daves-MBP-2:enduur dave$ cap production deploy --trace
** Invoke production (first_time)
** Execute production
** Invoke load:defaults (first_time)
** Execute load:defaults
cap aborted!
Don't know how to build task 'start' (see --tasks)
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/task_manager.rb:58:in `[]'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/task.rb:361:in `[]'
/usr/local/rvm/gems/ruby-2.3.1/gems/capistrano-3.8.0/lib/capistrano/dsl/task_enhancements.rb:7:in `before'
config/deploy.rb:48:in `block in <top (required)>'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/task_manager.rb:205:in `in_namespace'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/dsl_definition.rb:140:in `namespace'
config/deploy.rb:39:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.3.1/gems/capistrano-3.8.0/lib/capistrano/setup.rb:27:in `load'
/usr/local/rvm/gems/ruby-2.3.1/gems/capistrano-3.8.0/lib/capistrano/setup.rb:27:in `block (3 levels) in <top (required)>'
/usr/local/rvm/gems/ruby-2.3.1/gems/capistrano-3.8.0/lib/capistrano/configuration/variables.rb:32:in `untrusted!'
/usr/local/rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/delegate.rb:83:in `method_missing'
/usr/local/rvm/gems/ruby-2.3.1/gems/capistrano-3.8.0/lib/capistrano/setup.rb:26:in `block (2 levels) in <top (required)>'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/task.rb:250:in `block in execute'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/task.rb:250:in `each'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/task.rb:250:in `execute'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/task.rb:194:in `block in invoke_with_call_chain'
/usr/local/rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/monitor.rb:214:in `mon_synchronize'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/task.rb:187:in `invoke_with_call_chain'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/task.rb:180:in `invoke'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/application.rb:152:in `invoke_task'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/application.rb:108:in `block (2 levels) in top_level'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/application.rb:108:in `each'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/application.rb:108:in `block in top_level'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/application.rb:117:in `run_with_threads'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/application.rb:102:in `top_level'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/application.rb:80:in `block in run'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/application.rb:178:in `standard_exception_handling'
/usr/local/rvm/gems/ruby-2.3.1/gems/rake-12.0.0/lib/rake/application.rb:77:in `run'
/usr/local/rvm/gems/ruby-2.3.1/gems/capistrano-3.8.0/lib/capistrano/application.rb:14:in `run'
/usr/local/rvm/gems/ruby-2.3.1/gems/capistrano-3.8.0/bin/cap:3:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.3.1/bin/cap:23:in `load'
/usr/local/rvm/gems/ruby-2.3.1/bin/cap:23:in `'
/usr/local/rvm/gems/ruby-2.3.1/bin/ruby_executable_hooks:15:in `eval'
/usr/local/rvm/gems/ruby-2.3.1/bin/ruby_executable_hooks:15:in `'
Tasks: TOP => production

My Gemfile

source 'https://rubygems.org'

gem 'rails', '~> 5.0.2'

gem 'sqlite3'

group :development do
    gem 'capistrano',         require: false
    gem 'capistrano-rvm',     require: false
    gem 'capistrano-rails',   require: false
    gem 'capistrano-bundler', require: false
    gem 'capistrano3-puma',   require: false
end
gem 'puma', '~> 3.0'

gem 'sass-rails', '~> 5.0'

gem 'uglifier', '>= 1.3.0'

gem 'coffee-rails', '~> 4.2'

gem "font-awesome-rails"

gem 'mail_form'

# Use jquery as the JavaScript library
gem 'jquery-rails'
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 3.0'
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platform: :mri
end

group :development do
  # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.
  gem 'web-console'
  gem 'listen', '~> 3.0.5'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
gem 'globalize', git: 'https://github.com/globalize/globalize'
gem 'spina', git: 'https://github.com/denkGroot/Spina'
gem 'spina-articles', git: 'https://github.com/kinnrot/spina-articles.git'
gem 'will_paginate', '~> 3.1.0'
gem 'fog'
gem 'pg'
gem "wysiwyg-rails"

It seems the issue the Puma task inside the Deploy file.

Here is my capfile:

# Load DSL and set up stages
require "capistrano/setup"
require "capistrano/deploy"
require 'capistrano/rails'
require 'capistrano/bundler'
require 'capistrano/rvm'
require 'capistrano/puma'

# Include tasks from other gems included in your Gemfile
#
# For documentation on these, see for example:
#
#   https://github.com/capistrano/rvm
#   https://github.com/capistrano/rbenv
#   https://github.com/capistrano/chruby
#   https://github.com/capistrano/bundler
#   https://github.com/capistrano/rails
#   https://github.com/capistrano/passenger
#
# require 'capistrano/rvm'
# require 'capistrano/rbenv'
# require 'capistrano/chruby'
# require 'capistrano/bundler'
# require 'capistrano/rails/assets'
# require 'capistrano/rails/migrations'
# require 'capistrano/passenger'

# Load custom tasks from `lib/capistrano/tasks` if you have any defined
Dir.glob("lib/capistrano/tasks/*.rake").each { |r| import r }

Here is my Deploy file:

# config valid only for current version of Capistrano

server 'IP', port: 22, roles: [:web, :app, :db], primary: true

set :application, 'APP'
set :repo_url, 'URL'
set :user,            'XX'
set :puma_threads,    [4, 16]
set :puma_workers,    0

# Don't change these unless you know what you're doing
set :pty,             true
set :use_sudo,        false
set :stage,           :production
set :deploy_via,      :remote_cache
set :deploy_to,       "/home/#{fetch(:user)}/apps/#{fetch(:application)}"
set :puma_bind,       "unix://#{shared_path}/tmp/sockets/#{fetch(:application)}-puma.sock"
set :puma_state,      "#{shared_path}/tmp/pids/puma.state"
set :puma_pid,        "#{shared_path}/tmp/pids/puma.pid"
set :puma_access_log, "#{release_path}/log/puma.error.log"
set :puma_error_log,  "#{release_path}/log/puma.access.log"
set :ssh_options,     { forward_agent: true, user: fetch(:user), keys: %w(~/.ssh/id_rsa.pub) }
set :puma_preload_app, true
set :puma_worker_timeout, nil
set :puma_init_active_record, true  # Change to false when not using ActiveRecord

## Defaults:
# set :scm,           :git
# set :branch,        :master
# set :format,        :pretty
# set :log_level,     :debug
# set :keep_releases, 5

## Linked Files & Directories (Default None):
# set :linked_files, %w{config/database.yml}
# set :linked_dirs,  %w{bin log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system}

namespace :puma do
  desc 'Create Directories for Puma Pids and Socket'
  task :make_dirs do
    on roles(:app) do
      execute "mkdir #{shared_path}/tmp/sockets -p"
      execute "mkdir #{shared_path}/tmp/pids -p"
    end
  end

  before :start, :make_dirs
end

namespace :deploy do
  desc "Make sure local git is in sync with remote."
  task :check_revision do
    on roles(:app) do
      unless `git rev-parse HEAD` == `git rev-parse origin/master`
        puts "WARNING: HEAD is not the same as origin/master"
        puts "Run `git push` to sync changes."
        exit
      end
    end
  end

  desc 'Initial Deploy'
  task :initial do
    on roles(:app) do
      before 'deploy:restart', 'puma:start'
      invoke 'deploy'
    end
  end

  desc 'Restart application'
  task :restart do
    on roles(:app), in: :sequence, wait: 5 do
      invoke 'puma:restart'
    end
  end

  before :starting,     :check_revision
  after  :finishing,    :compile_assets
  after  :finishing,    :cleanup
  after  :finishing,    :restart
end

Body:
Looks like it was a Capistrano-puma issue
https://github.com/seuros/capistrano-puma/issues/213

Changing the require line in my Capfile to the following worked:

require 'capistrano/puma'
install_plugin Capistrano::Puma
install_plugin Capistrano::Puma::Workers


问:
Issues with using ggplot
I am facing some issues with using 'ggplot' function. I have the data table (Crop_cond) as shown in the image. I am using the following code to obtain a bar plot as shown in the image below.

I was able to obtain the graph but I want to obtain the plot far below here. I want to flip the colors. Any suggestions.

My plot:
[![enter image description here][1]][1]

[![enter image description here][2]][2]

[![enter image description here][3]][3]

答:
looks to me that you need stat="identity" to tell geom_bar that you are directly use the value instead of doing counting.

```<code>ggplot(Crop_cond, aes(x = END_CODE, y = VALUE)) +
  geom_bar(aes(fill = CONDITION),stat = "identity",position="fill")
</code>```

Title: Issues with using ggplot

Body:
looks to me that you need stat="identity" to tell geom_bar that you are directly use the value instead of doing counting.

ggplot(Crop_cond, aes(x = END_CODE, y = VALUE)) +
  geom_bar(aes(fill = CONDITION),stat = "identity",position="fill")


问:
How can I show only the first result in ng-repeat
I have an ecommerce angularjs project that uses ng-repeat. On a product detail page, I am getting more than 1 result. So I have to use ng-repeat.

How can I show only the first result/array of the response?

My response looks like this:

What I want to do is just show that first response [0]. I don't want to show the 2nd array until later.

Controller:

```<code>unarcoQS.controller ('prodCtrl', ['$scope', 'productService', 'ngCart',
'$route', '$routeParams', '$resource', function($scope, productService, ngCart,
$route, $routeParams, $resource)
{
id = $routeParams.PartNumber;

productService.query({PartNumber: id}, function(response){
   $scope.products = response;
});
</code>```

HTML:

```<code><div class="col-md-7" ng-repeat="product in products">
    <div class="product-title">{{product[0].Description}}</div>
    <div class="product-desc">{{product[0].Category}}</div>
</div>
</code>```

答:
You can use

 product in products[0]

 product in products ng-show="$index ==0"

 product in product | limitTo:1
Choose one and use

Body:
I have an ecommerce angularjs project that uses ng-repeat. On a product detail page, I am getting more than 1 result. So I have to use ng-repeat.

How can I show only the first result/array of the response?

My response looks like this:

What I want to do is just show that first response [0]. I don't want to show the 2nd array until later.

Controller:

unarcoQS.controller ('prodCtrl', ['$scope', 'productService', 'ngCart',
'$route', '$routeParams', '$resource', function($scope, productService, ngCart,
$route, $routeParams, $resource)
{
id = $routeParams.PartNumber;

productService.query({PartNumber: id}, function(response){
   $scope.products = response;
});

HTML:

{{product[0].Description}}

{{product[0].Category}}