问:
Avro Java API Timestamp Logical Type?
With the Avro Java API, I can make a simple record schema like:

```<code>    Schema schemaWithTimestamp = SchemaBuilder
            .record("MyRecord").namespace("org.demo")
            .fields()
            .name("timestamp").type().longType().noDefault()
            .endRecord();
</code>```

How do I tag a schema field with a logical type, specifically:
https://avro.apache.org/docs/1.8.1/api/java/org/apache/avro/LogicalTypes.TimestampMillis.html

答:
I think you may create schema manually:

```<code>List<Schema.Field> fields = new ArrayList<>();
Schema timeStampField = Schema.create(Schema.Type.LONG);
fields.add(new Schema.Field("timestamp", LogicalTypes.timestampMillis().addToSchema(timeStampField), null, null));
Schema resultSchema = Schema.createRecord("MyRecord", null, "org.demo", false, fields);
System.out.println(resultSchema);
</code>```

your schema:

```<code>{"type":"record","name":"MyRecord","namespace":"org.demo","fields":[{"name":"timestamp","type":"long"}]}
</code>```

resultSchema with timestampMillis:

```<code>{"type":"record","name":"MyRecodr","namespace":"org.demo","fields":[{"name":"timestamp","type":{"type":"long","logicalType":"timestamp-millis"}}]}
</code>```

Title: Avro Java API Timestamp Logical Type?

Body:
With the Avro Java API, I can make a simple record schema like:

    Schema schemaWithTimestamp = SchemaBuilder
            .record("MyRecord").namespace("org.demo")
            .fields()
            .name("timestamp").type().longType().noDefault()
            .endRecord();

How do I tag a schema field with a logical type, specifically:
https://avro.apache.org/docs/1.8.1/api/java/org/apache/avro/LogicalTypes.TimestampMillis.html

Body:
I think you may create schema manually:

List<Schema.Field> fields = new ArrayList<>();
Schema timeStampField = Schema.create(Schema.Type.LONG);
fields.add(new Schema.Field("timestamp", LogicalTypes.timestampMillis().addToSchema(timeStampField), null, null));
Schema resultSchema = Schema.createRecord("MyRecord", null, "org.demo", false, fields);
System.out.println(resultSchema);

your schema:

{"type":"record","name":"MyRecord","namespace":"org.demo","fields":[{"name":"timestamp","type":"long"}]}

resultSchema with timestampMillis:

{"type":"record","name":"MyRecodr","namespace":"org.demo","fields":[{"name":"timestamp","type":{"type":"long","logicalType":"timestamp-millis"}}]}


来源: stackexchange

问:
How to yank to host clipboard from inside a Docker container?
I have Vim installed inside a docker container.

I want to yank some text and somehow magically make it available on my host (macOS) clipboard.

Is that even possible?

UPDATE

So to clarify, this is my full use case...

docker run ... some container with Vim baked into the image

the default CMD will drop me into bash shell

I'm mounting an app directory from my host (macOS) into the container

from the container I run vim, write some code

from vim I want to yank some text and have it in both:

the docker system clipboard (so I can paste it into the container shell if I want)

the host (macOS) system clipboard (so I can paste it into other host programs; TextEdit or email, whatever)

Now I'm not sure how this works in the sense of the host (macOS) has to use a VM provided by the docker ecosystem in order to run docker in the first place (as macOS is not a Linux based system and as such can't natively run docker containers without an intermediary VM).

So I'm not sure if the tricks for getting content into the docker system clipboard will filter back through to the VM and into the actual (macOS) host.

x11

I've seen people suggest using X11 and mounting its socket file into the docker container, then using xclip (or xsel). I tried this but was unable to get Vim to yank into the appropriate register for xclip to pick up the yanked content. So subsequently I wasn't sure if my attempt to setup and mount x11 worked either:

brew install Caskroom/cask/xquartz

open -a XQuartz

as part of docker run -v /tmp/.X11-unix:/tmp/.X11-unix

from inside container apt-get install -y xclip

from within vim in the container "*yiw (select the "* selection register and then yiw yank the current word under the cursor) < but seems vim 8 inside of the container has no such register available to yank into? my vimrc that I've mounted into the container already has set clipboard+=unnamed (which is what I've used in the past to get vim to yank to the macOS system clipboard)

Note: if I tried to use xclip directly (just to see how it worked), most of what I tried resulted in Error: Can't open display: (null).

答:
It definitely is.

Take a look at https://github.com/wincent/clipper

It's a service that let's you write to clipboard using netcat.

All you would have to do would be to be able to access your machine's localhost from inside a docker container.

ContentLicense: CC BY-SA 3.0


问:
Eclipse IDE project directory structure help [Java]
I have been learning Java and have had no problem with projects in which multiple .java files were in the same Default Package.
I am now trying to separate code and create folders for images, but everything I have tried has failed.

How do I properly add folders for images and other classes, and properly set the path to it?
All paths should be relative to the project, I know that much ;_;

Here's a link to a picture of my IDE and error message from program output:

http://img262.imageshack.us/img262/8415/directory.png

Thanks!!

答: Drag using the mouse your Textures folder to the LWJGL 6 project folder.</p>

ContentLicense: CC BY-SA 2.5


问:
Spring Boot - inject map from properties file
property file looks like this:

```<code>url1=path_to_binary1
url2=path_to_binary2
</code>```

According this I tried following approach:

```<code>@Component
@EnableConfigurationProperties
public class ApplicationProperties {
    private Map<String, String> pathMapper;

    //get and set
}
</code>```

and in another component I autowired ApplicationProperties:

```<code>@Autowired
private ApplicationProperties properties;
      //inside some method:
      properties.getPathMapper().get(appName);
</code>```

produces NullPointerException.

How to correct it?

update

I have correct according user7757360 advice:

```<code>@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix="app")
public class ApplicationProperties {
</code>```

and properties file:

```<code>app.url1=path_to_binary1
app.url2=path_to_binary2
</code>```

Still doesn't work

Update 2

```<code>@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix="app")
public class ApplicationProperties {
    private Map<String, String> app;
</code>```

and inside application.properties:

```<code>app.url1=path_to_binary1
app.url2=path_to_binary2
</code>```

Still doesn't work

答:
Have the your.properties file under src/main/resources and either have it as a

```<code>@Configuration
@PropertySource("classpath:your.properties")
public class SpringConfig(){}
</code>```

or have it as a PropertyPlaceholderConfigurer in your Spring yourApplicationContext.xml.

Then use the property values like

```<code>@Value("app.url1")
String path_to_binary1;

@Value("app.url2")
String path_to_binary2;

// ...

System.out.println(path_to_binary1+path_to_binary2);
</code>```

Body:
property file looks like this:

url1=path_to_binary1
url2=path_to_binary2

According this I tried following approach:

@Component
@EnableConfigurationProperties
public class ApplicationProperties {
    private Map<String, String> pathMapper;

    //get and set
}

and in another component I autowired ApplicationProperties:

@Autowired
private ApplicationProperties properties;
      //inside some method:
      properties.getPathMapper().get(appName);

produces NullPointerException.

How to correct it?

update

I have correct according user7757360 advice:

@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix="app")
public class ApplicationProperties {

and properties file:

app.url1=path_to_binary1
app.url2=path_to_binary2

Still doesn't work

Update 2

@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix="app")
public class ApplicationProperties {
    private Map<String, String> app;

and inside application.properties:

app.url1=path_to_binary1
app.url2=path_to_binary2

Still doesn't work

Body:
Have the your.properties file under src/main/resources and either have it as a

@Configuration
@PropertySource("classpath:your.properties")
public class SpringConfig(){}

or have it as a PropertyPlaceholderConfigurer in your Spring yourApplicationContext.xml.

Then use the property values like

@Value("app.url1")
String path_to_binary1;

@Value("app.url2")
String path_to_binary2;

// ...

System.out.println(path_to_binary1+path_to_binary2);


问:
Laravel Paginator object does not have render method
I do the following:

```<code>$array = new LengthAwarePaginator(array_slice($array, $offset, $perPage, true), count($array),$perPage, $page, ['path' => $request->url(), 'query' => $request->query()]);
dd($array->render());
</code>```

and i get the proper html output of the render method.

Then I try:

```<code>$array =  new Paginator(array_slice($array, $offset, $perPage, true), $perPage, $page, ['path' => $request->url(), 'query' => $request->query()]);
dd($array->render());
</code>```

and the output is "".

When I (dd($array)); I get :

```<code>Paginator {#310 ▼
  #hasMore: false
  #items: Collection {#315 ▶}
  #perPage: 10
  #currentPage: 1
  #path: "https://localhost/search/3"
  #query: array:1 [▶]
  #fragment: null
  #pageName: "page"
}
</code>```

Anyone know why my Paginator doesn't have a render method?

答: The problem was because of a misunderstanding in the way Illuminate\Pagination\Paginator works. For the this object you cannot pass in an array of size $perPage like you do with a LengthAwarePaginator because this Paginator would then not know whether there is a next page or not. So, the solution that I came up with (although I have not found any docs which mention this) is to pass in array_slice($array, $offset, $perPage * 2, true) as input to the Paginator. This way it always knows whether there are more and I still don't need to know how many total items there are.

Body:
I do the following:

$array = new LengthAwarePaginator(array_slice($array, $offset, $perPage, true), count($array),$perPage, $page, ['path' => $request->url(), 'query' => $request->query()]);
dd($array->render());

and i get the proper html output of the render method.

Then I try:

$array =  new Paginator(array_slice($array, $offset, $perPage, true), $perPage, $page, ['path' => $request->url(), 'query' => $request->query()]);
dd($array->render());

and the output is "".

When I (dd($array)); I get :

Paginator {#310 ▼
  #hasMore: false
  #items: Collection {#315 ▶}
  #perPage: 10
  #currentPage: 1
  #path: "https://localhost/search/3"
  #query: array:1 [▶]
  #fragment: null
  #pageName: "page"
}

Anyone know why my Paginator doesn't have a render method?


问:
CSS - border not going over elements that float left
I have this code here:

```<code><div style="border:3px solid #808080;">
    <h1 style="text-transform: uppercase;font-size: 38px;color: #808080;text-align: center;">Lowell</h1>
    <div class="column-1">
         <img src="images/ruler-icon.png">
    </div>
    <div class="column-2">
         <img src="images/bed-icon.png">
    </div>
    <div class="column-3">
         <img src="images/bath-icon.png">
    </div>
</div>
</code>```

my problem is that the border does not go over the column-1, column-2, column-3...those elements are floating left, how do I get them to be included in the border?

Here is the CSS

```<code>.column-1, .column-2, .column-3
{
    float:left;
    width: 33%;
    border-right: 3px solid #808080;
    height: 52px;
    padding: 10px;
}
</code>```

答:
Either add a div in parent with clear:both property right after the floated divs as mentioned by RemyaJ. like this

https://jsfiddle.net/zmasvt8b/

Or

Simply give overflow:hidden property to the parent div. Like this

https://jsfiddle.net/jv5xtLg9/

Body:
I have this code here:

Lowell

my problem is that the border does not go over the column-1, column-2, column-3...those elements are floating left, how do I get them to be included in the border?

Here is the CSS

.column-1, .column-2, .column-3
{
    float:left;
    width: 33%;
    border-right: 3px solid #808080;
    height: 52px;
    padding: 10px;
}


问:
Application lifecycle when app is killed in the background
Some background on a problem that I have been encountering: in my app I have a singleton object that I use regularly to access things like id and token for network calls.  Sometimes when the app is killed in the background, this singleton loses its state. However, when the app is opened again and starts up in some Activity past the launcher Activity, the singleton is null.

I am in the process of refactoring this, but have been agonizing over how to ensure that the singleton will always be present even in app restart, but I'm not sure what Android does when the app restarts from being backgrounded.

I went through source code in some of the libraries we use in the app (Facebook, Intercom) to see how they manage their singletons and why their static variables seemed to just always be present, and came upon a theory.

So on a normal app cold start, the app behaves like this:

```<code>Application.onCreate() -> Launcher.onCreate() -> Activity A -> Activity B
</code>```

Say the user was in Activity B and backgrounds the app.  After using some other apps, they come back to my app but it has been killed at some point in between. The lifecycle then becomes this:

```<code>Application.onCreate() -> Activity B
</code>```

I think the problem is that I initialize the singleton in the launcher Activity, and as a result, when B tries to get a value from the singleton, it comes up null.  If I initialize the singleton in Application.onCreate(), it will always be initialized when the app is pulled up again.  Is this correct?

TL;DR An application that is killed and brought to foreground again will always call its Application.onCreate() and then forward directly to the Activity it was on. Therefore, app initializations that are critical to the app functioning should live in the Application onCreate().

答: Yes, the Application.onCreate() is called always when the app comes to foreground, so every Singleton that you need to initialize must be there.

Body:
Some background on a problem that I have been encountering: in my app I have a singleton object that I use regularly to access things like id and token for network calls.  Sometimes when the app is killed in the background, this singleton loses its state. However, when the app is opened again and starts up in some Activity past the launcher Activity, the singleton is null.

I am in the process of refactoring this, but have been agonizing over how to ensure that the singleton will always be present even in app restart, but I'm not sure what Android does when the app restarts from being backgrounded.

I went through source code in some of the libraries we use in the app (Facebook, Intercom) to see how they manage their singletons and why their static variables seemed to just always be present, and came upon a theory.

So on a normal app cold start, the app behaves like this:

Application.onCreate() -> Launcher.onCreate() -> Activity A -> Activity B

Say the user was in Activity B and backgrounds the app.  After using some other apps, they come back to my app but it has been killed at some point in between. The lifecycle then becomes this:

Application.onCreate() -> Activity B

I think the problem is that I initialize the singleton in the launcher Activity, and as a result, when B tries to get a value from the singleton, it comes up null.  If I initialize the singleton in Application.onCreate(), it will always be initialized when the app is pulled up again.  Is this correct?

TL;DR An application that is killed and brought to foreground again will always call its Application.onCreate() and then forward directly to the Activity it was on. Therefore, app initializations that are critical to the app functioning should live in the Application onCreate().


答:
The reason for this is that parent elements are never to contain floated elements. To make this happen, just add overflow:auto; to your main div. That will force the div to contain floated elements that "overflow" the container.

There are other, probably better ways to accomplish the same thing but this is the easiest.

Never, ever add HTML elements to do what CSS can and should do.

Title: CSS - border not going over elements that float left


问:
how to set chart.js grid color for line chart
I want to change the grids color of my line chart using options field but I have no idea from where to begin.
I First tried to change the canvas backgroud colors using gradient but the results weren't good.

```<code>canvas{
background:linear-gradient(top, #ea1a07 0%, #f4b841 75%,#f2dd43 100%);
}
</code>```

However, I didn't get what I want because as you see in the above image, not only the grids were colored but also the x values, y labels and the chart legend were colored too.

Picture of the result I'm getting with this css code

Example of what I want to get

my chart.js options are

```<code>options = {
        scales: {
          xAxes: [{
            gridLines: {
              color: 'rgba(171,171,171,1)',
              lineWidth: 1
            }
          }],
          yAxes: [{
            ticks: {
              beginAtZero: true,
              max: 100,
              min: 0,
              stepSize: 10
            },
            gridLines: {
              color: 'rgba(171,171,171,1)',
              lineWidth: 0.5
            }
          }]
        },
        responsive: true
      };
</code>```

So, is there a way to set only the grid's background to 3 different colors (with gradient or not)?
NB: I'm using chart.js with angular 2 (ng2-charts)

答:
The easiest way to do this is to use the chartjs-plugin-annotation plugin and configure 3 box annotations bound to your Y axis (each box would have a different color).

Here is an example below (and you can see it in action with this codepen).

```<code>var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: 'Points',
      data: [
        {x: 0, y: 2},
        {x: 1, y: 3},
        {x: 2, y: 2},
        {x: 1.02, y: 0.4},
        {x: 0, y: -1}
      ],
      backgroundColor: 'rgba(123, 83, 252, 0.8)',
      borderColor: 'rgba(33, 232, 234, 1)',
      borderWidth: 1,
      fill: false,
    }],
  },
  options: {
    title: {
      display: true,
      text: 'Chart.js - Gridline Background',
    },
    scales: {
      xAxes: [{
        type: 'linear',
        position: 'bottom',
        ticks: {
          min: -1,
          max: 8,
          stepSize: 1,
          fixedStepSize: 1,
        },
        gridLines: {
          color: 'rgba(171,171,171,1)',
          lineWidth: 1
        }
      }],
      yAxes: [{
        afterUpdate: function(scaleInstance) {
          console.dir(scaleInstance);
        },
        ticks: {
          min: -2,
          max: 4,
          stepSize: 1,
          fixedStepSize: 1,
        },
        gridLines: {
          color: 'rgba(171,171,171,1)',
          lineWidth: 0.5
        }
      }]
    },
    annotation: {
      annotations: [{
        type: 'box',
        yScaleID: 'y-axis-0',
        yMin:  1,
        yMax: 4,
        borderColor: 'rgba(255, 51, 51, 0.25)',
        borderWidth: 2,
        backgroundColor: 'rgba(255, 51, 51, 0.25)',
      }, {
        type: 'box',
        yScaleID: 'y-axis-0',
        yMin:  -1,
        yMax: 1,
        borderColor: 'rgba(255, 255, 0, 0.25)',
        borderWidth: 1,
        backgroundColor: 'rgba(255, 255, 0, 0.25)',
      }, {
        type: 'box',
        yScaleID: 'y-axis-0',
        yMin:  -2,
        yMax: -1,
        borderColor: 'rgba(0, 204, 0, 0.25)',
        borderWidth: 1,
        backgroundColor: 'rgba(0, 204, 0, 0.25)',
      }],
    }
  }
});
</code>```

It's important to note that the annotations are painted on top of the chart, so your annotation color needs to contain some transparency to see the stuff behind it.

There is no problem using this plugin with ng2-charts.  Just add the source in a

Body:
I want to change the grids color of my line chart using options field but I have no idea from where to begin.
I First tried to change the canvas backgroud colors using gradient but the results weren't good.

canvas{
background:linear-gradient(top, #ea1a07 0%, #f4b841 75%,#f2dd43 100%);
}

However, I didn't get what I want because as you see in the above image, not only the grids were colored but also the x values, y labels and the chart legend were colored too.

Picture of the result I'm getting with this css code

Example of what I want to get

my chart.js options are

options = {
        scales: {
          xAxes: [{
            gridLines: {
              color: 'rgba(171,171,171,1)',
              lineWidth: 1
            }
          }],
          yAxes: [{
            ticks: {
              beginAtZero: true,
              max: 100,
              min: 0,
              stepSize: 10
            },
            gridLines: {
              color: 'rgba(171,171,171,1)',
              lineWidth: 0.5
            }
          }]
        },
        responsive: true
      };

So, is there a way to set only the grid's background to 3 different colors (with gradient or not)?
NB: I'm using chart.js with angular 2 (ng2-charts)

Body:
The easiest way to do this is to use the chartjs-plugin-annotation plugin and configure 3 box annotations bound to your Y axis (each box would have a different color).

Here is an example below (and you can see it in action with this codepen).

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: 'Points',
      data: [
        {x: 0, y: 2},
        {x: 1, y: 3},
        {x: 2, y: 2},
        {x: 1.02, y: 0.4},
        {x: 0, y: -1}
      ],
      backgroundColor: 'rgba(123, 83, 252, 0.8)',
      borderColor: 'rgba(33, 232, 234, 1)',
      borderWidth: 1,
      fill: false,
    }],
  },
  options: {
    title: {
      display: true,
      text: 'Chart.js - Gridline Background',
    },
    scales: {
      xAxes: [{
        type: 'linear',
        position: 'bottom',
        ticks: {
          min: -1,
          max: 8,
          stepSize: 1,
          fixedStepSize: 1,
        },
        gridLines: {
          color: 'rgba(171,171,171,1)',
          lineWidth: 1
        }
      }],
      yAxes: [{
        afterUpdate: function(scaleInstance) {
          console.dir(scaleInstance);
        },
        ticks: {
          min: -2,
          max: 4,
          stepSize: 1,
          fixedStepSize: 1,
        },
        gridLines: {
          color: 'rgba(171,171,171,1)',
          lineWidth: 0.5
        }
      }]
    },
    annotation: {
      annotations: [{
        type: 'box',
        yScaleID: 'y-axis-0',
        yMin:  1,
        yMax: 4,
        borderColor: 'rgba(255, 51, 51, 0.25)',
        borderWidth: 2,
        backgroundColor: 'rgba(255, 51, 51, 0.25)',
      }, {
        type: 'box',
        yScaleID: 'y-axis-0',
        yMin:  -1,
        yMax: 1,
        borderColor: 'rgba(255, 255, 0, 0.25)',
        borderWidth: 1,
        backgroundColor: 'rgba(255, 255, 0, 0.25)',
      }, {
        type: 'box',
        yScaleID: 'y-axis-0',
        yMin:  -2,
        yMax: -1,
        borderColor: 'rgba(0, 204, 0, 0.25)',
        borderWidth: 1,
        backgroundColor: 'rgba(0, 204, 0, 0.25)',
      }],
    }
  }
});

It's important to note that the annotations are painted on top of the chart, so your annotation color needs to contain some transparency to see the stuff behind it.

There is no problem using this plugin with ng2-charts.  Just add the source in a <script> in your app's html file and add the annotation property into your options object.  Here is an Angular2 / ng2-charts example demonstrating how to use the annotations plugin.


问:
Upload an image (Base64) using Alamofire Swift 3
Iam trying to upload 2 images to server with JSON request using alamofire

and here's my code :

```<code>   let parameters = ["CreditCardImage":CreditCardImage,"CreditCardBackImage":CreditCardBackImage , "CustomerID" : CustomerID]

            let headers: HTTPHeaders = [
                "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
                "Accept": "application/json"
            ]

   Alamofire.request("MY URL", method : .post , parameters : parameters, encoding: JSONEncoding.default ,  headers: headers).responseJSON { response in

        // get json Response

        let json = JSON(response.result.value)

        print(json)

   }
</code>```

When i print the response iam getting message <<  unknown  >> in the console

and i tried that in postman it's not working too what's wrong with that ? any help ?

答:
you should use other Alamofire methods. Here is an example:

```<code>func uploadAvatar(image: UIImage) {
    Alamofire.upload(multipartFormData: { multipartFormData in
        if let imageData = UIImageJPEGRepresentation(image, 1) {
            multipartFormData.append(imageData, withName: "file", fileName: "file.png", mimeType: "image/png")
        }
    }, to: self.serverAddress + "/user/uploadAvatar", method: .post, headers: ["Authorization": User.shared.token], encodingCompletion: { _ in })
}
</code>```

Body:
Iam trying to upload 2 images to server with JSON request using alamofire

and here's my code :

   let parameters = ["CreditCardImage":CreditCardImage,"CreditCardBackImage":CreditCardBackImage , "CustomerID" : CustomerID]

            let headers: HTTPHeaders = [
                "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
                "Accept": "application/json"
            ]

   Alamofire.request("MY URL", method : .post , parameters : parameters, encoding: JSONEncoding.default ,  headers: headers).responseJSON { response in

        // get json Response

        let json = JSON(response.result.value)

        print(json)

   }

When i print the response iam getting message <<  unknown  >> in the console

and i tried that in postman it's not working too what's wrong with that ? any help ?

Body:
you should use other Alamofire methods. Here is an example:

func uploadAvatar(image: UIImage) {
    Alamofire.upload(multipartFormData: { multipartFormData in
        if let imageData = UIImageJPEGRepresentation(image, 1) {
            multipartFormData.append(imageData, withName: "file", fileName: "file.png", mimeType: "image/png")
        }
    }, to: self.serverAddress + "/user/uploadAvatar", method: .post, headers: ["Authorization": User.shared.token], encodingCompletion: { _ in })
}


问:
link django user to perticular site in site framework
I've setup Django sites framework in my project,
actually, i want to combine Django user to that particular site

What I want to achieve is that when user register from particular site or subsite which register with site framework then that user has to link to that particular site so that we can restrict a user to login to another site with their associate site credential.

答:
According to https://docs.djangoproject.com/en/1.10/ref/contrib/sites/

we bind model
`

```<code>from django.db import models
from django.contrib.sites.models import Site

class Article(models.Model):
    headline = models.CharField(max_length=200)
    # ...
    site = models.ForeignKey(Site, on_delete=models.CASCADE)
</code>```

`

so if we use different database for different site then there is no meaning of this because site table also changes for different site right

I need one database but differenciate user according site like above model using foreign key

Body:
According to https://docs.djangoproject.com/en/1.10/ref/contrib/sites/

we bind model
`

from django.db import models
from django.contrib.sites.models import Site

class Article(models.Model):
    headline = models.CharField(max_length=200)
    # ...
    site = models.ForeignKey(Site, on_delete=models.CASCADE)

`

so if we use different database for different site then there is no meaning of this because site table also changes for different site right

I need one database but differenciate user according site like above model using foreign key


问:
JavaScript variable empty after call of getJSON()
I'm having this issue with importing data from a JSON file. I use the .getJSON function to get the data which means to work according to the console log, but once I move out of the getJSON sub function the array in data2 disappears. I've narrowed it down to this section here:

```<code>function prepData() {
    data2 = [];

    $.getJSON('http://localhost/data').done(function(json) {
        data2 =json;
        console.log(data2);
    });

    console.log(data2);
    SelectedData = data2;
    return SelectedData;
};
</code>```

What might the issue be here?

答:
Your function:

```<code>function(json) {
    data2 = json;
}
</code>```

is executed after

```<code>console.log(data2);
SelectedData = data2;
</code>```

data2 is not defined yet at that point.

```<code>(1) function prepData(){
(2)    data2 = [];

(3)    $.getJSON('http://localhost/data').done(function(json) {
(4)        data2 =json;
(5)        console.log(data2);
       });

(6)    console.log(data2);
(7)    SelectedData= data2;
(8)    return SelectedData;
   };
</code>```

Execution order:

```<code>1 -> 2 -> 3 -> 6 -> 7 -> 8 -> 4 -> 5
</code>```

Common practice - Return promise instead of data:

```<code>function prepData(){
    return $.getJSON('http://localhost/data');
}

// more code here

prepData().done(function(json){
    console.log(json);
});
</code>```

Take a look at these more detailed demos.

jQuery on ES5: https://jsfiddle.net/DerekL/xtmy6po0/

```<code>function timeout(n){
    // create promise
    var defer = $.Deferred();

    // resolve after n milliseconds
    setTimeout(function(){
        defer.resolve(n);
    }, n);

    // return new promise that apply custom text
    return defer.then(function(v){
        return "Resolved after " + (v/1000) + " seconds";
    });
}

timeout(3000).then(function(message){
    // will be executed after 3 seconds
    alert(message);
});
</code>```

Equivalent ES7: https://jsfiddle.net/DerekL/8kLknbne/

```<code>async function timeout(n){
    // create timer
    let timer = () => new Promise(resolve => setTimeout(() => resolve(n), n));
    // return message
    return "Resolved after " + (await timer()/1000) + " seconds";
}

// call
timeout(3000).then(alert);
</code>```

Body:
I'm having this issue with importing data from a JSON file. I use the .getJSON function to get the data which means to work according to the console log, but once I move out of the getJSON sub function the array in data2 disappears. I've narrowed it down to this section here:

function prepData() {
    data2 = [];

    $.getJSON('http://localhost/data').done(function(json) {
        data2 =json;
        console.log(data2);
    });

    console.log(data2);
    SelectedData = data2;
    return SelectedData;
};

What might the issue be here?

Body:
Your function:

function(json) {
    data2 = json;
}

is executed after

console.log(data2);
SelectedData = data2;

data2 is not defined yet at that point.

(1) function prepData(){
(2)    data2 = [];

(3)    $.getJSON('http://localhost/data').done(function(json) {
(4)        data2 =json;
(5)        console.log(data2);
       });

(6)    console.log(data2);
(7)    SelectedData= data2;
(8)    return SelectedData;
   };

Execution order:

1 -> 2 -> 3 -> 6 -> 7 -> 8 -> 4 -> 5

Common practice - Return promise instead of data:

function prepData(){
    return $.getJSON('http://localhost/data');
}

// more code here

prepData().done(function(json){
    console.log(json);
});

Take a look at these more detailed demos.

jQuery on ES5: https://jsfiddle.net/DerekL/xtmy6po0/

function timeout(n){
    // create promise
    var defer = $.Deferred();

    // resolve after n milliseconds
    setTimeout(function(){
        defer.resolve(n);
    }, n);

    // return new promise that apply custom text
    return defer.then(function(v){
        return "Resolved after " + (v/1000) + " seconds";
    });
}

timeout(3000).then(function(message){
    // will be executed after 3 seconds
    alert(message);
});

Equivalent ES7: https://jsfiddle.net/DerekL/8kLknbne/

async function timeout(n){
    // create timer
    let timer = () => new Promise(resolve => setTimeout(() => resolve(n), n));
    // return message
    return "Resolved after " + (await timer()/1000) + " seconds";
}

// call
timeout(3000).then(alert);


问:
Joining two tables to fetch count
I've two tables with the following schema

```<code>GROUP_ID | PURCHASE_ID |ITEMS  ---> TABLE1
  1            21         X
  1            21         Y
  1            21         Z
  2            22         X

GROUP_ID  |CUSTOMER_ID |ITEMS  --->TABLE2
1             ABC        X
1             ABC        Y
1             ABC        Z
1             ABC        A
1             ABC        B
</code>```

A single GROUP_ID and PURCHASE_ID can have multiple items and similarly a single GROUP_ID and CUSTOMER_ID can have multiple ITEMS.The number of items bought will be only two or three per GROUP_ID and per PURCHASE_ID but a given CUSTOMER_ID,GROUP_ID can have a n number of items.

I want to query for each GROUP_ID and PURCHASE_ID and ITEMS[set], how many customers have bought at least all the ITEMS.

```<code>select distinct GROUP_ID,PURCHASE_ID,count(object_id)over(partition by GROUP_ID,PURCHASE_ID) from
        (select a.GROUP_ID GROUP_ID,a.PURCHASE_ID PURCHASE_ID,b.CUSTOMER_ID object_id from
        (select GROUP_ID,PURCHASE_ID,items,count(items)over(partition by GROUP_ID,PURCHASE_ID) val from  TABLE1)a,
        (select GROUP_ID,CUSTOMER_ID,ITEMS from TABLE2)b
        where a.GROUP_ID=b.GROUP_ID and a.items=b.ITEMS and val=3
        group by a.GROUP_ID,a.PURCHASE_ID,b.CUSTOMER_ID
        having count(*)=3)
</code>```

For the above given data for GROUP_ID=1 and PURCHASE_ID=21 the count should be 1 since there exists a customer with ID ABC who has the subset of items [X,Y,Z]
I've written code to fetch the count of customers for three items as above. Is there any way to optimize this or achieve this.

Any help is much appreciated

答:
This is a tricky one; I usually join the two tables on all the required columns and look for distinct counts to match like so:

```<code>select t1.group_id,
    t1.purchase_id,
    count(distinct t2.customer_id) as customer_count
from Table1 as t1
inner join Table2 as t2
on t2.group_id = t1.group_id
and t2.items = t1.items
group by t1.group_id,
    t1.purchase_id
having count(distinct t2.items) >= count(distinct t1.items)
</code>```

This is untested so try it and let me know if it works or not.

Title: Joining two tables to fetch count

Body:
I've two tables with the following schema

GROUP_ID | PURCHASE_ID |ITEMS  ---> TABLE1
  1            21         X
  1            21         Y
  1            21         Z
  2            22         X

GROUP_ID  |CUSTOMER_ID |ITEMS  --->TABLE2
1             ABC        X
1             ABC        Y
1             ABC        Z
1             ABC        A
1             ABC        B

A single GROUP_ID and PURCHASE_ID can have multiple items and similarly a single GROUP_ID and CUSTOMER_ID can have multiple ITEMS.The number of items bought will be only two or three per GROUP_ID and per PURCHASE_ID but a given CUSTOMER_ID,GROUP_ID can have a n number of items.

I want to query for each GROUP_ID and PURCHASE_ID and ITEMS[set], how many customers have bought at least all the ITEMS.

select distinct GROUP_ID,PURCHASE_ID,count(object_id)over(partition by GROUP_ID,PURCHASE_ID) from
        (select a.GROUP_ID GROUP_ID,a.PURCHASE_ID PURCHASE_ID,b.CUSTOMER_ID object_id from
        (select GROUP_ID,PURCHASE_ID,items,count(items)over(partition by GROUP_ID,PURCHASE_ID) val from  TABLE1)a,
        (select GROUP_ID,CUSTOMER_ID,ITEMS from TABLE2)b
        where a.GROUP_ID=b.GROUP_ID and a.items=b.ITEMS and val=3
        group by a.GROUP_ID,a.PURCHASE_ID,b.CUSTOMER_ID
        having count(*)=3)

For the above given data for GROUP_ID=1 and PURCHASE_ID=21 the count should be 1 since there exists a customer with ID ABC who has the subset of items [X,Y,Z]
I've written code to fetch the count of customers for three items as above. Is there any way to optimize this or achieve this.

Any help is much appreciated

Body:
This is a tricky one; I usually join the two tables on all the required columns and look for distinct counts to match like so:

select t1.group_id,
    t1.purchase_id,
    count(distinct t2.customer_id) as customer_count
from Table1 as t1
inner join Table2 as t2
on t2.group_id = t1.group_id
and t2.items = t1.items
group by t1.group_id,
    t1.purchase_id
having count(distinct t2.items) >= count(distinct t1.items)

This is untested so try it and let me know if it works or not.


问:
How to drop these rows in Pandas?
I am trying to drop the rows in my pandas dataframe that have no price in them. Technically, in the data source the dollar sign ($) appears by default so
df1.dropna(subset=['Price ($)'], inplace = True) does not work in my case. How can I drop the rows that have no price attached to them.

```<code>import pandas as pd

first = pd.read_excel('......')
df1 = pd.DataFrame(first)

   Car                          Price ($)

   Honda                          $200
   Benz                           $             ----------> drop
   Chevy                          $300
   BMW                            $250
   Kia                            $             ----------> drop
</code>```

答:
The other answer would work perfectly fine but here is another approach

```<code>df = df[df['Price ($)'].str.contains('\d+')]
</code>```

This would ensure that you get only the rows where there is a numeric price available in the Price column. As a bonus, this is also faster:)

Title: How to drop these rows in Pandas?

Body:
I am trying to drop the rows in my pandas dataframe that have no price in them. Technically, in the data source the dollar sign ($) appears by default so
df1.dropna(subset=['Price ($)'], inplace = True) does not work in my case. How can I drop the rows that have no price attached to them.

import pandas as pd

first = pd.read_excel('......')
df1 = pd.DataFrame(first)

   Car                          Price ($)

   Honda                          $200
   Benz                           $             ----------> drop
   Chevy                          $300
   BMW                            $250
   Kia                            $             ----------> drop

Body:
The other answer would work perfectly fine but here is another approach

df = df[df['Price ($)'].str.contains('\d+')]

This would ensure that you get only the rows where there is a numeric price available in the Price column. As a bonus, this is also faster:)


问:
What does the regex (?<n>a)(b)\2(c) match?
What does this regex match?

```<code>(?<n>a)(b)\2(c)
</code>```

It doesn't match abc, abac, abbc, abcc, or ab\x02c and it doesn't throw an exception.

If you take off the (c) it matches aba. My understanding is that unnamed captures get numbered first, and then the named captures. So (c) should get 2, except that I try to back-reference it before it's defined, so I thought maybe it would match a and a would get renumbered when it hits c, but that doesn't appear to be the case either.

答:
a's backreference is 'n'.  b's reference is '1' and the third is '2'

```<code>(?<n>a)(b)\1(c) matches abbc where n is a, 1 is b and 2 is c
</code>```

it numbers unnamed back references with 1 and counts up.  Non-capturing parentheses are not numbered.  So, it can't match anything.

Regular-Expressions.info on Brackets

Body:
What does this regex match?

(?<n>a)(b)\2(c)

It doesn't match abc, abac, abbc, abcc, or ab\x02c and it doesn't throw an exception.

If you take off the (c) it matches aba. My understanding is that unnamed captures get numbered first, and then the named captures. So (c) should get 2, except that I try to back-reference it before it's defined, so I thought maybe it would match a and a would get renumbered when it hits c, but that doesn't appear to be the case either.

Body:
a's backreference is 'n'.  b's reference is '1' and the third is '2'

(?<n>a)(b)\1(c) matches abbc where n is a, 1 is b and 2 is c

it numbers unnamed back references with 1 and counts up.  Non-capturing parentheses are not numbered.  So, it can't match anything.

Regular-Expressions.info on Brackets


问:
How to keep a running total in php foreach loop
I am trying to create a table that displays member data for three different types of members - it should display how many members were added each day, and then there needs to be a column that keeps a cumulative total month to date for the three different types of members. Example:

Members Added in March:

Date      Type A      Type A Total      Type B      Type B Total

1             23                23                   16                  16

2             13                36                   13                  29

3             16                52                   17                  46

My query looks like this:

```<code>$results=$wpdb->get_results("SELECT DAY(Subscription_Start_Date) as dayOfMonth, COUNT(a.user_id) as typeA, COUNT(b.user_id) as typeB, COUNT(c.user_id) as typeC
FROM users u
LEFT OUTER JOIN typeAUser a ON u.type_id = a.User_Id
LEFT OUTER JOIN typeBUser b ON u.type_id = b.User_Id
LEFT OUTER JOIN typeCUser c ON u.type_id = c.user_Id AND c.phone_opt_out != '1'
WHERE MONTH(Subscription_Start_Date) = MONTH(curdate()) AND YEAR(Subscription_Start_Date) = YEAR(curdate())
GROUP BY DAY(Subscription_Start_Date)
ORDER BY DAY(Subscription_Start_Date)");
</code>```

I am outputting the data into a table using a foreach loop like so:

```<code>$resultTable = "<table><thead>
        <tr><td colspan='7'>Month to Date Members Added $currentMonth</td></tr>
        <tr>
        <th>Day of the Month</th>
        <th>Type A</th>
        <th>Type A Month to Date</th>
        <th>Type B</th>
        <th>Type B Month to Date</th>
        <th>Type C</th>
        <th>Type C Month to Date</th>
        </tr></thead><tbody>";

foreach($results as $r){
    $aMemPerDay = $r->typeA;
    $bMemPerDay = $r->typeB;
    $cMemPerDay = $r->typeC;

    $resultTable .= "<tr>
        <td>$r->dayOfMonth</td>
        <td>$aMemPerDay</td>
        <td>???</td>
        <td>$bMemPerDay</td>
        <td>???</td>
        <td>$cMemPerDay</td>
        <td>???</td>
        </tr>";
}
$resultTable .="</tbody></table>";

echo $resultTable;
</code>```

The query returns the info I need for the number of members added per day, but I can't figure out how to keep a running total that increase each day. I have tried many things, but nothing seems to work. I tried implementing a variation of this solution within the foreach on each of the member types but when I put the $totalA variable into the table, it just printed out Array:

```<code>$totalA = array();
$runningSumA = 0;

foreach ($aMemPerDay as $aMem) {
    $runningSumA += $aMem;
    $totalA[] = $runningSum;
}
</code>```

I even tried using a MySQL variable in the query (since there are only 30 days per month, I figured it wouldn't be overly cumbersome), but I wasn't able to get a cumulative result there either. I know that there is probably some manageable answer out there, but I can't seem to come up with it. Any direction would be appreciated!

答:
```<code>$TotalA = 0;
$TotalB = 0;
$TotalC = 0;

foreach($results as $r){
    $aMemPerDay = $r->typeA;
    $bMemPerDay = $r->typeB;
    $cMemPerDay = $r->typeC;

    $TotalA += $aMemPerDay;
    $TotalB += $bMemPerDay;
    $TotalC += $bMemPerDay;

    $resultTable .= "<tr>
        <td>$r->dayOfMonth</td>
        <td>$aMemPerDay</td>
        <td>???</td>
        <td>$bMemPerDay</td>
        <td>???</td>
        <td>$cMemPerDay</td>
        <td>???</td>
        </tr>";
}
</code>```

Body:
I am trying to create a table that displays member data for three different types of members - it should display how many members were added each day, and then there needs to be a column that keeps a cumulative total month to date for the three different types of members. Example:

Members Added in March:

Date      Type A      Type A Total      Type B      Type B Total

1             23                23                   16                  16

2             13                36                   13                  29

3             16                52                   17                  46

My query looks like this:

$results=$wpdb->get_results("SELECT DAY(Subscription_Start_Date) as dayOfMonth, COUNT(a.user_id) as typeA, COUNT(b.user_id) as typeB, COUNT(c.user_id) as typeC
FROM users u
LEFT OUTER JOIN typeAUser a ON u.type_id = a.User_Id
LEFT OUTER JOIN typeBUser b ON u.type_id = b.User_Id
LEFT OUTER JOIN typeCUser c ON u.type_id = c.user_Id AND c.phone_opt_out != '1'
WHERE MONTH(Subscription_Start_Date) = MONTH(curdate()) AND YEAR(Subscription_Start_Date) = YEAR(curdate())
GROUP BY DAY(Subscription_Start_Date)
ORDER BY DAY(Subscription_Start_Date)");

I am outputting the data into a table using a foreach loop like so:

$resultTable = "

Month to Date Members Added $currentMonth

        Day of the Month
        Type A
        Type A Month to Date
        Type B
        Type B Month to Date
        Type C
        Type C Month to Date

";

foreach($results as $r){
    $aMemPerDay = $r->typeA;
    $bMemPerDay = $r->typeB;
    $cMemPerDay = $r->typeC;

    $resultTable .= "

        $r->dayOfMonth
        $aMemPerDay
        ???
        $bMemPerDay
        ???
        $cMemPerDay
        ???

";
}
$resultTable .="

";

echo $resultTable;

The query returns the info I need for the number of members added per day, but I can't figure out how to keep a running total that increase each day. I have tried many things, but nothing seems to work. I tried implementing a variation of this solution within the foreach on each of the member types but when I put the $totalA variable into the table, it just printed out Array:

$totalA = array();
$runningSumA = 0;

foreach ($aMemPerDay as $aMem) {
    $runningSumA += $aMem;
    $totalA[] = $runningSum;
}

I even tried using a MySQL variable in the query (since there are only 30 days per month, I figured it wouldn't be overly cumbersome), but I wasn't able to get a cumulative result there either. I know that there is probably some manageable answer out there, but I can't seem to come up with it. Any direction would be appreciated!


问:
How to make multi level treeview in JavaFX?
I have the following code. This successfully creates a root view with a Model1 and a Model1. I am having trouble adding items to Model1 though. How can I do that?</p>

```<code>@FXML
TreeView<String> locationTreeView;

public void loadTreeItems()
{

    ArrayList<String> rootItems = new ArrayList<String>();
    rootItems.add("Model1");
    rootItems.add("Model2");
    TreeItem<String> root = new TreeItem<String>("Root");

    root.setExpanded(true);
    for (String itemString : rootItems)
    {
        root.getChildren().add(new TreeItem<String>(itemString));
    }

    locationTreeView.setRoot(root);
}
</code>```

答:
Just add them to the tree items you create, in the same way you added to the root item:

```<code>public void loadTreeItems()
{

    TreeItem<String> root = new TreeItem<String>("Root");

    root.setExpanded(true);

    TreeItem<String> model1 = new TreeItem<String>("Model1");
    TreeItem<String> model2 = new TreeItem<String>("Model2");

    TreeItem<String> model11 = new TreeItem<String>("Model1.1");
    TreeItem<String> model12 = new TreeItem<String>("Model1.2");

    root.getChildren().add(model1);
    root.getChildren().add(model2);

    model1.getChildren().add(model11);
    model1.getChildren().add(model12);

    locationTreeView.setRoot(root);
}
</code>```

Obviously you can make loops to do this if you have some kind of repetitive structure.

Body:
I have the following code. This successfully creates a root view with a Model1 and a Model1. I am having trouble adding items to Model1 though. How can I do that?

@FXML
TreeView<String> locationTreeView;

public void loadTreeItems()
{

    ArrayList<String> rootItems = new ArrayList<String>();
    rootItems.add("Model1");
    rootItems.add("Model2");
    TreeItem<String> root = new TreeItem<String>("Root");

    root.setExpanded(true);
    for (String itemString : rootItems)
    {
        root.getChildren().add(new TreeItem<String>(itemString));
    }

    locationTreeView.setRoot(root);
}

Body:
Just add them to the tree items you create, in the same way you added to the root item:

public void loadTreeItems()
{

    TreeItem<String> root = new TreeItem<String>("Root");

    root.setExpanded(true);

    TreeItem<String> model1 = new TreeItem<String>("Model1");
    TreeItem<String> model2 = new TreeItem<String>("Model2");

    TreeItem<String> model11 = new TreeItem<String>("Model1.1");
    TreeItem<String> model12 = new TreeItem<String>("Model1.2");

    root.getChildren().add(model1);
    root.getChildren().add(model2);

    model1.getChildren().add(model11);
    model1.getChildren().add(model12);

    locationTreeView.setRoot(root);
}

Obviously you can make loops to do this if you have some kind of repetitive structure.


问:
webpack: commonchunksplugin with webworker and multiple chunks
I work on a legacy application that, for now, have to be split in a very specific way:
A simplified case is :
I have 4 modules:

```<code>//moduleA.js
export const moduleA = ['moduleA'];

//moduleB.js
import {moduleA} from './moduleA';
export const moduleB = ['moduleB'].concat(moduleA);

//moduleC.js
import {moduleA} from './moduleA';
import {moduleB} from './moduleB';
export const moduleC = ['moduleC'].concat(moduleA).concat(moduleB);

//webworkerModule.js
import {moduleB} from './moduleB';
import {moduleA} from './moduleA';

console.log("Webworker Module", moduleA, moduleB);
</code>```

What I need to do is to have an output of 5 files:

manifest.js that contain the common runtime of webpack

moduleA.js that contains only the code of moduleA

moduleB.js that contains only the code of moduleB

moduleC.js that contains only the code of moduleC

webworkerModule.js that contains the code of module A and module B and the webpack runtime

I tried multiple configuration, but I cannot obtain what I want.

```<code>const path = require('path');
const webpack = require('webpack');

const config = {
    entry:{
        moduleA:'./src/moduleA.js',
        moduleB:'./src/moduleB.js',
        moduleC:'./src/moduleC.js',
        webworkerModule:'./src/webworkerModule.js',
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].js'
    },
    resolve: {
        extensions: ['.js']
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            name: 'webworkerModule',
            chunks: ['webworkerModule'],
            minChunks: Infinity
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: ['moduleA', 'moduleB', 'manifest'],
            chunks: ['moduleA', 'moduleB', 'moduleC'],
            minChunks: Infinity
        })
    ]
};

module.exports = config;
</code>```

The above configuration for example produce the correct webworkerModule.js, but moduleA and moduleB is duplicated in every other files.

Has someone any insight about this ?

答:
I found a solution:

```<code>const path = require('path');
const webpack = require('webpack');

const configWW = {
    entry:{
        webworkerModule:'./src/webworkerModule.js',
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].js'
    },
    resolve: {
        extensions: ['.js']
    },
};

const configOthers =  {
    entry: {
        moduleA:'./src/moduleA.js',
        moduleB:'./src/moduleB.js',
        moduleC:'./src/moduleC.js',
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].js'
    },
    resolve: {
        extensions: ['.js']
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            names: ['moduleB', 'moduleA', 'manifest'],
            minChunks: Infinity
        })
    ]
};

module.exports = [configWW, configOthers];
</code>```

The main point of this solution was that I didn't know that it was possible to have multiple independent configuration.

Body:
I work on a legacy application that, for now, have to be split in a very specific way:
A simplified case is :
I have 4 modules:

//moduleA.js
export const moduleA = ['moduleA'];

//moduleB.js
import {moduleA} from './moduleA';
export const moduleB = ['moduleB'].concat(moduleA);

//moduleC.js
import {moduleA} from './moduleA';
import {moduleB} from './moduleB';
export const moduleC = ['moduleC'].concat(moduleA).concat(moduleB);

//webworkerModule.js
import {moduleB} from './moduleB';
import {moduleA} from './moduleA';

console.log("Webworker Module", moduleA, moduleB);

What I need to do is to have an output of 5 files:

manifest.js that contain the common runtime of webpack

moduleA.js that contains only the code of moduleA

moduleB.js that contains only the code of moduleB

moduleC.js that contains only the code of moduleC

webworkerModule.js that contains the code of module A and module B and the webpack runtime

I tried multiple configuration, but I cannot obtain what I want.

const path = require('path');
const webpack = require('webpack');

const config = {
    entry:{
        moduleA:'./src/moduleA.js',
        moduleB:'./src/moduleB.js',
        moduleC:'./src/moduleC.js',
        webworkerModule:'./src/webworkerModule.js',
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].js'
    },
    resolve: {
        extensions: ['.js']
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            name: 'webworkerModule',
            chunks: ['webworkerModule'],
            minChunks: Infinity
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: ['moduleA', 'moduleB', 'manifest'],
            chunks: ['moduleA', 'moduleB', 'moduleC'],
            minChunks: Infinity
        })
    ]
};

module.exports = config;

The above configuration for example produce the correct webworkerModule.js, but moduleA and moduleB is duplicated in every other files.

Has someone any insight about this ?

Body:
I found a solution:

const path = require('path');
const webpack = require('webpack');

const configWW = {
    entry:{
        webworkerModule:'./src/webworkerModule.js',
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].js'
    },
    resolve: {
        extensions: ['.js']
    },
};

const configOthers =  {
    entry: {
        moduleA:'./src/moduleA.js',
        moduleB:'./src/moduleB.js',
        moduleC:'./src/moduleC.js',
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].js'
    },
    resolve: {
        extensions: ['.js']
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({
            names: ['moduleB', 'moduleA', 'manifest'],
            minChunks: Infinity
        })
    ]
};

module.exports = [configWW, configOthers];

The main point of this solution was that I didn't know that it was possible to have multiple independent configuration.


问:
Android SDK manager won't open
So I installed the android sdk for Windows:

http://developer.android.com/sdk/index.html   (the installation link)

And ran into the path variable problem. So I fixed that by changing "PATH" in enviroment variables to include where my java.exe file is located from the JDK.

But now when I open the android sdk manager, a cmd-like screen just briefly flashes on for half a second then disappears. I have no idea what's going on and how to get this thing working.

答:
In the latest version of the Android SDK, running "SDK Manager.exe" and/or "AVD Manager.exe" will not open anymore. Even the "Launch Standalone SDK Manager" link in Android Studio, which can be previously found in Android SDK Settings, is now gone.

It is now recommended to perform manual SDK and AVD management inside Android Studio. But for those who do not have an Android Studio or for those who do not like to open Android Studio just to perform SDK management, you can still manage the SDK using the command line tools, "tools/bin/sdkmanager.bat" and "tools/bin/avdmanager.bat".

This information is available when running "tools/android.bat". I think this is true for those who currently have Android SDK tooks v25.3.1 and above.

Title: Android SDK manager won't open


问:
How to get google rank without getting blocked or capcha?
This is what I do in my program:

Use CURL to google search the keywords

Filter the results and compare to my aritcle

But when it run to 84th article, I got capcha to input. The number of articles is about 2000.

How to get the google rank without getting blocked or capcha?

Any comment is appriciated. Thank you!

答:
Take a look here: Is it ok to scrape data from Google results?

You should always do everything you can to NOT get into a captcha, no matter what site you scrape.

Captcha/block means you have been detected and that causes issues.

The site owner does not like it for sure, causing administrative work etc.

Check the answer of mine I linked, also the linked sites there. You can learn a lot about how to scrape Google (and how not)


问:
Object oriented design in javascript and 'this' pointer
I am creating a object in javascript like this

```<code>function myobject() {
   this.myvar1 = 0;
   this.myvar2 = 0;
}

myobject.prototype.a = function(){
    this.myvar1 +=1;
    $('#button').click(function () {  // 'this' is undefined
        alert(this.myvar1)
     })
}

var mything = new myobject();
mything.a()
</code>```

What is the proper way to pass the this pointer to an anonymous function?

答:
What's happening here is that jQuery is hijacking the value of this in the anonymous function used as a handler for the click event. It's kind of confusing, but jQuery's behavior is to assign the DOM element that triggered the event to this. There are a couple ways to set the value of this explicitly (the "context") for the callback function:

Function.prototype.bind - Part of the ECMAScript 5 standard, just starting to be implemented in browsers. For legacy support, you can extract it from the Prototype library.

$.proxy - jQuery's crappy equivalent of Function.prototype.bind, which was introduced in jQuery 1.4.

I wrote a couple posts on my blog that explain these in more detail if you're interested:

Organizing JavaScript with Namespaces and Function Prototypes

Understanding jQuery 1.4's $.proxy() method

In both cases, since this will now be your object and not the triggering DOM element, you can get the triggering DOM element by inspecting the event object, which will be the second parameter to your callback function.

Body:
I am creating a object in javascript like this

function myobject() {
   this.myvar1 = 0;
   this.myvar2 = 0;
}

myobject.prototype.a = function(){
    this.myvar1 +=1;
    $('#button').click(function () {  // 'this' is undefined
        alert(this.myvar1)
     })
}

var mything = new myobject();
mything.a()

What is the proper way to pass the this pointer to an anonymous function?


问:
How to add long click listener to multitouch gesture detection library
The sample application (shown below with my additions) is included in the Almeros library.  It allows the user to perform multi-touch gestures to move, size, rotate, and shove an object on an unchanging background:

I would like to implement a long click listener, but doing the obvious (adding implements View.OnLongClickListener and overriding public boolean onLongClick(View v) does not work (the method is never called).

What I have attempted to do is change the earth to a basketball through a long-click (both images are already included in the sample on github).

My question: How could long click events be used while preserving the existing gesture functionality provided by the library?

This is the sample code with a few of my few additions (which have been tagged with 20160326).

```<code>/**
 * Test activity for testing the different GestureDetectors.
 *
 * @author Almer Thie (code.almeros.com)
 * Copyright (c) 2013, Almer Thie (code.almeros.com)
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer
 *  in the documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 * OF SUCH DAMAGE.
 */
// 20170326 - Commented 1, Added 1
//public class TouchActivity extends Activity implements OnTouchListener {
public class TouchActivity extends AppCompatActivity implements View.OnTouchListener, View.OnLongClickListener {
    private Matrix mMatrix = new Matrix();
    private float mScaleFactor = .4f;
    private float mRotationDegrees = 0.f;
    private float mFocusX = 0.f;
    private float mFocusY = 0.f;
    private int mAlpha = 255;
    private int mImageHeight, mImageWidth;

    private ScaleGestureDetector mScaleDetector;
    private RotateGestureDetector mRotateDetector;
    private MoveGestureDetector mMoveDetector;
    private ShoveGestureDetector mShoveDetector;

    @SuppressWarnings("deprecation")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Determine the center of the screen to center 'earth'
        Display display = getWindowManager().getDefaultDisplay();
        mFocusX = display.getWidth()/2f;
        mFocusY = display.getHeight()/2f;

        // Set this class as touchListener to the ImageView
        ImageView view = (ImageView) findViewById(R.id.imageToMove);
        view.setOnTouchListener(this);
        //20160326 - Added 1
        view.setOnLongClickListener(this);

        // Determine dimensions of 'earth' image
        Drawable d      = this.getResources().getDrawable(R.drawable.earth);
        mImageHeight    = d.getIntrinsicHeight();
        mImageWidth     = d.getIntrinsicWidth();

        // View is scaled and translated by matrix, so scale and translate initially
        float scaledImageCenterX = (mImageWidth*mScaleFactor)/2;
        float scaledImageCenterY = (mImageHeight*mScaleFactor)/2;

        mMatrix.postScale(mScaleFactor, mScaleFactor);
        mMatrix.postTranslate(mFocusX - scaledImageCenterX, mFocusY - scaledImageCenterY);
        view.setImageMatrix(mMatrix);

        // Setup Gesture Detectors
        mScaleDetector  = new ScaleGestureDetector(getApplicationContext(), new ScaleListener());
        mRotateDetector = new RotateGestureDetector(getApplicationContext(), new RotateListener());
        mMoveDetector   = new MoveGestureDetector(getApplicationContext(), new MoveListener());
        mShoveDetector  = new ShoveGestureDetector(getApplicationContext(), new ShoveListener());
    }

    @SuppressWarnings("deprecation")
    public boolean onTouch(View v, MotionEvent event) {
        mScaleDetector.onTouchEvent(event);
        mRotateDetector.onTouchEvent(event);
        mMoveDetector.onTouchEvent(event);
        mShoveDetector.onTouchEvent(event);

        float scaledImageCenterX = (mImageWidth*mScaleFactor)/2;
        float scaledImageCenterY = (mImageHeight*mScaleFactor)/2;

        mMatrix.reset();
        mMatrix.postScale(mScaleFactor, mScaleFactor);
        mMatrix.postRotate(mRotationDegrees,  scaledImageCenterX, scaledImageCenterY);
        mMatrix.postTranslate(mFocusX - scaledImageCenterX, mFocusY - scaledImageCenterY);

        ImageView view = (ImageView) v;
        view.setImageMatrix(mMatrix);
        view.setAlpha(mAlpha);

        return true; // indicate event was handled
    }

    // 20170326 - Added method
    @Override
    public boolean onLongClick(View v) {
        Log.v("20170326", "onLongClick called <<<<<<<<<<<<<<<<<<<<<<<<<<<");
        ImageView view = (ImageView) findViewById(R.id.imageToMove);
        view.setImageDrawable(this.getResources().getDrawable(R.drawable.basketball));
        return true;
    }

    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            mScaleFactor *= detector.getScaleFactor(); // scale change since previous event

            // Don't let the object get too small or too large.
            mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 10.0f));

            return true;
        }
    }

    private class RotateListener extends RotateGestureDetector.SimpleOnRotateGestureListener {
        @Override
        public boolean onRotate(RotateGestureDetector detector) {
            mRotationDegrees -= detector.getRotationDegreesDelta();
            return true;
        }
    }

    private class MoveListener extends MoveGestureDetector.SimpleOnMoveGestureListener {
        @Override
        public boolean onMove(MoveGestureDetector detector) {
            PointF d = detector.getFocusDelta();
            mFocusX += d.x;
            mFocusY += d.y;

            // mFocusX = detector.getFocusX();
            // mFocusY = detector.getFocusY();
            return true;
        }
    }

    private class ShoveListener extends ShoveGestureDetector.SimpleOnShoveGestureListener {
        @Override
        public boolean onShove(ShoveGestureDetector detector) {
            mAlpha += detector.getShovePixelsDelta();
            if (mAlpha > 255)
                mAlpha = 255;
            else if (mAlpha < 0)
                mAlpha = 0;

            return true;
        }
    }

}
</code>```

答:
The answer here suffers from triggering unwanted long press events.  In other words, if the user takes more than GestureDetector's LONGPRESS_TIMEOUT = ViewConfiguration.getLongPressTimeout(), the long press event is fired, even though the user might be just trying to move or rotate or size.  Quick moves work fine, it's when they're trying to get precise, the long press event intercedes.  My first thought was to increase the timeout, but it appears that it's system wide for all views, set at 500ms, and is not customizable.

Thus, an alternate solution which is very simple and does not need or use GestureDetector is to use Handler.postDelayed() along with a Runnable.

```<code>public boolean onTouch(View v, MotionEvent event) {
    mScaleDetector.onTouchEvent(event);
    mRotateDetector.onTouchEvent(event);
    mMoveDetector.onTouchEvent(event);
    mShoveDetector.onTouchEvent(event);

    // 20170329 - removed 1, added 'if' block
    //mLongPressDetector.onTouchEvent(event);
    if(event.getAction() == MotionEvent.ACTION_DOWN) {
        // Start a timer on each ACTION_DOWN
        handler.postDelayed(mLongPressed, 1000);
    }
    .
    .
    .
}
</code>```

In each of the sample code onTouch() methods, the timer is removed.  In all cases except onMove(), the callback is removed unconditionally.  But in the case of the MoveListener, it gets triggered even when there is zero offset.  So I'll paste only the altered MoveListener here, but you need to put handler.removeCallbacks(mLongPressed); in all the listeners:

```<code>private class MoveListener extends MoveGestureDetector.SimpleOnMoveGestureListener {
    @Override
    public boolean onMove(MoveGestureDetector detector) {
        PointF d = detector.getFocusDelta();
        mFocusX += d.x;
        mFocusY += d.y;

        // 20170329 - Added 'if' block - remove listener if there is non-zero offset
        if ((d.x + d.y) != 0f) {
            handler.removeCallbacks(mLongPressed);
            Log.v(TAG, "onMove removed " + d.x + ", " + d.y);
        }
        return true;
    }
}
</code>```

Finally, in your activity, you instantiate the Handler and  implement the Runnable

```<code>// 20170329 - Added Handler and Runnable
final Handler handler = new Handler();
Runnable mLongPressed = new Runnable() {
    public void run() {
        Log.v(TAG, "mLongPressed Runnable triggered.");
        ImageView mView = (ImageView) findViewById(R.id.imageView);
        mView.setImageDrawable(getApplicationContext().getResources().getDrawable(R.drawable.basketball));
    }
};
</code>```

This solution came from this MSquare answer.

Body:
The sample application (shown below with my additions) is included in the Almeros library.  It allows the user to perform multi-touch gestures to move, size, rotate, and shove an object on an unchanging background:

I would like to implement a long click listener, but doing the obvious (adding implements View.OnLongClickListener and overriding public boolean onLongClick(View v) does not work (the method is never called).

What I have attempted to do is change the earth to a basketball through a long-click (both images are already included in the sample on github).

My question: How could long click events be used while preserving the existing gesture functionality provided by the library?

This is the sample code with a few of my few additions (which have been tagged with 20160326).

/**
 * Test activity for testing the different GestureDetectors.
 *
 * @author Almer Thie (code.almeros.com)
 * Copyright (c) 2013, Almer Thie (code.almeros.com)
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer
 *  in the documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 * OF SUCH DAMAGE.
 */
// 20170326 - Commented 1, Added 1
//public class TouchActivity extends Activity implements OnTouchListener {
public class TouchActivity extends AppCompatActivity implements View.OnTouchListener, View.OnLongClickListener {
    private Matrix mMatrix = new Matrix();
    private float mScaleFactor = .4f;
    private float mRotationDegrees = 0.f;
    private float mFocusX = 0.f;
    private float mFocusY = 0.f;
    private int mAlpha = 255;
    private int mImageHeight, mImageWidth;

    private ScaleGestureDetector mScaleDetector;
    private RotateGestureDetector mRotateDetector;
    private MoveGestureDetector mMoveDetector;
    private ShoveGestureDetector mShoveDetector;

    @SuppressWarnings("deprecation")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Determine the center of the screen to center 'earth'
        Display display = getWindowManager().getDefaultDisplay();
        mFocusX = display.getWidth()/2f;
        mFocusY = display.getHeight()/2f;

        // Set this class as touchListener to the ImageView
        ImageView view = (ImageView) findViewById(R.id.imageToMove);
        view.setOnTouchListener(this);
        //20160326 - Added 1
        view.setOnLongClickListener(this);

        // Determine dimensions of 'earth' image
        Drawable d      = this.getResources().getDrawable(R.drawable.earth);
        mImageHeight    = d.getIntrinsicHeight();
        mImageWidth     = d.getIntrinsicWidth();

        // View is scaled and translated by matrix, so scale and translate initially
        float scaledImageCenterX = (mImageWidth*mScaleFactor)/2;
        float scaledImageCenterY = (mImageHeight*mScaleFactor)/2;

        mMatrix.postScale(mScaleFactor, mScaleFactor);
        mMatrix.postTranslate(mFocusX - scaledImageCenterX, mFocusY - scaledImageCenterY);
        view.setImageMatrix(mMatrix);

        // Setup Gesture Detectors
        mScaleDetector  = new ScaleGestureDetector(getApplicationContext(), new ScaleListener());
        mRotateDetector = new RotateGestureDetector(getApplicationContext(), new RotateListener());
        mMoveDetector   = new MoveGestureDetector(getApplicationContext(), new MoveListener());
        mShoveDetector  = new ShoveGestureDetector(getApplicationContext(), new ShoveListener());
    }

    @SuppressWarnings("deprecation")
    public boolean onTouch(View v, MotionEvent event) {
        mScaleDetector.onTouchEvent(event);
        mRotateDetector.onTouchEvent(event);
        mMoveDetector.onTouchEvent(event);
        mShoveDetector.onTouchEvent(event);

        float scaledImageCenterX = (mImageWidth*mScaleFactor)/2;
        float scaledImageCenterY = (mImageHeight*mScaleFactor)/2;

        mMatrix.reset();
        mMatrix.postScale(mScaleFactor, mScaleFactor);
        mMatrix.postRotate(mRotationDegrees,  scaledImageCenterX, scaledImageCenterY);
        mMatrix.postTranslate(mFocusX - scaledImageCenterX, mFocusY - scaledImageCenterY);

        ImageView view = (ImageView) v;
        view.setImageMatrix(mMatrix);
        view.setAlpha(mAlpha);

        return true; // indicate event was handled
    }

    // 20170326 - Added method
    @Override
    public boolean onLongClick(View v) {
        Log.v("20170326", "onLongClick called <<<<<<<<<<<<<<<<<<<<<<<<<<<");
        ImageView view = (ImageView) findViewById(R.id.imageToMove);
        view.setImageDrawable(this.getResources().getDrawable(R.drawable.basketball));
        return true;
    }

    private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            mScaleFactor *= detector.getScaleFactor(); // scale change since previous event

            // Don't let the object get too small or too large.
            mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 10.0f));

            return true;
        }
    }

    private class RotateListener extends RotateGestureDetector.SimpleOnRotateGestureListener {
        @Override
        public boolean onRotate(RotateGestureDetector detector) {
            mRotationDegrees -= detector.getRotationDegreesDelta();
            return true;
        }
    }

    private class MoveListener extends MoveGestureDetector.SimpleOnMoveGestureListener {
        @Override
        public boolean onMove(MoveGestureDetector detector) {
            PointF d = detector.getFocusDelta();
            mFocusX += d.x;
            mFocusY += d.y;

            // mFocusX = detector.getFocusX();
            // mFocusY = detector.getFocusY();
            return true;
        }
    }

    private class ShoveListener extends ShoveGestureDetector.SimpleOnShoveGestureListener {
        @Override
        public boolean onShove(ShoveGestureDetector detector) {
            mAlpha += detector.getShovePixelsDelta();
            if (mAlpha > 255)
                mAlpha = 255;
            else if (mAlpha < 0)
                mAlpha = 0;

            return true;
        }
    }

}

Body:
The answer here suffers from triggering unwanted long press events.  In other words, if the user takes more than GestureDetector's LONGPRESS_TIMEOUT = ViewConfiguration.getLongPressTimeout(), the long press event is fired, even though the user might be just trying to move or rotate or size.  Quick moves work fine, it's when they're trying to get precise, the long press event intercedes.  My first thought was to increase the timeout, but it appears that it's system wide for all views, set at 500ms, and is not customizable.

Thus, an alternate solution which is very simple and does not need or use GestureDetector is to use Handler.postDelayed() along with a Runnable.

public boolean onTouch(View v, MotionEvent event) {
    mScaleDetector.onTouchEvent(event);
    mRotateDetector.onTouchEvent(event);
    mMoveDetector.onTouchEvent(event);
    mShoveDetector.onTouchEvent(event);

    // 20170329 - removed 1, added 'if' block
    //mLongPressDetector.onTouchEvent(event);
    if(event.getAction() == MotionEvent.ACTION_DOWN) {
        // Start a timer on each ACTION_DOWN
        handler.postDelayed(mLongPressed, 1000);
    }
    .
    .
    .
}

In each of the sample code onTouch() methods, the timer is removed.  In all cases except onMove(), the callback is removed unconditionally.  But in the case of the MoveListener, it gets triggered even when there is zero offset.  So I'll paste only the altered MoveListener here, but you need to put handler.removeCallbacks(mLongPressed); in all the listeners:

private class MoveListener extends MoveGestureDetector.SimpleOnMoveGestureListener {
    @Override
    public boolean onMove(MoveGestureDetector detector) {
        PointF d = detector.getFocusDelta();
        mFocusX += d.x;
        mFocusY += d.y;

        // 20170329 - Added 'if' block - remove listener if there is non-zero offset
        if ((d.x + d.y) != 0f) {
            handler.removeCallbacks(mLongPressed);
            Log.v(TAG, "onMove removed " + d.x + ", " + d.y);
        }
        return true;
    }
}

Finally, in your activity, you instantiate the Handler and  implement the Runnable

// 20170329 - Added Handler and Runnable
final Handler handler = new Handler();
Runnable mLongPressed = new Runnable() {
    public void run() {
        Log.v(TAG, "mLongPressed Runnable triggered.");
        ImageView mView = (ImageView) findViewById(R.id.imageView);
        mView.setImageDrawable(getApplicationContext().getResources().getDrawable(R.drawable.basketball));
    }
};

This solution came from this MSquare answer.


问:
OSRM route directions
Here is what I am trying to do. I have a pair of lat, lngs and I am trying to find the route between the pair of lat, lngs using OSRM. I extracted polylines from each step object using the OSRM route service output but couldn't figure out how to extract the direction for each step. How do I get the direction for each step?</p>

答:
See the API documentation for parameters to modify the response.

Passing steps=true will return RouteStep objects. A RouteStep contains the information you are looking for, i.e. StepManeuver objects, Lane objects and Intersection objects as well as distance and duration.

Title: OSRM route directions


问:
How to create a button that starts WiFi direct
I have no prior experience with app development and am now supposed to create an app in android studio that connects to a sensor by WiFi-direct. I have read up on WiFi-direct and tried to follow the guides https://developer.android.com/guide/topics/connectivity/wifip2p.html and https://stuff.mit.edu/afs/sipb/project/android/docs/training/connect-devices-wirelessly/wifi-direct.html but when using their code I have still no clue how to move forward. I have also looked at several demo apps for WiFi direct.

My code looks like this at the moment.

Broadcast reciever:

```<code>public class WiFiDirectBroadcastReceiver extends BroadcastReceiver {

private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;
private MainActivity mActivity;

public WiFiDirectBroadcastReceiver(WifiP2pManager manager, WifiP2pManager.Channel channel,
                                   MainActivity activity) {
    super();
    this.mManager = manager;
    this.mChannel = channel;
    this.mActivity = activity;
}

@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
        // Check to see if Wi-Fi is enabled and notify appropriate activity
        int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
        if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
            mActivity.setIsWifiP2pEnabled(true);
        } else {
            mActivity.setIsWifiP2pEnabled(false);
        }

    } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
        // Call WifiP2pManager.requestPeers() to get a list of current peers
    } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
        // Respond to new connection or disconnections
    } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
        // Respond to this device's wifi state changing
    }
}
}
</code>```

MainActivity:

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

WifiP2pManager mManager;
WifiP2pManager.Channel mChannel;
private boolean isWifiP2pEnabled = false;
BroadcastReceiver mReceiver;
IntentFilter mIntentFilter;

public void setIsWifiP2pEnabled(boolean isWifiP2pEnabled) {
    this.isWifiP2pEnabled = isWifiP2pEnabled;
}

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

    mIntentFilter = new IntentFilter();
    mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
    mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
    mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
    mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);

    mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
    mChannel = mManager.initialize(this, getMainLooper(), null);
    mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);

}

/* register the broadcast receiver with the intent values to be matched */
@Override
protected void onResume() {
    super.onResume();
    mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);
    registerReceiver(mReceiver, mIntentFilter);
}
/* unregister the broadcast receiver */
@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(mReceiver);
}

}
</code>```

The next part in the guide is that I should try to discover peers. Where should I implement this code?

```<code>mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {

    @Override
    public void onSuccess() {
        // Code for when the discovery initiation is successful goes here.
        // No services have actually been discovered yet, so this method
        // can often be left blank.  Code for peer discovery goes in the
        // onReceive method, detailed below.
    }

    @Override
    public void onFailure(int reasonCode) {
        // Code for when the discovery initiation fails goes here.
        // Alert the user that something went wrong.
    }
});
</code>```

My final product should be a button that when I press it I should search for peers and be able to connect to one. The sensor will boot in WiFi direct. Does anyone know where I can find more info on how to proceed or have tips on what classes I need and such?

Thank you!

答:
The way it works is by:

Calling discoverPeers when tapping on the button

Next, in your WiFiDirectBroadcastReceiver -> WIFI_P2P_PEERS_CHANGED_ACTION condition, request the list of available peers like this: mManager.requestPeers(mChannel, peerListListener);

Then, you have to implement WifiP2pManager.PeerListListener in your activity or fragment because the discovered peers will return into this method:

@Override
public void onPeersAvailable(WifiP2pDeviceList peerList) {}

Once you have the list of peers, you can connect to any peer using
mManager.connect(mChannel, config, new ActionListener() {});

I believe following https://developer.android.com/guide/topics/connectivity/wifip2p.html is good enough to get the api working.

Goodluck.

Body:
I have no prior experience with app development and am now supposed to create an app in android studio that connects to a sensor by WiFi-direct. I have read up on WiFi-direct and tried to follow the guides https://developer.android.com/guide/topics/connectivity/wifip2p.html and https://stuff.mit.edu/afs/sipb/project/android/docs/training/connect-devices-wirelessly/wifi-direct.html but when using their code I have still no clue how to move forward. I have also looked at several demo apps for WiFi direct.

My code looks like this at the moment.

Broadcast reciever:

public class WiFiDirectBroadcastReceiver extends BroadcastReceiver {

private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;
private MainActivity mActivity;

public WiFiDirectBroadcastReceiver(WifiP2pManager manager, WifiP2pManager.Channel channel,
                                   MainActivity activity) {
    super();
    this.mManager = manager;
    this.mChannel = channel;
    this.mActivity = activity;
}

@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
        // Check to see if Wi-Fi is enabled and notify appropriate activity
        int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
        if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
            mActivity.setIsWifiP2pEnabled(true);
        } else {
            mActivity.setIsWifiP2pEnabled(false);
        }

    } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
        // Call WifiP2pManager.requestPeers() to get a list of current peers
    } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
        // Respond to new connection or disconnections
    } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
        // Respond to this device's wifi state changing
    }
}
}

MainActivity:

public class MainActivity extends AppCompatActivity {

WifiP2pManager mManager;
WifiP2pManager.Channel mChannel;
private boolean isWifiP2pEnabled = false;
BroadcastReceiver mReceiver;
IntentFilter mIntentFilter;

public void setIsWifiP2pEnabled(boolean isWifiP2pEnabled) {
    this.isWifiP2pEnabled = isWifiP2pEnabled;
}

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

    mIntentFilter = new IntentFilter();
    mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
    mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
    mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
    mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);

    mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
    mChannel = mManager.initialize(this, getMainLooper(), null);
    mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);

}

/* register the broadcast receiver with the intent values to be matched */
@Override
protected void onResume() {
    super.onResume();
    mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);
    registerReceiver(mReceiver, mIntentFilter);
}
/* unregister the broadcast receiver */
@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(mReceiver);
}

}

The next part in the guide is that I should try to discover peers. Where should I implement this code?

mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {

    @Override
    public void onSuccess() {
        // Code for when the discovery initiation is successful goes here.
        // No services have actually been discovered yet, so this method
        // can often be left blank.  Code for peer discovery goes in the
        // onReceive method, detailed below.
    }

    @Override
    public void onFailure(int reasonCode) {
        // Code for when the discovery initiation fails goes here.
        // Alert the user that something went wrong.
    }
});

My final product should be a button that when I press it I should search for peers and be able to connect to one. The sensor will boot in WiFi direct. Does anyone know where I can find more info on how to proceed or have tips on what classes I need and such?

Thank you!


问:
How can I have tab 1 and 4 selected
I have two tab sections and I would like the first tab of each tab section to be selected by default. In this case tab 1 and tab 4 . How can I do that?

In my attempted I created a for loop selecting by class name, but I noticed only the last element in the loop is always selected not all. I did not included it as i think the issues is that only one tab can be selected at a time, but I do not see where this statement is.

Just picked up js a week ago. This a modified example i got from w3schools.

```<code>        <!DOCTYPE html>
<html>
<head>
<style>
body {font-family: "Lato", sans-serif;}

/* Style the tab */
div.tab {
    overflow: hidden;
    border: 1px solid #ccc;
    background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
div.tab button {
    background-color: inherit;
    float: left;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 14px 16px;
    transition: 0.3s;
    font-size: 17px;
}

/* Change background color of buttons on hover */
div.tab button:hover {
    background-color: #ddd;
}

/* Create an active/current tablink class */
div.tab button.active {
    background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
    display: none;
    padding: 6px 12px;
    border: 1px solid #ccc;
    border-top: none;
}

/* Style the close button */
.topright {
    float: right;
    cursor: pointer;
    font-size: 20px;
}

.topright:hover {color: red;}
</style>
</head>
<body>

<p>Click on the x button in the top right corner to close the current tab:</p>

<div class="tab">
  <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen1">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>
</div>

<div id="London" class="tabcontent">
  <span onclick="this.parentElement.style.display='none'" class="topright">x</span>
  <h3>London</h3>
  <p>London is the capital city of England.</p>
</div>

<div id="Paris" class="tabcontent">
  <span onclick="this.parentElement.style.display='none'" class="topright">x</span>
  <h3>Paris</h3>
  <p>Paris is the capital of France.</p>
</div>

<div id="Tokyo" class="tabcontent">
  <span onclick="this.parentElement.style.display='none'" class="topright">x</span>
  <h3>Tokyo</h3>
  <p>Tokyo is the capital of Japan.</p>
</div>

<p>Click on the x button in the top right corner to close the current tab:</p>

<div class="tab">
  <button class="tablinks" onclick="openCity(event, '1')" id="defaultOpen2">1</button>
  <button class="tablinks" onclick="openCity(event, '2')">2</button>
  <button class="tablinks" onclick="openCity(event, '3')">3</button>
</div>

<div id="1" class="tabcontent">
  <span onclick="this.parentElement.style.display='none'" class="topright">x</span>
  <h3>London</h3>
  <p>London is the capital city of England.</p>
</div>

<div id="2" class="tabcontent">
  <span onclick="this.parentElement.style.display='none'" class="topright">x</span>
  <h3>Paris</h3>
  <p>Paris is the capital of France.</p>
</div>

<div id="3" class="tabcontent">
  <span onclick="this.parentElement.style.display='none'" class="topright">x</span>
  <h3>Tokyo</h3>
  <p>Tokyo is the capital of Japan.</p>
</div>

<script>
function openCity(evt, cityName) {
    var i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
    document.getElementById(cityName).style.display = "block";
    evt.currentTarget.className += " active";
}

// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen1").click();
document.getElementById("defaultOpen2").click();
</script>

</body>
</html>
</code>```

答:
[not native english speaker]

Hi there. What is happening is that you're using the two tabs like just one. You need to isolate each tab and make some changes in the code so it will work as you want.

Here's the gist with comments in the parts that have changed:
https://gist.github.com/rdlagemann/720614ca5ca29726a9f671c0dd2d2385

Hope it helps!

Title: How can I have tab 1 and 4 selected

Body:
I have two tab sections and I would like the first tab of each tab section to be selected by default. In this case tab 1 and tab 4 . How can I do that?

In my attempted I created a for loop selecting by class name, but I noticed only the last element in the loop is always selected not all. I did not included it as i think the issues is that only one tab can be selected at a time, but I do not see where this statement is.

Just picked up js a week ago. This a modified example i got from w3schools.

        <!DOCTYPE html>

Click on the x button in the top right corner to close the current tab:

  <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen1">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>

  x

London

London is the capital city of England.

  x

Paris

Paris is the capital of France.

  x

Tokyo

Tokyo is the capital of Japan.

Click on the x button in the top right corner to close the current tab:

  <button class="tablinks" onclick="openCity(event, '1')" id="defaultOpen2">1</button>
  <button class="tablinks" onclick="openCity(event, '2')">2</button>
  <button class="tablinks" onclick="openCity(event, '3')">3</button>

  x

London

London is the capital city of England.

  x

Paris

Paris is the capital of France.

  x

Tokyo

Tokyo is the capital of Japan.


问:
How to get a list of distinct records with projections in grails?
Is there a way that I can get a list of distinct Order objects (based on customerName) with projections (selected fields only)?
Assuming only the id would be different, I want to fetch orders having unique customerName. Is it possible using projections or any other way?

My code is:

```<code>def criteria = Order.createCriteria()
def orders = criteria.list() {
    and {
        eq("showAddress", true)
        like("customerName", "%abcdPqrs%")
    }
    projections {
        distinct("customerName")
        property("deliveryAddress")
        property("billingAddress")
        property("")
    }
}
return orders
</code>```

The above code fetches duplicate (customerName) records from Order, how can I fix this?

答:
If you will see the SQL query generated by GORM, you will find that the distinct will apply on a complete row instead of the customerName. You can enable the logs by putting

```<code>logSql = true
</code>```

in datasource.groovy.

You can try this

```<code>def criteria = Order.createCriteria()
def orders = criteria.list() {
and {
    eq("showAddress", true)
    like("customerName", "%abcdPqrs%")
}
projections {
    groupProperty("customerName")
    property("deliveryAddress")
    property("billingAddress")
    property("")
}
}
</code>```

Body:
Is there a way that I can get a list of distinct Order objects (based on customerName) with projections (selected fields only)?
Assuming only the id would be different, I want to fetch orders having unique customerName. Is it possible using projections or any other way?

My code is:

def criteria = Order.createCriteria()
def orders = criteria.list() {
    and {
        eq("showAddress", true)
        like("customerName", "%abcdPqrs%")
    }
    projections {
        distinct("customerName")
        property("deliveryAddress")
        property("billingAddress")
        property("")
    }
}
return orders

The above code fetches duplicate (customerName) records from Order, how can I fix this?

Body:
If you will see the SQL query generated by GORM, you will find that the distinct will apply on a complete row instead of the customerName. You can enable the logs by putting

logSql = true

in datasource.groovy.

You can try this

def criteria = Order.createCriteria()
def orders = criteria.list() {
and {
    eq("showAddress", true)
    like("customerName", "%abcdPqrs%")
}
projections {
    groupProperty("customerName")
    property("deliveryAddress")
    property("billingAddress")
    property("")
}
}