问:
PHP SQL SELECT sum(value) WHERE x LIKE '%$month%' (foreach)
I have a table:

```<code>user_id |       month       | value
    1   | firstname_1_2017  |   5
    1   | secondname_1_2017 |   4
    1   | firstname_2_2017  |   7
    1   | secondname_2_2017 |   8
    1   | firstname_3_2017  |   5
    1   | secondname_3_2017 |   4
    1   | firstname_4_2017  |   7
    1   | secondname_4_2017 |   8
</code>```

I need sum "value" for each month with a foreach.

firstname_1_2017 + secondname_1_2017 = 9

firstname_2_2017 + secondname_2_2017 = 15

I have an array for the months:

```<code>$array_months = array( '1','2','3','4','5','6','7','8','9','10','11','12' );
</code>```

So I wrote (in php):

```<code>SELECT sum(value)
FROM table
WHERE user_id = $user_id
AND month LIKE '%_$array_months_2017%'
</code>```

When I write a foreach, the result is the same sum of all values repeat for each month (Example: Jan 48 points, Feb 48 points, Mar 48 points...).

I'd like this result with a foreach:

You have "9" points in January

You have "15" points in February

etc...

答:
You can extract the numbers from your month column values with the SUBSTRING_INDEX() function like this, giving 3_2017.

```<code>SUBSTRING_INDEX('firstname_3_2017', '_', -2)
</code>```

You can then transform that to a date-ish string with CONCAT(), yielding 1_3_2017.

```<code>CONCAT('1_',SUBSTRING_INDEX('firstname_3_2017', '_', -2))
</code>```

Then you can turn that into an actual DATE value with STR_TO_DATE().

```<code>STR_TO_DATE(CONCAT('1_',SUBSTRING_INDEX('firstname_3_2017', '_', -2)),'%d_%m_%Y')
</code>```

Cool, now you have a datatype you can actually work with. You can now use an aggregate query to get good stuff. Leveraging Samir's fiddle: http://sqlfiddle.com/#!9/8aabd/6/0

```<code>SELECT
  SUM(value) value,
  user_id,
  STR_TO_DATE(CONCAT('1_',SUBSTRING_INDEX(month, '_', -2)),'%d_%m_%Y') month_begin
  FROM table
 GROUP BY user_id, STR_TO_DATE(CONCAT('1_',SUBSTRING_INDEX(month, '_', -2)),'%d_%m_%Y')
</code>```

Summary: simple transformations of your month column can give you usable information.

Pro tip: when designing your tables try not to stuff values with different meanings into single columns. Read about normalization.

Pro tip 2: use actual DATE, TIMESTAMP, or DATETIME values for storing time-based information whenever possible. Date arithmetic and date-based indexing are powerful parts of DBMS servers.

Body:
I have a table:

user_id |       month       | value
    1   | firstname_1_2017  |   5
    1   | secondname_1_2017 |   4
    1   | firstname_2_2017  |   7
    1   | secondname_2_2017 |   8
    1   | firstname_3_2017  |   5
    1   | secondname_3_2017 |   4
    1   | firstname_4_2017  |   7
    1   | secondname_4_2017 |   8

I need sum "value" for each month with a foreach.

firstname_1_2017 + secondname_1_2017 = 9

firstname_2_2017 + secondname_2_2017 = 15

I have an array for the months:

$array_months = array( '1','2','3','4','5','6','7','8','9','10','11','12' );

So I wrote (in php):

SELECT sum(value)
FROM table
WHERE user_id = $user_id
AND month LIKE '%_$array_months_2017%'

When I write a foreach, the result is the same sum of all values repeat for each month (Example: Jan 48 points, Feb 48 points, Mar 48 points...).

I'd like this result with a foreach:

You have "9" points in January

You have "15" points in February

etc...

Body:
You can extract the numbers from your month column values with the SUBSTRING_INDEX() function like this, giving 3_2017.

SUBSTRING_INDEX('firstname_3_2017', '_', -2)

You can then transform that to a date-ish string with CONCAT(), yielding 1_3_2017.

CONCAT('1_',SUBSTRING_INDEX('firstname_3_2017', '_', -2))

Then you can turn that into an actual DATE value with STR_TO_DATE().

STR_TO_DATE(CONCAT('1_',SUBSTRING_INDEX('firstname_3_2017', '_', -2)),'%d_%m_%Y')

Cool, now you have a datatype you can actually work with. You can now use an aggregate query to get good stuff. Leveraging Samir's fiddle: http://sqlfiddle.com/#!9/8aabd/6/0

SELECT
  SUM(value) value,
  user_id,
  STR_TO_DATE(CONCAT('1_',SUBSTRING_INDEX(month, '_', -2)),'%d_%m_%Y') month_begin
  FROM table
 GROUP BY user_id, STR_TO_DATE(CONCAT('1_',SUBSTRING_INDEX(month, '_', -2)),'%d_%m_%Y')

Summary: simple transformations of your month column can give you usable information.

Pro tip: when designing your tables try not to stuff values with different meanings into single columns. Read about normalization.

Pro tip 2: use actual DATE, TIMESTAMP, or DATETIME values for storing time-based information whenever possible. Date arithmetic and date-based indexing are powerful parts of DBMS servers.


来源: stackexchange

问:
SQL data retrieve - C#
how do i retrieve data from a table within a loop or something. That means I want to retrieve row by row at a time. but the sequence of rows may differ.
For example, 1st time i want 5rd row,then 2nd, then 9...so on.

I searched it through the internet. I got only two answers.

Use several SqlConnection objects.

reader= sqlCommand.ExecuteReader();
While(reader.Read()){
    reader["Column Name"].ToString();
}

If you got my problem, please help me
Thank you.

答:
It's probably best to read your data into a DataSet, as shown in this example:

http://quickstart.developerfusion.co.uk/quickstart/howto/doc/adoplus/GetDataFromDB.aspx

ContentLicense: CC BY-SA 2.5

Title: SQL data retrieve - C#


问:
Reshape 59x16 double into 236x4?
How can I reshape a matrix in MATLAB, preferably using reshape?

A simple matrix setup:

```<code>A = [1 4 7 10; 2 5 8 11; 3 6 9 12]
</code>```

that I want to reshape into

```<code>B = [1 4; 2 5; 3 6; 7 10; 8 11; 9 12]
</code>```

I've tried numerous settings of reshape, but I cannot figure it out.

```<code>1 2 3 4
5 6 7 8
</code>```

reshaped into

```<code>1 2
5 6
3 4
7 8
</code>```

答:
If I understand the transformation properly it is:

```<code>A = [1 4 7 10; 2 5 8 11; 3 6 9 12]
B = A(:,1:end/2);
B = [B;A(:,end/2+1:end)];
</code>```

Is this correct?

EDIT:
Or the general case:

```<code>function [B] = elefaaant(A,n)
[a,b] = size(A);
if mod(b,n) ~= 0
    error('Cannot reshape')
end
B = zeros(a*n,b/n);
fac = b/n;
for i = 1:n
    B((i-1)*a+1:i*a,:) = A(:,(i-1)*fac+1:i*fac);
end
</code>```

ContentLicense: CC BY-SA 3.0

Title: Reshape 59x16 double into 236x4?

Body:
How can I reshape a matrix in MATLAB, preferably using reshape?

A simple matrix setup:

A = [1 4 7 10; 2 5 8 11; 3 6 9 12]

that I want to reshape into

B = [1 4; 2 5; 3 6; 7 10; 8 11; 9 12]

I've tried numerous settings of reshape, but I cannot figure it out.

1 2 3 4
5 6 7 8

reshaped into

1 2
5 6
3 4
7 8

Body:
If I understand the transformation properly it is:

A = [1 4 7 10; 2 5 8 11; 3 6 9 12]
B = A(:,1:end/2);
B = [B;A(:,end/2+1:end)];

Is this correct?

EDIT:
Or the general case:

function [B] = elefaaant(A,n)
[a,b] = size(A);
if mod(b,n) ~= 0
    error('Cannot reshape')
end
B = zeros(a*n,b/n);
fac = b/n;
for i = 1:n
    B((i-1)*a+1:i*a,:) = A(:,(i-1)*fac+1:i*fac);
end


问:
Is it possible to create a custom instance type on aws
One of our applications uses a lot of memory but not much CPU. We are using m4.2xlarge, which means we have 32 GB ram & 8 cores. As per my requirement we need 4 cores and 8gb ram.I searched for these combination of instance type but i didn't get that.So,is there any chance to create custom instance type.</p>

答:
I'm afraid there is no such thing as custom EC2 instance type. You'll need to select one from the offered EC2 instance classes.

Also, your assumption about the number of cores for the m4.2xlarge instance is incorrect. An m4.2xlarge instance has 4 virtual cores, not 8. See Virtual Cores by Amazon EC2 and RDS DB Instance Type.

According to this, each vCPU is a hyperthread of an Intel Xeon core (except for T2 and m3.medium instances). AWS does not guarantee anything beyond that.

So, if you want a 4 virtual CPU (i.e., 2 virtual cores x 2 hyperthreads per core = 4 vCPU) instance with 7.5 GiB RAM, you can select the c4.xlarge instance.


问:
how to avoid duplication users in my db with php
How are you all,

hope every one here is OK,

now I have a form that the admin can create users and he can delete users as will let me display the code first

this is my code

```<code>> > <?php error_reporting(E_ALL);
>
> session_start();
>   if(!isset($_SESSION['login']) ||
> $_SESSION['login']!='1' )         {
>       header("Location:loginpage.php");
>       } ?>
>
> <!DOCTYPE html PUBLIC "-//W3C//DTD
> XHTML 1.0 Transitional//EN"
> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
> <html
> xmlns="http://www.w3.org/1999/xhtml">
> <head> <meta http-equiv="Content-Type"
> content="text/html; charset=utf-8" />
> <title>My Control panel</title> <link
> href="../css_style.css"
> rel="stylesheet" type="text/css" />
> </head>
>
>
>
> <body> <div id="werpper"> <div
> id="content">
>
> <div id="header">My control -
> Panel</div> <div id="body_cntent">
> <div id="left_side">   <p>Home and
> instructions</p>   <p><a
> href="../control_panel.php">main
> directory</a></p>   <p><a
> href="add_event.php">Add new
> event</a></p>   <p><a
> href="../editoccasion.php">Control
> Occasion's</a></p>   <p><a
> href="add_photos_and_occasion.php">Add
> Photos_occasion</a></p>   <p><a
> href="../signout.php">Sign out</a></p>
> </div> <div id="right_side">
>
> <h2>Add new user</h2>
>
> <form action="" method="post">
>
> <table width="600" border="0"
> cellpadding="5" cellspacing="0">
> <tr>
>     <td width="78">User name</td>
>     <td width="2"> </td>
>     <td width="149"><input type="text" name="uname" value="" /></td>
>     <td width="332" rowspan="5" align="left" valign="top"><p
> class="red">For Administration use
> only.</p>
>       <p>You can add or delete users from <a
> href="edit_users.php">here</a><br />
>         You can't edit any user if you like to change any user account you
> can delete the user and create it
> again with the new
> information.</p></td>   </tr>   <tr>
>     <td>Password</td>
>     <td> </td>
>     <td><input type="text" name="pass" value="" /></td>
>     </tr>   <tr>
>     <td> </td>
>     <td> </td>
>     <td><input type="submit" name="submit" value="Add user" /></td>
>     </tr>   <tr>
>     <td> </td>
>     <td> </td>
>     <td> </td>
>     </tr>   <tr>
>     <td> </td>
>     <td> </td>
>     <td align="right"> </td>
>     </tr> </table> </form>
>
> </div> </div>
>
> <div id="footer"></div> </div> </div>
>
> <?php
>       if (isset($_POST['submit'])) {
>               include_once "../config/config.php";
>               $uname = $_POST['uname'];       $pass =$_POST['pass'];
>               $check = "select * from users where id = {$uname}";         $result_check
> = $db->query($check)or die($db->error);
>
>               while ($row = $result_check -> fetch_object()) {
>                       if(num_rows == 1){
>
>               echo "error";
>
>               }else{
>               $add_user = "insert into users (id, uname, pass) values ('',
> '$uname', '$pass')";
>               $result = $db -> query($add_user) or die ("$db->error");
>               if ($result) {
>                       echo "user added successfuly";
>                       }else{
>
>               echo "There was an error please try again later";
>
>               }           }       }   } ?>
>
> </body> </html>
</code>```

all I need here to know is how to solve the problem of this code

```<code>$check = "select * from users where id = {$uname}";
        $result_check = $db->query($check)or die($db->error);

        while ($row = $result_check -> fetch_object()) {

            if(num_rows == 1){

                echo "error";

                }
</code>```

how can I avoid duplication users in my db

答: In order to prevent duplicate users in your database, just do a select similar to the one you have listed before the INSERT checking to see if the user exists.  Another way however, a worse approach would be to add a UNIQUE constraint on the field in the database then your INSERT will fail upon duplication.</p>

Body:
How are you all,

hope every one here is OK,

now I have a form that the admin can create users and he can delete users as will let me display the code first

this is my code

> > <?php error_reporting(E_ALL);
>
> session_start();
>   if(!isset($_SESSION['login']) ||
> $_SESSION['login']!='1' )         {
>       header("Location:loginpage.php");
>       } ?>
>
> <!DOCTYPE html PUBLIC "-//W3C//DTD
> XHTML 1.0 Transitional//EN"
> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
>  xmlns="http://www.w3.org/1999/xhtml">
>  <meta http-equiv="Content-Type"
> content="text/html; charset=utf-8" />
> <title>My Control panel</title> <link
> href="../css_style.css"
> rel="stylesheet" type="text/css" />
>
>
>
>
>

 id="content">
>
>
My control -
> Panel

>

Home and
> instructions

 href="../control_panel.php">main
> directory

 href="add_event.php">Add new
> event

 href="../editoccasion.php">Control
> Occasion's

 href="add_photos_and_occasion.php">Add
> Photos_occasion

 href="../signout.php">Sign out

>

>
>
Add new user

>
> <form action="" method="post">
>
>
 cellpadding="5" cellspacing="0">
>

>     User name
>
>     <input type="text" name="uname" value="" />
>
 class="red">For Administration use
> only.

>
You can add or delete users from  href="edit_users.php">here

>         You can't edit any user if you like to change any user account you
> can delete the user and create it
> again with the new
> information.

>     Password
>
>     <input type="text" name="pass" value="" />
>

>
>
>     <input type="submit" name="submit" value="Add user" />
>

>
>
>
>

>
>
>
>

 </form>
>
>

>
>

>
> <?php
>       if (isset($_POST['submit'])) {
>               include_once "../config/config.php";
>               $uname = $_POST['uname'];       $pass =$_POST['pass'];
>               $check = "select * from users where id = {$uname}";         $result_check
> = $db->query($check)or die($db->error);
>
>               while ($row = $result_check -> fetch_object()) {
>                       if(num_rows == 1){
>
>               echo "error";
>
>               }else{
>               $add_user = "insert into users (id, uname, pass) values ('',
> '$uname', '$pass')";
>               $result = $db -> query($add_user) or die ("$db->error");
>               if ($result) {
>                       echo "user added successfuly";
>                       }else{
>
>               echo "There was an error please try again later";
>
>               }           }       }   } ?>
>
>

all I need here to know is how to solve the problem of this code

$check = "select * from users where id = {$uname}";
        $result_check = $db->query($check)or die($db->error);

        while ($row = $result_check -> fetch_object()) {

            if(num_rows == 1){

                echo "error";

                }

how can I avoid duplication users in my db


问:
Afdding HTML elements to zend navigation
So I wrote a class as such:

```<code>class Users_Navigation_Page_Notification extends Zend_Navigation_Page_Mvc{

    public function setLabel($label){
        if(substr($label, 0 , 1) == ':'){
            $label = 'Notification';
        }

        return parent::setLabel($label);
    }
}
</code>```

And if I try something like:

```<code>$label = 'Notification' . '<span>test</span>';
</code>```

It echo's out Notificationtest

which it shouldn't.

How do I make it render HTML elements out?

答:
Answer here https://stackoverflow.com/a/32823280/3684315 suggests using escapeLabels(false) function to disable escaping, which seems like a nicer solution.

<?= $this->navigation()->menu()->escapeLabels(false) ?>

Body:
So I wrote a class as such:

class Users_Navigation_Page_Notification extends Zend_Navigation_Page_Mvc{

    public function setLabel($label){
        if(substr($label, 0 , 1) == ':'){
            $label = 'Notification';
        }

        return parent::setLabel($label);
    }
}

And if I try something like:

$label = 'Notification' . 'test';

It echo's out Notificationtest

which it shouldn't.

How do I make it render HTML elements out?


问:
Generate all possible permutations of stenography keyboard?
Apologies in advance, because I understand roughly nothing of what goes on here, but this seemed to be the place to ask...

I'm hoping to generate all possible single simultaneous strokes from a stenography keyboard:
https://en.wikipedia.org/wiki/Stenotype#Keyboard_layout

The stenography keyboard contains 23 keys - the main 22:

```<code>STKPWHRAO*EUFRPBLGTSDZ
</code>```

If none of the AO*EU keys are included, a hyphen is used in their place, so all permutations of this sequence is also necessary:

```<code>STKPWHR-FRPBLGTSDZ
</code>```

The 23rd key is the number bar, which changes some of the keys, so permutations of these, although separate, would also help:

```<code>#12K3W4RAT50*EU6R7B8G9SDZ
#12K3W4R-6R7B8G9SDZ
</code>```

In a single simultaneous key stroke, any keys will always be recognised in the above order; they're either selected or ignored. For example, if "Z" is included, it will always be the last key of any permutation. I'm trying to generate all potential permutations, including those of individual keys.

The hyphen or asterisk in the middle of the keyboard helps differentiate between keys that are on both sides of the keyboard (S, T, P, R). For individual keys, for example, you'd list "T-" for the one on the left of the keyboard and "-T" for the one on the right of the keyboard. The entire left bank of the keyboard would be "STKPWHR-"; the entire right bank would be "-FRPBLGTSDZ".

I naively assume there's a simple way to generate this online, but ... I've been wrong before. From what I've been able to find, the main obstacle seems to be keeping the characters in sequential order. I can easily remove any duplicates, of which there would be many from the four sequences.

Even the permutations involving up to 10 keys of the 23 would be a huge help; it would be very rare that 15 or more keys would ever be used at the same time.

Any help much appreciated!

答:
I wrote a script in Python that will generate the combinations of steno order like you wanted. Some notes:

This is similar to some Plover code, which is also written in Python.

This code will generate chords with impossible combinations (unless you use a Philly shift, e.g. -SD, -TZ, -TSD, -SDZ, etc.)

I included the number bar output as well.

There are a lot of combinations…with chords ranging from 1 to 10 keys I got 1,698,159 results. For 1 to 23, there are 8,388,606 possible chords.

Here are the possible chords with 1 to 10 keys (note that this page will load slowly due to the large amount of data).

And here is the script that I used to generate this file:

from itertools import combinations
steno_order = (
    '#', 'S-', 'T-', 'K-', 'P-', 'W-', 'H-', 'R-',
    'A', 'O', '*', 'E', 'U',
    '-F', '-R', '-P', '-B', '-L', '-G', '-T', '-S', '-D', '-Z',
)
steno_to_number ={
    'S-': '1-',
    'T-': '2-',
    'P-': '3-',
    'H-': '4-',
    'A': '5',
    'O': '0',
    '-F': '-6',
    '-P': '-7',
    '-L': '-8',
    '-T': '-9',
}

def combinations_of_steno_order(min_keys, max_keys):
    assert min_keys < max_keys, 'Chord size must increase'
    for i in range(min_keys, max_keys):
        for chord in combinations(steno_order, i):
            shortform = ''
            add_hyphen = True
            if chord[0] == '#':
                # Convert to numbers if number bar is pressed.
                chord = [steno_to_number.get(steno_key, steno_key) for steno_key in chord]
            for steno_key in chord:
                if steno_key == '#':
                    shortform += steno_key
                elif steno_key[-1] == '-':
                    # Left-hand
                    shortform += steno_key[0]
                elif steno_key[0] == '-':
                    # Right-hand
                    if add_hyphen:
                        shortform += '-'
                        add_hyphen = False
                    shortform += steno_key[1]
                else:
                    # Center key
                    add_hyphen = False
                    shortform += steno_key
            yield shortform

print('\n'.join(list(combinations_of_steno_order(1, 10))))
```

Body:
Apologies in advance, because I understand roughly nothing of what goes on here, but this seemed to be the place to ask...

I'm hoping to generate all possible single simultaneous strokes from a stenography keyboard:
https://en.wikipedia.org/wiki/Stenotype#Keyboard_layout

The stenography keyboard contains 23 keys - the main 22:

STKPWHRAO*EUFRPBLGTSDZ

If none of the AO*EU keys are included, a hyphen is used in their place, so all permutations of this sequence is also necessary:

STKPWHR-FRPBLGTSDZ

The 23rd key is the number bar, which changes some of the keys, so permutations of these, although separate, would also help:

#12K3W4RAT50*EU6R7B8G9SDZ
#12K3W4R-6R7B8G9SDZ

In a single simultaneous key stroke, any keys will always be recognised in the above order; they're either selected or ignored. For example, if "Z" is included, it will always be the last key of any permutation. I'm trying to generate all potential permutations, including those of individual keys.

The hyphen or asterisk in the middle of the keyboard helps differentiate between keys that are on both sides of the keyboard (S, T, P, R). For individual keys, for example, you'd list "T-" for the one on the left of the keyboard and "-T" for the one on the right of the keyboard. The entire left bank of the keyboard would be "STKPWHR-"; the entire right bank would be "-FRPBLGTSDZ".

I naively assume there's a simple way to generate this online, but ... I've been wrong before. From what I've been able to find, the main obstacle seems to be keeping the characters in sequential order. I can easily remove any duplicates, of which there would be many from the four sequences.

Even the permutations involving up to 10 keys of the 23 would be a huge help; it would be very rare that 15 or more keys would ever be used at the same time.

Any help much appreciated!


问:
MVC Kendo Grid multiple functions for DataBound event
How can I have multiple functions for DataBound in Kendo Grid MVC

```<code>events.DataBound().Events(events => events.DataBound("AdvancedGrid.onDataBound", "alertMe"));
</code>```

so it will trig both function.

答:
Try this. It works fine for me.    </p>

```<code>.Events(ev=>{ev.DataBound(@<text>function(e){ onDataBound(e); alertMe(); }</text>); })
</code>```

Body:
How can I have multiple functions for DataBound in Kendo Grid MVC

events.DataBound().Events(events => events.DataBound("AdvancedGrid.onDataBound", "alertMe"));

so it will trig both function.

Body:
Try this. It works fine for me.

.Events(ev=>{ev.DataBound(@<text>function(e){ onDataBound(e); alertMe(); }</text>); })


问:
Excel - combining of function MATCH for multiple conditions
I have column M, which contains text. I would like to create a checker (cell M1), which would check if columns M3:M999999 contains words "Credit note" or "Internal credit note" or "Invoice correction", if so, I would like to be notified with some message, which has been shown in the cell M1.

I've tried this combination:

```<code>=IF(OR(M3:M999999="Invoice correction",M3:M999999="Internal credit note",M3:M999999="Credit note"), "NEEDS TO CHECK!", "OK")
</code>```

But it shows me error #VALUE, since it has problem the range, it works fine for 1 cell.

I tried to use it with function =MATCH but it can be used also for 1 cell only.

Do you know, how to use these or other function for multiple conditions, please? Or if the VBA would be better solution?

Thanks a lot!

答:
The problem is that the IF formula expects a check on one single cell, not an array. You will need to change the formula to make the checks in all the column with COUNTIF:

```<code>=IF(OR(COUNTIF(M3:M999999, "Invoice correction") > 0, COUNTIF(M3:M999999, "Internal credit note") > 0, COUNTIF(M3:M999999, "Credit note") > 0), "NEEDS TO CHECK!", "OK")
</code>```

Body:
I have column M, which contains text. I would like to create a checker (cell M1), which would check if columns M3:M999999 contains words "Credit note" or "Internal credit note" or "Invoice correction", if so, I would like to be notified with some message, which has been shown in the cell M1.

I've tried this combination:

=IF(OR(M3:M999999="Invoice correction",M3:M999999="Internal credit note",M3:M999999="Credit note"), "NEEDS TO CHECK!", "OK")

But it shows me error #VALUE, since it has problem the range, it works fine for 1 cell.

I tried to use it with function =MATCH but it can be used also for 1 cell only.

Do you know, how to use these or other function for multiple conditions, please? Or if the VBA would be better solution?

Thanks a lot!

Body:
The problem is that the IF formula expects a check on one single cell, not an array. You will need to change the formula to make the checks in all the column with COUNTIF:

=IF(OR(COUNTIF(M3:M999999, "Invoice correction") > 0, COUNTIF(M3:M999999, "Internal credit note") > 0, COUNTIF(M3:M999999, "Credit note") > 0), "NEEDS TO CHECK!", "OK")


问:
How to Disable UAC for my application
Well , when ever I am trying to run my application as administrator I am getting the following
error, and whether to allow or not.

If I am running the app directly and not as an administrator then this seems to work. Is there Some thing I need to do to get rid of the UAC , no I dont want user to manually change the UAC settings.

Do I need to tweak registry settings only for my programe or any certificate I need to sign with.

答:
In general, you can't disable UAC. The goal of UAC is to provide a defense in depth against malware. It would be counterproductive if an Tojan could just disable UAC.

What you can do is accept that UAC exists, and roll with it. You shouldn't usually run as Administrator, so it's perfectly fine to get a UAC dialog when you do. For instance, Auto Start can be handled as a per-user setting, which means you don't need to be an admin to change that.

Title: How to Disable UAC for my application


问:
Find (numbers) difference between two fields (numbers are comma separeted) using mysql (or maybe PHP)
I have the following table:

First column consists of all numbers that is need for the field, and the second one is some of numbers that are in the first column.

So, i should find the numbers that does not consist second column but exist in the first column.

For example, in the first row, i should return number:157, as it exists the first row, but not in the second one.

答:
So what's wrong with the following:

```<code><?php
$my_array = array
            (
              'first' => array
                         (
                           array(31,33,41,55,63,71,124,146,157,212),
                           array(55,57,70,71,72,73,74,76,124,158)
                         ),
              'second' => array
                         (
                           array(63,71,41,124,146,33,55,31,212),
                           array(71,57,70,124,158,55,76,72)
                         )
            );

for($i=0;$i<count($my_array['first']);$i++){
print_r(array_diff($my_array['first'][$i],array_intersect($my_array['first'][$i],$my_array['second'][$i])));
}

?>
</code>```

Outputs; Array ( [8] => 157 ) Array ( [5] => 73 [6] => 74 )

It's worth pointing out that I'm no PHP coder, so I'm sure there's room for considerable improvement... but you get the idea.

Body:
So what's wrong with the following:

<?php
$my_array = array
            (
              'first' => array
                         (
                           array(31,33,41,55,63,71,124,146,157,212),
                           array(55,57,70,71,72,73,74,76,124,158)
                         ),
              'second' => array
                         (
                           array(63,71,41,124,146,33,55,31,212),
                           array(71,57,70,124,158,55,76,72)
                         )
            );

for($i=0;$i<count($my_array['first']);$i++){
print_r(array_diff($my_array['first'][$i],array_intersect($my_array['first'][$i],$my_array['second'][$i])));
}

?>

Outputs; Array ( [8] => 157 ) Array ( [5] => 73 [6] => 74 )

It's worth pointing out that I'm no PHP coder, so I'm sure there's room for considerable improvement... but you get the idea.


问:
Using display:flex property to create a responsive (horizontally laid out) nav bar
For a mobile website, I have to display 5 elements in a responsive navbar. For small resolutions, I want them to pile up vertically. But for larger ones, my aim to to lay out the 5 items like so:

I'm trying to use the display:flex attribute to make this work. But unfortunately, I currently have:

How do I achieve the effect I'm looking for? It's tricky to have an elegant looking responsive navbar for 5 items (which looks balanced as well). So in case you want to suggest stylistic tweaks to the way I'm doing this, I'm open to that as well.

My code is simply:

```<code><div style="width:93%; max-width:400px;border: 1px solid #ccc;border-radius:4px;padding:5px 5px 5px 5px;background-color:#E8E8E8;box-shadow:0 1px 4px rgba(0, 0, 0, 0.1);">

<div style="display:flex;">
    <span style="font-size:12px;">Option 1</span> <span style="color:purple; font-size:12px;">({{ item_count }} items)</span>
    <span style="font-size:12px;">Option 2</span> <span style="color:purple; font-size:12px;">(({{ item_count }} items)</span>
</div>
<div style="display:flex;">
    <span style="font-size:12px;">Option 3</span> <span style="color:purple; font-size:12px;">(({{ item_count }} items)</span>
    <span style="font-size:12px;">Option 4</span> <span style="color:purple; font-size:12px;">(({{ item_count }} items)</span>
</div>

<span style="font-size:12px;">{{ other_options }} other options</span>
</div>
</code>```

The {{ }} syntax is Django template tags and can be ignored. Note that all options displayed are dynamically generated and can be of variable length.

答:
I would set a relative width and flex-wrap. For desktop devices you could then tweak the width with media queries

HTML:

```<code><div class="Wrapper">
  <div class="Item">Option 1</div>
  <div class="Item">Option 2</div>
  <div class="Item">Option 3</div>
  <div class="Item">Option 4</div>
</div>
</code>```

CSS:

```<code>.Wrapper {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  flex-wrap: wrap;
}

.Item {
  width: 50%;
}
</code>```

Body:
For a mobile website, I have to display 5 elements in a responsive navbar. For small resolutions, I want them to pile up vertically. But for larger ones, my aim to to lay out the 5 items like so:

I'm trying to use the display:flex attribute to make this work. But unfortunately, I currently have:

How do I achieve the effect I'm looking for? It's tricky to have an elegant looking responsive navbar for 5 items (which looks balanced as well). So in case you want to suggest stylistic tweaks to the way I'm doing this, I'm open to that as well.

My code is simply:

    Option 1 ({{ item_count }} items)
    Option 2 (({{ item_count }} items)

    Option 3 (({{ item_count }} items)
    Option 4 (({{ item_count }} items)

{{ other_options }} other options

The {{ }} syntax is Django template tags and can be ignored. Note that all options displayed are dynamically generated and can be of variable length.

Body:
I would set a relative width and flex-wrap. For desktop devices you could then tweak the width with media queries

HTML:

<div class="Wrapper">
  <div class="Item">Option 1</div>
  <div class="Item">Option 2</div>
  <div class="Item">Option 3</div>
  <div class="Item">Option 4</div>
</div>

CSS:

.Wrapper {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  flex-wrap: wrap;
}

.Item {
  width: 50%;
}


问:
Method hashMapOf() in Kotlin
Can anybody please give me Concrete example of hashMapOf() method and when should I use it?

If i do something like this:

```<code>val map2 : HashMap<String, String>  = hashMapOf()
    map2["ok"] = "yes"
</code>```

It means to initialize map2 property I can use it.

But like other method in Kotlin for example:

```<code>val arr = arrayListOf<String>("1", "2", "3")
</code>```

Is there any way I can use this method like above?

答:
It's simple:

```<code>val map = hashMapOf("ok" to "yes", "cancel" to "no")

print(map) // >>> {ok=yes, cancel=no}
</code>```

Method hashMapOf returns java.util.HashMap instance with the specified key-value pairs.

Under the hood:

```<code>/**
 * Creates a tuple of type [Pair] from this and [that].
 *
 * This can be useful for creating [Map] literals with less noise, for example:
 * @sample samples.collections.Maps.Instantiation.mapFromPairs
 */
public infix fun <A, B> A.to(that: B): Pair<A, B> = Pair(this, that)
</code>```

Title: Method hashMapOf() in Kotlin

Body:
Can anybody please give me Concrete example of hashMapOf() method and when should I use it?

If i do something like this:

val map2 : HashMap<String, String>  = hashMapOf()
    map2["ok"] = "yes"

It means to initialize map2 property I can use it.

But like other method in Kotlin for example:

val arr = arrayListOf<String>("1", "2", "3")

Is there any way I can use this method like above?

Body:
It's simple:

val map = hashMapOf("ok" to "yes", "cancel" to "no")

print(map) // >>> {ok=yes, cancel=no}

Method hashMapOf returns java.util.HashMap instance with the specified key-value pairs.

Under the hood:

/**
 * Creates a tuple of type [Pair] from this and [that].
 *
 * This can be useful for creating [Map] literals with less noise, for example:
 * @sample samples.collections.Maps.Instantiation.mapFromPairs
 */
public infix fun <A, B> A.to(that: B): Pair<A, B> = Pair(this, that)


问:
isset is not working on submit
This is a 5-star rating form and I am trying to make it work.

```<code><div class="stars">
  <form>
    <input class="star star-5" id="star-5" type="radio" name="star" value="5"/>
    <label class="star star-5" for="star-5"></label>
    <input class="star star-4" id="star-4" type="radio" name="star" value="4"/>
    <label class="star star-4" for="star-4"></label>
    <input class="star star-3" id="star-3" type="radio" name="star" value="3"/>
    <label class="star star-3" for="star-3"></label>
    <input class="star star-2" id="star-2" type="radio" name="star" value="2"/>
    <label class="star star-2" for="star-2"></label>
    <input class="star star-1" id="star-1" type="radio" name="star" value="1"/>
    <label class="star star-1" for="star-1"></label>
    <button class="button" type="submit" name="submit" value="submit">Submit</button>

  </form>
</div>
</code>```

When I press the submit button nothing happens. The code does not move into the if statement, though it should since submit is not longer null.

```<code><?php
if(isset($_POST['submit'])){
    $rating = $_POST['star'];
    echo "hello";
    echo $rating;
}
?>
</code>```

答:
set form method=post

if html and php code in same page use

set form action="" otherwise use

set form action=".php file"

for ex:<form method="post" action=" or .php file">

Title: isset is not working on submit

Body:
This is a 5-star rating form and I am trying to make it work.

  <form>
    <input class="star star-5" id="star-5" type="radio" name="star" value="5"/>

    <input class="star star-4" id="star-4" type="radio" name="star" value="4"/>

    <input class="star star-3" id="star-3" type="radio" name="star" value="3"/>

    <input class="star star-2" id="star-2" type="radio" name="star" value="2"/>

    <input class="star star-1" id="star-1" type="radio" name="star" value="1"/>

    <button class="button" type="submit" name="submit" value="submit">Submit</button>

  </form>

When I press the submit button nothing happens. The code does not move into the if statement, though it should since submit is not longer null.

<?php
if(isset($_POST['submit'])){
    $rating = $_POST['star'];
    echo "hello";
    echo $rating;
}
?>


问:
Styling HTML Dropdown List
I am trying to change the appearance of a dropdown for phone number extensions on my website.
Instead of all the text being unevenly spaced, it is spaced between the extension.

For example:

```<code>(+43) Austria
(+353) Ireland
(+1) United States
</code>```

Would become:

```<code>(+43)  Austria
(+353) Ireland
(+1)   United States
</code>```

I have tried simple whitespaces (as  ) and trying to separate the (+XX) and country name apart in separate  tags but to no avail.

The whitespaces have no effect and the   and spans just show up as their written code instead. Is there any way to format the dropdown to make this work? A sample of the HTML is below (the list of countries is extensive):

```<code>    <select class="countryCodeForMobile valid" id="countryCodeForMobile" name="countryCode">
    <option value="+61">(+61) Australia</option>
    <option value="+43">(+43) Austria</option>
    <option value="+32">(+32) Belgium</option>
    <option value="+55">(+55) Brazil</option>
    <option value="+1">(+1) Canada</option>
    <option value="+33">(+33) France</option>
    <option value="+49">(+49) Germany</option>
    <option value="+353">(+353) Ireland</option>
    <option value="+39">(+39) Italy</option>
    <option value="+31">(+31) Netherlands </option>
    <option value="+64">(+64) New Zealand</option>
    <option value="+48">(+48) Poland</option>
    <option value="+351">(+351) Portugal</option>
    <option value="+27">(+27) South Africa</option>
    <option value="+34">(+34) Spain</option>
    <option value="+41">(+41) Switzerland</option>
    <option selected="selected" value="+44">(+44) United Kingdom</option>
    <option value="+1">(+1) United States</option>
    </select>
</code>```

答: Nope. options are styled in a way native to the platform, and styling only a part of one doesn't work. (It usually wouldn't be a particularly good idea either.)</p>

Title: Styling HTML Dropdown List

Body:
I am trying to change the appearance of a dropdown for phone number extensions on my website.
Instead of all the text being unevenly spaced, it is spaced between the extension.

For example:

(+43) Austria
(+353) Ireland
(+1) United States

Would become:

(+43)  Austria
(+353) Ireland
(+1)   United States

I have tried simple whitespaces (as  ) and trying to separate the (+XX) and country name apart in separate  tags but to no avail.

The whitespaces have no effect and the   and spans just show up as their written code instead. Is there any way to format the dropdown to make this work? A sample of the HTML is below (the list of countries is extensive):

    <select class="countryCodeForMobile valid" id="countryCodeForMobile" name="countryCode">
    <option value="+61">(+61) Australia</option>
    <option value="+43">(+43) Austria</option>
    <option value="+32">(+32) Belgium</option>
    <option value="+55">(+55) Brazil</option>
    <option value="+1">(+1) Canada</option>
    <option value="+33">(+33) France</option>
    <option value="+49">(+49) Germany</option>
    <option value="+353">(+353) Ireland</option>
    <option value="+39">(+39) Italy</option>
    <option value="+31">(+31) Netherlands </option>
    <option value="+64">(+64) New Zealand</option>
    <option value="+48">(+48) Poland</option>
    <option value="+351">(+351) Portugal</option>
    <option value="+27">(+27) South Africa</option>
    <option value="+34">(+34) Spain</option>
    <option value="+41">(+41) Switzerland</option>
    <option selected="selected" value="+44">(+44) United Kingdom</option>
    <option value="+1">(+1) United States</option>
    </select>


答:
All items must go in the same parent container (flex container). Don't separate them into lines. Then use flex-wrap.

.container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.item {
  flex-basis: 300px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
    <span class="item">Option 1</span>
    <span class="item">Option 2</span>
    <span class="item">Option 3</span>
    <span class="item">Option 4</span>
    <span class="item">X other options</span>
</div></code>```

Feel free to change flex-basis to other value (you can use percentage like 50%), or use media queries to set it to proper value;

Title: Using display:flex property to create a responsive (horizontally laid out) nav bar

Body:
All items must go in the same parent container (flex container). Don't separate them into lines. Then use flex-wrap.

.container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.item {
  flex-basis: 300px;
}

<div class="container">
    <span class="item">Option 1</span>
    <span class="item">Option 2</span>
    <span class="item">Option 3</span>
    <span class="item">Option 4</span>
    <span class="item">X other options</span>
</div>

Feel free to change flex-basis to other value (you can use percentage like 50%), or use media queries to set it to proper value;


问:
Nth child in table not working Javascript
The td:nth-child('n') is not working over in my table it gives null in the log Where as it is working when i use children[n] it is a simple function for searching

I couldn't find the reason why it is giving out a null.. Here is the code

```<code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
    <title>Table Searching</title>
<style>
    th{
        font-weight: bolder;
    }
    table, th, td{
        font-size: 20px;
        border: 2px solid black;
        border-collapse: collapse;
    }
</style>
</head>
<body>
<input type="text" name="search">
<button class="s" onclick="Search()">Search by Name</button>
<button class="s" onclick="Search()">Search by Country</button>
<button class="s" onclick="Search()">Search by Pet</button>
<table>
    <tr>
        <th>Name</th>
        <th>Country</th>
        <th>Pet</th>
    </tr>
    <tr>
        <td>Abhi</td>
        <td>Canada</td>
        <td>koala</td>
    </tr>
    <tr>
        <td>Riya</td>
        <td>France</td>
        <td>Parrot</td>
    </tr>
    <tr>
        <td>Sid</td>
        <td>UK</td>
        <td>Pig</td>
    </tr>
    <tr>
        <td>Kritika</td>
        <td>Germany</td>
        <td>Cat</td>
    </tr>
    <tr>
        <td>Kartik</td>
        <td>China</td>
        <td>Frog</td>
    </tr>
    <tr>
        <td>Radhika</td>
        <td>India</td>
        <td>Dog</td>
    </tr>
</table>
<script>
    var input=document.getElementsByName("search")[0];
    var s=document.getElementsByClassName("s");
    var n=0;

    function Search(){
    for (var j=0; j<s.length; j++)
    {
        console.log("element");
        console.log(s[j]);
        console.log("target");
        console.log(event.target);
        if(s[j]==event.target){
            n=j;
            console.log(n);
        }
    }
        var val= input.value;
        var a=document.querySelectorAll("table > tbody > tr");
        console.log(a);
        for(var i =0; i<a.length; i++)
        {
            var d = a[i].querySelector('td:nth-child("+n+")');
            console.log(d);
            if(d.innerHTML.toLowerCase()==val.toLowerCase()){
                a[i].style.display="";
            }
            else
            {
                a[i].style.display="none";
            }
        }
    }
</script>
</body>
</html>
</code>```

答:
Here are the three reasons why you are giving out null in your code:

First, as stated by Satpal, this code 'td:nth-child("+n+")' will not replace n by its value. It's like writing td:nth-child("+n+") in css.
The solution for this is to write: 'td:nth-child(' + n + ')'. You then concatenate the value of n with the rest of the string

The value of n is an index in a array, so it starts at 0 and ends at array.length - 1. The problem is that the nth-child selector actually selects the nth-child (brilliant naming), so if n is 0 (in the case of searching by name), you'll try to select the 0th-child, wihich doesn't exist... You then have to write: 'td:nth-child(' + (n + 1) + ')' or change the definition of n

You have no
 tag in your HTML. Which means that all the content of the table will be wrapped in a tbody and your selector document.querySelectorAll("table > tbody > tr")will also selects the header of your table. To avoid that, change your HTML accordingly.

Something like that:

```<code><table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Country</th>
            <th>Pet</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Abhi</td>
            <td>Canada</td>
            <td>koala</td>
        </tr>
        <tr>
            <td>Riya</td>
            <td>France</td>
            <td>Parrot</td>
        </tr>
        <tr>
            <td>Sid</td>
            <td>UK</td>
            <td>Pig</td>
        </tr>
        <tr>
            <td>Kritika</td>
            <td>Germany</td>
            <td>Cat</td>
        </tr>
        <tr>
            <td>Kartik</td>
            <td>China</td>
            <td>Frog</td>
        </tr>
        <tr>
            <td>Radhika</td>
            <td>India</td>
            <td>Dog</td>
        </tr>
    </tbody>
</table>
</code>```

Here is a jsfiddle where the search works fine: https://jsfiddle.net/n23685b6/1/

Hope this helps!

Body:
The td:nth-child('n') is not working over in my table it gives null in the log Where as it is working when i use children[n] it is a simple function for searching

I couldn't find the reason why it is giving out a null.. Here is the code

<!DOCTYPE html>

<meta charset="utf-8">
    <title>Table Searching</title>

<input type="text" name="search">
<button class="s" onclick="Search()">Search by Name</button>
<button class="s" onclick="Search()">Search by Country</button>
<button class="s" onclick="Search()">Search by Pet</button>

        Name
        Country
        Pet

        Abhi
        Canada
        koala

        Riya
        France
        Parrot

        Sid
        UK
        Pig

        Kritika
        Germany
        Cat

        Kartik
        China
        Frog

        Radhika
        India
        Dog

Body:
Here are the three reasons why you are giving out null in your code:

First, as stated by Satpal, this code 'td:nth-child("+n+")' will not replace n by its value. It's like writing td:nth-child("+n+") in css.
The solution for this is to write: 'td:nth-child(' + n + ')'. You then concatenate the value of n with the rest of the string

The value of n is an index in a array, so it starts at 0 and ends at array.length - 1. The problem is that the nth-child selector actually selects the nth-child (brilliant naming), so if n is 0 (in the case of searching by name), you'll try to select the 0th-child, wihich doesn't exist... You then have to write: 'td:nth-child(' + (n + 1) + ')' or change the definition of n

You have no <tbody> tag in your HTML. Which means that all the content of the table will be wrapped in a tbody and your selector document.querySelectorAll("table > tbody > tr")will also selects the header of your table. To avoid that, change your HTML accordingly.

Something like that:

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Country</th>
            <th>Pet</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Abhi</td>
            <td>Canada</td>
            <td>koala</td>
        </tr>
        <tr>
            <td>Riya</td>
            <td>France</td>
            <td>Parrot</td>
        </tr>
        <tr>
            <td>Sid</td>
            <td>UK</td>
            <td>Pig</td>
        </tr>
        <tr>
            <td>Kritika</td>
            <td>Germany</td>
            <td>Cat</td>
        </tr>
        <tr>
            <td>Kartik</td>
            <td>China</td>
            <td>Frog</td>
        </tr>
        <tr>
            <td>Radhika</td>
            <td>India</td>
            <td>Dog</td>
        </tr>
    </tbody>
</table>

Here is a jsfiddle where the search works fine: https://jsfiddle.net/n23685b6/1/

Hope this helps!


问:
How to provide external url to docker image
I am working on Docker Image, I am a beginner on Docker.
I have one Docker Image, but what I want to update my Docker Image as that my Docker Image should accept the one external URL like:- and
start the further processing on it.

I do not have any clue how to do this, I am totally new on Docker and have only basic understanding of Docker.

答:
From what I can understand you want your new image to accept an external URL as a parameter and then start processing on top of it. It can be done by writing a bash script as an ENTRYPOINT script for the new image and the script will receive parameter value via CMD.

The Dockerfile will look something like:

```<code>FROM CURRENT_IMAGE
COPY custom-entrypoint.sh /root/
WORKDIR /root
ENTRYPOINT ["./custom-entrypoint.sh"]
</code>```

Build the image and now launch the container using docker run you can pass your URL as a parameter and use that in script as $1. E.g:

```<code>docker run YOUR_IMAGE MY_URL
</code>```

Body:
From what I can understand you want your new image to accept an external URL as a parameter and then start processing on top of it. It can be done by writing a bash script as an ENTRYPOINT script for the new image and the script will receive parameter value via CMD.

The Dockerfile will look something like:

FROM CURRENT_IMAGE
COPY custom-entrypoint.sh /root/
WORKDIR /root
ENTRYPOINT ["./custom-entrypoint.sh"]

Build the image and now launch the container using docker run you can pass your URL as a parameter and use that in script as $1. E.g:

docker run YOUR_IMAGE MY_URL


问:
How to check if a big decimal number can be divided by 2^x or 5^x
I have a big decimal number N (up to 100.000 digits) and I need to check if N can be divided by 2^X or 5^X ( 0 < X < 5 ).

```<code>bignumber % (2^x) == 0
</code>```

Can I get a tip? I don't have any idea.

答:
Check the number consisting of the last x digits. If it can be divided by 2^x, all number can, too. The same about 5^x.

The reason is that a decimal number with x last zeroes can always be divided by 2^x or 5^x, because it can be divided by 10^x. So, we can forget about the start digits and check only the last x ones.

For checking the divisibility use

```<code>char* number; // here the source number is put

strcopy(ending, &number[strlen(number) - x]);
long CheckedNumber = atoi(ending);

long NewCheckedNumber;
int i=0;
while (i<x){
  NewCheckedNumber = CheckedNumber / 5;
  if ( NewCheckedNumber * 5 != CheckedNumber ) return 0;
  CheckedNumber = NewCheckedNumber;
  i++;
}
return 1;
</code>```

Body:
I have a big decimal number N (up to 100.000 digits) and I need to check if N can be divided by 2^X or 5^X ( 0 < X < 5 ).

bignumber % (2^x) == 0

Can I get a tip? I don't have any idea.

Body:
Check the number consisting of the last x digits. If it can be divided by 2^x, all number can, too. The same about 5^x.

The reason is that a decimal number with x last zeroes can always be divided by 2^x or 5^x, because it can be divided by 10^x. So, we can forget about the start digits and check only the last x ones.

For checking the divisibility use

char* number; // here the source number is put

strcopy(ending, &number[strlen(number) - x]);
long CheckedNumber = atoi(ending);

long NewCheckedNumber;
int i=0;
while (i<x){
  NewCheckedNumber = CheckedNumber / 5;
  if ( NewCheckedNumber * 5 != CheckedNumber ) return 0;
  CheckedNumber = NewCheckedNumber;
  i++;
}
return 1;


问:
Xcode dynamic live update line chart
I am trying to create a line chart in which I will continuously plot data so the graph can be observed in real time updating, will be plotting around 5 points or so a second. The kind of graph I am looking for will look something like the graph shown here

https://www.vanmil.org/live-heart-rate-with-ios-and-meteor/

or

http://www.highcharts.com/demo/dynamic-update

I have been playing about with several different charting frameworks such as iOS charts, but I can't seem to get the exact graph I am looking for where live updates can be charted with an evolving X-Axis.

Using iOS charts, I managed to create a sort of evolving graph, example code below.

```<code>@IBOutlet weak var chartView: LineChartView!
var xAxisArray : [String]?
var yAxisArray : [Double]?
var date : NSDate?
var dateFormatter : NSDateFormatter?

override func viewDidLoad() {
    super.viewDidLoad()

    self.title = "Live Graph"

    let stringArray = NSMutableArray()
    let numberArray = NSMutableArray()

    dateFormatter = NSDateFormatter()
    dateFormatter!.dateFormat = "HH:mm:ss"
    date = NSDate()

    //Insert random values into chart
    for(var i = 0; i < 40; i++)
    {
        date = date!.dateByAddingTimeInterval(0.3)
        let stringDate = dateFormatter?.stringFromDate(date!)
        stringArray.addObject(stringDate!)
        let randomNum = self.randomBetweenNumbers(0.0005, secondNum: 0.0015)
        numberArray.addObject(randomNum)
    }

    xAxisArray = stringArray as NSArray as? [String]
    yAxisArray = numberArray as NSArray as? [Double]

    configureChart()
    setData()

    NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: "updateChart", userInfo: nil, repeats: true)
}

func configureChart()
{
    //Chart config
    chartView.descriptionText = ""
    chartView.noDataTextDescription = "Add Data"
    chartView.drawGridBackgroundEnabled = false
    chartView.dragEnabled = true
    chartView.rightAxis.enabled = false
    chartView.doubleTapToZoomEnabled = false
    chartView.legend.enabled = false

    //Configure xAxis
    let chartXAxis = chartView.xAxis as ChartXAxis
    chartXAxis.labelPosition = .Bottom
    chartXAxis.setLabelsToSkip(5)

    //configure yAxis

    chartView.zoom(1.0, scaleY: 1.0, x: 0.0, y: 0.0)
}

func randomBetweenNumbers(firstNum: CGFloat, secondNum: CGFloat) -> CGFloat{
    return CGFloat(arc4random()) / CGFloat(UINT32_MAX) * abs(firstNum - secondNum) + min(firstNum, secondNum)
}

func updateChart()
{
    let mutableArray = NSMutableArray()
    for(var i = 1; i < xAxisArray?.count; i++)
    {
        mutableArray.addObject(xAxisArray![i])
    }

    date = date!.dateByAddingTimeInterval(1.0)
    let str = dateFormatter!.stringFromDate(date!)
    mutableArray.addObject(str)

    xAxisArray = mutableArray as NSArray as? [String]

    //Numbers
    let numberArray = NSMutableArray()
    for(var i = 1; i < yAxisArray?.count; i++)
    {
        numberArray.addObject(yAxisArray![i])
    }

    let randomNum = self.randomBetweenNumbers(0.0005, secondNum: 0.0015)
    let convertToDouble = Double(randomNum)

    numberArray.addObject(convertToDouble)

    yAxisArray = numberArray as NSArray as? [Double]

    setData()
}

func setData()
{
    // 1 - creating an array of data entries
    var yVals1 : [ChartDataEntry] = [ChartDataEntry]()
    for var i = 0; i < xAxisArray!.count; i++ {
        yVals1.append(ChartDataEntry(value: yAxisArray![i], xIndex: i))
    }

    // 2 - create a data set with our array
    let set1: LineChartDataSet = LineChartDataSet(yVals: yVals1, label: "")

    set1.axisDependency = .Left // Line will correlate with left axis values
    set1.setColor(UIColor.blueColor().colorWithAlphaComponent(0.5)) // our line's opacity is 50%
    set1.setCircleColor(UIColor.blueColor()) // our circle will be dark red
    set1.lineWidth = 2.0
    set1.circleRadius = 6.0 // the radius of the node circle
    set1.fillAlpha = 65 / 255.0
    set1.fillColor = UIColor.blueColor()
    set1.highlightColor = UIColor.whiteColor()
    set1.drawCircleHoleEnabled = true
    set1.drawFilledEnabled = true

    //3 - create an array to store our LineChartDataSets
    var dataSets : [LineChartDataSet] = [LineChartDataSet]()
    dataSets.append(set1)

    //4 - pass our months in for our x-axis label value along with our dataSets
    let data: LineChartData = LineChartData(xVals: xAxisArray, dataSets: dataSets)

    //5 - finally set our data
    self.chartView.data = data

    //Clear text color
    chartView.data?.setValueTextColor(UIColor.clearColor())
}
</code>```

But if you try it out, you can see it is fairly jerky, plus every x axis label updates, I was hoping to have the X axis continue to evolve and just have it animate off the screen as the plotting continues like the one shown in the example.

Does anyone know any charting software that would allow me to replicate this type of graph, or if this effect can be achieved using iOS charts?

Edit:

I am trying to achieve this type of plotting example

http://www.code4app.net/ios/Dynamic-plot-curve-line-like-stock-chart/52d68b75cb7e84802f8b5340

Just hopefully a lot smoother,

答:
I have updated Chris Code to Charts 3.0

override func viewDidLoad() {
    super.viewDidLoad()

    //charts
    self.chartView.delegate = self
    let set_a: LineChartDataSet = LineChartDataSet(values:[ChartDataEntry(x: Double(0), y: Double(0))], label: "voice")
    set_a.drawCirclesEnabled = false
    set_a.setColor(UIColor.blue)

    let set_b: LineChartDataSet = LineChartDataSet(values: [ChartDataEntry(x: Double(0), y: Double(0))], label: "flow")
    set_b.drawCirclesEnabled = false
    set_b.setColor(UIColor.green)

    self.chartView.data = LineChartData(dataSets: [set_a,set_b])
    timer = Timer.scheduledTimer(timeInterval: 0.010, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
}

// add point
var i = 1
func updateCounter() {
    self.chartView.data?.addEntry(ChartDataEntry(x: Double(i), y: reading_a![i]), dataSetIndex: 0)
    self.chartView.data?.addEntry(ChartDataEntry(x:Double(i) , y:reading_b![i] ), dataSetIndex: 1)
    self.chartView.setVisibleXRange(minXRange: Double(1), maxXRange: Double(1000))
    self.chartView.notifyDataSetChanged()
    self.chartView.moveViewToX(Double(i))
    i = i + 1
}
```

ContentLicense: CC BY-SA 4.0

Title: Xcode dynamic live update line chart

Body:
I am trying to create a line chart in which I will continuously plot data so the graph can be observed in real time updating, will be plotting around 5 points or so a second. The kind of graph I am looking for will look something like the graph shown here

https://www.vanmil.org/live-heart-rate-with-ios-and-meteor/

or

http://www.highcharts.com/demo/dynamic-update

I have been playing about with several different charting frameworks such as iOS charts, but I can't seem to get the exact graph I am looking for where live updates can be charted with an evolving X-Axis.

Using iOS charts, I managed to create a sort of evolving graph, example code below.

@IBOutlet weak var chartView: LineChartView!
var xAxisArray : [String]?
var yAxisArray : [Double]?
var date : NSDate?
var dateFormatter : NSDateFormatter?

override func viewDidLoad() {
    super.viewDidLoad()

    self.title = "Live Graph"

    let stringArray = NSMutableArray()
    let numberArray = NSMutableArray()

    dateFormatter = NSDateFormatter()
    dateFormatter!.dateFormat = "HH:mm:ss"
    date = NSDate()

    //Insert random values into chart
    for(var i = 0; i < 40; i++)
    {
        date = date!.dateByAddingTimeInterval(0.3)
        let stringDate = dateFormatter?.stringFromDate(date!)
        stringArray.addObject(stringDate!)
        let randomNum = self.randomBetweenNumbers(0.0005, secondNum: 0.0015)
        numberArray.addObject(randomNum)
    }

    xAxisArray = stringArray as NSArray as? [String]
    yAxisArray = numberArray as NSArray as? [Double]

    configureChart()
    setData()

    NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: "updateChart", userInfo: nil, repeats: true)
}

func configureChart()
{
    //Chart config
    chartView.descriptionText = ""
    chartView.noDataTextDescription = "Add Data"
    chartView.drawGridBackgroundEnabled = false
    chartView.dragEnabled = true
    chartView.rightAxis.enabled = false
    chartView.doubleTapToZoomEnabled = false
    chartView.legend.enabled = false

    //Configure xAxis
    let chartXAxis = chartView.xAxis as ChartXAxis
    chartXAxis.labelPosition = .Bottom
    chartXAxis.setLabelsToSkip(5)

    //configure yAxis

    chartView.zoom(1.0, scaleY: 1.0, x: 0.0, y: 0.0)
}

func randomBetweenNumbers(firstNum: CGFloat, secondNum: CGFloat) -> CGFloat{
    return CGFloat(arc4random()) / CGFloat(UINT32_MAX) * abs(firstNum - secondNum) + min(firstNum, secondNum)
}

func updateChart()
{
    let mutableArray = NSMutableArray()
    for(var i = 1; i < xAxisArray?.count; i++)
    {
        mutableArray.addObject(xAxisArray![i])
    }

    date = date!.dateByAddingTimeInterval(1.0)
    let str = dateFormatter!.stringFromDate(date!)
    mutableArray.addObject(str)

    xAxisArray = mutableArray as NSArray as? [String]

    //Numbers
    let numberArray = NSMutableArray()
    for(var i = 1; i < yAxisArray?.count; i++)
    {
        numberArray.addObject(yAxisArray![i])
    }

    let randomNum = self.randomBetweenNumbers(0.0005, secondNum: 0.0015)
    let convertToDouble = Double(randomNum)

    numberArray.addObject(convertToDouble)

    yAxisArray = numberArray as NSArray as? [Double]

    setData()
}

func setData()
{
    // 1 - creating an array of data entries
    var yVals1 : [ChartDataEntry] = [ChartDataEntry]()
    for var i = 0; i < xAxisArray!.count; i++ {
        yVals1.append(ChartDataEntry(value: yAxisArray![i], xIndex: i))
    }

    // 2 - create a data set with our array
    let set1: LineChartDataSet = LineChartDataSet(yVals: yVals1, label: "")

    set1.axisDependency = .Left // Line will correlate with left axis values
    set1.setColor(UIColor.blueColor().colorWithAlphaComponent(0.5)) // our line's opacity is 50%
    set1.setCircleColor(UIColor.blueColor()) // our circle will be dark red
    set1.lineWidth = 2.0
    set1.circleRadius = 6.0 // the radius of the node circle
    set1.fillAlpha = 65 / 255.0
    set1.fillColor = UIColor.blueColor()
    set1.highlightColor = UIColor.whiteColor()
    set1.drawCircleHoleEnabled = true
    set1.drawFilledEnabled = true

    //3 - create an array to store our LineChartDataSets
    var dataSets : [LineChartDataSet] = [LineChartDataSet]()
    dataSets.append(set1)

    //4 - pass our months in for our x-axis label value along with our dataSets
    let data: LineChartData = LineChartData(xVals: xAxisArray, dataSets: dataSets)

    //5 - finally set our data
    self.chartView.data = data

    //Clear text color
    chartView.data?.setValueTextColor(UIColor.clearColor())
}

But if you try it out, you can see it is fairly jerky, plus every x axis label updates, I was hoping to have the X axis continue to evolve and just have it animate off the screen as the plotting continues like the one shown in the example.

Does anyone know any charting software that would allow me to replicate this type of graph, or if this effect can be achieved using iOS charts?

Edit:

I am trying to achieve this type of plotting example

http://www.code4app.net/ios/Dynamic-plot-curve-line-like-stock-chart/52d68b75cb7e84802f8b5340

Just hopefully a lot smoother,


问:
How to properly install a SSL for tomcat?
I am in need of having step by step information about installing a wildcard SSL in tomcat server. I tried suggestions in internet, even contacted the SSL provider but all are messing around, I believe my situation is complex. Check below for my setup.

The domain is purchased from www.inmotionhosting.com

The server is an Amazon EC2. I have installed Tomcat there (No Apache)

The SSL is purchased from Comodo. They sent me 2 files, "STAR_xxx_com.crt" and "STAR_xxx_com.ca-bundle". This is a wildcard SSL

Now, this is all I have. Can someone please provide the step by step instruction about what need to be done?

答: You would need the .pfx/.p12 file to add SSL support. You need to run the certificate export operation from the device where the CSR was generated. Once you have this you can refer this thread: Install SSL on EC2 Tomcat server


问:
using inline css in spfx webpart
I am trying use inline css in html content but it shows the error you see in the picture below;

How can I use inline css in spfx webpart ?

答:
<div className={`ms-Grid-col ms-u-md3`} style={{"border-color": "black"}}>
//Some Code

```

Title: using inline css in spfx webpart

Body:
<div className={`ms-Grid-col ms-u-md3`} style={{"border-color": "black"}}>
//Some Code
</div>


答:
Here is a javascript solution.

```<code>$(function(){
  $('#countryCodeForMobile option').each(function(){
    var $this = $(this),
    split = $this.text().split(' '),
    countryCode = split.shift(),
    country = split.slice(0,split.length).join(' '),
    text = countryCode.padEnd( 7, ' ').replace(/ /g, ' ') + country;
    $this.html( text );
  });
})
</code>```

It relies on a monospace typefont, though; such as courier-new.

Codepen: https://codepen.io/jamespoel/pen/WOJBeR

Title: Styling HTML Dropdown List

Body:
Here is a javascript solution.

$(function(){
  $('#countryCodeForMobile option').each(function(){
    var $this = $(this),
    split = $this.text().split(' '),
    countryCode = split.shift(),
    country = split.slice(0,split.length).join(' '),
    text = countryCode.padEnd( 7, ' ').replace(/ /g, '&nbsp;') + country;
    $this.html( text );
  });
})

It relies on a monospace typefont, though; such as courier-new.

Codepen: https://codepen.io/jamespoel/pen/WOJBeR


问:
calculate md5 of image loaded in java webdriver
I want calculate md5 of images that loaded in webdriver in java.
webdriver is Firefox.

```<code>import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.JavascriptExecutor;

String script = "var imgElement = document.querySelector('div.mtl:nth-child(2) > div:nth-child(1) > img:nth-child(1))'; *** return md5 of image *** ";
String url = "http://www.facebook.com";

WebDriver webDriver = new FirefoxDriver();
driver.get(url);
JavascriptExecutor js = (JavascriptExecutor) driver;
Stgin md5 = (String) js.executeScript(script);
</code>```

in this code, what must replace with :

*** return md5 of image ***

答:
You can use fetch with force-cache to get the content from cache. Then digest the arrayBuffer from the response. Unfortunately, MD5 is too old and the browser doesn't support it anymore. See more details about Crypto here. You can choose SHA-1, SHA-256, SHA-384, and SHA-512. See an example to digest SHA-256 below.

```<code>public void getImageSHA256(){
    driver.get("https://www.blognone.com/");
    WebElement img = driver.findElement(By.cssSelector("img"));
    String imgUrl = img.getAttribute("src").trim();
    String script = "function hex(buffer) {  var hexCodes = [];  var view = new DataView(buffer);  for (var i = 0; i < view.byteLength; i += 4) { var value = view.getUint32(i); var stringValue = value.toString(16); var padding = '00000000'; var paddedValue = (padding + stringValue).slice(-padding.length); hexCodes.push(paddedValue);  }  return hexCodes.join(\"\");}" +
    "var callback = arguments[arguments.length - 1];" +
    "fetch(arguments[0],{cache:'force-cache'}).then((response)=> {" +
        "return response.arrayBuffer(); }).then((buffer)=>{" +
            " return crypto.subtle.digest('SHA-256', buffer); }).then((hashArray)=>{" +
                " callback(hex(hashArray));"+
                "});";
    driver.manage().timeouts().setScriptTimeout(15, TimeUnit.SECONDS);
    Object response = ((JavascriptExecutor) driver).executeAsyncScript(script, imgUrl);
    System.out.println(response);
}
</code>```

Screenshot below show comparison between SHA-256 from my code and SHA-256 from an online tool.

Body:
I want calculate md5 of images that loaded in webdriver in java.
webdriver is Firefox.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.JavascriptExecutor;

String script = "var imgElement = document.querySelector('div.mtl:nth-child(2) > div:nth-child(1) > img:nth-child(1))'; *** return md5 of image *** ";
String url = "http://www.facebook.com";

WebDriver webDriver = new FirefoxDriver();
driver.get(url);
JavascriptExecutor js = (JavascriptExecutor) driver;
Stgin md5 = (String) js.executeScript(script);

in this code, what must replace with :

*** return md5 of image ***

Body:
You can use fetch with force-cache to get the content from cache. Then digest the arrayBuffer from the response. Unfortunately, MD5 is too old and the browser doesn't support it anymore. See more details about Crypto here. You can choose SHA-1, SHA-256, SHA-384, and SHA-512. See an example to digest SHA-256 below.

public void getImageSHA256(){
    driver.get("https://www.blognone.com/");
    WebElement img = driver.findElement(By.cssSelector("img"));
    String imgUrl = img.getAttribute("src").trim();
    String script = "function hex(buffer) {  var hexCodes = [];  var view = new DataView(buffer);  for (var i = 0; i < view.byteLength; i += 4) { var value = view.getUint32(i); var stringValue = value.toString(16); var padding = '00000000'; var paddedValue = (padding + stringValue).slice(-padding.length); hexCodes.push(paddedValue);  }  return hexCodes.join(\"\");}" +
    "var callback = arguments[arguments.length - 1];" +
    "fetch(arguments[0],{cache:'force-cache'}).then((response)=> {" +
        "return response.arrayBuffer(); }).then((buffer)=>{" +
            " return crypto.subtle.digest('SHA-256', buffer); }).then((hashArray)=>{" +
                " callback(hex(hashArray));"+
                "});";
    driver.manage().timeouts().setScriptTimeout(15, TimeUnit.SECONDS);
    Object response = ((JavascriptExecutor) driver).executeAsyncScript(script, imgUrl);
    System.out.println(response);
}

Screenshot below show comparison between SHA-256 from my code and SHA-256 from an online tool.


问:
SERIAL PORT doesn't accept Arabic letters?
```<code>string recievedData = ExecCommand(port, "AT", 300, "No phone connected");
recievedData = ExecCommand(port, "AT+CMGF=1", 300, "Failed to set message format.");
String command = "AT+CMGS=\"" + PhoneNo + "\"";
recievedData = ExecCommand(port, command, 300, "Failed to accept phoneNo");
command =  "عربي"+ char.ConvertFromUtf32(26) + "\r";
recievedData = ExecCommand(port, command, 3000, "Failed to send message");
</code>```

code is running very good with English
code send ???????
with arabic characters

答:
The default encoding for SerialPort is Encoding.ASCII.
You could set the encoding to UTF32. Or convert the string to bytes and send it that way.</p>

```<code>Encoding enc = new UTF8Encoding(true, true);
YourPort.Encoding = enc;

var bytes = Encoding.Unicode.GetBytes("عربي");
</code>```

Body:
string recievedData = ExecCommand(port, "AT", 300, "No phone connected");
recievedData = ExecCommand(port, "AT+CMGF=1", 300, "Failed to set message format.");
String command = "AT+CMGS=\"" + PhoneNo + "\"";
recievedData = ExecCommand(port, command, 300, "Failed to accept phoneNo");
command =  "عربي"+ char.ConvertFromUtf32(26) + "\r";
recievedData = ExecCommand(port, command, 3000, "Failed to send message");

code is running very good with English
code send ???????
with arabic characters

Body:
The default encoding for SerialPort is Encoding.ASCII.
You could set the encoding to UTF32. Or convert the string to bytes and send it that way.

Encoding enc = new UTF8Encoding(true, true);
YourPort.Encoding = enc;

var bytes = Encoding.Unicode.GetBytes("عربي");


问:
Loop to be used before function call in matlab
```<code>function output=Input(data,T)
[x,cmap]=imread('abc.tiff');

data=im2double(x);

ID_notNaN=find(~isnan(SWI));
D=data(:,1);
X=data(:,2);

F=nan(length(data(:,1)),1);
P(ID_notNaN)=SWI;
output=[data(:,1),data(:,2)];
</code>```

I want to apply the same function on all the 365 datasets I am having, but function can't work with any loop. Help me out with this

答:
Use function arrayfun, as explained in Matlab's documentation:

```<code>[B1,...,Bn] = arrayfun(Input,A1,...,An)
</code>```

where Input is the name of your function and n equals 365, the number of datasets you have.

Body:
function output=Input(data,T)
[x,cmap]=imread('abc.tiff');

data=im2double(x);

ID_notNaN=find(~isnan(SWI));
D=data(:,1);
X=data(:,2);

F=nan(length(data(:,1)),1);
P(ID_notNaN)=SWI;
output=[data(:,1),data(:,2)];

I want to apply the same function on all the 365 datasets I am having, but function can't work with any loop. Help me out with this

Body:
Use function arrayfun, as explained in Matlab's documentation:

[B1,...,Bn] = arrayfun(Input,A1,...,An)

where Input is the name of your function and n equals 365, the number of datasets you have.


问:
JavaScript - Find an object among an array of objects, inside an array of objects
I'm using Vue, lodash, etc.

```<code>{
  "street": {
    "id": "1",
    "streetName": "test",
    "buildings": [
      {
        "id": "1",
        "buildingName": "test"
      }
    ]
  }
}
</code>```

I have a setup similar to this. This is a singular object, I basically have an array of these.

All I get is a building.id value.

From it, I need to be able to find the building it belongs to, and there isn't any direct list of buildings for me to access.

Currently

I'm using a nested loop to loop through each site until I find the one that has a building with that id. I don't know if I'm doing it correctly, it doesn't feel correct.

```<code>for(var i = 0; i < streets.length; i++){
    for(var x = 0; x < streets[i].buildings.length;x++){
        if(streets[i].buildings[x].id == '2aec6bed-8cdd-4043-9041-3db4681c6d08'){

        }
    }
}
</code>```

Any tips? Thanks.

答:
Presumably you have a streets object that contains street objects, like:

```<code>var streets = [
  street :{ ...  },
  street :{ ...  },
  ...
];
</code>```

So you need to step into each street and iterate over the buildings. A for loop should be fairly efficient since it can return as soon as it finds the building. I don't think any of the built-in looping methods will do that.

The code in the OP won't work, as streets[i].buildings must be streets[i].streets.buildings and if(streets[i].buildings[x].id must be if(streets[i].street.buildings[x].id.

Below is a working for loop version, there's also a version using recent Array methods which are very much slower even on a very small dataset. According to jsperf, the for loop version is about 100 times faster in Safari, 10 times faster in Firefox and 50 times faster in Chrome.

I also think the for loop code is much more readable and therefore maintainable.

var streets = [{
      "street": {
        "id": "1",
        "streetName": "test",
        "buildings": [{
          "id": "1",
          "buildingName": "test"
        }, {
          "id": "2",
          "buildingName": "test"
        }]
      }
    }, {
      "street": {
        "id": "2",
        "streetName": "test",
        "buildings": [{
          "id": "3",
          "buildingName": "test"
        }]
      }
    }
];

function getBldById(data, id) {
  for (var i=0, iLen=streets.length; i<iLen; i++) {
    var street = streets[i].street;

    for (var j=0, jLen=street.buildings.length; j<jLen; j++) {
      if (street.buildings[j].id == id) {
        return street.buildings[j];
      }
    }
  }
  return null;
}

console.log(getBldById(streets, '1'));

function getBldById2(data, id) {
  return data.map(streetObj =>
    streetObj.street.buildings.find(building =>
      building.id === id)
    ).filter(v => v)[0];
}

console.log(getBldById2(streets, '1'));```

Body:
I'm using Vue, lodash, etc.

{
  "street": {
    "id": "1",
    "streetName": "test",
    "buildings": [
      {
        "id": "1",
        "buildingName": "test"
      }
    ]
  }
}

I have a setup similar to this. This is a singular object, I basically have an array of these.

All I get is a building.id value.

From it, I need to be able to find the building it belongs to, and there isn't any direct list of buildings for me to access.

Currently

I'm using a nested loop to loop through each site until I find the one that has a building with that id. I don't know if I'm doing it correctly, it doesn't feel correct.

for(var i = 0; i < streets.length; i++){
    for(var x = 0; x < streets[i].buildings.length;x++){
        if(streets[i].buildings[x].id == '2aec6bed-8cdd-4043-9041-3db4681c6d08'){

        }
    }
}

Any tips? Thanks.

Body:
Presumably you have a streets object that contains street objects, like:

var streets = [
  street :{ ...  },
  street :{ ...  },
  ...
];

So you need to step into each street and iterate over the buildings. A for loop should be fairly efficient since it can return as soon as it finds the building. I don't think any of the built-in looping methods will do that.

The code in the OP won't work, as streets[i].buildings must be streets[i].streets.buildings and if(streets[i].buildings[x].id must be if(streets[i].street.buildings[x].id.

Below is a working for loop version, there's also a version using recent Array methods which are very much slower even on a very small dataset. According to jsperf, the for loop version is about 100 times faster in Safari, 10 times faster in Firefox and 50 times faster in Chrome.

I also think the for loop code is much more readable and therefore maintainable.

var streets = [{
      "street": {
        "id": "1",
        "streetName": "test",
        "buildings": [{
          "id": "1",
          "buildingName": "test"
        }, {
          "id": "2",
          "buildingName": "test"
        }]
      }
    }, {
      "street": {
        "id": "2",
        "streetName": "test",
        "buildings": [{
          "id": "3",
          "buildingName": "test"
        }]
      }
    }
];

function getBldById(data, id) {
  for (var i=0, iLen=streets.length; i<iLen; i++) {
    var street = streets[i].street;

    for (var j=0, jLen=street.buildings.length; j<jLen; j++) {
      if (street.buildings[j].id == id) {
        return street.buildings[j];
      }
    }
  }
  return null;
}

console.log(getBldById(streets, '1'));

function getBldById2(data, id) {
  return data.map(streetObj =>
    streetObj.street.buildings.find(building =>
      building.id === id)
    ).filter(v => v)[0];
}

console.log(getBldById2(streets, '1'));


问:
mysqli query with joins and blanks rows
i have been developing a website where i need to join two tables and then fetch the results .

i have a database with two tables

Table 1 named with mem
Table 2 Named with Payment

now table 1 has names and drawid of all the users on website
table 2 has payments of members with payment month and draw

Draw id and draw is same in both the tables.
User has to pay for every month, and any user can pay fr any month in advance .

Now i need to fetch the total number of memebrs which have not paid the amount till the month 4th with name and the total instalments he has paid.

here is the query that i am using right now. its working good but only issue is that it is also giving me some blank results .

```<code> SELECT drawid,contact,dnd,mem.name, count(*) as numPayments,NULL
 numPaidPayments ,NULL PAID_CONTACT,NULL NAME_PAID FROM mem
 LEFT JOIN payment ON (mem.drawid = payment.draw) GROUP BY
  drawid HAVING numPayments < 4
  UNION
  SELECT NULL drawid,NULL contact, NULL dnd, NULL name,NULL
  numPayments,COUNT(*) as numPaidPayments ,contact PAID_CONTACT,mem.name
  NAME_PAID  FROM mem
   INNER JOIN payment ON (mem.drawid = payment.draw) GROUP BY
  drawid HAVING numPaidPayments >= 4
</code>```

I know it is because of using the NULL in query but i have less idea how to make it work without using NULL and get all non blank results ..

When i dont use NULL i get repeated results .

i am stuck here !!!

答: Use as between NULL and the rowname.

Title: mysqli query with joins and blanks rows

Body:
i have been developing a website where i need to join two tables and then fetch the results .

i have a database with two tables

Table 1 named with mem
Table 2 Named with Payment

now table 1 has names and drawid of all the users on website
table 2 has payments of members with payment month and draw

Draw id and draw is same in both the tables.
User has to pay for every month, and any user can pay fr any month in advance .

Now i need to fetch the total number of memebrs which have not paid the amount till the month 4th with name and the total instalments he has paid.

here is the query that i am using right now. its working good but only issue is that it is also giving me some blank results .

 SELECT drawid,contact,dnd,mem.name, count(*) as numPayments,NULL
 numPaidPayments ,NULL PAID_CONTACT,NULL NAME_PAID FROM mem
 LEFT JOIN payment ON (mem.drawid = payment.draw) GROUP BY
  drawid HAVING numPayments < 4
  UNION
  SELECT NULL drawid,NULL contact, NULL dnd, NULL name,NULL
  numPayments,COUNT(*) as numPaidPayments ,contact PAID_CONTACT,mem.name
  NAME_PAID  FROM mem
   INNER JOIN payment ON (mem.drawid = payment.draw) GROUP BY
  drawid HAVING numPaidPayments >= 4

I know it is because of using the NULL in query but i have less idea how to make it work without using NULL and get all non blank results ..

When i dont use NULL i get repeated results .

i am stuck here !!!

Body: Use as between NULL and the rowname.


问:
Per project sbt repositories/config
I work with a variety of SBT projects and not all of them share the same repositories/resolvers. I would like to be able to store the repositories configuration inside each project so that I can also build other people's projects without overriding the default (or theirs) repositories and sbt configuration.

Using the ~/.sbt/repositories is not an option since that is per user and not per project. I have tried passing parameters to sbt and that works; e.g. sbt compile -Dsbt.boot.properties=build/sbt.boot.properties. However, that requires people to remember this flag and type it/alias it every time.

Is there any way to get sbt to read configuration, or flags like the above, from its current directory? Thanks!

答:
Have you tried http://www.scala-sbt.org/0.13/docs/Resolvers.html?

Resolvers for Maven2 repositories are added as follows:

resolvers += "Sonatype OSS Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots"

This is the most common kind of user-defined resolvers. The rest of
  this page describes how to define other types of repositories.

Title: Per project sbt repositories/config


问:
react-native text doesn't align
My text component doesn't align when the text is more than 2 lines (see screenshot). I have tried playing around with alignment and ellipsizeMode but none of the settings change anything. Why is the 2nd line indented?

My code:

```<code><View style={{ flex: 4, flexDirection: 'row', marginTop: 10}}>
  <View style={{ flex: 1, alignItems: 'flex-end' }}>
    <CircleIndicator style={{marginRight: 29}} />
    <View
      style={{
        width: 4,
        height: '100%',
        backgroundColor: styles.colors.lipstick,
        marginRight: 35,
      }}
    />
  </View>
  <View style={{ flex: 2 }}>
    <View style={{ flex: 1 }}>
      <Text weight='bold' color='darkIndigo'> {activityType} </Text>
    </View>
    <View style={{ flex: 1 }}>
      <Text color='blueyGrey' style={{opacity: 0.5}}> {activityDate}
      </Text>
    </View>
    <View style={{ flex: 1, marginBottom: 30 }}>
      <Text color='blueyGrey'> {activityDescription} </Text>
    </View>
  </View>
  <View style={{ flex: 1 }} >
    <Text weight='bold' color='lipstick'> {activityPoints} PTS </Text>
  </View>
</View>
</code>```

答:
So I left this issue alone for a couple of days and revisited it. The reason for the misalignment was this:

```<code><Text color='blueyGrey'> {activityDescription} </Text>
</code>```

Changed it to:

```<code><Text color='blueyGrey'>{activityDescription}</Text>
</code>```

Such a rookie mistake :D

Title: react-native text doesn't align

Body:
My text component doesn't align when the text is more than 2 lines (see screenshot). I have tried playing around with alignment and ellipsizeMode but none of the settings change anything. Why is the 2nd line indented?

My code:

<View style={{ flex: 4, flexDirection: 'row', marginTop: 10}}>
  <View style={{ flex: 1, alignItems: 'flex-end' }}>
    <CircleIndicator style={{marginRight: 29}} />
    <View
      style={{
        width: 4,
        height: '100%',
        backgroundColor: styles.colors.lipstick,
        marginRight: 35,
      }}
    />
  </View>
  <View style={{ flex: 2 }}>
    <View style={{ flex: 1 }}>
      <Text weight='bold' color='darkIndigo'> {activityType} </Text>
    </View>
    <View style={{ flex: 1 }}>
      <Text color='blueyGrey' style={{opacity: 0.5}}> {activityDate}
      </Text>
    </View>
    <View style={{ flex: 1, marginBottom: 30 }}>
      <Text color='blueyGrey'> {activityDescription} </Text>
    </View>
  </View>
  <View style={{ flex: 1 }} >
    <Text weight='bold' color='lipstick'> {activityPoints} PTS </Text>
  </View>
</View>

Body:
So I left this issue alone for a couple of days and revisited it. The reason for the misalignment was this:

<Text color='blueyGrey'> {activityDescription} </Text>

Changed it to:

<Text color='blueyGrey'>{activityDescription}</Text>

Such a rookie mistake :D


问:
Why increasing number of workers (more than number of cores) still decrease execution time?
I always sure that there is no point to have more threads/processes than CPU cores (from the performance perspective). However, my python sample shows me a different result.

```<code>import concurrent.futures
import random
import time

def doSomething(task_num):
    print("executing...", task_num)
    time.sleep(1)  # simulate heavy operation that takes ~ 1 second
    return random.randint(1, 10) * random.randint(1, 500)  # real operation, used random to avoid caches and so on...

def main():
    # This part is not taken in consideration because I don't want to
    # measure the worker creation time
    executor = concurrent.futures.ProcessPoolExecutor(max_workers=60)

    start_time = time.time()

    for i in range(1, 100): # execute 100 tasks
        executor.map(doSomething, [i, ])
    executor.shutdown(wait=True)

    print("--- %s seconds ---" % (time.time() - start_time))

if __name__ == '__main__':
    main()
</code>```

Program results:

1 WORKER  --- 100.28233647346497 seconds ---

  2 WORKERS --- 50.26122164726257 seconds ---

  3 WORKERS --- 33.32741022109985 seconds ---

  4 WORKERS --- 25.399883031845093 seconds ---

  5 WORKERS --- 20.434186220169067 seconds ---

  10 WORKERS--- 10.903695344924927 seconds ---

  50 WORKERS--- 6.363946914672852 seconds ---

  60 WORKERS--- 4.819359302520752 seconds ---

How this can work faster having just 4 Logical processors ?

Here is my Computer specifications (Tested on Windows 8 and Ubuntu 14):

CPU Intel(R) Core(TM) i5-3210M CPU @ 2.50GHz
   Sockets: 1
   Cores:   2
   Logical processors:    4

答:
I extended your example with a more intensive computation (eg. matrix inversion). You will see what you expected: the computation time will decrease to the number of cores and increase afterwards (because of the cost of context switching). </p>

```<code>import concurrent.futures
import random
import time
import numpy as np
import matplotlib.pyplot as plt

def doSomething(task_num):
    print("executing...", task_num)
    for i in range(100000):
        A = np.random.normal(0,1,(1000,1000))
        B = np.inv(A)

    return random.randint(1, 10) * random.randint(1, 500)  # real operation, used random to avoid caches and so on...

def measureTime(nWorkers: int):
    executor = concurrent.futures.ProcessPoolExecutor(max_workers=nWorkers)
    start_time = time.time()
    for i in range(1, 40):  # execute 100 tasks
        executor.map(doSomething, [i, ])
    executor.shutdown(wait=True)
    return (time.time() - start_time)

def main():
    # This part is not taken in consideration because I don't want to
    # measure the worker creation time
    maxWorkers = 20
    dT = np.zeros(maxWorkers)
    for i in range(maxWorkers):
        dT[i] = measureTime(i+1)
        print("--- %s seconds ---" % dT[i])
    plt.plot(np.linspace(1,maxWorkers, maxWorkers), dT)
    plt.show()

if __name__ == '__main__':
    main()
</code>```

Body:
I always sure that there is no point to have more threads/processes than CPU cores (from the performance perspective). However, my python sample shows me a different result.

import concurrent.futures
import random
import time

def doSomething(task_num):
    print("executing...", task_num)
    time.sleep(1)  # simulate heavy operation that takes ~ 1 second
    return random.randint(1, 10) * random.randint(1, 500)  # real operation, used random to avoid caches and so on...

def main():
    # This part is not taken in consideration because I don't want to
    # measure the worker creation time
    executor = concurrent.futures.ProcessPoolExecutor(max_workers=60)

    start_time = time.time()

    for i in range(1, 100): # execute 100 tasks
        executor.map(doSomething, [i, ])
    executor.shutdown(wait=True)

    print("--- %s seconds ---" % (time.time() - start_time))

if __name__ == '__main__':
    main()

Program results:

1 WORKER  --- 100.28233647346497 seconds ---

  2 WORKERS --- 50.26122164726257 seconds ---

  3 WORKERS --- 33.32741022109985 seconds ---

  4 WORKERS --- 25.399883031845093 seconds ---

  5 WORKERS --- 20.434186220169067 seconds ---

  10 WORKERS--- 10.903695344924927 seconds ---

  50 WORKERS--- 6.363946914672852 seconds ---

  60 WORKERS--- 4.819359302520752 seconds ---

How this can work faster having just 4 Logical processors ?

Here is my Computer specifications (Tested on Windows 8 and Ubuntu 14):

CPU Intel(R) Core(TM) i5-3210M CPU @ 2.50GHz
   Sockets: 1
   Cores:   2
   Logical processors:    4

Body:
I extended your example with a more intensive computation (eg. matrix inversion). You will see what you expected: the computation time will decrease to the number of cores and increase afterwards (because of the cost of context switching).

import concurrent.futures
import random
import time
import numpy as np
import matplotlib.pyplot as plt

def doSomething(task_num):
    print("executing...", task_num)
    for i in range(100000):
        A = np.random.normal(0,1,(1000,1000))
        B = np.inv(A)

    return random.randint(1, 10) * random.randint(1, 500)  # real operation, used random to avoid caches and so on...

def measureTime(nWorkers: int):
    executor = concurrent.futures.ProcessPoolExecutor(max_workers=nWorkers)
    start_time = time.time()
    for i in range(1, 40):  # execute 100 tasks
        executor.map(doSomething, [i, ])
    executor.shutdown(wait=True)
    return (time.time() - start_time)

def main():
    # This part is not taken in consideration because I don't want to
    # measure the worker creation time
    maxWorkers = 20
    dT = np.zeros(maxWorkers)
    for i in range(maxWorkers):
        dT[i] = measureTime(i+1)
        print("--- %s seconds ---" % dT[i])
    plt.plot(np.linspace(1,maxWorkers, maxWorkers), dT)
    plt.show()

if __name__ == '__main__':
    main()


答:
Because you have two observations at the same time (5+4=9). Try this:

```<code>ggplot(data = df, aes(x = date, y = output))+
  geom_bar(stat="identity", position = "dodge")
</code>```

Edit: Or as suggested by @MbrMbr in the comments:

```<code>ggplot(data = df, aes(x = date, y = output))+
  geom_col(position = "dodge")
</code>```

Title: geom_col plots data in a wrong way

Body:
I have an issue with ggplot.
Data:

df <- structure(list(date = structure(c(1499050800, 1499054400, 1499058000,
1499061600, 1499065200, 1499068800, 1499072400, 1499076000, 1499079600,
1499083200, 1499086800, 1499090400, 1499094000, 1499097600, 1499101200,
1499104800, 1499108400, 1499112000, 1499115600, 1499119200, 1499122800,
1499126400, 1499130000, 1499133600, 1499137200, 1499140800, 1499144400,
1499144400, 1499148000, 1499151600, 1499155200, 1499158800, 1499162400,
1499166000), class = c("POSIXct", "POSIXt"), tzone = "UTC"),
    output = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0)), .Names = c("date",
"output"), row.names = c(NA, -34L), class = c("tbl_df", "tbl",
"data.frame"))

Plot:

ggplot()+
  geom_col(data = df, aes(x = date, y = output))

Value of 5 is plotted as 8.

Body:
Because you have two observations at the same time (5+4=9). Try this:

ggplot(data = df, aes(x = date, y = output))+
  geom_bar(stat="identity", position = "dodge")

Edit: Or as suggested by @MbrMbr in the comments:

ggplot(data = df, aes(x = date, y = output))+
  geom_col(position = "dodge")