问:
CSS doesn't apply to dynamically created text field
I have created a dynamic text field for my form. Both the add and delete function works perfectly fine but when I applied CSS it won't work.
I'm a newbie in javascript and really appreciate if you could help me in figure it out. Here is the code:

var counter = 1;
  var limit = 3;

  function showTextBox() {
      var newdiv = document.createElement('div');
      //var add = 'add' + (counter - 1) ;
      console.log(newdiv);
      //console.log(counter);
      var tr = document.getElementById(newdiv);
      console.log(tr);
      newdiv.id = 'add' + counter;
      var sample = newdiv.id;
      //console.log(sample);
      //console.log(newdiv.id);
      newdiv.innerHTML = "Option  <input type='text' >";
      //document.getElementById("newdiv").setAttribute("style", "borderRadius: 10px; borderColor: #777; cursor: text; height: 20px;");
      //newdiv.style.setProperty('border-radius', '10px', 'border-color', '#777', 'cursor', 'text', 'height', '20px');
      newdiv.style.paddingBottom = "10px";
      document.getElementById("tbhold").appendChild(newdiv);
      counter++;
  }

  function hideTextBox() {
      var add = 'add' + (counter - 1);
      //console.log(counter);
      var tr = document.getElementById(add);
      console.log(tr);
      tr.parentNode.removeChild(tr);
      counter--;
  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#option{
   font-size: 16px;
   text-align: center;
   top: 250px;
   padding-top: 50px;
  }
  #option > span{
   text-align: center;
   margin-left: 80px;
   top: 50px;
  }
  #tbhold > p > input{
   margin-left: 20px;
   border-radius: 10px;
   border-color: #777;
   cursor: text;
   height: 20px;
  }</code>```

    Name

Option  <input type="text" name="c_field" id="c_field">

     +  -

```

答:
Input isn't getting generated inside p so remove nesting of p tag

var counter = 1;
  var limit = 3;

  function showTextBox() {
      var newdiv = document.createElement('div');
      //var add = 'add' + (counter - 1) ;
      console.log(newdiv);
      //console.log(counter);
      var tr = document.getElementById(newdiv);
      console.log(tr);
      newdiv.id = 'add' + counter;
      var sample = newdiv.id;
      //console.log(sample);
      //console.log(newdiv.id);
      newdiv.innerHTML = "Option  <input type='text' >";
      //document.getElementById("newdiv").setAttribute("style", "borderRadius: 10px; borderColor: #777; cursor: text; height: 20px;");
      //newdiv.style.setProperty('border-radius', '10px', 'border-color', '#777', 'cursor', 'text', 'height', '20px');
      newdiv.style.paddingBottom = "10px";
      document.getElementById("tbhold").appendChild(newdiv);
      counter++;
  }

  function hideTextBox() {
      var add = 'add' + (counter - 1);
      //console.log(counter);
      var tr = document.getElementById(add);
      console.log(tr);
      tr.parentNode.removeChild(tr);
      counter--;
  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#option{
   font-size: 16px;
   text-align: center;
   top: 250px;
   padding-top: 50px;
  }
  #option > span{
   text-align: center;
   margin-left: 80px;
   top: 50px;
  }
  #tbhold input{
   margin-left: 20px;
   border-radius: 10px;
   border-color: #777;
   cursor: text;
   height: 20px;
  }</code>```

    Name

Option  <input type="text" name="c_field" id="c_field">

     +  -

```

Body:
I have created a dynamic text field for my form. Both the add and delete function works perfectly fine but when I applied CSS it won't work.
I'm a newbie in javascript and really appreciate if you could help me in figure it out. Here is the code:

var counter = 1;
  var limit = 3;

  function showTextBox() {
      var newdiv = document.createElement('div');
      //var add = 'add' + (counter - 1) ;
      console.log(newdiv);
      //console.log(counter);
      var tr = document.getElementById(newdiv);
      console.log(tr);
      newdiv.id = 'add' + counter;
      var sample = newdiv.id;
      //console.log(sample);
      //console.log(newdiv.id);
      newdiv.innerHTML = "Option  <input type='text' >";
      //document.getElementById("newdiv").setAttribute("style", "borderRadius: 10px; borderColor: #777; cursor: text; height: 20px;");
      //newdiv.style.setProperty('border-radius', '10px', 'border-color', '#777', 'cursor', 'text', 'height', '20px');
      newdiv.style.paddingBottom = "10px";
      document.getElementById("tbhold").appendChild(newdiv);
      counter++;
  }

  function hideTextBox() {
      var add = 'add' + (counter - 1);
      //console.log(counter);
      var tr = document.getElementById(add);
      console.log(tr);
      tr.parentNode.removeChild(tr);
      counter--;
  }

#option{
   font-size: 16px;
   text-align: center;
   top: 250px;
   padding-top: 50px;
  }
  #option > span{
   text-align: center;
   margin-left: 80px;
   top: 50px;
  }
  #tbhold > p > input{
   margin-left: 20px;
   border-radius: 10px;
   border-color: #777;
   cursor: text;
   height: 20px;
  }

    Name

Option  <input type="text" name="c_field" id="c_field">

     +  -

Body:
Input isn't getting generated inside p so remove nesting of p tag

var counter = 1;
  var limit = 3;

  function showTextBox() {
      var newdiv = document.createElement('div');
      //var add = 'add' + (counter - 1) ;
      console.log(newdiv);
      //console.log(counter);
      var tr = document.getElementById(newdiv);
      console.log(tr);
      newdiv.id = 'add' + counter;
      var sample = newdiv.id;
      //console.log(sample);
      //console.log(newdiv.id);
      newdiv.innerHTML = "Option  <input type='text' >";
      //document.getElementById("newdiv").setAttribute("style", "borderRadius: 10px; borderColor: #777; cursor: text; height: 20px;");
      //newdiv.style.setProperty('border-radius', '10px', 'border-color', '#777', 'cursor', 'text', 'height', '20px');
      newdiv.style.paddingBottom = "10px";
      document.getElementById("tbhold").appendChild(newdiv);
      counter++;
  }

  function hideTextBox() {
      var add = 'add' + (counter - 1);
      //console.log(counter);
      var tr = document.getElementById(add);
      console.log(tr);
      tr.parentNode.removeChild(tr);
      counter--;
  }

#option{
   font-size: 16px;
   text-align: center;
   top: 250px;
   padding-top: 50px;
  }
  #option > span{
   text-align: center;
   margin-left: 80px;
   top: 50px;
  }
  #tbhold input{
   margin-left: 20px;
   border-radius: 10px;
   border-color: #777;
   cursor: text;
   height: 20px;
  }

<div id="option">
    <span><strong>Name</strong></span>
    <div id="tbhold">
      <p>Option  <input type="text" name="c_field" id="c_field"></p>
     </div>
     <a href="javascript:showTextBox()"><span>+</span></a>&emsp;&emsp;<a href="javascript:hideTextBox()"><span>-</span></a>
   </div>


来源: stackexchange

问:
Multiply list with binary
I am trying to create a powerset by multiplying binary counter with array to get

```<code>Value of Counter            Subset
    000                    -> Empty set
    001                    -> a
    010                    -> b
    011                    -> ab
    100                    -> c
    101                    -> ac
    110                    -> bc
    111                    -> abc
</code>```

My code:

```<code>A = ['a','b','c']
n = len(A)
for i in range(2**n):
    print format(i,'b') and A
</code>```

I get all the outputs as ['a','b','c'] . Is there a different way to do the print statement to get the required result.

答:
You cant use bitwise operation between a string and a list.

I tried the following way.

```<code>A = ['a','b','c']
n = len(A)
for i in range(2**n):
    s = format(i,'b')[::-1]
    print(''.join( (A[j] for j in range(len(s)) if s[j]=='1' )))
</code>```

ContentLicense: CC BY-SA 3.0

Title: Multiply list with binary

Body:
I am trying to create a powerset by multiplying binary counter with array to get

Value of Counter            Subset
    000                    -> Empty set
    001                    -> a
    010                    -> b
    011                    -> ab
    100                    -> c
    101                    -> ac
    110                    -> bc
    111                    -> abc

My code:

A = ['a','b','c']
n = len(A)
for i in range(2**n):
    print format(i,'b') and A

I get all the outputs as ['a','b','c'] . Is there a different way to do the print statement to get the required result.

Body:
You cant use bitwise operation between a string and a list.

I tried the following way.

A = ['a','b','c']
n = len(A)
for i in range(2**n):
    s = format(i,'b')[::-1]
    print(''.join( (A[j] for j in range(len(s)) if s[j]=='1' )))


问:
I want to sort my products list in a descending order
I want to sort my product page in a descending order that is I want recently added products to show first when you open the product page. While I was trying to paginate the product page, It works fine but the problem is old products are shown first.

Here is my part of my  code

```<code> $per_page = 15;
 if(isset($_GET["page"]) && is_numeric($_GET['page'])){
  $page = $_GET["page"];
  }else{
    $page = 1;
    }
  $start_from = ($page-1) * $per_page;

  $query = "SELECT * FROM products LIMIT $start_from, $per_page DESC ";
  $post = $db->select($query);
    if($post){
        while($result = $post->fetch_assoc()){
</code>```

When I add DESC at the end of the query it shows an error saying "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DESC' at line 130" but when I remove it works fine but it does not sort in a descending order. Old products come first instead of being at the end of the page.

答:
The syntax you want for your query is </p>

```<code>"SELECT * FROM products ORDER BY fieldtoorderby DESC LIMIT $start_from, $per_page"
</code>```

Body:
I want to sort my product page in a descending order that is I want recently added products to show first when you open the product page. While I was trying to paginate the product page, It works fine but the problem is old products are shown first.

Here is my part of my  code

 $per_page = 15;
 if(isset($_GET["page"]) && is_numeric($_GET['page'])){
  $page = $_GET["page"];
  }else{
    $page = 1;
    }
  $start_from = ($page-1) * $per_page;

  $query = "SELECT * FROM products LIMIT $start_from, $per_page DESC ";
  $post = $db->select($query);
    if($post){
        while($result = $post->fetch_assoc()){

When I add DESC at the end of the query it shows an error saying "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DESC' at line 130" but when I remove it works fine but it does not sort in a descending order. Old products come first instead of being at the end of the page.

Body:
The syntax you want for your query is

"SELECT * FROM products ORDER BY fieldtoorderby DESC LIMIT $start_from, $per_page"


问:
send a post request via vuejs in laravel 5.5
I want to post comment related to a post via vuejs.
this is the route:

```<code>Route::post('/posts/{post}/comments', 'RoleController@store');
</code>```

the function is:

```<code>    public function store($id)
{
    $this->validate(request(), [
        'body' => 'required|min:3'
    ], [
        'body.min' => 'bla bla'
    ]);
    $user = auth()->id();
    $post = Post::find($id);
    Comment::create([
        'cbody' => request('body'),
        'post_id' => $post->id,
        'user_id' => $user,
        'cstatus' => 0
    ]);
}
</code>```

in vue file I have:

```<code>   export default {
    data() {
        return {
            data : {
                body : ''
            },
            errors : new Errors(),
            success : {
                status : false,
                message : ''
            }
        }
    },
    methods : {
        onSubmit() {
            axios.post(`/posts/${this.post.id}/comments` , this.data)
                .then(response => {
                    this.success = {
                        status : true,
                        message : this.$swal("bla bla ", "bla bla ", "info")
                    };
                    this.data = {
                        body : ''
                    }
                })
                .catch(error => this.errors.record(error.response.data) );
                    }
                }
            }
</code>```

but I get this error related to the line that axios is defined:

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

If I hard code

```<code>'post_id' => 66,
</code>```

and then remove property id:

```<code> axios.post(`/posts/${this.post}/comments` , this.data)
</code>```

it works.
I think the main problem is that I don't know how to write the url in axios with params.

答:
I couldn't solve this via post slug. but without slug, these codes saved me.
in my component send post as an argument to onSubmit function:

```<code><template>
    <div>
        <form @submit.prevent="onSubmit(post)" @keydown="errors.clear($event.target.name)">
                <div :class="['form-group' , { 'has-error' : errors.has('body')}]">
                    <label for="body"> write comment</label>
                    <textarea class="form-control" v-model="data.body" name="body" id="body" rows="7"></textarea>
                    <div class="error" v-if="errors.has('body')">{{ errors.get('body') }}</div>
                </div>
                <div class="form-group">
                    <button type="submit" :disabled="errors.any()" class="btn btn-default">submit</button>
                </div>
        </form>

    </div>
</template>
</code>```

script part I edit the axios url and put the Argument to onSubmit function:

```<code><script>
export default {
            props: ['post'],
            data() {
                return {
                    data : {
                     body : '',
                     post:'',
                    },
                    errors : new Errors(),
                    success : {
                        status : false,
                        message : ''
                    }
                }
            },
            methods : {
                onSubmit(post) {
                    axios.post('/posts/'+post+'/comments', this.data)
                        .then(response => {
                            this.success = {
                                status : true,
                            };
                            this.data = {
                                body : ''
                            }
                        })
                        .catch(error => this.errors.record(error.response.data) );
                            }
                        }
                    }
    </script>
</code>```

and use the props in my component like:

```<code><create-comment :post={{ $post->id }}></create-comment>
</code>```

with this route:

```<code>Route::post('/posts/{post}/comments', 'RoleController@store');
</code>```

and this function:

```<code>public function store(Post $post)
{
    $this->validate(request() , [
        'body' => 'required|min:5'
    ]);

    $user = auth()->user();

    $post->comments()->create([
        'user_id' => $user->id,
        'cbody' => request('body'),
        'cstatus'=>0
    ]);
}
</code>```

everything works fine, But trying with post.slug there's

```<code>message No query results for model [App\Post].
</code>```

error. here is my post model:

```<code><?php

namespace App;

use Cviebrock\EloquentSluggable\Sluggable;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $guarded=[];
    use Sluggable;
    public function user()
    {
        return $this->belongsTo(User::class);

    }
    public function comments()
    {
        return $this->hasMany(Comment::class);

    }
    public function tags()
    {
        return $this->belongsToMany(Tag::class)
                 ->select(['id','name']);
    }
    public function sluggable()
    {
       return[
           'slug'=>[
               'source'=>'title'
           ]
       ];
    }

    public function getRouteKeyName()
    {
        return 'slug';
    }
}
</code>```

Body:
I want to post comment related to a post via vuejs.
this is the route:

Route::post('/posts/{post}/comments', 'RoleController@store');

the function is:

    public function store($id)
{
    $this->validate(request(), [
        'body' => 'required|min:3'
    ], [
        'body.min' => 'bla bla'
    ]);
    $user = auth()->id();
    $post = Post::find($id);
    Comment::create([
        'cbody' => request('body'),
        'post_id' => $post->id,
        'user_id' => $user,
        'cstatus' => 0
    ]);
}

in vue file I have:

   export default {
    data() {
        return {
            data : {
                body : ''
            },
            errors : new Errors(),
            success : {
                status : false,
                message : ''
            }
        }
    },
    methods : {
        onSubmit() {
            axios.post(`/posts/${this.post.id}/comments` , this.data)
                .then(response => {
                    this.success = {
                        status : true,
                        message : this.$swal("bla bla ", "bla bla ", "info")
                    };
                    this.data = {
                        body : ''
                    }
                })
                .catch(error => this.errors.record(error.response.data) );
                    }
                }
            }

but I get this error related to the line that axios is defined:

 Cannot read property 'id' of undefined

If I hard code

'post_id' => 66,

and then remove property id:

 axios.post(`/posts/${this.post}/comments` , this.data)

it works.
I think the main problem is that I don't know how to write the url in axios with params.

Body:
I couldn't solve this via post slug. but without slug, these codes saved me.
in my component send post as an argument to onSubmit function:

<template>
    <div>
        <form @submit.prevent="onSubmit(post)" @keydown="errors.clear($event.target.name)">
                <div :class="['form-group' , { 'has-error' : errors.has('body')}]">
                    <label for="body"> write comment</label>
                    <textarea class="form-control" v-model="data.body" name="body" id="body" rows="7"></textarea>
                    <div class="error" v-if="errors.has('body')">{{ errors.get('body') }}</div>
                </div>
                <div class="form-group">
                    <button type="submit" :disabled="errors.any()" class="btn btn-default">submit</button>
                </div>
        </form>

    </div>
</template>

script part I edit the axios url and put the Argument to onSubmit function:

<script>
export default {
            props: ['post'],
            data() {
                return {
                    data : {
                     body : '',
                     post:'',
                    },
                    errors : new Errors(),
                    success : {
                        status : false,
                        message : ''
                    }
                }
            },
            methods : {
                onSubmit(post) {
                    axios.post('/posts/'+post+'/comments', this.data)
                        .then(response => {
                            this.success = {
                                status : true,
                            };
                            this.data = {
                                body : ''
                            }
                        })
                        .catch(error => this.errors.record(error.response.data) );
                            }
                        }
                    }
    </script>

and use the props in my component like:

<create-comment :post={{ $post->id }}></create-comment>

with this route:

Route::post('/posts/{post}/comments', 'RoleController@store');

and this function:

public function store(Post $post)
{
    $this->validate(request() , [
        'body' => 'required|min:5'
    ]);

    $user = auth()->user();

    $post->comments()->create([
        'user_id' => $user->id,
        'cbody' => request('body'),
        'cstatus'=>0
    ]);
}

everything works fine, But trying with post.slug there's

message No query results for model [App\Post].

error. here is my post model:

<?php

namespace App;

use Cviebrock\EloquentSluggable\Sluggable;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $guarded=[];
    use Sluggable;
    public function user()
    {
        return $this->belongsTo(User::class);

    }
    public function comments()
    {
        return $this->hasMany(Comment::class);

    }
    public function tags()
    {
        return $this->belongsToMany(Tag::class)
                 ->select(['id','name']);
    }
    public function sluggable()
    {
       return[
           'slug'=>[
               'source'=>'title'
           ]
       ];
    }

    public function getRouteKeyName()
    {
        return 'slug';
    }
}


问:
Seeding the random number generator in Javascript
Is it possible to seed the random number generator (Math.random) in JavaScript?

答: Many people who need a seedable random-number generator in Javascript these days are using David Bau's seedrandom module.</p>

OwnerDisplayName: weepy

ContentLicense: CC BY-SA 4.0


问:
SQL Server displays char(1) as 4 characters wide, padded by spaces
I've been constructing a simple query to return fixed width records for export to an older application. I've used

```<code>Select Cast([myColumn1] as char(1)), Cast([myColumn2] as char(1)) from myTable
</code>```

for single character columns, but the displayed result in SQL Server Management Studio always pads it out to 4 characters. For example, for a couple of single-character columns, it displays:

```<code>---- ----
P    A
</code>```

I would expect to see:

```<code>- -
P A
</code>```

I have a couple of questions:

Will this still occur if I use the query in code or will it format as expected with single character width? What I'm wondering is if it is a feature of the output pane in SSMS (although it exhibits the same behaviour when output to a file).

If it does occur, is there a workaround?

I hope that's not a dumb question, but can't seem to find any documentation...

答:
The underscores have no bearing on the actual data. 4 is the minimum number SSMS will display.

Try this and verify:

```<code>DECLARE @varA VARCHAR(4) = 'A'
,@varB VARCHAR(4) = 'B'
SELECT '|'+CAST(@varA AS CHAR(1))+'|'+@varB
</code>```

Body:
I've been constructing a simple query to return fixed width records for export to an older application. I've used

Select Cast([myColumn1] as char(1)), Cast([myColumn2] as char(1)) from myTable

for single character columns, but the displayed result in SQL Server Management Studio always pads it out to 4 characters. For example, for a couple of single-character columns, it displays:

---- ----
P    A

I would expect to see:

- -
P A

I have a couple of questions:

Will this still occur if I use the query in code or will it format as expected with single character width? What I'm wondering is if it is a feature of the output pane in SSMS (although it exhibits the same behaviour when output to a file).

If it does occur, is there a workaround?

I hope that's not a dumb question, but can't seem to find any documentation...

Body:
The underscores have no bearing on the actual data. 4 is the minimum number SSMS will display.

Try this and verify:

DECLARE @varA VARCHAR(4) = 'A'
,@varB VARCHAR(4) = 'B'
SELECT '|'+CAST(@varA AS CHAR(1))+'|'+@varB


问:
How to go back to parent screen in react-navigation?

Problem

```<code>RootTabNavigator
    | Auth Screen
    | Welcome Screen
    | MainTabNavigator
              | FeedStacknavigator
                       | Screen A

              | MenuStackNavigator
                       | Screen B <-I'm here and want to reset to 'Auth Screen'
</code>```

The tree structure shows my app's Navigation structure. I'm on 'Screen B' and would like to go back to Auth Screen. (NOT Navigate) When I navigate to Auth Screen, it create new Auth Screen and I want to avoid it.

```<code>if ( ... ) {
      // I'm getting undefined error here
      nextProps.navigation.reset('Autho');
</code>```

Why is it not working?

Possible Solution1: reset

```<code>  const resetAction = NavigationActions.reset({
      index: 0,
      actions: [
          // getting error because auth screen is not in MenuStacknavigator.
          NavigationActions.navigate({ routeName: 'Auth'})
      ]
  })
  this.props.navigation.dispatch(resetAction);
</code>```

Possible Solution #2 :

```<code>  const backAction = NavigationActions.back({
    key: 'Autho'
  })
  # Back Action doesn't do anything
  this.props.navigation.dispatch(backAction); # not working
</code>```

Possible Solution #3 :

dispatch custom action. <- there were some solutions for StackNavigator but in my case it's TabNavigator.

答:
Please feel free to answer. I've found a simple solution for now : </p>

```<code>const backAction = NavigationActions.back({
    key: null
})
nextProps.navigation.dispatch(backAction);
</code>```

Body:
Problem

RootTabNavigator
    | Auth Screen
    | Welcome Screen
    | MainTabNavigator
              | FeedStacknavigator
                       | Screen A

              | MenuStackNavigator
                       | Screen B <-I'm here and want to reset to 'Auth Screen'

The tree structure shows my app's Navigation structure. I'm on 'Screen B' and would like to go back to Auth Screen. (NOT Navigate) When I navigate to Auth Screen, it create new Auth Screen and I want to avoid it.

if ( ... ) {
      // I'm getting undefined error here
      nextProps.navigation.reset('Autho');

Why is it not working?

Possible Solution1: reset

  const resetAction = NavigationActions.reset({
      index: 0,
      actions: [
          // getting error because auth screen is not in MenuStacknavigator.
          NavigationActions.navigate({ routeName: 'Auth'})
      ]
  })
  this.props.navigation.dispatch(resetAction);

Possible Solution #2 :

  const backAction = NavigationActions.back({
    key: 'Autho'
  })
  # Back Action doesn't do anything
  this.props.navigation.dispatch(backAction); # not working

Possible Solution #3 :

dispatch custom action. <- there were some solutions for StackNavigator but in my case it's TabNavigator.

Body:
Please feel free to answer. I've found a simple solution for now :

const backAction = NavigationActions.back({
    key: null
})
nextProps.navigation.dispatch(backAction);


问:
double and single quotes in wrapping awk codes
I'm trying to extract a string from a group of strings stored in a variable, say foo, in bash:

```<code>foo="I foobar you"
</code>```

using awk, but I got different results when I wrapped awk with single and double quotes:

```<code>$ echo $foo | awk '{print $2}'
$ foobar

$ echo $foo | awk "{print $2}"
$ I foobar you
</code>```

Could anyone tell me why ' and " cause different results when wrapping awk?

答:
According to shell quoting rules:

Single quotes (‘ ‘) protect everything between the opening and closing quotes. The shell does no interpretation of the quoted text, passing it on verbatim to the command.

As in your code {print $2} passed on as it is to awk as an action:

$ echo $foo | awk '{print $2}'

$ foobar

Double quotes (“ “) protect most things between the opening and closing quotes. The shell does at least variable and command substitution on the quoted text. Different shells may do additional kinds of processing on double-quoted text. Because certain characters within double-quoted text are processed by the shell, they must be escaped within the text. Of note are the characters ‘$’, ‘‘’, ‘\’, and ‘"’, all of which must be preceded by a backslash within double-quoted text if they are to be passed on literally to the program.

So you have to escape $ to get the value of second col as:

$ echo $foo | awk "{print \$2}"

$ foobar

otherwise awk is doing its default action of printing the whole line as in your case.

Fully agreed with @Ed Mortan regarding the best practice of quoting the shell variables. Although the double quotes are default, but if accidentally ….

$ echo "$foo"      with double quotes

$ I foobar you

$ echo ‘$foo’      with single quotes

$ $foo

Remember, quoting rules are specific to shell. The above rules only apply to POSIX-complaint, Bourne-style shells (such as Bash, the GNU Bourne-Again Shell). It has nothing to do with awk, sed, grep, etc…

Body:
I'm trying to extract a string from a group of strings stored in a variable, say foo, in bash:

foo="I foobar you"

using awk, but I got different results when I wrapped awk with single and double quotes:

$ echo $foo | awk '{print $2}'
$ foobar

$ echo $foo | awk "{print $2}"
$ I foobar you

Could anyone tell me why ' and " cause different results when wrapping awk?


问:
Alamofire - Swift Compiler Error - Use of undeclared type
I am having the same problem but only if I archive the solution. I can build the project and install the app to the device without getting any compile errors.

Module 'Alamofire' has no member named 'request'

Why am I getting 59 errors if I want to archive the project? I cleaned the project, deleted all the derived folder, checked project settings -paths, bitcode = YES / NO etc. None of them fixed the compiler errors. Like I said if I build the app or install it to a device Xcode doesn't give any error for Alamofire. I also did "Build Active Architecture Only" Debug = YES Release = NO.

I cannot archive my project. The following are just 2 compile errors out of 59. All under the Swift Compiler Error. Thanks for your help.

答:
I hope it helps someone. The problem was on the root folder I saw a folder named Alamofire and it was empty. I downloaded the latest version from the following url and pasted everything under that folder. I can archive the project now!

https://github.com/Alamofire/Alamofire


问:
How do I print out the results of my delete script in Powershell
I'm trying to find a way to get my script to print out a log file of what files are actually being deleted. Does anyone know how I could go about doing this? Here is my screen I would like to add that onto.</p>

```<code>Where-Object { -not $_.PSIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays(-1) } |
    Remove-Item -Force
</code>```

答:
The overall easiest way if you just need a log would be to use a Transcript and Verbose Output.

your script would look like this, make sure you pay attention to the addition of -Verbose to your command.

```<code>Start-Transcript C:\Logs\Remove.txt
Some-Command | Where-Object { -not $_.PSIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays(-1) } | Remove-Item -Force -Verbose
Stop-Transcript
</code>```

then the C:\Logs\Remove.txt file will have a message like this for each removed file:

```<code>VERBOSE: Performing the operation "Remove File" on target "H:\dns.csv".
</code>```

Body:
I'm trying to find a way to get my script to print out a log file of what files are actually being deleted. Does anyone know how I could go about doing this? Here is my screen I would like to add that onto.

Where-Object { -not $_.PSIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays(-1) } |
    Remove-Item -Force

Body:
The overall easiest way if you just need a log would be to use a Transcript and Verbose Output.

your script would look like this, make sure you pay attention to the addition of -Verbose to your command.

Start-Transcript C:\Logs\Remove.txt
Some-Command | Where-Object { -not $_.PSIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays(-1) } | Remove-Item -Force -Verbose
Stop-Transcript

then the C:\Logs\Remove.txt file will have a message like this for each removed file:

VERBOSE: Performing the operation "Remove File" on target "H:\dns.csv".


问:
Java accessing a value in the client
I'm having problems trying to communicate between the server and the client class.
Here is my very simple Server.java:

```<code>public class Server {

  public static int position = 1;

  public int getPosition() {
    return position;
  }

  public static void main(String args[]) throws IOException {
    position++;
    ServerSocket server = new ServerSocket(8080);
    Socket s = server.accept();
    System.out.println(position);
  }

}
</code>```

And here is my Client:

```<code>public class Client {

  public static void main(String args[]) throws UnknownHostException, IOException {
    Server serv = new Server();
    Socket s = new Socket("127.0.0.1", 8080);
    System.out.println("Connected!!");
    int a = ser.getPosition();
    System.out.println(a);
  }
}
</code>```

So when I print the position on the Server I get 2, and when it prints in the Client it remains as 1 even though the value that is static was changed on the Server.

Please help me fix this. Any kind of help would be greatly appreciated!

Thanks!

答:
well, you don't communicate between the server and the client, just call the getPosition() method in server class, not by socket.
here is the tutorials and a guide.</p>

Title: Java accessing a value in the client

Body:
I'm having problems trying to communicate between the server and the client class.
Here is my very simple Server.java:

public class Server {

  public static int position = 1;

  public int getPosition() {
    return position;
  }

  public static void main(String args[]) throws IOException {
    position++;
    ServerSocket server = new ServerSocket(8080);
    Socket s = server.accept();
    System.out.println(position);
  }

}

And here is my Client:

public class Client {

  public static void main(String args[]) throws UnknownHostException, IOException {
    Server serv = new Server();
    Socket s = new Socket("127.0.0.1", 8080);
    System.out.println("Connected!!");
    int a = ser.getPosition();
    System.out.println(a);
  }
}

So when I print the position on the Server I get 2, and when it prints in the Client it remains as 1 even though the value that is static was changed on the Server.

Please help me fix this. Any kind of help would be greatly appreciated!

Thanks!


问:
WatchOS4 display complication for a second then replace it by blank display
I'm a beginner in iOS programming. I'm trying to make a sample display on the complication on the apple watch but it only shows for a second and becomes blank after.

Here is my code in the ComplicationController

```<code>func getLocalizableSampleTemplate(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTemplate?) -> Void) {
    // This method will be called once per supported complication, and the results will be cached
    var template: CLKComplicationTemplate?
    switch complication.family {
    case .modularSmall:
        let modularSmallTemplate =
            CLKComplicationTemplateModularSmallRingText()
        modularSmallTemplate.textProvider =
            CLKSimpleTextProvider(text: "R")
        modularSmallTemplate.fillFraction = 0.75
        modularSmallTemplate.ringStyle = CLKComplicationRingStyle.closed
        template = modularSmallTemplate
    case .modularLarge:
        let modularLargeTemplate =
            CLKComplicationTemplateModularLargeStandardBody()
        modularLargeTemplate.headerTextProvider = CLKSimpleTextProvider(text: "Sample title", shortText: "Title")
        modularLargeTemplate.body1TextProvider =
            CLKSimpleTextProvider(text: "Sample Text",
                                  shortText: "Text")
        modularLargeTemplate.body2TextProvider =
            CLKSimpleTextProvider(text: "Tap to open",
                                  shortText: "Tap")
        template = modularLargeTemplate
    case .utilitarianSmall:
        template = nil
    case .utilitarianLarge:
        template = nil
    case .circularSmall:
        template = nil

    case .utilitarianSmallFlat:
        template = nil

    case .extraLarge:
        template = nil
    }
    handler(template)

}
</code>```

I've also read an answer about this question to manage also in the func getTimelineEntries, I've tried to paste the same code as on the template but still the result is the same, it display blank.

Can someone help me please? Thank you for your time.

答:
The code you have only provides a sample template for the complication. This is only used in the list of complications, hence being referred to as a sample. If you want to display data once your complication is selected you need to utilize the getCurrentTimelineEntry function.

```<code>func getCurrentTimelineEntry(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimelineEntry?) -> Void) {
     // Example Switch Statement
     switch complication.family {
    case .modularSmall:
        let template = CLKComplicationTemplateModularSmallSimpleImage()
        template.imageProvider.tintColor = UIColor.color(fromHexString: "#81BE41")
        template.imageProvider = CLKImageProvider(onePieceImage: backImage, twoPieceImageBackground: backImage, twoPieceImageForeground: transImage)
        handler(template)
    case .utilitarianLarge:
        let template = CLKComplicationTemplateUtilitarianLargeFlat()

        template.textProvider = CLKSimpleTextProvider(text: "Header Text")

        handler(template)

    case .modularLarge:
        let template = CLKComplicationTemplateModularLargeStandardBody()
        template.headerTextProvider = CLKSimpleTextProvider(text: "Header Text")
        template.body1TextProvider = CLKSimpleTextProvider(text: "----", shortText: "----")
        template.body2TextProvider = CLKSimpleTextProvider(text: "----", shortText: "----")

        handler(template)
    default:
        handler(nil)
    }
}
</code>```

Also make sure that you are calling getTimelineStartDate() and getTimeLineEndDate()

```<code>func getTimelineStartDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) {

    let date = Calendar.current.startOfDay(for: Date())
    handler(date)
}

func getTimelineEndDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) {

    var  date = Calendar.current.startOfDay(for: Date())
    date = Calendar.current.date(byAdding: .day, value: 2, to: date)!
    handler(date)
}
</code>```

Body:
I'm a beginner in iOS programming. I'm trying to make a sample display on the complication on the apple watch but it only shows for a second and becomes blank after.

Here is my code in the ComplicationController

func getLocalizableSampleTemplate(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTemplate?) -> Void) {
    // This method will be called once per supported complication, and the results will be cached
    var template: CLKComplicationTemplate?
    switch complication.family {
    case .modularSmall:
        let modularSmallTemplate =
            CLKComplicationTemplateModularSmallRingText()
        modularSmallTemplate.textProvider =
            CLKSimpleTextProvider(text: "R")
        modularSmallTemplate.fillFraction = 0.75
        modularSmallTemplate.ringStyle = CLKComplicationRingStyle.closed
        template = modularSmallTemplate
    case .modularLarge:
        let modularLargeTemplate =
            CLKComplicationTemplateModularLargeStandardBody()
        modularLargeTemplate.headerTextProvider = CLKSimpleTextProvider(text: "Sample title", shortText: "Title")
        modularLargeTemplate.body1TextProvider =
            CLKSimpleTextProvider(text: "Sample Text",
                                  shortText: "Text")
        modularLargeTemplate.body2TextProvider =
            CLKSimpleTextProvider(text: "Tap to open",
                                  shortText: "Tap")
        template = modularLargeTemplate
    case .utilitarianSmall:
        template = nil
    case .utilitarianLarge:
        template = nil
    case .circularSmall:
        template = nil

    case .utilitarianSmallFlat:
        template = nil

    case .extraLarge:
        template = nil
    }
    handler(template)

}

I've also read an answer about this question to manage also in the func getTimelineEntries, I've tried to paste the same code as on the template but still the result is the same, it display blank.

Can someone help me please? Thank you for your time.

Body:
The code you have only provides a sample template for the complication. This is only used in the list of complications, hence being referred to as a sample. If you want to display data once your complication is selected you need to utilize the getCurrentTimelineEntry function.

func getCurrentTimelineEntry(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimelineEntry?) -> Void) {
     // Example Switch Statement
     switch complication.family {
    case .modularSmall:
        let template = CLKComplicationTemplateModularSmallSimpleImage()
        template.imageProvider.tintColor = UIColor.color(fromHexString: "#81BE41")
        template.imageProvider = CLKImageProvider(onePieceImage: backImage, twoPieceImageBackground: backImage, twoPieceImageForeground: transImage)
        handler(template)
    case .utilitarianLarge:
        let template = CLKComplicationTemplateUtilitarianLargeFlat()

        template.textProvider = CLKSimpleTextProvider(text: "Header Text")

        handler(template)

    case .modularLarge:
        let template = CLKComplicationTemplateModularLargeStandardBody()
        template.headerTextProvider = CLKSimpleTextProvider(text: "Header Text")
        template.body1TextProvider = CLKSimpleTextProvider(text: "----", shortText: "----")
        template.body2TextProvider = CLKSimpleTextProvider(text: "----", shortText: "----")

        handler(template)
    default:
        handler(nil)
    }
}

Also make sure that you are calling getTimelineStartDate() and getTimeLineEndDate()

func getTimelineStartDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) {

    let date = Calendar.current.startOfDay(for: Date())
    handler(date)
}

func getTimelineEndDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) {

    var  date = Calendar.current.startOfDay(for: Date())
    date = Calendar.current.date(byAdding: .day, value: 2, to: date)!
    handler(date)
}


问:
How to click on an element in the iframe?
In site https://www.google.com/recaptcha/api2/demo I'm trying to click on the iframe (recaptcha) and then on the button with the headphone icon. But I can not. How to do it? Where is the mistake?

```<code>driver.get(RECAPTCHA_PAGE_URL)
time.sleep(random.uniform(MIN_RAND, MAX_RAND))
iframes = driver.find_elements_by_tag_name("iframe")
driver.switch_to_frame(iframes[0])
time.sleep(random.uniform(MIN_RAND, MAX_RAND))
driver.find_element_by_xpath('//div[@class="recaptcha-checkbox-checkmark" and @role="presentation"]').click()
time.sleep(random.uniform(MIN_RAND, MAX_RAND))
driver.find_element_by_xpath('//button[@id="recaptcha-audio-button"]').click()
time.sleep(random.uniform(LONG_MIN_RAND, LONG_MAX_RAND))
</code>```

MIN_RAND ,MAX_RAND,LONG_MIN_RAND, LONG_MAX_RAND is nums.
Error:

```<code>raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: The element reference of <iframe name="etxg0ejyszkb" src="https://www.google.com/recaptcha/api2/bframe?hl=en&v=r20171129143447&k=6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-#etxg0ejyszkb"> stale; either the element is no longer attached to the DOM, it is not in the current frame context, or the document has been refreshed
</code>```

答:
You need to switch to the iframe first. Something like this</p>

```<code>    driver.switch_to_frame(driver.find_element_by_tag_name("iframe"))
</code>```

Body:
In site https://www.google.com/recaptcha/api2/demo I'm trying to click on the iframe (recaptcha) and then on the button with the headphone icon. But I can not. How to do it? Where is the mistake?

driver.get(RECAPTCHA_PAGE_URL)
time.sleep(random.uniform(MIN_RAND, MAX_RAND))
iframes = driver.find_elements_by_tag_name("iframe")
driver.switch_to_frame(iframes[0])
time.sleep(random.uniform(MIN_RAND, MAX_RAND))
driver.find_element_by_xpath('//div[@class="recaptcha-checkbox-checkmark" and @role="presentation"]').click()
time.sleep(random.uniform(MIN_RAND, MAX_RAND))
driver.find_element_by_xpath('//button[@id="recaptcha-audio-button"]').click()
time.sleep(random.uniform(LONG_MIN_RAND, LONG_MAX_RAND))

MIN_RAND ,MAX_RAND,LONG_MIN_RAND, LONG_MAX_RAND is nums.
Error:

raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: The element reference of  stale; either the element is no longer attached to the DOM, it is not in the current frame context, or the document has been refreshed

Body:
You need to switch to the iframe first. Something like this

    driver.switch_to_frame(driver.find_element_by_tag_name("iframe"))


问:
JMeter - ElasticSearch backend listener plugin doesn't work
I have JMeter 3.3 and I added ElasticSearch backend listener plugin.

I opened JMeter GUI and tried create back end listener and it failed with error:

```<code>2017-10-17 14:35:24,785 ERROR o.a.j.g.GuiPackage: Problem retrieving gui for org.apache.jmeter.visualizers.backend.BackendListenerGui
java.lang.NoClassDefFoundError: okhttp3/MediaType
    at net.kvak.jmeter.backendlistener.elasticsearch.ElasticsearchBackend.<clinit>(ElasticsearchBackend.java:50) ~[elasticsearch-backend-listener-1.5.jar:?]
    at java.lang.Class.forName0(Native Method) ~[?:1.8.0_144]
    at java.lang.Class.forName(Unknown Source) ~[?:1.8.0_144]
    at org.apache.jmeter.visualizers.backend.BackendListenerGui.actionPerformed(BackendListenerGui.java:166) ~[ApacheJMeter_components.jar:3.3 r1808647]
    at javax.swing.JComboBox.fireActionEvent(Unknown Source) ~[?:1.8.0_144]
    at javax.swing.JComboBox.setSelectedItem(Unknown Source) ~[?:1.8.0_144]
    at javax.swing.JComboBox.setSelectedIndex(Unknown Source) ~[?:1.8.0_144]
    at org.apache.jmeter.visualizers.backend.BackendListenerGui.clearGui(BackendListenerGui.java:281) ~[ApacheJMeter_components.jar:3.3 r1808647]
    at org.apache.jmeter.gui.GuiPackage.createTestElement(GuiPackage.java:348) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at org.apache.jmeter.gui.action.AddToTree.doAction(AddToTree.java:68) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at org.apache.jmeter.gui.action.ActionRouter.performAction(ActionRouter.java:80) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at org.apache.jmeter.gui.action.ActionRouter.lambda$actionPerformed$0(ActionRouter.java:65) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at java.awt.event.InvocationEvent.dispatch(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue.access$500(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_144]
    at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_144]
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue.dispatchEvent(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.run(Unknown Source) [?:1.8.0_144]
Caused by: java.lang.ClassNotFoundException: okhttp3.MediaType
    at java.net.URLClassLoader.findClass(Unknown Source) ~[?:1.8.0_144]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_144]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_144]
    ... 26 more
2017-10-17 14:35:30,212 ERROR o.a.j.g.a.AddToTree: Exception while adding a component to tree.
java.lang.RuntimeException: java.lang.NoClassDefFoundError: okhttp3/MediaType
    at org.apache.jmeter.gui.GuiPackage.createTestElement(GuiPackage.java:359) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at org.apache.jmeter.gui.action.AddToTree.doAction(AddToTree.java:68) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at org.apache.jmeter.gui.action.ActionRouter.performAction(ActionRouter.java:80) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at org.apache.jmeter.gui.action.ActionRouter.lambda$actionPerformed$0(ActionRouter.java:65) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at java.awt.event.InvocationEvent.dispatch(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue.access$500(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_144]
    at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_144]
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue.dispatchEvent(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.run(Unknown Source) [?:1.8.0_144]
Caused by: java.lang.NoClassDefFoundError: okhttp3/MediaType
    at net.kvak.jmeter.backendlistener.elasticsearch.ElasticsearchBackend.<clinit>(ElasticsearchBackend.java:50) ~[elasticsearch-backend-listener-1.5.jar:?]
    at java.lang.Class.forName0(Native Method) ~[?:1.8.0_144]
    at java.lang.Class.forName(Unknown Source) ~[?:1.8.0_144]
    at org.apache.jmeter.visualizers.backend.BackendListenerGui.actionPerformed(BackendListenerGui.java:166) ~[ApacheJMeter_components.jar:3.3 r1808647]
    at javax.swing.JComboBox.fireActionEvent(Unknown Source) ~[?:1.8.0_144]
    at javax.swing.JComboBox.setSelectedItem(Unknown Source) ~[?:1.8.0_144]
    at javax.swing.JComboBox.setSelectedIndex(Unknown Source) ~[?:1.8.0_144]
    at org.apache.jmeter.visualizers.backend.BackendListenerGui.clearGui(BackendListenerGui.java:281) ~[ApacheJMeter_components.jar:3.3 r1808647]
    at org.apache.jmeter.gui.GuiPackage.createTestElement(GuiPackage.java:348) ~[ApacheJMeter_core.jar:3.3 r1808647]
    ... 17 more
Caused by: java.lang.ClassNotFoundException: okhttp3.MediaType
    at java.net.URLClassLoader.findClass(Unknown Source) ~[?:1.8.0_144]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_144]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_144]
    at net.kvak.jmeter.backendlistener.elasticsearch.ElasticsearchBackend.<clinit>(ElasticsearchBackend.java:50) ~[elasticsearch-backend-listener-1.5.jar:?]
    at java.lang.Class.forName0(Native Method) ~[?:1.8.0_144]
    at java.lang.Class.forName(Unknown Source) ~[?:1.8.0_144]
    at org.apache.jmeter.visualizers.backend.BackendListenerGui.actionPerformed(BackendListenerGui.java:166) ~[ApacheJMeter_components.jar:3.3 r1808647]
    at javax.swing.JComboBox.fireActionEvent(Unknown Source) ~[?:1.8.0_144]
    at javax.swing.JComboBox.setSelectedItem(Unknown Source) ~[?:1.8.0_144]
    at javax.swing.JComboBox.setSelectedIndex(Unknown Source) ~[?:1.8.0_144]
    at org.apache.jmeter.visualizers.backend.BackendListenerGui.clearGui(BackendListenerGui.java:281) ~[ApacheJMeter_components.jar:3.3 r1808647]
    at org.apache.jmeter.gui.GuiPackage.createTestElement(GuiPackage.java:348) ~[ApacheJMeter_core.jar:3.3 r1808647]
    ... 17 more
</code>```

Sent question in plugin group but didn't receive any answer.

Is it working only with additional plugin/jars? on different version?

Also why doesn't it have page in https://jmeter-plugins.org/ (although it displayed in search results in site)?

答:
Alright, realized what was causing the issue when installing the plugin through the plugins manager. Basically, was missing a key/value pair in one of their JSON files for the dependencies.

Made the pull request. For now, to fix the issue all you will need to do is download some JAR files and put them into your "$JMETER_HOME/lib" folder.

Okio 1.13.0

OkHttp 3.9.1

GSON 2.8.2

Body:
I have JMeter 3.3 and I added ElasticSearch backend listener plugin.

I opened JMeter GUI and tried create back end listener and it failed with error:

2017-10-17 14:35:24,785 ERROR o.a.j.g.GuiPackage: Problem retrieving gui for org.apache.jmeter.visualizers.backend.BackendListenerGui
java.lang.NoClassDefFoundError: okhttp3/MediaType
    at net.kvak.jmeter.backendlistener.elasticsearch.ElasticsearchBackend.<clinit>(ElasticsearchBackend.java:50) ~[elasticsearch-backend-listener-1.5.jar:?]
    at java.lang.Class.forName0(Native Method) ~[?:1.8.0_144]
    at java.lang.Class.forName(Unknown Source) ~[?:1.8.0_144]
    at org.apache.jmeter.visualizers.backend.BackendListenerGui.actionPerformed(BackendListenerGui.java:166) ~[ApacheJMeter_components.jar:3.3 r1808647]
    at javax.swing.JComboBox.fireActionEvent(Unknown Source) ~[?:1.8.0_144]
    at javax.swing.JComboBox.setSelectedItem(Unknown Source) ~[?:1.8.0_144]
    at javax.swing.JComboBox.setSelectedIndex(Unknown Source) ~[?:1.8.0_144]
    at org.apache.jmeter.visualizers.backend.BackendListenerGui.clearGui(BackendListenerGui.java:281) ~[ApacheJMeter_components.jar:3.3 r1808647]
    at org.apache.jmeter.gui.GuiPackage.createTestElement(GuiPackage.java:348) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at org.apache.jmeter.gui.action.AddToTree.doAction(AddToTree.java:68) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at org.apache.jmeter.gui.action.ActionRouter.performAction(ActionRouter.java:80) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at org.apache.jmeter.gui.action.ActionRouter.lambda$actionPerformed$0(ActionRouter.java:65) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at java.awt.event.InvocationEvent.dispatch(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue.access$500(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_144]
    at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_144]
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue.dispatchEvent(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.run(Unknown Source) [?:1.8.0_144]
Caused by: java.lang.ClassNotFoundException: okhttp3.MediaType
    at java.net.URLClassLoader.findClass(Unknown Source) ~[?:1.8.0_144]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_144]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_144]
    ... 26 more
2017-10-17 14:35:30,212 ERROR o.a.j.g.a.AddToTree: Exception while adding a component to tree.
java.lang.RuntimeException: java.lang.NoClassDefFoundError: okhttp3/MediaType
    at org.apache.jmeter.gui.GuiPackage.createTestElement(GuiPackage.java:359) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at org.apache.jmeter.gui.action.AddToTree.doAction(AddToTree.java:68) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at org.apache.jmeter.gui.action.ActionRouter.performAction(ActionRouter.java:80) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at org.apache.jmeter.gui.action.ActionRouter.lambda$actionPerformed$0(ActionRouter.java:65) ~[ApacheJMeter_core.jar:3.3 r1808647]
    at java.awt.event.InvocationEvent.dispatch(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue.access$500(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue$3.run(Unknown Source) [?:1.8.0_144]
    at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_144]
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) [?:1.8.0_144]
    at java.awt.EventQueue.dispatchEvent(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [?:1.8.0_144]
    at java.awt.EventDispatchThread.run(Unknown Source) [?:1.8.0_144]
Caused by: java.lang.NoClassDefFoundError: okhttp3/MediaType
    at net.kvak.jmeter.backendlistener.elasticsearch.ElasticsearchBackend.<clinit>(ElasticsearchBackend.java:50) ~[elasticsearch-backend-listener-1.5.jar:?]
    at java.lang.Class.forName0(Native Method) ~[?:1.8.0_144]
    at java.lang.Class.forName(Unknown Source) ~[?:1.8.0_144]
    at org.apache.jmeter.visualizers.backend.BackendListenerGui.actionPerformed(BackendListenerGui.java:166) ~[ApacheJMeter_components.jar:3.3 r1808647]
    at javax.swing.JComboBox.fireActionEvent(Unknown Source) ~[?:1.8.0_144]
    at javax.swing.JComboBox.setSelectedItem(Unknown Source) ~[?:1.8.0_144]
    at javax.swing.JComboBox.setSelectedIndex(Unknown Source) ~[?:1.8.0_144]
    at org.apache.jmeter.visualizers.backend.BackendListenerGui.clearGui(BackendListenerGui.java:281) ~[ApacheJMeter_components.jar:3.3 r1808647]
    at org.apache.jmeter.gui.GuiPackage.createTestElement(GuiPackage.java:348) ~[ApacheJMeter_core.jar:3.3 r1808647]
    ... 17 more
Caused by: java.lang.ClassNotFoundException: okhttp3.MediaType
    at java.net.URLClassLoader.findClass(Unknown Source) ~[?:1.8.0_144]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_144]
    at java.lang.ClassLoader.loadClass(Unknown Source) ~[?:1.8.0_144]
    at net.kvak.jmeter.backendlistener.elasticsearch.ElasticsearchBackend.<clinit>(ElasticsearchBackend.java:50) ~[elasticsearch-backend-listener-1.5.jar:?]
    at java.lang.Class.forName0(Native Method) ~[?:1.8.0_144]
    at java.lang.Class.forName(Unknown Source) ~[?:1.8.0_144]
    at org.apache.jmeter.visualizers.backend.BackendListenerGui.actionPerformed(BackendListenerGui.java:166) ~[ApacheJMeter_components.jar:3.3 r1808647]
    at javax.swing.JComboBox.fireActionEvent(Unknown Source) ~[?:1.8.0_144]
    at javax.swing.JComboBox.setSelectedItem(Unknown Source) ~[?:1.8.0_144]
    at javax.swing.JComboBox.setSelectedIndex(Unknown Source) ~[?:1.8.0_144]
    at org.apache.jmeter.visualizers.backend.BackendListenerGui.clearGui(BackendListenerGui.java:281) ~[ApacheJMeter_components.jar:3.3 r1808647]
    at org.apache.jmeter.gui.GuiPackage.createTestElement(GuiPackage.java:348) ~[ApacheJMeter_core.jar:3.3 r1808647]
    ... 17 more

Sent question in plugin group but didn't receive any answer.

Is it working only with additional plugin/jars? on different version?

Also why doesn't it have page in https://jmeter-plugins.org/ (although it displayed in search results in site)?


问:
convert RGB pixel to wavelength
I need to identify a spectrum emitted from a light source (spectrometer).
To do that, I need to convert each pixel to a wavelength.

To overcome the problem that the RGB values do not have a single value, I will use a prism so that I will get an optical lattice. This way, I'm receiving a deployment of the spectrum, and the difference in the spectrum is only along the X axis.

My question is, how do I convert the pixels to wavelengths and receive a plot of intensity as a function of wavelength.

答:
Late to the party. But here is an idea for accurately(close to scientific methodology) converting RGB of a sensor pixel to intensity value in a wavelength plot.

Get a light source of known wavelength(s).

The narrower the emission bandwidth, the better. Lasers are suitable for such requirements but also note the power and make sure it does not exceed you image sensor limits. It is better to calibrate the measurement system with three wavelengths (red, green, blue). Ideally when using red laser, readout the raw image and look for any charge accumulations on green and blue channel of a pixel. (Since each pixel has bayer filter pattern over it). If the accumulation is too high consider a good quality image sensors. And , then follow the HSV method suggested by Noel Segura Meraz. Use vertical binning for the image you captured. Vertical binning is where you simply add the intensity values of a column in the sensor array. Once you calibrate the system with these three laser, mix and match them to verify if your interpolation function works well.

Get the wavelength efficiency of pixels in your image sensors

If it is not possible to get this info from spec sheet of the the image sensor then introduce a thin vertical slit in your optical setup just before the image sensor thereby selecting only a specific wavelength. Get all the vertically binned intensity values of each wavelength to characterize your image sensor. The thin slit should not be so thin that in introduces diffraction effects of light.
The image sensor would have great characteristics if it has almost same intensity values for every wavelength. Use this data to scale your wavelength vs intensity plot obtained from step 1.

Use a broadband input light source before your optical setup to get the best  out of your spectrum

Although what you are trying to achieve is totally valid, it is not a highly accurate instrumentation system therefore not used by researchers/industry. In a true spectrometer a diffraction grating (primarily) is used, the distance between the lines on a grating and the angle of incidence is used to calculate the spread of wavelengths on a CCD sensor (or any linear array of photo sensors as a matter of fact). Generally, this angle is tuned to achieve required wavelength spread without losing resolution. Here's an example from Andor to design a system with their products.

Title: convert RGB pixel to wavelength


问:
daterangepicker not getting loaded in liferay7
I want to use daterange picker inside my portlet in liferay 7.Below are the scripts that i am loading inside my java code :

```<code>"com.liferay.portlet.header-portlet-css= //cdn.jsdelivr.net/bootstrap/3/css/bootstrap.css",
"com.liferay.portlet.header-portlet-css= //cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.css",

//MomentJS
"com.liferay.portlet.header-portlet-javascript= /js/plugins/fullcalendar/moment.min.js",
"com.liferay.portlet.header-portlet-javascript= //cdn.jsdelivr.net/momentjs/latest/moment.min.js",
"com.liferay.portlet.header-portlet-javascript= //cdn.jsdelivr.net/jquery/1/jquery.min.js",
"com.liferay.portlet.header-portlet-javascript= //cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.js",
</code>```

but when i open the portlet, it says

```<code>Uncaught TypeError: $(...).daterangepicker is not a function
</code>```

I have loaded all scripts as mentioned on the daterangepicker page(http://www.daterangepicker.com/) . What am i missing here?

答:
You are in a trick use case, as plugin support for JQuery within liferay is somehow odd. Please, visit this post to find the answer:

jQuery plugin in a Liferay 7 theme

Body:
I want to use daterange picker inside my portlet in liferay 7.Below are the scripts that i am loading inside my java code :

"com.liferay.portlet.header-portlet-css= //cdn.jsdelivr.net/bootstrap/3/css/bootstrap.css",
"com.liferay.portlet.header-portlet-css= //cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.css",

//MomentJS
"com.liferay.portlet.header-portlet-javascript= /js/plugins/fullcalendar/moment.min.js",
"com.liferay.portlet.header-portlet-javascript= //cdn.jsdelivr.net/momentjs/latest/moment.min.js",
"com.liferay.portlet.header-portlet-javascript= //cdn.jsdelivr.net/jquery/1/jquery.min.js",
"com.liferay.portlet.header-portlet-javascript= //cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.js",

but when i open the portlet, it says

Uncaught TypeError: $(...).daterangepicker is not a function

I have loaded all scripts as mentioned on the daterangepicker page(http://www.daterangepicker.com/) . What am i missing here?


问:
How to customize UITextField like this?
another questions...

How can i make this textfield??

With on the left a FIXED placeholder with a string and after it, an touchable zone, with text or the blue rectangle like screenshot.

I need to implement a view? Or there is a simple way to do it directly in textfield?

thanks again!

A

答: Take a look at the TTMessageRecipientField. On the Mac, this is achieved with an NSTokenField, but this isn't available in UIKit.</p>

ContentLicense: CC BY-SA 2.5

Title: How to customize UITextField like this?


问:
Talend DI & Windows registry interaction
I want to interact with Windows registry from Talend tool.

As interact action I mean search, insert, update, loop on a entry list and delete some keys and values.

I use Talend Data Integration tool (TIS) in Enterprise version but Open Source edition (TOS) is welcome.

Any advise to do this ?

Thanks a lot

Thomas

答:
I don't believe there are native components for this; but you can achieve this by using a tSystem component which issues a command to interact with Windows registry.

For instance, to delete a registry key you execute the command :

```<code>reg delete "HKCU\Some\Registry\Path" /f
</code>```

(The path will be a parameter in your component).

Here's an example :

And the output :

Body:
I don't believe there are native components for this; but you can achieve this by using a tSystem component which issues a command to interact with Windows registry.

For instance, to delete a registry key you execute the command :

reg delete "HKCU\Some\Registry\Path" /f

(The path will be a parameter in your component).

Here's an example :

And the output :


问:
Log all access of subdirectories
I have a directory structure like

```<code>/logging.php
/customer1/
/customer2/
/customer3/
...
</code>```

Now I need to log all access of the subdirs customer1, customer2, customer3 and so on.

Can I somehow (like a htaccess rule) lead all access trough a php file logging.php which saves the access into a mysql database and than forwards to the wanted directory?

I don't want to include the logging.php in every single file of the subdirs, as the subdirs are dynamically generated.

答:
A simple .htaccess rule should suffice.

```<code>RewriteRule ^(customer\d+(/.*)?)$ /logging.php?path=$1 [L]
</code>```

Within logging.php, just look at $_GET['path']

This is assuming that the directory and files in question are in the web root of your site (Usually something like public_html/ or wwwroot/)

Title: Log all access of subdirectories

Body:
I have a directory structure like

/logging.php
/customer1/
/customer2/
/customer3/
...

Now I need to log all access of the subdirs customer1, customer2, customer3 and so on.

Can I somehow (like a htaccess rule) lead all access trough a php file logging.php which saves the access into a mysql database and than forwards to the wanted directory?

I don't want to include the logging.php in every single file of the subdirs, as the subdirs are dynamically generated.

Body:
A simple .htaccess rule should suffice.

RewriteRule ^(customer\d+(/.*)?)$ /logging.php?path=$1 [L]

Within logging.php, just look at $_GET['path']

This is assuming that the directory and files in question are in the web root of your site (Usually something like public_html/ or wwwroot/)


问:
Accessing a function/state of a component in a wrapping HOC
So I have a component A (extends React.component) and it is wrapped with a higher order component B.

In component B's methods, I need to setState for A, or call a function in A (so that it can do the setState) - how is this generally done?

I can paste actual code here, but I thought it may complicate matters if there are standard ways of handling this situation.

Edit: here's the code - isOpen needs to change for the Modal to close, and it needs to change in handleSubmit....

```<code>import React from 'react';
import Modal from 'react-modal';
import { withFormik, Form, Field } from 'formik';
import Yup from 'yup';

// first part of Formik integration
const formikEnhancer = withFormik({
  mapPropsToValues(props) {
    return {
      personName: props.email || '',
      personSurname: props.surname || '',
      personCongregation: props.congregation || ''
    }
  },
  validationSchema: Yup.object().shape({
    personName: Yup.string().required().min(1),
    personSurname: Yup.string().required().min(2),
    personCongregation: Yup.string().required().min(8)
  }),
  handleSubmit(values, {props, resetForm, setErrors, setSubmitting}) {
    submitNewPerson(values, {resetForm, setErrors, setSubmitting});
    props.testCall;
  }
});

function submitNewPerson(v, {resetForm, setErrors, setSubmitting}) {
  //e.preventDefault();

  congregations = [];
  congregations.push(v.personCongregation);

  const peep = {
    name: v.personName,
    surname: v.personSurname,
    congregations: congregations//,
    //startDate: Number(e.target.componentStartDate.value),
    //endDate: Number(e.target.componentEndDate.value)
  };
    // do the db insert here and check for errors
    setSubmitting(false);
  });
};

class AddPerson extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: undefined,
      isOpen: false
    }
  }

  componentWillMount() {
    Modal.setAppElement('body');
  }

  renderCong() {
    // this just maps out a list of select options
  }

  render() {
    return (
      <div>
        <button className="button" onClick={()=> this.setState({isOpen:true, error:undefined})}>+ Add Person</button>
        <Modal isOpen={this.state.isOpen} contentLabel="Add Person"
          className = "boxed-view__box" overlayClassName="boxed-view boxed-view--modal">
          <Form className="boxed-view__form">
            <div>
              <Field type="text" name="personName" placeholder="Name" />
            </div>
            <div>
                <Field type="text" name="personSurname" placeholder="Surname" />
            </div>
            <div>
             <Field component="select" name="personCongregation" value={this.state.cong}>
                <option key="0" value="">- Select Option -</option>
                {this.renderCong()}
              </Field>
            </div>
            <button disabled={this.props.isSubmitting} className="button">Add Person</button>
            <button disabled={this.props.isSubmitting} type="button" className="button button--secondary" onClick={
              ()=> {
                this.props.resetForm();
                this.setState({isOpen:false});
              }}>Cancel</button>
          </Form>

        </Modal>
      </div>
    )
  };
};
</code>```

答:
Generally you send props to the component and then you handle those props with a function, that in this case sets the state with stuff, example:

```<code>class B extends React.Component{

   render(){
       <A toUpdateState={this.state.valueB} />
   }
}

class A extends React.Component{

   updateState(){
       this.setState({
           ...this.state,
           valueA: this.props.toUpdateState
       })
   }

   render(){...}
}
</code>```

If you trigger the state in the B component the A component will receive the info.

There are other ways to do this but without the code its hard to give you a diferent solution.

Body:
So I have a component A (extends React.component) and it is wrapped with a higher order component B.

In component B's methods, I need to setState for A, or call a function in A (so that it can do the setState) - how is this generally done?

I can paste actual code here, but I thought it may complicate matters if there are standard ways of handling this situation.

Edit: here's the code - isOpen needs to change for the Modal to close, and it needs to change in handleSubmit....

import React from 'react';
import Modal from 'react-modal';
import { withFormik, Form, Field } from 'formik';
import Yup from 'yup';

// first part of Formik integration
const formikEnhancer = withFormik({
  mapPropsToValues(props) {
    return {
      personName: props.email || '',
      personSurname: props.surname || '',
      personCongregation: props.congregation || ''
    }
  },
  validationSchema: Yup.object().shape({
    personName: Yup.string().required().min(1),
    personSurname: Yup.string().required().min(2),
    personCongregation: Yup.string().required().min(8)
  }),
  handleSubmit(values, {props, resetForm, setErrors, setSubmitting}) {
    submitNewPerson(values, {resetForm, setErrors, setSubmitting});
    props.testCall;
  }
});

function submitNewPerson(v, {resetForm, setErrors, setSubmitting}) {
  //e.preventDefault();

  congregations = [];
  congregations.push(v.personCongregation);

  const peep = {
    name: v.personName,
    surname: v.personSurname,
    congregations: congregations//,
    //startDate: Number(e.target.componentStartDate.value),
    //endDate: Number(e.target.componentEndDate.value)
  };
    // do the db insert here and check for errors
    setSubmitting(false);
  });
};

class AddPerson extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: undefined,
      isOpen: false
    }
  }

  componentWillMount() {
    Modal.setAppElement('body');
  }

  renderCong() {
    // this just maps out a list of select options
  }

  render() {
    return (

        <button className="button" onClick={()=> this.setState({isOpen:true, error:undefined})}>+ Add Person</button>
        <Modal isOpen={this.state.isOpen} contentLabel="Add Person"
          className = "boxed-view__box" overlayClassName="boxed-view boxed-view--modal">
          <Form className="boxed-view__form">

              <Field type="text" name="personName" placeholder="Name" />

                <Field type="text" name="personSurname" placeholder="Surname" />

             <Field component="select" name="personCongregation" value={this.state.cong}>
                <option key="0" value="">- Select Option -</option>
                {this.renderCong()}
              </Field>

            <button disabled={this.props.isSubmitting} className="button">Add Person</button>
            <button disabled={this.props.isSubmitting} type="button" className="button button--secondary" onClick={
              ()=> {
                this.props.resetForm();
                this.setState({isOpen:false});
              }}>Cancel</button>
          </Form>

        </Modal>

    )
  };
};

Body:
Generally you send props to the component and then you handle those props with a function, that in this case sets the state with stuff, example:

class B extends React.Component{

   render(){
       <A toUpdateState={this.state.valueB} />
   }
}

class A extends React.Component{

   updateState(){
       this.setState({
           ...this.state,
           valueA: this.props.toUpdateState
       })
   }

   render(){...}
}

If you trigger the state in the B component the A component will receive the info.

There are other ways to do this but without the code its hard to give you a diferent solution.


问:
ServiceStack JWT Auth Provider example
Can anyone get me ServiceStack's JWT Auth Provider example.

I want to use servicestack for user registration and login.

Also google, facebook, twitter for sign up.

答:
Please read the docs on JWT Auth Provider which provides both Server registration and Client examples.

techstacks.io and gistlyn.com are some examples that uses both OAuth and JWT Auth Providers.

Title: ServiceStack JWT Auth Provider example


问:
Rails Migration Create Table Primary Key
I am writing a migration script to create a table with a primary key column that is named guid and is a VARCHAR(25). The issue is I feel like I am having to double my effort to achieve what should be possible in one step.

If I run:

```<code>create_table(:global_feeds, :primary_key => 'guid') do |t|
  t.string :guid, :limit => 25
  t.text :title
  t.text :subtitle

  ...

  t.timestamps
end
</code>```

I get a table with a primary key called guid no column called id (which is what I want). However, the issue is the guid column is an INT(11) with auto increment turned on. So I have to run one additional command:

```<code>change_column :global_feeds, :guid, :string, :limit => 25
</code>```

Seems a bit convoluted to have to basically run two SQL commands to get what I believe should be possible in one.

Any suggestions on how to optimize this?

答:
You need to use #column instead of #string. For instance:

```<code>create_table(:global_feeds, :primary_key => 'guid') do |t|
  t.column :guid, "varchar(25)", :null => false
  ...
end
</code>```

Note that the varchar type is not portable to databases other than MySQL.

Body:
I am writing a migration script to create a table with a primary key column that is named guid and is a VARCHAR(25). The issue is I feel like I am having to double my effort to achieve what should be possible in one step.

If I run:

create_table(:global_feeds, :primary_key => 'guid') do |t|
  t.string :guid, :limit => 25
  t.text :title
  t.text :subtitle

  ...

  t.timestamps
end

I get a table with a primary key called guid no column called id (which is what I want). However, the issue is the guid column is an INT(11) with auto increment turned on. So I have to run one additional command:

change_column :global_feeds, :guid, :string, :limit => 25

Seems a bit convoluted to have to basically run two SQL commands to get what I believe should be possible in one.

Any suggestions on how to optimize this?

Body:
You need to use #column instead of #string. For instance:

create_table(:global_feeds, :primary_key => 'guid') do |t|
  t.column :guid, "varchar(25)", :null => false
  ...
end

Note that the varchar type is not portable to databases other than MySQL.


问:
Google Cloud Platform: Temporary Server error?
Google Cloud Platform is raising an error like:
Error: Server Error The server encountered a temporary error and could not complete your request. Please try again in 30 seconds.

We have GCP, CDN and Google Cloud Load Balancing with GCP.

How can we fix this server error?

答:
There is a detailed status message in the HTTP Load Balancer logs.

Also, I suggest that you confirm from Developers Console that the corresponding backends are healthy.


问:
Confirm before delete in Sails.js
I'm currently editing a back-end page, but I have a few problems.
I need a confirmation before I delete the Action as you can see I tried this so far but my code is completely skipping the confirm() and only redirects to the index.

Please take a look at the controller code below

```<code>delete(req, res, next) {
        Action
                .findOne(req.param('id'))
                .then(({id}) => {
                    confirm('U staat op het punt een actie te verwijderen, klik op "ok" om hier mee door te gaan');
                    if(confirm()=== true) {
                        Action
                            .destroy(id)
                            .then(() => {
                                FlashService.setFlash(req, 'success', 'Action has been deleted')
                                res.redirect('/answer/index')
                            })
                            .catch(err => res.redirect('/answer/index'))
                    }
                })
                .catch(err => res.redirect('/answer/index'))
    }

}
</code>```

I also tried console.log to see where my code is stranding but that would only give this error:

Unhandled rejection ReferenceError: confirm is not defined

edit

I tought it also might be usefull to maybe see the HTML so here you go
as you can see the delete is called upon submit maybe I'm doing that extremly wrong but it seems to work besides the confirm mentioned before

```<code><form action="/action/delete/<%= action.id %>" method="POST">
                            <button type="submit"
                                    class="btn btn-sm btn-icon btn-pure btn-default on-default"
                                    data-toggle="tooltip"
                                    data-original-title="Verwijder"><i class="icon wb-trash" aria-hidden="true"></i>
                            </button>
                        </form>
</code>```

EDIT 2.0

I kind of fixed the problem but still not really I made the following javascript for the delete it's a little basic but that isn't the problem please take a look

```<code><script>
    function Delete(){
        let c = confirm('U staat op het punt een actie te verwijderen, klik op "ok" om hier mee door te gaan');
        if (c){
            console.log("done");
            window.location.href = "/action/delete/<%= action.id %>"
        }

        else{
            console.log("failed")
            window.location.href = "/answer/show/<%= answer.id %>"
        }
    }
</script>
</code>```

however, when I go to this page it says "action not defined" but I'm quite sure it is defined to be honest.

I don't really know what I'm doing wrong, any help would be nice

答:
You cannot use the client side confirm javascript on the server side. It does not exist. You should instead call confirm before sending request to the server.

Like so

```<code><button onclick="delete()">Delete</button>

<script>
function delete() {
var confirm = confirm("Do you want to delete?")
if(confirm){
// Call server
}
}
</script>
</code>```

Title: Confirm before delete in Sails.js

Body:
I'm currently editing a back-end page, but I have a few problems.
I need a confirmation before I delete the Action as you can see I tried this so far but my code is completely skipping the confirm() and only redirects to the index.

Please take a look at the controller code below

delete(req, res, next) {
        Action
                .findOne(req.param('id'))
                .then(({id}) => {
                    confirm('U staat op het punt een actie te verwijderen, klik op "ok" om hier mee door te gaan');
                    if(confirm()=== true) {
                        Action
                            .destroy(id)
                            .then(() => {
                                FlashService.setFlash(req, 'success', 'Action has been deleted')
                                res.redirect('/answer/index')
                            })
                            .catch(err => res.redirect('/answer/index'))
                    }
                })
                .catch(err => res.redirect('/answer/index'))
    }

}

I also tried console.log to see where my code is stranding but that would only give this error:

Unhandled rejection ReferenceError: confirm is not defined

edit

I tought it also might be usefull to maybe see the HTML so here you go
as you can see the delete is called upon submit maybe I'm doing that extremly wrong but it seems to work besides the confirm mentioned before

<form action="/action/delete/<%= action.id %>" method="POST">
                            <button type="submit"
                                    class="btn btn-sm btn-icon btn-pure btn-default on-default"
                                    data-toggle="tooltip"
                                    data-original-title="Verwijder">
                            </button>
                        </form>

EDIT 2.0

I kind of fixed the problem but still not really I made the following javascript for the delete it's a little basic but that isn't the problem please take a look

however, when I go to this page it says "action not defined" but I'm quite sure it is defined to be honest.

I don't really know what I'm doing wrong, any help would be nice

Body:
You cannot use the client side confirm javascript on the server side. It does not exist. You should instead call confirm before sending request to the server.

Like so

<button onclick="delete()">Delete</button>

<script>
function delete() {
var confirm = confirm("Do you want to delete?")
if(confirm){
// Call server
}
}
</script>


问:
Video compression process taking long processing time
Hello every one i am looking for the video compression (like whats'up /Telegram).After lot off R&d  i got ffmpeg & videocodec like library but both library taking long compression time now I am doing video compression successfully for all version but it is very time consuming process its taking almost ~30 second for 1Mb .Please if any have idea (about library or Algorithm ) how we do compression fast like what'up in less time
Thanku</p>

答: You can use preset argument to specific to veryfast.


问:
Laravel get unknown file after upload
in my administrator of website, i'm implementing upload file, when i design view and define validations and controller this uploader upload unknown file into upload directory when i try to use that

result of dd($request->all()); is:

```<code>array:6 [▼
  "_token" => "9tNfMnakc6viX2qYRYr6abkrJapo1qz7jG88USYf"
  "title" => "hello"
  "type" => "post"
  "images" => "Untitled-1.png"
]
</code>```

validation:

```<code>return [
    'title' => 'required|string|max:200|unique:contents',
    'images'=>'required|mimes:jpeg,jpg,gif,png'
];
</code>```

my store function on controller:

```<code>public function store(RequestContents $request)
{
    $featured_images = $request->file('images');
    $this->uploadImage($featured_images);
    ...
}

public function uploadImage($file)
{
    $year = Carbon::now()->year;
    $imagePath = "/uploads/post_images/{$year}/";
    $filename = $file->getClientOriginalName();
    $file->move(public_path($imagePath, $filename));
}
</code>```

html:

```<code><form action="manage_contents" method="POST" enctype="multipart/form-data">
...

<div class="media-body">
    <input type="file" class="file-styled" name="images">
</div>

...
</form>
</code>```

output:

答:
You need also the extension for the filename. What laravel 5 are you using?</p>

```<code>$filename = $file->getClientOriginalName() . $file->getClientOriginalExtension();
</code>```

Title: Laravel get unknown file after upload

Body:
in my administrator of website, i'm implementing upload file, when i design view and define validations and controller this uploader upload unknown file into upload directory when i try to use that

result of dd($request->all()); is:

array:6 [▼
  "_token" => "9tNfMnakc6viX2qYRYr6abkrJapo1qz7jG88USYf"
  "title" => "hello"
  "type" => "post"
  "images" => "Untitled-1.png"
]

validation:

return [
    'title' => 'required|string|max:200|unique:contents',
    'images'=>'required|mimes:jpeg,jpg,gif,png'
];

my store function on controller:

public function store(RequestContents $request)
{
    $featured_images = $request->file('images');
    $this->uploadImage($featured_images);
    ...
}

public function uploadImage($file)
{
    $year = Carbon::now()->year;
    $imagePath = "/uploads/post_images/{$year}/";
    $filename = $file->getClientOriginalName();
    $file->move(public_path($imagePath, $filename));
}

html:

<form action="manage_contents" method="POST" enctype="multipart/form-data">
...

    <input type="file" class="file-styled" name="images">

...
</form>

output:

Body:
You need also the extension for the filename. What laravel 5 are you using?

$filename = $file->getClientOriginalName() . $file->getClientOriginalExtension();


问:
Page fadeOut when links are clicked, except mailto: links
in the below code, I am fading out any page, and then fading in the new page, when any  tag is clicked. However, there are certain instances where we don't want to fade the page out on click, for example, when an  tag is set to open externally via target="_blank". The code below reflects this and is working successfully.

However, one thing I'm not sure how to achieve, is to prevent the fade out when a link contains a mailto: reference, as obviously this is designed to open a mailing client window. Therefore I don't want the page to fade out?

Thank you.

```<code>$(window).bind("pageshow", function(event) {
    if (event.originalEvent.persisted) {
        window.location.reload();
    }
});

(function($) {
    if (window.history) {
        $(window).on('popstate', function() {
            $("body").show();
        });
    }

    // When links are clicked
    $(document).on("click", "a", function() {
    var $link   = $(this);
    var $href   = $link.attr("href");
    var $target = $link.attr("target");

        // If link exists
        if ($href) {
            // Fade out all links unless set to open in external window target="_blank"
            if ($target !== "_blank") {
                $("body").fadeOut(250, function() {
                    history.pushState($href, null, null);
                    window.location.href = $href;
                });
                return false;
            }
        }
    });

    // On page load, fade in
    $(document).ready(function() {
        $("body").fadeTo(250, 1);
    });
}(window.jQuery));
</code>```

答:
For a link that contains a mailto: reference just change this part in your code

```<code>if ($href) {
</code>```

with this

```<code>if ($href && $href.indexOf('mailto:')!==-1) {
</code>```

Alternatively check this fiddle demonstrating the usage of :not. In your case don't forget to use event.preventDefault() for the mailto links from opening mail client window.

Body:
in the below code, I am fading out any page, and then fading in the new page, when any  tag is clicked. However, there are certain instances where we don't want to fade the page out on click, for example, when an  tag is set to open externally via target="_blank". The code below reflects this and is working successfully.

However, one thing I'm not sure how to achieve, is to prevent the fade out when a link contains a mailto: reference, as obviously this is designed to open a mailing client window. Therefore I don't want the page to fade out?

Thank you.

$(window).bind("pageshow", function(event) {
    if (event.originalEvent.persisted) {
        window.location.reload();
    }
});

(function($) {
    if (window.history) {
        $(window).on('popstate', function() {
            $("body").show();
        });
    }

    // When links are clicked
    $(document).on("click", "a", function() {
    var $link   = $(this);
    var $href   = $link.attr("href");
    var $target = $link.attr("target");

        // If link exists
        if ($href) {
            // Fade out all links unless set to open in external window target="_blank"
            if ($target !== "_blank") {
                $("body").fadeOut(250, function() {
                    history.pushState($href, null, null);
                    window.location.href = $href;
                });
                return false;
            }
        }
    });

    // On page load, fade in
    $(document).ready(function() {
        $("body").fadeTo(250, 1);
    });
}(window.jQuery));

Body:
For a link that contains a mailto: reference just change this part in your code

if ($href) {

with this

if ($href && $href.indexOf('mailto:')!==-1) {

Alternatively check this fiddle demonstrating the usage of :not. In your case don't forget to use event.preventDefault() for the mailto links from opening mail client window.


问:
QueryException SQLSTATE[42S02]: Base table or view not found: 1146 Table
i learn foreign key in laravel for the first time .. i have this message error when i insert data on the form to table . i think my table is fine. can u tell me how to solve this ?

Controller :

```<code>public function tambah(Request $request){
    $a = new Admin;
    $this->validate($request, ['nama'=>'required|unique:ab']);
    $a->id = $request->id;
    $a->nama = $request->nama;
    $a->save();

    return redirect()->to('admin/data_desa')->with('success','Data berhasil ditambahkan');
}

}
</code>```

table :

```<code> class CreateDesasTable extends Migration
 {
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    //
    Schema::dropIfExist('desas');
    Schema::create('desas', function(Blueprint $table){
    $table->increments('id');
    $table->string('nama');

});
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    //
    Schema::dropIfExist('desas');

}
}
</code>```

Route :

```<code>Route::group(['middleware' => 'web'], function(){
Route::group(['prefix' => 'tanitani'], function(){
    Route::get('admin', 'AdminController@index');
    Route::get('admin/data_desa','AdminController@tampil');
    Route::post('admin/data_desa', 'AdminController@tambah');
</code>```

答:
It looks like you are not working with laravel eloquent model conventions.

Are you sure that model Admin is the model that you are required to save desas data in your controller?

if the answer is true update model Admin with

```<code>protected $table = 'desas';
</code>```

Recommendation: Try to use the same name convention between models and database tables.

See https://laravel.com/docs/5.4/eloquent#eloquent-model-conventions for more information.

Recommended docs before continue:

https://laravel.com/docs/5.4/migrations

https://laravel.com/docs/5.4/eloquent

Body:
i learn foreign key in laravel for the first time .. i have this message error when i insert data on the form to table . i think my table is fine. can u tell me how to solve this ?

Controller :

public function tambah(Request $request){
    $a = new Admin;
    $this->validate($request, ['nama'=>'required|unique:ab']);
    $a->id = $request->id;
    $a->nama = $request->nama;
    $a->save();

    return redirect()->to('admin/data_desa')->with('success','Data berhasil ditambahkan');
}

}

table :

 class CreateDesasTable extends Migration
 {
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    //
    Schema::dropIfExist('desas');
    Schema::create('desas', function(Blueprint $table){
    $table->increments('id');
    $table->string('nama');

});
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    //
    Schema::dropIfExist('desas');

}
}

Route :

Route::group(['middleware' => 'web'], function(){
Route::group(['prefix' => 'tanitani'], function(){
    Route::get('admin', 'AdminController@index');
    Route::get('admin/data_desa','AdminController@tampil');
    Route::post('admin/data_desa', 'AdminController@tambah');

Body:
It looks like you are not working with laravel eloquent model conventions.

Are you sure that model Admin is the model that you are required to save desas data in your controller?

if the answer is true update model Admin with

protected $table = 'desas';

Recommendation: Try to use the same name convention between models and database tables.

See https://laravel.com/docs/5.4/eloquent#eloquent-model-conventions for more information.

Recommended docs before continue:

https://laravel.com/docs/5.4/migrations

https://laravel.com/docs/5.4/eloquent


问:
iOS - NSInternalInconsistencyException happens on iOS 9 and 10 but working fine on iOS 11
This is the error I am getting on devices with iOS 9 and 10 :

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'request for number of
  items before section 9223372036854775807 when there are only 1
  sections in the collection view'

The error seems clear to me, however I am unable to understand why this is not happening on devices with iOS 11.

I don't know how to fix it.

Here is my code :

```<code>extension MainTileViewController: MainForecastsDelegate {
func mainForecasts(_ forecastVC: MainForecastsViewController!, didChangeWith object: Any!) {
    if let cell = self.outletWeatherForecastCollectionView.cellForItem(at: self.currentIndexPath) as? MainTileCollectionViewCell {
        // Some stuff...
    }
}
</code>```

The crash happens here. This is a protocol method triggered when the user switch day etc...

Obviously I have an issue with my currentIndexPath.

Here is my initialization :

```<code> var currentIndexPath : IndexPath = []
</code>```

And in the viewDidLoad :

```<code>self.currentIndexPath = IndexPath(item: 0, section: 0)
</code>```

How can I secure my code so that it won't crash ? Can you explain me the changing behavior between collectionView from iOS 9/10 with iOS 11 ones (except prefetching).

答: I would suggest changing your approach a bit. Let your collection view cell subclass be responsible for updating itself, perhaps from a notification. Trying to retain an index path or reference to a cell will always be problematic given their tendency to be reused.</p>

Body:
This is the error I am getting on devices with iOS 9 and 10 :

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'request for number of
  items before section 9223372036854775807 when there are only 1
  sections in the collection view'

The error seems clear to me, however I am unable to understand why this is not happening on devices with iOS 11.

I don't know how to fix it.

Here is my code :

extension MainTileViewController: MainForecastsDelegate {
func mainForecasts(_ forecastVC: MainForecastsViewController!, didChangeWith object: Any!) {
    if let cell = self.outletWeatherForecastCollectionView.cellForItem(at: self.currentIndexPath) as? MainTileCollectionViewCell {
        // Some stuff...
    }
}

The crash happens here. This is a protocol method triggered when the user switch day etc...

Obviously I have an issue with my currentIndexPath.

Here is my initialization :

 var currentIndexPath : IndexPath = []

And in the viewDidLoad :

self.currentIndexPath = IndexPath(item: 0, section: 0)

How can I secure my code so that it won't crash ? Can you explain me the changing behavior between collectionView from iOS 9/10 with iOS 11 ones (except prefetching).


问:
Sending JSON to a server
How do I turn this...

```<code>{
  'name': 'John',
  'surname': 'Smith'
}
</code>```

...into this?

```<code>name=John&surname=Smith
</code>```

I'm trying to send JSON  to a server via AJAX

thank you

答:
```<code>var jsoncode = {
  'name': 'John',
  'surname': 'Smith'
};
var querystring = 'name=' + encodeURI(jsoncode.name) + '&surname=' + encodeURI(jsoncode.surname);
</code>```

Title: Sending JSON to a server

Body:
How do I turn this...

{
  'name': 'John',
  'surname': 'Smith'
}

...into this?

name=John&surname=Smith

I'm trying to send JSON  to a server via AJAX

thank you