问:
non-english address letters causes geocode() to return NA
I am using this recipe from r-bloggers.com to plot a basic map.

geocode() returns "NA" for several of the adresses that I am trying to plot. All adresses returning "NA" have the common attribute that they contain Danish letters "æ,Æ, ø,Ø, å,Å", so I strongly suspect that this is what is causing me problems.

Error message returned for address "Eskærvej 50, 5700 Svendborg, denmark"

```<code>cannot open URL 'http://maps.googleapis.com/maps/api/geocode/json?
address=Esk%E6rvej%2050,%205700%20Svendborg,%20denmark&sensor=false': HTTP
status was '400 Bad Request'
2: In FUN(X[[i]], ...) :
    geocoding failed for "Eskærvej 50, 5700 Svendborg, denmark".
  if accompanied by 500 Internal Server Error with using dsk, try google.
</code>```

Do you know of any way to work around this?

An example from my code:

```<code>    # CREATE DATA FRAME
df.svendborg_locations <- tibble(location = c("Belvedere 60, 5700 Svendborg, denmark"
                                          ,"Fruerstuevej 17 B, 5700 Svendborg, denmark"
                                          ,"Enghavevej 40, 5700 Svendborg, denmark"
                                          ,"Engdraget 2, 5700 Svendborg, denmark"
                                          ,"Belvedere 54, 5700 Svendborg, denmark"
                                          ,"Eskærvej 50, 5700 Svendborg, denmark"
                                          ,"Lundbyvej 43, 5700 Svendborg, denmark"
                                          ,"Eskærvej 63 B, 5700 Svendborg, denmark"
                                          ,"Skovbrynet 1, 5700 Svendborg, denmark"
                                          ,"Wiggers Park 201, 5700 Svendborg, denmark"
                                          ,"Hellet 3, 5700 Svendborg, denmark"
                                          ,"Gambøtvej 2, 5700 Svendborg, denmark"
                                          ,"Oluf Rings Vej 19, 5881 Skårup Fyn, denmark"
                                          ,"Rantzausmindevej 172 C, 5700 Svendborg"))
# GEOCODE
geo.svendborg_locations <- geocode(df.svendborg_locations$location)

# COMBINE DATA
df.svendborg_locations <- cbind(df.svendborg_locations, geo.svendborg_locations)
</code>```

session info

```<code>sessionInfo()
R version 3.4.1 (2017-06-30)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

Matrix products: default

locale:
[1] LC_COLLATE=Danish_Denmark.1252  LC_CTYPE=Danish_Denmark.1252    LC_MONETARY=Danish_Denmark.1252 LC_NUMERIC=C
[5] LC_TIME=Danish_Denmark.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] ggmap_2.6.1          gganimate_0.1.0.9000 gridExtra_2.3        dplyr_0.7.3          purrr_0.2.3          readr_1.1.1
 [7] tidyr_0.7.1          tibble_1.3.4         ggplot2_2.2.1        tidyverse_1.1.1

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.13      lubridate_1.6.0   lattice_0.20-35   png_0.1-7         assertthat_0.2.0  digest_0.6.12     psych_1.7.8       mime_0.5
 [9] R6_2.2.2          cellranger_1.1.0  plyr_1.8.4        httr_1.3.1        RgoogleMaps_1.4.1 rlang_0.1.2       lazyeval_0.2.0    readxl_1.0.0
[17] geosphere_1.5-7   miniUI_0.1.1      proto_1.0.0       labeling_0.3      stringr_1.2.0     foreign_0.8-69    munsell_0.4.3     shiny_1.0.5
[25] broom_0.4.2       compiler_3.4.1    httpuv_1.3.5      modelr_0.1.1      pkgconfig_2.0.1   mnormt_1.5-5      htmltools_0.3.6   grid_3.4.1
[33] nlme_3.1-131      jsonlite_1.5      xtable_1.8-2      gtable_0.2.0      magrittr_1.5      scales_0.5.0      stringi_1.1.5     mapproj_1.2-5
[41] reshape2_1.4.2    bindrcpp_0.2      sp_1.2-5          xml2_1.1.1        rjson_0.2.15      tools_3.4.1       forcats_0.2.0     glue_1.1.1
[49] maps_3.2.0        hms_0.3           jpeg_0.1-8        parallel_3.4.1    yaml_2.1.14       colorspace_1.3-2  rvest_0.3.2       ggExtra_0.7
[57] knitr_1.17        bindr_0.1         haven_1.1.0
</code>```

答:
Use enc2utf8

```<code>geo.svendborg_locations <- geocode(enc2utf8(df.svendborg_locations$location))
</code>```

That worked for me, although I got rate limited mid testing...

With OP's code, I got 5 rows with NAs, accompanied by 500 error codes.

With enc2utf8, I got 2 rows with NAs, both with error geocode failed with status OVER_QUERY_LIMIT, location = "Lundbyvej 43, 5700 Svendborg, denmark"

Body:
I am using this recipe from r-bloggers.com to plot a basic map.

geocode() returns "NA" for several of the adresses that I am trying to plot. All adresses returning "NA" have the common attribute that they contain Danish letters "æ,Æ, ø,Ø, å,Å", so I strongly suspect that this is what is causing me problems.

Error message returned for address "Eskærvej 50, 5700 Svendborg, denmark"

cannot open URL 'http://maps.googleapis.com/maps/api/geocode/json?
address=Esk%E6rvej%2050,%205700%20Svendborg,%20denmark&sensor=false': HTTP
status was '400 Bad Request'
2: In FUN(X[[i]], ...) :
    geocoding failed for "Eskærvej 50, 5700 Svendborg, denmark".
  if accompanied by 500 Internal Server Error with using dsk, try google.

Do you know of any way to work around this?

An example from my code:

    # CREATE DATA FRAME
df.svendborg_locations <- tibble(location = c("Belvedere 60, 5700 Svendborg, denmark"
                                          ,"Fruerstuevej 17 B, 5700 Svendborg, denmark"
                                          ,"Enghavevej 40, 5700 Svendborg, denmark"
                                          ,"Engdraget 2, 5700 Svendborg, denmark"
                                          ,"Belvedere 54, 5700 Svendborg, denmark"
                                          ,"Eskærvej 50, 5700 Svendborg, denmark"
                                          ,"Lundbyvej 43, 5700 Svendborg, denmark"
                                          ,"Eskærvej 63 B, 5700 Svendborg, denmark"
                                          ,"Skovbrynet 1, 5700 Svendborg, denmark"
                                          ,"Wiggers Park 201, 5700 Svendborg, denmark"
                                          ,"Hellet 3, 5700 Svendborg, denmark"
                                          ,"Gambøtvej 2, 5700 Svendborg, denmark"
                                          ,"Oluf Rings Vej 19, 5881 Skårup Fyn, denmark"
                                          ,"Rantzausmindevej 172 C, 5700 Svendborg"))
# GEOCODE
geo.svendborg_locations <- geocode(df.svendborg_locations$location)

# COMBINE DATA
df.svendborg_locations <- cbind(df.svendborg_locations, geo.svendborg_locations)

session info

sessionInfo()
R version 3.4.1 (2017-06-30)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

Matrix products: default

locale:
[1] LC_COLLATE=Danish_Denmark.1252  LC_CTYPE=Danish_Denmark.1252    LC_MONETARY=Danish_Denmark.1252 LC_NUMERIC=C
[5] LC_TIME=Danish_Denmark.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] ggmap_2.6.1          gganimate_0.1.0.9000 gridExtra_2.3        dplyr_0.7.3          purrr_0.2.3          readr_1.1.1
 [7] tidyr_0.7.1          tibble_1.3.4         ggplot2_2.2.1        tidyverse_1.1.1

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.13      lubridate_1.6.0   lattice_0.20-35   png_0.1-7         assertthat_0.2.0  digest_0.6.12     psych_1.7.8       mime_0.5
 [9] R6_2.2.2          cellranger_1.1.0  plyr_1.8.4        httr_1.3.1        RgoogleMaps_1.4.1 rlang_0.1.2       lazyeval_0.2.0    readxl_1.0.0
[17] geosphere_1.5-7   miniUI_0.1.1      proto_1.0.0       labeling_0.3      stringr_1.2.0     foreign_0.8-69    munsell_0.4.3     shiny_1.0.5
[25] broom_0.4.2       compiler_3.4.1    httpuv_1.3.5      modelr_0.1.1      pkgconfig_2.0.1   mnormt_1.5-5      htmltools_0.3.6   grid_3.4.1
[33] nlme_3.1-131      jsonlite_1.5      xtable_1.8-2      gtable_0.2.0      magrittr_1.5      scales_0.5.0      stringi_1.1.5     mapproj_1.2-5
[41] reshape2_1.4.2    bindrcpp_0.2      sp_1.2-5          xml2_1.1.1        rjson_0.2.15      tools_3.4.1       forcats_0.2.0     glue_1.1.1
[49] maps_3.2.0        hms_0.3           jpeg_0.1-8        parallel_3.4.1    yaml_2.1.14       colorspace_1.3-2  rvest_0.3.2       ggExtra_0.7
[57] knitr_1.17        bindr_0.1         haven_1.1.0

Body:
Use enc2utf8

geo.svendborg_locations <- geocode(enc2utf8(df.svendborg_locations$location))

That worked for me, although I got rate limited mid testing...

With OP's code, I got 5 rows with NAs, accompanied by 500 error codes.

With enc2utf8, I got 2 rows with NAs, both with error geocode failed with status OVER_QUERY_LIMIT, location = "Lundbyvej 43, 5700 Svendborg, denmark"


来源: stackexchange

问:
Multiple Set handlers in a property
I remember coming across some way to declare multiple Set handlers in a property but now I can't figure out how it's done.  It's useful in that one can assign different data types and the Set handler does the conversion, but I get the error

'Set' is already declared

thoughts anyone?

答:
It's not possible

It would be nice to be able to write both

```<code>sQuantity = "1234"
</code>```

and

```<code>sQuantity = 1234
</code>```

with two setter functions, but trying to write even one setter function with the wrong parameter type seems doomed to failure:-

```<code>error BC31064: 'Set' parameter must have the same type as the containing property.
</code>```

If Visual Basic doesn't allow conversion between setter parameter type and property type then there is no way it would be possible to have two setter functions. If setter functions are forced to have the same type as the property, then it could not know which to run if there were more than one!

So I'd argue 'not only does it not seem possible, but it is actually not possible!'

There is a workaround

What you can do however, is have two properties of different types changing the same underlying variable, so that you can write

```<code>sQuantityFromString = "1234"
</code>```

and

```<code>sQuantityFromInt = 1234
</code>```

using

```<code>Public Shared WriteOnly Property sQuantityFromInt () As Integer
</code>```

with a setter function that takes an integer as a parameter and with both properties setter functions modifying the same underlying string member variable.

```<code>Private Shared m_sQuantity As String = Nothing
</code>```

ContentLicense: CC BY-SA 3.0

Title: Multiple Set handlers in a property

Body:
It's not possible

It would be nice to be able to write both

sQuantity = "1234"

and

sQuantity = 1234

with two setter functions, but trying to write even one setter function with the wrong parameter type seems doomed to failure:-

error BC31064: 'Set' parameter must have the same type as the containing property.

If Visual Basic doesn't allow conversion between setter parameter type and property type then there is no way it would be possible to have two setter functions. If setter functions are forced to have the same type as the property, then it could not know which to run if there were more than one!

So I'd argue 'not only does it not seem possible, but it is actually not possible!'

There is a workaround

What you can do however, is have two properties of different types changing the same underlying variable, so that you can write

sQuantityFromString = "1234"

and

sQuantityFromInt = 1234

using

Public Shared WriteOnly Property sQuantityFromInt () As Integer

with a setter function that takes an integer as a parameter and with both properties setter functions modifying the same underlying string member variable.

Private Shared m_sQuantity As String = Nothing


问:
When running MapFragment in Android appears error: E/GoogleCertificates: Failed to load com.google.android.gms.googlecertificates
I added a mapFragment to my application. The activity runs ok but in the console I have the following error:

```<code>11-15 10:58:24.552
6030-6093/gchmapplications.hermandadsantamariavictoria
E/GoogleCertificates: Failed to load
com.google.android.gms.googlecertificates
pt: No acceptable module found. Local version is 0 and remote version
is 0.
at com.google.android.gms.dynamite.DynamiteModule.a(:com.google.android.gms.DynamiteModulesB@11743470:11)
at hx.a(:com.google.android.gms.DynamiteModulesB@11743470:12)
at hx.a(:com.google.android.gms.DynamiteModulesB@11743470:31)
at hx.b(:com.google.android.gms.DynamiteModulesB@11743470:30)
at ii.a(:com.google.android.gms.DynamiteModulesB@11743470:35)
at ii.a(:com.google.android.gms.DynamiteModulesB@11743470:20)
at com.google.maps.api.android.lib6.impl.ew.a(:com.google.android.gms.DynamiteModulesB@11743470:141)
at com.google.maps.api.android.lib6.impl.fc.run(:com.google.android.gms.DynamiteModulesB@11743470:27)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
</code>```

I've found some things about the versions in gradle. I have to putted all of them in 11.0.4 because of Firebase. If not, there can be possible errors (at least is the error that appears).

Here is my Gradle:

```<code>compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'com.android.support:support-v4:25.3.1'
compile 'com.android.support:cardview-v7:25.3.1'

compile 'com.google.firebase:firebase-core:11.0.4'
compile 'com.google.firebase:firebase-messaging:11.0.4'
compile 'com.google.android.gms:play-services-maps:11.0.4'
compile 'com.google.android.gms:play-services-location:11.0.4'
</code>```

I also have my credentials added in the Manifest.

Thanks in advance!

答:
You forgot to add include the google services.Google services is required to run the maps and other features.Add google services in the top level gradle</p>

```<code>dependencies {
    classpath 'com.google.gms:google-services:3.0.0'
}
</code>```

Body:
I added a mapFragment to my application. The activity runs ok but in the console I have the following error:

11-15 10:58:24.552
6030-6093/gchmapplications.hermandadsantamariavictoria
E/GoogleCertificates: Failed to load
com.google.android.gms.googlecertificates
pt: No acceptable module found. Local version is 0 and remote version
is 0.
at com.google.android.gms.dynamite.DynamiteModule.a(:com.google.android.gms.DynamiteModulesB@11743470:11)
at hx.a(:com.google.android.gms.DynamiteModulesB@11743470:12)
at hx.a(:com.google.android.gms.DynamiteModulesB@11743470:31)
at hx.b(:com.google.android.gms.DynamiteModulesB@11743470:30)
at ii.a(:com.google.android.gms.DynamiteModulesB@11743470:35)
at ii.a(:com.google.android.gms.DynamiteModulesB@11743470:20)
at com.google.maps.api.android.lib6.impl.ew.a(:com.google.android.gms.DynamiteModulesB@11743470:141)
at com.google.maps.api.android.lib6.impl.fc.run(:com.google.android.gms.DynamiteModulesB@11743470:27)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)

I've found some things about the versions in gradle. I have to putted all of them in 11.0.4 because of Firebase. If not, there can be possible errors (at least is the error that appears).

Here is my Gradle:

compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'com.android.support:support-v4:25.3.1'
compile 'com.android.support:cardview-v7:25.3.1'

compile 'com.google.firebase:firebase-core:11.0.4'
compile 'com.google.firebase:firebase-messaging:11.0.4'
compile 'com.google.android.gms:play-services-maps:11.0.4'
compile 'com.google.android.gms:play-services-location:11.0.4'

I also have my credentials added in the Manifest.

Thanks in advance!

Body:
You forgot to add include the google services.Google services is required to run the maps and other features.Add google services in the top level gradle

dependencies {
    classpath 'com.google.gms:google-services:3.0.0'
}


问:
Does SSL protect documents sent over it?
If I understand correctly, SSL will protect (encrypt) HTTP transfer sent over it. But does this apply only to HTTP commands and responses?

If I GET a plain text file and someone intercepts my transaction, do they see plain text or encrypted text?

答: SSL encryption encrypts all data transferred as part of a session. This includes HTTP commands, responses and all the payload data.

ContentLicense: CC BY-SA 2.5


问:
Multiple primary key constraints?
I have a table like this:

```<code>CREATE TABLE BACAEN
(
CAEN_KEY INT PRIMARY NOT NULL,
CAET_KEY INT,
BUUN_KEY INT
)
</code>```

I've already defined primary key on CAEN_KEY column. What I also need is to have unique records for CAET_KEY and BUUN_KEY together. (So, combination with same CAET_KEY / BUUN_KEY is allowed only once). The easiest way would be to generate one more composite primary key, but this is not possible because sql server doesn't allow multiple primary key constraints. What are alternatives to this?

Please note: I can not drop primary key constraint on CAEN_KEY.

答:
create unique index on your table </p>

```<code>CREATE UNIQUE INDEX indexname  ON BACAEN (CAET_KEY,BUUN_KEY);
</code>```

Title: Multiple primary key constraints?

Body:
I have a table like this:

CREATE TABLE BACAEN
(
CAEN_KEY INT PRIMARY NOT NULL,
CAET_KEY INT,
BUUN_KEY INT
)

I've already defined primary key on CAEN_KEY column. What I also need is to have unique records for CAET_KEY and BUUN_KEY together. (So, combination with same CAET_KEY / BUUN_KEY is allowed only once). The easiest way would be to generate one more composite primary key, but this is not possible because sql server doesn't allow multiple primary key constraints. What are alternatives to this?

Please note: I can not drop primary key constraint on CAEN_KEY.

Body:
create unique index on your table

CREATE UNIQUE INDEX indexname  ON BACAEN (CAET_KEY,BUUN_KEY);


问:
java xml, create self closing tag
I'm using the Xerces xml library in java.

I'm able to create an element like:

Element myElement = doc.createElement("element");

which would result in <element></element>.

How would I create an element that would result in a self closing tag like so?

<element/>

Thanks.

答:
For example you if you need to create an XML like

```<code> xml

<?xml version="1.0" encoding="UTF-8"?>
<RootElement>
   <element />
</RootElement>
</code>```

we can have our snippet of java code like the below.

```<code>import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class XmlTransformer{

    public static void main(String args[]) {
        String xml = "";
        try {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("RootElement");
            doc.appendChild(rootElement);

            Element myElement = doc.createElement("element");
            rootElement.appendChild(myElement);
            TransformerFactory transformerFactory = TransformerFactory
                    .newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);

            transformer.transform(source, result);
            xml = writer.toString();
            System.out.println(" xml \n \n " +xml);
        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (TransformerException tfe) {
            tfe.printStackTrace();
        }
    }

}
</code>```

Title: java xml, create self closing tag

Body:
For example you if you need to create an XML like

 xml

<?xml version="1.0" encoding="UTF-8"?>
<RootElement>
   <element />
</RootElement>

we can have our snippet of java code like the below.

import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class XmlTransformer{

    public static void main(String args[]) {
        String xml = "";
        try {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("RootElement");
            doc.appendChild(rootElement);

            Element myElement = doc.createElement("element");
            rootElement.appendChild(myElement);
            TransformerFactory transformerFactory = TransformerFactory
                    .newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);

            transformer.transform(source, result);
            xml = writer.toString();
            System.out.println(" xml \n \n " +xml);
        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (TransformerException tfe) {
            tfe.printStackTrace();
        }
    }

}


问:
applying Gregorian Calendar in JAVA
```<code>import  java.util.GregorianCalendar ;
public class MyCalendar extends  GregorianCalendar  {
public static void main(String[] args) {
           MyCalendar a = new MyCalendar();
           System.out.println(a.getCurrenttime());
}

public String getCurrenttime(){
     String time= YEAR+"-"+(MONTH+1)+"-"+DATE+"-"+HOUR+"-"+MINUTE+"-"+SECOND;
     return time;}}
</code>```

However, it always show the same time. What have I done wrong.

P.S. it is intended not to use command like gettime() directely. The string should remain there.

答:
Your title says “applying GregorianCalendar”, and that’s not what I am doing in this answer. While mustabelMo’s answer is correct, I wanted to show you how IMHO your task is best solved, and the first point is I recommend you don’t use the long outdated GregorianCalendar class. Today we have so much better in the modern Java date and time API known as java.time or JSR-310. For your need, you may use a LocalDateTime:

```<code>import java.time.ZoneId;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class MyCalendar {

    public static void main(String[] args) {
        MyCalendar a = new MyCalendar();
        System.out.println(a.getCurrentTime());
    }

    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("u-M-d-H-m-s");
    private LocalDateTime now = LocalDateTime.now(ZoneId.systemDefault());

    private String getCurrentTime() {
        return now.format(formatter);
    }

}
</code>```

The program prints something like

```<code>2017-11-15-11-59-1
</code>```

Other points to note:

Prefer composition over inheritance. Rather than inheriting from whatever class you use for getting calendar data, it’s better style to encapsulate an object of that class inside your class.

Use a formatter for formatting your date-time into a string, it’s more convenient and easier to change if you want a different format. For example, many will prefer to have the minutes and seconds printed in two digits always, with a leading zero as necessary. To obtain this, just use two format pattern letters instead of one:

```<code>    private static final DateTimeFormatter formatter
            = DateTimeFormatter.ofPattern("u-M-d-H-mm-ss");
</code>```

Now the output goes like

```<code>2017-11-15-12-03-01
</code>```

In the code I use ZoneId.systemDefault() to pick up the JVM’s time zone setting. This is fragile, it may be changed behind your back without notice. If you can, prefer a specific time zone in the region/city format, for example:

```<code>private LocalDateTime now = LocalDateTime.now(ZoneId.of("Asia/Hong_Kong"));
</code>```

Despite the name getCurrentTime() gives you the time the MyCalendar object was created, not the time the method was called. If you prefer the latter, just create a new LocalDateTime object within the method.

You may prefer to use ZonedDateTime or OffsetDateTime instead of LocalDateTime since these include a time zone and an offset from UTC, respectively. It’s often considered bad practice to throw this information away even when you don’t see any immediate use for it.

Title: applying Gregorian Calendar in JAVA

Body:
import  java.util.GregorianCalendar ;
public class MyCalendar extends  GregorianCalendar  {
public static void main(String[] args) {
           MyCalendar a = new MyCalendar();
           System.out.println(a.getCurrenttime());
}

public String getCurrenttime(){
     String time= YEAR+"-"+(MONTH+1)+"-"+DATE+"-"+HOUR+"-"+MINUTE+"-"+SECOND;
     return time;}}

However, it always show the same time. What have I done wrong.

P.S. it is intended not to use command like gettime() directely. The string should remain there.

Body:
Your title says “applying GregorianCalendar”, and that’s not what I am doing in this answer. While mustabelMo’s answer is correct, I wanted to show you how IMHO your task is best solved, and the first point is I recommend you don’t use the long outdated GregorianCalendar class. Today we have so much better in the modern Java date and time API known as java.time or JSR-310. For your need, you may use a LocalDateTime:

import java.time.ZoneId;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class MyCalendar {

    public static void main(String[] args) {
        MyCalendar a = new MyCalendar();
        System.out.println(a.getCurrentTime());
    }

    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("u-M-d-H-m-s");
    private LocalDateTime now = LocalDateTime.now(ZoneId.systemDefault());

    private String getCurrentTime() {
        return now.format(formatter);
    }

}

The program prints something like

2017-11-15-11-59-1

Other points to note:

Prefer composition over inheritance. Rather than inheriting from whatever class you use for getting calendar data, it’s better style to encapsulate an object of that class inside your class.

Use a formatter for formatting your date-time into a string, it’s more convenient and easier to change if you want a different format. For example, many will prefer to have the minutes and seconds printed in two digits always, with a leading zero as necessary. To obtain this, just use two format pattern letters instead of one:

    private static final DateTimeFormatter formatter
            = DateTimeFormatter.ofPattern("u-M-d-H-mm-ss");

Now the output goes like

2017-11-15-12-03-01

In the code I use ZoneId.systemDefault() to pick up the JVM’s time zone setting. This is fragile, it may be changed behind your back without notice. If you can, prefer a specific time zone in the region/city format, for example:

private LocalDateTime now = LocalDateTime.now(ZoneId.of("Asia/Hong_Kong"));

Despite the name getCurrentTime() gives you the time the MyCalendar object was created, not the time the method was called. If you prefer the latter, just create a new LocalDateTime object within the method.

You may prefer to use ZonedDateTime or OffsetDateTime instead of LocalDateTime since these include a time zone and an offset from UTC, respectively. It’s often considered bad practice to throw this information away even when you don’t see any immediate use for it.


问:
Vertex JS and Redis Sentinel Support
Does Vertx 3.5.0 supports Redis Sentinel or not? Any other ways to achieve it?

I have a Master and Slave Architecture in Redis, where I have failover implementation concepts. I can achieve this using NodeJS and Java, but while switching on to vertx-js I am unable to get the sentinel Connections.

Is there any updates regarding Sentinel Support for Vertx?

答:
As of 3.5.0 there is a Redis Sentinel implementation. This was contributed by the community and hasn't been extensively tested so it is not referenced in the docs. If you have experience with it you could help verify it and we can then add proper references to the docs.

<s>Also note that this support is currently not polyglot (so you're stuck with Java at the moment).</s>

There is Support for polyglot sentinel in the master branch. If you're brave enough, please test it! :)

Title: Vertex JS and Redis Sentinel Support


问:
Simulating Physical Keypress
So I have a keyboard, and it has a mode where it lights up every key you press.
I was wondering if you could physically simulate a keypress, AHK just sends it directly to the system.
However I need a way to make the keyboard light up, because AHK doesn't do that. The keyboard is not programmable.

Solutions in mostly any language are welcome.

答: This is not possible, you want to send a simulate keypress to your fysical keyboard. (this is i think a mechanical switch insite the keyboard self, that does do light up if you press a key) and it is only possible if the company did make a keyboard driver that allows you to change the settings (disable - light up) in the Windows Registry. (you did not give me the name of your keyboard but you can then try to searching into the registry for example software/Logitech/settings)  </p>

Title: Simulating Physical Keypress


问:
Twitter box is not auto filling with quote
I was working on a project 'quote generator'. Everything works fine except the Twitter button. It's opening a new window with a new tweet box but it is not filling the box with the desired quote in it. I'm a bit confused here. I tried everything. So a little help would be much appreciated. Thank you.

Here's my project: https://codepen.io/buzz_lightyear/pen/BmdzaZ

var quotes = ["The Way Get Started Is To Quit Talking And Begin Doing.", "The Pessimist Sees Difficulty In Every Opportunity. The Optimist Sees Opportunity In Every Difficulty.", "Don't Let Yesterday Take Up Too Much Of Today.", "You Learn More From Failure Than From Success. Don't Let It Stop You. Failure Builds Character.", "It's Not Whether You Get Knocked Down, It's Whether You Get Up.", "If You Are Working On Something That You Really Care About, You Don't Have To Be Pushed. The Vision Pulls You.", "People Who Are Crazy Enough To Think They Can Change The World, Are The Ones Who Do", "Failure Will Never Overtake Me If My Determination To Succeed Is Strong Enough.", "Entrepreneurs Are Great At Dealing With Uncertainty And Also Very Good At Minimizing Risk. That's The Classic Entrepreneur", "We May Encounter Many Defeats But We Must Not Be Defeated", "Knowing Is Not Enough; We Must Apply. Wishing Is Not Enough; We Must Do", "Imagine Your Life Is Perfect In Every Respect; What Would It Look Like?"];

function makeId() {
  var randomNumber = Math.floor(Math.random() * quotes.length);
  $("#quote > h1").html(quotes[randomNumber]);
}

$(document).ready(function() {
  $("#press > button").click(function() {
    $("#quote > i").fadeOut("slow").fadeIn("slow");
    $("#quote > h1").fadeOut("slow", function() {
      makeId();
      $(this).fadeIn("slow");
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Encode+Sans+Expanded" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link href="style.css" rel="stylesheet">

<div id="header">
  <h1>My Quote Machine</h1>
</div>

<div id="quote">
  <i class="fa fa-quote-left" aria-hidden="true" style="font-size: 15px; bottom: 10px;"></i>
  <h1>I shall not waste my days in trying to prolong them.</h1>
</div>
<div id="press">
  <div id="icon">
    <i class="fa fa-twitter fa-2x" id="twitterid" style="color: white"></i>
  </div>
  <button class="btn btn-lg">Quote</button>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="javascript.js" type="text/javascript"></script></code>```

答:
The twitter URL you are using needs text added to the end of it

```<code>https://twitter.com/intent/tweet/?text=ADD_YOUR_QUOTE_HERE
</code>```

So you just need to append some text using javascript into the URL when the user clicks on the bird icon.

Body:
I was working on a project 'quote generator'. Everything works fine except the Twitter button. It's opening a new window with a new tweet box but it is not filling the box with the desired quote in it. I'm a bit confused here. I tried everything. So a little help would be much appreciated. Thank you.

Here's my project: https://codepen.io/buzz_lightyear/pen/BmdzaZ

var quotes = ["The Way Get Started Is To Quit Talking And Begin Doing.", "The Pessimist Sees Difficulty In Every Opportunity. The Optimist Sees Opportunity In Every Difficulty.", "Don't Let Yesterday Take Up Too Much Of Today.", "You Learn More From Failure Than From Success. Don't Let It Stop You. Failure Builds Character.", "It's Not Whether You Get Knocked Down, It's Whether You Get Up.", "If You Are Working On Something That You Really Care About, You Don't Have To Be Pushed. The Vision Pulls You.", "People Who Are Crazy Enough To Think They Can Change The World, Are The Ones Who Do", "Failure Will Never Overtake Me If My Determination To Succeed Is Strong Enough.", "Entrepreneurs Are Great At Dealing With Uncertainty And Also Very Good At Minimizing Risk. That's The Classic Entrepreneur", "We May Encounter Many Defeats But We Must Not Be Defeated", "Knowing Is Not Enough; We Must Apply. Wishing Is Not Enough; We Must Do", "Imagine Your Life Is Perfect In Every Respect; What Would It Look Like?"];

function makeId() {
  var randomNumber = Math.floor(Math.random() * quotes.length);
  $("#quote > h1").html(quotes[randomNumber]);
}

$(document).ready(function() {
  $("#press > button").click(function() {
    $("#quote > i").fadeOut("slow").fadeIn("slow");
    $("#quote > h1").fadeOut("slow", function() {
      makeId();
      $(this).fadeIn("slow");
    });
  });
});

<link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Encode+Sans+Expanded" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link href="style.css" rel="stylesheet">

My Quote Machine

I shall not waste my days in trying to prolong them.

  <button class="btn btn-lg">Quote</button>

Body:
The twitter URL you are using needs text added to the end of it

https://twitter.com/intent/tweet/?text=ADD_YOUR_QUOTE_HERE

So you just need to append some text using javascript into the URL when the user clicks on the bird icon.


问:
extracting particular number from a line consisting of several numbers using python
As i consists of line having several numbers ,but i need to extract only first 6 digit number

```<code>import re
out=['DOT/R9.4x                 4616542  rtpbuild   x. : 20171111184750 p4 p4burtd review','DOT/dex                 4609974  build      ~. : 20171108044757 p4 p4burtd review']
for item in out:
    line=re.findall(r'\d{7}',item)
    print(line)
</code>```

i'm getting output as:

```<code>['4616542','2017111','1184750']
['4609974','2017110','8044757']
</code>```

but actually i need output of only 1st 7digit number:

```<code>[4616542]
[4609974]
</code>```

i dont need those remaining number which has been divided

答:
findall() finds all the matches and returns them as a list of
    strings, with each string representing one match.

findall() returns a list(and lists are iterables) and returns str
  objects. let's check :

```<code>import re
    out=['DOT/R9.4x                 4616542  rtpbuild   x. : 20171111184750 p4 p4burtd review','DOT/dex                 4609974  build      ~. : 20171108044757 p4 p4burtd review']
    for item in out:
        line=re.findall(r'\d{7}',item)
        for i in line:
            print(i)
</code>```

output:

```<code>4616542
2017111
1184750
4609974
2017110
8044757
</code>```

so instead of findall use re.search for first matches :

One line solution:

```<code>print([re.search(r'\d{7}',item).group() for item in out])
</code>```

output:

```<code>['4616542', '4609974']
</code>```

Body:
As i consists of line having several numbers ,but i need to extract only first 6 digit number

import re
out=['DOT/R9.4x                 4616542  rtpbuild   x. : 20171111184750 p4 p4burtd review','DOT/dex                 4609974  build      ~. : 20171108044757 p4 p4burtd review']
for item in out:
    line=re.findall(r'\d{7}',item)
    print(line)

i'm getting output as:

['4616542','2017111','1184750']
['4609974','2017110','8044757']

but actually i need output of only 1st 7digit number:

[4616542]
[4609974]

i dont need those remaining number which has been divided

Body:
findall() finds all the matches and returns them as a list of
    strings, with each string representing one match.

findall() returns a list(and lists are iterables) and returns str
  objects. let's check :

import re
    out=['DOT/R9.4x                 4616542  rtpbuild   x. : 20171111184750 p4 p4burtd review','DOT/dex                 4609974  build      ~. : 20171108044757 p4 p4burtd review']
    for item in out:
        line=re.findall(r'\d{7}',item)
        for i in line:
            print(i)

output:

4616542
2017111
1184750
4609974
2017110
8044757

so instead of findall use re.search for first matches :

One line solution:

print([re.search(r'\d{7}',item).group() for item in out])

output:

['4616542', '4609974']


问:
Dividing all values by the last entry of their row in R studio
I am working in R studio and I have a dataset such as:
(the letters stand for the column names)

```<code> a b c d e f
 0 1 3 1 0 1
 3 1 0 4 1 2
 0 1 0 0 3 4
</code>```

I want to divide all values by the f-value corresponding to their column. So that would mean every value in the first row has to be divided by 1, every value in the second row by two and every value in the third row by 4.

i ve tried it like this:

```<code>#divide every number through sum variable of their row
my_matched_matrix = as.matrix(my_matched)

#making a vector out of sum row
avector <- as.vector(my_matched['sum'])

#sweep
sweeped <- sweep(mat,avector, `/`)
</code>```

it gives me this error:

```<code>Error in dims[MARGIN] : invalid subscript type 'list'
</code>```

Does anyone have an idea if there is any other way of getting where i want?

Body:
I am working in R studio and I have a dataset such as:
(the letters stand for the column names)

 a b c d e f
 0 1 3 1 0 1
 3 1 0 4 1 2
 0 1 0 0 3 4

I want to divide all values by the f-value corresponding to their column. So that would mean every value in the first row has to be divided by 1, every value in the second row by two and every value in the third row by 4.

i ve tried it like this:

#divide every number through sum variable of their row
my_matched_matrix = as.matrix(my_matched)

#making a vector out of sum row
avector <- as.vector(my_matched['sum'])

#sweep
sweeped <- sweep(mat,avector, `/`)

it gives me this error:

Error in dims[MARGIN] : invalid subscript type 'list'

Does anyone have an idea if there is any other way of getting where i want?

Body:
Is this what you're looking for?

df <- read.table(text = "a b c d e f
                         0 1 3 1 0 1
                         3 1 0 4 1 2
                         0 1 0 0 3 4",
                 header = TRUE, stringsAsFactors = FALSE

df / df$f

Which returns:

    a    b c d    e f
1 0.0 1.00 3 1 0.00 1
2 1.5 0.50 0 2 0.50 1
3 0.0 0.25 0 0 0.75 1

If you want this to print a little nicer you could do this:

x <- df / df$f

format(x, nsmall = 2)

     a    b    c    d    e    f
1 0.00 1.00 3.00 1.00 0.00 1.00
2 1.50 0.50 0.00 2.00 0.50 1.00
3 0.00 0.25 0.00 0.00 0.75 1.00


问:
append versionnumber to asp:ScriptManager's compositescript tag
we are trying to get the following scenario working:

we use asp:scriptmanager / CompositeScripts to combine our scripts into a few script blocks but after each deploy to the test system we have trouble with testers not getting updated versions of css and javascript (browser cache). For the CSS we have defined our own css user control which appends a Siteversion parameter "?v=1.0.190" for instance to the css url. This siteversion is defined in web.config / appsettings and is bumped on every deploy.

We wanted to be able to use the same strategy for javascripts, but thus far I haven't had any success.
When rendering the script tag. the Scriptmanager renders

```<code><script src="/ScriptResource.axd?d=..." type="text/javascript"></script>
</code>```

Given that the current configured siteversion was 1.0.190, I would want it to render

```<code><script src="/ScriptResource.axd?d=...&v=1.0.190" type="text/javascript"></script>
</code>```

How do I get at the "script" html output from the script manager so I can change it?
It doesn't seem to be present in the stuff rendered in Render, RenderChildren or RenderControl

Yours
Andreas

答:
A much simpler solution in your page's onload works just fine for me:</p>

```<code>ScriptManager.GetCurrent(this).CompositeScript.Path += "?v=" + MyBuildNumber.Value;
</code>```

Body:
we are trying to get the following scenario working:

we use asp:scriptmanager / CompositeScripts to combine our scripts into a few script blocks but after each deploy to the test system we have trouble with testers not getting updated versions of css and javascript (browser cache). For the CSS we have defined our own css user control which appends a Siteversion parameter "?v=1.0.190" for instance to the css url. This siteversion is defined in web.config / appsettings and is bumped on every deploy.

We wanted to be able to use the same strategy for javascripts, but thus far I haven't had any success.
When rendering the script tag. the Scriptmanager renders

Given that the current configured siteversion was 1.0.190, I would want it to render

How do I get at the "script" html output from the script manager so I can change it?
It doesn't seem to be present in the stuff rendered in Render, RenderChildren or RenderControl

Yours
Andreas

Body:
A much simpler solution in your page's onload works just fine for me:

ScriptManager.GetCurrent(this).CompositeScript.Path += "?v=" + MyBuildNumber.Value;


问:
Invalid Identifier for type paramters
I am trying to execute what should be a simple query to get a distance column containing the distance from one SDO_GEOMETRY to another.

My code is as below

```<code>DECLARE query VARCHAR(4000); L_LATITUDE number; L_LONGITUDE number;

BEGIN
IF :P7_USER_POSTCODE IS NOT NULL THEN
    brian.GEOCODE_GM_JSON (:P7_USER_POSTCODE, L_LATITUDE, L_LONGITUDE);
END IF;

query :=     'SELECT
                     S.SPOT_ID,
                     dbms_lob.getlength("THUMBNAIL") "THUMBNAIL",
                     IND.SPOT_NAME,
                     IND.SPOT_DESCRIPTION,
                     SPOT.POSTCODE
             FROM SPOT_IMAGES S
             INNER JOIN SURFSPOTINDEX IND ON IND.SPOT_ID = S.SPOT_ID
             INNER JOIN SPOT_LOCATION SPOT ON SPOT.SPOT_ID = IND.SPOT_ID';

IF :P7_SEARCH IS NULL AND :P7_USER_POSTCODE IS NULL THEN
    return query;

ELSIF :P7_SEARCH IS NOT null  AND :P7_USER_POSTCODE IS NULL THEN

    query := query || ' ' ||
          'WHERE CONTAINS(IND.SPOT_DESCRIPTION, :P7_SEARCH, 123) > 0
           OR UPPER(IND.SPOT_NAME) LIKE UPPER(''%'' || :P7_SEARCH || ''%'')
            ';

            RETURN query;

ELSIF :P7_SEARCH IS null  AND :P7_USER_POSTCODE IS NOT NULL THEN

        query :=     'SELECT
                     S.SPOT_ID,
                     dbms_lob.getlength("THUMBNAIL") "THUMBNAIL",
                     IND.SPOT_NAME,
                     IND.SPOT_DESCRIPTION,
                     SPOT.POSTCODE,
                     ASDO_GEOM.SDO_DISTANCE(SPOT.LOCATION,
                                          SDO_GEOMETRY(2001,
                                          4326,
                                          SDO_POINT_TYPE(L_LONGITUDE, L_LATITUDE, null),
                                          null,
                                          null)
                     ,0.005, ''unit=mile'')   as DISTANCE
             FROM SPOT_IMAGES S
             INNER JOIN SURFSPOTINDEX IND ON IND.SPOT_ID = S.SPOT_ID
             INNER JOIN SPOT_LOCATION SPOT ON SPOT.SPOT_ID = IND.SPOT_ID
             ORDER BY Distance ASC';

          RETURN query;

END IF;

END;
</code>```

The final else if is where the error occurs.

I get the error

```<code> ORA-00904: "LONGITUDE": invalid identifier
</code>```

I cannot figure out why this is having googled the error code extensively.
The GEOCODE_GM_JSON returns latitude and longitude in the input variables and I have tested this and it is working correctly.

Any help would be appreciated.

Thanks.

答:
You haven't shown the full error stack and the message doesn't quite seem to correspond to your amended code, but it looks like you're embedding the string literals L_LATITUDE and L_LONGITUDE in the query string you're returning; but those variables don't mean anything to the caller when it tries to run that generated code.

You could concatenate in the actual variable values:

```<code>                     ASDO_GEOM.SDO_DISTANCE(SPOT.LOCATION,
                                          SDO_GEOMETRY(2001,
                                          4326,
                                          SDO_POINT_TYPE('
                                            || L_LONGITUDE ||', '|| L_LATITUDE
                                            ||', null),
                                          null,
                                          null)
                     ,0.005, ''unit=mile'')   as DISTANCE
</code>```

although that means that every query will have to be hard-parsed because of those literal values. Another function that returns the SDO point for the post code, instead of the latitude and longitude, might better if Apex can refer to that bind variable when it executes the query - the query in the previous branch, using :P7_SEARCH, implies it can. That would remove the concatenation, removing that hard-parse and reducing potential for SQL injection.

Title: Invalid Identifier for type paramters

Body:
I am trying to execute what should be a simple query to get a distance column containing the distance from one SDO_GEOMETRY to another.

My code is as below

DECLARE query VARCHAR(4000); L_LATITUDE number; L_LONGITUDE number;

BEGIN
IF :P7_USER_POSTCODE IS NOT NULL THEN
    brian.GEOCODE_GM_JSON (:P7_USER_POSTCODE, L_LATITUDE, L_LONGITUDE);
END IF;

query :=     'SELECT
                     S.SPOT_ID,
                     dbms_lob.getlength("THUMBNAIL") "THUMBNAIL",
                     IND.SPOT_NAME,
                     IND.SPOT_DESCRIPTION,
                     SPOT.POSTCODE
             FROM SPOT_IMAGES S
             INNER JOIN SURFSPOTINDEX IND ON IND.SPOT_ID = S.SPOT_ID
             INNER JOIN SPOT_LOCATION SPOT ON SPOT.SPOT_ID = IND.SPOT_ID';

IF :P7_SEARCH IS NULL AND :P7_USER_POSTCODE IS NULL THEN
    return query;

ELSIF :P7_SEARCH IS NOT null  AND :P7_USER_POSTCODE IS NULL THEN

    query := query || ' ' ||
          'WHERE CONTAINS(IND.SPOT_DESCRIPTION, :P7_SEARCH, 123) > 0
           OR UPPER(IND.SPOT_NAME) LIKE UPPER(''%'' || :P7_SEARCH || ''%'')
            ';

            RETURN query;

ELSIF :P7_SEARCH IS null  AND :P7_USER_POSTCODE IS NOT NULL THEN

        query :=     'SELECT
                     S.SPOT_ID,
                     dbms_lob.getlength("THUMBNAIL") "THUMBNAIL",
                     IND.SPOT_NAME,
                     IND.SPOT_DESCRIPTION,
                     SPOT.POSTCODE,
                     ASDO_GEOM.SDO_DISTANCE(SPOT.LOCATION,
                                          SDO_GEOMETRY(2001,
                                          4326,
                                          SDO_POINT_TYPE(L_LONGITUDE, L_LATITUDE, null),
                                          null,
                                          null)
                     ,0.005, ''unit=mile'')   as DISTANCE
             FROM SPOT_IMAGES S
             INNER JOIN SURFSPOTINDEX IND ON IND.SPOT_ID = S.SPOT_ID
             INNER JOIN SPOT_LOCATION SPOT ON SPOT.SPOT_ID = IND.SPOT_ID
             ORDER BY Distance ASC';

          RETURN query;

END IF;

END;

The final else if is where the error occurs.

I get the error

 ORA-00904: "LONGITUDE": invalid identifier

I cannot figure out why this is having googled the error code extensively.
The GEOCODE_GM_JSON returns latitude and longitude in the input variables and I have tested this and it is working correctly.

Any help would be appreciated.

Thanks.

Body:
You haven't shown the full error stack and the message doesn't quite seem to correspond to your amended code, but it looks like you're embedding the string literals L_LATITUDE and L_LONGITUDE in the query string you're returning; but those variables don't mean anything to the caller when it tries to run that generated code.

You could concatenate in the actual variable values:

                     ASDO_GEOM.SDO_DISTANCE(SPOT.LOCATION,
                                          SDO_GEOMETRY(2001,
                                          4326,
                                          SDO_POINT_TYPE('
                                            || L_LONGITUDE ||', '|| L_LATITUDE
                                            ||', null),
                                          null,
                                          null)
                     ,0.005, ''unit=mile'')   as DISTANCE

although that means that every query will have to be hard-parsed because of those literal values. Another function that returns the SDO point for the post code, instead of the latitude and longitude, might better if Apex can refer to that bind variable when it executes the query - the query in the previous branch, using :P7_SEARCH, implies it can. That would remove the concatenation, removing that hard-parse and reducing potential for SQL injection.


问:
composer identity issue Authorization failure error hyperldeger composer v0.15.0
I had the same issue which discussed here, and based on comments I fixed the problem by removing .composer-credentials directory and deploying my network again. Now I am using the new version of composer(v0.15.0). I already removed two directories (.composer-credentials and .composer-connection-profiles), but again when I run

composer identity issue -c admin@test-network -f membercard -u member -a "resource:org..."

I get the same error --> fabric-ca request register failed with errors [[{"code":400,"message":"Authorization failure"}]].

答:
In 0.15.x release connection profiles are not stored in ${HOME}/.composer-connection-profiles anymore. They are stored in your cards. Connection profiles should now not include a keyValStore property and as such the directory ${HOME}/.composer-credentials is not used to cache credentials anymore.
For 0.15.0 if you want to clear out cards and cached credentials then for now you need to delete the ${HOME}/.composer directory and re-import all your cards.
In the future you will be able to delete a card which will also clear any cached credentials.</p>


问:
How to delete an enum type value in postgres?
How do I delete an enum type value that I created in postgresql?

```<code>create type admin_level1 as enum('classifier', 'moderator', 'god');
</code>```

E.g. I want to remove moderator from the list.

I can't seem to find anything on the docs.

I'm using Postgresql 9.3.4.

答:
Very well written here:

http://blog.yo1.dog/updating-enum-values-in-postgresql-the-safe-and-easy-way/

rename the existing type

```<code>ALTER TYPE status_enum RENAME TO status_enum_old;
</code>```

create the new type

```<code>CREATE TYPE status_enum AS ENUM('queued', 'running', 'done');
</code>```

update the columns to use the new type

```<code>ALTER TABLE job ALTER COLUMN job_status TYPE status_enum USING job_status::text::status_enum;
</code>```

remove the old type

```<code>DROP TYPE status_enum_old;
</code>```

Possible Errors and Troubleshooting:

invalid input value for enum {enum name}: "{some value}" - One or more rows have a value ("{some value}") that is not in your new type. You must handle these rows before you can update the column type.

default for column "{column_name}" cannot be cast automatically to type {enum_name} - The default value for the column is not in your new type. You must change or remove the default value for the column before you can update the column type. Thanks to Philipp for this addition.

cannot alter type of a column used by a view or rule - All views and rules using the column have to be dropped before the ALTER can be executed and then recreated afterwards. There are ways to do that automatically.

Body:
How do I delete an enum type value that I created in postgresql?

create type admin_level1 as enum('classifier', 'moderator', 'god');

E.g. I want to remove moderator from the list.

I can't seem to find anything on the docs.

I'm using Postgresql 9.3.4.

Body:
Very well written here:

http://blog.yo1.dog/updating-enum-values-in-postgresql-the-safe-and-easy-way/

rename the existing type

ALTER TYPE status_enum RENAME TO status_enum_old;

create the new type

CREATE TYPE status_enum AS ENUM('queued', 'running', 'done');

update the columns to use the new type

ALTER TABLE job ALTER COLUMN job_status TYPE status_enum USING job_status::text::status_enum;

remove the old type

DROP TYPE status_enum_old;

Possible Errors and Troubleshooting:

invalid input value for enum {enum name}: "{some value}" - One or more rows have a value ("{some value}") that is not in your new type. You must handle these rows before you can update the column type.

default for column "{column_name}" cannot be cast automatically to type {enum_name} - The default value for the column is not in your new type. You must change or remove the default value for the column before you can update the column type. Thanks to Philipp for this addition.

cannot alter type of a column used by a view or rule - All views and rules using the column have to be dropped before the ALTER can be executed and then recreated afterwards. There are ways to do that automatically.

ContentLicense: CC BY-SA 4.0


问:
Measure service latency with Prometheus
I am new to Prometheus and Grafana. My primary goal is to get the response time per request.

For me it seemed to be a simple thing - but whatever I do I do not get the results I require.

I need to be able to analyse the service latency in the last minutes/hours/days. The current implementation I found was a simple SUMMARY (without definition of quantiles) which is scraped every 15s.

Is it possible to get the average request latency of the last minute from my Prometheus SUMMARY?

If YES: How? If NO: What should I do?

Currently I am using the following query:

```<code>rate(http_response_time_sum{application="myapp",handler="myHandler", status="200"}[1m])
/
rate(http_response_time_count{application="myapp",handler="myHandler", status="200"}[1m])
</code>```

I am getting two "datasets". The value of the first is "NaN". I suppose this is the result from a division by zero.

(I am using spring-client).

答: Your query is correct. The result will be NaN if there have been no queries in the past minute.</p>

Title: Measure service latency with Prometheus

Body:
I am new to Prometheus and Grafana. My primary goal is to get the response time per request.

For me it seemed to be a simple thing - but whatever I do I do not get the results I require.

I need to be able to analyse the service latency in the last minutes/hours/days. The current implementation I found was a simple SUMMARY (without definition of quantiles) which is scraped every 15s.

Is it possible to get the average request latency of the last minute from my Prometheus SUMMARY?

If YES: How? If NO: What should I do?

Currently I am using the following query:

rate(http_response_time_sum{application="myapp",handler="myHandler", status="200"}[1m])
/
rate(http_response_time_count{application="myapp",handler="myHandler", status="200"}[1m])

I am getting two "datasets". The value of the first is "NaN". I suppose this is the result from a division by zero.

(I am using spring-client).


问:
When I compile .c file it always creates .exe file with name 'a'
I use GCC compiler to compile and run C program on CMD.
When I compile C program using command gcc hello.c it creates an executable file file with name a.exe but when I use IDE it uses the name same as .c file as hello.exe.
Is it possible to create .exe file name same as .c file on CMD?

答:
You have to specify the name of the executable

```<code>gcc -c hello.c // compiling

gcc -o hello hello.o // linking
         ^------------------------- name of the executable
</code>```

you can do the compiling and the linking in one command

```<code>gcc -o hello hello.c
         ^------------------------- name of the executable
</code>```

Body:
You have to specify the name of the executable

gcc -c hello.c // compiling

gcc -o hello hello.o // linking
         ^------------------------- name of the executable

you can do the compiling and the linking in one command

gcc -o hello hello.c
         ^------------------------- name of the executable


问:
vuejs mounted lifecycle not triggering
in my App component below, mounted() lifecycle hook is not triggered:

```<code><template>
  <div>
    <div v-if='signedIn'>
        <router-view />
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import Oidc from 'oidc-client'

Vue.use(Oidc)

export default {
  data () {
    return {
      user: null,
      signedIn: false,
      mgr: new Oidc.UserManager({...settings...})
    }
  },
  methods: {
    signIn () {
    },
    signOut () {
    },
    getUser () {
    },
    mounted () {
      this.getUser()
    }
  }
}
</script>
</code>```

I have gone through the code several times, not sure what I'm missing.
I have this in the main.js file:

```<code>new Vue({
  el: '#app',
  render: h => h(App),
  router
})
</code>```

答:
You have the mounted inside the method area and this means that is a 'function' called mounted (like getUser()), not the mounted that automatically called when the component mounts.

You should change it like:

```<code>methods: {
    signIn () {
    },
    signOut () {
    },
    getUser () {
    }
  },
mounted () {
      this.getUser()
}
</code>```

And then it should work and be called automatically by Vue as a normal lifecycle method.

Hope it helps!

Title: vuejs mounted lifecycle not triggering

Body:
in my App component below, mounted() lifecycle hook is not triggered:

<template>

        <router-view />

</template>

I have gone through the code several times, not sure what I'm missing.
I have this in the main.js file:

new Vue({
  el: '#app',
  render: h => h(App),
  router
})

Body:
You have the mounted inside the method area and this means that is a 'function' called mounted (like getUser()), not the mounted that automatically called when the component mounts.

You should change it like:

methods: {
    signIn () {
    },
    signOut () {
    },
    getUser () {
    }
  },
mounted () {
      this.getUser()
}

And then it should work and be called automatically by Vue as a normal lifecycle method.

Hope it helps!


问:
WP Rest API with vue.js
I am not sure what I am doing wrong here, still  pretty noob at vue js so that might be the problem.
The problem is that it does not display anything. I got it to work with older vue version with a bit different code, but yeah...

```<code>var App = Vue.extend({});

var postList = Vue.extend({
  template:'#post-list-template',
  data: function(){
    return {
        posts: ''
    }
},

      mounted: function(){
      posts = this.$http.get('/wp-json/wp/v2/posts?per_page=10');

      posts.get(function(posts){
          this.$set('posts', posts);
      })
  }
 });

  var router = new VueRouter({
  mode: 'history',
  routes: [
  { path: '/', component: postList}
]
});

new Vue({
  el: '#app',
  router: router,
  template: '<router-view></router-view>'
});
</code>```

HTML is here if that makes things a bit easier to understand :

```<code>       <div class="container-fluid projects" id="projects">

           <h1 class="text-center project-heading">Projects</h1>

             <div class="white-wrap">

           <div id="app">

             <router-view></router-view>

            </div>

        </div>

            <template id="post-list-template">
             <div class="container">

                <div class="post-list">

                   <article v-for="post in posts">

                      <div class="post-content">

                       <h2>{{ post.title.rendered }}</h2>
                             {{ post.id }}
                           </div>

                  </article>

                  </div>

                 </div>

           </template>

         </div>
</code>```

答:
This resolved my problem:</p>

```<code>    var postLists = Vue.component('post-list',{
       template:'#post-list-template',
       data: function () {
         return {
               posts:'',
          }
        },
     mounted:function () {
          this.$http.get('./wp-json/wp/v2/posts').then(response => {

        // get body data
        this.posts = response.body;

        this.posts.forEach(function (){

        } );

       }, response => {
         console.log('Not Found');
       });
   }

   });

  //router
   var router = new VueRouter({

   routes: [
       { path: '', component: postLists },
      ]
    });

new Vue({
   el: '#app',
   router: router,

    });
</code>```

Title: WP Rest API with vue.js

Body:
I am not sure what I am doing wrong here, still  pretty noob at vue js so that might be the problem.
The problem is that it does not display anything. I got it to work with older vue version with a bit different code, but yeah...

var App = Vue.extend({});

var postList = Vue.extend({
  template:'#post-list-template',
  data: function(){
    return {
        posts: ''
    }
},

      mounted: function(){
      posts = this.$http.get('/wp-json/wp/v2/posts?per_page=10');

      posts.get(function(posts){
          this.$set('posts', posts);
      })
  }
 });

  var router = new VueRouter({
  mode: 'history',
  routes: [
  { path: '/', component: postList}
]
});

new Vue({
  el: '#app',
  router: router,
  template: '<router-view></router-view>'
});

HTML is here if that makes things a bit easier to understand :

Projects

             <router-view></router-view>

            <template id="post-list-template">

{{ post.title.rendered }}

                             {{ post.id }}

           </template>

Body:
This resolved my problem:

    var postLists = Vue.component('post-list',{
       template:'#post-list-template',
       data: function () {
         return {
               posts:'',
          }
        },
     mounted:function () {
          this.$http.get('./wp-json/wp/v2/posts').then(response => {

        // get body data
        this.posts = response.body;

        this.posts.forEach(function (){

        } );

       }, response => {
         console.log('Not Found');
       });
   }

   });

  //router
   var router = new VueRouter({

   routes: [
       { path: '', component: postLists },
      ]
    });

new Vue({
   el: '#app',
   router: router,

    });


问:
Stripe Connect payment in iOS
We want to integrate Stripe Connect with iOS application to transfer amount from one person to person.

Let's say, I want to transfer $100 to my sister's account using Stripe Connect Standalone/Managed Account. And we also want to take business commission from sender which includes stripe commission also.

We have gone through Sharing Customers also but won't be able to find any solution for Stripe Connect with iOS SDK.

We have also checked iOS SDK.

Can anyone please guide us how to integrate Stripe Connect with iOS mobile app in above scenario?

How can we transfer payment to end customer?

Do we need to integrate through iOS SDK or web page?

答:
You can easily integrate Stripe Connect with your iOS app check the following link
https://github.com/gurunglaxman0/StripeConnect-iOS

Once you connect your stripe user id with server you can create charges and application fee using Stripe Api's from backend

Title: Stripe Connect payment in iOS


问:
JavaScript - Try & Catch - Trouble Capturing Window.postMessage() Errors
I am having trouble catching errors when using window.postMessage().

I want to be able to capture the error I am getting -

"Unable to post message to http://www.that-domain.com. Recipient has origin http://www.this-domain.com

Simple example code ( should error ):

```<code> try {
    window.postMessage('1','http://www.differentDomain.com');
 }
 catch (e) {
     alert('error');
 }
</code>```

More detailed process flow:
I am adding a cross domain iframe to the document with jQuery and then posting to it. This shouldn't error because the target origins should match - they are both set by the proxyDomain variable.

```<code>var $iframeProxy = $('<iframe id="myIFrame" src="' + proxyDomain + '"></iframe>').appendTo('body');

window.storageProxy = $iframeProxy[0].contentWindow;

try {
    window.storageProxy.postMessage(message, proxyDomain);
}
catch (e) {
    alert('error');
}
</code>```

答:
No way to catch the error, but usually the error happens if the target origin is different, the case is test vs production scenario.

So you can check what is the parent domain and change the target origin accordingly:

```<code>function getTargetOrigin()
{
    try {
        var url = (window.location != window.parent.location) ? document.referrer : document.location.href;
        if (url.indexOf('www.myproduction-website.com')!=-1)
            return document.location.protocol + '//www.myproduction-website.com'
        else //set the alternative target
            return document.location.protocol + '//' + url.split('/')[2];
    }
    catch(e) //falback to production
    {
        return document.location.protocol + '//www.myproduction-website.com'
    }
}
</code>```

and use it inside the postMessage function:

```<code>function postMessage(message){
    window.top.postMessage( message,getTargetOrigin());
}
</code>```

With this solution you can use the same code in multiple server configuration without hard coding the targetOrigin url.

This solution fails if you navigate inside the frame and you recheck the document.referrer, in that case it will contain not the parent url but the previous frame url.
In that case consider to use the '*' as targetOrigin url, it's the only working solution to send messages to other domains.

Hope it helps!

Body:
I am having trouble catching errors when using window.postMessage().

I want to be able to capture the error I am getting -

"Unable to post message to http://www.that-domain.com. Recipient has origin http://www.this-domain.com

Simple example code ( should error ):

 try {
    window.postMessage('1','http://www.differentDomain.com');
 }
 catch (e) {
     alert('error');
 }

More detailed process flow:
I am adding a cross domain iframe to the document with jQuery and then posting to it. This shouldn't error because the target origins should match - they are both set by the proxyDomain variable.

var $iframeProxy = $('').appendTo('body');

window.storageProxy = $iframeProxy[0].contentWindow;

try {
    window.storageProxy.postMessage(message, proxyDomain);
}
catch (e) {
    alert('error');
}

Body:
No way to catch the error, but usually the error happens if the target origin is different, the case is test vs production scenario.

So you can check what is the parent domain and change the target origin accordingly:

function getTargetOrigin()
{
    try {
        var url = (window.location != window.parent.location) ? document.referrer : document.location.href;
        if (url.indexOf('www.myproduction-website.com')!=-1)
            return document.location.protocol + '//www.myproduction-website.com'
        else //set the alternative target
            return document.location.protocol + '//' + url.split('/')[2];
    }
    catch(e) //falback to production
    {
        return document.location.protocol + '//www.myproduction-website.com'
    }
}

and use it inside the postMessage function:

function postMessage(message){
    window.top.postMessage( message,getTargetOrigin());
}

With this solution you can use the same code in multiple server configuration without hard coding the targetOrigin url.

This solution fails if you navigate inside the frame and you recheck the document.referrer, in that case it will contain not the parent url but the previous frame url.
In that case consider to use the '*' as targetOrigin url, it's the only working solution to send messages to other domains.

Hope it helps!


问:
Python2/3 give different answers to the same math operation...why? (calculating percent difference)
Python 2 and Python 3 seem to arrive at different answers for the very simple math operation of finding percentage difference between two quantities.

For example:

```<code># Python 2.7.10
>>> def percent_difference(qty1, qty2):
...     diff = max(qty1, qty2) - min(qty1, qty2)
...     print(diff)
...     percent = diff / ( (qty1 + qty2) / 2)
...     print(percent)
...
>>> percent_difference(1, 2)
1
1

# Python 3.6.2

>>> def percent_difference(qty1, qty2):
...     diff = max(qty1, qty2) - min(qty1, qty2)
...     print(diff)
...     percent = diff / ( (qty1 + qty2) / 2)
...     print(percent)
...
>>> percent_difference(1, 2)
1
0.6666666666666666
</code>```

What's going on here?

(Python3 is correct)

答:
You need to tell Python that you want float output.
Try percent_difference(1.0, 2.0)

Body:
Python 2 and Python 3 seem to arrive at different answers for the very simple math operation of finding percentage difference between two quantities.

For example:

# Python 2.7.10
>>> def percent_difference(qty1, qty2):
...     diff = max(qty1, qty2) - min(qty1, qty2)
...     print(diff)
...     percent = diff / ( (qty1 + qty2) / 2)
...     print(percent)
...
>>> percent_difference(1, 2)
1
1

# Python 3.6.2

>>> def percent_difference(qty1, qty2):
...     diff = max(qty1, qty2) - min(qty1, qty2)
...     print(diff)
...     percent = diff / ( (qty1 + qty2) / 2)
...     print(percent)
...
>>> percent_difference(1, 2)
1
0.6666666666666666

What's going on here?

(Python3 is correct)


问:
Angular4 how to enable test coverage
I am working on an Angular4 project.

I am trying to set up code coverage. I created a very simple and small app.

I read every possible page I could find, but I am lost.

How do I set up code coverage in Angular4?

UPDATE2:
I have now decided to use karma coverage reporter
https://www.npmjs.com/package/karma-coverage
and therefore reworked the karma conf file as per the description.

The package json got updated to.

I now see the folder being generated, but the HTML file shows an empty table,

The test is being run and passes:

not sure what to do from here.

Here is my package json.

```<code>   {
  "name": "angular2-webpack",
  "version": "0.0.1",
  "description": "A webpack starter for Angular",
  "scripts": {
      "pretest": "npm run lint",
      "start": "webpack-dev-server --inline --progress --port 8080",
      "test": "karma start",
      "build": "rimraf dist && webpack --config config/webpack.prod.js --progress --profile --bail",
      "lint": "tslint --force \"src/**/*.ts\""
  },
  "license": "MIT",
    "dependencies": {
        "@angular/common": "4.1.2",
        "@angular/compiler": "4.1.2",
        "@angular/core": "4.1.2",
        "@angular/forms": "4.1.2",
        "@angular/http": "4.1.2",
        "@angular/platform-browser": "4.1.2",
        "@angular/platform-browser-dynamic": "4.1.2",
        "@angular/router": "4.1.2",
        "bootstrap": "^3.3.7",
        "core-js": "2.4.1",
        "es6-shim": "^0.35.3",
        "jquery": "^3.2.0",
        "reflect-metadata": "^0.1.10",
        "rxjs": "^5.0.1",
        "zone.js": "^0.8.10"
  },
  "devDependencies": {
      "@types/jasmine": "2.5.47",
      "@types/node": "^7.0.18",
      "angular2-template-loader": "^0.6.0",
      "awesome-typescript-loader": "^3.0.4",
      "css-loader": "^0.28.1",
      "extract-text-webpack-plugin": "^2.1.0",
      "file-loader": "^0.11.1",
      "html-loader": "^0.4.3",
      "html-webpack-plugin": "^2.16.1",
      "jasmine-core": "^2.4.1",
      "karma": "^1.7.0",
      "karma-chrome-launcher": "^2.0.0",
      "karma-coverage": "^1.1.1",
      "karma-jasmine": "^1.0.2",
      "karma-phantomjs-launcher": "^1.0.4",
      "karma-sourcemap-loader": "^0.3.7",
      "karma-webpack": "^2.0.1",
      "lint": "^1.1.2",
      "node-sass": "^4.5.0",
      "null-loader": "^0.1.1",
      "phantomjs-prebuilt": "^2.1.7",
      "raw-loader": "^0.5.1",
      "rimraf": "^2.5.2",
      "sass-loader": "^6.0.3",
      "style-loader": "^0.17.0",
      "tslint": "^5.2.0",
      "tslint-loader": "^3.5.3",
      "typescript": "~2.3.2",
      "webpack": "^2.2.1",
      "webpack-dev-server": "2.4.5",
      "webpack-merge": "^4.1.0"
  }
}
</code>```

Followed by my webpack config

```<code>var webpack = require('webpack');
var helpers = require('./helpers');
const ExtractTextPlugin = require("extract-text-webpack-plugin");

const extractSass = new ExtractTextPlugin({
    filename: "[name].[contenthash].css",
    disable: process.env.NODE_ENV === "development"
});

module.exports = {
    devtool: 'inline-source-map',

    resolve: {
        extensions: ['.ts', '.js']
    },

    module: {
        rules: [
            {
                test: /\.ts$/,
                loaders: [
                    {
                        loader: 'awesome-typescript-loader',
                        options: {configFileName: helpers.root('src', 'tsconfig.json')}
                    }, 'angular2-template-loader'
                ]
            },
            {
                test: /\.html$/,
                loader: 'html-loader'
            },
            {
                test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
                loader: 'file-loader?name=assets/[name].[hash].[ext]'
            },
            {
                test: /\.css$/,
                exclude: helpers.root('src', 'app'),
                loader: 'style-loader!css-loader?sourceMap'
            },
            {
                test: /\.css$/,
                include: helpers.root('src', 'app'),
                loader: 'raw-loader'
            },

            {
                test: /\.scss$/,
                exclude: helpers.root('src', 'app'),
                use: extractSass.extract({
                    use: [{
                        loader: "css-loader"
                    }, {
                        loader: "sass-loader"
                    }],
                    // use style-loader in development
                    fallback: "style-loader"
                })
            },
            {
                test: /\.scss$/,
                include: helpers.root('src', 'app'),
                loader: 'raw-loader'
            }
        ]
    },

    plugins: [
        extractSass,
        new webpack.ContextReplacementPlugin(
            // The (\\|\/) piece accounts for path separators in *nix and Windows
            /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
            helpers.root('./src'), // location of your src
            {} // a map of your routes
        )
    ]
}
</code>```

Followed by the now updated karma conf file:

```<code>  var webpackConfig = require('./webpack.test');
var path = require('path');

var ENV = process.env.npm_lifecycle_event;
var isTestWatch = ENV === 'test-watch';
module.exports = function (config) {
    var _config = {
        basePath: './',

        frameworks: ['jasmine'],

        files: [
            {pattern: './config/karma-test-shim.js', watched: false},
            '../src/**/*.js'
        ],
        // list of files to exclude
        exclude: [],
        preprocessors: {
            './config/karma-test-shim.js': ['webpack', 'sourcemap'],
            '../src/**/*.js': ['coverage']

        },
        coverageReporter: {
            type : 'html',
            dir : 'cover/'
        },
        webpack: webpackConfig,

        webpackMiddleware: {
            stats: 'errors-only'
        },

        webpackServer: {
            noInfo: true
        },

        reporters: ['progress', 'mocha','coverage'],

        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: false,
        browsers: isTestWatch ? ['PhantomJS'] : ['PhantomJS'],
        singleRun: true
    };

     config.set(_config);

};
</code>```

The code in its full glory can be found here

https://github.com/uweDuesing/angular2-webpack-template

答:
Add angularClt to your karma.conf file.
Something like this:

angularCli: {
      environment: 'dev',
      codeCoverage: true
    }```

codeCoverage is the important part if you want to run codeCoverage for an ejected app with the script command npm run test

Title: Angular4 how to enable test coverage

Body:
I am working on an Angular4 project.

I am trying to set up code coverage. I created a very simple and small app.

I read every possible page I could find, but I am lost.

How do I set up code coverage in Angular4?

UPDATE2:
I have now decided to use karma coverage reporter
https://www.npmjs.com/package/karma-coverage
and therefore reworked the karma conf file as per the description.

The package json got updated to.

I now see the folder being generated, but the HTML file shows an empty table,

The test is being run and passes:

not sure what to do from here.

Here is my package json.

   {
  "name": "angular2-webpack",
  "version": "0.0.1",
  "description": "A webpack starter for Angular",
  "scripts": {
      "pretest": "npm run lint",
      "start": "webpack-dev-server --inline --progress --port 8080",
      "test": "karma start",
      "build": "rimraf dist && webpack --config config/webpack.prod.js --progress --profile --bail",
      "lint": "tslint --force \"src/**/*.ts\""
  },
  "license": "MIT",
    "dependencies": {
        "@angular/common": "4.1.2",
        "@angular/compiler": "4.1.2",
        "@angular/core": "4.1.2",
        "@angular/forms": "4.1.2",
        "@angular/http": "4.1.2",
        "@angular/platform-browser": "4.1.2",
        "@angular/platform-browser-dynamic": "4.1.2",
        "@angular/router": "4.1.2",
        "bootstrap": "^3.3.7",
        "core-js": "2.4.1",
        "es6-shim": "^0.35.3",
        "jquery": "^3.2.0",
        "reflect-metadata": "^0.1.10",
        "rxjs": "^5.0.1",
        "zone.js": "^0.8.10"
  },
  "devDependencies": {
      "@types/jasmine": "2.5.47",
      "@types/node": "^7.0.18",
      "angular2-template-loader": "^0.6.0",
      "awesome-typescript-loader": "^3.0.4",
      "css-loader": "^0.28.1",
      "extract-text-webpack-plugin": "^2.1.0",
      "file-loader": "^0.11.1",
      "html-loader": "^0.4.3",
      "html-webpack-plugin": "^2.16.1",
      "jasmine-core": "^2.4.1",
      "karma": "^1.7.0",
      "karma-chrome-launcher": "^2.0.0",
      "karma-coverage": "^1.1.1",
      "karma-jasmine": "^1.0.2",
      "karma-phantomjs-launcher": "^1.0.4",
      "karma-sourcemap-loader": "^0.3.7",
      "karma-webpack": "^2.0.1",
      "lint": "^1.1.2",
      "node-sass": "^4.5.0",
      "null-loader": "^0.1.1",
      "phantomjs-prebuilt": "^2.1.7",
      "raw-loader": "^0.5.1",
      "rimraf": "^2.5.2",
      "sass-loader": "^6.0.3",
      "style-loader": "^0.17.0",
      "tslint": "^5.2.0",
      "tslint-loader": "^3.5.3",
      "typescript": "~2.3.2",
      "webpack": "^2.2.1",
      "webpack-dev-server": "2.4.5",
      "webpack-merge": "^4.1.0"
  }
}

Followed by my webpack config

var webpack = require('webpack');
var helpers = require('./helpers');
const ExtractTextPlugin = require("extract-text-webpack-plugin");

const extractSass = new ExtractTextPlugin({
    filename: "[name].[contenthash].css",
    disable: process.env.NODE_ENV === "development"
});

module.exports = {
    devtool: 'inline-source-map',

    resolve: {
        extensions: ['.ts', '.js']
    },

    module: {
        rules: [
            {
                test: /\.ts$/,
                loaders: [
                    {
                        loader: 'awesome-typescript-loader',
                        options: {configFileName: helpers.root('src', 'tsconfig.json')}
                    }, 'angular2-template-loader'
                ]
            },
            {
                test: /\.html$/,
                loader: 'html-loader'
            },
            {
                test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
                loader: 'file-loader?name=assets/[name].[hash].[ext]'
            },
            {
                test: /\.css$/,
                exclude: helpers.root('src', 'app'),
                loader: 'style-loader!css-loader?sourceMap'
            },
            {
                test: /\.css$/,
                include: helpers.root('src', 'app'),
                loader: 'raw-loader'
            },

            {
                test: /\.scss$/,
                exclude: helpers.root('src', 'app'),
                use: extractSass.extract({
                    use: [{
                        loader: "css-loader"
                    }, {
                        loader: "sass-loader"
                    }],
                    // use style-loader in development
                    fallback: "style-loader"
                })
            },
            {
                test: /\.scss$/,
                include: helpers.root('src', 'app'),
                loader: 'raw-loader'
            }
        ]
    },

    plugins: [
        extractSass,
        new webpack.ContextReplacementPlugin(
            // The (\\|\/) piece accounts for path separators in *nix and Windows
            /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
            helpers.root('./src'), // location of your src
            {} // a map of your routes
        )
    ]
}

Followed by the now updated karma conf file:

  var webpackConfig = require('./webpack.test');
var path = require('path');

var ENV = process.env.npm_lifecycle_event;
var isTestWatch = ENV === 'test-watch';
module.exports = function (config) {
    var _config = {
        basePath: './',

        frameworks: ['jasmine'],

        files: [
            {pattern: './config/karma-test-shim.js', watched: false},
            '../src/**/*.js'
        ],
        // list of files to exclude
        exclude: [],
        preprocessors: {
            './config/karma-test-shim.js': ['webpack', 'sourcemap'],
            '../src/**/*.js': ['coverage']

        },
        coverageReporter: {
            type : 'html',
            dir : 'cover/'
        },
        webpack: webpackConfig,

        webpackMiddleware: {
            stats: 'errors-only'
        },

        webpackServer: {
            noInfo: true
        },

        reporters: ['progress', 'mocha','coverage'],

        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: false,
        browsers: isTestWatch ? ['PhantomJS'] : ['PhantomJS'],
        singleRun: true
    };

     config.set(_config);

};

The code in its full glory can be found here

https://github.com/uweDuesing/angular2-webpack-template

Body:
Add angularClt to your karma.conf file.
Something like this:

angularCli: {
      environment: 'dev',
      codeCoverage: true
    }

codeCoverage is the important part if you want to run codeCoverage for an ejected app with the script command npm run test


问:
Vim: Stop "existing swap file" warnings
I have no idea why, but it seems that no matter how I quit out of Vim, it always leaves the swap files behind. So, whenever I open that file again, I get an irritating error about an existing swap file. Every time I have to choose "delete". I really wish this would stop. Is there anything I can put in my .vimrc to tell it, "just delete the swap file if it exists and leave me alone?"

答: It's possible that you have not enough rights for some directory in the path to your current directory. It just happened to me.</p>

Title: Vim: Stop "existing swap file" warnings


问:
How to change the default path separator in Visual Studio?
I have cross-platform projects, which I have to compile with GCC, Clang and MSVC. Whenever I use the Visual Studio's and type #include <foo..., IntelliSense suggests \ as the path separator. This obviously works on MSVC, but on GCC and other compilers triggers an error.

Is there a way to tell Visual Studio to use / instead?

答:
This can be done as follows:

Go to "Tools → Options… → Text Editor → C/C++ → Advanced"

Toggle "Use Forward Slash in #include Auto Complete" under the "IntelliSense" section


问:
WordPress/ Woo commerce plugin
I am working on a project called which sells sarees ( An Indian dress ). the problem I faced is the customer wants to save her body dimensions{they have more than one value}  in the account so when she buys a saree we can send the blouse with her sizes. </p>

<p>So is there any plugin [ paid / Free ] where I can add a new tab in my account area like my dimensions so the user can add her dimension there and save. </p>

答:
here are some plugins or links which will help you regarding this

https://wordpress.org/plugins/productsize-chart-for-woocommerce/
https://wordpress.org/plugins/yith-product-size-charts-for-woocommerce/
https://wordpress.org/plugins/product-size-charts-for-woocommerce/
https://docs.woocommerce.com/document/variable-product/
https://www.artsygeek.com/adding-sizes-to-products-in-woocommerce/

Thanks

Title: WordPress/ Woo commerce plugin

Body:
I am working on a project called which sells sarees ( An Indian dress ). the problem I faced is the customer wants to save her body dimensions{they have more than one value}  in the account so when she buys a saree we can send the blouse with her sizes.

So is there any plugin [ paid / Free ] where I can add a new tab in my account area like my dimensions so the user can add her dimension there and save.


问:
WiX installer : Can one msi have - one windows app and one windows service using WiX
I have created two separate msi for using Wix toolset:

 - Windows application

 - Windows service

Goal

Want to have one msi which can install both :

 - Windows application

 - Windows service

Problem

Is it possible using WiX ?

Can we make use of merge module to include both msi into one msm ? if yes, How ?

Edit 1

Getting an error -

The Directory with Id 'TARGETDIR_WindowsService' is not a valid root
  directory. There may only be a single root directory per product or
  module and its Id attribute value must be 'TARGETDIR' and its Name
  attribute value must be 'SourceDir'

If i am not changing the TARGETDIR then duplicate error is coming for both "TARGETDIR" and "ProgramFilesFolder".

答:
Yes, you can. You put them in different features. You can then build a UI to launch the app install, the service install or both. </p>

```<code><?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
    <Product Id="*" Name="SetupProject1" Language="1033" Version="1.0.0.0" Manufacturer="YourCompany" UpgradeCode="3fdc2c3a-72f3-4a5f-a182-3905272bf888">
        <Package InstallerVersion="200" Compressed="yes" InstallScope="perMachine" />

        <MajorUpgrade DowngradeErrorMessage="A newer version of [ProductName] is already installed." />
        <MediaTemplate />

        <Feature Id="ProductFeature" Title="My Application" Level="1">
            <ComponentGroupRef Id="ProductComponents" />
        </Feature>
        <Feature Id="ServiceFeature" Title="My Service" Level="1">
            <ComponentGroupRef Id="ProductComponents" />
        </Feature>
    </Product>

    <Fragment>
        <Directory Id="TARGETDIR" Name="SourceDir">
            <Directory Id="ProgramFilesFolder">
                <Directory Id="INSTALLFOLDER" Name="MyApplication" />
                <Directory Id="SERVICEFOLDER" Name="MyService" />
            </Directory>
        </Directory>
    </Fragment>

    <Fragment>
        <ComponentGroup Id="ProductComponents" Directory="INSTALLFOLDER">
        </ComponentGroup>
        <ComponentGroup Id="ServiceComponents" Directory="SERVICEFOLDER">
        </ComponentGroup>
    </Fragment>
</Wix>
</code>```

Body:
Yes, you can. You put them in different features. You can then build a UI to launch the app install, the service install or both.

<?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
    <Product Id="*" Name="SetupProject1" Language="1033" Version="1.0.0.0" Manufacturer="YourCompany" UpgradeCode="3fdc2c3a-72f3-4a5f-a182-3905272bf888">
        <Package InstallerVersion="200" Compressed="yes" InstallScope="perMachine" />

        <MajorUpgrade DowngradeErrorMessage="A newer version of [ProductName] is already installed." />
        <MediaTemplate />

        <Feature Id="ProductFeature" Title="My Application" Level="1">
            <ComponentGroupRef Id="ProductComponents" />
        </Feature>
        <Feature Id="ServiceFeature" Title="My Service" Level="1">
            <ComponentGroupRef Id="ProductComponents" />
        </Feature>
    </Product>

    <Fragment>
        <Directory Id="TARGETDIR" Name="SourceDir">
            <Directory Id="ProgramFilesFolder">
                <Directory Id="INSTALLFOLDER" Name="MyApplication" />
                <Directory Id="SERVICEFOLDER" Name="MyService" />
            </Directory>
        </Directory>
    </Fragment>

    <Fragment>
        <ComponentGroup Id="ProductComponents" Directory="INSTALLFOLDER">
        </ComponentGroup>
        <ComponentGroup Id="ServiceComponents" Directory="SERVICEFOLDER">
        </ComponentGroup>
    </Fragment>
</Wix>


问:
Quick search on filename
How can I quick search a class file or entire resource file in android studio?

Eclipse short cuts are

Shift+Ctrl+R for all resource files (include .java file)

Shift+Ctrl+T for all Java class in classpath

Currently, I have changed keymap settings to Eclipse so that I am able to use same short cuts in Android Studio. However, I need to know what is the default shortcut keys in Android Studio.

答: You can use search button or double shift</p>

Title: Quick search on filename


问:
How to create a histogram with fixed bin width on percentage scale reflective for each facet?
I would like to create a histogram where the y-axis shows the percentage per facet in ggplot2. I have seen several similar questions but some answers seem outdated or they show the percentage of all observations rather than per facet.

I tried this:

```<code>library(ggplot2)
library(scales)

ggplot(mtcars, aes(mpg))+
    facet_grid(cyl ~ am)+
    stat_count(aes(y=..prop..)) +
    theme_bw()+
    scale_y_continuous(labels = percent_format())
</code>```

Which seems to work, except that the binwidth is not fixed. Facets with few observations have large bars.

How could I fix the binwidth?

EDIT: Solution adapted from ACNB
I overlooked that before and I just saw that Andrey Kolyadin was quicker to provide a more concise solution.

```<code>binwidth <- 1
mtcars.stats <- mtcars %>%
    group_by(cyl, am) %>%
    mutate(bin = cut(mpg, breaks=seq(0,35, binwidth),
                     labels = seq(0 + binwidth, 35, binwidth)-(binwidth/2)),
           n = n()) %>%
    group_by(cyl, am, bin) %>%
    summarise(p = n()/n[1]) %>%
    ungroup() %>%
    mutate(bin = as.numeric(as.character(bin)))

ggplot(mtcars.stats, aes(x = bin, y= p)) +
    geom_col() +
    facet_grid(cyl~am)+
    theme_bw()+
    scale_y_continuous(labels = percent_format())
</code>```

答:
As alway I advice not to rely on statistics layer of ggplot2 and calculate necessary statistics before plotting:

```<code>library('zoo')
library('tidyverse')

# Selecting breaks
breaks <- seq.int(min(mtcars$mpg), max(mtcars$mpg), length.out = 19)

# Calculating densities
mt_hist <- mtcars %>%
  group_by(cyl, am) %>%
  summarise(x = list(rollmean(breaks, 2)),
            count = list(hist(mpg, breaks = breaks, plot = FALSE)$counts)) %>%
  unnest() %>%
  group_by(cyl, am) %>%
  mutate(count = count/sum(count))
</code>```

And plot itself:

```<code>ggplot(mt_hist)+
  aes(x = x,
      y = count)+
  geom_col()+
  facet_grid(cyl ~ am)+
  theme_bw()+
  scale_y_continuous(labels = percent_format())
</code>```

Body:
I would like to create a histogram where the y-axis shows the percentage per facet in ggplot2. I have seen several similar questions but some answers seem outdated or they show the percentage of all observations rather than per facet.

I tried this:

library(ggplot2)
library(scales)

ggplot(mtcars, aes(mpg))+
    facet_grid(cyl ~ am)+
    stat_count(aes(y=..prop..)) +
    theme_bw()+
    scale_y_continuous(labels = percent_format())

Which seems to work, except that the binwidth is not fixed. Facets with few observations have large bars.

How could I fix the binwidth?

EDIT: Solution adapted from ACNB
I overlooked that before and I just saw that Andrey Kolyadin was quicker to provide a more concise solution.

binwidth <- 1
mtcars.stats <- mtcars %>%
    group_by(cyl, am) %>%
    mutate(bin = cut(mpg, breaks=seq(0,35, binwidth),
                     labels = seq(0 + binwidth, 35, binwidth)-(binwidth/2)),
           n = n()) %>%
    group_by(cyl, am, bin) %>%
    summarise(p = n()/n[1]) %>%
    ungroup() %>%
    mutate(bin = as.numeric(as.character(bin)))

ggplot(mtcars.stats, aes(x = bin, y= p)) +
    geom_col() +
    facet_grid(cyl~am)+
    theme_bw()+
    scale_y_continuous(labels = percent_format())

Body:
As alway I advice not to rely on statistics layer of ggplot2 and calculate necessary statistics before plotting:

library('zoo')
library('tidyverse')

# Selecting breaks
breaks <- seq.int(min(mtcars$mpg), max(mtcars$mpg), length.out = 19)

# Calculating densities
mt_hist <- mtcars %>%
  group_by(cyl, am) %>%
  summarise(x = list(rollmean(breaks, 2)),
            count = list(hist(mpg, breaks = breaks, plot = FALSE)$counts)) %>%
  unnest() %>%
  group_by(cyl, am) %>%
  mutate(count = count/sum(count))

And plot itself:

ggplot(mt_hist)+
  aes(x = x,
      y = count)+
  geom_col()+
  facet_grid(cyl ~ am)+
  theme_bw()+
  scale_y_continuous(labels = percent_format())