问:
Get current position in stream from net/html tokenizer
I'm trying to figure out if there's a way to get the current character position of a tag using the golang.org/x/net/html tokenizer library?

Simplified code looks like:

```<code>func LookForForm(body string) {
    reader := strings.NewReader(body)
    tokenizer := html.NewTokenizer(reader)
    idx := 0
    lastIdx := 0
    for {
        token := tokenizer.Next()
        lastIdx = idx
        idx = int(reader.Size()) - int(reader.Len())
        switch token {
        case html.ErrorToken:
            return
        case html.StartTagToken:
            t := tokenizer.Token()
            tagName := strings.ToLower(t.Data)
            if tagName == "form" {
                fmt.Printf("found at form at %d\n", lastIdx)
                return
            }
        }
    }
}
</code>```

This doesn't work (I think) because reader is not reading character-by-character but by chunks so my calculation of Size - Len is invalid.  tokenizer maintains two private span structs ( https://github.com/golang/net/blob/master/html/token.go line 147) but I am unaware of how to access them.

One possible solution that just occurred to me is to make a "reader" that only reads a single character at a time so my Size and Len calculations are always correct. But, that seems like a hack and any suggestions would be appreciated.

答:
You might be able to accomplish what you are trying to do (not what you want) with careful arithmetic using Tokenizer's  Buffered method which returns the slice of bytes currently in buffer that have yet been tokenized. But I don't think you will get what you wanted, as
<form></form>
 would probably buffer the whole string before give you the first div token. In that case the size of the buffered content is not helpful in calculating the solution.

Tokenizing mark up lang with nested structure will almost always need to buffer the input to work. the private span attribute should be quite useless as it is only a reference in it's buffer, not absolute position from the reader.

Since the html Tokenizer is not providing an API to access the raw position of a tag in the original data, to get want you wanted I probably would just do a strings.Index or bytes.Index on the raw buffer of the token to get the position:

```<code>strings.Index(body, string(tokenizer.Raw()))
</code>```

Body:
I'm trying to figure out if there's a way to get the current character position of a tag using the golang.org/x/net/html tokenizer library?

Simplified code looks like:

func LookForForm(body string) {
    reader := strings.NewReader(body)
    tokenizer := html.NewTokenizer(reader)
    idx := 0
    lastIdx := 0
    for {
        token := tokenizer.Next()
        lastIdx = idx
        idx = int(reader.Size()) - int(reader.Len())
        switch token {
        case html.ErrorToken:
            return
        case html.StartTagToken:
            t := tokenizer.Token()
            tagName := strings.ToLower(t.Data)
            if tagName == "form" {
                fmt.Printf("found at form at %d\n", lastIdx)
                return
            }
        }
    }
}

This doesn't work (I think) because reader is not reading character-by-character but by chunks so my calculation of Size - Len is invalid.  tokenizer maintains two private span structs ( https://github.com/golang/net/blob/master/html/token.go line 147) but I am unaware of how to access them.

One possible solution that just occurred to me is to make a "reader" that only reads a single character at a time so my Size and Len calculations are always correct. But, that seems like a hack and any suggestions would be appreciated.

Body:
You might be able to accomplish what you are trying to do (not what you want) with careful arithmetic using Tokenizer's  Buffered method which returns the slice of bytes currently in buffer that have yet been tokenized. But I don't think you will get what you wanted, as <div><form></form></div> would probably buffer the whole string before give you the first div token. In that case the size of the buffered content is not helpful in calculating the solution.

Tokenizing mark up lang with nested structure will almost always need to buffer the input to work. the private span attribute should be quite useless as it is only a reference in it's buffer, not absolute position from the reader.

Since the html Tokenizer is not providing an API to access the raw position of a tag in the original data, to get want you wanted I probably would just do a strings.Index or bytes.Index on the raw buffer of the token to get the position:

strings.Index(body, string(tokenizer.Raw()))


来源: stackexchange

问:
Get the value of checkbox in wpf
Below is the xaml code I'm using. I'm trying to get the checkbox value in code-behind.

```<code><ListBox ItemsSource="{Binding AvailablePresentationObjects}" >
  <ListBox>
    <CheckBox Content="Puma" IsChecked="{Binding IsChecked}"/>
    <CheckBox Content="NIke" IsChecked="{Binding IsChecked}"/>
    <CheckBox Content="Adidas" IsChecked="{Binding IsChecked}"/>
    <CheckBox Content="reebok" IsChecked="{Binding IsChecked}"/>
  </ListBox>
</ListBox>
<Button x:Name="btnLaunchCache" HorizontalAlignment="Right"
        IsEnabled="{Binding Path=IsButtonEnabled,Mode=TwoWay}"
        Click="BtnLaunchCache_Click">
<TextBlock>Submit</TextBlock>
</code>```

答:
You can add an "x:Name" property to your checkboxes:

```<code>   <CheckBox x:Name="chkPuma" Content="Puma" IsChecked="{Binding IsChecked}"/>
</code>```

Then you can access "chkPuma.IsChecked" in the code behind.

ContentLicense: CC BY-SA 3.0

Title: Get the value of checkbox in wpf

Body:
Below is the xaml code I'm using. I'm trying to get the checkbox value in code-behind.

<ListBox ItemsSource="{Binding AvailablePresentationObjects}" >
  <ListBox>
    <CheckBox Content="Puma" IsChecked="{Binding IsChecked}"/>
    <CheckBox Content="NIke" IsChecked="{Binding IsChecked}"/>
    <CheckBox Content="Adidas" IsChecked="{Binding IsChecked}"/>
    <CheckBox Content="reebok" IsChecked="{Binding IsChecked}"/>
  </ListBox>
</ListBox>
<Button x:Name="btnLaunchCache" HorizontalAlignment="Right"
        IsEnabled="{Binding Path=IsButtonEnabled,Mode=TwoWay}"
        Click="BtnLaunchCache_Click">
<TextBlock>Submit</TextBlock>

Body:
You can add an "x:Name" property to your checkboxes:

   <CheckBox x:Name="chkPuma" Content="Puma" IsChecked="{Binding IsChecked}"/>

Then you can access "chkPuma.IsChecked" in the code behind.


问:
Ionic2 navController properties not working as expected
I am trying to build an app, which has the following work flow.

LoginPage

HomePage

Create Request page -> Present in HomePage and menu

Request Success page -> when request creation is success

Request List page -> Present in HomePage and menu

Request detail page -> on click of request item

From login page when user have given then correct credentials i am calling a service.If it is success,i am making Homepage as the root of nav controller.

```<code>if(getLoginDetails.status == "success")
{
this.navCtrl.setRoot(HomePage);
}
</code>```

but still when i used this.navCtrl.length() in HomePage constructor,its show 2.How can this happen,when i just replaced root element of navigation stack from LoginPage with homepage.As per my understanding,the count should come as 1.
Also except login each page has swipeEnabled = true menu and a back button.
Now suppose user go to HomePage and then createRequestPage and then used menu to go to requestListPage,now i need that when user click back button it should take user to homePage.For this my approach is that when user click through menu,i will remove all pages in navigation stack except the first one that is our root-Homepage.
I tried with this way but its not working-

```<code>this.navCtrl.remove(1,this.navCtrl.length(),{}).then(
()=>{
      this.navCtrl.push(RequestListPage)
});
</code>```

But this does not seems to work.
Can somebody help me with this.
Also some better docs for NavController of ionic2.

答:
if you put navCtrl in the provider that is the way:

In provider import

```<code>import { NavController, App } from 'ionic-angular';
</code>```

in export class init

```<code>private navCtrl: NavController;
</code>```

in constructor

```<code>constructor(private app:App) {

   this.navCtrl = app.getActiveNav();

}
</code>```

Define a function go to home page:

```<code>goToHomePage() {

    this.navCtrl.setRoot(HomePage);

}
</code>```

Now can call this.navCtrl in any page you like

```<code>import { YourProvider } from "../../your-provider";

@Component({

    selector: 'page',

    templateUrl: 'page.html',

    providers: [YourProvider]

})

export class YourPage{

  constructor(private yourProvider : YourProvider) {

}

goToHome() {
    this.yourProvider.goToHomePage();
}
</code>```

now you can use navCtrl

Goodluck

Body:
I am trying to build an app, which has the following work flow.

LoginPage

HomePage

Create Request page -> Present in HomePage and menu

Request Success page -> when request creation is success

Request List page -> Present in HomePage and menu

Request detail page -> on click of request item

From login page when user have given then correct credentials i am calling a service.If it is success,i am making Homepage as the root of nav controller.

if(getLoginDetails.status == "success")
{
this.navCtrl.setRoot(HomePage);
}

but still when i used this.navCtrl.length() in HomePage constructor,its show 2.How can this happen,when i just replaced root element of navigation stack from LoginPage with homepage.As per my understanding,the count should come as 1.
Also except login each page has swipeEnabled = true menu and a back button.
Now suppose user go to HomePage and then createRequestPage and then used menu to go to requestListPage,now i need that when user click back button it should take user to homePage.For this my approach is that when user click through menu,i will remove all pages in navigation stack except the first one that is our root-Homepage.
I tried with this way but its not working-

this.navCtrl.remove(1,this.navCtrl.length(),{}).then(
()=>{
      this.navCtrl.push(RequestListPage)
});

But this does not seems to work.
Can somebody help me with this.
Also some better docs for NavController of ionic2.

Body:
if you put navCtrl in the provider that is the way:

In provider import

import { NavController, App } from 'ionic-angular';

in export class init

private navCtrl: NavController;

in constructor

constructor(private app:App) {

   this.navCtrl = app.getActiveNav();

}

Define a function go to home page:

goToHomePage() {

    this.navCtrl.setRoot(HomePage);

}

Now can call this.navCtrl in any page you like

import { YourProvider } from "../../your-provider";

@Component({

    selector: 'page',

    templateUrl: 'page.html',

    providers: [YourProvider]

})

export class YourPage{

  constructor(private yourProvider : YourProvider) {

}

goToHome() {
    this.yourProvider.goToHomePage();
}

now you can use navCtrl

Goodluck


问:
Dropdown style is different in Mac OS safari and windows safari browser
I've been confused about the HTML dropdown  design style is differ in MAC OS and windows OS safari browser.

Is this expected native behavior style? Can we bring the windows dropdown style in MAC OS without using any javascript.

答:
As far as I remember all you have to do is add -webkit-appearance:none; to your dropdown class.

I refer to this post: How can I remove the gloss on a select element in Safari on Mac?


问:
CSS Flex spacing issue
I'm having trouble figuring out how to have two columns (which get shrunk into one big column when the screen size shrinks) display their whole content without overlapping. Here's the images of what is happening The first is when the app is on a larger screen, where the flex-direction is set to row. When the screen size is smaller, I have it switch flex-direction to column, which works well except I cannot figure out how to make the 2nd row (Trending Down) start where the Trending Up stops, where ever that may be. Instead it's starting the 2nd column right in the middle of it like you see in the image.

Here's the code full size:

```<code>.playersColumns {
display: flex;
flex-direction: row;
justify-content: center;
padding-top: 28px;
align-items: center;
}

.playersBody {
flex-wrap: wrap;
min-width: 255px;
}
</code>```

Here is the code when width < 600px (where the issue is occurring)

```<code>.playersColumns {
display: flex;
flex-direction: column;
justify-content: space-between;
padding-left: 52px;
}
</code>```

As you can see, players are being entered into the database, being displayed, and voted on. I need to have it line up one section on top of the other if there are only 2 players, or 20 players listed in Trending Up.

Here's the React:

```<code><div className="playersColumns">
      <div className="playersBody">
        <span className="trendHeaderUp">TRENDING UP</span>
        {
          orderedPlayersUp.map((player) => {
            return (
              <Player
                playerContent={player.playerContent}
                playerId={player.id}
                key={player.id}
                upvotePlayer={this.upvotePlayer}
                downvotePlayer={this.downvotePlayer}
                userLogIn={this.userLogIn}
                userLogOut={this.userLogOut}
              />
            )
          })
        }
      </div>
      <div className="playersBody">
        <span className="trendHeaderDown">TRENDING DOWN</span>
        {
          orderedPlayersDown.map((player) => {
            return (
              <Player
                playerContent={player.playerContent}
                playerId={player.id}
                key={player.id}
                upvotePlayer={this.upvotePlayer}
                downvotePlayer={this.downvotePlayer}
                userLogIn={this.userLogIn}
                userLogOut={this.userLogOut}
              />
            )
          })
        }
      </div>
    </div>
</code>```

答:
I fixed this with </p>

```<code>.playersBody {
height: auto;   <---- My height for the body area was not large and was causing it to scrunch up -- so I set it to auto.
flex-wrap: wrap;
min-width: 255px;
}

@media (max-width: 600px) {
.playersColumns {
display: flex;
/*flex: 1 0 165%;*/
flex-wrap: wrap;
align-content: space-between;
padding-left: 54px;
}
}
</code>```

Title: CSS Flex spacing issue

Body:
I'm having trouble figuring out how to have two columns (which get shrunk into one big column when the screen size shrinks) display their whole content without overlapping. Here's the images of what is happening The first is when the app is on a larger screen, where the flex-direction is set to row. When the screen size is smaller, I have it switch flex-direction to column, which works well except I cannot figure out how to make the 2nd row (Trending Down) start where the Trending Up stops, where ever that may be. Instead it's starting the 2nd column right in the middle of it like you see in the image.

Here's the code full size:

.playersColumns {
display: flex;
flex-direction: row;
justify-content: center;
padding-top: 28px;
align-items: center;
}

.playersBody {
flex-wrap: wrap;
min-width: 255px;
}

Here is the code when width < 600px (where the issue is occurring)

.playersColumns {
display: flex;
flex-direction: column;
justify-content: space-between;
padding-left: 52px;
}

As you can see, players are being entered into the database, being displayed, and voted on. I need to have it line up one section on top of the other if there are only 2 players, or 20 players listed in Trending Up.

Here's the React:

        TRENDING UP
        {
          orderedPlayersUp.map((player) => {
            return (
              <Player
                playerContent={player.playerContent}
                playerId={player.id}
                key={player.id}
                upvotePlayer={this.upvotePlayer}
                downvotePlayer={this.downvotePlayer}
                userLogIn={this.userLogIn}
                userLogOut={this.userLogOut}
              />
            )
          })
        }

        TRENDING DOWN
        {
          orderedPlayersDown.map((player) => {
            return (
              <Player
                playerContent={player.playerContent}
                playerId={player.id}
                key={player.id}
                upvotePlayer={this.upvotePlayer}
                downvotePlayer={this.downvotePlayer}
                userLogIn={this.userLogIn}
                userLogOut={this.userLogOut}
              />
            )
          })
        }

Body:
I fixed this with

.playersBody {
height: auto;   <---- My height for the body area was not large and was causing it to scrunch up -- so I set it to auto.
flex-wrap: wrap;
min-width: 255px;
}

@media (max-width: 600px) {
.playersColumns {
display: flex;
/*flex: 1 0 165%;*/
flex-wrap: wrap;
align-content: space-between;
padding-left: 54px;
}
}


问:
Spring SimpleFormController in 3.0
i notice that this controller has now been deprecated in the latest spring and was wondering what the alternative controller is?</p>

答:
In Spring 3.0 you should use simple classes annotated by @Controller. Such controller can handle more than one request. Each request is handled by its own method. These methods are annotated by @RequestMapping.

One thing you need to rethink is the fact, that a old school SimpleFormController handle a lot of different requests (at least: one to get the form and a second to submit the form). You have to handle this now by hand. But believe me it is easier.

For example this Controller in REST Style, will handle two requests:

/book - POST: to create a book

/book/form - GET: to get the form for creation

Java Code:

```<code>@RequestMapping("/book/**")
@Controller
public class BookController {

    @RequestMapping(value = "/book", method = RequestMethod.POST)
    public String create(
        @ModelAttribute("bookCommand") final BookCommand bookCommand) {

        Book book = createBookFromBookCommand(bookCommand);
        return "redirect:/book/" + book.getId();
    }

    @RequestMapping(value = "/book/form", method = RequestMethod.GET)
    public String createForm(final ModelMap modelMap) {
        modelMap.addAttribute("all", "what you need");
        return "book/create"; //book/create.jsp
    }
}
</code>```

Title: Spring SimpleFormController in 3.0

Body:
In Spring 3.0 you should use simple classes annotated by @Controller. Such controller can handle more than one request. Each request is handled by its own method. These methods are annotated by @RequestMapping.

One thing you need to rethink is the fact, that a old school SimpleFormController handle a lot of different requests (at least: one to get the form and a second to submit the form). You have to handle this now by hand. But believe me it is easier.

For example this Controller in REST Style, will handle two requests:

/book - POST: to create a book

/book/form - GET: to get the form for creation

Java Code:

@RequestMapping("/book/**")
@Controller
public class BookController {

    @RequestMapping(value = "/book", method = RequestMethod.POST)
    public String create(
        @ModelAttribute("bookCommand") final BookCommand bookCommand) {

        Book book = createBookFromBookCommand(bookCommand);
        return "redirect:/book/" + book.getId();
    }

    @RequestMapping(value = "/book/form", method = RequestMethod.GET)
    public String createForm(final ModelMap modelMap) {
        modelMap.addAttribute("all", "what you need");
        return "book/create"; //book/create.jsp
    }
}


问:
SpringBoot please suggest custom Query for
select * from ngb.subsidy where
(effective_start_date, effective_end_date) OVERLAPS
  ('2017-08-01'::DATE, '2017-08-01'::DATE) order by effective_start_date asc

Below given query is not working

```<code>@Query(value="select * from ngb.security_deposit sd  where sd.consumer_no = :consumerNo and (sd.effective_start_date, sd.effective_end_date) OVERLAPS (:effectiveStartDate::DATE, :effectiveEndDate::DATE) order by sd.effective_start_date asc",nativeQuery=true)

public  List<SecurityDepositInterface> findByConsumerNoAndEffectiveStartDateAndEffectiveEndDate(@Param("consumerNo") String consumerNo, @Param("effectiveStartDate") Date effectiveStartDate, @Param("effectiveEndDate") Date effectiveEndDate);
</code>```

showing
java.lang.IllegalArgumentException: Parameter with that name [effectiveStartDate] did not exist

答:
In your repo</p>

```<code> @Query(value="select * from ngb.subsidy where (effective_start_date, effective_end_date) OVERLAPS ('2017-08-01'::DATE, '2017-08-01'::DATE) order by effective_start_date asc",nativeQuery=true)

 List<Your Entity class> = findbyID(); // any name
</code>```

Body:
select * from ngb.subsidy where
(effective_start_date, effective_end_date) OVERLAPS
  ('2017-08-01'::DATE, '2017-08-01'::DATE) order by effective_start_date asc

Below given query is not working

@Query(value="select * from ngb.security_deposit sd  where sd.consumer_no = :consumerNo and (sd.effective_start_date, sd.effective_end_date) OVERLAPS (:effectiveStartDate::DATE, :effectiveEndDate::DATE) order by sd.effective_start_date asc",nativeQuery=true)

public  List<SecurityDepositInterface> findByConsumerNoAndEffectiveStartDateAndEffectiveEndDate(@Param("consumerNo") String consumerNo, @Param("effectiveStartDate") Date effectiveStartDate, @Param("effectiveEndDate") Date effectiveEndDate);

showing
java.lang.IllegalArgumentException: Parameter with that name [effectiveStartDate] did not exist

Body:
In your repo

 @Query(value="select * from ngb.subsidy where (effective_start_date, effective_end_date) OVERLAPS ('2017-08-01'::DATE, '2017-08-01'::DATE) order by effective_start_date asc",nativeQuery=true)

 List<Your Entity class> = findbyID(); // any name


问:
Function inside component - ReactJS
Pretty new to  React and I have this issue: I want to get URL+ImageUrl from coinData.

In Vue, I would just create a method in the component:

```<code>getCoinImage: function(symbol) {
  return CRYPTOCOMPARE_API_URI + this.coinData[symbol].ImageUrl;
}
</code>```

Then call the function in the view template and it would return full URL of the image I'm looking for.

How do I do it in React?

```<code>class App extends Component {

  constructor(props) {
    super(props);

this.state = {
  cryptos: [],
  coinData: {},
};
}

componentDidMount() {
 axios.get('https://api.coinmarketcap.com/v1/ticker/?limit=0')
.then(res => {
  const cryptos = res.data;
  this.setState({cryptos: cryptos});
  console.log(this.state.cryptos);

})

axios.get('https://min-api.cryptocompare.com/data/all/coinlist')
.then(res => {
const coinData = res.data.Data;
this.setState({coinData: coinData});
//console.log(coinData["BTC"].ImageUrl);
})
}

render() {
return (

    <table className="table is-striped is-narrow is-fullwidth"><thead>
        <tr>
          <td>Rank</td>
          <td>Name</td>
          <td>Symbol</td>
          <td>Price (USD)</td>
          <td>1h</td>
          <td>24h</td>
          <td>1 Week</td>
          <td>Market Cap</td>
        </tr>
      </thead>
      <tbody>{Object.keys(this.state.cryptos).map((key) => (
        <tr>
          <td>{this.state.cryptos[key].rank}</td>
          <td>{this.state.cryptos[key].name}</td>
          <td>{this.state.cryptos[key].symbol}</td>
          <td>{this.state.cryptos[key].price_usd}</td>
          <td>{this.state.cryptos[key].percent_change_1h}</td>
          <td>{this.state.cryptos[key].percent_change_24h}</td>
          <td>{this.state.cryptos[key].percent_change_7d}</td>
          <td>{this.state.cryptos[key].market_cap_usd}</td>
        </tr>
 ))};
      </tbody>
    </table>

);
}
}
</code>```

答:
First I would only update the state once both requests have been done

```<code>async componentDidMount() {
  const res1 = await axios.get('https://api.coinmarketcap.com/v1/ticker/?limit=0');
  const res2 = await axios.get('https://min-api.cryptocompare.com/data/all/coinlist');

  this.setState({
    cryptos: res1.data,
    coinData: res2.data.Data
  });
}
</code>```

Now you have access to everything you need to render your image in the render function. (I omitted some of the property for clarity purposes)

```<code>render() {
  const {cryptos, coinData} = this.state;

  return (

    <table className="table is-striped is-narrow is-fullwidth">
      <thead>
      <tr>
        <td>Symbol</td>
        <td>Image</td>
      </tr>
      </thead>
      <tbody>
      {Object.keys(this.state.cryptos).map((key) => (
        <tr>
          <td>{cryptos[key].symbol}</td>
          <td>{_.get(coinData, `[${cryptos[key].symbol}].ImageUrl`, `Not Found: ${cryptos[key].symbol}`)}</td>
          <td><img src={CRYPTOCOMPARE_API_URI + _.get(coinData, `[${cryptos[key].symbol}].ImageUrl`, '/default.png')} /></td>
        </tr>
      ))};
      </tbody>
    </table>
  );
}
</code>```

Title: Function inside component - ReactJS

Body:
Pretty new to  React and I have this issue: I want to get URL+ImageUrl from coinData.

In Vue, I would just create a method in the component:

getCoinImage: function(symbol) {
  return CRYPTOCOMPARE_API_URI + this.coinData[symbol].ImageUrl;
}

Then call the function in the view template and it would return full URL of the image I'm looking for.

How do I do it in React?

class App extends Component {

  constructor(props) {
    super(props);

this.state = {
  cryptos: [],
  coinData: {},
};
}

componentDidMount() {
 axios.get('https://api.coinmarketcap.com/v1/ticker/?limit=0')
.then(res => {
  const cryptos = res.data;
  this.setState({cryptos: cryptos});
  console.log(this.state.cryptos);

})

axios.get('https://min-api.cryptocompare.com/data/all/coinlist')
.then(res => {
const coinData = res.data.Data;
this.setState({coinData: coinData});
//console.log(coinData["BTC"].ImageUrl);
})
}

render() {
return (

          Rank
          Name
          Symbol
          Price (USD)
          1h
          24h
          1 Week
          Market Cap

{Object.keys(this.state.cryptos).map((key) => (

          {this.state.cryptos[key].rank}
          {this.state.cryptos[key].name}
          {this.state.cryptos[key].symbol}
          {this.state.cryptos[key].price_usd}
          {this.state.cryptos[key].percent_change_1h}
          {this.state.cryptos[key].percent_change_24h}
          {this.state.cryptos[key].percent_change_7d}
          {this.state.cryptos[key].market_cap_usd}

 ))};

);
}
}

Body:
First I would only update the state once both requests have been done

async componentDidMount() {
  const res1 = await axios.get('https://api.coinmarketcap.com/v1/ticker/?limit=0');
  const res2 = await axios.get('https://min-api.cryptocompare.com/data/all/coinlist');

  this.setState({
    cryptos: res1.data,
    coinData: res2.data.Data
  });
}

Now you have access to everything you need to render your image in the render function. (I omitted some of the property for clarity purposes)

render() {
  const {cryptos, coinData} = this.state;

  return (

    <table className="table is-striped is-narrow is-fullwidth">
      <thead>
      <tr>
        <td>Symbol</td>
        <td>Image</td>
      </tr>
      </thead>
      <tbody>
      {Object.keys(this.state.cryptos).map((key) => (
        <tr>
          <td>{cryptos[key].symbol}</td>
          <td>{_.get(coinData, `[${cryptos[key].symbol}].ImageUrl`, `Not Found: ${cryptos[key].symbol}`)}</td>
          <td><img src={CRYPTOCOMPARE_API_URI + _.get(coinData, `[${cryptos[key].symbol}].ImageUrl`, '/default.png')} /></td>
        </tr>
      ))};
      </tbody>
    </table>
  );
}


问:
Write to existing json file in specific place
I have a json file in which must be added some values which I am getting from another json file. the problem is that I could add anything at the end of the json, but not in the exact place.
My actual json file is:

```<code>{
  "id" : "some-id",
  "name" : "some-name",
  "email" : "some@email.com",
  "config" : {
    "pipelineConfigs" : [ {
      "application" : "service1",
      "pipelineConfigId" : "d2eb526c-839b-41b3-b59c-f86db6eebb4e"
    }, {
      "application" : "service2",
      "pipelineConfigId" : "f79394b6-e37f-42e2-a9b3-fdbcf85ad1d7"
    } ],
    "applications" : [ "service1", "service2" ],
    "clusters" : [ {
      "account" : "some-account",
      "stack" : "*",
      "detail" : "*",
      "applications" : null
    } ]
  },
  "updateTs" : 1510750871252,
  "createTs" : 1510743534340,
  "lastModifiedBy" : "admin"
}
</code>```

I am getting service3 and another-id from another json file Need to add them into destination json file in this way:

```<code>       {
      "application" : "service3",
      "pipelineConfigId" : "another-id"
    },
</code>```

after this part:

```<code>"config" : {
    "pipelineConfigs" : [
</code>```

and add the "service3" to "applications" : [ "service1", "service2" ],

The desired final result:

```<code>{
  "id" : "some-id",
  "name" : "some-name",
  "email" : "some@email.com",
  "config" : {
    "pipelineConfigs" : [ {
      "application" : "service1",
      "pipelineConfigId" : "d2eb526c-839b-41b3-b59c-f86db6eebb4e"
    }, {
      "application" : "service2",
      "pipelineConfigId" : "f79394b6-e37f-42e2-a9b3-fdbcf85ad1d7"
    }, {
      "application" : "service3",
      "pipelineConfigId" : "another-id"
    } ],
    "applications" : [ "service1", "service2", "service3" ],
    "clusters" : [ {
      "account" : "some-account",
      "stack" : "*",
      "detail" : "*",
      "applications" : null
    } ]
  },
  "updateTs" : 1510750871252,
  "createTs" : 1510743534340,
  "lastModifiedBy" : "admin"
}
</code>```

Which direction I should dig?

答:
Once you've loaded the JSON files, the structures are just nested Python dictionaries and lists:

```<code>import json

data = '''\
{
  "id" : "some-id",
  "name" : "some-name",
  "email" : "some@email.com",
  "config" : {
    "pipelineConfigs" : [ {
      "application" : "service1",
      "pipelineConfigId" : "d2eb526c-839b-41b3-b59c-f86db6eebb4e"
    }, {
      "application" : "service2",
      "pipelineConfigId" : "f79394b6-e37f-42e2-a9b3-fdbcf85ad1d7"
    } ],
    "applications" : [ "service1", "service2" ],
    "clusters" : [ {
      "account" : "some-account",
      "stack" : "*",
      "detail" : "*",
      "applications" : null
    } ]
  },
  "updateTs" : 1510750871252,
  "createTs" : 1510743534340,
  "lastModifiedBy" : "admin"
}'''

D = json.loads(data)
other = {'application':'service3',
         'pipelineconfigId':'another-id'}

# Make the two modifications...
D['config']['pipelineConfigs'].append(other)
D['config']['applications'].append(other['application'])

data = json.dumps(D,indent=2)
print(data)
</code>```

Output:

```<code>{
  "id": "some-id",
  "name": "some-name",
  "email": "some@email.com",
  "config": {
    "pipelineConfigs": [
      {
        "application": "service1",
        "pipelineConfigId": "d2eb526c-839b-41b3-b59c-f86db6eebb4e"
      },
      {
        "application": "service2",
        "pipelineConfigId": "f79394b6-e37f-42e2-a9b3-fdbcf85ad1d7"
      },
      {
        "application": "service3",
        "pipelineconfigId": "another-id"
      }
    ],
    "applications": [
      "service1",
      "service2",
      "service3"
    ],
    "clusters": [
      {
        "account": "some-account",
        "stack": "*",
        "detail": "*",
        "applications": null
      }
    ]
  },
  "updateTs": 1510750871252,
  "createTs": 1510743534340,
  "lastModifiedBy": "admin"
}
</code>```

Body:
I have a json file in which must be added some values which I am getting from another json file. the problem is that I could add anything at the end of the json, but not in the exact place.
My actual json file is:

{
  "id" : "some-id",
  "name" : "some-name",
  "email" : "some@email.com",
  "config" : {
    "pipelineConfigs" : [ {
      "application" : "service1",
      "pipelineConfigId" : "d2eb526c-839b-41b3-b59c-f86db6eebb4e"
    }, {
      "application" : "service2",
      "pipelineConfigId" : "f79394b6-e37f-42e2-a9b3-fdbcf85ad1d7"
    } ],
    "applications" : [ "service1", "service2" ],
    "clusters" : [ {
      "account" : "some-account",
      "stack" : "*",
      "detail" : "*",
      "applications" : null
    } ]
  },
  "updateTs" : 1510750871252,
  "createTs" : 1510743534340,
  "lastModifiedBy" : "admin"
}

I am getting service3 and another-id from another json file Need to add them into destination json file in this way:

       {
      "application" : "service3",
      "pipelineConfigId" : "another-id"
    },

after this part:

"config" : {
    "pipelineConfigs" : [

and add the "service3" to "applications" : [ "service1", "service2" ],

The desired final result:

{
  "id" : "some-id",
  "name" : "some-name",
  "email" : "some@email.com",
  "config" : {
    "pipelineConfigs" : [ {
      "application" : "service1",
      "pipelineConfigId" : "d2eb526c-839b-41b3-b59c-f86db6eebb4e"
    }, {
      "application" : "service2",
      "pipelineConfigId" : "f79394b6-e37f-42e2-a9b3-fdbcf85ad1d7"
    }, {
      "application" : "service3",
      "pipelineConfigId" : "another-id"
    } ],
    "applications" : [ "service1", "service2", "service3" ],
    "clusters" : [ {
      "account" : "some-account",
      "stack" : "*",
      "detail" : "*",
      "applications" : null
    } ]
  },
  "updateTs" : 1510750871252,
  "createTs" : 1510743534340,
  "lastModifiedBy" : "admin"
}

Which direction I should dig?

Body:
Once you've loaded the JSON files, the structures are just nested Python dictionaries and lists:

import json

data = '''\
{
  "id" : "some-id",
  "name" : "some-name",
  "email" : "some@email.com",
  "config" : {
    "pipelineConfigs" : [ {
      "application" : "service1",
      "pipelineConfigId" : "d2eb526c-839b-41b3-b59c-f86db6eebb4e"
    }, {
      "application" : "service2",
      "pipelineConfigId" : "f79394b6-e37f-42e2-a9b3-fdbcf85ad1d7"
    } ],
    "applications" : [ "service1", "service2" ],
    "clusters" : [ {
      "account" : "some-account",
      "stack" : "*",
      "detail" : "*",
      "applications" : null
    } ]
  },
  "updateTs" : 1510750871252,
  "createTs" : 1510743534340,
  "lastModifiedBy" : "admin"
}'''

D = json.loads(data)
other = {'application':'service3',
         'pipelineconfigId':'another-id'}

# Make the two modifications...
D['config']['pipelineConfigs'].append(other)
D['config']['applications'].append(other['application'])

data = json.dumps(D,indent=2)
print(data)

Output:

{
  "id": "some-id",
  "name": "some-name",
  "email": "some@email.com",
  "config": {
    "pipelineConfigs": [
      {
        "application": "service1",
        "pipelineConfigId": "d2eb526c-839b-41b3-b59c-f86db6eebb4e"
      },
      {
        "application": "service2",
        "pipelineConfigId": "f79394b6-e37f-42e2-a9b3-fdbcf85ad1d7"
      },
      {
        "application": "service3",
        "pipelineconfigId": "another-id"
      }
    ],
    "applications": [
      "service1",
      "service2",
      "service3"
    ],
    "clusters": [
      {
        "account": "some-account",
        "stack": "*",
        "detail": "*",
        "applications": null
      }
    ]
  },
  "updateTs": 1510750871252,
  "createTs": 1510743534340,
  "lastModifiedBy": "admin"
}


问:
Testing Windows 10 UWP purchases that use the Windows.Services.Store namespace
I'm updating an existing app to Windows 10 UWP from Windows 8.1 and thought I should utilise the latest Windows.Services.Store namespace for license and in app purchases.  I followed the instructions for testing and submitted a package to the store which I downloaded to get the license and associated again to start debugging.

Upon debugging, I expected to be able to set the purchase success/failure response through a popup dialog as occurs under the Windows.ApplicationModel.Store namespace.

However all I get is a request to input my credit card details, etc and I'm unable to get past that to test the rest of the process.

In addition, as this is an App with existing customers, as Microsoft instructions suggest, I set this beta submission to not appear in the store and only be visible to those with a direct link, yet it appears that existing customers have access to this beta version as the stats show acquisitions.

I've researched this but the best advice I saw was the suggestion to set the cost of licenses and addons in the store to zero and set their expiration date to a day so they can be purchased repeatedly.  But surely this makes licenses and addons available to existing customers for free and only allows testing of one purchase per day?

Frankly, using the live Store as part of the testing process seems reckless, especially as Microsoft don't provide details of how to perform such testing safely.

Please tell me that there is a sensible solution to beta testing purchasing without having to buy my own licenses and addons repeatedly, because that would be almost as idiotic as making licenses and addons available for free to my customers!

答:
Since you're updating your existing Windows 8.1 apps to UWP, this testing guidance may not apply to your specific case due to your existing customers.

If you don't want to set the add-on price for free, you could generate promotional codes for your hidden add-on product. So that you could have free access to the add-on by redeeming promo code and you could test if your add-on features work well after unlocking it in your UWP app.

You could find it from dashboard Attract list:

And you could select the add-on name you want to test:

Microsoft is working on optimizing the purchasing testing process for Windows.Service.Store namespace. If you have any suggestion about it, please feel free to submit your idea at Windows 10 Feedback Hub.


问:
Linux command 'll' is not working
I am able to run ll command with my user but not with sudo, it giving me error as command not found!</p>

答:
As it has been explained:

ll is actually an alias to ls -l

In your prompt, I would recommend using the following 3 commands when you are not sure about a command that you input:

type <command_name> will give you information about the command, in our particular case, the output will be: ll is aliased to 'ls -l'

which <command_name> will show you the path of the command you are going to use

whatis <command_name> will give you basic information about the command

Last but not least,  alias ll="ls -al" will allow you to create the alias you are looking for. However to avoid redefining your aliases every single time you open a new shell. You will have to save them in your .profile or add them in your .bashrc file (use .bash_aliases file for this purpose and uncomment that section in your .bashrc ) in the home directory of your user.

For additional information, please have a look at the following link:

https://unix.stackexchange.com/questions/183496/how-to-create-permanent-aliases-on-unix-like-systems

Title: Linux command 'll' is not working


问:
How do have text appear over my images?
I have written the code the way I like it so far (this site is a work in progress) and I have realized that I need text to appear over the images when I hover my cursor over them. I am a rookie and I have so much going on in my code that I have confused myself so bad I am going to the forums for the first time.

Here is the html:

.img-single {
  width: 550px;
  height: 367px;
  float: left;
  margin: 40px 15px;
  position: relative;
}

.img-single img {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0px;
  left: 0px;
  transition: all 200ms ease-in-out;
  -webkit-transition: all 200ms ease-in-out;
  -o-transition: all 200ms ease-in-out;
}

.img-single img:hover {
  width: 110%;
  height: 110%;
  position: absolute;
  top: -5%;
  left: -5%;
}

.img-single:hover {
  z-index: 1000;
}

.wrapper {
  width: 1160px;
  margin: 0 auto;
}

.port-box {
  overflow: hidden;
  padding; 80px 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <nav>
    <ul>
      <li> Home </li>
        <div class="logo"></div>
      <li class="dropdown">
        My Work
        <div class="dropdown-content">
          Cars
          Dogs
          Landscapes
          Concerts
          Nature
          Misc
        </div>
      <li> About me </li>
      <li> Contact Me </li>
    </ul>
  </nav>
  <main>
    <div class="port-box">
      <div class="wrapper">

          <div class="img-single">
            <img src="images/hud.jpg">
          </div>

          <div class="img-single">
            <img src="images/rocky.jpeg">
          </div>

          <div class="img-single">
            <img src="images/sunset.jpg">
          </div>

          <div class="img-single">
            <img src="images/concert.jpeg">
          </div>

          <div class="img-single">
            <img src="images/nature.jpg">
          </div>

          <div class="img-single">
            <img src="images/misc.jpeg">
          </div>

      </div>
    </div>
  </main>
  <div class="footer">
  Copyright © 2017 Richard Spradling
  </div>
</body></code>```

I realize there is already a hover effect, I would like to replace that with text appearing. Thank you.

答:
You can use display: none; when there is no hover on image and when there is hover on image use display: block;

.img-single {
  width: 550px;
  height: 367px;
  float: left;
  margin: 40px 15px;
  position: relative;
}

.img-single img {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0px;
  left: 0px;
  transition: all 200ms ease-in-out;
  -webkit-transition: all 200ms ease-in-out;
  -o-transition: all 200ms ease-in-out;
}

.img-single img:hover {
  width: 110%;
  height: 110%;
  position: absolute;
  top: -5%;
  left: -5%;
}

.img-single:hover {
  z-index: 1000;
}

.wrapper {
  width: 1160px;
  margin: 0 auto;
}

.port-box {
  overflow: hidden;
  padding;
  80px 0px;
}

.textimg {
  display: none;
  position: absolute;
  top: 50%;
  right: 50%;
}

.img-single:hover .textimg {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <ul>
    <li> Home </li>

      <div class="logo"></div>

    <li class="dropdown">
      My Work
      <div class="dropdown-content">
        Cars
        Dogs
        Landscapes
        Concerts
        Nature
        Misc
      </div>
      <li> About me </li>
      <li> Contact Me </li>
  </ul>
</nav>
<main>
  <div class="port-box">
    <div class="wrapper">

        <div class="img-single">
          <img src="images/hud.jpg">
          <div class="textimg">Text</div>
        </div>

        <div class="img-single">
          <img src="images/rocky.jpeg">
          <div class="textimg">Text</div>
        </div>

        <div class="img-single">
          <img src="images/sunset.jpg">
          <div class="textimg">Text</div>
        </div>

        <div class="img-single">
          <img src="images/concert.jpeg">
          <div class="textimg">Text</div>
        </div>

        <div class="img-single">
          <img src="images/nature.jpg">
          <div class="textimg">Text</div>
        </div>

        <div class="img-single">
          <img src="images/misc.jpeg">
          <div class="textimg">Text</div>
        </div>

    </div>
  </div>
</main>
<div class="footer">
  Copyright © 2017 Richard Spradling
</div></code>```

I have added this to your code :
In CSS:

```<code>.textimg {
    display:none;
    position: absolute;
    top:50%;
    right:50%;
}

.img-single:hover .textimg {
  display:block;
}
</code>```

HTML:

```<code><div class="img-single">
          <img src="images/misc.jpeg">
          <div class="textimg">Text</div>
</div>
</code>```

Title: How do have text appear over my images?

Body:
I have written the code the way I like it so far (this site is a work in progress) and I have realized that I need text to appear over the images when I hover my cursor over them. I am a rookie and I have so much going on in my code that I have confused myself so bad I am going to the forums for the first time.

Here is the html:

.img-single {
  width: 550px;
  height: 367px;
  float: left;
  margin: 40px 15px;
  position: relative;
}

.img-single img {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0px;
  left: 0px;
  transition: all 200ms ease-in-out;
  -webkit-transition: all 200ms ease-in-out;
  -o-transition: all 200ms ease-in-out;
}

.img-single img:hover {
  width: 110%;
  height: 110%;
  position: absolute;
  top: -5%;
  left: -5%;
}

.img-single:hover {
  z-index: 1000;
}

.wrapper {
  width: 1160px;
  margin: 0 auto;
}

.port-box {
  overflow: hidden;
  padding; 80px 0px;
}

 Home

        My Work

          Cars
          Dogs
          Landscapes
          Concerts
          Nature
          Misc

 About me

 Contact Me

  Copyright © 2017 Richard Spradling

I realize there is already a hover effect, I would like to replace that with text appearing. Thank you.

Body:
You can use display: none; when there is no hover on image and when there is hover on image use display: block;

.img-single {
  width: 550px;
  height: 367px;
  float: left;
  margin: 40px 15px;
  position: relative;
}

.img-single img {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0px;
  left: 0px;
  transition: all 200ms ease-in-out;
  -webkit-transition: all 200ms ease-in-out;
  -o-transition: all 200ms ease-in-out;
}

.img-single img:hover {
  width: 110%;
  height: 110%;
  position: absolute;
  top: -5%;
  left: -5%;
}

.img-single:hover {
  z-index: 1000;
}

.wrapper {
  width: 1160px;
  margin: 0 auto;
}

.port-box {
  overflow: hidden;
  padding;
  80px 0px;
}

.textimg {
  display: none;
  position: absolute;
  top: 50%;
  right: 50%;
}

.img-single:hover .textimg {
  display: block;
}

<nav>
  <ul>
    <li><a href="home.html"> Home </a></li>
    <a href="home.html">
      <div class="logo"></div>
    </a>
    <li class="dropdown">
      <a href="javascript:void(0)" class="dropbtn active">My Work</a>
      <div class="dropdown-content">
        <a href="#">Cars</a>
        <a href="#">Dogs</a>
        <a href="#">Landscapes</a>
        <a href="#">Concerts</a>
        <a href="#">Nature</a>
        <a href="#">Misc</a>
      </div>
      <li><a href="about.html"> About me </a></li>
      <li><a href="contact.html"> Contact Me </a></li>
  </ul>
</nav>
<main>
  <div class="port-box">
    <div class="wrapper">
      <a href="cars.html">
        <div class="img-single">
          <img src="images/hud.jpg">
          <div class="textimg">Text</div>
        </div>
      </a>
      <a href="dogs.html">
        <div class="img-single">
          <img src="images/rocky.jpeg">
          <div class="textimg">Text</div>
        </div>
      </a>
      <a href="landscapes.html">
        <div class="img-single">
          <img src="images/sunset.jpg">
          <div class="textimg">Text</div>
        </div>
      </a>
      <a href="concerts.html">
        <div class="img-single">
          <img src="images/concert.jpeg">
          <div class="textimg">Text</div>
        </div>
      </a>
      <a href="nature.html">
        <div class="img-single">
          <img src="images/nature.jpg">
          <div class="textimg">Text</div>
        </div>
      </a>
      <a href="misc.html">
        <div class="img-single">
          <img src="images/misc.jpeg">
          <div class="textimg">Text</div>
        </div>
      </a>
    </div>
  </div>
</main>
<div class="footer">
  Copyright &copy; 2017 Richard Spradling
</div>

I have added this to your code :
In CSS:

.textimg {
    display:none;
    position: absolute;
    top:50%;
    right:50%;
}

.img-single:hover .textimg {
  display:block;
}

HTML:

<div class="img-single">
          <img src="images/misc.jpeg">
          <div class="textimg">Text</div>
</div>


问:
Where to find root and intermediate certificates having a security token with only end certificate in it
First i must say im kinda new at digital signatures and PKI.
I have a few questions regarding the way the whole PKI infrastructure works.
Lets say i have a security token containing my private key + my valid end-entity certificate. Therefore i can sign files without issues. I am using the software provided by the certificate issuer to do so.

Assuming i send a signed file to somebody who uses the software of another issuer, will they able to verify the signature? My main concern here is how are they going to obtain the root and the intermediate certificates to build the certificate chain /we're talking the case where the Authority Information Access field is null/? Isn't building the chain the first step towards signature verification?

It seems to me that the software provided by the certificate issuer installs the intermediate and the root certificates on the computer. Is that correct?

If there's a way to find all of those intermediate/root certificates from the internet - where i might be able to find them?

A while ago i had this idea to create an app that can use ANY token to sign a message, and verify messages sent by ANY signer. We're talking chain validation, CRL and OCSP checks. Is that even possible?

答:
Assuming i send a signed file to somebody who uses the software of another issuer, will they able to verify the signature?

Cryptographically yes he can using the public key, but verifying a signature in depth it is a complex process:

cryptographic verification

Trust in the certification chain

Certificate revocation status

Validity on signing time (certificate not expired, or signature protected with a timestamp

And an essential factor that is the format of the signature. There are multiple digital signature formats (XMLDsig, CMS, CAdES, PKC#7, JWS, PAdES) encapsulating the digital signature and the verification software must deal with the formats and interoperability issues between versions and even different interpretations of the standard

My main concern here is how are they going to obtain the root and the intermediate certificates to build the certificate chain /we're talking the case where the Authority Information Access field is null/?

Most digital signature formats require certificates to be included in the signature itself. Then the verifier can validate the certification chain until root certificate, that must be included in a local truststore.

Isn't building the chain the first step towards signature verification?

Yes, it is. The issuer must validate the certification chain. A signature can not be considered valid if the issuer root certificate is not found in the local truststore.

It seems to me that the software provided by the certificate issuer installs the intermediate and the root certificates on the computer. Is that correct?

Yes, the certificate can be pre-provisioned in a computer, and some Operative Systems or programming languages have a truststore with a list of preloaded trusted issuers that can be used to validate the signature

If there's a way to find all of those intermediate/root certificates from the internet - where i might be able to find them?

You can usually download them from the web page of the Certificate Authority. The certificate  should include the AIA extension with a URL to download the issuer. Also, In the European Union there is a global list of trusted providers where references to all certificates in use are.

A while ago i had this idea to create an app that can use ANY token to sign a message, and verify messages sent by ANY signer. We're talking chain validation, CRL and OCSP checks. Is that even possible?

Yes it is possible and it is a real business area. There are several commercial digital signature validation platforms. Take a look to SD-DSS open-source project leaded by EU


问:
How can I use Material Components through object library/storyboard?
I'd like to know if it's possible to use Material Components dragging them from my object library directly to the storyboard views.

Thanks,

答:
Yes, You can use storyboard objects for designing MaterialDesign Components.

For Example:

If you want to have a floating button in your app, then simply drag UIButton object in storyboard and change its class Name from UIButton to MDCFloatingButton as in the following image.

Add set constraint, title and color as you wish.

The result in simulator will look like this -

Hope this helps..!


问:
Cannot integrate three.js with create react app
I have been trying to integrate threejs with create react app from past 2 days.
All the 3d scene related files are in plain javascript and are stored in public/js folder.It throws an error:

Refused to execute script from
  'https://cdn.rawgit.com/mrdoob/three.js/dev/examples/js/loaders/OBJLoader.js'
  because its MIME type ('text/plain') is not executable, and strict
  MIME type checking is enabled.

And when I add objloader.js in the local system it throws an error:

Uncaught Error: Unexpected line: <!DOCTYPE html> cannot be parsed by
  OBJloader

But I am able to render the 3D scene without react.Thanks in advance.Help much appreciated.

答:
I made a simple GitHub repo to mess with three js stuff in a react environment. It uses the OBJ loader and the MTL loader in threes examples directory. Take a look and let me know if you have any questions: https://github.com/garretthogan/react-obj-viewer

edit: also, if you aren't serving up the static asset files like *.obj to your client side app then when you try to load them with the client side URL (localhost:3000/assets/models/myobj.obj) for example, the create react app server probably just returns the root index.html as a fail safe, which then throws the unexpected line error because your OBJ parser can't parse it.


问:
Mapbox-gl and angular2
i'm trying to integrate mapbox-gl to angular2 application. But after making the service app doesn't work.

Service

```<code>    import {Injectable} from '@angular/core';
import * as mapboxgl from 'mapbox-gl';
import { Map } from 'mapbox-gl';

@Injectable()
export class MapService {
    map: Map;
    baseMaps: any;

    constructor() {

        (mapboxgl as any).accessToken = 'my_acces_token(in original code included';)

    }

}
</code>```

Module

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

import { AppComponent }  from './app.component';
import {MapService} from './services/mapService/mapBox.service'

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ],
  providers: [MapService]
})
export class AppModule { }
</code>```

After starting the app this is error i get

```<code>Failed to load resource: the server responded with a status of 404 (Not Found)
</code>```

and

```<code>ZoneAwareError
</code>```

mabpox-gl was installed with these commands

```<code>npm install mapbox-gl --save

and

npm install @types/mapbox-gl --save
</code>```

答:
Firstable, check if the @types library of mapboxgl support the mapbox-gl library version that you install.

Then, in service, declare the map like map: mapboxgl.Map;

and in your component declare the map like

```<code>this.map = new mapboxgl.Map({
            container: 'map',
            center: GlobalVariables.defaultCoord,
            maxZoom: GlobalVariables.defMaxZoom,
            minZoom: GlobalVariables.defMinZoom,
            zoom: GlobalVariables.defZoom,
            style: GlobalVariables.mapboxDark
        });
</code>```

Finally, go to tsconfig.json, in the "compilerOptions" field, and check if you set the types property with the mapboxgl types. For example:

```<code>"compilerOptions": {
"moduleResolution": "node",
"target": "es5",
"sourceMap": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"skipDefaultLibCheck": true,
"lib": [ "es5", "es6", "dom" ],
"types": [ "node", "geojson", "mapbox-gl" ]
</code>```

}

I hope that this helps.
Regards.

Title: Mapbox-gl and angular2

Body:
i'm trying to integrate mapbox-gl to angular2 application. But after making the service app doesn't work.

Service

    import {Injectable} from '@angular/core';
import * as mapboxgl from 'mapbox-gl';
import { Map } from 'mapbox-gl';

@Injectable()
export class MapService {
    map: Map;
    baseMaps: any;

    constructor() {

        (mapboxgl as any).accessToken = 'my_acces_token(in original code included';)

    }

}

Module

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent }  from './app.component';
import {MapService} from './services/mapService/mapBox.service'

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ],
  providers: [MapService]
})
export class AppModule { }

After starting the app this is error i get

Failed to load resource: the server responded with a status of 404 (Not Found)

and

ZoneAwareError

mabpox-gl was installed with these commands

npm install mapbox-gl --save

and

npm install @types/mapbox-gl --save

Body:
Firstable, check if the @types library of mapboxgl support the mapbox-gl library version that you install.

Then, in service, declare the map like map: mapboxgl.Map;

and in your component declare the map like

this.map = new mapboxgl.Map({
            container: 'map',
            center: GlobalVariables.defaultCoord,
            maxZoom: GlobalVariables.defMaxZoom,
            minZoom: GlobalVariables.defMinZoom,
            zoom: GlobalVariables.defZoom,
            style: GlobalVariables.mapboxDark
        });

Finally, go to tsconfig.json, in the "compilerOptions" field, and check if you set the types property with the mapboxgl types. For example:

"compilerOptions": {
"moduleResolution": "node",
"target": "es5",
"sourceMap": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"skipDefaultLibCheck": true,
"lib": [ "es5", "es6", "dom" ],
"types": [ "node", "geojson", "mapbox-gl" ]

}

I hope that this helps.
Regards.


问:
how to get multiple object json values and push to array using jquery
I am trying to get data from json and push to array but it is not working. it is possible or not getting multiple object values from json. anybody can tell it is possible or not? if it is possible how we can do it and where i stucked from my code?

html

```<code>        <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
        <script type="text/javascript">

        $( document ).ready(function() {
              var searchVal = [];
            var optionVal = [];
            var autocompVal = [];
            $.getJSON( "datas.json", function( data ) {

          $.each( data, function( key, val ) {
            searchVal.push(  key.searchVal.searchname );
          });

           $.each( data, function( key, val ) {
            optionVal.push(  key.optionVal.optionname );
          });

           $.each( data, function( key, val ) {
            autocompVal.push(  key.autocompVal );
          });

        console.log("Show all Array value="+searchVal +"=="+ optionVal +"=="+autocompVal);

        });

        $("#autoComplete").autocomplete({
                source: autocompVal,
                select: function (event, ui) {//when we select something from the search box
                    this.value = ui.item.label;
                    alert(this.value);
                    return false;
                }
            });

        });

        </script>

        <input type="text" id="autoComplete">
</code>```

datas.json:

```<code>        {
            "searchVal": [
                 { "searchname":"test1"},
                 { "searchname":"test2"}
                 ],
            "optionVal": [
                 { "optionname":"test11"},
                 { "optionname":"test12"},
                 { "optionname":"test13"}
                 ],
           "autocompVal": [
                 { "test11"},
                 { "test12"} ,
                 { "test13"},
                 { "test14"}
                 ]
        }
</code>```

答:
One change your structure of autocompVal array was wrong. I have changed it.
Hope it helps you.

var data =  {
            "searchVal": [
                 { "searchname":"test1"},
                 { "searchname":"test2"}
                 ],
                 "optionVal": [
                 { "optionname":"test11"},
                 { "optionname":"test12"},
                 { "optionname":"test13"}
                 ],
           "autocompVal": [
                  "test11",
                 "test12" ,
                  "test13",
                  "test14"
                 ]
        };

var searchVal = [];
var optionVal = [];
var autocompVal = [];

$.each( data.searchVal, function( index, item ) {
    searchVal.push(  item.searchname );
});

$.each( data.optionVal, function( index, item ) {
    optionVal.push(  item.optionname );
});

$.each( data.autocompVal, function( index, item ) {
     autocompVal.push(item);
});

console.log(searchVal);
console.log(optionVal);
console.log(autocompVal);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
I am trying to get data from json and push to array but it is not working. it is possible or not getting multiple object values from json. anybody can tell it is possible or not? if it is possible how we can do it and where i stucked from my code?

html

        <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

        <input type="text" id="autoComplete">

datas.json:

        {
            "searchVal": [
                 { "searchname":"test1"},
                 { "searchname":"test2"}
                 ],
            "optionVal": [
                 { "optionname":"test11"},
                 { "optionname":"test12"},
                 { "optionname":"test13"}
                 ],
           "autocompVal": [
                 { "test11"},
                 { "test12"} ,
                 { "test13"},
                 { "test14"}
                 ]
        }

Body:
One change your structure of autocompVal array was wrong. I have changed it.
Hope it helps you.

var data =  {
            "searchVal": [
                 { "searchname":"test1"},
                 { "searchname":"test2"}
                 ],
                 "optionVal": [
                 { "optionname":"test11"},
                 { "optionname":"test12"},
                 { "optionname":"test13"}
                 ],
           "autocompVal": [
                  "test11",
                 "test12" ,
                  "test13",
                  "test14"
                 ]
        };

var searchVal = [];
var optionVal = [];
var autocompVal = [];

$.each( data.searchVal, function( index, item ) {
    searchVal.push(  item.searchname );
});

$.each( data.optionVal, function( index, item ) {
    optionVal.push(  item.optionname );
});

$.each( data.autocompVal, function( index, item ) {
     autocompVal.push(item);
});

console.log(searchVal);
console.log(optionVal);
console.log(autocompVal);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
Why are there Debug & Release builds for .Net, but not for Java?
In .Net, you can specifically compile your projects under "Debug" or "Release" settings, Release having more optimizations. I know that this is deemed unnecessary in Java, because the jitter does these optimizations. What is the reason for the difference? (meaning, why is a pre-"jitter" compilation required/helpful)

Why is it deemed necessary in .Net/CLR, but not in Java/JDK?

答: I think they can easily be introduced in Java. Basically Debug build means: Include debug symbols and disable optimization. Release is vice versa. Debug and Release targets are generated by Visual Studio and are not mandatory. You can write your MSBuild script without VS. So you can create build script for Java with Debug and Release targets.</p>

ContentLicense: CC BY-SA 2.5


问:
how to take large size array in java
i am new to java and i want to take large input size array in java. but in gives me some Runtime Error - NZEC, I don't know about it and i also did some research on this error but did'nt find anything related to my problem.

```<code>   long n=sc.nextLong();// n can be upto 10^9;
   long a[]=new long[n];// declaring array of n;
</code>```

also i am facing a compile time error which is :

```<code>error: incompatible types: possible lossy conversion from long to int
</code>```

can anyone please solve my this issue??

答: To have such a large array may be inefficient in the first place. Can this be replaced with a better data structure that will help in your use case. May be the overall problem that is being attacked, if provided can help solve it in a different more efficient way. </p>

Title: how to take large size array in java

Body:
i am new to java and i want to take large input size array in java. but in gives me some Runtime Error - NZEC, I don't know about it and i also did some research on this error but did'nt find anything related to my problem.

   long n=sc.nextLong();// n can be upto 10^9;
   long a[]=new long[n];// declaring array of n;

also i am facing a compile time error which is :

error: incompatible types: possible lossy conversion from long to int

can anyone please solve my this issue??


问:
Import interface in Angular 2
In a Meteor app that uses Angular 2, I want to create a custom data type, something like this:

```<code>interface MyCustomType {
  index: number;
  value: string;
}
</code>```

I then want to use this custom type in multiple files. I've tried creating a separate file named "mycustom.type.ts", with the following content:

```<code>export interface MyCustomType {
  index: number;
  value: string;
}
</code>```

I then attempt to import this type so that it can be used in another file:

```<code>import MyCustomType from "./mycustom.type"
</code>```

However, Atom reports the following error:

```<code>TS Error File '/.../mycustom.type.ts' is not a module ...
</code>```

How should I be declaring and importing types, so that they can be used in multiple places?

答:
I think, problem is in the path:

Kindly refer below example:

If your file in another folder then refer below:

```<code>import { IPosts } from "../interfaces/iposts.type";
</code>```

iposts.type.ts :

```<code>export interface IPosts {
   userId: number;
   id: number;
   title: string;
   body: string;
}
</code>```

Title: Import interface in Angular 2

Body:
In a Meteor app that uses Angular 2, I want to create a custom data type, something like this:

interface MyCustomType {
  index: number;
  value: string;
}

I then want to use this custom type in multiple files. I've tried creating a separate file named "mycustom.type.ts", with the following content:

export interface MyCustomType {
  index: number;
  value: string;
}

I then attempt to import this type so that it can be used in another file:

import MyCustomType from "./mycustom.type"

However, Atom reports the following error:

TS Error File '/.../mycustom.type.ts' is not a module ...

How should I be declaring and importing types, so that they can be used in multiple places?

Body:
I think, problem is in the path:

Kindly refer below example:

If your file in another folder then refer below:

import { IPosts } from "../interfaces/iposts.type";

iposts.type.ts :

export interface IPosts {
   userId: number;
   id: number;
   title: string;
   body: string;
}


答:
Added a div overlay with position absolute with text. If your looking for text with effect on hover then,

.img-single {
  width: 550px;
  height: 367px;
  float: left;
  margin: 40px 15px;
  position: relative;
}

.img-single img {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0px;
  left: 0px;
  transition: all 200ms ease-in-out;
  -webkit-transition: all 200ms ease-in-out;
  -o-transition: all 200ms ease-in-out;
}

.img-single:hover {
  z-index: 1000;
}

.wrapper {
  width: 1160px;
  margin: 0 auto;
}

.port-box {
  overflow: hidden;
  padding;
  80px 0px;
}

.overlay {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100%;
  width: 100%;
  opacity: 0;
  transition: .5s ease;
  background-color: #008CBA;
}

.text {
  color: white;
  font-size: 20px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
}

.img-single:hover .overlay {
  opacity: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <ul>
    <li> Home </li>

      <div class="logo"></div>

    <li class="dropdown">
      My Work
      <div class="dropdown-content">
        Cars
        Dogs
        Landscapes
        Concerts
        Nature
        Misc
      </div>
      <li> About me </li>
      <li> Contact Me </li>
  </ul>
</nav>
<main>
  <div class="port-box">
    <div class="wrapper">

        <div class="img-single">
          <img src="http://via.placeholder.com/350x150">
          <div class="overlay">
            <div class="text">This Is My First Pic</div>
          </div>
        </div>

        <div class="img-single">
          <img src="http://via.placeholder.com/350x150">
          <div class="overlay">
            <div class="text">This Is My Second Pic</div>
          </div>
        </div>

        <div class="img-single">
          <img src="http://via.placeholder.com/350x150">
          <div class="overlay">
            <div class="text">This Is My Third Pic</div>
          </div>
        </div>

        <div class="img-single">
          <img src="http://via.placeholder.com/350x150">
          <div class="overlay">
            <div class="text">This Is My Fourth Pic</div>
          </div>
        </div>

        <div class="img-single">
          <img src="http://via.placeholder.com/350x150">
          <div class="overlay">
            <div class="text">This Is My Fifth Pic</div>
          </div>
        </div>

        <div class="img-single">
          <img src="http://via.placeholder.com/350x150">
          <div class="overlay">
            <div class="text">This Is My Sixth Pic</div>
          </div>
        </div>

    </div>
  </div>
</main>
<div class="footer">
  Copyright © 2017 Richard Spradling
</div></code>```

Title: How do have text appear over my images?

Body:
Added a div overlay with position absolute with text. If your looking for text with effect on hover then,

.img-single {
  width: 550px;
  height: 367px;
  float: left;
  margin: 40px 15px;
  position: relative;
}

.img-single img {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0px;
  left: 0px;
  transition: all 200ms ease-in-out;
  -webkit-transition: all 200ms ease-in-out;
  -o-transition: all 200ms ease-in-out;
}

.img-single:hover {
  z-index: 1000;
}

.wrapper {
  width: 1160px;
  margin: 0 auto;
}

.port-box {
  overflow: hidden;
  padding;
  80px 0px;
}

.overlay {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100%;
  width: 100%;
  opacity: 0;
  transition: .5s ease;
  background-color: #008CBA;
}

.text {
  color: white;
  font-size: 20px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
}

.img-single:hover .overlay {
  opacity: 1;
}

<nav>
  <ul>
    <li><a href="home.html"> Home </a></li>
    <a href="home.html">
      <div class="logo"></div>
    </a>
    <li class="dropdown">
      <a href="javascript:void(0)" class="dropbtn active">My Work</a>
      <div class="dropdown-content">
        <a href="#">Cars</a>
        <a href="#">Dogs</a>
        <a href="#">Landscapes</a>
        <a href="#">Concerts</a>
        <a href="#">Nature</a>
        <a href="#">Misc</a>
      </div>
      <li><a href="about.html"> About me </a></li>
      <li><a href="contact.html"> Contact Me </a></li>
  </ul>
</nav>
<main>
  <div class="port-box">
    <div class="wrapper">
      <a href="cars.html">
        <div class="img-single">
          <img src="http://via.placeholder.com/350x150">
          <div class="overlay">
            <div class="text">This Is My First Pic</div>
          </div>
        </div>
      </a>
      <a href="dogs.html">
        <div class="img-single">
          <img src="http://via.placeholder.com/350x150">
          <div class="overlay">
            <div class="text">This Is My Second Pic</div>
          </div>
        </div>
      </a>
      <a href="landscapes.html">
        <div class="img-single">
          <img src="http://via.placeholder.com/350x150">
          <div class="overlay">
            <div class="text">This Is My Third Pic</div>
          </div>
        </div>
      </a>
      <a href="concerts.html">
        <div class="img-single">
          <img src="http://via.placeholder.com/350x150">
          <div class="overlay">
            <div class="text">This Is My Fourth Pic</div>
          </div>
        </div>
      </a>
      <a href="nature.html">
        <div class="img-single">
          <img src="http://via.placeholder.com/350x150">
          <div class="overlay">
            <div class="text">This Is My Fifth Pic</div>
          </div>
        </div>
      </a>
      <a href="misc.html">
        <div class="img-single">
          <img src="http://via.placeholder.com/350x150">
          <div class="overlay">
            <div class="text">This Is My Sixth Pic</div>
          </div>
        </div>
      </a>
    </div>
  </div>
</main>
<div class="footer">
  Copyright &copy; 2017 Richard Spradling
</div>


问:
Why does code write this way the method indexOf() in String.class?
I'm reading the source code of String.class.

In the method indexOf() I see something I can't understand.

Here is the method indexOf() code snippet from String.class source code.

```<code>/**
 * Code shared by String and StringBuffer to do searches. The
 * source is the character array being searched, and the target
 * is the string being searched for.
 *
 * @param   source       the characters being searched.
 * @param   sourceOffset offset of the source string.
 * @param   sourceCount  count of the source string.
 * @param   target       the characters being searched for.
 * @param   targetOffset offset of the target string.
 * @param   targetCount  count of the target string.
 * @param   fromIndex    the index to begin searching from.
 */
static int indexOf(char[] source, int sourceOffset, int sourceCount,
        char[] target, int targetOffset, int targetCount,
        int fromIndex) {
    if (fromIndex >= sourceCount) {
        return (targetCount == 0 ? sourceCount : -1);
    }
    if (fromIndex < 0) {
        fromIndex = 0;
    }
    if (targetCount == 0) {
        return fromIndex;
    }

    char first = target[targetOffset];
    int max = sourceOffset + (sourceCount - targetCount);

    for (int i = sourceOffset + fromIndex; i <= max; i++) {
        /* Look for first character. */
        if (source[i] != first) {
            while (++i <= max && source[i] != first);
        }

        /* Found first character, now look at the rest of v2 */
        if (i <= max) {
            int j = i + 1;
            int end = j + targetCount - 1;
            for (int k = targetOffset + 1; j < end && source[j]
                    == target[k]; j++, k++);

            if (j == end) {
                /* Found whole string. */
                return i - sourceOffset;
            }
        }
    }
    return -1;
}
</code>```

I can't understand the code here.

```<code>if (fromIndex >= sourceCount) {
    return (targetCount == 0 ? sourceCount : -1);
}
</code>```

If the source String is "abcdedefg", sourceOffset is 2, sourceCount is 3,
and I want to search "d" from this,
why can't I search from index 4?

/**

* Ps:If the sourceCount means the length of the whole string, why not use source.length

* instead ?

*/

答:
This method accepts two character arrays - the source array is the one being searched and the target array is the one being searched for.

However, the offset and count variables limit the search to a sub-array of the source and a sub-array of the target.

Basically you are searching in the sub-array from source[sourceOffSet] to source[sourceOffset+sourceCount-1] for the String comprised of the characters in the sub-array from target[targetOffSet] to target[targetOffset+targetCount-1].

Here's an illustration. The relevant arrays for the search are the sub-arrays:

```<code>source array : |--------------------|
sub array    :       |-------|
                   source  source
                   offset  offset +
                           source
                           count - 1

target array : |--------------------|
sub array    :       |-------|
                   target  target
                   offset  offset +
                           target
                           count - 1
</code>```

However, the search is further limited by supplying fromIndex. You start the search from the fromIndex'th index of the source sub-array.

Since the length of the source sub-array is sourceCount, if fromIndex >= sourceCount, the target sub-array cannot be found, so unless the target sub-array is empty (i.e. targetCount == 0), -1 is returned.

Let's consider your example:

```<code>source : "abcdedefg"
sourceOffset : 2
sourceCount : 3
target : "d"
targetOffset : 0
targetCount : 1
fromIndex : 4
</code>```

These parameters mean you are searching in the source sub-string "cde" for the target sub-string "d" starting from index 4. However, there is no index 4 in "cde", so -1 is returned.

Regarding your

Ps:If the sourceCount means the length of the whole string, why not use source.length instead

As I explained sourceCount doesn't mean the length of the whole source array, just the length of the sub-array being searched.

Note that when you call someString.indexOf(str,fromIndex), the static method you asked about is being called with the following parameters:

```<code>public int indexOf(String str, int fromIndex) {
    return indexOf(value, 0, value.length,
            str.value, 0, str.value.length, fromIndex);
}
</code>```

In this case sourceCount is equal to source.length (i.e. the entire source array is being searched starting at fromIndex).

Body:
I'm reading the source code of String.class.

In the method indexOf() I see something I can't understand.

Here is the method indexOf() code snippet from String.class source code.

/**
 * Code shared by String and StringBuffer to do searches. The
 * source is the character array being searched, and the target
 * is the string being searched for.
 *
 * @param   source       the characters being searched.
 * @param   sourceOffset offset of the source string.
 * @param   sourceCount  count of the source string.
 * @param   target       the characters being searched for.
 * @param   targetOffset offset of the target string.
 * @param   targetCount  count of the target string.
 * @param   fromIndex    the index to begin searching from.
 */
static int indexOf(char[] source, int sourceOffset, int sourceCount,
        char[] target, int targetOffset, int targetCount,
        int fromIndex) {
    if (fromIndex >= sourceCount) {
        return (targetCount == 0 ? sourceCount : -1);
    }
    if (fromIndex < 0) {
        fromIndex = 0;
    }
    if (targetCount == 0) {
        return fromIndex;
    }

    char first = target[targetOffset];
    int max = sourceOffset + (sourceCount - targetCount);

    for (int i = sourceOffset + fromIndex; i <= max; i++) {
        /* Look for first character. */
        if (source[i] != first) {
            while (++i <= max && source[i] != first);
        }

        /* Found first character, now look at the rest of v2 */
        if (i <= max) {
            int j = i + 1;
            int end = j + targetCount - 1;
            for (int k = targetOffset + 1; j < end && source[j]
                    == target[k]; j++, k++);

            if (j == end) {
                /* Found whole string. */
                return i - sourceOffset;
            }
        }
    }
    return -1;
}

I can't understand the code here.

if (fromIndex >= sourceCount) {
    return (targetCount == 0 ? sourceCount : -1);
}

If the source String is "abcdedefg", sourceOffset is 2, sourceCount is 3,
and I want to search "d" from this,
why can't I search from index 4?

/**

* Ps:If the sourceCount means the length of the whole string, why not use source.length

* instead ?

*/

Body:
This method accepts two character arrays - the source array is the one being searched and the target array is the one being searched for.

However, the offset and count variables limit the search to a sub-array of the source and a sub-array of the target.

Basically you are searching in the sub-array from source[sourceOffSet] to source[sourceOffset+sourceCount-1] for the String comprised of the characters in the sub-array from target[targetOffSet] to target[targetOffset+targetCount-1].

Here's an illustration. The relevant arrays for the search are the sub-arrays:

source array : |--------------------|
sub array    :       |-------|
                   source  source
                   offset  offset +
                           source
                           count - 1

target array : |--------------------|
sub array    :       |-------|
                   target  target
                   offset  offset +
                           target
                           count - 1

However, the search is further limited by supplying fromIndex. You start the search from the fromIndex'th index of the source sub-array.

Since the length of the source sub-array is sourceCount, if fromIndex >= sourceCount, the target sub-array cannot be found, so unless the target sub-array is empty (i.e. targetCount == 0), -1 is returned.

Let's consider your example:

source : "abcdedefg"
sourceOffset : 2
sourceCount : 3
target : "d"
targetOffset : 0
targetCount : 1
fromIndex : 4

These parameters mean you are searching in the source sub-string "cde" for the target sub-string "d" starting from index 4. However, there is no index 4 in "cde", so -1 is returned.

Regarding your

Ps:If the sourceCount means the length of the whole string, why not use source.length instead

As I explained sourceCount doesn't mean the length of the whole source array, just the length of the sub-array being searched.

Note that when you call someString.indexOf(str,fromIndex), the static method you asked about is being called with the following parameters:

public int indexOf(String str, int fromIndex) {
    return indexOf(value, 0, value.length,
            str.value, 0, str.value.length, fromIndex);
}

In this case sourceCount is equal to source.length (i.e. the entire source array is being searched starting at fromIndex).


问:
How to get the current location dynamically using ZK framework?
i'm new in zk framework for java and i want the ability of create a map and retrieve the current location dinamically, currently this is my latest code for the map (lat and lng is hard coded that's the problem) :

```<code>        <div apply="br.com.minifrete.maps.GoogleMapsController">
        <!-- define the property 'zk.googleAPIkey' (or any other name)
            as a ZK-library-property, VM-arg or system-property
            or simply add your APIkey inline instead of ${c:property...} -->
        <!--<script type="text/javascript" content="zk.googleAPIkey='AIzaSyANBdLQzy9acJxEWCc7UOHhpIU9Zv94ZJ0'" />-->
        <script type="text/javascript"
            content="zk.googleAPIkey='AIzaSyANBdLQzy9acJxEWCc7UOHhpIU9Zv94ZJ0'" />
        <gmaps version="3.26" id="gmaps" width="520px"
            height="400px" showSmallCtrl="true" protocol="https">
            <ginfo id="info" open="true"
                content="Hello, <a href="http://www.zkoss.org\">ZK</a>." />
            <gmarker id="marker" lat="37.4410" lng="-122.1490"
                content="Hello, <a href="http://www.zkoss.org">ZK</a> on top of Gmarker." />
        </gmaps>
    </div>
</code>```

Thanks.

答:
Since ZK is running at the server-side there is no chance get the location from there. The only way (as already mentioned in Malte's comment above) is to use the html5 geolocation api.

The information obtained from there can be easily sent back to the server using a custom event. I created this zk fiddle example showing how to fire an event from the client side, and how to listen to it in your composer. You can then set the coordinates to the Gmaps component or as I did create a new Gmaps component dynamically.

Please note: zkfiddle is currently not running under HTTPS so I use dummy coordinates and a setTimeout simulating some delay. However I also provide the code to request the coordinates from navigator.geolocation.getCurrentLocation a line above just commented out.

Robert


问:
Verilog:Procedural Continuous Assignment to register is not supported
```<code>    input [31:0] write_data;
    input [4:0]  write_reg;
    reg [31:0] registers [31:0];

always @(*)
     assign registers[write_reg] = write_data;
</code>```

I have a 32-bit input write_data , which i want to an assign corresponding index which i get from write reg.Error says you cant do continuous assignment which i think causes by always@(*) but if i remove that

It says
object "registers" on left-hand side of assignment must have a net type
and its another error.

答:
You need to synchronously assign to registers. Because the synthesizer parses it and routes to a physical register (i.e. flip-flop)

```<code>always @(posedge clk)
    my_reg = my_data;
</code>```

Body:
    input [31:0] write_data;
    input [4:0]  write_reg;
    reg [31:0] registers [31:0];

always @(*)
     assign registers[write_reg] = write_data;

I have a 32-bit input write_data , which i want to an assign corresponding index which i get from write reg.Error says you cant do continuous assignment which i think causes by always@(*) but if i remove that

It says
object "registers" on left-hand side of assignment must have a net type
and its another error.

Body:
You need to synchronously assign to registers. Because the synthesizer parses it and routes to a physical register (i.e. flip-flop)

always @(posedge clk)
    my_reg = my_data;


问:
The IE Fieldset Background Color Bleed Bug
Setup:

I have an HTML page with a fieldset
  element. The background color of the
  fieldset element is different from the
  background of the page. The border of
  the fieldset has a slightly darker
  color that the background.

Problem:

In Firefox only the area inside the
  border has the specified background
  color. In IE7 the background color
  flows over the area delimited by the
  border (only at the top).

Question:

What can I do to make the background
  of the fieldset element stay within
  the area delimited by the border on
  IE7?

答:
see this article for how to fix this problem:

http://www.communitymx.com/content/article.cfm?cid=DD9F3

In summary:
"
Since IE's problem seems to extend from the fact that the legend is a child of the fieldset, the way to fix the bug is to disassociate the legend with the fieldset. The legend element has to stay nested within the fieldset element, of course, for the (X)HTML to remain valid, but if we absolutely position it, it will be removed from the flow of the document and treated by elements outside of it — including its parent — as if it didn't exist.
"

OwnerDisplayName: Diego Deberdt

LastEditorDisplayName: Diego Deberdt

OwnerDisplayName: Nils


问:
Know of an OCaml IDE?
Know of an OCAML/CAML IDE?  Especially one that runs on Linux?</p>

答:
You can try to edit, compile and run simple Ocaml codes even online with ideone.
There are also apps for mobile devices, which allows you to program/experiment with your smartphone.</p>

OwnerDisplayName: Dustin

ContentLicense: CC BY-SA 4.0

Title: Know of an OCaml IDE?


问:
Inflating custom RowView override ListView click events?
I'm running into an issue after inflating my custom RowView into my ListAdapter that I've bound to my ListView. I have a ItemClick event registered on my ListView item and when it is clicked, I expect the DetailView to be opened. However, it appears my click event is being overwritten as nothing happens when I click on the ListView item.

Here is a sample of the ExplorerActivity class that uses the ListView:

```<code>protected override void OnCreate(Bundle savedInstanceState)
{
        base.OnCreate(savedInstanceState);

        SetContentView(Resource.Layout.ExplorerView);

        exampleListView = FindViewById<ListView>(Resource.Id.exampleListView);

        string dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal),
                                 "TestDb.db3");

        SQLiteConnection myConn = new SQLiteConnection(dbPath);

        allItems = dbHelper.GetAllItems();

        exampleListView.Adapter = new exampleListAdapter(this, allItems);

        exampleListView.ItemClick += exampleListView_ItemClick;
}
</code>```

Sample ListAdapter code:

```<code>public override View GetView(int position, View convertView, ViewGroup parent)
{
    var item = items[position];

    if (convertView == null)
    {
        convertView = context.LayoutInflater.Inflate(Resource.Layout.CustomRowView, null);
    }

    convertView.FindViewById<TextView>(Resource.Id.ItemTextView).Text = item.Name;

}
</code>```

If I inflate a custom RowView, do I lose the click events I've registered on the ListView items? I've not been able to add the event to the entire customRowView in the ListAdapter, so I assumed it would be a ListView.ItemClick event.

Are my click events on the ListView being disregarded by the custom RowView? Each instance of a RowView is still a ListView item, correct?

I can't seem to find the proper object, e.g. RowView isn't a thing, so how do I bind an event the the ListView item after being inflating my custom RowView?

I've tried setting breakpoints in the explorer activity, but they are never hit, which is why I think the event no longer is registered on the ListView_ItemClick.

答:
If I inflate a custom RowView, do I lose the click events I've registered on the ListView items?

No, you won't lose the item click event of ListView. Item click event should be triggered correctly.

Are my click events on the ListView being disregarded by the custom RowView? Each instance of a RowView is still a ListView item, correct?

I made a basic demo for test, the Item click event can be triggered correctly. You can try my demo here

I can't seem to find the proper object, e.g. RowView isn't a thing, so how do I bind an event the the ListView item after being inflating my custom RowView?

One way is to bind the Item Click event of ListView. Other way is to bind click event to the inflated view:

```<code>public override View GetView(int position, View convertView, ViewGroup parent)
{
    var item = mList[position];

    if (convertView == null)
    {
        convertView = mContext.LayoutInflater.Inflate(Resource.Layout.CustomRowView,null);
    }
    var btn = convertView.FindViewById<Button>(Resource.Id.mBtn);
    btn.Click += Btn_Click;
    return convertView;
}

private void Btn_Click(object sender, EventArgs e)
{
    //do your job here
}
</code>```

Updates:

The issue lies on the buttons, once the buttons are added to the row view, the ItemClick doesn't work. If you want the ItemClick to work, you need to add android:focusable="false" and android:focusableInTouchMode="false" to every button like below:

```<code><Button
    android:id="@+id/btnClick"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:text="Click Me"/>
</code>```

Body:
I'm running into an issue after inflating my custom RowView into my ListAdapter that I've bound to my ListView. I have a ItemClick event registered on my ListView item and when it is clicked, I expect the DetailView to be opened. However, it appears my click event is being overwritten as nothing happens when I click on the ListView item.

Here is a sample of the ExplorerActivity class that uses the ListView:

protected override void OnCreate(Bundle savedInstanceState)
{
        base.OnCreate(savedInstanceState);

        SetContentView(Resource.Layout.ExplorerView);

        exampleListView = FindViewById<ListView>(Resource.Id.exampleListView);

        string dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal),
                                 "TestDb.db3");

        SQLiteConnection myConn = new SQLiteConnection(dbPath);

        allItems = dbHelper.GetAllItems();

        exampleListView.Adapter = new exampleListAdapter(this, allItems);

        exampleListView.ItemClick += exampleListView_ItemClick;
}

Sample ListAdapter code:

public override View GetView(int position, View convertView, ViewGroup parent)
{
    var item = items[position];

    if (convertView == null)
    {
        convertView = context.LayoutInflater.Inflate(Resource.Layout.CustomRowView, null);
    }

    convertView.FindViewById<TextView>(Resource.Id.ItemTextView).Text = item.Name;

}

If I inflate a custom RowView, do I lose the click events I've registered on the ListView items? I've not been able to add the event to the entire customRowView in the ListAdapter, so I assumed it would be a ListView.ItemClick event.

Are my click events on the ListView being disregarded by the custom RowView? Each instance of a RowView is still a ListView item, correct?

I can't seem to find the proper object, e.g. RowView isn't a thing, so how do I bind an event the the ListView item after being inflating my custom RowView?

I've tried setting breakpoints in the explorer activity, but they are never hit, which is why I think the event no longer is registered on the ListView_ItemClick.

Body:
If I inflate a custom RowView, do I lose the click events I've registered on the ListView items?

No, you won't lose the item click event of ListView. Item click event should be triggered correctly.

Are my click events on the ListView being disregarded by the custom RowView? Each instance of a RowView is still a ListView item, correct?

I made a basic demo for test, the Item click event can be triggered correctly. You can try my demo here

I can't seem to find the proper object, e.g. RowView isn't a thing, so how do I bind an event the the ListView item after being inflating my custom RowView?

One way is to bind the Item Click event of ListView. Other way is to bind click event to the inflated view:

public override View GetView(int position, View convertView, ViewGroup parent)
{
    var item = mList[position];

    if (convertView == null)
    {
        convertView = mContext.LayoutInflater.Inflate(Resource.Layout.CustomRowView,null);
    }
    var btn = convertView.FindViewById<Button>(Resource.Id.mBtn);
    btn.Click += Btn_Click;
    return convertView;
}

private void Btn_Click(object sender, EventArgs e)
{
    //do your job here
}

Updates:

The issue lies on the buttons, once the buttons are added to the row view, the ItemClick doesn't work. If you want the ItemClick to work, you need to add android:focusable="false" and android:focusableInTouchMode="false" to every button like below:

<Button
    android:id="@+id/btnClick"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:text="Click Me"/>


问:
Why is my ruby loop not ending?
I am new to ruby!
Here is my code:

```<code>require 'sdk'

def get_teams_from_evident
   teams_api = SDK::Team.all
   teams = []
   loop do
     teams_api.each do |team|
       puts team.name
       teams << team
     end
     if teams_api.next_page?
       team_api = teams_api.page(teams_api.next_page_number)
     else
       break
     end
   end
   teams
 end
</code>```

When i run it with

```<code>$ruby my_script.rb
</code>```

the program never exits, the loop remains hanging...

What am I doing wrong?

答:
As the comments have said, the only way your loop can end is if teams_api.next_page? returns false. If the loop continues to loop for ever, then you can infer that teams_api.next_page? always returns true. That doesn't seem logical though, your next step should be to check the documentation of #next_page?.

That's not the only way your loop can hang though. I've been fooled before, thinking my loop was spinning when in fact a function call inside the loop had frozen. You could add puts 'loop start' at the start of the loop to make sure, or you could use a gem like Byebug to step through the code.

Title: Why is my ruby loop not ending?

Body:
I am new to ruby!
Here is my code:

require 'sdk'

def get_teams_from_evident
   teams_api = SDK::Team.all
   teams = []
   loop do
     teams_api.each do |team|
       puts team.name
       teams << team
     end
     if teams_api.next_page?
       team_api = teams_api.page(teams_api.next_page_number)
     else
       break
     end
   end
   teams
 end

When i run it with

$ruby my_script.rb

the program never exits, the loop remains hanging...

What am I doing wrong?