问:
Why does my code not work (diary code)?
This is a code of a diary. I want the user to write something in the diary and this is gonna be the first page and gonna be put in a list. After writing enter the next page should be started and he writes something in the next page etc.
I get errors over and over and I don't know why. After writing "enter" I get errors. I am new to java and all in all programming/coding (if it's the same). Sorry if it's a really dumb question i'm asking :/
Thank you for every advice. I am thankful for everything because I want to learn as much as I can for my university which would be in 1 year.</p>

```<code>import java.util.ArrayList;
import java.util.Scanner;

public class NotizbuchKlasse{
    public static void Pages(){
        System.out.println("Tag 1 : Write something in your diary.");
        System.out.println("Write enter if you are done writing.");
        ArrayList<String> List = new ArrayList<String>();
        String ListInList;
        Scanner write;
        do{
            write = new Scanner(System.in);
            ListInList = write.next();}
        while (! ListInList.equals("enter"));
        System.out.println("This is now your page. Your page is gonna be
        created after writing something new.");
        String y = ListInList;
        List.add(y);
        write.close();
        Pages();
    }
public static void main(String[]Args){
    Pages();
}
}

day 1 : Write something in your diary.
Write enter if you are done writing.
hello diary
enter
This is now your page. Your page is gonna be created after writing something
new.
Exception in thread "main" day 1 : Write something in your diary.
Write enter if you are done writing.
java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:14)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:20)
    at NotizbuchKlasse.main(NotizbuchKlasse.java:38)
</code>```

答:
```<code>Give me the 2 numbers first:
1
2
Now give me the operation (+,-,*,/):
+
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at Taschenrechner.Operationen(Taschenrechner.java:10)
    at Taschenrechner.main(Taschenrechner.java:30)
</code>```

Means:

After inputting + there was an Exception thrown. It's InputMismatchException. It was thrown in (...) Scanner#nextInt in Taschenrechrer.java in line 30.

In the provided code, there are also three different problems. One is that you should distinguish between "x" and ''. The first one is a String, the other is a char.

The other one is the fact, that you probably expect floating division instead of integer, so you have to add 1.0 before dividing. Otherwise, the result will always be an integer.

But the most important one is the fact, that scanner is associated with the input stream. A stream is something that floats and can't fall back. This means, that you have to read the input once and then compare what it is. Calling a.next() three times will cause scanner reading 3 different inputs.

```<code>public class Taschenrechner {

    public static void calculator(){
        Scanner a = new Scanner(System.in);
        System.out.println("Give me the 2 numbers first: ");
        int x = a.nextInt();
        int y = a.nextInt();
        System.out.println("Now give me the operation (+,-,*,/): ");
        String op = a.next();
        if (op.equals("+"){
            float result = x + y;
            System.out.println("result: " + result);
        }
        else if (op.equals("-")){
            float result = x - y;
            System.out.println("result: " + result);
        }
        else if (op.equals("*")){
            float result = x * y;
            System.out.println("result: " + result);
        }
        else{
            float result = 1.0 * x / y;
            System.out.println("result: " + result);
            }
        a.close();
        }

        public static void main(String []args) {
            calculator();
        }

}
</code>```

Title: Why does my code not work (diary code)?

Body:
This is a code of a diary. I want the user to write something in the diary and this is gonna be the first page and gonna be put in a list. After writing enter the next page should be started and he writes something in the next page etc.
I get errors over and over and I don't know why. After writing "enter" I get errors. I am new to java and all in all programming/coding (if it's the same). Sorry if it's a really dumb question i'm asking :/
Thank you for every advice. I am thankful for everything because I want to learn as much as I can for my university which would be in 1 year.

import java.util.ArrayList;
import java.util.Scanner;

public class NotizbuchKlasse{
    public static void Pages(){
        System.out.println("Tag 1 : Write something in your diary.");
        System.out.println("Write enter if you are done writing.");
        ArrayList<String> List = new ArrayList<String>();
        String ListInList;
        Scanner write;
        do{
            write = new Scanner(System.in);
            ListInList = write.next();}
        while (! ListInList.equals("enter"));
        System.out.println("This is now your page. Your page is gonna be
        created after writing something new.");
        String y = ListInList;
        List.add(y);
        write.close();
        Pages();
    }
public static void main(String[]Args){
    Pages();
}
}

day 1 : Write something in your diary.
Write enter if you are done writing.
hello diary
enter
This is now your page. Your page is gonna be created after writing something
new.
Exception in thread "main" day 1 : Write something in your diary.
Write enter if you are done writing.
java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:14)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:20)
    at NotizbuchKlasse.main(NotizbuchKlasse.java:38)

Body:
Give me the 2 numbers first:
1
2
Now give me the operation (+,-,*,/):
+
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at Taschenrechner.Operationen(Taschenrechner.java:10)
    at Taschenrechner.main(Taschenrechner.java:30)

Means:

After inputting + there was an Exception thrown. It's InputMismatchException. It was thrown in (...) Scanner#nextInt in Taschenrechrer.java in line 30.

In the provided code, there are also three different problems. One is that you should distinguish between "x" and ''. The first one is a String, the other is a char.

The other one is the fact, that you probably expect floating division instead of integer, so you have to add 1.0 before dividing. Otherwise, the result will always be an integer.

But the most important one is the fact, that scanner is associated with the input stream. A stream is something that floats and can't fall back. This means, that you have to read the input once and then compare what it is. Calling a.next() three times will cause scanner reading 3 different inputs.

public class Taschenrechner {

    public static void calculator(){
        Scanner a = new Scanner(System.in);
        System.out.println("Give me the 2 numbers first: ");
        int x = a.nextInt();
        int y = a.nextInt();
        System.out.println("Now give me the operation (+,-,*,/): ");
        String op = a.next();
        if (op.equals("+"){
            float result = x + y;
            System.out.println("result: " + result);
        }
        else if (op.equals("-")){
            float result = x - y;
            System.out.println("result: " + result);
        }
        else if (op.equals("*")){
            float result = x * y;
            System.out.println("result: " + result);
        }
        else{
            float result = 1.0 * x / y;
            System.out.println("result: " + result);
            }
        a.close();
        }

        public static void main(String []args) {
            calculator();
        }

}


来源: stackexchange

问:
How provide dynamic message in custom loopback validation?
Here is from documentation:

```<code>User.validate('name', customValidator, {message: 'Bad name'});
function customValidator(err) {
    if (this.name === 'bad') err();
});
var user = new User({name: 'Peter'});
user.isValid(); // true
user.name = 'bad';
user.isValid(); // false
</code>```

Is there a way to modify message variable during validation? For example, this.name === 'bad' the message is Bad name but when this.name === 'very bad' the message should be Very Bad name. How this can be done?

答:
Suddenly there is a addError method with signature errors.add(attr, message, code), so:

```<code>User.validate('name', customValidator);
function customValidator(err) {
    if (this.name === 'bad') {
        this.errors.add('name', `Name is bad`, 'name.bad')
        err();
    }
    if (this.name === 'very bad') {
        this.errors.add('name', `Name is very bad`, 'name.very.bad')
        err();
    }
});
</code>```

This works, but keep in mind that you will have +1 custom code and message, see error.details.codes.name and error.details.messages.name paths from rough json below:

```<code>{
  "error": {
    "statusCode": 422,
    "name": "ValidationError",
    "message": "The `Entity` instance is not valid. Details: `name` Name is very bad (value: very bad).",
    "details": {
      "context": "Entity",
      "codes": {
        "name": [
          "name.very.bad",
          "custom"
        ],
        },
      "messages": {
        "name": [
          "Name is very bad",
          "is invalid"
        ]
      }
    },
    "stack": "..."
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here is from documentation:

User.validate('name', customValidator, {message: 'Bad name'});
function customValidator(err) {
    if (this.name === 'bad') err();
});
var user = new User({name: 'Peter'});
user.isValid(); // true
user.name = 'bad';
user.isValid(); // false

Is there a way to modify message variable during validation? For example, this.name === 'bad' the message is Bad name but when this.name === 'very bad' the message should be Very Bad name. How this can be done?

Body:
Suddenly there is a addError method with signature errors.add(attr, message, code), so:

User.validate('name', customValidator);
function customValidator(err) {
    if (this.name === 'bad') {
        this.errors.add('name', `Name is bad`, 'name.bad')
        err();
    }
    if (this.name === 'very bad') {
        this.errors.add('name', `Name is very bad`, 'name.very.bad')
        err();
    }
});

This works, but keep in mind that you will have +1 custom code and message, see error.details.codes.name and error.details.messages.name paths from rough json below:

{
  "error": {
    "statusCode": 422,
    "name": "ValidationError",
    "message": "The `Entity` instance is not valid. Details: `name` Name is very bad (value: very bad).",
    "details": {
      "context": "Entity",
      "codes": {
        "name": [
          "name.very.bad",
          "custom"
        ],
        },
      "messages": {
        "name": [
          "Name is very bad",
          "is invalid"
        ]
      }
    },
    "stack": "..."
  }
}


问:
Use microsoft-graph-client in project with SystemJS
Currently I'm trying to get ng2-adal to work within my project, but I ran into some trouble.

Fortunately I got an answer from Fei Xue, but it still hangs. By trying to reproduce the problem I published a sample project on GitHub, but Fei had problems in the first run to get it to work and he provided a working sample from his side. I cloned the repo and tried it out and after removing the e2e test and updating rx.js to version 5.4.2 it worked.

Then I tried to add the microsoft-graph-client to the project. Fei already added it to the package.json, so I just had to use it...

Within the file microsoftGraph.component.ts I imported the client and tried to use it by calling by this code:

```<code>   if (this.isLoggedIn) {
        this.adalService.acquireToken('https://graph.microsoft.com').subscribe((token) => {
            console.log(token);

            this.graphClient = Client.init({
                debugLogging: true,
                authProvider: (done) => {
                    done(undefined, token);
                }
            });
        });
    }
</code>```

As soon as I insert that code and build the project, I get an error message in the browser console (NOT from the compiler):

```<code>GET http://localhost:3000/@microsoft/microsoft-graph-client 404 (Not Found)
</code>```

so i started to configure the systemjs.config.js file within the project and added the map and package configuration:

```<code>map: {
    ...
    '@microsoft/microsoft-graph-client': 'npm:@microsoft/microsoft-graph-client/lib/src',
    ...
},
packages: {
    ...
    '@microsoft/microsoft-graph-client': {
        main: 'index.js',
        defaultExtension: 'js'
    }
    ...
}
</code>```

After build and reload I got some error messages, complaining about missing es6-promise and superagent:

```<code>GET http://localhost:3000/es6-promise 404 (Not Found)
GET http://localhost:3000/superagent 404 (Not Found)
</code>```

So I added but packages accordingly, like I added the graph client above. But this leads no to a pletora of missing packages (e.g. formidable, form-data, url, stream, mime, util, zlib, ...).

If I would continue to add all of them, I guess I would get further missing packages, down the road of all npm dependencies that each of these packages have declared.

Conclusion

I made something wrong and another way exists to configure system.js to make all this stuff automatically and not by hand. But how? Please give me some insights on how to configure system.js correctly to use the microsoft-graph-client.

答:
AFAIK, this is a know issue to load the microsoft-graph-client SDK using SystemJS( refer here).

And to call the Microsoft Graph, I follow the code sample(msgraph-typescript-typings) using superagent.

Here is the changing code for for the microsoftGraph.component.ts:

```<code>import { Component, Inject, OnInit } from '@angular/core';

import { AuthHttp, AuthConfig, AUTH_PROVIDERS, provideAuth } from 'angular2-jwt/angular2-jwt';

import * as MicrosoftGraph from "@microsoft/microsoft-graph-types"

import * as request from 'superagent';

import { AdalService } from 'ng2-adal/services/adal.service';
import {SecretService} from '../services/secret.service';

@Component({
    selector: 'MicrosoftGraph',
    template: `<button (click)="getProfile()">Get profile using Microsoft Graph</button>`
})
export class MicrosoftGraphComponent {

    private userProfile: any;

    constructor(
        private adalService: AdalService,
        private secretService: SecretService,
        private http1: AuthHttp) {
        adalService.init(secretService.adalConfig);

        }

   public getProfile(){
       this.adalService.acquireToken("https://graph.microsoft.com").subscribe(function(token){
        console.log(token)

        request
            .get("https://graph.microsoft.com/v1.0/me")
            .set('Authorization', 'Bearer ' + token)
            .end((err:any, res:any) => {
                if (err) {
                    console.error(err)
                    return;
                }
                let user:[MicrosoftGraph.User] = res.body;
                  console.log(user);

            })
       })
  }

}
</code>```

Body:
Currently I'm trying to get ng2-adal to work within my project, but I ran into some trouble.

Fortunately I got an answer from Fei Xue, but it still hangs. By trying to reproduce the problem I published a sample project on GitHub, but Fei had problems in the first run to get it to work and he provided a working sample from his side. I cloned the repo and tried it out and after removing the e2e test and updating rx.js to version 5.4.2 it worked.

Then I tried to add the microsoft-graph-client to the project. Fei already added it to the package.json, so I just had to use it...

Within the file microsoftGraph.component.ts I imported the client and tried to use it by calling by this code:

   if (this.isLoggedIn) {
        this.adalService.acquireToken('https://graph.microsoft.com').subscribe((token) => {
            console.log(token);

            this.graphClient = Client.init({
                debugLogging: true,
                authProvider: (done) => {
                    done(undefined, token);
                }
            });
        });
    }

As soon as I insert that code and build the project, I get an error message in the browser console (NOT from the compiler):

GET http://localhost:3000/@microsoft/microsoft-graph-client 404 (Not Found)

so i started to configure the systemjs.config.js file within the project and added the map and package configuration:

map: {
    ...
    '@microsoft/microsoft-graph-client': 'npm:@microsoft/microsoft-graph-client/lib/src',
    ...
},
packages: {
    ...
    '@microsoft/microsoft-graph-client': {
        main: 'index.js',
        defaultExtension: 'js'
    }
    ...
}

After build and reload I got some error messages, complaining about missing es6-promise and superagent:

GET http://localhost:3000/es6-promise 404 (Not Found)
GET http://localhost:3000/superagent 404 (Not Found)

So I added but packages accordingly, like I added the graph client above. But this leads no to a pletora of missing packages (e.g. formidable, form-data, url, stream, mime, util, zlib, ...).

If I would continue to add all of them, I guess I would get further missing packages, down the road of all npm dependencies that each of these packages have declared.

Conclusion

I made something wrong and another way exists to configure system.js to make all this stuff automatically and not by hand. But how? Please give me some insights on how to configure system.js correctly to use the microsoft-graph-client.

Body:
AFAIK, this is a know issue to load the microsoft-graph-client SDK using SystemJS( refer here).

And to call the Microsoft Graph, I follow the code sample(msgraph-typescript-typings) using superagent.

Here is the changing code for for the microsoftGraph.component.ts:

import { Component, Inject, OnInit } from '@angular/core';

import { AuthHttp, AuthConfig, AUTH_PROVIDERS, provideAuth } from 'angular2-jwt/angular2-jwt';

import * as MicrosoftGraph from "@microsoft/microsoft-graph-types"

import * as request from 'superagent';

import { AdalService } from 'ng2-adal/services/adal.service';
import {SecretService} from '../services/secret.service';

@Component({
    selector: 'MicrosoftGraph',
    template: `<button (click)="getProfile()">Get profile using Microsoft Graph</button>`
})
export class MicrosoftGraphComponent {

    private userProfile: any;

    constructor(
        private adalService: AdalService,
        private secretService: SecretService,
        private http1: AuthHttp) {
        adalService.init(secretService.adalConfig);

        }

   public getProfile(){
       this.adalService.acquireToken("https://graph.microsoft.com").subscribe(function(token){
        console.log(token)

        request
            .get("https://graph.microsoft.com/v1.0/me")
            .set('Authorization', 'Bearer ' + token)
            .end((err:any, res:any) => {
                if (err) {
                    console.error(err)
                    return;
                }
                let user:[MicrosoftGraph.User] = res.body;
                  console.log(user);

            })
       })
  }

}


问:
Redirect user to another page once increment value reach 100
I have created a UI where when service return true value, I have created a loading bar which will reach 100%, after reaching 100% user should be redirect to another page.

lets assume, If the service return false value, the status bar stay at 10% loaded.

Link to jsfiddle

I have created function were I have written the progress bar logic and I am returning true value when service return true and redirecting to other URL.

everything is working great. But I want the progress bar to reach 100% and after that only user should be redirected. Below is the code (And above is jsfiddle link):

```<code>var serviceStatus = true; // Suppose value from service
var elem = document.getElementById("blueBar");
var perNum = document.getElementById("progressPercentage");

var width = 10; // intial progress bar width
var id = setInterval(progressBar, 10);
function progressBar() {
    if (width >= 100 || serviceStatus === false) {
        clearInterval(id);
        return false;
    } else {
        width ++;
        elem.style.width = width + '%';
        perNum.innerHTML = width * 1  + '%';
        //return true;
    }
}

function redirectUser(progressBar) {
    console.log(progressBar);
    // if (frame === true) {
    //  window.location = "http://www.google.com";
    // };
}

redirectUser(progressBar());
</code>```

Thanks, any questions? please ask.

答:
Here you go https://jsfiddle.net/4t6bppjs/10/

```<code>function redirectUser(progressBar) {
    if(progressBar) {
        setTimeout( function() {
            //---- window.location
        }, 1000);
    }
}
</code>```

I just added setTimeout.

Body:
I have created a UI where when service return true value, I have created a loading bar which will reach 100%, after reaching 100% user should be redirect to another page.

lets assume, If the service return false value, the status bar stay at 10% loaded.

Link to jsfiddle

I have created function were I have written the progress bar logic and I am returning true value when service return true and redirecting to other URL.

everything is working great. But I want the progress bar to reach 100% and after that only user should be redirected. Below is the code (And above is jsfiddle link):

var serviceStatus = true; // Suppose value from service
var elem = document.getElementById("blueBar");
var perNum = document.getElementById("progressPercentage");

var width = 10; // intial progress bar width
var id = setInterval(progressBar, 10);
function progressBar() {
    if (width >= 100 || serviceStatus === false) {
        clearInterval(id);
        return false;
    } else {
        width ++;
        elem.style.width = width + '%';
        perNum.innerHTML = width * 1  + '%';
        //return true;
    }
}

function redirectUser(progressBar) {
    console.log(progressBar);
    // if (frame === true) {
    //  window.location = "http://www.google.com";
    // };
}

redirectUser(progressBar());

Thanks, any questions? please ask.

Body:
Here you go https://jsfiddle.net/4t6bppjs/10/

function redirectUser(progressBar) {
    if(progressBar) {
        setTimeout( function() {
            //---- window.location
        }, 1000);
    }
}

I just added setTimeout.


问:
var in class gives error

Possible Duplicate:

  Using var outside of a method

```<code>class A {
string X;
}
// Proper
class A {
var X;
}
// Improper (gives error)
</code>```

Why is it, that i cant have var type variable declare in Class and what can be done in order to achieve it OR what is an alternative ?

In function/method, i can declare a var type variable,then why can't, i do it in class ?

Thanks.

答: If you really don't know the type of object your instance variable will hold, use object, not var. var doesn't mean "i don't know", it means "infer the type for me" - this is why it can never be used on class members.

ContentLicense: CC BY-SA 2.5

Title: var in class gives error

Body:
Possible Duplicate:

  Using var outside of a method

class A {
string X;
}
// Proper
class A {
var X;
}
// Improper (gives error)

Why is it, that i cant have var type variable declare in Class and what can be done in order to achieve it OR what is an alternative ?

In function/method, i can declare a var type variable,then why can't, i do it in class ?

Thanks.


问:
How to remove div tag?
I have a plugin that allows me to remove the style from the div.
I would like to remove the div tag too.

For the moment the plugin realizes this action :

```<code><div class="GCO9_TDM"><p>text</p></div>  --> <div><p>text</p></div>
</code>```

This is the code of my plugin :

CKEDITOR.plugins.add( 'supprimerDivision', {
icons: 'supprimerDivision',
    init: function( editor ) {

        editor.addCommand( 'supprimerDivision', {
            exec: function( editor ) {

                var element = editor.getSelection().getStartElement();
                    while (element) {
                        if (element.getName() == 'div') {
                            element.setAttribute('class', '');
                            break;
                        }

                        element = element.getParent();
                    }
            }
        });

        editor.ui.addButton( 'supprimerDivision', {
            label: 'supprime la division',
            command: 'supprimerDivision',
            toolbar: 'insert'
        } );
     }
});```
</div>
</div>
</p>

<p>Thanks, have a good day.</p>

<p><strong>EDIT :</strong> my html code</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="cache-control" content="no-cache">
        <title>Editeur</title>
        <script type="text/javascript" src="ckeditor/ckeditor.js"></script> <!-- emplacement de ckeditor -->
        <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
    </head>
    <body>

        <form action="enregistrementBDD.php" method="post">
            <textarea id="editor" name="editor">

            </textarea>
            <script>
                CKEDITOR.replace( 'editor', {     //remplace le textarea par une instance de ckeditor
                        height: 600,              //taille de la fênetre

                        allowedContent: true, //permet de définir des règles de contenu autorisé (true désactive le filtre)

                        //startupOutlineBlocks: true, //autorise le plugin showblock a être actif dès le lancement

                        toolbarCanCollapse: true, //permet de cacher la barre d'outil via un bouton situé en bas à droite des menus

                        extraPlugins: 'espace,'+
                        'ckeditor_wiris,'+
                        'dropdownmenumanager,'+

                        'raccourciClavier,'+
                        'supprimerStyle,'+
                        'supprimerDivision,'+

                        'GCO12_DocIll,'+
                        'SLT2_Num_XXX1_DocIll,'+
                        'STI1_Titre_XXX1_DocIll',

                        //fullPage: true, //page HTML complète avec balise <html>, <head>, <body>...
                } );
            </script>
        </form>

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

答:
I had already tried this code but it works now, here is the solution

CKEDITOR.plugins.add( 'supprimerDivision', {
icons: 'supprimerDivision',
    init: function( editor ) {

        editor.addCommand( 'supprimerDivision', {
            exec: function( editor ) {

                var element = editor.getSelection().getStartElement();
                    while (element) {
                        if (element.getName() == 'div') {
                            element.setAttribute('class', '');
                            element.remove("div");
                            break;
                        }

                        element = element.getParent();
                    }
            }
        });

        editor.ui.addButton( 'supprimerDivision', {
            label: 'supprime la division',
            command: 'supprimerDivision',
            toolbar: 'insert'
        } );
     }
});```

Title: How to remove div tag?

Body:
I have a plugin that allows me to remove the style from the div.
I would like to remove the div tag too.

For the moment the plugin realizes this action :

text

  -->

text

This is the code of my plugin :

CKEDITOR.plugins.add( 'supprimerDivision', {
icons: 'supprimerDivision',
    init: function( editor ) {

        editor.addCommand( 'supprimerDivision', {
            exec: function( editor ) {

                var element = editor.getSelection().getStartElement();
                    while (element) {
                        if (element.getName() == 'div') {
                            element.setAttribute('class', '');
                            break;
                        }

                        element = element.getParent();
                    }
            }
        });

        editor.ui.addButton( 'supprimerDivision', {
            label: 'supprime la division',
            command: 'supprimerDivision',
            toolbar: 'insert'
        } );
     }
});

Thanks, have a good day.

EDIT : my html code

<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="cache-control" content="no-cache">
        <title>Editeur</title>

        <form action="enregistrementBDD.php" method="post">
            <textarea id="editor" name="editor">

            </textarea>

        </form>


问:
Static Initialization in Java?
I was trying to execute the following code:

```<code>public class StaticTest {

    private static List<String> dat1;
    {
        dat1 = new ArrayList<>();
    }

    private StaticTest(){
        System.out.println(dat1.contains("a")); //Marked Line 2: this one is not throwing
    }

    public static void main(String[] args) {
        System.out.println(dat1.contains("a")); //Marked Line 1: This line throws null pointer
        new StaticTest();
    }
}
</code>```

I tried to execute the above code, I got Null pointer exception at Marked Line 1. But when I commented Marked Line 1 I got the output.

Why am I getting the exception in first case and not in second ?

When I use private static List<String> dat1= new ArrayList<>();, no exception is thrown.

答:
Simple:

```<code>System.out.println(dat1.contains("a"));
</code>```

runs a constructor (because it is inside the constructor!).
And part of running the constructor is: to run all non-static initializer blocks of a class.

Whereas:

```<code>public static void main(String[] args) {
  System.out.println(dat1.contains("a")); //Marked Line 1: This line
</code>```

does only run your static initializers - but no constructor code (it does - but after that line).

So your problem is that this initializer block:

```<code>{
    dat1 = new ArrayList<>();
}
</code>```

isn't static!

In other words: your problem is caused by mixing static/non-static in very  unhealthy ways. If a field is static, make sure that a static init code will initialize it.

Btw: the reasonable solution is to simply do:

```<code>private final static List<String> data = new ArrayList<>();
</code>```

This makes sure that the list is initialized as soon as possible; and then compiler will even tell you when you forgot to initialize it.

ContentLicense: CC BY-SA 4.0

Title: Static Initialization in Java?

Body:
I was trying to execute the following code:

public class StaticTest {

    private static List<String> dat1;
    {
        dat1 = new ArrayList<>();
    }

    private StaticTest(){
        System.out.println(dat1.contains("a")); //Marked Line 2: this one is not throwing
    }

    public static void main(String[] args) {
        System.out.println(dat1.contains("a")); //Marked Line 1: This line throws null pointer
        new StaticTest();
    }
}

I tried to execute the above code, I got Null pointer exception at Marked Line 1. But when I commented Marked Line 1 I got the output.

Why am I getting the exception in first case and not in second ?

When I use private static List<String> dat1= new ArrayList<>();, no exception is thrown.

Body:
Simple:

System.out.println(dat1.contains("a"));

runs a constructor (because it is inside the constructor!).
And part of running the constructor is: to run all non-static initializer blocks of a class.

Whereas:

public static void main(String[] args) {
  System.out.println(dat1.contains("a")); //Marked Line 1: This line

does only run your static initializers - but no constructor code (it does - but after that line).

So your problem is that this initializer block:

{
    dat1 = new ArrayList<>();
}

isn't static!

In other words: your problem is caused by mixing static/non-static in very  unhealthy ways. If a field is static, make sure that a static init code will initialize it.

Btw: the reasonable solution is to simply do:

private final static List<String> data = new ArrayList<>();

This makes sure that the list is initialized as soon as possible; and then compiler will even tell you when you forgot to initialize it.


问:
matlab: detecting better branchpoints from skeleton
I have two skeleton images over which I extracted the branchpoints. Unfortunately, the branchpoints do not seem to be correct. Does anyone has a suggestion on how to extract valid branchpoints (i.e. "y"-like shape points)?

```<code>reg1 = imread('region1.tif');
[i,j] = ind2sub(size(reg1), find(bwmorph(reg1,'branchpoint') == 1));
h=figure; imshow(reg1); hold on; plot(j,i,'rx');print(h,'reg1overlay','-dtiff');
</code>```

In the first example below there should be only one branchpoint:

```<code>reg2 = imread('region2.tif');
[i,j] = ind2sub(size(reg2), find(bwmorph(reg2,'branchpoint') == 1));
h=figure; imshow(reg2); hold on; plot(j,i,'rx');print(h,'reg2overlay','-dtiff');
</code>```

In the second example below there should be only no branchpoints:

答:
Try:</p>

```<code>branchskel = bwmorph(BW,'skel',Inf); %BW is your binarized image
branchskel = bwmorph(branchskel,'thin'); %this should remove those pixel piles that are giving you problems
B = bwmorph(branchskel, 'branchpoints');
[yb,xb] = find(B);
</code>```

Body:
I have two skeleton images over which I extracted the branchpoints. Unfortunately, the branchpoints do not seem to be correct. Does anyone has a suggestion on how to extract valid branchpoints (i.e. "y"-like shape points)?

reg1 = imread('region1.tif');
[i,j] = ind2sub(size(reg1), find(bwmorph(reg1,'branchpoint') == 1));
h=figure; imshow(reg1); hold on; plot(j,i,'rx');print(h,'reg1overlay','-dtiff');

In the first example below there should be only one branchpoint:

reg2 = imread('region2.tif');
[i,j] = ind2sub(size(reg2), find(bwmorph(reg2,'branchpoint') == 1));
h=figure; imshow(reg2); hold on; plot(j,i,'rx');print(h,'reg2overlay','-dtiff');

In the second example below there should be only no branchpoints:

Body:
Try:

branchskel = bwmorph(BW,'skel',Inf); %BW is your binarized image
branchskel = bwmorph(branchskel,'thin'); %this should remove those pixel piles that are giving you problems
B = bwmorph(branchskel, 'branchpoints');
[yb,xb] = find(B);


问:
How to open browser from Visual Studio Code API
I am just exploring a way in order to open the default browser from Visual Studio Code API used for developing extensions.

Following is my code :

```<code>var disposable = vscode.commands.registerCommand('extension.browser', () => {
  // The code you place here will be executed every time your command is executed
  vscode.Uri.call("http://facebook.com");
});
</code>```

How to open Browser URL from API using vscode class.

答:
There is no need for node or external libraries.

If you are using VS Code 1.31+, use the vscode.env.openExternal function:

```<code>import * as vscode from 'vscode';

vscode.env.openExternal(vscode.Uri.parse('https://example.com'));
</code>```

For older VS Code versions, use the vscode.open command:

```<code>vscode.commands.executeCommand('vscode.open', vscode.Uri.parse('https://example.com'))
</code>```

Both of these will open the page in the user's default browser

Body:
I am just exploring a way in order to open the default browser from Visual Studio Code API used for developing extensions.

Following is my code :

var disposable = vscode.commands.registerCommand('extension.browser', () => {
  // The code you place here will be executed every time your command is executed
  vscode.Uri.call("http://facebook.com");
});

How to open Browser URL from API using vscode class.

Body:
There is no need for node or external libraries.

If you are using VS Code 1.31+, use the vscode.env.openExternal function:

import * as vscode from 'vscode';

vscode.env.openExternal(vscode.Uri.parse('https://example.com'));

For older VS Code versions, use the vscode.open command:

vscode.commands.executeCommand('vscode.open', vscode.Uri.parse('https://example.com'))

Both of these will open the page in the user's default browser


答:
In the ggplotly call you can add a 'tooltip' argument that defines which values show up in the tooltip. To customize this tooltip we can add a text aesthetic to the ggplot call. ggplot will ignore this (and throw a warning that it's doing so) but in the ggplotly call you can add tooltip = c("y","text") and it will put text in the tooltip. Now all we need to do is define text to be the dateformat you want and we have the desired tooltip.

Code: Note that I also had to add group = 1 to the aesthetic, If you don't add this it will try and plot each point as a separate line, resulting in an empty graph.

```<code>p <- ggplot(df, aes(DateTime)) + ylab("Val") +
  geom_line(aes(y = Val1, col = "Val1", text = paste("DateTime:", format(DateTime, "%A %T")), group = 1),lwd=0.5) +
  geom_line(aes(y = Val2, col = "Val2", text = paste("DateTime:", format(DateTime, "%A %T")), group = 1),lwd=0.5) +
  scale_x_datetime(labels = date_format("%m-%d %H:%M"),expand = c(0,0)) +
  scale_y_continuous(expand = c(0,10))  +
  theme(text = element_text(size=9),
        axis.text.x = element_text(angle = 90, hjust = 1),
        legend.text = element_text(size=10),
        panel.background = element_rect(fill = "white", colour = "black"),
        panel.grid.major.x = element_line(color = 'grey75', size = 0.2))
ggplotly(p, tooltip = c("y","text")) %>% config(displayModeBar = FALSE) %>% layout(xaxis=list(fixedrange=TRUE)) %>% layout(yaxis=list(fixedrange=TRUE))
</code>```

Plot:

Title: R : How to config ggplotly displaying values on the line graph?

Body:
My plot on ggplotly shows unnecessary info while cursor pointing on the line graph.

Here is my example code :

df <- read.table(text="
                              DateTime,Val1,Val2
                 1  ,2017-07-01 09:32:00      ,401.7542   ,275.5876
                 2  ,2017-07-01 09:30:00      ,402.7049   ,359.2615
                 3  ,2017-07-01 09:29:00      ,402.5912   ,276.4372
                 4  ,2017-07-01 09:28:00      ,402.7526   ,362.6202
                 5  ,2017-07-01 09:27:00      ,402.4538   ,361.3867
                 6  ,2017-07-01 09:26:00      ,401.8847   ,359.6318
                 7  ,2017-07-01 09:25:00      ,402.2666   ,274.8941
                 8  ,2017-07-01 09:24:00      ,403.0774   ,277.4844
                 9  ,2017-07-01 09:23:00      ,403.0516   ,363.3593
                 10 ,2017-07-01 09:22:00      ,402.5764   ,275.4202
                 11 ,2017-07-01 09:21:00      ,402.2379   ,275.0550
                 12 ,2017-07-01 09:20:00      ,401.9060   ,277.2950
                 13 ,2017-07-01 09:19:00      ,401.9451   ,361.0770
                 14 ,2017-07-01 09:18:00      ,401.4484   ,361.3591
                 15 ,2017-07-01 09:17:00      ,402.5519   ,274.8206
                 16 ,2017-07-01 09:16:00      ,402.1426   ,279.2438
                 17 ,2017-07-01 09:15:00      ,402.4618   ,360.7491
                 18 ,2017-07-01 09:14:00      ,403.3124   ,276.4756
                 19 ,2017-07-01 09:13:00      ,402.3604   ,276.7015
                 20 ,2017-07-01 09:12:00      ,402.5518   ,363.2422
                 21 ,2017-07-01 09:11:00      ,404.7830   ,360.2075
                 22 ,2017-07-01 09:10:00      ,403.7317   ,275.8560
                 23 ,2017-07-01 09:09:00      ,403.2151   ,276.8633
                 24 ,2017-07-01 09:08:00      ,404.2897   ,361.6937
                 25 ,2017-07-01 09:07:00      ,403.8227   ,355.2353
                 26 ,2017-07-01 09:06:00      ,402.8998   ,276.0700
                 27 ,2017-07-01 09:05:00      ,403.1328   ,362.2495
                 28 ,2017-07-01 09:04:00      ,404.1612   ,361.9048
                 29 ,2017-07-01 09:03:00      ,403.7537   ,274.9531
                 30 ,2017-07-01 09:02:00      ,402.1621   ,360.7682
                 31 ,2017-07-01 09:01:00      ,403.0805   ,360.8172
                 32 ,2017-07-01 09:00:00      ,403.3630   ,276.2874
                 33 ,2017-07-01 08:59:00      ,402.8351   ,275.9734
                 34 ,2017-07-01 08:58:00      ,403.6484   ,360.5585
                 35 ,2017-07-01 08:57:00      ,403.4342   ,357.7776
                 36 ,2017-07-01 08:56:00      ,402.4444   ,275.8763
                 37 ,2017-07-01 08:55:00      ,403.2913   ,361.2458
                 38 ,2017-07-01 08:54:00      ,403.2985   ,276.7728
                 39 ,2017-07-01 08:53:00      ,403.2600   ,276.6644
                 40 ,2017-07-01 08:52:00      ,401.9991   ,361.2737
                 41 ,2017-07-01 08:51:00      ,404.9158   ,358.2727
                 42 ,2017-07-01 08:50:00      ,403.8922   ,357.0592
                 43 ,2017-07-01 08:49:00      ,403.0070   ,359.5312
                 44 ,2017-07-01 08:48:00      ,404.8530   ,360.1790
                 45 ,2017-07-01 08:47:00      ,404.1543   ,359.4836
                 46 ,2017-07-01 08:46:00      ,403.9200   ,357.9064
                 47 ,2017-07-01 08:45:00      ,403.9197   ,358.6364
                 48 ,2017-07-01 08:44:00      ,406.0925   ,358.6248
                 49 ,2017-07-01 08:43:00      ,401.5529   ,359.9990
                 50 ,2017-07-01 08:42:00      ,402.4422   ,356.6060",sep=",",header=TRUE,stringsAsFactors=FALSE)
df$DateTime <- as.POSIXct(df$DateTime)
library(plotly)
library(ggplot2)
library(scales)

p <- ggplot(df, aes(DateTime)) + ylab("Val") +
  geom_line(aes(y = Val1, col = "Val1"),lwd=0.5) +
  geom_line(aes(y = Val2, col = "Val2"),lwd=0.5) +
  scale_x_datetime(labels = date_format("%m-%d %H:%M"),expand = c(0,0)) +
  scale_y_continuous(expand = c(0,10))  +
  theme(text = element_text(size=9),
        axis.text.x = element_text(angle = 90, hjust = 1),
        legend.text = element_text(size=10),
        panel.background = element_rect(fill = "white", colour = "black"),
        panel.grid.major.x = element_line(color = 'grey75', size = 0.2))
ggplotly(p) %>% config(displayModeBar = FALSE) %>% layout(xaxis=list(fixedrange=TRUE)) %>% layout(yaxis=list(fixedrange=TRUE))

So how to config format displaying weekdays instead of date and hide that unnecessary line or hide both these 2 info-lines including DateTime to show only Val?

My expected output :

Thanks so much for your helps in advance.

Body:
In the ggplotly call you can add a 'tooltip' argument that defines which values show up in the tooltip. To customize this tooltip we can add a text aesthetic to the ggplot call. ggplot will ignore this (and throw a warning that it's doing so) but in the ggplotly call you can add tooltip = c("y","text") and it will put text in the tooltip. Now all we need to do is define text to be the dateformat you want and we have the desired tooltip.

Code: Note that I also had to add group = 1 to the aesthetic, If you don't add this it will try and plot each point as a separate line, resulting in an empty graph.

p <- ggplot(df, aes(DateTime)) + ylab("Val") +
  geom_line(aes(y = Val1, col = "Val1", text = paste("DateTime:", format(DateTime, "%A %T")), group = 1),lwd=0.5) +
  geom_line(aes(y = Val2, col = "Val2", text = paste("DateTime:", format(DateTime, "%A %T")), group = 1),lwd=0.5) +
  scale_x_datetime(labels = date_format("%m-%d %H:%M"),expand = c(0,0)) +
  scale_y_continuous(expand = c(0,10))  +
  theme(text = element_text(size=9),
        axis.text.x = element_text(angle = 90, hjust = 1),
        legend.text = element_text(size=10),
        panel.background = element_rect(fill = "white", colour = "black"),
        panel.grid.major.x = element_line(color = 'grey75', size = 0.2))
ggplotly(p, tooltip = c("y","text")) %>% config(displayModeBar = FALSE) %>% layout(xaxis=list(fixedrange=TRUE)) %>% layout(yaxis=list(fixedrange=TRUE))

Plot:


问:
Cannot GET / Node.js when publish with azure
i just have a problem when i publish to azure . it said: Cannot GET / when i open the website .

i using static site with node.js , angular.js, and loopback(API)

here my client side (site.js):

```<code>var express = require('express'),
    app = express();

app.use(express.static(__dirname + '/Public'));

var server = app.listen(1338, function() {
  console.log('Listening on port %d', server.address().port);
});
</code>```

There is index.html inside Public Folder .

this is my Package.json :

```<code>{
  "name": "angular-site",
  "version": "1.0.0",
  "description": "static server to server Node.js",
  "main": "site.js",
  "author": "Jordan Leonardi",
  "dependencies": {
    "express": "^4.8.5"
  }
}
</code>```

when i tried to localhost, its look Fine, but when i tried to Azurewebsites its give me back an error " Cannot GET / " . .

答: Also, you should use process.env.PORT || 1338 instead of custom port 1338 when you deploy your app to cloud service such as Azure App Service, Heroku etc.

Body:
i just have a problem when i publish to azure . it said: Cannot GET / when i open the website .

i using static site with node.js , angular.js, and loopback(API)

here my client side (site.js):

var express = require('express'),
    app = express();

app.use(express.static(__dirname + '/Public'));

var server = app.listen(1338, function() {
  console.log('Listening on port %d', server.address().port);
});

There is index.html inside Public Folder .

this is my Package.json :

{
  "name": "angular-site",
  "version": "1.0.0",
  "description": "static server to server Node.js",
  "main": "site.js",
  "author": "Jordan Leonardi",
  "dependencies": {
    "express": "^4.8.5"
  }
}

when i tried to localhost, its look Fine, but when i tried to Azurewebsites its give me back an error " Cannot GET / " . .


问:
StringBuilder and string equality check
I am trying this sample of code and OpTest when System.Console.WriteLine(s == t); it returns false. Can somebody explain this?

```<code>public static void OpTest<T>(T s, T t) where T : class
{
    System.Console.WriteLine(s == t);
}
static void Main()
{
    string s1 = "строка";
    System.Text.StringBuilder sb = new System.Text.StringBuilder(s1);
    System.Console.Write(sb);
    string s2 = sb.ToString();
    OpTest<string>(s1, s2);
}
</code>```

答:
There are many answers already, but I have something extra to add. If you're stuck on this kind of issue it can help to use ildasm.exe to look at the generated IL. For example:

```<code>public class Foo
{
    public static void OpTest_1<T>(T s, T t) where T : class
    {
        var val = s == t;
    }

    public static void OpTest_2(string s, string t)
    {
        var val = s == t;
    }

    // Does not compile.
    //public static void OpTest_3<T>(T s, T t) where T : struct
    //{
    //    var val = s == t;
    //}
}
</code>```

Gives for OpTest_1:

```<code>.method public hidebysig static void  OpTest_1<class T>(!!T s, !!T t) cil managed
{
  // Code size       17 (0x11)
  .maxstack  2
  .locals init ([0] bool val)
  IL_0000:  nop
  IL_0001:  ldarg.0
  IL_0002:  box        !!T
  IL_0007:  ldarg.1
  IL_0008:  box        !!T
  IL_000d:  ceq
  IL_000f:  stloc.0
  IL_0010:  ret
} // end of method Foo::OpTest_1
</code>```

So you see it calls ceq which checks for reference equality.

The other one has this IL:

```<code>.method public hidebysig static void  OpTest_2(string s, string t) cil managed
{
  // Code size       10 (0xa)
  .maxstack  2
  .locals init ([0] bool val)
  IL_0000:  nop
  IL_0001:  ldarg.0
  IL_0002:  ldarg.1
  IL_0003:  call       bool [mscorlib]System.String::op_Equality(string, string)
  IL_0008:  stloc.0
  IL_0009:  ret
} // end of method Foo::OpTest_2
</code>```

That doesn't use ceq but the string equality operation in mscorlib and will give a result as expected.

Like I said, just to add another way of researching this issue. For more high level details I'd recommend reading @JonSkeet's answer.

Title: StringBuilder and string equality check

Body:
I am trying this sample of code and OpTest when System.Console.WriteLine(s == t); it returns false. Can somebody explain this?

public static void OpTest<T>(T s, T t) where T : class
{
    System.Console.WriteLine(s == t);
}
static void Main()
{
    string s1 = "строка";
    System.Text.StringBuilder sb = new System.Text.StringBuilder(s1);
    System.Console.Write(sb);
    string s2 = sb.ToString();
    OpTest<string>(s1, s2);
}

Body:
There are many answers already, but I have something extra to add. If you're stuck on this kind of issue it can help to use ildasm.exe to look at the generated IL. For example:

public class Foo
{
    public static void OpTest_1<T>(T s, T t) where T : class
    {
        var val = s == t;
    }

    public static void OpTest_2(string s, string t)
    {
        var val = s == t;
    }

    // Does not compile.
    //public static void OpTest_3<T>(T s, T t) where T : struct
    //{
    //    var val = s == t;
    //}
}

Gives for OpTest_1:

.method public hidebysig static void  OpTest_1<class T>(!!T s, !!T t) cil managed
{
  // Code size       17 (0x11)
  .maxstack  2
  .locals init ([0] bool val)
  IL_0000:  nop
  IL_0001:  ldarg.0
  IL_0002:  box        !!T
  IL_0007:  ldarg.1
  IL_0008:  box        !!T
  IL_000d:  ceq
  IL_000f:  stloc.0
  IL_0010:  ret
} // end of method Foo::OpTest_1

So you see it calls ceq which checks for reference equality.

The other one has this IL:

.method public hidebysig static void  OpTest_2(string s, string t) cil managed
{
  // Code size       10 (0xa)
  .maxstack  2
  .locals init ([0] bool val)
  IL_0000:  nop
  IL_0001:  ldarg.0
  IL_0002:  ldarg.1
  IL_0003:  call       bool [mscorlib]System.String::op_Equality(string, string)
  IL_0008:  stloc.0
  IL_0009:  ret
} // end of method Foo::OpTest_2

That doesn't use ceq but the string equality operation in mscorlib and will give a result as expected.

Like I said, just to add another way of researching this issue. For more high level details I'd recommend reading @JonSkeet's answer.


问:
Which view should be used for new Material Design Bottom Navigation?
I am sure that y'all have heard about the addition of bottom navigation to the material design guidelines. I am planning on adding it to my app. However, I am not sure what the best way to approach it is. What kind of a view would be best to show the bottom bar?</p>

答:
BottomNavigationView is a component added in Google Support Library 25. It provides a quick navigation between top level views within an app. It should be used when application has three to five top-level destinations. My implementation includes the switching between Fragments on Selecting the Menu Items.

Add to the build.gradle of your project module

```<code>compile'com.android.support:design:25.3.1'
</code>```

Create the BottomNavigationView in xml of your layout and provide a menu resource to it:

```<code><android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginEnd="0dp"
    android:layout_marginStart="0dp"
    android:background="?android:attr/windowBackground"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"/>
</code>```

Create a file here navigation.xml in menu resource folder. This file is used for providing the MenuItems in BottomNavigationView

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
   android:id="@+id/navigation_home"
   android:icon="@drawable/ic_home_black_24dp"
   android:title="@string/title_home" />
<item
   android:id="@+id/navigation_dashboard"
   android:icon="@drawable/ic_dashboard_black_24dp"
   android:title="@string/title_dashboard" />

<item
   android:id="@+id/navigation_notifications"
   android:icon="@drawable/ic_notifications_black_24dp"
   android:title="@string/title_notifications" />

<item
   android:id="@+id/navigation_settings"
   android:icon="@drawable/ic_settings_black_24dp"
   android:title="@string/title_settings" />

</menu>
</code>```

With everything in line this much code shows up the BottomBar on running the app. Now lets set the listener for the Click Events OnNavigationItemSelectedListener and OnNavigationItemReselectedListener on Menu Items -

```<code>private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
        = new BottomNavigationView.OnNavigationItemSelectedListener() {

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {

        switch (item.getItemId()) {
            case R.id.navigation_home:
                return true;

            case R.id.navigation_dashboard:
                return true;

            case R.id.navigation_notifications:
                return true;

            case R.id.navigation_settings:
                return true;

        }
        return true;
    }

};

private BottomNavigationView.OnNavigationItemReselectedListener mOnNavigationItemReselectedListener = new BottomNavigationView.OnNavigationItemReselectedListener() {
    @Override
    public void onNavigationItemReselected(@NonNull MenuItem item) {

        switch (item.getItemId()) {

            case R.id.navigation_home:
                Log.d(TAG, "Navigation Reselected ===");
                break;

            case R.id.navigation_dashboard:
                Log.d(TAG, "Dashboard Reselected ===");
                break;

            case R.id.navigation_notifications:
                Log.d(TAG, "Notification Reselected ===");
                break;

            case R.id.navigation_settings:
                Log.d(TAG, "Settings Reselected ===");
                break;
        }

    }
};

bottomNavigationView.setOnNavigationItemSelectedListener
(mOnNavigationItemSelectedListener);

bottomNavigationView.setOnNavigationItemReselectedListener
(mOnNavigationItemReselectedListener);
</code>```

If the no of Menu Items are more than 3 then the selected Item will take more space in the BottomNavView and it looks a little weird as of now, may be intentionally Google has kept it like this.

This behavior is defined by ShiftingMode property of BottomNavigationView, which can't be disabled in a straightforward way as of now, as its api is not public. But there is a way through Reflection to do it :

```<code>BottomNavigationMenuView menuView = (BottomNavigationMenuView)
btmNavigationView.getChildAt(0);

try {

        Field shiftingMode = menuView.getClass()
        .getDeclaredField("mShiftingMode");

        shiftingMode.setAccessible(true);
        shiftingMode.setBoolean(menuView, false);
        shiftingMode.setAccessible(false);

        for (int i = 0; i < menuView.getChildCount(); i++) {

        BottomNavigationItemView item =
        (BottomNavigationItemView) menuView.getChildAt(i);
        item.setShiftingMode(false);
        //To update view, set the checked value again
        item.setChecked(item.getItemData().isChecked());
        }

    } catch (NoSuchFieldException e) {
        e.printStackTrace();

    } catch (IllegalAccessException e) {
        e.printStackTrace();

    } catch (SecurityException e) {
        e.printStackTrace();
    }
</code>```

After calling above code result is :

For more information checkout my Github Project:
https://github.com/pmahsky/BottomNavigationViewDemo

Body:
BottomNavigationView is a component added in Google Support Library 25. It provides a quick navigation between top level views within an app. It should be used when application has three to five top-level destinations. My implementation includes the switching between Fragments on Selecting the Menu Items.

Add to the build.gradle of your project module

compile'com.android.support:design:25.3.1'

Create the BottomNavigationView in xml of your layout and provide a menu resource to it:

<android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginEnd="0dp"
    android:layout_marginStart="0dp"
    android:background="?android:attr/windowBackground"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"/>

Create a file here navigation.xml in menu resource folder. This file is used for providing the MenuItems in BottomNavigationView

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
   android:id="@+id/navigation_home"
   android:icon="@drawable/ic_home_black_24dp"
   android:title="@string/title_home" />
<item
   android:id="@+id/navigation_dashboard"
   android:icon="@drawable/ic_dashboard_black_24dp"
   android:title="@string/title_dashboard" />

<item
   android:id="@+id/navigation_notifications"
   android:icon="@drawable/ic_notifications_black_24dp"
   android:title="@string/title_notifications" />

<item
   android:id="@+id/navigation_settings"
   android:icon="@drawable/ic_settings_black_24dp"
   android:title="@string/title_settings" />

</menu>

With everything in line this much code shows up the BottomBar on running the app. Now lets set the listener for the Click Events OnNavigationItemSelectedListener and OnNavigationItemReselectedListener on Menu Items -

private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
        = new BottomNavigationView.OnNavigationItemSelectedListener() {

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {

        switch (item.getItemId()) {
            case R.id.navigation_home:
                return true;

            case R.id.navigation_dashboard:
                return true;

            case R.id.navigation_notifications:
                return true;

            case R.id.navigation_settings:
                return true;

        }
        return true;
    }

};

private BottomNavigationView.OnNavigationItemReselectedListener mOnNavigationItemReselectedListener = new BottomNavigationView.OnNavigationItemReselectedListener() {
    @Override
    public void onNavigationItemReselected(@NonNull MenuItem item) {

        switch (item.getItemId()) {

            case R.id.navigation_home:
                Log.d(TAG, "Navigation Reselected ===");
                break;

            case R.id.navigation_dashboard:
                Log.d(TAG, "Dashboard Reselected ===");
                break;

            case R.id.navigation_notifications:
                Log.d(TAG, "Notification Reselected ===");
                break;

            case R.id.navigation_settings:
                Log.d(TAG, "Settings Reselected ===");
                break;
        }

    }
};

bottomNavigationView.setOnNavigationItemSelectedListener
(mOnNavigationItemSelectedListener);

bottomNavigationView.setOnNavigationItemReselectedListener
(mOnNavigationItemReselectedListener);

If the no of Menu Items are more than 3 then the selected Item will take more space in the BottomNavView and it looks a little weird as of now, may be intentionally Google has kept it like this.

This behavior is defined by ShiftingMode property of BottomNavigationView, which can't be disabled in a straightforward way as of now, as its api is not public. But there is a way through Reflection to do it :

BottomNavigationMenuView menuView = (BottomNavigationMenuView)
btmNavigationView.getChildAt(0);

try {

        Field shiftingMode = menuView.getClass()
        .getDeclaredField("mShiftingMode");

        shiftingMode.setAccessible(true);
        shiftingMode.setBoolean(menuView, false);
        shiftingMode.setAccessible(false);

        for (int i = 0; i < menuView.getChildCount(); i++) {

        BottomNavigationItemView item =
        (BottomNavigationItemView) menuView.getChildAt(i);
        item.setShiftingMode(false);
        //To update view, set the checked value again
        item.setChecked(item.getItemData().isChecked());
        }

    } catch (NoSuchFieldException e) {
        e.printStackTrace();

    } catch (IllegalAccessException e) {
        e.printStackTrace();

    } catch (SecurityException e) {
        e.printStackTrace();
    }

After calling above code result is :

For more information checkout my Github Project:
https://github.com/pmahsky/BottomNavigationViewDemo


问:
there is a method in python like __call__?
If x is an object in whose class the method "--call--" is defined, we can call x() directly to execute the method "--call--". Is there a method like "--call--" via which I call x directly to get the value of an attribute of x ? Thanks</p>

答:
Hello shuairenqin,

You can access the class attribute using object or instance using python several inbuilt method like,

1. object.getitem(self, key)

Called to implement evaluation of self[key]. For sequence types, the accepted keys should be integers and slice objects. Note that the special interpretation of negative indexes (if the class wishes to emulate a sequence type) is up to the getitem() method. If key is of an inappropriate type, TypeError may be raised; if of a value outside the set of indexes for the sequence (after any special interpretation of negative values), IndexError should be raised. For mapping types, if key is missing (not in the container), KeyError should be raised.

```<code>Note for loops expect that an IndexError will be raised for illegal indexes to allow proper detection of the end of the sequence.
</code>```

For Example,

```<code>class Library:
    def __init__(self):
         self.books = { 'title' : 1, 'title2' : 2, 'title3' : 2 }
    def __getitem__(self, i):
             return self.books[i]
    def __iter__(self):
        return self.books.itervalues()

librarya = Library()
print librarya['title']
</code>```

2. object.call(self[, args...])

Called when the instance is “called” as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x.call(arg1, arg2, ...).

For Example,

```<code>class Animal(object):
    def __init__(self, name, legs):
        self.name = name
        self.legs = legs
        self.stomach = []

    def __call__(self,food):
        self.stomach.append(food)

    def poop(self):
        if len(self.stomach) > 0:
            return self.stomach.pop(0)

    def __str__(self):
        return 'A animal named %s' % (self.name)

cow = Animal('king', 4)  #We make a cow
dog = Animal('flopp', 4) #We can make many animals
print 'We have 2 animales a cow name %s and dog named %s,both have %s legs' % (cow.name, dog.name, cow.legs)
print cow  #here __str__ metod work

#We give food to cow
cow('gras')
print cow.stomach

#We give food to dog
dog('bone')
dog('beef')
print dog.stomach

#What comes inn most come out
print cow.poop()
print cow.stomach  #Empty stomach

print cow
'''-->output
We have 2 animales a cow name king and dog named flopp,both have 4 legs
A animal named king
['gras']
['bone', 'beef']
gras
[]
'''
</code>```

3. object.getattr(self, name)

Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception.

Note that if the attribute is found through the normal mechanism, getattr() is not called. (This is an intentional asymmetry between getattr() and setattr().) This is done both for efficiency reasons and because otherwise getattr() would have no way to access other attributes of the instance. Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the getattribute() method below for a way to actually get total control in new-style classes.

For Example,

```<code>class MyClass(object):

    def __init__(self):
        self.data = {'name1': 'Vora Mayur', 'name2': 'Vora Mihir'}

    def __getattr__(self, attr):
        return self.data[attr]

obj = MyClass()
print obj.name1
</code>```

Body:
Hello shuairenqin,

You can access the class attribute using object or instance using python several inbuilt method like,

1. object.getitem(self, key)

Called to implement evaluation of self[key]. For sequence types, the accepted keys should be integers and slice objects. Note that the special interpretation of negative indexes (if the class wishes to emulate a sequence type) is up to the getitem() method. If key is of an inappropriate type, TypeError may be raised; if of a value outside the set of indexes for the sequence (after any special interpretation of negative values), IndexError should be raised. For mapping types, if key is missing (not in the container), KeyError should be raised.

Note for loops expect that an IndexError will be raised for illegal indexes to allow proper detection of the end of the sequence.

For Example,

class Library:
    def __init__(self):
         self.books = { 'title' : 1, 'title2' : 2, 'title3' : 2 }
    def __getitem__(self, i):
             return self.books[i]
    def __iter__(self):
        return self.books.itervalues()

librarya = Library()
print librarya['title']

2. object.call(self[, args...])

Called when the instance is “called” as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x.call(arg1, arg2, ...).

For Example,

class Animal(object):
    def __init__(self, name, legs):
        self.name = name
        self.legs = legs
        self.stomach = []

    def __call__(self,food):
        self.stomach.append(food)

    def poop(self):
        if len(self.stomach) > 0:
            return self.stomach.pop(0)

    def __str__(self):
        return 'A animal named %s' % (self.name)

cow = Animal('king', 4)  #We make a cow
dog = Animal('flopp', 4) #We can make many animals
print 'We have 2 animales a cow name %s and dog named %s,both have %s legs' % (cow.name, dog.name, cow.legs)
print cow  #here __str__ metod work

#We give food to cow
cow('gras')
print cow.stomach

#We give food to dog
dog('bone')
dog('beef')
print dog.stomach

#What comes inn most come out
print cow.poop()
print cow.stomach  #Empty stomach

print cow
'''-->output
We have 2 animales a cow name king and dog named flopp,both have 4 legs
A animal named king
['gras']
['bone', 'beef']
gras
[]
'''

3. object.getattr(self, name)

Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception.

Note that if the attribute is found through the normal mechanism, getattr() is not called. (This is an intentional asymmetry between getattr() and setattr().) This is done both for efficiency reasons and because otherwise getattr() would have no way to access other attributes of the instance. Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the getattribute() method below for a way to actually get total control in new-style classes.

For Example,

class MyClass(object):

    def __init__(self):
        self.data = {'name1': 'Vora Mayur', 'name2': 'Vora Mihir'}

    def __getattr__(self, attr):
        return self.data[attr]

obj = MyClass()
print obj.name1


问:
how to split number in digits and add a character in between
Input : 2134
Desired Output : 21:34

How to get that result with PIG?

答:
```<code>output_relation = foreach input_relation generate CONCAT(SUBSTRING((chararray)Number,0,2),':',SUBSTRING((chararray)Number,2,4)) ;
</code>```

above code will give you (:) between no, I have taken 2134 as (Number:Int)

Body:
output_relation = foreach input_relation generate CONCAT(SUBSTRING((chararray)Number,0,2),':',SUBSTRING((chararray)Number,2,4)) ;

above code will give you (:) between no, I have taken 2134 as (Number:Int)


问:
Why can't I directly assign an int to an int pointer like this: int *p = 6;?
error: invalid conversion from 'int' to 'int*'

int *q = 8;

Works fine.

*q = 6;

Why can't I directly assign an int to an int pointer like this: int *q = 6; and I can assign it safely in the next line?

答:
If you re-write it like this:

```<code>int* q = 8;
    *q = 6;
</code>```

Then you can see the * has two different purposes.

Body:
If you re-write it like this:

int* q = 8;
    *q = 6;

Then you can see the * has two different purposes.


问:
Put a string into dictionary Python
Basically, I have the following file:

```<code>Paris, 458 boulevard Saint-Germain
Paris, 343 boulevard Saint-Germain
Marseille, 343 boulevard Camille Flammarion
Marseille, 29 rue Camille Desmoulins
Marseille, 1 chemin des Aubagnens
Paris, 12 rue des singes
Paris, 34 quai VoLtAiRe
Paris, 34 rue Voltaire
Lille, 120 boulevard Victor Hugo
Marseille, 50 rue Voltaire
Toulouse, 90 rue Voltaire
Marseille, 78 boulevard de la libération
Lille, 30 rue Victor Danel
Mont Saint Martin, 42 rue de Lyon
Mont de Marsan, 100 avenue Pierre de Coubertin
Strasbourg, 391 boulevard de Nancy
Lyon, 56 rue du Docteur Albéric Pont
Lille, 90 rue d'Arras
Lille, 76 impasse Georges Pompidou
Lyon, 2 allée des fleurs
</code>```

Let's consider the first line

```<code>Paris, 458 boulevard Saint-Germain
</code>```

I'd like to split that string and then add 'Paris' as a key in a dictionary, and add "468 boulevard Saint-Germain" as a value.

Then, the following line is

```<code>Paris, 343 boulevard Saint-Germain
</code>```

As I already have Paris in my dictionary, I'd like to add "343 boulevard Saint-Germain" as a second value for Paris.

So far I have the following code:

```<code>import os, sys
import functions

class Addresses:

    def __init__(self):

        self.city = ""
        self.address = ""

addresses = {}

print("Hello")
userInput = input("Type a key : ")
if userInput == 'q':
    line = functions.myReadline(sys.argv[1])
    for line in line:
        addresses[line] = Addresses()
        addresses[line].city = line.split(',')
        addresses[line].address = line.split(',')
    for address in addresses.values():
        print("{0} : adresse correspondante {1}".format(address.city, address.address))
else:
    print("non")
</code>```

Basically I want {0} to be the city and {1} to be the address. But when I execute it, here is what it gives to me:

```<code>Hello
Type a key : q
['Paris', ' 458 boulevard Saint-Germain'] : adresse correspondante ['Paris', ' 458 boulevard Saint-Germain']
['Paris', ' 343 boulevard Saint-Germain'] : adresse correspondante ['Paris', ' 343 boulevard Saint-Germain']
['Marseille', ' 343 boulevard Camille Flammarion'] : adresse correspondante ['Marseille', ' 343 boulevard Camille Flammarion']
['Marseille', ' 29 rue Camille Desmoulins'] : adresse correspondante ['Marseille', ' 29 rue Camille Desmoulins']
['Marseille', ' 1 chemin des Aubagnens'] : adresse correspondante ['Marseille', ' 1 chemin des Aubagnens']
['Paris', ' 12 rue des singes'] : adresse correspondante ['Paris', ' 12 rue des singes']
['Paris', ' 34 quai VoLtAiRe'] : adresse correspondante ['Paris', ' 34 quai VoLtAiRe']
['Paris', ' 34 rue Voltaire'] : adresse correspondante ['Paris', ' 34 rue Voltaire']
['Lille', ' 120 boulevard Victor Hugo'] : adresse correspondante ['Lille', ' 120 boulevard Victor Hugo']
['Marseille', ' 50 rue Voltaire'] : adresse correspondante ['Marseille', ' 50 rue Voltaire']
['Toulouse', ' 90 rue Voltaire'] : adresse correspondante ['Toulouse', ' 90 rue Voltaire']
['Marseille', ' 78 boulevard de la libération'] : adresse correspondante ['Marseille', ' 78 boulevard de la libération']
['Lille', ' 30 rue Victor Danel'] : adresse correspondante ['Lille', ' 30 rue Victor Danel']
['Mont Saint Martin', ' 42 rue de Lyon'] : adresse correspondante ['Mont Saint Martin', ' 42 rue de Lyon']
['Mont de Marsan', ' 100 avenue Pierre de Coubertin'] : adresse correspondante ['Mont de Marsan', ' 100 avenue Pierre de Coubertin']
['Strasbourg', ' 391 boulevard de Nancy'] : adresse correspondante ['Strasbourg', ' 391 boulevard de Nancy']
['Lyon', ' 56 rue du Docteur Albéric Pont'] : adresse correspondante ['Lyon', ' 56 rue du Docteur Albéric Pont']
['Lille', " 90 rue d'Arras"] : adresse correspondante ['Lille', " 90 rue d'Arras"]
['Lille', ' 76 impasse Georges Pompidou'] : adresse correspondante ['Lille', ' 76 impasse Georges Pompidou']
['Lyon', ' 2 allée des fleurs'] : adresse correspondante ['Lyon', ' 2 allée des fleurs']
</code>```

Could you please help? Thanks

答:
Should you not do:

```<code>addresses[line] = Addresses()
parts = line.split(',')
addresses[line].city = parts[0]
addresses[line].address = part[1]
</code>```

?

Title: Put a string into dictionary Python

Body:
Basically, I have the following file:

Paris, 458 boulevard Saint-Germain
Paris, 343 boulevard Saint-Germain
Marseille, 343 boulevard Camille Flammarion
Marseille, 29 rue Camille Desmoulins
Marseille, 1 chemin des Aubagnens
Paris, 12 rue des singes
Paris, 34 quai VoLtAiRe
Paris, 34 rue Voltaire
Lille, 120 boulevard Victor Hugo
Marseille, 50 rue Voltaire
Toulouse, 90 rue Voltaire
Marseille, 78 boulevard de la libération
Lille, 30 rue Victor Danel
Mont Saint Martin, 42 rue de Lyon
Mont de Marsan, 100 avenue Pierre de Coubertin
Strasbourg, 391 boulevard de Nancy
Lyon, 56 rue du Docteur Albéric Pont
Lille, 90 rue d'Arras
Lille, 76 impasse Georges Pompidou
Lyon, 2 allée des fleurs

Let's consider the first line

Paris, 458 boulevard Saint-Germain

I'd like to split that string and then add 'Paris' as a key in a dictionary, and add "468 boulevard Saint-Germain" as a value.

Then, the following line is

Paris, 343 boulevard Saint-Germain

As I already have Paris in my dictionary, I'd like to add "343 boulevard Saint-Germain" as a second value for Paris.

So far I have the following code:

import os, sys
import functions

class Addresses:

    def __init__(self):

        self.city = ""
        self.address = ""

addresses = {}

print("Hello")
userInput = input("Type a key : ")
if userInput == 'q':
    line = functions.myReadline(sys.argv[1])
    for line in line:
        addresses[line] = Addresses()
        addresses[line].city = line.split(',')
        addresses[line].address = line.split(',')
    for address in addresses.values():
        print("{0} : adresse correspondante {1}".format(address.city, address.address))
else:
    print("non")

Basically I want {0} to be the city and {1} to be the address. But when I execute it, here is what it gives to me:

Hello
Type a key : q
['Paris', ' 458 boulevard Saint-Germain'] : adresse correspondante ['Paris', ' 458 boulevard Saint-Germain']
['Paris', ' 343 boulevard Saint-Germain'] : adresse correspondante ['Paris', ' 343 boulevard Saint-Germain']
['Marseille', ' 343 boulevard Camille Flammarion'] : adresse correspondante ['Marseille', ' 343 boulevard Camille Flammarion']
['Marseille', ' 29 rue Camille Desmoulins'] : adresse correspondante ['Marseille', ' 29 rue Camille Desmoulins']
['Marseille', ' 1 chemin des Aubagnens'] : adresse correspondante ['Marseille', ' 1 chemin des Aubagnens']
['Paris', ' 12 rue des singes'] : adresse correspondante ['Paris', ' 12 rue des singes']
['Paris', ' 34 quai VoLtAiRe'] : adresse correspondante ['Paris', ' 34 quai VoLtAiRe']
['Paris', ' 34 rue Voltaire'] : adresse correspondante ['Paris', ' 34 rue Voltaire']
['Lille', ' 120 boulevard Victor Hugo'] : adresse correspondante ['Lille', ' 120 boulevard Victor Hugo']
['Marseille', ' 50 rue Voltaire'] : adresse correspondante ['Marseille', ' 50 rue Voltaire']
['Toulouse', ' 90 rue Voltaire'] : adresse correspondante ['Toulouse', ' 90 rue Voltaire']
['Marseille', ' 78 boulevard de la libération'] : adresse correspondante ['Marseille', ' 78 boulevard de la libération']
['Lille', ' 30 rue Victor Danel'] : adresse correspondante ['Lille', ' 30 rue Victor Danel']
['Mont Saint Martin', ' 42 rue de Lyon'] : adresse correspondante ['Mont Saint Martin', ' 42 rue de Lyon']
['Mont de Marsan', ' 100 avenue Pierre de Coubertin'] : adresse correspondante ['Mont de Marsan', ' 100 avenue Pierre de Coubertin']
['Strasbourg', ' 391 boulevard de Nancy'] : adresse correspondante ['Strasbourg', ' 391 boulevard de Nancy']
['Lyon', ' 56 rue du Docteur Albéric Pont'] : adresse correspondante ['Lyon', ' 56 rue du Docteur Albéric Pont']
['Lille', " 90 rue d'Arras"] : adresse correspondante ['Lille', " 90 rue d'Arras"]
['Lille', ' 76 impasse Georges Pompidou'] : adresse correspondante ['Lille', ' 76 impasse Georges Pompidou']
['Lyon', ' 2 allée des fleurs'] : adresse correspondante ['Lyon', ' 2 allée des fleurs']

Could you please help? Thanks

Body:
Should you not do:

addresses[line] = Addresses()
parts = line.split(',')
addresses[line].city = parts[0]
addresses[line].address = part[1]

?


问:
UIDatePicker minimal value?
In Swift, I have a var datePicker = UIDatePicker(). I'm trying to set the datePicker to have a minimum value of Jan, 1st, 1920 (I want a range from Jan, 1st, 1920 to current date. I read how to set the maximumDate of the UIDatePicker, that was easy, but I couldn't find how to set the minimum to a specific date. I read that it should be datePicker.minimumDate but I'm not sure how to set the exact date from above. Suggestions?

答:
You can use the NSDateFormatter as the following:</p>

```<code>let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY-MM-DD"
let date = dateFormatter.dateFromString("1920-01-01")

let datePicker = UIDatePicker()
datePicker.minimumDate = date
</code>```

Title: UIDatePicker minimal value?

Body:
You can use the NSDateFormatter as the following:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY-MM-DD"
let date = dateFormatter.dateFromString("1920-01-01")

let datePicker = UIDatePicker()
datePicker.minimumDate = date


答: Because C# doesn't support this level of type inferencing. Your alternatives are to use a language, such as F#, that does support this level of type inferencing or beg the C# team to implement the feature. I've got a pretty good guess which one you'll have more luck with...</p>

Title: var in class gives error

Body:
Possible Duplicate:

  Using var outside of a method

class A {
string X;
}
// Proper
class A {
var X;
}
// Improper (gives error)

Why is it, that i cant have var type variable declare in Class and what can be done in order to achieve it OR what is an alternative ?

In function/method, i can declare a var type variable,then why can't, i do it in class ?

Thanks.


问:
Why does my code not work (diary code)?
This is a code of a diary. I want the user to write something in the diary and this is gonna be the first page and gonna be put in a list. After writing enter the next page should be started and he writes something in the next page etc.
I get errors over and over and I don't know why. After writing "enter" I get errors. I am new to java and all in all programming/coding (if it's the same). Sorry if it's a really dumb question i'm asking :/
Thank you for every advice. I am thankful for everything because I want to learn as much as I can for my university which would be in 1 year.</p>

```<code>import java.util.ArrayList;
import java.util.Scanner;

public class NotizbuchKlasse{
    public static void Pages(){
        System.out.println("Tag 1 : Write something in your diary.");
        System.out.println("Write enter if you are done writing.");
        ArrayList<String> List = new ArrayList<String>();
        String ListInList;
        Scanner write;
        do{
            write = new Scanner(System.in);
            ListInList = write.next();}
        while (! ListInList.equals("enter"));
        System.out.println("This is now your page. Your page is gonna be
        created after writing something new.");
        String y = ListInList;
        List.add(y);
        write.close();
        Pages();
    }
public static void main(String[]Args){
    Pages();
}
}

day 1 : Write something in your diary.
Write enter if you are done writing.
hello diary
enter
This is now your page. Your page is gonna be created after writing something
new.
Exception in thread "main" day 1 : Write something in your diary.
Write enter if you are done writing.
java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:14)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:20)
    at NotizbuchKlasse.main(NotizbuchKlasse.java:38)
</code>```

答:
First of all, when you are reading the operation sign you need to read it as an String since it is not an Integer.
Moreover, when comparing Strings you should use the equals method.
Finally, when performing the division you should cast one of the operands to float to obtain a float result (otherwise you will obtain the casted division - int -).

This said, your code should look like:

```<code>import java.util.Scanner;

public class Taschenrechner {

    public static void calculator() {
        Scanner input = new Scanner(System.in);
        // Read input numbers
        System.out.println("Give me the 2 numbers first: ");
        int x = input.nextInt();
        int y = input.nextInt();

        // Read operation
        System.out.println("Now give me the operation (+,-,*,/): ");
        String operation = input.next();

        // Perform operation
        float result = 0;
        if (operation.equals("+")) {
            result = x + y;
        } else if (operation.equals("-")) {
            result = x - y;
        } else if (operation.equals("*")) {
            result = x * y;
        } else if (operation.equals("/")) {
            // Add float casting to one of the operands to obtain a float result
            result = x / ((float) y);
        } else {
            System.err.println("ERROR: Unrecognised operation " + operation);
        }

        // Print result
        System.out.println("Result: " + result);

        // Close scanner
        input.close();
    }

    public static void main(String[] args) {
        calculator();
    }
}
</code>```

Notice that:

I have moved the result print to the end of the function since you are duplicating code.

I have added an else case for the operations that are not supported.

The Strings are compared using the equals method.

If you want you can change the if, if-else, else by a switch-case.

Title: Why does my code not work (diary code)?

Body:
This is a code of a diary. I want the user to write something in the diary and this is gonna be the first page and gonna be put in a list. After writing enter the next page should be started and he writes something in the next page etc.
I get errors over and over and I don't know why. After writing "enter" I get errors. I am new to java and all in all programming/coding (if it's the same). Sorry if it's a really dumb question i'm asking :/
Thank you for every advice. I am thankful for everything because I want to learn as much as I can for my university which would be in 1 year.

import java.util.ArrayList;
import java.util.Scanner;

public class NotizbuchKlasse{
    public static void Pages(){
        System.out.println("Tag 1 : Write something in your diary.");
        System.out.println("Write enter if you are done writing.");
        ArrayList<String> List = new ArrayList<String>();
        String ListInList;
        Scanner write;
        do{
            write = new Scanner(System.in);
            ListInList = write.next();}
        while (! ListInList.equals("enter"));
        System.out.println("This is now your page. Your page is gonna be
        created after writing something new.");
        String y = ListInList;
        List.add(y);
        write.close();
        Pages();
    }
public static void main(String[]Args){
    Pages();
}
}

day 1 : Write something in your diary.
Write enter if you are done writing.
hello diary
enter
This is now your page. Your page is gonna be created after writing something
new.
Exception in thread "main" day 1 : Write something in your diary.
Write enter if you are done writing.
java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:14)
    at NotizbuchKlasse.Pages(NotizbuchKlasse.java:20)
    at NotizbuchKlasse.main(NotizbuchKlasse.java:38)

Body:
First of all, when you are reading the operation sign you need to read it as an String since it is not an Integer.
Moreover, when comparing Strings you should use the equals method.
Finally, when performing the division you should cast one of the operands to float to obtain a float result (otherwise you will obtain the casted division - int -).

This said, your code should look like:

import java.util.Scanner;

public class Taschenrechner {

    public static void calculator() {
        Scanner input = new Scanner(System.in);
        // Read input numbers
        System.out.println("Give me the 2 numbers first: ");
        int x = input.nextInt();
        int y = input.nextInt();

        // Read operation
        System.out.println("Now give me the operation (+,-,*,/): ");
        String operation = input.next();

        // Perform operation
        float result = 0;
        if (operation.equals("+")) {
            result = x + y;
        } else if (operation.equals("-")) {
            result = x - y;
        } else if (operation.equals("*")) {
            result = x * y;
        } else if (operation.equals("/")) {
            // Add float casting to one of the operands to obtain a float result
            result = x / ((float) y);
        } else {
            System.err.println("ERROR: Unrecognised operation " + operation);
        }

        // Print result
        System.out.println("Result: " + result);

        // Close scanner
        input.close();
    }

    public static void main(String[] args) {
        calculator();
    }
}

Notice that:

I have moved the result print to the end of the function since you are duplicating code.

I have added an else case for the operations that are not supported.

The Strings are compared using the equals method.

If you want you can change the if, if-else, else by a switch-case.


答:
Create appropriate date components

```<code>let components = DateComponents(year: 1920, month: 1, day: 1)
</code>```

Create a date from the components

```<code>let minimumDate = Calendar.current.date(from: components)
</code>```

Set the minimum date

```<code>let picker = UIDatePicker()
picker.minimumDate = minimumDate
</code>```

Title: UIDatePicker minimal value?

Body: In Swift, I have a var datePicker = UIDatePicker(). I'm trying to set the datePicker to have a minimum value of Jan, 1st, 1920 (I want a range from Jan, 1st, 1920 to current date. I read how to set the maximumDate of the UIDatePicker, that was easy, but I couldn't find how to set the minimum to a specific date. I read that it should be datePicker.minimumDate but I'm not sure how to set the exact date from above. Suggestions?

Body:
Create appropriate date components

let components = DateComponents(year: 1920, month: 1, day: 1)

Create a date from the components

let minimumDate = Calendar.current.date(from: components)

Set the minimum date

let picker = UIDatePicker()
picker.minimumDate = minimumDate


答:
This code

```<code>{
    dat1 = new ArrayList<>();
}
</code>```

This constructor block. Which will be executed every constructor after super() , so it will not run on Mark1 yet.

If you have code like this, it will be executed when class is loaded.

```<code>static {
    dat1 = new ArrayList<>();
}
</code>```

more detail here
http://www.jusfortechies.com/java/core-java/static-blocks.php

Title: Static Initialization in Java?

Body:
I was trying to execute the following code:

public class StaticTest {

    private static List<String> dat1;
    {
        dat1 = new ArrayList<>();
    }

    private StaticTest(){
        System.out.println(dat1.contains("a")); //Marked Line 2: this one is not throwing
    }

    public static void main(String[] args) {
        System.out.println(dat1.contains("a")); //Marked Line 1: This line throws null pointer
        new StaticTest();
    }
}

I tried to execute the above code, I got Null pointer exception at Marked Line 1. But when I commented Marked Line 1 I got the output.

Why am I getting the exception in first case and not in second ?

When I use private static List<String> dat1= new ArrayList<>();, no exception is thrown.

Body:
This code

{
    dat1 = new ArrayList<>();
}

This constructor block. Which will be executed every constructor after super() , so it will not run on Mark1 yet.

If you have code like this, it will be executed when class is loaded.

static {
    dat1 = new ArrayList<>();
}

more detail here
http://www.jusfortechies.com/java/core-java/static-blocks.php


问:
How can I wrap each element in a slot?
I wrote a component (Component B) that accepts list of custom components via slot like this

```<code>// Component A
<div class="component-a">
  ...
  <component-b>
    <component-x></component-x>
    <component-y></component-y>
  </component-b>
  ...
</div>
</code>```

and I want to wrap component x and y in other component, such as li tag.

```<code>// Output
...
<ul>
  <li><component-x></component-x></li>
  <li><component-y></component-y></li>
</ul>
...
</code>```

I tried with

```<code>// Component B
<div class="component-b">
  <ul>
    <li v-for="item in $slots.default">
      <component :is="item"></component>
    </li>
  </ul>
</div>
</code>```

It doesn't work. The item is VNode object and it can't render with component tag. Is there any solution to solve this problem?

Edit: My wrapping component is not li tag, it's a custom component with specified props that I set it in component B. If I wrap them from component A, I need to write the custom component and its props repeatedly.

Edit2: Render function maybe solve this problem, but I'm looking for solution with html template (single file component).

答:
This works?

```<code><div class="component-a">
  <component-b>
    <component-x></component-x>
    <component-y></component-y>
  </component-b>
</div>
</code>```

Then use

```<code><div class="component-a">
  <component-b>
    <ul>
      <li><component-x></component-x></li>
      <li><component-y></component-y></li>
    </ul>
  </component-b>
</div>
</code>```

Title: How can I wrap each element in a slot?

Body:
I wrote a component (Component B) that accepts list of custom components via slot like this

// Component A

  ...
  <component-b>
    <component-x></component-x>
    <component-y></component-y>
  </component-b>
  ...

and I want to wrap component x and y in other component, such as li tag.

// Output
...

<component-x></component-x>

<component-y></component-y>

...

I tried with

// Component B

      <component :is="item"></component>

It doesn't work. The item is VNode object and it can't render with component tag. Is there any solution to solve this problem?

Edit: My wrapping component is not li tag, it's a custom component with specified props that I set it in component B. If I wrap them from component A, I need to write the custom component and its props repeatedly.

Edit2: Render function maybe solve this problem, but I'm looking for solution with html template (single file component).

Body:
This works?

<div class="component-a">
  <component-b>
    <component-x></component-x>
    <component-y></component-y>
  </component-b>
</div>

Then use

<div class="component-a">
  <component-b>
    <ul>
      <li><component-x></component-x></li>
      <li><component-y></component-y></li>
    </ul>
  </component-b>
</div>


问:
Validation error with simple-schema
I'm trying to insert an array into an object and I'm not having any luck. I think the schema is rejecting it based on validation but I'm not sure why. If I console.log(this.state.typeOfWork) and check typeof it states its an Object which contains:

```<code>(2) ["Audit - internal", "Audit - external"]
0: "Audit - internal"
1: "Audit - external"
</code>```

My collection after an update contains:

```<code>"roleAndSkills": {
    "typeOfWork": []
  }
</code>```

Example: Schema

```<code>roleAndSkills: { type: Object, optional: true },
  'roleAndSkills.typeOfWork': { type: Array, optional: true },
  'roleAndSkills.typeOfWork.$': { type: String, optional: true }
</code>```

Example: update

```<code>ProfileCandidate.update(this.state.profileCandidateCollectionId, {
      $set: {
        roleAndSkills: {
          typeOfWork: [this.state.typeOfWork]
        }
      }
    });
</code>```

答:
Simple schema has some problems with validation on Objects or Arrays, i had the same problem in a recent app i developed.

What can you do?
well, what i did, on the Collections.js file, when you are saying:

```<code>typeOfWork:{
  type: Array
}
</code>```

Try adding the property blackbox:true, like this:

```<code>typeOfWork:{
  blackbox: true,
  type: Array
}
</code>```

This will tell your Schema that this field is taking an Array, but ignore further validation.

The validation i made was on main.js, just to be sure i had no empty array and the data was plain text.

As requested here is my update method, im my case i used objects not arrays but it works the same way.

```<code> editUser: function (editedUserVars, uid) {
      console.log(uid);
      return Utilizadores.update(
        {_id: uid},
        {$set:{
          username: editedUserVars.username,
          usernim: editedUserVars.usernim,
          userrank: {short: editedUserVars.userrank.short,
          long: editedUserVars.userrank.long},
          userspec: {short: editedUserVars.userspec.short,
          long: editedUserVars.userspec.long},
          usertype: editedUserVars.usertype}},
        {upsert: true})

    },
</code>```

here it the collection schema

```<code>UtilizadoresSchema = new SimpleSchema({
 username:{
    type: String
 },
 usernim:{
    type: String
 },
 userrank:{
    blackbox: true,
    type: Object
 },
 userspec:{
    blackbox: true,
    type: Object
 },
 usertype:{
    type: String
 }
});
Utilizadores.attachSchema(UtilizadoresSchema);
</code>```

Hope it helps

Rob

Title: Validation error with simple-schema

Body:
I'm trying to insert an array into an object and I'm not having any luck. I think the schema is rejecting it based on validation but I'm not sure why. If I console.log(this.state.typeOfWork) and check typeof it states its an Object which contains:

(2) ["Audit - internal", "Audit - external"]
0: "Audit - internal"
1: "Audit - external"

My collection after an update contains:

"roleAndSkills": {
    "typeOfWork": []
  }

Example: Schema

roleAndSkills: { type: Object, optional: true },
  'roleAndSkills.typeOfWork': { type: Array, optional: true },
  'roleAndSkills.typeOfWork.$': { type: String, optional: true }

Example: update

ProfileCandidate.update(this.state.profileCandidateCollectionId, {
      $set: {
        roleAndSkills: {
          typeOfWork: [this.state.typeOfWork]
        }
      }
    });

Body:
Simple schema has some problems with validation on Objects or Arrays, i had the same problem in a recent app i developed.

What can you do?
well, what i did, on the Collections.js file, when you are saying:

typeOfWork:{
  type: Array
}

Try adding the property blackbox:true, like this:

typeOfWork:{
  blackbox: true,
  type: Array
}

This will tell your Schema that this field is taking an Array, but ignore further validation.

The validation i made was on main.js, just to be sure i had no empty array and the data was plain text.

As requested here is my update method, im my case i used objects not arrays but it works the same way.

 editUser: function (editedUserVars, uid) {
      console.log(uid);
      return Utilizadores.update(
        {_id: uid},
        {$set:{
          username: editedUserVars.username,
          usernim: editedUserVars.usernim,
          userrank: {short: editedUserVars.userrank.short,
          long: editedUserVars.userrank.long},
          userspec: {short: editedUserVars.userspec.short,
          long: editedUserVars.userspec.long},
          usertype: editedUserVars.usertype}},
        {upsert: true})

    },

here it the collection schema

UtilizadoresSchema = new SimpleSchema({
 username:{
    type: String
 },
 usernim:{
    type: String
 },
 userrank:{
    blackbox: true,
    type: Object
 },
 userspec:{
    blackbox: true,
    type: Object
 },
 usertype:{
    type: String
 }
});
Utilizadores.attachSchema(UtilizadoresSchema);

Hope it helps

Rob