问:
Component is not rendering with react-router
I made a few routes, but my components don't render when I click on the links. I don't get any errors, the components, except for Navbar, simply don't render. BrowswerHistory yields the same result. I'm using react-router 3.0.0 version. What is wrong with my router structure?

```<code>import {Router, Route, IndexRoute,  hashHistory} from 'react-router';

const router = (
    <Router history={hashHistory}>
        <Route path="/" component={Navbar}>
            <IndexRoute  component={Main}></IndexRoute>
            <Route path="other" component={Other}></Route>
            <Route path="aboutus" component={AboutUs}></Route>
        </Route>
    </Router>
    );

   ReactDOM.render(
    router,
     document.getElementById('root')
   );
</code>```

Navbar component:

```<code>import React from 'react';
import {Link} from 'react-router';
class Navbar extends React.Component {
render() {
return (
 <nav>
  <ul className="menu-list">
    <li className="menu-item">
      <Link to="/" className="menu-link">Main</Link>
    </li>
    <li className="menu-item">
      <Link to="aboutus" href="" className="menu-link">About Us</Link>
    </li>
    <li className="menu-item">
      <Link to="other" className="menu-link">Some other item</Link>
    </li>
  </ul>
 </nav>
  );
 }
}

 export default Navbar;
</code>```

答:
Because you forgot this part: {this.props.children}. You need to specify the place where you want to render your child component.

Reason why this is required: NavBar is main component, all other component will render inside this, so you need to use {this.props.children}, at this place child component will render.

Use this:

```<code>return (
  <nav>
    <ul className="menu-list">

      <li className="menu-item">
        <Link to="/" className="menu-link">Main</Link>
      </li>

      <li className="menu-item">
        <Link to="aboutus" href="" className="menu-link">About Us</Link>
      </li>

      <li className="menu-item">
        <Link to="other" className="menu-link">Some other item</Link>
      </li>

    </ul>
    {this.props.children} //added this line
  </nav>
);
</code>```

Body:
I made a few routes, but my components don't render when I click on the links. I don't get any errors, the components, except for Navbar, simply don't render. BrowswerHistory yields the same result. I'm using react-router 3.0.0 version. What is wrong with my router structure?

import {Router, Route, IndexRoute,  hashHistory} from 'react-router';

const router = (
    <Router history={hashHistory}>
        <Route path="/" component={Navbar}>
            <IndexRoute  component={Main}></IndexRoute>
            <Route path="other" component={Other}></Route>
            <Route path="aboutus" component={AboutUs}></Route>
        </Route>
    </Router>
    );

   ReactDOM.render(
    router,
     document.getElementById('root')
   );

Navbar component:

import React from 'react';
import {Link} from 'react-router';
class Navbar extends React.Component {
render() {
return (

      <Link to="/" className="menu-link">Main</Link>

      <Link to="aboutus" href="" className="menu-link">About Us</Link>

      <Link to="other" className="menu-link">Some other item</Link>

  );
 }
}

 export default Navbar;

Body:
Because you forgot this part: {this.props.children}. You need to specify the place where you want to render your child component.

Reason why this is required: NavBar is main component, all other component will render inside this, so you need to use {this.props.children}, at this place child component will render.

Use this:

return (
  <nav>
    <ul className="menu-list">

      <li className="menu-item">
        <Link to="/" className="menu-link">Main</Link>
      </li>

      <li className="menu-item">
        <Link to="aboutus" href="" className="menu-link">About Us</Link>
      </li>

      <li className="menu-item">
        <Link to="other" className="menu-link">Some other item</Link>
      </li>

    </ul>
    {this.props.children} //added this line
  </nav>
);


来源: stackexchange

问:
Error : No provider for ValidateService
I'm using @angular/cli . to validate the form I used validate service by creating a folder called services and then ran ng g service validate.
two files created and inside validate.service, I wrote some validation functions. then I imported it to my another file and created an instance inside the constructor to call it using this key word like below.

```<code> constructor(private vd : ValidateService) { }
</code>```

then I check with ng serve. so it give the following error

```<code>ERROR Error: Uncaught (in promise): Error: No provider for ValidateService!
</code>```

some says, this bundle are broken, it will fix soon and instead of it use dev bundle. what is this. I have no idea

答:
There are two ways to do it and latest way of doing:

First:

```<code>@NgModule({
    imports: [],
 providers: [ValidateService]
})
</code>```

Second:

```<code>@Component({
    selector: 'countries',
    providers: [ValidateService]
})
</code>```

It depends on the requirement.

If you want one service instance per component instance, add it to the
  providers of the component. If you want a unique instance for the
  whole app, add it to the providers of the NgModule. This is covered by
  the documentation on services and dependency injection.

As explained by @JB Nizet in comment section

ContentLicense: CC BY-SA 3.0

Title: Error : No provider for ValidateService

Body:
I'm using @angular/cli . to validate the form I used validate service by creating a folder called services and then ran ng g service validate.
two files created and inside validate.service, I wrote some validation functions. then I imported it to my another file and created an instance inside the constructor to call it using this key word like below.

 constructor(private vd : ValidateService) { }

then I check with ng serve. so it give the following error

ERROR Error: Uncaught (in promise): Error: No provider for ValidateService!

some says, this bundle are broken, it will fix soon and instead of it use dev bundle. what is this. I have no idea

Body:
There are two ways to do it and latest way of doing:

First:

@NgModule({
    imports: [],
 providers: [ValidateService]
})

Second:

@Component({
    selector: 'countries',
    providers: [ValidateService]
})

It depends on the requirement.

If you want one service instance per component instance, add it to the
  providers of the component. If you want a unique instance for the
  whole app, add it to the providers of the NgModule. This is covered by
  the documentation on services and dependency injection.

As explained by @JB Nizet in comment section


问:
Select many-to-many relation with "owns" column
I put my efforts to solve following problem:
I have 2 tables in my database:
videos and users_videos as pivot between videos and users (i receive user_id from token, so users table is in another db)

Having an user id, i want to select all videos and attach column containing true or false whether user owns a video.

So far i realized this with following query:

```<code> SELECT v.*, TRUE AS has_video FROM users_videos AS uv
 RIGHT JOIN videos AS v
 ON uv.video_id = v.id
 WHERE (uv.user_id = 1)
 UNION
 (
    SELECT v.*, FALSE AS has_video FROM videos AS v

    EXCEPT

    SELECT v.*, FALSE AS has_video FROM users_videos AS uv
    RIGHT JOIN videos AS v
    ON uv.video_id = v.id
    WHERE (uv.user_id = 1)
  )
</code>```

Although it selects all videos 3 times. Is there any more optimal solution for such kind of problems?

@EDIT ---

Tables structure

```<code>users_videos:
id integer
user_id integer
video_id integer

videos:
id: integer
title: string
</code>```

Example data:

users_videos

```<code>| id | user_id | video_id
-------------------------
  1    1          1
</code>```

videos

```<code>| id | title   |
----------------
  1  | Example 1
-----------------
  2  | Example 2
-----------------
</code>```

Desired result:

```<code>| id | title      | has_video
------------------------------
  1  | Example 1  |   true
------------------------------
  2  | Example 2  |   false
------------------------------
</code>```

@UPDATE --

Used @Stefano Zanini approach:

```<code>SELECT DISTINCT
        v.*,
        CASE
            WHEN uv.user_id IS NULL OR uv.user_id <> 1 THEN FALSE
            ELSE TRUE
        END has_video
FROM    videos v
LEFT JOIN
        users_videos uv
ON      uv.video_id = v.id
</code>```

But one more question came to my mind:

What if i want to display videos in specific category?
Let's say it's another many to many relation on

videos and categories tables with pivot videos_categories

答:
You can do that without the UNION and EXCEPT like this

```<code>select distinct
        v.*,
        case
            when uv.user_id is null or uv.user_id <> 1 then false
            else true
        end has_video
from    videos v
left join
        user_videos uv
on      uv.video_id = v.id
</code>```

Since you described this as a many-to-many relationship, more than one user can own the same video, hence the need for distinct.

The swap from right to left join is just because I think it's easier to read.

Edit

To filter the results on a specific category (as per question edit) you can add a couple of join and a condition in the where

```<code>select distinct
        v.*,
        case
            when uv.user_id is null or uv.user_id <> 1 then false
            else true
        end has_video
from    videos v
join    videos_categories vc
on      v.id = vc.video_id
join    categories c
on      vc.category_id = c.id
left join
        user_videos uv
on      uv.video_id = v.id
where   c.category = 'someCategory'
</code>```

Body:
I put my efforts to solve following problem:
I have 2 tables in my database:
videos and users_videos as pivot between videos and users (i receive user_id from token, so users table is in another db)

Having an user id, i want to select all videos and attach column containing true or false whether user owns a video.

So far i realized this with following query:

 SELECT v.*, TRUE AS has_video FROM users_videos AS uv
 RIGHT JOIN videos AS v
 ON uv.video_id = v.id
 WHERE (uv.user_id = 1)
 UNION
 (
    SELECT v.*, FALSE AS has_video FROM videos AS v

    EXCEPT

    SELECT v.*, FALSE AS has_video FROM users_videos AS uv
    RIGHT JOIN videos AS v
    ON uv.video_id = v.id
    WHERE (uv.user_id = 1)
  )

Although it selects all videos 3 times. Is there any more optimal solution for such kind of problems?

@EDIT ---

Tables structure

users_videos:
id integer
user_id integer
video_id integer

videos:
id: integer
title: string

Example data:

users_videos

| id | user_id | video_id
-------------------------
  1    1          1

videos

| id | title   |
----------------
  1  | Example 1
-----------------
  2  | Example 2
-----------------

Desired result:

| id | title      | has_video
------------------------------
  1  | Example 1  |   true
------------------------------
  2  | Example 2  |   false
------------------------------

@UPDATE --

Used @Stefano Zanini approach:

SELECT DISTINCT
        v.*,
        CASE
            WHEN uv.user_id IS NULL OR uv.user_id <> 1 THEN FALSE
            ELSE TRUE
        END has_video
FROM    videos v
LEFT JOIN
        users_videos uv
ON      uv.video_id = v.id

But one more question came to my mind:

What if i want to display videos in specific category?
Let's say it's another many to many relation on

videos and categories tables with pivot videos_categories

Body:
You can do that without the UNION and EXCEPT like this

select distinct
        v.*,
        case
            when uv.user_id is null or uv.user_id <> 1 then false
            else true
        end has_video
from    videos v
left join
        user_videos uv
on      uv.video_id = v.id

Since you described this as a many-to-many relationship, more than one user can own the same video, hence the need for distinct.

The swap from right to left join is just because I think it's easier to read.

Edit

To filter the results on a specific category (as per question edit) you can add a couple of join and a condition in the where

select distinct
        v.*,
        case
            when uv.user_id is null or uv.user_id <> 1 then false
            else true
        end has_video
from    videos v
join    videos_categories vc
on      v.id = vc.video_id
join    categories c
on      vc.category_id = c.id
left join
        user_videos uv
on      uv.video_id = v.id
where   c.category = 'someCategory'


问:
why I cant deserlize json using datacontractserializer when using wrapped format
My wcf service uses the wrapped format body style. When I try deserializing it using DataContractJsonSerializer isn't deserializing the json properly

```<code>  SignInResult returnedUser = new SignInResult();
            MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(provider.SignIn(username, password)));
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(SignInResult),"root");
            returnedUser =  serializer.ReadObject(stream) as SignInResult;
            stream.Close();
            return returnedUser;
</code>```

but I don't get a object populated according to the following json

```<code>{
  "SignInResult": {
    "CreationDate": "/Date(1480598102923+0000)/",
    "Email": "bladsa@as.com",
    "IsApproved": true,
    "IsLockedOut": false,
    "IsOnline": true,
    "IsValidLogin": true,
    "LastActivityDate": "/Date(1490954750307+0100)/",
    "LastLockoutDate": "/Date(-6816268800000+0000)/",
    "LastLoginDate": "/Date(1490954750307+0100)/",
    "LastPasswordChangedDate": "/Date(-2208988800000+0000)/",
    "ProviderName": "LoginProvider",
    "ProviderUserKey": "dcc5f38f-f71e-4d9d-bdb2-58fb60b7a65e",
    "UserName": "schoi"
  }
}
</code>```

It does work if I use the bare format so it definately something to do with the wrapped message format.

I know I can do this in Newsoft json but I know I will get asked to use Microsofts way.

答:
its so simple. at first we create a jsondeserilzer method like this:

```<code>public static T DataJsonDeserializer<T>(string jsonString)
{
    var mStrm = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
    var jsonSerializer = new DataContractJsonSerializer(typeof(T));
    var objResponse = jsonSerializer.ReadObject(mStrm);
    return (T)objResponse;
}
</code>```

then we create a json object like this:

```<code>public class SignInResult
{
    public DateTime CreationDate { get; set; }
    public string Email { get; set; }
    public bool IsApproved { get; set; }
    public bool IsLockedOut { get; set; }
    public bool IsOnline { get; set; }
    public bool IsValidLogin { get; set; }
    public DateTime LastActivityDate { get; set; }
    public DateTime LastLockoutDate { get; set; }
    public DateTime LastLoginDate { get; set; }
    public DateTime LastPasswordChangedDate { get; set; }
    public string ProviderName { get; set; }
    public string ProviderUserKey { get; set; }
    public string UserName { get; set; }
}

public class RootObject
{
    public SignInResult SignInResult { get; set; }
}
</code>```

finally you can deserilze any thing like this:

```<code>    var x = JsonDeserializer<RootObject>(provider.SignIn(username, password)));
</code>```

Body:
My wcf service uses the wrapped format body style. When I try deserializing it using DataContractJsonSerializer isn't deserializing the json properly

  SignInResult returnedUser = new SignInResult();
            MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(provider.SignIn(username, password)));
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(SignInResult),"root");
            returnedUser =  serializer.ReadObject(stream) as SignInResult;
            stream.Close();
            return returnedUser;

but I don't get a object populated according to the following json

{
  "SignInResult": {
    "CreationDate": "/Date(1480598102923+0000)/",
    "Email": "bladsa@as.com",
    "IsApproved": true,
    "IsLockedOut": false,
    "IsOnline": true,
    "IsValidLogin": true,
    "LastActivityDate": "/Date(1490954750307+0100)/",
    "LastLockoutDate": "/Date(-6816268800000+0000)/",
    "LastLoginDate": "/Date(1490954750307+0100)/",
    "LastPasswordChangedDate": "/Date(-2208988800000+0000)/",
    "ProviderName": "LoginProvider",
    "ProviderUserKey": "dcc5f38f-f71e-4d9d-bdb2-58fb60b7a65e",
    "UserName": "schoi"
  }
}

It does work if I use the bare format so it definately something to do with the wrapped message format.

I know I can do this in Newsoft json but I know I will get asked to use Microsofts way.

Body:
its so simple. at first we create a jsondeserilzer method like this:

public static T DataJsonDeserializer<T>(string jsonString)
{
    var mStrm = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
    var jsonSerializer = new DataContractJsonSerializer(typeof(T));
    var objResponse = jsonSerializer.ReadObject(mStrm);
    return (T)objResponse;
}

then we create a json object like this:

public class SignInResult
{
    public DateTime CreationDate { get; set; }
    public string Email { get; set; }
    public bool IsApproved { get; set; }
    public bool IsLockedOut { get; set; }
    public bool IsOnline { get; set; }
    public bool IsValidLogin { get; set; }
    public DateTime LastActivityDate { get; set; }
    public DateTime LastLockoutDate { get; set; }
    public DateTime LastLoginDate { get; set; }
    public DateTime LastPasswordChangedDate { get; set; }
    public string ProviderName { get; set; }
    public string ProviderUserKey { get; set; }
    public string UserName { get; set; }
}

public class RootObject
{
    public SignInResult SignInResult { get; set; }
}

finally you can deserilze any thing like this:

    var x = JsonDeserializer<RootObject>(provider.SignIn(username, password)));


问:
ping multiple sub nets / bash
I'm trying to ping multiple sub nets
what I'm doing now is simply repeating the loop
but I believe should be much simpler solution to do it in one loop</p>

```<code>for i in 192.168.0.{1..254}
do
echo $1 >> live_host_list & disown
done
echo "net 192.168.0.0 Scanned"
echo "starting 10.0.0.0 network"
for i in 10.0.0.{1..254}
do
echo $1 >> live_host_list & disown
done
echo "net 10.0.0.0 Scanned"
</code>```

Title: ping multiple sub nets / bash

Body:
I'm trying to ping multiple sub nets
what I'm doing now is simply repeating the loop
but I believe should be much simpler solution to do it in one loop

for i in 192.168.0.{1..254}
do
echo $1 >> live_host_list & disown
done
echo "net 192.168.0.0 Scanned"
echo "starting 10.0.0.0 network"
for i in 10.0.0.{1..254}
do
echo $1 >> live_host_list & disown
done
echo "net 10.0.0.0 Scanned"

Body:
You can very easily generate a list of IP's using perl oneliner.

perl -MNet::IP -lnE '$ip=Net::IP->new($_) or warn "wrong input: $_";while($ip){say$ip++->ip()}'

You need the Net::IP module. The above code - formatted for easy reading:

perl -MNet::IP -lnE '
    $ip = Net::IP->new($_) or warn "wrong input: $_";
    while( $ip ) {
        say$ip++->ip()
    }'

The nice thing with the above is, it could accept many different inputs, e.g. you can use it as:

perl -MNet::IP -lnE '$ip=Net::IP->new($_)or warn "wrong input: $_";while($ip){say$ip++->ip()}' <<EOF
10.10.10.252 - 10.10.11.2
192.168.1.240/29
10.10.9.32 + 7
10.10.100.100
EOF

so, you can use as input

range of IP addresses: 10.10.10.252 - 10.10.11.2

class-less prefix 192.168.1.240/29

start + next N 10.10.9.32 + 7

1 address alone 10.10.100.100

the above produces:

10.10.10.252
10.10.10.253
10.10.10.254
10.10.10.255
10.10.11.0
10.10.11.1
10.10.11.2
192.168.1.240
192.168.1.241
192.168.1.242
192.168.1.243
192.168.1.244
192.168.1.245
192.168.1.246
192.168.1.247
10.10.9.32
10.10.9.33
10.10.9.34
10.10.9.35
10.10.9.36
10.10.9.37
10.10.9.38
10.10.9.39
10.10.100.100


问:
How would I call only one variable from a function that contains multiple variables?
So basically I am trying to create a hangman game, and as of right now I'm just trying to pass a variable from one function to another, though I'm confused on how to do so, here is my code:

```<code>import random

print("Welcome to Hangman!")

def wordSelection():
  words = ["test", "random"]
  wordChoice = random.randint(0, 1)
  selectedWord = words[wordChoice]
  print(selectedWord)
  return selectedWord

def guessWord():
  selectedWord = wordSelection()
  print(selectedWord)

wordSelection()
guessWord()
</code>```

The question I have is basically, how am I able to call the variable 'selectedWord' from the wordSelection function and pass it into the guessWord() function?

I tried to at the bottom as you can see, however I just called the whole function again, instead of only specifically getting selectedWord rather than the whole function.

What could I do to ONLY get 'selectedWord' from WordSelection() rather than just getting the whole function - is this possible?

答:
You have a misunderstanding about how variables work, especially in Python.

In Python, a variable is simply a label that refers to a value that exists somewhere in memory. For example:

```<code> x = 3
 # Now you can refer to the value `3` by the name x
 y = x
 # Now `y` refers to the *same* `3` that is in memory - it's not a copy!
 print(id(x))
 print(id(y))
 # Will print the same ID, but it will probably be different on your
 # system and mine
</code>```

When you return a value from a function, you're not returning the name - you're returning effectively where the value lives. If you want to keep that value, you're going to have to give it a name:

```<code>def fun():
    result = 42
    print(id(result))
    return result

fun()  # Discards the return value
print(fun())  # prints the return value
print(id(fun))  # prints where the return value lives
value = fun()   # actually stores the return value by giving it a name
print(id(value))    # now you can use that value later!
print(value + 3)    # you can use it more times
</code>```

So in your code, you want to call a function that gives you a random word, which you can do like this:

```<code>def word_selection():
    # Note I used snake case - see
    # https://www.python.org/dev/peps/pep-0008/#function-names
    # for more info
    words = ['test', 'random', 'python', 'awesome', 'something', 'completely', 'different']
    return random.choice(words)
</code>```

In order to do anything with this value, you need to store it. It's returned wherever you call the function. In Python you call something by adding parenthesis () after it:

```<code>print(word_selection)  # Doesn't call the function
print(word_selection())   # Does call the function, then prints the result
</code>```

So you can either require an argument on your guess_word function and pass it in:

```<code>def guess_word(word):
    # do whatever you need to do here
    print('Time to guess:', word)   # don't really give them the answer, though

guess_word(word_selection())   # you can call it like this

secret_word = word_selection()   # or store the value first
guess_word(secret_word)          # and then pass it to your function
</code>```

Writing your program like that is probably a good exercise in seeing how that stuff works - but you could actually make it the same by doing something like this:

```<code>WORD_LIST = ['python', 'something', 'completely', 'different']

def guess_word(word):
    print('Time to guess the word:', '*'*len(word))

guess_word(random.choice(WORD_LIST))
</code>```

Body:
So basically I am trying to create a hangman game, and as of right now I'm just trying to pass a variable from one function to another, though I'm confused on how to do so, here is my code:

import random

print("Welcome to Hangman!")

def wordSelection():
  words = ["test", "random"]
  wordChoice = random.randint(0, 1)
  selectedWord = words[wordChoice]
  print(selectedWord)
  return selectedWord

def guessWord():
  selectedWord = wordSelection()
  print(selectedWord)

wordSelection()
guessWord()

The question I have is basically, how am I able to call the variable 'selectedWord' from the wordSelection function and pass it into the guessWord() function?

I tried to at the bottom as you can see, however I just called the whole function again, instead of only specifically getting selectedWord rather than the whole function.

What could I do to ONLY get 'selectedWord' from WordSelection() rather than just getting the whole function - is this possible?

Body:
You have a misunderstanding about how variables work, especially in Python.

In Python, a variable is simply a label that refers to a value that exists somewhere in memory. For example:

 x = 3
 # Now you can refer to the value `3` by the name x
 y = x
 # Now `y` refers to the *same* `3` that is in memory - it's not a copy!
 print(id(x))
 print(id(y))
 # Will print the same ID, but it will probably be different on your
 # system and mine

When you return a value from a function, you're not returning the name - you're returning effectively where the value lives. If you want to keep that value, you're going to have to give it a name:

def fun():
    result = 42
    print(id(result))
    return result

fun()  # Discards the return value
print(fun())  # prints the return value
print(id(fun))  # prints where the return value lives
value = fun()   # actually stores the return value by giving it a name
print(id(value))    # now you can use that value later!
print(value + 3)    # you can use it more times

So in your code, you want to call a function that gives you a random word, which you can do like this:

def word_selection():
    # Note I used snake case - see
    # https://www.python.org/dev/peps/pep-0008/#function-names
    # for more info
    words = ['test', 'random', 'python', 'awesome', 'something', 'completely', 'different']
    return random.choice(words)

In order to do anything with this value, you need to store it. It's returned wherever you call the function. In Python you call something by adding parenthesis () after it:

print(word_selection)  # Doesn't call the function
print(word_selection())   # Does call the function, then prints the result

So you can either require an argument on your guess_word function and pass it in:

def guess_word(word):
    # do whatever you need to do here
    print('Time to guess:', word)   # don't really give them the answer, though

guess_word(word_selection())   # you can call it like this

secret_word = word_selection()   # or store the value first
guess_word(secret_word)          # and then pass it to your function

Writing your program like that is probably a good exercise in seeing how that stuff works - but you could actually make it the same by doing something like this:

WORD_LIST = ['python', 'something', 'completely', 'different']

def guess_word(word):
    print('Time to guess the word:', '*'*len(word))

guess_word(random.choice(WORD_LIST))


问:
How to bypass the proxy using java
Here belwo is my code

```<code>import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;

import com.sun.org.apache.xml.internal.security.utils.Base64;

public class webpageDisplay {

    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        System.getProperties().put( "proxySet", "true" );
        System.getProperties().put( "proxyHost", "I given proxy host" );
        System.getProperties().put( "proxyPort", "85" );
        URL url=new URL("http://www.yahoo.com");
        URLConnection uc = url.openConnection ();
        String encoded = new String
              (Base64.encode(new String("user:pass").getBytes()));
        uc.setRequestProperty("Proxy-Authorization", "Basic " + encoded);
        uc.connect();

         //String url = "http://www.yahoo.com";
            JEditorPane editor = new JEditorPane(url);
            editor.setEditable(false);
            JScrollPane pane = new JScrollPane(editor);
            JFrame f = new JFrame("HTML Demo");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(pane);
            f.setSize(800, 600);
            f.setVisible(true);

    }

}
</code>```

even though i provided proxy host and userid still iam getting erorr as below

```<code>Exception in thread "main" java.net.UnknownHostException: www.yahoo.com
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:196)
    at java.net.Socket.connect(Socket.java:530)
    at java.net.Socket.connect(Socket.java:480)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:169)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:406)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:541)
    at sun.net.www.http.HttpClient.<init>(HttpClient.java:245)
    at sun.net.www.http.HttpClient.New(HttpClient.java:318)
    at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:790)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:738)
    at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:649)
    at webpageDisplay.main(webpageDisplay.java:26)
</code>```

Can anyone suggest how to resolve the issue or how can i bypass the proxy

答:
```<code>System.setProperty("http.proxyHost", "132.186.192.234");
System.setProperty("http.proxyPort", "8080");
System.setProperty("https.proxyUser", "ad001\\userid");
System.setProperty("https.proxyPassword", "sect");
</code>```

Title: How to bypass the proxy using java

Body:
Here belwo is my code

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;

import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;

import com.sun.org.apache.xml.internal.security.utils.Base64;

public class webpageDisplay {

    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        System.getProperties().put( "proxySet", "true" );
        System.getProperties().put( "proxyHost", "I given proxy host" );
        System.getProperties().put( "proxyPort", "85" );
        URL url=new URL("http://www.yahoo.com");
        URLConnection uc = url.openConnection ();
        String encoded = new String
              (Base64.encode(new String("user:pass").getBytes()));
        uc.setRequestProperty("Proxy-Authorization", "Basic " + encoded);
        uc.connect();

         //String url = "http://www.yahoo.com";
            JEditorPane editor = new JEditorPane(url);
            editor.setEditable(false);
            JScrollPane pane = new JScrollPane(editor);
            JFrame f = new JFrame("HTML Demo");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(pane);
            f.setSize(800, 600);
            f.setVisible(true);

    }

}

even though i provided proxy host and userid still iam getting erorr as below

Exception in thread "main" java.net.UnknownHostException: www.yahoo.com
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:196)
    at java.net.Socket.connect(Socket.java:530)
    at java.net.Socket.connect(Socket.java:480)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:169)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:406)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:541)
    at sun.net.www.http.HttpClient.<init>(HttpClient.java:245)
    at sun.net.www.http.HttpClient.New(HttpClient.java:318)
    at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:790)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:738)
    at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:649)
    at webpageDisplay.main(webpageDisplay.java:26)

Can anyone suggest how to resolve the issue or how can i bypass the proxy


问:
reactjs - how to set inline style of backgroundcolor?
I want to set the style properties of some elements but I don't have the syntax correct.  Can anyone suggest where I am wrong?

```<code>import React from 'react';
import debug from 'debug'

const log = debug('app:component:Header');

var bgColors = { "Default": "#81b71a",
                    "Blue": "#00B1E1",
                    "Cyan": "#37BC9B",
                    "Green": "#8CC152",
                    "Red": "#E9573F",
                    "Yellow": "#F6BB42",
};

export default class SideBar extends React.Component {

  constructor(props) {
    super(props);

  }

  render() {

    return (

    <a style="{{backgroundColor: {bgColors.Default}}}" >default</a>
    <a style="{{backgroundColor: {bgColors.Blue}}}" >blue</a>
    <a style="{{backgroundColor: {bgColors.Cyan}}}" >cyan</a>
    <a style="{{backgroundColor: {bgColors.Green}}}" >green</a>
    <a style="{{backgroundColor: {bgColors.Red}}}"  >red</a>
    <a style="{{backgroundColor: {bgColors.Yellow}}}" >yellow</a>
           );
  }

}
</code>```

UPDATE: for anyone looking at this please see comments this is not working code.

答:
If you want more than one style this is the correct full answer.
This is div with class and style:</p>

```<code><div className="class-example" style={{width: '300px', height: '150px'}}></div>
</code>```

Body:
I want to set the style properties of some elements but I don't have the syntax correct.  Can anyone suggest where I am wrong?

import React from 'react';
import debug from 'debug'

const log = debug('app:component:Header');

var bgColors = { "Default": "#81b71a",
                    "Blue": "#00B1E1",
                    "Cyan": "#37BC9B",
                    "Green": "#8CC152",
                    "Red": "#E9573F",
                    "Yellow": "#F6BB42",
};

export default class SideBar extends React.Component {

  constructor(props) {
    super(props);

  }

  render() {

    return (

    default
    blue
    cyan
    green
    red
    yellow
           );
  }

}

UPDATE: for anyone looking at this please see comments this is not working code.

Body:
If you want more than one style this is the correct full answer.
This is div with class and style:

<div className="class-example" style={{width: '300px', height: '150px'}}></div>


问:
I cannot use the Color.FromName(string s) method
I need to use the FromName Method, but for some reason it is not available.
I have been googling for a while but I cannot find a solution.

答: Try using System.Drawing.Color.FromName instead of Color.FromName. If that doesn't help, maybe the problem comes from the Framework, which is quite unlikely .. </p>


问:
How to check if a class in javascript exists
I am defining a class in javascript using this...

```<code>// file_a.js
function class_a() {
    this.prop1 = null;
    this.prop2 = null;
}

// file_b.js
var obj = new class_a;
// I need to check here if class_a exists
</code>```

How can I do this?

Regards

答:
```<code>if (typeof class_a === 'function')
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am defining a class in javascript using this...

// file_a.js
function class_a() {
    this.prop1 = null;
    this.prop2 = null;
}

// file_b.js
var obj = new class_a;
// I need to check here if class_a exists

How can I do this?

Regards

Body: if (typeof class_a === 'function')


问:
Angular 2 lazy loading redirecting to a blank page
I changed my angular 2 scripts and created a new feature module that contain component of signup and signin pages:

```<code>import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { SignupComponent } from './signup/signup.component';
import { SigninComponent } from './signin/signin.component';
import { NotfoundComponent } from '../notfound/notfound.component';
import { ChildRoutingModule } from './auth.route';
@NgModule({
    declarations:[
        SignupComponent,
        SigninComponent,
        NotfoundComponent
    ],

    imports:[
        FormsModule,
        HttpModule,

        ChildRoutingModule
    ]
})

export class AuthModule{}
</code>```

And of course I created a child route file called ChildRoutingModule:

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';
import { SigninComponent } from './signin/signin.component';
import { SignupComponent } from './signup/signup.component';

const childRoutes: Routes = [
    {path: 'signup', loadChildren: './auth.module#AuthModule'},
    {path: 'signin', component: SigninComponent}

];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(childRoutes)
  ],
  exports:[RouterModule]
})
export class ChildRoutingModule { }
</code>```

In this routes file, I created a lazy loading to home page by using:

```<code>{path: 'signup', loadChildren: './auth.module#AuthModule'},
</code>```

as you see it at the AuthModule exported class.

Here is the parent root module:

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SigninComponent } from './auth/signin/signin.component';
import { SignupComponent } from './auth/signup/signup.component';
import { NotfoundComponent } from './notfound/notfound.component';
import { ChildRoutingModule } from './auth/auth.route';
import { HomeComponent } from './home/home.component';

const appRoutes: Routes = [
    //{path: '', redirectTo:'signup', pathMatch:'full'},
    {path: '', component: HomeComponent},

    {path: '**', component: NotfoundComponent}
];

@NgModule({
  imports: [
    RouterModule.forRoot(appRoutes)
  ],
  exports:[RouterModule]
})
export class AppRoutingModule { }
</code>```

And here is the parent module app.module:

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';

import {RouterModule} from '@angular/router';

import { AppComponent } from './app.component';
import { AuthModule } from './auth/auth.module';

import {AuthService} from './auth/auth.service';

import { AppRoutingModule } from './routes';
import { ChildRoutingModule } from './auth/auth.route';
import { HomeComponent } from './home/home.component';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent
  ],
  imports: [
    ChildRoutingModule,
    BrowserModule,
    AuthModule,
    RouterModule,
    AppRoutingModule,
    CommonModule

  ],
  providers: [AuthService],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

My problem now is that when I hit the register button in the home component:

```<code><h1>Home Page</h1>
<button [routerLink]="['/signup']" type="button" class="btn btn-primary">Register</button>
<hr>
<button type="button" class="btn btn-primary">Login</button>
</code>```

With no script in the home.component.ts, I will redirect to a blank component with the correct link:

localhost:4200/signup

And with no errors at the console.

P.S.: if I typed localhost:4200/singin it will show me the sign in component normally

答:
It looks to me like you have a circular dependency.

AuthModule imports the ChildRoutingModule that includes a signup route lazily-loaded to AuthModule.
That is why signin works, but signup does not, as signup is a circular dependency.

EDIT

To solve this, I would change up your routing a bit.  First off, I wouldn't create separate NgModules just to hold route configurations.  Add the route configs to the appopriate modules.  I haven't tested this exact code, but it should look something like this:

```<code>//app.routes.ts

import { Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { NotfoundComponent } from './notfound/notfound.component';

export const ROUTES: Routes = [
    {path: '', component: HomeComponent},
    {path: 'signin', loadChildren: './auth/auth.module#AuthModule'},
    {path: '**', component: NotfoundComponent}
];
</code>```

Use that in your AppModule:

```<code>// app.module.ts

import { ROUTES as appRoutes } from './app.routes';

...

imports: [
    ...
    RouterModule.forRoot(appRoutes)
],
</code>```

Then do a similar thing for the route config for the AuthModule:

```<code>//auth.routes.ts

import { Routes } from '@angular/router';
import { SigninComponent } from './signin/signin.component';
import { SignupComponent } from './signup/signup.component';

export const ROUTES: Routes = [
    {path: '', component: SigninComponent},
    {path: 'signup', loadChildren: './auth.module#AuthModule'}
];
</code>```

And Import it in your AuthModule:

```<code>//auth.module.ts

import { ROUTES as authRoutes } from './auth.routes';

imports: [
    ...
    RouterModule.forChild(authRoutes)
]
</code>```

With this, your whole AuthModule is lazily loaded and your url's stay the same as you have them.

Body:
I changed my angular 2 scripts and created a new feature module that contain component of signup and signin pages:

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { SignupComponent } from './signup/signup.component';
import { SigninComponent } from './signin/signin.component';
import { NotfoundComponent } from '../notfound/notfound.component';
import { ChildRoutingModule } from './auth.route';
@NgModule({
    declarations:[
        SignupComponent,
        SigninComponent,
        NotfoundComponent
    ],

    imports:[
        FormsModule,
        HttpModule,

        ChildRoutingModule
    ]
})

export class AuthModule{}

And of course I created a child route file called ChildRoutingModule:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';
import { SigninComponent } from './signin/signin.component';
import { SignupComponent } from './signup/signup.component';

const childRoutes: Routes = [
    {path: 'signup', loadChildren: './auth.module#AuthModule'},
    {path: 'signin', component: SigninComponent}

];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(childRoutes)
  ],
  exports:[RouterModule]
})
export class ChildRoutingModule { }

In this routes file, I created a lazy loading to home page by using:

{path: 'signup', loadChildren: './auth.module#AuthModule'},

as you see it at the AuthModule exported class.

Here is the parent root module:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SigninComponent } from './auth/signin/signin.component';
import { SignupComponent } from './auth/signup/signup.component';
import { NotfoundComponent } from './notfound/notfound.component';
import { ChildRoutingModule } from './auth/auth.route';
import { HomeComponent } from './home/home.component';

const appRoutes: Routes = [
    //{path: '', redirectTo:'signup', pathMatch:'full'},
    {path: '', component: HomeComponent},

    {path: '**', component: NotfoundComponent}
];

@NgModule({
  imports: [
    RouterModule.forRoot(appRoutes)
  ],
  exports:[RouterModule]
})
export class AppRoutingModule { }

And here is the parent module app.module:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';

import {RouterModule} from '@angular/router';

import { AppComponent } from './app.component';
import { AuthModule } from './auth/auth.module';

import {AuthService} from './auth/auth.service';

import { AppRoutingModule } from './routes';
import { ChildRoutingModule } from './auth/auth.route';
import { HomeComponent } from './home/home.component';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent
  ],
  imports: [
    ChildRoutingModule,
    BrowserModule,
    AuthModule,
    RouterModule,
    AppRoutingModule,
    CommonModule

  ],
  providers: [AuthService],
  bootstrap: [AppComponent]
})
export class AppModule { }

My problem now is that when I hit the register button in the home component:

Home Page

<button [routerLink]="['/signup']" type="button" class="btn btn-primary">Register</button>

<button type="button" class="btn btn-primary">Login</button>

With no script in the home.component.ts, I will redirect to a blank component with the correct link:

localhost:4200/signup

And with no errors at the console.

P.S.: if I typed localhost:4200/singin it will show me the sign in component normally

Body:
It looks to me like you have a circular dependency.

AuthModule imports the ChildRoutingModule that includes a signup route lazily-loaded to AuthModule.
That is why signin works, but signup does not, as signup is a circular dependency.

EDIT

To solve this, I would change up your routing a bit.  First off, I wouldn't create separate NgModules just to hold route configurations.  Add the route configs to the appopriate modules.  I haven't tested this exact code, but it should look something like this:

//app.routes.ts

import { Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { NotfoundComponent } from './notfound/notfound.component';

export const ROUTES: Routes = [
    {path: '', component: HomeComponent},
    {path: 'signin', loadChildren: './auth/auth.module#AuthModule'},
    {path: '**', component: NotfoundComponent}
];

Use that in your AppModule:

// app.module.ts

import { ROUTES as appRoutes } from './app.routes';

...

imports: [
    ...
    RouterModule.forRoot(appRoutes)
],

Then do a similar thing for the route config for the AuthModule:

//auth.routes.ts

import { Routes } from '@angular/router';
import { SigninComponent } from './signin/signin.component';
import { SignupComponent } from './signup/signup.component';

export const ROUTES: Routes = [
    {path: '', component: SigninComponent},
    {path: 'signup', loadChildren: './auth.module#AuthModule'}
];

And Import it in your AuthModule:

//auth.module.ts

import { ROUTES as authRoutes } from './auth.routes';

imports: [
    ...
    RouterModule.forChild(authRoutes)
]

With this, your whole AuthModule is lazily loaded and your url's stay the same as you have them.


问:
Searchbox to URL in Javascript html
Okay, so I have this code

Admin Login

<form method="post" action="ingen_javascript.htm"
  onsubmit="CheckPassword();return false;" name="login">
```
Username: <input type="text" name="username">
Password: <input type="password" name="password">
```
<input type="submit" value="login"
  onclick="CheckPassword();return false;">
</form>

```

and you can see that if you type anything on and click enter, it will come up with that in the URL. But how do I get rid of the password and just use the username but instead of 'Username:' it says 'vite:' and instead of 'login' it says 'go!'

答:
After rereading your question and noticing the title hints that you are actually trying to use this code as some sort of searchable navigation instead of a "password" system like the original code, I've updated my answer.  I use a <datalist> element to provide a list of suggested page names since you likely have a finite list of pages you want to be accessible this way rather than allowing arbitrary urls. The JavaScript then checks against that list so it only navigates to pages that actually exist.

// get go and vite by thier id
var go = document.getElementById('go'),
  vite = document.getElementById('vite')
  // get all of the option elements inside of the pages datalist
  pages = document.querySelectorAll('#pages > option');

// convert the node list that querySelectorAll returned into a real array
pages = Array.prototype.slice.call(pages);

// convert pages from an array of element into an array of strings
// containing the value of each of the elements
pages = pages.map(function (item) {
  return item.value;
});

// goToSelectedPage should not be capitalized, in JS it is convention to
// only capitalize constructor functions
function goToSelectedPage () {
  var page = vite.value,
    url = page + '.htm';
  // if the value of vite is in the list of pages
  if (-1 !== pages.indexOf(page)) {
    console.log('Navigating to ' + url);
    // disabling the page change for this example
    //location.href = url;
  }
}

// attach the goToSelectedPage function to the click event on go
// All vaguely modern browsers support addEventListener,
// no need to check for it and fall back to attachEvent
go.addEventListener('click', goToSelectedPage, false);
// add an event listener to vite that will call goToSelectedPage
// if they press the enter key instead of clicking the Go! button
vite.addEventListener('keyup', function (evt) {
  if (evt.key === 'Enter') {
    goToSelectedPage();
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  color: blue; /* instead of wrapping the page in a font tag,
                  add the color to styling for the body */
}
.login-header {
  font-family: Comic Sans Ms;
  text-align: center;
  font-size: 20pt;
  color: #0F0;
}</code>```

Admin Login

Vite: <input type="text" id="vite" list="pages"> <button id="go" type="button">Go!</button>

<datalist id="pages">
  <option value="foo">
  <option value="bar">
  <option value="baz">
</datalist>```

Instead of using inline styles and font tags, I moved the styling into a

Title: Searchbox to URL in Javascript html

Body:
Okay, so I have this code

Admin Login

<form method="post" action="ingen_javascript.htm"
  onsubmit="CheckPassword();return false;" name="login">

Username: <input type="text" name="username">
Password: <input type="password" name="password">

<input type="submit" value="login"
  onclick="CheckPassword();return false;">
</form>

and you can see that if you type anything on and click enter, it will come up with that in the URL. But how do I get rid of the password and just use the username but instead of 'Username:' it says 'vite:' and instead of 'login' it says 'go!'

Body:
After rereading your question and noticing the title hints that you are actually trying to use this code as some sort of searchable navigation instead of a "password" system like the original code, I've updated my answer.  I use a <datalist> element to provide a list of suggested page names since you likely have a finite list of pages you want to be accessible this way rather than allowing arbitrary urls. The JavaScript then checks against that list so it only navigates to pages that actually exist.

// get go and vite by thier id
var go = document.getElementById('go'),
  vite = document.getElementById('vite')
  // get all of the option elements inside of the pages datalist
  pages = document.querySelectorAll('#pages > option');

// convert the node list that querySelectorAll returned into a real array
pages = Array.prototype.slice.call(pages);

// convert pages from an array of element into an array of strings
// containing the value of each of the elements
pages = pages.map(function (item) {
  return item.value;
});

// goToSelectedPage should not be capitalized, in JS it is convention to
// only capitalize constructor functions
function goToSelectedPage () {
  var page = vite.value,
    url = page + '.htm';
  // if the value of vite is in the list of pages
  if (-1 !== pages.indexOf(page)) {
    console.log('Navigating to ' + url);
    // disabling the page change for this example
    //location.href = url;
  }
}

// attach the goToSelectedPage function to the click event on go
// All vaguely modern browsers support addEventListener,
// no need to check for it and fall back to attachEvent
go.addEventListener('click', goToSelectedPage, false);
// add an event listener to vite that will call goToSelectedPage
// if they press the enter key instead of clicking the Go! button
vite.addEventListener('keyup', function (evt) {
  if (evt.key === 'Enter') {
    goToSelectedPage();
  }
});

body {
  color: blue; /* instead of wrapping the page in a font tag,
                  add the color to styling for the body */
}
.login-header {
  font-family: Comic Sans Ms;
  text-align: center;
  font-size: 20pt;
  color: #0F0;
}

<h1 class="login-header">Admin Login</h1>
<label for="vite">Vite:</label> <input type="text" id="vite" list="pages"> <button id="go" type="button">Go!</button>
<!-- datalist is invisible but will be used by the vite element to provide an
auto complete suggestion list -->
<datalist id="pages">
  <option value="foo">
  <option value="bar">
  <option value="baz">
</datalist>

Instead of using inline styles and font tags, I moved the styling into a <style> block and gave the h1 tag a class that applies its styling. I removed the form since you aren't actually submitting a form. Using a <button type="button"> instead of submit input will ensure that pressing the button by itself does not try to submit a form, causing navigation. I used getElementById to get references to the vite and go elements and querySelectorAll, which finds elements based on a CSS selector string to grab the option elements. The list of option elements are then refined into a list of their values so we can search that list to confirm that a page exists before we try navigating to it.

Other notes:
You don't need to (and should not) use the language or type attribute on script tags, just use a bare <script> tag. Language has been deprecated for a long time and was never standardized. Type never really did anything either because a few different factors. Neither are needed, every browser that has ever supported the script tag defaults to JavaScript.

Further reading:

Introduction to CSS

Eloquent JavaScript A great (and free) book about JS

Convert NodeList to Array

Array.prototype.indexOf

I wrote Spotting bad JavaScript tutorials to help people who are learning JS; there are a lot of bad and/or outdated tutorials out there. A lot of beginners use that bad information unknowingly and develop bad habits. Knowing what to look out for can help you avoid things that may lead you to those bad habits.

For posterity I'll leave this here for anyone who is thinking about using code similar to the code in the question as a "password" system. Using something like basic authentication would be a much better idea than using secret filenames. Someone will find those pages eventually. I've had search engines somehow find files that were never linked to anywhere! Don't count on an obscure filename to keep it private.


问:
Cannot use inheritance properly Ionic 2
I am working on an app with different pages and I wanted to have an abstract class for the page from which all the pages inherit from.
The problem is if I "extend" one class with the abstract one, it works, but as soon as I two or more pages extend the abstract class it gives me this error:

```<code>Cannot read property 'prototype' of undefined
</code>```

My AbstractPage is this one:

```<code>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Contact } from '../contact/contact';
import { Page1 } from '../page1/page1';
import { Page2 } from '../page2/page2';
import { Page3 } from '../page3/page3';
import { Page4 } from '../page4/page4';
import { Page5 } from '../page5/page5';
import { Page6 } from '../page6/page6';
import { Page7 } from '../page7/page7';
import { Page8 } from '../page8/page8';
import { Page9 } from '../page9/page9';
import { Page10 } from '../page10/page10';
import { Page11 } from '../page11/page11';
import { Page12 } from '../page12/page12';
import { Page13 } from '../page13/page13';
import { Page14 } from '../page14/page14';
import { Page15 } from '../page15/page15';
import { Page16 } from '../page16/page16';

export abstract class AbstractPage {
  static pages = [Page1, Page2, Page3, Page4, Page5, Page6, Page7, Page8, Page9, Page10, Page11, Page12, Page13, Page14, Page15, Page16];
  pageNumber: number;
  hasSharableContent: boolean;
  public navCtrl: NavController;

  constructor( page_number: number, has_sharable_content: boolean) {
    this.pageNumber = page_number;
    this.hasSharableContent = has_sharable_content;
  }

  changePage(direction: number) {
    if (direction==1){
      console.log(direction,this.pageNumber);
      this.navCtrl.setRoot(AbstractPage.pages[this.pageNumber], {}, {animate: true, direction: 'forward'});
    }
    else if(direction == 2){
      this.navCtrl.push(Contact);
    }
    else{
      this.navCtrl.setRoot(AbstractPage.pages[this.pageNumber-1], {}, {animate: true, direction: 'back'});
    }
  }
}
</code>```

My Page1 is:

```<code>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {AbstractPage } from '../abstract-page/abstract-page';

@Component({
  selector: 'page1',
  templateUrl: 'page1.html'
})

export class Page1 extends AbstractPage{
  constructor(public navCtrl: NavController) {
    super(1, false);
  }
}
</code>```

My Page2 is:

```<code>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { AbstractPage } from '../abstract-page/abstract-page';

@Component({
  selector: 'page2',
  templateUrl: 'page2.html'
})

export class Page2 extends AbstractPage{
  constructor(public navCtrl: NavController) {
    super(2, true);
  }
}
</code>```

I've added a repo on GitHub if someone wants to try and solve the problem:
https://github.com/francescobenintende/Tests/tree/master/abstraction

Error:
http://imgur.com/a/0PfTe

答:
Update:

You can't use this kind of Page component inheritance with Ionic2 and Typescript now.Hope you can do that with Ionic3 and latest Typescript which will be included with Ionic3.This issue is related to the Typescript and web pack.

You can get more info here.

You too can see the issue here if you explore the main.js.map file.It creates a subclass(Page1) first and after that base class (AbstractPage).That is the reason for this error.But unfortunately, we cannot change the order.

Old Answer:

You can try with public constructor() on the abstract class as shown below.

```<code> export abstract class AbstractPage {

  constructor(public page_number: number,public has_sharable_content: boolean) {

    }

  changePage(direction: number) {
    if (direction==1){
      console.log(direction,this.page_number);
      this.navCtrl.setRoot(AbstractPage.pages[this.page_number], {}, {animate: true, direction: 'forward'});
    }
    else if(direction == 2){
      this.navCtrl.push(Contact);
    }
    else{
      this.navCtrl.setRoot(AbstractPage.pages[this.page_number-1], {}, {animate: true, direction: 'back'});
    }
  }
}
</code>```

Title: Cannot use inheritance properly Ionic 2

Body:
I am working on an app with different pages and I wanted to have an abstract class for the page from which all the pages inherit from.
The problem is if I "extend" one class with the abstract one, it works, but as soon as I two or more pages extend the abstract class it gives me this error:

Cannot read property 'prototype' of undefined

My AbstractPage is this one:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Contact } from '../contact/contact';
import { Page1 } from '../page1/page1';
import { Page2 } from '../page2/page2';
import { Page3 } from '../page3/page3';
import { Page4 } from '../page4/page4';
import { Page5 } from '../page5/page5';
import { Page6 } from '../page6/page6';
import { Page7 } from '../page7/page7';
import { Page8 } from '../page8/page8';
import { Page9 } from '../page9/page9';
import { Page10 } from '../page10/page10';
import { Page11 } from '../page11/page11';
import { Page12 } from '../page12/page12';
import { Page13 } from '../page13/page13';
import { Page14 } from '../page14/page14';
import { Page15 } from '../page15/page15';
import { Page16 } from '../page16/page16';

export abstract class AbstractPage {
  static pages = [Page1, Page2, Page3, Page4, Page5, Page6, Page7, Page8, Page9, Page10, Page11, Page12, Page13, Page14, Page15, Page16];
  pageNumber: number;
  hasSharableContent: boolean;
  public navCtrl: NavController;

  constructor( page_number: number, has_sharable_content: boolean) {
    this.pageNumber = page_number;
    this.hasSharableContent = has_sharable_content;
  }

  changePage(direction: number) {
    if (direction==1){
      console.log(direction,this.pageNumber);
      this.navCtrl.setRoot(AbstractPage.pages[this.pageNumber], {}, {animate: true, direction: 'forward'});
    }
    else if(direction == 2){
      this.navCtrl.push(Contact);
    }
    else{
      this.navCtrl.setRoot(AbstractPage.pages[this.pageNumber-1], {}, {animate: true, direction: 'back'});
    }
  }
}

My Page1 is:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {AbstractPage } from '../abstract-page/abstract-page';

@Component({
  selector: 'page1',
  templateUrl: 'page1.html'
})

export class Page1 extends AbstractPage{
  constructor(public navCtrl: NavController) {
    super(1, false);
  }
}

My Page2 is:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { AbstractPage } from '../abstract-page/abstract-page';

@Component({
  selector: 'page2',
  templateUrl: 'page2.html'
})

export class Page2 extends AbstractPage{
  constructor(public navCtrl: NavController) {
    super(2, true);
  }
}

I've added a repo on GitHub if someone wants to try and solve the problem:
https://github.com/francescobenintende/Tests/tree/master/abstraction

Error:
http://imgur.com/a/0PfTe

Body:
Update:

You can't use this kind of Page component inheritance with Ionic2 and Typescript now.Hope you can do that with Ionic3 and latest Typescript which will be included with Ionic3.This issue is related to the Typescript and web pack.

You can get more info here.

You too can see the issue here if you explore the main.js.map file.It creates a subclass(Page1) first and after that base class (AbstractPage).That is the reason for this error.But unfortunately, we cannot change the order.

Old Answer:

You can try with public constructor() on the abstract class as shown below.

 export abstract class AbstractPage {

  constructor(public page_number: number,public has_sharable_content: boolean) {

    }

  changePage(direction: number) {
    if (direction==1){
      console.log(direction,this.page_number);
      this.navCtrl.setRoot(AbstractPage.pages[this.page_number], {}, {animate: true, direction: 'forward'});
    }
    else if(direction == 2){
      this.navCtrl.push(Contact);
    }
    else{
      this.navCtrl.setRoot(AbstractPage.pages[this.page_number-1], {}, {animate: true, direction: 'back'});
    }
  }
}


问:
Does click lib provide a way to print the builtin help message?
I am using the click lib.

In my code , sometimes I want to print help msg ,
But the only way I know is :

```<code>python xxx --help
</code>```

But I want to print the help msg in my code using a certain function , for example:

```<code>click.print_help_msg()
</code>```

Is there a function like this ?

答:
You can use click.echo something like this :

```<code>click.echo('FooBar')
</code>```

echo also supports color codes and filtering based on type such as :

```<code>click.echo('FooBar', err=True)
</code>```

You can refer to the documentation for more understanding.

ContentLicense: CC BY-SA 4.0

Body:
I am using the click lib.

In my code , sometimes I want to print help msg ,
But the only way I know is :

python xxx --help

But I want to print the help msg in my code using a certain function , for example:

click.print_help_msg()

Is there a function like this ?

Body:
You can use click.echo something like this :

click.echo('FooBar')

echo also supports color codes and filtering based on type such as :

click.echo('FooBar', err=True)

You can refer to the documentation for more understanding.


问:
how to make json work in a jsp page using tomcat server?
I have downloaded json library , and my jsp pages are in tomcat/webapps/star/index.jsp .

So where should I extract the json libraries so that the json code contained in index.jsp works ?

答:
As usual, 3rd party libraries in JAR flavor should go in Webapp/WEB-INF/lib folder. This folder is taken in the webapp's default runtime classpath. If you'd like to share the same libs among multiple webapplications on the same server, then rather drop it in Tomcat/lib folder.

By the way, such JSON libraries only converts Java objects to JSON strings and vice versa. They have completely nothing to do with JSON in the JSP side. It's JavaScript who's responsible for that part.


问:
evaluate symbolic expression over meshgrind in python
I would like to evaluate a symbolic expression over a meshgrid. My testcode is the following:

```<code>import sympy as sym
import numpy as np

x,y = sym.symbols('x,y')
test = sym.gamma(x)/sym.sqrt(y)

X = np.linspace( start = 1, stop = 2)
Y = np.linspace( start = 4, stop = 7)

X, Y = np.meshgrid(X, Y)

Z = test.evalf(subs = {x : X, y: Y})
</code>```

It seems that python tries to create an object with many many dimensions, which is totally not what I have in mind. Is there a way to do this without loops over the function arguments?

Best

答:
As you are interested in numerical evaluations, use of sympy does not offer you any advantage compared to numpy/scipy whose functions can also be applied to all elements of an ndarray via a single call.

```<code>from scipy.special import gamma
from numpy import sqrt

test = lambda x, y: gamma(x)/sqrt(y)

Z = text(X, Y)
</code>```

Body:
I would like to evaluate a symbolic expression over a meshgrid. My testcode is the following:

import sympy as sym
import numpy as np

x,y = sym.symbols('x,y')
test = sym.gamma(x)/sym.sqrt(y)

X = np.linspace( start = 1, stop = 2)
Y = np.linspace( start = 4, stop = 7)

X, Y = np.meshgrid(X, Y)

Z = test.evalf(subs = {x : X, y: Y})

It seems that python tries to create an object with many many dimensions, which is totally not what I have in mind. Is there a way to do this without loops over the function arguments?

Best

Body:
As you are interested in numerical evaluations, use of sympy does not offer you any advantage compared to numpy/scipy whose functions can also be applied to all elements of an ndarray via a single call.

from scipy.special import gamma
from numpy import sqrt

test = lambda x, y: gamma(x)/sqrt(y)

Z = text(X, Y)


问:
Prolog why the following term doesn't unify?
In prolog = is used for unification, as far as I understand if the two terms can be matched maybe with the help if variable instantiation, they are unified.

So why the following query fails

```<code>?- 2+2 = 4.
</code>```

Although 2+2 yields into 4 which is the same number as the other term.

答:
Complementing the other posts, I would like to suggest (#=)/2 as a more declarative alternative to (is)/2 when reasoning about integers.

(#=)/2 denotes arithmetic equality of integer expressions. This involves an evaluation step and is therefore different from just syntactic equality. In your case, you expected the former, but got the latter.

Usage example, with GNU Prolog:

```
| ?- 4 <b>#=</b> 2+2.

yes
```

The primary advantage of (#=)/2 is that it works in all directions:

```
| ?- 4 #= 2+<b>X</b>.

<b>X = 2</b>
```

In contrast, we get with (is)/2:

```
| ?- 4 is 2+X.
<b>uncaught exception: error(instantiation_error,(is)/2)</b>
```

Such problems are very common (see instantiation-error) when beginners first learn about arithmetic, and so I recommend you start using more declarative predicates at least in the beginning.

Body:
In prolog = is used for unification, as far as I understand if the two terms can be matched maybe with the help if variable instantiation, they are unified.

So why the following query fails

?- 2+2 = 4.

Although 2+2 yields into 4 which is the same number as the other term.

Body:
Complementing the other posts, I would like to suggest (#=)/2 as a more declarative alternative to (is)/2 when reasoning about integers.

(#=)/2 denotes arithmetic equality of integer expressions. This involves an evaluation step and is therefore different from just syntactic equality. In your case, you expected the former, but got the latter.

Usage example, with GNU Prolog:

| ?- 4 #= 2+2.

yes

The primary advantage of (#=)/2 is that it works in all directions:

| ?- 4 #= 2+X.

X = 2

In contrast, we get with (is)/2:

| ?- 4 is 2+X.
uncaught exception: error(instantiation_error,(is)/2)

Such problems are very common (see instantiation-error) when beginners first learn about arithmetic, and so I recommend you start using more declarative predicates at least in the beginning.


问:
JavaScript transfering one element to another (multiple times) by using event
I want to transfer multiple times after click on "przenieś" the whole li from one div class="listContainer two" to another, and back again (and again) using JavaScript. How should I prepare the JavaScript code for the most efficient way?

Item 1 z listy 1 Przenieś

Item 2 z listy 1 Przenieś

Item 1 z listy 2 Przenieś

Item 2 z listy 2 Przenieś

```

答:
you can try this code

<button id="append">click</button>

Item 1 z listy 1 Przenieś

Item 2 z listy 1 Przenieś

```

Body:
you can try this code

<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
<button id="append">click</button>
<div class="list">
  <div class="listContainer two">
    <ul id="list1">
      <li>Item 1 z listy 1 <a class="moveBtn">Przenieś</a></li>
      <li>Item 2 z listy 1 <a class="moveBtn">Przenieś</a></li>
   </ul>
  </div>
</div>

<script>
$('#append').click(function(){
  $html = $('.list > .listContainer').html();
  $('.list').append($html);
});
</script>


问:
How can I allow a private insecure registry to be used inside a minikube node?
I know there are about a thousand answers to various permutations of this question but none of the fifteen or so that I've tried have worked.

I'm running on Mac OS Sierra and using Minikube 0.17.1 as well as kubectl 1.5.3.

We run our own private Docker registry that is insecure as it is not open to the internet. (This is not my choice or in my control so it's not open for discussion). This is my first foray into Kubernetes and actually container orchestration altogether. I also have a very intermediate level of knowledge about Docker in general so I'm drowning in terminology/platform soup here.

When I execute

```<code>kubectl run perf-ui --image=X.X.X.X/performance/perf-ui:master
</code>```

I see

image pull failed for X.X.X.X/performance/perf-ui:master, this may be because there are no credentials on this request.  details: (Error response from daemon: Get https://X.X.X.X/v1/_ping: dial tcp X.X.X.X:443: getsockopt: connection refused)

We have an Ubuntu box that accesses the same registry (not using Kubernetes, just Docker) that works just fine. This is likely due to

DOCKER_OPTS="--insecure-registry X.X.X.X"

being in /etc/default/docker.

I made a similar change using the UI of Docker for Mac. I don't know where this change persisted in a config file. After this change a docker pull worked on my laptop!!! Again, this is just using Docker not Kubernetes. The interesting part is I got the same "Connection refused error" (as it tries to access via HTTPS) on my Mac as I get in the Minikube VM and after the change the pull worked. I feel like I'm on to something there.

After sshing into minikube (the VM created my minikube start) using

```<code>minikube ssh
</code>```

I added the following content to /var/lib/boot2docker/profile

```<code>export EXTRA_ARGS="$EXTRA_ARGS --insecure-registry 10.129.100.3
export DOCKER_OPTS="$DOCKER_OPTS --insecure-registry 10.129.100.3
</code>```

As you can infer, nothing has worked. I know I've tried other things but they too have failed.

I know this isn't the most comprehensive explanation but I've been digging into this for the past 4 hours.

The bottom line is docker pulls work from our Ubuntu box with the config file setup correctly and from my Mac with the setting configured properly.

How can I enable the same setting in my "Linux 2.6" VM that was created by Minikube?

If someone knows the answer I would be forever grateful.

Thank you in advance!

答:
You can use kube-registry-proxy from (needs some configuration):
https://github.com/kubernetes/kubernetes/blob/master/cluster/saltbase/salt/kube-registry-proxy/kube-registry-proxy.yaml

Then you can refer to localhost:5050 as your registry. The trick is that localhost is allowed as an insecure registry by default.

Body:
I know there are about a thousand answers to various permutations of this question but none of the fifteen or so that I've tried have worked.

I'm running on Mac OS Sierra and using Minikube 0.17.1 as well as kubectl 1.5.3.

We run our own private Docker registry that is insecure as it is not open to the internet. (This is not my choice or in my control so it's not open for discussion). This is my first foray into Kubernetes and actually container orchestration altogether. I also have a very intermediate level of knowledge about Docker in general so I'm drowning in terminology/platform soup here.

When I execute

kubectl run perf-ui --image=X.X.X.X/performance/perf-ui:master

I see

image pull failed for X.X.X.X/performance/perf-ui:master, this may be because there are no credentials on this request.  details: (Error response from daemon: Get https://X.X.X.X/v1/_ping: dial tcp X.X.X.X:443: getsockopt: connection refused)

We have an Ubuntu box that accesses the same registry (not using Kubernetes, just Docker) that works just fine. This is likely due to

DOCKER_OPTS="--insecure-registry X.X.X.X"

being in /etc/default/docker.

I made a similar change using the UI of Docker for Mac. I don't know where this change persisted in a config file. After this change a docker pull worked on my laptop!!! Again, this is just using Docker not Kubernetes. The interesting part is I got the same "Connection refused error" (as it tries to access via HTTPS) on my Mac as I get in the Minikube VM and after the change the pull worked. I feel like I'm on to something there.

After sshing into minikube (the VM created my minikube start) using

minikube ssh

I added the following content to /var/lib/boot2docker/profile

export EXTRA_ARGS="$EXTRA_ARGS --insecure-registry 10.129.100.3
export DOCKER_OPTS="$DOCKER_OPTS --insecure-registry 10.129.100.3

As you can infer, nothing has worked. I know I've tried other things but they too have failed.

I know this isn't the most comprehensive explanation but I've been digging into this for the past 4 hours.

The bottom line is docker pulls work from our Ubuntu box with the config file setup correctly and from my Mac with the setting configured properly.

How can I enable the same setting in my "Linux 2.6" VM that was created by Minikube?

If someone knows the answer I would be forever grateful.

Thank you in advance!


问:
how to limit file size when it's working?
I have a problem.
I need convert multicast source using opencaster.
I receive multicast and write to file input.ts, then i send input.ts to other multicast:
tsudpreceive 239.1.1.1 50000 > input.ts &
tsudpsend input.ts 224.5.5.5 5000 3000000 &
but input.ts size have grown.
I have no idea to stop it.
Please help me!

答: Instead of making input.ts an ordinary file, create it by using "mkfifo input.ts"</p>


问:
passing search query from main activity to fragment
I am building an android app for gif search using GIPHYAPI, which contains multiple fragments and a search menu. whenever I am trying to pass query it gives error like "Attempt to read from null array".

Following is my mainactivity.java

```<code>public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener, TabLayout.OnTabSelectedListener{

private TabLayout tabLayout;
private GifAdapter adapter;
private ViewPager viewPager;
private Fragment[] mFragments;

@Override
public void onTabSelected(TabLayout.Tab tab) {
    viewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(TabLayout.Tab tab) {

}

@Override
public void onTabReselected(TabLayout.Tab tab) {

}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    tabLayout = (TabLayout) findViewById(R.id.tabLayout);

    tabLayout.addTab(tabLayout.newTab().setText("Trending"));
    tabLayout.addTab(tabLayout.newTab().setText("Funny"));
    tabLayout.addTab(tabLayout.newTab().setText("Happy"));
    tabLayout.addTab(tabLayout.newTab().setText("Sad"));
    tabLayout.addTab(tabLayout.newTab().setText("Minion"));
    tabLayout.addTab(tabLayout.newTab().setText("Awesome"));
    tabLayout.addTab(tabLayout.newTab().setText("Search"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    viewPager = (ViewPager) findViewById(R.id.pager);

    Pager adapter = new Pager(getSupportFragmentManager(), tabLayout.getTabCount());

    viewPager.setAdapter(adapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.setOnTabSelectedListener(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_items,menu);
    MenuItem menuItem = menu.findItem(R.id.action_search);
    SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
    searchView.setOnSearchClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            viewPager.setCurrentItem(6); //Switch to SearchView
        }
    });
    searchView.setOnQueryTextListener(this);
    return true;
}

@Override
public boolean onQueryTextSubmit(String query) {
    viewPager.setCurrentItem(6);
    return ((Searchable) mFragments[6]).performSearch(query);
}

@Override
public boolean onQueryTextChange(String newText) {
    return false;
}
}
</code>```

Following is my FragActivitySearch.java

```<code>public class FragActivitySearch extends Fragment implements Searchable {
private RecyclerView recyclerView;
private GifAdapter adapter;
protected ViewPager mViewPager;
private Fragment[] mFragments;

private String Query;
@Override
public boolean performSearch(String query) {
    Query = query;
    new GiphyTask(Helper.getGiphyQueryUrl(Query,
            100, GiphyQueryBuilder.EndPoint.SEARCH, ""), new GiphyTask.Callback() {
        @Override
        public void onResponse(List<Gif> gifs) {
            adapter.setGifs(gifs);
        }
    }).execute();

    return true;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    View rootView = inflater.inflate(R.layout.activity_search, container, false);
    recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
    recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 1));

    adapter = new GifAdapter(getActivity(), new ArrayList<Gif>());
    recyclerView.setAdapter(adapter);

    recyclerView.setRecyclerListener(new RecyclerView.RecyclerListener() {
        @Override
        public void onViewRecycled(RecyclerView.ViewHolder holder) {
            GifAdapter.GifViewHolder gifHolder = (GifAdapter.GifViewHolder) holder;
            gifHolder.stopPlayback();
        }
    });

    return rootView;
}

}
</code>```

whenever I try to run this code it gives me following runtime error.

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.share.gifimage, PID: 8275
              java.lang.NullPointerException: Attempt to read from null array
                  at com.share.gifimage.MainActivity.onQueryTextSubmit(MainActivity.java:91)
                  at android.support.v7.widget.SearchView.onSubmitQuery(SearchView.java:1242)
                  at android.support.v7.widget.SearchView$9.onEditorAction(SearchView.java:1219)
                  at android.widget.TextView.onEditorAction(TextView.java:4902)
                  at com.android.internal.widget.EditableInputConnection.performEditorAction(EditableInputConnection.java:138)
                  at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:364)
                  at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:91)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6077)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
</code>```

I just want to pass the query and load appropriate results.

答:
You never iitialized your mFragments array, and it seems null.

And this line,

```<code>((Searchable) mFragments[6]).performSearch(query);
</code>```

you are trying to reach 6th element of null array.

Also your error log says the same thing:

```<code>java.lang.NullPointerException: Attempt to read from null array
</code>```

You must initialize your array and add your fragments to this array.

Body:
I am building an android app for gif search using GIPHYAPI, which contains multiple fragments and a search menu. whenever I am trying to pass query it gives error like "Attempt to read from null array".

Following is my mainactivity.java

public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener, TabLayout.OnTabSelectedListener{

private TabLayout tabLayout;
private GifAdapter adapter;
private ViewPager viewPager;
private Fragment[] mFragments;

@Override
public void onTabSelected(TabLayout.Tab tab) {
    viewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(TabLayout.Tab tab) {

}

@Override
public void onTabReselected(TabLayout.Tab tab) {

}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    tabLayout = (TabLayout) findViewById(R.id.tabLayout);

    tabLayout.addTab(tabLayout.newTab().setText("Trending"));
    tabLayout.addTab(tabLayout.newTab().setText("Funny"));
    tabLayout.addTab(tabLayout.newTab().setText("Happy"));
    tabLayout.addTab(tabLayout.newTab().setText("Sad"));
    tabLayout.addTab(tabLayout.newTab().setText("Minion"));
    tabLayout.addTab(tabLayout.newTab().setText("Awesome"));
    tabLayout.addTab(tabLayout.newTab().setText("Search"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    viewPager = (ViewPager) findViewById(R.id.pager);

    Pager adapter = new Pager(getSupportFragmentManager(), tabLayout.getTabCount());

    viewPager.setAdapter(adapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.setOnTabSelectedListener(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_items,menu);
    MenuItem menuItem = menu.findItem(R.id.action_search);
    SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
    searchView.setOnSearchClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            viewPager.setCurrentItem(6); //Switch to SearchView
        }
    });
    searchView.setOnQueryTextListener(this);
    return true;
}

@Override
public boolean onQueryTextSubmit(String query) {
    viewPager.setCurrentItem(6);
    return ((Searchable) mFragments[6]).performSearch(query);
}

@Override
public boolean onQueryTextChange(String newText) {
    return false;
}
}

Following is my FragActivitySearch.java

public class FragActivitySearch extends Fragment implements Searchable {
private RecyclerView recyclerView;
private GifAdapter adapter;
protected ViewPager mViewPager;
private Fragment[] mFragments;

private String Query;
@Override
public boolean performSearch(String query) {
    Query = query;
    new GiphyTask(Helper.getGiphyQueryUrl(Query,
            100, GiphyQueryBuilder.EndPoint.SEARCH, ""), new GiphyTask.Callback() {
        @Override
        public void onResponse(List<Gif> gifs) {
            adapter.setGifs(gifs);
        }
    }).execute();

    return true;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    View rootView = inflater.inflate(R.layout.activity_search, container, false);
    recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
    recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 1));

    adapter = new GifAdapter(getActivity(), new ArrayList<Gif>());
    recyclerView.setAdapter(adapter);

    recyclerView.setRecyclerListener(new RecyclerView.RecyclerListener() {
        @Override
        public void onViewRecycled(RecyclerView.ViewHolder holder) {
            GifAdapter.GifViewHolder gifHolder = (GifAdapter.GifViewHolder) holder;
            gifHolder.stopPlayback();
        }
    });

    return rootView;
}

}

whenever I try to run this code it gives me following runtime error.

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.share.gifimage, PID: 8275
              java.lang.NullPointerException: Attempt to read from null array
                  at com.share.gifimage.MainActivity.onQueryTextSubmit(MainActivity.java:91)
                  at android.support.v7.widget.SearchView.onSubmitQuery(SearchView.java:1242)
                  at android.support.v7.widget.SearchView$9.onEditorAction(SearchView.java:1219)
                  at android.widget.TextView.onEditorAction(TextView.java:4902)
                  at com.android.internal.widget.EditableInputConnection.performEditorAction(EditableInputConnection.java:138)
                  at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:364)
                  at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:91)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6077)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

I just want to pass the query and load appropriate results.

Body:
You never iitialized your mFragments array, and it seems null.

And this line,

((Searchable) mFragments[6]).performSearch(query);

you are trying to reach 6th element of null array.

Also your error log says the same thing:

java.lang.NullPointerException: Attempt to read from null array

You must initialize your array and add your fragments to this array.


问:
How could I implement a serial communication protocol in a object-oriented form?
I’m working on with an embedded device that is connected to PC using RS232.

I need to do a software to communicate with this embedded device.

I program in Delphi. I never used to use object-oriented in the past. But I'm trying to change this.

I am not able to think in an object oriented manner to solve this problem.

I have this protocol:

```<code><STX><STX><COMMAND>[<DATA><DATA>...]<CHKSUM><ETX>
</code>```

where:

```<code><STX> is the Start of TeXt (0x55);
<COMMAND> can be 0x01 for read, 0x02 for write, etc;
<DATA> is any value;
<CHKSUM> is the checksum;
<ETX> is the End of TeXt (0x04).
</code>```

The software computer will send a command via serial, and the device will answer, using the same protocol.

For example:

```<code>Reset command
PC sends     : <STX><STX><0x09><0x00><CHKSUM><ETX>
Device answer: <STX><STX><0x09><0x00><CHKSUM><ETX>

Get Version
PC sends     : <STX><STX><0x00><0x02><CHKSUM><ETX>
Device answer: <STX><STX><0x00><0x00><VER_L><VER_H><CHKSUM><ETX>
</code>```

I have to send a file stream to the device.

I'd like to obtain suggestions and/or examples of the best way to implement this in an object oriented manner. I'd like to be able to do unit-test too.

Thanks

答:
Sort of hard to answer but from the small amount of info I have, here's how I'd do it:

Either you class that knows how to serialize themself or you use the visitor pattern for serializing. This has the advantage of decoupling your data from the serialization and let you implement other serialization mechanism more easily.

So I'd have a Data class, a Command class which contains a collection(choose your preferred container) of Data. The Command class would likely handle the checksum calculation through a public method. I would also have a communication class to encapsulate the Command and begin and end the communication. Then I'd have a class responsible for interfacing with the serial port which would have a Send method that would take a reference on the communication class.

From the available info, that's what I can come up with design-wise.

As for unit test, with a good design, you should be able to unit test almost everything. Remember to use stubs, you don't want to hit that serial port during testing so make a fake serial communication class that writes in a string for example and compare the outputted string to the expected value specification wise.

Body:
I’m working on with an embedded device that is connected to PC using RS232.

I need to do a software to communicate with this embedded device.

I program in Delphi. I never used to use object-oriented in the past. But I'm trying to change this.

I am not able to think in an object oriented manner to solve this problem.

I have this protocol:

<STX><STX><COMMAND>[<DATA><DATA>...]<CHKSUM><ETX>

where:

<STX> is the Start of TeXt (0x55);
<COMMAND> can be 0x01 for read, 0x02 for write, etc;
<DATA> is any value;
<CHKSUM> is the checksum;
<ETX> is the End of TeXt (0x04).

The software computer will send a command via serial, and the device will answer, using the same protocol.

For example:

Reset command
PC sends     : <STX><STX><0x09><0x00><CHKSUM><ETX>
Device answer: <STX><STX><0x09><0x00><CHKSUM><ETX>

Get Version
PC sends     : <STX><STX><0x00><0x02><CHKSUM><ETX>
Device answer: <STX><STX><0x00><0x00><VER_L><VER_H><CHKSUM><ETX>

I have to send a file stream to the device.

I'd like to obtain suggestions and/or examples of the best way to implement this in an object oriented manner. I'd like to be able to do unit-test too.

Thanks


问:
Validation message color ASP.NET MVC 4
I am using ASP.NET MVC 4 Razor.

I want to change the validation color message to Red. It's not working even if I change the CSS file.

My CSS file:

```<code>.field-validation-error {
  color: #E80C4D;
  font-weight: bold;
}

.field-validation-valid {
  display: none;
}

input.input-validation-error {
  border: 1px solid #E80C4D;
}

input[type="checkbox"].input-validation-error {
  border: 0 none;
}

.validation-summary-errors {
  color: #E80C4D;
  font-weight: bold;
  font-size: 1.1em;
}

.validation-summary-valid {
  display: none;
}
</code>```

A part of my view:

```<code><td>@Html.LabelFor(model => model.nom_candidat)</td>

<td>
    @Html.TextBoxFor(model => model.nom_candidat)
    @Html.ValidationMessageFor(Model => Model.nom_candidat)
</td>
</code>```

答:
You can use this piece of code to change the validation colour:</p>
```<code>@Html.ValidationMessageFor(m=>m.FirstName, "", new{@class="text-danger"})
</code>```

Title: Validation message color ASP.NET MVC 4

Body:
I am using ASP.NET MVC 4 Razor.

I want to change the validation color message to Red. It's not working even if I change the CSS file.

My CSS file:

.field-validation-error {
  color: #E80C4D;
  font-weight: bold;
}

.field-validation-valid {
  display: none;
}

input.input-validation-error {
  border: 1px solid #E80C4D;
}

input[type="checkbox"].input-validation-error {
  border: 0 none;
}

.validation-summary-errors {
  color: #E80C4D;
  font-weight: bold;
  font-size: 1.1em;
}

.validation-summary-valid {
  display: none;
}

A part of my view:

@Html.LabelFor(model => model.nom_candidat)

    @Html.TextBoxFor(model => model.nom_candidat)
    @Html.ValidationMessageFor(Model => Model.nom_candidat)

Body:
You can use this piece of code to change the validation colour:

@Html.ValidationMessageFor(m=>m.FirstName, "", new{@class="text-danger"})


问:
GoogleWebAuthorizationBroker.AuthorizeAsync() hangs if browser closed
I'm writing a C# desktop app that can copy its output to a users Google Drive. However when I try an authorise access to Google with GoogleWebAuthorizationBroker.AuthorizeAsync() if the user closes the authentication page in the browser the method never returns!

Even if I use a 30 sec cancellation token it never returns if the browser is closed.

```<code>public bool Authorise()
{
    _authorised = false;
    UserCredential credential = null;
    try
    {
        // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
        CancellationTokenSource cts = new CancellationTokenSource(new TimeSpan(0,0,30));
        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = this.ClientId, ClientSecret = this.ClientSecret },
                                                                 Scopes,
                                                                 UserName,
                                                                 cts.Token,//CancellationToken.None,
                                                                 new FileDataStore(AppName)).Result;
    }
    catch (Exception)
    {
        return _authorised;
    }

    if ((credential != null) && (credential.Token.AccessToken != null))
    {

        Service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = AppName, });
        _authorised = true;
    }

    return _authorised;
}
</code>```

How can I trap the user closing the browser window and stop my application hanging?

答:
It is not possible, in general, to detect when the user has closed the browser window/tab.
For example, if the user is already running their default browser, then GoogleWebAuthorizationBroker opens a new tab, this is not running in the process started in LocalServerCodeReceiver. That new process terminates immediately.

However, currently the CancellationToken passed to GoogleWebAuthorizationBroker.AuthorizeAsync is not honoured whilst waiting for the auth response, meaning even trying to use a simple timeout doesn't work. #968 filed to fix this.

Body:
I'm writing a C# desktop app that can copy its output to a users Google Drive. However when I try an authorise access to Google with GoogleWebAuthorizationBroker.AuthorizeAsync() if the user closes the authentication page in the browser the method never returns!

Even if I use a 30 sec cancellation token it never returns if the browser is closed.

public bool Authorise()
{
    _authorised = false;
    UserCredential credential = null;
    try
    {
        // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
        CancellationTokenSource cts = new CancellationTokenSource(new TimeSpan(0,0,30));
        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = this.ClientId, ClientSecret = this.ClientSecret },
                                                                 Scopes,
                                                                 UserName,
                                                                 cts.Token,//CancellationToken.None,
                                                                 new FileDataStore(AppName)).Result;
    }
    catch (Exception)
    {
        return _authorised;
    }

    if ((credential != null) && (credential.Token.AccessToken != null))
    {

        Service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = AppName, });
        _authorised = true;
    }

    return _authorised;
}

How can I trap the user closing the browser window and stop my application hanging?


问:
Show List value in DataGridView
I have a List and a DataGridView. I added elements to the List, but when I tried to show that List value in the DataGridView, it's not shown.

```<code>public partial class Queries : Form {
    List<EmployeeDetails> lst = new List<EmployeeDetails> { };

    public Queries() {
        InitializeComponent();
    }

    public void btnSubmit_Click(object sender, EventArgs e) {
        EmployeeDetails emp = new EmployeeDetails();
        emp.id = Convert.ToInt32(numId.Value);
        emp.name = tbName.Text;
        emp.malecheck = rbMale.Checked;
        emp.femealecheck = rbFemale.Checked;
        lst.Add(emp);
    }

    private void btnDataGridView_Click(object sender, EventArgs e) {
        LinqdataGridView.DataSource = lst;
    }
}
</code>```

答:
You can use BindingSource, try this;

```<code>private void btnDataGridView_Click(object sender, EventArgs e){
    var source = new BindingSource();
    source.Datasource = lst;
    LinqdataGridView.DataSource = source;
}
</code>```

Hope helps,

Title: Show List value in DataGridView

Body:
I have a List and a DataGridView. I added elements to the List, but when I tried to show that List value in the DataGridView, it's not shown.

public partial class Queries : Form {
    List<EmployeeDetails> lst = new List<EmployeeDetails> { };

    public Queries() {
        InitializeComponent();
    }

    public void btnSubmit_Click(object sender, EventArgs e) {
        EmployeeDetails emp = new EmployeeDetails();
        emp.id = Convert.ToInt32(numId.Value);
        emp.name = tbName.Text;
        emp.malecheck = rbMale.Checked;
        emp.femealecheck = rbFemale.Checked;
        lst.Add(emp);
    }

    private void btnDataGridView_Click(object sender, EventArgs e) {
        LinqdataGridView.DataSource = lst;
    }
}

Body:
You can use BindingSource, try this;

private void btnDataGridView_Click(object sender, EventArgs e){
    var source = new BindingSource();
    source.Datasource = lst;
    LinqdataGridView.DataSource = source;
}

Hope helps,


问:
WPF XAML StringFormat assign amount of decimal places through binding
I have the need to give the user the ability to set their own Decimal Formating option in XAML.

I know how to set StringFormat into Binding, but I only know how to do it manually. How can I Bind the String Format value inside a binding.

答:
How can I Bind the String Format value inside a binding.

You cannot because StringFormat is not a dependency property.

But you could use a multi binding that binds to two properties, the actual source property and the format source property, and an IMultiValueConverter class:

WPF Binding and Dynamically Assigning StringFormat Property

WPF: MultiBinding and IMultiValueConverter: https://blog.csainty.com/2009/12/wpf-multibinding-and.html