问:
Rshiny: Generating Dynamic HTML using loops
I am interested to generate a list of divs each with dynamic values in Rshiny such as below.

```<code><div>1</div>
<div>2</div>
<div>3</div>
.
.
.
<div>9</div>
</code>```

I did this by (on the server) looping through a list and vector of each element of the list. I render a UI output$x1, output$x2, output$x3, etc. Similarly, I loop through to create 9 UI elements on the ui function. The code is as below:

```<code># Define UI for app that draws a histogram ----
ui <- fluidPage(
  fluidRow(
    lapply(1:9, function(i) {
      uiOutput(paste0('x', i))
    })

  )

)

# Define server logic required to draw a histogram ----
server <- function(input, output) {

  obj<- list(

    col1=1:3,
    col2=4:5,
    col3=5:9

  )

  for(elem in obj){
    for(num in elem){
      print(paste0(num))
      output[[paste0(x,num)]]<-renderUI({
        tags$div(
          tags$p(
            num
          )
        )
      })
    }
  }

}
</code>```

shinyApp(ui, server)
I have two problems with my code:

1) Nothing is on my UI for some reason unknown to me.

2) I believe when ui is printed out, it will only print the final value of the div. For example, output$x1 = 9,  output$x2= 9, etc

答:
Use tagList in the UI, with a do.call

paste("x", not paste(x

use local to define outputs in a loop, otherwise you would get only the last one

```<code>ui <- fluidPage(
  fluidRow(
    do.call(tagList, lapply(1:9, function(i) {
      uiOutput(paste0('x', i))
    }))
  )
)

server <- function(input, output) {

  obj <- list(
    col1=1:3,
    col2=4:5,
    col3=5:9
  )

  for(elem in obj){
    for(num in elem){
      local({
        mynum <- num
        output[[paste0("x",mynum)]] <- renderUI({
          tags$div(
            tags$p(
              mynum
            )
          )
        })
      })
    }
  }

}
shinyApp(ui, server)
</code>```

Body:
I am interested to generate a list of divs each with dynamic values in Rshiny such as below.

1

2

3

.
.
.

9

I did this by (on the server) looping through a list and vector of each element of the list. I render a UI output$x1, output$x2, output$x3, etc. Similarly, I loop through to create 9 UI elements on the ui function. The code is as below:

# Define UI for app that draws a histogram ----
ui <- fluidPage(
  fluidRow(
    lapply(1:9, function(i) {
      uiOutput(paste0('x', i))
    })

  )

)

# Define server logic required to draw a histogram ----
server <- function(input, output) {

  obj<- list(

    col1=1:3,
    col2=4:5,
    col3=5:9

  )

  for(elem in obj){
    for(num in elem){
      print(paste0(num))
      output[[paste0(x,num)]]<-renderUI({
        tags$div(
          tags$p(
            num
          )
        )
      })
    }
  }

}

shinyApp(ui, server)
I have two problems with my code:

1) Nothing is on my UI for some reason unknown to me.

2) I believe when ui is printed out, it will only print the final value of the div. For example, output$x1 = 9,  output$x2= 9, etc

Body:
Use tagList in the UI, with a do.call

paste("x", not paste(x

use local to define outputs in a loop, otherwise you would get only the last one

ui <- fluidPage(
  fluidRow(
    do.call(tagList, lapply(1:9, function(i) {
      uiOutput(paste0('x', i))
    }))
  )
)

server <- function(input, output) {

  obj <- list(
    col1=1:3,
    col2=4:5,
    col3=5:9
  )

  for(elem in obj){
    for(num in elem){
      local({
        mynum <- num
        output[[paste0("x",mynum)]] <- renderUI({
          tags$div(
            tags$p(
              mynum
            )
          )
        })
      })
    }
  }

}
shinyApp(ui, server)


来源: stackexchange

问:
How to "Pass configuration data to your plug-in" and what's the purpose of the same ? Any real time scenario with example?
What's the use of passing configuration data to plugin and how to do this ?

https://learn.microsoft.com/en-us/powerapps/developer/common-data-service/write-plug-in

Pass configuration data to your plug-in
When you register a plug-in you have the ability to pass configuration data to it. Configuration data allows you to define how a specific instance of a registered plug-in should behave. This information is passed as string data to parameters in the constructor of your class. There are two parameters: unsecure and secure. Use the first unsecure parameter for data that you don't mind if people can see. Use the second secure parameter for sensitive data.

The following code shows the three possible signatures for a plug-in class named SamplePlugin.

```<code>public SamplePlugin()
public SamplePlugin(string unsecure)
public SamplePlugin(string unsecure, string secure)
</code>```

答:
What's the use of passing configuration data to plugin and how to do this ?

Sometimes we may need to do configuration items just like connection strings or log settings in application development files, web.config or app.config. Similarly, You can pass this from the plugin step when you are registering using plugin registration tool.

The biggest difference that you’ll seen mentioned between these two settings is that the secure configuration is only viewable by CRM Administrators while the unsecure configuration is viewable by any CRM user. However, there’s another important difference: the unsecure config will automatically move between environments with your CRM solutions.
This means that even a setting that you might consider fine to let any CRM user read like the URL of a website or settings to enable more verbose trace logging in a development environment might be more appropriate in the secure configuration if you want it to be different between environments. Otherwise, you have to worry about overriding the unsecure config setting in production with the value you have in your development environment every time you import a solution containing the plugin step.

Any real time scenario with example?

Web service credentials (secure)

Website URL that differs between environments (secure)

Log settings that you don’t want to move with a CRM solution (secure)

Template string that you’d want to move with a CRM solution (unsecure)

Constants that you’d want to move with a solution like “MaxRetries” or “NumberOfDaysToFollowUp” (unsecure)

Reference

ContentLicense: CC BY-SA 4.0

Body:
What's the use of passing configuration data to plugin and how to do this ?

https://learn.microsoft.com/en-us/powerapps/developer/common-data-service/write-plug-in

Pass configuration data to your plug-in
When you register a plug-in you have the ability to pass configuration data to it. Configuration data allows you to define how a specific instance of a registered plug-in should behave. This information is passed as string data to parameters in the constructor of your class. There are two parameters: unsecure and secure. Use the first unsecure parameter for data that you don't mind if people can see. Use the second secure parameter for sensitive data.

The following code shows the three possible signatures for a plug-in class named SamplePlugin.

public SamplePlugin()
public SamplePlugin(string unsecure)
public SamplePlugin(string unsecure, string secure)


问:
Select-Option returns every option not just selected option
I've created a select list with options, and when an option is selected I want to be able to read what the option that was selected was.

When I try read the option it returns the full list of every option that was available to choose.

The options are created from an array and displayed using *ngFor.

.component.html:

```<code><form action="">
    <select id ="fruitSelect" (change)="fruity()" name="fruitSelect" autofocus >
      <option>Enter/Select Fruit</option>
      <option  *ngFor="let fruit of fruits" value="fruit">{{fruit}}</option>
    </select>
  </form>
</code>```

.component.ts:

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  fruits: any = ['Apple', 'Pear', 'Banana', 'Orange']

  fruity() {
    var e = document.getElementById("fruitSelect")
    console.log(e.textContent)
  }
}
</code>```

View example here

Currently, this returns Enter/Select FruitApplePearBananaOrange, I want just Orange for example.

How do I return just the selected option?
Also, I do not want to have a submit button, I want the function to run when the option changes hence the use of (change).

答:
You have to set [(ngModel)]="selectedFruit" (change)="fruity($event)" or (change)="fruity($event.target.value)"

Try this:

```<code><select id ="fruitSelect" (change)="fruity($event)" name="fruitSelect" autofocus [(ngModel)]="selectedFruit">
  <option>Enter/Select Fruit</option>
  <option  *ngFor="let fruit of fruits" [value]="fruit">{{fruit}}</option>
</select>
</code>```

TS:

```<code> fruity(selectedValue) {
    console.log(selectedValue)
  }
</code>```

Body:
I've created a select list with options, and when an option is selected I want to be able to read what the option that was selected was.

When I try read the option it returns the full list of every option that was available to choose.

The options are created from an array and displayed using *ngFor.

.component.html:

<form action="">
    <select id ="fruitSelect" (change)="fruity()" name="fruitSelect" autofocus >
      <option>Enter/Select Fruit</option>
      <option  *ngFor="let fruit of fruits" value="fruit">{{fruit}}</option>
    </select>
  </form>

.component.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  fruits: any = ['Apple', 'Pear', 'Banana', 'Orange']

  fruity() {
    var e = document.getElementById("fruitSelect")
    console.log(e.textContent)
  }
}

View example here

Currently, this returns Enter/Select FruitApplePearBananaOrange, I want just Orange for example.

How do I return just the selected option?
Also, I do not want to have a submit button, I want the function to run when the option changes hence the use of (change).

Body:
You have to set [(ngModel)]="selectedFruit" (change)="fruity($event)" or (change)="fruity($event.target.value)"

Try this:

<select id ="fruitSelect" (change)="fruity($event)" name="fruitSelect" autofocus [(ngModel)]="selectedFruit">
  <option>Enter/Select Fruit</option>
  <option  *ngFor="let fruit of fruits" [value]="fruit">{{fruit}}</option>
</select>

TS:

 fruity(selectedValue) {
    console.log(selectedValue)
  }


问:
How do I reinterpret_cast between any two types?
I would like to re-declare the type of a given variable, but unfortunately reinterpret_cast<> does not help here. This line:

```<code>reinterpret_cast<std::vector<double>>(std::string("Hello"));
</code>```

results in the following compiler error:

```<code>invalid cast from type 'std::string {aka std::basic_string<char>}' to type 'std::vector<double>'
</code>```

Is there a different, clean approach?

Notes:

I know that reinterpret_cast<> is not a proper conversion. I really do only want to re-declare the type here. Some code around this line will make sure it is only performed when appropriate

Why actually does this line above not work?

I am aware of this option, which I think is too messy: *reinterpret_cast(&OldType)

Edit/Some context: This line will be part of a templated function, with:

```<code>reinterpret_cast<T>(std::string())
</code>```

For T == std::string this is completely fine, but unfortunately the compiler will also try to instantiate (but at runtime never use) it for T == std::vector<>. And this is C++11, so there is no static_if.

答:
For T == std::string this is completely fine, but unfortunately the compiler will also try to instantiate (but at runtime never use) it for T == std::vector<>. And this is C++11, so there is no static_if.

In C++17, as you said, you can use if constexpr:

```<code>template <typename T>
void foo(const T& value)
{
    bar(value);

    if constexpr (std::is_same<std::string, T>::value) {
        // Specific code for string
    } else constexpr (std::is_same<std::vector<int>, T>::value) {
        // specific code for vector...
    }
    // ...
}
</code>```

Prior to C++17, you might use overloads, potentially with tag dispatching, SFINAE.

```<code>void foo_specific(const std::string& s)
{
    // Specific code for string
}

void foo_specific(const std::vector<T>& v)
{
    // Specific code for vector
}

template <typename T, std::enable_if_t<std::is_integral<T>::value>, int> = 0>
void foo_specific(const T& n)
{
    // Specific code for integral
}

// ...

template <typename T>
void foo(const T& value)
{
    bar(value);

    foo_specific(value);

    // ...
}
</code>```

Body:
I would like to re-declare the type of a given variable, but unfortunately reinterpret_cast<> does not help here. This line:

reinterpret_cast<std::vector<double>>(std::string("Hello"));

results in the following compiler error:

invalid cast from type 'std::string {aka std::basic_string<char>}' to type 'std::vector<double>'

Is there a different, clean approach?

Notes:

I know that reinterpret_cast<> is not a proper conversion. I really do only want to re-declare the type here. Some code around this line will make sure it is only performed when appropriate

Why actually does this line above not work?

I am aware of this option, which I think is too messy: *reinterpret_cast(&OldType)

Edit/Some context: This line will be part of a templated function, with:

reinterpret_cast<T>(std::string())

For T == std::string this is completely fine, but unfortunately the compiler will also try to instantiate (but at runtime never use) it for T == std::vector<>. And this is C++11, so there is no static_if.

Body:
For T == std::string this is completely fine, but unfortunately the compiler will also try to instantiate (but at runtime never use) it for T == std::vector<>. And this is C++11, so there is no static_if.

In C++17, as you said, you can use if constexpr:

template <typename T>
void foo(const T& value)
{
    bar(value);

    if constexpr (std::is_same<std::string, T>::value) {
        // Specific code for string
    } else constexpr (std::is_same<std::vector<int>, T>::value) {
        // specific code for vector...
    }
    // ...
}

Prior to C++17, you might use overloads, potentially with tag dispatching, SFINAE.

void foo_specific(const std::string& s)
{
    // Specific code for string
}

void foo_specific(const std::vector<T>& v)
{
    // Specific code for vector
}

template <typename T, std::enable_if_t<std::is_integral<T>::value>, int> = 0>
void foo_specific(const T& n)
{
    // Specific code for integral
}

// ...

template <typename T>
void foo(const T& value)
{
    bar(value);

    foo_specific(value);

    // ...
}


问:
autofocus not working after remove and adding again to the dom
I trying to set focus on show:

```<code><div>
  <div style="height: 50px; width: 100%" (click)="inEdit=true">
    <div *ngIf="!inEdit">
      bla
    </div>
    <mat-form-field *ngIf="inEdit">
      <input (blur)="inEdit=false"
      autofocus matInput >
    </mat-form-field>
  </div>
</div>
</code>```

it is work only on first click.

stackbliz

答:
We can achieve all DOM related operations in Angular using @ViewChild decorator whic comes from angular core.

Related Template

HTML :

```<code><input type="text" #inputName>
</code>```

Component :

```<code>import { Component,AfterViewInit,ViewChild ElementRef} from '@angular/core';
...

@ViewChild('inputName') inputEl:ElementRef;

ngAfterViewInit() {
      setTimeout(() => this.inputEl.nativeElement.focus());
}
</code>```

Using this ElementRef we can do dynamic DOM(Component) Rendering.

Note:

Make sure before going to use ElememntRef,All DOM is rendered in local browser

Body:
I trying to set focus on show:

      bla

    <mat-form-field *ngIf="inEdit">
      <input (blur)="inEdit=false"
      autofocus matInput >
    </mat-form-field>

it is work only on first click.

stackbliz

Body:
We can achieve all DOM related operations in Angular using @ViewChild decorator whic comes from angular core.

Related Template

HTML :

<input type="text" #inputName>

Component :

import { Component,AfterViewInit,ViewChild ElementRef} from '@angular/core';
...

@ViewChild('inputName') inputEl:ElementRef;

ngAfterViewInit() {
      setTimeout(() => this.inputEl.nativeElement.focus());
}

Using this ElementRef we can do dynamic DOM(Component) Rendering.

Note:

Make sure before going to use ElememntRef,All DOM is rendered in local browser


问:
Why *this* is not *this*?
I just wrote this piece of code to represent this error that is killing me (Grrr!)

I wonder why when I get error: method undefined I have checked in Safari and this variable inside parserDidStart() method is not of type EpisodeController it is of type EpisodeFeedParser why is this?

```<code><html>
<head>
<script type="text/javascript">
var EpisodeFeedParser = function(url){
    this.url = url;
    this.didStartCallback = null;
};
EpisodeFeedParser.prototype.parse = function(doc){
    this.didStartCallback(this);
};

var EpisodeController = function(){
    this.episodes = new Array();
    this.parser = null; //lazy
};
EpisodeController.prototype.parserDidStart = function(parser){
    console.log("here *this* is not of type EpisodeController but it is EpisodeFeedParser Why?");
    this.testEpi(); //**********ERROR HERE!***********
};
EpisodeController.prototype.fetchEpisodes = function(urlString){
    if(urlString !== undefined){
        if(parser === undefined){
            var parser = new EpisodeFeedParser(urlString);
            parser.didStartCallback = this.parserDidStart;
            this.parser = parser;
        }
        this.parser.parse();
    }
};
EpisodeController.prototype.testEpi = function(){
console.log("it worked!");
};

function testEpisode(){
    var controller = new EpisodeController();
    controller.fetchEpisodes("myurl");
}
</script>
</head>
<body>
<button type="button" onclick="testEpisode()">press me</button>
</body>
</html>
</code>```

答:
```<code>EpisodeFeedParser.prototype.parse = function(doc){
    this.didStartCallback(this);
};
</code>```

I don't understand why you'd expect this to be anything other than an EpisodeFeedParser.

ContentLicense: CC BY-SA 3.0

Title: Why *this* is not *this*?

Body:
I just wrote this piece of code to represent this error that is killing me (Grrr!)

I wonder why when I get error: method undefined I have checked in Safari and this variable inside parserDidStart() method is not of type EpisodeController it is of type EpisodeFeedParser why is this?

<button type="button" onclick="testEpisode()">press me</button>

Body:
EpisodeFeedParser.prototype.parse = function(doc){
    this.didStartCallback(this);
};

I don't understand why you'd expect this to be anything other than an EpisodeFeedParser.


问:
Parse page to get input and then submit post including this input value
I want to parse page where is form and this form includes token input
need to take this token value and send with my inputs

this is curl code what i was using before they added token input

$username = @$_POST['user'];
$password = @$_POST['password'];
$to = @$_POST['to'];
$text = @$_POST['text'];
$loginUrl = '';
$sendUrl = '';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $loginUrl);
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "user=$username&password=$password");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch)."/n";
}
//sending
curl_setopt($ch, CURLOPT_URL, $sendUrl);
curl_setopt($ch, CURLOPT_POSTFIELDS, "recipients=$to&message_body=$text");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name-send');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie-send.txt');
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch)."/n";
}
echo $answer;
```

<p>This is page what i want to parse</p>

<pre class="lang-html prettyprint-override"><code><form name="user_action" method="post" action="index.php?page=11&lang=ge">
<input type="hidden" name="csrf_token" value="7e71ea58eaaa55986b0fdc71b2d44c92">
<input type="text" id="user" name="user" class="round_border medium_box">
<input type="password" id="password" name="password" class="round_border medium_box">
<input type="submit" value="შესვლა" class="btn red_btn round_border medium">
</form>
</code>```

No i can't post without this token <input type="hidden" name="csrf_token" value="7e71ea58eaaa55986b0fdc71b2d44c92">

And all i need is to to parse this page first to get token and same time send post with this token

答:
@Stevish is correct, you should be using DOMDocument, but i suggest a slightly different approach: loop all input children of the form instead, eg

```<code>$domd=@DOMDocument::loadHTML($answer);
$xp=new DOMXPath($domd);
$inputs=array();
foreach($xp->query("//form[@name='user_action']//input") as $input){
    $inputs[$input->getAttribute("name")]=$input->getAttribute("value");
}
</code>```

that should leave you with

```<code>$inputs=array (
  'csrf_token' => '7e71ea58eaaa55986b0fdc71b2d44c92',
  'user' => '',
  'password' => '',
  '' => 'á¨áá¡ááá',
)
</code>```

.. also you're encoding $to nor $message here, what do you think will happen if $message contains blabla&to=moreblabla ? it would overwrite your previous $to and make your $to variable irrelevant, you need to url-encode that shit, so either

```<code>curl_setopt($ch, CURLOPT_POSTFIELDS, "recipients=".urlencode($to)."&message_body=".urlencode($text));
</code>```

or better yet, use http_build_query,

```<code>curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(
    array(
        "recipients" => $to,
        "message_body" => $text
    )
));
</code>```

... or even better,

```<code>$domd=@DOMDocument::loadHTML($answer);
$xp=new DOMXPath($domd);
$inputs=array();
foreach($xp->query("//form[@name='user_action']//input") as $input){
    $inputs[$input->getAttribute("name")]=$input->getAttribute("value");
}
$inputs["recipients"]=$to;
$inputs["message_body"]=$text;
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($inputs));
</code>```

Body:
I want to parse page where is form and this form includes token input
need to take this token value and send with my inputs

this is curl code what i was using before they added token input

$username = @$_POST['user'];
$password = @$_POST['password'];
$to = @$_POST['to'];
$text = @$_POST['text'];
$loginUrl = '';
$sendUrl = '';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $loginUrl);
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "user=$username&password=$password");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch)."/n";
}
//sending
curl_setopt($ch, CURLOPT_URL, $sendUrl);
curl_setopt($ch, CURLOPT_POSTFIELDS, "recipients=$to&message_body=$text");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name-send');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie-send.txt');
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch)."/n";
}
echo $answer;

This is page what i want to parse

<form name="user_action" method="post" action="index.php?page=11&lang=ge">
<input type="hidden" name="csrf_token" value="7e71ea58eaaa55986b0fdc71b2d44c92">
<input type="text" id="user" name="user" class="round_border medium_box">
<input type="password" id="password" name="password" class="round_border medium_box">
<input type="submit" value="შესვლა" class="btn red_btn round_border medium">
</form>

No i can't post without this token <input type="hidden" name="csrf_token" value="7e71ea58eaaa55986b0fdc71b2d44c92">

And all i need is to to parse this page first to get token and same time send post with this token

Body:
@Stevish is correct, you should be using DOMDocument, but i suggest a slightly different approach: loop all input children of the form instead, eg

$domd=@DOMDocument::loadHTML($answer);
$xp=new DOMXPath($domd);
$inputs=array();
foreach($xp->query("//form[@name='user_action']//input") as $input){
    $inputs[$input->getAttribute("name")]=$input->getAttribute("value");
}

that should leave you with

$inputs=array (
  'csrf_token' => '7e71ea58eaaa55986b0fdc71b2d44c92',
  'user' => '',
  'password' => '',
  '' => 'á¨áá¡ááá',
)

.. also you're encoding $to nor $message here, what do you think will happen if $message contains blabla&to=moreblabla ? it would overwrite your previous $to and make your $to variable irrelevant, you need to url-encode that shit, so either

curl_setopt($ch, CURLOPT_POSTFIELDS, "recipients=".urlencode($to)."&message_body=".urlencode($text));

or better yet, use http_build_query,

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(
    array(
        "recipients" => $to,
        "message_body" => $text
    )
));

... or even better,

$domd=@DOMDocument::loadHTML($answer);
$xp=new DOMXPath($domd);
$inputs=array();
foreach($xp->query("//form[@name='user_action']//input") as $input){
    $inputs[$input->getAttribute("name")]=$input->getAttribute("value");
}
$inputs["recipients"]=$to;
$inputs["message_body"]=$text;
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($inputs));


问:
convert a key value pair into 2 different objects
Let me explain here

```<code>let obj = {manager:XYZ}
//output:[{position:"manager",name:"XYZ"}]
</code>```

you can also use lodash to find the solution

答:
Another option is to use a for-loop:

let obj = {manager:'XYZ'}

let output = [];
for (var key in obj) {
  output.push({ position: key, name: obj[key] });
}

console.log(output);```

Body:
Let me explain here

let obj = {manager:XYZ}
//output:[{position:"manager",name:"XYZ"}]

you can also use lodash to find the solution


问:
Are Multiple Lambda callbacks possible
I have a lambda/server less function that is going to perform several API calls that will take some time. I want to update the user on the front end as each task completed (progress bar style) but the only way I'm aware of to send information back is the callback function, which I can only use once at the end of the whole process.

Is there a way of sending multiple callbacks?

Thanks in advance.

答:
No, you can call AWS Lambda callback only once.
So you can receive result only once: when it is done or failed.

Here is wha related documentation says:

When the callback is called, AWS Lambda continues the Lambda function
  invocation until the event loop is empty.

It means that after callback called - you will receive the response. However, function can finish its work later, but you will not be able to get any new data from function anymore.

Moreover, it is very important to remember, that when you call Lambda you actually make a call to stateless container. So it is impossible to save the state and then read it with the next call. You should never save and rely on any data saved inside of that container.

Possible solution for you can be splitting your job to few chunks and send each chunk for processing separately. Then, upon receiving responses about successful processing of the chunk you can update progress bar.

Title: Are Multiple Lambda callbacks possible


问:
Recyclerview notifyDataSetChanged not called when again go to same activity
In my Requirement having wizard step.So If I am in Second Step.And pressing back.And Now I m in first wizard.And pressing next so it recreate activity.that's why I have put it into OnCreate.

When I go to that activity for first time then My Adapter notifydatasetchange work properly but when I'm go back and again goes to same activity
Notifydatasetchange() not working means onbindviewholder not called.

Even I have Tried to set adapter again but it's not still called.This is my code.What I have missing? Any help is appreciated!

```<code>    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.ProposalInviteOwnersView);
       _lstviewNearByPeople = FindViewById<RecyclerView>(Resource.Id.lstviewNearByPeople);
        _layoutmanager = new LinearLayoutManager(this, LinearLayoutManager.Horizontal, false);
        _lstviewNearByPeople.HasFixedSize = true;
        _lstviewNearByPeople.SetLayoutManager(_layoutmanager);
        BindtoNearByAdapter();
    }

    public void BindtoNearByAdapter()
    {
        try
        {
            if (GlobalConst.LstNearByPeople.Count > 0)
            {
                _lstNearByPeople = new List<Owners>();
                _lstNearByPeople.AddRange(GlobalConst.LstNearByPeople);

                if(_nearByCollaboratorAdapter==null)
                {
                    _lstviewNearByPeople.Visibility = ViewStates.Visible;

                    _nearByCollaboratorAdapter = new NearByCollaboratorAdapter(this, _lstNearByPeople, this, mlastPosition);
                    _lstviewNearByPeople.SetAdapter(_nearByCollaboratorAdapter);

                }
                else
                {
                    _nearByCollaboratorAdapter.updateItems(_lstNearByPeople);

                }

            }
            else
            {
                _noNearByDevicelayout.Visibility = ViewStates.Visible;
                _lstviewNearByPeople.Visibility = ViewStates.Gone;
            }

        }
        catch (System.Exception ex)
        {
            Core.Helpers.GlobalLogic.createCrashReport(ex);
            Toast.MakeText(this, ex.Message.ToString(), ToastLength.Short).Show();
        }
    }

    public class NearByCollaboratorAdapter : RecyclerView.Adapter
{
    public List<Owners> _lstNearByPeople;
    readonly ISelectCollaborator _listner;
    readonly Activity _context;
    protected int mLastPosition;

    public NearByCollaboratorAdapter(Activity context, List<Owners> lstNearByPeople, ISelectCollaborator listner, int _mLastPosition)
    {
        _lstNearByPeople = lstNearByPeople;
        _context = context;
        _listner = listner;
        mLastPosition = _mLastPosition;

    }
    public override int ItemCount => _lstNearByPeople.Count;

    public void updateItems(List<Owners> lstNearByPeople)
    {
        _lstNearByPeople.Clear();
        _lstNearByPeople.AddRange(lstNearByPeople);
        this.NotifyDataSetChanged();
    }

}
</code>```

答:
Implement an onResume method... </p>

```<code>@Override
public void OnResume (){
  super.onResume();
  BindtoNearByAdapter()
}
</code>```

Body:
In my Requirement having wizard step.So If I am in Second Step.And pressing back.And Now I m in first wizard.And pressing next so it recreate activity.that's why I have put it into OnCreate.

When I go to that activity for first time then My Adapter notifydatasetchange work properly but when I'm go back and again goes to same activity
Notifydatasetchange() not working means onbindviewholder not called.

Even I have Tried to set adapter again but it's not still called.This is my code.What I have missing? Any help is appreciated!

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.ProposalInviteOwnersView);
       _lstviewNearByPeople = FindViewById<RecyclerView>(Resource.Id.lstviewNearByPeople);
        _layoutmanager = new LinearLayoutManager(this, LinearLayoutManager.Horizontal, false);
        _lstviewNearByPeople.HasFixedSize = true;
        _lstviewNearByPeople.SetLayoutManager(_layoutmanager);
        BindtoNearByAdapter();
    }

    public void BindtoNearByAdapter()
    {
        try
        {
            if (GlobalConst.LstNearByPeople.Count > 0)
            {
                _lstNearByPeople = new List<Owners>();
                _lstNearByPeople.AddRange(GlobalConst.LstNearByPeople);

                if(_nearByCollaboratorAdapter==null)
                {
                    _lstviewNearByPeople.Visibility = ViewStates.Visible;

                    _nearByCollaboratorAdapter = new NearByCollaboratorAdapter(this, _lstNearByPeople, this, mlastPosition);
                    _lstviewNearByPeople.SetAdapter(_nearByCollaboratorAdapter);

                }
                else
                {
                    _nearByCollaboratorAdapter.updateItems(_lstNearByPeople);

                }

            }
            else
            {
                _noNearByDevicelayout.Visibility = ViewStates.Visible;
                _lstviewNearByPeople.Visibility = ViewStates.Gone;
            }

        }
        catch (System.Exception ex)
        {
            Core.Helpers.GlobalLogic.createCrashReport(ex);
            Toast.MakeText(this, ex.Message.ToString(), ToastLength.Short).Show();
        }
    }

    public class NearByCollaboratorAdapter : RecyclerView.Adapter
{
    public List<Owners> _lstNearByPeople;
    readonly ISelectCollaborator _listner;
    readonly Activity _context;
    protected int mLastPosition;

    public NearByCollaboratorAdapter(Activity context, List<Owners> lstNearByPeople, ISelectCollaborator listner, int _mLastPosition)
    {
        _lstNearByPeople = lstNearByPeople;
        _context = context;
        _listner = listner;
        mLastPosition = _mLastPosition;

    }
    public override int ItemCount => _lstNearByPeople.Count;

    public void updateItems(List<Owners> lstNearByPeople)
    {
        _lstNearByPeople.Clear();
        _lstNearByPeople.AddRange(lstNearByPeople);
        this.NotifyDataSetChanged();
    }

}

Body:
Implement an onResume method...

@Override
public void OnResume (){
  super.onResume();
  BindtoNearByAdapter()
}


问:
How can I ignore a parameter in a URL?
My app decodes URLs and I've noticed that when it hits an "&", the process stops and ignores the rest of the URL. It appears that URLComponents is breaking up the URL into pieces - my required parameter and the one that it believes to be a parameter.

```<code> hxxp://www.g.com/url?u=http://a.com/test&d=another
  - scheme : "hxxp"
  - host : "www.g.com"
  - path : "/url"
  ▿ queryItems : 2 elements
    ▿ 0 : u=http://a.com/test
      - name : "u"
      ▿ value : Optional<String>
        - some : "http://a.com/test"
    ▿ 1 : d=another
      - name : "d"
      ▿ value : Optional<String>
        - some : "another"
</code>```

What I need from above is the full URL after "u=".

Here is the initial call to the function that decodes the string:

```<code>if (fullDecode.contains("?u=")) {
            initialDecode = getQueryStringParameter(urlToAttempt: fullDecode, param: "u")!
</code>```

Here is the function that returns the decoded string:

```<code>func getQueryStringParameter(urlToAttempt: String, param: String) -> String? {
        guard let urlDecoded = URLComponents(string: urlToAttempt) else { return nil }
        print(urlDecoded)
        return urlDecoded.queryItems?.first(where: { $0.name == param })?.value
    }
</code>```

For this code, if the url was "http://www.g.com/url?u=http://a.com/test&d=another", it would return "http://a.com/test" - everything else is stripped away. I'd like it to return "http://a.com/test&d=another"

Is there a way that I'm able to do this with URLComponents, or do I need to do custom code to support this?

Update
If I change the url that's being passed to " hxxp://www.g.com/url?u=http://a.com/test%26d=another", URLComponents returns the full url back with the &d=another intact. I'm now going to try to percent encode the special character before sending to the function and see if that fixes the issue.

Second Update

Here is a heavily modified type of link I need to decode:

```<code>hxxps://ue.pt.com/v2/url?u=https-3A__oe.le.com_-3Fauthkey-3D-2521IB-2DCRV-2DqQ88-26cid-3DBACDF2ED353D-26id-3DBACDF2EFB61D353D-2521549-26parId-3Droot-26o-3DOneUp&d=DwMGaQ&c=WNpQK9bFmT89misLWAzsd66s44iGV-VujF_o4whjrfc&r=Ej_UhLznQMBqt3H3IYBQkjyx4xqdnS9mLiYA&m=HOBrLfxamFr4PYdACIR-A49th_oIe3MW69N7X-E&s=bXWSJ8gaSbKSlNuIf30S7Qsa6RcMKA-EOvP577XUyq0&e=
</code>```

These links are generated, which is why I have no control of how the link is built. I need to be able to decode this link to a legible URL. I have dictionaries for the special obfuscation like "-3A__" is "://" Where the above fails is where you see &d=DwM... It's not encoded, and that's where URLComponents is failing:

```<code>https://oe.le.com/?authkey=!IB-CRV-qQ88&cid=BACDF2ED353D&id=BACDF2EFB6353D!549&parId=root&o=OneUp
</code>```

Does this help?

答:
You can split your URL string with "?u=" as a separator and get the second array element using this function

Otherwise, you can loop on all your queryItems and concatenate them.

Title: How can I ignore a parameter in a URL?

Body:
My app decodes URLs and I've noticed that when it hits an "&", the process stops and ignores the rest of the URL. It appears that URLComponents is breaking up the URL into pieces - my required parameter and the one that it believes to be a parameter.

 hxxp://www.g.com/url?u=http://a.com/test&d=another
  - scheme : "hxxp"
  - host : "www.g.com"
  - path : "/url"
  ▿ queryItems : 2 elements
    ▿ 0 : u=http://a.com/test
      - name : "u"
      ▿ value : Optional<String>
        - some : "http://a.com/test"
    ▿ 1 : d=another
      - name : "d"
      ▿ value : Optional<String>
        - some : "another"

What I need from above is the full URL after "u=".

Here is the initial call to the function that decodes the string:

if (fullDecode.contains("?u=")) {
            initialDecode = getQueryStringParameter(urlToAttempt: fullDecode, param: "u")!

Here is the function that returns the decoded string:

func getQueryStringParameter(urlToAttempt: String, param: String) -> String? {
        guard let urlDecoded = URLComponents(string: urlToAttempt) else { return nil }
        print(urlDecoded)
        return urlDecoded.queryItems?.first(where: { $0.name == param })?.value
    }

For this code, if the url was "http://www.g.com/url?u=http://a.com/test&d=another", it would return "http://a.com/test" - everything else is stripped away. I'd like it to return "http://a.com/test&d=another"

Is there a way that I'm able to do this with URLComponents, or do I need to do custom code to support this?

Update
If I change the url that's being passed to " hxxp://www.g.com/url?u=http://a.com/test%26d=another", URLComponents returns the full url back with the &d=another intact. I'm now going to try to percent encode the special character before sending to the function and see if that fixes the issue.

Second Update

Here is a heavily modified type of link I need to decode:

hxxps://ue.pt.com/v2/url?u=https-3A__oe.le.com_-3Fauthkey-3D-2521IB-2DCRV-2DqQ88-26cid-3DBACDF2ED353D-26id-3DBACDF2EFB61D353D-2521549-26parId-3Droot-26o-3DOneUp&d=DwMGaQ&c=WNpQK9bFmT89misLWAzsd66s44iGV-VujF_o4whjrfc&r=Ej_UhLznQMBqt3H3IYBQkjyx4xqdnS9mLiYA&m=HOBrLfxamFr4PYdACIR-A49th_oIe3MW69N7X-E&s=bXWSJ8gaSbKSlNuIf30S7Qsa6RcMKA-EOvP577XUyq0&e=

These links are generated, which is why I have no control of how the link is built. I need to be able to decode this link to a legible URL. I have dictionaries for the special obfuscation like "-3A__" is "://" Where the above fails is where you see &d=DwM... It's not encoded, and that's where URLComponents is failing:

https://oe.le.com/?authkey=!IB-CRV-qQ88&cid=BACDF2ED353D&id=BACDF2EFB6353D!549&parId=root&o=OneUp

Does this help?


问:
vs. [UIWebView loadRequest:] - optimizing return from iAD to a view with a UIWebView
I have a view that includes a UIWebView as well as an iAD AdBannerView.

To optimize the experience and reduce bandwidth contention - I suspend the UIWebView's network activity when the iAd "detail view" is being loaded and resume it when the user returns from the ad. Currently, I simply do the following:

```<code>-(BOOL)bannerViewActionShouldBegin:(ADBannerView *)banner willLeaveApplication:(BOOL)willLeave
{

    if (self.webView.loading) {
        [self.webView stopLoading];
        self.loadingWasInterrupted = TRUE;
    }
    return YES;
}

-(void)bannerViewActionDidFinish:(ADBannerView *)banner
{
    if (self.loadingWasInterrupted) {
        //Should use loadRequest: instead?
        [self.webView reload];
    }
}
</code>```

I'm trying to understand if it there is any difference between calling reload vs. loadRequest: a second time, and if so, which is more efficient.

I'm guessing reload simply just saves you having to hold onto the request object and really does the same thing but I'd like to know for sure. The docs and header don't offer any clue.

I understand I could pick apart the network activity to understand what's happening but would appreciate any insight from someone who has looked at this before or who generally understands if reload behavior differs from loadRequest at all. Thank you.

答:
I'm guessing here, but I believe the reload is doing a loadRequest: internally. If you are really intent on testing this you cold add a temporary subclass to UIWebView and override the reload and loadRequest methods just for the sake of logging.</p>

```<code>- (void)reload
{
    NSLog(@"reload called");
    [super reload];
}

- (void)loadRequest:(NSURLRequest *)request
{
    NSLog(@"loadRequest called");
    [super loadRequest:request];
}
</code>```

Body:
I have a view that includes a UIWebView as well as an iAD AdBannerView.

To optimize the experience and reduce bandwidth contention - I suspend the UIWebView's network activity when the iAd "detail view" is being loaded and resume it when the user returns from the ad. Currently, I simply do the following:

-(BOOL)bannerViewActionShouldBegin:(ADBannerView *)banner willLeaveApplication:(BOOL)willLeave
{

    if (self.webView.loading) {
        [self.webView stopLoading];
        self.loadingWasInterrupted = TRUE;
    }
    return YES;
}

-(void)bannerViewActionDidFinish:(ADBannerView *)banner
{
    if (self.loadingWasInterrupted) {
        //Should use loadRequest: instead?
        [self.webView reload];
    }
}

I'm trying to understand if it there is any difference between calling reload vs. loadRequest: a second time, and if so, which is more efficient.

I'm guessing reload simply just saves you having to hold onto the request object and really does the same thing but I'd like to know for sure. The docs and header don't offer any clue.

I understand I could pick apart the network activity to understand what's happening but would appreciate any insight from someone who has looked at this before or who generally understands if reload behavior differs from loadRequest at all. Thank you.

Body:
I'm guessing here, but I believe the reload is doing a loadRequest: internally. If you are really intent on testing this you cold add a temporary subclass to UIWebView and override the reload and loadRequest methods just for the sake of logging.

- (void)reload
{
    NSLog(@"reload called");
    [super reload];
}

- (void)loadRequest:(NSURLRequest *)request
{
    NSLog(@"loadRequest called");
    [super loadRequest:request];
}


问:
Turn off Hammer JS events in Angular 2 to allow scrolling
I am using Hammer JS for swipeleft and swiperight events, but the user still needs to be able to scroll up and down.  I was able to capture the swipeup and swipedown events, but what I really want to do is disable them (and panup and pandown).  How would I do that inside of Angular 2?

Under Manager there is a method off that unbinds an event, I just don't know how to call this from within Angular 2.

Manager off method doc

Or is there another way to override Hammer JS to allow normal scrolling?

答:
You can create one .ts file in my case it is hammer.config.ts
In that file put following code,

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

declare var Hammer: any;

export class AppHammerConfig extends HammerGestureConfig {
    buildHammer(element: HTMLElement) {
        let mc = new Hammer(element, {
            touchAction: "auto",
        });
        return mc;
    }
}
</code>```

After that in your app.module.ts file put following object in providers,

```<code>{ provide: HAMMER_GESTURE_CONFIG, useClass: AppHammerConfig }
</code>```

It will look like,

```<code> providers: [
    //other_providers,
    { provide: HAMMER_GESTURE_CONFIG, useClass: AppHammerConfig }
  ]
</code>```

Don't forget to import  HAMMER_GESTURE_CONFIG in app.module.ts like,

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

Also you need to import your created class AppHammerConfig from its location like,

```<code>import { AppHammerConfig } from '--path--/hammer.config';
</code>```

This works for me.!

Body:
You can create one .ts file in my case it is hammer.config.ts
In that file put following code,

import { HammerGestureConfig } from '@angular/platform-browser';

declare var Hammer: any;

export class AppHammerConfig extends HammerGestureConfig {
    buildHammer(element: HTMLElement) {
        let mc = new Hammer(element, {
            touchAction: "auto",
        });
        return mc;
    }
}

After that in your app.module.ts file put following object in providers,

{ provide: HAMMER_GESTURE_CONFIG, useClass: AppHammerConfig }

It will look like,

 providers: [
    //other_providers,
    { provide: HAMMER_GESTURE_CONFIG, useClass: AppHammerConfig }
  ]

Don't forget to import  HAMMER_GESTURE_CONFIG in app.module.ts like,

import { HAMMER_GESTURE_CONFIG } from '@angular/platform-browser';

Also you need to import your created class AppHammerConfig from its location like,

import { AppHammerConfig } from '--path--/hammer.config';

This works for me.!


问:
What is the efficient way to calculate human eye contrast difference for RGB values?
In order to check if two colors in grayscale will be too close to be distinguished by the human eye. I want to be able to generate a warning to the user if 'dangerous' colors are picked. Hence based on the result we can decide if for people with bad eye sight we should change one of the two colors to white or black to enhance the readable contrast.

For example the Hex colours #9d5fb0 (purple) and #318261 (green) will turn into almost the same grey tone. Seen in HSB the B value is just 1% different from the other and therefor the healthy human eye cannot really see the difference. Or for the same the 8-Bit K value in this case differs 2%.

I have learned the luminance method is the more sophisticated way for judging grey tones the way the human eye sees colors. Yet how to do this programatically is beyond my current understanding. I could write it either PHP or JS once I understand the math.

In order to either pick values from CSS, from a screen pixel or from a file as image object, I guess we should always handle the input as RGB right?

something like:

```<code>$result = grayScaleDifference('#9d5fb0','#318261');
</code>```

or

```<code>$result = 8bitK_difference('#9d5fb0','#318261');
</code>```

or

```<code>$result = luminanceDifference('#9d5fb0','#318261');
</code>```

So what is the best script style formula to compare them without changing or converting the actual image or color objects?

答:
Just for a better syntax and ease of use I have put the whole theory into one single parser within an object that runs as follows.

The parser will compute these values in one step from color 318261:

A returned object will look like:

```<code>hex: "#318261"
rgb: {
  r: 49,
  g: 130,
  b: 97
}
int: 10313648
dec: {
  r: 0.19215686274509805,
  g: 0.5098039215686274,
  b: 0.3803921568627451
}
lin: {
  r: 0.030713443732993635,
  g: 0.2232279573168085,
  b: 0.11953842798834562
}
y: 0.17481298771137443
lstar: 48.86083783595441
</code>```

JavaScript can call the object internal parser with a Hex color string as a parameter. The hex string can look like either 000 or #000 or 000000 or #000000. There are two ways to process the result.

A: take the returned object as a whole into a variable:

```<code>var result = Color_Parser.parseHex('318261');
var lstar = result.lstar;
</code>```

B: parse once and thereafter access parts of the last parser result. For example pick only the the L* contrast value would be just:

```<code>Color_Parser.parseHex('#ABC');
var lstar = Color_Parser.result.lstar;
</code>```

Here is the full code:

```<code>const Color_Parser = {
  version: '1.0.0.beta',
  name: 'Color_Parser',
  result: null, // the parser output
  loging: true, // set to false to disable writing each step to console log
  parseHex: function(_input) {
    if (this.loging) {
      console.log(this.name + ', input: ' + _input);
    }
    this.result = {};
    // pre flight checks
    if (!_input) {
      this.result.error = true;
      console.log(this.name + ', error');
      return this.result;
    }
    // first convert shorthand Hex strings to full strings
    this.result.hex = String(_input);
    if (this.result.hex.length == 3) {
      this.result.hex = '#' + this.result.hex.substr(0, 1) + this.result.hex.substr(0, 1) + this.result.hex.substr(1, 1) + this.result.hex.substr(1, 1) + this.result.hex.substr(2, 1) + this.result.hex.substr(2, 1);
    }
    if (this.result.hex.length == 4) {
      this.result.hex = '#' + this.result.hex.substr(1, 1) + this.result.hex.substr(1, 1) + this.result.hex.substr(2, 1) + this.result.hex.substr(2, 1) + this.result.hex.substr(3, 1) + this.result.hex.substr(3, 1);
    }
    if (this.result.hex.length == 6) {
      this.result.hex = '#' + this.result.hex;
    }
    if (this.loging) {
      console.log(this.name + ', added to result: ' + this.result.hex);
    }
    // second get int values from the string segments as channels
    this.result.rgb = {
      r: null,
      g: null,
      b: null
    };
    this.result.rgb.r = parseInt(this.result.hex.substr(1, 2), 16);
    this.result.rgb.g = parseInt(this.result.hex.substr(3, 2), 16);
    this.result.rgb.b = parseInt(this.result.hex.substr(5, 2), 16);
    if (this.loging) {
      console.log(this.name + ', added to result: ' + this.result.rgb);
    }
    // third get the combined color int value
    this.result.int = ((this.result.rgb.r & 0x0ff) << 16) | ((this.result.rgb.g & 0x0ff) << 8) | (this.result.rgb.b & 0x0ff);
    if (this.loging) {
      console.log(this.name + ', added to result: ' + this.result.int);
    }
    // fourth turn 8 bit channels to decimal
    this.result.dec = {
      r: null,
      g: null,
      b: null
    };
    this.result.dec.r = this.result.rgb.r / 255.0; // red channel to decimal
    this.result.dec.g = this.result.rgb.g / 255.0; // green channel to decimal
    this.result.dec.b = this.result.rgb.b / 255.0; // blue channel to decimal
    if (this.loging) {
      console.log(this.name + ', added to result: ' + this.result.dec);
    }
    // fifth linearize each channel
    this.result.lin = {
      r: null,
      g: null,
      b: null
    };
    for (var i = 0, len = 3; i < len; i++) {
      if (this.result.dec[['r', 'g', 'b'][i]] <= 0.04045) {
        this.result.lin[['r', 'g', 'b'][i]] = this.result.dec[['r', 'g', 'b'][i]] / 12.92;
      } else {
        this.result.lin[['r', 'g', 'b'][i]] = Math.pow(((this.result.dec[['r', 'g', 'b'][i]] + 0.055) / 1.055), 2.4);
      }
    }
    if (this.loging) {
      console.log(this.name + ', added to result: ' + this.result.lin);
    }
    // get Y from linear result
    this.result.y = (0.2126 * (this.result.lin.r)); // red channel
    this.result.y += (0.7152 * (this.result.lin.g)); // green channel
    this.result.y += (0.0722 * (this.result.lin.b)); // blue channel
    if (this.loging) {
      console.log(this.name + ', added to result: ' + this.result.y);
    }
    // get L* contrast from Y
    if (this.result.y <= (216 / 24389)) {
      this.result.lstar = this.result.y * (24389 / 27);
    } else {
      this.result.lstar = Math.pow(this.result.y, (1 / 3)) * 116 - 16;
    }
    if (this.loging) {
      console.log(this.name + ', added to result: ' + this.result.lstar);
    }
    // compute grayscale is to be continued hereafter
    // compute inverted rgb color
    this.result.invert = {
      r: null,
      g: null,
      b: null,
      hex: null
    };
    this.result.invert.r = (255 - this.result.rgb.r);
    this.result.invert.g = (255 - this.result.rgb.g);
    this.result.invert.b = (255 - this.result.rgb.b);
    // reverse compute hex from inverted rgb
    this.result.invert.hex = this.result.invert.b.toString(16); // begin with blue channel
    if (this.result.invert.hex.length < 2) {
      this.result.invert.hex = '0' + this.result.invert.hex;
    }
    this.result.invert.hex = this.result.invert.g.toString(16) + this.result.invert.hex;
    if (this.result.invert.hex.length < 4) {
      this.result.invert.hex = '0' + this.result.invert.hex;
    }
    this.result.invert.hex = this.result.invert.r.toString(16) + this.result.invert.hex;
    if (this.result.invert.hex.length < 6) {
      this.result.invert.hex = '0' + this.result.invert.hex;
    }
    this.result.invert.hex = '#' + this.result.invert.hex;
    this.result.error = false;
    if (this.loging) {
      console.log(this.name + ', final output:');
    }
    if (this.loging) {
      console.log(this.result);
    }
    return this.result;
  }
}
</code>```

Body:
In order to check if two colors in grayscale will be too close to be distinguished by the human eye. I want to be able to generate a warning to the user if 'dangerous' colors are picked. Hence based on the result we can decide if for people with bad eye sight we should change one of the two colors to white or black to enhance the readable contrast.

For example the Hex colours #9d5fb0 (purple) and #318261 (green) will turn into almost the same grey tone. Seen in HSB the B value is just 1% different from the other and therefor the healthy human eye cannot really see the difference. Or for the same the 8-Bit K value in this case differs 2%.

I have learned the luminance method is the more sophisticated way for judging grey tones the way the human eye sees colors. Yet how to do this programatically is beyond my current understanding. I could write it either PHP or JS once I understand the math.

In order to either pick values from CSS, from a screen pixel or from a file as image object, I guess we should always handle the input as RGB right?

something like:

$result = grayScaleDifference('#9d5fb0','#318261');

or

$result = 8bitK_difference('#9d5fb0','#318261');

or

$result = luminanceDifference('#9d5fb0','#318261');

So what is the best script style formula to compare them without changing or converting the actual image or color objects?

Body:
Just for a better syntax and ease of use I have put the whole theory into one single parser within an object that runs as follows.

The parser will compute these values in one step from color 318261:

A returned object will look like:

hex: "#318261"
rgb: {
  r: 49,
  g: 130,
  b: 97
}
int: 10313648
dec: {
  r: 0.19215686274509805,
  g: 0.5098039215686274,
  b: 0.3803921568627451
}
lin: {
  r: 0.030713443732993635,
  g: 0.2232279573168085,
  b: 0.11953842798834562
}
y: 0.17481298771137443
lstar: 48.86083783595441

JavaScript can call the object internal parser with a Hex color string as a parameter. The hex string can look like either 000 or #000 or 000000 or #000000. There are two ways to process the result.

A: take the returned object as a whole into a variable:

var result = Color_Parser.parseHex('318261');
var lstar = result.lstar;

B: parse once and thereafter access parts of the last parser result. For example pick only the the L* contrast value would be just:

Color_Parser.parseHex('#ABC');
var lstar = Color_Parser.result.lstar;

Here is the full code:

const Color_Parser = {
  version: '1.0.0.beta',
  name: 'Color_Parser',
  result: null, // the parser output
  loging: true, // set to false to disable writing each step to console log
  parseHex: function(_input) {
    if (this.loging) {
      console.log(this.name + ', input: ' + _input);
    }
    this.result = {};
    // pre flight checks
    if (!_input) {
      this.result.error = true;
      console.log(this.name + ', error');
      return this.result;
    }
    // first convert shorthand Hex strings to full strings
    this.result.hex = String(_input);
    if (this.result.hex.length == 3) {
      this.result.hex = '#' + this.result.hex.substr(0, 1) + this.result.hex.substr(0, 1) + this.result.hex.substr(1, 1) + this.result.hex.substr(1, 1) + this.result.hex.substr(2, 1) + this.result.hex.substr(2, 1);
    }
    if (this.result.hex.length == 4) {
      this.result.hex = '#' + this.result.hex.substr(1, 1) + this.result.hex.substr(1, 1) + this.result.hex.substr(2, 1) + this.result.hex.substr(2, 1) + this.result.hex.substr(3, 1) + this.result.hex.substr(3, 1);
    }
    if (this.result.hex.length == 6) {
      this.result.hex = '#' + this.result.hex;
    }
    if (this.loging) {
      console.log(this.name + ', added to result: ' + this.result.hex);
    }
    // second get int values from the string segments as channels
    this.result.rgb = {
      r: null,
      g: null,
      b: null
    };
    this.result.rgb.r = parseInt(this.result.hex.substr(1, 2), 16);
    this.result.rgb.g = parseInt(this.result.hex.substr(3, 2), 16);
    this.result.rgb.b = parseInt(this.result.hex.substr(5, 2), 16);
    if (this.loging) {
      console.log(this.name + ', added to result: ' + this.result.rgb);
    }
    // third get the combined color int value
    this.result.int = ((this.result.rgb.r & 0x0ff) << 16) | ((this.result.rgb.g & 0x0ff) << 8) | (this.result.rgb.b & 0x0ff);
    if (this.loging) {
      console.log(this.name + ', added to result: ' + this.result.int);
    }
    // fourth turn 8 bit channels to decimal
    this.result.dec = {
      r: null,
      g: null,
      b: null
    };
    this.result.dec.r = this.result.rgb.r / 255.0; // red channel to decimal
    this.result.dec.g = this.result.rgb.g / 255.0; // green channel to decimal
    this.result.dec.b = this.result.rgb.b / 255.0; // blue channel to decimal
    if (this.loging) {
      console.log(this.name + ', added to result: ' + this.result.dec);
    }
    // fifth linearize each channel
    this.result.lin = {
      r: null,
      g: null,
      b: null
    };
    for (var i = 0, len = 3; i < len; i++) {
      if (this.result.dec[['r', 'g', 'b'][i]] <= 0.04045) {
        this.result.lin[['r', 'g', 'b'][i]] = this.result.dec[['r', 'g', 'b'][i]] / 12.92;
      } else {
        this.result.lin[['r', 'g', 'b'][i]] = Math.pow(((this.result.dec[['r', 'g', 'b'][i]] + 0.055) / 1.055), 2.4);
      }
    }
    if (this.loging) {
      console.log(this.name + ', added to result: ' + this.result.lin);
    }
    // get Y from linear result
    this.result.y = (0.2126 * (this.result.lin.r)); // red channel
    this.result.y += (0.7152 * (this.result.lin.g)); // green channel
    this.result.y += (0.0722 * (this.result.lin.b)); // blue channel
    if (this.loging) {
      console.log(this.name + ', added to result: ' + this.result.y);
    }
    // get L* contrast from Y
    if (this.result.y <= (216 / 24389)) {
      this.result.lstar = this.result.y * (24389 / 27);
    } else {
      this.result.lstar = Math.pow(this.result.y, (1 / 3)) * 116 - 16;
    }
    if (this.loging) {
      console.log(this.name + ', added to result: ' + this.result.lstar);
    }
    // compute grayscale is to be continued hereafter
    // compute inverted rgb color
    this.result.invert = {
      r: null,
      g: null,
      b: null,
      hex: null
    };
    this.result.invert.r = (255 - this.result.rgb.r);
    this.result.invert.g = (255 - this.result.rgb.g);
    this.result.invert.b = (255 - this.result.rgb.b);
    // reverse compute hex from inverted rgb
    this.result.invert.hex = this.result.invert.b.toString(16); // begin with blue channel
    if (this.result.invert.hex.length < 2) {
      this.result.invert.hex = '0' + this.result.invert.hex;
    }
    this.result.invert.hex = this.result.invert.g.toString(16) + this.result.invert.hex;
    if (this.result.invert.hex.length < 4) {
      this.result.invert.hex = '0' + this.result.invert.hex;
    }
    this.result.invert.hex = this.result.invert.r.toString(16) + this.result.invert.hex;
    if (this.result.invert.hex.length < 6) {
      this.result.invert.hex = '0' + this.result.invert.hex;
    }
    this.result.invert.hex = '#' + this.result.invert.hex;
    this.result.error = false;
    if (this.loging) {
      console.log(this.name + ', final output:');
    }
    if (this.loging) {
      console.log(this.result);
    }
    return this.result;
  }
}


问:
Plotting a dictionary of dictionaries
I have a dictionary of dictionaries with the following structure:

{'ytrain_0': {'Neut': 0,'hard': 143,'hard linked': 1507,'soft': 112,'soft linked': 1238},
'ytrain_102000': {'Neut': 426,'hard': 519,'hard linked': 829,'soft': 467,'soft linked': 759},
'ytrain_105000': {'Neut': 406,'hard': 489,'hard linked': 826,'soft': 499,'soft linked': 780}}
```

<p>This is just an example. My real dictionary has 78 dictionaries. Now what I want to do is that I want to make a histogram for each example <code>(train_0,ytrain_102000,ytrain_105000)</code>. How can I do that in python? I haven't been able to figure that out. </p>

<p>Instead of creating 78 different graphs and adjusting it one image myself. I want to make 78 graphs in one image using python. I know we can do that in R using mfrow(). But I don't know how to do that in python? Can someone help me out with it?</p>

<p>I am using the following code to plot: </p>

```output = []

for a in dictionary_test.keys():
    output.append(dictionary_test[a])

import pandas as pd
pd.DataFrame(output).hist()

ax = pd.DataFrame(output).plot.bar(rot=0)

axes = pd.DataFrame(output).plot.bar(rot=0, subplots=True)
axes[1].legend(loc=2)
```

I get the following graph:

enter image description here

How to make sure that heading of each subplot does not appear on the other graph?

答:
try this:

```<code>dict = {'ytrain_0': {'Neut': 0,'hard': 143,'hard linked': 1507,'soft': 112,'soft linked': 1238},
'ytrain_102000': {'Neut': 426,'hard': 519,'hard linked': 829,'soft': 467,'soft linked': 759},
'ytrain_105000': {'Neut': 406,'hard': 489,'hard linked': 826,'soft': 499,'soft linked': 780}}

output = []

for a in dict.keys():
    output.append(dict[a]['Neut'])

import pandas as pd
pd.DataFrame(output).hist()
</code>```

and the plot it with matplotlib library

Title: Plotting a dictionary of dictionaries

Body:
I have a dictionary of dictionaries with the following structure:

{'ytrain_0': {'Neut': 0,'hard': 143,'hard linked': 1507,'soft': 112,'soft linked': 1238},
'ytrain_102000': {'Neut': 426,'hard': 519,'hard linked': 829,'soft': 467,'soft linked': 759},
'ytrain_105000': {'Neut': 406,'hard': 489,'hard linked': 826,'soft': 499,'soft linked': 780}}

This is just an example. My real dictionary has 78 dictionaries. Now what I want to do is that I want to make a histogram for each example (train_0,ytrain_102000,ytrain_105000). How can I do that in python? I haven't been able to figure that out.

Instead of creating 78 different graphs and adjusting it one image myself. I want to make 78 graphs in one image using python. I know we can do that in R using mfrow(). But I don't know how to do that in python? Can someone help me out with it?

I am using the following code to plot:

output = []

for a in dictionary_test.keys():
    output.append(dictionary_test[a])

import pandas as pd
pd.DataFrame(output).hist()

ax = pd.DataFrame(output).plot.bar(rot=0)

axes = pd.DataFrame(output).plot.bar(rot=0, subplots=True)
axes[1].legend(loc=2)

I get the following graph:

enter image description here

How to make sure that heading of each subplot does not appear on the other graph?

Body:
try this:

dict = {'ytrain_0': {'Neut': 0,'hard': 143,'hard linked': 1507,'soft': 112,'soft linked': 1238},
'ytrain_102000': {'Neut': 426,'hard': 519,'hard linked': 829,'soft': 467,'soft linked': 759},
'ytrain_105000': {'Neut': 406,'hard': 489,'hard linked': 826,'soft': 499,'soft linked': 780}}

output = []

for a in dict.keys():
    output.append(dict[a]['Neut'])

import pandas as pd
pd.DataFrame(output).hist()

and the plot it with matplotlib library


问:
Cannot read property 'lang' of undefined at ToolbarStrings.setLocale
I got the following error

```<code>Uncaught TypeError: Cannot read property 'lang' of undefined
at ToolbarStrings.setLocale (toolbar-min.js:9)
at Object.start (toolbar-min.js:41)
at toolbar-min.js:41
ToolbarStrings.setLocale @ toolbar-min.js:9
start @ toolbar-min.js:41
(anonymous) @ toolbar-min.js:41
</code>```

for the following code

```<code>function ToolbarStrings(){var a="EN";this.setLocale=function(){
    var b=document.getElementsByTagName("<html>")[0],
    c=document.getElementsByTagName("<body>")[0];
    this.locale=(b.lang?b.lang:b.getAttribute("xml:lang")?b.getAttribute("xml:lang"):c.lang?c.lang:a).substr(0,2).toUpperCase(),
    this.locale&&traduction[this.locale]||(this.locale=a),
    this.ForceDefaultLocale&&(this.locale=this.ForceDefaultLocale)
}
</code>```

in fact this is just a part of this JavaScript file i'm using,
i don't know if there is a problem with the syntax or something else

can you help me find a solution?

答:
The code seems to be trying to get the language declaration in your HTML. This would look something like this:

```<code><html lang="en">
</code>```

But the line document.getElementsByTagName("")[0] returns nothing, hence why b.lang fails. You don't have an <> tag in your document, since getElementByTagName is looking for that name inside the brackets. You need document.getElementsByTagName("html")

let htmlTags = document.getElementsByTagName("html");

let htmlTagsInExtraAngleBrackets = document.getElementsByTagName("");

console.log('number of elements selected with "html"', htmlTags.length)
console.log('number of elements selected with ""', htmlTagsInExtraAngleBrackets.length)```

Body:
I got the following error

Uncaught TypeError: Cannot read property 'lang' of undefined
at ToolbarStrings.setLocale (toolbar-min.js:9)
at Object.start (toolbar-min.js:41)
at toolbar-min.js:41
ToolbarStrings.setLocale @ toolbar-min.js:9
start @ toolbar-min.js:41
(anonymous) @ toolbar-min.js:41

for the following code

function ToolbarStrings(){var a="EN";this.setLocale=function(){
    var b=document.getElementsByTagName("")[0],
    c=document.getElementsByTagName("")[0];
    this.locale=(b.lang?b.lang:b.getAttribute("xml:lang")?b.getAttribute("xml:lang"):c.lang?c.lang:a).substr(0,2).toUpperCase(),
    this.locale&&traduction[this.locale]||(this.locale=a),
    this.ForceDefaultLocale&&(this.locale=this.ForceDefaultLocale)
}

in fact this is just a part of this JavaScript file i'm using,
i don't know if there is a problem with the syntax or something else

can you help me find a solution?

Body:
The code seems to be trying to get the language declaration in your HTML. This would look something like this:

<html lang="en">

But the line document.getElementsByTagName("<html>")[0] returns nothing, hence why b.lang fails. You don't have an <<html>> tag in your document, since getElementByTagName is looking for that name inside the brackets. You need document.getElementsByTagName("html")

let htmlTags = document.getElementsByTagName("html");

let htmlTagsInExtraAngleBrackets = document.getElementsByTagName("<html>");

console.log('number of elements selected with "html"', htmlTags.length)
console.log('number of elements selected with "<html>"', htmlTagsInExtraAngleBrackets.length)


答:
Change this:

```<code>var b=document.getElementsByTagName("<html>")[0],
    c=document.getElementsByTagName("<body>")[0];
</code>```

To this:

```<code>var b=document.getElementsByTagName("html")[0],
    c=document.getElementsByTagName("body")[0];
</code>```

Explanation:

The error is stating that you are trying to use the lang property on a variable that is undefined. This indicates that the b or c variables are undefined.

The reason is because it could not find an element by tag name  because that is invalid. It should be html (without angle brackets).

Title: Cannot read property 'lang' of undefined at ToolbarStrings.setLocale

Body:
Change this:

var b=document.getElementsByTagName("<html>")[0],
    c=document.getElementsByTagName("<body>")[0];

To this:

var b=document.getElementsByTagName("html")[0],
    c=document.getElementsByTagName("body")[0];

Explanation:

The error is stating that you are trying to use the lang property on a variable that is undefined. This indicates that the b or c variables are undefined.

The reason is because it could not find an element by tag name <html> because that is invalid. It should be html (without angle brackets).


问:
How to get rid of duplicates from cloudantdb?
I am new to non-relational databases.
I have spent hours googling any way to get rid of duplicates from my cloudant database comprised of Twitter data.

For example in the following screenshot, there are duplicated in the text field. Is there any way to drop them using Cloudant dashboard or any other method?

Thanks...

答:
There are no handy uniqueness constraints in Cloudant as those you'd find in a relational database. The only thing that is unique is the document id. As you're free to supply your own document id, you could make that the (say) md5 hash of the tweet body string. That way you'd get a conflict if you tried to insert a dupe.

Otherwise you'd need to create a view that emits the body (or hash thereof) as a key and have a separate process that checks this view for dupes and removes them as necessary, as outlined in the accepted answer here:

Identifying Duplicates in CouchDB


问:
How to get state from multiple children components to parent to handle without using Redux
I have a parent which encloses three child component in a tab view, the parent also contain a button which handles a POST request after getting all the state from all three child components. How do I retrieve all the states from the three child components back to the parent to handle once the button in the parent is clicked?

I do not wish to use Redux as it is complicated to me even though I have watched multiple videos and learnt through many different sources

答:
You could use redux, save in store and update your parents but if you don't want to use it, you could do something like this :

```<code>import React, { Component } from 'react';
import { View } from 'react-native';

class ParentComponent extends Component {

  state = {
    child1: 0,
    child2: 0,
    child3: 0,
  };

  settingState = (key, val) => {
    this.setState(state => ({
      ...state,
      [key]: val,
    }));
  };

  render() {
    const { child1, child2, child3 } = this.state;
    return (
      <View>
        <ChildOne child1={child1} settingState={this.settingState} />
        <ChildTwo child2={child2} settingState={this.settingState} />
        <ChildThree child3={child3} settingState={this.settingState} />
      </View>
    );
  }
}

export default ParentComponent;
</code>```

Like this you're setting the state from the parent and have access to it any time. You won't be able to access a child's state, as far as i know.

Body:
You could use redux, save in store and update your parents but if you don't want to use it, you could do something like this :

import React, { Component } from 'react';
import { View } from 'react-native';

class ParentComponent extends Component {

  state = {
    child1: 0,
    child2: 0,
    child3: 0,
  };

  settingState = (key, val) => {
    this.setState(state => ({
      ...state,
      [key]: val,
    }));
  };

  render() {
    const { child1, child2, child3 } = this.state;
    return (
      <View>
        <ChildOne child1={child1} settingState={this.settingState} />
        <ChildTwo child2={child2} settingState={this.settingState} />
        <ChildThree child3={child3} settingState={this.settingState} />
      </View>
    );
  }
}

export default ParentComponent;

Like this you're setting the state from the parent and have access to it any time. You won't be able to access a child's state, as far as i know.


问:
Sending hex characters over a socket
I am trying to send a hex character to a socket to indicate a new message.  This code works:

```<code>  $socket->send("\x{0B}");
  $socket->send($contents);
  $socket->send("\x{1C}");
  $socket->send("\x{0D}");
</code>```

However, since this happens in a loop, I need variable hex characters, and I have not figure out how to get it to work.  This is what I have tried.

```<code>my $start_char = get(); # returns, for example 0B
my $end_char = get(); # 1C
my $end_seg = get(); #0D

$socket->send("\x{$start_char}");
$socket->send($contents);
$socket->send("\x{$end_char}");
$socket->send("\x{$end_seg}");
</code>```

I can verify that the variables returned by the function are correct on the perl side, but the server does not accept them as valid characters.  Any input regarding how to do this?

答:
If you have a small amount of data, ysth's answer makes sense.

If you have a larger amount of data, you may want to look at pack.

pack ("H*", "0B") and pack ("C*", 0x0B) both give "\x0B".

Title: Sending hex characters over a socket

Body:
I am trying to send a hex character to a socket to indicate a new message.  This code works:

  $socket->send("\x{0B}");
  $socket->send($contents);
  $socket->send("\x{1C}");
  $socket->send("\x{0D}");

However, since this happens in a loop, I need variable hex characters, and I have not figure out how to get it to work.  This is what I have tried.

my $start_char = get(); # returns, for example 0B
my $end_char = get(); # 1C
my $end_seg = get(); #0D

$socket->send("\x{$start_char}");
$socket->send($contents);
$socket->send("\x{$end_char}");
$socket->send("\x{$end_seg}");

I can verify that the variables returned by the function are correct on the perl side, but the server does not accept them as valid characters.  Any input regarding how to do this?


问:
Looping through SerenityRest Response in JAVA
I am trying to get a count of all models from the cars object, which is part of a SerenityRest response.

```<code>Response response = SerenityRest.rest()
        .contentType("application/json")
        .when()
        .get("/api/");
if (response.statusCode() == 200) {
   int numUniqueModels = response.body().path("cars.size()");  // 3
}
</code>```

Response:

```<code>   "cars": {
       "Acura": [
           "ILX",
           "MDX",
           "TLX"
       ],
       "Audi": [
           "A3",
           "A4",
           "A6",
           "A7"
       ],
       "BMW": [
           "x",
           "y"
       ]
   }
</code>```

For example,

```<code>response.body().path("cars.size()") = 3,
</code>```

but i need the sum of cars.Acura.size() + cars.Audi.size() + cars.BMW.size() to get all models. However, i don't know if the exact names Acura, Audi or BMW will exist in the response, since vehicles may change dynamically. To solve this, i will need to do some kind of a loop, where:

```<code>sum = 0;
for (int i = 0; i < response.body().path("cars.size()"); i++) {
   sum += response.body().path("cars.[i].size()");
}
</code>```

The sum should give a total number of car models = 9.
The problem is that this syntax: path("cars.[i].size()") is not correct. What is the correct call?

答:
If you want to make complex request with rest-assured you have to follow the synthax described here groovy gpath as mentionned here rest-assured doc:

Note that the JsonPath implementation uses Groovy's GPath syntax and is not to be confused with Jayway's JsonPath implementation.

So you have to play with some groovy synthax:

```<code>int total = JsonPath.from("{  "
              + " \"cars\": {\n"
              + "       \"Acura\": [\n"
              + "           \"ILX\",\n"
              + "           \"MDX\",\n"
              + "           \"TLX\"\n"
              + "       ],\n"
              + "       \"Audi\": [\n"
              + "           \"A3\",\n"
              + "           \"A4\",\n"
              + "           \"A6\",\n"
              + "           \"A7\"\n"
              + "       ],\n"
              + "       \"BMW\": [\n"
              + "           \"x\",\n"
              + "           \"y\"\n"
              + "       ]\n"
              + "   }"
              + "}")
        .getInt("cars.collect { it.value.size() }.sum()")
</code>```

So this expression should make the job cars.collect { it.value.size() }.sum(). The collect method is like a map method in functional programming. So you map the collection cars HashMap with the size() of its values and you collect the sum()!

Edit

So you just have to do:

```<code>Response response = SerenityRest.rest()
        .contentType("application/json")
        .when()
        .get("/api/");
if (response.statusCode() == 200) {
   int numUniqueModels = response.body().path("cars.collect { it.value.size() }.sum()");  // 9
}
</code>```

Body:
I am trying to get a count of all models from the cars object, which is part of a SerenityRest response.

Response response = SerenityRest.rest()
        .contentType("application/json")
        .when()
        .get("/api/");
if (response.statusCode() == 200) {
   int numUniqueModels = response.body().path("cars.size()");  // 3
}

Response:

   "cars": {
       "Acura": [
           "ILX",
           "MDX",
           "TLX"
       ],
       "Audi": [
           "A3",
           "A4",
           "A6",
           "A7"
       ],
       "BMW": [
           "x",
           "y"
       ]
   }

For example,

response.body().path("cars.size()") = 3,

but i need the sum of cars.Acura.size() + cars.Audi.size() + cars.BMW.size() to get all models. However, i don't know if the exact names Acura, Audi or BMW will exist in the response, since vehicles may change dynamically. To solve this, i will need to do some kind of a loop, where:

sum = 0;
for (int i = 0; i < response.body().path("cars.size()"); i++) {
   sum += response.body().path("cars.[i].size()");
}

The sum should give a total number of car models = 9.
The problem is that this syntax: path("cars.[i].size()") is not correct. What is the correct call?

Body:
If you want to make complex request with rest-assured you have to follow the synthax described here groovy gpath as mentionned here rest-assured doc:

Note that the JsonPath implementation uses Groovy's GPath syntax and is not to be confused with Jayway's JsonPath implementation.

So you have to play with some groovy synthax:

int total = JsonPath.from("{  "
              + " \"cars\": {\n"
              + "       \"Acura\": [\n"
              + "           \"ILX\",\n"
              + "           \"MDX\",\n"
              + "           \"TLX\"\n"
              + "       ],\n"
              + "       \"Audi\": [\n"
              + "           \"A3\",\n"
              + "           \"A4\",\n"
              + "           \"A6\",\n"
              + "           \"A7\"\n"
              + "       ],\n"
              + "       \"BMW\": [\n"
              + "           \"x\",\n"
              + "           \"y\"\n"
              + "       ]\n"
              + "   }"
              + "}")
        .getInt("cars.collect { it.value.size() }.sum()")

So this expression should make the job cars.collect { it.value.size() }.sum(). The collect method is like a map method in functional programming. So you map the collection cars HashMap with the size() of its values and you collect the sum()!

Edit

So you just have to do:

Response response = SerenityRest.rest()
        .contentType("application/json")
        .when()
        .get("/api/");
if (response.statusCode() == 200) {
   int numUniqueModels = response.body().path("cars.collect { it.value.size() }.sum()");  // 9
}


问:
Send email to all the rows from mysql in codeigniter
i need to send emails to all the rows in database table with their corresponsing data. i am able to send single emails by their id, but now i need to send in bulk. i have done in pure php but in codeigniter not able to figure out. how to do this.

my controller is

```<code>     public function autoformcomplete()
        {
            $this->load->model('admin/Reminder_model');
            $datan = $this->Reminder_model->autoformemail();

//this should be in whileloop, that i am not able to figure out
             $email = $datan[0]['email'];
                $config = array(
                        'protocol'  => 'smtp',
                        'smtp_host' => 'email-smtp.eu-west-1.amazonaws.com',
                         'smtp_port' => 587,
                        'smtp_crypto' => 'tls',
                        'smtp_user' => 'user',
                         'smtp_pass' => 'pass',
                        'mailtype'  => 'text',
                         'charset'   => 'utf-8',
                         );
              $this->email->initialize($config);
              $this->email->set_mailtype("html");
              $this->email->set_newline("\r\n");
              $this->email->set_crlf("\r\n");
              $subject = "Complete Your Partially Filled Application-".$appid."";
              $data['datan'] = $datan;
              $mesg = $this->load->view('email/reminder/form_complete',$data,true);
              $this->email->to($email);
              $this->email->from('mail@mail.com','My Company');
              $this->email->subject($subject);
              $this->email->message($mesg);
              $this->email->send();
              echo "sent";

        }
</code>```

My Model is

```<code>public function autoformemail(){

        $this->db->order_by('id', 'DESC');
        $query = $this->db->get('appstbldata');
        return $query->result_array();

       }
</code>```

答:
Just use a foreach loop

```<code>public function autoformcomplete() {
    $this->load->model( 'admin/Reminder_model' );
    $datan = $this->Reminder_model->autoformemail();

    foreach ( $datan as $index => $val ) {
        // $val now references the current pointer to an element in your $datan array
        $email  = $val['email'];
        $config = array(
            'protocol'    => 'smtp',
            'smtp_host'   => 'email-smtp.eu-west-1.amazonaws.com',
            'smtp_port'   => 587,
            'smtp_crypto' => 'tls',
            'smtp_user'   => 'user',
            'smtp_pass'   => 'pass',
            'mailtype'    => 'text',
            'charset'     => 'utf-8',
        );
        $this->email->initialize( $config );
        $this->email->set_mailtype( "html" );
        $this->email->set_newline( "\r\n" );
        $this->email->set_crlf( "\r\n" );
        $subject       = "Complete Your Partially Filled Application-" . $appid . "";
        $data['datan'] = $datan;
        $mesg          = $this->load->view( 'email/reminder/form_complete', $data, true );
        $this->email->to( $email );
        $this->email->from( 'mail@mail.com', 'My Company' );
        $this->email->subject( $subject );
        $this->email->message( $mesg );
        $this->email->send();
        echo "sent";
    }

}
</code>```

I dunno what your point of $data['datan'] = $datan; line is though

Body:
i need to send emails to all the rows in database table with their corresponsing data. i am able to send single emails by their id, but now i need to send in bulk. i have done in pure php but in codeigniter not able to figure out. how to do this.

my controller is

     public function autoformcomplete()
        {
            $this->load->model('admin/Reminder_model');
            $datan = $this->Reminder_model->autoformemail();

//this should be in whileloop, that i am not able to figure out
             $email = $datan[0]['email'];
                $config = array(
                        'protocol'  => 'smtp',
                        'smtp_host' => 'email-smtp.eu-west-1.amazonaws.com',
                         'smtp_port' => 587,
                        'smtp_crypto' => 'tls',
                        'smtp_user' => 'user',
                         'smtp_pass' => 'pass',
                        'mailtype'  => 'text',
                         'charset'   => 'utf-8',
                         );
              $this->email->initialize($config);
              $this->email->set_mailtype("html");
              $this->email->set_newline("\r\n");
              $this->email->set_crlf("\r\n");
              $subject = "Complete Your Partially Filled Application-".$appid."";
              $data['datan'] = $datan;
              $mesg = $this->load->view('email/reminder/form_complete',$data,true);
              $this->email->to($email);
              $this->email->from('mail@mail.com','My Company');
              $this->email->subject($subject);
              $this->email->message($mesg);
              $this->email->send();
              echo "sent";

        }

My Model is

public function autoformemail(){

        $this->db->order_by('id', 'DESC');
        $query = $this->db->get('appstbldata');
        return $query->result_array();

       }

Body:
Just use a foreach loop

public function autoformcomplete() {
    $this->load->model( 'admin/Reminder_model' );
    $datan = $this->Reminder_model->autoformemail();

    foreach ( $datan as $index => $val ) {
        // $val now references the current pointer to an element in your $datan array
        $email  = $val['email'];
        $config = array(
            'protocol'    => 'smtp',
            'smtp_host'   => 'email-smtp.eu-west-1.amazonaws.com',
            'smtp_port'   => 587,
            'smtp_crypto' => 'tls',
            'smtp_user'   => 'user',
            'smtp_pass'   => 'pass',
            'mailtype'    => 'text',
            'charset'     => 'utf-8',
        );
        $this->email->initialize( $config );
        $this->email->set_mailtype( "html" );
        $this->email->set_newline( "\r\n" );
        $this->email->set_crlf( "\r\n" );
        $subject       = "Complete Your Partially Filled Application-" . $appid . "";
        $data['datan'] = $datan;
        $mesg          = $this->load->view( 'email/reminder/form_complete', $data, true );
        $this->email->to( $email );
        $this->email->from( 'mail@mail.com', 'My Company' );
        $this->email->subject( $subject );
        $this->email->message( $mesg );
        $this->email->send();
        echo "sent";
    }

}

I dunno what your point of $data['datan'] = $datan; line is though


问:
Function to determine if two numbers are nearly equal when rounded to n significant decimal digits
I have been asked to test a library provided by a 3rd party. The library is known to be accurate to n significant figures. Any less-significant errors can safely be ignored. I want to write a function to help me compare the results:

```<code>def nearlyequal(a, b, sigfig=5):
</code>```

The purpose of this function is to determine if two floating-point numbers (a and b) are approximately equal. The function will return True if a==b (exact match) or if a and b have the same value when rounded to sigfig significant-figures when written in decimal.

Can anybody suggest a good implementation? I've written a mini unit-test. Unless you can see a bug in my tests then a good implementation should pass the following:

```<code>assert nearlyequal(1, 1, 5)
assert nearlyequal(1.0, 1.0, 5)
assert nearlyequal(1.0, 1.0, 5)
assert nearlyequal(-1e-9, 1e-9, 5)
assert nearlyequal(1e9, 1e9 + 1 , 5)
assert not nearlyequal(1e4, 1e4 + 1, 5)
assert nearlyequal(0.0, 1e-15, 5)
assert not nearlyequal(0.0, 1e-4, 6)
</code>```

Additional notes:

Values a and b might be of type int, float or numpy.float64. Values a and b will always be of the same type. It's vital that conversion does not introduce additional error into the function.

Lets keep this numerical, so functions that convert to strings or use non-mathematical tricks are not ideal. This program will be audited by somebody who is a mathematician who will want to be able to prove that the function does what it is supposed to do.

Speed... I've got to compare a lot of numbers so the faster the better.

I've got numpy, scipy and the standard-library. Anything else will be hard for me to get, especially for such a small part of the project.

答:
This is a fairly common issue with floating point numbers. I solve it based on the discussion in Section 1.5 of Demmel[1]. (1) Calculate the roundoff error. (2) Check that the roundoff error is less than some epsilon. I haven't used python in some time and only have version 2.4.3, but I'll try to get this correct.

Step 1. Roundoff error

```<code>def roundoff_error(exact, approximate):
    return abs(approximate/exact - 1.0)
</code>```

Step 2. Floating point equality

```<code>def float_equal(float1, float2, epsilon=2.0e-9):
    return (roundoff_error(float1, float2) < epsilon)
</code>```

There are a couple obvious deficiencies with this code.

Division by zero error if the exact value is Zero.

Does not verify that the arguments are floating point values.

Revision 1.

```<code>def roundoff_error(exact, approximate):
    if (exact == 0.0 or approximate == 0.0):
        return abs(exact + approximate)
    else:
        return abs(approximate/exact - 1.0)

def float_equal(float1, float2, epsilon=2.0e-9):
    if not isinstance(float1,float):
        raise TypeError,"First argument is not a float."
    elif not isinstance(float2,float):
        raise TypeError,"Second argument is not a float."
    else:
        return (roundoff_error(float1, float2) < epsilon)
</code>```

That's a little better. If either the exact or the approximate value is zero, than the error is equal to the value of the other. If something besides a floating point value is provided, a TypeError is raised.

At this point, the only difficult thing is setting the correct value for epsilon. I noticed in the documentation for version 2.6.1 that there is an epsilon attribute in sys.float_info, so I would use twice that value as the default epsilon. But the correct value depends on both your application and your algorithm.

[1] James W. Demmel, Applied Numerical Linear Algebra, SIAM, 1997.

OwnerDisplayName: Salim Fadhley

Body:
I have been asked to test a library provided by a 3rd party. The library is known to be accurate to n significant figures. Any less-significant errors can safely be ignored. I want to write a function to help me compare the results:

def nearlyequal(a, b, sigfig=5):

The purpose of this function is to determine if two floating-point numbers (a and b) are approximately equal. The function will return True if a==b (exact match) or if a and b have the same value when rounded to sigfig significant-figures when written in decimal.

Can anybody suggest a good implementation? I've written a mini unit-test. Unless you can see a bug in my tests then a good implementation should pass the following:

assert nearlyequal(1, 1, 5)
assert nearlyequal(1.0, 1.0, 5)
assert nearlyequal(1.0, 1.0, 5)
assert nearlyequal(-1e-9, 1e-9, 5)
assert nearlyequal(1e9, 1e9 + 1 , 5)
assert not nearlyequal(1e4, 1e4 + 1, 5)
assert nearlyequal(0.0, 1e-15, 5)
assert not nearlyequal(0.0, 1e-4, 6)

Additional notes:

Values a and b might be of type int, float or numpy.float64. Values a and b will always be of the same type. It's vital that conversion does not introduce additional error into the function.

Lets keep this numerical, so functions that convert to strings or use non-mathematical tricks are not ideal. This program will be audited by somebody who is a mathematician who will want to be able to prove that the function does what it is supposed to do.

Speed... I've got to compare a lot of numbers so the faster the better.

I've got numpy, scipy and the standard-library. Anything else will be hard for me to get, especially for such a small part of the project.

LastEditorDisplayName: starblue

Body:
This is a fairly common issue with floating point numbers. I solve it based on the discussion in Section 1.5 of Demmel[1]. (1) Calculate the roundoff error. (2) Check that the roundoff error is less than some epsilon. I haven't used python in some time and only have version 2.4.3, but I'll try to get this correct.

Step 1. Roundoff error

def roundoff_error(exact, approximate):
    return abs(approximate/exact - 1.0)

Step 2. Floating point equality

def float_equal(float1, float2, epsilon=2.0e-9):
    return (roundoff_error(float1, float2) < epsilon)

There are a couple obvious deficiencies with this code.

Division by zero error if the exact value is Zero.

Does not verify that the arguments are floating point values.

Revision 1.

def roundoff_error(exact, approximate):
    if (exact == 0.0 or approximate == 0.0):
        return abs(exact + approximate)
    else:
        return abs(approximate/exact - 1.0)

def float_equal(float1, float2, epsilon=2.0e-9):
    if not isinstance(float1,float):
        raise TypeError,"First argument is not a float."
    elif not isinstance(float2,float):
        raise TypeError,"Second argument is not a float."
    else:
        return (roundoff_error(float1, float2) < epsilon)

That's a little better. If either the exact or the approximate value is zero, than the error is equal to the value of the other. If something besides a floating point value is provided, a TypeError is raised.

At this point, the only difficult thing is setting the correct value for epsilon. I noticed in the documentation for version 2.6.1 that there is an epsilon attribute in sys.float_info, so I would use twice that value as the default epsilon. But the correct value depends on both your application and your algorithm.

[1] James W. Demmel, Applied Numerical Linear Algebra, SIAM, 1997.

OwnerDisplayName: tmh

ContentLicense: CC BY-SA 2.5


问:
Display text in jtextarea with newline and spacing
I have set the text of JTextArea with setText function

```<code>abc="PREFIX table: <http://www.daml.org/2003/01/periodictable/PeriodicTable#> " +
            "SELECT ?name " +
            "FROM <http://www.daml.org/2003/01/periodictable/PeriodicTable.owl>" +
            "WHERE {" +
            "      ?element table:name ?name. " +
            "      FILTER(str(?name)=\"sodium\") " +
            "      }"
texta.setText(abc);//abc is very long string
</code>```

How do I display the string with newlines and spacing in the JTextArea.

答: Use new lines in your String.  The '\n' character.

Body:
I have set the text of JTextArea with setText function

abc="PREFIX table: <http://www.daml.org/2003/01/periodictable/PeriodicTable#> " +
            "SELECT ?name " +
            "FROM <http://www.daml.org/2003/01/periodictable/PeriodicTable.owl>" +
            "WHERE {" +
            "      ?element table:name ?name. " +
            "      FILTER(str(?name)=\"sodium\") " +
            "      }"
texta.setText(abc);//abc is very long string

How do I display the string with newlines and spacing in the JTextArea.