问:
Can I convert pandas dataframe to spark rdd?
Pbm:

a) Read a local file into Panda dataframe say PD_DF
b) Manipulate/Massge the PD_DF and add columns to dataframe
c) Need to write PD_DF to HDFS using spark.  How do I do it ?

答:
I use Spark 1.6.0. First transform pandas dataframe into spark dataframe then spark dataframe spark rdd</p>

```<code>sparkDF = sqlContext.createDataFrame(pandasDF)
sparkRDD = sparkDF.rdd.map(list)
type(sparkRDD)
pyspark.rdd.PipelinedRDD
</code>```

Body:
I use Spark 1.6.0. First transform pandas dataframe into spark dataframe then spark dataframe spark rdd

sparkDF = sqlContext.createDataFrame(pandasDF)
sparkRDD = sparkDF.rdd.map(list)
type(sparkRDD)
pyspark.rdd.PipelinedRDD


来源: stackexchange

问:
zuul multiple urls one path
Hi I have a route that can have multiple servers...

I have tried the following to no luck:

```<code>zuul.routes.example.path=/example/**
zuul.routes.example.serviceId=example
example.ribbon.eureka.enabled=false
example.ribbon.eureka.listOfServers=http://127.0.0.1/metrics,http://127.0.0.1/info
</code>```

This just returns the following error:

Caused by: com.netflix.client.ClientException: Load balancer does not have available server for client: example

I am using eureka for most routes, but for this one in particular I cannot use eureka.

Is it possible to get zuul to loadbalance between the two urls?

Solved

The answer below solves this issue with config, however I would mention I was using spring-boot-starter-parent, I also had to upgrade the dependency management to Camden.SR7

```<code><dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
<!--         <version>Brixton.SR5</version> -->
        <version>Camden.SR7</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>
</code>```

答:
Yes, you can. Try the following properties instead of yours.</p>

```<code>zuul.routes.example.path=/example/**
zuul.routes.example.serviceId=example
example.ribbon.NIWSServerListClassName=com.netflix.loadbalancer.ConfigurationBasedServerList
example.ribbon.listOfServers=http://127.0.0.1/metrics,http://127.0.0.1/info
</code>```

ContentLicense: CC BY-SA 3.0

Title: zuul multiple urls one path

Body:
Hi I have a route that can have multiple servers...

I have tried the following to no luck:

zuul.routes.example.path=/example/**
zuul.routes.example.serviceId=example
example.ribbon.eureka.enabled=false
example.ribbon.eureka.listOfServers=http://127.0.0.1/metrics,http://127.0.0.1/info

This just returns the following error:

Caused by: com.netflix.client.ClientException: Load balancer does not have available server for client: example

I am using eureka for most routes, but for this one in particular I cannot use eureka.

Is it possible to get zuul to loadbalance between the two urls?

Solved

The answer below solves this issue with config, however I would mention I was using spring-boot-starter-parent, I also had to upgrade the dependency management to Camden.SR7

<dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>

        <version>Camden.SR7</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

Body:
Yes, you can. Try the following properties instead of yours.

zuul.routes.example.path=/example/**
zuul.routes.example.serviceId=example
example.ribbon.NIWSServerListClassName=com.netflix.loadbalancer.ConfigurationBasedServerList
example.ribbon.listOfServers=http://127.0.0.1/metrics,http://127.0.0.1/info


问:
Multi line regex expression
I have the following file, and I'm trying to use /\|\".*\"\|/gm match multi line..end here, but the regex finds nothing using sed -e ':a;N;$!ba;s/\|\".*\"\|/abcxyz/gm' t >  t.2, I can't find out what's wrong with it.

```<code>    |2012-10-12 13:41:08.067|2012-10-12 13:45:03.282|f||"multi line star t herer erj
jdkajdkfj
   end here"|2017
</code>```

答:
This might work for you (GNU sed):

```<code>sed -e ':a;N;$!ba;s/|".*"|/|"abcxyz"|/' file
</code>```

The | and the " do not need to be quoted. If the | is quoted it acts as the alternation metacharacter i.e. this|that meaning this or that.

N.B. The :a;N;$!ba construct slurps the entire file into memory and because the .* is greedy, more than one record may be matched.

Title: Multi line regex expression

Body:
I have the following file, and I'm trying to use /\|\".*\"\|/gm match multi line..end here, but the regex finds nothing using sed -e ':a;N;$!ba;s/\|\".*\"\|/abcxyz/gm' t >  t.2, I can't find out what's wrong with it.

    |2012-10-12 13:41:08.067|2012-10-12 13:45:03.282|f||"multi line star t herer erj
jdkajdkfj
   end here"|2017

Body:
This might work for you (GNU sed):

sed -e ':a;N;$!ba;s/|".*"|/|"abcxyz"|/' file

The | and the " do not need to be quoted. If the | is quoted it acts as the alternation metacharacter i.e. this|that meaning this or that.

N.B. The :a;N;$!ba construct slurps the entire file into memory and because the .* is greedy, more than one record may be matched.


问:
Django + Angular2: How to fetch data from database?
I am using angular2 as a front end in my html pages.I have a django project that uses postgresql.
Which is the best approach to use the angular2 in the django project to connect to the django models and the database to perform basic operations(CRUD)like Read,Update etc?

Currently I need to fetch the data from the database dynamically.
(e.g.If user clicks on the product from the product list then product details should be retrieved from the database and it is shown to the user)

Any advice or reference example link will be helpful.

答:
I'm recently working on the similar project you have. My approach is just like @praba230890 mentioned above.

Here are some samples...

Django

In views.py

```<code>class HView(APIView):
  def get(self, request, format=None):
    request_hero_id = request.query_params.get('id', None)
    if request_hero_id:
      return Response(
        {
          'id': 1,
          'name': 'test',
          'position': 'mid'
        },
        status=status.HTTP_200_OK
      )
    return Response(
      { 'error': 'does not exist' },
      status=status.HTTP_404_NOT_FOUND
    )

class HsView(APIView):
  def get(self, request, format=None):
    return Response(
      [
        {
          'id': 1,
          'name': 'test',
          'position': 'mid'
        },
        {
          'id': 2,
          'name': 'test',
          'position': 'mid'
        }
      ],
        status=status.HTTP_200_OK
    )
</code>```

In urls.py

```<code>urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'', include('shweb.urls')),
]
</code>```

You will need to install django-cros-headers if you run into CROS errors. Also, you will need to configure your settings.py

Angular2

In api-service.service.ts

```<code>import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';

import 'rxjs/add/operator/toPromise';

import { Hero } from '../utils/hero';

@Injectable()
export class ApiService {
  /** Modify this later */
  private backend_api_url: string = 'http://localhost:8000/api/';
  private api_headers: Headers    = new Headers(
    { 'Content-Type': 'application/json' }
  );

  constructor(private http: Http) { }

  getHero(id: number): Promise<Hero>{
    const url = `${this.backend_api_url}htest/?id=${id}`;

    return this.http.get(url).toPromise().then(
      response => response.json() as Hero
    ).catch(this.handleError);
  } // END getHero

  getHeroes(): Promise<Hero[]>{
    const url = `${this.backend_api_url}htests`;
    console.log(url);
    return this.http.get(url).toPromise().then(
      response => {
        console.log(response.json());
        return response.json() as Hero[];
      }
    ).catch(this.handleError);
  } // END getHeroes

  private handleError(error: any): Promise<any>{
    console.error('An error occurred', error); // TODO: update this
    return Promise.reject(error.message || error);
  }
}
</code>```

In hero.ts

```<code>export class Hero{
  id: number;
  name: string;
  position: string;
}
</code>```

In your component file, inject the api-service into component

```<code>@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit{
  title: string = 'Dashboard';
  heroes: Hero[] = [];

  constructor(private apiService: ApiService){}

  ngOnInit(): void{
    this.getHeroes();
  }

  getHeroes(): void{
    this.apiService.getHeroes().then(heroes => this.heroes = heroes);
  } // END getHeroes
}
</code>```

Basically, using API to retrieve data and cast into class; then, you can use those data.

PS. I haven't touched the credentials and security part. I believe you need to have some sort of Authentication implemented for secure API communication. (In my case, only GETs are allowed. Therefore, I put the security part for later.)

Hope this would help!

Body:
I'm recently working on the similar project you have. My approach is just like @praba230890 mentioned above.

Here are some samples...

Django

In views.py

class HView(APIView):
  def get(self, request, format=None):
    request_hero_id = request.query_params.get('id', None)
    if request_hero_id:
      return Response(
        {
          'id': 1,
          'name': 'test',
          'position': 'mid'
        },
        status=status.HTTP_200_OK
      )
    return Response(
      { 'error': 'does not exist' },
      status=status.HTTP_404_NOT_FOUND
    )

class HsView(APIView):
  def get(self, request, format=None):
    return Response(
      [
        {
          'id': 1,
          'name': 'test',
          'position': 'mid'
        },
        {
          'id': 2,
          'name': 'test',
          'position': 'mid'
        }
      ],
        status=status.HTTP_200_OK
    )

In urls.py

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'', include('shweb.urls')),
]

You will need to install django-cros-headers if you run into CROS errors. Also, you will need to configure your settings.py

Angular2

In api-service.service.ts

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';

import 'rxjs/add/operator/toPromise';

import { Hero } from '../utils/hero';

@Injectable()
export class ApiService {
  /** Modify this later */
  private backend_api_url: string = 'http://localhost:8000/api/';
  private api_headers: Headers    = new Headers(
    { 'Content-Type': 'application/json' }
  );

  constructor(private http: Http) { }

  getHero(id: number): Promise<Hero>{
    const url = `${this.backend_api_url}htest/?id=${id}`;

    return this.http.get(url).toPromise().then(
      response => response.json() as Hero
    ).catch(this.handleError);
  } // END getHero

  getHeroes(): Promise<Hero[]>{
    const url = `${this.backend_api_url}htests`;
    console.log(url);
    return this.http.get(url).toPromise().then(
      response => {
        console.log(response.json());
        return response.json() as Hero[];
      }
    ).catch(this.handleError);
  } // END getHeroes

  private handleError(error: any): Promise<any>{
    console.error('An error occurred', error); // TODO: update this
    return Promise.reject(error.message || error);
  }
}

In hero.ts

export class Hero{
  id: number;
  name: string;
  position: string;
}

In your component file, inject the api-service into component

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit{
  title: string = 'Dashboard';
  heroes: Hero[] = [];

  constructor(private apiService: ApiService){}

  ngOnInit(): void{
    this.getHeroes();
  }

  getHeroes(): void{
    this.apiService.getHeroes().then(heroes => this.heroes = heroes);
  } // END getHeroes
}

Basically, using API to retrieve data and cast into class; then, you can use those data.

PS. I haven't touched the credentials and security part. I believe you need to have some sort of Authentication implemented for secure API communication. (In my case, only GETs are allowed. Therefore, I put the security part for later.)

Hope this would help!


问:
Does if with ifelse ,ifelse needs to have at least one else statement
```<code>if ()
{}else if (){}
else if (){}
else if (){}
else{}
</code>```

Do we need to have at least one  else {}?

答:
Nope, an else block is not required.

The following is perfectly valid:

```<code>if (....) {
}
else if (...) {
}
</code>```

Body:
if ()
{}else if (){}
else if (){}
else if (){}
else{}

Do we need to have at least one  else {}?

Body:
Nope, an else block is not required.

The following is perfectly valid:

if (....) {
}
else if (...) {
}

ContentLicense: CC BY-SA 2.5


问:
Retrieve data from Firebase and send an email
I want to know if there is some service to do what I want to do. The point is that I have an app connected to Firebase (I don't have backend) and I want to automatize some emails. Every day I want to send an email with some of the records stored in Firebase. I don't want to code with node or whatever, so I am looking something like Zapier (I have taken a look at it, and I think it's not possible to do this). I have taken a look at Cloud Functions for Firebase but seems that the function is a trigger, and I need something like a daily job. Any idea?</p>

答: While you may not like the idea of using Node.js, Cloud Functions for Firebase would be a way to build this functionality with relatively little code. You can find out how to send an email in this sample and see how to set up a cron job in this sample.</p>


问:
Syntax error in VBA
I have a syntax challenge that is returning a "Data Mismatch" error

Basically, I am using the VBA DMin function to target a range of prices using two criteria, one string and one date.

The code:

```<code>EndDate = #11/1/2017#

Target = DMin("Price", "qryPrice", " [CodeName]='Macan'" And " [MyDate] <=" & EndDate)
</code>```

I can't seem to figure out the syntax in order to use both of the different criteria data types. [CodeName] is string, [MyDate] is date/time

答:
Remove quote marks around And. Try # delimiters.

Target = DMin("Price", "qryPrice", "[CodeName]='Macan' And [MyDate] <=#" & EndDate & "#")

Why hard-coded date? Could just put the date directly in the DMin() expression.

Shouldn't CodeName and EndDate be dynamic?

Title: Syntax error in VBA

Body:
I have a syntax challenge that is returning a "Data Mismatch" error

Basically, I am using the VBA DMin function to target a range of prices using two criteria, one string and one date.

The code:

EndDate = #11/1/2017#

Target = DMin("Price", "qryPrice", " [CodeName]='Macan'" And " [MyDate] <=" & EndDate)

I can't seem to figure out the syntax in order to use both of the different criteria data types. [CodeName] is string, [MyDate] is date/time


问:
Remove ith item from a C++ std::vector
How do I remove the ith item from a std::vector?

I know I want to delete the ith element. I have int i; and std::vector<process> pList; where process is a struct. I want to do something equivalent to the following:

```<code>pList.remove(i);
</code>```

答:
Use Vector.Erase. The complexity is linear on the number of elements erased (destructors) plus the number of elements after the last element deleted (moving).</p>

```<code>iterator erase ( iterator position );
iterator erase ( iterator first, iterator last );
</code>```

Title: Remove ith item from a C++ std::vector

Body:
How do I remove the ith item from a std::vector?

I know I want to delete the ith element. I have int i; and std::vector<process> pList; where process is a struct. I want to do something equivalent to the following:

pList.remove(i);

Body:
Use Vector.Erase. The complexity is linear on the number of elements erased (destructors) plus the number of elements after the last element deleted (moving).

iterator erase ( iterator position );
iterator erase ( iterator first, iterator last );


问:
href is empty, how to get the URL?
I was using Python/Scrapy. When I try to find the URL of a “next page” button, I find the href attribute of the button is empty. And the button works. Is it possible to get the link by an xPath or CSS selector?

The HTML is like this:

Seuraava
```

答:
Is it possible to get the link by an xPath or CSS selector?

No.

That link is using an AngularJS click handler:

```<code>ng-click="togglePage(page + 1)"
</code>```

This will call a function named togglePage(). Tracing what this function does will require some digging -- analyzing it automatically is essentially impossible.

Title: href is empty, how to get the URL?

Body:
Is it possible to get the link by an xPath or CSS selector?

No.

That link is using an AngularJS click handler:

ng-click="togglePage(page + 1)"

This will call a function named togglePage(). Tracing what this function does will require some digging -- analyzing it automatically is essentially impossible.


问:
Crystal Report Application Crashes after created windows intstaller in setUp and Deployment in Vs 2010
I have created windows form application and it has a print option , the report should be crystal report . CrystalDecisions.CrystalReports.Engine.dll i am using for created the report.

Scenario:

1)The application works fine when run inside the Vs 2010.Able to print
  the report. 2) If i close the vs and Go to Debug folder and run the
  application , its working fine and able to create the Report.

Problem:

3) Application Crashes while Install the application and when click
  the print option has crashed ,all other modules are working fine.The
  problem happens for report.

So How to create a installable Windows application without crashing crystal report.

This is the method i have used to create the Installable file.

App crash when click print option.

答:
Check:

crystal report runtime version.

OS 32bit or 64bit.

visual c++ redistributable.


问:
Bundle JSON as a plain JSON file with Webpack
I have a web-app that requires a configuration JSON file which contains end-points and other required start-up parameters.

If I use the json-loader, the file is not "real json", it'll look something like this:

```<code>module.exports = {
    "name": "foo",
    "key": true,
};
</code>```

What I would like is plain old JSON which means it can be parsed and changed as part of a deployment process before being sent to the web server where it will be served from.

An alternative is to use the file-loader.  However, that means that (even though it's a trivial task) I have to write the code to download the file myself.  I would like to have webpack handle this and be available.

Is there a way that I can require a JSON file, which is written as a plain-old JSON file and imported at run time?

答:
Is there a way that I can require a JSON file, which is written as a
  plain-old JSON file and imported at run time?

Webpack acts on compile-time. That means when you require a file, it loads that file, performs modifications as specified by the loader-chain and exports you the final result from that chain. So what you're asking for sounds like a loader, that acts like a file-loader, but exports an IIFE that returns a promise for the required file.

In theory it's possible to have a webpack loader, lets say an async-file-loader that gets the input from the file-loader will handle the async requst for you. Let's assume something like:

```<code>const promisedFile = require('async-file-loader!file-loader!./myJson.json');
promisedFile.then(file => { console.log(JSON.parse(file)); });
</code>```

But then the whole logic for handling the request would be boundled within that call. The async-file-loader would look something like this:

```<code>module.exports = function(source) {
    return `module.exports = eval("(function(url){
      /* define async request func, preform request and return promise in here */
   })(${url})")`;
}
</code>```

Pretty nasty...

When you want to load your json-file in runtime, I'll see 2 options:

use the file-loader and request the json file asyncronously on your own.

use a server-sided scripting language and inject the config into the .html file. If your're using nodejs and express for example on your backend side, you could easily inject the config using Cheerio before serving the request.

Body:
I have a web-app that requires a configuration JSON file which contains end-points and other required start-up parameters.

If I use the json-loader, the file is not "real json", it'll look something like this:

module.exports = {
    "name": "foo",
    "key": true,
};

What I would like is plain old JSON which means it can be parsed and changed as part of a deployment process before being sent to the web server where it will be served from.

An alternative is to use the file-loader.  However, that means that (even though it's a trivial task) I have to write the code to download the file myself.  I would like to have webpack handle this and be available.

Is there a way that I can require a JSON file, which is written as a plain-old JSON file and imported at run time?

Body:
Is there a way that I can require a JSON file, which is written as a
  plain-old JSON file and imported at run time?

Webpack acts on compile-time. That means when you require a file, it loads that file, performs modifications as specified by the loader-chain and exports you the final result from that chain. So what you're asking for sounds like a loader, that acts like a file-loader, but exports an IIFE that returns a promise for the required file.

In theory it's possible to have a webpack loader, lets say an async-file-loader that gets the input from the file-loader will handle the async requst for you. Let's assume something like:

const promisedFile = require('async-file-loader!file-loader!./myJson.json');
promisedFile.then(file => { console.log(JSON.parse(file)); });

But then the whole logic for handling the request would be boundled within that call. The async-file-loader would look something like this:

module.exports = function(source) {
    return `module.exports = eval("(function(url){
      /* define async request func, preform request and return promise in here */
   })(${url})")`;
}

Pretty nasty...

When you want to load your json-file in runtime, I'll see 2 options:

use the file-loader and request the json file asyncronously on your own.

use a server-sided scripting language and inject the config into the .html file. If your're using nodejs and express for example on your backend side, you could easily inject the config using Cheerio before serving the request.


问:
How to obfuscate files without using any external libraries?
I am currently trying to obscure the contents of files or simply txt files without using any libraries. I know that this won't be very secure at all but what I basically want is a program that asks you what the password to "encrypt" it with is, then it asks what the files name is and then it finds that file and "encrypts" it. Then another program is used to "decrypt" it so it asks for the password and filename and then "decrypts" it. I don't care about actual security so if it can be easily opened it's fine I just need it so it doesn't just open if you click the file.

On top of that I don't want it to use ANY libraries so no pycrypto or anything like that.

I am on 64 bit windows.

I also am a complete beginner in tthe world of code and only know basic things such as how to get user input, print stuff, if loops and while loops.

Thanks in advance!

答:
I don't know if this qualifies as an "external library" in your mind, but if you're on a linux machine you probably have the gpg command available to you. This is a reasonably* secure encryption protocol, which you could access from python - or directly from the command line, if you just want the files protected and you don't care about having it done through python.

Alternatively, you could bang together a trivial mechanism for obscuring a file's contents based on a known password. For example, you could "stretch" the password to the length of the file text (multiply the string by (1 + (text length / password length)) and then zip the two together. This gives you a bunch of tuples, which can by converted to their ordinal value (ord('f')=>102, for example) and xored together (ord('f')^ord('b')=>4) and converted back to chars (chr(4) => the unprintable '\x04'). The resulting chars are your cyphertext.
All of this is trivial to break, of course, but it's easy to implement, and decryption is trivial.

*intentional understatement :)


问:
Opening browser's home page in other than IIE
I'm writing a bit of code to display an EU Cookie notification.

If the visitor does not accept the use of cookies, I want to take them somewhere else. My first thought was to take them to the browser's home page.

I found a way to do it in IE - I have been told that the method on that page is for IE 10 or less.

I have not found a way to do so in other browsers.

If this turns out to be more trouble than it is worth, I'll take them somewhere via a specific URL, such as www.google.com

Does anyone know of the method to accomplish the same thing in browsers such as Firefox, Safari, Chrome, etc?

答:
Most browsers implement an address that will point to the home page. You should be able to redirect the user to the proper location after you figure out their browser.

For Chrome you can link them to about:newtab, which may be different from the home page, but it is probably the closest you will find. The actual homepage button is not implemented in Javascript and does not use a URL.

For Firefox you can link to about:home.

For Opera you can link to opera:speeddial. (I did not test this one, if someone wants to I'll update)

The documentation you linked to claims to be obsolete after IE10. I think you can link to about:home on IE same as Firefox if your solution isn't working afer IE10. (I did not test this one, if someone wants to I'll update).


问:
SQL: Find all records in Table A that do not have a value in Table B based on a column value in Table B
Using Microsoft SQL Server 2012, I'm trying to get all businesses who did not make a payment in 2016.

Here is my schema

```<code>Business Table
---------------
Id     Name
1      Business A
2      Business B

Payments Table
---------------
Id     BusinessId   Year
1      2            2016
2      1            2017
3      2            2017
</code>```

I need a SQL statement that returns Business A since it does not have a payment for 2016.

Here is what I have tried:

```<code>SELECT [Business].Name
FROM Businesses as [Business]
Left Outer JOIN Payments as [Payment]
     ON [Payment].BusinessId = [Business].Id
Where [Business].Id is null and [Payment].TaxYear = 2016
</code>```

Any help would be greatly appreciated.

Also, the title might be a little convoluted, so a suggested edit for the title of this question would be welcome as well.

答:
NOT EXISTS, should return Business A since it does not have a 2016 transaction</p>

```<code>SELECT B.Name
FROM Business as B
WHERE NOT EXISTS (
  SELECT 1 FROM Payments P
Where P.TaxYear = 2016
     AND P.BusinessId = B.Id )
</code>```

Body:
Using Microsoft SQL Server 2012, I'm trying to get all businesses who did not make a payment in 2016.

Here is my schema

Business Table
---------------
Id     Name
1      Business A
2      Business B

Payments Table
---------------
Id     BusinessId   Year
1      2            2016
2      1            2017
3      2            2017

I need a SQL statement that returns Business A since it does not have a payment for 2016.

Here is what I have tried:

SELECT [Business].Name
FROM Businesses as [Business]
Left Outer JOIN Payments as [Payment]
     ON [Payment].BusinessId = [Business].Id
Where [Business].Id is null and [Payment].TaxYear = 2016

Any help would be greatly appreciated.

Also, the title might be a little convoluted, so a suggested edit for the title of this question would be welcome as well.

Body:
NOT EXISTS, should return Business A since it does not have a 2016 transaction

SELECT B.Name
FROM Business as B
WHERE NOT EXISTS (
  SELECT 1 FROM Payments P
Where P.TaxYear = 2016
     AND P.BusinessId = B.Id )


问:
simulate current date during tests
I am writing tests and I wonder if there is a way to change the current date during my test?

The point is that I am testing the statistic functionality of the application, which is connected to a tracking model that creates an instance every time an action is called (only some actions are tracked, via a "before_filter only" call)

So I need to call this actions in different controller at different points in time to test my analytics component is making the right calculations, but I did not find any way to implement change_current_time in the following sample code:

```<code>test "login count" do
  change_current_time(2.day.ago)
  get "users/login/testuser/testpassword"
  assert login_count(2.day.ago) == 1
  change_current_time(1.day.ago)
  get "users/login/testuser/testpassword"
  get "users/login/testuser1/testpassword1"
  assert login_count(1.day.ago) == 2
end
</code>```

答:
There is gem for mocking time in Rails.

https://github.com/harvesthq/time-warp

```<code>time = (2.days.ago)

pretend_now_is(time) do
  get "users/login/testuser/testpassword"
  assert login_count(Date.today) == 1 # it's stubbed
end

time = (1.days.ago)

pretend_now_is(time) do
  get "users/login/testuser/testpassword"
  get "users/login/testuser1/testpassword1"
  assert login_count(Date.today) == 2
end
</code>```

Title: simulate current date during tests

Body:
I am writing tests and I wonder if there is a way to change the current date during my test?

The point is that I am testing the statistic functionality of the application, which is connected to a tracking model that creates an instance every time an action is called (only some actions are tracked, via a "before_filter only" call)

So I need to call this actions in different controller at different points in time to test my analytics component is making the right calculations, but I did not find any way to implement change_current_time in the following sample code:

test "login count" do
  change_current_time(2.day.ago)
  get "users/login/testuser/testpassword"
  assert login_count(2.day.ago) == 1
  change_current_time(1.day.ago)
  get "users/login/testuser/testpassword"
  get "users/login/testuser1/testpassword1"
  assert login_count(1.day.ago) == 2
end

Body:
There is gem for mocking time in Rails.

https://github.com/harvesthq/time-warp

time = (2.days.ago)

pretend_now_is(time) do
  get "users/login/testuser/testpassword"
  assert login_count(Date.today) == 1 # it's stubbed
end

time = (1.days.ago)

pretend_now_is(time) do
  get "users/login/testuser/testpassword"
  get "users/login/testuser1/testpassword1"
  assert login_count(Date.today) == 2
end


问:
execute a command by switching to root user in ansible
I am working on Ansible playbook to execute some of my tasks. In one of my tasks, I need to switch to particular directory and then execute a command using sudo but I need to do all these things by switching to root user first otherwise it won't work. So in general this is what I do without ansible:

```<code>david@machineA:/tmp/parallel-20140422$ sudo su
root@machineA:/tmp/parallel-20140422# sudo ./configure && make && make install
</code>```

After above steps, I see GNU parallel library is installed in my system correctly. But with the below steps using Ansible, I don't see my GNU library getting installed at all.

```<code>- name: install gnu parallel
  command: chdir=/tmp/parallel-20140422 sudo ./configure && make && make install
</code>```

Now my question is how can I switch to root user and execute a particular command. I am running Ansible 1.5.4 and looks like I cannot upgrade. I even tried with below but still it doesn't work:

```<code>- name: install gnu parallel
  command: chdir=/tmp/parallel-20140422 sudo ./configure && make && make install
  sudo: true
  sudo_user: root
</code>```

I am running my playbook using below command:

```<code>ansible-playbook -e 'host_key_checking=False' setup.yml -u david --ask-pass --sudo -U root --ask-sudo-pass
</code>```

答:
From your comment:

I know command module is working fine bcoz I verified for other tasks and they work fine.

command module might be working for other commands, but in this example you use a shell syntax (&&) to execute multiple commands. This syntax will not work in the command module (because this module runs commands directly from Python and does not support combined commands).

You need to use the shell module in this case.

```<code>- name: install gnu parallel
  shell: ./configure && make && make install
  args:
    chdir=/tmp/parallel-20140422
  sudo: true
  sudo_user: root
</code>```

Body:
I am working on Ansible playbook to execute some of my tasks. In one of my tasks, I need to switch to particular directory and then execute a command using sudo but I need to do all these things by switching to root user first otherwise it won't work. So in general this is what I do without ansible:

david@machineA:/tmp/parallel-20140422$ sudo su
root@machineA:/tmp/parallel-20140422# sudo ./configure && make && make install

After above steps, I see GNU parallel library is installed in my system correctly. But with the below steps using Ansible, I don't see my GNU library getting installed at all.

- name: install gnu parallel
  command: chdir=/tmp/parallel-20140422 sudo ./configure && make && make install

Now my question is how can I switch to root user and execute a particular command. I am running Ansible 1.5.4 and looks like I cannot upgrade. I even tried with below but still it doesn't work:

- name: install gnu parallel
  command: chdir=/tmp/parallel-20140422 sudo ./configure && make && make install
  sudo: true
  sudo_user: root

I am running my playbook using below command:

ansible-playbook -e 'host_key_checking=False' setup.yml -u david --ask-pass --sudo -U root --ask-sudo-pass

Body:
From your comment:

I know command module is working fine bcoz I verified for other tasks and they work fine.

command module might be working for other commands, but in this example you use a shell syntax (&&) to execute multiple commands. This syntax will not work in the command module (because this module runs commands directly from Python and does not support combined commands).

You need to use the shell module in this case.

- name: install gnu parallel
  shell: ./configure && make && make install
  args:
    chdir=/tmp/parallel-20140422
  sudo: true
  sudo_user: root


问:
How to create a simple search input text in AngularJS material design?
I am looking for some easy way to have something similar to what is available in angular-mdl for expandable search text field as below..
This will add a search button on click it will expand to text field.

```<code><!-- Expandable Textfield -->
<form action="#">
  <div class="mdl-textfield mdl-js-textfield mdl-textfield--expandable">
    <label class="mdl-button mdl-js-button mdl-button--icon" for="sample6">
      <i class="material-icons">search</i>
    </label>
    <div class="mdl-textfield__expandable-holder">
      <input class="mdl-textfield__input" type="text" id="sample6">
      <label class="mdl-textfield__label" for="sample-expandable">Expandable Input</label>
    </div>
  </div>
</form>
</code>```

My requirement is to have such a search button in the Card title snapped to the right when user clicks it should expand to take input.. and I need to do it in Angular-Material.

Any inputs or help..!
Thanks.

答: Seems like there are no clean 'native' angular material option for that, so I used one of the textfield options from 'material design lite' library - expandable search button gif-demo </p>

Body:
I am looking for some easy way to have something similar to what is available in angular-mdl for expandable search text field as below..
This will add a search button on click it will expand to text field.

<form action="#">

      search

      <input class="mdl-textfield__input" type="text" id="sample6">
      Expandable Input

</form>

My requirement is to have such a search button in the Card title snapped to the right when user clicks it should expand to take input.. and I need to do it in Angular-Material.

Any inputs or help..!
Thanks.


问:
django admin site - divide in sections object attributes
I've been playing around with the django admin site and so far I've been able to add some attributes into the view where all objects of a model are shown, however (as i have a lot of attributes in the model) i would like to know if there is a way to divide by sections the attributes of the object when creating or modifying the object so readability can be better.

I've been trying to find a way but I haven't found it. As english is not my native language maybe I'm not searching for the right key words.

If anyone could point me in the right direction I would by grateful. Thanks in advance.

答: Have you tried customizing/overriding the admin templates? Take a look here in the docs. That might be what you need. Good luck!</p>


问:
ListActivities setItemChecked in onListItemClick not working
I have this code here:

```<code>@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    if(l.isItemChecked(position))
        l.setItemChecked(position, false);
    else
        l.setItemChecked(position, true);
    Toast.makeText(mContext, "Mission: " + ((TreeNode)l.getItemAtPosition(position)).getTitle(), Toast.LENGTH_LONG).show();

}
</code>```

It works as far as the debugger goes, but the setItemChecked never seems to really set the item both graphically I do not see the check box appear and then on the next click through the isItemChecked still returns false.

Not sure what I am doing wrong here?

答:
just try this.....
make android:focusable="false" to check box</p>

Body:
I have this code here:

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    if(l.isItemChecked(position))
        l.setItemChecked(position, false);
    else
        l.setItemChecked(position, true);
    Toast.makeText(mContext, "Mission: " + ((TreeNode)l.getItemAtPosition(position)).getTitle(), Toast.LENGTH_LONG).show();

}

It works as far as the debugger goes, but the setItemChecked never seems to really set the item both graphically I do not see the check box appear and then on the next click through the isItemChecked still returns false.

Not sure what I am doing wrong here?


问:
Calling python script with node js express server
With below code I have created a HTTP server on port 3000 and have added some get parameters. I want to invoke a python script with this express.js server code such that when I hit localhost:3000/key1/abc/key2/234 python script will get invoked. I've my python script ready which takes input args as sys.argv. Please suggest how to call python script with this code so that it will take value1 and value 2 as input arguments and return json.</p>

```<code>var express = require('express');
var app = express();
app.get('/key1/:value1/key2/:value2',function(req,res)
{
    console.log(req.params);
    var value1 = req.params.value1;
    var value2 = req.params.value2;
    res.send(req.params);
});
app.listen(3000,function()
{
    console.log("Server listening on port 3000");
});
</code>```

答:
To run a Python script from Node.js would require spawning a new process.
You can do that with child_process.

You would run python as the executable and give your script name as the first argument.

Here is an example based on the documentation linked above:

```<code>const spawn = require('child_process').spawn;
const ls = spawn('python', ['script.py', 'arg1', 'arg2']);

ls.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

ls.stderr.on('data', (data) => {
  console.log(`stderr: ${data}`);
});

ls.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});
</code>```

Body:
With below code I have created a HTTP server on port 3000 and have added some get parameters. I want to invoke a python script with this express.js server code such that when I hit localhost:3000/key1/abc/key2/234 python script will get invoked. I've my python script ready which takes input args as sys.argv. Please suggest how to call python script with this code so that it will take value1 and value 2 as input arguments and return json.

var express = require('express');
var app = express();
app.get('/key1/:value1/key2/:value2',function(req,res)
{
    console.log(req.params);
    var value1 = req.params.value1;
    var value2 = req.params.value2;
    res.send(req.params);
});
app.listen(3000,function()
{
    console.log("Server listening on port 3000");
});

Body:
To run a Python script from Node.js would require spawning a new process.
You can do that with child_process.

You would run python as the executable and give your script name as the first argument.

Here is an example based on the documentation linked above:

const spawn = require('child_process').spawn;
const ls = spawn('python', ['script.py', 'arg1', 'arg2']);

ls.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

ls.stderr.on('data', (data) => {
  console.log(`stderr: ${data}`);
});

ls.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});


问:
Who adds interrupt vector table to process virtual address space?
Is loading of IV table in virtual address space assembly, linker or loader job?
Also which part of OS reserve space for stack and heap in general?</p>

答: Neither, the BIOS normally loads the IVT so it can handle real mode interrupts.</p>


答:
I think you are looking for the combination of businesses and years that are not in the payments table.  If so:

```<code>select b.*
from businesses b cross join
     (select distinct year from payments) y left join
     payments p
     on b.id = p.businessid and b.year = y.year
where p.businessid is null;
</code>```

The cross join generates all combinations of businesses and years.  The left join and where clause then finds the ones that don't exist.

If you are only looking for one year, then @maSTAShuFu answer is the correct approach.

Title: SQL: Find all records in Table A that do not have a value in Table B based on a column value in Table B

Body:
I think you are looking for the combination of businesses and years that are not in the payments table.  If so:

select b.*
from businesses b cross join
     (select distinct year from payments) y left join
     payments p
     on b.id = p.businessid and b.year = y.year
where p.businessid is null;

The cross join generates all combinations of businesses and years.  The left join and where clause then finds the ones that don't exist.

If you are only looking for one year, then @maSTAShuFu answer is the correct approach.


问:
Real time update with Angular 2 and Node js
In Angular 2 I have a navbar and I show how many unread messages the person has. When the person clicks the message, it marks it as read. My database is marked as read, but the navbar doesn't update until I refresh the page entirely.

What can I do to solve this problem?

答: You can do it in a normal way no need to any real time. Just add a flag and set to boolean and make an HTTP cal. real-time data means you need to use a socket and establish a socket connection.</p>


问:
What's the point of throwing an exception?
I'm writing a login class in c#, and I'm trying to be diligent about throwing exceptions for null passwords, insufficiant password characters, etc. The thing that suddenly occured to me was - What do I do with these exception? What/who are they for? Whether I handle the exception or not, the app will still fail at that point. Is the exception for other developers, the customer!? </p>

答:
The exception itself happens to prevent bigger problems in the future. If you just silently did nothing when you knew something happened that wasn't supposed to, the program calling your code might assume that the user's file got saved when it really didn't, which can obviously be worse than if it's able to tell the user, "I couldn't save your file."

The message you give to an exception is for other developers. If the program crashes during development, the developer should be able to see the stack trace and more easily figure out why something happened that wasn't supposed to. Ideally you'll be able to log errors in such a way that developers can see them even in production.


问:
Get user's friends's profile picture React-native
I'm trying to retrieve all user's friends profile pictures to render them in a list view.

I get all user's friends that are in the application with this Graph Request:

```<code>`const infoRequest = new GraphRequest(
      '/me',
         {
           parameters: {
               fields: {
                        string: 'email, name, first_name, middle_name,
                 last_name, picture.type(large), cover, birthday, location, friends'
                    }
                }
            },
            this._responseInfoCallback
        );`
</code>```

Then, I'm trying to render his friends's profile picture with this function

```<code>`renderFriends() {
      if(this.state.user != null) {
        return this.state.user.friends.data.map(friend =>
          <View>
            <Image
              source={{uri:'https://graph.facebook.com/{friend.id}/picture?
                        type=large'}}
              style={styles.profilePicture}
            />
            <Text key={friend.id} >{friend.name}</Text>
          </View>
        )
      }
    }`
</code>```

All names are rendered correctly but images are not rendered.

You can check the style of the image below:

```<code>`profilePicture: {
    height: 120,
    width: 120,
    borderRadius: 60,
    marginTop: height / 15,
  },`
</code>```

答:
Change

```<code>{{ uri: 'https://graph.facebook.com/{friend.id}/picture?type=large' }}
</code>```

By

```<code>{{ uri: 'https://graph.facebook.com/' + friend.id + '/picture?type=large' }}
</code>```

{friend.id} doesn't get replaced by the friend id, it is interpreted as the literal string {friend.id}, which gives you the wrong url.

Body:
I'm trying to retrieve all user's friends profile pictures to render them in a list view.

I get all user's friends that are in the application with this Graph Request:

`const infoRequest = new GraphRequest(
      '/me',
         {
           parameters: {
               fields: {
                        string: 'email, name, first_name, middle_name,
                 last_name, picture.type(large), cover, birthday, location, friends'
                    }
                }
            },
            this._responseInfoCallback
        );`

Then, I'm trying to render his friends's profile picture with this function

`renderFriends() {
      if(this.state.user != null) {
        return this.state.user.friends.data.map(friend =>
          <View>
            <Image
              source={{uri:'https://graph.facebook.com/{friend.id}/picture?
                        type=large'}}
              style={styles.profilePicture}
            />
            <Text key={friend.id} >{friend.name}</Text>
          </View>
        )
      }
    }`

All names are rendered correctly but images are not rendered.

You can check the style of the image below:

`profilePicture: {
    height: 120,
    width: 120,
    borderRadius: 60,
    marginTop: height / 15,
  },`

Body:
Change

{{ uri: 'https://graph.facebook.com/{friend.id}/picture?type=large' }}

By

{{ uri: 'https://graph.facebook.com/' + friend.id + '/picture?type=large' }}

{friend.id} doesn't get replaced by the friend id, it is interpreted as the literal string {friend.id}, which gives you the wrong url.


问:
What goes inside of an html blockquote tag to indicate the author?
I have a blockquote tag, is there a semantic tag I could put inside for the author name? For example:

```<code><blockquote>Anyone who has neber made a mistake has never tried anything new
-<author>Einstein</author>
</blockquote>
</code>```

<author> is not an actual html tag, is there any appropriate tag?

答:
```<code>    <blockquote>Anyone who has neber made a mistake has never tried anything new -
 <cite>Einstein</cite>
    </blockquote>
</code>```

Body:
I have a blockquote tag, is there a semantic tag I could put inside for the author name? For example:

Anyone who has neber made a mistake has never tried anything new
-<author>Einstein</author>

<author> is not an actual html tag, is there any appropriate tag?


问:
Use Powershell and SSH-Sessions to launch openconnect VPN
I need to launch an openconnect VPN on a linux router from a powershell script on Windows.

I have a working script on the linux router:

```<code>echo PASSWORD | sudo openconnect -b --no-dtls --interface=sslvpn host.isp.com --authgroup=SharedVPN --user=username --passwd-on-stdin
</code>```

When I run the script locally on the router, the vpn launches perfectly.
Here is my powershell script from the windows machine:

Import-Module SSH-Sessions
New-SshSession -ComputerName "10.1.43.11" -Username "ubuntu" -KeyFile "C:\keys.pem"
Invoke-SshCommand -ComputerName "10.1.43.11" -Command '/usr/local/sbin/InitializeVPN'
Remove-SshSession -computername "10.1.43.11"

When I run the powershell script, it does launch the VPN, but freezes there, waiting for the VPN to end. I can kill the process on the router and then the powershell script finishes. I need the VPN to run in the background. So I modified the script on the router like this:

echo PASSWORD | sudo openconnect -b --no-dtls --interface=sslvpn host.isp.com --authgroup=SharedVPN --user=username --passwd-on-stdin &

Now when I run the powershell script, it does seem to send it into the background, but the VPN doesn't stay up and I only get partial output to the screen:

```<code>Key file specified. Will override password. Trying to read key file...
Successfully connected to 10.1.43.11
10.1.43.11: POST https://host.isp.com/
Connected to ip_addr:443
SSL negotiation with host.isp.com
Connected to HTTPS on host.isp.com
XML POST enabled
POST https://host.isp.com/
Connected to ip_addr:443
SSL negotiation with host.isp.com
Connected to HTTPS on host.isp.com
XML POST enabled
10.1.43.11 should now be disconnected and disposed.
</code>```

When I run it directly on the router, there is more after the last "XML POST enabled":

```<code>Please enter your username and password.
POST https://host.isp.com/
Got CONNECT response: HTTP/1.1 200 OK
CSTP connected. DPD 30, Keepalive 20
Connected as 10.251.0.29, using SSL
Continuing in background; pid 11049
Connect Banner:
| Access to this system is restricted to authorized users. Unauthorized use is strictly prohibited. Information on this system may be intercepted, recorded, read, copied, and disclosed by and to authorized personnel for official purposes, including criminal investigations. Access or use of this system whether authorized or unauthorized, constitutes your awareness and consent to these terms. DISCONNECT IMMEDIATELY if you do not agree to the conditions stated in this warning.
|
</code>```

How do I get the VPN to launch in the background?

I'm using ubuntu 16.04, openconnect 7.08, powershell 5.1, windows server 2016,
downloaded SSH-Sessions from http://www.powershelladmin.com/wiki/SSH_from_PowerShell_using_the_SSH.NET_library#Downloads

答:
Well, I got it working using plink:

```<code>C:\bin\plink.exe -i C:\key.ppk ubuntu@10.1.43.11 "nohup /usr/local/sbin/InitializeVPN >/home/ubuntu/VPN.out 2>/home/ubuntu/VPN.err </dev/null &"
</code>```

stdin, stdout, and stderr had to be redirected and use nohup.

I found it here: Getting ssh to execute a command in the background on target machine

Don't know if I'll take the time to get it working with PowerShell and SSH-Sessions now. Maybe if I need something more complex in the future.

Body:
I need to launch an openconnect VPN on a linux router from a powershell script on Windows.

I have a working script on the linux router:

echo PASSWORD | sudo openconnect -b --no-dtls --interface=sslvpn host.isp.com --authgroup=SharedVPN --user=username --passwd-on-stdin

When I run the script locally on the router, the vpn launches perfectly.
Here is my powershell script from the windows machine:

Import-Module SSH-Sessions
New-SshSession -ComputerName "10.1.43.11" -Username "ubuntu" -KeyFile "C:\keys.pem"
Invoke-SshCommand -ComputerName "10.1.43.11" -Command '/usr/local/sbin/InitializeVPN'
Remove-SshSession -computername "10.1.43.11"

When I run the powershell script, it does launch the VPN, but freezes there, waiting for the VPN to end. I can kill the process on the router and then the powershell script finishes. I need the VPN to run in the background. So I modified the script on the router like this:

echo PASSWORD | sudo openconnect -b --no-dtls --interface=sslvpn host.isp.com --authgroup=SharedVPN --user=username --passwd-on-stdin &

Now when I run the powershell script, it does seem to send it into the background, but the VPN doesn't stay up and I only get partial output to the screen:

Key file specified. Will override password. Trying to read key file...
Successfully connected to 10.1.43.11
10.1.43.11: POST https://host.isp.com/
Connected to ip_addr:443
SSL negotiation with host.isp.com
Connected to HTTPS on host.isp.com
XML POST enabled
POST https://host.isp.com/
Connected to ip_addr:443
SSL negotiation with host.isp.com
Connected to HTTPS on host.isp.com
XML POST enabled
10.1.43.11 should now be disconnected and disposed.

When I run it directly on the router, there is more after the last "XML POST enabled":

Please enter your username and password.
POST https://host.isp.com/
Got CONNECT response: HTTP/1.1 200 OK
CSTP connected. DPD 30, Keepalive 20
Connected as 10.251.0.29, using SSL
Continuing in background; pid 11049
Connect Banner:
| Access to this system is restricted to authorized users. Unauthorized use is strictly prohibited. Information on this system may be intercepted, recorded, read, copied, and disclosed by and to authorized personnel for official purposes, including criminal investigations. Access or use of this system whether authorized or unauthorized, constitutes your awareness and consent to these terms. DISCONNECT IMMEDIATELY if you do not agree to the conditions stated in this warning.
|

How do I get the VPN to launch in the background?

I'm using ubuntu 16.04, openconnect 7.08, powershell 5.1, windows server 2016,
downloaded SSH-Sessions from http://www.powershelladmin.com/wiki/SSH_from_PowerShell_using_the_SSH.NET_library#Downloads

Body:
Well, I got it working using plink:

C:\bin\plink.exe -i C:\key.ppk ubuntu@10.1.43.11 "nohup /usr/local/sbin/InitializeVPN >/home/ubuntu/VPN.out 2>/home/ubuntu/VPN.err </dev/null &"

stdin, stdout, and stderr had to be redirected and use nohup.

I found it here: Getting ssh to execute a command in the background on target machine

Don't know if I'll take the time to get it working with PowerShell and SSH-Sessions now. Maybe if I need something more complex in the future.


问:
How to use Leaflet maps with aspx?
I have just created an ASPX project and would like to integrate leaflet maps.

I have used leaflet before with HTML pages but now ASPX is requiring me to put everything inside a <asp:content> tag.

My Code

```<code><asp:Content ID="MapPage" ContentPlaceHolderID="MainContent" runat="server">
   <link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css"
    integrity="sha512-07I2e+7D8p6he1SIM+1twR5TIrhUQn9+I6yjqD53JQjFiMf8EtC93ty0/5vJTZGF8aAocvHYNEDJajGdNx1IsQ=="
    crossorigin=""/>

   <script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet.js"
    integrity="sha512-A7vV8IFfih/D732iSSKi20u/ooOfj/AGehOKq0f4vLT1Zr2Y+RX7C+w8A1gaSasGtRUZpF/NZgzSAu4/Gc41Lg=="
    crossorigin=""></script>

    <div id="mapid" style="height:100px; width:100px;"></div>

</asp:Content>
</code>```

I took the link and script tags from http://leafletjs.com/examples/quick-start/

their tutorial... Also, VS17 says HTML5 doesn't recognize crossorigin or integrity fields... any suggestions?

答:
Could you please try this, this works for me.

```<code><%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master"
AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs"
Inherits="WebApplication1.WebForm3" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1"
runat="server">

<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="shortcut icon" type="image/x-icon" href="docs/images/favicon.ico" />

   <link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css" integrity="sha512-07I2e+7D8p6he1SIM+1twR5TIrhUQn9+I6yjqD53JQjFiMf8EtC93ty0/5vJTZGF8aAocvHYNEDJajGdNx1IsQ==" crossorigin=""/>
    <script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet.js" integrity="sha512-A7vV8IFfih/D732iSSKi20u/ooOfj/AGehOKq0f4vLT1Zr2Y+RX7C+w8A1gaSasGtRUZpF/NZgzSAu4/Gc41Lg==" crossorigin=""></script>

<body>

<div id="mapid" style="width: 600px; height: 400px;"></div>
<script>

var mymap = L.map('mapid').setView([51.505, -0.09], 13);

L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
    maxZoom: 18,
    attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
        '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
        'Imagery © <a href="http://mapbox.com">Mapbox</a>',
    id: 'mapbox.streets'
}).addTo(mymap);
</code>```

Title: How to use Leaflet maps with aspx?

Body:
I have just created an ASPX project and would like to integrate leaflet maps.

I have used leaflet before with HTML pages but now ASPX is requiring me to put everything inside a <asp:content> tag.

My Code

<asp:Content ID="MapPage" ContentPlaceHolderID="MainContent" runat="server">
   <link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css"
    integrity="sha512-07I2e+7D8p6he1SIM+1twR5TIrhUQn9+I6yjqD53JQjFiMf8EtC93ty0/5vJTZGF8aAocvHYNEDJajGdNx1IsQ=="
    crossorigin=""/>

</asp:Content>

I took the link and script tags from http://leafletjs.com/examples/quick-start/

their tutorial... Also, VS17 says HTML5 doesn't recognize crossorigin or integrity fields... any suggestions?

Body:
Could you please try this, this works for me.

<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master"
AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs"
Inherits="WebApplication1.WebForm3" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1"
runat="server">

<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="shortcut icon" type="image/x-icon" href="docs/images/favicon.ico" />

   <link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css" integrity="sha512-07I2e+7D8p6he1SIM+1twR5TIrhUQn9+I6yjqD53JQjFiMf8EtC93ty0/5vJTZGF8aAocvHYNEDJajGdNx1IsQ==" crossorigin=""/>
    <script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet.js" integrity="sha512-A7vV8IFfih/D732iSSKi20u/ooOfj/AGehOKq0f4vLT1Zr2Y+RX7C+w8A1gaSasGtRUZpF/NZgzSAu4/Gc41Lg==" crossorigin=""></script>

<body>

<div id="mapid" style="width: 600px; height: 400px;"></div>
<script>

var mymap = L.map('mapid').setView([51.505, -0.09], 13);

L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
    maxZoom: 18,
    attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
        '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
        'Imagery © <a href="http://mapbox.com">Mapbox</a>',
    id: 'mapbox.streets'
}).addTo(mymap);


问:
What is the syntax for " M_PI_4" and "M_PI_2" in Swift 3?
I know M_PI is now CGFloat.pi but am not sure what M_PI_4 would be.  I tried CGFloat.pi*4 but that wasn't correct.

答:
Swift 3.1:
M_PI_4 is now .pi / 4

Body:
Swift 3.1:
M_PI_4 is now .pi / 4


问:
How to reproduce TCP protocol 3-way handshake with raw sockets correctly?
Im simulating tcp protocol's 3-way handshake in c++, along with wireshark as my code runs.
My code crafts the headers at ip and tcp layers, packs them, then send it to an http server with tcp header's SYN flag set to 1.

I can see on wireshark the full datagram with both ip and tcp headers ok. Seems to be no errors.
My process bind a socket with the same address and port as contained in the already sent packet's header.

Wireshark shows packet successfully sent but there isn't any income packet from the server acknowledging my SYN.
What am i doing wrong?

I am on Ubuntu 10.10, 2.6.35-23.

The code is messy, sorry for that. Its just for testing.

main.cpp:

```<code>    char host[100],buf[1000],*data=NULL,source_ip[20]; //buf is the complete packet
sockaddr_in dest;
hostent *server;
IPV4_HDR *v4hdr=NULL;
TCP_HDR *tcphdr=NULL;
memset(&buf, 0, sizeof(buf));

cout << "Creating RAW socket..." << endl;
int s;
if ((s = socket(AF_INET, SOCK_RAW, IPPROTO_TCP)) == -1) {
    cout << "Error creating socket: " << errno << endl;
    return 1;
}

cout << "Setting the socket in RAW mode..." << endl;
int optval = 1;
if ((setsockopt(s, IPPROTO_IP, IP_HDRINCL, &optval, sizeof(optval))) == -1) {
    cout << "Failed to set socket in RAW mode..." << endl;
    return 1;
}
cout << "Successful.\n";

cout << "nResolving Hostname..." << endl;
if((server=gethostbyname("www.site.com"))==0)
{
    cout << "Unable to resolve." << endl;
    return 1;
}
dest.sin_family = AF_INET;
dest.sin_port = htons(50000);
memcpy(&dest.sin_addr.s_addr,server->h_addr,server->h_length);
cout << "Resolved." << endl;

v4hdr = (IPV4_HDR *)buf; //lets point to the ip header portion
v4hdr->ip_version=4;
v4hdr->ip_header_len=5;
v4hdr->ip_tos = 16;
v4hdr->ip_total_length = htons ( sizeof(IPV4_HDR) + sizeof(TCP_HDR) );
v4hdr->ip_id = htons(2);
v4hdr->ip_frag_offset = 0;
v4hdr->ip_frag_offset1 = 0;
v4hdr->ip_reserved_zero = 0;
v4hdr->ip_dont_fragment = 1;
v4hdr->ip_more_fragment = 0;
v4hdr->ip_ttl = 64;
v4hdr->ip_protocol = IPPROTO_TCP;
v4hdr->ip_srcaddr = inet_addr("192.168.0.103");
v4hdr->ip_destaddr = inet_addr(inet_ntoa(dest.sin_addr));
v4hdr->ip_checksum = 0;

tcphdr = (TCP_HDR *)&buf[sizeof(IPV4_HDR)]; //get the pointer to the tcp header in the packet

tcphdr->source_port = htons(52000);
tcphdr->dest_port = htons(80);
tcphdr->window = htons(5840);
tcphdr->acknowledge = 0;
tcphdr->data_offset = 8;
tcphdr->urg=0;
tcphdr->ack=0;
tcphdr->psh=0;
tcphdr->rst=0;
tcphdr->syn=1;
tcphdr->fin=0;
tcphdr->options1=htonl(0x020405b4);
tcphdr->options2=htonl(0x04020103);
tcphdr->options3=htonl(0x03060000);

cout << sizeof(*tcphdr) << endl;

//tcphdr->ns=0;

tcphdr->checksum = csum((unsigned short *) buf, (sizeof(ip_hdr) + sizeof(tcp_header)));;
int bytes = 0;
if((bytes = sendto(s , buf , sizeof(IPV4_HDR)+sizeof(TCP_HDR), 0,
(sockaddr *)&dest, sizeof(dest)))==-1)
{
    cout << "Error sending packet: " << errno << endl;
    return 1;
}
cout << bytes << " bytes sent!" << endl;
close(s);
</code>```

// This is on tcp.h...

```<code>typedef struct ip_hdr
{
unsigned char ip_header_len:4; // 4-bit header length (in 32-bit words)

                               // normally=5 (Means 20 Bytes may be 24 also)

unsigned char ip_version :4;   // 4-bit IPv4 version

unsigned char ip_tos;          // IP type of service

unsigned short ip_total_length; // Total length

unsigned short ip_id;          // Unique identifier

unsigned char ip_frag_offset :5; // Fragment offset field

unsigned char ip_more_fragment :1;
unsigned char ip_dont_fragment :1;
unsigned char ip_reserved_zero :1;

unsigned char ip_frag_offset1; //fragment offset

unsigned char ip_ttl;          // Time to live

unsigned char ip_protocol;     // Protocol(TCP,UDP etc)

unsigned short ip_checksum;    // IP checksum

unsigned int ip_srcaddr;       // Source address

unsigned int ip_destaddr;      // Source address

} IPV4_HDR;

// TCP header

typedef struct tcp_header
{
unsigned short source_port;   // source port

unsigned short dest_port;     // destination port

unsigned int sequence;        // sequence number - 32 bits

unsigned int acknowledge;     // acknowledgement number - 32 bits

unsigned char reserved_part1:4; //according to rfc
unsigned char data_offset:4;    /*The number of 32-bit words
                                  in the TCP header.
                                  This indicates where the data begins.
                                  The length of the TCP header
                                  is always a multiple
                                  of 32 bits.*/

unsigned char fin :1; //Finish Flag

unsigned char syn :1; //Synchronise Flag

unsigned char rst :1; //Reset Flag

unsigned char psh :1; //Push Flag

unsigned char ack :1; //Acknowledgement Flag

unsigned char urg :1; //Urgent Flag

unsigned char reserved_part2:2;

unsigned short window :16; // window

//unsigned char ns :1;          //Nonce Sum Flag Added in RFC 3540.

//unsigned char ecn :1; //ECN-Echo Flag

//unsigned char cwr :1; //Congestion Window Reduced Flag

////////////////////////////////

unsigned short checksum; // checksum

unsigned short urgent_pointer; // urgent pointer

unsigned int options1;
unsigned int options2;
unsigned int options3;

} TCP_HDR;
</code>```

答: You haven't gotten this far yet, but you will need to firewall the local port you are using so that the kernel doesn't reply to SYN/ACK with a RST.</p>

Body:
Im simulating tcp protocol's 3-way handshake in c++, along with wireshark as my code runs.
My code crafts the headers at ip and tcp layers, packs them, then send it to an http server with tcp header's SYN flag set to 1.

I can see on wireshark the full datagram with both ip and tcp headers ok. Seems to be no errors.
My process bind a socket with the same address and port as contained in the already sent packet's header.

Wireshark shows packet successfully sent but there isn't any income packet from the server acknowledging my SYN.
What am i doing wrong?

I am on Ubuntu 10.10, 2.6.35-23.

The code is messy, sorry for that. Its just for testing.

main.cpp:

    char host[100],buf[1000],*data=NULL,source_ip[20]; //buf is the complete packet
sockaddr_in dest;
hostent *server;
IPV4_HDR *v4hdr=NULL;
TCP_HDR *tcphdr=NULL;
memset(&buf, 0, sizeof(buf));

cout << "Creating RAW socket..." << endl;
int s;
if ((s = socket(AF_INET, SOCK_RAW, IPPROTO_TCP)) == -1) {
    cout << "Error creating socket: " << errno << endl;
    return 1;
}

cout << "Setting the socket in RAW mode..." << endl;
int optval = 1;
if ((setsockopt(s, IPPROTO_IP, IP_HDRINCL, &optval, sizeof(optval))) == -1) {
    cout << "Failed to set socket in RAW mode..." << endl;
    return 1;
}
cout << "Successful.\n";

cout << "nResolving Hostname..." << endl;
if((server=gethostbyname("www.site.com"))==0)
{
    cout << "Unable to resolve." << endl;
    return 1;
}
dest.sin_family = AF_INET;
dest.sin_port = htons(50000);
memcpy(&dest.sin_addr.s_addr,server->h_addr,server->h_length);
cout << "Resolved." << endl;

v4hdr = (IPV4_HDR *)buf; //lets point to the ip header portion
v4hdr->ip_version=4;
v4hdr->ip_header_len=5;
v4hdr->ip_tos = 16;
v4hdr->ip_total_length = htons ( sizeof(IPV4_HDR) + sizeof(TCP_HDR) );
v4hdr->ip_id = htons(2);
v4hdr->ip_frag_offset = 0;
v4hdr->ip_frag_offset1 = 0;
v4hdr->ip_reserved_zero = 0;
v4hdr->ip_dont_fragment = 1;
v4hdr->ip_more_fragment = 0;
v4hdr->ip_ttl = 64;
v4hdr->ip_protocol = IPPROTO_TCP;
v4hdr->ip_srcaddr = inet_addr("192.168.0.103");
v4hdr->ip_destaddr = inet_addr(inet_ntoa(dest.sin_addr));
v4hdr->ip_checksum = 0;

tcphdr = (TCP_HDR *)&buf[sizeof(IPV4_HDR)]; //get the pointer to the tcp header in the packet

tcphdr->source_port = htons(52000);
tcphdr->dest_port = htons(80);
tcphdr->window = htons(5840);
tcphdr->acknowledge = 0;
tcphdr->data_offset = 8;
tcphdr->urg=0;
tcphdr->ack=0;
tcphdr->psh=0;
tcphdr->rst=0;
tcphdr->syn=1;
tcphdr->fin=0;
tcphdr->options1=htonl(0x020405b4);
tcphdr->options2=htonl(0x04020103);
tcphdr->options3=htonl(0x03060000);

cout << sizeof(*tcphdr) << endl;

//tcphdr->ns=0;

tcphdr->checksum = csum((unsigned short *) buf, (sizeof(ip_hdr) + sizeof(tcp_header)));;
int bytes = 0;
if((bytes = sendto(s , buf , sizeof(IPV4_HDR)+sizeof(TCP_HDR), 0,
(sockaddr *)&dest, sizeof(dest)))==-1)
{
    cout << "Error sending packet: " << errno << endl;
    return 1;
}
cout << bytes << " bytes sent!" << endl;
close(s);

// This is on tcp.h...

typedef struct ip_hdr
{
unsigned char ip_header_len:4; // 4-bit header length (in 32-bit words)

                               // normally=5 (Means 20 Bytes may be 24 also)

unsigned char ip_version :4;   // 4-bit IPv4 version

unsigned char ip_tos;          // IP type of service

unsigned short ip_total_length; // Total length

unsigned short ip_id;          // Unique identifier

unsigned char ip_frag_offset :5; // Fragment offset field

unsigned char ip_more_fragment :1;
unsigned char ip_dont_fragment :1;
unsigned char ip_reserved_zero :1;

unsigned char ip_frag_offset1; //fragment offset

unsigned char ip_ttl;          // Time to live

unsigned char ip_protocol;     // Protocol(TCP,UDP etc)

unsigned short ip_checksum;    // IP checksum

unsigned int ip_srcaddr;       // Source address

unsigned int ip_destaddr;      // Source address

} IPV4_HDR;

// TCP header

typedef struct tcp_header
{
unsigned short source_port;   // source port

unsigned short dest_port;     // destination port

unsigned int sequence;        // sequence number - 32 bits

unsigned int acknowledge;     // acknowledgement number - 32 bits

unsigned char reserved_part1:4; //according to rfc
unsigned char data_offset:4;    /*The number of 32-bit words
                                  in the TCP header.
                                  This indicates where the data begins.
                                  The length of the TCP header
                                  is always a multiple
                                  of 32 bits.*/

unsigned char fin :1; //Finish Flag

unsigned char syn :1; //Synchronise Flag

unsigned char rst :1; //Reset Flag

unsigned char psh :1; //Push Flag

unsigned char ack :1; //Acknowledgement Flag

unsigned char urg :1; //Urgent Flag

unsigned char reserved_part2:2;

unsigned short window :16; // window

//unsigned char ns :1;          //Nonce Sum Flag Added in RFC 3540.

//unsigned char ecn :1; //ECN-Echo Flag

//unsigned char cwr :1; //Congestion Window Reduced Flag

////////////////////////////////

unsigned short checksum; // checksum

unsigned short urgent_pointer; // urgent pointer

unsigned int options1;
unsigned int options2;
unsigned int options3;

} TCP_HDR;


问:
How to provide different sizes for iMessage Sticker App Grid Sticker
I have created an iOS iMessage sticker app, and according to apple documentation, I should be able to display the stickers in one of three different sizes.

However, no matter what size I make the sticker images (300px by 300px, 408px by 408px, 618px by 618px) they only show up as the middle grid option, with three stickers per row. Does anyone know how to fix this issue, maybe I am missing something simple?

Documentation on this topic is scarce because it is fairly new. Thanks for the help.

Link to documentation: https://developer.apple.com/ios/human-interface-guidelines/extensions/messaging/

答:
Importing the images at 300x300, 408x408, or 618x618 will ONLY affect the size the sticker appears in the conversation(when sent as initial message or dragged onto an existing message bubble. Changing the dimensions of your images will NOT affect it's orientation in the grid layout.

To change the grid layout in the StickerBrowserView you can do it one of two ways:

InterfaceBuilder

Click on the StickerPack folder so it is highlighted(or select any sticker from your pack) and then you can change the "Sticker Size" option from the dropdown menu in the attributes inspector on the right-hand side to your preferred presentation style: small(2 columns), medium(3 columns), or large(4 columns). That's all! This will change every sticker to display this way in the layout. No matter what size you import your images at, your app will scale it down/up to the correct dimensions for use in the chosen layout.

Programmatically

First, set up a new project as a "messages application", then create a new file to subclass MSStickerBrowserViewController, create array to store stickers, load/create stickers(while storing each into stickers array), and make sure to implement the 2 required datasource methods of MSStickerBrowserViewController. For this, you can just drag your images into the Extensions directory.

SubclassFile.Swift

```<code>import UIKit
import Messages

class MyBrowserVC: MSStickerBrowserViewController {

    //create stickers array
    var stickers = [MSSticker]()

    //load assets into stickers array
    func loadStickers() {
        createSticker(asset: "boycott", localizedDescription: "boycottSticker")
        createSticker(asset: "alluminaughty", localizedDescription: "alluminaughtySticker")
        createSticker(asset: "beer", localizedDescription: "beerSticker")
    }

    //func to create sticker
    func createSticker(asset: String, localizedDescription: String) {

        //create url from assets in main bundle
        guard let stickerPath = Bundle.main.path(forResource: asset, ofType: "png") else {
            print("Couldn't create sticker path for", asset)
            return
        }
        let stickerURL = URL(fileURLWithPath: stickerPath)
        let sticker: MSSticker

        //create sticker from path(and localized description) and add to array
        do {
            try sticker = MSSticker(contentsOfFileURL: stickerURL,
                                 localizedDescription: localizedDescription)
            stickers.append(sticker)
        } catch {
            print(error)
            return
        }
    }

    //datasource methods
    override func numberOfStickers(in stickerBrowserView: MSStickerBrowserView) -> Int {
        return stickers.count
    }
    override func stickerBrowserView(_ stickerBrowserView: MSStickerBrowserView,
                                          stickerAt index: Int) -> MSSticker {
        return stickers[index]
    }
}
</code>```

In your MessagesViewController(should be there automatically when beginning a new project), create instance of your BrowserVC from your subclass, set sticker size, browserVC frame, add subview to front, and load stickers to the browser view.

MessageViewController.swift

```<code>import UIKit
import Messages

class MessagesViewController: MSMessagesAppViewController {

    //create BrowserVC instance of Subclass
    var browserVC: MyBrowserVC!

    override func viewDidLoad() {
        super.viewDidLoad()

    //the next line of code is where you can adjust the "grid layout"
    //your options are: .small(2 columns), .regular(3 columns), or .large(4 columns)

        //instantiate browserVC with sticker size and set frame
        browserVC = MyBrowserVC(stickerSize: .regular)
        browserVC.view.frame = self.view.frame

        //send browserVC to front
        self.addChild(browserVC)
        browserVC.didMove(toParent: self)
        self.view.addSubview(browserVC.view)

        //load stickers onto the browser view
        browserVC.loadStickers()
        browserVC.stickerBrowserView.reloadData()
    }
}
</code>```

For better info, check out the WWDC video released last year on Stickers! This is where I started learning to build stickers, then hit up the documentation!

ContentLicense: CC BY-SA 4.0

Body:
Importing the images at 300x300, 408x408, or 618x618 will ONLY affect the size the sticker appears in the conversation(when sent as initial message or dragged onto an existing message bubble. Changing the dimensions of your images will NOT affect it's orientation in the grid layout.

To change the grid layout in the StickerBrowserView you can do it one of two ways:

InterfaceBuilder

Click on the StickerPack folder so it is highlighted(or select any sticker from your pack) and then you can change the "Sticker Size" option from the dropdown menu in the attributes inspector on the right-hand side to your preferred presentation style: small(2 columns), medium(3 columns), or large(4 columns). That's all! This will change every sticker to display this way in the layout. No matter what size you import your images at, your app will scale it down/up to the correct dimensions for use in the chosen layout.

Programmatically

First, set up a new project as a "messages application", then create a new file to subclass MSStickerBrowserViewController, create array to store stickers, load/create stickers(while storing each into stickers array), and make sure to implement the 2 required datasource methods of MSStickerBrowserViewController. For this, you can just drag your images into the Extensions directory.

SubclassFile.Swift

import UIKit
import Messages

class MyBrowserVC: MSStickerBrowserViewController {

    //create stickers array
    var stickers = [MSSticker]()

    //load assets into stickers array
    func loadStickers() {
        createSticker(asset: "boycott", localizedDescription: "boycottSticker")
        createSticker(asset: "alluminaughty", localizedDescription: "alluminaughtySticker")
        createSticker(asset: "beer", localizedDescription: "beerSticker")
    }

    //func to create sticker
    func createSticker(asset: String, localizedDescription: String) {

        //create url from assets in main bundle
        guard let stickerPath = Bundle.main.path(forResource: asset, ofType: "png") else {
            print("Couldn't create sticker path for", asset)
            return
        }
        let stickerURL = URL(fileURLWithPath: stickerPath)
        let sticker: MSSticker

        //create sticker from path(and localized description) and add to array
        do {
            try sticker = MSSticker(contentsOfFileURL: stickerURL,
                                 localizedDescription: localizedDescription)
            stickers.append(sticker)
        } catch {
            print(error)
            return
        }
    }

    //datasource methods
    override func numberOfStickers(in stickerBrowserView: MSStickerBrowserView) -> Int {
        return stickers.count
    }
    override func stickerBrowserView(_ stickerBrowserView: MSStickerBrowserView,
                                          stickerAt index: Int) -> MSSticker {
        return stickers[index]
    }
}

In your MessagesViewController(should be there automatically when beginning a new project), create instance of your BrowserVC from your subclass, set sticker size, browserVC frame, add subview to front, and load stickers to the browser view.

MessageViewController.swift

import UIKit
import Messages

class MessagesViewController: MSMessagesAppViewController {

    //create BrowserVC instance of Subclass
    var browserVC: MyBrowserVC!

    override func viewDidLoad() {
        super.viewDidLoad()

    //the next line of code is where you can adjust the "grid layout"
    //your options are: .small(2 columns), .regular(3 columns), or .large(4 columns)

        //instantiate browserVC with sticker size and set frame
        browserVC = MyBrowserVC(stickerSize: .regular)
        browserVC.view.frame = self.view.frame

        //send browserVC to front
        self.addChild(browserVC)
        browserVC.didMove(toParent: self)
        self.view.addSubview(browserVC.view)

        //load stickers onto the browser view
        browserVC.loadStickers()
        browserVC.stickerBrowserView.reloadData()
    }
}

For better info, check out the WWDC video released last year on Stickers! This is where I started learning to build stickers, then hit up the documentation!


问:
Scalate's render tag is not able to resolve the template
Scalate's render tag is not able to resolve the template and throws the following exception:

org.fusesource.scalate.util.ResourceNotFoundException: Could not load resource: [file:/Users/xxxxx/template/abc-conf.ssp]
    at org.fusesource.scalate.util.ResourceLoader$class.createNotFoundException(ResourceLoader.scala:58)
    at org.fusesource.scalate.util.FileResourceLoader.createNotFoundException(ResourceLoader.scala:61)
    at org.fusesource.scalate.util.ResourceLoader$class.resourceOrFail(ResourceLoader.scala:55)
    at org.fusesource.scalate.util.FileResourceLoader.resourceOrFail(ResourceLoader.scala:61)
    at org.fusesource.scalate.util.UriResource.delegate(Resource.scala:90)
    at org.fusesource.scalate.util.DelegateResource.text(Resource.scala:215)
    at org.fusesource.scalate.ssp.SspCodeGenerator.generate(SspCodeGenerator.scala:152)
    at org.fusesource.scalate.TemplateEngine.compileAndLoad(TemplateEngine.scala:802)
    a

答: It's looking for templates in a folder called template, but you've told me in your comment that your templates are in a folder called template*s*. Rename your folder to template and it should work.


问:
Does if with ifelse ,ifelse needs to have at least one else statement
```<code>if ()
{}else if (){}
else if (){}
else if (){}
else{}
</code>```

Do we need to have at least one  else {}?

答: You do not need an else. If your conditions fail, no code will be executed without the else.</p>

Body:
if ()
{}else if (){}
else if (){}
else if (){}
else{}

Do we need to have at least one  else {}?


问:
How to do timestamp regex given start time and end time?
I was working on extracting the log lines of interest from a huge log file.
Note that I'm not familiar with python at all.

The log line all starts from a timestamp, like

09:00:00.648711172 [Info  ] [....]
```

<p>And I want to match it with a specific period of time, say from 09:00 to 09:30, I came up with the following solution:</p>

```r'^(09:[012][0-9]|30)
```

The problem is this cannot apply to a generic case, say we're given a start_time and an end_time, how can I do the match?

答:
Short of building your regex pattern for different start_time and end_time, you can capture and parse the time and compare it with actual time range:

```<code>import datetime

start_time = datetime.time(9, 00)
end_time = datetime.time(9, 30)

log_line = "09:00:00.648711172 [Info  ] [....]"

log_time = datetime.datetime.strptime(log_line[:log_line.find(".")], "%H:%M:%S").time()
if start_time <= log_time <= end_time:
    print("Woo, we've found a match: {}".format(log_line))
else:
    print("Close, but no cigar with the line: {}".format(log_line))
</code>```

Body:
I was working on extracting the log lines of interest from a huge log file.
Note that I'm not familiar with python at all.

The log line all starts from a timestamp, like

09:00:00.648711172 [Info  ] [....]

And I want to match it with a specific period of time, say from 09:00 to 09:30, I came up with the following solution:

r'^(09:[012][0-9]|30)

The problem is this cannot apply to a generic case, say we're given a start_time and an end_time, how can I do the match?

Body:
Short of building your regex pattern for different start_time and end_time, you can capture and parse the time and compare it with actual time range:

import datetime

start_time = datetime.time(9, 00)
end_time = datetime.time(9, 30)

log_line = "09:00:00.648711172 [Info  ] [....]"

log_time = datetime.datetime.strptime(log_line[:log_line.find(".")], "%H:%M:%S").time()
if start_time <= log_time <= end_time:
    print("Woo, we've found a match: {}".format(log_line))
else:
    print("Close, but no cigar with the line: {}".format(log_line))


问:
Does AWS support weighted load balancing?
Does AWS natively support weighted load balancing?

From what I see, ELB does only support round-robin load balancing (without any configurable weights). I have not found reliable documentation on it, though.

The easiest thing that I can think of is to put a load balancer like Nginx in front of it, for example:

```<code>upstream backend  {
  server backend1.example.com weight=1;
  server backend2.example.com weight=2;
  server backend3.example.com weight=4;
}
</code>```

Here, out of seven requests, one will go to backend1, two to backend2, and four to backend4.

It will work, but it also means you have to setup a server with Nginx just for that. If AWS would directly support weighted load balancing that would be far easier to setup.

答:
UPDATE: This answer might be outdated. See @DanielC's answer for more recent information.

The How Elastic Load Balancing Works documentation page states:

With a Classic Load Balancer, the load balancer node that receives the request selects a registered instance using the round robin routing algorithm for TCP listeners and the least outstanding requests routing algorithm for HTTP and HTTPS listeners.

With an Application Load Balancer, the load balancer node that receives the request evaluates the listener rules in priority order to determine which rule to apply, and then selects a target from the target group for the rule action using the round robin routing algorithm. Routing is performed independently for each target group, even when a target is registered with multiple target groups.

The Elastic Load balancing service does not support weighted round-robin (where you specify the weights).

You could use Amazon Route 53 with a Weighted Routing Policy. From the Choosing a Routing Policy documentation page:

Use the weighted routing policy when you have multiple resources that perform the same function (for example, web servers that serve the same website) and you want Amazon Route 53 to route traffic to those resources in proportions that you specify (for example, one quarter to one server and three quarters to the other).

Body:
Does AWS natively support weighted load balancing?

From what I see, ELB does only support round-robin load balancing (without any configurable weights). I have not found reliable documentation on it, though.

The easiest thing that I can think of is to put a load balancer like Nginx in front of it, for example:

upstream backend  {
  server backend1.example.com weight=1;
  server backend2.example.com weight=2;
  server backend3.example.com weight=4;
}

Here, out of seven requests, one will go to backend1, two to backend2, and four to backend4.

It will work, but it also means you have to setup a server with Nginx just for that. If AWS would directly support weighted load balancing that would be far easier to setup.


问:
PHP variable in href in PHP
I'm struggling with the syntax of this:

```<code>echo '<strong><a href="<?php echo get_post_meta( get_the_ID(), 'data_sheet', true );?>" target="_blank">Datasheet</a></strong>';
</code>```

The central PHP element gets a URL from a WooCommerce custom field (I know this works ok on its own). That needs to be turned into a viable link opening a new page, and the whole sits in a PHP wrapper on the page.

Where am I going wrong?

答:
Try adding more to / changing the href

something like this might work

```<code>echo '<strong><a href="data_sheet.php?id='.$_GET['id'].'" target="_blank">Datasheet</a></strong>';
</code>```

You'll have to adjust a little bit, but should do the trick

Title: PHP variable in href in PHP

Body:
I'm struggling with the syntax of this:

echo '<a href="<?php echo get_post_meta( get_the_ID(), 'data_sheet', true );?>" target="_blank">Datasheet';

The central PHP element gets a URL from a WooCommerce custom field (I know this works ok on its own). That needs to be turned into a viable link opening a new page, and the whole sits in a PHP wrapper on the page.

Where am I going wrong?

Body:
Try adding more to / changing the href

something like this might work

echo '<strong><a href="data_sheet.php?id='.$_GET['id'].'" target="_blank">Datasheet</a></strong>';

You'll have to adjust a little bit, but should do the trick


问:
Loading native lib error
I have problem with starting my app on linux, from IDE and direct from win everthink is ok, but on linux I'm getting following error:

```<code>native lib Version = RXTX-2.2pre2
mar 06, 2017 7:54:44 PM org.jnativehook.DefaultLibraryLocator getLibraries
SEVERE: Unable to extract the native library /org/jnativehook/lib/linux/arm/libJNativeHook.so!

Exception in thread "AWT-EventQueue-0" java.lang.UnsatisfiedLinkError: org.jnativehook.GlobalScreen.getAutoRepeatRate()Ljava/lang/Integer;
at org.jnativehook.GlobalScreen.getAutoRepeatRate(Native Method)
at org.jnativehook.GlobalScreen.<clinit>(Unknown Source)
at the.main.pac.TheModbusSimpleTesterWindow$1.run(TheModbusSimpleTesterWindow.java:74)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
</code>```

Thanks for help in advance

答: The library tries to extract the naive code from the Jar if no library is found on the java.library.path property.  If you are repacking the Jar, you must pack the libraries to the same location within the Jar and fully comply with the GPL licence for your project.  The library must be included as a stand-alone library to comply with the Lesser-GPL.  You can specify a different library loading method or location by implementing the NativeLibraryLocator interface.  See DefaultLibraryLocator for an implementation example.

Title: Loading native lib error

Body:
I have problem with starting my app on linux, from IDE and direct from win everthink is ok, but on linux I'm getting following error:

native lib Version = RXTX-2.2pre2
mar 06, 2017 7:54:44 PM org.jnativehook.DefaultLibraryLocator getLibraries
SEVERE: Unable to extract the native library /org/jnativehook/lib/linux/arm/libJNativeHook.so!

Exception in thread "AWT-EventQueue-0" java.lang.UnsatisfiedLinkError: org.jnativehook.GlobalScreen.getAutoRepeatRate()Ljava/lang/Integer;
at org.jnativehook.GlobalScreen.getAutoRepeatRate(Native Method)
at org.jnativehook.GlobalScreen.<clinit>(Unknown Source)
at the.main.pac.TheModbusSimpleTesterWindow$1.run(TheModbusSimpleTesterWindow.java:74)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Thanks for help in advance


问:
Mouse move event if mouse down happened
How I can use mouse move event when mouse down event happened and when mouse up event I don't want to use mouse move event? I want draw line on canvas in this way.
Please help me? </p>

答: You may create a global variable drawing that becomes true on mouse down and becomes false on mouse up. Then, on mouse move, only draw if drawing == true.

Title: Mouse move event if mouse down happened


问:
Does TypeScript (^2.3.3) lose type information on array spread?
When I create a new array by using the array spread operator TypeScript seems to lose the correct type information.

This does not happen if I create the new array with Array.combine().

I've prepared a simple example to demonstrate this. I use declaration merging to have the constants (ACES, TWOS, etc.) have their corresponding type. Then I create the type Category to be a "supertype".

The variable sectionsSpread is of type string[] after creating it with the array spread operator. The variable sectionsCombined is of type Category[].

I expected the variable sectionsSpread to be also of type Category[].

Is this a bug? Have I got array spreading wrong?

```<code>const ACES = 'ACES';
type ACES = typeof ACES;

const TWOS = 'TWOS';
type TWOS = typeof TWOS;

const THREES = 'THREES';
type THREES = typeof THREES;

const FULL_HOUSE = 'FULL_HOUSE';
type FULL_HOUSE = typeof FULL_HOUSE;

const SMALL_STRAIGHT = 'SMALL_STRAIGHT';
type SMALL_STRAIGHT = typeof SMALL_STRAIGHT;

const LARGE_STRAIGHT = 'LARGE_STRAIGHT';
type LARGE_STRAIGHT = typeof LARGE_STRAIGHT;

type Category = ACES | TWOS | THREES |
    FULL_HOUSE | SMALL_STRAIGHT | LARGE_STRAIGHT;

const upperSection: Array<Category> = [ACES, TWOS, THREES];
const lowerSection: Array<Category> = [FULL_HOUSE, SMALL_STRAIGHT, LARGE_STRAIGHT];

const sectionsSpread = [
    ...upperSection,
    ...lowerSection
];

const sectionsCombined = upperSection.concat(lowerSection);
</code>```

UDATE

@dbandstra and @basarat pointed me in the right direction. After reading the suggested blog post I think I understand Literal Type Widening. But this still doesn't explain the behaviour of the typeof operator in this context for me.

I hope the following examples make my problem more clear:

```<code>const ACES = 'ACES';
type ACES = 'ACES'; // non-widening literal type

const TWOS = 'TWOS';
type TWOS = 'TWOS'; // non-widening literal type

type Category = ACES | TWOS; // are these values or types?

const upperSection: Category[] = [ACES];
const lowerSection: Category[] = [TWOS];

const sectionsSpread = [
    ...upperSection,
    ...lowerSection,
]; // is of type Category[]
</code>```

If I use typeof the variable sectionsSpread ends up being of type string[] instead:

```<code>const ACES = 'ACES';
type ACES = typeof ACES; // what does typeof do here?

const TWOS = 'TWOS';
type TWOS = typeof TWOS; // what does typeof do here?

type Category = ACES | TWOS; // are these values or types?

const upperSection: Category[] = [ACES];
const lowerSection: Category[] = [TWOS];

const sectionsSpread = [
    ...upperSection,
    ...lowerSection,
]; // is of type string[]
</code>```

答:
This is widening vs. non-widening. An explicit annotation means TypeScript doesn't change its meaning when assigning to other values.

Widening:

```<code>const ACES = 'ACES';
type Category = typeof ACES;

const upperSection: Category[] = [];

const sectionsSpread = [
    ...upperSection,
]; // string[]
</code>```

Non widening:

```<code>const ACES = 'ACES';
type Category = 'ACES';

const upperSection: Category[] = [];

const sectionsSpread = [
    ...upperSection,
]; // Category
</code>```

Body:
When I create a new array by using the array spread operator TypeScript seems to lose the correct type information.

This does not happen if I create the new array with Array.combine().

I've prepared a simple example to demonstrate this. I use declaration merging to have the constants (ACES, TWOS, etc.) have their corresponding type. Then I create the type Category to be a "supertype".

The variable sectionsSpread is of type string[] after creating it with the array spread operator. The variable sectionsCombined is of type Category[].

I expected the variable sectionsSpread to be also of type Category[].

Is this a bug? Have I got array spreading wrong?

const ACES = 'ACES';
type ACES = typeof ACES;

const TWOS = 'TWOS';
type TWOS = typeof TWOS;

const THREES = 'THREES';
type THREES = typeof THREES;

const FULL_HOUSE = 'FULL_HOUSE';
type FULL_HOUSE = typeof FULL_HOUSE;

const SMALL_STRAIGHT = 'SMALL_STRAIGHT';
type SMALL_STRAIGHT = typeof SMALL_STRAIGHT;

const LARGE_STRAIGHT = 'LARGE_STRAIGHT';
type LARGE_STRAIGHT = typeof LARGE_STRAIGHT;

type Category = ACES | TWOS | THREES |
    FULL_HOUSE | SMALL_STRAIGHT | LARGE_STRAIGHT;

const upperSection: Array<Category> = [ACES, TWOS, THREES];
const lowerSection: Array<Category> = [FULL_HOUSE, SMALL_STRAIGHT, LARGE_STRAIGHT];

const sectionsSpread = [
    ...upperSection,
    ...lowerSection
];

const sectionsCombined = upperSection.concat(lowerSection);

UDATE

@dbandstra and @basarat pointed me in the right direction. After reading the suggested blog post I think I understand Literal Type Widening. But this still doesn't explain the behaviour of the typeof operator in this context for me.

I hope the following examples make my problem more clear:

const ACES = 'ACES';
type ACES = 'ACES'; // non-widening literal type

const TWOS = 'TWOS';
type TWOS = 'TWOS'; // non-widening literal type

type Category = ACES | TWOS; // are these values or types?

const upperSection: Category[] = [ACES];
const lowerSection: Category[] = [TWOS];

const sectionsSpread = [
    ...upperSection,
    ...lowerSection,
]; // is of type Category[]

If I use typeof the variable sectionsSpread ends up being of type string[] instead:

const ACES = 'ACES';
type ACES = typeof ACES; // what does typeof do here?

const TWOS = 'TWOS';
type TWOS = typeof TWOS; // what does typeof do here?

type Category = ACES | TWOS; // are these values or types?

const upperSection: Category[] = [ACES];
const lowerSection: Category[] = [TWOS];

const sectionsSpread = [
    ...upperSection,
    ...lowerSection,
]; // is of type string[]

Body:
This is widening vs. non-widening. An explicit annotation means TypeScript doesn't change its meaning when assigning to other values.

Widening:

const ACES = 'ACES';
type Category = typeof ACES;

const upperSection: Category[] = [];

const sectionsSpread = [
    ...upperSection,
]; // string[]

Non widening:

const ACES = 'ACES';
type Category = 'ACES';

const upperSection: Category[] = [];

const sectionsSpread = [
    ...upperSection,
]; // Category