问:
How to validate only 1 array[] is required from 10 fields in CodeIgniter Form validation

I have a 1 Add User form that can add multiple user up to 10.

Now I need to validate only 1 field are required in form_validation rules. But, for sure what I need now is not a fixed field to validated. So, I can submit the data on the randomize field inside the form. (10 fields available, and only need 1 required field but once again not a fixed field because I was tried fixed field and really bothering me).

```<code><form action="x" method="post" class="form-horizontal">
<?php for ($i=1; $i<=10; $i++) { ?>
   <div class="form-group">
      <label class="control-label col-sm-3">Username <?php echo $i; ?></label>
      <div class="col-sm-9">
         <input type="text" class="form-control" name="user[]">
      </div>
   </div>
<?php } ?>
</code>```

Validation rules inside controller's function

```<code>if ( ! empty($this->input->post('user', TRUE)))
{
    $this->form_validation->set_rules('user[]', 'User', 'trim|alpha_numeric|min_length[2]');
}
</code>```

I'm trying to add required into user[] validation rules, its not working because all user[] fields become required.

Then im trying to add $this->form_validation->set_rules('user[0]', 'User', 'trim|required|alpha_numeric|min_length[2]'); into the form validation rules, so the code is look like this.

```<code>if ( ! empty($this->input->post('user', TRUE)))
{
    $this->form_validation->set_rules('user[0]', 'User', 'trim|required|alpha_numeric|min_length[2]');
    $this->form_validation->set_rules('user[]', 'User', 'trim|alpha_numeric|min_length[2]');
}
</code>```

It was successfully validated for one field are required that is Username 1 field on array 0.
 But sometimes it really bothering me to input only 1 new user only on Username 1.

Because sometimes I felt really easy to input on Username 4 or Username 9 because the cursor is near there.

Is there any way to validate this user[] fields for only required on 1 field no matter which fields is there. Like Username 3 maybe on Username 7.

答:
Short answer, no.

Looking at the main execute function in the form validation library you will see that determines if the $_POST field is an array, and if so, runs the validation function on each item of the array separately. You can confirm this by writing your own validation function and echoing something at the top of the function. It will run one iteration per item.

With that being said you could make a rule like this in libraries/MY_Form_validation.php:

```<code>public function required_array($unused, $config) {
    $config = explode(',', $config);
    $items = $_POST[$config[0]];
    $i = 0;
    foreach ($items as $item) {
        if (!empty($item)) {
            $i++;
        }
    }
    //echo 'num items: ' . $i;
    $req = isset($config[1]) ? $config[1] : 1;
    if ($i < $req) {
        $this->set_message('required_array', 'Atleast ' . $req . ' {field} must be filled in.');
        return false;
    } else {
        return true;
    }
}
</code>```

use like: $this->form_validation->set_rules('user[]', 'User', 'required_array[user, 3]');

However not only is this a hack, this will never be reached if there are no items in the array as CI has a special way of dealing with requires that we can't/shouldn't modify to add our function as it is a system file and that is bad practice.

Here is the section of code from validation that prevents the solution from working:

```<code>    if (
        ($postdata === NULL OR $postdata === '')
        && $callback === FALSE
        && $callable === FALSE
        && ! in_array($rule, array('required', 'isset', 'matches'), TRUE)
    )
    {
        continue;
    }
</code>```

So your best bet is to check to see if one is filled in outside of CI validation.

Body:
I have a 1 Add User form that can add multiple user up to 10.

Now I need to validate only 1 field are required in form_validation rules. But, for sure what I need now is not a fixed field to validated. So, I can submit the data on the randomize field inside the form. (10 fields available, and only need 1 required field but once again not a fixed field because I was tried fixed field and really bothering me).

<form action="x" method="post" class="form-horizontal">
<?php for ($i=1; $i<=10; $i++) { ?>

      Username <?php echo $i; ?>

         <input type="text" class="form-control" name="user[]">

<?php } ?>

Validation rules inside controller's function

if ( ! empty($this->input->post('user', TRUE)))
{
    $this->form_validation->set_rules('user[]', 'User', 'trim|alpha_numeric|min_length[2]');
}

I'm trying to add required into user[] validation rules, its not working because all user[] fields become required.

Then im trying to add $this->form_validation->set_rules('user[0]', 'User', 'trim|required|alpha_numeric|min_length[2]'); into the form validation rules, so the code is look like this.

if ( ! empty($this->input->post('user', TRUE)))
{
    $this->form_validation->set_rules('user[0]', 'User', 'trim|required|alpha_numeric|min_length[2]');
    $this->form_validation->set_rules('user[]', 'User', 'trim|alpha_numeric|min_length[2]');
}

It was successfully validated for one field are required that is Username 1 field on array 0.
 But sometimes it really bothering me to input only 1 new user only on Username 1.

Because sometimes I felt really easy to input on Username 4 or Username 9 because the cursor is near there.

Is there any way to validate this user[] fields for only required on 1 field no matter which fields is there. Like Username 3 maybe on Username 7.

Body:
Short answer, no.

Looking at the main execute function in the form validation library you will see that determines if the $_POST field is an array, and if so, runs the validation function on each item of the array separately. You can confirm this by writing your own validation function and echoing something at the top of the function. It will run one iteration per item.

With that being said you could make a rule like this in libraries/MY_Form_validation.php:

public function required_array($unused, $config) {
    $config = explode(',', $config);
    $items = $_POST[$config[0]];
    $i = 0;
    foreach ($items as $item) {
        if (!empty($item)) {
            $i++;
        }
    }
    //echo 'num items: ' . $i;
    $req = isset($config[1]) ? $config[1] : 1;
    if ($i < $req) {
        $this->set_message('required_array', 'Atleast ' . $req . ' {field} must be filled in.');
        return false;
    } else {
        return true;
    }
}

use like: $this->form_validation->set_rules('user[]', 'User', 'required_array[user, 3]');

However not only is this a hack, this will never be reached if there are no items in the array as CI has a special way of dealing with requires that we can't/shouldn't modify to add our function as it is a system file and that is bad practice.

Here is the section of code from validation that prevents the solution from working:

    if (
        ($postdata === NULL OR $postdata === '')
        && $callback === FALSE
        && $callable === FALSE
        && ! in_array($rule, array('required', 'isset', 'matches'), TRUE)
    )
    {
        continue;
    }

So your best bet is to check to see if one is filled in outside of CI validation.


来源: stackexchange

问:
Shell script to count no of character,word,line in a file
```<code>#!/bin/bash

clear
character=0
word=0
line=`echo -e "\n"`
space=`echo -e " "`

if [ $# -eq 0 ]
then
    echo "You haven't entered any line"
elif [ $# -eq 1 ]
then
    filename=$1
    while read -n1 newline
    do
        if [ '$newline' == '$line' ]
        then
            ((line++))
        elif [ '$newline' == '$space' ]
        then
            ((word++))
        else
            ((character++))
        fi
    done < $filename
    echo "No of line =$line"
    echo "No of word =$word"
    echo "No of character =$character"
fi
</code>```

答:
```<code>#!/bin/bash

WC=$(cat $1 | wc -mlw)

echo "No of line =$(echo $WC | awk '{print $1}')"
echo "No of word =$(echo $WC | awk '{print $2}')"
echo "No of character =$(echo $WC | awk '{print $3}')"
</code>```

ContentLicense: CC BY-SA 3.0


问:
How to write date / timestamp string to Date timestamp column in Oracle DB?
I have stored some Oracle tables in Hadoop using AVRO file format and Hive external tables to access the data.

I have stored Date and Timestamp values as a formatted String, using the TO_CHAR function from Oracle on the import.

Now I want to export this exact data back with Spark to an Oracle table having a Date column. I use the command:

```<code>// Create a data frame from the Hive table
val data = sqlContext.sql("select * from avro_table")

// export df to existing oracle table
data.write.mode("overwrite").jdbc(jdbcString, "tableName", prop)
</code>```

But then i get the error:

ORA-00902: invalid data type

This is because it tries to insert a string into a date column. Is there a safe way to insert a date / timestamp string from a Spark dataframe to an Oracle date / timestamp column? With safe i mean do not lose any timezone information.

答:
You should use to_date, to_timestamp and/or date_format functions to do the transformation from stringified date/timestamp values to their corresponding type-aware ones.

date_format(dateExpr: Column, format: String): Column Converts a date/timestamp/string to a value of string in the format specified by the date format given by the second argument.

to_date(e: Column, fmt: String): Column Converts the column into a DateType with a specified format (see http://docs.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html) return null if fail.

to_timestamp(s: Column, fmt: String): Column Convert time string to a Unix timestamp (in seconds) with a specified format (see http://docs.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html) to Unix timestamp (in seconds), return null if fail.

Use select or withColumn operators.

A sample code could be as follows:

```<code>data.withColumn("real_date", date_format(...))
  .write
  .mode("overwrite")
  .jdbc(jdbcString, "tableName", prop)
</code>```

Body:
I have stored some Oracle tables in Hadoop using AVRO file format and Hive external tables to access the data.

I have stored Date and Timestamp values as a formatted String, using the TO_CHAR function from Oracle on the import.

Now I want to export this exact data back with Spark to an Oracle table having a Date column. I use the command:

// Create a data frame from the Hive table
val data = sqlContext.sql("select * from avro_table")

// export df to existing oracle table
data.write.mode("overwrite").jdbc(jdbcString, "tableName", prop)

But then i get the error:

ORA-00902: invalid data type

This is because it tries to insert a string into a date column. Is there a safe way to insert a date / timestamp string from a Spark dataframe to an Oracle date / timestamp column? With safe i mean do not lose any timezone information.

Body:
You should use to_date, to_timestamp and/or date_format functions to do the transformation from stringified date/timestamp values to their corresponding type-aware ones.

date_format(dateExpr: Column, format: String): Column Converts a date/timestamp/string to a value of string in the format specified by the date format given by the second argument.

to_date(e: Column, fmt: String): Column Converts the column into a DateType with a specified format (see http://docs.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html) return null if fail.

to_timestamp(s: Column, fmt: String): Column Convert time string to a Unix timestamp (in seconds) with a specified format (see http://docs.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html) to Unix timestamp (in seconds), return null if fail.

Use select or withColumn operators.

A sample code could be as follows:

data.withColumn("real_date", date_format(...))
  .write
  .mode("overwrite")
  .jdbc(jdbcString, "tableName", prop)


问:
Changes to variable handling in PHP
I am unable to understand variable Parsing.

I have gone through this link uniform_variable_syntax but this link is so hard me for understand.

```<code>class Test{

    public $var=array('baz'=>'a');

    function a(){

        return 'amazing_class<br/>';
    }
}

 function a(){

    return 'amazing_out_of_class<br/>';
}

$obj=new Test();

$bar='var';
echo "1. ".$obj->$bar['baz']();  //Output amazing_out_of_class

$bar=array('baz'=>'a');
echo "2. ".$obj->{$bar['baz']}(); //Output amazing_class
</code>```

Now lets look at first case : $obj->$bar['baz']()

($obj->$bar)['baz']()  >>>   ($obj->var['baz'])() >>> a() >>> amazing_out_of_class

Now i also suppose it $obj->{$bar['baz']}() parsed same as above and expected Notice error : undefined Property a

$obj->{$bar['baz']}()  >>>   ($obj->a)() >>> ($obj->a) is Notice error : undefined Property a

Notice error : undefined Property a  is my assumption according to first case but its output amazing_class

答:
Its pretty simple

```<code>$bar='var';
echo "1. ".$obj->$bar['baz']();  //Output amazing_out_of_class
</code>```

For example $obj->$bar'baz' evaluates as bellow

```<code>$obj->$bar['baz']() -> $obj->$var['baz']() -> {$obj->a} () -> a()
</code>```

Second One also evaluates as a

```<code>$obj->{$bar['baz']}() -> $obj->{a}() ( $bar['baz'] as a)
</code>```

Reference :http://php.net/manual/en/language.variables.php
           php.net/manual/en/language.types.string.php

Please add, if anything is missing

```<code>$bar=array('baz'=>'a');
echo "2. ".$obj->{$bar['baz']}();
</code>```

Title: Changes to variable handling in PHP

Body:
I am unable to understand variable Parsing.

I have gone through this link uniform_variable_syntax but this link is so hard me for understand.

class Test{

    public $var=array('baz'=>'a');

    function a(){

        return 'amazing_class
';
    }
}

 function a(){

    return 'amazing_out_of_class
';
}

$obj=new Test();

$bar='var';
echo "1. ".$obj->$bar['baz']();  //Output amazing_out_of_class

$bar=array('baz'=>'a');
echo "2. ".$obj->{$bar['baz']}(); //Output amazing_class

Now lets look at first case : $obj->$bar['baz']()

($obj->$bar)['baz']()  >>>   ($obj->var['baz'])() >>> a() >>> amazing_out_of_class

Now i also suppose it $obj->{$bar['baz']}() parsed same as above and expected Notice error : undefined Property a

$obj->{$bar['baz']}()  >>>   ($obj->a)() >>> ($obj->a) is Notice error : undefined Property a

Notice error : undefined Property a  is my assumption according to first case but its output amazing_class

Body:
Its pretty simple

$bar='var';
echo "1. ".$obj->$bar['baz']();  //Output amazing_out_of_class

For example $obj->$bar'baz' evaluates as bellow

$obj->$bar['baz']() -> $obj->$var['baz']() -> {$obj->a} () -> a()

Second One also evaluates as a

$obj->{$bar['baz']}() -> $obj->{a}() ( $bar['baz'] as a)

Reference :http://php.net/manual/en/language.variables.php
           php.net/manual/en/language.types.string.php

Please add, if anything is missing

$bar=array('baz'=>'a');
echo "2. ".$obj->{$bar['baz']}();


问:
unable to insert data into database from html
I am trying to  insert  data from a html file into my database "customers"

I am however able to connect to database but unable to insert data from a html file to my database

screenshot of error

Notes:

I have not set password for phpmyadmin just the username as "root"

all files are stored in same folder (C:\wamp64\www)

customers.html

```<code><!DOCTYPE html>
<html>
<head>
        <title>customers</title>
</head>
<body>

  <center><form action="SignUp.php" method="POST">
        <input type="text" name="id" placeholder="customer id"><br>
        <input type="text" name="firstname" placeholder="firstname"><br>
        <input type="text" name="orderno" placeholder="order no"> <br>
        <input type="text" name="city" placeholder="city"><br>
        <input type="text" name="price" placeholder="product price"><br>
        <button type="submit">order</button>
     </form>
</center>
</body>
</html>
</code>```

SignUp.php

```<code><?php

include 'db.php';

$sql= "INSERT INTO customers (id,firstname,orderno,city,price)
VALUES ('345','username','979','city','4465')";

 if($result=mysql_query($sql)==true)
        echo "data inserted successfully";
 else
        echo "failed to insert data";
?>
</code>```

db.php

```<code><?php

$conn=mysqli_connect("localhost","root","","customers");
if(!$conn){
        die("connection failed : " .mysqli_connect_error());
}
else{
        echo "connection created successfully"."<br>";
}

?>
</code>```

答:
I don't know if this is your issue but, Instead of customers.html you should make it customers.php, make your life a little easier, and also

This statement

```<code><?php

include 'db.php';

$sql= "INSERT INTO customers (id,firstname,orderno,city,price)
VALUES ('345','username','979','city','4465')";

 if($result=mysql_query($sql)==true)
        echo "data inserted successfully";
 else
        echo "failed to insert data";
?>
</code>```

should be

```<code><?php

include 'db.php';

$sql= "INSERT INTO customers (id, firstname, orderno, city, price)
VALUES ('345','username','979','city','4465')";

 if($result=mysql_query($sql)==true) {
        echo "data inserted successfully";
 } else {
        echo "failed to insert data";
 }
?>
</code>```

You did not include the brackets in your if/else code.

If you're going to be using mysqli to connect to the db you might as well transform your SignUp.php to

```<code><?php
$sql = "INSERT INTO MyGuests (id, firstname, orderno, city, price)
VALUES ('345', 'username', '979', 'city', '4465')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>
</code>```

Also you might wanna take a look at this

As well as this

Body:
I am trying to  insert  data from a html file into my database "customers"

I am however able to connect to database but unable to insert data from a html file to my database

screenshot of error

Notes:

I have not set password for phpmyadmin just the username as "root"

all files are stored in same folder (C:\wamp64\www)

customers.html

<!DOCTYPE html>

        <title>customers</title>

  <form action="SignUp.php" method="POST">
        <input type="text" name="id" placeholder="customer id">

        <input type="text" name="firstname" placeholder="firstname">

        <input type="text" name="orderno" placeholder="order no">

        <input type="text" name="city" placeholder="city">

        <input type="text" name="price" placeholder="product price">

        <button type="submit">order</button>
     </form>

SignUp.php

<?php

include 'db.php';

$sql= "INSERT INTO customers (id,firstname,orderno,city,price)
VALUES ('345','username','979','city','4465')";

 if($result=mysql_query($sql)==true)
        echo "data inserted successfully";
 else
        echo "failed to insert data";
?>

db.php

<?php

$conn=mysqli_connect("localhost","root","","customers");
if(!$conn){
        die("connection failed : " .mysqli_connect_error());
}
else{
        echo "connection created successfully"."
";
}

?>

Body:
I don't know if this is your issue but, Instead of customers.html you should make it customers.php, make your life a little easier, and also

This statement

<?php

include 'db.php';

$sql= "INSERT INTO customers (id,firstname,orderno,city,price)
VALUES ('345','username','979','city','4465')";

 if($result=mysql_query($sql)==true)
        echo "data inserted successfully";
 else
        echo "failed to insert data";
?>

should be

<?php

include 'db.php';

$sql= "INSERT INTO customers (id, firstname, orderno, city, price)
VALUES ('345','username','979','city','4465')";

 if($result=mysql_query($sql)==true) {
        echo "data inserted successfully";
 } else {
        echo "failed to insert data";
 }
?>

You did not include the brackets in your if/else code.

If you're going to be using mysqli to connect to the db you might as well transform your SignUp.php to

<?php
$sql = "INSERT INTO MyGuests (id, firstname, orderno, city, price)
VALUES ('345', 'username', '979', 'city', '4465')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

Also you might wanna take a look at this

As well as this


问:
How to auto-refresh news feed
Hey guys, I just created a news feed and I was wondering if there was a way to auto-refresh the feed with javascript or php, sort of like facebook, without refreshing the whole page. Thanks in advance.</p>

答: You need to use a technology called AJAX to achieve this.  As your question is not very specific the answer can't be either I'm afraid, but the general idea is a javascript running in the browser polls the server every couple of minutes for data, and the server returns some (XML in true AJAX, JSON, a HTML fragment, etc). The script then processes the data and modifies the DOM based on the results of the processing.  </p>

ContentLicense: CC BY-SA 2.5

Title: How to auto-refresh news feed


问:
Auto update docker image if exist new version of images on DockerHub
I want to update and restart my application ( docker container ) when I push new version of this app to Docker Hub.

Can You tell any solution for auto update an image and restart them on server?

P.S I hear about kubernetes, but its very hard to understanding how use it

答:
There are lots of possibilities:

Write a poll service to look if a new version is uploaded and let it trigger a redeploy

if you have a private registry you might be able to add a trigger (notifications) to a new push. The trigger might trigger a new build.

if you let e.g. jenkins do the whole build it can also take care of the build and redeploy.

You can trigger ansible to do a redeploy based on a new version.

etc. etc.


问:
Change CSS of nth class in Jquery or Javascript
I am trying to change the text color of the 5th infobox (class) in my code below. The text color changes but for all the infoboxes.

//INFOBOX5
var json_data = {"headers":["Platform","Value1","value1","valueP1","valueP2"],"rows":[["platform2","xxx",404.07000000000005,1634,6364],["platform5","xxx",404.07000000000005,1634,6364],["platform1","xxx",352.8,1634,6364],["platform3","xxx",352.8,1634,6364],
["platform3","xxx",352.8,1634,6364],["platform4","xxx",352.8,1634,6364]]};

    var platform_data = json_data.rows;
    var platform1_element = document.getElementById("platform1");
    var platform5_element = document.getElementById("platform5");
    var platform6_element = document.getElementById("platform6");
    var platform2_element = document.getElementById("platform2");
    var platform3_element = document.getElementById("platform3");
    var platform4_element = document.getElementById("platform4");

    function onlyUnique(value, index, self) {
        return self.indexOf(value) === index;
    }
    function formatNumber (num) {
        return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
    }
    var platforms = [];
    for (var i in platform_data) {
        if (platform_data[i][0] != null){
            platforms[i] = platform_data[i][0].toLowerCase();
        }
    }

    var unique_platforms = platforms.filter( onlyUnique );

    var target_width = 100/(unique_platforms.length-2);
    var width_str=target_width+"%";

    platform1_element.classList.add("hidden");
    platform5_element.classList.add("hidden");
    platform6_element.classList.add("hidden");
    platform3_element.classList.add("hidden");
    platform2_element.classList.add("hidden");
    platform4_element.classList.add("hidden");

    var total_value1 = 0;
    var total_value2 = 0;
    var total_display_value1 = 0;
    var total_video_value1 = 0;
    var total_mixed_value1 = 0;
    var total_other_value1 = 0;
    var total_display_value2 = 0;
    var total_video_value2 = 0;
    var total_mixed_value2 = 0;
    var value2_numbers = [];

    for (var i in unique_platforms) {
        var platform_name = unique_platforms[i].toLowerCase();

        var display_value1_total = 0;
        var display_value2_total = 0;
        var video_value1_total = 0;
        var video_value2_total = 0;
        var mixed_value1_total = 0;
        var mixed_value2_total = 0;
        var other_value1_total = 0;

        for (var x in platform_data){
            if (platform_data[x][0] != null){
                    if(platform_data[x][0].toLowerCase() == platform_name){
                    switch(platform_data[x][1]) {
                        case "display":
                        // Red Dot
                        display_value1_total = display_value1_total + platform_data[x][2];
                        total_value1 = total_value1 + display_value1_total;
                        break;
                        case "video":
                        video_value1_total = video_value1_total + platform_data[x][2];
                        total_value1 = total_value1 + video_value1_total;
                        break;
                        case "mixed":
                        mixed_value1_total = mixed_value1_total + platform_data[x][2];
                        total_value1 = total_value1 + mixed_value1_total;
                        break;
                        case "Other":
                        other_value1_total = other_value1_total + platform_data[x][2];
                        total_value1 = total_value1 + other_value1_total;
                        break;
                        default:
                        doNothing = "";
                    }
                }
            }else {
                value2_numbers = platform_data[x];
            }
        }

        var platform_value1 = display_value1_total + video_value1_total + mixed_value1_total + other_value1_total;
        var generic_element = document.getElementById(platform_name);

        var element_value1_name = platform_name+"_value1";
        var fl_value1 = parseFloat(platform_value1).toFixed(0);
        var curr_flag = "€"+formatNumber(fl_value1);
        document.getElementById(element_value1_name).innerHTML = curr_flag;

        total_display_value1 = total_display_value1 + display_value1_total;
        total_video_value1 = total_video_value1 + video_value1_total;
        total_mixed_value1 = total_mixed_value1 + mixed_value1_total;
    }

    var total_value1_string = "
€" + formatNumber(Number(total_value1).toFixed(0)) + "
";
    //document.getElementById("total_value1").innerHTML = total_value1_string;

  if (value2_numbers.length == 0){
      value2_numbers = platform_data[0];
  }
  var fl_value2 = 0;
  var curr_flag_bud = '';
  var element_value2_name = '';

  for (var i in json_data.headers){
      switch(json_data.headers[i]) {
            case "valueP1":
                    element_value2_name = "platform1_value2";
                    fl_value2 = parseFloat(value2_numbers[i]).toFixed(0);
                    curr_flag_bud = "€"+formatNumber(fl_value2);
                    document.getElementById(element_value2_name).innerHTML = curr_flag_bud;
                    break;
        case "valueP2":
                    element_value2_name = "platform2_value2";
                    fl_value2 = parseFloat(value2_numbers[i]).toFixed(0);
                    curr_flag_bud = "€" +formatNumber(fl_value2);
                    document.getElementById(element_value2_name).innerHTML = curr_flag_bud;
                    break;
           case "valueP1":
                    element_value2_name = "platform1_value2";
                    fl_value2 = parseFloat(value2_numbers[i]).toFixed(0);
                    curr_flag_bud = "€" +formatNumber(fl_value2);
                    document.getElementById(element_value2_name).innerHTML = curr_flag_bud;
                    break;
                    default:
         }
    }

    var statBox = Array.from(document.querySelectorAll('.infobox'));

    var element_id;

    var parentBoxlist = Array.from(document.querySelectorAll('.parentbox'));

    var channel_value1_check = 0;
    var value1_channels = [];

 //   if (total_mixed_value1 > 0.0) {channel_value1_check = channel_value1_check + 1;value1_channels[0] = 'mixed';};
 //   if (total_video_value1 > 0.0) {channel_value1_check = channel_value1_check + 1;value1_channels[1] = 'video';};
 //   if (total_display_value1 > 0.0) {channel_value1_check = channel_value1_check + 1;value1_channels[2] = 'display';};

    statBox.forEach(function(box) {
        switch(unique_platforms.length) {
            case 1:
                    // 1 box
                    element_id = box.getAttribute('id');
                    if (unique_platforms.includes(element_id)){
                        box.classList.add('infobox1');
                        box.classList.remove('hidden');
                    }
                    break;
                    case 2:
                    // 2 box's
                    element_id = box.getAttribute('id');
                    if (unique_platforms.includes(element_id)){
                        box.classList.add('infobox2');
                        box.classList.remove('hidden');
                    }
                    break;
                    case 3:
                    // 3 box's
                     element_id = box.getAttribute('id');
                    if (unique_platforms.includes(element_id)){
                        box.classList.add('infobox3');
                        box.classList.remove('hidden');
                    }
                    break;
                    case 4:
                    // 4 box's
                     element_id = box.getAttribute('id');
                    if (unique_platforms.includes(element_id)){
                        box.classList.add('infobox4');
                        box.classList.remove('hidden');
                    }
                    break;
                    case 5:
                    // 5 box's
                    element_id = box.getAttribute('id');
                    if (unique_platforms.includes(element_id)){
                        box.classList.add('infobox5');
                        box.classList.remove('hidden');
                    }
                    break;
                    default:
                }
            });

$(".boxbox:nth-of-type(1)").css("color", "#fff");```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css?family=Roboto');

    body{
    color: #fff;
    font-family: Roboto;
    margin:0;
    overflow:hidden;
    }
    h1{
    font-size: 1.2vw;
    }
    h3{
    font-size: 1.1vw!important;
    font-weight: 100;
    margin: 0;
    padding: 5px;
    }
    .redSq{
    background-color: #ff000a;
    width: 117px;
    height: 241px;
    float:left;
    }
.row {
    display: table;
    width: 99.8%;
    height: 180px;
    color: #454545;
    background-color:#dee9f3;
    //border: solid 1px #454545;
    box-shadow: 1px 2px 4px rgba(0, 0, 0, .5);
    margin-bottom: 10px;
}
.row > .col-lg-6 {
    display: table-cell;
    vertical-align: middle;
}
.container {
  display: flex;
  flex-wrap: wrap;
}
.container > div {
  padding: 15px;
  margin: 5px;
  flex: 0 0 calc(100% - 20px);
  text-align: left;
}
td{
  padding: 2px 2px;
  text-align: center;
  margin: 6px 0;
  border: none;
}
table{
  width: 100%;
  background-color:#454545;
  font-weight:500;
  border-collapse: separate;
  border-spacing:0.3em 1.1em;
  color: #fff;
  border: 0;
}
p{
    font-size: 1.2vw;
}
    .boxes{
    padding-top: 40px;
    padding-left: 30px;
    padding-right: 5%;
    min-width: 200px;
    float:left;
    display: inline-block;
    }

    #line{
    border-bottom: solid 1px #CCC;
    margin-top: 0px;
    padding-top: 15px;
    }

    .infobox {
    float:left;
    margin: 0;
    box-shadow: 1px 2px 4px rgba(0, 0, 0, .5);
    color: #454545;
    }

    .infobox1 {
    float:left;
    min-height:150px;
    min-width: 100%;
    margin: 0;
    }

    .infobox2 {
    float:left;
    min-height:150px;
    min-width: 49%;
    margin: 0 0.5%;
    //padding: 18px 0;
    }

    .infobox3 {
    float:left;
    min-height:150px;
    min-width: 32.33%;
    margin: 0 0.5%;
    //padding: 18px 0;
    }

    .infobox4 {
    float:left;
    //min-height:150px;
    min-width: 23.9%;
    margin: 0 0.5%;
    //padding: 18px 0;
    }

    .infobox5 {
    float:left;
    min-height:150px;
    min-width: 32.33%;
    margin: 0 0.5% 0.7%;
    //padding: 18px 0;
    }

    div.leftBox{
    float:left;
    width:60%;
    margin: 15px 0 0 25px;
    font-size: 1.1vw;
    }
    div.rightBox{
    float:left;
    width: 60%;
    margin: 15px 0 0 25px;
    font-size: 1.1vw;
    }

    .infocontentheader {
    //text-align: center;
    line-height: 2.8;
    //color: #fff;
    vertical-align: middle;
    height: 100%;
    float:left;
    width:25%;
    }

    .infocontent{
    text-align: center;
    color: #fff;
    width: 50%;
    float: left;
    }

    div#platform1.infocontentheader{
    background-color: #3c5999;
    }

    div#platform1.infobox img{
        display: block;
        margin: 0 auto 0 auto;
    }

    p#sTitle {
         font-weight: 900;
         font-size: 1.5vw;
     }

     p#bTitle {
         //font-weight: 900;
         font-size: 1.2vw;
     }

     p#platform1_value1, p#platform5_value1, p#platform4_value1 ,p#platform3_value1,
     p#platform2_value1, p#twitter_value1 {
         font-weight: 900;
         font-size: 1.3em;
         margin: 10px 0 0 20px;
     }

     p#platform1_budget, p#platform5_budget, p#platform4_budget, p#platform3_budget,
     p#platform2_budget, p#twitter_budget{
        font-size: 1.2em;
        margin: 10px 0 0 20px;
     }

    div#twitter.infocontentheader{
    background-color: #1da1f2;
    }
    div#twitter.infobox img{
        display: block;
        margin: 0 auto 0 auto;
    }

    div#platform3.infocontentheader{
    background-color: #a15aa0;
    }

    div#display.parentbox{
    background-color: #b3b3b3;
    color: #fff;
    }

    div#video.parentbox{
    background-color: #999999;
    color: #fff;
    }

    div#mixed.parentbox{
    background-color: #c1c1c1;
    color: #fff;
    }

    #platform3 div.infocontentheader{
    color: #fff;
    }
    div#platform3.infobox img{

        display: block;
        margin: 0 auto 0 auto;
    }

    div#platform3_value.infocontent{
    color: #000;
    }

    div#platform5.infocontentheader{
    background-color: #ff0102;
    }
    div#platform5.infobox img{
    display: block;
    margin: 0 auto 0 auto;
    }
    div#platform4.infocontentheader{
        background-color: #cac9c2;
    }
    div#platform4.infobox img{
        display: block;
        margin: 10% auto 0 auto;
    }
  div#platform2.infobox{
    background-color: #fff;
    }
    div#platform2.infobox img{
    display: block;
    margin: 10% auto 0 auto;
    }

    .hidden{
    display:none;
    }

    #parent_div_1{
        width:50%;
        min-height: 150px;
        background-color: #757476;
        margin-right:0px;
        float:left;
    }
    #parent_div_2{
        width:50%;
        min-height: 150px;
        background-color: #8D8D8D;
        margin-right:0px;
        float:left;
    }
    .parentbox{
        width:33.33%;
        min-height: 150px;
        /*background-color: #8D8D8D;*/
        margin-right:0px;
        float:left;
    }
    .parentbox1{
        width:100%;
        min-height: 150px;
        margin-right:0px;
        float:left;
    }
    .parentbox2{
        width:50%;
        min-height: 150px;
        margin-right:0px;
        float:left;
    }
    .parentbox3{
        width:33.33%;
        min-height: 150px;
        margin-right:0px;
        float:left;
    }
    .child_div_1{
    margin-top: 50px;
    margin-left: 15%;
    margin-bottom: 0px;
    text-align: left;
    }
    .child_div_2{
    margin-left: 15%;
    margin-top: 10px;
    margin-bottom: 40px;
    text-align: left;
    }
     .child_budget{
    margin-top: 10px;
    margin-bottom: 40px;
    padding-left:15%;
    text-align: left;
    float: left;
    }
    .child_value1{
    margin-top: 10px;
    margin-bottom: 40px;
    padding-right: 15%;
    text-align: left;
    float:right;
    }
     .child_title{
    margin-top: 50px;
    margin-bottom: 0px;
    text-align: center;
    }
    .child_budget_number{
        padding-right: 20%;
    }
    .child_value1_number{
        padding-left: 20%;
    }

.boxbox {
    display: table;
    width: 99.8%;
    height: 160px;
    color: #454545;
    font-size:1.1vw;
}

.boxbox {
    float:left;
    display: table;
    width: 99.8%;
    height: 180px;
    color: #454545;
}
.boxbox > .col-lg-6 {
    display: table-cell;
    vertical-align: middle;
}</code>```

value1

value2

value1

value2

value1

value2

value1

value2

value1

value2

value1

value2

```

答: Use: element.eq(n); where n is the index value of the element</p>

Body:
I am trying to change the text color of the 5th infobox (class) in my code below. The text color changes but for all the infoboxes.

//INFOBOX5
var json_data = {"headers":["Platform","Value1","value1","valueP1","valueP2"],"rows":[["platform2","xxx",404.07000000000005,1634,6364],["platform5","xxx",404.07000000000005,1634,6364],["platform1","xxx",352.8,1634,6364],["platform3","xxx",352.8,1634,6364],
["platform3","xxx",352.8,1634,6364],["platform4","xxx",352.8,1634,6364]]};

    var platform_data = json_data.rows;
    var platform1_element = document.getElementById("platform1");
    var platform5_element = document.getElementById("platform5");
    var platform6_element = document.getElementById("platform6");
    var platform2_element = document.getElementById("platform2");
    var platform3_element = document.getElementById("platform3");
    var platform4_element = document.getElementById("platform4");

    function onlyUnique(value, index, self) {
        return self.indexOf(value) === index;
    }
    function formatNumber (num) {
        return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
    }
    var platforms = [];
    for (var i in platform_data) {
        if (platform_data[i][0] != null){
            platforms[i] = platform_data[i][0].toLowerCase();
        }
    }

    var unique_platforms = platforms.filter( onlyUnique );

    var target_width = 100/(unique_platforms.length-2);
    var width_str=target_width+"%";

    platform1_element.classList.add("hidden");
    platform5_element.classList.add("hidden");
    platform6_element.classList.add("hidden");
    platform3_element.classList.add("hidden");
    platform2_element.classList.add("hidden");
    platform4_element.classList.add("hidden");

    var total_value1 = 0;
    var total_value2 = 0;
    var total_display_value1 = 0;
    var total_video_value1 = 0;
    var total_mixed_value1 = 0;
    var total_other_value1 = 0;
    var total_display_value2 = 0;
    var total_video_value2 = 0;
    var total_mixed_value2 = 0;
    var value2_numbers = [];

    for (var i in unique_platforms) {
        var platform_name = unique_platforms[i].toLowerCase();

        var display_value1_total = 0;
        var display_value2_total = 0;
        var video_value1_total = 0;
        var video_value2_total = 0;
        var mixed_value1_total = 0;
        var mixed_value2_total = 0;
        var other_value1_total = 0;

        for (var x in platform_data){
            if (platform_data[x][0] != null){
                    if(platform_data[x][0].toLowerCase() == platform_name){
                    switch(platform_data[x][1]) {
                        case "display":
                        // Red Dot
                        display_value1_total = display_value1_total + platform_data[x][2];
                        total_value1 = total_value1 + display_value1_total;
                        break;
                        case "video":
                        video_value1_total = video_value1_total + platform_data[x][2];
                        total_value1 = total_value1 + video_value1_total;
                        break;
                        case "mixed":
                        mixed_value1_total = mixed_value1_total + platform_data[x][2];
                        total_value1 = total_value1 + mixed_value1_total;
                        break;
                        case "Other":
                        other_value1_total = other_value1_total + platform_data[x][2];
                        total_value1 = total_value1 + other_value1_total;
                        break;
                        default:
                        doNothing = "";
                    }
                }
            }else {
                value2_numbers = platform_data[x];
            }
        }

        var platform_value1 = display_value1_total + video_value1_total + mixed_value1_total + other_value1_total;
        var generic_element = document.getElementById(platform_name);

        var element_value1_name = platform_name+"_value1";
        var fl_value1 = parseFloat(platform_value1).toFixed(0);
        var curr_flag = "€"+formatNumber(fl_value1);
        document.getElementById(element_value1_name).innerHTML = curr_flag;

        total_display_value1 = total_display_value1 + display_value1_total;
        total_video_value1 = total_video_value1 + video_value1_total;
        total_mixed_value1 = total_mixed_value1 + mixed_value1_total;
    }

    var total_value1_string = "
€" + formatNumber(Number(total_value1).toFixed(0)) + "
";
    //document.getElementById("total_value1").innerHTML = total_value1_string;

  if (value2_numbers.length == 0){
      value2_numbers = platform_data[0];
  }
  var fl_value2 = 0;
  var curr_flag_bud = '';
  var element_value2_name = '';

  for (var i in json_data.headers){
      switch(json_data.headers[i]) {
            case "valueP1":
                    element_value2_name = "platform1_value2";
                    fl_value2 = parseFloat(value2_numbers[i]).toFixed(0);
                    curr_flag_bud = "€"+formatNumber(fl_value2);
                    document.getElementById(element_value2_name).innerHTML = curr_flag_bud;
                    break;
        case "valueP2":
                    element_value2_name = "platform2_value2";
                    fl_value2 = parseFloat(value2_numbers[i]).toFixed(0);
                    curr_flag_bud = "€" +formatNumber(fl_value2);
                    document.getElementById(element_value2_name).innerHTML = curr_flag_bud;
                    break;
           case "valueP1":
                    element_value2_name = "platform1_value2";
                    fl_value2 = parseFloat(value2_numbers[i]).toFixed(0);
                    curr_flag_bud = "€" +formatNumber(fl_value2);
                    document.getElementById(element_value2_name).innerHTML = curr_flag_bud;
                    break;
                    default:
         }
    }

    var statBox = Array.from(document.querySelectorAll('.infobox'));

    var element_id;

    var parentBoxlist = Array.from(document.querySelectorAll('.parentbox'));

    var channel_value1_check = 0;
    var value1_channels = [];

 //   if (total_mixed_value1 > 0.0) {channel_value1_check = channel_value1_check + 1;value1_channels[0] = 'mixed';};
 //   if (total_video_value1 > 0.0) {channel_value1_check = channel_value1_check + 1;value1_channels[1] = 'video';};
 //   if (total_display_value1 > 0.0) {channel_value1_check = channel_value1_check + 1;value1_channels[2] = 'display';};

    statBox.forEach(function(box) {
        switch(unique_platforms.length) {
            case 1:
                    // 1 box
                    element_id = box.getAttribute('id');
                    if (unique_platforms.includes(element_id)){
                        box.classList.add('infobox1');
                        box.classList.remove('hidden');
                    }
                    break;
                    case 2:
                    // 2 box's
                    element_id = box.getAttribute('id');
                    if (unique_platforms.includes(element_id)){
                        box.classList.add('infobox2');
                        box.classList.remove('hidden');
                    }
                    break;
                    case 3:
                    // 3 box's
                     element_id = box.getAttribute('id');
                    if (unique_platforms.includes(element_id)){
                        box.classList.add('infobox3');
                        box.classList.remove('hidden');
                    }
                    break;
                    case 4:
                    // 4 box's
                     element_id = box.getAttribute('id');
                    if (unique_platforms.includes(element_id)){
                        box.classList.add('infobox4');
                        box.classList.remove('hidden');
                    }
                    break;
                    case 5:
                    // 5 box's
                    element_id = box.getAttribute('id');
                    if (unique_platforms.includes(element_id)){
                        box.classList.add('infobox5');
                        box.classList.remove('hidden');
                    }
                    break;
                    default:
                }
            });

$(".boxbox:nth-of-type(1)").css("color", "#fff");

@import url('https://fonts.googleapis.com/css?family=Roboto');

    body{
    color: #fff;
    font-family: Roboto;
    margin:0;
    overflow:hidden;
    }
    h1{
    font-size: 1.2vw;
    }
    h3{
    font-size: 1.1vw!important;
    font-weight: 100;
    margin: 0;
    padding: 5px;
    }
    .redSq{
    background-color: #ff000a;
    width: 117px;
    height: 241px;
    float:left;
    }
.row {
    display: table;
    width: 99.8%;
    height: 180px;
    color: #454545;
    background-color:#dee9f3;
    //border: solid 1px #454545;
    box-shadow: 1px 2px 4px rgba(0, 0, 0, .5);
    margin-bottom: 10px;
}
.row > .col-lg-6 {
    display: table-cell;
    vertical-align: middle;
}
.container {
  display: flex;
  flex-wrap: wrap;
}
.container > div {
  padding: 15px;
  margin: 5px;
  flex: 0 0 calc(100% - 20px);
  text-align: left;
}
td{
  padding: 2px 2px;
  text-align: center;
  margin: 6px 0;
  border: none;
}
table{
  width: 100%;
  background-color:#454545;
  font-weight:500;
  border-collapse: separate;
  border-spacing:0.3em 1.1em;
  color: #fff;
  border: 0;
}
p{
    font-size: 1.2vw;
}
    .boxes{
    padding-top: 40px;
    padding-left: 30px;
    padding-right: 5%;
    min-width: 200px;
    float:left;
    display: inline-block;
    }

    #line{
    border-bottom: solid 1px #CCC;
    margin-top: 0px;
    padding-top: 15px;
    }

    .infobox {
    float:left;
    margin: 0;
    box-shadow: 1px 2px 4px rgba(0, 0, 0, .5);
    color: #454545;
    }

    .infobox1 {
    float:left;
    min-height:150px;
    min-width: 100%;
    margin: 0;
    }

    .infobox2 {
    float:left;
    min-height:150px;
    min-width: 49%;
    margin: 0 0.5%;
    //padding: 18px 0;
    }

    .infobox3 {
    float:left;
    min-height:150px;
    min-width: 32.33%;
    margin: 0 0.5%;
    //padding: 18px 0;
    }

    .infobox4 {
    float:left;
    //min-height:150px;
    min-width: 23.9%;
    margin: 0 0.5%;
    //padding: 18px 0;
    }

    .infobox5 {
    float:left;
    min-height:150px;
    min-width: 32.33%;
    margin: 0 0.5% 0.7%;
    //padding: 18px 0;
    }

    div.leftBox{
    float:left;
    width:60%;
    margin: 15px 0 0 25px;
    font-size: 1.1vw;
    }
    div.rightBox{
    float:left;
    width: 60%;
    margin: 15px 0 0 25px;
    font-size: 1.1vw;
    }

    .infocontentheader {
    //text-align: center;
    line-height: 2.8;
    //color: #fff;
    vertical-align: middle;
    height: 100%;
    float:left;
    width:25%;
    }

    .infocontent{
    text-align: center;
    color: #fff;
    width: 50%;
    float: left;
    }

    div#platform1.infocontentheader{
    background-color: #3c5999;
    }

    div#platform1.infobox img{
        display: block;
        margin: 0 auto 0 auto;
    }

    p#sTitle {
         font-weight: 900;
         font-size: 1.5vw;
     }

     p#bTitle {
         //font-weight: 900;
         font-size: 1.2vw;
     }

     p#platform1_value1, p#platform5_value1, p#platform4_value1 ,p#platform3_value1,
     p#platform2_value1, p#twitter_value1 {
         font-weight: 900;
         font-size: 1.3em;
         margin: 10px 0 0 20px;
     }

     p#platform1_budget, p#platform5_budget, p#platform4_budget, p#platform3_budget,
     p#platform2_budget, p#twitter_budget{
        font-size: 1.2em;
        margin: 10px 0 0 20px;
     }

    div#twitter.infocontentheader{
    background-color: #1da1f2;
    }
    div#twitter.infobox img{
        display: block;
        margin: 0 auto 0 auto;
    }

    div#platform3.infocontentheader{
    background-color: #a15aa0;
    }

    div#display.parentbox{
    background-color: #b3b3b3;
    color: #fff;
    }

    div#video.parentbox{
    background-color: #999999;
    color: #fff;
    }

    div#mixed.parentbox{
    background-color: #c1c1c1;
    color: #fff;
    }

    #platform3 div.infocontentheader{
    color: #fff;
    }
    div#platform3.infobox img{

        display: block;
        margin: 0 auto 0 auto;
    }

    div#platform3_value.infocontent{
    color: #000;
    }

    div#platform5.infocontentheader{
    background-color: #ff0102;
    }
    div#platform5.infobox img{
    display: block;
    margin: 0 auto 0 auto;
    }
    div#platform4.infocontentheader{
        background-color: #cac9c2;
    }
    div#platform4.infobox img{
        display: block;
        margin: 10% auto 0 auto;
    }
  div#platform2.infobox{
    background-color: #fff;
    }
    div#platform2.infobox img{
    display: block;
    margin: 10% auto 0 auto;
    }

    .hidden{
    display:none;
    }

    #parent_div_1{
        width:50%;
        min-height: 150px;
        background-color: #757476;
        margin-right:0px;
        float:left;
    }
    #parent_div_2{
        width:50%;
        min-height: 150px;
        background-color: #8D8D8D;
        margin-right:0px;
        float:left;
    }
    .parentbox{
        width:33.33%;
        min-height: 150px;
        /*background-color: #8D8D8D;*/
        margin-right:0px;
        float:left;
    }
    .parentbox1{
        width:100%;
        min-height: 150px;
        margin-right:0px;
        float:left;
    }
    .parentbox2{
        width:50%;
        min-height: 150px;
        margin-right:0px;
        float:left;
    }
    .parentbox3{
        width:33.33%;
        min-height: 150px;
        margin-right:0px;
        float:left;
    }
    .child_div_1{
    margin-top: 50px;
    margin-left: 15%;
    margin-bottom: 0px;
    text-align: left;
    }
    .child_div_2{
    margin-left: 15%;
    margin-top: 10px;
    margin-bottom: 40px;
    text-align: left;
    }
     .child_budget{
    margin-top: 10px;
    margin-bottom: 40px;
    padding-left:15%;
    text-align: left;
    float: left;
    }
    .child_value1{
    margin-top: 10px;
    margin-bottom: 40px;
    padding-right: 15%;
    text-align: left;
    float:right;
    }
     .child_title{
    margin-top: 50px;
    margin-bottom: 0px;
    text-align: center;
    }
    .child_budget_number{
        padding-right: 20%;
    }
    .child_value1_number{
        padding-left: 20%;
    }

.boxbox {
    display: table;
    width: 99.8%;
    height: 160px;
    color: #454545;
    font-size:1.1vw;
}

.boxbox {
    float:left;
    display: table;
    width: 99.8%;
    height: 180px;
    color: #454545;
}
.boxbox > .col-lg-6 {
    display: table-cell;
    vertical-align: middle;
}

value1

value2

value1

value2

value1

value2

value1

value2

value1

value2

value1

value2


问:
Php preg_match_all search two strings with one pattern
I have a string like this:

```<code>{img:amp.jpg}
</code>```

or like this:

```<code>{img:amp.jpg alt:something}
</code>```

I'm using php function preg_match_all to get an image filename like "amp.jpg" or alt attribute like "something" at one time, but the alt attribute is optional. The problem is how to use one pattern to search filename and alt attribute if is set.

Finally i want to build an html image tag like:

```<code><img src="amp.jpg" alt="something">
</code>```

答:
This creates the tag. When alt is not set it's empty in the tag.

```<code>$re = '/{img:(.*?)(?:}| alt:(.*?)})/';
$str = '{img:amp.jpg alt:something}';
$subst = '<img src="$1" alt="$2" />';

$result = preg_replace($re, $subst, $str, 1);
</code>```

See https://regex101.com/r/IaPf6Y/2

Body:
I have a string like this:

{img:amp.jpg}

or like this:

{img:amp.jpg alt:something}

I'm using php function preg_match_all to get an image filename like "amp.jpg" or alt attribute like "something" at one time, but the alt attribute is optional. The problem is how to use one pattern to search filename and alt attribute if is set.

Finally i want to build an html image tag like:

Body:
This creates the tag. When alt is not set it's empty in the tag.

$re = '/{img:(.*?)(?:}| alt:(.*?)})/';
$str = '{img:amp.jpg alt:something}';
$subst = '<img src="$1" alt="$2" />';

$result = preg_replace($re, $subst, $str, 1);

See https://regex101.com/r/IaPf6Y/2


问:
Twitter Search In user_timeline.json
Am using jQuery to retrieve tweets in .json. One part of my application requires old tweets, and twitter search returns tweets only for last 6 days. This old tweets have to contain certain hashtag.
I know that user_timeline API method can return 3200 tweets, but i cant understand how to get 3200 tweets, loop through them and find tweets i need.
Here is what i have for now:

```<code>function TwitterAPI(){}
TwitterAPI.Statuses = function Statuses(){}

TwitterAPI.Statuses.hashed = function(username, hashtag, count, to, callback){
   requestURL = "http://search.twitter.com/search.json?q=%23" + hashtag + "&rpp=" + count + "&from=" + username + "&to=" + to + "&callback=?";
   //requestURL =  "http://otter.topsy.com/search.json?q=from:" + username + "+" + hashtag + "&perpage=1"
   $.getJSON(requestURL, callback);
  }

var user_info = ["name", "birthday", "hobby", "homepage"];
  $("#info ul li.userinfo").append('<img src="images/lilspinner.gif" />');
  $.each(user_info, function() {
   var hashtag = this;
   TwitterAPI.Statuses.hashed("<%= @profile.name %>", hashtag, 1, "twisnt", function(json, status){
    var content = "";
    $.each(json.results, function(i, info){
     text = info.text.replace( /(\#)\w+\b/,"").replace( /(\@)\w+\b/,"");
     if (hashtag == "homepage") {
      content = "<a style='display:none' href='"+text+"'>"+text+"</a>";
     }
     else {
      content = "<span style='display:none'>"+text+"</span>";
     }
    });
    $("li#" + hashtag).append(content);
    $("li#" + hashtag + " img").remove();
    $("li#" + hashtag + " *").fadeIn("slow");
   })
});
</code>```

It does everything i need, but only when needed messages where tweeted in last 6 days,

答:
According to the twitter API you can only get 100 results at a time. Use the rpp search item to request 100 and start on page 1. Then you can loop through pages getting 100 items at a time. Do this 15 times to get 1500 items. The reason for this is twitter only allows you to get the last 15 pages for a max of 1500 items.

Example:

```<code>var maxRpp = 100;

var i; //pages
for (i = 1;i <= 15; i++) {
     $.getJSON('http://search.twitter.com/search.json?q=pants&result_type=recent&page=' + i + '&rpp=' + maxRpp + '&callback=?',function(data){
          //do thing
     });
};
</code>```

Source:
Twitter API

Title: Twitter Search In user_timeline.json

Body:
Am using jQuery to retrieve tweets in .json. One part of my application requires old tweets, and twitter search returns tweets only for last 6 days. This old tweets have to contain certain hashtag.
I know that user_timeline API method can return 3200 tweets, but i cant understand how to get 3200 tweets, loop through them and find tweets i need.
Here is what i have for now:

function TwitterAPI(){}
TwitterAPI.Statuses = function Statuses(){}

TwitterAPI.Statuses.hashed = function(username, hashtag, count, to, callback){
   requestURL = "http://search.twitter.com/search.json?q=%23" + hashtag + "&rpp=" + count + "&from=" + username + "&to=" + to + "&callback=?";
   //requestURL =  "http://otter.topsy.com/search.json?q=from:" + username + "+" + hashtag + "&perpage=1"
   $.getJSON(requestURL, callback);
  }

var user_info = ["name", "birthday", "hobby", "homepage"];
  $("#info ul li.userinfo").append('');
  $.each(user_info, function() {
   var hashtag = this;
   TwitterAPI.Statuses.hashed("<%= @profile.name %>", hashtag, 1, "twisnt", function(json, status){
    var content = "";
    $.each(json.results, function(i, info){
     text = info.text.replace( /(\#)\w+\b/,"").replace( /(\@)\w+\b/,"");
     if (hashtag == "homepage") {
      content = ""+text+"";
     }
     else {
      content = ""+text+"";
     }
    });
    $("li#" + hashtag).append(content);
    $("li#" + hashtag + " img").remove();
    $("li#" + hashtag + " *").fadeIn("slow");
   })
});

It does everything i need, but only when needed messages where tweeted in last 6 days,

Body:
According to the twitter API you can only get 100 results at a time. Use the rpp search item to request 100 and start on page 1. Then you can loop through pages getting 100 items at a time. Do this 15 times to get 1500 items. The reason for this is twitter only allows you to get the last 15 pages for a max of 1500 items.

Example:

var maxRpp = 100;

var i; //pages
for (i = 1;i <= 15; i++) {
     $.getJSON('http://search.twitter.com/search.json?q=pants&result_type=recent&page=' + i + '&rpp=' + maxRpp + '&callback=?',function(data){
          //do thing
     });
};

Source:
Twitter API


问:
How to use token authentication while testing REST API
I am trying to use test the API request by using tokens. I was able to extract the token but I struggle to find a way to use it.

This is how I get my token:

```<code>@pytest.mark.django_db
class TestUserAPI(APITestCase):

    def setUp(self):
        self.created_user = UserFactory()
        User.objects.create_user(username='test', password='pass1234')

    def test_authentification(self):
        request = self.client.post('http://localhost:8000/api/v1/auth/',
                                  {
                                      "username": "test",
                                      "password": "pass1234"
                                  })

        TestUserAPI.token = request.data["token"]

        assert request.status_code == 200
</code>```

and this is how I use it:

```<code>def test_profile(self):
    request = self.client.get('http://localhost:8000/api/v1/profile/',
                              TokenAuthentication = 'token {}'.format(TestUserAPI.token))

    assert request.status_code == status.HTTP_200_OK
</code>```

It gives me 401 error. What is the correct way of using token?

答: According to documentation correct header format is Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b

Body:
I am trying to use test the API request by using tokens. I was able to extract the token but I struggle to find a way to use it.

This is how I get my token:

@pytest.mark.django_db
class TestUserAPI(APITestCase):

    def setUp(self):
        self.created_user = UserFactory()
        User.objects.create_user(username='test', password='pass1234')

    def test_authentification(self):
        request = self.client.post('http://localhost:8000/api/v1/auth/',
                                  {
                                      "username": "test",
                                      "password": "pass1234"
                                  })

        TestUserAPI.token = request.data["token"]

        assert request.status_code == 200

and this is how I use it:

def test_profile(self):
    request = self.client.get('http://localhost:8000/api/v1/profile/',
                              TokenAuthentication = 'token {}'.format(TestUserAPI.token))

    assert request.status_code == status.HTTP_200_OK

It gives me 401 error. What is the correct way of using token?


问:
Increase efficiency for following algorithm
Problem:-

```<code>input = n
output :-

1     2      3.......n [first row]
2n+1 2n+2   2n+3....3n [second row]

3n+1  3n+2   3n+3...4n [second last row]
n+1   n+2    n+3....2n [last row]
</code>```

In the problem we have to print a square such that we have 'n' numbers of rows in our square and in every row we have 'n' numbers. We prepare rows from numbers from 1 to square(n) in such way we fill numbers for first row, then last row, second row, second last row and so on.....

for e.g. if n = 4

We start from 1 print upto 4 then print a newline, so our first row is:-

```<code>1 2 3 4
</code>```

Then our last row comes in continuation

```<code>5 6 7 8
</code>```

then our second row will be

```<code>9 10 11 12
</code>```

few examples:

```<code>input = 1
output = 1

input = 2
output = 1 2
         3 4

input = 3
output = 1 2 3
         7 8 9
         4 5 6
</code>```

My Code:

```<code>n = int(input().strip())
lines = [i for i in range (1, n + 1)]

line_order1 = []
line_order2 = []

#Reordering lines so we know the staring element of our method
for i in lines:
    if(i % 2 == 1):
        line_order1.append(i)
    else:
        line_order2.append(i)

 print(line_order1)
 print(line_order2)

 // Getting the desired order of lines
 line_order2.reverse()
 line_order1.extend(line_order2)
 print(line_order1)

 // Now printing the desired square
 for l in line_order1:
     for i in range (1, n+1):
         k = n * (l - 1)
         print(k + i, end = " ")
     print("\n")
</code>```

Is there a better way to do this in terms of execution time?

答:
While I see a few minor places you can improve your code, the performance is unlikely to be much better (my suggestions below might not make any performance difference at all). Your code will take O(n**2) time, which is the best you can do, since you need to print out that many numbers to form your square. Even if you combine some of your longer, more verbose steps into more compact versions, they'll can only possibly be better by a constant factor.

My first suggestion is to number the lines from 0 to n-1 instead of from 1 to n. This will save you some effort when you have to calculate how what multiple of n to include in the values for the row. Currently you've got an awkward l - 1 in your calculation that you could skip if you just used zero-indexed numbers for the rows. (Also l is a terrible variable name, since it looks like the digit 1 (one) in some fonts.)

My next suggestion is to simplify your code that builds the order. You don't need three lists, you can do the whole thing with one list that you feed two range objects, each counting up or down by two.

```<code>line_order = list(range(0, n, 2)) # count up by twos
line_order.extend(range(n - 1 - n%2, 0, -2)) # count down starting at either n-1 or n-2
</code>```

Or, if you're willing to use a standard library module, you could import itertools and then use:

```<code>line_order = itertools.chain(range(0, n, 2), range(n - 1 - n%2, 0, -2))
</code>```

The itertools.chain function returns an iterator that yields values from each of its iterable arguments as if they were concatenated together, without making any copies of the data or using significant extra memory. The difference is not likely to be a much here (since the maximum n you can usefully print out is fairly small), but if you were doing something different with the result of this algorithm and n was in the billions it would be very nice to avoid filling a list with that many values.

My last suggestion is to use a range again to generate all the numbers in each row directly, rather than explicitly looping from 1 to n and adding k each time.

```<code>for row_num in line_order:
    print(*range(n * row_num + 1, n * (rownum + 1) + 1))
</code>```

You can compute the start and end points with the multiples of n already included, rather than needing to do that in a separate step for each one. You certainly didn't need to be recomputing k as often as you were before. You can pass all the values from the range to print in one go using iterable unpacking syntax (*args).

Note though that unpacking the range that way is sort of the reverse of the previous suggestion regarding itertools.chain. If n is large, using a loop over the range would be more memory efficient, since you won't need all n values to exist in memory at a the same time. Here's what that would look like:

```<code>for line_num in line_order:
    for value in range(n * row_num + 1, n * (rownum + 1) + 1):
        print(value, end=" ")
    print()
</code>```

Body:
Problem:-

input = n
output :-

1     2      3.......n [first row]
2n+1 2n+2   2n+3....3n [second row]

3n+1  3n+2   3n+3...4n [second last row]
n+1   n+2    n+3....2n [last row]

In the problem we have to print a square such that we have 'n' numbers of rows in our square and in every row we have 'n' numbers. We prepare rows from numbers from 1 to square(n) in such way we fill numbers for first row, then last row, second row, second last row and so on.....

for e.g. if n = 4

We start from 1 print upto 4 then print a newline, so our first row is:-

1 2 3 4

Then our last row comes in continuation

5 6 7 8

then our second row will be

9 10 11 12

few examples:

input = 1
output = 1

input = 2
output = 1 2
         3 4

input = 3
output = 1 2 3
         7 8 9
         4 5 6

My Code:

n = int(input().strip())
lines = [i for i in range (1, n + 1)]

line_order1 = []
line_order2 = []

#Reordering lines so we know the staring element of our method
for i in lines:
    if(i % 2 == 1):
        line_order1.append(i)
    else:
        line_order2.append(i)

 print(line_order1)
 print(line_order2)

 // Getting the desired order of lines
 line_order2.reverse()
 line_order1.extend(line_order2)
 print(line_order1)

 // Now printing the desired square
 for l in line_order1:
     for i in range (1, n+1):
         k = n * (l - 1)
         print(k + i, end = " ")
     print("\n")

Is there a better way to do this in terms of execution time?

Body:
While I see a few minor places you can improve your code, the performance is unlikely to be much better (my suggestions below might not make any performance difference at all). Your code will take O(n**2) time, which is the best you can do, since you need to print out that many numbers to form your square. Even if you combine some of your longer, more verbose steps into more compact versions, they'll can only possibly be better by a constant factor.

My first suggestion is to number the lines from 0 to n-1 instead of from 1 to n. This will save you some effort when you have to calculate how what multiple of n to include in the values for the row. Currently you've got an awkward l - 1 in your calculation that you could skip if you just used zero-indexed numbers for the rows. (Also l is a terrible variable name, since it looks like the digit 1 (one) in some fonts.)

My next suggestion is to simplify your code that builds the order. You don't need three lists, you can do the whole thing with one list that you feed two range objects, each counting up or down by two.

line_order = list(range(0, n, 2)) # count up by twos
line_order.extend(range(n - 1 - n%2, 0, -2)) # count down starting at either n-1 or n-2

Or, if you're willing to use a standard library module, you could import itertools and then use:

line_order = itertools.chain(range(0, n, 2), range(n - 1 - n%2, 0, -2))

The itertools.chain function returns an iterator that yields values from each of its iterable arguments as if they were concatenated together, without making any copies of the data or using significant extra memory. The difference is not likely to be a much here (since the maximum n you can usefully print out is fairly small), but if you were doing something different with the result of this algorithm and n was in the billions it would be very nice to avoid filling a list with that many values.

My last suggestion is to use a range again to generate all the numbers in each row directly, rather than explicitly looping from 1 to n and adding k each time.

for row_num in line_order:
    print(*range(n * row_num + 1, n * (rownum + 1) + 1))

You can compute the start and end points with the multiples of n already included, rather than needing to do that in a separate step for each one. You certainly didn't need to be recomputing k as often as you were before. You can pass all the values from the range to print in one go using iterable unpacking syntax (*args).

Note though that unpacking the range that way is sort of the reverse of the previous suggestion regarding itertools.chain. If n is large, using a loop over the range would be more memory efficient, since you won't need all n values to exist in memory at a the same time. Here's what that would look like:

for line_num in line_order:
    for value in range(n * row_num + 1, n * (rownum + 1) + 1):
        print(value, end=" ")
    print()


问:
How to change asp.net DropDownList SelectedValue using javascript?
I have three dropdownlist controls in my asp.net web app project from which the user will choose items. What I want is that the user must not choose the same values, meaning that the value selected in the one Dropdownlist can not be selected in the other dropdownlist, and if the user tries to select the same value I want to reset the selectedValue property to that dropdownlist. Is there anyway I can achieve this using javascript? It's better to make it on the client side.

Thank you!

The Dropdownlist Looks like this: Image here

答:
Use change Event of every dropdownlist

this is just one change event that i use for Dropdownlist. Do same thing for other drowpdownlists.

```<code>var firstDropVal="";
var SecndDropVal="";
var ThrdDropVal ="";

    $("#dropOne").change(function () {

            var firstDropVal = $("#dropOne").val();
           var firstDropVal = $("#dropTwo").val();
          var firstDropVal = $("#dropThree").val();

        if(firstDropVal == SecndDropVal){

         $("#dropOne").val(0)// Or Do what you want to do
         }

        });
</code>```

Body:
Use change Event of every dropdownlist

this is just one change event that i use for Dropdownlist. Do same thing for other drowpdownlists.

var firstDropVal="";
var SecndDropVal="";
var ThrdDropVal ="";

    $("#dropOne").change(function () {

            var firstDropVal = $("#dropOne").val();
           var firstDropVal = $("#dropTwo").val();
          var firstDropVal = $("#dropThree").val();

        if(firstDropVal == SecndDropVal){

         $("#dropOne").val(0)// Or Do what you want to do
         }

        });


问:
Extract string in parentheses using c#
I have a string ---TIMESTAMP Tue, 24 Oct 2017 02:11:56 -0400 [1508825516987]---

I want to get the value within the [] (i.e. 1508825516987)

How can I get the value using Regex?

答:
Explanation:

\[ : [ is a meta char and needs to be escaped if you want to match it literally.

(.*?) : match everything in a non-greedy way and capture it.

\] : ] is a meta char and needs to be escaped if you want to match it literally.

Source of explanation: Click

```<code>static void Main(string[] args)
{
    string txt = "---TIMESTAMP Tue, 24 Oct 2017 02:11:56 -0400 [1508825516987]---";

    Regex regex = new Regex(@"\[(.*?)\]", RegexOptions.IgnoreCase | RegexOptions.Singleline);
    Match match = regex.Match(txt);
    if (match.Success)
    {
        for (int i = 1; i < match.Groups.Count; i++)
        {
            String extract = match.Groups[i].ToString();
            Console.Write(extract.ToString());
        }
    }
    Console.ReadLine();
}
</code>```

Links to learn to create regular expressions:

Regexstorm

RegExr

Update 1:

```<code>Regex regex = new Regex(@"^---.*\[(.*?)\]", RegexOptions.IgnoreCase | RegexOptions.Singleline);
</code>```

^ is start of string

--- are your (start) characters

.* is any char between --- and [

Title: Extract string in parentheses using c#

Body:
Explanation:

\[ : [ is a meta char and needs to be escaped if you want to match it literally.

(.*?) : match everything in a non-greedy way and capture it.

\] : ] is a meta char and needs to be escaped if you want to match it literally.

Source of explanation: Click

static void Main(string[] args)
{
    string txt = "---TIMESTAMP Tue, 24 Oct 2017 02:11:56 -0400 [1508825516987]---";

    Regex regex = new Regex(@"\[(.*?)\]", RegexOptions.IgnoreCase | RegexOptions.Singleline);
    Match match = regex.Match(txt);
    if (match.Success)
    {
        for (int i = 1; i < match.Groups.Count; i++)
        {
            String extract = match.Groups[i].ToString();
            Console.Write(extract.ToString());
        }
    }
    Console.ReadLine();
}

Links to learn to create regular expressions:

Regexstorm

RegExr

Update 1:

Regex regex = new Regex(@"^---.*\[(.*?)\]", RegexOptions.IgnoreCase | RegexOptions.Singleline);

^ is start of string

--- are your (start) characters

.* is any char between --- and [


问:
Data Cleaning Using Stringr
I have a data table with two columns, the first column containing an Id variable, and the second column containing a string. The string in the second column is in the format

"A:randomString|B:randomString|C:randomString".

I want to alter the table to have 4 columns: Id, A, B, and C. Id would stay the same, A would have the random string following each A:, B would have the string following each B:, and C would have the string following C:.

Is it possible to do this using stringr?

答:
You may choose to use this:

```<code>library(stringr)
xt <- "A:randomString|B:randomString|C:randomString"
colnm <- unlist(str_extract_all(xt, "[A-Z](?=:)"))
values <- setNames(data.frame(rbind(unlist(str_extract_all(xt,"(?![A-Z]:)\\w+" )))), colnm)
</code>```

Output:

```<code>print(values)
             A            B            C
1 randomString randomString randomString
</code>```

Title: Data Cleaning Using Stringr

Body:
You may choose to use this:

library(stringr)
xt <- "A:randomString|B:randomString|C:randomString"
colnm <- unlist(str_extract_all(xt, "[A-Z](?=:)"))
values <- setNames(data.frame(rbind(unlist(str_extract_all(xt,"(?![A-Z]:)\\w+" )))), colnm)

Output:

print(values)
             A            B            C
1 randomString randomString randomString


问:
Pointer addition and element size
At: http://www.fredosaurus.com/notes-cpp/arrayptr/26arraysaspointers.html

Under: Pointer addition and element size

There is the following code:

```<code>// Assume sizeof(int) is 4.
int b[100];  // b is an array of 100 ints.
int* p;      // p is a a pointer to an int.
p = b;       // Assigns address of first element of b. Ie, &b[0]
p = p + 1;   // Adds 4 to p (4 == 1 * sizeof(int)). Ie, &b[1]
</code>```

How did "p" in the last line become "4"?

Thanks.

答:
The comment in the code you post it explains it: addition of an integer x to a pointer increases the pointer's value by x multiplied by the sizeof the type it is pointing to.

This is convenient because it doesn't usually make sense to change the pointer in smaller increments - you wouldn't want it to point into the middle of one of the elements.

ContentLicense: CC BY-SA 4.0

Title: Pointer addition and element size

Body:
At: http://www.fredosaurus.com/notes-cpp/arrayptr/26arraysaspointers.html

Under: Pointer addition and element size

There is the following code:

// Assume sizeof(int) is 4.
int b[100];  // b is an array of 100 ints.
int* p;      // p is a a pointer to an int.
p = b;       // Assigns address of first element of b. Ie, &b[0]
p = p + 1;   // Adds 4 to p (4 == 1 * sizeof(int)). Ie, &b[1]

How did "p" in the last line become "4"?

Thanks.


问:
3 Collection Views on One View Controller
I have 3 collection views on 1 view controller.  I've tried a few of the other suggestions I've found on Stack but nothing seems to work.

All 3 Collection Views are in a separate cell of a HomeTableViewController.  I tried to create the outlet connection to the HomeTableViewController but I get the error Outlets cannot be connected to repeating content.

I've read many people being able to hook up their multiple collectionViews so I am a bit confused as to where I'm going wrong...

答:
You should create outlet in the UITableViewCell. Then you can provide tags to collectionViews in each cell in tableView:cellForRowAtIndexPath Method:

```<code>yourCell.collectionViewOutlet.tag = indexPath.row + 1000
</code>```

you should replace 1000 with Any Constant Integer if the tags conflict with tags of other views.

Then use these tags to differentiate all collectionviews in collectionview:cellForItemForIndexpath method:

```<code>if(collectionView.tag == 1000){
//Code for collection view in first row of the table
}
else if(collectionView.tag == 1001){
//Code for collection view in second row of the table
}
else if(collectionView.tag == 1002){
//Code for collection view in third row of the table
}
</code>```

You should also keep in mind to return number of items for each collection view just like above.

Tags make the life whole lot easier , don't they?
Happy Coding (Y)

Body:
You should create outlet in the UITableViewCell. Then you can provide tags to collectionViews in each cell in tableView:cellForRowAtIndexPath Method:

yourCell.collectionViewOutlet.tag = indexPath.row + 1000

you should replace 1000 with Any Constant Integer if the tags conflict with tags of other views.

Then use these tags to differentiate all collectionviews in collectionview:cellForItemForIndexpath method:

if(collectionView.tag == 1000){
//Code for collection view in first row of the table
}
else if(collectionView.tag == 1001){
//Code for collection view in second row of the table
}
else if(collectionView.tag == 1002){
//Code for collection view in third row of the table
}

You should also keep in mind to return number of items for each collection view just like above.

Tags make the life whole lot easier , don't they?
Happy Coding (Y)


问:
can't load blender model on threeJS scene is undefined
I already followed some questions that are on SO to solve this problem, but i still can't load external objects (blender).

Basicly i export it as a ThreeJS JSON file , this is my JSON file:

```<code>{
    "textures":[],
    "animations":[{
        "fps":24,
        "tracks":[],
        "name":"default"
    }],
    "geometries":[{
        "materials":[{
            "colorEmissive":[0,0,0],
            "DbgName":"Material.113",
            "DbgIndex":0,
            "shading":"phong",
            "specularCoef":50,
            "transparent":false,
            "visible":true,
            "blending":1,
            "depthWrite":true,
            "DbgColor":15658734,
            "doubleSided":false,
            "wireframe":false,
            "colorSpecular":[0.5,0.5,0.5],
            "opacity":1,
            "depthTest":true,
            "colorDiffuse":[0.0396404,0.0396404,0.0396404]
        },{
            "colorEmissive":[0,0,0],
            "DbgName":"Material.112",
            "DbgIndex":1,
            "shading":"lambert",
            "transparent":false,
            "visible":true,
            "blending":1,
            "depthWrite":true,
            "DbgColor":15597568,
            "doubleSided":false,
            "wireframe":false,
            "opacity":1,
            "depthTest":true,
            "colorDiffuse":[0.8,0.443066,0.182712]
        },{
            "colorEmissive":[0,0,0],
            "DbgName":"Material.114",
            "DbgIndex":2,
            "shading":"phong",
            "specularCoef":50,
            "transparent":false,
            "visible":true,
            "blending":1,
            "depthWrite":true,
            "DbgColor":60928,
            "doubleSided":false,
            "wireframe":false,
            "colorSpecular":[0.5,0.5,0.5],
            "opacity":1,
            "depthTest":true,
            "colorDiffuse":[0.8,0.614231,0.407028]
        }],
        "data":{
            "uvs":[],
            "normals":[-0,0,1,-1,-0,0,1,-0,-0,-0,-1,0,-1,4.76837e-07,0,-1,-0,0,-2.38419e-07,-1,2.38419e-07,-2.38419e-07,-1,2.38419e-07,-2.38419e-07,-1,2.38419e-07 },
        "type":"Geometry",
        "uuid":"639CD2C2-56FB-4D8F-B53B-B8C3E040803C",
        "name":"Cube.111Geometry.4"
    }],
    "object":{
        "children":[{
            "name":"Cube.001",
            "uuid":"1213E565-1F93-497F-B4F0-843C1F17BCAD",
            "matrix":[-0.6,0,0,0,0,0,0.6,0,0,0.6,0,0,-0.866864,0.6,2.6259,1],
            "visible":true,
            "type":"Mesh",
            "material":["87C3E87D-CD72-4A6F-963A-84474DFE4059","FABD8A0F-02B0-4665-A21E-5CD1E4DDD518","E4331AC2-6CAC-4BCE-A5BD-89A811DD4D76"],
            "castShadow":true,
            "receiveShadow":true,
            "geometry":"639CD2C2-56FB-4D8F-B53B-B8C3E040803C"
        }],
        "matrix":[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],
        "type":"Scene",
        "uuid":"23736546-1486-4089-967C-6DA05CB3F49C"
    },
    "materials":[{
        "vertexColors":0,
        "color":13398062,
        "uuid":"FABD8A0F-02B0-4665-A21E-5CD1E4DDD518",
        "depthWrite":true,
        "depthTest":true,
        "type":"MeshLambertMaterial",
        "blending":1,
        "emissive":0,
        "name":"Material.112"
    },{
        "vertexColors":0,
        "shininess":50,
        "color":657930,
        "uuid":"87C3E87D-CD72-4A6F-963A-84474DFE4059",
        "specular":8355711,
        "depthWrite":true,
        "depthTest":true,
        "type":"MeshPhongMaterial",
        "blending":1,
        "emissive":0,
        "name":"Material.113"
    },{
        "vertexColors":0,
        "shininess":50,
        "color":13409383,
        "uuid":"E4331AC2-6CAC-4BCE-A5BD-89A811DD4D76",
        "specular":8355711,
        "depthWrite":true,
        "depthTest":true,
        "type":"MeshPhongMaterial",
        "blending":1,
        "emissive":0,
        "name":"Material.114"
    }],
    "metadata":{
        "generator":"io_three",
        "sourceFile":"DAMA1.blend",
        "version":4.4,
        "type":"Object"
    },
    "images":[]
}
</code>```

i omitted some data on the normals array, but basicly i try to load it like this:

```<code>var objLoader =new THREE.ObjectLoader();
objLoader.load('assets/dama.json', function (geometry) {
  this.scene.add(geometry);
});
</code>```

it founds the file but i get an error like this:  Cannot read property 'scene' of undefined

maybe it has something to do with the exported settings, but i already changed buffergeometry to geometry and added scene checkbox, what am i doing wrong ?:S

答:
I am not sure about it. But you can try this,

```<code>var scope = this;
var objLoader =new THREE.ObjectLoader();
objLoader.load('assets/dama.json', function (geometry) {
    scope.scene.add(geometry);
});
</code>```

I hope that your scene is the property of an object and that may be the reason why you referred it as this.scene. The problem with this is, when you call this inside the load function it will refer to THREE.ObjectLoader. So if you need to refer to the underlying object using this, you should take a copy of it first and then use it.

If you are not using an object to hold the scene, just call scene.add(geometry) instead of scope.scene.add() and this.scene.add()

Body:
I already followed some questions that are on SO to solve this problem, but i still can't load external objects (blender).

Basicly i export it as a ThreeJS JSON file , this is my JSON file:

{
    "textures":[],
    "animations":[{
        "fps":24,
        "tracks":[],
        "name":"default"
    }],
    "geometries":[{
        "materials":[{
            "colorEmissive":[0,0,0],
            "DbgName":"Material.113",
            "DbgIndex":0,
            "shading":"phong",
            "specularCoef":50,
            "transparent":false,
            "visible":true,
            "blending":1,
            "depthWrite":true,
            "DbgColor":15658734,
            "doubleSided":false,
            "wireframe":false,
            "colorSpecular":[0.5,0.5,0.5],
            "opacity":1,
            "depthTest":true,
            "colorDiffuse":[0.0396404,0.0396404,0.0396404]
        },{
            "colorEmissive":[0,0,0],
            "DbgName":"Material.112",
            "DbgIndex":1,
            "shading":"lambert",
            "transparent":false,
            "visible":true,
            "blending":1,
            "depthWrite":true,
            "DbgColor":15597568,
            "doubleSided":false,
            "wireframe":false,
            "opacity":1,
            "depthTest":true,
            "colorDiffuse":[0.8,0.443066,0.182712]
        },{
            "colorEmissive":[0,0,0],
            "DbgName":"Material.114",
            "DbgIndex":2,
            "shading":"phong",
            "specularCoef":50,
            "transparent":false,
            "visible":true,
            "blending":1,
            "depthWrite":true,
            "DbgColor":60928,
            "doubleSided":false,
            "wireframe":false,
            "colorSpecular":[0.5,0.5,0.5],
            "opacity":1,
            "depthTest":true,
            "colorDiffuse":[0.8,0.614231,0.407028]
        }],
        "data":{
            "uvs":[],
            "normals":[-0,0,1,-1,-0,0,1,-0,-0,-0,-1,0,-1,4.76837e-07,0,-1,-0,0,-2.38419e-07,-1,2.38419e-07,-2.38419e-07,-1,2.38419e-07,-2.38419e-07,-1,2.38419e-07 },
        "type":"Geometry",
        "uuid":"639CD2C2-56FB-4D8F-B53B-B8C3E040803C",
        "name":"Cube.111Geometry.4"
    }],
    "object":{
        "children":[{
            "name":"Cube.001",
            "uuid":"1213E565-1F93-497F-B4F0-843C1F17BCAD",
            "matrix":[-0.6,0,0,0,0,0,0.6,0,0,0.6,0,0,-0.866864,0.6,2.6259,1],
            "visible":true,
            "type":"Mesh",
            "material":["87C3E87D-CD72-4A6F-963A-84474DFE4059","FABD8A0F-02B0-4665-A21E-5CD1E4DDD518","E4331AC2-6CAC-4BCE-A5BD-89A811DD4D76"],
            "castShadow":true,
            "receiveShadow":true,
            "geometry":"639CD2C2-56FB-4D8F-B53B-B8C3E040803C"
        }],
        "matrix":[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],
        "type":"Scene",
        "uuid":"23736546-1486-4089-967C-6DA05CB3F49C"
    },
    "materials":[{
        "vertexColors":0,
        "color":13398062,
        "uuid":"FABD8A0F-02B0-4665-A21E-5CD1E4DDD518",
        "depthWrite":true,
        "depthTest":true,
        "type":"MeshLambertMaterial",
        "blending":1,
        "emissive":0,
        "name":"Material.112"
    },{
        "vertexColors":0,
        "shininess":50,
        "color":657930,
        "uuid":"87C3E87D-CD72-4A6F-963A-84474DFE4059",
        "specular":8355711,
        "depthWrite":true,
        "depthTest":true,
        "type":"MeshPhongMaterial",
        "blending":1,
        "emissive":0,
        "name":"Material.113"
    },{
        "vertexColors":0,
        "shininess":50,
        "color":13409383,
        "uuid":"E4331AC2-6CAC-4BCE-A5BD-89A811DD4D76",
        "specular":8355711,
        "depthWrite":true,
        "depthTest":true,
        "type":"MeshPhongMaterial",
        "blending":1,
        "emissive":0,
        "name":"Material.114"
    }],
    "metadata":{
        "generator":"io_three",
        "sourceFile":"DAMA1.blend",
        "version":4.4,
        "type":"Object"
    },
    "images":[]
}

i omitted some data on the normals array, but basicly i try to load it like this:

var objLoader =new THREE.ObjectLoader();
objLoader.load('assets/dama.json', function (geometry) {
  this.scene.add(geometry);
});

it founds the file but i get an error like this:  Cannot read property 'scene' of undefined

maybe it has something to do with the exported settings, but i already changed buffergeometry to geometry and added scene checkbox, what am i doing wrong ?:S

Body:
I am not sure about it. But you can try this,

var scope = this;
var objLoader =new THREE.ObjectLoader();
objLoader.load('assets/dama.json', function (geometry) {
    scope.scene.add(geometry);
});

I hope that your scene is the property of an object and that may be the reason why you referred it as this.scene. The problem with this is, when you call this inside the load function it will refer to THREE.ObjectLoader. So if you need to refer to the underlying object using this, you should take a copy of it first and then use it.

If you are not using an object to hold the scene, just call scene.add(geometry) instead of scope.scene.add() and this.scene.add()


答:
May be you need to change from

```<code>$obj->$bar['baz']();
</code>```

To

```<code>$obj->{$bar}['baz']();
</code>```

Final code would be as

```<code>$bar='var';
echo "1. ".$obj->{$bar}['baz']();  //Output amazing_out_of_class

$bar=array('baz'=>'a');
echo "2. ".$obj->{$bar['baz']}(); //Output amazing_class
</code>```

Live demo : https://eval.in/915826

Title: Changes to variable handling in PHP

Body:
I am unable to understand variable Parsing.

I have gone through this link uniform_variable_syntax but this link is so hard me for understand.

class Test{

    public $var=array('baz'=>'a');

    function a(){

        return 'amazing_class
';
    }
}

 function a(){

    return 'amazing_out_of_class
';
}

$obj=new Test();

$bar='var';
echo "1. ".$obj->$bar['baz']();  //Output amazing_out_of_class

$bar=array('baz'=>'a');
echo "2. ".$obj->{$bar['baz']}(); //Output amazing_class

Now lets look at first case : $obj->$bar['baz']()

($obj->$bar)['baz']()  >>>   ($obj->var['baz'])() >>> a() >>> amazing_out_of_class

Now i also suppose it $obj->{$bar['baz']}() parsed same as above and expected Notice error : undefined Property a

$obj->{$bar['baz']}()  >>>   ($obj->a)() >>> ($obj->a) is Notice error : undefined Property a

Notice error : undefined Property a  is my assumption according to first case but its output amazing_class

Body:
May be you need to change from

$obj->$bar['baz']();

To

$obj->{$bar}['baz']();

Final code would be as

$bar='var';
echo "1. ".$obj->{$bar}['baz']();  //Output amazing_out_of_class

$bar=array('baz'=>'a');
echo "2. ".$obj->{$bar['baz']}(); //Output amazing_class

Live demo : https://eval.in/915826


问:
How to allow only integer value in input field for mobile application
I am using meteor+blaze for application development and need to allow only integer value in number input field for user details form.

I tried to use keypress/keyup events for input type nuber but not able to get the event for decimal point, android mobile number keypad return same keycode 229 for .,- keys and when i return false for keycode 229, it's not working. But events are working fine with number value keys on mobile.

code:

```<code>'keyup #weight': function (event, instance) {
        event.preventDefault();
        if (event.keyCode < 48 || event.keyCode > 57) {
            console.log(this, "Integer values only");
            return false;  // stop processing
        }
    }
</code>```

Please advise, how can I prevent the user from entering a decimal value in the input field?

答:
If you need only integers you can use:</p>

```<code> <input type="text" name="n" pattern="[0-9]*" />
</code>```

Body:
I am using meteor+blaze for application development and need to allow only integer value in number input field for user details form.

I tried to use keypress/keyup events for input type nuber but not able to get the event for decimal point, android mobile number keypad return same keycode 229 for .,- keys and when i return false for keycode 229, it's not working. But events are working fine with number value keys on mobile.

code:

'keyup #weight': function (event, instance) {
        event.preventDefault();
        if (event.keyCode < 48 || event.keyCode > 57) {
            console.log(this, "Integer values only");
            return false;  // stop processing
        }
    }

Please advise, how can I prevent the user from entering a decimal value in the input field?

Body:
If you need only integers you can use:

 <input type="text" name="n" pattern="[0-9]*" />


问:
Auto Layout (Constraints) Center 2 side by side views in a parent view
I'm trying to figure out how to do this with auto layout (iOS6) and constraints.

Basically I have my large view divided up into two sections on the bottom. Inside of those sections (currently subviews) I have an image view and a label. I want to center those on both sides, with variable length text.

My head is mostly wrapped around auto layout, but I'm not sure the best approach to this. I'm inclined to think it's not possible in IB, but is in code.

Going to continue trying to figure this out, but in the meantime here is the example I'm trying to create.

答:
There are several ways to do this.  In basic terms, here is how to center 1..n items, assuming all your items have constrained sizes and are not going to grow.

Put 2 spacers on each side of your items.  Anchor the spacers to the parent edges. Anchor your first and last items to the anchors.  Finally, assign 1 spacer to have the width of the other spacer.  You do not need to explicitly set any spacer size, as it will be solved.

spacer1 -> left=parent:left width=spacer2:width

spacer2 -> right=parent:right

yourFirstItem -> left=spacer1:right

yourLastItem -> right=spacer2:left

If spacers aren't your thing, and you and you have an odd number of items, center the middle one to the center of the parent. Also, make sure the first and last items are not anchored to the parent edges.

yourMiddleItem = centerX=parent:centerX

otherItems->yourMiddleItem<-otherItems

If spacers aren't your thing, and you have an even number of items, center the 2 inner items' edges to the center of the parent. Also, make sure the first and last items are not anchored to the parent edges.

leftMiddleItem -> right=parent:centerX

rightMiddleItem -> left=parent:centerX

otherItems->leftMiddleItem rightMiddleItem<-otherItems

You can also center an invisible placeholder in the center, and anchor to that, but you will still need to consider an odd/even number of items when constraining, so I don't recommend that approach.


问:
How to change default kivy logo with another image logo?
How can I change the default kivy icon logo? I tried in buildozer spec but nothing happens - when I convert my app in the apk the icon does not change.</p>

答: Change the icon.filename setting in the buildozer.spec file.


问:
PHP - isolate first letter from a text
I have a set of articles, in which I want to style the first letter from each article (with CSS).

the articles usually start with a paragrah, like:

```<code><p> bla bla </p>
</code>```

So how could I wrap the first letter from this text within a <span> tag ?

答:
```<code><?php

$str = '<p> bla bla </p>';
$search = '_^<p> *([\w])(.+) *</p>$_i';
$replacement = '<p><span>$1</span>$2</p>';

$new = preg_replace( $search, $replacement, $str );

echo $new."\n";
</code>```

Title: PHP - isolate first letter from a text

Body:
I have a set of articles, in which I want to style the first letter from each article (with CSS).

the articles usually start with a paragrah, like:

 bla bla

So how could I wrap the first letter from this text within a <span> tag ?