问:
emulate a function that propagate into every field like operator= and destructor
As I understand, there are some special functions that propagate to every field members by default.    :-

copy assignment, copy constructor, move assignment, move constructor, destructor, etc.

```<code>class B{};
class C{B b;};
C c1;  C c2;
c1=c2; //<-- automatic invoke B::operator=()
</code>```

Is it possible to deploy some C++ trick to create/emulate a custom function that has such a cool feature?

If no, it is a complete answer.

If yes, please show demo ; I believe it should be a free function e.g. :-

```<code>class A{};
class B{};
void f(A a){}
class C{public: A a;B b;};
//no need to code "void f(C c){f(c.a);}"
C c1;
f(c1);  //<-- automatic invoke f(c1.a), but not invoke f(c1.b)
</code>```

Template function and SFINAE might be useful but I don't know how to apply in this case.

I think it may be useful for some more advance RAII.

答:
Write as_tie:

```<code>struct C{
  A a;
  B b;
  friend auto as_tie(C& c){
    return std::tie(c.a, c.b);
  }
};
</code>```

you need to write this for every type you want to interact with in this way; there is no way to avoid that until compile-time reflection arrives in C++.  However, as_tie makes things like ==, swap, and the like easy to implement, so you get bonus payoff.

After that, a mixture of foreach-tuple-element, override set objects, y-combinators, and invoke-if-possible gives you the ability to say "recursively apply f to each of its members".

Barring you having to do this dozens of times in a variety of contexts, it won't be worth it.

In short, no, not really.  But maybe sorta with a lot of work.

Body:
As I understand, there are some special functions that propagate to every field members by default.    :-

copy assignment, copy constructor, move assignment, move constructor, destructor, etc.

class B{};
class C{B b;};
C c1;  C c2;
c1=c2; //<-- automatic invoke B::operator=()

Is it possible to deploy some C++ trick to create/emulate a custom function that has such a cool feature?

If no, it is a complete answer.

If yes, please show demo ; I believe it should be a free function e.g. :-

class A{};
class B{};
void f(A a){}
class C{public: A a;B b;};
//no need to code "void f(C c){f(c.a);}"
C c1;
f(c1);  //<-- automatic invoke f(c1.a), but not invoke f(c1.b)

Template function and SFINAE might be useful but I don't know how to apply in this case.

I think it may be useful for some more advance RAII.

Body:
Write as_tie:

struct C{
  A a;
  B b;
  friend auto as_tie(C& c){
    return std::tie(c.a, c.b);
  }
};

you need to write this for every type you want to interact with in this way; there is no way to avoid that until compile-time reflection arrives in C++.  However, as_tie makes things like ==, swap, and the like easy to implement, so you get bonus payoff.

After that, a mixture of foreach-tuple-element, override set objects, y-combinators, and invoke-if-possible gives you the ability to say "recursively apply f to each of its members".

Barring you having to do this dozens of times in a variety of contexts, it won't be worth it.

In short, no, not really.  But maybe sorta with a lot of work.


来源: stackexchange

问:
Retaining n most recent directories in a backup script
I have directory in /home/backup/ that stores yearly backups. Inside the backup folder, we have these directories:

```<code>/home/backup/2012
/home/backup/2013
/home/backup/2014
/home/backup/2015
/home/backup/2016
/home/backup/2017
</code>```

and every year I have to clean up the data, keeping only the last three years of backup.

In the above case, I have to delete:

```<code>/home/backup/2012
/home/backup/2013
/home/backup/2014
</code>```

What is the best way to find the directories to be deleted?  I have this but it doesn't work:

```<code>find /home/ecentrix/recording/ -maxdepth 1 -mindepth 1 -type d -ctime +1095 -exec rm -rf {} \;
</code>```

Do you guys have another idea to do that?

答:
Solution

```<code># Check if extended globbing is on
shopt extglob

# If extended globbing is off, run this line
shopt -s extglob

# Remove all files except 2015, 2016, and 2017
rm -r -i /home/backup/!(2015|2016|2017)

# Turn off extended globbing (optional)
shop -u extglob
</code>```

Explanation

shopt -s extglob allows you to match any files except the ones inside !(...). So that line means remove any file in /home/backup except 2015, 2016, or 2017.

The -i flag in rm -r -i ... allows you to interactively confirm the removal of each file. Remove -i if you want the files to be removed automatically.

Dynamic Dates

This solution is valid for automation (e.g. cron jobs)

```<code># Number of latest years to keep
LATEST_YEARS=3

# Get the current year
current_year=$(date '+%Y')

# Get the first/earliest year to keep
first_year=$(( current_year - $(($LATEST_YEARS - 1)) ))

# Turn on extended globbing
shopt -s extglob

# Store years to keep in an array
keep_years=( $(seq $first_year $current_year) )

# Specify files to keep
rm -r /home/backup/!(${keep_years[0]}|${keep_years[1]}|${keep_years[2]})
</code>```

NOTE: ALL FILES IN BACKUP DIRECTORY WILL BE REMOVED EXCEPT LAST 3 YEARS

ContentLicense: CC BY-SA 3.0

Body:
I have directory in /home/backup/ that stores yearly backups. Inside the backup folder, we have these directories:

/home/backup/2012
/home/backup/2013
/home/backup/2014
/home/backup/2015
/home/backup/2016
/home/backup/2017

and every year I have to clean up the data, keeping only the last three years of backup.

In the above case, I have to delete:

/home/backup/2012
/home/backup/2013
/home/backup/2014

What is the best way to find the directories to be deleted?  I have this but it doesn't work:

find /home/ecentrix/recording/ -maxdepth 1 -mindepth 1 -type d -ctime +1095 -exec rm -rf {} \;

Do you guys have another idea to do that?

Body:
Solution

# Check if extended globbing is on
shopt extglob

# If extended globbing is off, run this line
shopt -s extglob

# Remove all files except 2015, 2016, and 2017
rm -r -i /home/backup/!(2015|2016|2017)

# Turn off extended globbing (optional)
shop -u extglob

Explanation

shopt -s extglob allows you to match any files except the ones inside !(...). So that line means remove any file in /home/backup except 2015, 2016, or 2017.

The -i flag in rm -r -i ... allows you to interactively confirm the removal of each file. Remove -i if you want the files to be removed automatically.

Dynamic Dates

This solution is valid for automation (e.g. cron jobs)

# Number of latest years to keep
LATEST_YEARS=3

# Get the current year
current_year=$(date '+%Y')

# Get the first/earliest year to keep
first_year=$(( current_year - $(($LATEST_YEARS - 1)) ))

# Turn on extended globbing
shopt -s extglob

# Store years to keep in an array
keep_years=( $(seq $first_year $current_year) )

# Specify files to keep
rm -r /home/backup/!(${keep_years[0]}|${keep_years[1]}|${keep_years[2]})

NOTE: ALL FILES IN BACKUP DIRECTORY WILL BE REMOVED EXCEPT LAST 3 YEARS


问:
Widgets next to each other same size in Qt
I have two widgets, one arbitrary (usually a QLineEdit), and one QLabel which displays a Pixmap. They are placed next to each other with a QHBoxLayout. The widget with this layout is in turn placed in another layout.

Now, what I want is that the label with the pixmap is automatically resized so that it is as high as the arbitrary widget next to it. However, even when I set the label's sizePolicy to Maximum, it still seems to expand to the  original pixmap size, instead of resizing the pixmap and shrinking to match the other widget. Instead of having two equally large widgets I have the arbitrary one which is smaller than the pixmap next to it.

Any ideas how to get the size of the pixmap label to match the size of the widget next to it?

答:
How about:</p>

```<code>int height = arbitraryWidget->height();             // get desired height.

label->setSizeHint(QSize(label->width(), height);   // set size hint to current width and desired height.
label->setSizePolicy(QSizePolicy::Fixed);           // optional, but this ensures size is desired.
</code>```

ContentLicense: CC BY-SA 2.5

Body:
How about:

int height = arbitraryWidget->height();             // get desired height.

label->setSizeHint(QSize(label->width(), height);   // set size hint to current width and desired height.
label->setSizePolicy(QSizePolicy::Fixed);           // optional, but this ensures size is desired.


问:
Nexus 3 Rest api to check if component exist
Maybe I miss something but i can't find a way to upload a component(jar or dll) to the nexus 3 repository from the UI. So I am trying to build a tool for this job, to optimize the upload process I need a way to check if component exist in the nexus repository programmatically, all my tries to find suitable rest api failed.

Anyone have suggestions?

答:
Maybe you can upload a groovy script and use that script to check whether the component exists or not.</p>

```<code>import org.sonatype.nexus.repository.storage.Query;
import org.sonatype.nexus.repository.storage.StorageFacet;
import groovy.json.JsonOutput;

def repositoryId = args.split(',')[0];
def groupId = args.split(',')[1];
def artifactId = args.split(',')[2];
def baseVersion = args.split(',')[3];
def latestOnly = args.split(',')[4];

def repo = repository.repositoryManager.get(repositoryId);
StorageFacet storageFacet = repo.facet(StorageFacet);
def tx = storageFacet.txSupplier().get();

tx.begin();
def components = tx.findComponents(Query.builder().where('group = ').param(groupId).and('name = ').param(artifactId).build(), [repo]);

def found = components.findAll{it.attributes().child('maven2').get('baseVersion')==baseVersion}.collect{
def version = it.attributes().child('maven2').get('version');\"${version}\"};

// found = found.unique().sort();
def latest = found.isEmpty() ? found : found.last();

tx.commit();
def result = latestOnly == 'latest' ? JsonOutput.toJson(latest) : JsonOutput.toJson(found);

return result;
</code>```

Body:
Maybe you can upload a groovy script and use that script to check whether the component exists or not.

import org.sonatype.nexus.repository.storage.Query;
import org.sonatype.nexus.repository.storage.StorageFacet;
import groovy.json.JsonOutput;

def repositoryId = args.split(',')[0];
def groupId = args.split(',')[1];
def artifactId = args.split(',')[2];
def baseVersion = args.split(',')[3];
def latestOnly = args.split(',')[4];

def repo = repository.repositoryManager.get(repositoryId);
StorageFacet storageFacet = repo.facet(StorageFacet);
def tx = storageFacet.txSupplier().get();

tx.begin();
def components = tx.findComponents(Query.builder().where('group = ').param(groupId).and('name = ').param(artifactId).build(), [repo]);

def found = components.findAll{it.attributes().child('maven2').get('baseVersion')==baseVersion}.collect{
def version = it.attributes().child('maven2').get('version');\"${version}\"};

// found = found.unique().sort();
def latest = found.isEmpty() ? found : found.last();

tx.commit();
def result = latestOnly == 'latest' ? JsonOutput.toJson(latest) : JsonOutput.toJson(found);

return result;


问:
Populating React-Native ListView from JSON Data
React-Native amateur here, I've written a php api to retrieve data from a MySQL server, and I need to put this into a ListView to display on an app.

The code for showing this is:

constructor(props) {
    super(props);
    var ds = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1 !== r2
    });
    this.state = {
      dataSource: ds.cloneWithRows(this.props.response)
    };
  }

  renderRow(rowData) {
      return (
        <View style={styles.row}>
        <Text>{response}</Text>
        </View>
        )
    }

    render() {
      return {
        <ListView
          dataSource={this.state.dataSource}
          renderRow={this.renderRow.bind(this)}/>
      );
    }
  }```
</div>
</div>
</p>

<p>And the API json return is as follows:</p>

```[{"barcode":"50201600","name":"Cadbury's Creme
Egg","tescoPrice":"1","sainsburysPrice":"1","asdaPrice":"1"},
{"barcode":"5034660520191","name":"Cadburys Twirl 4
Pack","tescoPrice":"1","sainsburysPrice":"1","asdaPrice":"1"}]
```

The error I get is:Objects are not valid as a React child (found: object with keys {barcode, name, tescoPrice, sainsburysPrice, asdaPrice}). If you meant to render a collection of children, use an array instead. Check the render method of 'Text'

Any ideas?

Cheers

答:
From the error i see, you need to change from:

renderRow(rowData) {
  return (
    <View style={styles.row}>
      <Text>{response}</Text>
    </View>
 )
}```
</div>
</div>
</p>

<p>into something like:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>    renderRow(rowData) {
      return (
        <View style={styles.row}>
          <Text>{rowData.name}</Text>
        </View>
     )
    }</code>```

Body:
React-Native amateur here, I've written a php api to retrieve data from a MySQL server, and I need to put this into a ListView to display on an app.

The code for showing this is:

constructor(props) {
    super(props);
    var ds = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1 !== r2
    });
    this.state = {
      dataSource: ds.cloneWithRows(this.props.response)
    };
  }

  renderRow(rowData) {
      return (
        <View style={styles.row}>
        <Text>{response}</Text>
        </View>
        )
    }

    render() {
      return {
        <ListView
          dataSource={this.state.dataSource}
          renderRow={this.renderRow.bind(this)}/>
      );
    }
  }

And the API json return is as follows:

[{"barcode":"50201600","name":"Cadbury's Creme
Egg","tescoPrice":"1","sainsburysPrice":"1","asdaPrice":"1"},
{"barcode":"5034660520191","name":"Cadburys Twirl 4
Pack","tescoPrice":"1","sainsburysPrice":"1","asdaPrice":"1"}]

The error I get is:Objects are not valid as a React child (found: object with keys {barcode, name, tescoPrice, sainsburysPrice, asdaPrice}). If you meant to render a collection of children, use an array instead. Check the render method of 'Text'

Any ideas?

Cheers

Body:
From the error i see, you need to change from:

renderRow(rowData) {
  return (
    <View style={styles.row}>
      <Text>{response}</Text>
    </View>
 )
}

into something like:

    renderRow(rowData) {
      return (
        <View style={styles.row}>
          <Text>{rowData.name}</Text>
        </View>
     )
    }


问:
How to solve: Use of unresolved identifier 'indexPath' in Swift
```<code>func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
    return interests.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt cellForItemAtindexPath: IndexPath) -> UICollectionViewCell
{
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Storyboard.CellIdentifier, forIndexPath:indexPath) as! InterestCollectionViewCell

    cell.interest = self.interest[indexPath.item]

    return cell
}
</code>```

答:
Change to this:

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Storyboard.CellIdentifier, forIndexPath:indexPath) as! InterestCollectionViewCell

    cell.interest = self.interest[indexPath.item]

    return cell
}
</code>```

UPDATE

And if this is the UICollectionView function you also needs to add the override keyword before func

```<code>override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Storyboard.CellIdentifier, forIndexPath:indexPath) as! InterestCollectionViewCell

    cell.interest = self.interest[indexPath.item]

    return cell
}
</code>```

Body:
Change to this:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Storyboard.CellIdentifier, forIndexPath:indexPath) as! InterestCollectionViewCell

    cell.interest = self.interest[indexPath.item]

    return cell
}

UPDATE

And if this is the UICollectionView function you also needs to add the override keyword before func

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Storyboard.CellIdentifier, forIndexPath:indexPath) as! InterestCollectionViewCell

    cell.interest = self.interest[indexPath.item]

    return cell
}


问:
What are callback classes in ActiveRecord::Base in Rails
Can some one explain 16 Callback classes in this guide http://guides.rubyonrails.org/active_record_validations_callbacks.html</p>

答:
everything works by convention, you can try the following example:</p>

```<code>#generate PictrueFile model with name attribute and generate seed
rails g model PictureFile name:string
#seeds.rb
3.times do |i|
  PictureFile.create(name: "name#{i}")
end

#create picture_file.rb and picture_file_callbacks.rb in model directory
#picture_file_callbacks.rb
class PictureFileCallbacks
  def after_destroy(picture_file)
    PictureFile.create(name: "demo")
  end
end

#picture_file_callbacks.rb
class PictureFile < ApplicationRecord
  after_destroy PictureFileCallbacks.new
end

execute the command in rails c
PictureFile.first.destroy
PictrueFile.pluck(:name) #=>["name1", "name2", "demo"]
</code>```

Body:
everything works by convention, you can try the following example:

#generate PictrueFile model with name attribute and generate seed
rails g model PictureFile name:string
#seeds.rb
3.times do |i|
  PictureFile.create(name: "name#{i}")
end

#create picture_file.rb and picture_file_callbacks.rb in model directory
#picture_file_callbacks.rb
class PictureFileCallbacks
  def after_destroy(picture_file)
    PictureFile.create(name: "demo")
  end
end

#picture_file_callbacks.rb
class PictureFile < ApplicationRecord
  after_destroy PictureFileCallbacks.new
end

execute the command in rails c
PictureFile.first.destroy
PictrueFile.pluck(:name) #=>["name1", "name2", "demo"]


问:
Nginx Static Content 404 Error on Every File Except Index
I have nginx 1.4.6 running  on an ubuntu 16.04 server.  My content consists of two files in the folder /var/www/html/, index.html and test.html.  All files are chmod'ed to 755 and belong to the user www-data.  My nginx.conf:

```<code>user www-data;
worker_processes auto;
pid /run/nginx.pid;

events {
        worker_connections 768;
}

http {
        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers on;

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        gzip on;
        gzip_disable "msie6";

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
}
</code>```

My configuration file in /etc/nginx/sites-enabled/:

```<code>server {
      listen 80;

      root /var/www/html/;
      index index.html index.htm;

      server_name example.com;

      location / {

      }
}
</code>```

When I browse to http://example.com/ (not the real hostname), I see the contents of index.html (yay).  When I browse to http://example.com/test.html I get HTTP 404.  I get this when I try to use curl, and any browser.

A lot of the other questions on this site (and on serverfault) seem to indicate problems serving static content with rewrite rules or a combination with reverse proxying to other services.  I just want to be able to serve the most simple static site imaginable.

Both the access.log and error.log do not even show that any requests are coming through.   The log files are both owned by and allow write access by user www-data.

答:
In your current configuration on accessing example.com the control will be

 going to location / block there you have no entry point mentioned, hence

change the configuration to

```<code>server {
      listen 80;

      root /var/www/html/;
      index index.html index.htm;

      server_name example.com;

}
</code>```

or

```<code>server {
      listen 80;
      index index.html index.htm;
      server_name example.com;

      location /{
        # you can use alias instead
        root /var/www/html/;
      }

}
</code>```

Body:
I have nginx 1.4.6 running  on an ubuntu 16.04 server.  My content consists of two files in the folder /var/www/html/, index.html and test.html.  All files are chmod'ed to 755 and belong to the user www-data.  My nginx.conf:

user www-data;
worker_processes auto;
pid /run/nginx.pid;

events {
        worker_connections 768;
}

http {
        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers on;

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        gzip on;
        gzip_disable "msie6";

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
}

My configuration file in /etc/nginx/sites-enabled/:

server {
      listen 80;

      root /var/www/html/;
      index index.html index.htm;

      server_name example.com;

      location / {

      }
}

When I browse to http://example.com/ (not the real hostname), I see the contents of index.html (yay).  When I browse to http://example.com/test.html I get HTTP 404.  I get this when I try to use curl, and any browser.

A lot of the other questions on this site (and on serverfault) seem to indicate problems serving static content with rewrite rules or a combination with reverse proxying to other services.  I just want to be able to serve the most simple static site imaginable.

Both the access.log and error.log do not even show that any requests are coming through.   The log files are both owned by and allow write access by user www-data.

Body:
In your current configuration on accessing example.com the control will be

 going to location / block there you have no entry point mentioned, hence

change the configuration to

server {
      listen 80;

      root /var/www/html/;
      index index.html index.htm;

      server_name example.com;

}

or

server {
      listen 80;
      index index.html index.htm;
      server_name example.com;

      location /{
        # you can use alias instead
        root /var/www/html/;
      }

}


问:
Spring-Boot + Velocity generate exception at startup
I am currently testing using Spring-Boot to deploy a Freemarker application.
I fact my simple test is working fine. But in my log I see the following exception and I wonder what it could be:

```<code>2014-08-14 15:03:26.774 +0000 DEBUG         [                main]    [o.s.w.servlet.view.freemarker.FreeMarkerConfigurer:346] -  Cannot resolve template loader path [classpath:/templates/] to [java.io.File]: using SpringTemplateLoader as fallback
java.io.FileNotFoundException: class path resource [templates/] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/jre/lib/htmlconverter.jar!/templates/
at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:207) ~[spring-core-4.0.6.RELEASE.jar:4.0.6.RELEASE]
</code>```

But my templates are correctly used. Is that exception "normal"?
Note that we are not using the Spring-Boot parent pom. We are using our own parent.

答:
Add configuration below would solve the problem!

spring.velocity.prefer-file-system-access=false
spring.velocity.prefix=/templates

Body:
I am currently testing using Spring-Boot to deploy a Freemarker application.
I fact my simple test is working fine. But in my log I see the following exception and I wonder what it could be:

2014-08-14 15:03:26.774 +0000 DEBUG         [                main]    [o.s.w.servlet.view.freemarker.FreeMarkerConfigurer:346] -  Cannot resolve template loader path [classpath:/templates/] to [java.io.File]: using SpringTemplateLoader as fallback
java.io.FileNotFoundException: class path resource [templates/] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home/jre/lib/htmlconverter.jar!/templates/
at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:207) ~[spring-core-4.0.6.RELEASE.jar:4.0.6.RELEASE]

But my templates are correctly used. Is that exception "normal"?
Note that we are not using the Spring-Boot parent pom. We are using our own parent.


问:
How to parse java method body?
I want to parse java source files (.java) in order to identify methods, in a class, that contain calls to a specific method.

In the below example, I need to know which methods contain a call to xyz(). So, the parser should return method01 and method03

```<code>public class A{
    private void method01(){
        //some statements
        xyz();
        //more statements
    }

    private void method02(){
        //some statements
        xyz123();
        //more statements
    }

    private void method03(){
        //some statements
        xyz();
        //more statements
    }
}
</code>```

I tried using javaparser (com.github.javaparser). I created a vistor and by overriding

```<code>public void visit(MethodDeclaration n, Void arg)
</code>```

I am able to “visit” all methods in the class.

But I don't know how to parse the body of the visted method. I’m reluctant to use  n.getBody().toString().contains(“xyz()”)

答:
By inspecting the Javadoc, it looks like you could do something like this:

```<code>private MethodDeclaration currentMethod = null;

@Override
public void visit(MethodDeclaration n, Void arg) {
    currentMethod = n;
    super.visit(n, arg);
    currentMethod = null;
}

@Override
public void visit(MethodCallExpr n, Void arg) {
    super.visit(n, arg);
    if (currentMethod != null && n.getName().asString().equals("xyz") {
        // Found an invocation of xyz in method this.currentMethod
    }
}
</code>```

The code above keeps track of the current method and finds when a method call is visited that matches the name "xyz"

Title: How to parse java method body?

Body:
I want to parse java source files (.java) in order to identify methods, in a class, that contain calls to a specific method.

In the below example, I need to know which methods contain a call to xyz(). So, the parser should return method01 and method03

public class A{
    private void method01(){
        //some statements
        xyz();
        //more statements
    }

    private void method02(){
        //some statements
        xyz123();
        //more statements
    }

    private void method03(){
        //some statements
        xyz();
        //more statements
    }
}

I tried using javaparser (com.github.javaparser). I created a vistor and by overriding

public void visit(MethodDeclaration n, Void arg)

I am able to “visit” all methods in the class.

But I don't know how to parse the body of the visted method. I’m reluctant to use  n.getBody().toString().contains(“xyz()”)

Body:
By inspecting the Javadoc, it looks like you could do something like this:

private MethodDeclaration currentMethod = null;

@Override
public void visit(MethodDeclaration n, Void arg) {
    currentMethod = n;
    super.visit(n, arg);
    currentMethod = null;
}

@Override
public void visit(MethodCallExpr n, Void arg) {
    super.visit(n, arg);
    if (currentMethod != null && n.getName().asString().equals("xyz") {
        // Found an invocation of xyz in method this.currentMethod
    }
}

The code above keeps track of the current method and finds when a method call is visited that matches the name "xyz"


问:
Java overloading and overriding
We always say that method overloading is static polymorphism and overriding is runtime polymorphism. What exactly do we mean by static here? Is the call to a method resolved on compiling the code? So whats the difference between normal method call and calling a final method? Which one is linked at compile time?</p>

答:
Method Overloading simply means providing two separate methods in a class with the same name but different arguments while method return type may or may not be different which allows us to reuse the same method name.

But both methods are different hence can be resolved by compiler at compile time that's is why it is also known as Compile Time Polymorphism or Static Polymorphism

Method Overriding means defining a method in the child class which is already defined in the parent class with same method signature i.e same name, arguments and return type.

```<code>Mammal mammal = new Cat();
System.out.println(mammal.speak());
</code>```

At the line mammal.speak() compiler says the speak() method of reference type Mammal is getting called, so for compiler this call is Mammal.speak().

But at the execution time JVM knows clearly that mammal reference is holding the reference of object of Cat, so for JVM this call is Cat.speak().

Because method call is getting resolved at runtime by JVM that's why it is also known as Runtime Polymorphism and Dynamic Method Dispatch.

Difference Between Method Overloading and Method Overriding

For more details, you can read Everything About Method Overloading Vs Method Overriding.

Title: Java overloading and overriding

Body:
Method Overloading simply means providing two separate methods in a class with the same name but different arguments while method return type may or may not be different which allows us to reuse the same method name.

But both methods are different hence can be resolved by compiler at compile time that's is why it is also known as Compile Time Polymorphism or Static Polymorphism

Method Overriding means defining a method in the child class which is already defined in the parent class with same method signature i.e same name, arguments and return type.

Mammal mammal = new Cat();
System.out.println(mammal.speak());

At the line mammal.speak() compiler says the speak() method of reference type Mammal is getting called, so for compiler this call is Mammal.speak().

But at the execution time JVM knows clearly that mammal reference is holding the reference of object of Cat, so for JVM this call is Cat.speak().

Because method call is getting resolved at runtime by JVM that's why it is also known as Runtime Polymorphism and Dynamic Method Dispatch.

Difference Between Method Overloading and Method Overriding

For more details, you can read Everything About Method Overloading Vs Method Overriding.


问:
Is there any ActionScript 3 to JavaScript (and vice versa) migration guide?
as a skilled AS3 developer I wonder if there is something like AS3 to JS migration guide. After all both languages have a lot in common.

I have in mind something like the old AS2 to AS3 migration guide - a list where I could simply look up the AS3 functionality and the JS counterpart, or vice versa.

I am not saying you can easily convert all your code like that but it would tell me where to start.

PS: I think it is a great idea and if such guide doesn't exist someone should write one :).

答:
You're going to have a difficult time of this considering a lot of the flash.* packages don't have any native JavaScript counterparts. Maybe a robust JavaScript library can ease the transition, but there will be a lot not migrate-able.

However, many of the Top-level datatypes do have a JavaScript counterpart (i.e; Date, Array, String, Object, null, Number/Integer)


问:
The JS arent working on my Rails project
so, i get that form HTML template:
https://codepen.io/colorlib/pen/rxddKy

but after implemented, it arent working ):

The login View:

```<code><% if flash[:notice] %>
    <div class="notice"><%= flash[:notice] %></div> <% end %>

<div class="login-page">   <div class="form">
    <form class="register-form">
      <input type="text" name="login[email]" placeholder="Email"/>
      <input type="password" name="login[senha]" placeholder="Senha"/>
      <button>Cadastrar</button>
      <p class="message">Já é registrado? <a href="#">Login</a></p>
    </form>
    <form class="login-form" action="/login/acessorecebendo" method="post">
      <input type="text" name="login[email]" placeholder="email"/>
      <input type="password" name="login[senha]" placeholder="password"/>
      <button>login</button>
      <p class="message">Não está registrado <a href="#">Criar uma conta</a></p>
    </form>
    <% if session[:user] %>
        <a href="/login/sair">Sair sessão <%= @user.nome %> </a>
    <% end %>   </div> </div>
</code>```

the login JS:

```<code>$(document).ready(function(){
    $('.message a').click(function(){
        $('form').animate({height: "toggle", opacity: "toggle"}, "slow");
    });
});
</code>```

the application.js are with:

```<code>//= require jquery
//= require rails-ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree .
</code>```

and also, i've been included the gem 'jquery' on my gemfile.

Nothing is happing when i click on the hiperlink "create account":
https://s13.postimg.org/8wzhw1tjr/Screenshot_20170606_224605.png

The CTRL+U on the browser:

```<code><!DOCTYPE html>
<html>
  <head>
    <title>V2Michel</title>
    <meta name="csrf-param" content="authenticity_token" />
<meta name="csrf-token" content="D47bHUTHcwdqpFlaiDZA3LJr4236jZSSppt9q/FBwK0DPDmc76zIcsfeZSlBMFVJUNxqpFM0u/kM/AfhdNePXw==" />

    <link rel="stylesheet" media="all" href="/assets/fornecedors.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload" />
<link rel="stylesheet" media="all" href="/assets/home.self-d58d58b8f163d83cd8eab0042d14c22afb73ea76b61d7cd85bca19a5d2eee2ce.css?body=1" data-turbolinks-track="reload" />
<link rel="stylesheet" media="all" href="/assets/login.self-a6ac1a027c5fa2959e7c8dc0a7e2483f324f0b0833b337aa2c9560848d55a040.css?body=1" data-turbolinks-track="reload" />
<link rel="stylesheet" media="all" href="/assets/produtos.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload" />
<link rel="stylesheet" media="all" href="/assets/scaffolds.self-2404dddc0e44f7051d6852d95406118fcf78ccd9df57e634c29cf011ebdb47cb.css?body=1" data-turbolinks-track="reload" />
<link rel="stylesheet" media="all" href="/assets/application.self-451e5f1e26abd1c402b1a9c60a4af0e0d30f25a334b1266b6270d9fe17346210.css?body=1" data-turbolinks-track="reload" />
    <script src="/assets/jquery.self-bd7ddd393353a8d2480a622e80342adf488fb6006d667e8b42e4c0073393abee.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/jquery_ujs.self-784a997f6726036b1993eb2217c9cb558e1cbb801c6da88105588c56f13b466a.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/rails-ujs.self-56055fe2ac3f3902deb9d12c17b2d725d432162b48fc443946daf7dfbc96d88a.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/turbolinks.self-1d1fddf91adc38ac2045c51f0a3e05ca97d07d24d15a4dcbf705009106489e69.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/bootstrap/transition.self-6ad2488465135ab731a045a8ebbe3ea2fc501aed286042496eda1664fdd07ba9.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/bootstrap/alert.self-742145c5bb847aafdadc6e339be795628f8bc25f177e851f03a8c42278eb0312.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/bootstrap/button.self-126ac9bf0e7f2d8568f8da3a00fd5f0fac6eae0946331003370161fbf8d7975e.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/bootstrap/carousel.self-e47323f363ceb3dc0bdbce05e36e709ed428e339833a41140a85cb0af24b8127.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/bootstrap/collapse.self-2eb697f62b587bb786ff940d82dd4be88cdeeaf13ca128e3da3850c5fcaec301.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/bootstrap/dropdown.self-561cca1cbaf67474e01e9536f106bad541594860a6df997004591c1c1957a147.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/bootstrap/modal.self-3e78617ade5663314b7ee0ea10375a5b34d59ffbade44939e3f2a4e4ef2019b3.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/bootstrap/tab.self-5bf7078b682f8b131332eefa46b45fa5eff2eca745fc0d03e2991450888f7c28.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/bootstrap/affix.self-6d6f1a7fc5c8aabf3547fa1b794fab6268f54bc55ad815e55873c71f52513517.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/bootstrap/scrollspy.self-969f3c5f48cdf1e439c7fa1154c13b948715f5c689f87837c0b64521d3b46ef6.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/bootstrap/tooltip.self-05afb177e08f98997ccfc84fa08a215e4b27d48d5fe4d049080675e9dffd8199.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/bootstrap/popover.self-0aa93860b59fe7393f1dd490f54b3cb994f9d6155adffce034d4e14ae361b041.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/bootstrap-sprockets.self-fbfa5ad7d9aa0afe439ec4ff3883acc4cb92b62cb67c40d674320c9aa1d4642d.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/action_cable.self-be3674a79bb9d13d41d259b2c17fad23aef20946dab3603b9d02374ea795005f.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/cable.self-8484513823f404ed0c0f039f75243bfdede7af7919dda65f2e66391252443ce9.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/fornecedors.self-877aef30ae1b040ab8a3aba4e3e309a11d7f2612f44dde450b5c157aa5f95c05.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/home.self-877aef30ae1b040ab8a3aba4e3e309a11d7f2612f44dde450b5c157aa5f95c05.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/login.self-144986660d26a713be586866e762e4bc122ae13576cf144f04c7bf36ee4dcc31.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/produtos.self-877aef30ae1b040ab8a3aba4e3e309a11d7f2612f44dde450b5c157aa5f95c05.js?body=1" data-turbolinks-track="reload"></script>
<script src="/assets/application.self-d9c1df0d36a69bf8167ebb20070284ed3c5f931e7f6efe185b0936aad00629a6.js?body=1" data-turbolinks-track="reload"></script>
  </head>

  <body>

<div class="login-page">
  <div class="form">
    <form class="register-form">
      <input type="text" name="login[email]" placeholder="Email"/>
      <input type="password" name="login[senha]" placeholder="Senha"/>
      <button>Cadastrar</button>
      <p class="message">Já é registrado? <a href="#">Login</a></p>
    </form>
    <form class="login-form" action="/login/acessorecebendo" method="post">
      <input type="text" name="login[email]" placeholder="email"/>
      <input type="password" name="login[senha]" placeholder="password"/>
      <button>login</button>
      <p class="message">Não está registrado <a href="#">Criar uma conta</a></p>
    </form>
  </div>
</div>
  </body>
</html>
</code>```

I've deleted the attribute href on the hiperlink "create account" and Works ! lololol

答:
It's definitely something messing with your assets, I copied your code and modified it to take script and style, since the ctrl+u don't bring it. It's working!

Next step you can ctrl+s in your page, save all assets together the ctrl+u and publish it somewhere, I will check it tomorrow if you want ^^

My code

```<code><!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

    <style>
        @import url(https://fonts.googleapis.com/css?family=Roboto:300);

        .login-page {
            width: 360px;
            padding: 8% 0 0;
            margin: auto;
        }

        .form {
            position: relative;
            z-index: 1;
            background: #FFFFFF;
            max-width: 360px;
            margin: 0 auto 100px;
            padding: 45px;
            text-align: center;
            box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24);
        }

        .form input {
            font-family: "Roboto", sans-serif;
            outline: 0;
            background: #f2f2f2;
            width: 100%;
            border: 0;
            margin: 0 0 15px;
            padding: 15px;
            box-sizing: border-box;
            font-size: 14px;
        }

        .form button {
            font-family: "Roboto", sans-serif;
            text-transform: uppercase;
            outline: 0;
            background: #4CAF50;
            width: 100%;
            border: 0;
            padding: 15px;
            color: #FFFFFF;
            font-size: 14px;
            -webkit-transition: all 0.3 ease;
            transition: all 0.3 ease;
            cursor: pointer;
        }

        .form button:hover, .form button:active, .form button:focus {
            background: #43A047;
        }

        .form .message {
            margin: 15px 0 0;
            color: #b3b3b3;
            font-size: 12px;
        }

        .form .message a {
            color: #4CAF50;
            text-decoration: none;
        }

        .form .register-form {
            display: none;
        }

        .container {
            position: relative;
            z-index: 1;
            max-width: 300px;
            margin: 0 auto;
        }

        .container:before, .container:after {
            content: "";
            display: block;
            clear: both;
        }

        .container .info {
            margin: 50px auto;
            text-align: center;
        }

        .container .info h1 {
            margin: 0 0 15px;
            padding: 0;
            font-size: 36px;
            font-weight: 300;
            color: #1a1a1a;
        }

        .container .info span {
            color: #4d4d4d;
            font-size: 12px;
        }

        .container .info span a {
            color: #000000;
            text-decoration: none;
        }

        .container .info span .fa {
            color: #EF3B3A;
        }

        body {
            background: #76b852; /* fallback for old browsers */
            background: -webkit-linear-gradient(right, #76b852, #8DC26F);
            background: -moz-linear-gradient(right, #76b852, #8DC26F);
            background: -o-linear-gradient(right, #76b852, #8DC26F);
            background: linear-gradient(to left, #76b852, #8DC26F);
            font-family: "Roboto", sans-serif;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
        }
    </style>

</head>

<body>
<div class="login-page">
    <div class="form">
        <form class="register-form">
            <input type="text" name="login[email]" placeholder="Email"/>
            <input type="password" name="login[senha]" placeholder="Senha"/>
            <button>Cadastrar</button>
            <p class="message">Já é registrado? <a href="#">Login</a></p>
        </form>
        <form class="login-form" action="/login/acessorecebendo" method="post">
            <input type="text" name="login[email]" placeholder="email"/>
            <input type="password" name="login[senha]" placeholder="password"/>
            <button>login</button>
            <p class="message">Não está registrado <a href="#">Criar uma conta</a></p>
        </form>
    </div>
</div>
<script>
    $('.message a').click(function () {
        $('form').animate({height: "toggle", opacity: "toggle"}, "slow");
    });
</script>
</body>
</html>
</code>```

Body:
so, i get that form HTML template:
https://codepen.io/colorlib/pen/rxddKy

but after implemented, it arent working ):

The login View:

<% if flash[:notice] %>

<%= flash[:notice] %>
 <% end %>

    <form class="register-form">
      <input type="text" name="login[email]" placeholder="Email"/>
      <input type="password" name="login[senha]" placeholder="Senha"/>
      <button>Cadastrar</button>

Já é registrado? Login

    </form>
    <form class="login-form" action="/login/acessorecebendo" method="post">
      <input type="text" name="login[email]" placeholder="email"/>
      <input type="password" name="login[senha]" placeholder="password"/>
      <button>login</button>

Não está registrado Criar uma conta

    </form>
    <% if session[:user] %>
        Sair sessão <%= @user.nome %>
    <% end %>

the login JS:

$(document).ready(function(){
    $('.message a').click(function(){
        $('form').animate({height: "toggle", opacity: "toggle"}, "slow");
    });
});

the application.js are with:

//= require jquery
//= require rails-ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree .

and also, i've been included the gem 'jquery' on my gemfile.

Nothing is happing when i click on the hiperlink "create account":
https://s13.postimg.org/8wzhw1tjr/Screenshot_20170606_224605.png

The CTRL+U on the browser:

<!DOCTYPE html>

    <title>V2Michel</title>
    <meta name="csrf-param" content="authenticity_token" />
<meta name="csrf-token" content="D47bHUTHcwdqpFlaiDZA3LJr4236jZSSppt9q/FBwK0DPDmc76zIcsfeZSlBMFVJUNxqpFM0u/kM/AfhdNePXw==" />

    <link rel="stylesheet" media="all" href="/assets/fornecedors.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload" />
<link rel="stylesheet" media="all" href="/assets/home.self-d58d58b8f163d83cd8eab0042d14c22afb73ea76b61d7cd85bca19a5d2eee2ce.css?body=1" data-turbolinks-track="reload" />
<link rel="stylesheet" media="all" href="/assets/login.self-a6ac1a027c5fa2959e7c8dc0a7e2483f324f0b0833b337aa2c9560848d55a040.css?body=1" data-turbolinks-track="reload" />
<link rel="stylesheet" media="all" href="/assets/produtos.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.css?body=1" data-turbolinks-track="reload" />
<link rel="stylesheet" media="all" href="/assets/scaffolds.self-2404dddc0e44f7051d6852d95406118fcf78ccd9df57e634c29cf011ebdb47cb.css?body=1" data-turbolinks-track="reload" />
<link rel="stylesheet" media="all" href="/assets/application.self-451e5f1e26abd1c402b1a9c60a4af0e0d30f25a334b1266b6270d9fe17346210.css?body=1" data-turbolinks-track="reload" />

    <form class="register-form">
      <input type="text" name="login[email]" placeholder="Email"/>
      <input type="password" name="login[senha]" placeholder="Senha"/>
      <button>Cadastrar</button>

Já é registrado? Login

    </form>
    <form class="login-form" action="/login/acessorecebendo" method="post">
      <input type="text" name="login[email]" placeholder="email"/>
      <input type="password" name="login[senha]" placeholder="password"/>
      <button>login</button>

Não está registrado Criar uma conta

    </form>

I've deleted the attribute href on the hiperlink "create account" and Works ! lololol

Body:
It's definitely something messing with your assets, I copied your code and modified it to take script and style, since the ctrl+u don't bring it. It's working!

Next step you can ctrl+s in your page, save all assets together the ctrl+u and publish it somewhere, I will check it tomorrow if you want ^^

My code

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

    <style>
        @import url(https://fonts.googleapis.com/css?family=Roboto:300);

        .login-page {
            width: 360px;
            padding: 8% 0 0;
            margin: auto;
        }

        .form {
            position: relative;
            z-index: 1;
            background: #FFFFFF;
            max-width: 360px;
            margin: 0 auto 100px;
            padding: 45px;
            text-align: center;
            box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24);
        }

        .form input {
            font-family: "Roboto", sans-serif;
            outline: 0;
            background: #f2f2f2;
            width: 100%;
            border: 0;
            margin: 0 0 15px;
            padding: 15px;
            box-sizing: border-box;
            font-size: 14px;
        }

        .form button {
            font-family: "Roboto", sans-serif;
            text-transform: uppercase;
            outline: 0;
            background: #4CAF50;
            width: 100%;
            border: 0;
            padding: 15px;
            color: #FFFFFF;
            font-size: 14px;
            -webkit-transition: all 0.3 ease;
            transition: all 0.3 ease;
            cursor: pointer;
        }

        .form button:hover, .form button:active, .form button:focus {
            background: #43A047;
        }

        .form .message {
            margin: 15px 0 0;
            color: #b3b3b3;
            font-size: 12px;
        }

        .form .message a {
            color: #4CAF50;
            text-decoration: none;
        }

        .form .register-form {
            display: none;
        }

        .container {
            position: relative;
            z-index: 1;
            max-width: 300px;
            margin: 0 auto;
        }

        .container:before, .container:after {
            content: "";
            display: block;
            clear: both;
        }

        .container .info {
            margin: 50px auto;
            text-align: center;
        }

        .container .info h1 {
            margin: 0 0 15px;
            padding: 0;
            font-size: 36px;
            font-weight: 300;
            color: #1a1a1a;
        }

        .container .info span {
            color: #4d4d4d;
            font-size: 12px;
        }

        .container .info span a {
            color: #000000;
            text-decoration: none;
        }

        .container .info span .fa {
            color: #EF3B3A;
        }

        body {
            background: #76b852; /* fallback for old browsers */
            background: -webkit-linear-gradient(right, #76b852, #8DC26F);
            background: -moz-linear-gradient(right, #76b852, #8DC26F);
            background: -o-linear-gradient(right, #76b852, #8DC26F);
            background: linear-gradient(to left, #76b852, #8DC26F);
            font-family: "Roboto", sans-serif;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
        }
    </style>

</head>

<body>
<div class="login-page">
    <div class="form">
        <form class="register-form">
            <input type="text" name="login[email]" placeholder="Email"/>
            <input type="password" name="login[senha]" placeholder="Senha"/>
            <button>Cadastrar</button>
            <p class="message">Já é registrado? <a href="#">Login</a></p>
        </form>
        <form class="login-form" action="/login/acessorecebendo" method="post">
            <input type="text" name="login[email]" placeholder="email"/>
            <input type="password" name="login[senha]" placeholder="password"/>
            <button>login</button>
            <p class="message">Não está registrado <a href="#">Criar uma conta</a></p>
        </form>
    </div>
</div>
<script>
    $('.message a').click(function () {
        $('form').animate({height: "toggle", opacity: "toggle"}, "slow");
    });
</script>
</body>
</html>


问:
I am trying to build a website that has a file manager on it. Is there any way to pull file paths and files from Google Drive?
I would also like to pull from Dropbox, Box, and iCloud Drive. If there is no way, I will try to work around it but I was just wondering. I would like to be able to see the whole drive (all files and folders accessible). Thanks.</p>

答: Depending on what you exactly are looking to do, you can use Google Drive's API to create/open files on your Drive for a serious project. If you are just experimenting with an idea, you can host your site directly from Google Drive.</p>


问:
How do I add all the filenames under a certain folder to an arraylist using Java
I have this much so far

```<code> import java.io.File;
 import java.io.FilenameFilter;
 import java.util.ArrayList;
 import java.util.Arrays;

 import org.pdfbox.util.Splitter;
 public class fileName {
     public static void main(String args[]){
         File file = new File("/Users/apple/Desktop/");
         String[] directories = file.list(new FilenameFilter(){

             @Override
             public boolean accept(File current, String name) {
                return new File(current, name).isDirectory();
             }
         });
 System.out.println(Arrays.toString(directories));
 ArrayList<String[]>SSOList = new ArrayList<String[]>();
     }
 }
</code>```

It prints the names of all the files on my desktop but I want to add them to an arraylist. How do I do that?

答:
```<code>ArrayList<String> SSOList =  new ArrayList<String>(Arrays.asList(directories))
</code>```

or you can use:

```<code>Collections.addAll(SSOList, directories);
</code>```

Also if SSOList is the name of the ArrayList you want the files to be stored in, I think you need to change it to an array list of Strings and not array list of array of Strings :

```<code>List<String>SSOList = new ArrayList<String>();
</code>```

Body:
I have this much so far

 import java.io.File;
 import java.io.FilenameFilter;
 import java.util.ArrayList;
 import java.util.Arrays;

 import org.pdfbox.util.Splitter;
 public class fileName {
     public static void main(String args[]){
         File file = new File("/Users/apple/Desktop/");
         String[] directories = file.list(new FilenameFilter(){

             @Override
             public boolean accept(File current, String name) {
                return new File(current, name).isDirectory();
             }
         });
 System.out.println(Arrays.toString(directories));
 ArrayList<String[]>SSOList = new ArrayList<String[]>();
     }
 }

It prints the names of all the files on my desktop but I want to add them to an arraylist. How do I do that?

Body:
ArrayList<String> SSOList =  new ArrayList<String>(Arrays.asList(directories))

or you can use:

Collections.addAll(SSOList, directories);

Also if SSOList is the name of the ArrayList you want the files to be stored in, I think you need to change it to an array list of Strings and not array list of array of Strings :

List<String>SSOList = new ArrayList<String>();


问:
Handling Local vs Remote Database TimeZone Differences in Tests
I have unit test in Java that writes a constant Timestamp to a row in my local test database, reads it back and compares it to what I expected. This works fine on my local laptop which is under the GMT timezone.

When I commit the code to our continuous integration server, the test fails with the different in time being -5 hours. This is no surprise since our integration server is hosted on AWS on the East Coast of US. However, it is causing a problem...

Short of changing my local MySQL server to have the same timezone as the remote server (and having all the developers in my team do so also), can anyone show me how to fix this issue in code without getting too hacky?

```<code>//Fetch actual table contents
IDataSet databaseDataSet = databaseTester.getConnection().createDataSet();
ITable actualTable = databaseDataSet.getTable("batch");

// Load expected data from an XML dataset
IDataSet expectedDataSet = new XmlDataSet(getClass().getResourceAsStream("/dbunit/expected_insert_batch.xml"));
ITable expectedTable = expectedDataSet.getTable("batch");

// Assert actual database table match expected table
Assertion.assertEquals(expectedTable, actualTable);
</code>```

Thanks,

答: You need to make your test not depend on environment. Look for places where you can make this field dynamic and it should work anywhere.</p>

Body:
I have unit test in Java that writes a constant Timestamp to a row in my local test database, reads it back and compares it to what I expected. This works fine on my local laptop which is under the GMT timezone.

When I commit the code to our continuous integration server, the test fails with the different in time being -5 hours. This is no surprise since our integration server is hosted on AWS on the East Coast of US. However, it is causing a problem...

Short of changing my local MySQL server to have the same timezone as the remote server (and having all the developers in my team do so also), can anyone show me how to fix this issue in code without getting too hacky?

//Fetch actual table contents
IDataSet databaseDataSet = databaseTester.getConnection().createDataSet();
ITable actualTable = databaseDataSet.getTable("batch");

// Load expected data from an XML dataset
IDataSet expectedDataSet = new XmlDataSet(getClass().getResourceAsStream("/dbunit/expected_insert_batch.xml"));
ITable expectedTable = expectedDataSet.getTable("batch");

// Assert actual database table match expected table
Assertion.assertEquals(expectedTable, actualTable);

Thanks,


问:
endswith() matching?
I am using the code below to match using endswith in Python.

```<code>while not buff.endswith('/abc #'):
</code>```

But I run into a problem when the line ends as shown below:

```<code>('console /abc/xyz* #')

('console /abc/xyz/pqrs* #')
</code>```

Now how to match with endswith for "/abc" anywhere, but # must be the last character?

答:
I think there's a language barrier here making it hard to understand the requirements, so I'll just propose a solution based on my best guess:</p>

```<code>while not (buff.endswith("#") and "/abc" in buff):
</code>```

Title: endswith() matching?

Body:
I am using the code below to match using endswith in Python.

while not buff.endswith('/abc #'):

But I run into a problem when the line ends as shown below:

('console /abc/xyz* #')

('console /abc/xyz/pqrs* #')

Now how to match with endswith for "/abc" anywhere, but # must be the last character?

Body:
I think there's a language barrier here making it hard to understand the requirements, so I'll just propose a solution based on my best guess:

while not (buff.endswith("#") and "/abc" in buff):


问:
Java overloading and overriding
Suppose i have two methods in a class say

public void eat(int i,String s) and

public void eat(String s, int i)

then what is it like. Overloading or overriding?

答:
Method Overloading simply means providing two separate methods in a class with the same name but different arguments while method return type may or may not be different which allows us to reuse the same method name.

Method Overriding means defining a method in the child class which is already defined in the parent class with same method signature i.e same name, arguments and return type.

Difference Between Method Overloading and Method Overriding

For more details, you can read Everything About Method Overloading Vs Method Overriding.

Title: Java overloading and overriding

ContentLicense: CC BY-SA 4.0


问:
Postgresql - Window Function Aggregate
I'm attempting to find the number of new users per month by product type. However, I continue to receive an error requesting cnt to be used in an aggregate function.

```<code>SELECT EXTRACT(MONTH FROM date) AS month
FROM (SELECT users.date,
             COUNT(*) OVER(PARTITION BY product_type) AS cnt FROM users) AS u
GROUP BY month
ORDER BY cnt DESC;
</code>```

答:
That seems like a very strange construct.  Here is a method that doesn't use window functions:</p>

```<code>select date_trunc('month', date) as  yyyymm, product_id, count(*)
from (select distinct on (u.userid) u.*
      from users u
      order by u.userid, u.date
     ) u
group by date_trunc('month', date), product_id
order by yyyymm, product_id;
</code>```

Title: Postgresql - Window Function Aggregate

Body:
I'm attempting to find the number of new users per month by product type. However, I continue to receive an error requesting cnt to be used in an aggregate function.

SELECT EXTRACT(MONTH FROM date) AS month
FROM (SELECT users.date,
             COUNT(*) OVER(PARTITION BY product_type) AS cnt FROM users) AS u
GROUP BY month
ORDER BY cnt DESC;

Body:
That seems like a very strange construct.  Here is a method that doesn't use window functions:

select date_trunc('month', date) as  yyyymm, product_id, count(*)
from (select distinct on (u.userid) u.*
      from users u
      order by u.userid, u.date
     ) u
group by date_trunc('month', date), product_id
order by yyyymm, product_id;


问:
Distributed Data Structure across multiple machines with multicast
I am looking into the possibility of Distributing a data structure across multiple machines. I would like it to run in a process on each machine, and using (Multicast?) replicate a copy of the full data structure on all of the machines.

Does anyone have any experience in this that could point me in the right direction?

答:
Distributed locking is hard -- and you might well need to lock, unless you're reading only. I suggest you take a look at a distributed caching framework like Microsoft's Velocity (which may be renamed as part of Azure now), or the free, open source and very good memcached.

There are other, pay-for options too -- notably GemFire and Coherence.

I'd give memcache a go, it works pretty well.


问:
One signal create a new Ios User every time
Every time I launch my app One signal create a new Ios User no matter if its the same device. This is not happen in Android only in Ios.

This is a pic of OneSignal Users, all Iphone5,3 is a only device.

I init one signal with this code in app.components.ts:

```<code>window["plugins"].OneSignal
        .startInit("MyID", "MyIDOne")
        .handleNotificationOpened(notificationOpenedCallback)
        .endInit();
</code>```

答:
This should not happen except in some cases where you delete the app from your device and re-install it. If this is happening in another case, then there is either a problem with the version of the OneSignal SDK you are using, or with the way it has been integrated into your application.

Based on the limited details here I'm not sure how to resolve this. I recommend getting in touch with the OneSignal support team and sending a copy of the code you are using to initialize OneSignal to help troubleshoot the problem.

Body:
Every time I launch my app One signal create a new Ios User no matter if its the same device. This is not happen in Android only in Ios.

This is a pic of OneSignal Users, all Iphone5,3 is a only device.

I init one signal with this code in app.components.ts:

window["plugins"].OneSignal
        .startInit("MyID", "MyIDOne")
        .handleNotificationOpened(notificationOpenedCallback)
        .endInit();


问:
How to make multiple Axios requests using a dynamic array of links in Javascript?
linksArray is an array with six links.

I want to use this array to perform (6) get requests. Then, I want to take the response and setState after the response is mapped through to get the results I want.

Any help here?

```<code>getGistsDescriptions = () => {
let promiseArray = linksArray.map((url) => { return axios.get(url)});

axios.all(promiseArray)
     .then(axios.spread((...res) => {
       console.log(...res);

      /*let temp = res.map((element) => {
        return element.data;
      });*/

       //this.setState({ gistsDescriptions: temp });
     }))
     .catch((err) => {
    console.log(err);
  });
 }
</code>```

I also tried this:

```<code>getGistsDescriptions = () => {
let promiseArray = linksArray.map((url) => { return axios.get(url)});

axios.all(promiseArray)
     .then((results) => {
       console.log(results);

      /*let temp = results.map((element) => {
        return element.data;
      });*/

       //this.setState({ gistsDescriptions: temp });
     })
     .catch((err) => {
    console.log(err);
  });
}
</code>```

答:
First thing you should do is to check whether links array contains actually contains valid links.

The following code works for me:

/* axios v0.16.2 | (c) 2017 by Matt Zabriskie */
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.axios=t():e.axios=t()}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return e[r].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){e.exports=n(1)},function(e,t,n){"use strict";function r(e){var t=new s(e),n=i(s.prototype.request,t);return o.extend(n,s.prototype,t),o.extend(n,t),n}var o=n(2),i=n(3),s=n(5),u=n(6),a=r(u);a.Axios=s,a.create=function(e){return r(o.merge(u,e))},a.Cancel=n(23),a.CancelToken=n(24),a.isCancel=n(20),a.all=function(e){return Promise.all(e)},a.spread=n(25),e.exports=a,e.exports.default=a},function(e,t,n){"use strict";function r(e){return"[object Array]"===R.call(e)}function o(e){return"[object ArrayBuffer]"===R.call(e)}function i(e){return"undefined"!=typeof FormData&&e instanceof FormData}function s(e){var t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&e.buffer instanceof ArrayBuffer}function u(e){return"string"==typeof e}function a(e){return"number"==typeof e}function c(e){return"undefined"==typeof e}function f(e){return null!==e&&"object"==typeof e}function p(e){return"[object Date]"===R.call(e)}function d(e){return"[object File]"===R.call(e)}function l(e){return"[object Blob]"===R.call(e)}function h(e){return"[object Function]"===R.call(e)}function m(e){return f(e)&&h(e.pipe)}function y(e){return"undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams}function w(e){return e.replace(/^\s*/,"").replace(/\s*$/,"")}function v(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product)&&("undefined"!=typeof window&&"undefined"!=typeof document)}function g(e,t){if(null!==e&&"undefined"!=typeof e)if("object"==typeof e||r(e)||(e=[e]),r(e))for(var n=0,o=e.length;n<o;n++)t.call(null,e[n],n,e);else for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.call(null,e[i],i,e)}function x(){function e(e,n){"object"==typeof t[n]&&"object"==typeof e?t[n]=x(t[n],e):t[n]=e}for(var t={},n=0,r=arguments.length;n<r;n++)g(arguments[n],e);return t}function b(e,t,n){return g(t,function(t,r){n&&"function"==typeof t?e[r]=E(t,n):e[r]=t}),e}var E=n(3),C=n(4),R=Object.prototype.toString;e.exports={isArray:r,isArrayBuffer:o,isBuffer:C,isFormData:i,isArrayBufferView:s,isString:u,isNumber:a,isObject:f,isUndefined:c,isDate:p,isFile:d,isBlob:l,isFunction:h,isStream:m,isURLSearchParams:y,isStandardBrowserEnv:v,forEach:g,merge:x,extend:b,trim:w}},function(e,t){"use strict";e.exports=function(e,t){return function(){for(var n=new Array(arguments.length),r=0;r<n.length;r++)n[r]=arguments[r];return e.apply(t,n)}}},function(e,t){function n(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function r(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&n(e.slice(0,0))}/*!
  * Determine if an object is a Buffer
  *
  * @author   Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  * @license  MIT
  */
e.exports=function(e){return null!=e&&(n(e)||r(e)||!!e._isBuffer)}},function(e,t,n){"use strict";function r(e){this.defaults=e,this.interceptors={request:new s,response:new s}}var o=n(6),i=n(2),s=n(17),u=n(18),a=n(21),c=n(22);r.prototype.request=function(e){"string"==typeof e&&(e=i.merge({url:arguments[0]},arguments[1])),e=i.merge(o,this.defaults,{method:"get"},e),e.method=e.method.toLowerCase(),e.baseURL&&!a(e.url)&&(e.url=c(e.baseURL,e.url));var t=[u,void 0],n=Promise.resolve(e);for(this.interceptors.request.forEach(function(e){t.unshift(e.fulfilled,e.rejected)}),this.interceptors.response.forEach(function(e){t.push(e.fulfilled,e.rejected)});t.length;)n=n.then(t.shift(),t.shift());return n},i.forEach(["delete","get","head","options"],function(e){r.prototype[e]=function(t,n){return this.request(i.merge(n||{},{method:e,url:t}))}}),i.forEach(["post","put","patch"],function(e){r.prototype[e]=function(t,n,r){return this.request(i.merge(r||{},{method:e,url:t,data:n}))}}),e.exports=r},function(e,t,n){"use strict";function r(e,t){!i.isUndefined(e)&&i.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}function o(){var e;return"undefined"!=typeof XMLHttpRequest?e=n(8):"undefined"!=typeof process&&(e=n(8)),e}var i=n(2),s=n(7),u={"Content-Type":"application/x-www-form-urlencoded"},a={adapter:o(),transformRequest:[function(e,t){return s(t,"Content-Type"),i.isFormData(e)||i.isArrayBuffer(e)||i.isBuffer(e)||i.isStream(e)||i.isFile(e)||i.isBlob(e)?e:i.isArrayBufferView(e)?e.buffer:i.isURLSearchParams(e)?(r(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString()):i.isObject(e)?(r(t,"application/json;charset=utf-8"),JSON.stringify(e)):e}],transformResponse:[function(e){if("string"==typeof e)try{e=JSON.parse(e)}catch(e){}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,validateStatus:function(e){return e>=200&&e<300}};a.headers={common:{Accept:"application/json, text/plain, */*"}},i.forEach(["delete","get","head"],function(e){a.headers[e]={}}),i.forEach(["post","put","patch"],function(e){a.headers[e]=i.merge(u)}),e.exports=a},function(e,t,n){"use strict";var r=n(2);e.exports=function(e,t){r.forEach(e,function(n,r){r!==t&&r.toUpperCase()===t.toUpperCase()&&(e[t]=n,delete e[r])})}},function(e,t,n){"use strict";var r=n(2),o=n(9),i=n(12),s=n(13),u=n(14),a=n(10),c="undefined"!=typeof window&&window.btoa&&window.btoa.bind(window)||n(15);e.exports=function(e){return new Promise(function(t,f){var p=e.data,d=e.headers;r.isFormData(p)&&delete d["Content-Type"];var l=new XMLHttpRequest,h="onreadystatechange",m=!1;if("undefined"==typeof window||!window.XDomainRequest||"withCredentials"in l||u(e.url)||(l=new window.XDomainRequest,h="onload",m=!0,l.onprogress=function(){},l.ontimeout=function(){}),e.auth){var y=e.auth.username||"",w=e.auth.password||"";d.Authorization="Basic "+c(y+":"+w)}if(l.open(e.method.toUpperCase(),i(e.url,e.params,e.paramsSerializer),!0),l.timeout=e.timeout,l[h]=function(){if(l&&(4===l.readyState||m)&&(0!==l.status||l.responseURL&&0===l.responseURL.indexOf("file:"))){var n="getAllResponseHeaders"in l?s(l.getAllResponseHeaders()):null,r=e.responseType&&"text"!==e.responseType?l.response:l.responseText,i={data:r,status:1223===l.status?204:l.status,statusText:1223===l.status?"No Content":l.statusText,headers:n,config:e,request:l};o(t,f,i),l=null}},l.onerror=function(){f(a("Network Error",e,null,l)),l=null},l.ontimeout=function(){f(a("timeout of "+e.timeout+"ms exceeded",e,"ECONNABORTED",l)),l=null},r.isStandardBrowserEnv()){var v=n(16),g=(e.withCredentials||u(e.url))&&e.xsrfCookieName?v.read(e.xsrfCookieName):void 0;g&&(d[e.xsrfHeaderName]=g)}if("setRequestHeader"in l&&r.forEach(d,function(e,t){"undefined"==typeof p&&"content-type"===t.toLowerCase()?delete d[t]:l.setRequestHeader(t,e)}),e.withCredentials&&(l.withCredentials=!0),e.responseType)try{l.responseType=e.responseType}catch(t){if("json"!==e.responseType)throw t}"function"==typeof e.onDownloadProgress&&l.addEventListener("progress",e.onDownloadProgress),"function"==typeof e.onUploadProgress&&l.upload&&l.upload.addEventListener("progress",e.onUploadProgress),e.cancelToken&&e.cancelToken.promise.then(function(e){l&&(l.abort(),f(e),l=null)}),void 0===p&&(p=null),l.send(p)})}},function(e,t,n){"use strict";var r=n(10);e.exports=function(e,t,n){var o=n.config.validateStatus;n.status&&o&&!o(n.status)?t(r("Request failed with status code "+n.status,n.config,null,n.request,n)):e(n)}},function(e,t,n){"use strict";var r=n(11);e.exports=function(e,t,n,o,i){var s=new Error(e);return r(s,t,n,o,i)}},function(e,t){"use strict";e.exports=function(e,t,n,r,o){return e.config=t,n&&(e.code=n),e.request=r,e.response=o,e}},function(e,t,n){"use strict";function r(e){return encodeURIComponent(e).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var o=n(2);e.exports=function(e,t,n){if(!t)return e;var i;if(n)i=n(t);else if(o.isURLSearchParams(t))i=t.toString();else{var s=[];o.forEach(t,function(e,t){null!==e&&"undefined"!=typeof e&&(o.isArray(e)&&(t+="[]"),o.isArray(e)||(e=[e]),o.forEach(e,function(e){o.isDate(e)?e=e.toISOString():o.isObject(e)&&(e=JSON.stringify(e)),s.push(r(t)+"="+r(e))}))}),i=s.join("&")}return i&&(e+=(e.indexOf("?")===-1?"?":"&")+i),e}},function(e,t,n){"use strict";var r=n(2);e.exports=function(e){var t,n,o,i={};return e?(r.forEach(e.split("\n"),function(e){o=e.indexOf(":"),t=r.trim(e.substr(0,o)).toLowerCase(),n=r.trim(e.substr(o+1)),t&&(i[t]=i[t]?i[t]+", "+n:n)}),i):i}},function(e,t,n){"use strict";var r=n(2);e.exports=r.isStandardBrowserEnv()?function(){function e(e){var t=e;return n&&(o.setAttribute("href",t),t=o.href),o.setAttribute("href",t),{href:o.href,protocol:o.protocol?o.protocol.replace(/:$/,""):"",host:o.host,search:o.search?o.search.replace(/^\?/,""):"",hash:o.hash?o.hash.replace(/^#/,""):"",hostname:o.hostname,port:o.port,pathname:"/"===o.pathname.charAt(0)?o.pathname:"/"+o.pathname}}var t,n=/(msie|trident)/i.test(navigator.userAgent),o=document.createElement("a");return t=e(window.location.href),function(n){var o=r.isString(n)?e(n):n;return o.protocol===t.protocol&&o.host===t.host}}():function(){return function(){return!0}}()},function(e,t){"use strict";function n(){this.message="String contains an invalid character"}function r(e){for(var t,r,i=String(e),s="",u=0,a=o;i.charAt(0|u)||(a="=",u%1);s+=a.charAt(63&t>>8-u%1*8)){if(r=i.charCodeAt(u+=.75),r>255)throw new n;t=t<<8|r}return s}var o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";n.prototype=new Error,n.prototype.code=5,n.prototype.name="InvalidCharacterError",e.exports=r},function(e,t,n){"use strict";var r=n(2);e.exports=r.isStandardBrowserEnv()?function(){return{write:function(e,t,n,o,i,s){var u=[];u.push(e+"="+encodeURIComponent(t)),r.isNumber(n)&&u.push("expires="+new Date(n).toGMTString()),r.isString(o)&&u.push("path="+o),r.isString(i)&&u.push("domain="+i),s===!0&&u.push("secure"),document.cookie=u.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}()},function(e,t,n){"use strict";function r(){this.handlers=[]}var o=n(2);r.prototype.use=function(e,t){return this.handlers.push({fulfilled:e,rejected:t}),this.handlers.length-1},r.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},r.prototype.forEach=function(e){o.forEach(this.handlers,function(t){null!==t&&e(t)})},e.exports=r},function(e,t,n){"use strict";function r(e){e.cancelToken&&e.cancelToken.throwIfRequested()}var o=n(2),i=n(19),s=n(20),u=n(6);e.exports=function(e){r(e),e.headers=e.headers||{},e.data=i(e.data,e.headers,e.transformRequest),e.headers=o.merge(e.headers.common||{},e.headers[e.method]||{},e.headers||{}),o.forEach(["delete","get","head","post","put","patch","common"],function(t){delete e.headers[t]});var t=e.adapter||u.adapter;return t(e).then(function(t){return r(e),t.data=i(t.data,t.headers,e.transformResponse),t},function(t){return s(t)||(r(e),t&&t.response&&(t.response.data=i(t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)})}},function(e,t,n){"use strict";var r=n(2);e.exports=function(e,t,n){return r.forEach(n,function(n){e=n(e,t)}),e}},function(e,t){"use strict";e.exports=function(e){return!(!e||!e.__CANCEL__)}},function(e,t){"use strict";e.exports=function(e){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(e)}},function(e,t){"use strict";e.exports=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}},function(e,t){"use strict";function n(e){this.message=e}n.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},n.prototype.__CANCEL__=!0,e.exports=n},function(e,t,n){"use strict";function r(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");var t;this.promise=new Promise(function(e){t=e});var n=this;e(function(e){n.reason||(n.reason=new o(e),t(n.reason))})}var o=n(23);r.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},r.source=function(){var e,t=new r(function(t){e=t});return{token:t,cancel:e}},e.exports=r},function(e,t){"use strict";e.exports=function(e){return function(t){return e.apply(null,t)}}}])});
//# sourceMappingURL=axios.min.map

let linksArr = ['https://jsonplaceholder.typicode.com/posts', 'https://jsonplaceholder.typicode.com/comments'];

axios.all(linksArr.map(l => axios.get(l)))
  .then(axios.spread(function (...res) {
    // all requests are now complete
    console.log(res);
  }));```
</div>
</div>
</p>

<p>Alternatively, you can also use fetch and promises</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// sample links
let linksArr = [undefined, undefined];

let promiseArr = linksArr.map(l => fetch(l).then(res => res.json()));

Promise.all(promiseArr).then(res => {
  /* do something with res here... */
  console.log(res);
})</code>```

Body:
linksArray is an array with six links.

I want to use this array to perform (6) get requests. Then, I want to take the response and setState after the response is mapped through to get the results I want.

Any help here?

getGistsDescriptions = () => {
let promiseArray = linksArray.map((url) => { return axios.get(url)});

axios.all(promiseArray)
     .then(axios.spread((...res) => {
       console.log(...res);

      /*let temp = res.map((element) => {
        return element.data;
      });*/

       //this.setState({ gistsDescriptions: temp });
     }))
     .catch((err) => {
    console.log(err);
  });
 }

I also tried this:

getGistsDescriptions = () => {
let promiseArray = linksArray.map((url) => { return axios.get(url)});

axios.all(promiseArray)
     .then((results) => {
       console.log(results);

      /*let temp = results.map((element) => {
        return element.data;
      });*/

       //this.setState({ gistsDescriptions: temp });
     })
     .catch((err) => {
    console.log(err);
  });
}

Body:
First thing you should do is to check whether links array contains actually contains valid links.

The following code works for me:

/* axios v0.16.2 | (c) 2017 by Matt Zabriskie */
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.axios=t():e.axios=t()}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return e[r].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){e.exports=n(1)},function(e,t,n){"use strict";function r(e){var t=new s(e),n=i(s.prototype.request,t);return o.extend(n,s.prototype,t),o.extend(n,t),n}var o=n(2),i=n(3),s=n(5),u=n(6),a=r(u);a.Axios=s,a.create=function(e){return r(o.merge(u,e))},a.Cancel=n(23),a.CancelToken=n(24),a.isCancel=n(20),a.all=function(e){return Promise.all(e)},a.spread=n(25),e.exports=a,e.exports.default=a},function(e,t,n){"use strict";function r(e){return"[object Array]"===R.call(e)}function o(e){return"[object ArrayBuffer]"===R.call(e)}function i(e){return"undefined"!=typeof FormData&&e instanceof FormData}function s(e){var t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&e.buffer instanceof ArrayBuffer}function u(e){return"string"==typeof e}function a(e){return"number"==typeof e}function c(e){return"undefined"==typeof e}function f(e){return null!==e&&"object"==typeof e}function p(e){return"[object Date]"===R.call(e)}function d(e){return"[object File]"===R.call(e)}function l(e){return"[object Blob]"===R.call(e)}function h(e){return"[object Function]"===R.call(e)}function m(e){return f(e)&&h(e.pipe)}function y(e){return"undefined"!=typeof URLSearchParams&&e instanceof URLSearchParams}function w(e){return e.replace(/^\s*/,"").replace(/\s*$/,"")}function v(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product)&&("undefined"!=typeof window&&"undefined"!=typeof document)}function g(e,t){if(null!==e&&"undefined"!=typeof e)if("object"==typeof e||r(e)||(e=[e]),r(e))for(var n=0,o=e.length;n<o;n++)t.call(null,e[n],n,e);else for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.call(null,e[i],i,e)}function x(){function e(e,n){"object"==typeof t[n]&&"object"==typeof e?t[n]=x(t[n],e):t[n]=e}for(var t={},n=0,r=arguments.length;n<r;n++)g(arguments[n],e);return t}function b(e,t,n){return g(t,function(t,r){n&&"function"==typeof t?e[r]=E(t,n):e[r]=t}),e}var E=n(3),C=n(4),R=Object.prototype.toString;e.exports={isArray:r,isArrayBuffer:o,isBuffer:C,isFormData:i,isArrayBufferView:s,isString:u,isNumber:a,isObject:f,isUndefined:c,isDate:p,isFile:d,isBlob:l,isFunction:h,isStream:m,isURLSearchParams:y,isStandardBrowserEnv:v,forEach:g,merge:x,extend:b,trim:w}},function(e,t){"use strict";e.exports=function(e,t){return function(){for(var n=new Array(arguments.length),r=0;r<n.length;r++)n[r]=arguments[r];return e.apply(t,n)}}},function(e,t){function n(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}function r(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&n(e.slice(0,0))}/*!
  * Determine if an object is a Buffer
  *
  * @author   Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  * @license  MIT
  */
e.exports=function(e){return null!=e&&(n(e)||r(e)||!!e._isBuffer)}},function(e,t,n){"use strict";function r(e){this.defaults=e,this.interceptors={request:new s,response:new s}}var o=n(6),i=n(2),s=n(17),u=n(18),a=n(21),c=n(22);r.prototype.request=function(e){"string"==typeof e&&(e=i.merge({url:arguments[0]},arguments[1])),e=i.merge(o,this.defaults,{method:"get"},e),e.method=e.method.toLowerCase(),e.baseURL&&!a(e.url)&&(e.url=c(e.baseURL,e.url));var t=[u,void 0],n=Promise.resolve(e);for(this.interceptors.request.forEach(function(e){t.unshift(e.fulfilled,e.rejected)}),this.interceptors.response.forEach(function(e){t.push(e.fulfilled,e.rejected)});t.length;)n=n.then(t.shift(),t.shift());return n},i.forEach(["delete","get","head","options"],function(e){r.prototype[e]=function(t,n){return this.request(i.merge(n||{},{method:e,url:t}))}}),i.forEach(["post","put","patch"],function(e){r.prototype[e]=function(t,n,r){return this.request(i.merge(r||{},{method:e,url:t,data:n}))}}),e.exports=r},function(e,t,n){"use strict";function r(e,t){!i.isUndefined(e)&&i.isUndefined(e["Content-Type"])&&(e["Content-Type"]=t)}function o(){var e;return"undefined"!=typeof XMLHttpRequest?e=n(8):"undefined"!=typeof process&&(e=n(8)),e}var i=n(2),s=n(7),u={"Content-Type":"application/x-www-form-urlencoded"},a={adapter:o(),transformRequest:[function(e,t){return s(t,"Content-Type"),i.isFormData(e)||i.isArrayBuffer(e)||i.isBuffer(e)||i.isStream(e)||i.isFile(e)||i.isBlob(e)?e:i.isArrayBufferView(e)?e.buffer:i.isURLSearchParams(e)?(r(t,"application/x-www-form-urlencoded;charset=utf-8"),e.toString()):i.isObject(e)?(r(t,"application/json;charset=utf-8"),JSON.stringify(e)):e}],transformResponse:[function(e){if("string"==typeof e)try{e=JSON.parse(e)}catch(e){}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,validateStatus:function(e){return e>=200&&e<300}};a.headers={common:{Accept:"application/json, text/plain, */*"}},i.forEach(["delete","get","head"],function(e){a.headers[e]={}}),i.forEach(["post","put","patch"],function(e){a.headers[e]=i.merge(u)}),e.exports=a},function(e,t,n){"use strict";var r=n(2);e.exports=function(e,t){r.forEach(e,function(n,r){r!==t&&r.toUpperCase()===t.toUpperCase()&&(e[t]=n,delete e[r])})}},function(e,t,n){"use strict";var r=n(2),o=n(9),i=n(12),s=n(13),u=n(14),a=n(10),c="undefined"!=typeof window&&window.btoa&&window.btoa.bind(window)||n(15);e.exports=function(e){return new Promise(function(t,f){var p=e.data,d=e.headers;r.isFormData(p)&&delete d["Content-Type"];var l=new XMLHttpRequest,h="onreadystatechange",m=!1;if("undefined"==typeof window||!window.XDomainRequest||"withCredentials"in l||u(e.url)||(l=new window.XDomainRequest,h="onload",m=!0,l.onprogress=function(){},l.ontimeout=function(){}),e.auth){var y=e.auth.username||"",w=e.auth.password||"";d.Authorization="Basic "+c(y+":"+w)}if(l.open(e.method.toUpperCase(),i(e.url,e.params,e.paramsSerializer),!0),l.timeout=e.timeout,l[h]=function(){if(l&&(4===l.readyState||m)&&(0!==l.status||l.responseURL&&0===l.responseURL.indexOf("file:"))){var n="getAllResponseHeaders"in l?s(l.getAllResponseHeaders()):null,r=e.responseType&&"text"!==e.responseType?l.response:l.responseText,i={data:r,status:1223===l.status?204:l.status,statusText:1223===l.status?"No Content":l.statusText,headers:n,config:e,request:l};o(t,f,i),l=null}},l.onerror=function(){f(a("Network Error",e,null,l)),l=null},l.ontimeout=function(){f(a("timeout of "+e.timeout+"ms exceeded",e,"ECONNABORTED",l)),l=null},r.isStandardBrowserEnv()){var v=n(16),g=(e.withCredentials||u(e.url))&&e.xsrfCookieName?v.read(e.xsrfCookieName):void 0;g&&(d[e.xsrfHeaderName]=g)}if("setRequestHeader"in l&&r.forEach(d,function(e,t){"undefined"==typeof p&&"content-type"===t.toLowerCase()?delete d[t]:l.setRequestHeader(t,e)}),e.withCredentials&&(l.withCredentials=!0),e.responseType)try{l.responseType=e.responseType}catch(t){if("json"!==e.responseType)throw t}"function"==typeof e.onDownloadProgress&&l.addEventListener("progress",e.onDownloadProgress),"function"==typeof e.onUploadProgress&&l.upload&&l.upload.addEventListener("progress",e.onUploadProgress),e.cancelToken&&e.cancelToken.promise.then(function(e){l&&(l.abort(),f(e),l=null)}),void 0===p&&(p=null),l.send(p)})}},function(e,t,n){"use strict";var r=n(10);e.exports=function(e,t,n){var o=n.config.validateStatus;n.status&&o&&!o(n.status)?t(r("Request failed with status code "+n.status,n.config,null,n.request,n)):e(n)}},function(e,t,n){"use strict";var r=n(11);e.exports=function(e,t,n,o,i){var s=new Error(e);return r(s,t,n,o,i)}},function(e,t){"use strict";e.exports=function(e,t,n,r,o){return e.config=t,n&&(e.code=n),e.request=r,e.response=o,e}},function(e,t,n){"use strict";function r(e){return encodeURIComponent(e).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var o=n(2);e.exports=function(e,t,n){if(!t)return e;var i;if(n)i=n(t);else if(o.isURLSearchParams(t))i=t.toString();else{var s=[];o.forEach(t,function(e,t){null!==e&&"undefined"!=typeof e&&(o.isArray(e)&&(t+="[]"),o.isArray(e)||(e=[e]),o.forEach(e,function(e){o.isDate(e)?e=e.toISOString():o.isObject(e)&&(e=JSON.stringify(e)),s.push(r(t)+"="+r(e))}))}),i=s.join("&")}return i&&(e+=(e.indexOf("?")===-1?"?":"&")+i),e}},function(e,t,n){"use strict";var r=n(2);e.exports=function(e){var t,n,o,i={};return e?(r.forEach(e.split("\n"),function(e){o=e.indexOf(":"),t=r.trim(e.substr(0,o)).toLowerCase(),n=r.trim(e.substr(o+1)),t&&(i[t]=i[t]?i[t]+", "+n:n)}),i):i}},function(e,t,n){"use strict";var r=n(2);e.exports=r.isStandardBrowserEnv()?function(){function e(e){var t=e;return n&&(o.setAttribute("href",t),t=o.href),o.setAttribute("href",t),{href:o.href,protocol:o.protocol?o.protocol.replace(/:$/,""):"",host:o.host,search:o.search?o.search.replace(/^\?/,""):"",hash:o.hash?o.hash.replace(/^#/,""):"",hostname:o.hostname,port:o.port,pathname:"/"===o.pathname.charAt(0)?o.pathname:"/"+o.pathname}}var t,n=/(msie|trident)/i.test(navigator.userAgent),o=document.createElement("a");return t=e(window.location.href),function(n){var o=r.isString(n)?e(n):n;return o.protocol===t.protocol&&o.host===t.host}}():function(){return function(){return!0}}()},function(e,t){"use strict";function n(){this.message="String contains an invalid character"}function r(e){for(var t,r,i=String(e),s="",u=0,a=o;i.charAt(0|u)||(a="=",u%1);s+=a.charAt(63&t>>8-u%1*8)){if(r=i.charCodeAt(u+=.75),r>255)throw new n;t=t<<8|r}return s}var o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";n.prototype=new Error,n.prototype.code=5,n.prototype.name="InvalidCharacterError",e.exports=r},function(e,t,n){"use strict";var r=n(2);e.exports=r.isStandardBrowserEnv()?function(){return{write:function(e,t,n,o,i,s){var u=[];u.push(e+"="+encodeURIComponent(t)),r.isNumber(n)&&u.push("expires="+new Date(n).toGMTString()),r.isString(o)&&u.push("path="+o),r.isString(i)&&u.push("domain="+i),s===!0&&u.push("secure"),document.cookie=u.join("; ")},read:function(e){var t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}()},function(e,t,n){"use strict";function r(){this.handlers=[]}var o=n(2);r.prototype.use=function(e,t){return this.handlers.push({fulfilled:e,rejected:t}),this.handlers.length-1},r.prototype.eject=function(e){this.handlers[e]&&(this.handlers[e]=null)},r.prototype.forEach=function(e){o.forEach(this.handlers,function(t){null!==t&&e(t)})},e.exports=r},function(e,t,n){"use strict";function r(e){e.cancelToken&&e.cancelToken.throwIfRequested()}var o=n(2),i=n(19),s=n(20),u=n(6);e.exports=function(e){r(e),e.headers=e.headers||{},e.data=i(e.data,e.headers,e.transformRequest),e.headers=o.merge(e.headers.common||{},e.headers[e.method]||{},e.headers||{}),o.forEach(["delete","get","head","post","put","patch","common"],function(t){delete e.headers[t]});var t=e.adapter||u.adapter;return t(e).then(function(t){return r(e),t.data=i(t.data,t.headers,e.transformResponse),t},function(t){return s(t)||(r(e),t&&t.response&&(t.response.data=i(t.response.data,t.response.headers,e.transformResponse))),Promise.reject(t)})}},function(e,t,n){"use strict";var r=n(2);e.exports=function(e,t,n){return r.forEach(n,function(n){e=n(e,t)}),e}},function(e,t){"use strict";e.exports=function(e){return!(!e||!e.__CANCEL__)}},function(e,t){"use strict";e.exports=function(e){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(e)}},function(e,t){"use strict";e.exports=function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}},function(e,t){"use strict";function n(e){this.message=e}n.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},n.prototype.__CANCEL__=!0,e.exports=n},function(e,t,n){"use strict";function r(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");var t;this.promise=new Promise(function(e){t=e});var n=this;e(function(e){n.reason||(n.reason=new o(e),t(n.reason))})}var o=n(23);r.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},r.source=function(){var e,t=new r(function(t){e=t});return{token:t,cancel:e}},e.exports=r},function(e,t){"use strict";e.exports=function(e){return function(t){return e.apply(null,t)}}}])});
//# sourceMappingURL=axios.min.map

let linksArr = ['https://jsonplaceholder.typicode.com/posts', 'https://jsonplaceholder.typicode.com/comments'];

axios.all(linksArr.map(l => axios.get(l)))
  .then(axios.spread(function (...res) {
    // all requests are now complete
    console.log(res);
  }));

Alternatively, you can also use fetch and promises

// sample links
let linksArr = [undefined, undefined];

let promiseArr = linksArr.map(l => fetch(l).then(res => res.json()));

Promise.all(promiseArr).then(res => {
  /* do something with res here... */
  console.log(res);
})