问:
Why can I pass a list of named arguments -- but not unnamed arguments -- to this decorator?
This question is not a duplicate of How pass unknown list of unnamed arguments to a python decorator?. I'm asking a different but related question here.

I have created a python decorator my_decorator method as shown below. I want this decorator to accept an unknown list of arguments:

```<code>#!/usr/bin/env python
from functools import wraps

class A:
    def my_decorator(self, func=None, *args, **kwargs):
        print "Hello World2!"
        print 'args = {}'.format(args)
        print 'kwargs = {}'.format(kwargs)
        def inner_function(decorated_function):
            def wrapped_func(*fargs, **fkwargs):
                print "Hello World3!"
                return decorated_function(*fargs, **fkwargs)
            return wrapped_func

        if func:
            return inner_function(func)
        else:
            return inner_function

class B:
    my_a = A()

    @my_a.my_decorator(a1="Yolo", b1="Bolo")
    def my_func(self):
         print "Hello World1!"

my_B = B()
my_B.my_func()
</code>```

This code works perfectly fine:

Hello World2!
args = ()
kwargs = {'a1': 'Yolo', 'b1': 'Bolo'}
Hello World3!
Hello World1!
```

<p>However, now, instead of passing named arguments to <code>@my_a.my_decorator</code>, I want to pass unnamed arguments like this: <code>@my_a.my_decorator('Yolo', 'Bolo')</code> and it fails:</p>

<pre class="lang-none prettyprint-override"><code>Hello World2!
args = ('Bolo',)
kwargs = {}
Hello World3!
Traceback (most recent call last):
  File "./decorator_test.py", line 20, in <module>
    class B:
  File "./decorator_test.py", line 23, in B
    @my_a.my_decorator('Yolo', 'Bolo')
  File "./decorator_test.py", line 12, in wrapped_func
    return decorated_function(*fargs, **fkwargs)
TypeError: 'str' object is not callable
</code>```

How can I fix this?

答:
```<code>def my_decorator(self, *args, **kwargs):
    [skip]
    if 'func' in kwargs:
        return inner_function(kwargs.pop('func'))
    else:
        return inner_function
</code>```

Body:
This question is not a duplicate of How pass unknown list of unnamed arguments to a python decorator?. I'm asking a different but related question here.

I have created a python decorator my_decorator method as shown below. I want this decorator to accept an unknown list of arguments:

#!/usr/bin/env python
from functools import wraps

class A:
    def my_decorator(self, func=None, *args, **kwargs):
        print "Hello World2!"
        print 'args = {}'.format(args)
        print 'kwargs = {}'.format(kwargs)
        def inner_function(decorated_function):
            def wrapped_func(*fargs, **fkwargs):
                print "Hello World3!"
                return decorated_function(*fargs, **fkwargs)
            return wrapped_func

        if func:
            return inner_function(func)
        else:
            return inner_function

class B:
    my_a = A()

    @my_a.my_decorator(a1="Yolo", b1="Bolo")
    def my_func(self):
         print "Hello World1!"

my_B = B()
my_B.my_func()

This code works perfectly fine:

Hello World2!
args = ()
kwargs = {'a1': 'Yolo', 'b1': 'Bolo'}
Hello World3!
Hello World1!

However, now, instead of passing named arguments to @my_a.my_decorator, I want to pass unnamed arguments like this: @my_a.my_decorator('Yolo', 'Bolo') and it fails:

Hello World2!
args = ('Bolo',)
kwargs = {}
Hello World3!
Traceback (most recent call last):
  File "./decorator_test.py", line 20, in <module>
    class B:
  File "./decorator_test.py", line 23, in B
    @my_a.my_decorator('Yolo', 'Bolo')
  File "./decorator_test.py", line 12, in wrapped_func
    return decorated_function(*fargs, **fkwargs)
TypeError: 'str' object is not callable

How can I fix this?


来源: stackexchange

问:
Where to find the youtube API Key?
I followed all the steps. I selected my desired API (YouTube Data API) and created a project.
I am searching now for about 20 minutes but I can't find the API Key?
My user interface is in german, is it possible that it is named to something else than API Key? Maybe Clientschlüssel (Client Key) ?

This is all I found:

There is also a JSON object, but no API Key:

```<code>var myInfos = {
    "web":{
        "client_id":"censored",
        "project_id":"censored",
        "auth_uri":"https://accounts.google.com/o/oauth2/auth",
        "token_uri":"https://accounts.google.com/o/oauth2/token",
        "auth_provider_x509_cert_url":"censored",
        "client_secret":"censored",
        "redirect_uris":["https://localhost/ex/YouTube/index.html"],
        "javascript_origins":["http://localhost"]
    }
}
</code>```

答:
I finally found it!
You have to go to Zugangsdaten (Credentials) and then click on Anmeldedaten erstellen (create credentials), now you can select API Key!

ContentLicense: CC BY-SA 3.0

Title: Where to find the youtube API Key?

Body:
I followed all the steps. I selected my desired API (YouTube Data API) and created a project.
I am searching now for about 20 minutes but I can't find the API Key?
My user interface is in german, is it possible that it is named to something else than API Key? Maybe Clientschlüssel (Client Key) ?

This is all I found:

There is also a JSON object, but no API Key:

var myInfos = {
    "web":{
        "client_id":"censored",
        "project_id":"censored",
        "auth_uri":"https://accounts.google.com/o/oauth2/auth",
        "token_uri":"https://accounts.google.com/o/oauth2/token",
        "auth_provider_x509_cert_url":"censored",
        "client_secret":"censored",
        "redirect_uris":["https://localhost/ex/YouTube/index.html"],
        "javascript_origins":["http://localhost"]
    }
}


问:
SBT app with Spark and Cassandra - Symbol 'type <none>.package.DataFrame' is missing from the classpath
I'm trying to create simple Apache Spark application that will connect to Cassandra using Datastax Cassandra connector  and do some operation and am getting error

Symbol 'type <none>.package.DataFrame' is missing from the classpath.

My build.sbt:

```<code>name := "spark-app"
version := "1.0"
scalaVersion := "2.11.11"

libraryDependencies ++= Seq(
  "com.datastax.spark" %% "spark-cassandra-connector" % "2.0.0",
  "org.apache.spark" %% "spark-core" % "2.1.1" % "provided"
)

resolvers += "Spark Packages Repo" at "https://dl.bintray.com/spark-packages/maven"
</code>```

My simple application:

```<code>package com.budgetbakers.be.dwh.spark
import com.datastax.spark.connector._
import org.apache.spark.{SparkConf, SparkContext}

object Distinct {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf(true)
      .set("spark.cassandra.connection.host", "127.0.0.1")

    val sc = new SparkContext(conf)
    println(sc.cassandraTable("ks", "users").select("gender").distinct().collect().mkString(","))
    sc.stop()
  }
}
</code>```

when i try to package project i get following compilation error:

```<code>[error] /.../Distinct.scala:18: Symbol 'type <none>.package.DataFrame' is missing from the classpath.
[error] This symbol is required by 'value com.datastax.spark.connector.package.dataFrame'.
[error] Make sure that type DataFrame is in your classpath and check for conflicting dependencies with `-Ylog-classpath`.
[error] A full rebuild may help if 'package.class' was compiled against an incompatible version of <none>.package.
[error]     println(sc.cassandraTable("ks", "users").select("gender").distinct().collect().mkString(","))
[error]             ^
</code>```

Am I missing something? Maybe there is some dependency conflict?

Versions of apps I use:

cassandra: 3.1

apache spark: 2.1.1

spark cassandra connector: 2.0.0

scala: 2.11

sbt: 0.13.15

sbt assembly plugin: 0.14.0

答: Try adding the spark-sql dependency as well as the core library. For future reference there are example build files here

Body:
I'm trying to create simple Apache Spark application that will connect to Cassandra using Datastax Cassandra connector  and do some operation and am getting error

Symbol 'type <none>.package.DataFrame' is missing from the classpath.

My build.sbt:

name := "spark-app"
version := "1.0"
scalaVersion := "2.11.11"

libraryDependencies ++= Seq(
  "com.datastax.spark" %% "spark-cassandra-connector" % "2.0.0",
  "org.apache.spark" %% "spark-core" % "2.1.1" % "provided"
)

resolvers += "Spark Packages Repo" at "https://dl.bintray.com/spark-packages/maven"

My simple application:

package com.budgetbakers.be.dwh.spark
import com.datastax.spark.connector._
import org.apache.spark.{SparkConf, SparkContext}

object Distinct {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf(true)
      .set("spark.cassandra.connection.host", "127.0.0.1")

    val sc = new SparkContext(conf)
    println(sc.cassandraTable("ks", "users").select("gender").distinct().collect().mkString(","))
    sc.stop()
  }
}

when i try to package project i get following compilation error:

[error] /.../Distinct.scala:18: Symbol 'type <none>.package.DataFrame' is missing from the classpath.
[error] This symbol is required by 'value com.datastax.spark.connector.package.dataFrame'.
[error] Make sure that type DataFrame is in your classpath and check for conflicting dependencies with `-Ylog-classpath`.
[error] A full rebuild may help if 'package.class' was compiled against an incompatible version of <none>.package.
[error]     println(sc.cassandraTable("ks", "users").select("gender").distinct().collect().mkString(","))
[error]             ^

Am I missing something? Maybe there is some dependency conflict?

Versions of apps I use:

cassandra: 3.1

apache spark: 2.1.1

spark cassandra connector: 2.0.0

scala: 2.11

sbt: 0.13.15

sbt assembly plugin: 0.14.0


问:
Removing unknown number of markers each time the function is called [Google Maps API android]
I'm using googles map api for android devices and  I have a function which generate markers all over the map, the function is called every couple of seconds and the markers place may change, therefor I need a way to remove all the irrelevant markers and i don't know how to remove a bunch of them while i don't know how many of them i have.

my function looks like this:

```<code>                        JSONObject counter = jObj.getJSONObject(String.valueOf(x));
                    while (counter.getString("untilwhen")!= "true")
                    {
                        JSONObject lat = jObj.getJSONObject(String.valueOf(x));
                        String latitude = lat.getString("latitude");
                        JSONObject lon = jObj.getJSONObject(String.valueOf(x));
                        String longitude = lon.getString("longitude");
                        LatLng latLng1 = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
                        mMap.addMarker(new MarkerOptions().position(latLng1).title("user"));
                        x = x+1;
                        counter = jObj.getJSONObject(String.valueOf(x));
                    }
</code>```

how can i make mMap.addMarker(new MarkerOptions().position(latLng1).title("user")); remove all the old one and replace them with the new.

hope you understood...

答: You need to keep track of your markers you have on the map. addMarker returns a marker so put that in a list or else call clear() to remove all the markers on your map

Body:
I'm using googles map api for android devices and  I have a function which generate markers all over the map, the function is called every couple of seconds and the markers place may change, therefor I need a way to remove all the irrelevant markers and i don't know how to remove a bunch of them while i don't know how many of them i have.

my function looks like this:

                        JSONObject counter = jObj.getJSONObject(String.valueOf(x));
                    while (counter.getString("untilwhen")!= "true")
                    {
                        JSONObject lat = jObj.getJSONObject(String.valueOf(x));
                        String latitude = lat.getString("latitude");
                        JSONObject lon = jObj.getJSONObject(String.valueOf(x));
                        String longitude = lon.getString("longitude");
                        LatLng latLng1 = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
                        mMap.addMarker(new MarkerOptions().position(latLng1).title("user"));
                        x = x+1;
                        counter = jObj.getJSONObject(String.valueOf(x));
                    }

how can i make mMap.addMarker(new MarkerOptions().position(latLng1).title("user")); remove all the old one and replace them with the new.

hope you understood...


问:
Hint on using a regex lookaround needed
Suppose there is a sequence ...a...b...a...b...c... ,where a,b and c are string constants. And dots represent arbitrary number of some other (not a, b or c) symbols between a,b and c.

I would like to match "a...b...c" a laziest way (the last a-b-c triad), but the regexp engine grabs the bigger "a...b...a...b...c" and goes further.

I tried to use a negative lookahead in forms of a\w+b\w+(?!a)\w+c or a\w+b\w+?(?!a)\w+?c  etc. but didn't succeed so far.

答:
There's no need to use looakarounds for this. Put .* at the beginning of the regexp, and put what you want to match into a capture group:

```<code>.*(a.*b.*c)
</code>```

Then use .group(1) to get the contents of the capture group.

The greedy .* at the beginning makes this find the last triad.

DEMO

Title: Hint on using a regex lookaround needed

Body:
There's no need to use looakarounds for this. Put .* at the beginning of the regexp, and put what you want to match into a capture group:

.*(a.*b.*c)

Then use .group(1) to get the contents of the capture group.

The greedy .* at the beginning makes this find the last triad.

DEMO


问:
Creating CSS from a HTML file
I have an html file which contains many elements:

Course Name

        16. Please
        write below the Course Name in order of preference.

      (Please
        see the "Instructions to Candidate" for list of courses)

```

<p>As can be seen, 1 div has many divs in it. Now I want to create a css file that will contain all the styling of this html page (need not be same). Have to write something in java code. I have the DOM object of this file available to me.</p>

<p>Basically, I want all the styles to be removed from here and will be kept under a CSS file like for div with id = imgElt11289447233738dIi15v css will be:</p>

<pre class="lang-css prettyprint-override"><code>#imgElt11289447233738dIi15v{BORDER-RIGHT: 0px; BORDER-TOP: 0px; Z-INDEX: 1; LEFT: 795px; BORDER-LEFT: 0px; WIDTH: 90px; CURSOR: auto; BORDER-BOTTOM: 0px; POSITION: absolute; TOP: 186px; HEIGHT: 93px}
</code>```

I am don't till this part but since I don't know how many levels of hierarchy of elements will be there is there any way to do the same for all child elements as well?

I used the following code

```<code>public static Document getStyleInCSSfile(Document aoDoc, String aoPathToWrite, String aoFileName) throws ApplicationException {
    String loValue = null;
    String loID = null;
    String lsContent = "";
    Element loRoot = aoDoc.getRootElement();
    List loTempElementList = loRoot.getChildren();
    int liCounter;
    for (liCounter = 0; liCounter < loTempElementList.size(); liCounter++) {
        Element loTemplateEle = (Element) loTempElementList.get(liCounter);
        String loId=loTemplateEle.getAttribute("id").getValue();
        loID = loTemplateEle.getAttributeValue("id");
        if(null != loID)
        {
            loValue = loTemplateEle.getAttributeValue("style");
            if(loValue!=null && loValue.trim().length()>0)
            {
                loTemplateEle.removeAttribute("style");
                lsContent = lsContent.concat("#"+loID+"{"+loValue+"}\n");
            }
        }
    }
    SaveFormOnLocalUtil.writeToFile(aoPathToWrite,aoFileName,lsContent);
    return aoDoc;
}
</code>```

Edit : got to know that some regular expression may help by getting a string of SAX parser object and and using regular expression on it... any idea? any one? how to implement it

答:
is it effective to define a style for each single tag?

if i were you i'd checked if any other tag has the same style and if all elements with one style had the same 'tag_name' i'd used the following:

```<code>tag_name{text-transform:uppercase;text-align:center;}
</code>```

and every element with this tag name (if its' style isn't set in any other way) would have this style.

if there's a lot of different tags with the same style:

```<code>.class_name{text-transform:uppercase;text-align:center;}
</code>```

<tag class="class_name">content</tag>

Title: Creating CSS from a HTML file

Body:
I have an html file which contains many elements:

Course Name

        16. Please
        write below the Course Name in order of preference.

      (Please
        see the "Instructions to Candidate" for list of courses)

As can be seen, 1 div has many divs in it. Now I want to create a css file that will contain all the styling of this html page (need not be same). Have to write something in java code. I have the DOM object of this file available to me.

Basically, I want all the styles to be removed from here and will be kept under a CSS file like for div with id = imgElt11289447233738dIi15v css will be:

#imgElt11289447233738dIi15v{BORDER-RIGHT: 0px; BORDER-TOP: 0px; Z-INDEX: 1; LEFT: 795px; BORDER-LEFT: 0px; WIDTH: 90px; CURSOR: auto; BORDER-BOTTOM: 0px; POSITION: absolute; TOP: 186px; HEIGHT: 93px}

I am don't till this part but since I don't know how many levels of hierarchy of elements will be there is there any way to do the same for all child elements as well?

I used the following code

public static Document getStyleInCSSfile(Document aoDoc, String aoPathToWrite, String aoFileName) throws ApplicationException {
    String loValue = null;
    String loID = null;
    String lsContent = "";
    Element loRoot = aoDoc.getRootElement();
    List loTempElementList = loRoot.getChildren();
    int liCounter;
    for (liCounter = 0; liCounter < loTempElementList.size(); liCounter++) {
        Element loTemplateEle = (Element) loTempElementList.get(liCounter);
        String loId=loTemplateEle.getAttribute("id").getValue();
        loID = loTemplateEle.getAttributeValue("id");
        if(null != loID)
        {
            loValue = loTemplateEle.getAttributeValue("style");
            if(loValue!=null && loValue.trim().length()>0)
            {
                loTemplateEle.removeAttribute("style");
                lsContent = lsContent.concat("#"+loID+"{"+loValue+"}\n");
            }
        }
    }
    SaveFormOnLocalUtil.writeToFile(aoPathToWrite,aoFileName,lsContent);
    return aoDoc;
}

Edit : got to know that some regular expression may help by getting a string of SAX parser object and and using regular expression on it... any idea? any one? how to implement it

Body:
is it effective to define a style for each single tag?

if i were you i'd checked if any other tag has the same style and if all elements with one style had the same 'tag_name' i'd used the following:

tag_name{text-transform:uppercase;text-align:center;}

and every element with this tag name (if its' style isn't set in any other way) would have this style.

if there's a lot of different tags with the same style:

.class_name{text-transform:uppercase;text-align:center;}

<tag class="class_name">content</tag>

ContentLicense: CC BY-SA 2.5


答:
You need to use tempered greedy tokens here in between the three parts.

Imagine a is abc, b is bff and c is cca. Then, you'd use

```<code>(?s)abc(?:(?!abc).)*?bff(?:(?!abc).)*?cca
</code>```

See the regex demo

Details:

(?s) - same as re.S or re.DOTALL modifier, makes . match newlines

abc - a literal string abc or some pattern #1

(?:(?!abc).)*? - any 0+ chars other than newline that does not start an abc sequence, as few as possible

bff - a literal string bff or some pattern #2

(?:(?!abc).)*? - see above

cca - a literal string cca or some pattern #3

Title: Hint on using a regex lookaround needed

Body:
Suppose there is a sequence ...a...b...a...b...c... ,where a,b and c are string constants. And dots represent arbitrary number of some other (not a, b or c) symbols between a,b and c.

I would like to match "a...b...c" a laziest way (the last a-b-c triad), but the regexp engine grabs the bigger "a...b...a...b...c" and goes further.

I tried to use a negative lookahead in forms of a\w+b\w+(?!a)\w+c or a\w+b\w+?(?!a)\w+?c  etc. but didn't succeed so far.

Body:
You need to use tempered greedy tokens here in between the three parts.

Imagine a is abc, b is bff and c is cca. Then, you'd use

(?s)abc(?:(?!abc).)*?bff(?:(?!abc).)*?cca

See the regex demo

Details:

(?s) - same as re.S or re.DOTALL modifier, makes . match newlines

abc - a literal string abc or some pattern #1

(?:(?!abc).)*? - any 0+ chars other than newline that does not start an abc sequence, as few as possible

bff - a literal string bff or some pattern #2

(?:(?!abc).)*? - see above

cca - a literal string cca or some pattern #3


问:
Replicating ng-if with a directive
So I have this directive which will allow use declaratively hide or show elements:

```<code><div cdt-visible-to="Admin,Moderator">...</div>
</code>```

So our HTML becomes as declarative as possible. And this is what our directive looks like:

```<code>eDiscovery.directive('cdtVisibleTo', ['AuthService', function (AuthService) {

    return {

      restrict: 'AE',

      link: function ($scope, elem, attrs) {

        let cdtArray = String(attrs['cdtVisibleTo'] || '')
        .split(/[ ,]+/).map(i => String(i).trim()).filter(i => i);

        let ln = cdtArray.length;

        for (let i = 0; i < ln; i++) {
          let r = cdtArray[i];
          if(AuthService.hasPersona(r)){
            elem.removeAttr('hidden');
            return;
          }
        }

        elem.attr('hidden', 'hidden');

      }
    }
  }]);
</code>```

So this is like a stand-in for ng-show.

My question is - what would a stand-in for ng-if look like?

What is the best way to remove elements from the DOM altogether with an Angular directive?

答:
You can use the .remove() method of Angular element to remove an element from the DOM:
First get the angular element from your elem and then use the remove function

To do this perform:

```<code>angular.element(elem).remove();
</code>```

I guess you want to remove it from the DOM if no one of the the Personas passed to the directive is authorized, so maybe you can use the following code:

```<code>var notAuthorized = false;
for (let i = 0; i < ln; i++) {
  let r = cdtArray[i];
  if(AuthService.hasPersona(r)){
    notAuthorized = true; //A Persona is authorized
    return;
  }
}

if (notAuthorized) {
    angular.element(elem).remove();
}
</code>```

More info & methods of angular.element:
https://docs.angularjs.org/api/ng/function/angular.element

Title: Replicating ng-if with a directive

Body:
So I have this directive which will allow use declaratively hide or show elements:

...

So our HTML becomes as declarative as possible. And this is what our directive looks like:

eDiscovery.directive('cdtVisibleTo', ['AuthService', function (AuthService) {

    return {

      restrict: 'AE',

      link: function ($scope, elem, attrs) {

        let cdtArray = String(attrs['cdtVisibleTo'] || '')
        .split(/[ ,]+/).map(i => String(i).trim()).filter(i => i);

        let ln = cdtArray.length;

        for (let i = 0; i < ln; i++) {
          let r = cdtArray[i];
          if(AuthService.hasPersona(r)){
            elem.removeAttr('hidden');
            return;
          }
        }

        elem.attr('hidden', 'hidden');

      }
    }
  }]);

So this is like a stand-in for ng-show.

My question is - what would a stand-in for ng-if look like?

What is the best way to remove elements from the DOM altogether with an Angular directive?

Body:
You can use the .remove() method of Angular element to remove an element from the DOM:
First get the angular element from your elem and then use the remove function

To do this perform:

angular.element(elem).remove();

I guess you want to remove it from the DOM if no one of the the Personas passed to the directive is authorized, so maybe you can use the following code:

var notAuthorized = false;
for (let i = 0; i < ln; i++) {
  let r = cdtArray[i];
  if(AuthService.hasPersona(r)){
    notAuthorized = true; //A Persona is authorized
    return;
  }
}

if (notAuthorized) {
    angular.element(elem).remove();
}

More info & methods of angular.element:
https://docs.angularjs.org/api/ng/function/angular.element


问:
How to make docker volume update automatically?
I have a dockerfile with the following commands. Nothing fancy. (for context: made from this tutorial)

```<code>FROM node:boron

# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

# Install app dependencies
COPY package.json /usr/src/app/
RUN npm install

# Bundle app source
ADD . /usr/src/app

EXPOSE 8080
CMD [ "npm", "start" ]
</code>```

When I run a build, it all works.

```<code>local:~/projects/tap/ws$ docker build -t test-img .
Sending build context to Docker daemon 13.82 kB
Step 1/8 : FROM node:boron
 ---> 3f3928767182
Step 2/8 : RUN mkdir -p /usr/src/app
 ---> Using cache
 ---> 8ba120374422
Step 3/8 : WORKDIR /usr/src/app
 ---> Using cache
 ---> c6f6cccd7833
Step 4/8 : COPY package.json /usr/src/app/
 ---> Using cache
 ---> 2c7f185c3e3f
Step 5/8 : RUN npm install
 ---> Using cache
 ---> 0197f3d8777b
Step 6/8 : ADD . /usr/src/app
 ---> 6a2df3e80f66
Removing intermediate container 93a56a2721e8
Step 7/8 : EXPOSE 8080
 ---> Running in ff21ca7efd15
 ---> 53cda9fd451f
Removing intermediate container ff21ca7efd15
Step 8/8 : CMD npm start
 ---> Running in 293d99bb9ca3
 ---> b8e026d96ba7
Removing intermediate container 293d99bb9ca3
Successfully built b8e026d96ba7
</code>```

And then it boots up just fine.

```<code>local:~/projects/tap/ws$ docker run -p 49160:8080 -d -v /Users/amflare/projects/tap/ws/test:/user/src/app/test --name test test-img
22ce30a882be992cd245ef3bcb15a945b40c4507d2f56a366b410c12bbe9d801
</code>```

But the mounted volume /usr/src/app/test will not update when I make changes in the host directory. From what I can tell from the documentation, it should just work. The mount exists (see below), and everything built and ran correctly. So I am at a loss. Does anyone know what I am doing wrong?

Since this is the most simple of docker containers, I hope that someone has encountered, and solved this problem before.

```<code>local:~/projects/tap/ws$ docker inspect test

...

Mounts": [
  {
    "Type": "bind",
    "Source": "/Users/amflare/projects/tap/ws/test",
    "Destination": "/user/src/app/test",
    "Mode": "",
    "RW": true,
    "Propagation": ""
  }
],
</code>```

答:
You did just a typo here /user/src/app/test. It should be /usr, not /user. So fix your docker run -v.....

I can see that it is not a typo only in Stack Overflow due to you showed this:

```<code>Mounts": [
  {
    "Type": "bind",
    "Source": "/Users/amflare/projects/tap/ws/test",
    "Destination": "/user/src/app/test",
    "Mode": "",
    "RW": true,
    "Propagation": ""
  }
],
</code>```

Body:
I have a dockerfile with the following commands. Nothing fancy. (for context: made from this tutorial)

FROM node:boron

# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

# Install app dependencies
COPY package.json /usr/src/app/
RUN npm install

# Bundle app source
ADD . /usr/src/app

EXPOSE 8080
CMD [ "npm", "start" ]

When I run a build, it all works.

local:~/projects/tap/ws$ docker build -t test-img .
Sending build context to Docker daemon 13.82 kB
Step 1/8 : FROM node:boron
 ---> 3f3928767182
Step 2/8 : RUN mkdir -p /usr/src/app
 ---> Using cache
 ---> 8ba120374422
Step 3/8 : WORKDIR /usr/src/app
 ---> Using cache
 ---> c6f6cccd7833
Step 4/8 : COPY package.json /usr/src/app/
 ---> Using cache
 ---> 2c7f185c3e3f
Step 5/8 : RUN npm install
 ---> Using cache
 ---> 0197f3d8777b
Step 6/8 : ADD . /usr/src/app
 ---> 6a2df3e80f66
Removing intermediate container 93a56a2721e8
Step 7/8 : EXPOSE 8080
 ---> Running in ff21ca7efd15
 ---> 53cda9fd451f
Removing intermediate container ff21ca7efd15
Step 8/8 : CMD npm start
 ---> Running in 293d99bb9ca3
 ---> b8e026d96ba7
Removing intermediate container 293d99bb9ca3
Successfully built b8e026d96ba7

And then it boots up just fine.

local:~/projects/tap/ws$ docker run -p 49160:8080 -d -v /Users/amflare/projects/tap/ws/test:/user/src/app/test --name test test-img
22ce30a882be992cd245ef3bcb15a945b40c4507d2f56a366b410c12bbe9d801

But the mounted volume /usr/src/app/test will not update when I make changes in the host directory. From what I can tell from the documentation, it should just work. The mount exists (see below), and everything built and ran correctly. So I am at a loss. Does anyone know what I am doing wrong?

Since this is the most simple of docker containers, I hope that someone has encountered, and solved this problem before.

local:~/projects/tap/ws$ docker inspect test

...

Mounts": [
  {
    "Type": "bind",
    "Source": "/Users/amflare/projects/tap/ws/test",
    "Destination": "/user/src/app/test",
    "Mode": "",
    "RW": true,
    "Propagation": ""
  }
],

Body:
You did just a typo here /user/src/app/test. It should be /usr, not /user. So fix your docker run -v.....

I can see that it is not a typo only in Stack Overflow due to you showed this:

Mounts": [
  {
    "Type": "bind",
    "Source": "/Users/amflare/projects/tap/ws/test",
    "Destination": "/user/src/app/test",
    "Mode": "",
    "RW": true,
    "Propagation": ""
  }
],


问:
Change Border Color for DatePicker
I would like to change the border color for the focus state on the DatePicker control.
I took a look at the Default Style Template and didn't see any Focus State for the VisualStateManager.

The only thing I saw was a primitive control for the TextBox as follows:

```<code><controlsPrimitives:DatePickerTextBox x:Name="TextBox" SelectionBackground="{TemplateBinding SelectionBackground}" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}" Grid.Column="0" />
</code>```

How can I change the color for the focus state for the border for the DatePicker... I had no problem changing this color for the TextBox, ComboBox and the CheckBox controls.

Please Help!

答:
You're right, the DatePicker control doesn't have a Focus state for the VisualStateManager. Note that it is possible to add a state group and Focused/Unfocused states for the DatePicker, but that wouldn't be the best approach here.

The template for the DatePicker control contains a DatePickerTextBox control, which, according to MSDN, "represents the text input of a DatePicker".

Looking at the template for the DatePickerTextBox, we find that it has a FocusStates state group, and definitions for both the Unfocused and Focused states. We also find this line:

```<code><Border x:Name="FocusVisual" BorderBrush="#FF6DBDD1" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="1" IsHitTestVisible="False" Opacity="0"/>
</code>```

So as you can see, the default "focused color" is #FF6DBDD1. The Focused state for the DatePickerTextBox sets the Opacity property of this border to 1.

To change the border color for the Focused state, you can create a copy of this template, replacing #FF6DBDD1 with the color you want. Then, create a copy of the DatePicker template, which should specify that the DatePickerTextBox contained within it should use your modified template.

Alternatively, you can create a copy of the DatePickerTextBox template, make the adjustment to the border color, and place this template in a style with TargetType set to DatePickerTextBox:

```<code><Style x:Key="MyStyle1" TargetType="DatePickerTextBox">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="DatePickerTextBox">
                <!-- Modified template for DatePickerTextBox goes here -->
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

Hopefully this is useful to you!

EDIT: Default Template for DatePickerTextBox

Most of the default styles and templates for controls are available on MSDN. However (for whatever reason), DatePickerTextBox is not. If you have a copy of Expression Blend (which I highly recommend if you are working with the appearance of controls; it's invaluable -- download a free trial here), you can do the following:

Right-click on a DatePicker, click "Edit Template -> Edit a Copy...". You'll see the DatePickerTextBox in the "Objects and Timeline" panel. Right-click on that, click "Edit Template -> Edit a Copy..." once more. You can then right-click on the Template in the "Objects and Timeline" panel and click "View XAML."

Again, if you're doing any sort of work like this, I can't recommend Blend highly enough. It will save you so much time in the long run (and you'll learn a ton about XAML, styles, templates, how they all fit together, etc). If you don't have access to it, though, here's the default template for the DatePickerTextBox control:

```<code><Style x:Key="DatePickerTextBoxStyle" TargetType="System_Windows_Controls_Primitives:DatePickerTextBox">
   <Setter Property="VerticalContentAlignment" Value="Center"/>
   <Setter Property="HorizontalContentAlignment" Value="Left"/>
   <Setter Property="Template">
      <Setter.Value>
         <ControlTemplate TargetType="System_Windows_Controls_Primitives:DatePickerTextBox">
            <Grid x:Name="Root">
               <Grid.Resources>
                  <SolidColorBrush x:Key="WatermarkBrush" Color="#FFAAAAAA"/>
               </Grid.Resources>
               <VisualStateManager.VisualStateGroups>
                  <VisualStateGroup x:Name="CommonStates">
                     <VisualStateGroup.Transitions>
                        <VisualTransition GeneratedDuration="0"/>
                        <VisualTransition GeneratedDuration="0:0:0.1" To="MouseOver"/>
                     </VisualStateGroup.Transitions>
                     <VisualState x:Name="Normal"/>
                     <VisualState x:Name="MouseOver">
                        <Storyboard>
                           <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)" Storyboard.TargetName="ContentElement">
                              <SplineColorKeyFrame KeyTime="0" Value="#FF99C1E2"/>
                           </ColorAnimationUsingKeyFrames>
                           <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)" Storyboard.TargetName="ContentElement2">
                              <SplineColorKeyFrame KeyTime="0" Value="#FF99C1E2"/>
                           </ColorAnimationUsingKeyFrames>
                        </Storyboard>
                     </VisualState>
                  </VisualStateGroup>
                  <VisualStateGroup x:Name="WatermarkStates">
                     <VisualStateGroup.Transitions>
                        <VisualTransition GeneratedDuration="0"/>
                     </VisualStateGroup.Transitions>
                     <VisualState x:Name="Unwatermarked"/>
                     <VisualState x:Name="Watermarked">
                        <Storyboard>
                           <DoubleAnimation Duration="0" To="0" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="ContentElement"/>
                           <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="Watermark"/>
                        </Storyboard>
                     </VisualState>
                  </VisualStateGroup>
                  <VisualStateGroup x:Name="FocusStates">
                     <VisualStateGroup.Transitions>
                        <VisualTransition GeneratedDuration="0"/>
                     </VisualStateGroup.Transitions>
                     <VisualState x:Name="Unfocused"/>
                     <VisualState x:Name="Focused">
                        <Storyboard>
                           <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="FocusVisual"/>
                        </Storyboard>
                     </VisualState>
                  </VisualStateGroup>
               </VisualStateManager.VisualStateGroups>
               <Border x:Name="Border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="1" Opacity="1">
                  <Grid x:Name="WatermarkContent" Background="{TemplateBinding Background}">
                     <Border x:Name="ContentElement" BorderBrush="#FFFFFFFF" BorderThickness="1" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}"/>
                     <Border x:Name="ContentElement2" BorderBrush="#FFFFFFFF" BorderThickness="1">
                        <ContentControl x:Name="Watermark" Background="{TemplateBinding Background}" Content="{TemplateBinding Watermark}" Foreground="{StaticResource WatermarkBrush}" FontSize="{TemplateBinding FontSize}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" IsHitTestVisible="False" IsTabStop="False" Opacity="0" Padding="2" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>
                     </Border>
                     <Border x:Name="FocusVisual" BorderBrush="#FF6DBDD1" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="1" IsHitTestVisible="False" Opacity="0"/>
                  </Grid>
               </Border>
            </Grid>
         </ControlTemplate>
      </Setter.Value>
   </Setter>
</Style>
</code>```

Apologies for the length, and many thanks to this thread (which had the same issue).

Title: Change Border Color for DatePicker

Body:
I would like to change the border color for the focus state on the DatePicker control.
I took a look at the Default Style Template and didn't see any Focus State for the VisualStateManager.

The only thing I saw was a primitive control for the TextBox as follows:

<controlsPrimitives:DatePickerTextBox x:Name="TextBox" SelectionBackground="{TemplateBinding SelectionBackground}" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}" Grid.Column="0" />

How can I change the color for the focus state for the border for the DatePicker... I had no problem changing this color for the TextBox, ComboBox and the CheckBox controls.

Please Help!

Body:
You're right, the DatePicker control doesn't have a Focus state for the VisualStateManager. Note that it is possible to add a state group and Focused/Unfocused states for the DatePicker, but that wouldn't be the best approach here.

The template for the DatePicker control contains a DatePickerTextBox control, which, according to MSDN, "represents the text input of a DatePicker".

Looking at the template for the DatePickerTextBox, we find that it has a FocusStates state group, and definitions for both the Unfocused and Focused states. We also find this line:

<Border x:Name="FocusVisual" BorderBrush="#FF6DBDD1" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="1" IsHitTestVisible="False" Opacity="0"/>

So as you can see, the default "focused color" is #FF6DBDD1. The Focused state for the DatePickerTextBox sets the Opacity property of this border to 1.

To change the border color for the Focused state, you can create a copy of this template, replacing #FF6DBDD1 with the color you want. Then, create a copy of the DatePicker template, which should specify that the DatePickerTextBox contained within it should use your modified template.

Alternatively, you can create a copy of the DatePickerTextBox template, make the adjustment to the border color, and place this template in a style with TargetType set to DatePickerTextBox:

<Style x:Key="MyStyle1" TargetType="DatePickerTextBox">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="DatePickerTextBox">
                <!-- Modified template for DatePickerTextBox goes here -->
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Hopefully this is useful to you!

EDIT: Default Template for DatePickerTextBox

Most of the default styles and templates for controls are available on MSDN. However (for whatever reason), DatePickerTextBox is not. If you have a copy of Expression Blend (which I highly recommend if you are working with the appearance of controls; it's invaluable -- download a free trial here), you can do the following:

Right-click on a DatePicker, click "Edit Template -> Edit a Copy...". You'll see the DatePickerTextBox in the "Objects and Timeline" panel. Right-click on that, click "Edit Template -> Edit a Copy..." once more. You can then right-click on the Template in the "Objects and Timeline" panel and click "View XAML."

Again, if you're doing any sort of work like this, I can't recommend Blend highly enough. It will save you so much time in the long run (and you'll learn a ton about XAML, styles, templates, how they all fit together, etc). If you don't have access to it, though, here's the default template for the DatePickerTextBox control:

<Style x:Key="DatePickerTextBoxStyle" TargetType="System_Windows_Controls_Primitives:DatePickerTextBox">
   <Setter Property="VerticalContentAlignment" Value="Center"/>
   <Setter Property="HorizontalContentAlignment" Value="Left"/>
   <Setter Property="Template">
      <Setter.Value>
         <ControlTemplate TargetType="System_Windows_Controls_Primitives:DatePickerTextBox">
            <Grid x:Name="Root">
               <Grid.Resources>
                  <SolidColorBrush x:Key="WatermarkBrush" Color="#FFAAAAAA"/>
               </Grid.Resources>
               <VisualStateManager.VisualStateGroups>
                  <VisualStateGroup x:Name="CommonStates">
                     <VisualStateGroup.Transitions>
                        <VisualTransition GeneratedDuration="0"/>
                        <VisualTransition GeneratedDuration="0:0:0.1" To="MouseOver"/>
                     </VisualStateGroup.Transitions>
                     <VisualState x:Name="Normal"/>
                     <VisualState x:Name="MouseOver">
                        <Storyboard>
                           <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)" Storyboard.TargetName="ContentElement">
                              <SplineColorKeyFrame KeyTime="0" Value="#FF99C1E2"/>
                           </ColorAnimationUsingKeyFrames>
                           <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)" Storyboard.TargetName="ContentElement2">
                              <SplineColorKeyFrame KeyTime="0" Value="#FF99C1E2"/>
                           </ColorAnimationUsingKeyFrames>
                        </Storyboard>
                     </VisualState>
                  </VisualStateGroup>
                  <VisualStateGroup x:Name="WatermarkStates">
                     <VisualStateGroup.Transitions>
                        <VisualTransition GeneratedDuration="0"/>
                     </VisualStateGroup.Transitions>
                     <VisualState x:Name="Unwatermarked"/>
                     <VisualState x:Name="Watermarked">
                        <Storyboard>
                           <DoubleAnimation Duration="0" To="0" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="ContentElement"/>
                           <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="Watermark"/>
                        </Storyboard>
                     </VisualState>
                  </VisualStateGroup>
                  <VisualStateGroup x:Name="FocusStates">
                     <VisualStateGroup.Transitions>
                        <VisualTransition GeneratedDuration="0"/>
                     </VisualStateGroup.Transitions>
                     <VisualState x:Name="Unfocused"/>
                     <VisualState x:Name="Focused">
                        <Storyboard>
                           <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="FocusVisual"/>
                        </Storyboard>
                     </VisualState>
                  </VisualStateGroup>
               </VisualStateManager.VisualStateGroups>
               <Border x:Name="Border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="1" Opacity="1">
                  <Grid x:Name="WatermarkContent" Background="{TemplateBinding Background}">
                     <Border x:Name="ContentElement" BorderBrush="#FFFFFFFF" BorderThickness="1" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}"/>
                     <Border x:Name="ContentElement2" BorderBrush="#FFFFFFFF" BorderThickness="1">
                        <ContentControl x:Name="Watermark" Background="{TemplateBinding Background}" Content="{TemplateBinding Watermark}" Foreground="{StaticResource WatermarkBrush}" FontSize="{TemplateBinding FontSize}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" IsHitTestVisible="False" IsTabStop="False" Opacity="0" Padding="2" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>
                     </Border>
                     <Border x:Name="FocusVisual" BorderBrush="#FF6DBDD1" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="1" IsHitTestVisible="False" Opacity="0"/>
                  </Grid>
               </Border>
            </Grid>
         </ControlTemplate>
      </Setter.Value>
   </Setter>
</Style>

Apologies for the length, and many thanks to this thread (which had the same issue).


问:
Unable to make a UDP request
I am trying to build a BitTorrent client in go. I need to make UDP requests to connect to the various trackers. For this I use the net package and do this:

```<code>net.Dial("udp", "udp://hostname:1337/announce")
</code>```

I get a "too many colons in address" error.

If I try this:

```<code>net.Dial("udp", "hostname:1337/announce")
</code>```

I get a "nodename nor servname provided, or not known" error.

How do I fix this?

答:
So you'll need to send it to the IP address and port as provided by the .torrent metafile (announce field).

And once you open the net.Conn you can conn.Write() to the socket and similarly conn.Read()

So you've just about gotten i:

```<code>    conn, err := net.Dial("udp", announceAddr:Port)
</code>```

When connecting with HTTP, yeah you use the /announce endpoint, but not with UDP

The specs explain how many bytes to read and write (it is fixed at first, but later dynamic when it comes to reading the peer list). I've found this link, rather, the most useful: https://github.com/naim94a/udpt/wiki/The-BitTorrent-UDP-tracker-protocol

Title: Unable to make a UDP request

Body:
I am trying to build a BitTorrent client in go. I need to make UDP requests to connect to the various trackers. For this I use the net package and do this:

net.Dial("udp", "udp://hostname:1337/announce")

I get a "too many colons in address" error.

If I try this:

net.Dial("udp", "hostname:1337/announce")

I get a "nodename nor servname provided, or not known" error.

How do I fix this?

Body:
So you'll need to send it to the IP address and port as provided by the .torrent metafile (announce field).

And once you open the net.Conn you can conn.Write() to the socket and similarly conn.Read()

So you've just about gotten i:

    conn, err := net.Dial("udp", announceAddr:Port)

When connecting with HTTP, yeah you use the /announce endpoint, but not with UDP

The specs explain how many bytes to read and write (it is fixed at first, but later dynamic when it comes to reading the peer list). I've found this link, rather, the most useful: https://github.com/naim94a/udpt/wiki/The-BitTorrent-UDP-tracker-protocol


问:
Closing android application from fragment
I have only one activity in my application with multiple fragments. Whenever a user opens the app, it starts with startupFragment. Whenever user navigate through the fragments and presses  back, it takes him back to startupFragment. But when in the startupFragment, I want user, when clicked back, to be able to close the application. Now, here is the code, when the application is started for creating the fragment.:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Set starting fragment
    StartupFragment startupFragment = new StartupFragment();
    android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().add(R.id.content_main, startupFragment, "startupFragmentTag").commit();

}
</code>```

As you can see, I have added the tag "startupFragmentTag" to be able to identify it. This is my code onBackPressed:

```<code>@Override
public void onBackPressed()
{

    Fragment startup = getFragmentManager().findFragmentByTag("startupFragmentTag");

    if(startup == null) {

        android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
        StartupFragment startupFragment = new StartupFragment();
        manager.beginTransaction().replace(R.id.content_main, startupFragment, "startupFragmentTag").commit();

    } else {

        finish();

    }
}
</code>```

So basically what I tried here, is when user is in another fragment, when the user presses back, it will take him/her back to startupFragment. But when in that fragment, when pressing back again, I want the user to be able to exit the application, which won't happen given the code now.

I find the startupFragment by its tag and check if it exists. If not, it will take back the user to it. But if it exists, user should be able to quit, that why finish() is called.

Does the previous fragments not get destroyed? But that shouldn't be the case, because even if I open the app and instantly press back, it won't exit the app.

What am I doing here wrong?

答:
You're working with fragments, so to finish your app you need to finish the parent activity.

Try this to finish the activity from startupfragment:

```<code>getActivity().finish();
</code>```

Body:
I have only one activity in my application with multiple fragments. Whenever a user opens the app, it starts with startupFragment. Whenever user navigate through the fragments and presses  back, it takes him back to startupFragment. But when in the startupFragment, I want user, when clicked back, to be able to close the application. Now, here is the code, when the application is started for creating the fragment.:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Set starting fragment
    StartupFragment startupFragment = new StartupFragment();
    android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().add(R.id.content_main, startupFragment, "startupFragmentTag").commit();

}

As you can see, I have added the tag "startupFragmentTag" to be able to identify it. This is my code onBackPressed:

@Override
public void onBackPressed()
{

    Fragment startup = getFragmentManager().findFragmentByTag("startupFragmentTag");

    if(startup == null) {

        android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
        StartupFragment startupFragment = new StartupFragment();
        manager.beginTransaction().replace(R.id.content_main, startupFragment, "startupFragmentTag").commit();

    } else {

        finish();

    }
}

So basically what I tried here, is when user is in another fragment, when the user presses back, it will take him/her back to startupFragment. But when in that fragment, when pressing back again, I want the user to be able to exit the application, which won't happen given the code now.

I find the startupFragment by its tag and check if it exists. If not, it will take back the user to it. But if it exists, user should be able to quit, that why finish() is called.

Does the previous fragments not get destroyed? But that shouldn't be the case, because even if I open the app and instantly press back, it won't exit the app.

What am I doing here wrong?

Body:
You're working with fragments, so to finish your app you need to finish the parent activity.

Try this to finish the activity from startupfragment:

getActivity().finish();


问:
Hibernate disconnect proxy when fetch=FetchType.LAZY
```<code>@Entity
public class Master implements Serializable{
private List slaves;
@OneToMany(mappedBy = "Master",fetch=FetchType.LAZY)
public List getSlaves() {
   return slaves;
}
}

I want this code to pass.

List m = createQuery("from Master where id=1").getResultList();
for (Master master : m) {
    assertNull(master.getSlaves());
}
</code>```

I want getSlaves() to return null and not to initialize a proxy to connect to the database(this master has slaves and I dont want to delete them from database).

Is there any way to do that in Hibernate or JPA?

Is there also way of doing that when fetch is EAGER?

答:
Silently failing proxies would be a tricky thing to debug.

After seeing the code of hibernate, I don't think you have an option to configure that. You can try to reflectively call collection.setInitialized(), to pseudo-initialize the collection, but that'd be ugly.

Body:
@Entity
public class Master implements Serializable{
private List slaves;
@OneToMany(mappedBy = "Master",fetch=FetchType.LAZY)
public List getSlaves() {
   return slaves;
}
}

I want this code to pass.

List m = createQuery("from Master where id=1").getResultList();
for (Master master : m) {
    assertNull(master.getSlaves());
}

I want getSlaves() to return null and not to initialize a proxy to connect to the database(this master has slaves and I dont want to delete them from database).

Is there any way to do that in Hibernate or JPA?

Is there also way of doing that when fetch is EAGER?


问:
How to make the "rotating animation" change speed at random. Fidget spinner animation.
I created this animated fidget spinner for a project.

https://jsfiddle.net/e2tt2mao/450/

Right now i am simply rotating the object by using CSS keyframes.

However I was wondering how I would make the speed change more randomly? For example times where its spinning at a slower rate vs times where it spins at a fast rate.

Here is an example of the type of spin animation i would like: https://68.media.tumblr.com/6b689487196da8bea9d540e203f7cd2e/tumblr_oqapg6uMXW1s5laego1_500.gif

```<code>@-webkit-keyframes spinnerRotate
{
    from{-webkit-transform:rotate(0deg);}
    to{-webkit-transform:rotate(360deg);}
}
@-moz-keyframes spinnerRotate
{
    from{-moz-transform:rotate(0deg);}
    to{-moz-transform:rotate(360deg);}
}
@-ms-keyframes spinnerRotate
{
    from{-ms-transform:rotate(0deg);}
    to{-ms-transform:rotate(360deg);}
}
</code>```

答:
One posibility is to nest several containers, and set a different animation for each one - but you can reuse the keyframes between them.

Play with the timing and so and you can get different effects:

div {
   display: inline-block;
}

.inner {
  width: 200px;
  height: 200px;
  background-color: tomato;

}

.container {
   margin: 30px;
   animation: rotate 3s ease-in-out infinite;
}

.container2 {
   animation: rotate 5s ease-in-out infinite;
}

.container3 {
   animation: rotate 7s ease-in-out infinite;
   animation-direction: alternate-reverse;
}

@keyframes rotate {
from {transform: rotate(0deg);}
to {transform: rotate(360deg);}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="container2">
<div class="container3">
<div class="inner">
</div>
</div>
</div>
</div></code>```

Body:
I created this animated fidget spinner for a project.

https://jsfiddle.net/e2tt2mao/450/

Right now i am simply rotating the object by using CSS keyframes.

However I was wondering how I would make the speed change more randomly? For example times where its spinning at a slower rate vs times where it spins at a fast rate.

Here is an example of the type of spin animation i would like: https://68.media.tumblr.com/6b689487196da8bea9d540e203f7cd2e/tumblr_oqapg6uMXW1s5laego1_500.gif

@-webkit-keyframes spinnerRotate
{
    from{-webkit-transform:rotate(0deg);}
    to{-webkit-transform:rotate(360deg);}
}
@-moz-keyframes spinnerRotate
{
    from{-moz-transform:rotate(0deg);}
    to{-moz-transform:rotate(360deg);}
}
@-ms-keyframes spinnerRotate
{
    from{-ms-transform:rotate(0deg);}
    to{-ms-transform:rotate(360deg);}
}

Body:
One posibility is to nest several containers, and set a different animation for each one - but you can reuse the keyframes between them.

Play with the timing and so and you can get different effects:

div {
   display: inline-block;
}

.inner {
  width: 200px;
  height: 200px;
  background-color: tomato;

}

.container {
   margin: 30px;
   animation: rotate 3s ease-in-out infinite;
}

.container2 {
   animation: rotate 5s ease-in-out infinite;
}

.container3 {
   animation: rotate 7s ease-in-out infinite;
   animation-direction: alternate-reverse;
}

@keyframes rotate {
from {transform: rotate(0deg);}
to {transform: rotate(360deg);}
}

<div class="container">
<div class="container2">
<div class="container3">
<div class="inner">
</div>
</div>
</div>
</div>


问:
How do you enable auto-complete functionality in Visual Studio C++ express edition?
Please guide me, how do you enable autocomplete functionality in VS C++? By auto-complete, I mean, when I put a dot after control name, the editor should display a dropdown menu to select from.

Thank you.

答: All the answers were missing Ctrl-J (which enables and disables autocomplete).</p>


问:
How to perform a join based on intervals with dplyr?
I have a data frame containing two columns: a grouping variable and a interval period over which the grouping variable holds. I have another data frame with a date column and a value column. How can I join these two tables together somewhat efficiently with dplyr+tidyverse functions?

```<code>library(dplyr)
library(lubridate)
ty <- data_frame(date = mdy(paste(1, 1 + seq(20), 2017, sep = "/")),
                 y = c(rnorm(7), rnorm(7, mean = 2), rnorm(6, mean = -1)))
gy <- data_frame(period = interval(mdy(c("01/01/2017", "01/08/2017", "01/15/2017")),
                                   mdy(c("01/07/2017", "01/14/2017", "01/20/2017"))),
                          batch = c(1, 2, 3))
</code>```

I want to build the table that is equivalent to:

```<code>ty %>% mutate(batch = c(rep(1, 7), rep(2, 7), rep(3, 6)))
</code>```

Ideally, this should work reasonably quickly on data sets of up to 1,000,000 rows. Better still if it works on 100,000,000 :).

答:
How about:

```<code>ty %>%
  mutate(batch = case_when(
  ty$date %within% gy$period[1] ~gy$batch[1],
  ty$date %within% gy$period[2] ~gy$batch[2],
  ty$date %within% gy$period[3] ~gy$batch[3]))
</code>```

You would obviously need to define the case_when intervals. How many have you got? I've used cat and paste0 with good effect for that in the past.

Edited to reflect OP's comments. This should take care of the NSE and would allow the generation of the case_when intervals programatically:

```<code>ty %>%
  mutate(batch = eval(parse(text = paste0("case_when(",
                                      paste(
                                        paste0(
                                          "ty$date %within% gy$period[",
                                          seq_along(gy$period),
                                          "] ~gy$batch[",
                                          seq_along(gy$period),
                                          "]"
                                        ),
                                        collapse = ", "
                                      ), ")"))))
</code>```

Body:
I have a data frame containing two columns: a grouping variable and a interval period over which the grouping variable holds. I have another data frame with a date column and a value column. How can I join these two tables together somewhat efficiently with dplyr+tidyverse functions?

library(dplyr)
library(lubridate)
ty <- data_frame(date = mdy(paste(1, 1 + seq(20), 2017, sep = "/")),
                 y = c(rnorm(7), rnorm(7, mean = 2), rnorm(6, mean = -1)))
gy <- data_frame(period = interval(mdy(c("01/01/2017", "01/08/2017", "01/15/2017")),
                                   mdy(c("01/07/2017", "01/14/2017", "01/20/2017"))),
                          batch = c(1, 2, 3))

I want to build the table that is equivalent to:

ty %>% mutate(batch = c(rep(1, 7), rep(2, 7), rep(3, 6)))

Ideally, this should work reasonably quickly on data sets of up to 1,000,000 rows. Better still if it works on 100,000,000 :).

Body:
How about:

ty %>%
  mutate(batch = case_when(
  ty$date %within% gy$period[1] ~gy$batch[1],
  ty$date %within% gy$period[2] ~gy$batch[2],
  ty$date %within% gy$period[3] ~gy$batch[3]))

You would obviously need to define the case_when intervals. How many have you got? I've used cat and paste0 with good effect for that in the past.

Edited to reflect OP's comments. This should take care of the NSE and would allow the generation of the case_when intervals programatically:

ty %>%
  mutate(batch = eval(parse(text = paste0("case_when(",
                                      paste(
                                        paste0(
                                          "ty$date %within% gy$period[",
                                          seq_along(gy$period),
                                          "] ~gy$batch[",
                                          seq_along(gy$period),
                                          "]"
                                        ),
                                        collapse = ", "
                                      ), ")"))))


问:
How can I catch two (or more) @ngrx/store actions and hold subscription in components till that happens?
In my main component I starting initialization of my data:

```<code>_store.dispatch(_statusActions.initialize());
</code>```

That triggers all initialization actions:

```<code>@Effect()
loading$ = this.actions$
    .ofType(StatusActions.INITIALIZING)
    .mergeMap(() => Observable.from([
        this._characterActions.initCharacters(),
        this._vehicleActions.initVehicles()
    ]))
</code>```

After data is loaded in the Store, success actions triggeres for all of store entities.

For vehicles:

```<code>@Effect()
loadVehicles$ = this.actions$
    .ofType(VehicleActions.INIT_VEHICLES)
    .switchMap(() => this._vehicleService.getVehicles()
        .map((vehicles: Vehicle[]) => this._vehicleActions.initVehiclesSuccess(vehicles))
        .catch(err => Observable.of(this._statusActions.dataLoadingError('vehicles')))
    );
</code>```

And for characters:

```<code>@Effect()
loadVehicles$ = this.actions$
    .ofType(CharacterActions.INIT_CHARACTERS)
    .switchMap(() => this._characterService.getCharacters())
    .map((characters: Character[]) =>
        this._characterActions.initCharactersSucess(characters))
</code>```

And, finally, after all *_DATA_SUCCESS actions triggered, I want my INITIALIZED action to be triggered to put READY flag in my Storage.

```<code>export const initReducer = (state: boolean = false, action: Action): boolean => {
switch (action.type){
    case StatusActions.INITIALIZING:
        return false;
    case StatusActions.INITIALIZED:
        console.log('App initialized...');
        return true;
    default:
        return state;
}
</code>```

My question - how to perfom that? How to know when all success actions has been triggered?

UPD

Snks mtx, I followed your first and faster adwise.

Sory for extra question, but I realy stuck looking for nice whay to do the
next step. How to hold this subscription (inside component) till my INITIALIZED action will be fired (need to remove this terrible crutch with if(vehicles.length>0) ):

```<code>constructor(
...
) {
  this.vehicles$ = _store.select(s => s.vehicles);
  this.initialized$ = _store.select(s => s.initilized);
}

ngOnInit() {
let id = this._route.snapshot.params.id ? this._route.snapshot.params.id :
null;
this.sub = this.vehicles$.subscribe(vehicles => {
    if (vehicles.length > 0){
      if(id){
        this.vehicle = vehicles.find(item => item.id === Number(id))
      } else {
        this.vehicle = new Vehicle(vehicles[vehicles.length-1].id+1, '');
      }
      this.viewReady = true;
    }
  })
}

ngOnDestroy(){
  this.sub && this.sub.unsubscribe();
}
</code>```

I tried to insert skipUntil() before subscribe(), but now I get problem
opening this component from another one (when all data already loaded). In this case subscribe callback can't fired any more! I can't understend why...

```<code>...
private initDone$ = new Subject<boolean>();
...

this.initialized$.subscribe((init: Init) => {
  if(init.app)
    this.initDone$.next(true);
})

this.sub = this.vehicles$.skipUntil(this.initDone$).subscribe(vehicles => {
    if(id)
      this.vehicle = vehicles.find(item => item.id === Number(id))
    else
      this.vehicle = new Vehicle(vehicles[vehicles.length-1].id+1, '');

    this.viewReady = true;
  });
}
</code>```

To reproduce my problem just press on one of the vehicles in list. Subscribe callback not firing. Then press F5 -> now vehicle loading, beacouse callback was fired as designed.

Full source code is here: GitHub,
last version running on GitHub Pages

答:
I can think of two ways to do this (I'm sure there are other ways):

1. In the reducer

Let the initReducer-state have flags for each request that has to succeed for the ready-flag to be set to true by reducing both *_DATA_SUCCESS actions in the initReducer:

init.reducer.ts

export interface InitState = {
    characterSuccess: boolean,
    vehicleSuccess: boolean,
    ready: boolean
}

const initialState = {
    characterSuccess = false,
    vehicleSuccess = false,
    ready = false
};

export const initReducer (state: InitState = initialState, action: Action): InitState {
    switch (action.type) {
        /* ...
         * other cases, like INITIALIZING or INITIALIZING_ERROR...
         */

        case CharacterActions.CHARACTER_DATA_SUCCESS: {
            /* set characterSuccess to true.
             *
             * if vehicleSuccess is already true
             * this means that both requests completed successfully
             * otherwise ready will stay false until the second request completes
             */
            return Object.assign({}, state, {
                characterSuccess: true
                ready: state.vehicleSuccess
            });
        }

        case VehicleActions.VEHICLE_DATA_SUCCESS: {
            /* set vehicleSuccess to true.
             *
             * if characterSuccess is already true
             * this means that both requests completed successfully
             * otherwise ready will stay false until the second request completes
             */
            return Object.assign({}, state, {
                vehicleSuccess: true,
                ready: state.characterSuccess
            });
        }

        default:
            return state;
    }
}
```

<h2>2. Use selectors</h2>

<p>If you created the <code>initReducer</code> just to track if you are currently initializing, you can omit the whole reducer and use <strong>selectors</strong> that compute a derived state instead.<br>
I like to use the reselect library because it lets you create efficient selectors that only recompute when a change happens (= memoized selectors).</p>

<p>First, add a <code>loading</code>- and <code>ready</code>-flag to the state-shape of both the Vehicles- and the Characters-reducer.<br>
Then, add selector-functions at the reducer level.<br>
Example for VehiclesReducer:</p>

<p><strong>vehicle.reducer.ts</strong>
<em>(Repeat the same for the Characters-reducer)</em></p>

<pre class="lang-js prettyprint-override"><code>export interface VehicleState {
    // vehicle ids and entities etc...
    loading: boolean;
    ready: boolean;
}

const initialState: VehicleState = {
    // other init values
    loading: false,
    ready: false
}

export function reducer(state = initialState, action: Action): VehicleState {
    switch (action.type) {
        // other cases...

        case VehicleActions.INIT_VEHICLES: {
            return Object.assign({}, state, {
                loading: true,
                ready: false
            });
        }

        case VehicleActions.VEHICLE_DATA_SUCCESS: {
            return Object.assign({}, state, {
                /* other reducer logic like
                 * entities: action.payload
                 */
                loading: false,
                ready: true
            });
        }

        default:
            return state;
    }
}

// Selector functions
export const getLoading = (state: VehicleState) => state.loading;
export const getReady = (state: VehicleState) => state.ready;
</code>```

Next, in your root-reducer or in an additional file where you put your selectors, compose selectors that give you the desired derived state:

selectors.ts

import { MyGlobalAppState } from './root.reducer';
import * as fromVehicle from './vehicle.reducer';
import * as fromCharacter from './character.reducer';
import { createSelector } from 'reselect';

// selector for vehicle-state
export const getVehicleState  = (state: MyGlobalAppState) => state.vehicle;
// selector for character-state
export const getCharacterState = (state: MyGlobalAppState) => state.character;

// selectors from vehicle
export const getVehicleLoading = createSelector(getVehicleState, fromVehicle.getLoading);
export const getVehicleReady = createSelector(getVehicleState, fromVehicle.getReady);

// selectors from character
export const getCharacterLoading = createSelector(getCharacterState, fromCharacter.getLoading);
export const getCharacterReady = createSelector(getCharacterState, fromCharacter.getReady);

// combined selectors that will calculate a derived state from both vehicle-state and character-state
export const getLoading = createSelector(getVehicleLoading, getCharacterLoading, (vehicle, character) => {
    return (vehicle || character);
});

export const getReady = createSelector(getVehicleReady, getCharacterReady, (vehicle, character) => {
    return (vehicle && character);
});
```

<p>Now you can use these selector in your component:</p>

<pre class="lang-js prettyprint-override"><code>import * as selectors from './selectors';

let loading$ = this.store.select(selectors.getLoading);
let ready$ = this.store.select(selectors.getReady);

loading$.subscribe(loading => console.log(loading)); // will emit true when requests are still running
ready$.subscribe(ready => console.log(ready)); // will emit true when both requests where successful
</code>```

While this approach may be more verbose, it is cleaner and follows established practices of redux. And you might be able to omit the whole initReducer.

If you haven't used selectors before, it is showcased in the ngrx-example-app.

Regarding the update:

Since you are using the router, you could for example use a router-guard to withhold route activation until initializing is done. Implement the CanActivate interface:

@Injectable()
export class InitializedGuard implements CanActivate {
    constructor(private store: Store<MyGlobalAppState>) { }

    canActivate(): Observable<boolean> {
        return this.store.select(fromRoot.getInitState) // select initialized from store
            .filter(initialized => initialized === true)
            .take(1)
    }
}
```

<p>Then, add the guard to your route:</p>

<pre class="lang-js prettyprint-override"><code>{
    path: 'vehicle/:id',
    component: VehicleComponent,
    canActivate: [ InitializedGuard ]
}
</code>```

Route-activation guards are also showcased in the ngrx-example-app, look here

Body:
In my main component I starting initialization of my data:

_store.dispatch(_statusActions.initialize());

That triggers all initialization actions:

@Effect()
loading$ = this.actions$
    .ofType(StatusActions.INITIALIZING)
    .mergeMap(() => Observable.from([
        this._characterActions.initCharacters(),
        this._vehicleActions.initVehicles()
    ]))

After data is loaded in the Store, success actions triggeres for all of store entities.

For vehicles:

@Effect()
loadVehicles$ = this.actions$
    .ofType(VehicleActions.INIT_VEHICLES)
    .switchMap(() => this._vehicleService.getVehicles()
        .map((vehicles: Vehicle[]) => this._vehicleActions.initVehiclesSuccess(vehicles))
        .catch(err => Observable.of(this._statusActions.dataLoadingError('vehicles')))
    );

And for characters:

@Effect()
loadVehicles$ = this.actions$
    .ofType(CharacterActions.INIT_CHARACTERS)
    .switchMap(() => this._characterService.getCharacters())
    .map((characters: Character[]) =>
        this._characterActions.initCharactersSucess(characters))

And, finally, after all *_DATA_SUCCESS actions triggered, I want my INITIALIZED action to be triggered to put READY flag in my Storage.

export const initReducer = (state: boolean = false, action: Action): boolean => {
switch (action.type){
    case StatusActions.INITIALIZING:
        return false;
    case StatusActions.INITIALIZED:
        console.log('App initialized...');
        return true;
    default:
        return state;
}

My question - how to perfom that? How to know when all success actions has been triggered?

UPD

Snks mtx, I followed your first and faster adwise.

Sory for extra question, but I realy stuck looking for nice whay to do the
next step. How to hold this subscription (inside component) till my INITIALIZED action will be fired (need to remove this terrible crutch with if(vehicles.length>0) ):

constructor(
...
) {
  this.vehicles$ = _store.select(s => s.vehicles);
  this.initialized$ = _store.select(s => s.initilized);
}

ngOnInit() {
let id = this._route.snapshot.params.id ? this._route.snapshot.params.id :
null;
this.sub = this.vehicles$.subscribe(vehicles => {
    if (vehicles.length > 0){
      if(id){
        this.vehicle = vehicles.find(item => item.id === Number(id))
      } else {
        this.vehicle = new Vehicle(vehicles[vehicles.length-1].id+1, '');
      }
      this.viewReady = true;
    }
  })
}

ngOnDestroy(){
  this.sub && this.sub.unsubscribe();
}

I tried to insert skipUntil() before subscribe(), but now I get problem
opening this component from another one (when all data already loaded). In this case subscribe callback can't fired any more! I can't understend why...

...
private initDone$ = new Subject<boolean>();
...

this.initialized$.subscribe((init: Init) => {
  if(init.app)
    this.initDone$.next(true);
})

this.sub = this.vehicles$.skipUntil(this.initDone$).subscribe(vehicles => {
    if(id)
      this.vehicle = vehicles.find(item => item.id === Number(id))
    else
      this.vehicle = new Vehicle(vehicles[vehicles.length-1].id+1, '');

    this.viewReady = true;
  });
}

To reproduce my problem just press on one of the vehicles in list. Subscribe callback not firing. Then press F5 -> now vehicle loading, beacouse callback was fired as designed.

Full source code is here: GitHub,
last version running on GitHub Pages

Body:
I can think of two ways to do this (I'm sure there are other ways):

1. In the reducer

Let the initReducer-state have flags for each request that has to succeed for the ready-flag to be set to true by reducing both *_DATA_SUCCESS actions in the initReducer:

init.reducer.ts

export interface InitState = {
    characterSuccess: boolean,
    vehicleSuccess: boolean,
    ready: boolean
}

const initialState = {
    characterSuccess = false,
    vehicleSuccess = false,
    ready = false
};

export const initReducer (state: InitState = initialState, action: Action): InitState {
    switch (action.type) {
        /* ...
         * other cases, like INITIALIZING or INITIALIZING_ERROR...
         */

        case CharacterActions.CHARACTER_DATA_SUCCESS: {
            /* set characterSuccess to true.
             *
             * if vehicleSuccess is already true
             * this means that both requests completed successfully
             * otherwise ready will stay false until the second request completes
             */
            return Object.assign({}, state, {
                characterSuccess: true
                ready: state.vehicleSuccess
            });
        }

        case VehicleActions.VEHICLE_DATA_SUCCESS: {
            /* set vehicleSuccess to true.
             *
             * if characterSuccess is already true
             * this means that both requests completed successfully
             * otherwise ready will stay false until the second request completes
             */
            return Object.assign({}, state, {
                vehicleSuccess: true,
                ready: state.characterSuccess
            });
        }

        default:
            return state;
    }
}

2. Use selectors

If you created the initReducer just to track if you are currently initializing, you can omit the whole reducer and use selectors that compute a derived state instead.

I like to use the reselect library because it lets you create efficient selectors that only recompute when a change happens (= memoized selectors).

First, add a loading- and ready-flag to the state-shape of both the Vehicles- and the Characters-reducer.

Then, add selector-functions at the reducer level.

Example for VehiclesReducer:

vehicle.reducer.ts
(Repeat the same for the Characters-reducer)

export interface VehicleState {
    // vehicle ids and entities etc...
    loading: boolean;
    ready: boolean;
}

const initialState: VehicleState = {
    // other init values
    loading: false,
    ready: false
}

export function reducer(state = initialState, action: Action): VehicleState {
    switch (action.type) {
        // other cases...

        case VehicleActions.INIT_VEHICLES: {
            return Object.assign({}, state, {
                loading: true,
                ready: false
            });
        }

        case VehicleActions.VEHICLE_DATA_SUCCESS: {
            return Object.assign({}, state, {
                /* other reducer logic like
                 * entities: action.payload
                 */
                loading: false,
                ready: true
            });
        }

        default:
            return state;
    }
}

// Selector functions
export const getLoading = (state: VehicleState) => state.loading;
export const getReady = (state: VehicleState) => state.ready;

Next, in your root-reducer or in an additional file where you put your selectors, compose selectors that give you the desired derived state:

selectors.ts

import { MyGlobalAppState } from './root.reducer';
import * as fromVehicle from './vehicle.reducer';
import * as fromCharacter from './character.reducer';
import { createSelector } from 'reselect';

// selector for vehicle-state
export const getVehicleState  = (state: MyGlobalAppState) => state.vehicle;
// selector for character-state
export const getCharacterState = (state: MyGlobalAppState) => state.character;

// selectors from vehicle
export const getVehicleLoading = createSelector(getVehicleState, fromVehicle.getLoading);
export const getVehicleReady = createSelector(getVehicleState, fromVehicle.getReady);

// selectors from character
export const getCharacterLoading = createSelector(getCharacterState, fromCharacter.getLoading);
export const getCharacterReady = createSelector(getCharacterState, fromCharacter.getReady);

// combined selectors that will calculate a derived state from both vehicle-state and character-state
export const getLoading = createSelector(getVehicleLoading, getCharacterLoading, (vehicle, character) => {
    return (vehicle || character);
});

export const getReady = createSelector(getVehicleReady, getCharacterReady, (vehicle, character) => {
    return (vehicle && character);
});

Now you can use these selector in your component:

import * as selectors from './selectors';

let loading$ = this.store.select(selectors.getLoading);
let ready$ = this.store.select(selectors.getReady);

loading$.subscribe(loading => console.log(loading)); // will emit true when requests are still running
ready$.subscribe(ready => console.log(ready)); // will emit true when both requests where successful

While this approach may be more verbose, it is cleaner and follows established practices of redux. And you might be able to omit the whole initReducer.

If you haven't used selectors before, it is showcased in the ngrx-example-app.

Regarding the update:

Since you are using the router, you could for example use a router-guard to withhold route activation until initializing is done. Implement the CanActivate interface:

@Injectable()
export class InitializedGuard implements CanActivate {
    constructor(private store: Store<MyGlobalAppState>) { }

    canActivate(): Observable<boolean> {
        return this.store.select(fromRoot.getInitState) // select initialized from store
            .filter(initialized => initialized === true)
            .take(1)
    }
}

Then, add the guard to your route:

{
    path: 'vehicle/:id',
    component: VehicleComponent,
    canActivate: [ InitializedGuard ]
}

Route-activation guards are also showcased in the ngrx-example-app, look here


问:
Exception when removing element from HashMap java.util.ConcurrentModificationException
I am trying to write a logic to find the quickest route, the input is given in format "1-2-30#2-3-25#3-4-30#..." which means from station 1 to 2 it will take 30 minutes. In this code when i am recursively calling searchMapKey() function, if the key is not present, then i am getting execption "Exception in thread "main" java.util.ConcurrentModificationException"</p>

```<code>    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.LinkedHashMap;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.Set;
    import java.util.StringTokenizer;

    public class QuickestRoute {
static int totalWeight = 0;

public static String outpit;

public static void main(String[] args) {
    // TODO Auto-generated method stub
    String input1[] = { "1-2-30#2-3-25#3-4-30#4-5-45#5-6-30#6-7-15#7-8-60#8-9-40",
            "10-11-45#11-4-60#4-12-60#12-13-45#13-14-30#14-15-35",
            "1-3-40#3-4-25#4-16-30#16-17-15#17-18-20#18-19-30#19-20-25", "21-12-30#12-17-180#17-22-45" }; };
    String input2 = "12#18";
    String[] output = quickestMetroRoute(input1, input2);
    /*
     * for(int i=0;i<output.length;i++) System.out.println(output[i]);
     */
}

public static String[] quickestMetroRoute(String[] input1, String input2) {
    // Write code here
    Map<String, Integer> input = new HashMap<String, Integer>();
    for (int i = 0; i < input1.length; i++) {
        StringTokenizer str = new StringTokenizer(input1[i], "#");
        while (str.hasMoreTokens()) {
            String[] parts = str.nextToken().split("-");
            String node = parts[0] + "-" + parts[1];
            int weight = Integer.parseInt(parts[2]);
            input.put(node, weight);
        }
    }
     Map<String, Integer> sortedMap = sortByValue(input);
    System.out.println(Collections.singletonList(sortedMap));
    String[] parts = input2.split("#");
    String source = parts[0];
    String destination = parts[1];
    searchMapKey(source, destination, sortedMap);
    /*
     * for (Map.Entry<String, Integer> entry : input.entrySet()) { String
     * key = entry.getKey(); Integer value = entry.getValue(); // ... }
     */
    System.out.println("outpit: " + outpit);
    System.out.println("totalWeight: " + totalWeight);

    return input1;
}

private static void searchMapKey(String source, String destination, Map<String, Integer> input) {
    // TODO Auto-generated method stub
    for (Iterator<Entry<String, Integer>> it = input.entrySet().iterator(); it.hasNext();) {
        Entry<String, Integer> entry = it.next();
        String key = entry.getKey();
        Integer value = entry.getValue();
        // ...
        String[] nodeParts = key.split("-");
        String nodeFirst = nodeParts[0];
        String nodeSecond = nodeParts[1];

        if (nodeFirst.equals(source)) {
            totalWeight += value;
            outpit += key;
            if (destination.equals(nodeSecond)) {
                totalWeight += value;
                outpit += key;
                return;
            } else {
                input.remove(key);
                searchMapKey(nodeSecond, destination, input);
            }
        }
        if (nodeSecond.equals(source)) {
            totalWeight += value;
            outpit += key;
            if (destination.equals(nodeFirst)) {
                totalWeight += value;
                outpit += key;
                return;
            } else {
                input.remove(key);
                searchMapKey(nodeFirst, destination, input);
            }
        }
    }

}

private static Map<String, Integer> sortByValue(Map<String, Integer> unsortMap) {

    // 1. Convert Map to List of Map
    List<Map.Entry<String, Integer>> list =
            new LinkedList<Map.Entry<String, Integer>>(unsortMap.entrySet());

    // 2. Sort list with Collections.sort(), provide a custom Comparator
    //    Try switch the o1 o2 position for a different order
    Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
        public int compare(Map.Entry<String, Integer> o1,
                           Map.Entry<String, Integer> o2) {
            return (o1.getValue()).compareTo(o2.getValue());
        }
    });

    // 3. Loop the sorted list and put it into a new insertion order Map LinkedHashMap
    Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
    for (Map.Entry<String, Integer> entry : list) {
        sortedMap.put(entry.getKey(), entry.getValue());
    }

    /*
    //classic iterator example
    for (Iterator<Map.Entry<String, Integer>> it = list.iterator(); it.hasNext(); ) {
        Map.Entry<String, Integer> entry = it.next();
        sortedMap.put(entry.getKey(), entry.getValue());
    }*/

    return sortedMap;
}

}
</code>```

答:
Modifying a Map while you have a live Iterator on it invalidates the iterator. Depending on the exact contents of the map, you may get a ConcurrentModificationException, as you've seen.

One way to solve this is to make the modifications via the iterator (i.e., call it.remove()) instead of directly on the map (input.remove(key)).

Body:
I am trying to write a logic to find the quickest route, the input is given in format "1-2-30#2-3-25#3-4-30#..." which means from station 1 to 2 it will take 30 minutes. In this code when i am recursively calling searchMapKey() function, if the key is not present, then i am getting execption "Exception in thread "main" java.util.ConcurrentModificationException"

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.LinkedHashMap;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.Set;
    import java.util.StringTokenizer;

    public class QuickestRoute {
static int totalWeight = 0;

public static String outpit;

public static void main(String[] args) {
    // TODO Auto-generated method stub
    String input1[] = { "1-2-30#2-3-25#3-4-30#4-5-45#5-6-30#6-7-15#7-8-60#8-9-40",
            "10-11-45#11-4-60#4-12-60#12-13-45#13-14-30#14-15-35",
            "1-3-40#3-4-25#4-16-30#16-17-15#17-18-20#18-19-30#19-20-25", "21-12-30#12-17-180#17-22-45" }; };
    String input2 = "12#18";
    String[] output = quickestMetroRoute(input1, input2);
    /*
     * for(int i=0;i<output.length;i++) System.out.println(output[i]);
     */
}

public static String[] quickestMetroRoute(String[] input1, String input2) {
    // Write code here
    Map<String, Integer> input = new HashMap<String, Integer>();
    for (int i = 0; i < input1.length; i++) {
        StringTokenizer str = new StringTokenizer(input1[i], "#");
        while (str.hasMoreTokens()) {
            String[] parts = str.nextToken().split("-");
            String node = parts[0] + "-" + parts[1];
            int weight = Integer.parseInt(parts[2]);
            input.put(node, weight);
        }
    }
     Map<String, Integer> sortedMap = sortByValue(input);
    System.out.println(Collections.singletonList(sortedMap));
    String[] parts = input2.split("#");
    String source = parts[0];
    String destination = parts[1];
    searchMapKey(source, destination, sortedMap);
    /*
     * for (Map.Entry<String, Integer> entry : input.entrySet()) { String
     * key = entry.getKey(); Integer value = entry.getValue(); // ... }
     */
    System.out.println("outpit: " + outpit);
    System.out.println("totalWeight: " + totalWeight);

    return input1;
}

private static void searchMapKey(String source, String destination, Map<String, Integer> input) {
    // TODO Auto-generated method stub
    for (Iterator<Entry<String, Integer>> it = input.entrySet().iterator(); it.hasNext();) {
        Entry<String, Integer> entry = it.next();
        String key = entry.getKey();
        Integer value = entry.getValue();
        // ...
        String[] nodeParts = key.split("-");
        String nodeFirst = nodeParts[0];
        String nodeSecond = nodeParts[1];

        if (nodeFirst.equals(source)) {
            totalWeight += value;
            outpit += key;
            if (destination.equals(nodeSecond)) {
                totalWeight += value;
                outpit += key;
                return;
            } else {
                input.remove(key);
                searchMapKey(nodeSecond, destination, input);
            }
        }
        if (nodeSecond.equals(source)) {
            totalWeight += value;
            outpit += key;
            if (destination.equals(nodeFirst)) {
                totalWeight += value;
                outpit += key;
                return;
            } else {
                input.remove(key);
                searchMapKey(nodeFirst, destination, input);
            }
        }
    }

}

private static Map<String, Integer> sortByValue(Map<String, Integer> unsortMap) {

    // 1. Convert Map to List of Map
    List<Map.Entry<String, Integer>> list =
            new LinkedList<Map.Entry<String, Integer>>(unsortMap.entrySet());

    // 2. Sort list with Collections.sort(), provide a custom Comparator
    //    Try switch the o1 o2 position for a different order
    Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
        public int compare(Map.Entry<String, Integer> o1,
                           Map.Entry<String, Integer> o2) {
            return (o1.getValue()).compareTo(o2.getValue());
        }
    });

    // 3. Loop the sorted list and put it into a new insertion order Map LinkedHashMap
    Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
    for (Map.Entry<String, Integer> entry : list) {
        sortedMap.put(entry.getKey(), entry.getValue());
    }

    /*
    //classic iterator example
    for (Iterator<Map.Entry<String, Integer>> it = list.iterator(); it.hasNext(); ) {
        Map.Entry<String, Integer> entry = it.next();
        sortedMap.put(entry.getKey(), entry.getValue());
    }*/

    return sortedMap;
}

}


问:
Can I make a class with an `__exit__` method but not an `__enter__` method?
I have a class that needs to run a TensorFlow session for each instance of the class, as long as that instance exists.

TensorFlow sessions use context managers, but I don't want to force anyone who uses my class to put my class into a context manager.

Is there any way to auto-close the session once the instance is no longer in use without using a context manager?

Can I just put in an __exit__ method and not an __enter__ method and start the session without the context manager and just close the session in the exit?

答:
Is there any way to auto-close the session once the instance is no longer in use without using a context manager?

Not really, how would an object figure out when it’s no longer being used? If there was a safe way to do this, there wouldn’t be a need for context managers in the first place.

So you have to use context managers and the with statement to get this kind of feedback. But just because you have to use context managers, that does not mean that you actually need to have some separate “thing” you open. You can return anything in the __enter__ method, including the current object.

So the simplest context manager implementation that closes itself when the context is closed looks like this:

```<code>class MyClass:
    def __enter__ (self):
        return self

    def __exit__ (self, *exc):
        self.close()

    def close (self):
        # actually close the object
</code>```

In fact, this pattern is so common, that there is a built-in recipe for this context manager: contextlib.closing. Using that, you do not actually need to modify your class at all, you can just wrap it in a closing() call and have it call close when the context is exited:

```<code>with closing(my_object):
    my_object.do_something()

# my_object.close() is automatically called
</code>```

Body:
Is there any way to auto-close the session once the instance is no longer in use without using a context manager?

Not really, how would an object figure out when it’s no longer being used? If there was a safe way to do this, there wouldn’t be a need for context managers in the first place.

So you have to use context managers and the with statement to get this kind of feedback. But just because you have to use context managers, that does not mean that you actually need to have some separate “thing” you open. You can return anything in the __enter__ method, including the current object.

So the simplest context manager implementation that closes itself when the context is closed looks like this:

class MyClass:
    def __enter__ (self):
        return self

    def __exit__ (self, *exc):
        self.close()

    def close (self):
        # actually close the object

In fact, this pattern is so common, that there is a built-in recipe for this context manager: contextlib.closing. Using that, you do not actually need to modify your class at all, you can just wrap it in a closing() call and have it call close when the context is exited:

with closing(my_object):
    my_object.do_something()

# my_object.close() is automatically called


问:
Can't figure out how to display output
This might sound like a simple thing for you programmers out there but i can't seem to figure it out. I'm making a program that converts Decimal Numbers into Roman Numerals. I've got the core code working but i can't seem to think how i can display the results on the screen. I would like it so that when the user types a number into a text box the result appears in another text box at the press of a button. Thanks for your time & help.

```<code><html>
<head>
  <meta charset="UTF-8">
  <script src="Main.js" type="text/javascript"></script>
  <link href="Main.css" rel="stylesheet" type="text/css"/>
</head>
<body>
        <form id="Awesome">
        <label>Input Text Here: </label><input type="text" id="txtBox">
        <br><br>
        <label>Dec to Roman #: </label><input type="text" id="Results">
        <br><br>
        <input type="button" value="Calculate" id="Execute">

        </div>
        </form>
</body>
</html>
</code>```

Javascript

```<code>function convertToRoman(num) {
var romans = {
M:  1000,
CM: 900,
D:  500,
CD: 400,
C:  100,
XC: 90,
L:  50,
XL: 40,
X:  10,
IX: 9,
V:  5,
IV: 4,
I:  1,
};

var result = '';

for (var key in romans) {
if (num >= romans[key]) {
    result += key.repeat(Math.trunc(num / romans[key]));
    num -= romans[key] * Math.trunc(num / romans[key]);
}
}

return result;

}
</code>```

答:
use document.getElementById() method, pass the input id there.
Then for the result, you can set it with .value to your result.

To grab the num: var num = document.getElementById('txtBox').value;

To display the result: document.getElementById('Results').value = result;

A basic functional example of this with your code, here: https://jsfiddle.net/4czkfrnd/

Title: Can't figure out how to display output

Body:
This might sound like a simple thing for you programmers out there but i can't seem to figure it out. I'm making a program that converts Decimal Numbers into Roman Numerals. I've got the core code working but i can't seem to think how i can display the results on the screen. I would like it so that when the user types a number into a text box the result appears in another text box at the press of a button. Thanks for your time & help.

  <meta charset="UTF-8">

  <link href="Main.css" rel="stylesheet" type="text/css"/>

        <form id="Awesome">
        Input Text Here: <input type="text" id="txtBox">

        Dec to Roman #: <input type="text" id="Results">

        <input type="button" value="Calculate" id="Execute">

        </form>

Javascript

function convertToRoman(num) {
var romans = {
M:  1000,
CM: 900,
D:  500,
CD: 400,
C:  100,
XC: 90,
L:  50,
XL: 40,
X:  10,
IX: 9,
V:  5,
IV: 4,
I:  1,
};

var result = '';

for (var key in romans) {
if (num >= romans[key]) {
    result += key.repeat(Math.trunc(num / romans[key]));
    num -= romans[key] * Math.trunc(num / romans[key]);
}
}

return result;

}


问:
Library to recognize Dutch dates in text?
I have a series of strings (in Dutch) that contain a date in either a DD-MM-YYYY format or in a textual format DD month YYYY. See an example selection here: https://paste.ee/p/XZLha. I'm looking for a Python (2.7) library that is able to recognize the date from these text strings.

dateutil is not able to properly parse Dutch

dateparser is not able to parse fuzzy strings - it only accepts strings with dates and days. It can handle Dutch dates though.

I'd like to get your input on possible solutions. I'm considering stripping the text around the dates away and working with dateparser.

答: The built-in datetime module's datetime.strpdate() can parse dates in a number of formats, including locale-specific ones. You still need to extract a date from the text first - either with a regex of some other means of analysis (e.g. maybe they are in some known, very specific parts of the text).