问:
Dynamically add element to DOM in angular
This is how my page looks like on initial load

```<code><body>
 <div class="col-md-12" id="dataPanes">
   <div class="row dataPane"> Chunk of html elements </div>
 </div>

 <div class"col-md-12 text-right">
   <input type="button" class="btn btn-primary" value="Add dynamic row" ng-click="addElementChunk()" />
</body>
</code>```

I am in need to add rows to div#dataPanes on button click

If I was using jQuery,addElementChunk() function would have looked as below

```<code>var addElementChunk = function()
{
   var html = "<div class='row dataPane'> Chunk of html elements </div>";
   $("#dataPanes").append(html);
}
</code>```

but how do I implement the same in angular??

答:
you can append new div using angular ng-repeat directive

lets say you have an array that contain one element and every time you click the button you add another element to the array, while you are repeating it in your "dataPane" div

so you code could be:

HTML

```<code><div ng-app="myApp" ng-controller="myCtr">
    <div class="col-md-12" id="dataPanes">
        <div class="row dataPane" ng-repeat="element in added_elements"> Chunk of html elements ( {{element}} ) </div>
    </div>

    <div class="col-md-12 text-right">
        <input type="button" class="btn btn-primary" value="Add dynamic row" ng-click="addMoreElements()" />
    </div>
</div>
</code>```

JS

```<code>angular
.module('myApp', [])
.controller('myCtr', ['$scope', function($scope) {
    $scope.added_elements = ["elem 1"];
    $scope.addMoreElements = function(){
        $scope.added_elements.push("elem "+ ($scope.added_elements.length+1));
    }
}])
</code>```

so you can add whatever data you want about your repeated row and bind it in html in simple way without having to repeat the whole html code

Working Demo

Body:
This is how my page looks like on initial load

 Chunk of html elements

   <input type="button" class="btn btn-primary" value="Add dynamic row" ng-click="addElementChunk()" />

I am in need to add rows to div#dataPanes on button click

If I was using jQuery,addElementChunk() function would have looked as below

var addElementChunk = function()
{
   var html = "
 Chunk of html elements
";
   $("#dataPanes").append(html);
}

but how do I implement the same in angular??

Body:
you can append new div using angular ng-repeat directive

lets say you have an array that contain one element and every time you click the button you add another element to the array, while you are repeating it in your "dataPane" div

so you code could be:

HTML

<div ng-app="myApp" ng-controller="myCtr">
    <div class="col-md-12" id="dataPanes">
        <div class="row dataPane" ng-repeat="element in added_elements"> Chunk of html elements ( {{element}} ) </div>
    </div>

    <div class="col-md-12 text-right">
        <input type="button" class="btn btn-primary" value="Add dynamic row" ng-click="addMoreElements()" />
    </div>
</div>

JS

angular
.module('myApp', [])
.controller('myCtr', ['$scope', function($scope) {
    $scope.added_elements = ["elem 1"];
    $scope.addMoreElements = function(){
        $scope.added_elements.push("elem "+ ($scope.added_elements.length+1));
    }
}])

so you can add whatever data you want about your repeated row and bind it in html in simple way without having to repeat the whole html code

Working Demo


来源: stackexchange

问:
String vs string

Possible Duplicate:

  In C# what is the difference between String and string

Should I use string or String when declaring a basic string variable in c# and does it matter?

答: It doesn't matter, though it's best to be consistent: lower-case string is an alias for String.

ContentLicense: CC BY-SA 3.0

Title: String vs string

ContentLicense: CC BY-SA 2.5


问:
Error "Cannot set property 'eventManager' of null" in Dynamics 365
I got this script error popup when I opened record today. I have never got this error before and there's no change after I last opened the record days ago.

The error message is "TypeError: Unable to set property 'eventManager' of undefined or null reference".

I have no idea about it and need help to solve this issue. It occurred in both sandbox and prod environment.

答: I also have this problem. It seems that last crm system update contains some changes regarding js. In my case this error is made by the js function where I add OnLoad event to subgrid. If that function is disabled everything works fine.</p>


问:
Opencart admin panel not accessible
Since I installed a SSL certificate on my website, the admin panel is not accessible.

It´s actually because I cannot click the login button.

https://www.umweltfreunde.com/admin/

Thanks a lot for helping me fix this.

Razvan

答:
It is because on your site, the base URL is not https. Currently it is as in the screenshot below:

Please make changes in your admin header file to change the base URL to HTTPS.

Title: Opencart admin panel not accessible


问:
Why is content_tag helper printing the "flash" contents in the browser?
To explain further, I have the following code in my Rails app Layout:

```<code><!-- Stuff omitted -->
<% unless flash.empty? %>
  <%= flash.each do |name, msg| %>
    <%= content_tag :div, msg, :id => "flash_#{name}" %>
  <% end %>
<% end %>
<%= yield %>
</code>```

And for the controller:

```<code>#stuff omitted
def create
  user = User.authenticate(params[:email], params[:password])
  if user
    session[:user_id] = user.id
    redirect_to root_url, :notice => "Logged in!"
  else
    flash.now.alert = "Invalid email or password"
    render :new
  end
end
</code>```

Ok, so, If I happen to fail the authentication, this is what I'm seeing in the browser:

Can you guys tell me why is the hash({:alert => "Invalid email or password"}) appearing under the message? I'm really clueless about what is wrong,

(BTW, This is taken from Rails Casts #250)

答:
You can try the following:

in application.html.erb you can write:

```<code><% unless flash.empty? %>
  <% flash.each do |name, msg| %>
    <%= content_tag :div, msg, class: "alert alert-#{name}" %>
  <% end %>
<% end %>
<%= yield %>
</code>```

in controller you can write:

flash[:danger] = "Invalid email or password"

Body:
To explain further, I have the following code in my Rails app Layout:

<% unless flash.empty? %>
  <%= flash.each do |name, msg| %>
    <%= content_tag :div, msg, :id => "flash_#{name}" %>
  <% end %>
<% end %>
<%= yield %>

And for the controller:

#stuff omitted
def create
  user = User.authenticate(params[:email], params[:password])
  if user
    session[:user_id] = user.id
    redirect_to root_url, :notice => "Logged in!"
  else
    flash.now.alert = "Invalid email or password"
    render :new
  end
end

Ok, so, If I happen to fail the authentication, this is what I'm seeing in the browser:

Can you guys tell me why is the hash({:alert => "Invalid email or password"}) appearing under the message? I'm really clueless about what is wrong,

(BTW, This is taken from Rails Casts #250)

Body:
You can try the following:

in application.html.erb you can write:

<% unless flash.empty? %>
  <% flash.each do |name, msg| %>
    <%= content_tag :div, msg, class: "alert alert-#{name}" %>
  <% end %>
<% end %>
<%= yield %>

in controller you can write:

flash[:danger] = "Invalid email or password"


问:
Enforce ordering of variables / methods in a class file
How to enforce ordering for a class file with resharper?

For example, I want to enforce all developers to use the following order of declaring variables / properties / methods

Private variables
Protected variables
Public variables
Protected properties
Public properties
Public constructor
Public methods etc.

答:
Resharper may help you to maintain order in the file, but cannot enforce this.

You may achieve your goal if you combine Resharper with code analysis tool, which will produce warnings if an order of class members is broken, and enabling 'Treat warnings as errors' setting (Right click on project > Properties > Build).

Take a look at Stylecop analyzers project: https://github.com/DotNetAnalyzers/StyleCopAnalyzers one of the stylecop rules enforces order and is configurable

Once you make your project failing because of incorrect ordering you may use Resharpers code clean-up 'Apply Layout'. Desired order of class members may be configured in C# > File Layout section of Resharper options


问:
Access Python Rest API using AJAX jQuery
I don't know python.

I'm just requesting Python REST APIs using jQuery and AJAX.

Here's my Code so far:

```<code><!DOCTYPE html>
<html>
<head>
<title>Announcements</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div id="announcements">

</div>
<script>
$(document).ready(function(){
    $.ajax({
        dataType: "json",
        method: "GET",
        url: "/mhtsessions/annoucements/",
        data: {
          csrfmiddlewaretoken:  getCookie('csrftoken')
        },
        success: function(data){
            $("#announcements").html(data);
      }
    });
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

});
</script>
</body>
</html>
</code>```

I also need to pass CSRF Token to access the APIs.

Where CSRF Token is generated by Django Rest Framework.

I've seen this Question, it's not my case, and I also need to pass CSRF Token.

EDIT:

Also, I'm getting response in JSON in POSTMAN, I just need JS or AJAX Code to show it to users.

答:
Actually, you dont need to use csrf_token for GET request (requests that are not meant to change data in database). I will write a working example for POST request using jquery.

```<code>   $('.deleteCheckpoint').click(function(e){
      e.preventDefault();
      $.ajax({
        type: "POST",
        url: 'checkpoint/delete/',
        data: {
          csrfmiddlewaretoken:  getCookie('csrftoken')
        },
      success: function(){
        notification_message('Checkpoint was succesfully deleted');
      }
      });
   });
</code>```

The function getCookie is from the official documentation https://docs.djangoproject.com/en/1.11/ref/csrf/

Make sure that you have already store the cookie with the csrf_token, if you havent then include a  {% csrf_token %} in you html page. Django will automatically store the csrf_token in the browser, as a result the getCookie function will return the correct value.

Body:
I don't know python.

I'm just requesting Python REST APIs using jQuery and AJAX.

Here's my Code so far:

<!DOCTYPE html>

<title>Announcements</title>

I also need to pass CSRF Token to access the APIs.

Where CSRF Token is generated by Django Rest Framework.

I've seen this Question, it's not my case, and I also need to pass CSRF Token.

EDIT:

Also, I'm getting response in JSON in POSTMAN, I just need JS or AJAX Code to show it to users.

Body:
Actually, you dont need to use csrf_token for GET request (requests that are not meant to change data in database). I will write a working example for POST request using jquery.

   $('.deleteCheckpoint').click(function(e){
      e.preventDefault();
      $.ajax({
        type: "POST",
        url: 'checkpoint/delete/',
        data: {
          csrfmiddlewaretoken:  getCookie('csrftoken')
        },
      success: function(){
        notification_message('Checkpoint was succesfully deleted');
      }
      });
   });

The function getCookie is from the official documentation https://docs.djangoproject.com/en/1.11/ref/csrf/

Make sure that you have already store the cookie with the csrf_token, if you havent then include a  {% csrf_token %} in you html page. Django will automatically store the csrf_token in the browser, as a result the getCookie function will return the correct value.


问:
Foreach loop in CodeIgniter
I'm using the CI framework and I'm trying to make a foreach loop so that all products of my site are displayed.

This is my controller file:

```<code>class AlleCadeausController extends CI_Controller {

public function index()
{
    $this->load->model('allecadeaus_model');
    $data['cadeaus'] = $this->allecadeaus_model->get_cadeaus();
    $this->load->view('allecadeaus');
}
</code>```

This is my model file:

```<code><?php
class Allecadeaus_model extends CI_Model {
   public function __construct()
   {
       parent::__construct();
   }
    public function get_cadeaus()
    {
        $query = $this->db->query('SELECT * FROM products');
        $result = $query->result_array();
        return $result;
    }
}
</code>```

this is my view:

```<code><?php
foreach ($cadeaus as $cadeau)
{
    echo $cadeau->product_naam;
}
?>
</code>```

The error is:

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: cadeaus

Filename: views/allecadeaus.php

Line Number: 3

Backtrace:

File: /home/ubuntu/workspace/application/views/allecadeaus.php Line: 3
  Function: _error_handler

File:
  /home/ubuntu/workspace/application/controllers/AlleCadeausController.php
  Line: 11 Function: view

File: /home/ubuntu/workspace/index.php Line: 315 Function:
  require_once

My table name is products

答:
You haven't pass data to the view you just load view.
for passing data to view you have to do

```<code>$this->load->view('allecadeaus',$data);
</code>```

Here are good documentation for passing data from controller to view Contact ME

Title: Foreach loop in CodeIgniter

Body:
I'm using the CI framework and I'm trying to make a foreach loop so that all products of my site are displayed.

This is my controller file:

class AlleCadeausController extends CI_Controller {

public function index()
{
    $this->load->model('allecadeaus_model');
    $data['cadeaus'] = $this->allecadeaus_model->get_cadeaus();
    $this->load->view('allecadeaus');
}

This is my model file:

<?php
class Allecadeaus_model extends CI_Model {
   public function __construct()
   {
       parent::__construct();
   }
    public function get_cadeaus()
    {
        $query = $this->db->query('SELECT * FROM products');
        $result = $query->result_array();
        return $result;
    }
}

this is my view:

<?php
foreach ($cadeaus as $cadeau)
{
    echo $cadeau->product_naam;
}
?>

The error is:

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: cadeaus

Filename: views/allecadeaus.php

Line Number: 3

Backtrace:

File: /home/ubuntu/workspace/application/views/allecadeaus.php Line: 3
  Function: _error_handler

File:
  /home/ubuntu/workspace/application/controllers/AlleCadeausController.php
  Line: 11 Function: view

File: /home/ubuntu/workspace/index.php Line: 315 Function:
  require_once

My table name is products

Body:
You haven't pass data to the view you just load view.
for passing data to view you have to do

$this->load->view('allecadeaus',$data);

Here are good documentation for passing data from controller to view Contact ME


问:
Is there a listener for input checkbox to execute before change
I am having a checkbox and I could perform some operations when the checkbox is clicked using onchange function. But, what I need is, I have to prompt a popup/warning like, If you click the checkbox, some irreversible change could happen. If the user clicks ok in the popup go on with the onchange function, else if the user clicks cancel, undo the change operation. Is there a way to do this?</p>

答:
```<code>var checkbox = document.getElementById('myCheckbox');

checkbox.addEventListener('change', firePrompt);

function firePrompt(e) {
  if (e.target.checked) {
    setTimeout(function() {
      var result = confirm('Proceed?');
      if (result) {
        alert('User said OK');
      } else {
        alert('User said no!');
        e.target.checked = false;
      }
    }, 5)
  }
}
</code>```

I had to add a setTimeout as firePrompt was immediately fired and wouldn't display the tick until the User had either clicked OK or Cancel.

Here's a JSFiddle

Body:
var checkbox = document.getElementById('myCheckbox');

checkbox.addEventListener('change', firePrompt);

function firePrompt(e) {
  if (e.target.checked) {
    setTimeout(function() {
      var result = confirm('Proceed?');
      if (result) {
        alert('User said OK');
      } else {
        alert('User said no!');
        e.target.checked = false;
      }
    }, 5)
  }
}

I had to add a setTimeout as firePrompt was immediately fired and wouldn't display the tick until the User had either clicked OK or Cancel.

Here's a JSFiddle


问:
How can I get this query in correct format?
I've been trying to get some data to input to my sqli database using php..

Looking at the insert queries when I do it by GUI on PHPMyAdmin the variables need to be wrapped in single quotes..

This is how I am building the query so far:

```<code>$fields = array('`appName`' => $_POST[appName],
                    '`appDescription`' => $_POST[appDescription],
                    '`UploadDate`' => date("Y-m-d"),
                    '`appWebsite`' => $_POST[appWebsite]);
printarray($fields);

print "<br>";
print "<br>";

$columns = implode(", ",array_keys($fields));
$escaped_values = array_map('mysql_real_escape_string', array_values($fields));
$values  = implode(", ", $escaped_values);

$sql = "INSERT INTO `applist`.`apps` ($columns) VALUES ($values)";

print $sql;
print "<br>";

if (mysqli_query($conn, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error";
}
</code>```

This is giving me the query like so..

```<code>INSERT INTO `applist`.`apps` (`appName`, `appDescription`, `UploadDate`, `appWebsite`)
VALUES (SDD, DDD, 2017-06-02, DDDD)
</code>```

How do I get the values of the array wrapped in single quotes?

Any help appreciated.

答:
$columns = implode(", ",array_keys($fields));
  $escaped_values = array_map('mysql_real_escape_string', array_values($fields));

Ouch. not good.

Kudos trying to escape the content, but you're going to come unstuck using this code if the data ever contains commas.

You've got the beginnings of a nice generic method for inserting data, consider:

```<code>function insert($db_conn, $table, $data)
{
   $ins_vals=array(); // note we write the transformed data to a new array
      // as we may be modifying the column names too
   foreach ($data as $key=>$val) {
       // we need to protect the column names from injection attacks as
       // well as the data hence:
       $quoted_key="`" . str_replace("`", "", $key) . "`";

       // next we create an appropriate representation of the data value
       if (is_null($val)) {
           $ins_vals[$quoted_key]="NULL"; // in SQL 'NULL' != NULL
       } else if (is_numeric($val)) {
           // nothing to change here
           $ins_vals[$quoted_key]=$val;   // no need to quote/escape
       } else {
           $ins_vals[$quoted_key]="'"
               . mysqli_real_escape_string($dbconn, $val)
               . "'";
       }
   }
   // then we stick the bits together in an SQL statement
   $cols=implode(",", array_keys($ins_vals));
   $vals=implode(",", $ins_vals);
   $sql="INSERT INTO $table ($cols) VALUES ($vals)";
   return mysqli_query($dbconn, $sql);
}
</code>```

Body:
I've been trying to get some data to input to my sqli database using php..

Looking at the insert queries when I do it by GUI on PHPMyAdmin the variables need to be wrapped in single quotes..

This is how I am building the query so far:

$fields = array('`appName`' => $_POST[appName],
                    '`appDescription`' => $_POST[appDescription],
                    '`UploadDate`' => date("Y-m-d"),
                    '`appWebsite`' => $_POST[appWebsite]);
printarray($fields);

print "
";
print "
";

$columns = implode(", ",array_keys($fields));
$escaped_values = array_map('mysql_real_escape_string', array_values($fields));
$values  = implode(", ", $escaped_values);

$sql = "INSERT INTO `applist`.`apps` ($columns) VALUES ($values)";

print $sql;
print "
";

if (mysqli_query($conn, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error";
}

This is giving me the query like so..

INSERT INTO `applist`.`apps` (`appName`, `appDescription`, `UploadDate`, `appWebsite`)
VALUES (SDD, DDD, 2017-06-02, DDDD)

How do I get the values of the array wrapped in single quotes?

Any help appreciated.

Body:
$columns = implode(", ",array_keys($fields));
  $escaped_values = array_map('mysql_real_escape_string', array_values($fields));

Ouch. not good.

Kudos trying to escape the content, but you're going to come unstuck using this code if the data ever contains commas.

You've got the beginnings of a nice generic method for inserting data, consider:

function insert($db_conn, $table, $data)
{
   $ins_vals=array(); // note we write the transformed data to a new array
      // as we may be modifying the column names too
   foreach ($data as $key=>$val) {
       // we need to protect the column names from injection attacks as
       // well as the data hence:
       $quoted_key="`" . str_replace("`", "", $key) . "`";

       // next we create an appropriate representation of the data value
       if (is_null($val)) {
           $ins_vals[$quoted_key]="NULL"; // in SQL 'NULL' != NULL
       } else if (is_numeric($val)) {
           // nothing to change here
           $ins_vals[$quoted_key]=$val;   // no need to quote/escape
       } else {
           $ins_vals[$quoted_key]="'"
               . mysqli_real_escape_string($dbconn, $val)
               . "'";
       }
   }
   // then we stick the bits together in an SQL statement
   $cols=implode(",", array_keys($ins_vals));
   $vals=implode(",", $ins_vals);
   $sql="INSERT INTO $table ($cols) VALUES ($vals)";
   return mysqli_query($dbconn, $sql);
}


问:
How to set month value based on count
How to get the correct month in javascript. I don't want to use any plugin for this.

var date = new Date();
var month = date.getMonth();
// value is 06 current month;

var month = date.getMonth() + 15;
// now value is 21```
</div>
</div>
</p>

<p>Here, if the getMonth() count more than 12 means how can I get the correct month.
If more than 12 means I need to increase the year also right. </p>

<p>For Example,</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>// assume current month December
var month = date.getMonth()+3;  // value is 14</code>```

I want to show the month as "03" (MARCH). Please help me how can I do this

答:
You may set the month, causing it to also change the year:

```<code>var date=new Date();
alert(date+"");
date.setMonth(date.getMonth() + 15);
alert(date+"");
</code>```

The js engine already takes care of month overflows...

Title: How to set month value based on count

Body:
How to get the correct month in javascript. I don't want to use any plugin for this.

var date = new Date();
var month = date.getMonth();
// value is 06 current month;

var month = date.getMonth() + 15;
// now value is 21

Here, if the getMonth() count more than 12 means how can I get the correct month.
If more than 12 means I need to increase the year also right.

For Example,

// assume current month December
var month = date.getMonth()+3;  // value is 14

I want to show the month as "03" (MARCH). Please help me how can I do this

Body:
You may set the month, causing it to also change the year:

var date=new Date();
alert(date+"");
date.setMonth(date.getMonth() + 15);
alert(date+"");

The js engine already takes care of month overflows...


问:
jquery/javascript - hide div if containing image is broken
i have a div with the class 'userFeatureProductImage'. this div is repeated however occasionally a broken image might come through so i want to hide the div as a precaution if this does happen. how can i do this?</p>

答:
Use the error event which is called when an error occurs with the image:

```<code>$(".userFeatureProductImage img").error(function(){
   $(this).parent().hide();
});
</code>```

Example: http://jsfiddle.net/jonathon/vWwpc/

Body:
Use the error event which is called when an error occurs with the image:

$(".userFeatureProductImage img").error(function(){
   $(this).parent().hide();
});

Example: http://jsfiddle.net/jonathon/vWwpc/


问:
Throwing exception from CompletableFuture
I have the following code:

```<code>// How to throw the ServerException?
public void myFunc() throws ServerException{
    // Some code
    CompletableFuture<A> a = CompletableFuture.supplyAsync(() -> {
        try {
            return someObj.someFunc();
        } catch(ServerException ex) {
            // throw ex; gives an error here.
        }
    }));
    // Some code
}
</code>```

someFunc() throws a ServerException. I don't want to handle this here but throw the exception from someFunc() to caller of myFunc().

答:
Even if other's answer is very nice. but I give you another way to throw a checked exception in CompletableFuture.

IF you don't want to invoke a CompletableFuture in another thread, you can use an anonymous class to handle it like this:

```<code>CompletableFuture<A> a = new CompletableFuture<A>() {{
    try {
        complete(someObj.someFunc());
    } catch (ServerException ex) {
        completeExceptionally(ex);
    }
}};
</code>```

IF you want to invoke a CompletableFuture in another thread, you also can use an anonymous class to handle it, but run method by runAsync:

```<code>CompletableFuture<A> a = new CompletableFuture<A>() {{
    CompletableFuture.runAsync(() -> {
        try {
            complete(someObj.someFunc());
        } catch (ServerException ex) {
            completeExceptionally(ex);
        }
    });
}};
</code>```

Body:
I have the following code:

// How to throw the ServerException?
public void myFunc() throws ServerException{
    // Some code
    CompletableFuture a = CompletableFuture.supplyAsync(() -> {
        try {
            return someObj.someFunc();
        } catch(ServerException ex) {
            // throw ex; gives an error here.
        }
    }));
    // Some code
}

someFunc() throws a ServerException. I don't want to handle this here but throw the exception from someFunc() to caller of myFunc().

Body:
Even if other's answer is very nice. but I give you another way to throw a checked exception in CompletableFuture.

IF you don't want to invoke a CompletableFuture in another thread, you can use an anonymous class to handle it like this:

CompletableFuture<A> a = new CompletableFuture<A>() {{
    try {
        complete(someObj.someFunc());
    } catch (ServerException ex) {
        completeExceptionally(ex);
    }
}};

IF you want to invoke a CompletableFuture in another thread, you also can use an anonymous class to handle it, but run method by runAsync:

CompletableFuture<A> a = new CompletableFuture<A>() {{
    CompletableFuture.runAsync(() -> {
        try {
            complete(someObj.someFunc());
        } catch (ServerException ex) {
            completeExceptionally(ex);
        }
    });
}};

ContentLicense: CC BY-SA 4.0


问:
Web Development, Domain and Site Hosting
I'm not 100% sure if I'm on the correct section but i'll transfer the post once I know where it's supposed to be but I am looking for advice regarding web development, setting up a domain and hosting it.

I'm currently working on a personal project using Cloud9. Which is an online development environment where I can develop and host. The reason why I chose this is because it has MySQL usability as I retrieve and store data on the project I am working on.

I am now at the point where I want to get a domain and host a site to transfer my project over to a live website with my own domain which also has SQL/MySQL usability.

Any advice or where would be the best place to look up on methods of pursuing this?

Edit: I develop using PHP and JavaScript with MySQL

答:
To start I would suggest heroku, they have a free option and some nice guides, depending on which server side language you use . This way you can get used to hosting some apps and doing deployments, seeing logs etc.

The database doesn't have to be on the same hosting necessarily, you can use mongolab for example.

For domain names it's a different thing,  you will have to use the likes of godaddy


答:
You should pass the data to the view follow the below code:</p>

```<code>public function index()
{
    $this->load->model('allecadeaus_model');
    $data['cadeaus'] = $this->allecadeaus_model->get_cadeaus();
    $this->load->view('allecadeaus, $data');
}
</code>```

Title: Foreach loop in CodeIgniter

Body:
You should pass the data to the view follow the below code:

public function index()
{
    $this->load->model('allecadeaus_model');
    $data['cadeaus'] = $this->allecadeaus_model->get_cadeaus();
    $this->load->view('allecadeaus, $data');
}


问:
Spring, Thymeleaf - Change color text
I'm working on my project and at certain stage I need to change the color of certain words (Hashtags in this case).

I have this code in the controller:

(Note that 'resultado' is a valid string to get the tweets without problems)

```<code> List<Tweet> listaTuits = twitter.searchOperations().search(resultado).getTweets();
    List<ObjetoTuit> listaPropia = new ArrayList<ObjetoTuit>();
</code>```

I use listaPropia to get what I need from the original list

```<code>    for(int i=0; i<listaTuits.size();i++){
            Tweet enUso = listaTuits.get(i);

            String textoAManipular = enUso.getText();

            int contAux = this.listaDe5Elementos.getNumElementos();

            if(contAux>0 && textoAManipular.contains(this.listaDe5Elementos.getElemento1())){
                textoAManipular.replace(this.listaDe5Elementos.getElemento1(), "<span class=\"elem1\">"+this.listaDe5Elementos.getElemento1()+"</span>");
            }
            if(contAux>1 && textoAManipular.contains(this.listaDe5Elementos.getElemento2())){
                textoAManipular = textoAManipular.replace(this.listaDe5Elementos.getElemento2(), "<span class=\"elem2\">"+this.listaDe5Elementos.getElemento2()+"</span>");
            }
            if(contAux>2 && textoAManipular.contains(this.listaDe5Elementos.getElemento3())){
                textoAManipular = textoAManipular.replace(this.listaDe5Elementos.getElemento3(), "<span class=\"elem3\">"+this.listaDe5Elementos.getElemento3()+"</span>");
            }
            if(contAux>3 && textoAManipular.contains(this.listaDe5Elementos.getElemento4())){
                textoAManipular = textoAManipular.replace(this.listaDe5Elementos.getElemento4(), "<span class=\"elem4\">"+this.listaDe5Elementos.getElemento4()+"</span>");
            }
            if(contAux>4 && textoAManipular.contains(this.listaDe5Elementos.getElemento5())){
                textoAManipular = textoAManipular.replace(this.listaDe5Elementos.getElemento5(), "<span class=\"elem5\">"+this.listaDe5Elementos.getElemento5()+"</span>");
            }
            listaPropia.add(new ObjetoTuit(enUso.getId() ,textoAManipular, enUso.getFromUserId(), enUso.getFromUser(), enUso.getProfileImageUrl(),
                    enUso.getUser().getLocation(),  enUso.getRetweetCount(), enUso.getFavoriteCount(), enUso.getCreatedAt()));
        }
</code>```

At this moment I should have the complete list of items, and the 'textoAManipular' field should have a tag from class="elem1" to class="elem5"

```<code>ModelAndView mav = new ModelAndView("vistaPrincipal");
mav.addObject("listaobjetostuits", listaPropia);
return mav;
</code>```

Ok and now, in the view:

```<code><table class="table table-striped table-bordered">
        <thead>
            <tr>
                <th class="text-center">TEXTO</th>
                <th class="text-center">NOMBRE USUARIO</th>
                <th class="text-center">IMAGEN PERFIL</th>
                <th class="text-center">LOCALIZACION USUARIO</th>
                <th class="text-center">CONTADOR RETUITS</th>
                <th class="text-center">CONTADOR ME GUSTA</th>
                <th class="text-center">FECHA CREACION</th>
            </tr>
        </thead>
        <tbody th:each="tuit : ${listaobjetostuits}">
            <tr>
                <th th:text="${tuit.texto}"></th>
                <th th:text="${tuit.nombreUsuario}"></th>
                <th><img th:src="${tuit.urlImagenPerfil}" class="img-thumbnail" /></th>
                <th th:text="${tuit.localizacionUser}"></th>
                <th th:text="${tuit.numRT}"></th>
                <th th:text="${tuit.numMG}"></th>
                <th th:text="${tuit.fechaCreacion}"></th>
            </tr>
        </tbody>
    </table>
</code>```

And here comes the problem I try to explain before, I can not change the color of the text. I've tried what you told me, changing the id tag to class tag, using jQuery or even using a style:color tag.

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
        $(".elem1").css("color", "red");
        $(".elem2").css("color", "blue");
        $(".elem3").css("color", "green");
        $(".elem4").css("color", "yellow");
        $(".elem5").css("color", "brown");
});
</script>
</code>```

This doesn't work for me.

Any idea?

答:
You should use CSS classes instead of ids. Because id should be unique in DOM tree, CSS classes not, and I assume you have more than one word of same kind.

CSS file:

```<code>.red { color:red; }
.green { color:green; }
</code>```

Your replace method:

```<code>  text.replace(word, '<span class="red">' + word + '</span>')
</code>```

With this code, you can replace multiple words, and gave them same CSS class, that will add the color.

In your case you would have to run your code after replace methods are called, which would be additional work, with CSS the browser will do the work for you.

UPDATE:

Your CSS should look like this:

```<code><style>
    .red  { color: 'red' };
    .blue { color: 'blue'};
     ...
</style>
</code>```

It seems to be working fine within this example. As you can see I have used a map to store all mappings (word to color). That was the code is shorter.

```<code>Map<String,String> mappings = new HashMap<>();
mappings.put("Trump", "red");

String t = "<th>#Lynch not #Trump #ComeyDay </th>";
for(Map.Entry<String,String> entry: mappings.entrySet()){
   t= t.replace(entry.getKey(), "<span class=\""+entry.getValue()+"\">" +entry.getKey() + "</span>");
}

System.out.print(t);
</code>```

The output is:

```<code><th>#Lynch not #<span class="red">Trump</span> #ComeyDay </th>
</code>```

Title: Spring, Thymeleaf - Change color text

Body:
I'm working on my project and at certain stage I need to change the color of certain words (Hashtags in this case).

I have this code in the controller:

(Note that 'resultado' is a valid string to get the tweets without problems)

 List<Tweet> listaTuits = twitter.searchOperations().search(resultado).getTweets();
    List<ObjetoTuit> listaPropia = new ArrayList<ObjetoTuit>();

I use listaPropia to get what I need from the original list

    for(int i=0; i<listaTuits.size();i++){
            Tweet enUso = listaTuits.get(i);

            String textoAManipular = enUso.getText();

            int contAux = this.listaDe5Elementos.getNumElementos();

            if(contAux>0 && textoAManipular.contains(this.listaDe5Elementos.getElemento1())){
                textoAManipular.replace(this.listaDe5Elementos.getElemento1(), ""+this.listaDe5Elementos.getElemento1()+"");
            }
            if(contAux>1 && textoAManipular.contains(this.listaDe5Elementos.getElemento2())){
                textoAManipular = textoAManipular.replace(this.listaDe5Elementos.getElemento2(), ""+this.listaDe5Elementos.getElemento2()+"");
            }
            if(contAux>2 && textoAManipular.contains(this.listaDe5Elementos.getElemento3())){
                textoAManipular = textoAManipular.replace(this.listaDe5Elementos.getElemento3(), ""+this.listaDe5Elementos.getElemento3()+"");
            }
            if(contAux>3 && textoAManipular.contains(this.listaDe5Elementos.getElemento4())){
                textoAManipular = textoAManipular.replace(this.listaDe5Elementos.getElemento4(), ""+this.listaDe5Elementos.getElemento4()+"");
            }
            if(contAux>4 && textoAManipular.contains(this.listaDe5Elementos.getElemento5())){
                textoAManipular = textoAManipular.replace(this.listaDe5Elementos.getElemento5(), ""+this.listaDe5Elementos.getElemento5()+"");
            }
            listaPropia.add(new ObjetoTuit(enUso.getId() ,textoAManipular, enUso.getFromUserId(), enUso.getFromUser(), enUso.getProfileImageUrl(),
                    enUso.getUser().getLocation(),  enUso.getRetweetCount(), enUso.getFavoriteCount(), enUso.getCreatedAt()));
        }

At this moment I should have the complete list of items, and the 'textoAManipular' field should have a tag from class="elem1" to class="elem5"

ModelAndView mav = new ModelAndView("vistaPrincipal");
mav.addObject("listaobjetostuits", listaPropia);
return mav;

Ok and now, in the view:

                TEXTO
                NOMBRE USUARIO
                IMAGEN PERFIL
                LOCALIZACION USUARIO
                CONTADOR RETUITS
                CONTADOR ME GUSTA
                FECHA CREACION

And here comes the problem I try to explain before, I can not change the color of the text. I've tried what you told me, changing the id tag to class tag, using jQuery or even using a style:color tag.

This doesn't work for me.

Any idea?

Body:
You should use CSS classes instead of ids. Because id should be unique in DOM tree, CSS classes not, and I assume you have more than one word of same kind.

CSS file:

.red { color:red; }
.green { color:green; }

Your replace method:

  text.replace(word, '<span class="red">' + word + '</span>')

With this code, you can replace multiple words, and gave them same CSS class, that will add the color.

In your case you would have to run your code after replace methods are called, which would be additional work, with CSS the browser will do the work for you.

UPDATE:

Your CSS should look like this:

<style>
    .red  { color: 'red' };
    .blue { color: 'blue'};
     ...
</style>

It seems to be working fine within this example. As you can see I have used a map to store all mappings (word to color). That was the code is shorter.

Map<String,String> mappings = new HashMap<>();
mappings.put("Trump", "red");

String t = "<th>#Lynch not #Trump #ComeyDay </th>";
for(Map.Entry<String,String> entry: mappings.entrySet()){
   t= t.replace(entry.getKey(), "<span class=\""+entry.getValue()+"\">" +entry.getKey() + "</span>");
}

System.out.print(t);

The output is:

<th>#Lynch not #<span class="red">Trump</span> #ComeyDay </th>


问:
Is it possible to run javascript after a page has loaded using a omnibox extension?
I am trying to build an omnibox extension. Essentially I want this extension to pull up a url, then wait for that url to load, then execute some simple javascript.

Not sure if it's appreciated to put long blocks of code in questions, please feel free to yell at me if not.

manifest.json:

```<code>{
    "manifest_version": 2,
    "name": "AutoATR",
    "version": "0.1",
    "omnibox": { "keyword" : "atr" },
    "icons": {
      "16": "package.png"
    },
    "background": {
      "persistent": true,
      "scripts": ["background.js"]
    }
}
</code>```

background.js:

```<code>function resetDefaultSuggestion() {
  chrome.omnibox.setDefaultSuggestion({
  description: 'atr: Placeholder: %s'
  });
}
resetDefaultSuggestion();

function navigate(url) {
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs)
{
  chrome.tabs.update(tabs[0].id, {url: url});
  });
}

function finder(theID) {
  document.getElementById('theElement').value=theID
  document.getElementsByClassName('btn')[1].click()
}

chrome.omnibox.onInputEntered.addListener(function() {
    // Navigate to URL
    navigate("https://theURL.com");
});

// **** Would like to wait for just this tab to load.
// Then Execute finder(). ****
</code>```

答:
You can use manifest for your task:
change location in background script location of tab to your pathURL and in manifest.json add next code : </p>

```<code>  "content_scripts": [{
            "matches": ["http://pathURL"],
            "js": ["js/script.js"]
        }]
</code>```

<p>js/script.js will be loaded after your browser tab path will match with "http://pathURL" pattern. </p>

Body:
I am trying to build an omnibox extension. Essentially I want this extension to pull up a url, then wait for that url to load, then execute some simple javascript.

Not sure if it's appreciated to put long blocks of code in questions, please feel free to yell at me if not.

manifest.json:

{
    "manifest_version": 2,
    "name": "AutoATR",
    "version": "0.1",
    "omnibox": { "keyword" : "atr" },
    "icons": {
      "16": "package.png"
    },
    "background": {
      "persistent": true,
      "scripts": ["background.js"]
    }
}

background.js:

function resetDefaultSuggestion() {
  chrome.omnibox.setDefaultSuggestion({
  description: 'atr: Placeholder: %s'
  });
}
resetDefaultSuggestion();

function navigate(url) {
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs)
{
  chrome.tabs.update(tabs[0].id, {url: url});
  });
}

function finder(theID) {
  document.getElementById('theElement').value=theID
  document.getElementsByClassName('btn')[1].click()
}

chrome.omnibox.onInputEntered.addListener(function() {
    // Navigate to URL
    navigate("https://theURL.com");
});

// **** Would like to wait for just this tab to load.
// Then Execute finder(). ****

Body:
You can use manifest for your task:
change location in background script location of tab to your pathURL and in manifest.json add next code :

  "content_scripts": [{
            "matches": ["http://pathURL"],
            "js": ["js/script.js"]
        }]

js/script.js will be loaded after your browser tab path will match with "http://pathURL" pattern.


问:
background: fixed no repeat not working on mobile
I am building a webpage where I want the background image to scale to fit the whole screen, maintain aspect ratio and be fixed (so if you scroll down, the background image stays in the same place).

I have achieved this in desktop browsers with the CSS below, but it doesn't work on an iPhone or iPad. On those devices the background is too big (it continues below the fold) and if you scroll down far enough, the image will start repeating.  Anyone have a fix? THanks!

```<code>HTML {
  background: url(photos/2452.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
</code>```

答:
I had a very simple solution for this, after struggling with all the methods of fixing this.

i had the problem on my mobile IOS devices.

css (desktop)

```<code>#ci-hero-11 .widget-wrap , #ci-hero-12 .widget-wrap {
background-size: auto;
background-attachment: fixed;
}

.widget-wrap {
background-attachment: scroll;
}
</code>```

Then i overwrite it with media query removing "fixed" as background attachment.

css (mobile)

```<code>@media (max-width: 767px) {
#ci-hero-11 .widget-wrap , #ci-hero-12 .widget-wrap {

    background-attachment: initial;

}
}
</code>```

initial -   Sets this property to its default value. I think because IOS doesn't accept 'fixed' it falls back to a default value it accepts, scroll.

This worked for me on every device. Hope it helps someone else as well.

Body:
I am building a webpage where I want the background image to scale to fit the whole screen, maintain aspect ratio and be fixed (so if you scroll down, the background image stays in the same place).

I have achieved this in desktop browsers with the CSS below, but it doesn't work on an iPhone or iPad. On those devices the background is too big (it continues below the fold) and if you scroll down far enough, the image will start repeating.  Anyone have a fix? THanks!

HTML {
  background: url(photos/2452.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

Body:
I had a very simple solution for this, after struggling with all the methods of fixing this.

i had the problem on my mobile IOS devices.

css (desktop)

#ci-hero-11 .widget-wrap , #ci-hero-12 .widget-wrap {
background-size: auto;
background-attachment: fixed;
}

.widget-wrap {
background-attachment: scroll;
}

Then i overwrite it with media query removing "fixed" as background attachment.

css (mobile)

@media (max-width: 767px) {
#ci-hero-11 .widget-wrap , #ci-hero-12 .widget-wrap {

    background-attachment: initial;

}
}

initial -   Sets this property to its default value. I think because IOS doesn't accept 'fixed' it falls back to a default value it accepts, scroll.

This worked for me on every device. Hope it helps someone else as well.


问:
How to generate the configuration to connect to a remote Kubernetes host
I have finished setting up a test Kubernets host running on a bare metal Centos 7. This will be used as a test system as we will be deploying everything in IBM Bluemix Kubernetes service.

Getting the configuration from Bluemix is easy... and while our Kubernetes on Centos works OK I don't know how to generate the configuration to access it from our workstations. It is explained at
https://kubernetes.io/docs/tasks/administer-cluster/share-configuration/

but I am new to setting up a Kubernetes host... and have no idea where that

```<code>$ cluster/kube-up.sh
</code>```

command is... or which package to install to get it.

Thanks for any guide on this.

答:
You can try option see, copy admin.conf file to your workstation, then run

```<code> kubectl --kubeconfig=./admin.conf proxy -p 80
</code>```

after this your can access your dashboard from workstation http://localhost/ui

Body:
I have finished setting up a test Kubernets host running on a bare metal Centos 7. This will be used as a test system as we will be deploying everything in IBM Bluemix Kubernetes service.

Getting the configuration from Bluemix is easy... and while our Kubernetes on Centos works OK I don't know how to generate the configuration to access it from our workstations. It is explained at
https://kubernetes.io/docs/tasks/administer-cluster/share-configuration/

but I am new to setting up a Kubernetes host... and have no idea where that

$ cluster/kube-up.sh

command is... or which package to install to get it.

Thanks for any guide on this.

Body:
You can try option see, copy admin.conf file to your workstation, then run

 kubectl --kubeconfig=./admin.conf proxy -p 80

after this your can access your dashboard from workstation http://localhost/ui


问:
String vs string

Possible Duplicate:

  In C# what is the difference between String and string

Should I use string or String when declaring a basic string variable in c# and does it matter?

答: They both point to the same class. It doesn't matter which one you use.</p>

Title: String vs string


问:
update bar chart using a slider in matplotlib
I try to make a simple bar chart, where I can monitor a chemical reaction ( A -> B) using a slider for reaction steps.
So far, the following code yields a bar chart for A with a slider for reactionsteps. The print function prints the expected values for A after certain reaction steps. However, the plot won't be updated. I tried plt.draw(), plt.show() and fig.canvas.draw() but none of them worked.

```<code>import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import Slider, Button

fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)
fig.canvas.set_window_title('Einfluss der Geschwindigkeitskonstanten')

a0 = 1
b0 = 0
plt.axis([0, 5, 0, 2])
plt.xticks([1, 4], ['A', 'B'])
plt.bar(1, a0, color = 'red')

#slider:
axcolor = 'lightblue'
axrs = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)
srs = Slider(axrs, 'RS', 0, 20, valinit=0)

def slider_val_fkt(t):
    ya = []
    t = srs.val
    ya = [np.exp(-0.6 * t)]
    print(ya)
    plt.bar(1, ya, color = 'red')
    #plt.draw()
    #plt.show()
    fig.canvas.draw()

srs.on_changed(slider_val_fkt)

plt.show()
</code>```

答:
The new bar is drawn inside the slider axes instead of the original axes:

To overcome this you should work on the axes objects instead of using pyplot. However, since you anyways want to update the bar instead of drawing a new one, it is sufficient here to work with the bars themselves and update them using set_height.

```<code>bars = plt.bar(1, a0, color = 'red')

axrs = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor='lightblue')
srs = Slider(axrs, 'RS', 0, 20, valinit=0)

def slider_val_fkt(t):
    t = srs.val
    ya = [np.exp(-0.6 * t)]
    bars[0].set_height(ya[0])
    fig.canvas.draw_idle()

srs.on_changed(slider_val_fkt)
</code>```

Body:
I try to make a simple bar chart, where I can monitor a chemical reaction ( A -> B) using a slider for reaction steps.
So far, the following code yields a bar chart for A with a slider for reactionsteps. The print function prints the expected values for A after certain reaction steps. However, the plot won't be updated. I tried plt.draw(), plt.show() and fig.canvas.draw() but none of them worked.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import Slider, Button

fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)
fig.canvas.set_window_title('Einfluss der Geschwindigkeitskonstanten')

a0 = 1
b0 = 0
plt.axis([0, 5, 0, 2])
plt.xticks([1, 4], ['A', 'B'])
plt.bar(1, a0, color = 'red')

#slider:
axcolor = 'lightblue'
axrs = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)
srs = Slider(axrs, 'RS', 0, 20, valinit=0)

def slider_val_fkt(t):
    ya = []
    t = srs.val
    ya = [np.exp(-0.6 * t)]
    print(ya)
    plt.bar(1, ya, color = 'red')
    #plt.draw()
    #plt.show()
    fig.canvas.draw()

srs.on_changed(slider_val_fkt)

plt.show()

Body:
The new bar is drawn inside the slider axes instead of the original axes:

To overcome this you should work on the axes objects instead of using pyplot. However, since you anyways want to update the bar instead of drawing a new one, it is sufficient here to work with the bars themselves and update them using set_height.

bars = plt.bar(1, a0, color = 'red')

axrs = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor='lightblue')
srs = Slider(axrs, 'RS', 0, 20, valinit=0)

def slider_val_fkt(t):
    t = srs.val
    ya = [np.exp(-0.6 * t)]
    bars[0].set_height(ya[0])
    fig.canvas.draw_idle()

srs.on_changed(slider_val_fkt)


问:
Elements
 are not scaling to the container
I want to create a table using flexbox. The problem is columns are not scaling to the 100% of the container - in fact table, thead and tbody are in correct size, but trs are not.

HTML:

```<code><table>
    <thead>
        <tr>
            <td>Header 1</td>
            <td>Header 2</td>
        </tr>
    <tr>
            <td><input placeholder="Filter" /></td>
            <td><input placeholder="Filter" /></td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>123</td>
            <td>456</td>
        </tr>
        <tr>
            <td>123</td>
            <td>456</td>
        </tr>
        <tr>
            <td>123</td>
            <td>456</td>
        </tr>
        <tr>
            <td>123</td>
            <td>456</td>
        </tr>
        <tr>
            <td>123</td>
            <td>456</td>
        </tr>
    <tr>
            <td>123</td>
            <td>456</td>
        </tr>
    <tr>
            <td>123</td>
            <td>456</td>
        </tr>
    <tr>
            <td>123</td>
            <td>456</td>
        </tr>
    </tbody>
</table>
</code>```

LESS:

```<code>table {
  display: flex;
  flex-direction: column;
  align-items: stretch;
  height: 200px;

  thead, tbody {
    flex: 1 1 auto;
  }

  tbody {
    overflow-y: scroll;
  }
}
</code>```

Codepen here

答:
Why the cells does not align is because you added display: flex to the table and both it and the thead/tbody stopped behave as just that.

Each group of tr (in the thead and tbody), which no longer has a normal shared table as a direct parent, will size by their content.

Their might even be an anonymous table created, which even better would describe the issue, but can't say that for sure, so if someone knows that, feel free to comment or update my answer.

By adding these 2 rules, it will start work similar to a table.

```<code>tbody tr, thead tr {
  display: flex;
}
tbody td, thead td {
  flex: 1;
}
</code>```

Updated codepen

May I recommend you use the table elements as is, or if you want Flexbox, do like this instead, using i.e. div elements.

Updated codepen

Stack snippet

.table {
  display: flex;
  flex-direction: column;
  height: 200px;
}
.table .scroller {
  flex: 1;
  overflow: auto;
  min-height: 0;
}
.table .scroller .row {
  flex: 1 1 auto;
}
.table .row {
  display: flex;
}
.table .row > div {
  flex: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="table">
  <div class="row">
    <div>Header 1</div>
    <div>Header 2</div>
  </div>
  <div class="row">
    <div><input placeholder="Filter" /></div>
    <div><input placeholder="Filter" /></div>
  </div>
  <div class="scroller">
    <div class="row">
      <div>123</div>
      <div>456</div>
    </div>
    <div class="row">
      <div>123</div>
      <div>456</div>
    </div>
    <div class="row">
      <div>123</div>
      <div>456</div>
    </div>
    <div class="row">
      <div>123</div>
      <div>456</div>
    </div>
    <div class="row">
      <div>123</div>
      <div>456</div>
    </div>
    <div class="row">
      <div>123</div>
      <div>456</div>
    </div>
    <div class="row">
      <div>123</div>
      <div>456</div>
    </div>
    <div class="row">
      <div>123</div>
      <div>456</div>
    </div>
    <div class="row">
      <div>123</div>
      <div>456</div>
    </div>
    <div class="row">
      <div>123</div>
      <div>456</div>
    </div>
    <div class="row">
      <div>123</div>
      <div>456</div>
    </div>
    <div class="row">
      <div>123</div>
      <div>456</div>
    </div>
  </div>
</div></code>```

Title: Elements <tr> are not scaling to the container

Body:
I want to create a table using flexbox. The problem is columns are not scaling to the 100% of the container - in fact table, thead and tbody are in correct size, but trs are not.

HTML:

            Header 1
            Header 2

            <input placeholder="Filter" />
            <input placeholder="Filter" />

            123
            456

            123
            456

            123
            456

            123
            456

            123
            456

            123
            456

            123
            456

            123
            456

LESS:

table {
  display: flex;
  flex-direction: column;
  align-items: stretch;
  height: 200px;

  thead, tbody {
    flex: 1 1 auto;
  }

  tbody {
    overflow-y: scroll;
  }
}

Codepen here

Body:
Why the cells does not align is because you added display: flex to the table and both it and the thead/tbody stopped behave as just that.

Each group of tr (in the thead and tbody), which no longer has a normal shared table as a direct parent, will size by their content.

Their might even be an anonymous table created, which even better would describe the issue, but can't say that for sure, so if someone knows that, feel free to comment or update my answer.

By adding these 2 rules, it will start work similar to a table.

tbody tr, thead tr {
  display: flex;
}
tbody td, thead td {
  flex: 1;
}

Updated codepen

May I recommend you use the table elements as is, or if you want Flexbox, do like this instead, using i.e. div elements.

Updated codepen

Stack snippet

.table {
  display: flex;
  flex-direction: column;
  height: 200px;
}
.table .scroller {
  flex: 1;
  overflow: auto;
  min-height: 0;
}
.table .scroller .row {
  flex: 1 1 auto;
}
.table .row {
  display: flex;
}
.table .row > div {
  flex: 1;
}

<div class="table">
  <div class="row">
    <div>Header 1</div>
    <div>Header 2</div>
  </div>
  <div class="row">
    <div><input placeholder="Filter" /></div>
    <div><input placeholder="Filter" /></div>
  </div>
  <div class="scroller">
    <div class="row">
      <div>123</div>
      <div>456</div>
    </div>
    <div class="row">
      <div>123</div>
      <div>456</div>
    </div>
    <div class="row">
      <div>123</div>
      <div>456</div>
    </div>
    <div class="row">
      <div>123</div>
      <div>456</div>
    </div>
    <div class="row">
      <div>123</div>
      <div>456</div>
    </div>
    <div class="row">
      <div>123</div>
      <div>456</div>
    </div>
    <div class="row">
      <div>123</div>
      <div>456</div>
    </div>
    <div class="row">
      <div>123</div>
      <div>456</div>
    </div>
    <div class="row">
      <div>123</div>
      <div>456</div>
    </div>
    <div class="row">
      <div>123</div>
      <div>456</div>
    </div>
    <div class="row">
      <div>123</div>
      <div>456</div>
    </div>
    <div class="row">
      <div>123</div>
      <div>456</div>
    </div>
  </div>
</div>


问:
Shortcut for echo "
";print_r($myarray);echo "
";
Is there a Shortcut for

```<code>echo "```";
   print_r($myarray);
echo "```";
</code>```

It is really annoying typing those just to get a readable format of an array.

答:
```<code><?php
$people = array(
    "maurice"=> array("name"=>"Andrew",
                      "age"=>40,
                      "gender"=>"male"),
    "muteti" => array("name"=>"Francisca",
                      "age"=>30,
                      "gender"=>"Female")
               );
'```'.
print_r($people).
'```';

/*foreach ($people as $key => $value) {
    echo "<h2><strong>$key</strong></h2><br>";
    foreach ($value as $values) {
    echo $values."<br>";;
    }
}*/
//echo $people['maurice']['name'];

?>
</code>```

Title: Shortcut for echo "<pre>";print_r($myarray);echo "</pre>";

Body:
Is there a Shortcut for

echo "
";
   print_r($myarray);
echo "
";

It is really annoying typing those just to get a readable format of an array.

Body:
<?php
$people = array(
    "maurice"=> array("name"=>"Andrew",
                      "age"=>40,
                      "gender"=>"male"),
    "muteti" => array("name"=>"Francisca",
                      "age"=>30,
                      "gender"=>"Female")
               );
'<pre>'.
print_r($people).
'</pre>';

/*foreach ($people as $key => $value) {
    echo "<h2><strong>$key</strong></h2><br>";
    foreach ($value as $values) {
    echo $values."<br>";;
    }
}*/
//echo $people['maurice']['name'];

?>


问:
-webkit-box-reflect disappears while transitioning
I'm looking for a solution for this:
When the image starting the transition it loses the reflection till the end, when it comes back.

What am I missing? Thanks!

.specials-box {
    width: 330px;
    margin: 50px 0;
    height: 500px;
    position: relative;
    cursor: pointer;
}

.special-img {
   width: 80%;
    position: absolute;
    top: 20px;
    left: 10%;
   transition: all 0.3s ease-in-out;
  -webkit-box-reflect: below 0px -webkit-gradient(linear, left top, left bottom, from(transparent), color-stop(70%, transparent) , to(rgba(250, 250, 250, 0.3)));
  transition: all 0.3s ease-in-out;
  filter: grayscale(100%);
}

.specials-box:hover .special-img {
  filter: grayscale(0%);
  top:0;
  transition: all 0.3s ease-in-out;
  -webkit-box-reflect: below 25px -webkit-gradient(linear, left top, left bottom, from(transparent), color-stop(70%, transparent) , to(rgba(250, 250, 250, 0.3)));
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="specials-box">
  <img class="special-img" src="https://koktelbolt.shoprenter.hu/custom/koktelbolt/image/data/specials/4.png" />
</div></code>```

答:
Gradients don't support transitions yet (although the current spec says they should support like gradient to like gradient transitions via interpolation.).
just posted an example for understanding

        .year {
        display: inline-block;
        padding: 10px 15px;
        cursor: pointer;
        text-align: center;
        color: #fff;
        font-size: 17px;
        border-radius: 20px;
         background: rgba(5,176,196,1);
        background: -webkit-linear-gradient(170deg, #05b0c4, #80ff8f);
        background: -o-linear-gradient(170deg, 170deg, #05b0c4, #80ff8f);
        background: -moz-linear-gradient(170deg, 170deg, #05b0c4, #80ff8f);
        background: linear-gradient(170deg, #05b0c4, #80ff8f);
        transition:all 0.4s linear;
    }
    .year:hover {
        background: rgba(5,176,196,1);
        background: -webkit-linear-gradient(170deg, #80ff8f, #05b0c4);
        background: -o-linear-gradient(170deg, #80ff8f, #05b0c4);
        background: -moz-linear-gradient(170deg, #80ff8f, #05b0c4);
        background: linear-gradient(170deg, #80ff8f, #05b0c4);
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="year">2017</div></code>```

You can use pseudo classes for it

.button {
  display: inline-block;
  margin-top: 10%;
  padding: 1em 2em;
  font-size: 2em;
  color: #fff;
  font-family: arial, sans-serif;
  text-decoration: none;
  border-radius: 0.3em;
  position: relative;
  background-color: #ccc;
  background-image: linear-gradient(to top, #6d8aa0, #8ba2b4);
  -webkit-backface-visibility: hidden;
  z-index: 1;
}
.button:after {
  position: absolute;
  content: '';
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border-radius: 0.3em;
  background-image: linear-gradient(to top, red, blue);
  transition: opacity 0.5s ease-out;
  z-index: 2;
  opacity: 0;
}
.button:hover:after {
  opacity: 1;
}
.button span {
  position: relative;
  z-index: 3;
}
body {
  text-align: center;
  background: #ddd;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span>BUTTON</span></code>```

Body:
Gradients don't support transitions yet (although the current spec says they should support like gradient to like gradient transitions via interpolation.).
just posted an example for understanding

        .year {
        display: inline-block;
        padding: 10px 15px;
        cursor: pointer;
        text-align: center;
        color: #fff;
        font-size: 17px;
        border-radius: 20px;
         background: rgba(5,176,196,1);
        background: -webkit-linear-gradient(170deg, #05b0c4, #80ff8f);
        background: -o-linear-gradient(170deg, 170deg, #05b0c4, #80ff8f);
        background: -moz-linear-gradient(170deg, 170deg, #05b0c4, #80ff8f);
        background: linear-gradient(170deg, #05b0c4, #80ff8f);
        transition:all 0.4s linear;
    }
    .year:hover {
        background: rgba(5,176,196,1);
        background: -webkit-linear-gradient(170deg, #80ff8f, #05b0c4);
        background: -o-linear-gradient(170deg, #80ff8f, #05b0c4);
        background: -moz-linear-gradient(170deg, #80ff8f, #05b0c4);
        background: linear-gradient(170deg, #80ff8f, #05b0c4);
    }

<div class="year">2017</div>

You can use pseudo classes for it

.button {
  display: inline-block;
  margin-top: 10%;
  padding: 1em 2em;
  font-size: 2em;
  color: #fff;
  font-family: arial, sans-serif;
  text-decoration: none;
  border-radius: 0.3em;
  position: relative;
  background-color: #ccc;
  background-image: linear-gradient(to top, #6d8aa0, #8ba2b4);
  -webkit-backface-visibility: hidden;
  z-index: 1;
}
.button:after {
  position: absolute;
  content: '';
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border-radius: 0.3em;
  background-image: linear-gradient(to top, red, blue);
  transition: opacity 0.5s ease-out;
  z-index: 2;
  opacity: 0;
}
.button:hover:after {
  opacity: 1;
}
.button span {
  position: relative;
  z-index: 3;
}
body {
  text-align: center;
  background: #ddd;
}

<a class="button" href="#"><span>BUTTON</span></a>


问:
Changes to button in fragment not shown on screen
I have a ViewPager that loads a quiz-question from database.
In my fragment i implemented a left- and right arrow to try to inform the user that the view is slideable. I also wanted to implement onClickListeners to them so that they also can be clicked to change to the next or previous fragment.

To indicate when the user is on the first/last question i used setAlpha on the background to gray it out. I can see in the debugger that the method is called, but alpha-change is not shown on the display of the device. Now if i scroll two pages forward and back again to the first, i can see that the button is gray.

Relevant code from my fragment:

```<code>public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
    if(mQuestion.getId() == 10) ) {
        mRightButton.getBackground().setAlpha(40);
    } else {
        mRightButton.getBackground().setAlpha(255);
        mRightButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ((QuizActivity)getActivity()).nextFragment();
            }
        });
    }

    if(mQuestion.getId() == 1) {
        mLeftButton.getBackground().setAlpha(40); // is called but not changing the alpha on the button until i slide forward and back...
    } else {
        mLeftButton.getBackground().setAlpha(255);
        mLeftButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ((QuizActivity)getActivity()).previousFragment();
            }
        });
    }
}
</code>```

The onClickListeners work as intended.

答: Just discovered that if i use setVisibility(View.HIDDEN) instead of changing the Alpha it works fine.</p>

Body:
I have a ViewPager that loads a quiz-question from database.
In my fragment i implemented a left- and right arrow to try to inform the user that the view is slideable. I also wanted to implement onClickListeners to them so that they also can be clicked to change to the next or previous fragment.

To indicate when the user is on the first/last question i used setAlpha on the background to gray it out. I can see in the debugger that the method is called, but alpha-change is not shown on the display of the device. Now if i scroll two pages forward and back again to the first, i can see that the button is gray.

Relevant code from my fragment:

public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
    if(mQuestion.getId() == 10) ) {
        mRightButton.getBackground().setAlpha(40);
    } else {
        mRightButton.getBackground().setAlpha(255);
        mRightButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ((QuizActivity)getActivity()).nextFragment();
            }
        });
    }

    if(mQuestion.getId() == 1) {
        mLeftButton.getBackground().setAlpha(40); // is called but not changing the alpha on the button until i slide forward and back...
    } else {
        mLeftButton.getBackground().setAlpha(255);
        mLeftButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ((QuizActivity)getActivity()).previousFragment();
            }
        });
    }
}

The onClickListeners work as intended.


问:
service content when duplicated does not display
i have owl carousel when duplicate the content it wont display why is that

jsfiddle

```<code>       <div class="col-sm-12">
      <div id="service-slider" class="owl-carousel">
      <!--Service item 1 -->
 <div class="item">
<div class="service-items">
    <img class="img-circle service-slider-image"
        src="images/service-slider1.jpg" alt="">
    <div class="service-details">
        <h3>Engagement  Make up</h3>
        <!--
            <p>Dramatically maintain clicks-and-mortar solutions without
            functional solutions. Completely synergize resource </p>
                                            --><!--
            <a href="#" class="more-service"><i class="fa fa-plus"></i></a>
                                             -->
    </div>
</div>
</code>```

答:
maybe i don't understand correctly your issue. but why don't you remove hide content signs

see below

SERVICES

— What can I do for you?

Engagement  Make up

Dramatically maintain clicks-and-mortar solutions without functional solutions. Completely synergize resource

Pre-Wedding  Make up

Reception Make up

Dramatically maintain clicks-and-mortar solutions without functional solutions. Completely synergize resource

Celebrity Make

Dramatically maintain clicks-and-mortar solutions without functional solutions. Completely synergize resource

Fashion

Dramatically maintain clicks-and-mortar solutions without functional solutions. Completely synergize resource

Hair Styles

Dramatically maintain clicks-and-mortar solutions without functional solutions. Completely synergize resource

```

Body:
i have owl carousel when duplicate the content it wont display why is that

jsfiddle

Engagement  Make up

Body:
maybe i don't understand correctly your issue. but why don't you remove hide content signs

see below

<section id="service">
            <div class="container">
                <div class="row">
                    <div class="col-sm-12">
                        <div class="col-sm-12">
                            <div class="theme-title-area">
                                <h2>SERVICES</h2>
                                <h6>— What can I do for you?</h6>
                            </div>
                        </div>
                    </div>
                    <!-- service slider -->
                    <div class="col-sm-12">
                        <div id="service-slider" class="owl-carousel">
                            <!--Service item 1 -->
                            <div class="item">
                                <div class="service-items">
                                    <img class="img-circle service-slider-image" src="images/service-slider1.jpg" alt="">
                                    <div class="service-details">
                                        <h3>Engagement  Make up</h3>
                                                                             <p>Dramatically maintain clicks-and-mortar solutions without functional solutions. Completely synergize resource </p>
                                                                                <a href="#" class="more-service"><i class="fa fa-plus"></i></a>

                                    </div>
                                </div>
                            </div>
                            <!--END OF Service item 1 -->
                            <!--Service item 2 -->
                            <div class="item">
                                <div class="service-items">
                                    <img class="img-circle service-slider-image" src="images/service-slider2.jpg" alt="">
                                    <div class="service-details">
                                        <h3>Pre-Wedding  Make up</h3>
                                        <!--                                        <p>Dramatically maintain clicks-and-mortar solutions without functional solutions. Completely synergize resource </p>
                                            --><!--                                         <a href="#" class="more-service"><i class="fa fa-plus"></i></a>
                                            -->
                                    </div>
                                </div>
                            </div>
                            <!--END OF Service item 2 -->
                            <!--Service item 3 -->
                            <div class="item">
                                <div class="service-items">
                                    <img class="img-circle service-slider-image" src="images/service-slider3.jpg" alt="">
                                    <div class="service-details">
                                        <h3>Reception Make up</h3>
                                                                        <p>Dramatically maintain clicks-and-mortar solutions without functional solutions. Completely synergize resource </p>
                                                                                <a href="#" class="more-service"><i class="fa fa-plus"></i></a>

                                    </div>
                                </div>
                            </div>
                            <!--END OF Service item 3 -->
                            <!--Service item 4 -->
                            <div class="item">
                                <div class="service-items">
                                    <img class="img-circle service-slider-image" src="images/service-slider1.jpg" alt="">
                                    <div class="service-details">
                                        <h3>Celebrity Make </h3>
                                                                           <p>Dramatically maintain clicks-and-mortar solutions without functional solutions. Completely synergize resource </p>
                                                                             <a href="#" class="more-service"> <i class="fa fa-plus"></i></a>

                                    </div>
                                </div>
                            </div>
                            <!--END OF Service item 4 -->
                            <!--Service item 5 -->
                            <div class="item">
                                <div class="service-items">
                                    <img class="img-circle service-slider-image" src="images/service-slider2.jpg" alt="">
                                    <div class="service-details">
                                        <h3>Fashion</h3>
                                                                       <p>Dramatically maintain clicks-and-mortar solutions without functional solutions. Completely synergize resource </p>
                                                                            <a href="#" class="more-service"> <i class="fa fa-plus"></i></a>

                                    </div>
                                </div>
                            </div>
                            <!--END OF Service item 5 -->
                            <!--Service item 6 -->
                            <div class="item">
                                <div class="service-items">
                                    <img class="img-circle service-slider-image" src="images/service-slider3.jpg" alt="">
                                    <div class="service-details">
                                        <h3>Hair Styles</h3>
                                                                       <p>Dramatically maintain clicks-and-mortar solutions without functional solutions. Completely synergize resource </p>
                                                                                <a href="#" class="more-service"> <i class="fa fa-plus"></i></a>

                                    </div>
                                </div>
                            </div>
                            <!--END OF Service item 6 -->
                        </div>
                    </div>
                    <!-- end of service slider -->
                </div>
            </div>
            <!-- end of service slider -->
        </section>


问:
Modifying parts of the integer-like string
For any k-digit integer i, the goal is to produce an m-digit string where the first n digits, where n=m-k are zeros, say. Using python would be helpful.

For example, given m=5 and i=324, how to produce "00324"?

EDIT:
The zfill function pads the integer with zeros. Is there any more general function that pads the integer with an arbitrary integer/character?

答:
You can use zfill

```<code>i = 324
m = 5
s = str(i).zfill(m)
# '00324'
</code>```

Body:
You can use zfill

i = 324
m = 5
s = str(i).zfill(m)
# '00324'


问:
When to use an object or an array in javascript?
I just found out that Arrays inherit directly from Object in javascript.  I'm finding the difference between an array and an object is fairly minuscule.

How do i know when to use one over the other?

答:
Objects keys are strings; array keys are integers. JavaScript objects are maps (String -> anything) and arrays are lists (ordered collections ofanything).

Does that help?


问:
AJAX on Load command for a Liquid code
I wanted to add a onClick function when I click on the link.
Basically, whenever I click on "Click" it should add the liquid code in the div.
What it is doing is, adding a liquid code yes, but just the code and not the content it should be adding with the liquid code. Here is my code:

Index

```<code>    <a href="#" id="myLink">Click me!</a>
    <div id="result"></div>

    <script src="http://code.jquery.com/jquery-latest.min.js"

type="text/javascript"></script>
    <script>
      $("#myLink").on("click", function(){
        $("#result").load("liquidcode.html");
      });
    </script>
</code>```

liquidcode.html

```<code>{% include 'cod-checker' %}
</code>```

What I get after clicking on "Click Me" is this {% include 'cod-checker' %}

答:
Answering here to expand my comment, since there was a request for actual code from the question author.

My comment, which is the basis of the anser:

I would suggest making an AJAX request on click then, to an endpoint
  from your server. Make that endpoint provide a parsed html version of
  your liquidcode.liquid (just assuming the filename here).

On client side, jQuery-aided AJAX looks like this:

$("#myLink").on("click", function() {
  $("#result").load("myAwesomeServerEndpoint", function() {
    console.log('BOOM, server-parsed HTML was successfully loaded inside #result');
  });
});```
</div>
</div>
</p>

<p>As for server side, I really have no clue what framework you are using. (Ruby on Rails?)</p>

<p>In an MVC fashion, you need to register a route called "myAwesomeServerEndpoint".
Assign a Controller to that route, say "myAwesomeServerController".
This Controller is not supposed to do much, it should just render your <code>liquicode.liquid</code> template.</p>

<p>Pseudocode for your controller (since I dont know Ruby on Rails):</p>

```return HtmlResponse(render("liquicode.liquid"));
```

Make sure that the response is sent as HTML and that the route is exposed to AJAX requests, and that should be it.

Again, this is not a solution but just a rough concenpt

Title: AJAX on Load command for a Liquid code

Body:
I wanted to add a onClick function when I click on the link.
Basically, whenever I click on "Click" it should add the liquid code in the div.
What it is doing is, adding a liquid code yes, but just the code and not the content it should be adding with the liquid code. Here is my code:

Index

    Click me!

liquidcode.html

{% include 'cod-checker' %}

What I get after clicking on "Click Me" is this {% include 'cod-checker' %}

Body:
Answering here to expand my comment, since there was a request for actual code from the question author.

My comment, which is the basis of the anser:

I would suggest making an AJAX request on click then, to an endpoint
  from your server. Make that endpoint provide a parsed html version of
  your liquidcode.liquid (just assuming the filename here).

On client side, jQuery-aided AJAX looks like this:

$("#myLink").on("click", function() {
  $("#result").load("myAwesomeServerEndpoint", function() {
    console.log('BOOM, server-parsed HTML was successfully loaded inside #result');
  });
});

As for server side, I really have no clue what framework you are using. (Ruby on Rails?)

In an MVC fashion, you need to register a route called "myAwesomeServerEndpoint".
Assign a Controller to that route, say "myAwesomeServerController".
This Controller is not supposed to do much, it should just render your liquicode.liquid template.

Pseudocode for your controller (since I dont know Ruby on Rails):

return HtmlResponse(render("liquicode.liquid"));

Make sure that the response is sent as HTML and that the route is exposed to AJAX requests, and that should be it.

Again, this is not a solution but just a rough concenpt


问:
get the substrings between {} in a string Scala
I have a string str=" {$a}/{$b}/{$c}/{$d}"

I want a function that returns list of strings which are in between { and }

so for fun(str) output should be List($a,$b,$c,$d)

I tried
 println("""\}.*\{""".r.split("{$a}/{$b}/{$c}/{$d}").toList)

but I got only List( {$a,$d})

答:
You can try to use Scala regex group capture for this, like:

```<code>"""\{(.*?)\}""".r.findAllIn("{$a}/{$b}/{$c}/{$d}").matchData.map(_.group(1)).toList
</code>```

Explanation:

?: for non-greedy capture

findAllIn: find all group pattern

_.group(1) for capture data

Body:
You can try to use Scala regex group capture for this, like:

"""\{(.*?)\}""".r.findAllIn("{$a}/{$b}/{$c}/{$d}").matchData.map(_.group(1)).toList

Explanation:

?: for non-greedy capture

findAllIn: find all group pattern

_.group(1) for capture data


问:
Problems navigating to Angular UI router state
I have a route definition as follows:

```<code>        $stateProvider
          .state('vehicles', {
            url: '/vehicles',
            templateUrl: 'foo/bar1.html'
        }).state('vehicles.id', {
            url: '/{id}',
            templateUrl: 'foo/bar3.html'
        }).state('vehicles.create', {
            url: '/create',
            templateUrl: 'foo/bar2.html',
            controller: 'VehicleCreateController'
        });
</code>```

I have a button that does

```<code>$state.go("vehicles.create");
</code>```

The problem is, that while the URL changes correctly, the page remains the same. Only after the second click, the correct template appears.

答:
use : for your params and ? to make those params optional if you need.

check the below code snippet, for routing with params.

```<code>$stateProvider
.state('contacts.detail', {
    url: "/contacts/:contactId",
    templateUrl: 'contacts.detail.html',
    controller: function ($stateParams) {
        // If we got here from a url of /contacts/42
        expect($stateParams).toBe({contactId: "42"});
    }
})
</code>```

check this for more clear view on routing.

Body:
I have a route definition as follows:

        $stateProvider
          .state('vehicles', {
            url: '/vehicles',
            templateUrl: 'foo/bar1.html'
        }).state('vehicles.id', {
            url: '/{id}',
            templateUrl: 'foo/bar3.html'
        }).state('vehicles.create', {
            url: '/create',
            templateUrl: 'foo/bar2.html',
            controller: 'VehicleCreateController'
        });

I have a button that does

$state.go("vehicles.create");

The problem is, that while the URL changes correctly, the page remains the same. Only after the second click, the correct template appears.

Body:
use : for your params and ? to make those params optional if you need.

check the below code snippet, for routing with params.

$stateProvider
.state('contacts.detail', {
    url: "/contacts/:contactId",
    templateUrl: 'contacts.detail.html',
    controller: function ($stateParams) {
        // If we got here from a url of /contacts/42
        expect($stateParams).toBe({contactId: "42"});
    }
})

check this for more clear view on routing.


问:
remove() does not work
I am trying to make a 'detect typing'-function for a chat program.

Everything works regarding detection of when a user is typing or sending a message, but $("#"+data.person+"").remove(); does not work.

The console is printing "is typing function stopped - remove", so it should work.

Any suggestions to what I am missing? Also, please let me know if I should add more code. I am just assuming that this is enough to get an idea of what is going on.

Client-side

var myUserName;
var myUserPassword;
var myUserID;
var currentConversation;
var conversationInvite;

$(document).ready(function() {
 var socket = io.connect("localhost:3000");
    var typing = false;
    var timeout = undefined;

    function timeoutFunction() {
            typing = false;
            socket.emit("typing", false, currentConversation);
          }

$(document).on('pageshow', '#chat', function(e,data){
    $('.chatContent').height(getRealContentHeight());
});

function getRealContentHeight() {
 var header = $.mobile.activePage.find("div[data-role='header']:visible");
 var footer = $.mobile.activePage.find("div[data-role='footer']:visible");
 var content = $.mobile.activePage.find("div[data-role='content']:visible:visible");
 var viewport_height = $(window).height();

 var content_height = viewport_height - header.outerHeight() - footer.outerHeight();
 if((content.outerHeight() - header.outerHeight() - footer.outerHeight()) <= viewport_height) {
  content_height -= (content.outerHeight() - content.height());
 }
 return content_height;
}

//-----Chat
 // Sending the message
        $("#msg").keypress(function(e){
          var msg = $("#msg").val();
          if (e.which === 13) {
            if (msg.trim() == "") {
              return;
            } else {
                var timeInMs = Date.now();

                function fulldate(date) {
                  var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                  'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
                  return months[date.getUTCMonth()] + ' ' + date.getUTCDate() + ', ' + date.getUTCFullYear();
                }

                var message = {
                 message_id: currentConversation,
                 message_sender: myUserName,
                   message_body: msg,
                   time: timeInMs,
                   date: fulldate(new Date(timeInMs))
                };
                socket.emit("send message", message, currentConversation);
                $("#msg").val("");
                $("#msg").focus();

                clearTimeout(timeout);
                timeoutFunction();
            }
          } else if (e.which !== 13) {
                if (typing === false && $("#msg").is(":focus")) {
                    typing = true;
                    socket.emit("typing", true, currentConversation, myUserName);
                    clearTimeout(timeout);
                    timeout = setTimeout(timeoutFunction, 3000);
                } else {
                    console.log("Timeout function started");
                    //clearTimeout(timeout);
                    timeoutFunction();
                }
            }
        });

        socket.on("isTyping", function(data) {
            if (data.isTyping) {
              if ($("#"+data.person+"").length === 0) {
                $(".chatContent").append("
" + data.person + " is typing...
");
                timeout = setTimeout(timeoutFunction, 5000);
                console.log(data.person);
              }
            } else {
             console.log(data.person);
               $("#"+ data.person +"").remove();
               console.log("is typing function stopped - remove");
              }
          });

});```
</div>
</div>
</p>

<p><strong>Server-side</strong></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> // Detect typing
    socket.on("typing", function(data, currentConversation, myUserName) {
        socket.broadcast.to(currentConversation).emit("isTyping", {isTyping: data, person: myUserName});
        console.log("Someone is typing");
    });</code>```

答:
The else clause is executed as a result of the timeout function.  What is the result of adding console.log(currentConversation) to the timeout function? Are you certain that, when the timeout function is being called that the html element already exists? To test for that, you could do the following, assuming data.person is correctly populated. </p>

```<code>if($("#"+data.person).length){ console.log(data.person+" html id exists."); }
else {console.log(data.person+" html element does not exist.");}
</code>```

<p>Inserting your logic in the first clause would successfully execute the remove statement where it's not needed in the second because the element no longer exists. </p>

Title: remove() does not work

Body:
I am trying to make a 'detect typing'-function for a chat program.

Everything works regarding detection of when a user is typing or sending a message, but $("#"+data.person+"").remove(); does not work.

The console is printing "is typing function stopped - remove", so it should work.

Any suggestions to what I am missing? Also, please let me know if I should add more code. I am just assuming that this is enough to get an idea of what is going on.

Client-side

var myUserName;
var myUserPassword;
var myUserID;
var currentConversation;
var conversationInvite;

$(document).ready(function() {
 var socket = io.connect("localhost:3000");
    var typing = false;
    var timeout = undefined;

    function timeoutFunction() {
            typing = false;
            socket.emit("typing", false, currentConversation);
          }

$(document).on('pageshow', '#chat', function(e,data){
    $('.chatContent').height(getRealContentHeight());
});

function getRealContentHeight() {
 var header = $.mobile.activePage.find("div[data-role='header']:visible");
 var footer = $.mobile.activePage.find("div[data-role='footer']:visible");
 var content = $.mobile.activePage.find("div[data-role='content']:visible:visible");
 var viewport_height = $(window).height();

 var content_height = viewport_height - header.outerHeight() - footer.outerHeight();
 if((content.outerHeight() - header.outerHeight() - footer.outerHeight()) <= viewport_height) {
  content_height -= (content.outerHeight() - content.height());
 }
 return content_height;
}

//-----Chat
 // Sending the message
        $("#msg").keypress(function(e){
          var msg = $("#msg").val();
          if (e.which === 13) {
            if (msg.trim() == "") {
              return;
            } else {
                var timeInMs = Date.now();

                function fulldate(date) {
                  var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                  'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
                  return months[date.getUTCMonth()] + ' ' + date.getUTCDate() + ', ' + date.getUTCFullYear();
                }

                var message = {
                 message_id: currentConversation,
                 message_sender: myUserName,
                   message_body: msg,
                   time: timeInMs,
                   date: fulldate(new Date(timeInMs))
                };
                socket.emit("send message", message, currentConversation);
                $("#msg").val("");
                $("#msg").focus();

                clearTimeout(timeout);
                timeoutFunction();
            }
          } else if (e.which !== 13) {
                if (typing === false && $("#msg").is(":focus")) {
                    typing = true;
                    socket.emit("typing", true, currentConversation, myUserName);
                    clearTimeout(timeout);
                    timeout = setTimeout(timeoutFunction, 3000);
                } else {
                    console.log("Timeout function started");
                    //clearTimeout(timeout);
                    timeoutFunction();
                }
            }
        });

        socket.on("isTyping", function(data) {
            if (data.isTyping) {
              if ($("#"+data.person+"").length === 0) {
                $(".chatContent").append("
" + data.person + " is typing...
");
                timeout = setTimeout(timeoutFunction, 5000);
                console.log(data.person);
              }
            } else {
             console.log(data.person);
               $("#"+ data.person +"").remove();
               console.log("is typing function stopped - remove");
              }
          });

});

Server-side

 // Detect typing
    socket.on("typing", function(data, currentConversation, myUserName) {
        socket.broadcast.to(currentConversation).emit("isTyping", {isTyping: data, person: myUserName});
        console.log("Someone is typing");
    });

Body:
The else clause is executed as a result of the timeout function.  What is the result of adding console.log(currentConversation) to the timeout function? Are you certain that, when the timeout function is being called that the html element already exists? To test for that, you could do the following, assuming data.person is correctly populated.

if($("#"+data.person).length){ console.log(data.person+" html id exists."); }
else {console.log(data.person+" html element does not exist.");}

Inserting your logic in the first clause would successfully execute the remove statement where it's not needed in the second because the element no longer exists.


问:
Mailboxer: creating link to new conversation on a product page
I am working on a marketplace.
I have a page with all the products.

I want to create a link on each of this product, to allow user to send message to the seller, creating a new conversation.

I am thinking about creating a link with that:

```<code><%= link_to "Contactar", new_conversation_path %>
</code>```

But can i put in this link the recipient directly ?

If yes, what should i change in the conversation_controller ?

```<code>def new
  recipients = Product.where(user: params[:user_id])
end

def create
  receipt = current_user.send_message(recipient, params[:body], params[:subject])
  redirect_to conversation_path(receipt.conversation)
end
</code>```

答:
But can i put in this link the recipient directly ?

Yes! You can pass the individual recipient id directly in the link like below

```<code><%= link_to "Contactar", new_conversation_path(recipient_id: @your_recipient.id %>
</code>```

And access the recipient's id with params[:recipient_id] in the new method.

Body:
I am working on a marketplace.
I have a page with all the products.

I want to create a link on each of this product, to allow user to send message to the seller, creating a new conversation.

I am thinking about creating a link with that:

<%= link_to "Contactar", new_conversation_path %>

But can i put in this link the recipient directly ?

If yes, what should i change in the conversation_controller ?

def new
  recipients = Product.where(user: params[:user_id])
end

def create
  receipt = current_user.send_message(recipient, params[:body], params[:subject])
  redirect_to conversation_path(receipt.conversation)
end

Body:
But can i put in this link the recipient directly ?

Yes! You can pass the individual recipient id directly in the link like below

<%= link_to "Contactar", new_conversation_path(recipient_id: @your_recipient.id %>

And access the recipient's id with params[:recipient_id] in the new method.


问:
C# How to use Directory White Spaces into process.arguements?
The program created utilizes a 3rd party tool to generate a log file.

However the arguments provided for the the tool requires various files from Directory locations as part of generating the logs. Therefore the main argument of @"-r C:\test\ftk\ntuser.dat -d C:\System Volume Information\" + restoreFolder.Name + " -p runmru"; would be used to generate the logs.

May someone advise on how to make the arguments of "C:\System Volume Information\" be processed by the system with the white spaces in placed? Thanks!

The codes:

```<code>            Process process = new Process();
            process.StartInfo.FileName = @"C:\test\ftk\ripxp\ripxp.exe";
            process.StartInfo.Arguments = @"-r C:\test\ftk\ntuser.dat -d C:\System Volume Information\" + restoreFolder.Name + " -p runmru";
            process.StartInfo.CreateNoWindow = false;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardError = true;
            process.Start();
</code>```

答:
If I correctly understood the question, you can wrap the name with quotes:</p>

```<code>"... \"C:\System Volume Information\" + restoreFolder.Name + "\"..."
</code>```

Body:
The program created utilizes a 3rd party tool to generate a log file.

However the arguments provided for the the tool requires various files from Directory locations as part of generating the logs. Therefore the main argument of @"-r C:\test\ftk\ntuser.dat -d C:\System Volume Information\" + restoreFolder.Name + " -p runmru"; would be used to generate the logs.

May someone advise on how to make the arguments of "C:\System Volume Information\" be processed by the system with the white spaces in placed? Thanks!

The codes:

            Process process = new Process();
            process.StartInfo.FileName = @"C:\test\ftk\ripxp\ripxp.exe";
            process.StartInfo.Arguments = @"-r C:\test\ftk\ntuser.dat -d C:\System Volume Information\" + restoreFolder.Name + " -p runmru";
            process.StartInfo.CreateNoWindow = false;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardError = true;
            process.Start();

Body:
If I correctly understood the question, you can wrap the name with quotes:

"... \"C:\System Volume Information\" + restoreFolder.Name + "\"..."


答:
Here is one method:

```<code>select (date_trunc('minute', ts) +
        (case when extract(second from ts) > 30 then 30 else 0 end) * interval '1 second'
       ) as rounded_ts
</code>```

Note:  This rounds 30 second downward.

Title: Postgresql round timestamp to nearest 30 seconds

Body:
is possible in postgres to round timestamp to nearest 30 seconds?
For example:

source -> result

2017-06-07 14:11:20 -> 2017-06-07 14:11:00
2017-06-07 14:11:40 -> 2017-06-07 14:11:30
2017-06-07 14:12:10 -> 2017-06-07 14:12:00

Body:
Here is one method:

select (date_trunc('minute', ts) +
        (case when extract(second from ts) > 30 then 30 else 0 end) * interval '1 second'
       ) as rounded_ts

Note:  This rounds 30 second downward.