问:
Delete function always selects same ID - blog - Codeigniter
So, I have been trying to get this delete function to work now for a while.

At the bottom of the foreach I have a delete function. The funtion itself does work, however it always selects the post id of 1.

View

```<code><div><?php foreach($posts as $post) : ?>
<hr>
<h3><?php echo $post['title']; ?></h3>
<div class="row">
    <div class="col-md-3">
        <img class="post-thumb" src="<?php echo site_url(); ?>posts/image/<?php echo $post['post_image']; ?>">
    </div>
    <div class="col-md-9">
        <small class="post-date">Posted on: <?php echo $post['created_at']; ?> in <strong><?php echo $post['name']; ?></strong></small><br>
    <?php echo word_limiter($post['body'], 60); ?>
    <br><br>
    <p><a class="btn btn-default" href="<?php echo site_url('/posts/'.$post['slug']); ?>">Read More</a></p>
    </div>
</div>
<?php echo form_open('/posts/delete/'.$post['id']); ?>
    <input type="submit" value="Delete" class="btn btn-danger">
</form>
</code>```

Controller

```<code>public function posts($offset = 0){

  // Pagination Config
  $config['base_url'] = base_url() . 'admins/posts/';
  $config['total_rows'] = $this->db->count_all('posts');
  $config['per_page'] = 10;
  $config['uri_segment'] = 3;
  $config['attributes'] = array('class' => 'pagination-link');

  // Init Pagination
  $this->pagination->initialize($config);

  $data['title'] = 'Latest Posts';

  $data['posts'] = $this->post_model->get_posts(FALSE, $config['per_page'], $offset);

    $this->load->view('templates/header');
    $this->load->view('admins/posts', $data);
    $this->load->view('templates/footer');
}
</code>```

Model

```<code>public function delete_post($id){
  $image_file_name = $this->db->select('post_image')->get_where('posts', array('id' => $id))->row()->post_image;
  $cwd = getcwd(); // save the current working directory
  $image_file_path = $cwd."\\assets\\images\\posts\\";
  chdir($image_file_path);
  unlink($image_file_name);
  chdir($cwd); // Restore the previous working directory
  $this->db->where('id', $id);
  $this->db->delete('posts');
  return true;
}
</code>```

EDIT:
get_posts in model

```<code>public function get_posts($slug = FALSE, $limit = FALSE, $offset = FALSE){
  if($limit){
    $this->db->limit($limit, $offset);
  }
  if($slug === FALSE){
    $this->db->order_by('posts.id', 'DESC');
    $this->db->join('categories', 'categories.id = posts.category_id');
    $query = $this->db->get('posts');
    return $query->result_array();
  }

  $query = $this->db->get_where('posts', array('slug' => $slug));
  return $query->row_array();
}
</code>```

The function does run and I get a confirmation message, so the only thing I am really confused about is the Id.
The whole thing is written using the CodeIgniter Framework.

答:
you are returning only 1 line with row_array() function so you should replace for result_array():</p>

```<code>public function get_posts($slug = FALSE, $limit = FALSE, $offset = FALSE){
  if($limit){
    $this->db->limit($limit, $offset);
  }

  if($slug === FALSE){
    $this->db->order_by('posts.id', 'DESC');
    $this->db->join('categories', 'categories.id = posts.category_id');
    $query = $this->db->get('posts');
    return $query->result_array();
  }else{
    $query = $this->db->get_where('posts', array('slug' => $slug));
    return $query->result_array();
  }
}
</code>```

Body:
So, I have been trying to get this delete function to work now for a while.

At the bottom of the foreach I have a delete function. The funtion itself does work, however it always selects the post id of 1.

View

<?php foreach($posts as $post) : ?>

<?php echo $post['title']; ?>

        <img class="post-thumb" src="<?php echo site_url(); ?>posts/image/<?php echo $post['post_image']; ?>">

        Posted on: <?php echo $post['created_at']; ?> in <?php echo $post['name']; ?>

    <?php echo word_limiter($post['body'], 60); ?>

<a class="btn btn-default" href="<?php echo site_url('/posts/'.$post['slug']); ?>">Read More

<?php echo form_open('/posts/delete/'.$post['id']); ?>
    <input type="submit" value="Delete" class="btn btn-danger">
</form>

Controller

public function posts($offset = 0){

  // Pagination Config
  $config['base_url'] = base_url() . 'admins/posts/';
  $config['total_rows'] = $this->db->count_all('posts');
  $config['per_page'] = 10;
  $config['uri_segment'] = 3;
  $config['attributes'] = array('class' => 'pagination-link');

  // Init Pagination
  $this->pagination->initialize($config);

  $data['title'] = 'Latest Posts';

  $data['posts'] = $this->post_model->get_posts(FALSE, $config['per_page'], $offset);

    $this->load->view('templates/header');
    $this->load->view('admins/posts', $data);
    $this->load->view('templates/footer');
}

Model

public function delete_post($id){
  $image_file_name = $this->db->select('post_image')->get_where('posts', array('id' => $id))->row()->post_image;
  $cwd = getcwd(); // save the current working directory
  $image_file_path = $cwd."\\assets\\images\\posts\\";
  chdir($image_file_path);
  unlink($image_file_name);
  chdir($cwd); // Restore the previous working directory
  $this->db->where('id', $id);
  $this->db->delete('posts');
  return true;
}

EDIT:
get_posts in model

public function get_posts($slug = FALSE, $limit = FALSE, $offset = FALSE){
  if($limit){
    $this->db->limit($limit, $offset);
  }
  if($slug === FALSE){
    $this->db->order_by('posts.id', 'DESC');
    $this->db->join('categories', 'categories.id = posts.category_id');
    $query = $this->db->get('posts');
    return $query->result_array();
  }

  $query = $this->db->get_where('posts', array('slug' => $slug));
  return $query->row_array();
}

The function does run and I get a confirmation message, so the only thing I am really confused about is the Id.
The whole thing is written using the CodeIgniter Framework.

Body:
you are returning only 1 line with row_array() function so you should replace for result_array():

public function get_posts($slug = FALSE, $limit = FALSE, $offset = FALSE){
  if($limit){
    $this->db->limit($limit, $offset);
  }

  if($slug === FALSE){
    $this->db->order_by('posts.id', 'DESC');
    $this->db->join('categories', 'categories.id = posts.category_id');
    $query = $this->db->get('posts');
    return $query->result_array();
  }else{
    $query = $this->db->get_where('posts', array('slug' => $slug));
    return $query->result_array();
  }
}


来源: stackexchange

问:
List<T> add method in C#
As I know. List Add method works as below.

```<code>List<string> cities = new List<string>();
cities.Add("New York");
cities.Add("Mumbai");
cities.Add("Berlin");
cities.Add("Istanbul");
</code>```

If I designed the data structure as this

```<code>List<object> lstObj = new List<object>();
if (true)  // string members
{
    cities.Add("New York");
    cities.Add("Istanbul");
}
else // List obj members here
{
    List<object> AListObject= new List<object>();
    cities.Add(AListObject);  // how to handle this?
}
</code>```

Does the List Add method works or not if I add different types members in the same function.

答:
You can add anything to a List<object>, so if you changed cities to a List<object> then your code would work.

```<code>var list = new List<object>();

list.Add("hello");
list.Add(1);
list.Add(new List<bool>());

Console.WriteLine(list.Count());
</code>```

Having said that, it's almost certainly a bad way to code whatever it is you're trying to do.

ContentLicense: CC BY-SA 2.5

Title: List<T> add method in C#

Body:
As I know. List Add method works as below.

List<string> cities = new List<string>();
cities.Add("New York");
cities.Add("Mumbai");
cities.Add("Berlin");
cities.Add("Istanbul");

If I designed the data structure as this

List<object> lstObj = new List<object>();
if (true)  // string members
{
    cities.Add("New York");
    cities.Add("Istanbul");
}
else // List obj members here
{
    List<object> AListObject= new List<object>();
    cities.Add(AListObject);  // how to handle this?
}

Does the List Add method works or not if I add different types members in the same function.

Body:
You can add anything to a List<object>, so if you changed cities to a List<object> then your code would work.

var list = new List<object>();

list.Add("hello");
list.Add(1);
list.Add(new List<bool>());

Console.WriteLine(list.Count());

Having said that, it's almost certainly a bad way to code whatever it is you're trying to do.


问:
ActiveRecord find and only return selected columns

edit 2

If you stumble across this, check both answers as I'd now use pluck for this

I have a fairly large custom dataset that I'd like to return to be echoe'd out as json. One part is:

```<code>l=Location.find(row.id)
tmp[row.id]=l
</code>```

but I'd like to do something like:

```<code>l=Location.find(row.id).select("name, website, city")
tmp[row.id]=l
</code>```

but this doesn't seem to be working. How would I get this to work?

thx

edit 1

alternatively, is there a way that I can pass an array of only the attributes I want included?

答:
My answer comes quite late because I'm a pretty new developer. This is what you can do:

```<code>Location.select(:name, :website, :city).find(row.id)
</code>```

Btw, this is Rails 4

ContentLicense: CC BY-SA 3.0

Body:
edit 2

If you stumble across this, check both answers as I'd now use pluck for this

I have a fairly large custom dataset that I'd like to return to be echoe'd out as json. One part is:

l=Location.find(row.id)
tmp[row.id]=l

but I'd like to do something like:

l=Location.find(row.id).select("name, website, city")
tmp[row.id]=l

but this doesn't seem to be working. How would I get this to work?

thx

edit 1

alternatively, is there a way that I can pass an array of only the attributes I want included?

Body:
My answer comes quite late because I'm a pretty new developer. This is what you can do:

Location.select(:name, :website, :city).find(row.id)

Btw, this is Rails 4

ContentLicense: CC BY-SA 4.0


问:
Looking for ways to simplify my code
I'm having trouble adding another function in that macro I used to activate or deactivate columns in a Excel Workbook we are using at work. I'm getting the Out of stack space error when running it just adding one of the following function.

Mostly, I've used an If( ;1;0) to manage the activation part and an If(;TRUE;FALSE) for the locked/unlocked part. The function I want to had is based on the same idea using a verification code to Clearcontents of a cell and locked it. If the verification code is false, then, I want the cell to be unlocked so the user can write the value. Here is the code line I want to had times 15 as already done for the locked, unlocked function.

```<code>If Range("AS16") = "Vrai" Then
Range("AA16").ClearContents
Range("AA16").Locked = True
Else:
Range("AA16").Locked = False
End If
</code>```

Here is the code I'm using right now.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
ActiveSheet.Unprotect ("Francis")
Dim Cell As Range
Set Cell = ActiveCell
Application.ScreenUpdating = False

For Each cellule In Range("S50:X50")
If cellule.Value = "1" Then cellule.EntireColumn.Hidden = False
Next cellule

For Each cellule In Range("S50:X50")
If cellule.Value = "0" Then cellule.EntireColumn.Hidden = True
Next cellule

For Each cellule In Range("I50:J50")
If cellule.Value = "1" Then cellule.EntireColumn.Hidden = False
Next cellule

For Each cellule In Range("I50:J50")
If cellule.Value = "0" Then cellule.EntireColumn.Hidden = True
Next cellule

If Range("AR16") = "Vrai" Then
Range("K16").Locked = False
Range("O16").Locked = False
Else:
Range("K16").Locked = True
Range("O16").Locked = True
End If

If Range("AR18") = "Vrai" Then
Range("K18").Locked = False
Range("O18").Locked = False
Else:
Range("K18").Locked = True
Range("O18").Locked = True
End If

If Range("AR20") = "Vrai" Then
Range("K20").Locked = False
Range("O20").Locked = False
Else:
Range("K20").Locked = True
Range("O20").Locked = True
End If

If Range("AR22") = "Vrai" Then
Range("K22").Locked = False
Range("O22").Locked = False
Else:
Range("K22").Locked = True
Range("O22").Locked = True
End If

If Range("AR24") = "Vrai" Then
Range("K24").Locked = False
Range("O24").Locked = False
Else:
Range("K24").Locked = True
Range("O24").Locked = True
End If

If Range("AR26") = "Vrai" Then
Range("K26").Locked = False
Range("O26").Locked = False
Else:
Range("K26").Locked = True
Range("O26").Locked = True
End If

If Range("AR28") = "Vrai" Then
Range("K28").Locked = False
Range("O28").Locked = False
Else:
Range("K28").Locked = True
Range("O28").Locked = True
End If

If Range("AR30") = "Vrai" Then
Range("K30").Locked = False
Range("O30").Locked = False
Else:
Range("K30").Locked = True
Range("O30").Locked = True
End If

If Range("AR32") = "Vrai" Then
Range("K32").Locked = False
Range("O32").Locked = False
Else:
Range("K32").Locked = True
Range("O32").Locked = True
End If

If Range("AR34") = "Vrai" Then
Range("K34").Locked = False
Range("O34").Locked = False
Else:
Range("K34").Locked = True
Range("O34").Locked = True
End If

If Range("AR36") = "Vrai" Then
Range("K36").Locked = False
Range("O36").Locked = False
Else:
Range("K36").Locked = True
Range("O36").Locked = True
End If

If Range("AR38") = "Vrai" Then
Range("K38").Locked = False
Range("O38").Locked = False
Else:
Range("K38").Locked = True
Range("O38").Locked = True
End If

If Range("AR40") = "Vrai" Then
Range("K40").Locked = False
Range("O40").Locked = False
Else:
Range("K40").Locked = True
Range("O40").Locked = True
End If

If Range("AR42") = "Vrai" Then
Range("K42").Locked = False
Range("O42").Locked = False
Else:
Range("K42").Locked = True
Range("O42").Locked = True
End If

If Range("AR44") = "Vrai" Then
Range("K44").Locked = False
Range("O44").Locked = False
Else:
Range("K44").Locked = True
Range("O44").Locked = True
End If

Application.ScreenUpdating = True
Application.Goto Cell

'ActiveSheet.Protect Password:="Francis"
End Sub
</code>```

Thanks a lot for your help.

Have a nice day!

答:
The Out of stack error is caused by the Change event, as noted by @Mat

Try this version which also turns the events off and on

```<code>Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim cellule As Range, r As Long, isVrai As Boolean

    ActiveSheet.Unprotect "Francis"
    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    For Each cellule In Union(Range("I50:J50"), Range("S50:X50"))
        With cellule
            Select Case .Value2
                Case "1": .EntireColumn.Hidden = False
                Case "0": .EntireColumn.Hidden = True
            End Select
        End With
    Next
    For r = 16 To 44 Step 2
        isVrai = (Range("AR" & r).Value2 = "Vrai")
        Range("K" & r).Locked = Not isVrai
        Range("O" & r).Locked = Not isVrai
        If isVrai Then Range("AR" & r).ClearContents
    Next

    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With
    'ActiveSheet.Protect Password:="Francis"
End Sub
</code>```

Title: Looking for ways to simplify my code

Body:
I'm having trouble adding another function in that macro I used to activate or deactivate columns in a Excel Workbook we are using at work. I'm getting the Out of stack space error when running it just adding one of the following function.

Mostly, I've used an If( ;1;0) to manage the activation part and an If(;TRUE;FALSE) for the locked/unlocked part. The function I want to had is based on the same idea using a verification code to Clearcontents of a cell and locked it. If the verification code is false, then, I want the cell to be unlocked so the user can write the value. Here is the code line I want to had times 15 as already done for the locked, unlocked function.

If Range("AS16") = "Vrai" Then
Range("AA16").ClearContents
Range("AA16").Locked = True
Else:
Range("AA16").Locked = False
End If

Here is the code I'm using right now.

Private Sub Worksheet_Change(ByVal Target As Range)
ActiveSheet.Unprotect ("Francis")
Dim Cell As Range
Set Cell = ActiveCell
Application.ScreenUpdating = False

For Each cellule In Range("S50:X50")
If cellule.Value = "1" Then cellule.EntireColumn.Hidden = False
Next cellule

For Each cellule In Range("S50:X50")
If cellule.Value = "0" Then cellule.EntireColumn.Hidden = True
Next cellule

For Each cellule In Range("I50:J50")
If cellule.Value = "1" Then cellule.EntireColumn.Hidden = False
Next cellule

For Each cellule In Range("I50:J50")
If cellule.Value = "0" Then cellule.EntireColumn.Hidden = True
Next cellule

If Range("AR16") = "Vrai" Then
Range("K16").Locked = False
Range("O16").Locked = False
Else:
Range("K16").Locked = True
Range("O16").Locked = True
End If

If Range("AR18") = "Vrai" Then
Range("K18").Locked = False
Range("O18").Locked = False
Else:
Range("K18").Locked = True
Range("O18").Locked = True
End If

If Range("AR20") = "Vrai" Then
Range("K20").Locked = False
Range("O20").Locked = False
Else:
Range("K20").Locked = True
Range("O20").Locked = True
End If

If Range("AR22") = "Vrai" Then
Range("K22").Locked = False
Range("O22").Locked = False
Else:
Range("K22").Locked = True
Range("O22").Locked = True
End If

If Range("AR24") = "Vrai" Then
Range("K24").Locked = False
Range("O24").Locked = False
Else:
Range("K24").Locked = True
Range("O24").Locked = True
End If

If Range("AR26") = "Vrai" Then
Range("K26").Locked = False
Range("O26").Locked = False
Else:
Range("K26").Locked = True
Range("O26").Locked = True
End If

If Range("AR28") = "Vrai" Then
Range("K28").Locked = False
Range("O28").Locked = False
Else:
Range("K28").Locked = True
Range("O28").Locked = True
End If

If Range("AR30") = "Vrai" Then
Range("K30").Locked = False
Range("O30").Locked = False
Else:
Range("K30").Locked = True
Range("O30").Locked = True
End If

If Range("AR32") = "Vrai" Then
Range("K32").Locked = False
Range("O32").Locked = False
Else:
Range("K32").Locked = True
Range("O32").Locked = True
End If

If Range("AR34") = "Vrai" Then
Range("K34").Locked = False
Range("O34").Locked = False
Else:
Range("K34").Locked = True
Range("O34").Locked = True
End If

If Range("AR36") = "Vrai" Then
Range("K36").Locked = False
Range("O36").Locked = False
Else:
Range("K36").Locked = True
Range("O36").Locked = True
End If

If Range("AR38") = "Vrai" Then
Range("K38").Locked = False
Range("O38").Locked = False
Else:
Range("K38").Locked = True
Range("O38").Locked = True
End If

If Range("AR40") = "Vrai" Then
Range("K40").Locked = False
Range("O40").Locked = False
Else:
Range("K40").Locked = True
Range("O40").Locked = True
End If

If Range("AR42") = "Vrai" Then
Range("K42").Locked = False
Range("O42").Locked = False
Else:
Range("K42").Locked = True
Range("O42").Locked = True
End If

If Range("AR44") = "Vrai" Then
Range("K44").Locked = False
Range("O44").Locked = False
Else:
Range("K44").Locked = True
Range("O44").Locked = True
End If

Application.ScreenUpdating = True
Application.Goto Cell

'ActiveSheet.Protect Password:="Francis"
End Sub

Thanks a lot for your help.

Have a nice day!

Body:
The Out of stack error is caused by the Change event, as noted by @Mat

Try this version which also turns the events off and on

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim cellule As Range, r As Long, isVrai As Boolean

    ActiveSheet.Unprotect "Francis"
    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    For Each cellule In Union(Range("I50:J50"), Range("S50:X50"))
        With cellule
            Select Case .Value2
                Case "1": .EntireColumn.Hidden = False
                Case "0": .EntireColumn.Hidden = True
            End Select
        End With
    Next
    For r = 16 To 44 Step 2
        isVrai = (Range("AR" & r).Value2 = "Vrai")
        Range("K" & r).Locked = Not isVrai
        Range("O" & r).Locked = Not isVrai
        If isVrai Then Range("AR" & r).ClearContents
    Next

    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With
    'ActiveSheet.Protect Password:="Francis"
End Sub


问:
Foundation framework. No NSString.h file
I'm getting a few errors just after I updated my working copy via SVN.

```<code>/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.2.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSCharacterSet.h:8:0 /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.2.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSCharacterSet.h:8:32: error: Foundation/NSString.h: No such file or directory

/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.2.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSCharacterSet.h:45:0 /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.2.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSCharacterSet.h:45: error: expected ')' before 'unichar'

/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.2.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSPathUtilities.h:10:0 /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.2.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSPathUtilities.h:10: error: cannot find interface declaration for 'NSString'
</code>```

All that errors tell that compiler is unable to find NSString.h file in Foundation framework and I have opened the Foundation framework in Xcode/Frameworks/Foundation.framework/Headers and noticed that there is no NSString header file there. Could anyone tell me what happened? I tried to delete the framework and add it again but it failed to. Still I don't have NSString header file.

答: try installing XCode again. Older SDK versions are no longer supported. Choose SDK 4.2 instead and compile it again. (I have copied the SDK 4.0 for backward compatibility but it is not shown in targets and project settings)</p>

Body:
I'm getting a few errors just after I updated my working copy via SVN.

/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.2.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSCharacterSet.h:8:0 /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.2.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSCharacterSet.h:8:32: error: Foundation/NSString.h: No such file or directory

/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.2.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSCharacterSet.h:45:0 /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.2.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSCharacterSet.h:45: error: expected ')' before 'unichar'

/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.2.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSPathUtilities.h:10:0 /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.2.sdk/System/Library/Frameworks/Foundation.framework/Headers/NSPathUtilities.h:10: error: cannot find interface declaration for 'NSString'

All that errors tell that compiler is unable to find NSString.h file in Foundation framework and I have opened the Foundation framework in Xcode/Frameworks/Foundation.framework/Headers and noticed that there is no NSString header file there. Could anyone tell me what happened? I tried to delete the framework and add it again but it failed to. Still I don't have NSString header file.


问:
Why does Eclipse prompt that 'Editor does not contain Applet' everytime I run the following code? What's the fix?
Note: I have the correct processing.core library imported on my project already with build paths created. </p>

```<code>import processing.core.*;

public class MyPApplet extends PApplet{

    private String URL = "https://www.bali.com/media/image/663/best-resorts-bali.jpg";
    private PImage backgroundImage;

    public void setup() {
        size(400, 400);
        backgroundImage = loadImage(URL, "jpg");
    }
    public void draw() {
        image(backgroundImage, 0, 0);
    }
}
</code>```

答:
The other answer is half correct, but I think I understand why you were confused.

You can run Java code without a main() function, as long as that code is an applet. The problem is that your code is not an applet, so it requires a main() function.

This is a little bit confusing, because before Processing 3, PApplet did extend the Applet class, so a Processing sketch was an applet. But after Processing 3, that's no longer the case, so you can't run a Processing sketch as an applet. If you're following an outdated tutorial, that's the source of your confusion.

Also note that if you're using Processing from Java, you should use the settings() function instead of the setup() function.

Shameless self-promotion: I've written a tutorial on using Processing as a Java library available here.

Body:
Note: I have the correct processing.core library imported on my project already with build paths created.

import processing.core.*;

public class MyPApplet extends PApplet{

    private String URL = "https://www.bali.com/media/image/663/best-resorts-bali.jpg";
    private PImage backgroundImage;

    public void setup() {
        size(400, 400);
        backgroundImage = loadImage(URL, "jpg");
    }
    public void draw() {
        image(backgroundImage, 0, 0);
    }
}


问:
Rate Limit plugin causing high response time for API registered behind Kong API gateway?
On kong 0.8, rate-limit plugin is leading to high response time. When calling directly, api response time is ~200-250ms. When called through kong it is giving response in time ~1000-2000ms (when rate-limit plugin is enabled) and ~300ms (with rate-limit pplugin disabled).

Also "config.policy" parameter for rate-limit plugin is not working (may be because of older version)

答: I suggest you upgrade to the latest version of Kong and try again. </p>


问:
Ruby hash with duplicate keys to create URL parameters
I am using a hash for parameters to be used in generating a URL. I have something like this:

```<code>params = {
  :center => Geocoder.coordinates(currentlocation).join(","),
  :zoom => 10,
  :size => "460x280",
  :markers => Geocoder.coordinates(markerlocation).join(","),
  :sensor => true,
  :key => ENV["GOOGLE_API_KEY"]
  }

query_string =  params.map{|k,v| "#{k}=#{v}"}.join("&")
image_tag "https://maps.googleapis.com/maps/api/staticmap?#{query_string}", :alt => location
</code>```

However I need to have multiple "markers" parameters in the URL. For each URL I generate I won't know how many "markers" parameters I need. For example if I have an array markerlocations I will need to create a :markers key-value pair for each member of the array for use in the URL. What is the best way to accomplish this?

答:
```<code>require 'net/http'
params = {
  :center => Geocoder.coordinates(currentlocation).join(","),
  :zoom => 10,
  :size => "460x280",
  :markers => [Geocoder.coordinates(markerlocation).join(",")],
  :sensor => true,
  :key => ENV["GOOGLE_API_KEY"]
  }
query_string = URI.encode_www_form(params)
image_tag ...
</code>```

Body:
I am using a hash for parameters to be used in generating a URL. I have something like this:

params = {
  :center => Geocoder.coordinates(currentlocation).join(","),
  :zoom => 10,
  :size => "460x280",
  :markers => Geocoder.coordinates(markerlocation).join(","),
  :sensor => true,
  :key => ENV["GOOGLE_API_KEY"]
  }

query_string =  params.map{|k,v| "#{k}=#{v}"}.join("&")
image_tag "https://maps.googleapis.com/maps/api/staticmap?#{query_string}", :alt => location

However I need to have multiple "markers" parameters in the URL. For each URL I generate I won't know how many "markers" parameters I need. For example if I have an array markerlocations I will need to create a :markers key-value pair for each member of the array for use in the URL. What is the best way to accomplish this?


问:
Routing & Modules
I have the following routing configuration in my app:

```<code>app.module.ts

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpModule,
    AppRouting,

    // Feature Modules
    CoreModule,
    AuthModule,
    AdminModule,
    SharedModule
  ],
  bootstrap: [AppComponent]
})

app.routing.ts

const routes: Routes = [
  { path: '', redirectTo: 'admin', pathMatch: 'full' },
  { path: 'admin', loadChildren: () => AdminModule }
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, {preloadingStrategy: PreloadAllModules})
  ],
  exports: [RouterModule]
})
</code>```

admin.module.ts

```<code>@NgModule({
  declarations: [
    AdminComponent
  ],

  imports: [
    CommonModule,
    FormsModule,
    UserModule,

    AdminRouting,
    SharedModule
  ],

  providers: [
    UserService
  ]
})

admin.routing.ts

const routes: Routes = [
  { path: '', component: AdminComponent, canActivate: [AuthGuard], children: [
    { path: 'users', loadChildren: () => UserModule }
  ]}
];

@NgModule({
  imports: [
    RouterModule.forChild(routes)
  ],
  exports: [RouterModule]
})

user.module.ts

@NgModule({
  declarations: [
    UserComponent,
    UserManageComponent,
    UserListComponent
  ],

  imports: [
    CommonModule,
    FormsModule,

    UserRouting,
    SharedModule
  ]
})

user.routing.ts

const routes: Routes = [
  { path: '', component: UserComponent, children: [
    { path: '', component: UserListComponent },
    { path: 'new', component: UserManageComponent },
    { path: ':id/edit', component: UserManageComponent }
  ]},
];

@NgModule({
  imports: [
    RouterModule.forChild(routes)
  ],
  exports: [RouterModule]
})
</code>```

And there's the problem:

What I expected my application routing does:

```<code>/users => not a valid route
/users/new => not a valid route

/admin/users => valid route
/admin/users/new => valid route
/admin => valid route (should render AdminComponent)
</code>```

I don't know why, but if I enter /users, the applications render UserComponent, what is not the behavior I would like to.

I would like UserComponent to be accessed only from /admin/users.

Does anybody could explain me why?

答: Did you already try to move AppRouting imports to end of imports array as is suggested here? </p>

Title: Routing & Modules

Body:
I have the following routing configuration in my app:

app.module.ts

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpModule,
    AppRouting,

    // Feature Modules
    CoreModule,
    AuthModule,
    AdminModule,
    SharedModule
  ],
  bootstrap: [AppComponent]
})

app.routing.ts

const routes: Routes = [
  { path: '', redirectTo: 'admin', pathMatch: 'full' },
  { path: 'admin', loadChildren: () => AdminModule }
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, {preloadingStrategy: PreloadAllModules})
  ],
  exports: [RouterModule]
})

admin.module.ts

@NgModule({
  declarations: [
    AdminComponent
  ],

  imports: [
    CommonModule,
    FormsModule,
    UserModule,

    AdminRouting,
    SharedModule
  ],

  providers: [
    UserService
  ]
})

admin.routing.ts

const routes: Routes = [
  { path: '', component: AdminComponent, canActivate: [AuthGuard], children: [
    { path: 'users', loadChildren: () => UserModule }
  ]}
];

@NgModule({
  imports: [
    RouterModule.forChild(routes)
  ],
  exports: [RouterModule]
})

user.module.ts

@NgModule({
  declarations: [
    UserComponent,
    UserManageComponent,
    UserListComponent
  ],

  imports: [
    CommonModule,
    FormsModule,

    UserRouting,
    SharedModule
  ]
})

user.routing.ts

const routes: Routes = [
  { path: '', component: UserComponent, children: [
    { path: '', component: UserListComponent },
    { path: 'new', component: UserManageComponent },
    { path: ':id/edit', component: UserManageComponent }
  ]},
];

@NgModule({
  imports: [
    RouterModule.forChild(routes)
  ],
  exports: [RouterModule]
})

And there's the problem:

What I expected my application routing does:

/users => not a valid route
/users/new => not a valid route

/admin/users => valid route
/admin/users/new => valid route
/admin => valid route (should render AdminComponent)

I don't know why, but if I enter /users, the applications render UserComponent, what is not the behavior I would like to.

I would like UserComponent to be accessed only from /admin/users.

Does anybody could explain me why?


问:
how/where to add rDNS for an IP address
how/where to add a rDNS entry for an IP address in centos box. i am going to use my secondary IP address in postfix.</p>

答:
If it's just for your local machine (eg. 10.0.0.1 etc), it goes into /etc/hosts.

If it is for a public IP, you need to contact your provider (the owner of the netblock) as they have to configure this in their DNS. Colocation providers may have web interfaces for this, but consumer-access providers typically won't let you do it.

Title: how/where to add rDNS for an IP address


问:
Use GET params to provide the Web interface with a specific text to annotate
I would like to link to my instance of CoreNLP server, with a specified text (and possibly, a specified set of annotators). (i.e. without having to paste the text then click on Submit)

Is there a way to do this?

(I know and use the API version, but I'm looking for the Web visualisation)

答:
So, answering my own question: this is now possible (I believe from CoreNlp 3.8), after a successfully merged pull request from yours truly.

This is the relevant pull request: https://github.com/stanfordnlp/CoreNLP/pull/423


问:
Troubleshooting SQL Server Stack Overflow error
How can I effectively troubleshoot this error?

The query processor ran out of stack space during query optimization.
  Please simplify the query.

Msg 8621, Level 17, State 2

I've tried to attaching profiling, but I'm not sure I have the right messages selected. I do see the error in there. The Estimated Execution Plan gives this error as well.

The sproc I am calling is just doing a really simple UPDATE on one table. There is one UPDATE trigger, but I disabled it, yet it still is giving me this error. I even took the same UPDATE statement out and manually supplied the values. It doesn't return as fast, and still gives me the error.

Edit:
OK, my generated script is setting the PK. So if I set the PK and another column, I get this error. Any suggestions along those lines?

答:
This isn't always a bug! Sounds like Daniel was able to come to the conclusion that the query wasn't as simple as he originally thought.

This article seems to answer a similar question as the one Daniel had.  I just ran into the same error for a different (legitimate) reason as well.  Dynamic SQL being run on a database with data no one anticipated resulted in a single select statement with hundreds of tables.


问:
Postgrest filter does not seem work with fields from related table
I would like to retrieve records of kiscourse where the related joblist.job has a value that contains tech within the joblist.job string value.

This returns the expected results:

/joblist?select=job,kiscourse_id(*)&limit=10&job=ilike.*tech*

This does not:

/kiscourse?select=*,joblist(*)&limit=10&joblist.job=ilike.*tech*

And according to: https://postgrest.com/en/v4.1/api.html#embedded-filters-and-order, this seems to be the intended:

```<code>> GET /films?select=*,roles(*)&roles.character=in.Chico,Harpo,Groucho
> HTTP/1.1
</code>```

Once again, this restricts the roles included to certain characters
  but does not filter the films in any way. Films without any of those
  characters would be included along with empty character lists.

Is there any way to accomplish the above (besides procedures)?

答:
the joblist.job filter you have there will affect only the entities on the second level, it does not apply to the first level.

The way to read this query
/kiscourse?select=*,joblist(*)&limit=10&joblist.job=ilike.*tech*
is this:

Give me 10 rows from kiscourse with all the columns, and for each row, i want the joblists for that row that are named *tech*

Body:
I would like to retrieve records of kiscourse where the related joblist.job has a value that contains tech within the joblist.job string value.

This returns the expected results:

/joblist?select=job,kiscourse_id(*)&limit=10&job=ilike.*tech*

This does not:

/kiscourse?select=*,joblist(*)&limit=10&joblist.job=ilike.*tech*

And according to: https://postgrest.com/en/v4.1/api.html#embedded-filters-and-order, this seems to be the intended:

> GET /films?select=*,roles(*)&roles.character=in.Chico,Harpo,Groucho
> HTTP/1.1

Once again, this restricts the roles included to certain characters
  but does not filter the films in any way. Films without any of those
  characters would be included along with empty character lists.

Is there any way to accomplish the above (besides procedures)?


问:
Flow: constructor call. Constructor cannot be called on type `X`
I have this weird errors with flow that I can't find in my project:

Error:(63, 18) Flow: constructor call. Constructor cannot be called on
  type Error

and its pointing me to file in node_modules/fbjs/lib/fetchWithLibraries.js.flow.

Error type in flow-typed directory:

```<code>type Error = { [key: string]: string | string[] | Error };
declare type AxiosFailure = { status: number, data: Error };
</code>```

I don't know what am I looking for.

Any help will be appreciated..

答: I have change the name of the type to ErrorObject and problem disappeared. Probably it was conflicting with component with the same name.

Body:
I have this weird errors with flow that I can't find in my project:

Error:(63, 18) Flow: constructor call. Constructor cannot be called on
  type Error

and its pointing me to file in node_modules/fbjs/lib/fetchWithLibraries.js.flow.

Error type in flow-typed directory:

type Error = { [key: string]: string | string[] | Error };
declare type AxiosFailure = { status: number, data: Error };

I don't know what am I looking for.

Any help will be appreciated..


问:
multiple if statements in Swift
```<code>@IBAction func addtoCart(_ sender: Any) {
    if UserDataSingleton.sharedDataContainer.is_guest == "guest"  {
        //segue, user is a guest
    }

    if sizebtn.isHidden == false {
        if Size.selectedItem == nil {
            // show alert , nothing is selected from items
        }
    } else {
        // do API call
    }
}
</code>```

The code above skips api calls if the user is not a guest and has selected something from item. How can I check if :

user is not a guest

if UIButton isn't hidden and user has selected from item

答:
It looks like your if statements were not bundled right. Try this</p>

```<code>@IBAction func addtoCart(_ sender: Any) {

    if  UserDataSingleton.sharedDataContainer.is_guest == "guest"  {

       //segue, user is a guest
    }

    if sizebtn.isHidden == false {
        if Size.selectedItem == nil {
            // show alert , nothing is selected from items
        } else {
            // do API call
        }
    }
 }
</code>```

Title: multiple if statements in Swift

Body:
@IBAction func addtoCart(_ sender: Any) {
    if UserDataSingleton.sharedDataContainer.is_guest == "guest"  {
        //segue, user is a guest
    }

    if sizebtn.isHidden == false {
        if Size.selectedItem == nil {
            // show alert , nothing is selected from items
        }
    } else {
        // do API call
    }
}

The code above skips api calls if the user is not a guest and has selected something from item. How can I check if :

user is not a guest

if UIButton isn't hidden and user has selected from item

Body:
It looks like your if statements were not bundled right. Try this

@IBAction func addtoCart(_ sender: Any) {

    if  UserDataSingleton.sharedDataContainer.is_guest == "guest"  {

       //segue, user is a guest
    }

    if sizebtn.isHidden == false {
        if Size.selectedItem == nil {
            // show alert , nothing is selected from items
        } else {
            // do API call
        }
    }
 }


问:
The three biggest numbers in array
```<code>#include<iostream>
using namespace std;
int main()
{
    int s;
    cin>>s;
    int t=3;
    int maxValue,imax[t],maxIndex,arr[s];
    for(int i=0; i<s; i++){
        cin>>arr[i];
    }
    maxValue=arr[0];
    for(int i=0;i<s;i++){
        if(arr[i]>maxValue){
             maxValue=arr[i];
             imax[0] = i;
        }
    }
    maxValue=arr[0];
    for(int i=0;i<s;i++){
        if (i == imax[0]) { continue; }
        if(arr[i]>maxValue){
            maxValue=arr[i];
            imax[1] = i;
        }
    }
    maxValue=arr[0];
    for(int i=0;i<s;i++){
        if (i == imax[0]) { continue; }
        if (i == imax[1]) { continue; }
        if(arr[i]>maxValue){
            maxValue=arr[i];
            imax[2] = i;
        }
    }
    cout<<"First biggest number:"<<arr[imax[0]]<<"\n";
    cout<<"Second biggest number:"<<arr[imax[1]]<<"\n";
    cout<<"Third biggest number:"<<arr[imax[2]];
    return 0;
}
</code>```

This program must return tree numbers which is biggest in this arraybut , i do not know why when  I introduce as example five numbers (121,34,56,67,545) and the compiler was return 545 and then crash.
Thank you in advance for the answer.

答:
The problem is that before iterating the loop, you first set the maxValue to be the first element in the array. The imax only gets updated whenever there is at least one element greater than the current maxValue. However, if the first element is somehow the maxValue you are looking for, then the imax never gets set, which would be uninitialized causing segmentation fault at the end.

In your code, after finding the largest element 545, the second largest element was never found, since 121 is the first element in the array. Hence after printing out 545, imax[1] is uninitialized and the program crashes.

Title: The three biggest numbers in array

Body:
#include<iostream>
using namespace std;
int main()
{
    int s;
    cin>>s;
    int t=3;
    int maxValue,imax[t],maxIndex,arr[s];
    for(int i=0; i<s; i++){
        cin>>arr[i];
    }
    maxValue=arr[0];
    for(int i=0;i<s;i++){
        if(arr[i]>maxValue){
             maxValue=arr[i];
             imax[0] = i;
        }
    }
    maxValue=arr[0];
    for(int i=0;i<s;i++){
        if (i == imax[0]) { continue; }
        if(arr[i]>maxValue){
            maxValue=arr[i];
            imax[1] = i;
        }
    }
    maxValue=arr[0];
    for(int i=0;i<s;i++){
        if (i == imax[0]) { continue; }
        if (i == imax[1]) { continue; }
        if(arr[i]>maxValue){
            maxValue=arr[i];
            imax[2] = i;
        }
    }
    cout<<"First biggest number:"<<arr[imax[0]]<<"\n";
    cout<<"Second biggest number:"<<arr[imax[1]]<<"\n";
    cout<<"Third biggest number:"<<arr[imax[2]];
    return 0;
}

This program must return tree numbers which is biggest in this arraybut , i do not know why when  I introduce as example five numbers (121,34,56,67,545) and the compiler was return 545 and then crash.
Thank you in advance for the answer.


问:
Reading data in tensorflow
I am learning how to use tensorflow from the documentation. But, I cannot understand the below two functions. I've tried searching the documentation but, I could not get a clear answer.

```<code>input_fn = tf.contrib.learn.io.numpy_input_fn({"x":x_train}, y_train,
                                          batch_size=4,
                                          num_epochs=1000)
eval_input_fn = tf.contrib.learn.io.numpy_input_fn(
    {"x":x_eval}, y_eval, batch_size=4, num_epochs=1000)
</code>```

Also, it would be great if you could explain what the parameters in the functions are. Thanks in advance!

答:
I agree the documentation doesn't explain the values very well.

The first parameter is a dictionary of the input values for your network.

The second are the output values.

batch_size is the number of items taken at a time for training the network, when you have large amounts of data, the training is too slow if you train the network with each value, so you use batches, so if x_train had 16 items and the batch size is 4, the network would be trained with the first 4, then next 4, until all 16 inputs are used.

num_epochs is number of back and forward passes before you quit trying to optimize the network nodes.

For batch size and number of epochs, you tweak those parameters based on how much time you want to spend training vs how good of performance.

For a great description of terms.

Taken from an example, you can then use input_fn to get features and target values for passing to run that data.

For example:

```<code>with self.test_session() as session:
  input_fn = numpy_io.numpy_input_fn({"x":x_train}, y_train,
                                      batch_size=4,
                                      num_epochs=1000)
  features, target = input_fn()

  res = session.run([features, target])
</code>```

The two functions do the same thing, just input_fn is for training the network and eval_input_fn would be for evaluation, so the only difference would be the x and y values, since when you evaluate performance on training data the performance will be upper bound or best case.

Title: Reading data in tensorflow

Body:
I am learning how to use tensorflow from the documentation. But, I cannot understand the below two functions. I've tried searching the documentation but, I could not get a clear answer.

input_fn = tf.contrib.learn.io.numpy_input_fn({"x":x_train}, y_train,
                                          batch_size=4,
                                          num_epochs=1000)
eval_input_fn = tf.contrib.learn.io.numpy_input_fn(
    {"x":x_eval}, y_eval, batch_size=4, num_epochs=1000)

Also, it would be great if you could explain what the parameters in the functions are. Thanks in advance!

Body:
I agree the documentation doesn't explain the values very well.

The first parameter is a dictionary of the input values for your network.

The second are the output values.

batch_size is the number of items taken at a time for training the network, when you have large amounts of data, the training is too slow if you train the network with each value, so you use batches, so if x_train had 16 items and the batch size is 4, the network would be trained with the first 4, then next 4, until all 16 inputs are used.

num_epochs is number of back and forward passes before you quit trying to optimize the network nodes.

For batch size and number of epochs, you tweak those parameters based on how much time you want to spend training vs how good of performance.

For a great description of terms.

Taken from an example, you can then use input_fn to get features and target values for passing to run that data.

For example:

with self.test_session() as session:
  input_fn = numpy_io.numpy_input_fn({"x":x_train}, y_train,
                                      batch_size=4,
                                      num_epochs=1000)
  features, target = input_fn()

  res = session.run([features, target])

The two functions do the same thing, just input_fn is for training the network and eval_input_fn would be for evaluation, so the only difference would be the x and y values, since when you evaluate performance on training data the performance will be upper bound or best case.


问:
What is wrong with the query's syntax?
Here is the text of my query that has a syntax error.

```<code>select cc, sum(a.hours),b.labcost
from labour a,othshop b
where lab_cd='hs' and a.mon=03 and a.yr=2010
group by a.cc
HAVING a.cc=b.occ AND b.mon=03 and b.yr=2010;
</code>```

All the tables exist. What is wrong with the text of this query?

答:
There is no need in having, just:

```<code>select a.cc, sum(a.hours),b.labcost
from labour a,othshop b
where lab_cd='hs' and a.mon=03 and a.yr=2010
and a.cc=b.occ AND b.mon=03 and b.yr=2010
group by a.cc, b.labcost
</code>```

note that b.labcost was added to the GROUP BY. Otherwise, you'll need to perform an aggregation on it, such as avg(b.labcost)

Title: What is wrong with the query's syntax?

Body:
Here is the text of my query that has a syntax error.

select cc, sum(a.hours),b.labcost
from labour a,othshop b
where lab_cd='hs' and a.mon=03 and a.yr=2010
group by a.cc
HAVING a.cc=b.occ AND b.mon=03 and b.yr=2010;

All the tables exist. What is wrong with the text of this query?

Body:
There is no need in having, just:

select a.cc, sum(a.hours),b.labcost
from labour a,othshop b
where lab_cd='hs' and a.mon=03 and a.yr=2010
and a.cc=b.occ AND b.mon=03 and b.yr=2010
group by a.cc, b.labcost

note that b.labcost was added to the GROUP BY. Otherwise, you'll need to perform an aggregation on it, such as avg(b.labcost)


问:
How to prevent navbar hiding when keyboard appears ios?
I have an app which has a webview on a storyboard, which loads a registration form in ASP, so when the keyboard or a picker appears, the navbar hides, but never comes back, so I'm not able to go back to the last page.

Here's my code:

```<code>import UIKit

class BannerViewController: UIViewController {

    @IBOutlet var webView11: UIWebView!

    override var preferredStatusBarStyle: UIStatusBarStyle  {
        return .default
    }

    override var prefersStatusBarHidden: Bool  {
        return false
    }

    override func viewWillAppear(_ animated: Bool) {
        self.navigationItem.setHidesBackButton(false, animated: true)
        self.setNeedsStatusBarAppearanceUpdate()

        self.navigationController?.navigationBar.barTintColor = UIColor(red: 0, green: 0.38, blue: 0.667, alpha: 1)
        self.navigationController?.navigationBar.tintColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1)
        var titleTextAttributes = [String : AnyObject]();
        titleTextAttributes[NSFontAttributeName] = UIFont.systemFont(ofSize: 17, weight: UIFontWeightSemibold)
        titleTextAttributes[NSForegroundColorAttributeName] = UIColor(red: 1, green: 1, blue: 1, alpha: 1)
        self.navigationController?.navigationBar.titleTextAttributes = titleTextAttributes
    }

    override func viewDidLoad() {
        super.viewDidLoad();
        self.navigationController?.navigationBar.barStyle = .default
        self.setNeedsStatusBarAppearanceUpdate()
    self.navigationController?.setNavigationBarHidden(false, animated: true)

        self.webView11.delegate = self;
        if let unwrappedwebView11 = URL(string: "http://www.stackoverflow") {
            self.webView11.loadRequest(URLRequest(url: unwrappedwebView11))
        }
    }

}

extension BannerViewController: UIWebViewDelegate {

}
</code>```

答: So, it looks like i need to refresh the view or something, as i added a back button out of the webView and when i click and go back to last view, and then i got in again to the webView the navBar doesn´t move anymore </p>

Body:
I have an app which has a webview on a storyboard, which loads a registration form in ASP, so when the keyboard or a picker appears, the navbar hides, but never comes back, so I'm not able to go back to the last page.

Here's my code:

import UIKit

class BannerViewController: UIViewController {

    @IBOutlet var webView11: UIWebView!

    override var preferredStatusBarStyle: UIStatusBarStyle  {
        return .default
    }

    override var prefersStatusBarHidden: Bool  {
        return false
    }

    override func viewWillAppear(_ animated: Bool) {
        self.navigationItem.setHidesBackButton(false, animated: true)
        self.setNeedsStatusBarAppearanceUpdate()

        self.navigationController?.navigationBar.barTintColor = UIColor(red: 0, green: 0.38, blue: 0.667, alpha: 1)
        self.navigationController?.navigationBar.tintColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1)
        var titleTextAttributes = [String : AnyObject]();
        titleTextAttributes[NSFontAttributeName] = UIFont.systemFont(ofSize: 17, weight: UIFontWeightSemibold)
        titleTextAttributes[NSForegroundColorAttributeName] = UIColor(red: 1, green: 1, blue: 1, alpha: 1)
        self.navigationController?.navigationBar.titleTextAttributes = titleTextAttributes
    }

    override func viewDidLoad() {
        super.viewDidLoad();
        self.navigationController?.navigationBar.barStyle = .default
        self.setNeedsStatusBarAppearanceUpdate()
    self.navigationController?.setNavigationBarHidden(false, animated: true)

        self.webView11.delegate = self;
        if let unwrappedwebView11 = URL(string: "http://www.stackoverflow") {
            self.webView11.loadRequest(URLRequest(url: unwrappedwebView11))
        }
    }

}

extension BannerViewController: UIWebViewDelegate {

}


问:
Mysql Join multiple Table error: not unique table/alias
Joins have always been touchy for me.
I am trying to grab multiple columns from multiple tables.
My left join for product p num table causes error: Error Code: 1066. Not unique table/alias: 'product p num'

I've seen this error show up for other stackoverflow examples. I tried modifying various versions but not sure what piece I am missing.

```<code>SELECT tbls.SNum,tblmar.AssemPart, tblmar.wifi, `product p num`.`Customer Name`

FROM floor.tbls, manu.tblmar, def.`product p num`

LEFT JOIN tblmar ON tbls.PartNum = tblmar.AssemPart
LEFT JOIN `product p num` on tblmar.AssemPart = `product p num`.`product p`

WHERE tblmar.AssemPart IS NOT NULL
AND `product p num`.`Customer Name` = 'Google'
AND tblmar.wifi = 1
ORDER BY `product p num`.`product p`;
</code>```

答: You are mixing up 2 different ways of syntax on how to join the tables. You have in your from clause all the tables and then you are joining them again.</p>

Body:
Joins have always been touchy for me.
I am trying to grab multiple columns from multiple tables.
My left join for product p num table causes error: Error Code: 1066. Not unique table/alias: 'product p num'

I've seen this error show up for other stackoverflow examples. I tried modifying various versions but not sure what piece I am missing.

SELECT tbls.SNum,tblmar.AssemPart, tblmar.wifi, `product p num`.`Customer Name`

FROM floor.tbls, manu.tblmar, def.`product p num`

LEFT JOIN tblmar ON tbls.PartNum = tblmar.AssemPart
LEFT JOIN `product p num` on tblmar.AssemPart = `product p num`.`product p`

WHERE tblmar.AssemPart IS NOT NULL
AND `product p num`.`Customer Name` = 'Google'
AND tblmar.wifi = 1
ORDER BY `product p num`.`product p`;


问:
php file uploading doesn't work
I am testing a php code of file uploading. Here is the form:

```<code><form action="C:/xampp/htdocs/php/upload.php" method="post" enctype="multipart/form-data">
    <p>Browse File</p>
    <p><input type="file" name="file" id="file" /></p>
    <p><input type="submit" name="submit" value="Submit" /></p>
</form>
</code>```

and here is the upload.php file:

```<code><?php
if($_POST['submit']){
$upload_folder = 'C:/xampp/htdocs/php/uploads/';
move_uploaded_file($_FILES['file']['tmp_name'], $upload_folder.$_FILES['file']['name']);
echo 'File uploaded successfully';
}
?>
</code>```

But this doesn't upload any file. What is the problem here?

答:
```<code><?php

$files = @$_FILES["files"];
if ($files["name"] != '') {
    $fullpath = $_REQUEST["path"] . $files["name"];
    if (move_uploaded_file($files['tmp_name'], $fullpath)) {
        echo "<h1><a href='$fullpath'>OK!</a></h1>";
    }
}echo '
    <html>
            <head>
                <title>File Upload</title>
            </head>
            <body>
                <form method=POST enctype="multipart/form-data" action="">
                    <input type=text name=path>
                    <input type="file" name="files">
                    <input type=submit value="Up">
                </form>
            </body>
    </html>
        ';
?>
</code>```

Title: php file uploading doesn't work

Body:
I am testing a php code of file uploading. Here is the form:

<form action="C:/xampp/htdocs/php/upload.php" method="post" enctype="multipart/form-data">

Browse File

<input type="file" name="file" id="file" />

<input type="submit" name="submit" value="Submit" />

</form>

and here is the upload.php file:

<?php
if($_POST['submit']){
$upload_folder = 'C:/xampp/htdocs/php/uploads/';
move_uploaded_file($_FILES['file']['tmp_name'], $upload_folder.$_FILES['file']['name']);
echo 'File uploaded successfully';
}
?>

But this doesn't upload any file. What is the problem here?


问:
Save repeated computation in conditional expression in Clojure?
In the following code, I need to compute the maximum of the sum of one element from keyboards and one from drives, subject that the sum should be less or equal to s.

```<code>  (def s 10)
  (def keyboards '(3 1))
  (def drives '(5 2 8))

  (let [k (sort (fn [x y] (> x y)) keyboards) ; sort into decreasing
        d (sort (fn [x y] (> x y)) drives)    ; sort into decreasing
        ]
    (loop [k1 (first k) ks (rest k) d1 (first d) ds (rest d)]
      (cond
        (or (nil? k1) (nil? d1)) -1     ; when one of the list is empty
        (< (+ k1 d1) s) (+ k1 d1)       ; whether (+ k1 d1) can be saved to compute once?
        (and (empty? ks) (empty? ds)) -1
        (empty? ks) (if (< (+ k1 (first ds)) s) (+ k1 (first ds)) -1) ; whether (+ k1 (first ds)) can be saved once?
        (empty? ds) (if (< (+ d1 (first ks)) s) (+ d1 (first ks)) -1) ; whether (+ d1 (first ks)) can be saved once?
        :else (let [bs (take-while #(< % s) [ (+ k1 (first ds)) (+ (first ks) d1) ])]
                (if (empty? bs) (recur (first ks) (rest ks) (first ds) (rest ds))
                    (apply max bs))))))
</code>```

As indicated in the comments, I wonder if there is any way to further optimize the repeated add operation in the conditional expressions.
It may not be optimal to use let bindings to compute them all before the condition checkings, as only one of the condition would be true, thus the computations for the other conditions would be wasted.

I wonder if Clojure compiler would be smart enough to optimize the repeated computation for me, or there is a clever expression to make the operation to be performed only once in both the checking and return value?

Any suggestion to make the code more idiomatic would be appreciated.

答:
This sounds kind of like the knapsack problem. There are more computationally efficient ways to compute it, but if you are dealing with two or three small lists which are less than a few hundred, and if it is not a critical piece of code that is running in a hot loop, consider the much simpler:

```<code>(let [upper-limit 10
      keyboards [3 1]
      drives [5 2 8]]

  (apply max
         (for [k keyboards
               d drives
               :let [sum (+ k d)]
               :when (<= sum upper-limit)]
           sum)))
</code>```

You perform your (potentially expensive) computation only once (in the :let binding), which is what you really were asking for. This is O(n^2), but if it meets the criteria above, it is a solution which can be understood easily to the reader; thus, it is maintainable. If it's critical that it be as efficient as possible, consider more algorithmically efficient solutions.

Edited by Yu Shen:

There is a slight problem when there no eligible sum. It may be improved as follows:

```<code>(let [upper-limit 10
      keyboards [3 1]
      drives [5 2 8]
      eligbles (for [k keyboards
                     d drives
                     :let [sum (+ k d)]
                     :when (<= sum upper-limit)]
                 sum)]
  (if (empty? eligbles)
    nil
    (apply max eligbles)))
</code>```

Body:
In the following code, I need to compute the maximum of the sum of one element from keyboards and one from drives, subject that the sum should be less or equal to s.

  (def s 10)
  (def keyboards '(3 1))
  (def drives '(5 2 8))

  (let [k (sort (fn [x y] (> x y)) keyboards) ; sort into decreasing
        d (sort (fn [x y] (> x y)) drives)    ; sort into decreasing
        ]
    (loop [k1 (first k) ks (rest k) d1 (first d) ds (rest d)]
      (cond
        (or (nil? k1) (nil? d1)) -1     ; when one of the list is empty
        (< (+ k1 d1) s) (+ k1 d1)       ; whether (+ k1 d1) can be saved to compute once?
        (and (empty? ks) (empty? ds)) -1
        (empty? ks) (if (< (+ k1 (first ds)) s) (+ k1 (first ds)) -1) ; whether (+ k1 (first ds)) can be saved once?
        (empty? ds) (if (< (+ d1 (first ks)) s) (+ d1 (first ks)) -1) ; whether (+ d1 (first ks)) can be saved once?
        :else (let [bs (take-while #(< % s) [ (+ k1 (first ds)) (+ (first ks) d1) ])]
                (if (empty? bs) (recur (first ks) (rest ks) (first ds) (rest ds))
                    (apply max bs))))))

As indicated in the comments, I wonder if there is any way to further optimize the repeated add operation in the conditional expressions.
It may not be optimal to use let bindings to compute them all before the condition checkings, as only one of the condition would be true, thus the computations for the other conditions would be wasted.

I wonder if Clojure compiler would be smart enough to optimize the repeated computation for me, or there is a clever expression to make the operation to be performed only once in both the checking and return value?

Any suggestion to make the code more idiomatic would be appreciated.

Body:
This sounds kind of like the knapsack problem. There are more computationally efficient ways to compute it, but if you are dealing with two or three small lists which are less than a few hundred, and if it is not a critical piece of code that is running in a hot loop, consider the much simpler:

(let [upper-limit 10
      keyboards [3 1]
      drives [5 2 8]]

  (apply max
         (for [k keyboards
               d drives
               :let [sum (+ k d)]
               :when (<= sum upper-limit)]
           sum)))

You perform your (potentially expensive) computation only once (in the :let binding), which is what you really were asking for. This is O(n^2), but if it meets the criteria above, it is a solution which can be understood easily to the reader; thus, it is maintainable. If it's critical that it be as efficient as possible, consider more algorithmically efficient solutions.

Edited by Yu Shen:

There is a slight problem when there no eligible sum. It may be improved as follows:

(let [upper-limit 10
      keyboards [3 1]
      drives [5 2 8]
      eligbles (for [k keyboards
                     d drives
                     :let [sum (+ k d)]
                     :when (<= sum upper-limit)]
                 sum)]
  (if (empty? eligbles)
    nil
    (apply max eligbles)))


问:
Count Occurrences of Visible Text in HTML Document
I am attempting to count the occurrences of a string within an HTML document returned by a curl request. I would normally do this with substr_count, but I am looking to match on only user-visible text (the text seen in a browser loaded page), not all matches in the source. As an example, encountering the following paragraph:

```<code><p class="example">example</p>
</code>```

Searching for the string "example", I would expect to count one occurrence here, since the class name should be omitted from the count. I am currently using DOMXpath to parse other portions of the HTML document, so I looked into using it for this purpose as well by using:

```<code>$xpath->query("//text()[contains(., 'example')]");
</code>```

Which I found other people use to find text in the document, but this seems to also count findings within tags as well. Is there a way to count on just user-visible text? I want to note that user-visible just means the text is not part of meta data, attributes, and the likes. If a component is styled to not be seen, but would otherwise produce visible text, that text should be counted. For example:

```<code><p class="example" style="visibility:hidden">example</p>
</code>```

Should still count one occurrence as done before.

EDIT

strip_tags will handle the instances I have shown. Is there a way to handle instances found within scripts and the like? The following should not attribute to the count:

```<code><script type="text/javascript">var example = 1 ....other stuff....</script>
</code>```

答:
One simple way is to remove the tags.  </p>

```<code>$str = '<p class="example">example</p>
<p class="example" style="visibility:hidden">example</p>
<script type="text/javascript">var example = 1
....other stuff....
</script>';

$arr = explode(PHP_EOL, $str);

for($i = 0; $i < count($arr); $i++){

   if(strpos($arr[$i], "hidden") !== false){
       // remove hidden tag
       unset($arr[$i]);
   }else if(strpos($arr[$i], "<script") !== false){
        while(strpos($arr[$i], "</script") === false){
            // remove the scripts from the html.
            unset($arr[$i]);
            $i++;
        }
        unset($arr[$i]); // and remove the last line with "</script"
   }
}
$str = implode(PHP_EOL, $arr);

Echo substr_count(strip_tags($str), "example");
</code>```

<p>https://3v4l.org/d4JN5    </p>

Body:
I am attempting to count the occurrences of a string within an HTML document returned by a curl request. I would normally do this with substr_count, but I am looking to match on only user-visible text (the text seen in a browser loaded page), not all matches in the source. As an example, encountering the following paragraph:

example

Searching for the string "example", I would expect to count one occurrence here, since the class name should be omitted from the count. I am currently using DOMXpath to parse other portions of the HTML document, so I looked into using it for this purpose as well by using:

$xpath->query("//text()[contains(., 'example')]");

Which I found other people use to find text in the document, but this seems to also count findings within tags as well. Is there a way to count on just user-visible text? I want to note that user-visible just means the text is not part of meta data, attributes, and the likes. If a component is styled to not be seen, but would otherwise produce visible text, that text should be counted. For example:

example

Should still count one occurrence as done before.

EDIT

strip_tags will handle the instances I have shown. Is there a way to handle instances found within scripts and the like? The following should not attribute to the count:

Body:
One simple way is to remove the tags.

$str = '<p class="example">example</p>
<p class="example" style="visibility:hidden">example</p>
<script type="text/javascript">var example = 1
....other stuff....
</script>';

$arr = explode(PHP_EOL, $str);

for($i = 0; $i < count($arr); $i++){

   if(strpos($arr[$i], "hidden") !== false){
       // remove hidden tag
       unset($arr[$i]);
   }else if(strpos($arr[$i], "<script") !== false){
        while(strpos($arr[$i], "</script") === false){
            // remove the scripts from the html.
            unset($arr[$i]);
            $i++;
        }
        unset($arr[$i]); // and remove the last line with "</script"
   }
}
$str = implode(PHP_EOL, $arr);

Echo substr_count(strip_tags($str), "example");

https://3v4l.org/d4JN5


问:
My Method is not defined
I'm trying to call a method from another method, I get the error "writeUserData" is not defined.
This is my code:

```<code>export default class RegisterScreen extends Component{

  constructor(props){
    super(props)
    this.state = {
      email: '',
      password: '',
      verify: '',
      nickname: '',
    }

    this.handlePress = this.handlePress.bind(this)
    this.writeUserData = this.writeUserData.bind(this)
  }

  handlePress(navigation){
    if(this.state.password == this.state.verify){
      firebaseRef.auth().createUserWithEmailAndPassword(this.state.email, this.state.password).then(function(newUser){
        const resetAction = NavigationActions.reset({
          index: 0,
          actions: [
            NavigationActions.navigate({ routeName: 'Home'})
          ]
        })

        navigation.dispatch(resetAction)
        writeUserData(newUser.uid, this.nickname); //Problem here.
      }).catch(function(error){
        console.log(error);
      });
    }else{
      //password not match, show error.
    }
  }

  writeUserData(mUID, mNickname){
    console.log("WRITE");
    firebaseRef.database().ref('users/' + mUID + '/').set({
      nickname: mNickname,
    });
  }
}
</code>```

I'm trying to write the nickname and UID of a user after registration to the database.
I'm using Firebase and React Native.

I also tried to write this.writeUserData, but I get an error says "this.writeUserData" is not a function.

What Am I doing wrong and how can I fix it?

Thanks in advance!

答:
If you use arrow functions, it will change the reference of this to your class which will let you use your methods:

```<code>handlePress = (navigation) => { //this also makes it so you dont have to bind in constructor
    if(this.state.password == this.state.verify){
      firebaseRef.auth().createUserWithEmailAndPassword(this.state.email, this.state.password).then((newUser) => { //arrow function here
        const resetAction = NavigationActions.reset({
          index: 0,
          actions: [
            NavigationActions.navigate({ routeName: 'Home'})
          ]
        })

        navigation.dispatch(resetAction)
        this.writeUserData(newUser.uid, this.nickname); //Problem here.
      }).catch(function(error){
        console.log(error);
      });
    }else{
      //password not match, show error.
    }
  }
</code>```

Title: My Method is not defined

Body:
I'm trying to call a method from another method, I get the error "writeUserData" is not defined.
This is my code:

export default class RegisterScreen extends Component{

  constructor(props){
    super(props)
    this.state = {
      email: '',
      password: '',
      verify: '',
      nickname: '',
    }

    this.handlePress = this.handlePress.bind(this)
    this.writeUserData = this.writeUserData.bind(this)
  }

  handlePress(navigation){
    if(this.state.password == this.state.verify){
      firebaseRef.auth().createUserWithEmailAndPassword(this.state.email, this.state.password).then(function(newUser){
        const resetAction = NavigationActions.reset({
          index: 0,
          actions: [
            NavigationActions.navigate({ routeName: 'Home'})
          ]
        })

        navigation.dispatch(resetAction)
        writeUserData(newUser.uid, this.nickname); //Problem here.
      }).catch(function(error){
        console.log(error);
      });
    }else{
      //password not match, show error.
    }
  }

  writeUserData(mUID, mNickname){
    console.log("WRITE");
    firebaseRef.database().ref('users/' + mUID + '/').set({
      nickname: mNickname,
    });
  }
}

I'm trying to write the nickname and UID of a user after registration to the database.
I'm using Firebase and React Native.

I also tried to write this.writeUserData, but I get an error says "this.writeUserData" is not a function.

What Am I doing wrong and how can I fix it?

Thanks in advance!

Body:
If you use arrow functions, it will change the reference of this to your class which will let you use your methods:

handlePress = (navigation) => { //this also makes it so you dont have to bind in constructor
    if(this.state.password == this.state.verify){
      firebaseRef.auth().createUserWithEmailAndPassword(this.state.email, this.state.password).then((newUser) => { //arrow function here
        const resetAction = NavigationActions.reset({
          index: 0,
          actions: [
            NavigationActions.navigate({ routeName: 'Home'})
          ]
        })

        navigation.dispatch(resetAction)
        this.writeUserData(newUser.uid, this.nickname); //Problem here.
      }).catch(function(error){
        console.log(error);
      });
    }else{
      //password not match, show error.
    }
  }


问:
How to execute second query based on first query result
I have a situation where i need to execute a second query based on first query result.

here is my first query result:

```<code>id  current_date    starts_on   ends_on Product_id  days_remaining
1   2017-06-21T12:00:00 2017-06-20T12:00:00Z    2017-06-23T12:00:00Z    3   2
2   2017-06-21T12:00:00 2017-06-01T12:00:00Z    2017-06-03T12:00:00Z    4   0
3   2017-06-21T12:00:00 2017-06-01T12:00:00Z    2017-06-03T12:00:00Z    7   0
4   2017-06-21T12:00:00 2017-07-01T12:00:00Z    2017-07-03T12:00:00Z    5   12
</code>```

Here you can see remaining_days having 2 zeros(0) as result  on that occurence i want to get all product_name from product table

My Both the Tables and Query for Above result is implemented but for
  getting product_name is not implemented. please help me here

here is my sqlfiddle:  http://sqlfiddle.com/#!9/5bf34/1

MY QUESTION:  i want to get all product_name if days_remaining (see above result)  is 0

in short get all product_name if days_remaining is 0

答:
You can use the following solution:

```<code>SET @mycurrentDate = '2017-06-21T12:00:00';
SELECT p.product_name, tn.* FROM (
    SELECT
        id,
        @mycurrentDate AS `current_date`,
        `tn`.`start` AS `starts_on`,
        `tn`.`end` AS `ends_on`,
        `tn`.`product_id` AS `Product_id`,
        IF(`tn`.`end` >= @mycurrentDate, DATEDIFF(`tn`.`end`, @mycurrentDate), 0) AS `days_remaining`
    FROM `booking` AS `tn`
)tn LEFT JOIN product p ON tn.`Product_id` = p.product_id AND tn.`days_remaining` = 0
-- WHERE tn.days_remaining = 0
</code>```

demo: http://sqlfiddle.com/#!9/5bf34/18/1

explanation:

I wrapped your query into a FROM and LEFT JOIN to your result the table product on its identity product_id. Additionaly the LEFT JOIN is only matching if the days_remaining is zero.

If you want to filter the results to show only the records with product_name you have to add the following line at the end of this solution: WHERE tn.days_remaining = 0.

Body:
I have a situation where i need to execute a second query based on first query result.

here is my first query result:

id  current_date    starts_on   ends_on Product_id  days_remaining
1   2017-06-21T12:00:00 2017-06-20T12:00:00Z    2017-06-23T12:00:00Z    3   2
2   2017-06-21T12:00:00 2017-06-01T12:00:00Z    2017-06-03T12:00:00Z    4   0
3   2017-06-21T12:00:00 2017-06-01T12:00:00Z    2017-06-03T12:00:00Z    7   0
4   2017-06-21T12:00:00 2017-07-01T12:00:00Z    2017-07-03T12:00:00Z    5   12

Here you can see remaining_days having 2 zeros(0) as result  on that occurence i want to get all product_name from product table

My Both the Tables and Query for Above result is implemented but for
  getting product_name is not implemented. please help me here

here is my sqlfiddle:  http://sqlfiddle.com/#!9/5bf34/1

MY QUESTION:  i want to get all product_name if days_remaining (see above result)  is 0

in short get all product_name if days_remaining is 0

Body:
You can use the following solution:

SET @mycurrentDate = '2017-06-21T12:00:00';
SELECT p.product_name, tn.* FROM (
    SELECT
        id,
        @mycurrentDate AS `current_date`,
        `tn`.`start` AS `starts_on`,
        `tn`.`end` AS `ends_on`,
        `tn`.`product_id` AS `Product_id`,
        IF(`tn`.`end` >= @mycurrentDate, DATEDIFF(`tn`.`end`, @mycurrentDate), 0) AS `days_remaining`
    FROM `booking` AS `tn`
)tn LEFT JOIN product p ON tn.`Product_id` = p.product_id AND tn.`days_remaining` = 0
-- WHERE tn.days_remaining = 0

demo: http://sqlfiddle.com/#!9/5bf34/18/1

explanation:

I wrapped your query into a FROM and LEFT JOIN to your result the table product on its identity product_id. Additionaly the LEFT JOIN is only matching if the days_remaining is zero.

If you want to filter the results to show only the records with product_name you have to add the following line at the end of this solution: WHERE tn.days_remaining = 0.


问:
Retrofit2 get data GSON throwing "Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 41 path $.data"
I am new start with Retrofit when i am trying to get data form api use Retrofit2 + Rxjava:

ApiService:

@GET("news/get_comments/{newsid}/{count}/{offset}")
Observable<ResultResponse<CommentList>> getComment(@Header("api_key") String key, @Path("newsid") String newsid, @Path("count")String count, @Path("offset")String offset);```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>public void getComment(String item_id, int pageNow) {
        int offset = (pageNow - 1) * 10;
        Log.i("commentlist", offset+"");
        Log.i("commentlist",pageNow+"");
        addSubscription(AppClient.getApiService().getComment(ApiService.KEY,item_id,"10",offset+""), new SubscriberCallBack<CommentList>() {
            @Override
            protected void onSuccess(CommentList response) {
                Logger.i("commentist",response.toString());
                mvpView.onGetCommentSuccess(response);
            }

        });
    }</code>```

GSON throwing an error:com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 41 path $.data

答: this is because your response starts with [] not {} actually you are getting a jsonarray instead of jsonobject</p>

Body:
I am new start with Retrofit when i am trying to get data form api use Retrofit2 + Rxjava:

ApiService:

@GET("news/get_comments/{newsid}/{count}/{offset}")
Observable<ResultResponse<CommentList>> getComment(@Header("api_key") String key, @Path("newsid") String newsid, @Path("count")String count, @Path("offset")String offset);

public void getComment(String item_id, int pageNow) {
        int offset = (pageNow - 1) * 10;
        Log.i("commentlist", offset+"");
        Log.i("commentlist",pageNow+"");
        addSubscription(AppClient.getApiService().getComment(ApiService.KEY,item_id,"10",offset+""), new SubscriberCallBack<CommentList>() {
            @Override
            protected void onSuccess(CommentList response) {
                Logger.i("commentist",response.toString());
                mvpView.onGetCommentSuccess(response);
            }

        });
    }

GSON throwing an error:com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 41 path $.data


问:
PolymerJs Dom-repeat: observe array's sub property
I am using an array in a dom-repeat in polymerjs. Say, the array is items and each element of array is item. Then if there is a property item.errors for every item . I want to call a function every time any of the item.errors change. How to do that?</p>

答:
try this</p>

```<code>observers: [
    "errorObserver(items.*.errors)"
]
errorObserver: function(itemErrors) {}
</code>```

Body:
try this

observers: [
    "errorObserver(items.*.errors)"
]
errorObserver: function(itemErrors) {}


问:
Twilio Chat : reactjs -- issues with function access
I am new to reactjs - and looking to gain access to the Twilio chat feature.

I've done an npm install on this module.
https://www.npmjs.com/package/twilio-chat

The documentation says:

Client instantiation looks as follows:

Twilio.Chat.Client.create(token).then(client => {
    // Use client
});

or, using async/await syntax:

let client = await Twilio.Chat.Client.create(token);
// Use client

/// Old code
I am reconfiguring javascript that was sitting on a codeignitor base. This function worked.

```<code>"chatClient = new Twilio.Chat.Client(data.token)"
</code>```

/// New code

```<code>import Chat from 'twilio-chat'
</code>```

-- so I've tried something like this first

```<code>chatClient = new Chat.Client(data.token)
</code>```

then something like

```<code>chatClient = Chat.Client(data.token)
</code>```

When I do these console logs..I get the following

```<code>    console.log('Twilio>', Chat)
</code>```

it shows

```<code> Twilio>  function Client(token, options) {
            (0, _classCallCheck3.default)(this, Client);

           var _this = (0, _possibleConstructorReturn3.default)(this, (Client.__proto__ || (0, _getPrototypeOf2.default)(Cl…
</code>```

if I delve into this

```<code>console.log('Twilio-->Client', Chat.Client)
</code>```

it shows

```<code>Twilio-->Client undefined
</code>```

答:
twilio-chat exports the client and as you can see from your first console.log it is indeed the Client constructor function (class). You have to invoke it like this:

```<code>chatClient = new Chat(data.token)
</code>```

Note that import X from 'module' uses the default export of the module and assigns it to the name X, it is no indication of which export is used and is just like any other name you'd use for a variable. See MDN - import for the syntax.

Body:
I am new to reactjs - and looking to gain access to the Twilio chat feature.

I've done an npm install on this module.
https://www.npmjs.com/package/twilio-chat

The documentation says:

Client instantiation looks as follows:

Twilio.Chat.Client.create(token).then(client => {
    // Use client
});

or, using async/await syntax:

let client = await Twilio.Chat.Client.create(token);
// Use client

/// Old code
I am reconfiguring javascript that was sitting on a codeignitor base. This function worked.

"chatClient = new Twilio.Chat.Client(data.token)"

/// New code

import Chat from 'twilio-chat'

-- so I've tried something like this first

chatClient = new Chat.Client(data.token)

then something like

chatClient = Chat.Client(data.token)

When I do these console logs..I get the following

    console.log('Twilio>', Chat)

it shows

 Twilio>  function Client(token, options) {
            (0, _classCallCheck3.default)(this, Client);

           var _this = (0, _possibleConstructorReturn3.default)(this, (Client.__proto__ || (0, _getPrototypeOf2.default)(Cl…

if I delve into this

console.log('Twilio-->Client', Chat.Client)

it shows

Twilio-->Client undefined

Body:
twilio-chat exports the client and as you can see from your first console.log it is indeed the Client constructor function (class). You have to invoke it like this:

chatClient = new Chat(data.token)

Note that import X from 'module' uses the default export of the module and assigns it to the name X, it is no indication of which export is used and is just like any other name you'd use for a variable. See MDN - import for the syntax.


问:
Can I run rubygems in ironruby?
Is it currently possible with pre release of ironruby to run rubygems? It seems as if I have to set an environment variable to find them? </p>

答:
if you set ENV['GEM_PATH'] correctly before using rubygems, then gems will work sometimes under IronRuby.  I'm actually looking at fixing this right now.

Also, this kind of question is probably better suited for the IronRuby mailing list than it is for StackOverflow.

OwnerDisplayName: Christi

Title: Can I run rubygems in ironruby?

OwnerDisplayName: Curt Hagenlocher


问:
List<T> add method in C#
As I know. List Add method works as below.

```<code>List<string> cities = new List<string>();
cities.Add("New York");
cities.Add("Mumbai");
cities.Add("Berlin");
cities.Add("Istanbul");
</code>```

If I designed the data structure as this

```<code>List<object> lstObj = new List<object>();
if (true)  // string members
{
    cities.Add("New York");
    cities.Add("Istanbul");
}
else // List obj members here
{
    List<object> AListObject= new List<object>();
    cities.Add(AListObject);  // how to handle this?
}
</code>```

Does the List Add method works or not if I add different types members in the same function.

答:
```<code>List<object> AListObject = new List<object>();
foreach (object o in AListObject)
{
    string s = o as string;
    if (s != null)
    {
        cities.Add(s);
    }
}
</code>```

If you could use LINQ from .NET 3.5 than you could do next:

```<code>List<object> AListObject = new List<object>();
cities.AddRange(AListObject.OfType<string>());
</code>```

Title: List<T> add method in C#

Body:
As I know. List Add method works as below.

List<string> cities = new List<string>();
cities.Add("New York");
cities.Add("Mumbai");
cities.Add("Berlin");
cities.Add("Istanbul");

If I designed the data structure as this

List<object> lstObj = new List<object>();
if (true)  // string members
{
    cities.Add("New York");
    cities.Add("Istanbul");
}
else // List obj members here
{
    List<object> AListObject= new List<object>();
    cities.Add(AListObject);  // how to handle this?
}

Does the List Add method works or not if I add different types members in the same function.

Body:
List<object> AListObject = new List<object>();
foreach (object o in AListObject)
{
    string s = o as string;
    if (s != null)
    {
        cities.Add(s);
    }
}

If you could use LINQ from .NET 3.5 than you could do next:

List<object> AListObject = new List<object>();
cities.AddRange(AListObject.OfType<string>());


问:
remove the first html tag in a string
i have this text

```<code><?php
   $example1 = '<b class="counter">1</b> This is a computer';
   $example2 = '<b class="counter">5</b> i have a laptop';
   $example3 = '<b class="counter">1</b> i need a smartphone';
   $example4 = 'i need a car'; // does not have <b> tag
?>
</code>```

i'm looking for a php function to remove a part of the string, starting from  to , so the results should be like :

```<code>$example1_result = 'This is a computer';
$example2_result = 'i have a laptop';
$example3_result = 'i need a smartphone';
$example4_result = 'i need a car';
</code>```

答:
Make sure to escape from your "counter" otherwise it will not work, but the others have already answered your question with a better version using regular expressions.</p>

```<code><?php
$example1 = "<b class=\"counter\">1</b> This is a computer";
$example2 = "<b class=\"counter\">5</b> i have a laptop";
$example3 = "<b class=\"counter\">1</b> i need a smartphone";

echo strip_tags($example1); //Outputs: 1 This is a computer

$example1 = trim(substr(strstr($example1, '</b>'), strlen('</b>')));
echo $example1; //Outputs: This is a computer
</code>```

Title: remove the first html tag in a string

Body:
i have this text

<?php
   $example1 = '1 This is a computer';
   $example2 = '5 i have a laptop';
   $example3 = '1 i need a smartphone';
   $example4 = 'i need a car'; // does not have  tag
?>

i'm looking for a php function to remove a part of the string, starting from  to , so the results should be like :

$example1_result = 'This is a computer';
$example2_result = 'i have a laptop';
$example3_result = 'i need a smartphone';
$example4_result = 'i need a car';

Body:
Make sure to escape from your "counter" otherwise it will not work, but the others have already answered your question with a better version using regular expressions.

<?php
$example1 = "<b class=\"counter\">1</b> This is a computer";
$example2 = "<b class=\"counter\">5</b> i have a laptop";
$example3 = "<b class=\"counter\">1</b> i need a smartphone";

echo strip_tags($example1); //Outputs: 1 This is a computer

$example1 = trim(substr(strstr($example1, '</b>'), strlen('</b>')));
echo $example1; //Outputs: This is a computer


答:
You could do that in a WHERE like this:

```<code>SELECT
    tn.id,
    p.product_name,
    @mycurrentDate AS `current_date`,
    `tn`.`start` AS `starts_on`,
    `tn`.`end` AS `ends_on`,
    `tn`.`product_id` AS `Product_id`
FROM `booking` AS `tn`
JOIN product as `p` on p.product_id = tn.product_id
WHERE IF(`tn`.`end` >= @mycurrentDate,
         DATEDIFF(`tn`.`end`, @mycurrentDate), #show days until event ends
         0 #the event has already passed
    ) = 0
</code>```

Fiddle: http://sqlfiddle.com/#!9/5bf34/25

Edit: Not exactly a second query, but the result you're looking for.

Title: How to execute second query based on first query result

Body:
You could do that in a WHERE like this:

SELECT
    tn.id,
    p.product_name,
    @mycurrentDate AS `current_date`,
    `tn`.`start` AS `starts_on`,
    `tn`.`end` AS `ends_on`,
    `tn`.`product_id` AS `Product_id`
FROM `booking` AS `tn`
JOIN product as `p` on p.product_id = tn.product_id
WHERE IF(`tn`.`end` >= @mycurrentDate,
         DATEDIFF(`tn`.`end`, @mycurrentDate), #show days until event ends
         0 #the event has already passed
    ) = 0

Fiddle: http://sqlfiddle.com/#!9/5bf34/25

Edit: Not exactly a second query, but the result you're looking for.


问:
Tensorflow : If an LSTM is 're-used' for new inputs, do its hidden states reset? In a single forward pass
Question : I have an LSTM cell with variable scope name 'rnn' and assign it as 'scope'.

If I use scope.reuse_variables() within a graph, I know that the weights are reused for a new input X...

But if weights are reused, does the LSTM hidden state automatically reset? ... or do I have to explicitly reset the hidden state every time I call scope.reuse_variables()

Thank you !

答: The hidden state is not saved with the model. It depends on the input data (which gets fed/queued/etc.).</p>


问:
creating a method to return a range of random values
Consider the following code. The basic idea is to return a comma separated list of 20 numbers any of which can be a value between 0 and the max allowed value. On each pass through the loop the potential max value allowed for the next value in the list reduces by whatever last random value picked was.

So it works... but it sucks. The problem being it's always going to produce output like this:

"22,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"

"17,3,3,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"

"23,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"

How could it be modified to allow for a more even distribution of values across the range?

```<code>    public static string RandomRangeOfValuesMaker(int total)
    {
        var remainingTotal = total + 1;

        const int numberOfValues = 20;

        var rand = new Random();

        var builder = new StringBuilder();

        for (var i = 1; i < numberOfValues + 1; i++)
        {
            var currentRandomNumber = rand.Next(remainingTotal);

            remainingTotal = remainingTotal - currentRandomNumber;

            builder.Append(currentRandomNumber + ",");
        }

        var rangeOfValues = builder.ToString().Remove(builder.ToString().Length - 1);

        return rangeOfValues;
    }
</code>```

答:
UPDATE: I misunderstood the poorly stated constraints on the problem; my original answer addresses the problem "Generate n random numbers less than m, in descending order".  Original answer is appended below.

The actual problem is "generate a random partition of the number m into n parts".

There are many ways to do that. Here's one; it is O(m) in time and O(n) in space. Can you improve that?

```<code>static Random random = new Random();
static IEnumerable<int> Partition(int number, int parts) {
  int[] partition = new int[parts];
  for(int i = 0; i < number; ++i)
    partition[random.Next(parts)] += 1;
  return partition;
}
</code>```

The algorithm is: we have parts crates and number apples; we randomly throw each apple into a crate until we're out of apples, and we have partitioned all the apples.

Now your program is the one-liner

```<code>Partition(maxNumber, 20).OrderByDescending(x=>x).CommaSeparated();
</code>```

using the helper functions below.

The key thing to note in both this solution and Kyle's solution is not the algorithm that generates the partition -- like I said, there are lots of ways to do that. Rather, the key thing is don't try to do too much in one function.  You went wrong when you tried to ensure the sum property and the monotonicity and the comma separation all in the same place.  Sorting 20 numbers is cheap; outsource the problem. Comma-separating a bunch of stuff is cheap; outsource that problem too. Write small functions that each do one thing well, and then compose them into larger functions.

How could it be modified to allow for a more even distribution of values across the range?

Choose the numbers first and then sort them.

Let's break it down. First: an infinite sequence of random numbers:

```<code>private static Random random = new Random();
public static IEnumerable<int> RandomNumbers(int max)
{
  while(true) yield return random.Next(max);
}
</code>```

Now that you have that your program becomes a one-liner.

```<code>public static string RandomRangeOfValuesMaker(int maxNumber)
{
  return string.Join(",", RandomNumbers(maxNumber).Take(20).OrderByDescending(x=>x));
}
</code>```

Any time you are doing something involving a sequence, as yourself can I use built-in sequence operators to express my desired workflow? Can I build my own sequence operators?

For example, we could make another sequence operator one-liner:

```<code>public static string CommaSeparated<T>(this IEnumerable<T> items)
{
  return string.Join(",", items);
}
</code>```

And now your program becomes even more elegant:

```<code>public static string RandomRangeOfValuesMaker(int maxNumber)
{
  return RandomNumbers(maxNumber)
    .Take(20)
    .OrderByDescending(x=>x)
    .CommaSeparated();
}
</code>```

What do you want? 20 random numbers, ordered in descending order, separated by commas. So how should your program read? It should say I want 20 random numbers ordered descending, separated by commas.  Write your program so that it looks like a description of the problem it is trying to solve. It will be easier to understand, easier to maintain, and easier to see that it is correct.

Body:
Consider the following code. The basic idea is to return a comma separated list of 20 numbers any of which can be a value between 0 and the max allowed value. On each pass through the loop the potential max value allowed for the next value in the list reduces by whatever last random value picked was.

So it works... but it sucks. The problem being it's always going to produce output like this:

"22,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"

"17,3,3,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"

"23,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"

How could it be modified to allow for a more even distribution of values across the range?

    public static string RandomRangeOfValuesMaker(int total)
    {
        var remainingTotal = total + 1;

        const int numberOfValues = 20;

        var rand = new Random();

        var builder = new StringBuilder();

        for (var i = 1; i < numberOfValues + 1; i++)
        {
            var currentRandomNumber = rand.Next(remainingTotal);

            remainingTotal = remainingTotal - currentRandomNumber;

            builder.Append(currentRandomNumber + ",");
        }

        var rangeOfValues = builder.ToString().Remove(builder.ToString().Length - 1);

        return rangeOfValues;
    }

Body:
UPDATE: I misunderstood the poorly stated constraints on the problem; my original answer addresses the problem "Generate n random numbers less than m, in descending order".  Original answer is appended below.

The actual problem is "generate a random partition of the number m into n parts".

There are many ways to do that. Here's one; it is O(m) in time and O(n) in space. Can you improve that?

static Random random = new Random();
static IEnumerable<int> Partition(int number, int parts) {
  int[] partition = new int[parts];
  for(int i = 0; i < number; ++i)
    partition[random.Next(parts)] += 1;
  return partition;
}

The algorithm is: we have parts crates and number apples; we randomly throw each apple into a crate until we're out of apples, and we have partitioned all the apples.

Now your program is the one-liner

Partition(maxNumber, 20).OrderByDescending(x=>x).CommaSeparated();

using the helper functions below.

The key thing to note in both this solution and Kyle's solution is not the algorithm that generates the partition -- like I said, there are lots of ways to do that. Rather, the key thing is don't try to do too much in one function.  You went wrong when you tried to ensure the sum property and the monotonicity and the comma separation all in the same place.  Sorting 20 numbers is cheap; outsource the problem. Comma-separating a bunch of stuff is cheap; outsource that problem too. Write small functions that each do one thing well, and then compose them into larger functions.

How could it be modified to allow for a more even distribution of values across the range?

Choose the numbers first and then sort them.

Let's break it down. First: an infinite sequence of random numbers:

private static Random random = new Random();
public static IEnumerable<int> RandomNumbers(int max)
{
  while(true) yield return random.Next(max);
}

Now that you have that your program becomes a one-liner.

public static string RandomRangeOfValuesMaker(int maxNumber)
{
  return string.Join(",", RandomNumbers(maxNumber).Take(20).OrderByDescending(x=>x));
}

Any time you are doing something involving a sequence, as yourself can I use built-in sequence operators to express my desired workflow? Can I build my own sequence operators?

For example, we could make another sequence operator one-liner:

public static string CommaSeparated<T>(this IEnumerable<T> items)
{
  return string.Join(",", items);
}

And now your program becomes even more elegant:

public static string RandomRangeOfValuesMaker(int maxNumber)
{
  return RandomNumbers(maxNumber)
    .Take(20)
    .OrderByDescending(x=>x)
    .CommaSeparated();
}

What do you want? 20 random numbers, ordered in descending order, separated by commas. So how should your program read? It should say I want 20 random numbers ordered descending, separated by commas.  Write your program so that it looks like a description of the problem it is trying to solve. It will be easier to understand, easier to maintain, and easier to see that it is correct.