问:
How can I move up a
 using bootstrap?
Q1

How can I move the background image

 up so the image is under the navigation bar using bootstrap.

I have tried using float and display: flex.However, it doesn't seem to work.

Site code

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
   <head>
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/fullPage.js/2.9.4/jquery.fullpage.min.js"></script>
   </head>

   <body>
      <nav class="navbar navbar-default navbar-fixed-top">
         <div class="container-fluid">
            <div class="navbar-header">
               <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
               <span class="sr-only">Toggle navigation</span>
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
               </button>
               <img src="http://i1126.photobucket.com/albums/l611/ldocherty1/logo1_zpsep8qps5m.png" alt="Logo design">
               <h1 class="nav-title centre-block">Liam Docherty's Digital Portfolio</h1>
            </div>
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
               <ul class="nav navbar-nav">
                  <li>Home
                  </li>
                  <li class="dropdown">
                     Units <span class="caret"></span>
                     <ul class="dropdown-menu">
                        <li>Unit 6
                        </li>
                        <li>Unit 14
                        </li>
                        <li>Unit 7
                        </li>
                        <li>Unit 1
                        </li>
                     </ul>
                  </li>
                  <li class="dropdown">
                     About <span class="caret"></span>
                     <ul class="dropdown-menu">
                        <li>About Me
                        </li>
                        <li>CV
                        </li>
                        <li>Education
                        </li>
                     </ul>
                  </li>
                  <li>Contact Me
                  </li>
               </ul>
            </div>
         </div>
      </nav>
      <div id="sections">
         <div class="section one">
            <div class="shape"></div>
            <div class="hero"></div>
            <h1 class="s1-text center-block">WELCOME TO MY</h1>
            <h1 class="s2-text center-block">PORTFOLIO</h1>
             <i class="fa fa-angle-down" style="font-size:100px;"></i>
         </div>
         <section id="contact-me" class="section two">
             <i class="fa fa-angle-up" style="font-size:100px;"></i>
      </div>
      <script>
         $(document).ready(function() {
           $('#sections').fullpage();
         });
      </script>
   </body>
</html></code>```

答:
I think you want to add the background image to the whole section one. just try this--add the hero class to your class="section one". Don't add margin.

snippet

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
   <head>
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/fullPage.js/2.9.4/jquery.fullpage.min.js"></script>
   </head>

   <body>
      <nav class="navbar navbar-default navbar-fixed-top">
         <div class="container-fluid">
            <div class="navbar-header">
               <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
               <span class="sr-only">Toggle navigation</span>
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
               </button>
               <img src="http://i1126.photobucket.com/albums/l611/ldocherty1/logo1_zpsep8qps5m.png" alt="Logo design">
               <h1 class="nav-title centre-block">Liam Docherty's Digital Portfolio</h1>
            </div>
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
               <ul class="nav navbar-nav">
                  <li>Home
                  </li>
                  <li class="dropdown">
                     Units <span class="caret"></span>
                     <ul class="dropdown-menu">
                        <li>Unit 6
                        </li>
                        <li>Unit 14
                        </li>
                        <li>Unit 7
                        </li>
                        <li>Unit 1
                        </li>
                     </ul>
                  </li>
                  <li class="dropdown">
                     About <span class="caret"></span>
                     <ul class="dropdown-menu">
                        <li>About Me
                        </li>
                        <li>CV
                        </li>
                        <li>Education
                        </li>
                     </ul>
                  </li>
                  <li>Contact Me
                  </li>
               </ul>
            </div>
         </div>
      </nav>
      <div id="sections">
         <div class="section one hero">
            <div class="shape"></div>

            <h1 class="s1-text center-block">WELCOME TO MY</h1>
            <h1 class="s2-text center-block">PORTFOLIO</h1>
             <i class="fa fa-angle-down" style="font-size:100px;"></i>
         </div>
         <section id="contact-me" class="section two">
             <i class="fa fa-angle-up" style="font-size:100px;"></i>
      </div>
      <script>
         $(document).ready(function() {
           $('#sections').fullpage();
         });
      </script>
   </body>
</html></code>```

Title: How can I move up a <div> using bootstrap?

Body:
Q1

How can I move the background image

 up so the image is under the navigation bar using bootstrap.

I have tried using float and display: flex.However, it doesn't seem to work.

Site code

<!DOCTYPE html>

      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

               <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
               Toggle navigation

               </button>

Liam Docherty's Digital Portfolio

Home

                     Units

Unit 6

Unit 14

Unit 7

Unit 1

                     About

About Me

CV

Education

Contact Me

WELCOME TO MY

PORTFOLIO

Body:
I think you want to add the background image to the whole section one. just try this--add the hero class to your class="section one". Don't add margin.

snippet

<style>
      .body {
      font-family: 'Roboto', sans-serif;
      color: black;
      }
      .navbar.navbar-default {
      background-color: #FFFFFF;
      height: 10vh;
      z-index: 100;
      }
      .navbar.navbar-default ul {
      list-style-type: none;
      text-align: right;
      }
      .navbar.navbar-default ul li {
      display: inline-block;
      }
      .dropdown-menu li {
      text-align: center;
      }
      .dropdown .dropdown-menu {
      background-color: #FFFFFF;
      }
      .dropdown .dropdown-menu a {
      color: white;
      }
      .navbar.navbar-default ul li a {
      display: inline-block;
      padding: 3.5vh 8px 4px;
      color: black;
      text-decoration: none;
      font-size: 14pt;
      }
      .navbar.navbar-default ul li:after {
      content: '';
      position: absolute;
      right: 50%;
      bottom: 0;
      left: 50%;
      height: 3px;
      background-color: black;
      border-radius: 9px;
      transition: all .2s;
      }
      .nav.navbar-nav,
      .nav.navbar-nav>li {
      float: none;
      }
      .navbar.navbar-default ul li:hover:after {
      right: 0;
      left: 0;
      }
      .navbar.navbar-default ul.dropdown-menu li,
      .navbar.navbar-default ul.dropdown-menu li a {
      position: relative;
      display: block;
      }
      .section {
      min-height: 100vh;
      }
      .one {
      background-color: #FFFFFF;
      }
      .two {
      background-color: #FFFFFF;
      }
      #sections .section {
      padding-top: 50px;
      }
      .hero {
      background: url("https://static.pexels.com/photos/38892/pexels-photo-38892.jpeg") center center no-repeat;
      background-attachment: fixed;
      background-size: cover;
      width: 100%;
      max-width: 100%;
      width: 100vw;
      height: 60%;
      }
      .shape {
      border-radius: 25px;
      background: #4D5061;
      content: url(http://i1126.photobucket.com/albums/l611/ldocherty1/IMG_0730_zpsiz4dqc47.jpg);
      color: white;
      height: 300px;
      margin: auto;
      padding: 3px;
      width: 300px;
      top: 15%;
      left: 50%;
      margin-left: -150px;
      z-index: 10;
      }
      .fa-angle-down {
      color: #0000;
      bottom: 0px;
      margin: 0 auto;
      }
      .fa-angle-up {
      color: #0000;
      bottom: 0px;
      margin: 0 auto;
      }
      .s1-text {
      text-align: center;
      color: black;
      z-index: 99;
      font-size: 18pt;
      }
      .s2-text {
      text-align: center;
      color: black;
      z-index: 99;
      font-size: 18pt;
      }
      .nav-text {
      font-size: 14pt;
      }
   </style>

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/fullPage.js/2.9.4/jquery.fullpage.min.js"></script>
   </head>

   <body>
      <nav class="navbar navbar-default navbar-fixed-top">
         <div class="container-fluid">
            <div class="navbar-header">
               <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
               <span class="sr-only">Toggle navigation</span>
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
               <span class="icon-bar"></span>
               </button>
               <a class="navbar-brand" href="http://i1126.photobucket.com/albums/l611/ldocherty1/logo1_zpsep8qps5m.png"><img src="http://i1126.photobucket.com/albums/l611/ldocherty1/logo1_zpsep8qps5m.png" alt="Logo design"></a>
               <h1 class="nav-title centre-block">Liam Docherty's Digital Portfolio</h1>
            </div>
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
               <ul class="nav navbar-nav">
                  <li><a href="#">Home</a>
                  </li>
                  <li class="dropdown">
                     <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="true">Units <span class="caret"></span></a>
                     <ul class="dropdown-menu">
                        <li><a href="#">Unit 6</a>
                        </li>
                        <li><a href="#section3">Unit 14</a>
                        </li>
                        <li><a href="#">Unit 7</a>
                        </li>
                        <li><a href="#">Unit 1</a>
                        </li>
                     </ul>
                  </li>
                  <li class="dropdown">
                     <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">About <span class="caret"></span></a>
                     <ul class="dropdown-menu">
                        <li><a href="#">About Me</a>
                        </li>
                        <li><a href="#">CV</a>
                        </li>
                        <li><a href="#">Education</a>
                        </li>
                     </ul>
                  </li>
                  <li><a href="#contact-me">Contact Me</a>
                  </li>
               </ul>
            </div>
         </div>
      </nav>
      <div id="sections">
         <div class="section one hero">
            <div class="shape"></div>

            <h1 class="s1-text center-block">WELCOME TO MY</h1>
            <h1 class="s2-text center-block">PORTFOLIO</h1>
            <a href="#section two"> <i class="fa fa-angle-down" style="font-size:100px;"></i></a>
         </div>
         <section id="contact-me" class="section two">
            <a href="#section one"> <i class="fa fa-angle-up" style="font-size:100px;"></i></a>
      </div>
      <script>
         $(document).ready(function() {
           $('#sections').fullpage();
         });
      </script>
   </body>
</html>


来源: stackexchange

问:
Advanced aggregate pivot on datetime for employee status
I'm working with a table which stores timestamps for a variety of status types and i want it pivoted to get a clearer picture of each employees actual "busy" time... (so i can run work load/stats)

There are a couple of caveat's..

Employee can assign themself in progress twice by mistake (See Row 5 for EMP1 in sample data), I want the pivot to use the earliest time

Employee can either set themself as FRO or FRV  (both are variations of being free for new assignments) so whether employee is FRO or FRV it should display either of the two status types in the FREE column

Status Types:

ST = Start/Assigned

IP = Work in progress

FRV = Free in vehicle

FRO = Free in office

Sample Data for the status table:

```<code> DateTime              emp      status
 3/26/2017 14:20:30    EMP1      ST
 3/26/2017 14:21:16    EMP1      FRO
 3/26/2017 14:26:11    EMP1      ST
 3/26/2017 14:26:42    EMP1      IP
 3/26/2017 14:26:45    EMP1      IP
 3/26/2017 14:28:35    EMP1      FRO
 3/26/2017 14:21:15    EMP2      ST
 3/26/2017 14:22:35    EMP2      IP
 3/26/2017 14:55:53    EMP2      FRV
 3/26/2017 14:20:48    EMP3      ST
 3/26/2017 14:23:49    EMP3      FRV
</code>```

The desired result after the pivot would be as shown below:

(ST = Start,  IP = Work In Progress, FREE = Not busy)

```<code>emp     ST                      IP                     FREE
EMP1    3/26/2017 14:20:30      null                   3/26/2017 14:21:16
EMP1    3/26/2017 14:26:11      3/26/2017 14:26:42     3/26/2017 14:28:35
EMP2    3/26/2017 14:21:15      3/26/2017 14:22:35     3/26/2017 14:55:53
EMP3    3/26/2017 14:20:48      null                   3/26/2017 14:23:49
</code>```

test table with sample data.

```<code>CREATE TABLE test (
      [DateTime] [datetime] NULL,
      [emp] [varchar](6) NOT NULL,
      [status] [varchar](6) NOT NULL
      )

INSERT INTO test values
('2017-03-26 14:20:30.000', 'EMP1', 'ST'),
('2017-03-26 14:21:16.000', 'EMP1', 'FRO'),
('2017-03-26 14:26:11.000', 'EMP1', 'ST'),
('2017-03-26 14:26:42.000', 'EMP1', 'IP'),
('2017-03-26 14:26:45.000', 'EMP1', 'IP'),
('2017-03-26 14:28:35.000', 'EMP1', 'FRO'),
('2017-03-26 14:21:15.000', 'EMP2', 'ST'),
('2017-03-26 14:22:35.000', 'EMP2', 'IP'),
('2017-03-26 14:55:53.000', 'EMP2', 'FRV'),
('2017-03-26 14:20:48.000', 'EMP3', 'ST'),
('2017-03-26 14:23:49.000', 'EMP3', 'FRV')
</code>```

Any help much appreciated, happy to further explain if the request is too vague......

Thanks

答:
I look at this logic as:  You want to group the records based on each start.  Once you have the group, then the rest is just aggregation.

In SQL Server 2012+, assigning the group is easy . . . it is the cumulative sum of the number of starts up to each record.  In SQL Server 2008, this is trickier.  But you can do it with a correlated subquery:

```<code>select emp,
       min(case when status = 'ST' then datetime end) as st,
       min(case when status = 'IP' then datetime end) as ip,
       max(case when status in ('FRQ', 'FRV') then datetime end) as fr
from (select t.*,
             (select count(*)
              from test t2
              where t2.emp = t.emp and t2.datetime <= t.datetime and
                    t2.status = 'ST'
             ) as grp
      from test t
     ) t
group by emp, grp;
</code>```

Here is a SQL Fiddle.

ContentLicense: CC BY-SA 3.0

Body:
I'm working with a table which stores timestamps for a variety of status types and i want it pivoted to get a clearer picture of each employees actual "busy" time... (so i can run work load/stats)

There are a couple of caveat's..

Employee can assign themself in progress twice by mistake (See Row 5 for EMP1 in sample data), I want the pivot to use the earliest time

Employee can either set themself as FRO or FRV  (both are variations of being free for new assignments) so whether employee is FRO or FRV it should display either of the two status types in the FREE column

Status Types:

ST = Start/Assigned

IP = Work in progress

FRV = Free in vehicle

FRO = Free in office

Sample Data for the status table:

 DateTime              emp      status
 3/26/2017 14:20:30    EMP1      ST
 3/26/2017 14:21:16    EMP1      FRO
 3/26/2017 14:26:11    EMP1      ST
 3/26/2017 14:26:42    EMP1      IP
 3/26/2017 14:26:45    EMP1      IP
 3/26/2017 14:28:35    EMP1      FRO
 3/26/2017 14:21:15    EMP2      ST
 3/26/2017 14:22:35    EMP2      IP
 3/26/2017 14:55:53    EMP2      FRV
 3/26/2017 14:20:48    EMP3      ST
 3/26/2017 14:23:49    EMP3      FRV

The desired result after the pivot would be as shown below:

(ST = Start,  IP = Work In Progress, FREE = Not busy)

emp     ST                      IP                     FREE
EMP1    3/26/2017 14:20:30      null                   3/26/2017 14:21:16
EMP1    3/26/2017 14:26:11      3/26/2017 14:26:42     3/26/2017 14:28:35
EMP2    3/26/2017 14:21:15      3/26/2017 14:22:35     3/26/2017 14:55:53
EMP3    3/26/2017 14:20:48      null                   3/26/2017 14:23:49

test table with sample data.

CREATE TABLE test (
      [DateTime] [datetime] NULL,
      [emp] [varchar](6) NOT NULL,
      [status] [varchar](6) NOT NULL
      )

INSERT INTO test values
('2017-03-26 14:20:30.000', 'EMP1', 'ST'),
('2017-03-26 14:21:16.000', 'EMP1', 'FRO'),
('2017-03-26 14:26:11.000', 'EMP1', 'ST'),
('2017-03-26 14:26:42.000', 'EMP1', 'IP'),
('2017-03-26 14:26:45.000', 'EMP1', 'IP'),
('2017-03-26 14:28:35.000', 'EMP1', 'FRO'),
('2017-03-26 14:21:15.000', 'EMP2', 'ST'),
('2017-03-26 14:22:35.000', 'EMP2', 'IP'),
('2017-03-26 14:55:53.000', 'EMP2', 'FRV'),
('2017-03-26 14:20:48.000', 'EMP3', 'ST'),
('2017-03-26 14:23:49.000', 'EMP3', 'FRV')

Any help much appreciated, happy to further explain if the request is too vague......

Thanks

Body:
I look at this logic as:  You want to group the records based on each start.  Once you have the group, then the rest is just aggregation.

In SQL Server 2012+, assigning the group is easy . . . it is the cumulative sum of the number of starts up to each record.  In SQL Server 2008, this is trickier.  But you can do it with a correlated subquery:

select emp,
       min(case when status = 'ST' then datetime end) as st,
       min(case when status = 'IP' then datetime end) as ip,
       max(case when status in ('FRQ', 'FRV') then datetime end) as fr
from (select t.*,
             (select count(*)
              from test t2
              where t2.emp = t.emp and t2.datetime <= t.datetime and
                    t2.status = 'ST'
             ) as grp
      from test t
     ) t
group by emp, grp;

Here is a SQL Fiddle.


问:
Uploading blob in phpMyAdmin fails with "Request-URI Too Long"
I'm trying to upload a file to a mediumblob column in phpMyAdmin:

When I try to upload a 100KB jpg file it works fine, but then when I try to upload a 5500KB jpg file I get an error:

Error in Processing Request

Error code: 414

Error text: Request-URI Too Long

答:
This might be occurring because the max_packet_size has been exceeded.

Run the following query in the MySQL prompt

```<code>SET GLOBAL max_allowed_packet=<Set a bigger value here>;
</code>```

The max allowed value is 1073741824

Body:
This might be occurring because the max_packet_size has been exceeded.

Run the following query in the MySQL prompt

SET GLOBAL max_allowed_packet=<Set a bigger value here>;

The max allowed value is 1073741824


问:
AlertDialog not displaying in android studio
I have an AlertDialog in android studio as shown below:

```<code>final EditText columninput = new EditText(this);
columninput.setInputType(InputType.TYPE_CLASS_NUMBER);

AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setTitle("Choose column number");
adb.setView(columninput);
adb.setMessage("Please specify the number of columns you would like to decrypt your message with.");
adb.setCancelable(true);
adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        boolean bool = true;

        try {
            col = Integer.parseInt(columninput.getText().toString());
        }
        catch (Exception e) {
            bool = false;
            Toast t = Toast.makeText(getApplicationContext(), "Incorrect input", Toast.LENGTH_LONG);
            t.show();
        }

        if (bool) {
             dialog.dismiss();
        }
    }
});

adb.show();

method1(toRead, col);
</code>```

Note that toRead is another variable dealt with outside of this context; it should not be causing any errors. When I run my application, the AlertDialog is never shown, and method1 runs immediately. However, when I comment out the last line (method1(toRead, col)), the alertdialog appears when the application is run. Why is this, and how can I ensure that the alertDialog is always shown?

答:
This issue appears because, when you open AlertDialog, the activity goes into pause state.
So, when you hide the last line and don't call the method the activity is able to go into Pause state and the AlertDialog appears successfully.

While in the other case, when the last method is called, what happens is:

 before your AlertDialog gets created, the method1() gets called.

I hope this helps.

Body:
I have an AlertDialog in android studio as shown below:

final EditText columninput = new EditText(this);
columninput.setInputType(InputType.TYPE_CLASS_NUMBER);

AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setTitle("Choose column number");
adb.setView(columninput);
adb.setMessage("Please specify the number of columns you would like to decrypt your message with.");
adb.setCancelable(true);
adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        boolean bool = true;

        try {
            col = Integer.parseInt(columninput.getText().toString());
        }
        catch (Exception e) {
            bool = false;
            Toast t = Toast.makeText(getApplicationContext(), "Incorrect input", Toast.LENGTH_LONG);
            t.show();
        }

        if (bool) {
             dialog.dismiss();
        }
    }
});

adb.show();

method1(toRead, col);

Note that toRead is another variable dealt with outside of this context; it should not be causing any errors. When I run my application, the AlertDialog is never shown, and method1 runs immediately. However, when I comment out the last line (method1(toRead, col)), the alertdialog appears when the application is run. Why is this, and how can I ensure that the alertDialog is always shown?


问:
CodeContract.Requires(param != null) doesn't prove that param won't be null?
Hello
I have a method listed bellow:

```<code>    public static PasswordCredential Create(string password, string username, string pinCode = null)
    {
        Contract.Requires<ArgumentException>(!string.IsNullOrWhiteSpace(password), "Invalid Argument: password");
        Contract.Requires<ArgumentException>(!string.IsNullOrWhiteSpace(username), "Invalid Argument: username");

        PasswordCredential credential = new PasswordCredential();
        UTF8Encoding encoder = new UTF8Encoding();
        SHA512Managed sha512hasher = new SHA512Managed();

        credential.PasswordHash = sha512hasher.ComputeHash(encoder.GetBytes(password)); <-- Requires unproven: s != null
        credential.Username = username;
        credential.PinCode = pinCode;

        return credential;
    }
</code>```

Does this mean that Contract.Requires doesn't prove the expression? If so what's the use for it? :?

UPDATE

Ok, I found a very weird behavior of code contracts. I moved this method to another project and it worked. No more requires unproven warnings. Then I get back to the original project, and in Messages window, I found this line:
Message 1 CodeContracts: Suggested precondition: Contract.Requires(password != null);
When I double click this item, I'm navigated to PasswordCredential's PinCode property.

```<code>        [DataMember]
    public string PinCode
    {
        get { return _PinCode; }
        set { _PinCode = value == null ? null : value.Trim(); } <-- I'm navigated here
    }
</code>```

but when I click the warning item, I'm navigated to encoder.GetBytes(password) line.
I don't understand what's wrong. Is it a bug?

答:
Ok
There's an issue with CC (which can be reproduced only in my project :D). I sent the project to CC team and got very fast response. They are investigating and probably it will be fixed in the next release.
Anyway thanks for your support guys.</p>

ContentLicense: CC BY-SA 2.5

Body:
Hello
I have a method listed bellow:

    public static PasswordCredential Create(string password, string username, string pinCode = null)
    {
        Contract.Requires<ArgumentException>(!string.IsNullOrWhiteSpace(password), "Invalid Argument: password");
        Contract.Requires<ArgumentException>(!string.IsNullOrWhiteSpace(username), "Invalid Argument: username");

        PasswordCredential credential = new PasswordCredential();
        UTF8Encoding encoder = new UTF8Encoding();
        SHA512Managed sha512hasher = new SHA512Managed();

        credential.PasswordHash = sha512hasher.ComputeHash(encoder.GetBytes(password)); <-- Requires unproven: s != null
        credential.Username = username;
        credential.PinCode = pinCode;

        return credential;
    }

Does this mean that Contract.Requires doesn't prove the expression? If so what's the use for it? :?

UPDATE

Ok, I found a very weird behavior of code contracts. I moved this method to another project and it worked. No more requires unproven warnings. Then I get back to the original project, and in Messages window, I found this line:
Message 1 CodeContracts: Suggested precondition: Contract.Requires(password != null);
When I double click this item, I'm navigated to PasswordCredential's PinCode property.

        [DataMember]
    public string PinCode
    {
        get { return _PinCode; }
        set { _PinCode = value == null ? null : value.Trim(); } <-- I'm navigated here
    }

but when I click the warning item, I'm navigated to encoder.GetBytes(password) line.
I don't understand what's wrong. Is it a bug?


问:
How to give Space between rows and columns of NSCollectionView?
I have created collection view and I am unable to give space between the collection view items. So please help.... Thanks in advance...

I have used this link to create collection view https://andrehoffmann.wordpress.com/2009/08/29/nscollectionview-tutorial-for-dummies-xcode-3-1-3/

答:
You need to modify the CollectionView's layout. Probably the simplest thing to do is give it a Flow layout, and assign your properties there. Here's an example:

```<code>let layout = UICollectionViewFlowLayout()
layout.minimumInteritemSpacing = 5
layout.sectionInset = EdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
layout.minimumLineSpacing = 8
self.collectionView.collectionViewLayout = layout
</code>```

If you want to do much more than this with respect to item layout, you'll need to subclass UICollectionViewLayout and override the various layout method.

Body:
You need to modify the CollectionView's layout. Probably the simplest thing to do is give it a Flow layout, and assign your properties there. Here's an example:

let layout = UICollectionViewFlowLayout()
layout.minimumInteritemSpacing = 5
layout.sectionInset = EdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
layout.minimumLineSpacing = 8
self.collectionView.collectionViewLayout = layout

If you want to do much more than this with respect to item layout, you'll need to subclass UICollectionViewLayout and override the various layout method.


问:
Making a data structure available to all instances of a class?
I have a node data structure that represents nodes in a binary tree. I have some data that is relevant to the entire tree and rather than storing copies of it in each node, I just store indices in nodes that I use to access this global data. So my Node class has a constant property TreeData that contains the data I want available to all nodes:

```<code>classdef Node

    properties (Constant)
        treeData = TreeData
    end

    ...
    ...
end
</code>```

with TreeData being defined as

```<code>classdef TreeData < handle
    properties
        s
        w
    end
end
</code>```

This works fine, however its a nuisance having an entire extra class (TreeData) just to define two variables that should be accessible to all the nodes. So is there a better way of doing this? In another language I would just declare a static variable in the Node class to hold this data but in MATLAB it seems like you need getters and setters for static variables, which would end up leading to even more code having to be written than this TreeData class.

I don't just want something that works, I already have that, I'm looking for the most efficient/best-practice way to make a data structure available to all instances of a class in MATLAB.

答:
The easiest way might be to just define a global variable. If you use a long enough name, there's a good chance you will never have a naming conflict. Simple, yes. Best practice, no.

Matlab does have static-like variables, but they use the keyword persistent. They are local to the function where they are declared, but their values persist in memory between calls to the function. It's similar to how some other languages allow you to create static local variables for a function.

It's hard to say what the best solution is for your situation without knowing how you are using this variable. If the variable is a counter, you could create an adjustCounter function that accepts an amount to adjust the counter and returns the new value. Getting the counter value is simply a matter of telling it to adjust by 0.

Here is another similar question with several different suggested solutions.

Body:
I have a node data structure that represents nodes in a binary tree. I have some data that is relevant to the entire tree and rather than storing copies of it in each node, I just store indices in nodes that I use to access this global data. So my Node class has a constant property TreeData that contains the data I want available to all nodes:

classdef Node

    properties (Constant)
        treeData = TreeData
    end

    ...
    ...
end

with TreeData being defined as

classdef TreeData < handle
    properties
        s
        w
    end
end

This works fine, however its a nuisance having an entire extra class (TreeData) just to define two variables that should be accessible to all the nodes. So is there a better way of doing this? In another language I would just declare a static variable in the Node class to hold this data but in MATLAB it seems like you need getters and setters for static variables, which would end up leading to even more code having to be written than this TreeData class.

I don't just want something that works, I already have that, I'm looking for the most efficient/best-practice way to make a data structure available to all instances of a class in MATLAB.


问:
Maximum of Longest Increasing Sequences
I have a code that will find all the cycles of a list, e.g for [1,2,3] the cycles are [1,2,3], [2,3,1], [3,1,2]. I also have a code for finding the longest increasing subsequence.

What I want to do is input a list, find the longest increasing subsequence of every cycle of that list, and then return the maximum length out of all of these. how do I go from these two functions to finding the LIS of every cycle and then return the maximum?

Here is my code so far:

```<code>def cycles(X):

  n = len(X)

  values = []

  for i in range(0,n):
    values.append(X[i:n] + X[0:i])

  return values

def longest_increasing_subsequence(d):

    l = []

    for i in range(len(d)):

        l.append(max([l[j] for j in range(i) if l[j][-1] < d[i]] or  [[]], key=len)  + [d[i]])

    return len(max(l, key=len))
</code>```

I'd appreciate any help. thanks.

答:
Try this code:</p>

```<code>l = [3,4,5,9,8,1,2,7,7,7,7,7,7,7,6,0,1]
empty = []
one = [1]
two = [2,1]
three = [1,0,2,3]
tricky = [1,2,3,0,-2,-1]
ring = [3,4,5,0,1,2]
internal = [9,1,2,3,4,5,0]

# consider your list as a ring, continuous and infinite
def longest_increasing_subsequence(l):
    length = len(l)
    if length == 0: return 0  # list is empty
    i, tmp, longest = [0, 1, 1]
    # 1 < tmp means that ring is finished, but the sequence continue to increase
    while i < length or 1 < tmp:
        # compare elements on the ring
        if l[i%length] < l[(i+1)%length]:
            tmp += 1
        else:
            if longest < tmp: longest = tmp
            tmp = 1
        i += 1
    return longest

print("0 == " + str(longest_increasing_subsequence(empty)))
print("1 == " + str(longest_increasing_subsequence(one)))
print("2 == " + str(longest_increasing_subsequence(two)))
print("3 == " + str(longest_increasing_subsequence(three)))
print("5 == " + str(longest_increasing_subsequence(tricky)))
print("5 == " + str(longest_increasing_subsequence(internal)))
print("6 == " + str(longest_increasing_subsequence(ring)))
print("6 == " + str(longest_increasing_subsequence(l)))
</code>```

Title: Maximum of Longest Increasing Sequences

Body:
I have a code that will find all the cycles of a list, e.g for [1,2,3] the cycles are [1,2,3], [2,3,1], [3,1,2]. I also have a code for finding the longest increasing subsequence.

What I want to do is input a list, find the longest increasing subsequence of every cycle of that list, and then return the maximum length out of all of these. how do I go from these two functions to finding the LIS of every cycle and then return the maximum?

Here is my code so far:

def cycles(X):

  n = len(X)

  values = []

  for i in range(0,n):
    values.append(X[i:n] + X[0:i])

  return values

def longest_increasing_subsequence(d):

    l = []

    for i in range(len(d)):

        l.append(max([l[j] for j in range(i) if l[j][-1] < d[i]] or  [[]], key=len)  + [d[i]])

    return len(max(l, key=len))

I'd appreciate any help. thanks.

Body:
Try this code:

l = [3,4,5,9,8,1,2,7,7,7,7,7,7,7,6,0,1]
empty = []
one = [1]
two = [2,1]
three = [1,0,2,3]
tricky = [1,2,3,0,-2,-1]
ring = [3,4,5,0,1,2]
internal = [9,1,2,3,4,5,0]

# consider your list as a ring, continuous and infinite
def longest_increasing_subsequence(l):
    length = len(l)
    if length == 0: return 0  # list is empty
    i, tmp, longest = [0, 1, 1]
    # 1 < tmp means that ring is finished, but the sequence continue to increase
    while i < length or 1 < tmp:
        # compare elements on the ring
        if l[i%length] < l[(i+1)%length]:
            tmp += 1
        else:
            if longest < tmp: longest = tmp
            tmp = 1
        i += 1
    return longest

print("0 == " + str(longest_increasing_subsequence(empty)))
print("1 == " + str(longest_increasing_subsequence(one)))
print("2 == " + str(longest_increasing_subsequence(two)))
print("3 == " + str(longest_increasing_subsequence(three)))
print("5 == " + str(longest_increasing_subsequence(tricky)))
print("5 == " + str(longest_increasing_subsequence(internal)))
print("6 == " + str(longest_increasing_subsequence(ring)))
print("6 == " + str(longest_increasing_subsequence(l)))


问:
Self-disposing timer
How can I automatically dispose of, and nullify, a timer after it's elapsed?

The sender is a random object with no method; I can't dynamically access the original timer via the EventHandler.

Another function will want to check if this timer is null, or running (and interrupt it).

I could run logic such as:

if (timer != null && timer.Enabled) but I'd rather if (timer != null)

I could also instantiate the variable with a dummy timer, and simply check if this is enabled, but I know if this variable were to suddenly become null, the program would crash.

Should I just use the prior if statement; won't these timers in memory start to add up?

EDIT:

```<code>static void Main()
{
    Timer timer = null;
    timer = new Timer(5000);
    timer.Elapsed += (sender, e) => {
        var T = (Timer)sender;
        T.Dispose();
        T = null;
        Console.WriteLine(T);
    };
    timer.Start();

    while (true)
    {
        Console.WriteLine(timer);
        System.Threading.Thread.Sleep(1000);
    }
}
</code>```

答:
The sender is a random object with no method

It's not. The object is your timer. You just need to cast it back to its original type:

```<code>private void TimerTick(object sender, EventArgs e)
{
    var timer = (Timer)sender;
    timer.Enabled = false;
}
</code>```

Title: Self-disposing timer

Body:
How can I automatically dispose of, and nullify, a timer after it's elapsed?

The sender is a random object with no method; I can't dynamically access the original timer via the EventHandler.

Another function will want to check if this timer is null, or running (and interrupt it).

I could run logic such as:

if (timer != null && timer.Enabled) but I'd rather if (timer != null)

I could also instantiate the variable with a dummy timer, and simply check if this is enabled, but I know if this variable were to suddenly become null, the program would crash.

Should I just use the prior if statement; won't these timers in memory start to add up?

EDIT:

static void Main()
{
    Timer timer = null;
    timer = new Timer(5000);
    timer.Elapsed += (sender, e) => {
        var T = (Timer)sender;
        T.Dispose();
        T = null;
        Console.WriteLine(T);
    };
    timer.Start();

    while (true)
    {
        Console.WriteLine(timer);
        System.Threading.Thread.Sleep(1000);
    }
}

Body:
The sender is a random object with no method

It's not. The object is your timer. You just need to cast it back to its original type:

private void TimerTick(object sender, EventArgs e)
{
    var timer = (Timer)sender;
    timer.Enabled = false;
}


问:
Process fork in linux
```<code>#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>

int main(){
pid_t pid;
int num_coconuts = 17;
pid = fork();

if(pid == 0) {
    num_coconuts = 42;
    exit(0);
} else {
    wait(NULL);  }
}

printf("I see %d coconuts!\n", num_coconuts);
exit(0);
}
</code>```

The result is "I see 17 coconuts". Why num_coconuts did not change when pid == 0 ?

答:
Let's observe what your code does:

You set num_coconuts = 17.

You fork and get a new process.

You check if a process is the child (pid == 0) or if it is the parent (pid != 0).

In the child process you set num_coconuts = 42 but then you immediately exit.

You print num_coconuts

As you can see your child process can never reach 5. because you exit in step 4. Delete the exit() and you will get the two coconuts.

Title: Process fork in linux

Body:
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>

int main(){
pid_t pid;
int num_coconuts = 17;
pid = fork();

if(pid == 0) {
    num_coconuts = 42;
    exit(0);
} else {
    wait(NULL);  }
}

printf("I see %d coconuts!\n", num_coconuts);
exit(0);
}

The result is "I see 17 coconuts". Why num_coconuts did not change when pid == 0 ?


问:
AspectJ designator @args() not working in Spring AOP
I am learning Spring and I searched a lot about how to properly use @args() AspectJ designator but I am still not clear completely. What I know about it is that it limits joint-point matches to the execution of methods whose arguments are annoted with the given annotation types. This does not seem to work in my case.

So here goes my files:

Human.java

```<code>@Component
public class Human {
    int sleepHours;
    public int sleep(String sleepHours) {
        this.sleepHours = Integer.parseInt(sleepHours);
        System.out.println("Humans sleep for " + this.sleepHours + " hours.");
        return this.sleepHours+1;
    }
}
</code>```

Sleepable.java - Sleepable annotation

```<code> package com.aspect;
 public @interface Sleepable {

 }
</code>```

SleepingAspect.java - Aspect

```<code>@Component
@Aspect
public class SleepingAspect {

    @Pointcut("@args(com.aspect.Sleepable)")
    public void sleep(){};

    @Before("sleep()")
    public void beforeSleep() {
        System.out.println("Closing eyes before sleeping");
    }

    @AfterReturning("sleep()")
    public void afterSleep() {
        System.out.println("Opening eyes after sleep");
    }
}
</code>```

MainApp.java

```<code>public class MainApp {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        Human human = (Human) context.getBean("human");
        @Sleepable
        String sleepHours = "8";
        human.sleep(sleepHours);
    }
}
</code>```

Output

Humans sleep for 8 hours.

Expected Output

Closing eyes before sleeping

Humans sleep for 8 hours.

Opening eyes after sleep

答:
You have several mistakes in your code:

Spring AOP can only intercept method calls upon Spring components. What you are trying to intercept is an annotation on a local variable. Not even the much more powerful AspectJ can intercept anything concerning local variables, only read/write access to class members. Thus, what you are trying to do is impossible. And by the way, it is bad application design. Why would anyone want to rely on method internals when trying to apply cross-cutting behaviour? Method internals are subject to frequent refactoring. Suggestion: Put your annotation on method public int sleep(String sleepHours).

Your annotation is invisible during runtime because your forgot to add a meta annotation like @Retention(RetentionPolicy.RUNTIME).

@args is the wrong pointcut type. It captures method arguments the types of which are annotated. You want to use @annotation(com.aspect.Sleepable) instead.

I think you should not try a copy & paste cold start with Spring AOP but read the Spring AOP manual first. Everything I explained here can be found there.

Update: So according to you comments you were just practicing and trying to make up an example for @args(). Here is one in plain AspectJ. You can easily use it in similar form in Spring AOP. The @Before advice shows you how to match on an argument with an annotation on its class, the @After advice also shows how to bind the corresponding annotation to an advice argument.

Annotation + class using it:

package com.company.app;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {}
```

<pre class="lang-java prettyprint-override"><code>package com.company.app;

@MyAnnotation
public class MyClass {}
</code>```

Driver application:

package com.company.app;

public class Application {
  public static void main(String[] args) {
    new Application().doSomething(new MyClass(), 11);
  }

  public String doSomething(MyClass myClass, int i) {
    return "blah";
  }
}
```

<p>As you can see, here we use the annotated class <code>MyClass</code> in a method argument. This can be matched with <code>@args()</code> in the following aspect.</p>

<p><strong>Aspect:</strong></p>

<pre class="lang-java prettyprint-override"><code>package com.company.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

import com.company.app.MyAnnotation;

@Aspect
public class MyAspect {
  @Before("@args(com.company.app.MyAnnotation, ..)")
  public void myBeforeAdvice(JoinPoint thisJoinPoint) {
    System.out.println("Before " + thisJoinPoint);
  }

  @After("@args(myAnnotation, ..)")
  public void myAfterAdvice(JoinPoint thisJoinPoint, MyAnnotation myAnnotation) {
    System.out.println("After " + thisJoinPoint + " -> " + myAnnotation);
  }
}
</code>```

Console log:

Before call(String com.company.app.Application.doSomething(MyClass, int))
Before execution(String com.company.app.Application.doSomething(MyClass, int))
After execution(String com.company.app.Application.doSomething(MyClass, int)) -> @com.company.app.MyAnnotation()
After call(String com.company.app.Application.doSomething(MyClass, int)) -> @com.company.app.MyAnnotation()
```

Of course, call() joinpoints are unavailable in Spring AOP, so there you would only see two lines of log output.

Body:
I am learning Spring and I searched a lot about how to properly use @args() AspectJ designator but I am still not clear completely. What I know about it is that it limits joint-point matches to the execution of methods whose arguments are annoted with the given annotation types. This does not seem to work in my case.

So here goes my files:

Human.java

@Component
public class Human {
    int sleepHours;
    public int sleep(String sleepHours) {
        this.sleepHours = Integer.parseInt(sleepHours);
        System.out.println("Humans sleep for " + this.sleepHours + " hours.");
        return this.sleepHours+1;
    }
}

Sleepable.java - Sleepable annotation

 package com.aspect;
 public @interface Sleepable {

 }

SleepingAspect.java - Aspect

@Component
@Aspect
public class SleepingAspect {

    @Pointcut("@args(com.aspect.Sleepable)")
    public void sleep(){};

    @Before("sleep()")
    public void beforeSleep() {
        System.out.println("Closing eyes before sleeping");
    }

    @AfterReturning("sleep()")
    public void afterSleep() {
        System.out.println("Opening eyes after sleep");
    }
}

MainApp.java

public class MainApp {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        Human human = (Human) context.getBean("human");
        @Sleepable
        String sleepHours = "8";
        human.sleep(sleepHours);
    }
}

Output

Humans sleep for 8 hours.

Expected Output

Closing eyes before sleeping

Humans sleep for 8 hours.

Opening eyes after sleep

Body:
You have several mistakes in your code:

Spring AOP can only intercept method calls upon Spring components. What you are trying to intercept is an annotation on a local variable. Not even the much more powerful AspectJ can intercept anything concerning local variables, only read/write access to class members. Thus, what you are trying to do is impossible. And by the way, it is bad application design. Why would anyone want to rely on method internals when trying to apply cross-cutting behaviour? Method internals are subject to frequent refactoring. Suggestion: Put your annotation on method public int sleep(String sleepHours).

Your annotation is invisible during runtime because your forgot to add a meta annotation like @Retention(RetentionPolicy.RUNTIME).

@args is the wrong pointcut type. It captures method arguments the types of which are annotated. You want to use @annotation(com.aspect.Sleepable) instead.

I think you should not try a copy & paste cold start with Spring AOP but read the Spring AOP manual first. Everything I explained here can be found there.

Update: So according to you comments you were just practicing and trying to make up an example for @args(). Here is one in plain AspectJ. You can easily use it in similar form in Spring AOP. The @Before advice shows you how to match on an argument with an annotation on its class, the @After advice also shows how to bind the corresponding annotation to an advice argument.

Annotation + class using it:

package com.company.app;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {}

package com.company.app;

@MyAnnotation
public class MyClass {}

Driver application:

package com.company.app;

public class Application {
  public static void main(String[] args) {
    new Application().doSomething(new MyClass(), 11);
  }

  public String doSomething(MyClass myClass, int i) {
    return "blah";
  }
}

As you can see, here we use the annotated class MyClass in a method argument. This can be matched with @args() in the following aspect.

Aspect:

package com.company.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

import com.company.app.MyAnnotation;

@Aspect
public class MyAspect {
  @Before("@args(com.company.app.MyAnnotation, ..)")
  public void myBeforeAdvice(JoinPoint thisJoinPoint) {
    System.out.println("Before " + thisJoinPoint);
  }

  @After("@args(myAnnotation, ..)")
  public void myAfterAdvice(JoinPoint thisJoinPoint, MyAnnotation myAnnotation) {
    System.out.println("After " + thisJoinPoint + " -> " + myAnnotation);
  }
}

Console log:

Before call(String com.company.app.Application.doSomething(MyClass, int))
Before execution(String com.company.app.Application.doSomething(MyClass, int))
After execution(String com.company.app.Application.doSomething(MyClass, int)) -> @com.company.app.MyAnnotation()
After call(String com.company.app.Application.doSomething(MyClass, int)) -> @com.company.app.MyAnnotation()

Of course, call() joinpoints are unavailable in Spring AOP, so there you would only see two lines of log output.


问:
Rename a table in MySQL
Renaming a table is not working in MySQL

```<code>RENAME TABLE group TO member;
</code>```

The error message is

#1064 - You have an error in your SQL syntax; check the manual that corresponds
        to your MySQL server version for the right syntax to use near 'group
        RENAME TO member' at line 1
```

The query is working fine on other tables for me, but not with the table group.

答:
Table name change</p>

```<code>RENAME TABLE old_table_name TO new_table_name;
</code>```

Title: Rename a table in MySQL

Body:
Renaming a table is not working in MySQL

RENAME TABLE group TO member;

The error message is

#1064 - You have an error in your SQL syntax; check the manual that corresponds
        to your MySQL server version for the right syntax to use near 'group
        RENAME TO member' at line 1

The query is working fine on other tables for me, but not with the table group.

Body:
Table name change

RENAME TABLE old_table_name TO new_table_name;

ContentLicense: CC BY-SA 4.0


问:
What is this line is in Angular syntax?
Unfortunately I do not understand following syntax. I know what it does, it removes a listener for the listener's array.

```<code>this._listeners = this._listeners.filter(1 => 1 !== listener);
</code>```

I do not understand this syntax in Angular2 and it is used everywhere.
1 => 1 !== listener.

The whole code snippet is

```<code>subscribe(listener: ListenerCallback): UnsubscribeCallback {
    this._listeners.push(listener);

    return () => { // returns an unsubscribe function
        this._listener = this._listeners.filter(1 => 1 !== listener);
    };
}
</code>```

答:
I think that's a typo in your book.

Assuming it's

```<code>this._listener = this._listeners.filter(listener => 1 !== listener);
</code>```

This will filter _listeners array and

will return any element which is not equal to 1 ( listener => 1 !== listener )

That's a short hand syntax for

```<code>this._listener = this._listeners.filter((listener) =>{
    return 1 !== listener
});
</code>```

which is shorter for

```<code>this._listener = this._listeners.filter((listener) =>{
    if(1 !== listener){
      return listener;
    }
});
</code>```

Title: What is this line is in Angular syntax?

Body:
Unfortunately I do not understand following syntax. I know what it does, it removes a listener for the listener's array.

this._listeners = this._listeners.filter(1 => 1 !== listener);

I do not understand this syntax in Angular2 and it is used everywhere.
1 => 1 !== listener.

The whole code snippet is

subscribe(listener: ListenerCallback): UnsubscribeCallback {
    this._listeners.push(listener);

    return () => { // returns an unsubscribe function
        this._listener = this._listeners.filter(1 => 1 !== listener);
    };
}

Body:
I think that's a typo in your book.

Assuming it's

this._listener = this._listeners.filter(listener => 1 !== listener);

This will filter _listeners array and

will return any element which is not equal to 1 ( listener => 1 !== listener )

That's a short hand syntax for

this._listener = this._listeners.filter((listener) =>{
    return 1 !== listener
});

which is shorter for

this._listener = this._listeners.filter((listener) =>{
    if(1 !== listener){
      return listener;
    }
});


问:
React-Native parent Node change children value
I am looking for all web but I no found any solution, maybe because I am newer with React-Native universe.

Well, my question is about Node Parent change value of Children.

My situation is, I have a data controller and this data controller listen data from events and when the events happen it need update a component like Slider.

the render need be.

```<code><DataListener url={this.state.service_url}>
    <Slider style={this.styles.slider_component}/>
</DataListener>
</code>```

I need understand the cycle to get a default Slider with my Class DataListener. Is it with props in constructor? How can I get the slider inside DataListener and change this value like this.default_slider.value = 0.4

Thanks Advance
Victor C Tavernari

答:
You should pass down the value as a prop and then your slider component can deal with it appropriately.  Of course DataListener has to get the value in the first place and as you have detailed that let's assume it is in state (when you update state (via this.setState(newState)) it will cause a re-render of the DataListener which will in turn re-render the Slider with the new property):

```<code><DataListener url={this.state.service_url}>
  <Slider style={this.styles.slider_component} value={this.state.value}/>
</DataListener>
</code>```

the data controller event you refer to would then be something like

```<code>onEvent(e) {
  this.setState({value: e.value});
}
</code>```

Body:
I am looking for all web but I no found any solution, maybe because I am newer with React-Native universe.

Well, my question is about Node Parent change value of Children.

My situation is, I have a data controller and this data controller listen data from events and when the events happen it need update a component like Slider.

the render need be.

<DataListener url={this.state.service_url}>
    <Slider style={this.styles.slider_component}/>
</DataListener>

I need understand the cycle to get a default Slider with my Class DataListener. Is it with props in constructor? How can I get the slider inside DataListener and change this value like this.default_slider.value = 0.4

Thanks Advance
Victor C Tavernari

Body:
You should pass down the value as a prop and then your slider component can deal with it appropriately.  Of course DataListener has to get the value in the first place and as you have detailed that let's assume it is in state (when you update state (via this.setState(newState)) it will cause a re-render of the DataListener which will in turn re-render the Slider with the new property):

<DataListener url={this.state.service_url}>
  <Slider style={this.styles.slider_component} value={this.state.value}/>
</DataListener>

the data controller event you refer to would then be something like

onEvent(e) {
  this.setState({value: e.value});
}


问:
Hiding user input on terminal in Linux script
I have bash script like the following:

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

echo "Please enter your username";
read username;

echo "Please enter your password";
read password;
</code>```

I want that when the user types the password on the terminal, it should not be displayed (or something like  *******) should be displayed). How do I achieve this?

答:
Update

In case you want to get fancy by outputting an * for each character they type, you can do something like this (using andreas' read -s solution):

```<code>unset password;
while IFS= read -r -s -n1 pass; do
  if [[ -z $pass ]]; then
     echo
     break
  else
     echo -n '*'
     password+=$pass
  fi
done
</code>```

Without being fancy

```<code>echo "Please enter your username";
read username;

echo "Please enter your password";
stty -echo
read password;
stty echo
</code>```

Body:
I have bash script like the following:

#!/bin/bash

echo "Please enter your username";
read username;

echo "Please enter your password";
read password;

I want that when the user types the password on the terminal, it should not be displayed (or something like  *******) should be displayed). How do I achieve this?

Body:
Update

In case you want to get fancy by outputting an * for each character they type, you can do something like this (using andreas' read -s solution):

unset password;
while IFS= read -r -s -n1 pass; do
  if [[ -z $pass ]]; then
     echo
     break
  else
     echo -n '*'
     password+=$pass
  fi
done

Without being fancy

echo "Please enter your username";
read username;

echo "Please enter your password";
stty -echo
read password;
stty echo


问:
Git, merge two remote branches
I created second branch -> git checkout -b branch2
After it, created any file, add, commit and push to branch2.

Now I checkout to master branch. How can I added new_file from branch2 to master branch? Any merge option -> your branch is up to date.

答:
If you only want the one added file you can:</p>

```<code>git checkout master
git checkout branch2 -- the_file
git add the_file
git commit -m "adding the_file from branch2"
</code>```

Title: Git, merge two remote branches

Body:
If you only want the one added file you can:

git checkout master
git checkout branch2 -- the_file
git add the_file
git commit -m "adding the_file from branch2"


问:
Send POST HTTP with ClaudiaJS and AWS Lambda
I building a service for push notifications in the facebook messenger. My nodejs app works fine in my localhost, but doesn't in AWS.

I use request module (npm) for send message.

My service can get the parameters, but doesn't send HTTP POST.

```<code>var ApiBuilder = require('claudia-api-builder'),
  api = new ApiBuilder();

var request = require('request')

api.get('hello', function (req) {

  var token = req.queryString.token;
  var sender = req.queryString.sender;
  var msg = req.queryString.msg;
  messageData = {};
  messageData.text = msg;

  request({
      url: 'https://graph.facebook.com/v2.6/me/messages',
      qs: { access_token: token },
      method: 'POST',
      json: {
          recipient: { id: sender },
          message: messageData,
      }
  }, function (error, response, body) {
      if (error) {
          return 'Error sending message: ' + error;
      } else if (response.body.error) {
          return 'Error: ' + response.body.error;
      }
  });

  return sender + ' ' + messageData.text  ;
})

module.exports = api;
</code>```

答:
You need to return a promise out of the API builder method handler for asynchronous operations. You can use something like got or minimal-request-promise to turn the HTTP request into a Promise, or just use a simple promise wrapper such as return new Promise((resolve, reject) => request(...., function (error, result) { if (error) { return reject(errror); else resolve(result) } }))

See item #4 in the guide on how to use external services from Claudia here: https://claudiajs.com/tutorials/external-services.html

Body:
I building a service for push notifications in the facebook messenger. My nodejs app works fine in my localhost, but doesn't in AWS.

I use request module (npm) for send message.

My service can get the parameters, but doesn't send HTTP POST.

var ApiBuilder = require('claudia-api-builder'),
  api = new ApiBuilder();

var request = require('request')

api.get('hello', function (req) {

  var token = req.queryString.token;
  var sender = req.queryString.sender;
  var msg = req.queryString.msg;
  messageData = {};
  messageData.text = msg;

  request({
      url: 'https://graph.facebook.com/v2.6/me/messages',
      qs: { access_token: token },
      method: 'POST',
      json: {
          recipient: { id: sender },
          message: messageData,
      }
  }, function (error, response, body) {
      if (error) {
          return 'Error sending message: ' + error;
      } else if (response.body.error) {
          return 'Error: ' + response.body.error;
      }
  });

  return sender + ' ' + messageData.text  ;
})

module.exports = api;


问:
Difference in uses between malloc and calloc
```<code>gcc 4.5.1 c89
</code>```

I have written this source code for my better understanding of malloc and calloc.

I understand, but just have a few questions.

```<code>dev = malloc(number * sizeof *devices);
</code>```

is equal to this calloc. I am not concerned about clearing the memory.

```<code>dev = calloc(number, sizeof *devices);
</code>```

What is that exactly, compared to doing this 5 times in a while loop:

```<code>dev = malloc(sizeof *devices);
</code>```

I guess the first one and the second is creating a pointer to 5 struct device. And the third is creating a single pointer to a struct device?

My program illustrates this 3 different methods compiled and ran with valgrind --leak-check=full.

Many thanks for any advice.

```<code>#include <stdio.h>
#include <stdlib.h>

struct Devices {
#define MAX_NAME_SIZE 80
    size_t id;
    char name[MAX_NAME_SIZE];
};

struct Devices* create_device(struct Devices *dev);
void destroy_device(struct Devices *dev);

int main(void)
{
    size_t num_devices = 5;
    size_t i = 0;
    struct Devices *device = NULL;
    struct Devices *dev_malloc = NULL;
    struct Devices *dev_calloc = NULL;

    for(i = 0; i < num_devices; i++) {
        device = create_device(device);
        /* Assign values */
        device->id = i + 1;
        sprintf(device->name, "Device%zu", device->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", device->id);
        printf("Name --- [ %s ]\n", device->name);
        /* Test free */
        destroy_device(device);
    }

    printf("\n");
    dev_malloc = malloc(num_devices * sizeof *dev_malloc);
    for(i = 0; i < num_devices; i++) {
        /* Assign values */
        dev_malloc->id = i + 1;
        sprintf(dev_malloc->name, "dev_malloc%zu", dev_malloc->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", dev_malloc->id);
        printf("Name --- [ %s ]\n", dev_malloc->name);
    }
    /* Test free */
    destroy_device(dev_malloc);

    printf("\n");
    dev_calloc = calloc(num_devices, sizeof *dev_calloc);
    for(i = 0; i < num_devices; i++) {
        /* Assign values */
        dev_calloc->id = i + 1;
        sprintf(dev_calloc->name, "dev_calloc%zu", dev_calloc->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", dev_calloc->id);
        printf("Name --- [ %s ]\n", dev_calloc->name);
    }
    /* Test free */
    destroy_device(dev_calloc);

    return 0;
}

struct Devices* create_device(struct Devices *dev)
{
    /* Not checking for memory error - just simple test */
    return dev = malloc(sizeof *dev);
}

void destroy_device(struct Devices *dev)
{
    if(dev != NULL) {
        free(dev);
    }
}
</code>```

答:
malloc(n) allocates n bytes plus padding and overhead.

calloc(m, n) allocates m*n bytes plus padding and overhead, and then zero's the memory.

That's it.

Body:
gcc 4.5.1 c89

I have written this source code for my better understanding of malloc and calloc.

I understand, but just have a few questions.

dev = malloc(number * sizeof *devices);

is equal to this calloc. I am not concerned about clearing the memory.

dev = calloc(number, sizeof *devices);

What is that exactly, compared to doing this 5 times in a while loop:

dev = malloc(sizeof *devices);

I guess the first one and the second is creating a pointer to 5 struct device. And the third is creating a single pointer to a struct device?

My program illustrates this 3 different methods compiled and ran with valgrind --leak-check=full.

Many thanks for any advice.

#include <stdio.h>
#include <stdlib.h>

struct Devices {
#define MAX_NAME_SIZE 80
    size_t id;
    char name[MAX_NAME_SIZE];
};

struct Devices* create_device(struct Devices *dev);
void destroy_device(struct Devices *dev);

int main(void)
{
    size_t num_devices = 5;
    size_t i = 0;
    struct Devices *device = NULL;
    struct Devices *dev_malloc = NULL;
    struct Devices *dev_calloc = NULL;

    for(i = 0; i < num_devices; i++) {
        device = create_device(device);
        /* Assign values */
        device->id = i + 1;
        sprintf(device->name, "Device%zu", device->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", device->id);
        printf("Name --- [ %s ]\n", device->name);
        /* Test free */
        destroy_device(device);
    }

    printf("\n");
    dev_malloc = malloc(num_devices * sizeof *dev_malloc);
    for(i = 0; i < num_devices; i++) {
        /* Assign values */
        dev_malloc->id = i + 1;
        sprintf(dev_malloc->name, "dev_malloc%zu", dev_malloc->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", dev_malloc->id);
        printf("Name --- [ %s ]\n", dev_malloc->name);
    }
    /* Test free */
    destroy_device(dev_malloc);

    printf("\n");
    dev_calloc = calloc(num_devices, sizeof *dev_calloc);
    for(i = 0; i < num_devices; i++) {
        /* Assign values */
        dev_calloc->id = i + 1;
        sprintf(dev_calloc->name, "dev_calloc%zu", dev_calloc->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", dev_calloc->id);
        printf("Name --- [ %s ]\n", dev_calloc->name);
    }
    /* Test free */
    destroy_device(dev_calloc);

    return 0;
}

struct Devices* create_device(struct Devices *dev)
{
    /* Not checking for memory error - just simple test */
    return dev = malloc(sizeof *dev);
}

void destroy_device(struct Devices *dev)
{
    if(dev != NULL) {
        free(dev);
    }
}


问:
Setting the leading zero in hours,minutes and seconds in php
I have a script which i want to use to generate some data from a certain date. The problem i am having is setting the leading zero for minutes,hours and seconds.

For instance

```<code><?php
for($i=0;$i<25;$i++){
    //echo $i.'<br/>';
    $start = "2012-10-01 $i:00:00";
    echo $start.'<br/>';
}
?>
</code>```

I want all hours from 0 to 9 to have a leading zero. Is there a functions that can help me have the leading zero in hours,minutes or seconds?.

Body:
I have a script which i want to use to generate some data from a certain date. The problem i am having is setting the leading zero for minutes,hours and seconds.

For instance

<?php
for($i=0;$i<25;$i++){
    //echo $i.'
';
    $start = "2012-10-01 $i:00:00";
    echo $start.'
';
}
?>

I want all hours from 0 to 9 to have a leading zero. Is there a functions that can help me have the leading zero in hours,minutes or seconds?.

Body:
Try str_pad

for($i=0;$i<25;$i++){
    $temp = str_pad($i,2,"0",STR_PAD_LEFT)
    $start = "2012-10-01 $temp:00:00";
    echo $start.'<br/>';
}

Demo


问:
android something wrong with the loop-cannot put the value into hashmap
This problem has bothered me for a long time. I use a cloud database called bmob, and I found that I can successfully get the data I want. However, there might be some mistakes in the loops, and I could only get the information of the last selected item.

p.s. I use an array list called Playlist to store the calculated data that I will use to display a list-view in the next activity.

here is my code:

```<code>public class DestinationActivity extends Activity implements OnClickListener, NumberPicker.OnValueChangeListener {

private TextView from_place, date, days, start_time, end_time, number, money_view;
private Button addButton, subButton;
private ImageView backButton, telephone;
private ListView listView;
private Button destinationOk_btn;
private ShapeLoadingDialog shapeLoadingDialog;

private Tip startTip;

private Calendar calendar;
private DatePickerDialog dialog;
private TimePickerDialog dialog2;

private List<Destination> destinationList = new ArrayList<Destination>();

private DestinationAdapter adapter;

private int number_value = 1;

private String time_start;
private String time_end;
private int travel_days;
double travelTime;//total playing time
double travel_time;
private int money;
private int num = 1;

private ArrayList<Integer> select_placeID = new ArrayList<Integer>();
public Map<Integer,Double> weightMap;
public List<Plan> planList = new ArrayList<Plan>();
int[] selectedID = new int[10];

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.destination_layout);

    //initialize the cloud database
    Bmob.initialize(this, BmobConfig.APP_ID);

    listView = (ListView) findViewById(R.id.list_destination);

    destinationOk_btn = (Button) findViewById(R.id.okButton);

    initDestinations(); // initialize the data

    adapter = new DestinationAdapter(destinationList, DestinationActivity.this);
    //adapter = new DestinationAdapter(this, destinationList, DestinationAdapter.getIsSelected());
    listView.setAdapter(adapter);

    //....listeners and textviews.......

    //submit button
    destinationOk_btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            select_placeID.clear();

            for (int i = 0; i < destinationList.size(); i++) {
                if (DestinationAdapter.getIsSelected().get(i)) {
                    select_placeID.add((i + 1));
                }

            }

            //change to int array
            selectedID = new int[select_placeID.size()];
            for(int i = 0;i<select_placeID.size();i++){
                selectedID[i] = select_placeID.get(i);
            }

            if (select_placeID.size() == 0) {
                AlertDialog.Builder builder1 = new AlertDialog.Builder(DestinationActivity.this);
                builder1.setMessage("no records");
                builder1.show();
            }
            else {
                AlertDialog.Builder builder = new AlertDialog.Builder(DestinationActivity.this);

                builder.setMessage("waiting for magic...");
                builder.show();

                /**
                 * calculate the route
                 */
                if (validate()) {
                    new calRoute().execute();
                }

            }
        }

    });
}

//initialize the data
private void initDestinations() {
    //........
}

@Override
public void onClick(View v) {
    //.......
}

/**
 * asynctask
 */
private class calRoute extends AsyncTask<Void, Void, List<Plan>>{

    public calRoute(){
        // TODO Auto-generated constructor stub
    }

    @Override
    protected List<Plan> doInBackground(Void... params) {

        List<Plan> result = calculate(time_start, time_end, travel_days);

        return result;
    }

    @Override
    protected void onPostExecute(List<Plan> result) {
        super.onPostExecute(result);
        if (result != null) {
            Toast.makeText(DestinationActivity.this, "success", Toast.LENGTH_SHORT).show();

            if(planList.size() > 0) {

                Intent intent = new Intent();
                intent.setClass(DestinationActivity.this, ActivityPlan.class);

                intent.putParcelableArrayListExtra("planInfo", (ArrayList<? extends Parcelable>) planList);

                startActivity(intent);
            }

            else{
                Toast.makeText(DestinationActivity.this, "no plan", Toast.LENGTH_SHORT).show();
            }
        }

    }
}

/**
 *plan
 **/
public List<Plan> calculate(String time_start, String time_end, int travel_days) {

    SimpleDateFormat df = new SimpleDateFormat(("HH:mm"));

    Date starttime = new Date();
    Date endtime = new Date();
    try {
        starttime = df.parse(time_start);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    try {
        endtime = df.parse(time_end);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    double l = endtime.getTime() - starttime.getTime();
    double hour = (l / (60 * 60 * 1000));
    double min = ((l / (60 * 1000)) - hour * 60);

    if(min == 0){
        min = 60;
    }
    else {
        travel_time = ((1.0 * travel_days * hour) * (min / 60));
        DecimalFormat decimalFormat = new DecimalFormat("#.0");
        travelTime = Double.parseDouble(decimalFormat.format(travel_time));
    }

    weightMap = new LinkedHashMap<Integer, Double>(); //store weight
    int totalPriority = 0;//total priority

    final Destination start = new Destination(116.32133, 39.92269);

    final HashMap<Integer, Integer> pMap = new HashMap<Integer, Integer>();
    final HashMap<Integer, String> nameMap = new HashMap<Integer, String>();
    final HashMap<Integer, Destination> objectMap = new LinkedHashMap<Integer, Destination>();
    /**
     * get the data from cloud database
     */
            BmobQuery<Destination> query = new BmobQuery<Destination>();
            for (int sid: selectedID) {

                query.addWhereEqualTo("id", sid);

                query.findObjects(new FindListener<Destination>() {

                    @Override
                    public void done(List<Destination> list, BmobException e) {
                        if (e == null) {
                            System.out.println("success：total" + list.size() + "items。");
                            for (Destination destination : list) {

                                int p = destination.getPriority();

                                int id = destination.getId();

                                String name = destination.getName();

                                double longitude = destination.getLongitude();
                                double latitude = destination.getLatitude();

                                objectMap.put(id, new Destination(longitude, latitude));

                                System.out.println(id);

                                double dis = DistanceUtil.distance(start.getLongitude(), start.getLatitude(),
                                        longitude, latitude);

                                pMap.put(id, p);
                                weightMap.put(id, new Double(dis));
                                nameMap.put(id, name);

                            }
                        } else {
                            Log.i("bmob", "error：" + e.getMessage() + "," + e.getErrorCode());
                        }
                    }
                });
            }

    for (Integer key : pMap.keySet()) {
        int p = pMap.get(key).intValue();
        totalPriority = totalPriority + p;
    }

    double weight = 0.0;
    for (Map.Entry<Integer, Double> hm : weightMap.entrySet()) {
        double hm2Value = pMap.get(hm.getKey());
        weight = totalPriority / hm.getValue() * hm2Value;

        weightMap.put(hm.getKey(), weight);
    }

    /**
     * 按照weight值来排序
     * 判断是否传递数据给plan_activity
     */
    MapUtil.sortByValue(weightMap);

    //排好序后计算距离
    Iterator it = weightMap.entrySet().iterator();
    int order = 0;
    while (it.hasNext()) {
        order++;
        Map.Entry entry = (Map.Entry) it.next();
        objectMap.put(new Integer(order), objectMap.get(entry.getKey()));
    }

    PlanTask planTask = new PlanTask();//封装了每个plan计算的方法

    for (Map.Entry<Integer, Double> entry : weightMap.entrySet()) {
        System.out.println("id= " + entry.getKey());

        double play_time = planTask.calPlay_time(weightMap.size(),
                weightMap.get(entry.getKey()), travelTime);

        double driving_time = planTask.calDrive_time(DistanceUtil.distance(
                objectMap.get(entry.getKey()).getLatitude(),
                objectMap.get(entry.getKey()).getLongitude(),
                objectMap.get(entry.getKey() + 1).getLatitude(),
                objectMap.get(entry.getKey() + 1).getLongitude()
        ));

        String arrive_time = "hello world";//未完待续

        String place_name = nameMap.get(entry.getKey());

        Plan plan = new Plan(place_name, arrive_time, driving_time, play_time);

        //传递plan对象list
        planList.add(entry.getKey(), plan);
    }

    return planList;

}
</code>```

}

When I debug it, I found that in calculate() functions, the output of

```<code>  BmobQuery<Destination> query = new BmobQuery<Destination>();
            for (int sid: selectedID) {

                query.addWhereEqualTo("id", sid);

query.findObjects(new FindListener<Destination>() {

                    @Override
                    public void done(List<Destination> list, BmobException e) {
                        if (e == null) {
                            System.out.println("success：total" + list.size() + "items。");
                            for (Destination destination : list) {

                                int p = destination.getPriority();

                                int id = destination.getId();

                                String name = destination.getName();

                                double longitude = destination.getLongitude();
                                double latitude = destination.getLatitude();

                                objectMap.put(id, new Destination(longitude, latitude));

                                System.out.println(id);

                                //calculate the distance
                                double dis = DistanceUtil.distance(start.getLongitude(), start.getLatitude(),
                                        longitude, latitude);

                                pMap.put(id, p);
                                weightMap.put(id, new Double(dis));
                                nameMap.put(id, name);

                            }
                        } else {
                            Log.i("bmob", "error：" + e.getMessage() + "," + e.getErrorCode());
                        }
                    }
                });
</code>```

is "success：total 1 items." and after the loop, if I have selected 3 items, it would be "success：total 1 items."  for 3 times and only the information of the last item is caught.
AND the size of three hash map: pMap, nameMap and objectMap are all zero. Why is it??? It is so strange...

There is no error in LogCAT, however, the ordered list view cannot display in the second activity. PLEASE help me, it has bothered me for a long time.
Thank you!!!

答:
I couldn't figure out much unfortunately, since I am not really comfortable with reactive programming yet as the platform uses a lot of rxjava in general, but here is something that would enhance the code a little bit

```<code>final HashMap<Integer, Integer> pMap = new HashMap<Integer, Integer>();
final HashMap<Integer, String> nameMap = new HashMap<Integer, String>();
final HashMap<Integer, Destination> objectMap = new LinkedHashMap<Integer, Destination>();

/**
 * get the data from cloud database
 */
BmobQuery<Destination> query = new BmobQuery<Destination>();

// this time only one list of three elements is added instead of three lists of one element each
query.addWhereContainedIn("id", Arrays.asList(selectedID));

query.findObjects(new FindListener<Destination>() {
                @Override
                public void done(List<Destination> list, BmobException e) {
                    if (e == null) {
                        System.out.println("success：total" + list.size() + "items。");
                        for (Destination destination : list) {

                            int p = destination.getPriority();

                            int id = destination.getId();

                            String name = destination.getName();

                            double longitude = destination.getLongitude();
                            double latitude = destination.getLatitude();

                            objectMap.put(id, new Destination(longitude, latitude));

                            System.out.println(id);

                            //calculate the distance
                            double dis = DistanceUtil.distance(start.getLongitude(), start.getLatitude(),
                                    longitude, latitude);

                            pMap.put(id, p);
                            weightMap.put(id, new Double(dis));
                            nameMap.put(id, name);

                        }
                        // continue execution here though you won't be able to return a list of plans here
                    } else {
                        Log.i("bmob", "error：" + e.getMessage() + "," + e.getErrorCode());
                    }
                }
});
</code>```

Hope this helps :)

Body:
This problem has bothered me for a long time. I use a cloud database called bmob, and I found that I can successfully get the data I want. However, there might be some mistakes in the loops, and I could only get the information of the last selected item.

p.s. I use an array list called Playlist to store the calculated data that I will use to display a list-view in the next activity.

here is my code:

public class DestinationActivity extends Activity implements OnClickListener, NumberPicker.OnValueChangeListener {

private TextView from_place, date, days, start_time, end_time, number, money_view;
private Button addButton, subButton;
private ImageView backButton, telephone;
private ListView listView;
private Button destinationOk_btn;
private ShapeLoadingDialog shapeLoadingDialog;

private Tip startTip;

private Calendar calendar;
private DatePickerDialog dialog;
private TimePickerDialog dialog2;

private List<Destination> destinationList = new ArrayList<Destination>();

private DestinationAdapter adapter;

private int number_value = 1;

private String time_start;
private String time_end;
private int travel_days;
double travelTime;//total playing time
double travel_time;
private int money;
private int num = 1;

private ArrayList<Integer> select_placeID = new ArrayList<Integer>();
public Map<Integer,Double> weightMap;
public List<Plan> planList = new ArrayList<Plan>();
int[] selectedID = new int[10];

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.destination_layout);

    //initialize the cloud database
    Bmob.initialize(this, BmobConfig.APP_ID);

    listView = (ListView) findViewById(R.id.list_destination);

    destinationOk_btn = (Button) findViewById(R.id.okButton);

    initDestinations(); // initialize the data

    adapter = new DestinationAdapter(destinationList, DestinationActivity.this);
    //adapter = new DestinationAdapter(this, destinationList, DestinationAdapter.getIsSelected());
    listView.setAdapter(adapter);

    //....listeners and textviews.......

    //submit button
    destinationOk_btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            select_placeID.clear();

            for (int i = 0; i < destinationList.size(); i++) {
                if (DestinationAdapter.getIsSelected().get(i)) {
                    select_placeID.add((i + 1));
                }

            }

            //change to int array
            selectedID = new int[select_placeID.size()];
            for(int i = 0;i<select_placeID.size();i++){
                selectedID[i] = select_placeID.get(i);
            }

            if (select_placeID.size() == 0) {
                AlertDialog.Builder builder1 = new AlertDialog.Builder(DestinationActivity.this);
                builder1.setMessage("no records");
                builder1.show();
            }
            else {
                AlertDialog.Builder builder = new AlertDialog.Builder(DestinationActivity.this);

                builder.setMessage("waiting for magic...");
                builder.show();

                /**
                 * calculate the route
                 */
                if (validate()) {
                    new calRoute().execute();
                }

            }
        }

    });
}

//initialize the data
private void initDestinations() {
    //........
}

@Override
public void onClick(View v) {
    //.......
}

/**
 * asynctask
 */
private class calRoute extends AsyncTask<Void, Void, List<Plan>>{

    public calRoute(){
        // TODO Auto-generated constructor stub
    }

    @Override
    protected List<Plan> doInBackground(Void... params) {

        List<Plan> result = calculate(time_start, time_end, travel_days);

        return result;
    }

    @Override
    protected void onPostExecute(List<Plan> result) {
        super.onPostExecute(result);
        if (result != null) {
            Toast.makeText(DestinationActivity.this, "success", Toast.LENGTH_SHORT).show();

            if(planList.size() > 0) {

                Intent intent = new Intent();
                intent.setClass(DestinationActivity.this, ActivityPlan.class);

                intent.putParcelableArrayListExtra("planInfo", (ArrayList<? extends Parcelable>) planList);

                startActivity(intent);
            }

            else{
                Toast.makeText(DestinationActivity.this, "no plan", Toast.LENGTH_SHORT).show();
            }
        }

    }
}

/**
 *plan
 **/
public List<Plan> calculate(String time_start, String time_end, int travel_days) {

    SimpleDateFormat df = new SimpleDateFormat(("HH:mm"));

    Date starttime = new Date();
    Date endtime = new Date();
    try {
        starttime = df.parse(time_start);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    try {
        endtime = df.parse(time_end);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    double l = endtime.getTime() - starttime.getTime();
    double hour = (l / (60 * 60 * 1000));
    double min = ((l / (60 * 1000)) - hour * 60);

    if(min == 0){
        min = 60;
    }
    else {
        travel_time = ((1.0 * travel_days * hour) * (min / 60));
        DecimalFormat decimalFormat = new DecimalFormat("#.0");
        travelTime = Double.parseDouble(decimalFormat.format(travel_time));
    }

    weightMap = new LinkedHashMap<Integer, Double>(); //store weight
    int totalPriority = 0;//total priority

    final Destination start = new Destination(116.32133, 39.92269);

    final HashMap<Integer, Integer> pMap = new HashMap<Integer, Integer>();
    final HashMap<Integer, String> nameMap = new HashMap<Integer, String>();
    final HashMap<Integer, Destination> objectMap = new LinkedHashMap<Integer, Destination>();
    /**
     * get the data from cloud database
     */
            BmobQuery<Destination> query = new BmobQuery<Destination>();
            for (int sid: selectedID) {

                query.addWhereEqualTo("id", sid);

                query.findObjects(new FindListener<Destination>() {

                    @Override
                    public void done(List<Destination> list, BmobException e) {
                        if (e == null) {
                            System.out.println("success：total" + list.size() + "items。");
                            for (Destination destination : list) {

                                int p = destination.getPriority();

                                int id = destination.getId();

                                String name = destination.getName();

                                double longitude = destination.getLongitude();
                                double latitude = destination.getLatitude();

                                objectMap.put(id, new Destination(longitude, latitude));

                                System.out.println(id);

                                double dis = DistanceUtil.distance(start.getLongitude(), start.getLatitude(),
                                        longitude, latitude);

                                pMap.put(id, p);
                                weightMap.put(id, new Double(dis));
                                nameMap.put(id, name);

                            }
                        } else {
                            Log.i("bmob", "error：" + e.getMessage() + "," + e.getErrorCode());
                        }
                    }
                });
            }

    for (Integer key : pMap.keySet()) {
        int p = pMap.get(key).intValue();
        totalPriority = totalPriority + p;
    }

    double weight = 0.0;
    for (Map.Entry<Integer, Double> hm : weightMap.entrySet()) {
        double hm2Value = pMap.get(hm.getKey());
        weight = totalPriority / hm.getValue() * hm2Value;

        weightMap.put(hm.getKey(), weight);
    }

    /**
     * 按照weight值来排序
     * 判断是否传递数据给plan_activity
     */
    MapUtil.sortByValue(weightMap);

    //排好序后计算距离
    Iterator it = weightMap.entrySet().iterator();
    int order = 0;
    while (it.hasNext()) {
        order++;
        Map.Entry entry = (Map.Entry) it.next();
        objectMap.put(new Integer(order), objectMap.get(entry.getKey()));
    }

    PlanTask planTask = new PlanTask();//封装了每个plan计算的方法

    for (Map.Entry<Integer, Double> entry : weightMap.entrySet()) {
        System.out.println("id= " + entry.getKey());

        double play_time = planTask.calPlay_time(weightMap.size(),
                weightMap.get(entry.getKey()), travelTime);

        double driving_time = planTask.calDrive_time(DistanceUtil.distance(
                objectMap.get(entry.getKey()).getLatitude(),
                objectMap.get(entry.getKey()).getLongitude(),
                objectMap.get(entry.getKey() + 1).getLatitude(),
                objectMap.get(entry.getKey() + 1).getLongitude()
        ));

        String arrive_time = "hello world";//未完待续

        String place_name = nameMap.get(entry.getKey());

        Plan plan = new Plan(place_name, arrive_time, driving_time, play_time);

        //传递plan对象list
        planList.add(entry.getKey(), plan);
    }

    return planList;

}

}

When I debug it, I found that in calculate() functions, the output of

  BmobQuery<Destination> query = new BmobQuery<Destination>();
            for (int sid: selectedID) {

                query.addWhereEqualTo("id", sid);

query.findObjects(new FindListener<Destination>() {

                    @Override
                    public void done(List<Destination> list, BmobException e) {
                        if (e == null) {
                            System.out.println("success：total" + list.size() + "items。");
                            for (Destination destination : list) {

                                int p = destination.getPriority();

                                int id = destination.getId();

                                String name = destination.getName();

                                double longitude = destination.getLongitude();
                                double latitude = destination.getLatitude();

                                objectMap.put(id, new Destination(longitude, latitude));

                                System.out.println(id);

                                //calculate the distance
                                double dis = DistanceUtil.distance(start.getLongitude(), start.getLatitude(),
                                        longitude, latitude);

                                pMap.put(id, p);
                                weightMap.put(id, new Double(dis));
                                nameMap.put(id, name);

                            }
                        } else {
                            Log.i("bmob", "error：" + e.getMessage() + "," + e.getErrorCode());
                        }
                    }
                });

is "success：total 1 items." and after the loop, if I have selected 3 items, it would be "success：total 1 items."  for 3 times and only the information of the last item is caught.
AND the size of three hash map: pMap, nameMap and objectMap are all zero. Why is it??? It is so strange...

There is no error in LogCAT, however, the ordered list view cannot display in the second activity. PLEASE help me, it has bothered me for a long time.
Thank you!!!

Body:
I couldn't figure out much unfortunately, since I am not really comfortable with reactive programming yet as the platform uses a lot of rxjava in general, but here is something that would enhance the code a little bit

final HashMap<Integer, Integer> pMap = new HashMap<Integer, Integer>();
final HashMap<Integer, String> nameMap = new HashMap<Integer, String>();
final HashMap<Integer, Destination> objectMap = new LinkedHashMap<Integer, Destination>();

/**
 * get the data from cloud database
 */
BmobQuery<Destination> query = new BmobQuery<Destination>();

// this time only one list of three elements is added instead of three lists of one element each
query.addWhereContainedIn("id", Arrays.asList(selectedID));

query.findObjects(new FindListener<Destination>() {
                @Override
                public void done(List<Destination> list, BmobException e) {
                    if (e == null) {
                        System.out.println("success：total" + list.size() + "items。");
                        for (Destination destination : list) {

                            int p = destination.getPriority();

                            int id = destination.getId();

                            String name = destination.getName();

                            double longitude = destination.getLongitude();
                            double latitude = destination.getLatitude();

                            objectMap.put(id, new Destination(longitude, latitude));

                            System.out.println(id);

                            //calculate the distance
                            double dis = DistanceUtil.distance(start.getLongitude(), start.getLatitude(),
                                    longitude, latitude);

                            pMap.put(id, p);
                            weightMap.put(id, new Double(dis));
                            nameMap.put(id, name);

                        }
                        // continue execution here though you won't be able to return a list of plans here
                    } else {
                        Log.i("bmob", "error：" + e.getMessage() + "," + e.getErrorCode());
                    }
                }
});

Hope this helps :)


问:
How to print from two lists
I have two lists with diffrent itemsas follows:

```<code>numbers = ['1','2','3','4','5','6','7',]

days = ['mon','tue','wed','thu','fri','sat','sun',]
</code>```

I want to print from both to look like this:

```<code>result = 1
         mon
         2
         tue
         3
         wed
         4
         thu.....etc
</code>```

Is there such as code that does this?
Regards

答: You can use zip to combine two lists.</p>

Title: How to print from two lists

Body:
I have two lists with diffrent itemsas follows:

numbers = ['1','2','3','4','5','6','7',]

days = ['mon','tue','wed','thu','fri','sat','sun',]

I want to print from both to look like this:

result = 1
         mon
         2
         tue
         3
         wed
         4
         thu.....etc

Is there such as code that does this?
Regards

Body: You can use zip to combine two lists.


答: The zip() function is probably what you want here.

Title: How to print from two lists