问:
Rouer outlet *ngIF
I have the following app structure:

master.html - my app component HTML template structure:

```<code><header>
<sidebar-right>
<sidebar-left>

<router-outlet>

<footer>
</code>```

Now.. I have 2 scenarios:

Guests

Logged in user

If the user is a guest, I need to display the <intro></intro> component without the sidebars, and if the user is a logged in member, show the router outlet with all those tags (sidebars, header, etc..)

How I can do that? Since I can't use the router outlet inside *ngIf, I have no idea how to make it work the way described above.

Any ideas?

Desired output idea:

```<code><section *ngIf="loggedIn">
<header>
    <sidebar-right>
    <sidebar-left>

    <router-outlet>

    <footer>
</section>
<section *ngIf="!loggedIn">
<intro></intro>
</section>
</code>```

答:
Put the Guest View and the User View in two different routes and then add a Route Guard, which will serve as a condition for a route being viewable. This does what the *ngIf would have if it worked on the router-outlet tag.

Move the contents that you want the Logged-In user to see out of the app component HTML template and into a component of its own. Do the same for the contents for the Guest User.

Add both components as routes in your route configuration and set the 'canActivate' value of the component for Logged-In user to an imported 'authentication guard service'(that you will create):

```<code>import { AuthGuardService } from '../auth-guard.service';

const routes: Routes = [
  { path: 'guest',
    component: guestComponent
  },
  { path: 'logged-in-user',
    component: loggedInUserComponent,
    canActivate: [AuthGuardService]
  }
];
</code>```

Create the Guard Service:

```<code>import { Injectable }     from '@angular/core';
import { CanActivate }    from '@angular/router';

@Injectable()
export class AuthGuardService implements CanActivate {
  loggedIn: boolean;

  canActivate() {
    return this.loggedIn;
  }
}
</code>```

The loggedInUser component can only be navigated to and viewed if the loggedIn value is true.

You can find this and more the documentation on the angular.io site:
https://angular.io/docs/ts/latest/guide/router.html#!#guards

Title: Rouer outlet *ngIF

Body:
I have the following app structure:

master.html - my app component HTML template structure:

<sidebar-right>
<sidebar-left>

<router-outlet>

Now.. I have 2 scenarios:

Guests

Logged in user

If the user is a guest, I need to display the <intro></intro> component without the sidebars, and if the user is a logged in member, show the router outlet with all those tags (sidebars, header, etc..)

How I can do that? Since I can't use the router outlet inside *ngIf, I have no idea how to make it work the way described above.

Any ideas?

Desired output idea:

    <sidebar-right>
    <sidebar-left>

    <router-outlet>

<intro></intro>

Body:
Put the Guest View and the User View in two different routes and then add a Route Guard, which will serve as a condition for a route being viewable. This does what the *ngIf would have if it worked on the router-outlet tag.

Move the contents that you want the Logged-In user to see out of the app component HTML template and into a component of its own. Do the same for the contents for the Guest User.

Add both components as routes in your route configuration and set the 'canActivate' value of the component for Logged-In user to an imported 'authentication guard service'(that you will create):

import { AuthGuardService } from '../auth-guard.service';

const routes: Routes = [
  { path: 'guest',
    component: guestComponent
  },
  { path: 'logged-in-user',
    component: loggedInUserComponent,
    canActivate: [AuthGuardService]
  }
];

Create the Guard Service:

import { Injectable }     from '@angular/core';
import { CanActivate }    from '@angular/router';

@Injectable()
export class AuthGuardService implements CanActivate {
  loggedIn: boolean;

  canActivate() {
    return this.loggedIn;
  }
}

The loggedInUser component can only be navigated to and viewed if the loggedIn value is true.

You can find this and more the documentation on the angular.io site:
https://angular.io/docs/ts/latest/guide/router.html#!#guards


来源: stackexchange

问:
How to match two values independently of their respectiv postions in a string
I'm searching for the best way to match two values simultaneously.

I'd like to get a true value if both values are in a string but i don't know in which order they appear in the string (e.g. abcdef or bedfa in case i want to match a and b)

Is there a better solution (especially if later I would need more complex values to match) than:

```<code>$string =~ m/(a.*b)|(b.*a)/i
</code>```

答:
Why not just this?

```<code>$string =~ /a/i && $string =~ /b/i
</code>```

It's more legible.

ContentLicense: CC BY-SA 2.5

Body:
I'm searching for the best way to match two values simultaneously.

I'd like to get a true value if both values are in a string but i don't know in which order they appear in the string (e.g. abcdef or bedfa in case i want to match a and b)

Is there a better solution (especially if later I would need more complex values to match) than:

$string =~ m/(a.*b)|(b.*a)/i

Body:
Why not just this?

$string =~ /a/i && $string =~ /b/i

It's more legible.


问:
awk match command and memory usage
I realised that my awk script was using more and more memory as time goes, when I wasn't supposed to store anything in memory so I decided to do some tests.

This is a very simple script (mine is bigger, but I reproduce the problem on a very basic one). My awk script is used inside a bash script, the $file variable is the file on which the awk runs.

```<code>awk '
{
    if(match($0,"word"))
    {
        line=substr($0, RSTART - 20, RLENGTH + 20)
        print line
    }
}
' "$file"
</code>```

If I execute this script on a big file, in which each line contains word, the memory usage of the awk script is raising super fast, even faster if I print to a file. I have to stop it before it freezes my computer. Do you have an idea what is causing this big memory usage ?
In my real script, the files are usually smaller and the match function is not triggered every line like in this function, but I would prefer to be sure nothing wrong  will happen.

EDIT : This problem doesn't seem to appear while using mawk, only with GNU awk, I have no idea why.

答:
Trying this alternative

```<code>awk '
/word/ {
        # you can match here, if result of operation is needed for later action
        print "hello"
   }
' "$file"
</code>```

match on every line induce some more computation like define the index of the longest occurence (testing lot of possibilities), ... so yes it is exponantial with file size (and line size inside)

If match is a conditionnal part that cannotn be separate from surrounding code, use at least index() in place of match() (or better if( $0 ~ /word/) if not other result than checking presence is the goal)

ContentLicense: CC BY-SA 3.0

Title: awk match command and memory usage

Body:
I realised that my awk script was using more and more memory as time goes, when I wasn't supposed to store anything in memory so I decided to do some tests.

This is a very simple script (mine is bigger, but I reproduce the problem on a very basic one). My awk script is used inside a bash script, the $file variable is the file on which the awk runs.

awk '
{
    if(match($0,"word"))
    {
        line=substr($0, RSTART - 20, RLENGTH + 20)
        print line
    }
}
' "$file"

If I execute this script on a big file, in which each line contains word, the memory usage of the awk script is raising super fast, even faster if I print to a file. I have to stop it before it freezes my computer. Do you have an idea what is causing this big memory usage ?
In my real script, the files are usually smaller and the match function is not triggered every line like in this function, but I would prefer to be sure nothing wrong  will happen.

EDIT : This problem doesn't seem to appear while using mawk, only with GNU awk, I have no idea why.

Body:
Trying this alternative

awk '
/word/ {
        # you can match here, if result of operation is needed for later action
        print "hello"
   }
' "$file"

match on every line induce some more computation like define the index of the longest occurence (testing lot of possibilities), ... so yes it is exponantial with file size (and line size inside)

If match is a conditionnal part that cannotn be separate from surrounding code, use at least index() in place of match() (or better if( $0 ~ /word/) if not other result than checking presence is the goal)


问:
How to close all the threads before main thread by interrupting ctrl+c?
I have created pool of 5 threads using _beginthread() in C. All the threads from pool will run infinitely to do job received from client. For example, when client will be connected, the free thread from pool will handle this. After completing its task the thread will wait for next client. Now my problem is that, whenever I enter ctrl+c from server, the program get terminated. But I want to close all the running and waiting threads from pool before terminating the main thread.

答:
For Windows

```<code>#include <windows.h>
#include <stdio.h>

BOOL WINAPI signal_handler(DWORD signal) {

    if (signal == CTRL_C_EVENT){
        printf("CTRL C caught here .\n");
    }
    return TRUE;
}

main()
{
    ....
    SetConsoleCtrlHandler(signal_handler, TRUE);

   .....

     printf("This should appear after signal_handler\n");
}
</code>```

For linux

```<code>#include<stdio.h>
#include<signal.h>

void signal_handler()
{
    printf("CTRL C caught here .\n");
}

main()
{

    ...
    // SIGINT is signal name create  when Ctrl+c will pressed
    signal(SIGINT,signal_handler);

    printf("This should appear after signal_handler\n");

}
</code>```

Once ctrl-c is captured you can close all the threads and other cleanup stuff

Body:
For Windows

#include <windows.h>
#include <stdio.h>

BOOL WINAPI signal_handler(DWORD signal) {

    if (signal == CTRL_C_EVENT){
        printf("CTRL C caught here .\n");
    }
    return TRUE;
}

main()
{
    ....
    SetConsoleCtrlHandler(signal_handler, TRUE);

   .....

     printf("This should appear after signal_handler\n");
}

For linux

#include<stdio.h>
#include<signal.h>

void signal_handler()
{
    printf("CTRL C caught here .\n");
}

main()
{

    ...
    // SIGINT is signal name create  when Ctrl+c will pressed
    signal(SIGINT,signal_handler);

    printf("This should appear after signal_handler\n");

}

Once ctrl-c is captured you can close all the threads and other cleanup stuff


问:
Select all those rows whose certain columns (and not all the columns) have specific values
I need to select all those rows whose certain columns (and not all the columns) have specific values.

For example:

```<code>SELECT * from TABLE1
WHERE col_A in (1,2)
   or col_B in (1,2)
   or col_C in (1,2)
</code>```

What is the best way to achieve it?

答: SELECT * from TABLE1 WHERE col_A in (&v1,&v2) or col_B in (&v3,&v4) or col_C in (&v5,&v6)</p>

Body:
I need to select all those rows whose certain columns (and not all the columns) have specific values.

For example:

SELECT * from TABLE1
WHERE col_A in (1,2)
   or col_B in (1,2)
   or col_C in (1,2)

What is the best way to achieve it?


问:
mnlogit error when calling predict with newdata
I'd like to fit a model using the mnlogit package and use it to make out-of-sample predictions.  I've set up a toy example using the fishing data that comes with mnlogit:

```<code>library(data.table)
library(mnlogit)

data(Fish, package="mnlogit")
fish_dt <- data.table(Fish)
rm(Fish)

unique_id <- unique(fish_dt[, chid])
set.seed(54321)
train_id <- sample(unique_id, size=0.5*length(unique_id))

setkey(fish_dt, chid, alt)
train <- fish_dt[J(train_id)]
test <- fish_dt[!J(train_id)]
setkey(train, chid, alt)
setkey(test, chid, alt)
stopifnot(nrow(train) + nrow(test) == nrow(fish_dt))  # Partition fish_dt

mnlogit_formula <- mode ~ catch | income
mnlogit_model <- mnlogit(mnlogit_formula, data=train, choiceVar="alt")

train_predictions <- predict(mnlogit_model, probability=F)
stopifnot(length(train_predictions) == length(unique(train[, chid])))  # One per choice
mean(subset(train, mode)[, alt] == train_predictions)  # Around 0.42 accuracy in sample

## Would like to do the same out of sample, i.e. with data table "test"
test_predictions <- predict(mnlogit_model, newdata=test, probability=F)  # Error
test_predictions <- predict(mnlogit_model, newdata=as.data.frame(test), probability=F)  # Same error
</code>```

The error I get is:

Error in colnames<-(*tmp*, value = list(chid = c(1L, 2L, 3L, 4L,
  5L,  :    length of 'dimnames' [2] not equal to array extent

I'm running R version 3.0.2 (2013-09-25) on Ubuntu 14.04.2 LTS.

Am I using the package incorrectly or is this a bug?

Edit:  See comments:  I tried removing the "mode" column from the "test" data table, but that gives me a "newdata must have same columns as training data" error:

```<code>test[, mode := NULL]
mnlogit_predictions <- predict(mnlogit_model, newdata=test, probability=F)  # Error
</code>```

Edit:  Here's an example where I use the mlogit package (which is similar but can be significantly slower for large problems):

```<code>library(data.table)
library(mlogit)

data(Fish, package="mnlogit")
fish_dt <- data.table(Fish)
rm(Fish)

unique_id <- unique(fish_dt[, chid])
set.seed(54321)
train_id <- sample(unique_id, size=0.5*length(unique_id))

setkey(fish_dt, chid, alt)
train <- fish_dt[J(train_id)]
test <- fish_dt[!J(train_id)]
setkey(train, chid, alt)
setkey(test, chid, alt)
stopifnot(nrow(train) + nrow(test) == nrow(fish_dt))  # Partition fish_dt

train_mlogit <- mlogit.data(train, choice="mode", shape="long",
                            chid.var="chid", alt.var="alt")
test_mlogit <- mlogit.data(test, choice="mode", shape="long",
                           chid.var="chid", alt.var="alt")

model_formula <- mode ~ catch | income
mlogit_model <- mlogit(model_formula, data=train_mlogit)

## In-sample performance
train_predictions <- predict(mlogit_model, newdata=train_mlogit)
stopifnot(nrow(train_predictions) == length(unique(train[, chid])))  # One per choice
train_predictions <- colnames(train_predictions)[apply(train_predictions, 1, which.max)]
mean(subset(train, mode)[, alt] == train_predictions)  # Around 0.42 accuracy in sample

## Out-of-sample performance
test_predictions <- predict(mlogit_model, newdata=test_mlogit)
test_predictions <- colnames(test_predictions)[apply(test_predictions, 1, which.max)]
mean(subset(test, mode)[, alt] == test_predictions)  # Around 0.41 accuracy out of sample
</code>```

I'd like to do exactly that, but with mnlogit instead of mlogit.

答:
Predict works well with mnlogit objects. However, your 'test' object is a data table and not mlogit.data object, so you would require to pass choiceVar in the predict call as well.

```<code>test_predictions <- predict(mnlogit_model, newdata=test,choiceVar="alt")  # works
test_predictions <- predict(mnlogit_model, newdata=as.data.frame(test), probability=F,choiceVar="alt")  # this also works
</code>```

Thanks

Body:
I'd like to fit a model using the mnlogit package and use it to make out-of-sample predictions.  I've set up a toy example using the fishing data that comes with mnlogit:

library(data.table)
library(mnlogit)

data(Fish, package="mnlogit")
fish_dt <- data.table(Fish)
rm(Fish)

unique_id <- unique(fish_dt[, chid])
set.seed(54321)
train_id <- sample(unique_id, size=0.5*length(unique_id))

setkey(fish_dt, chid, alt)
train <- fish_dt[J(train_id)]
test <- fish_dt[!J(train_id)]
setkey(train, chid, alt)
setkey(test, chid, alt)
stopifnot(nrow(train) + nrow(test) == nrow(fish_dt))  # Partition fish_dt

mnlogit_formula <- mode ~ catch | income
mnlogit_model <- mnlogit(mnlogit_formula, data=train, choiceVar="alt")

train_predictions <- predict(mnlogit_model, probability=F)
stopifnot(length(train_predictions) == length(unique(train[, chid])))  # One per choice
mean(subset(train, mode)[, alt] == train_predictions)  # Around 0.42 accuracy in sample

## Would like to do the same out of sample, i.e. with data table "test"
test_predictions <- predict(mnlogit_model, newdata=test, probability=F)  # Error
test_predictions <- predict(mnlogit_model, newdata=as.data.frame(test), probability=F)  # Same error

The error I get is:

Error in colnames<-(*tmp*, value = list(chid = c(1L, 2L, 3L, 4L,
  5L,  :    length of 'dimnames' [2] not equal to array extent

I'm running R version 3.0.2 (2013-09-25) on Ubuntu 14.04.2 LTS.

Am I using the package incorrectly or is this a bug?

Edit:  See comments:  I tried removing the "mode" column from the "test" data table, but that gives me a "newdata must have same columns as training data" error:

test[, mode := NULL]
mnlogit_predictions <- predict(mnlogit_model, newdata=test, probability=F)  # Error

Edit:  Here's an example where I use the mlogit package (which is similar but can be significantly slower for large problems):

library(data.table)
library(mlogit)

data(Fish, package="mnlogit")
fish_dt <- data.table(Fish)
rm(Fish)

unique_id <- unique(fish_dt[, chid])
set.seed(54321)
train_id <- sample(unique_id, size=0.5*length(unique_id))

setkey(fish_dt, chid, alt)
train <- fish_dt[J(train_id)]
test <- fish_dt[!J(train_id)]
setkey(train, chid, alt)
setkey(test, chid, alt)
stopifnot(nrow(train) + nrow(test) == nrow(fish_dt))  # Partition fish_dt

train_mlogit <- mlogit.data(train, choice="mode", shape="long",
                            chid.var="chid", alt.var="alt")
test_mlogit <- mlogit.data(test, choice="mode", shape="long",
                           chid.var="chid", alt.var="alt")

model_formula <- mode ~ catch | income
mlogit_model <- mlogit(model_formula, data=train_mlogit)

## In-sample performance
train_predictions <- predict(mlogit_model, newdata=train_mlogit)
stopifnot(nrow(train_predictions) == length(unique(train[, chid])))  # One per choice
train_predictions <- colnames(train_predictions)[apply(train_predictions, 1, which.max)]
mean(subset(train, mode)[, alt] == train_predictions)  # Around 0.42 accuracy in sample

## Out-of-sample performance
test_predictions <- predict(mlogit_model, newdata=test_mlogit)
test_predictions <- colnames(test_predictions)[apply(test_predictions, 1, which.max)]
mean(subset(test, mode)[, alt] == test_predictions)  # Around 0.41 accuracy out of sample

I'd like to do exactly that, but with mnlogit instead of mlogit.

Body:
Predict works well with mnlogit objects. However, your 'test' object is a data table and not mlogit.data object, so you would require to pass choiceVar in the predict call as well.

test_predictions <- predict(mnlogit_model, newdata=test,choiceVar="alt")  # works
test_predictions <- predict(mnlogit_model, newdata=as.data.frame(test), probability=F,choiceVar="alt")  # this also works

Thanks


问:
Why is my Perl test failing incorrectly?
I have created the following testing class:

```<code>package Test::DB;

# $Id$
#

use strict;
use warnings;

our $VERSION = '0.01';

use Carp;
use English '-no_match_vars';
use Test::Most;

use base 'Test::Class';

sub startup : Tests(startup) {
    eval {
        require esp_libs_db;

        esp_libs_db->import;

        1;
    } or Carp::croak($EVAL_ERROR);

    return 1;
}

sub connect : Tests(2) {
    can_ok 'esp_libs_db', 'espDbConnect';

    my $schema = 'test_schema';

    throws_ok { espDbConnect($schema) }
      qr/Cannot locate database ($schema) connection file./,
      'dies when connection file does not exist';

    return 1;
}

1;
</code>```

When I come to run the test I get the following output:

```<code>t/run.t ..
#
# Test::DB->connect
1..2
ok 1 - esp_libs_db->can('espDbConnect')
not ok 2 - dies when connection file does not exist

#   Failed test 'dies when connection file does not exist'
#   at t/tests/Test/DB.pm line 39.
#   (in Test::DB->connect)
# expecting: Regexp ((?-xism:Cannot locate database (test_schema) connection file.))
# found: <FONT color=red size=4 face=arial>ERROR: PM_DB_0004: Cannot locate database (test_schema) connection file.</FONT> at t/tests/Test/DB.pm line 38
# Looks like you failed 1 test of 2.
Dubious, test returned 1 (wstat 256, 0x100)
Failed 1/2 subtests

Test Summary Report
-------------------
t/run.t (Wstat: 256 Tests: 2 Failed: 1)
  Failed test:  2
  Non-zero exit status: 1
Files=1, Tests=2,  3 wallclock secs ( 0.44 usr  0.07 sys +  2.44 cusr  0.43 csys =  3.38 CPU)
Result: FAIL
</code>```

I cannot see why the second test is failing when it should quite clearly pass

答:
( and ) are special characters in regular expressions, try escaping them:

```<code>qr/Cannot locate database \($schema\) connection file./
</code>```

Body:
I have created the following testing class:

package Test::DB;

# $Id$
#

use strict;
use warnings;

our $VERSION = '0.01';

use Carp;
use English '-no_match_vars';
use Test::Most;

use base 'Test::Class';

sub startup : Tests(startup) {
    eval {
        require esp_libs_db;

        esp_libs_db->import;

        1;
    } or Carp::croak($EVAL_ERROR);

    return 1;
}

sub connect : Tests(2) {
    can_ok 'esp_libs_db', 'espDbConnect';

    my $schema = 'test_schema';

    throws_ok { espDbConnect($schema) }
      qr/Cannot locate database ($schema) connection file./,
      'dies when connection file does not exist';

    return 1;
}

1;

When I come to run the test I get the following output:

t/run.t ..
#
# Test::DB->connect
1..2
ok 1 - esp_libs_db->can('espDbConnect')
not ok 2 - dies when connection file does not exist

#   Failed test 'dies when connection file does not exist'
#   at t/tests/Test/DB.pm line 39.
#   (in Test::DB->connect)
# expecting: Regexp ((?-xism:Cannot locate database (test_schema) connection file.))
# found: ERROR: PM_DB_0004: Cannot locate database (test_schema) connection file. at t/tests/Test/DB.pm line 38
# Looks like you failed 1 test of 2.
Dubious, test returned 1 (wstat 256, 0x100)
Failed 1/2 subtests

Test Summary Report
-------------------
t/run.t (Wstat: 256 Tests: 2 Failed: 1)
  Failed test:  2
  Non-zero exit status: 1
Files=1, Tests=2,  3 wallclock secs ( 0.44 usr  0.07 sys +  2.44 cusr  0.43 csys =  3.38 CPU)
Result: FAIL

I cannot see why the second test is failing when it should quite clearly pass

Body:
( and ) are special characters in regular expressions, try escaping them:

qr/Cannot locate database \($schema\) connection file./


问:
Add java List in JsonObject return value
I want to add a list in the json return value. Here is my code -

```<code>    @RequestMapping(value = "/servicearea", produces="application/json")
    @ResponseBody
    public String ServiceArea(Model model, HttpServletRequest req, HttpServletResponse res)
    {

        List<ServiceArea> serviceLists = locationService.getAllServiceArea();

        JsonObject result = Json.createObjectBuilder()
                .add("message", "test")
                .add("serviceLists", serviceLists)
                .build();

        return result.toString();
    }
</code>```

'serviceLists' is the one that I want to add. I'm getting error in this line - .add("serviceLists", serviceLists). Error message is that JsonObjectBuilder is not applicable for the arguments.

Thanks in advance.

答:
Below solution is only useful if you are using Rest API and Spring.

create class ServiceListPojo:

```<code>public class ServiceListPOJO{
List<ServiceArea> serviceLists;

public void setServiceLists(List<ServiceArea> serviceLists){
this.serviceLists = serviceLists;
}
}
</code>```

Annotate your controller with @RestController

```<code>@RestController
public class SomeController{
@RequestMapping(value = "/servicearea")
    public ServiceListPOJO ServiceArea()
    {
        List<ServiceArea> serviceLists = locationService.getAllServiceArea();
        ServiceListPOJO slp = new ServiceListPOJO();
       slp.setServciceLists(serviceLists);
       return slp;
    }
}
</code>```

Body:
I want to add a list in the json return value. Here is my code -

    @RequestMapping(value = "/servicearea", produces="application/json")
    @ResponseBody
    public String ServiceArea(Model model, HttpServletRequest req, HttpServletResponse res)
    {

        List<ServiceArea> serviceLists = locationService.getAllServiceArea();

        JsonObject result = Json.createObjectBuilder()
                .add("message", "test")
                .add("serviceLists", serviceLists)
                .build();

        return result.toString();
    }

'serviceLists' is the one that I want to add. I'm getting error in this line - .add("serviceLists", serviceLists). Error message is that JsonObjectBuilder is not applicable for the arguments.

Thanks in advance.

Body:
Below solution is only useful if you are using Rest API and Spring.

create class ServiceListPojo:

public class ServiceListPOJO{
List<ServiceArea> serviceLists;

public void setServiceLists(List<ServiceArea> serviceLists){
this.serviceLists = serviceLists;
}
}

Annotate your controller with @RestController

@RestController
public class SomeController{
@RequestMapping(value = "/servicearea")
    public ServiceListPOJO ServiceArea()
    {
        List<ServiceArea> serviceLists = locationService.getAllServiceArea();
        ServiceListPOJO slp = new ServiceListPOJO();
       slp.setServciceLists(serviceLists);
       return slp;
    }
}


问:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/hadoop/hbase/HBaseConfiguration
I am using Hadoop 1.0.3 and HBase 0.94.22. I am trying to run a mapper program to read values from a Hbase table and output them to a file. I am getting the following error:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/hadoop/hbase/HBaseConfiguration
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:340)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:149)
Caused by: java.lang.ClassNotFoundException: org.apache.hadoop.hbase.HBaseConfiguration
    at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
```

<p>The code is as below</p>

```import java.io.IOException;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
import org.apache.hadoop.hbase.mapreduce.TableMapper;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

    public class Test {

    static class TestMapper extends TableMapper<Text, IntWritable> {
        private static final IntWritable one = new IntWritable(1);

        public void map(ImmutableBytesWritable row, Result value, Context context) throws    IOException, InterruptedException
        {
            ImmutableBytesWritable userkey = new ImmutableBytesWritable(row.get(), 0 , Bytes.SIZEOF_INT);
            String key =Bytes.toString(userkey.get());
            context.write(new Text(key), one);

        }
    }

    public static void main(String[] args) throws Exception {

        HBaseConfiguration conf = new HBaseConfiguration();
        Job job = new Job(conf, "hbase_freqcounter");
        job.setJarByClass(Test.class);
        Scan scan = new Scan();

        FileOutputFormat.setOutputPath(job, new Path(args[0]));
        String columns = "data";
        scan.addFamily(Bytes.toBytes(columns));
        scan.setFilter(new FirstKeyOnlyFilter());
        TableMapReduceUtil.initTableMapperJob("test",scan, TestMapper.class, Text.class, IntWritable.class, job);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);
        System.exit(job.waitForCompletion(true)?0:1);

    }

}
```

I get the above code exported to a jar file and on the command line I use the below command to run the above code.

hadoop jar /home/testdb.jar test

where test is the folder to which the mapper results should be written.

I have checked a few other links like Caused by: java.lang.ClassNotFoundException: org.apache.zookeeper.KeeperException where it has been suggested to include the zookeeper file in the classpath, but while creating the project in eclipse I have already included zookeeper file from the lib directory of hbase. The file I have included is zookeeper-3.4.5.jar. Ans also visited this link too HBase - java.lang.NoClassDefFoundError in java , but I am using a mapper class to get the values from the hbase table not any client API. I know I am making a mistake somewhere, guys could you please help me out ??

I have noted another strange thing, when I remove all of the code in the main function except the first line " HBaseConfiguration conf = new HBaseConfiguration();", then export the code to a jar file and try to compile the jar file as hadoop jar test.jar I still get the same error. It seems either I am defining the conf variable incorrectly or there is some issue with my environment.

答:
here CreateTable is my java class file

use this command

java -cp .:/home/hadoop/hbase/hbase-0.94.8/hbase-0.94.8.jar:/home/hadoop/hbase/hbase-0.94.8/lib/*  CreateTable

Body:
I am using Hadoop 1.0.3 and HBase 0.94.22. I am trying to run a mapper program to read values from a Hbase table and output them to a file. I am getting the following error:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/hadoop/hbase/HBaseConfiguration
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:340)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:149)
Caused by: java.lang.ClassNotFoundException: org.apache.hadoop.hbase.HBaseConfiguration
    at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

The code is as below

import java.io.IOException;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
import org.apache.hadoop.hbase.mapreduce.TableMapper;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

    public class Test {

    static class TestMapper extends TableMapper<Text, IntWritable> {
        private static final IntWritable one = new IntWritable(1);

        public void map(ImmutableBytesWritable row, Result value, Context context) throws    IOException, InterruptedException
        {
            ImmutableBytesWritable userkey = new ImmutableBytesWritable(row.get(), 0 , Bytes.SIZEOF_INT);
            String key =Bytes.toString(userkey.get());
            context.write(new Text(key), one);

        }
    }

    public static void main(String[] args) throws Exception {

        HBaseConfiguration conf = new HBaseConfiguration();
        Job job = new Job(conf, "hbase_freqcounter");
        job.setJarByClass(Test.class);
        Scan scan = new Scan();

        FileOutputFormat.setOutputPath(job, new Path(args[0]));
        String columns = "data";
        scan.addFamily(Bytes.toBytes(columns));
        scan.setFilter(new FirstKeyOnlyFilter());
        TableMapReduceUtil.initTableMapperJob("test",scan, TestMapper.class, Text.class, IntWritable.class, job);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);
        System.exit(job.waitForCompletion(true)?0:1);

    }

}

I get the above code exported to a jar file and on the command line I use the below command to run the above code.

hadoop jar /home/testdb.jar test

where test is the folder to which the mapper results should be written.

I have checked a few other links like Caused by: java.lang.ClassNotFoundException: org.apache.zookeeper.KeeperException where it has been suggested to include the zookeeper file in the classpath, but while creating the project in eclipse I have already included zookeeper file from the lib directory of hbase. The file I have included is zookeeper-3.4.5.jar. Ans also visited this link too HBase - java.lang.NoClassDefFoundError in java , but I am using a mapper class to get the values from the hbase table not any client API. I know I am making a mistake somewhere, guys could you please help me out ??

I have noted another strange thing, when I remove all of the code in the main function except the first line " HBaseConfiguration conf = new HBaseConfiguration();", then export the code to a jar file and try to compile the jar file as hadoop jar test.jar I still get the same error. It seems either I am defining the conf variable incorrectly or there is some issue with my environment.

ContentLicense: CC BY-SA 4.0


问:
How can I access both of tables'fields in leftJoin in Yii2
I need tour's fields but below code just get tourPackage's fields and I have to use Active Record.

I know I have to use property in another model for fix this problem but I don't want use property because there are a lot of fields or property.

How can I get tour's table data ?

```<code>$models = TourPackage::find()->select(['tour.*'])->leftJoin('tour', 'tour.id=tour_package.tour_id')->all();
</code>```

答:
Your using TourPackage object ,
so you can't get attributes of Tour model.
If you want to get Tour model attributes,please try asArray()

ex.

```<code>$models = TourPackage::find()->select(['tour.*'])->leftJoin('tour', 'tour.id=tour_package.tour_id')->asArray()->all();
</code>```

Now you will get Tour  model attributes.

Body:
I need tour's fields but below code just get tourPackage's fields and I have to use Active Record.

I know I have to use property in another model for fix this problem but I don't want use property because there are a lot of fields or property.

How can I get tour's table data ?

$models = TourPackage::find()->select(['tour.*'])->leftJoin('tour', 'tour.id=tour_package.tour_id')->all();

Body:
Your using TourPackage object ,
so you can't get attributes of Tour model.
If you want to get Tour model attributes,please try asArray()

ex.

$models = TourPackage::find()->select(['tour.*'])->leftJoin('tour', 'tour.id=tour_package.tour_id')->asArray()->all();

Now you will get Tour  model attributes.


问:
Is it possible to reduce no of markers in a matplotlib plot?
I have a fitted distribution curve where I would like to reduce no. of markers.

Can anyone suggest tricks to do that?

答:
The plot command has an argument markevery.

markevery    [None | int | length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]

This is a bit cryptic, but there is an example on the matplotlib page, showing different ways to use this argument.

Quoting from the example's text:

Integer arguments are fairly intuitive.  e.g. markevery=5 will plot every
  5th marker starting from the first data point.

  Float arguments allow markers to be spaced at approximately equal distances
  along the line.  The theoretical distance along the line between markers is
  determined by multiplying the display-coordinate distance of the axes
  bounding-box diagonal by the value of markevery.  The data points closest
  to the theoretical distances will be shown.

So for a simple example case, use

```<code>plt.plot(x,y, marker="o", markevery=5)
</code>```

to plot every 5th marker only.

Body:
The plot command has an argument markevery.

markevery    [None | int | length-2 tuple of int | slice | list/array of int | float | length-2 tuple of float]

This is a bit cryptic, but there is an example on the matplotlib page, showing different ways to use this argument.

Quoting from the example's text:

Integer arguments are fairly intuitive.  e.g. markevery=5 will plot every
  5th marker starting from the first data point.

  Float arguments allow markers to be spaced at approximately equal distances
  along the line.  The theoretical distance along the line between markers is
  determined by multiplying the display-coordinate distance of the axes
  bounding-box diagonal by the value of markevery.  The data points closest
  to the theoretical distances will be shown.

So for a simple example case, use

plt.plot(x,y, marker="o", markevery=5)

to plot every 5th marker only.


问:
How to use static methods in view templates
I want to use static class constants in my view template

Javascript

```<code>class FilterModel {
  static const FILTER_TYPE_STRING() {
    return 'string';
  }
}
</code>```

HTML

```<code><div show.bind="selectedFacet.type===FilterModel.FILTER_TYPE_STRING">
</div>
</code>```

答:
Short answer: the binding language does not support that.

I met the problem before, but didn't find a good workaround. In such case, I usually define a constant, which the class would set the value from in the constructor and add a comment to show it should be static.

```<code>const _filterTypeString: string = 'string';

export class FilterModel {
    /*static*/ filterTypeString: string = _filterTypeString;
}
</code>```

Longer answer: static members in JavaScript are being transpiled directly into the class, not into the prototype, so instances do not have reference to it. The difference is:

```<code>class MyClass {
    instanceMember: number = 256
    static staticMember: number = 1024;
}

//referencing them:
MyClass.prototype.instanceMember
MyClass.staticMember
</code>```

Everytime when you create an object instance, it creates a copy of the prototype, so that this would have equal values to the prototype. That's what Aurelia does also, creates an instance, when creating a view-model.

In the view template, you can only access members of that object, which is inherited from the prototype. Since the static method is not a member of that object, you cannot access it. Of course, you might create a reference, but I found this workaround more annoying than the one above. With code example:

```<code>export class FilterModel {
    static filterTypeString: string = 'string';
    refToFilterTypeString = FilterModel.filterTypeString;
}
</code>```

HTML:

```<code><div show.bind="selectedFacet.type === refToFilterTypeString">
</div>
</code>```

Body:
I want to use static class constants in my view template

Javascript

class FilterModel {
  static const FILTER_TYPE_STRING() {
    return 'string';
  }
}

HTML

Body:
Short answer: the binding language does not support that.

I met the problem before, but didn't find a good workaround. In such case, I usually define a constant, which the class would set the value from in the constructor and add a comment to show it should be static.

const _filterTypeString: string = 'string';

export class FilterModel {
    /*static*/ filterTypeString: string = _filterTypeString;
}

Longer answer: static members in JavaScript are being transpiled directly into the class, not into the prototype, so instances do not have reference to it. The difference is:

class MyClass {
    instanceMember: number = 256
    static staticMember: number = 1024;
}

//referencing them:
MyClass.prototype.instanceMember
MyClass.staticMember

Everytime when you create an object instance, it creates a copy of the prototype, so that this would have equal values to the prototype. That's what Aurelia does also, creates an instance, when creating a view-model.

In the view template, you can only access members of that object, which is inherited from the prototype. Since the static method is not a member of that object, you cannot access it. Of course, you might create a reference, but I found this workaround more annoying than the one above. With code example:

export class FilterModel {
    static filterTypeString: string = 'string';
    refToFilterTypeString = FilterModel.filterTypeString;
}

HTML:

<div show.bind="selectedFacet.type === refToFilterTypeString">
</div>


问:
Checking whether a word is TCL keyword or Not
The question is regarding TCL. I have a word I want to compare whether it is TCL keyword or not. Please suggest me is there any way to do that?

I was thinking may create a list which contains all TCL keywords then compare with the word I'm having. any suggestion on creating that list?

Is there any better method?

Regards
keerthan

答:
Tcl doesn't have keywords. The language design explicitly doesn't use them.

But you do have a standard set of commands (as listed in the index of the manual pages at https://www.tcl.tk/man/tcl/TclCmd/contents.htm; only a few of those don't correspond to actual commands). You can then add a few extra words (then, else, elseif) and that will give you a sensible first cut at things that you can pretend are keywords for the purposes of stuff like syntax highlighting.

If you're doing actual parsing of Tcl, you need a different approach.


问:
Nested classes inside a class cannot acces varibale from each other
Please take a look at the following snippet. You can understand what I am trying to do. The vlan_start of PairTwo class must be derived from the values of PortOne. How do I do that?

```<code>>>> class G8032:
...     class PairOne:
...         vlan_start = 1101
...         vlan_count = 600
...     class PairTwo:
...         vlan_start = G8032.PairOne.vlan_start + G8032.PairOne.vlan_count
...         vlan_count = 400
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in G8032
  File "<stdin>", line 6, in PairTwo
NameError: name 'G8032' is not defined
>>>
</code>```

EDIT:
I have tried without G8032 in G8032.PairOne.vlan_***. it still doesn't work.

答:
Why not doing something like this -

```<code>class G8032:
    pass

class PairOne:
    vlan_start = 1101
    vlan_count = 600
class PairTwo:
    p = PairOne()
    vlan_start = p.vlan_start + p.vlan_count
    vlan_count = 400

if __name__ == "__main__":
    g = G8032()
    g.PairOne = PairOne()
    g.PairTwo = PairTwo()
</code>```

You may find this thread interesting - Nested classes' scope?

Body:
Please take a look at the following snippet. You can understand what I am trying to do. The vlan_start of PairTwo class must be derived from the values of PortOne. How do I do that?

>>> class G8032:
...     class PairOne:
...         vlan_start = 1101
...         vlan_count = 600
...     class PairTwo:
...         vlan_start = G8032.PairOne.vlan_start + G8032.PairOne.vlan_count
...         vlan_count = 400
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in G8032
  File "<stdin>", line 6, in PairTwo
NameError: name 'G8032' is not defined
>>>

EDIT:
I have tried without G8032 in G8032.PairOne.vlan_***. it still doesn't work.

Body:
Why not doing something like this -

class G8032:
    pass

class PairOne:
    vlan_start = 1101
    vlan_count = 600
class PairTwo:
    p = PairOne()
    vlan_start = p.vlan_start + p.vlan_count
    vlan_count = 400

if __name__ == "__main__":
    g = G8032()
    g.PairOne = PairOne()
    g.PairTwo = PairTwo()

You may find this thread interesting - Nested classes' scope?


问:
How to speed collection "contains" execution plan?
If I make analogy to Oracle database : they have the notion of "index" and "hint" to speed the execution of a query. So I want to make the analogy to Java : is it possible to make the execution of the "contains" method of a collection to be quick ?

答:
It depends on what do you want to do with that collection. These are the standard options:

If the order of insertion doesn't matter, then you can use a HashSet. Once you have this Set set up, the contains() method will run in O(constant) time.

Alternatively, you can use a LinkedHashSet. It is almost the same as the HashSet, but it maintains a LinkedList on the top of the Set so you can maintain the order of original insertion.

If you want to maintain the natural ordering of your items, you can use a TreeSet. Its contains() method will return in O(log n) time which is still fairly quick.

If none of these is good for you, then you can have your collection, assign another HashSet and maintain them together. However, I'm afraid that the performance gain isn't justified at most of the cases.


答:
In TourPackage you need to define public attributes, that you will join from Tour.
For instance if you have column number in tour, then you can write:

```<code>class TourPackage extends \yii\db\ActiveRecord
{
    public $number
    // ..and other properties you take from tour
</code>```

in TourPackage class, and add the following select in Query:

```<code>$models = TourPackage::find()->addSelect(['tour_package.*', 'tour.number AS number'])->leftJoin('tour', 'tour.id=tour_package.tour_id')->all();
</code>```

Of course, you can write addSelect(['tour_package.*', 'tour.*']), but in that case tour columns with similar name will override tour_package columns.

Title: How can I access both of tables'fields in leftJoin in Yii2

Body:
In TourPackage you need to define public attributes, that you will join from Tour.
For instance if you have column number in tour, then you can write:

class TourPackage extends \yii\db\ActiveRecord
{
    public $number
    // ..and other properties you take from tour

in TourPackage class, and add the following select in Query:

$models = TourPackage::find()->addSelect(['tour_package.*', 'tour.number AS number'])->leftJoin('tour', 'tour.id=tour_package.tour_id')->all();

Of course, you can write addSelect(['tour_package.*', 'tour.*']), but in that case tour columns with similar name will override tour_package columns.


问:
matrix 2d array with pointer
This is the code I wrote to take the values of a matrix and display it

```<code>#include<stdio.h>

int ** readMatrix(int rows, int cols)
{
    int i,j, matrix[rows*cols];
    int *b[rows];
    int **y=b;

    int k=0;
    for(k=0; k < rows; k++)
    {
        b[k]=&matrix[k*cols];
    }

    for(i=0; i< rows*cols; i++)
    {
        scanf("%d", matrix+i);
    }
    return y;
}

void displayMatrix(int **a, int rows, int cols)
{
    int k=0,j;
    for(k=0; k < rows; k++)
    {
        for(j=0; j < cols; j++)
        {
            printf("%d ", *(*(a + k) + j));
        }
        printf("\n");
    }
}

int main()
{
    int rows,cols;
    printf("Enter the number of rows:\n");
    scanf("%d",&rows);
    if(rows <= 0)
    {
        printf("Invalid Input");
    }
    else
    {
        printf("Enter the number of columns:\n");
        scanf("%d",&cols);
        if(cols <= 0)
        {
            printf("Invalid Input");
        }
        else
        {
            printf("Enter the values:\n");
            int **a = readMatrix(rows, cols);
            displayMatrix(a, rows, cols);
        }
    }
}
</code>```

The program is getting stuck at the loop in displayMatrix, but it displays fine if I remove the outer for loop.

The error I get is Segmentation fault (core dumped).

What am I doing wrong?

PS: I have to use the above function signature with double pointers.

答:
Your problem in readMatrix is that it returns a pointer to a local variable in that function.  You're not supposed to do that, because local variables get deallocated after the function returns, which is why you're getting a segmentation fault.

You need to create one with malloc in the function (and remember to free it).  You will need to put #include <stdlib.h> at the top with the other headers to access these functions.  You can see the changes below to make this work.

```<code>int** readMatrix(int rows, int cols) {
    int i, j;
    int **matrix = malloc(rows * sizeof(int*));

    for(i = 0; i < rows; i++) {
        matrix[i] = malloc(cols * sizeof(int));
        for(j = 0; j < cols; j++) {
            scanf("%d", &matrix[i][j]);
        }
    }

    return matrix;
}
</code>```

Now it may be helpful to have a function for freeing this data structure.  Here's how you can do that.

```<code>void freeMatrix(int **matrix, int rows) {
    int i;
    for(i = 0; i < rows; i++) {
        free(matrix[i]);
    }
    free(matrix);
}
</code>```

Then change the main function to accommodate these changes as follows.

```<code>int **a = readMatrix(rows, cols);
displayMatrix(a, rows, cols);
freeMatrix(a, rows);
</code>```

Title: matrix 2d array with pointer

Body:
This is the code I wrote to take the values of a matrix and display it

#include<stdio.h>

int ** readMatrix(int rows, int cols)
{
    int i,j, matrix[rows*cols];
    int *b[rows];
    int **y=b;

    int k=0;
    for(k=0; k < rows; k++)
    {
        b[k]=&matrix[k*cols];
    }

    for(i=0; i< rows*cols; i++)
    {
        scanf("%d", matrix+i);
    }
    return y;
}

void displayMatrix(int **a, int rows, int cols)
{
    int k=0,j;
    for(k=0; k < rows; k++)
    {
        for(j=0; j < cols; j++)
        {
            printf("%d ", *(*(a + k) + j));
        }
        printf("\n");
    }
}

int main()
{
    int rows,cols;
    printf("Enter the number of rows:\n");
    scanf("%d",&rows);
    if(rows <= 0)
    {
        printf("Invalid Input");
    }
    else
    {
        printf("Enter the number of columns:\n");
        scanf("%d",&cols);
        if(cols <= 0)
        {
            printf("Invalid Input");
        }
        else
        {
            printf("Enter the values:\n");
            int **a = readMatrix(rows, cols);
            displayMatrix(a, rows, cols);
        }
    }
}

The program is getting stuck at the loop in displayMatrix, but it displays fine if I remove the outer for loop.

The error I get is Segmentation fault (core dumped).

What am I doing wrong?

PS: I have to use the above function signature with double pointers.

Body:
Your problem in readMatrix is that it returns a pointer to a local variable in that function.  You're not supposed to do that, because local variables get deallocated after the function returns, which is why you're getting a segmentation fault.

You need to create one with malloc in the function (and remember to free it).  You will need to put #include <stdlib.h> at the top with the other headers to access these functions.  You can see the changes below to make this work.

int** readMatrix(int rows, int cols) {
    int i, j;
    int **matrix = malloc(rows * sizeof(int*));

    for(i = 0; i < rows; i++) {
        matrix[i] = malloc(cols * sizeof(int));
        for(j = 0; j < cols; j++) {
            scanf("%d", &matrix[i][j]);
        }
    }

    return matrix;
}

Now it may be helpful to have a function for freeing this data structure.  Here's how you can do that.

void freeMatrix(int **matrix, int rows) {
    int i;
    for(i = 0; i < rows; i++) {
        free(matrix[i]);
    }
    free(matrix);
}

Then change the main function to accommodate these changes as follows.

int **a = readMatrix(rows, cols);
displayMatrix(a, rows, cols);
freeMatrix(a, rows);


问:
How to deploy Azure service fabric project on to a remote cluster(Azure)
I have Created a cluster in Azure http://******.######.cloudapp.azure.com:19080
but don't know how to deploy my service fabric project on to it.
Link to application manifest
ApplicationManifest.xml</p>

答: Your first option is to use the powershell commands. You can also right-click your application in visual studio and select "Publish". Make sure you are using the correct publish profile.</p>


答:
Don't nest these classes. When the line vlan_start = G8032.PairOne.vlan_start + G8032.PairOne.vlan_count is executed, the G8032 class is not completely defined yet.

If you absolutely need to supporty the syntax you mentioned in the comments
 (x = G8032.PairOne.vlan_start) then you could (but probably shouldn't) use the code below:

```<code>class PairOne:
    vlan_start = 1101
    vlan_count = 600

class PairTwo:
    vlan_start = PairOne.vlan_start + PairOne.vlan_count
    vlan_count = 40

class G8032:
    PairOne = PairOne
    PairTwo = PairTwo

print(G8032.PairOne.vlan_start)
print(G8032.PairTwo.vlan_start)
# 1101
# 1701
</code>```

Title: Nested classes inside a class cannot acces varibale from each other

Body:
Don't nest these classes. When the line vlan_start = G8032.PairOne.vlan_start + G8032.PairOne.vlan_count is executed, the G8032 class is not completely defined yet.

If you absolutely need to supporty the syntax you mentioned in the comments
 (x = G8032.PairOne.vlan_start) then you could (but probably shouldn't) use the code below:

class PairOne:
    vlan_start = 1101
    vlan_count = 600

class PairTwo:
    vlan_start = PairOne.vlan_start + PairOne.vlan_count
    vlan_count = 40

class G8032:
    PairOne = PairOne
    PairTwo = PairTwo

print(G8032.PairOne.vlan_start)
print(G8032.PairTwo.vlan_start)
# 1101
# 1701


问:
Printing to logs the "conditon"
NEWEST UPDATE

package com.karanvir.again;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    EditText city;
    Button go;
    TextView resultofw;
    String text;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        city=(EditText) findViewById(R.id.editText);
        go=(Button) findViewById(R.id.button);
        setSupportActionBar(toolbar);
        DownloadTask task=new DownloadTask();
        resultofw=(TextView) findViewById(R.id.textView);
        task.execute("http://api.apixu.com/v1/current.json?key=76d62bf509e64633a4970055170706&q="+city.toString());

    }

    public class DownloadTask extends AsyncTask<String,Void,String> {
        @Override
        protected String doInBackground(String... urls) {
            String result = "";
            URL url;
            HttpURLConnection urlConnection = null;
            try {
                url = new URL(urls[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                InputStream in = urlConnection.getInputStream();
                InputStreamReader reader = new InputStreamReader(in);
                int data = reader.read();
                while (data != -1) {
                    char current = (char) data;
                    result += current;
                    data = reader.read();
                }
                return result;

            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
//conver result into json object
            try{
                JSONObject jsonObject=new JSONObject(result);

                //get current JSONObject from result JSONObject
                JSONObject currentJSONObject = jsonObject.getJSONObject("current");

                //Now get condition JSONObject from current JSONObject
                JSONObject conditionJSONObject = currentJSONObject.getJSONObject("condition");
                text = conditionJSONObject.getString("text");

                //Now print condition JSONObject
                Log.i("website content", "condition json object : " + text.toString());
                JSONArray arr= new JSONArray(conditionJSONObject.toString());

            } catch (Exception e){

            }

        }
    }

public  void click(View view){

    resultofw.setText(text);

}

}```
</div>
</div>
</p>

<p>SO how can i fix this aswell, im tryng to add the strings to the array. and then pull out what is said after "text"</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>//conver result into json object
            try{
                JSONObject jsonObject=new JSONObject(result);

                //get current JSONObject from result JSONObject
                JSONObject currentJSONObject = jsonObject.getJSONObject("current");

                //Now get condition JSONObject from current JSONObject
                JSONObject conditionJSONObject = currentJSONObject.getJSONObject("condition");

                //Now print condition JSONObject
                Log.i("website content", "condition json object : " + conditionJSONObject.toString());
                JSONArray arr= new JSONArray(conditionJSONObject.toString());

                for(int i=0;i<arr.length();i++){
                    JSONObject jsonpart= arr.getJSONObject(i);
                    Log.i("Part",jsonpart.getString("text"));
                }</code>```

What im trying to do is print everything after ""condition":{"text":"Partly cloudy","icon":"//cdn.apixu.com/weather/64x64/day/116.png","code":1003},"wind_mph":15.0,"wind_kph":24.1,"wind_degree":240,"wind_dir":"WSW","pressure_mb":1016.0,"pressure_in":30.5,"precip_mm":0.0,"precip_in":0.0,"humidity":71,"cloud":50,"feelslike_c":9.6,"feelslike_f":49.2,"vis_km":10.0,"vis_miles":6.0}}" To my logs, im using JSONG to process the data from this site:http://api.apixu.com/v1/current.json?key=76d62bf509e64633a4970055170706&q=Paris
Its not appearing in my logcat, please help AND YES I HAVE INCLUDED USES PERMISSION IN MY MENIFEST

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.karanvir.again.MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </RelativeLayout>

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>```
<pre class="snippet-code-css lang-css prettyprint-override"><code>06-07 01:42:19.594 20523-20523/com.karanvir.again E/Zygote: v2
06-07 01:42:19.594 20523-20523/com.karanvir.again I/libpersona: KNOX_SDCARD checking this for 10291
06-07 01:42:19.594 20523-20523/com.karanvir.again I/libpersona: KNOX_SDCARD not a persona
06-07 01:42:19.594 20523-20523/com.karanvir.again I/SELinux: Function: selinux_compare_spd_ram, index[1], SPD-policy is existed. and_ver=SEPF_SM-G870W_5.0 ver=38
06-07 01:42:19.594 20523-20523/com.karanvir.again W/SELinux: Function: selinux_compare_spd_ram, index[1], priority [2], priority version is VE=SEPF_SECMOBILE_6.0.1_0013
06-07 01:42:19.594 20523-20523/com.karanvir.again E/Zygote: accessInfo : 0
06-07 01:42:19.594 20523-20523/com.karanvir.again W/SELinux: SELinux: seapp_context_lookup: seinfo=default, level=s0:c512,c768, pkgname=com.karanvir.again
06-07 01:42:19.594 20523-20523/com.karanvir.again I/art: Late-enabling -Xcheck:jni
06-07 01:42:19.974 20523-20523/com.karanvir.again W/ResourcesManager: getTopLevelResources: /data/app/com.karanvir.again-2/base.apk / 1.0 running in com.karanvir.again rsrc of package null
06-07 01:42:20.064 20523-20523/com.karanvir.again W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm --instruction-set-features=smp,div,atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=krait --instruction-set-features=default --dex-file=/data/app/com.karanvir.again-2/split_lib_dependencies_apk.apk --oat-file=/data/dalvik-cache/arm/data@app@com.karanvir.again-2@split_lib_dependencies_apk.apk@classes.dex) because non-0 exit status
06-07 01:42:20.304 20523-20523/com.karanvir.again W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm --instruction-set-features=smp,div,atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=krait --instruction-set-features=default --dex-file=/data/app/com.karanvir.again-2/split_lib_slice_0_apk.apk --oat-file=/data/dalvik-cache/arm/data@app@com.karanvir.again-2@split_lib_slice_0_apk.apk@classes.dex) because non-0 exit status
06-07 01:42:20.364 20523-20523/com.karanvir.again W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm --instruction-set-features=smp,div,atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=krait --instruction-set-features=default --dex-file=/data/app/com.karanvir.again-2/split_lib_slice_1_apk.apk --oat-file=/data/dalvik-cache/arm/data@app@com.karanvir.again-2@split_lib_slice_1_apk.apk@classes.dex) because non-0 exit status
06-07 01:42:20.414 20523-20523/com.karanvir.again W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm --instruction-set-features=smp,div,atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=krait --instruction-set-features=default --dex-file=/data/app/com.karanvir.again-2/split_lib_slice_2_apk.apk --oat-file=/data/dalvik-cache/arm/data@app@com.karanvir.again-2@split_lib_slice_2_apk.apk@classes.dex) because non-0 exit status
06-07 01:42:20.484 20523-20523/com.karanvir.again W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm --instruction-set-features=smp,div,atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=krait --instruction-set-features=default --dex-file=/data/app/com.karanvir.again-2/split_lib_slice_3_apk.apk --oat-file=/data/dalvik-cache/arm/data@app@com.karanvir.again-2@split_lib_slice_3_apk.apk@classes.dex) because non-0 exit status
06-07 01:42:20.544 20523-20523/com.karanvir.again W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm --instruction-set-features=smp,div,atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=krait --instruction-set-features=default --dex-file=/data/app/com.karanvir.again-2/split_lib_slice_4_apk.apk --oat-file=/data/dalvik-cache/arm/data@app@com.karanvir.again-2@split_lib_slice_4_apk.apk@classes.dex) because non-0 exit status
06-07 01:42:20.614 20523-20523/com.karanvir.again W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm --instruction-set-features=smp,div,atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=krait --instruction-set-features=default --dex-file=/data/app/com.karanvir.again-2/split_lib_slice_5_apk.apk --oat-file=/data/dalvik-cache/arm/data@app@com.karanvir.again-2@split_lib_slice_5_apk.apk@classes.dex) because non-0 exit status
06-07 01:42:20.694 20523-20523/com.karanvir.again W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm --instruction-set-features=smp,div,atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=krait --instruction-set-features=default --dex-file=/data/app/com.karanvir.again-2/split_lib_slice_6_apk.apk --oat-file=/data/dalvik-cache/arm/data@app@com.karanvir.again-2@split_lib_slice_6_apk.apk@classes.dex) because non-0 exit status
06-07 01:42:20.754 20523-20523/com.karanvir.again W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm --instruction-set-features=smp,div,atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=krait --instruction-set-features=default --dex-file=/data/app/com.karanvir.again-2/split_lib_slice_7_apk.apk --oat-file=/data/dalvik-cache/arm/data@app@com.karanvir.again-2@split_lib_slice_7_apk.apk@classes.dex) because non-0 exit status
06-07 01:42:20.814 20523-20523/com.karanvir.again W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm --instruction-set-features=smp,div,atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=krait --instruction-set-features=default --dex-file=/data/app/com.karanvir.again-2/split_lib_slice_8_apk.apk --oat-file=/data/dalvik-cache/arm/data@app@com.karanvir.again-2@split_lib_slice_8_apk.apk@classes.dex) because non-0 exit status
06-07 01:42:20.894 20523-20523/com.karanvir.again W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm --instruction-set-features=smp,div,atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=krait --instruction-set-features=default --dex-file=/data/app/com.karanvir.again-2/split_lib_slice_9_apk.apk --oat-file=/data/dalvik-cache/arm/data@app@com.karanvir.again-2@split_lib_slice_9_apk.apk@classes.dex) because non-0 exit status
06-07 01:42:20.894 20523-20523/com.karanvir.again W/System: ClassLoader referenced unknown path: /data/app/com.karanvir.again-2/lib/arm
06-07 01:42:20.914 20523-20523/com.karanvir.again I/InstantRun: starting instant run server: is main process
06-07 01:42:20.994 20523-20523/com.karanvir.again W/ResourcesManager: getTopLevelResources: /data/app/com.karanvir.again-2/base.apk / 1.0 running in com.karanvir.again rsrc of package null
06-07 01:42:20.994 20523-20523/com.karanvir.again W/ResourcesManager: getTopLevelResources: /data/app/com.karanvir.again-2/base.apk / 1.0 running in com.karanvir.again rsrc of package null
06-07 01:42:21.114 20523-20523/com.karanvir.again W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
06-07 01:42:21.424 20523-20780/com.karanvir.again I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
06-07 01:42:21.424 20523-20780/com.karanvir.again I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
06-07 01:42:21.464 20523-20787/com.karanvir.again I/Adreno-EGL: <qeglDrvAPI_eglInitialize:379>: EGL 1.4 QUALCOMM build:  (Ia10634f51b)
                                                                OpenGL ES Shader Compiler Version: E031.29.00.00
                                                                Build Date: 01/28/16 Thu
                                                                Local Branch: ss
                                                                Remote Branch:
                                                                Local Patches:
                                                                Reconstruct Branch:
06-07 01:42:21.474 20523-20787/com.karanvir.again I/OpenGLRenderer: Initialized EGL, version 1.4
06-07 01:42:21.544 20523-20523/com.karanvir.again W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
06-07 01:42:21.574 20523-20523/com.karanvir.again I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@5600697 time:300881669</code>```

package com.karanvir.again;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

import org.json.JSONObject;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        DownloadTask task=new DownloadTask();
        task.execute("http://api.apixu.com/v1/current.json?key=76d62bf509e64633a4970055170706&q=Paris");

    }

    public class DownloadTask extends AsyncTask<String,Void,String> {
        @Override
        protected String doInBackground(String... urls) {
            String result = "";
            URL url;
            HttpURLConnection urlConnection = null;
            try {
                url = new URL(urls[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                InputStream in = urlConnection.getInputStream();
                InputStreamReader reader = new InputStreamReader(in);
                int data = reader.read();
                while (data != -1) {
                    char current = (char) data;
                    result += current;
                    data = reader.read();
                }
                return result;

            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
//conver result into json object
            try{
                JSONObject jsonObject=new JSONObject(result);
String xx=jsonObject.getString("condition");
                Log.i("website content", xx);

            } catch (Exception e){

            }

        }
    }

}```

Title: Printing to logs the "conditon"

Body:
NEWEST UPDATE

package com.karanvir.again;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    EditText city;
    Button go;
    TextView resultofw;
    String text;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        city=(EditText) findViewById(R.id.editText);
        go=(Button) findViewById(R.id.button);
        setSupportActionBar(toolbar);
        DownloadTask task=new DownloadTask();
        resultofw=(TextView) findViewById(R.id.textView);
        task.execute("http://api.apixu.com/v1/current.json?key=76d62bf509e64633a4970055170706&q="+city.toString());

    }

    public class DownloadTask extends AsyncTask<String,Void,String> {
        @Override
        protected String doInBackground(String... urls) {
            String result = "";
            URL url;
            HttpURLConnection urlConnection = null;
            try {
                url = new URL(urls[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                InputStream in = urlConnection.getInputStream();
                InputStreamReader reader = new InputStreamReader(in);
                int data = reader.read();
                while (data != -1) {
                    char current = (char) data;
                    result += current;
                    data = reader.read();
                }
                return result;

            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
//conver result into json object
            try{
                JSONObject jsonObject=new JSONObject(result);

                //get current JSONObject from result JSONObject
                JSONObject currentJSONObject = jsonObject.getJSONObject("current");

                //Now get condition JSONObject from current JSONObject
                JSONObject conditionJSONObject = currentJSONObject.getJSONObject("condition");
                text = conditionJSONObject.getString("text");

                //Now print condition JSONObject
                Log.i("website content", "condition json object : " + text.toString());
                JSONArray arr= new JSONArray(conditionJSONObject.toString());

            } catch (Exception e){

            }

        }
    }

public  void click(View view){

    resultofw.setText(text);

}

}

SO how can i fix this aswell, im tryng to add the strings to the array. and then pull out what is said after "text"

//conver result into json object
            try{
                JSONObject jsonObject=new JSONObject(result);

                //get current JSONObject from result JSONObject
                JSONObject currentJSONObject = jsonObject.getJSONObject("current");

                //Now get condition JSONObject from current JSONObject
                JSONObject conditionJSONObject = currentJSONObject.getJSONObject("condition");

                //Now print condition JSONObject
                Log.i("website content", "condition json object : " + conditionJSONObject.toString());
                JSONArray arr= new JSONArray(conditionJSONObject.toString());

                for(int i=0;i<arr.length();i++){
                    JSONObject jsonpart= arr.getJSONObject(i);
                    Log.i("Part",jsonpart.getString("text"));
                }

What im trying to do is print everything after ""condition":{"text":"Partly cloudy","icon":"//cdn.apixu.com/weather/64x64/day/116.png","code":1003},"wind_mph":15.0,"wind_kph":24.1,"wind_degree":240,"wind_dir":"WSW","pressure_mb":1016.0,"pressure_in":30.5,"precip_mm":0.0,"precip_in":0.0,"humidity":71,"cloud":50,"feelslike_c":9.6,"feelslike_f":49.2,"vis_km":10.0,"vis_miles":6.0}}" To my logs, im using JSONG to process the data from this site:http://api.apixu.com/v1/current.json?key=76d62bf509e64633a4970055170706&q=Paris
Its not appearing in my logcat, please help AND YES I HAVE INCLUDED USES PERMISSION IN MY MENIFEST

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.karanvir.again.MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </RelativeLayout>

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

06-07 01:42:19.594 20523-20523/com.karanvir.again E/Zygote: v2
06-07 01:42:19.594 20523-20523/com.karanvir.again I/libpersona: KNOX_SDCARD checking this for 10291
06-07 01:42:19.594 20523-20523/com.karanvir.again I/libpersona: KNOX_SDCARD not a persona
06-07 01:42:19.594 20523-20523/com.karanvir.again I/SELinux: Function: selinux_compare_spd_ram, index[1], SPD-policy is existed. and_ver=SEPF_SM-G870W_5.0 ver=38
06-07 01:42:19.594 20523-20523/com.karanvir.again W/SELinux: Function: selinux_compare_spd_ram, index[1], priority [2], priority version is VE=SEPF_SECMOBILE_6.0.1_0013
06-07 01:42:19.594 20523-20523/com.karanvir.again E/Zygote: accessInfo : 0
06-07 01:42:19.594 20523-20523/com.karanvir.again W/SELinux: SELinux: seapp_context_lookup: seinfo=default, level=s0:c512,c768, pkgname=com.karanvir.again
06-07 01:42:19.594 20523-20523/com.karanvir.again I/art: Late-enabling -Xcheck:jni
06-07 01:42:19.974 20523-20523/com.karanvir.again W/ResourcesManager: getTopLevelResources: /data/app/com.karanvir.again-2/base.apk / 1.0 running in com.karanvir.again rsrc of package null
06-07 01:42:20.064 20523-20523/com.karanvir.again W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm --instruction-set-features=smp,div,atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=krait --instruction-set-features=default --dex-file=/data/app/com.karanvir.again-2/split_lib_dependencies_apk.apk --oat-file=/data/dalvik-cache/arm/data@app@com.karanvir.again-2@split_lib_dependencies_apk.apk@classes.dex) because non-0 exit status
06-07 01:42:20.304 20523-20523/com.karanvir.again W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm --instruction-set-features=smp,div,atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=krait --instruction-set-features=default --dex-file=/data/app/com.karanvir.again-2/split_lib_slice_0_apk.apk --oat-file=/data/dalvik-cache/arm/data@app@com.karanvir.again-2@split_lib_slice_0_apk.apk@classes.dex) because non-0 exit status
06-07 01:42:20.364 20523-20523/com.karanvir.again W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm --instruction-set-features=smp,div,atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=krait --instruction-set-features=default --dex-file=/data/app/com.karanvir.again-2/split_lib_slice_1_apk.apk --oat-file=/data/dalvik-cache/arm/data@app@com.karanvir.again-2@split_lib_slice_1_apk.apk@classes.dex) because non-0 exit status
06-07 01:42:20.414 20523-20523/com.karanvir.again W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm --instruction-set-features=smp,div,atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=krait --instruction-set-features=default --dex-file=/data/app/com.karanvir.again-2/split_lib_slice_2_apk.apk --oat-file=/data/dalvik-cache/arm/data@app@com.karanvir.again-2@split_lib_slice_2_apk.apk@classes.dex) because non-0 exit status
06-07 01:42:20.484 20523-20523/com.karanvir.again W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm --instruction-set-features=smp,div,atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=krait --instruction-set-features=default --dex-file=/data/app/com.karanvir.again-2/split_lib_slice_3_apk.apk --oat-file=/data/dalvik-cache/arm/data@app@com.karanvir.again-2@split_lib_slice_3_apk.apk@classes.dex) because non-0 exit status
06-07 01:42:20.544 20523-20523/com.karanvir.again W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm --instruction-set-features=smp,div,atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=krait --instruction-set-features=default --dex-file=/data/app/com.karanvir.again-2/split_lib_slice_4_apk.apk --oat-file=/data/dalvik-cache/arm/data@app@com.karanvir.again-2@split_lib_slice_4_apk.apk@classes.dex) because non-0 exit status
06-07 01:42:20.614 20523-20523/com.karanvir.again W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm --instruction-set-features=smp,div,atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=krait --instruction-set-features=default --dex-file=/data/app/com.karanvir.again-2/split_lib_slice_5_apk.apk --oat-file=/data/dalvik-cache/arm/data@app@com.karanvir.again-2@split_lib_slice_5_apk.apk@classes.dex) because non-0 exit status
06-07 01:42:20.694 20523-20523/com.karanvir.again W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm --instruction-set-features=smp,div,atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=krait --instruction-set-features=default --dex-file=/data/app/com.karanvir.again-2/split_lib_slice_6_apk.apk --oat-file=/data/dalvik-cache/arm/data@app@com.karanvir.again-2@split_lib_slice_6_apk.apk@classes.dex) because non-0 exit status
06-07 01:42:20.754 20523-20523/com.karanvir.again W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm --instruction-set-features=smp,div,atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=krait --instruction-set-features=default --dex-file=/data/app/com.karanvir.again-2/split_lib_slice_7_apk.apk --oat-file=/data/dalvik-cache/arm/data@app@com.karanvir.again-2@split_lib_slice_7_apk.apk@classes.dex) because non-0 exit status
06-07 01:42:20.814 20523-20523/com.karanvir.again W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm --instruction-set-features=smp,div,atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=krait --instruction-set-features=default --dex-file=/data/app/com.karanvir.again-2/split_lib_slice_8_apk.apk --oat-file=/data/dalvik-cache/arm/data@app@com.karanvir.again-2@split_lib_slice_8_apk.apk@classes.dex) because non-0 exit status
06-07 01:42:20.894 20523-20523/com.karanvir.again W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=arm --instruction-set-features=smp,div,atomic_ldrd_strd --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=krait --instruction-set-features=default --dex-file=/data/app/com.karanvir.again-2/split_lib_slice_9_apk.apk --oat-file=/data/dalvik-cache/arm/data@app@com.karanvir.again-2@split_lib_slice_9_apk.apk@classes.dex) because non-0 exit status
06-07 01:42:20.894 20523-20523/com.karanvir.again W/System: ClassLoader referenced unknown path: /data/app/com.karanvir.again-2/lib/arm
06-07 01:42:20.914 20523-20523/com.karanvir.again I/InstantRun: starting instant run server: is main process
06-07 01:42:20.994 20523-20523/com.karanvir.again W/ResourcesManager: getTopLevelResources: /data/app/com.karanvir.again-2/base.apk / 1.0 running in com.karanvir.again rsrc of package null
06-07 01:42:20.994 20523-20523/com.karanvir.again W/ResourcesManager: getTopLevelResources: /data/app/com.karanvir.again-2/base.apk / 1.0 running in com.karanvir.again rsrc of package null
06-07 01:42:21.114 20523-20523/com.karanvir.again W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
06-07 01:42:21.424 20523-20780/com.karanvir.again I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
06-07 01:42:21.424 20523-20780/com.karanvir.again I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
06-07 01:42:21.464 20523-20787/com.karanvir.again I/Adreno-EGL: <qeglDrvAPI_eglInitialize:379>: EGL 1.4 QUALCOMM build:  (Ia10634f51b)
                                                                OpenGL ES Shader Compiler Version: E031.29.00.00
                                                                Build Date: 01/28/16 Thu
                                                                Local Branch: ss
                                                                Remote Branch:
                                                                Local Patches:
                                                                Reconstruct Branch:
06-07 01:42:21.474 20523-20787/com.karanvir.again I/OpenGLRenderer: Initialized EGL, version 1.4
06-07 01:42:21.544 20523-20523/com.karanvir.again W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
06-07 01:42:21.574 20523-20523/com.karanvir.again I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@5600697 time:300881669

package com.karanvir.again;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

import org.json.JSONObject;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        DownloadTask task=new DownloadTask();
        task.execute("http://api.apixu.com/v1/current.json?key=76d62bf509e64633a4970055170706&q=Paris");

    }

    public class DownloadTask extends AsyncTask<String,Void,String> {
        @Override
        protected String doInBackground(String... urls) {
            String result = "";
            URL url;
            HttpURLConnection urlConnection = null;
            try {
                url = new URL(urls[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                InputStream in = urlConnection.getInputStream();
                InputStreamReader reader = new InputStreamReader(in);
                int data = reader.read();
                while (data != -1) {
                    char current = (char) data;
                    result += current;
                    data = reader.read();
                }
                return result;

            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
//conver result into json object
            try{
                JSONObject jsonObject=new JSONObject(result);
String xx=jsonObject.getString("condition");
                Log.i("website content", xx);

            } catch (Exception e){

            }

        }
    }

}

Body: Log.d("website content", jsonObject.getString("condition").toString());


问:
How to make circular buttons with Font Awesome icons (and hover effect)?
I am trying to create buttons like the picture below.

I am using stacked Font Awesome icons to put the icons on top of a circle and it looks like this:

(Ignore the gray line at the bottom.  That's a result of poor screenshotting.)

However, as you can see, the icons are a tiny bit off.  Ideally, I want to push them up a bit so they are vertically centered in the circle and either make the circles bigger or the icons smaller to get the nice padding as in the example.  I also want to change the color of the circle which I don't know how to do and add hover effects (like change the icon to white).

Here is my code.

.footer {
  position: absolute;
  bottom: 0;
  height: 50px;
  background-color: #C0C0C0;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link
  rel="stylesheet"
  href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
  integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
  crossorigin="anonymous"
/>
<link
  rel="stylesheet"
  href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"
/>
<div class="row footer">
  <!-- FOOTER -->
  <div class="col-md-4"></div>
  <div class="col-md-4 text-center" id="copyright">
    <span class="fa-stack fa-lg">
      <i class="fa fa-circle fa-stack-2x"></i>
      <i class="fa fa-linkedin fa-stack-1x fa-inverse"></i>
    </span>

    <span class="fa-stack fa-lg">
      <i class="fa fa-circle fa-stack-2x"></i>
      <i class="fa fa-envelope-o fa-stack-1x fa-inverse" aria-hidden="true"></i>
    </span>
  </div>
</div></code>```

答:
To manually adjust the position of the icons you will have to create the black background separately and then position the icons inside it.

Best way to go forward would be using ul li, as follow

```<code><ul class="social_icon">
     <li>
        <a href="https://www.facebook.com/xxxxxxx" class="facebook">
          <i class="fa fa-facebook"></i>
        </a>
     </li>
     <li>
        <a href="https://twitter.com/xxxxxx" class="twitter">
          <i class="fa fa-twitter"></i>
        </a>
     </li>
     <li>
        <a href="https://in.linkedin.com/xxxxxxxx" class="linkedin">
          <i class="fa fa-linkedin"></i>
        </a>
     </li>
     <li>
        <a href="mailTo:mail@xxxxxxxxxx.com" class="email">
           <i class="fa fa-envelope"></i>
        </a>
     </li>
</ul>
</code>```

CSS would go something like this:

```<code>.social_icon {
    list-style: none;
    padding: 0;
    margin: 0;
    float: left;
    width: 100%;
}

.social_icon li {
    width: 38px;
    height: 38px;
    background: black;
    border-radius: 100%;
    margin-right: 10px;
    line-height: 40px;
    text-align: center;
    display: inline-block;
}

.facebook i {
    position: relative;
    top: xx;
}
</code>```

Body:
I am trying to create buttons like the picture below.

I am using stacked Font Awesome icons to put the icons on top of a circle and it looks like this:

(Ignore the gray line at the bottom.  That's a result of poor screenshotting.)

However, as you can see, the icons are a tiny bit off.  Ideally, I want to push them up a bit so they are vertically centered in the circle and either make the circles bigger or the icons smaller to get the nice padding as in the example.  I also want to change the color of the circle which I don't know how to do and add hover effects (like change the icon to white).

Here is my code.

.footer {
  position: absolute;
  bottom: 0;
  height: 50px;
  background-color: #C0C0C0;
  width: 100%;
}

<link
  rel="stylesheet"
  href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
  integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
  crossorigin="anonymous"
/>
<link
  rel="stylesheet"
  href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"
/>

Body:
To manually adjust the position of the icons you will have to create the black background separately and then position the icons inside it.

Best way to go forward would be using ul li, as follow

<ul class="social_icon">
     <li>
        <a href="https://www.facebook.com/xxxxxxx" class="facebook">
          <i class="fa fa-facebook"></i>
        </a>
     </li>
     <li>
        <a href="https://twitter.com/xxxxxx" class="twitter">
          <i class="fa fa-twitter"></i>
        </a>
     </li>
     <li>
        <a href="https://in.linkedin.com/xxxxxxxx" class="linkedin">
          <i class="fa fa-linkedin"></i>
        </a>
     </li>
     <li>
        <a href="mailTo:mail@xxxxxxxxxx.com" class="email">
           <i class="fa fa-envelope"></i>
        </a>
     </li>
</ul>

CSS would go something like this:

.social_icon {
    list-style: none;
    padding: 0;
    margin: 0;
    float: left;
    width: 100%;
}

.social_icon li {
    width: 38px;
    height: 38px;
    background: black;
    border-radius: 100%;
    margin-right: 10px;
    line-height: 40px;
    text-align: center;
    display: inline-block;
}

.facebook i {
    position: relative;
    top: xx;
}


问:
How to click "Go" button on go to finder dialog by applescript?
How to click "Go" button on go to finder dialog by applescript?
I have below code: "dialogObj" is the dialog of Go to Finder dialog, but the "click button 1 of searchFor" does not work in here.</p>

```<code>-- Get the search for pop-up object
set searchFor to first sheet of dialogObj

-- Select all the text in the search field and press delete
key code 0 using command down
key code 51
delay 0.5
--Paste file name
keystroke "v" using {command down}
delay 0.5

-- Click the 'Go' button in the search for pop-up
set textField to value of first text field of first sheet of dialogObj
*click button 1 of searchFor*
delay 1
</code>```

答:
In macOS Sierra the text field has been replaced with a combo box:

Try

```<code>tell 1st sheet of dialogObj
    set textField to value of combo box 1
    click button "Go"
end
</code>```

By the way: If you select the entire text you don't need to press Delete. Any pasted or typed text overwrites the selection.

Body:
How to click "Go" button on go to finder dialog by applescript?
I have below code: "dialogObj" is the dialog of Go to Finder dialog, but the "click button 1 of searchFor" does not work in here.

-- Get the search for pop-up object
set searchFor to first sheet of dialogObj

-- Select all the text in the search field and press delete
key code 0 using command down
key code 51
delay 0.5
--Paste file name
keystroke "v" using {command down}
delay 0.5

-- Click the 'Go' button in the search for pop-up
set textField to value of first text field of first sheet of dialogObj
*click button 1 of searchFor*
delay 1

Body:
In macOS Sierra the text field has been replaced with a combo box:

Try

tell 1st sheet of dialogObj
    set textField to value of combo box 1
    click button "Go"
end

By the way: If you select the entire text you don't need to press Delete. Any pasted or typed text overwrites the selection.