问:
Scala Lazy Val Question
I have a scenario where I have some objects that need to take in references from each other.  The only way I can get this to compile is to use lazy

```<code>class A(b:B)
class B(a:A)
lazy val a:A = new A(b)
lazy val b:B = new B(a)
</code>```

I can do the same thing using some actors, and get it to compile also

```<code>    abstract class Message
    case class Message1 extends Message
    case class Message2 extends Message

    class Actor1(otherActor:Actor) extends Actor {
        def act() {
            loop {
                react {
                    case Message1 =>
                        println("received message1")
                        otherActor ! Message2
                    case _ =>
                }
            }
        }
    }

    class Actor2(otherActor:Actor) extends Actor {
        def act() {
            loop {
                react {
                    case Message2 =>
                        println("received message2")
                        otherActor ! Message1
                    case _ =>
                }
            }
        }
    }

    lazy val actor1:Actor = new Actor1(actor2)
    lazy val actor2:Actor = new Actor2(actor1)
</code>```

However, when I add the following:

```<code>    actor1.start
    actor2.start
    actor1 ! Message1
</code>```

I get the following error:

Exception in thread "main"
  java.lang.NoClassDefFoundError:
  com/fictitiousCompany/stackOverflowQuestion/Test
  Caused by:
  java.lang.ClassNotFoundException:
  com.fictitiousCompany.stackOverflowQuestion.Test
    at
  java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at
  java.security.AccessController.doPrivileged(Native
  Method)   at
  java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at
  java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at
  sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at
  java.lang.ClassLoader.loadClass(ClassLoader.java:248)

I'm using the Scala Eclipse Plugin 2.8.1.

答:
Note that even your smaller example would have issues (in the REPL):

```<code>{
class A(b:B)
class B(a:A)
lazy val a:A = new A(b)
lazy val b:B = new B(a)
a
}
// causes stack overflow error
</code>```

As soon as a needs to be evaluated therefore constructed, it would require B, which requires A. In order for this to work a or b would have to finish being constructed.

Using by-name parameters allows the smaller example to evaluate.

```<code>{
class A(b: => B)
class B(a: => A)
lazy val a:A = new A(b)
lazy val b:B = new B(a)
a
}
</code>```

Note sure if that'll work for your actor example as well.

Edit: by name params worked locally on 2.8.0. I replaced case class with object to get rid of some deprecation warnings and added start methods on actor1, actor2 and kick the whole thing with actor1 ! Message1. Aside from this I haven't used actor before, so I can't comment more. Here is what I tested:

```<code>import scala.actors._

abstract class Message
object Message1 extends Message
object Message2 extends Message

class Actor1(otherActor: => Actor) extends Actor {
def act() {
    loop {
    react {
        case Message1 =>
        println("received message1")
        otherActor ! Message2
        case _ =>
    }
    }
}
}

class Actor2(otherActor: => Actor) extends Actor {
def act() {
    loop {
    react {
        case Message2 =>
        println("received message2")
        otherActor ! Message1
        case _ =>
    }
    }
}
}

{
  lazy val actor1:Actor = new Actor1(actor2)
  lazy val actor2:Actor = new Actor2(actor1)
  actor1.start
  actor2.start
  actor1 ! Message1
}
</code>```

Prints a bunch of:

```<code>received message1
received message2
</code>```

Title: Scala Lazy Val Question

Body:
I have a scenario where I have some objects that need to take in references from each other.  The only way I can get this to compile is to use lazy

class A(b:B)
class B(a:A)
lazy val a:A = new A(b)
lazy val b:B = new B(a)

I can do the same thing using some actors, and get it to compile also

    abstract class Message
    case class Message1 extends Message
    case class Message2 extends Message

    class Actor1(otherActor:Actor) extends Actor {
        def act() {
            loop {
                react {
                    case Message1 =>
                        println("received message1")
                        otherActor ! Message2
                    case _ =>
                }
            }
        }
    }

    class Actor2(otherActor:Actor) extends Actor {
        def act() {
            loop {
                react {
                    case Message2 =>
                        println("received message2")
                        otherActor ! Message1
                    case _ =>
                }
            }
        }
    }

    lazy val actor1:Actor = new Actor1(actor2)
    lazy val actor2:Actor = new Actor2(actor1)

However, when I add the following:

    actor1.start
    actor2.start
    actor1 ! Message1

I get the following error:

Exception in thread "main"
  java.lang.NoClassDefFoundError:
  com/fictitiousCompany/stackOverflowQuestion/Test
  Caused by:
  java.lang.ClassNotFoundException:
  com.fictitiousCompany.stackOverflowQuestion.Test
    at
  java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at
  java.security.AccessController.doPrivileged(Native
  Method)   at
  java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at
  java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at
  sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at
  java.lang.ClassLoader.loadClass(ClassLoader.java:248)

I'm using the Scala Eclipse Plugin 2.8.1.

Body:
Note that even your smaller example would have issues (in the REPL):

{
class A(b:B)
class B(a:A)
lazy val a:A = new A(b)
lazy val b:B = new B(a)
a
}
// causes stack overflow error

As soon as a needs to be evaluated therefore constructed, it would require B, which requires A. In order for this to work a or b would have to finish being constructed.

Using by-name parameters allows the smaller example to evaluate.

{
class A(b: => B)
class B(a: => A)
lazy val a:A = new A(b)
lazy val b:B = new B(a)
a
}

Note sure if that'll work for your actor example as well.

Edit: by name params worked locally on 2.8.0. I replaced case class with object to get rid of some deprecation warnings and added start methods on actor1, actor2 and kick the whole thing with actor1 ! Message1. Aside from this I haven't used actor before, so I can't comment more. Here is what I tested:

import scala.actors._

abstract class Message
object Message1 extends Message
object Message2 extends Message

class Actor1(otherActor: => Actor) extends Actor {
def act() {
    loop {
    react {
        case Message1 =>
        println("received message1")
        otherActor ! Message2
        case _ =>
    }
    }
}
}

class Actor2(otherActor: => Actor) extends Actor {
def act() {
    loop {
    react {
        case Message2 =>
        println("received message2")
        otherActor ! Message1
        case _ =>
    }
    }
}
}

{
  lazy val actor1:Actor = new Actor1(actor2)
  lazy val actor2:Actor = new Actor2(actor1)
  actor1.start
  actor2.start
  actor1 ! Message1
}

Prints a bunch of:

received message1
received message2


来源: stackexchange

问:
Where is a singleton instance stored in ninject?
The title has it all.  When I do this:

```<code>var kernel = new StandardKernel();
kernel.Bind<IMyClass>().To<MyClass>().InSingletonScope();
var myClass = kernel.Get<IMyClass>();
</code>```

Where is the instance of MyClass stored?  Is it stored in a static dictionary somewhere globally?  Or is it stored in the kernel instance?

For example if I do this:

```<code>var kernel1 = new StandardKernel();
var kernel2 = new StandardKernel();
kernel1.Bind<IMyClass>().To<MyClass>().InSingletonScope();
kernel2.Bind<IMyClass>().To<MyClass>().InSingletonScope();
var myClass1 = kernel1.Get<IMyClass>();
var myClass2 = kernel2.Get<IMyClass>();
</code>```

Will myClass1 be the same instance as myClass2 or will they be different instances.

To kind of jump on an inevitable question "Why do you need to do that?":  It doesn't matter.  That is not the point of the question.  I have my reasons and just want to know how this piece works.

答:
For others that are wondering:  It stores it outside of the kernel.  You will get the same instance with both kernels.

Edit - Test I ran to come to this conclusion:

```<code>var kernel1 = new StandardKernel();
var kernel2 = new StandardKernel();
kernel1.Bind<IMyClass>().To<MyClass>().InSingletonScope();
kernel2.Bind<IMyClass>().To<MyClass>().InSingletonScope();
var myClass1 = kernel1.Get<IMyClass>();
var myClass2 = kernel2.Get<IMyClass>();
var same = myClass1 == myClass2;
Console.WriteLine(same ? "Same" : "Different");
</code>```

Output: Same

Edit Again:
I must have had a typo because I tested again and got "Different".

ContentLicense: CC BY-SA 3.0

Body:
The title has it all.  When I do this:

var kernel = new StandardKernel();
kernel.Bind<IMyClass>().To<MyClass>().InSingletonScope();
var myClass = kernel.Get<IMyClass>();

Where is the instance of MyClass stored?  Is it stored in a static dictionary somewhere globally?  Or is it stored in the kernel instance?

For example if I do this:

var kernel1 = new StandardKernel();
var kernel2 = new StandardKernel();
kernel1.Bind<IMyClass>().To<MyClass>().InSingletonScope();
kernel2.Bind<IMyClass>().To<MyClass>().InSingletonScope();
var myClass1 = kernel1.Get<IMyClass>();
var myClass2 = kernel2.Get<IMyClass>();

Will myClass1 be the same instance as myClass2 or will they be different instances.

To kind of jump on an inevitable question "Why do you need to do that?":  It doesn't matter.  That is not the point of the question.  I have my reasons and just want to know how this piece works.

Body:
For others that are wondering:  It stores it outside of the kernel.  You will get the same instance with both kernels.

Edit - Test I ran to come to this conclusion:

var kernel1 = new StandardKernel();
var kernel2 = new StandardKernel();
kernel1.Bind<IMyClass>().To<MyClass>().InSingletonScope();
kernel2.Bind<IMyClass>().To<MyClass>().InSingletonScope();
var myClass1 = kernel1.Get<IMyClass>();
var myClass2 = kernel2.Get<IMyClass>();
var same = myClass1 == myClass2;
Console.WriteLine(same ? "Same" : "Different");

Output: Same

Edit Again:
I must have had a typo because I tested again and got "Different".


问:
What and where are the stack and heap?

What are the stack and heap?

Where are they located physically in a computer's memory?

To what extent are they controlled by the OS or language run-time?

What is their scope?

What determines their sizes?

What makes one faster?

答:
I have something to share, although the major points are already covered.

Stack

Very fast access.

Stored in RAM.

Function calls are loaded here along with the local variables and function parameters passed.

Space is freed automatically when program goes out of a scope.

Stored in sequential memory.

Heap

Slow access comparatively to Stack.

Stored in RAM.

Dynamically created variables are stored here, which later requires freeing the allocated memory after use.

Stored wherever memory allocation is done, accessed by pointer always.

Interesting note:

Should the function calls had been stored in heap, it would had resulted in 2 messy points:

Due to sequential storage in stack, execution is faster. Storage in heap would have resulted in huge time consumption thus making the whole program execute slower.

If functions were stored in heap (messy storage pointed by pointer), there would have been no way to return to the caller address back (which stack gives due to sequential storage in memory).

OwnerDisplayName: matt

ContentLicense: CC BY-SA 4.0

Title: What and where are the stack and heap?


问:
jqte text editor is changing html tags
I am using jqte as a text editor with my CodeIgniter application however when I save the content it's converting the tags which I don't want it to do.

For example, I would like it like this:

```<code><p>Lorum ipsum<br />dolor simit</p>
</code>```

but instead it is changing to this:

```<code><p>Lorum ipsum<br>dolor simit<p>
</code>```

How do I convert it back?

答:
In php you can use</p>

```<code><?php
 echo htmlspecialchars_decode($your_string);
?>
</code>```

Title: jqte text editor is changing html tags

Body:
I am using jqte as a text editor with my CodeIgniter application however when I save the content it's converting the tags which I don't want it to do.

For example, I would like it like this:

Lorum ipsum
dolor simit

but instead it is changing to this:

Lorum ipsum
dolor simit

How do I convert it back?

Body:
In php you can use

<?php
 echo htmlspecialchars_decode($your_string);
?>


问:
Possibility to cancel Observable in Angular 2 typescript with a button click and trigger a new one
I have three buttons in my UI. Each Button would trigger an Observable to a different backend server endpoint.

For example:

Button 1 : HTTP GET Observable to https://endpoint1.something?params=whatever

Button 2:  HTTP GET Observable to https://endpoint2.something?params=whatever

..

Description

Each of the Blue buttons would need to trigger three different Endpoints and would provide user some autocompletion below the input box after clicking the respective button (instance, when hasProperty button is clicked <hasProperty> is shown and any suggestions are show below).

Problem

After I select for example hasSeatBeltand then go ahead to click the hasValue button I still get Suggestions from the previous hasProperty Observable

Is there any way to Cancel the Previous Observable when on clicks on the other Buttons?

Code Snippets

component.html (input box +  + space for Observable data)

```<code><div class="row">
        <div class="col-12">
            <h5>Your Semantic Query</h5>
            <code>
                {{sentence | json}}
            </code>
            <div class="form-group">
                <form class="form-inline">
                    <input type="search" class="form-control"
                           [(ngModel)] = "sentence"
                           [formControl]="searchField"
                           (keydown)="selected = false; true;"
                    #searchbox style="width: 500px;">
                </form>
            </div>
            <div>
                <p class="lead" *ngIf="loading">Loading...</p>
            </div>
            <ul class="list-group ac-keywords" *ngIf="searchField.value !== '' && !selected">
                <li class="list-group-item"
                    *ngFor="let eachProp of results | async" (click)="searchbox.value = eachProp.translated; selected=true; sentence=sentence+eachProp.translated;"
                >
                    {{eachProp.translated}}
                </li>
            </ul>
        </div>
    </div>
</code>```

component.html (button) area

```<code><div class="btn-group">
                    <li>
                        <button class="btn btn-primary btn-lg"
                                (click)="hasPropertyRelation('hasProperty')"> hasProperty </button>
                    </li>
                    <li>
                        <button class="btn btn-primary btn-lg"
                                (click)="hasValueRelation('hasValue')"> hasValue </button>
                    </li>
                    <li>
                        <button class="btn btn-primary btn-lg" #refBtn
                                (click)="hasReferenceRelation('hasReference')"> hasReference </button>
                    </li>
                    <li *ngFor="let eachButton of objectRelationsButton['listOfSQP']">
                        <button class="btn btn-warning btn-lg" #objBtn (click)="objectPropRelation(eachButton)">
                            {{eachButton}}
                        </button>
                    </li>
                </div>]
</code>```

component.ts

```<code>    private loading: boolean = false;
    public objectRelationsButton: Object = {};
    public sentence: any;
    private results: Observable<SearchItem[]>;
    private searchField: FormControl;
    selected: boolean = false;
    @Input() configSPQ: Object;
    @Input() lang: string;
    constructor(private backendCall: backednCallService) {}

    ngOnInit(): void {
        this.searchField = new FormControl();
        // get the yellow buttons from server..
        let dummyJSON = this.configSPQ;
        this.backendCall.getSQPButton(dummyJSON)
            .then(res => this.objectRelationsButton = res);
        this.sentence = this.configSPQ['frozenConcept'];
    }

    // Blue hasProperty Button
    hasPropertyRelation(inputVal: string) {
       // add text dynamically
       this.sentence += ' <' + inputVal + '> ';
        // HTTP Observable
        this.results = this.searchField.valueChanges
            .debounceTime(400)
            .distinctUntilChanged()
            .do( _ => this.loading = true)
            .switchMap(term =>
                this.expSearch.searchForProperty(this.configSPQ)
            )
            .do( _ => this.loading = false);
    }

    // hasValue Blue Button
    hasValueRelation(inputVal: string) {
        // CANCEL PREVIOUS OBSERVABLE MAYBE HERE
        this.sentence += ' <' + inputVal + '> ';
    }

    hasReferenceRelation(inputVal: string) {
        this.sentence += ' <' + inputVal + '> ';
    }

    objectPropRelation(inputVal: string) {
        this.sentence += ' <' + inputVal + '> ';
    }
</code>```

答:
If you emit to .switchMap it will cancel the previous http observable if you emit a new value. There are a few different ways you could do this, and I would do it by merging the valueChanges observable with an observable you can emit a value to and then switchMap and subscribe to that.

```<code>results$ = this.searchField.valueChanges.debounceTime(400).distinctUntilChanged();
cancel$ = new BehaviorSubject(false);

...
this.results = this.results$.merge(this.cancel$).do(() => this.loading = true)
  .switchMap(term => {
    if (term) {
      return this.expSearch.searchForProperty(this.configSPQ);
    }
    return of();
  })
  .do(() => this.loading = false);
</code>```

Then in the other buttons, you can do this.cancel$.next(false) in order to cancel the current http search.

Body:
I have three buttons in my UI. Each Button would trigger an Observable to a different backend server endpoint.

For example:

Button 1 : HTTP GET Observable to https://endpoint1.something?params=whatever

Button 2:  HTTP GET Observable to https://endpoint2.something?params=whatever

..

Description

Each of the Blue buttons would need to trigger three different Endpoints and would provide user some autocompletion below the input box after clicking the respective button (instance, when hasProperty button is clicked <hasProperty> is shown and any suggestions are show below).

Problem

After I select for example hasSeatBeltand then go ahead to click the hasValue button I still get Suggestions from the previous hasProperty Observable

Is there any way to Cancel the Previous Observable when on clicks on the other Buttons?

Code Snippets

component.html (input box +  + space for Observable data)

Your Semantic Query

                {{sentence | json}}

                <form class="form-inline">
                    <input type="search" class="form-control"
                           [(ngModel)] = "sentence"
                           [formControl]="searchField"
                           (keydown)="selected = false; true;"
                    #searchbox style="width: 500px;">
                </form>

Loading...

                    {{eachProp.translated}}

component.html (button) area

                        <button class="btn btn-primary btn-lg"
                                (click)="hasPropertyRelation('hasProperty')"> hasProperty </button>

                        <button class="btn btn-primary btn-lg"
                                (click)="hasValueRelation('hasValue')"> hasValue </button>

                        <button class="btn btn-primary btn-lg" #refBtn
                                (click)="hasReferenceRelation('hasReference')"> hasReference </button>

                        <button class="btn btn-warning btn-lg" #objBtn (click)="objectPropRelation(eachButton)">
                            {{eachButton}}
                        </button>

]

component.ts

    private loading: boolean = false;
    public objectRelationsButton: Object = {};
    public sentence: any;
    private results: Observable<SearchItem[]>;
    private searchField: FormControl;
    selected: boolean = false;
    @Input() configSPQ: Object;
    @Input() lang: string;
    constructor(private backendCall: backednCallService) {}

    ngOnInit(): void {
        this.searchField = new FormControl();
        // get the yellow buttons from server..
        let dummyJSON = this.configSPQ;
        this.backendCall.getSQPButton(dummyJSON)
            .then(res => this.objectRelationsButton = res);
        this.sentence = this.configSPQ['frozenConcept'];
    }

    // Blue hasProperty Button
    hasPropertyRelation(inputVal: string) {
       // add text dynamically
       this.sentence += ' <' + inputVal + '> ';
        // HTTP Observable
        this.results = this.searchField.valueChanges
            .debounceTime(400)
            .distinctUntilChanged()
            .do( _ => this.loading = true)
            .switchMap(term =>
                this.expSearch.searchForProperty(this.configSPQ)
            )
            .do( _ => this.loading = false);
    }

    // hasValue Blue Button
    hasValueRelation(inputVal: string) {
        // CANCEL PREVIOUS OBSERVABLE MAYBE HERE
        this.sentence += ' <' + inputVal + '> ';
    }

    hasReferenceRelation(inputVal: string) {
        this.sentence += ' <' + inputVal + '> ';
    }

    objectPropRelation(inputVal: string) {
        this.sentence += ' <' + inputVal + '> ';
    }

Body:
If you emit to .switchMap it will cancel the previous http observable if you emit a new value. There are a few different ways you could do this, and I would do it by merging the valueChanges observable with an observable you can emit a value to and then switchMap and subscribe to that.

results$ = this.searchField.valueChanges.debounceTime(400).distinctUntilChanged();
cancel$ = new BehaviorSubject(false);

...
this.results = this.results$.merge(this.cancel$).do(() => this.loading = true)
  .switchMap(term => {
    if (term) {
      return this.expSearch.searchForProperty(this.configSPQ);
    }
    return of();
  })
  .do(() => this.loading = false);

Then in the other buttons, you can do this.cancel$.next(false) in order to cancel the current http search.


问:
Asp.Net MVC Routing and URL Issue
Firstly, thank you for your answers. I have a problem about routing on Asp.Net MVC.

You can see my solution here on the photo where my controllers and views located. I would like to open "UserProfile.cshtml" from "Index.cshtml". Well, my first approach is using Ajax to post "UserProfile Action" in ProfileController.

```<code> $.ajax({
        url: "/Profile/UserProfile",
        type: "POST",
        dataType: "json"})
           .done(function(response){
               window.location = '/Profile/UserProfile'});
</code>```

this code blocks goes to controller and hits the "UserProfile" Action but returns no error and no view. Even URL doesn't change.

```<code>   public ActionResult UserProfile()
    {
       return View ();
    }
</code>```

I would highly appreciate your helpful answers and support. Thank you!

答:
First, you need to have Razor (.cshtml) views, not aspx for mvc to be able to serve these pages out of the box. If you have a controller action named UserProfile in a ProfileController and call return View(), then mvc will be default try to return the view located at Views/Profile/UserProfile.cshtml (it will actually also check a couple other locations such as the Views/Shared/ folder for the view). The following should work for you:

```<code>//located in ProfileController
[HttpPost]
public ActionResult UserProfile()
{
   return View();
}

//located at Views/Profile/UserProfile.cshtml
`<h4>you've found your user profile page!</h4>`
</code>```

If you're trying to hit this view by ajax- then you'll need to attack the problem from a slightly different direction. Redirecting on the server side will not work with ajax since it is asynchronous. You can achieve this by using the .done() ajax callback something like the following:

```<code> $.ajax({
     url: "/Profile/UserProfile",
     type: "POST",
     dataType: "json"
 }).done(function(response){
     window.location = '/Profile/UserProfile'
 });
</code>```

Title: Asp.Net MVC Routing and URL Issue

Body:
Firstly, thank you for your answers. I have a problem about routing on Asp.Net MVC.

You can see my solution here on the photo where my controllers and views located. I would like to open "UserProfile.cshtml" from "Index.cshtml". Well, my first approach is using Ajax to post "UserProfile Action" in ProfileController.

 $.ajax({
        url: "/Profile/UserProfile",
        type: "POST",
        dataType: "json"})
           .done(function(response){
               window.location = '/Profile/UserProfile'});

this code blocks goes to controller and hits the "UserProfile" Action but returns no error and no view. Even URL doesn't change.

   public ActionResult UserProfile()
    {
       return View ();
    }

I would highly appreciate your helpful answers and support. Thank you!

Body:
First, you need to have Razor (.cshtml) views, not aspx for mvc to be able to serve these pages out of the box. If you have a controller action named UserProfile in a ProfileController and call return View(), then mvc will be default try to return the view located at Views/Profile/UserProfile.cshtml (it will actually also check a couple other locations such as the Views/Shared/ folder for the view). The following should work for you:

//located in ProfileController
[HttpPost]
public ActionResult UserProfile()
{
   return View();
}

//located at Views/Profile/UserProfile.cshtml
`<h4>you've found your user profile page!</h4>`

If you're trying to hit this view by ajax- then you'll need to attack the problem from a slightly different direction. Redirecting on the server side will not work with ajax since it is asynchronous. You can achieve this by using the .done() ajax callback something like the following:

 $.ajax({
     url: "/Profile/UserProfile",
     type: "POST",
     dataType: "json"
 }).done(function(response){
     window.location = '/Profile/UserProfile'
 });


问:
ggplot place facet between two rows of facets
I have 9 plots with 3 time series in each plot, one of these plots contains only one curve and it's the reference plot which I would like to place in between the two rows that contain the other 8 plots. Is there an easy way to do so?
I use facet_wrap(~density,nrow=2) but I get one row with 5 and another with 4 plots. I am sure other people had this problem, is there an easy way around to organize the position of this reference plot, or do I have to create two separate plots and overlay them? Otherwise I might have to move this reference plot in all the other plots but it seems redundant information.

This is my current result, but as you can see it's not very well laid out.

答:
The graphic you are looking for can be generated with gridArrange from the
gridExtra package.  Here is
an example using the storms data set from the
dplyr.

```<code>library(ggplot2)
library(gridExtra)
library(dplyr)
data(storms, package = 'dplyr')
str(storms)

## Classes 'tbl_df', 'tbl' and 'data.frame':    10010 obs. of  13 variables:
##  $ name       : chr  "Amy" "Amy" "Amy" "Amy" ...
##  $ year       : num  1975 1975 1975 1975 1975 ...
##  $ month      : num  6 6 6 6 6 6 6 6 6 6 ...
##  $ day        : int  27 27 27 27 28 28 28 28 29 29 ...
##  $ hour       : num  0 6 12 18 0 6 12 18 0 6 ...
##  $ lat        : num  27.5 28.5 29.5 30.5 31.5 32.4 33.3 34 34.4 34 ...
##  $ long       : num  -79 -79 -79 -79 -78.8 -78.7 -78 -77 -75.8 -74.8 ...
##  $ status     : chr  "tropical depression" "tropical depression" "tropical depression" "tropical depression" ...
##  $ category   : Ord.factor w/ 7 levels "-1"<"0"<"1"<"2"<..: 1 1 1 1 1 1 1 1 2 2 ...
##  $ wind       : int  25 25 25 25 25 25 25 30 35 40 ...
##  $ pressure   : int  1013 1013 1013 1013 1012 1012 1011 1006 1004 1002 ...
##  $ ts_diameter: num  NA NA NA NA NA NA NA NA NA NA ...
##  $ hu_diameter: num  NA NA NA NA NA NA NA NA NA NA ...
</code>```

Let's create two graphics. The first graphic will be only form category == -1
storms (this would be the control group in your question).  The second
graphic will be a facteted graphic for the category > -1 storm

First, we'll build a generic ggplot object for the graphics.

```<code>graphic <-
  ggplot() +
  aes(x = long, y = lat, color = category) +
  geom_point() +
  facet_wrap( ~ category) +
  scale_color_hue(breaks = levels(storms$category),
                  labels = levels(storms$category),
                  drop = FALSE)
</code>```

Next we build the two graphics as needed.

```<code>g1 <- graphic %+% dplyr::filter(storms, category == -1) + theme(legend.position = "none")
g2 <- graphic %+% dplyr::filter(storms, category != -1)
</code>```

gridExtra::grid.arrange can take a layout matrix where the numbers 1 and 2
denote the first and second graphics passed to the function.  (This works for
a lot more than just two graphics, by the way.)  By repeating the values of 1
and 2 in the matrix we can control the relative size of the two graphics in
the graphics device.

```<code>gridExtra::grid.arrange(g1, g2,
                        layout_matrix =
                          matrix(c(1, 1, 1, 2, 2, 2, 2, 2,
                                   1, 1, 1, 2, 2, 2, 2, 2,
                                   1, 1, 1, 2, 2, 2, 2, 2),
                                 byrow = TRUE, nrow = 3)
                        )
</code>```

Body:
The graphic you are looking for can be generated with gridArrange from the
gridExtra package.  Here is
an example using the storms data set from the
dplyr.

library(ggplot2)
library(gridExtra)
library(dplyr)
data(storms, package = 'dplyr')
str(storms)

## Classes 'tbl_df', 'tbl' and 'data.frame':    10010 obs. of  13 variables:
##  $ name       : chr  "Amy" "Amy" "Amy" "Amy" ...
##  $ year       : num  1975 1975 1975 1975 1975 ...
##  $ month      : num  6 6 6 6 6 6 6 6 6 6 ...
##  $ day        : int  27 27 27 27 28 28 28 28 29 29 ...
##  $ hour       : num  0 6 12 18 0 6 12 18 0 6 ...
##  $ lat        : num  27.5 28.5 29.5 30.5 31.5 32.4 33.3 34 34.4 34 ...
##  $ long       : num  -79 -79 -79 -79 -78.8 -78.7 -78 -77 -75.8 -74.8 ...
##  $ status     : chr  "tropical depression" "tropical depression" "tropical depression" "tropical depression" ...
##  $ category   : Ord.factor w/ 7 levels "-1"<"0"<"1"<"2"<..: 1 1 1 1 1 1 1 1 2 2 ...
##  $ wind       : int  25 25 25 25 25 25 25 30 35 40 ...
##  $ pressure   : int  1013 1013 1013 1013 1012 1012 1011 1006 1004 1002 ...
##  $ ts_diameter: num  NA NA NA NA NA NA NA NA NA NA ...
##  $ hu_diameter: num  NA NA NA NA NA NA NA NA NA NA ...

Let's create two graphics. The first graphic will be only form category == -1
storms (this would be the control group in your question).  The second
graphic will be a facteted graphic for the category > -1 storm

First, we'll build a generic ggplot object for the graphics.

graphic <-
  ggplot() +
  aes(x = long, y = lat, color = category) +
  geom_point() +
  facet_wrap( ~ category) +
  scale_color_hue(breaks = levels(storms$category),
                  labels = levels(storms$category),
                  drop = FALSE)

Next we build the two graphics as needed.

g1 <- graphic %+% dplyr::filter(storms, category == -1) + theme(legend.position = "none")
g2 <- graphic %+% dplyr::filter(storms, category != -1)

gridExtra::grid.arrange can take a layout matrix where the numbers 1 and 2
denote the first and second graphics passed to the function.  (This works for
a lot more than just two graphics, by the way.)  By repeating the values of 1
and 2 in the matrix we can control the relative size of the two graphics in
the graphics device.

gridExtra::grid.arrange(g1, g2,
                        layout_matrix =
                          matrix(c(1, 1, 1, 2, 2, 2, 2, 2,
                                   1, 1, 1, 2, 2, 2, 2, 2,
                                   1, 1, 1, 2, 2, 2, 2, 2),
                                 byrow = TRUE, nrow = 3)
                        )


问:
Reference master page stored at root from sub domain folder in asp.net
I have a folder in the root called secure and I have a sub domain called secure which maps to the secure folder. However, I'm getting the following error:
 The virtual path '/MasterPage.master' maps to another application, which is not allowed.

Is there a setting somewhere that I can change or some other way to make this work without making a masterpage within the secure folder that has the same data as the root version?

答:
Can you post your IIS setup a little clearer please. From your description it sounds like you have:

http://yourserver (root)

http://yourserver/secure (folder) [is this an application or just a folder?]

http://secure.yourserver (sub-domain) [maps to same folder as http://yourserver/secure]

EDIT

You could store your master pages in a folder

http://yourserver/layouts/MasterPage.master

Then map that folder to your second web site

http://secure.yourserver/layouts

http://secure.yourserver/layouts/MasterPage.master

Then update your page master references to "layouts/MasterPage.master"

ContentLicense: CC BY-SA 2.5


问:
Unable to change to landscape mode in android
Since I made a lot of changes to the app, I am starting this thread to reflect them.  I am still having problems changing orientation.

Here's the code

```<code>Activity

    package com.flash;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.util.Log;

public class QuizActivity extends Activity {

private static final String TAG = "QuizActivity";

private Button mTrueButton;
private Button mFalseButton;
private ImageButton mPrevButton;
private ImageButton mNextButton;
private TextView mQuestionTextView;

private TrueFalse[] mQuestionBank;
private int mCurrentIndex = 0;

/**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(TAG, "onCreate(Bundle)");
    setQuestionBank();
    if (getResources().getConfiguration().orientation
            == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
        setContentView(R.layout.activity_quiz);
        ProcessPortrait();
    } else {
        if (getResources().getConfiguration().orientation
            == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
        setContentView(R.layout.mainland);
        ProcessLandscape();
        }
    }
}

private void ProcessPortrait() {
    mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
    mQuestionTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();
        }
    });
    updateQuestion();

    mTrueButton = (Button) findViewById(R.id.true_button);
    mTrueButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkAnswer(true);
        }
    });

    mFalseButton = (Button) findViewById(R.id.false_button);
    mFalseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkAnswer(false);
        }
    });

    mPrevButton = (ImageButton) findViewById(R.id.prev_button);
    mPrevButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mCurrentIndex == 0) {
                mCurrentIndex = mQuestionBank.length - 1;
            } else {
                mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
            }
            updateQuestion();
        }
    });

    mNextButton = (ImageButton) findViewById(R.id.next_button);
    mNextButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();
        }
    });
}

private void ProcessLandscape() {
    mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
    mQuestionTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();
        }
    });
    updateQuestion();

    mTrueButton = (Button) findViewById(R.id.true_button);
    mTrueButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkAnswer(true);
        }
    });

    mFalseButton = (Button) findViewById(R.id.false_button);
    mFalseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkAnswer(false);
        }
    });

    mNextButton = (ImageButton) findViewById(R.id.next_button);
    mNextButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();
        }
    });
}

private void setQuestionBank() {
    mQuestionBank = new TrueFalse[]{
        new TrueFalse(R.string.question_oceans, true),
        new TrueFalse(R.string.question_mideast, false),
        new TrueFalse(R.string.question_africa, false),
        new TrueFalse(R.string.question_americas, true),
        new TrueFalse(R.string.question_asia, true)
    };
}

private void updateQuestion() {
    int question = mQuestionBank[mCurrentIndex].getmQuestion();
    mQuestionTextView.setText(question);
}

private void checkAnswer(boolean userPressedTrue) {
    boolean answerIsTrue = mQuestionBank[mCurrentIndex].ismTrueQuestion();

    int messageResId = 0;

    if (userPressedTrue == answerIsTrue) {
        messageResId = R.string.correct_Toast;
    } else {
        messageResId = R.string.incorrect_Toast;
    }

    Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show();
}

@Override
public void onStart() {
    super.onStart();
    Log.d(TAG, "onStart() called");
}

@Override
public void onPause() {
    super.onPause();
    Log.d(TAG, "onStart() called");
}

@Override
public void onResume() {
    super.onResume();
    Log.d(TAG, "onResume() called");
}

@Override
public void onStop() {
    super.onStop();
    Log.d(TAG, "onStop() called");
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.d(TAG, "onDestroy() called");
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    if (getResources().getConfiguration().orientation
            == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
        setContentView(R.layout.main);
        ProcessPortrait();
    } else if (getResources().getConfiguration().orientation
            == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
        setContentView(R.layout.mainland);
        ProcessLandscape();
    }
}
</code>```

}

```<code>XML

Portrait

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:gravity="center"
          android:orientation="vertical">

    <TextView
        android:id="@+id/question_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="24dp"
        android:textSize="10sp"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/true_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:text="@string/true_button" />

        <Button
            android:id="@+id/false_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:text="@string/false_button" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageButton
            android:id="@+id/prev_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:contentDescription="@string/prev_button"
            android:src="@drawable/arrow_left"/>

        <ImageButton
            android:id="@+id/next_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:contentDescription="@string/next_button"
            android:src="@drawable/arrow_right"/>

        </LinearLayout>

    </LinearLayout>
</code>```

Landscape

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="match_parent"
             android:layout_height="match_parent">

    <TextView
        android:id="@+id/question_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:padding="24dp"
        android:textSize="10sp"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/true_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:text="@string/true_button" />

        <Button
            android:id="@+id/false_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:text="@string/false_button" />

    </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_vertical|center_horizontal"
            android:orientation="horizontal">

            <ImageButton
                android:id="@+id/next_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="10sp"
                android:contentDescription="@string/next_button"
                android:gravity="bottom|right"
                android:src="@drawable/arrow_right"/>

        </LinearLayout>

    </FrameLayout>

Manifest

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.flash"
        android:versionCode="1"
        android:versionName="1.0"
    >
        <application android:label="@string/app_name"
                 android:icon="@drawable/ic_launcher" >
            <activity android:name=".QuizActivity"
                  android:label="@string/app_name"
                  android:configChanges="orientation|
        keyboardHidden|screenSize">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    </manifest>
</code>```

When I debug using my phone, landscape works, although it may by my phone that is adjusting to the new orientation and not the app.

I am currently unable to get the debugger to work when using the emulator, so that is an issue I need help with as well.

When I run/debug the app, the home page displays and I have to press the recent apps button on the emulator and then double click on the app to bring it forward, hmmm, yet another issue.

Anyway, any help will be greatly appreciated

答:
I installed some updates to the android sdk and when I ran the app, I got a message saying that the ant build xml imported from my project directory could not be found. Tried several things to correct. Waste of time. I decided to go back to using Android Studio, and now the app works in both landscape and portrait, each having their own layout.

Thanks everyone for all your help. We almost had it. My advice to netbeans is to stabilize their platform, as just about anything a developer does breaks it.

This question is officially closed

Body:
Since I made a lot of changes to the app, I am starting this thread to reflect them.  I am still having problems changing orientation.

Here's the code

Activity

    package com.flash;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.util.Log;

public class QuizActivity extends Activity {

private static final String TAG = "QuizActivity";

private Button mTrueButton;
private Button mFalseButton;
private ImageButton mPrevButton;
private ImageButton mNextButton;
private TextView mQuestionTextView;

private TrueFalse[] mQuestionBank;
private int mCurrentIndex = 0;

/**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(TAG, "onCreate(Bundle)");
    setQuestionBank();
    if (getResources().getConfiguration().orientation
            == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
        setContentView(R.layout.activity_quiz);
        ProcessPortrait();
    } else {
        if (getResources().getConfiguration().orientation
            == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
        setContentView(R.layout.mainland);
        ProcessLandscape();
        }
    }
}

private void ProcessPortrait() {
    mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
    mQuestionTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();
        }
    });
    updateQuestion();

    mTrueButton = (Button) findViewById(R.id.true_button);
    mTrueButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkAnswer(true);
        }
    });

    mFalseButton = (Button) findViewById(R.id.false_button);
    mFalseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkAnswer(false);
        }
    });

    mPrevButton = (ImageButton) findViewById(R.id.prev_button);
    mPrevButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mCurrentIndex == 0) {
                mCurrentIndex = mQuestionBank.length - 1;
            } else {
                mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
            }
            updateQuestion();
        }
    });

    mNextButton = (ImageButton) findViewById(R.id.next_button);
    mNextButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();
        }
    });
}

private void ProcessLandscape() {
    mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
    mQuestionTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();
        }
    });
    updateQuestion();

    mTrueButton = (Button) findViewById(R.id.true_button);
    mTrueButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkAnswer(true);
        }
    });

    mFalseButton = (Button) findViewById(R.id.false_button);
    mFalseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkAnswer(false);
        }
    });

    mNextButton = (ImageButton) findViewById(R.id.next_button);
    mNextButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();
        }
    });
}

private void setQuestionBank() {
    mQuestionBank = new TrueFalse[]{
        new TrueFalse(R.string.question_oceans, true),
        new TrueFalse(R.string.question_mideast, false),
        new TrueFalse(R.string.question_africa, false),
        new TrueFalse(R.string.question_americas, true),
        new TrueFalse(R.string.question_asia, true)
    };
}

private void updateQuestion() {
    int question = mQuestionBank[mCurrentIndex].getmQuestion();
    mQuestionTextView.setText(question);
}

private void checkAnswer(boolean userPressedTrue) {
    boolean answerIsTrue = mQuestionBank[mCurrentIndex].ismTrueQuestion();

    int messageResId = 0;

    if (userPressedTrue == answerIsTrue) {
        messageResId = R.string.correct_Toast;
    } else {
        messageResId = R.string.incorrect_Toast;
    }

    Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show();
}

@Override
public void onStart() {
    super.onStart();
    Log.d(TAG, "onStart() called");
}

@Override
public void onPause() {
    super.onPause();
    Log.d(TAG, "onStart() called");
}

@Override
public void onResume() {
    super.onResume();
    Log.d(TAG, "onResume() called");
}

@Override
public void onStop() {
    super.onStop();
    Log.d(TAG, "onStop() called");
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.d(TAG, "onDestroy() called");
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    if (getResources().getConfiguration().orientation
            == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
        setContentView(R.layout.main);
        ProcessPortrait();
    } else if (getResources().getConfiguration().orientation
            == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
        setContentView(R.layout.mainland);
        ProcessLandscape();
    }
}

}

XML

Portrait

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:gravity="center"
          android:orientation="vertical">

    <TextView
        android:id="@+id/question_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="24dp"
        android:textSize="10sp"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/true_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:text="@string/true_button" />

        <Button
            android:id="@+id/false_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:text="@string/false_button" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageButton
            android:id="@+id/prev_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:contentDescription="@string/prev_button"
            android:src="@drawable/arrow_left"/>

        <ImageButton
            android:id="@+id/next_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:contentDescription="@string/next_button"
            android:src="@drawable/arrow_right"/>

        </LinearLayout>

    </LinearLayout>

Landscape

    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="match_parent"
             android:layout_height="match_parent">

    <TextView
        android:id="@+id/question_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:padding="24dp"
        android:textSize="10sp"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/true_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:text="@string/true_button" />

        <Button
            android:id="@+id/false_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            android:text="@string/false_button" />

    </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_vertical|center_horizontal"
            android:orientation="horizontal">

            <ImageButton
                android:id="@+id/next_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="10sp"
                android:contentDescription="@string/next_button"
                android:gravity="bottom|right"
                android:src="@drawable/arrow_right"/>

        </LinearLayout>

    </FrameLayout>

Manifest

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.flash"
        android:versionCode="1"
        android:versionName="1.0"
    >
        <application android:label="@string/app_name"
                 android:icon="@drawable/ic_launcher" >
            <activity android:name=".QuizActivity"
                  android:label="@string/app_name"
                  android:configChanges="orientation|
        keyboardHidden|screenSize">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    </manifest>

When I debug using my phone, landscape works, although it may by my phone that is adjusting to the new orientation and not the app.

I am currently unable to get the debugger to work when using the emulator, so that is an issue I need help with as well.

When I run/debug the app, the home page displays and I have to press the recent apps button on the emulator and then double click on the app to bring it forward, hmmm, yet another issue.

Anyway, any help will be greatly appreciated


问:
How to use event like (onSelect) instead of (change)

because for (change) event to trigger , We  need to change the selected data in UI. Can we use EventEmitter for this. I want one event which gets triggered when we select one or more elements. Thanks

<select multiple (change)="setSelected($event.target)">
    <option *ngFor="#item of myOptions" [value]="item.value">{{item.name}}</option>
</select>

```<code>export class myClass {
...
myOptions: [];
...
setSelected(selectElement) {
    for (var i = 0; i < selectElement.options.length; i++) {
        var optionElement = selectElement.options[i];
        var optionModel = this.myOptions[i];

        if (optionElement.selected == true) { optionModel.selected = true; }
        else { optionModel.selected = false; }
    }
}
</code>```

}

答:
As others have said you can achieve this with ngModel

```<code><select multiple [(ngModel)]="selectedOptions" (change)="getSelected()">
    <option *ngFor="let item of myOptions" [value]="item.value">
        {{item.name}}
    </option>
</select>
</code>```

selectedOptions is an array of the selected option values in your dropdown. You can use the change event or the ngModelChange event to detect when 1 or multiple options are selected.

Here is a stackblitz demonstrating this (https://stackblitz.com/edit/angular-bvchcj?file=app%2Fapp.component.html)

Body:
because for (change) event to trigger , We  need to change the selected data in UI. Can we use EventEmitter for this. I want one event which gets triggered when we select one or more elements. Thanks

<select multiple (change)="setSelected($event.target)">
    <option *ngFor="#item of myOptions" [value]="item.value">{{item.name}}</option>
</select>

export class myClass {
...
myOptions: [];
...
setSelected(selectElement) {
    for (var i = 0; i < selectElement.options.length; i++) {
        var optionElement = selectElement.options[i];
        var optionModel = this.myOptions[i];

        if (optionElement.selected == true) { optionModel.selected = true; }
        else { optionModel.selected = false; }
    }
}

}

Body:
As others have said you can achieve this with ngModel

<select multiple [(ngModel)]="selectedOptions" (change)="getSelected()">
    <option *ngFor="let item of myOptions" [value]="item.value">
        {{item.name}}
    </option>
</select>

selectedOptions is an array of the selected option values in your dropdown. You can use the change event or the ngModelChange event to detect when 1 or multiple options are selected.

Here is a stackblitz demonstrating this (https://stackblitz.com/edit/angular-bvchcj?file=app%2Fapp.component.html)


问:
This if statement is not even working correctly
```<code>if string in secret_word:
    print("Good!")
else:
    print("Bad...")
</code>```

I'm trying to check if a letter is a word like this:

if A is in the word Apple then it will return Good! But if it is not, it will return Bad...

It also says that it is a TypeError and not an indentation error.

答:
This is a problem with your indentation. You can learn about indentation here: https://docs.python.org/2.0/ref/indentation.html and on the web. To get your code working do the following:</p>

```<code>string = "A"
secret_word = "Apple"

if string in secret_word:
    print("Good!")
else:
    print("Bad...")
</code>```

Body:
if string in secret_word:
    print("Good!")
else:
    print("Bad...")

I'm trying to check if a letter is a word like this:

if A is in the word Apple then it will return Good! But if it is not, it will return Bad...

It also says that it is a TypeError and not an indentation error.

Body:
This is a problem with your indentation. You can learn about indentation here: https://docs.python.org/2.0/ref/indentation.html and on the web. To get your code working do the following:

string = "A"
secret_word = "Apple"

if string in secret_word:
    print("Good!")
else:
    print("Bad...")


问:
AngularJS and Shadow DOM
I'm developing a web component form.
I'm having troubles with angularjs bootsrap.

I'm creating dinamically a custom element with form.createdCallback <form> and <input, textarea etc> and adding ng-app="", ng-controller="" attributes.
Later I encapsule it with template.createShadowRoot()

I use document.addEventListener('DOMContentLoaded', function(){angular.bootstrap(document, ['mform'])}), but doing this not execute anything from my angular app...

So, I tried removing the line template.createShadowRoot() and angular execute everything pretty well... so I arrived to the conclusion that the problem is angular not compiling inside shadow dom.

There's any hack or way to do this?

答:
I'm not sure if this really answers your question, but I am able to get Shadow DOM to work in Angular 1.x. Be aware that if you are after CSS encapsulation, then this will only work on browsers that natively support Shadow DOM since the Polyfill can not do the same thing.

I use $compile to create the contents of the Shadow DOM and bind that back into the directive.

Here is my code example:

```<code><!DOCTYPE html>
<html ng-app="app">
  <head>
    <meta charset="utf-8">
    <title>Angular 1.x ShadowDOM example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
    <script>
    var app = angular.module('app', []);

    app.controller('myElController', ($scope) => {

    });

    var template = `
    <style>
    :host {
      left: 50%;
      position: fixed;
      top: 50%;
      transform: translate(-50%,-50%);
      border: 1px solid black;
      box-shadow: 4px 4px 4px rgba(0,0,0,.4);
      display: inline-block;
      padding: 6px 12px;
    }

    h3 {
      border-bottom: 1px solid #999;
      margin: 0 -12px 8px;
      padding: 0 12px 8px;
    }

    p {
      margin: 0;
    }
    </style>
        <h3>{{title}}</h3>
      <p>{{info}}</p>
    `;

    app.directive('myEl', ($compile) => {
        return {
          "restrict": "E",
          "controller": "myElController",
          "template": '',
          "scope": {
            "title": "@",
            "info": "@"
          },
          "link": function($scope, $element) {
            console.log('here');
            $scope.shadowRoot = $element[0].attachShadow({mode:'open'});
            $scope.shadowRoot.innerHTML = template;
            $compile($scope.shadowRoot)($scope);
          }
        };
    });
    </script>
  </head>
  <body>
    <div>
      <my-el title="This is a title" info="This is the info of the element"></my-el>
    </div>
    <div class="shell">
      <h3>Outside title (H3)</h3>
      <p>Outside content (P)</p>
    </div>
  </body>
</html>
</code>```

Title: AngularJS and Shadow DOM

Body:
I'm not sure if this really answers your question, but I am able to get Shadow DOM to work in Angular 1.x. Be aware that if you are after CSS encapsulation, then this will only work on browsers that natively support Shadow DOM since the Polyfill can not do the same thing.

I use $compile to create the contents of the Shadow DOM and bind that back into the directive.

Here is my code example:

<!DOCTYPE html>
<html ng-app="app">
  <head>
    <meta charset="utf-8">
    <title>Angular 1.x ShadowDOM example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
    <script>
    var app = angular.module('app', []);

    app.controller('myElController', ($scope) => {

    });

    var template = `
    <style>
    :host {
      left: 50%;
      position: fixed;
      top: 50%;
      transform: translate(-50%,-50%);
      border: 1px solid black;
      box-shadow: 4px 4px 4px rgba(0,0,0,.4);
      display: inline-block;
      padding: 6px 12px;
    }

    h3 {
      border-bottom: 1px solid #999;
      margin: 0 -12px 8px;
      padding: 0 12px 8px;
    }

    p {
      margin: 0;
    }
    </style>
        <h3>{{title}}</h3>
      <p>{{info}}</p>
    `;

    app.directive('myEl', ($compile) => {
        return {
          "restrict": "E",
          "controller": "myElController",
          "template": '',
          "scope": {
            "title": "@",
            "info": "@"
          },
          "link": function($scope, $element) {
            console.log('here');
            $scope.shadowRoot = $element[0].attachShadow({mode:'open'});
            $scope.shadowRoot.innerHTML = template;
            $compile($scope.shadowRoot)($scope);
          }
        };
    });
    </script>
  </head>
  <body>
    <div>
      <my-el title="This is a title" info="This is the info of the element"></my-el>
    </div>
    <div class="shell">
      <h3>Outside title (H3)</h3>
      <p>Outside content (P)</p>
    </div>
  </body>
</html>


问:
How to fix Invalid byte 1 of 1-byte UTF-8 sequence
I am trying to fetch the below xml from db using a java method but I am getting an error

Code used to parse the xml

```<code>DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();

InputSource is = new InputSource(new ByteArrayInputStream(cond.getBytes()));

Document doc = db.parse(is);

Element elem = doc.getDocumentElement();

// here we expect a series of <data><name>N</name><value>V</value></data>
NodeList nodes = elem.getElementsByTagName("data");

TableID jobId = new TableID(_processInstanceId);
Job myJob = Job.queryByID(_clientContext, jobId, true);

if (nodes.getLength() == 0) {
    log(Level.DEBUG, "No data found on condition XML");

}

for (int i = 0; i < nodes.getLength(); i++) {
    // loop through the <data> in the XML

    Element dataTags = (Element) nodes.item(i);
    String name = getChildTagValue(dataTags, "name");
    String value = getChildTagValue(dataTags, "value");

    log(Level.INFO, "UserData/Value=" + name + "/" + value);

    myJob.setBulkUserData(name, value);
}

myJob.save();
</code>```

The Data

```<code><ContactDetails>307896043</ContactDetails>
<ContactName>307896043</ContactName>
<Preferred_Completion_Date>
</Preferred_Completion_Date>
<service_address>A-End Address: 1ST HELIERST HELIERJT2 3XP832THE CABLES 1 POONHA LANEST HELIER JE JT2 3XP</service_address>
<ServiceOrderId>315473043</ServiceOrderId>
<ServiceOrderTypeId>50</ServiceOrderTypeId>
<CustDesiredDate>2013-03-20T18:12:04</CustDesiredDate>
<OrderId>307896043</OrderId>
<CreateWho>csmuser</CreateWho>
<AccountInternalId>20100333</AccountInternalId>
<ServiceInternalId>20766093</ServiceInternalId>
<ServiceInternalIdResets>0</ServiceInternalIdResets>
<Primary_Offer_Name  action='del'>MyMobile Blue £44.99 [12 month term]</Primary_Offer_Name>
<Disc_Reason  action='del'>8</Disc_Reason>
<Sup_Offer  action='del'>80000257</Sup_Offer>
<Service_Type  action='del'>A-01-00</Service_Type>
<Priority  action='del'>4</Priority>
<Account_Number  action='del'>0</Account_Number>
<Offer  action='del'>80000257</Offer>
<msisdn  action='del'>447797142520</msisdn>
<imsi  action='del'>234503184</imsi>
<sim  action='del'>5535</sim>
<ocb9_ARM  action='del'>false</ocb9_ARM>
<port_in_required  action='del'>
</port_in_required>
<ocb9_mob  action='del'>none</ocb9_mob>
<ocb9_mob_BB  action='del'>
</ocb9_mob_BB>
<ocb9_LandLine  action='del'>
</ocb9_LandLine>
<ocb9_LandLine_BB  action='del'>
</ocb9_LandLine_BB>
<Contact_2>
</Contact_2>
<Acc_middle_name>
</Acc_middle_name>
<MarketCode>7</MarketCode>
<Acc_last_name>Port_OUT</Acc_last_name>
<Contact_1>
</Contact_1>
<Acc_first_name>.</Acc_first_name>
<EmaiId>
</EmaiId>
</code>```

The ERROR

```<code> org.apache.xerces.impl.io.MalformedByteSequenceException: Invalid byte 1 of 1-byte UTF-8 sequence.
</code>```

I read in some threads it's because of some special characters in the xml.
How to fix this issue ?

答:
Those like me who understand character encoding principles, also read Joel's article which is funny as it contains wrong characters anyway and still can't figure out what the heck (spoiler alert, I'm Mac user) then your solution can be as simple as removing your local repo and clone it again.

My code base did not change since the last time it was running OK so it made no sense to have UTF errors given the fact that our build system never complained about it....till I remembered that I accidentally unplugged my computer few days ago with IntelliJ Idea and the whole thing running (Java/Tomcat/Hibernate)

My Mac did a brilliant job as pretending nothing happened and I carried on business as usual but the underlying file system was left corrupted somehow. Wasted the whole day trying to figure this one out. I hope it helps somebody.

Body:
I am trying to fetch the below xml from db using a java method but I am getting an error

Code used to parse the xml

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();

InputSource is = new InputSource(new ByteArrayInputStream(cond.getBytes()));

Document doc = db.parse(is);

Element elem = doc.getDocumentElement();

// here we expect a series of <data><name>N</name><value>V</value></data>
NodeList nodes = elem.getElementsByTagName("data");

TableID jobId = new TableID(_processInstanceId);
Job myJob = Job.queryByID(_clientContext, jobId, true);

if (nodes.getLength() == 0) {
    log(Level.DEBUG, "No data found on condition XML");

}

for (int i = 0; i < nodes.getLength(); i++) {
    // loop through the <data> in the XML

    Element dataTags = (Element) nodes.item(i);
    String name = getChildTagValue(dataTags, "name");
    String value = getChildTagValue(dataTags, "value");

    log(Level.INFO, "UserData/Value=" + name + "/" + value);

    myJob.setBulkUserData(name, value);
}

myJob.save();

The Data

<ContactDetails>307896043</ContactDetails>
<ContactName>307896043</ContactName>
<Preferred_Completion_Date>
</Preferred_Completion_Date>
<service_address>A-End Address: 1ST HELIERST HELIERJT2 3XP832THE CABLES 1 POONHA LANEST HELIER JE JT2 3XP</service_address>
<ServiceOrderId>315473043</ServiceOrderId>
<ServiceOrderTypeId>50</ServiceOrderTypeId>
<CustDesiredDate>2013-03-20T18:12:04</CustDesiredDate>
<OrderId>307896043</OrderId>
<CreateWho>csmuser</CreateWho>
<AccountInternalId>20100333</AccountInternalId>
<ServiceInternalId>20766093</ServiceInternalId>
<ServiceInternalIdResets>0</ServiceInternalIdResets>
<Primary_Offer_Name  action='del'>MyMobile Blue £44.99 [12 month term]</Primary_Offer_Name>
<Disc_Reason  action='del'>8</Disc_Reason>
<Sup_Offer  action='del'>80000257</Sup_Offer>
<Service_Type  action='del'>A-01-00</Service_Type>
<Priority  action='del'>4</Priority>
<Account_Number  action='del'>0</Account_Number>
<Offer  action='del'>80000257</Offer>
<msisdn  action='del'>447797142520</msisdn>
<imsi  action='del'>234503184</imsi>
<sim  action='del'>5535</sim>
<ocb9_ARM  action='del'>false</ocb9_ARM>
<port_in_required  action='del'>
</port_in_required>
<ocb9_mob  action='del'>none</ocb9_mob>
<ocb9_mob_BB  action='del'>
</ocb9_mob_BB>
<ocb9_LandLine  action='del'>
</ocb9_LandLine>
<ocb9_LandLine_BB  action='del'>
</ocb9_LandLine_BB>
<Contact_2>
</Contact_2>
<Acc_middle_name>
</Acc_middle_name>
<MarketCode>7</MarketCode>
<Acc_last_name>Port_OUT</Acc_last_name>
<Contact_1>
</Contact_1>
<Acc_first_name>.</Acc_first_name>
<EmaiId>
</EmaiId>

The ERROR

 org.apache.xerces.impl.io.MalformedByteSequenceException: Invalid byte 1 of 1-byte UTF-8 sequence.

I read in some threads it's because of some special characters in the xml.
How to fix this issue ?


问:
Mercurial: Indicating that a branch has passed testing?
I am working on establishing a workflow at my company if we were to migrate to DVCS (most likely Mercurial).  One of the things I would like to do is to have a repository for QA.  The idea being that each developer works on a branch and when they are done the branch is pushed to QA.  From there the test team can do their testing and report back any bugs.  Once the branch is fully tested and acceptable it will be pushed to a staging repository where the merge back to the mainline will happen before pushing to the central repository.

This can work quite easily if everyone just communicates the status of their work in some way, but I know this doesn't always happen as you would want it to.  What I am worried about is branches in the QA repo waiting around but nobody knows if it is waiting to be tested, currently being tested, waiting for fixes, waiting to be pushed to the staging area etc.  So what I am looking for are ideas of how a status can be added to a branch?  What would also be good would be to do it in a way that we could use hooks to also notify people of changes in the status.

Any ideas would be appreciated.

答:
Why would a developer push something to a QA repository if it wasn't ready to be QA'd?  I think the act of pushing changesets to a QA designated repository should be the signal that the feature is ready to be tested.

Feature branches by cloning is my favorite approach.


问:
Sort Points Using C++
I have an array of std::vector<cv::Point> that looks like-

```<code>[49, 500]
[49, 129]
[441, 501]
[49, 374]
[440, 374]
[440, 259]
[440, 128]
[49, 260]
</code>```

Let consider array elements as [x, y]. Now I need to get 4 elements from the array having-

lowest x with highest y

lowest x with lowest y

highest x with lowest y

highest x with highest y

currently, I am using functions to sort based on conditions and then fetch a point.

```<code>bool SortForMinXMaxY(const Point & a, const Point &b)
{
    return (a.x < b.x || a.y > b.y) ;
}
</code>```

What should be the standard approach with C++ and OpenCV to achieve the goal?

答:
The logic used in the compare function is not correct. It does not meet the requirements of strictly weak ordering.

Change it to:

```<code>bool SortForMinXMaxY(const Point & a, const Point &b)
{
   if ( a.x != b.x )
   {
      return (a.x < b.x);
   }
   return (a.y > b.y);
}
</code>```

Title: Sort Points Using C++

Body:
I have an array of std::vector<cv::Point> that looks like-

[49, 500]
[49, 129]
[441, 501]
[49, 374]
[440, 374]
[440, 259]
[440, 128]
[49, 260]

Let consider array elements as [x, y]. Now I need to get 4 elements from the array having-

lowest x with highest y

lowest x with lowest y

highest x with lowest y

highest x with highest y

currently, I am using functions to sort based on conditions and then fetch a point.

bool SortForMinXMaxY(const Point & a, const Point &b)
{
    return (a.x  b.y) ;
}

What should be the standard approach with C++ and OpenCV to achieve the goal?

Body:
The logic used in the compare function is not correct. It does not meet the requirements of strictly weak ordering.

Change it to:

bool SortForMinXMaxY(const Point & a, const Point &b)
{
   if ( a.x != b.x )
   {
      return (a.x < b.x);
   }
   return (a.y > b.y);
}


问:
PowerShell batch rename with regex?
So I have a group of files with the following file names:

a-2.txt

b-1.txt

c-3.txt

I am trying to rename them to something like:

1.txt  ----->b-1.txt

2.txt  ----->a-2.txt

3.txt  ----->c-3.txt

But, I can't figure out what the corresponding regular expression would be, and how to code it into PowerShell. I see tons of examples to remove spaces or underscores, but nothing to remove from a string.

答:
try this (remove whatif)</p>

```<code>Get-ChildItem "c:\temp" -file -Filter "*.txt" | where BaseName -Match ".-." | %{
$newname="{0}{1}" -f ($_.BaseName -split '-')[1], $_.Extension
Rename-Item $_.FullName $newname -WhatIf
}
</code>```

Title: PowerShell batch rename with regex?

Body:
try this (remove whatif)

Get-ChildItem "c:\temp" -file -Filter "*.txt" | where BaseName -Match ".-." | %{
$newname="{0}{1}" -f ($_.BaseName -split '-')[1], $_.Extension
Rename-Item $_.FullName $newname -WhatIf
}


问:
Automapper set destination element to an empty list object
I am new to using automapper in C#, but I want to know how I can set a value in my map to element to an empty list.

So, in the ForMember where you map your from and to, I want to be able to do to create a new object and use that object to be a list which is empty. How can you do this in automapper?

答:
You'd use .ForMember() and .UseValue()

```<code>public class Source
{
    public int Id { get; set; }
}

public class Dest
{
    public int Id { get; set; }
    public List<Foo> Foos { get; set; }
}

public class Foo
{
    public string Name { get; set; }
}
</code>```

Mapping config

```<code>CreateMap<Source, Dest>()
    .ForMember(d => d.Foos, m => m.UseValue( new List<Foo>() ));
</code>```

Usage

```<code>var source = service.GetItem();
var dest = Mapper.Map<Dest>(source);

Assert.IsTrue(dest.Foos.GetType() == typeof(List<Foo>));
</code>```

Body:
You'd use .ForMember() and .UseValue()

public class Source
{
    public int Id { get; set; }
}

public class Dest
{
    public int Id { get; set; }
    public List<Foo> Foos { get; set; }
}

public class Foo
{
    public string Name { get; set; }
}

Mapping config

CreateMap<Source, Dest>()
    .ForMember(d => d.Foos, m => m.UseValue( new List<Foo>() ));

Usage

var source = service.GetItem();
var dest = Mapper.Map<Dest>(source);

Assert.IsTrue(dest.Foos.GetType() == typeof(List<Foo>));


问:
Good ruby url shortener gems?
What good, reliable ruby gems do you use for shortening URLs?</p>

答: There are many gems out there. It dependes on your need. Shortly gem provides many url shortener services(googl, bitly,...). Check that out.</p>

Title: Good ruby url shortener gems?


问:
flow type question mark before or after param?
Can someone explain the difference between:

```<code>function foo(bar: ?string) {
  console.log(bar);
}
</code>```

and:

```<code>function foo(bar?: string) {
  console.log(bar);
}
</code>```

When to use one over the other?

答:
?string (maybe type) means that bar property can be string aswell as null and void.

bar? means that this property is optional.

More info: https://flow.org/en/docs/types/primitives/

Body:
Can someone explain the difference between:

function foo(bar: ?string) {
  console.log(bar);
}

and:

function foo(bar?: string) {
  console.log(bar);
}

When to use one over the other?


问:
Error: --alias must be specified using PEPK tool
So I'm trying to Enroll a new App Sign In to publish a new application and I got the following error when I enter the following command

java -jar "/path/to/pepk.jar" --keystore="/path/to/key_prod.keystore" --alias="myAlias" --encryptionkey="1230928312431093randomkey1231238u981y8u23" --output="/path/to/private_key.pem"

Error:

Error: --alias must be specified

  USAGE:

  java -jar pepk.jar --keystore < release_keystore > --alias < key_alias > --encryptionkey=< encryption_key_hex > --output=< output_file >

Is my syntax ok? I don't understand why it says my alias is not specified.

Thanks!

答:
Using Java version 1.8 the correct syntax was

java -jar pepk.jar --alias=myAlias --keystore=myKey.keystore --output=private_key.pem --encryptionkey=c647randomKeyfde6a

I added the pepk.jar file and my keystore in the root of my folder when executing the command.


问:
R error: unknown timezone with as.POSIXct()
I am trying to convert a unix epoch timestamps to a date-time object using as.POSIXct()

I need to specify timezones (either Europe/London or UTC) when I call as.POSIXct().

If I run

```<code>> t<-as.POSIXct(1445329330, tz="Europe/London", origin="1970-01-01")
> t
</code>```

R returns
    "2015-10-20 09:22:10 BST"
    Warning messages:
    1: In as.POSIXlt.POSIXct(x, tz) : unknown timezone 'default/Europe/London'
    2: In as.POSIXlt.POSIXct(x, tz) : unknown timezone 'default/Europe/London'

I have tried specifying tz="BST", but this also returns warnings

```<code>Warning messages:
1: In as.POSIXlt.POSIXct(x, tz) : unknown timezone 'BST
          '
2: In as.POSIXlt.POSIXct(x, tz) : unknown timezone 'default/Europe/London'
3: In as.POSIXlt.POSIXct(x, tz) : unknown timezone 'BST
          '
4: In as.POSIXlt.POSIXct(x, tz) : unknown timezone 'default/Europe/London'
</code>```

I have looked up the zoneinfo/zone.tab as per Joshua Ulrich's post and "Europe/London" does appear in the zone.tab file, while "BST" does not. So I think that Europe/London should be a valid tz option. Is this correct?

Does anyone have suggestions as to why I am getting warnings, and why the specified timezone is not being assigned to the as.POSIXct object?

It should be noted that my scripts which call as.POSIXct() were running without warnings prior to updating MacOS to High Sierra. Could the OS update lead to these warnings? When I run Sys.timezone() it returns NA

Many thanks in advance

Iris

答:
It does look like you need to update your system with a timezone, even though it isn't being used.

I can't seem to set my timezone to NA, but if I set my environment with, for example Sys.setenv(TZ='Twilight Zone'), or anything that isn't on the tz list I also get the same errors that you do.

Body:
I am trying to convert a unix epoch timestamps to a date-time object using as.POSIXct()

I need to specify timezones (either Europe/London or UTC) when I call as.POSIXct().

If I run

> t<-as.POSIXct(1445329330, tz="Europe/London", origin="1970-01-01")
> t

R returns
    "2015-10-20 09:22:10 BST"
    Warning messages:
    1: In as.POSIXlt.POSIXct(x, tz) : unknown timezone 'default/Europe/London'
    2: In as.POSIXlt.POSIXct(x, tz) : unknown timezone 'default/Europe/London'

I have tried specifying tz="BST", but this also returns warnings

Warning messages:
1: In as.POSIXlt.POSIXct(x, tz) : unknown timezone 'BST
          '
2: In as.POSIXlt.POSIXct(x, tz) : unknown timezone 'default/Europe/London'
3: In as.POSIXlt.POSIXct(x, tz) : unknown timezone 'BST
          '
4: In as.POSIXlt.POSIXct(x, tz) : unknown timezone 'default/Europe/London'

I have looked up the zoneinfo/zone.tab as per Joshua Ulrich's post and "Europe/London" does appear in the zone.tab file, while "BST" does not. So I think that Europe/London should be a valid tz option. Is this correct?

Does anyone have suggestions as to why I am getting warnings, and why the specified timezone is not being assigned to the as.POSIXct object?

It should be noted that my scripts which call as.POSIXct() were running without warnings prior to updating MacOS to High Sierra. Could the OS update lead to these warnings? When I run Sys.timezone() it returns NA

Many thanks in advance

Iris


问:
CSS - automatic div width
I have html structure that can change depending on the page context. On some pages looks like:

```<code><div class="container">
  <div class="column">
    blah
  </div>
</div>
</code>```

And on others:

```<code><div class="container">
  <div class="column">
    blah
  </div>
  <div class="column">
    blah
  </div>
</div>
</code>```

So, the container has a fluid width (100%).

The .column div is fluid too, and should have the width of its container in the first example, ie. 100%,
and in the second example 50% width and aligned to left.

Like:

```<code>----------------------------
|                           |
|         column1           |
|                           |
-----------------------------
</code>```

and

```<code>----------------------------
|            |              |
|  column2   |  column2     |
|            |              |
-----------------------------
</code>```

How can I do this?

I should also note that I can't change any markup within column1/column2 (can't add classes or anything like that, maybe only using javascript hacks or capture the php output and using regex :)

答:
I can think of two solutions.

Use CSS3 flex box.

Set the columns to display: table-cell; on the columns and display: table-row; on the container.

Title: CSS - automatic div width

Body:
I have html structure that can change depending on the page context. On some pages looks like:

    blah

And on others:

    blah

    blah

So, the container has a fluid width (100%).

The .column div is fluid too, and should have the width of its container in the first example, ie. 100%,
and in the second example 50% width and aligned to left.

Like:

----------------------------
|                           |
|         column1           |
|                           |
-----------------------------

and

----------------------------
|            |              |
|  column2   |  column2     |
|            |              |
-----------------------------

How can I do this?

I should also note that I can't change any markup within column1/column2 (can't add classes or anything like that, maybe only using javascript hacks or capture the php output and using regex :)


问:
Should Hibernate be able to handle overlapping foreign keys?
I have a table that has two foreign keys to two different tables with both foreign keys sharing one column:

```<code>CREATE TABLE ZipAreas
(
  country_code CHAR(2) NOT NULL,
  zip_code VARCHAR(10) NOT NULL,
  state_code VARCHAR(5) NOT NULL,
  city_name VARCHAR(100) NOT NULL,
  PRIMARY KEY (country_code, zip_code, state_code, city_name),
  FOREIGN KEY (country_code, zip_code) REFERENCES Zips (country_code, code),
  FOREIGN KEY (country_code, state_code, city_name) REFERENCES Cities (country_code, state_code, name)
)
</code>```

As you can see, there are two FKs sharing country_code (coincidentally referencing the same column at the end of the referentiation path). The entity class looks like (JPA 1.0 @IdClass):

```<code>@Entity
@Table(name = "ZipAreas")
@IdClass(value = ZipAreaId.class)
public class ZipArea implements Serializable
{
    @Id
    @Column(name = "country_code", insertable = false, updatable = false)
    private String countryCode;

    @Id
    @Column(name = "zip_code", insertable = false, updatable = false)
    private String zipCode;

    @Id
    @Column(name = "state_code", insertable = false, updatable = false)
    private String stateCode;

    @Id
    @Column(name = "city_name", insertable = false, updatable = false)
    private String cityName;

    @ManyToOne
    @JoinColumns(value = {@JoinColumn(name = "country_code", referencedColumnName = "country_code"), @JoinColumn(name = "zip_code", referencedColumnName = "code")})
    private Zip zip = null;

    @ManyToOne
    @JoinColumns(value = {@JoinColumn(name = "country_code", referencedColumnName = "country_code", insertable = false, updatable = false), @JoinColumn(name = "state_code", referencedColumnName = "state_code"), @JoinColumn(name = "city_name", referencedColumnName = "name")})
    private City city = null;

    ...
}
</code>```

As you can see I flagged the countryCode property and city's country_code @JoinColumn as read-only (insertable = false, updatable = false). Hibernate fails with this saying:

```<code>Exception in thread "main" javax.persistence.PersistenceException: [PersistenceUnit: geoinfo] Unable to configure EntityManagerFactory
    at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:374)
    at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:56)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:48)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:32)
    at tld.geoinfo.Main.main(Main.java:27)
Caused by: org.hibernate.AnnotationException: Mixing insertable and non insertable columns in a property is not allowed: tld.geoinfo.model.ZipAreacity
    at org.hibernate.cfg.Ejb3Column.checkPropertyConsistency(Ejb3Column.java:563)
    at org.hibernate.cfg.AnnotationBinder.bindManyToOne(AnnotationBinder.java:2703)
    at org.hibernate.cfg.AnnotationBinder.processElementAnnotations(AnnotationBinder.java:1600)
    at org.hibernate.cfg.AnnotationBinder.processIdPropertiesIfNotAlready(AnnotationBinder.java:796)
    at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:707)
    at org.hibernate.cfg.Configuration$MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:3977)
    at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3931)
    at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1368)
    at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1345)
    at org.hibernate.ejb.Ejb3Configuration.buildMappings(Ejb3Configuration.java:1477)
    at org.hibernate.ejb.EventListenerConfigurator.configure(EventListenerConfigurator.java:193)
    at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:1096)
    at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:278)
    at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:362)
    ... 4 more
</code>```

This looks pretty basic to me honestly. "Mixing insertable and non insertable columns in a property is not allowed" is such a weak "excuse", isn't it?

Should Hibernate be able to handle this, e.g. according to the JPA spec? Is this a bug?

答:
This is still not solved in Hibernate 5.
However, if I use @JoinColumnsOrFormulas I get ClassCastException.
Appending insertable = false, updatable = false on all join columns solved my problem:

Example:

```<code>@ManyToOne
@JoinColumns(value = {
    @JoinColumn(name = "country_code", referencedColumnName = "country_code", insertable = false, updatable = false),
    @JoinColumn(name = "state_code", referencedColumnName = "state_code", insertable = false, updatable = false),
    @JoinColumn(name = "city_name", referencedColumnName = "name", insertable = false, updatable = false)})
private City city = null;
</code>```

Body:
I have a table that has two foreign keys to two different tables with both foreign keys sharing one column:

CREATE TABLE ZipAreas
(
  country_code CHAR(2) NOT NULL,
  zip_code VARCHAR(10) NOT NULL,
  state_code VARCHAR(5) NOT NULL,
  city_name VARCHAR(100) NOT NULL,
  PRIMARY KEY (country_code, zip_code, state_code, city_name),
  FOREIGN KEY (country_code, zip_code) REFERENCES Zips (country_code, code),
  FOREIGN KEY (country_code, state_code, city_name) REFERENCES Cities (country_code, state_code, name)
)

As you can see, there are two FKs sharing country_code (coincidentally referencing the same column at the end of the referentiation path). The entity class looks like (JPA 1.0 @IdClass):

@Entity
@Table(name = "ZipAreas")
@IdClass(value = ZipAreaId.class)
public class ZipArea implements Serializable
{
    @Id
    @Column(name = "country_code", insertable = false, updatable = false)
    private String countryCode;

    @Id
    @Column(name = "zip_code", insertable = false, updatable = false)
    private String zipCode;

    @Id
    @Column(name = "state_code", insertable = false, updatable = false)
    private String stateCode;

    @Id
    @Column(name = "city_name", insertable = false, updatable = false)
    private String cityName;

    @ManyToOne
    @JoinColumns(value = {@JoinColumn(name = "country_code", referencedColumnName = "country_code"), @JoinColumn(name = "zip_code", referencedColumnName = "code")})
    private Zip zip = null;

    @ManyToOne
    @JoinColumns(value = {@JoinColumn(name = "country_code", referencedColumnName = "country_code", insertable = false, updatable = false), @JoinColumn(name = "state_code", referencedColumnName = "state_code"), @JoinColumn(name = "city_name", referencedColumnName = "name")})
    private City city = null;

    ...
}

As you can see I flagged the countryCode property and city's country_code @JoinColumn as read-only (insertable = false, updatable = false). Hibernate fails with this saying:

Exception in thread "main" javax.persistence.PersistenceException: [PersistenceUnit: geoinfo] Unable to configure EntityManagerFactory
    at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:374)
    at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:56)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:48)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:32)
    at tld.geoinfo.Main.main(Main.java:27)
Caused by: org.hibernate.AnnotationException: Mixing insertable and non insertable columns in a property is not allowed: tld.geoinfo.model.ZipAreacity
    at org.hibernate.cfg.Ejb3Column.checkPropertyConsistency(Ejb3Column.java:563)
    at org.hibernate.cfg.AnnotationBinder.bindManyToOne(AnnotationBinder.java:2703)
    at org.hibernate.cfg.AnnotationBinder.processElementAnnotations(AnnotationBinder.java:1600)
    at org.hibernate.cfg.AnnotationBinder.processIdPropertiesIfNotAlready(AnnotationBinder.java:796)
    at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:707)
    at org.hibernate.cfg.Configuration$MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:3977)
    at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3931)
    at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1368)
    at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1345)
    at org.hibernate.ejb.Ejb3Configuration.buildMappings(Ejb3Configuration.java:1477)
    at org.hibernate.ejb.EventListenerConfigurator.configure(EventListenerConfigurator.java:193)
    at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:1096)
    at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:278)
    at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:362)
    ... 4 more

This looks pretty basic to me honestly. "Mixing insertable and non insertable columns in a property is not allowed" is such a weak "excuse", isn't it?

Should Hibernate be able to handle this, e.g. according to the JPA spec? Is this a bug?

Body:
This is still not solved in Hibernate 5.
However, if I use @JoinColumnsOrFormulas I get ClassCastException.
Appending insertable = false, updatable = false on all join columns solved my problem:

Example:

@ManyToOne
@JoinColumns(value = {
    @JoinColumn(name = "country_code", referencedColumnName = "country_code", insertable = false, updatable = false),
    @JoinColumn(name = "state_code", referencedColumnName = "state_code", insertable = false, updatable = false),
    @JoinColumn(name = "city_name", referencedColumnName = "name", insertable = false, updatable = false)})
private City city = null;


问:
Why are my enum fields being serialized?
According to this document, enum constants' fields are not serialized. So I put together the following demo:

```<code>import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

enum EnumBasedSingleton
{
  INSTANCE;

  EnumBasedSingleton() {
    value = 42;
  }

  int value;

  public int getValue()
  {
    return value;
  }
  public void setValue(int value)
  {
    this.value = value;
  }
}

class EnumBasedSingletonDemo
{
  static void saveToFile(EnumBasedSingleton singleton, String filename)
    throws Exception
  {
    try (FileOutputStream fileOut = new FileOutputStream(filename);
         ObjectOutputStream out = new ObjectOutputStream(fileOut))
    {
      out.writeObject(singleton);
    }
  }

  static EnumBasedSingleton readFromFile(String filename)
    throws Exception
  {
    try (FileInputStream fileIn = new FileInputStream(filename);
         ObjectInputStream in = new ObjectInputStream(fileIn) )
    {
      return (EnumBasedSingleton)in.readObject();
    }
  }

  public static void main(String[] args)
    throws Exception
  {
    EnumBasedSingleton singleton = EnumBasedSingleton.INSTANCE;
    singleton.setValue(111);
    String filename = "myfile.bin";
    saveToFile(singleton, filename);
    EnumBasedSingleton singleton2 = readFromFile(filename);
    System.out.println(singleton2.getValue());
  }
}
</code>```

I was expecting the output to be 42 but what I got is 111. Am I misunderstanding the document or are enum constants' fields serialized? I'm running this in Java 9.

答:
There is only ever one instance of an enum constant during the lifetime of a java process.

The document you linked states

The serialized form of an enum constant consists solely of its name;
  field values of the constant are not present in the form. To serialize
  an enum constant, ObjectOutputStream writes the value returned by the
  enum constant's name method. To deserialize an enum constant,
  ObjectInputStream reads the constant name from the stream; the
  deserialized constant is then obtained by calling the
  java.lang.Enum.valueOf method, passing the constant's enum type along
  with the received constant name as arguments.

In other words, the constant's name is used to retrieve the appropriate instance. That instance, however, is the same instance you serialized, it's not a new instance, the enum constructor was not invoked again. And since you had changed the state of the enum constant earlier, you're seeing that changed value.

Had you started a new java process and tried to deserialize the contents of that file without touching the enum constant, you would have seen its original value of 42.

The misunderstanding might stem from using mutable state in your enums. That's strongly discouraged.

Body:
According to this document, enum constants' fields are not serialized. So I put together the following demo:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

enum EnumBasedSingleton
{
  INSTANCE;

  EnumBasedSingleton() {
    value = 42;
  }

  int value;

  public int getValue()
  {
    return value;
  }
  public void setValue(int value)
  {
    this.value = value;
  }
}

class EnumBasedSingletonDemo
{
  static void saveToFile(EnumBasedSingleton singleton, String filename)
    throws Exception
  {
    try (FileOutputStream fileOut = new FileOutputStream(filename);
         ObjectOutputStream out = new ObjectOutputStream(fileOut))
    {
      out.writeObject(singleton);
    }
  }

  static EnumBasedSingleton readFromFile(String filename)
    throws Exception
  {
    try (FileInputStream fileIn = new FileInputStream(filename);
         ObjectInputStream in = new ObjectInputStream(fileIn) )
    {
      return (EnumBasedSingleton)in.readObject();
    }
  }

  public static void main(String[] args)
    throws Exception
  {
    EnumBasedSingleton singleton = EnumBasedSingleton.INSTANCE;
    singleton.setValue(111);
    String filename = "myfile.bin";
    saveToFile(singleton, filename);
    EnumBasedSingleton singleton2 = readFromFile(filename);
    System.out.println(singleton2.getValue());
  }
}

I was expecting the output to be 42 but what I got is 111. Am I misunderstanding the document or are enum constants' fields serialized? I'm running this in Java 9.