问:
Print hierachical data in a parent child form unordered list php?
I have data in mysql table in a parent child hierarchy like;

```<code>|---------+-----------+-------------|
| msg_id  | parent_id |    msg      |
|---------+-----------+-------------|
|       1 | NULL      |   msg1      |
|       2 | NULL      |   msg2      |
|       3 | NULL      |   msg3      |
|       4 | 1         | msg1_child1 |
|       5 | 1         | msg1_child2 |
|       6 | 3         | msg3_child1 |
|---------+-----------+-------------|
</code>```

I need to display it in a parent-child unordered list format like

```<code> -msg1
   -msg1-child1
   -msg2-child2
 -msg2
 -msg3
   -msg3-child1
</code>```

How do I do it? I need help especially how could I display it in a hierarchy on a form.

答:
```<code>function get_list($parent='NULL', $counter=0, $spaces=""){

    $sql = "SELECT * FROM t1 WHERE parent_id = ".parent;
    $rs[$counter] = mysql_query($sql) or die(mysql_error());
    while($row[$counter] = mysql_fetch_array($rs[$counter])){
        echo $spaces.$row[$counter]['msg']."<br />";
        get_list($row[$counter]['parent_id'], $counter+1, "  ".$spaces);
    }
    mysql_free_result($rs[$counter]);
}
</code>```

<p>Or, close to that.  </p>

Body:
I have data in mysql table in a parent child hierarchy like;

|---------+-----------+-------------|
| msg_id  | parent_id |    msg      |
|---------+-----------+-------------|
|       1 | NULL      |   msg1      |
|       2 | NULL      |   msg2      |
|       3 | NULL      |   msg3      |
|       4 | 1         | msg1_child1 |
|       5 | 1         | msg1_child2 |
|       6 | 3         | msg3_child1 |
|---------+-----------+-------------|

I need to display it in a parent-child unordered list format like

 -msg1
   -msg1-child1
   -msg2-child2
 -msg2
 -msg3
   -msg3-child1

How do I do it? I need help especially how could I display it in a hierarchy on a form.

Body:
function get_list($parent='NULL', $counter=0, $spaces=""){

    $sql = "SELECT * FROM t1 WHERE parent_id = ".parent;
    $rs[$counter] = mysql_query($sql) or die(mysql_error());
    while($row[$counter] = mysql_fetch_array($rs[$counter])){
        echo $spaces.$row[$counter]['msg']."<br />";
        get_list($row[$counter]['parent_id'], $counter+1, "&nbsp;&nbsp;".$spaces);
    }
    mysql_free_result($rs[$counter]);
}

Or, close to that.


来源: stackexchange

问:
Create leading dots in CSS
What is a nice way to do leading dots in a table of contents with CSS?

Example:

```<code>Link.............Chapter 1
Link.............Chapter 2
Link.............Chapter 3
</code>```

答:
Dot leaders can be be done without spans or classes. Here's a responsive solution for HTML tables, modified to center the dot leader vertically:

http://codepen.io/Paulie-D/pen/bpMyBQ

```<code>table {
    width: 90%;
    margin:100px auto;
    table-layout:fixed;
    border-collapse: collapse;
    }

td {
    padding:1em 0 0 0;
    vertical-align:bottom;
    }

td span{
    background-color:#fff;
    }

td:first-child {
    text-align: left;
    font-weight: 700;
    overflow: hidden;
    position: relative;
    }

td:first-child::after {
    content: '';
    position: absolute;
    bottom: .4em;
    width:1500px;
    height:0px ;
    margin-left: 1em;
    border-bottom:2px dotted grey;
}

td:last-child {
    text-align:right;
    width:3em;
    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Create leading dots in CSS

Body:
What is a nice way to do leading dots in a table of contents with CSS?

Example:

Link.............Chapter 1
Link.............Chapter 2
Link.............Chapter 3

Body:
Dot leaders can be be done without spans or classes. Here's a responsive solution for HTML tables, modified to center the dot leader vertically:

http://codepen.io/Paulie-D/pen/bpMyBQ

table {
    width: 90%;
    margin:100px auto;
    table-layout:fixed;
    border-collapse: collapse;
    }

td {
    padding:1em 0 0 0;
    vertical-align:bottom;
    }

td span{
    background-color:#fff;
    }

td:first-child {
    text-align: left;
    font-weight: 700;
    overflow: hidden;
    position: relative;
    }

td:first-child::after {
    content: '';
    position: absolute;
    bottom: .4em;
    width:1500px;
    height:0px ;
    margin-left: 1em;
    border-bottom:2px dotted grey;
}

td:last-child {
    text-align:right;
    width:3em;
    }


问:
Extract only pattern matched text
I have written a basic program using regular expression.
However the entire line is being returned instead of the matched part.

I want to extract the number only.

```<code>use strict;
use warnings;

my $line = "ABMA 1234";
$line =~ /(\s)(\d){4}/;

print $line; #prints *ABMA 1234*
</code>```

Is my regular expression incorrect?

答:
You can replace the exact value with the corresponding values. And your are not removing the text \w;

```<code>use strict;
use warnings;

my $line = "ABMA 1234";
$line=~s/([A-z]*)\s+(\d+)/$2/;

print $line; #prints only 1234
</code>```

If you want to store the value in the new string then

```<code>(my $newstring = $line)=~s/([A-z]*)\s+(\d+)/$2/;

print $newstring; #prints only 1234
</code>```

Just try this:

Title: Extract only pattern matched text

Body:
I have written a basic program using regular expression.
However the entire line is being returned instead of the matched part.

I want to extract the number only.

use strict;
use warnings;

my $line = "ABMA 1234";
$line =~ /(\s)(\d){4}/;

print $line; #prints *ABMA 1234*

Is my regular expression incorrect?

Body:
You can replace the exact value with the corresponding values. And your are not removing the text \w;

use strict;
use warnings;

my $line = "ABMA 1234";
$line=~s/([A-z]*)\s+(\d+)/$2/;

print $line; #prints only 1234

If you want to store the value in the new string then

(my $newstring = $line)=~s/([A-z]*)\s+(\d+)/$2/;

print $newstring; #prints only 1234

Just try this:


问:
Showing correct response in Postman but wrong response in Android app
I have a Registration page in android where user enters his/her name, email, phone and password. When I register any new user from the app, the response I am getting is always E/Json response: {"success":false,"msg":"User already Exists"}even when the user does not exists. But when I hit the same query through Postman, I am getting proper response like

```<code>{
  "success": true,
  "msg": "Confirmation Link to activate your account has been sent to your email address",
  "data": {
    "studentId": 8
  }
}
</code>```

If I register with new users through Postman I am getting correct response but from app it is always showing "User already Exists".

Here is my Register Activity :

```<code>public class RegisterActivity extends AppCompatActivity implements ServerRequests.Registereponse {

    private EditText password, phone, email;
    public static EditText name;
    ServerRequests serverRequests;
    JSONParser jsonParser;
    private Button registerButton;
    TextView alreadyMember;

    Editor editor;
    UserSession session;
    SharedPreferences sharedPreferences;

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

        jsonParser = new JSONParser();
        serverRequests = new ServerRequests(getApplicationContext());
        serverRequests.setRegistereponse(this);

        alreadyMember = (TextView) findViewById(R.id.alreadyMember);

        name = (EditText) findViewById(R.id.FName);
        phone = (EditText) findViewById(R.id.PhoneNum);
        email = (EditText) findViewById(R.id.mail);
        password = (EditText) findViewById(R.id.password);
        registerButton = (Button) findViewById(R.id.email_sign_in_button);

        sharedPreferences = getApplicationContext().getSharedPreferences("Reg", 0);
        editor = sharedPreferences.edit();

        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CharSequence temp_emailID = email.getText().toString();
                if (name.getText().toString().length() == 0) {
                    name.setError("Please enter your name");
                    name.requestFocus();

                } else if (phone.getText().toString().length() == 0) {
                    phone.setError("Please enter your phone number");
                    phone.requestFocus();

                } else if (!isValidEmail(temp_emailID)) {
                    email.setError("Please enter valid email");
                    email.requestFocus();

                } else if (password.getText().toString().length() == 0) {
                    password.setError("Please enter password");
                    password.requestFocus();

                } else {

                    try {
                        String Name = name.getText().toString();
                        String Email = email.getText().toString();
                        String Password = password.getText().toString();
                        String Phone = phone.getText().toString();

                        JSONObject obj = jsonParser.makeRegisterJson(Name, Email, Password, Long.parseLong(Phone));
                        Log.e("final Json", obj.toString());
                        serverRequests.register(obj);

                        editor.putString("name", Name);
                        editor.putString("email", Email);
                        editor.putString("password", Password);
                        editor.putString("phone", Phone);
                        editor.commit();
                        //    Toast.makeText(RegisterActivity.this, "Registered Successfully!", Toast.LENGTH_LONG).show();

                    } catch (Exception e) {

                    }
                }

                //   startActivity(new Intent(RegisterActivity.this, LoginActivity.class));

            }
        });

        alreadyMember.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                finish();
            }
        });

    }

    @Override
    public void onRegsiterReposne(JSONObject object) {
        Toast.makeText(RegisterActivity.this, "hiii" + object.toString(), Toast.LENGTH_SHORT).show();

    }

    public final static boolean isValidEmail(CharSequence target) {
        if (TextUtils.isEmpty(target)) {
            return false;
        } else {
            return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
        }
    }

}
</code>```

Here is my Server Request class :

```<code>public void setRegistereponse(Registereponse registereponse) {
        this.registereponse = registereponse;
    }

    private Registereponse registereponse;

    public interface Registereponse {
        void onRegsiterReposne(JSONObject object);
    }

    public void register(JSONObject jsonObject) {

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.REGISTER_URL, jsonObject,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            Log.e("Json response", "" + response);
                            boolean b = response.getBoolean("success");

                            if (registereponse != null) {
                                registereponse.onRegsiterReposne(response);

                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Error ", "" + error);
                    }
                }
        );

        queue.add(jsonObjectRequest);
    }
</code>```

Here is my JSON Parser class :

```<code>public class JSONParser {

    //----------For Register

    public JSONObject makeRegisterJson(String name, String email, String password, long phone) throws JSONException {

        JSONObject object = new JSONObject();

        object.put("name", name);
        object.put("email", email);
        object.put("password", password);
        object.put("phone", phone);
        // if its in array------
       /*JSONObject finalObject=new JSONObject();
       finalObject.put("request",object);
       return finalObject;*/
        return object;
    }
</code>```

Server Side :
I have done coding in Php using codeigniter framework:

This is my controller method:

```<code>public function register_post()
    {
        $data['name']       = $this->post('name');
        $data['email']      = $this->post('email');
        $data['phone']      = $this->post('phone');
        $data['password']   = $this->post('password');

        if (isset($data['name']) && !empty($data['name']) && isset($data['email']) && !empty($data['email']) && isset($data['phone']) && !empty($data['phone']) && isset($data['password']) && !empty($data['password']))
        {

            $model_response=$this->api_model->register_user($data);

            if($model_response == "E101"){
                $data_result['success'] = false;
                $data_result['msg'] = "User already Exists";
            }

            if($model_response == "E103" || $model_response == "E102"){
                $data_result['success'] = false;
                $data_result['msg'] = "Record Not Inserted";
            }
            else
                {
                    $name = $data['name'];
                    $emailid = $data['email'];
                    $link = "<a href=''>Verification Link</a>";
                    $mail = new PHPMailer;
                    $mail->isSMTP();
                    $mail->Debugoutput = 'html';
                    $mail->Host = "dash.dash.in";
                    $mail->Port = 25;
                    $mail->SMTPAuth = true;
                    $mail->isHTML(true);
                    $mail->Username = "dash@dash.in";
                    $mail->Password = "******";
                    $mail->setFrom('dash@dash.in','Training App');
                    $mail->addAddress($emailid, 'Registration');
                    $mail->Subject = 'Registration - Training App';
                    $mail->Body = "<p>Hi $name,<br/><br/>You are successfully registered with us.<br/><br/> Please Click below link to activate your account<br/> Link - $link<br/><br/>If you have any queries or encounter any problems in logging in, please contact us on :<br>dash@dash.com <br/><br/> Thank you.</p>";
                    if($mail->send()){

                        $data_result['success'] = true;
                        $data_result['msg'] = "Confirmation Link to activate your account has been sent to your email address";
                        $data_result['data'] = array('studentId' => $model_response);
                    }else{
                        $data_result['success'] = false;
                        $data_result["msg"] = "Failed to send mail.";
                    }
                }

        }
        else{
            $data_result['success'] = false;
            $data_result['msg'] = "Please Check Your Request";
        }
        $this->response($data_result);
    }
</code>```

This is my model Code:

```<code>public function register_user($data)
        {
            $email = $data['email'];
            $this->db->select('username as email');
            $this->db->where('username',$email);
            $query = $this->db->get('tbl_login');

            if($query->row() > 0)
            {
                return "E101";
            }else{
                $data_l = array(
                'username'  => $data['email'],
                'role'      => 2,
                'password'  => md5($data['password'])
                );
                $this->db->insert('tbl_login', $data_l);
                if ($this->db->affected_rows() == 1) {
                    $loginId = $this->db->insert_id();
                    $data_s = array(
                    'name'  => $data['name'],
                    'email' => $data['email'],
                    'phone' => $data['phone'],
                    'loginId' => $loginId
                    );
                    $this->db->insert('student', $data_s);
                    if ($this->db->affected_rows() == 1) {
                        $studentId = $this->db->insert_id();
                        return $studentId;
                    } else {
                        return "E102";
                    }
                }else {
                    return "E103";
                }
            }
        }
</code>```

I dont know where am I going wrong.

答:
Please have look below your code, just I added one line queue.getCache().clear(); That will work.</p>

```<code>public void setRegistereponse(Registereponse registereponse) {
    this.registereponse = registereponse;
}

private Registereponse registereponse;

public interface Registereponse {
    void onRegsiterReposne(JSONObject object);
}

public void register(JSONObject jsonObject) {

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.REGISTER_URL, jsonObject,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        Log.e("Json response", "" + response);
                        boolean b = response.getBoolean("success");

                        if (registereponse != null) {
                            registereponse.onRegsiterReposne(response);

                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("Error ", "" + error);
                }
            }
    );
    queue.getCache().clear();
    queue.add(jsonObjectRequest);
}
</code>```

Body:
I have a Registration page in android where user enters his/her name, email, phone and password. When I register any new user from the app, the response I am getting is always E/Json response: {"success":false,"msg":"User already Exists"}even when the user does not exists. But when I hit the same query through Postman, I am getting proper response like

{
  "success": true,
  "msg": "Confirmation Link to activate your account has been sent to your email address",
  "data": {
    "studentId": 8
  }
}

If I register with new users through Postman I am getting correct response but from app it is always showing "User already Exists".

Here is my Register Activity :

public class RegisterActivity extends AppCompatActivity implements ServerRequests.Registereponse {

    private EditText password, phone, email;
    public static EditText name;
    ServerRequests serverRequests;
    JSONParser jsonParser;
    private Button registerButton;
    TextView alreadyMember;

    Editor editor;
    UserSession session;
    SharedPreferences sharedPreferences;

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

        jsonParser = new JSONParser();
        serverRequests = new ServerRequests(getApplicationContext());
        serverRequests.setRegistereponse(this);

        alreadyMember = (TextView) findViewById(R.id.alreadyMember);

        name = (EditText) findViewById(R.id.FName);
        phone = (EditText) findViewById(R.id.PhoneNum);
        email = (EditText) findViewById(R.id.mail);
        password = (EditText) findViewById(R.id.password);
        registerButton = (Button) findViewById(R.id.email_sign_in_button);

        sharedPreferences = getApplicationContext().getSharedPreferences("Reg", 0);
        editor = sharedPreferences.edit();

        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CharSequence temp_emailID = email.getText().toString();
                if (name.getText().toString().length() == 0) {
                    name.setError("Please enter your name");
                    name.requestFocus();

                } else if (phone.getText().toString().length() == 0) {
                    phone.setError("Please enter your phone number");
                    phone.requestFocus();

                } else if (!isValidEmail(temp_emailID)) {
                    email.setError("Please enter valid email");
                    email.requestFocus();

                } else if (password.getText().toString().length() == 0) {
                    password.setError("Please enter password");
                    password.requestFocus();

                } else {

                    try {
                        String Name = name.getText().toString();
                        String Email = email.getText().toString();
                        String Password = password.getText().toString();
                        String Phone = phone.getText().toString();

                        JSONObject obj = jsonParser.makeRegisterJson(Name, Email, Password, Long.parseLong(Phone));
                        Log.e("final Json", obj.toString());
                        serverRequests.register(obj);

                        editor.putString("name", Name);
                        editor.putString("email", Email);
                        editor.putString("password", Password);
                        editor.putString("phone", Phone);
                        editor.commit();
                        //    Toast.makeText(RegisterActivity.this, "Registered Successfully!", Toast.LENGTH_LONG).show();

                    } catch (Exception e) {

                    }
                }

                //   startActivity(new Intent(RegisterActivity.this, LoginActivity.class));

            }
        });

        alreadyMember.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                finish();
            }
        });

    }

    @Override
    public void onRegsiterReposne(JSONObject object) {
        Toast.makeText(RegisterActivity.this, "hiii" + object.toString(), Toast.LENGTH_SHORT).show();

    }

    public final static boolean isValidEmail(CharSequence target) {
        if (TextUtils.isEmpty(target)) {
            return false;
        } else {
            return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
        }
    }

}

Here is my Server Request class :

public void setRegistereponse(Registereponse registereponse) {
        this.registereponse = registereponse;
    }

    private Registereponse registereponse;

    public interface Registereponse {
        void onRegsiterReposne(JSONObject object);
    }

    public void register(JSONObject jsonObject) {

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.REGISTER_URL, jsonObject,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            Log.e("Json response", "" + response);
                            boolean b = response.getBoolean("success");

                            if (registereponse != null) {
                                registereponse.onRegsiterReposne(response);

                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Error ", "" + error);
                    }
                }
        );

        queue.add(jsonObjectRequest);
    }

Here is my JSON Parser class :

public class JSONParser {

    //----------For Register

    public JSONObject makeRegisterJson(String name, String email, String password, long phone) throws JSONException {

        JSONObject object = new JSONObject();

        object.put("name", name);
        object.put("email", email);
        object.put("password", password);
        object.put("phone", phone);
        // if its in array------
       /*JSONObject finalObject=new JSONObject();
       finalObject.put("request",object);
       return finalObject;*/
        return object;
    }

Server Side :
I have done coding in Php using codeigniter framework:

This is my controller method:

public function register_post()
    {
        $data['name']       = $this->post('name');
        $data['email']      = $this->post('email');
        $data['phone']      = $this->post('phone');
        $data['password']   = $this->post('password');

        if (isset($data['name']) && !empty($data['name']) && isset($data['email']) && !empty($data['email']) && isset($data['phone']) && !empty($data['phone']) && isset($data['password']) && !empty($data['password']))
        {

            $model_response=$this->api_model->register_user($data);

            if($model_response == "E101"){
                $data_result['success'] = false;
                $data_result['msg'] = "User already Exists";
            }

            if($model_response == "E103" || $model_response == "E102"){
                $data_result['success'] = false;
                $data_result['msg'] = "Record Not Inserted";
            }
            else
                {
                    $name = $data['name'];
                    $emailid = $data['email'];
                    $link = "Verification Link";
                    $mail = new PHPMailer;
                    $mail->isSMTP();
                    $mail->Debugoutput = 'html';
                    $mail->Host = "dash.dash.in";
                    $mail->Port = 25;
                    $mail->SMTPAuth = true;
                    $mail->isHTML(true);
                    $mail->Username = "dash@dash.in";
                    $mail->Password = "******";
                    $mail->setFrom('dash@dash.in','Training App');
                    $mail->addAddress($emailid, 'Registration');
                    $mail->Subject = 'Registration - Training App';
                    $mail->Body = "
Hi $name,

You are successfully registered with us.

 Please Click below link to activate your account
 Link - $link

If you have any queries or encounter any problems in logging in, please contact us on :
dash@dash.com

 Thank you.
";
                    if($mail->send()){

                        $data_result['success'] = true;
                        $data_result['msg'] = "Confirmation Link to activate your account has been sent to your email address";
                        $data_result['data'] = array('studentId' => $model_response);
                    }else{
                        $data_result['success'] = false;
                        $data_result["msg"] = "Failed to send mail.";
                    }
                }

        }
        else{
            $data_result['success'] = false;
            $data_result['msg'] = "Please Check Your Request";
        }
        $this->response($data_result);
    }

This is my model Code:

public function register_user($data)
        {
            $email = $data['email'];
            $this->db->select('username as email');
            $this->db->where('username',$email);
            $query = $this->db->get('tbl_login');

            if($query->row() > 0)
            {
                return "E101";
            }else{
                $data_l = array(
                'username'  => $data['email'],
                'role'      => 2,
                'password'  => md5($data['password'])
                );
                $this->db->insert('tbl_login', $data_l);
                if ($this->db->affected_rows() == 1) {
                    $loginId = $this->db->insert_id();
                    $data_s = array(
                    'name'  => $data['name'],
                    'email' => $data['email'],
                    'phone' => $data['phone'],
                    'loginId' => $loginId
                    );
                    $this->db->insert('student', $data_s);
                    if ($this->db->affected_rows() == 1) {
                        $studentId = $this->db->insert_id();
                        return $studentId;
                    } else {
                        return "E102";
                    }
                }else {
                    return "E103";
                }
            }
        }

I dont know where am I going wrong.

Body:
Please have look below your code, just I added one line queue.getCache().clear(); That will work.

public void setRegistereponse(Registereponse registereponse) {
    this.registereponse = registereponse;
}

private Registereponse registereponse;

public interface Registereponse {
    void onRegsiterReposne(JSONObject object);
}

public void register(JSONObject jsonObject) {

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.REGISTER_URL, jsonObject,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        Log.e("Json response", "" + response);
                        boolean b = response.getBoolean("success");

                        if (registereponse != null) {
                            registereponse.onRegsiterReposne(response);

                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("Error ", "" + error);
                }
            }
    );
    queue.getCache().clear();
    queue.add(jsonObjectRequest);
}


问:
return sample date between min date and max date in R in a dataframe
How to return sample date between min date and max date in R in a dataframe as an additional column?</p>

```<code>Course MinEnrollmentDate MaxEnrollmentDate
Maths 3/11/2016 3/4/2016
Chemistry 6/11/2016 6/4/2016
Physics 9/11/2016 9/4/2016
English 12/11/2016 12/4/2016
Science 3/11/2017 3/4/2017
</code>```

答:
A step by step lubridate solution, for the sake of completeness (using GGamba's df):

```<code>if (!require(lubridate)) {
  install.packages("lubridate")
}

df <-  read.table(text = 'Course MinEnrollmentDate MaxEnrollmentDate
                  Maths 3/11/2016 3/4/2016
                  Chemistry 6/11/2016 6/4/2016
                  Physics 9/11/2016 9/4/2016
                  English 12/11/2016 12/4/2016
                  Science 3/11/2017 3/4/2017', header = T, stringsAsFactors = F)

no_days <- as.POSIXct(df$MinEnrollmentDate, format = "%d/%m/%Y") - as.POSIXct(df$MaxEnrollmentDate, format = "%d/%m/%Y")

random_days <- sapply(no_days, function(x) sample(x = 1:x, size = 1, replace = T) )

df$random_date <- as.POSIXct(df$MinEnrollmentDate, format = "%d/%m/%Y") + days(random_days)
</code>```

Body:
How to return sample date between min date and max date in R in a dataframe as an additional column?

Course MinEnrollmentDate MaxEnrollmentDate
Maths 3/11/2016 3/4/2016
Chemistry 6/11/2016 6/4/2016
Physics 9/11/2016 9/4/2016
English 12/11/2016 12/4/2016
Science 3/11/2017 3/4/2017

Body:
A step by step lubridate solution, for the sake of completeness (using GGamba's df):

if (!require(lubridate)) {
  install.packages("lubridate")
}

df <-  read.table(text = 'Course MinEnrollmentDate MaxEnrollmentDate
                  Maths 3/11/2016 3/4/2016
                  Chemistry 6/11/2016 6/4/2016
                  Physics 9/11/2016 9/4/2016
                  English 12/11/2016 12/4/2016
                  Science 3/11/2017 3/4/2017', header = T, stringsAsFactors = F)

no_days <- as.POSIXct(df$MinEnrollmentDate, format = "%d/%m/%Y") - as.POSIXct(df$MaxEnrollmentDate, format = "%d/%m/%Y")

random_days <- sapply(no_days, function(x) sample(x = 1:x, size = 1, replace = T) )

df$random_date <- as.POSIXct(df$MinEnrollmentDate, format = "%d/%m/%Y") + days(random_days)


问:
Where is the String Receiving Part in this Code? (Bluetooth chat Application)
I just need to Modify the Bluetooth Chat Application.  The String will be Successfully Received in ListView , but i don't have an idea to Where is the String Receiving Part Processing in below Code.

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {

    private EditText et_tnum;
    private EditText et_pass;
    private TextView status;
    private Button btnConnect;
    private ListView listView;
    private Dialog dialog;
    private TextInputLayout inputLayout;
    private ArrayAdapter<String> chatAdapter;
    private ArrayList<String> chatMessages;
    private BluetoothAdapter bluetoothAdapter;

    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_OBJECT = 4;
    public static final int MESSAGE_TOAST = 5;
    public static final String DEVICE_OBJECT = "device_name";

    private static final int REQUEST_ENABLE_BLUETOOTH = 1;
    private ChatController chatController;
    private BluetoothDevice connectingDevice;
    private ArrayAdapter<String> discoveredDevicesAdapter;

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

        //check device support bluetooth or not
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available!", Toast.LENGTH_SHORT).show();
            finish();
        }

        //show bluetooth devices dialog when click connect button
    btnConnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPrinterPickDialog();
            }
        });

        //set chat adapter
        chatMessages = new ArrayList<>();
        chatAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, chatMessages);
        listView.setAdapter(chatAdapter);
    }

    private Handler handler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_STATE_CHANGE:
                    switch (msg.arg1) {
                        case ChatController.STATE_CONNECTED:
                            setStatus("Connected to: " + connectingDevice.getName());
                            btnConnect.setEnabled(false);
                            break;
                        case ChatController.STATE_CONNECTING:
                            setStatus("Connecting...");
                            btnConnect.setEnabled(false);
                            break;
                        case ChatController.STATE_LISTEN:
                        case ChatController.STATE_NONE:
                            setStatus("Not connected");
                            break;
                    }
                    break;
                case MESSAGE_WRITE:
                    byte[] writeBuf = (byte[]) msg.obj;

                    String writeMessage = new String(writeBuf);
                    chatMessages.add("Me: " + writeMessage);
                    chatAdapter.notifyDataSetChanged();
                    break;
                case MESSAGE_READ:
                    byte[] readBuf = (byte[]) msg.obj;

                    String readMessage = new String(readBuf, 0, msg.arg1);
                    chatMessages.add(connectingDevice.getName() + ":  " + readMessage);
                    chatAdapter.notifyDataSetChanged();
                    break;
                case MESSAGE_DEVICE_OBJECT:
                    connectingDevice = msg.getData().getParcelable(DEVICE_OBJECT);
                    Toast.makeText(getApplicationContext(), "Connected to " + connectingDevice.getName(),
                        Toast.LENGTH_SHORT).show();
                    break;
                case MESSAGE_TOAST:
                    Toast.makeText(getApplicationContext(), msg.getData().getString("toast"),
                        Toast.LENGTH_SHORT).show();
                    break;
            }
            return false;
        }
    });

private void showPrinterPickDialog() {
    dialog = new Dialog(this);
    dialog.setContentView(R.layout.layout_bluetooth);
    dialog.setTitle("Bluetooth Devices");

    if (bluetoothAdapter.isDiscovering()) {
        bluetoothAdapter.cancelDiscovery();
    }
    bluetoothAdapter.startDiscovery();

    //Initializing bluetooth adapters
    ArrayAdapter<String> pairedDevicesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
    discoveredDevicesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);

    //locate listviews and attatch the adapters
    ListView listView = (ListView) dialog.findViewById(R.id.pairedDeviceList);
    ListView listView2 = (ListView) dialog.findViewById(R.id.discoveredDeviceList);
    listView.setAdapter(pairedDevicesAdapter);
    listView2.setAdapter(discoveredDevicesAdapter);

    // Register for broadcasts when a device is discovered
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    registerReceiver(discoveryFinishReceiver, filter);

    // Register for broadcasts when discovery has finished
    filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    registerReceiver(discoveryFinishReceiver, filter);

    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();

    // If there are paired devices, add each one to the ArrayAdapter
    if (pairedDevices.size() > 0) {
        for (BluetoothDevice device : pairedDevices) {
            pairedDevicesAdapter.add(device.getName() + "\n" + device.getAddress());
        }
    } else {
        pairedDevicesAdapter.add(getString(R.string.none_paired));
    }

    //Handling listview item click event
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            bluetoothAdapter.cancelDiscovery();
            String info = ((TextView) view).getText().toString();
            String address = info.substring(info.length() - 17);

            connectToDevice(address);
            dialog.dismiss();
        }

    });

    listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            bluetoothAdapter.cancelDiscovery();
            String info = ((TextView) view).getText().toString();
            String address = info.substring(info.length() - 17);

            connectToDevice(address);
            dialog.dismiss();
        }
    });

    dialog.findViewById(R.id.cancelButton).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
    dialog.setCancelable(false);
    dialog.show();
}

private void setStatus(String s) {
    status.setText(s);
}

private void connectToDevice(String deviceAddress) {
    bluetoothAdapter.cancelDiscovery();
    BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
    chatController.connect(device);
}

private void findViewsByIds() {
    status = (TextView) findViewById(R.id.status);
    btnConnect = (Button) findViewById(R.id.btn_connect);
    listView = (ListView) findViewById(R.id.list);
    et_tnum = (EditText) findViewById(R.id.et_tnum);
    et_pass = (EditText) findViewById(R.id.et_pass);
    View btnSend = (Button) findViewById(R.id.btn_send);

}

  btnSend.setOnClickListener(new View.OnClickListener()
 { @Override
  public void onClick(View view)
  { String number =et_tnum.getText().toString();
  String password=et_pass.getText().toString();
  if (et_pass.getText().toString().equals(""))
  { Toast.makeText(MainActivity.this, "Please input some texts", Toast.LENGTH_SHORT).show(); }
  else {
  String numberpass= "Account Number:"+number+"\nPassword:"+password;
  sendMessage(numberpass);
  et_pass.setText("");
  }
  }
  });

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case REQUEST_ENABLE_BLUETOOTH:
            if (resultCode == Activity.RESULT_OK) {
                chatController = new ChatController(this, handler);
            } else {
                Toast.makeText(this, "Bluetooth still disabled, turn off application!", Toast.LENGTH_SHORT).show();
                finish();
            }
     }
 }

 private void sendMessage(String message) {
     if (chatController.getState() != ChatController.STATE_CONNECTED) {
        Toast.makeText(this, "Connection was lost!", Toast.LENGTH_SHORT).show();
        return;
     }

     if (message.length() > 0) {
         byte[] send = message.getBytes();
         chatController.write(send);
     }
 }

 @Override
 public void onStart() {
     super.onStart();
     if (!bluetoothAdapter.isEnabled()) {
         Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
         startActivityForResult(enableIntent, REQUEST_ENABLE_BLUETOOTH);
     } else {
         chatController = new ChatController(this, handler);
     }
 }

 @Override
 public void onResume() {
     super.onResume();

     if (chatController != null) {
         if (chatController.getState() == ChatController.STATE_NONE) {
             chatController.start();
         }
     }
 }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (chatController != null)
            chatController.stop();

    }

    private final BroadcastReceiver discoveryFinishReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    String recieverAddress = device.getName();
                    String recieverPassword = device.getAddress();
                    et_tnum.setText(recieverAddress);
                    et_pass.setText(recieverPassword);
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                if (discoveredDevicesAdapter.getCount() == 0) {
                discoveredDevicesAdapter.add(getString(R.string.none_found));
                }
            }
        }
    };
}
</code>```

activity_main.xml

```<code>   <LinearLayout
    android:layout_width="348dp"
    android:layout_height="80dp"
    android:orientation="vertical">

    <TextView
        android:id="@+id/status"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Not Connected" />

    <Button
        android:id="@+id/btn_connect"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Connect" />
</LinearLayout>

<ListView
    android:id="@+id/list"
    android:layout_width="332dp"
    android:layout_height="164dp" />

<EditText
    android:id="@+id/et_tnum"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="Account Number"
    android:inputType="textEmailAddress|textPersonName" />

<EditText
    android:id="@+id/et_pass"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="Password"
    android:inputType="textPassword" />

<Button
    android:id="@+id/btn_send"
    android:layout_width="213dp"
    android:layout_height="wrap_content"
    android:text="verify" />
</code>```

答:
it's at </p>

```<code>case MESSAGE_READ:
                //read recieved data
                byte[] readBuf = (byte[]) msg.obj;
                //convert recieved data to String
                //readMessage is your String where the recieved message is saved
                String readMessage = new String(readBuf, 0, msg.arg1);
                chatMessages.add(connectingDevice.getName() + ":  " + readMessage);
                chatAdapter.notifyDataSetChanged();
                break;
</code>```

Body:
I just need to Modify the Bluetooth Chat Application.  The String will be Successfully Received in ListView , but i don't have an idea to Where is the String Receiving Part Processing in below Code.

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private EditText et_tnum;
    private EditText et_pass;
    private TextView status;
    private Button btnConnect;
    private ListView listView;
    private Dialog dialog;
    private TextInputLayout inputLayout;
    private ArrayAdapter<String> chatAdapter;
    private ArrayList<String> chatMessages;
    private BluetoothAdapter bluetoothAdapter;

    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_OBJECT = 4;
    public static final int MESSAGE_TOAST = 5;
    public static final String DEVICE_OBJECT = "device_name";

    private static final int REQUEST_ENABLE_BLUETOOTH = 1;
    private ChatController chatController;
    private BluetoothDevice connectingDevice;
    private ArrayAdapter<String> discoveredDevicesAdapter;

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

        //check device support bluetooth or not
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available!", Toast.LENGTH_SHORT).show();
            finish();
        }

        //show bluetooth devices dialog when click connect button
    btnConnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPrinterPickDialog();
            }
        });

        //set chat adapter
        chatMessages = new ArrayList<>();
        chatAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, chatMessages);
        listView.setAdapter(chatAdapter);
    }

    private Handler handler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_STATE_CHANGE:
                    switch (msg.arg1) {
                        case ChatController.STATE_CONNECTED:
                            setStatus("Connected to: " + connectingDevice.getName());
                            btnConnect.setEnabled(false);
                            break;
                        case ChatController.STATE_CONNECTING:
                            setStatus("Connecting...");
                            btnConnect.setEnabled(false);
                            break;
                        case ChatController.STATE_LISTEN:
                        case ChatController.STATE_NONE:
                            setStatus("Not connected");
                            break;
                    }
                    break;
                case MESSAGE_WRITE:
                    byte[] writeBuf = (byte[]) msg.obj;

                    String writeMessage = new String(writeBuf);
                    chatMessages.add("Me: " + writeMessage);
                    chatAdapter.notifyDataSetChanged();
                    break;
                case MESSAGE_READ:
                    byte[] readBuf = (byte[]) msg.obj;

                    String readMessage = new String(readBuf, 0, msg.arg1);
                    chatMessages.add(connectingDevice.getName() + ":  " + readMessage);
                    chatAdapter.notifyDataSetChanged();
                    break;
                case MESSAGE_DEVICE_OBJECT:
                    connectingDevice = msg.getData().getParcelable(DEVICE_OBJECT);
                    Toast.makeText(getApplicationContext(), "Connected to " + connectingDevice.getName(),
                        Toast.LENGTH_SHORT).show();
                    break;
                case MESSAGE_TOAST:
                    Toast.makeText(getApplicationContext(), msg.getData().getString("toast"),
                        Toast.LENGTH_SHORT).show();
                    break;
            }
            return false;
        }
    });

private void showPrinterPickDialog() {
    dialog = new Dialog(this);
    dialog.setContentView(R.layout.layout_bluetooth);
    dialog.setTitle("Bluetooth Devices");

    if (bluetoothAdapter.isDiscovering()) {
        bluetoothAdapter.cancelDiscovery();
    }
    bluetoothAdapter.startDiscovery();

    //Initializing bluetooth adapters
    ArrayAdapter<String> pairedDevicesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
    discoveredDevicesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);

    //locate listviews and attatch the adapters
    ListView listView = (ListView) dialog.findViewById(R.id.pairedDeviceList);
    ListView listView2 = (ListView) dialog.findViewById(R.id.discoveredDeviceList);
    listView.setAdapter(pairedDevicesAdapter);
    listView2.setAdapter(discoveredDevicesAdapter);

    // Register for broadcasts when a device is discovered
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    registerReceiver(discoveryFinishReceiver, filter);

    // Register for broadcasts when discovery has finished
    filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    registerReceiver(discoveryFinishReceiver, filter);

    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();

    // If there are paired devices, add each one to the ArrayAdapter
    if (pairedDevices.size() > 0) {
        for (BluetoothDevice device : pairedDevices) {
            pairedDevicesAdapter.add(device.getName() + "\n" + device.getAddress());
        }
    } else {
        pairedDevicesAdapter.add(getString(R.string.none_paired));
    }

    //Handling listview item click event
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            bluetoothAdapter.cancelDiscovery();
            String info = ((TextView) view).getText().toString();
            String address = info.substring(info.length() - 17);

            connectToDevice(address);
            dialog.dismiss();
        }

    });

    listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            bluetoothAdapter.cancelDiscovery();
            String info = ((TextView) view).getText().toString();
            String address = info.substring(info.length() - 17);

            connectToDevice(address);
            dialog.dismiss();
        }
    });

    dialog.findViewById(R.id.cancelButton).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
    dialog.setCancelable(false);
    dialog.show();
}

private void setStatus(String s) {
    status.setText(s);
}

private void connectToDevice(String deviceAddress) {
    bluetoothAdapter.cancelDiscovery();
    BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
    chatController.connect(device);
}

private void findViewsByIds() {
    status = (TextView) findViewById(R.id.status);
    btnConnect = (Button) findViewById(R.id.btn_connect);
    listView = (ListView) findViewById(R.id.list);
    et_tnum = (EditText) findViewById(R.id.et_tnum);
    et_pass = (EditText) findViewById(R.id.et_pass);
    View btnSend = (Button) findViewById(R.id.btn_send);

}

  btnSend.setOnClickListener(new View.OnClickListener()
 { @Override
  public void onClick(View view)
  { String number =et_tnum.getText().toString();
  String password=et_pass.getText().toString();
  if (et_pass.getText().toString().equals(""))
  { Toast.makeText(MainActivity.this, "Please input some texts", Toast.LENGTH_SHORT).show(); }
  else {
  String numberpass= "Account Number:"+number+"\nPassword:"+password;
  sendMessage(numberpass);
  et_pass.setText("");
  }
  }
  });

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case REQUEST_ENABLE_BLUETOOTH:
            if (resultCode == Activity.RESULT_OK) {
                chatController = new ChatController(this, handler);
            } else {
                Toast.makeText(this, "Bluetooth still disabled, turn off application!", Toast.LENGTH_SHORT).show();
                finish();
            }
     }
 }

 private void sendMessage(String message) {
     if (chatController.getState() != ChatController.STATE_CONNECTED) {
        Toast.makeText(this, "Connection was lost!", Toast.LENGTH_SHORT).show();
        return;
     }

     if (message.length() > 0) {
         byte[] send = message.getBytes();
         chatController.write(send);
     }
 }

 @Override
 public void onStart() {
     super.onStart();
     if (!bluetoothAdapter.isEnabled()) {
         Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
         startActivityForResult(enableIntent, REQUEST_ENABLE_BLUETOOTH);
     } else {
         chatController = new ChatController(this, handler);
     }
 }

 @Override
 public void onResume() {
     super.onResume();

     if (chatController != null) {
         if (chatController.getState() == ChatController.STATE_NONE) {
             chatController.start();
         }
     }
 }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (chatController != null)
            chatController.stop();

    }

    private final BroadcastReceiver discoveryFinishReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    String recieverAddress = device.getName();
                    String recieverPassword = device.getAddress();
                    et_tnum.setText(recieverAddress);
                    et_pass.setText(recieverPassword);
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                if (discoveredDevicesAdapter.getCount() == 0) {
                discoveredDevicesAdapter.add(getString(R.string.none_found));
                }
            }
        }
    };
}

activity_main.xml

   <LinearLayout
    android:layout_width="348dp"
    android:layout_height="80dp"
    android:orientation="vertical">

    <TextView
        android:id="@+id/status"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Not Connected" />

    <Button
        android:id="@+id/btn_connect"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Connect" />
</LinearLayout>

<ListView
    android:id="@+id/list"
    android:layout_width="332dp"
    android:layout_height="164dp" />

<EditText
    android:id="@+id/et_tnum"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="Account Number"
    android:inputType="textEmailAddress|textPersonName" />

<EditText
    android:id="@+id/et_pass"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="Password"
    android:inputType="textPassword" />

<Button
    android:id="@+id/btn_send"
    android:layout_width="213dp"
    android:layout_height="wrap_content"
    android:text="verify" />

Body:
it's at

case MESSAGE_READ:
                //read recieved data
                byte[] readBuf = (byte[]) msg.obj;
                //convert recieved data to String
                //readMessage is your String where the recieved message is saved
                String readMessage = new String(readBuf, 0, msg.arg1);
                chatMessages.add(connectingDevice.getName() + ":  " + readMessage);
                chatAdapter.notifyDataSetChanged();
                break;


问:
RISCV : spike pk hello returns Failed to run
I am new to both RISCV and Ubuntu(64it) env. Have no idea how to solve this problem.

I built the RISCV toolchain and could compile hello.c by using the command "riscv64-unknown-elf-gcc -o hello hello.c" The hello object file is sucessfully generated.

However, when I executed "spike pk hello" it returns
"Failed to run : No such file or directory
 Child dts process failed"

I thought there is something to do with path. So, I went to riscv/bin/ where spike is located and executed "./spike", it gives me exactly the same result.

What would you suggest ? I am totally stuck......

答:
You should install dtc. Use "sudo apt-get install device-tree-compiler"

After installing that package, you will unfortunately have to rebuild the toolchain to get it to notice that it was installed.


问:
CASCADE Delete mysql
I'm creating a small 3-table database, essentially using it as a buffer for data, so it's using ENGINER = MEMORY. The database has the following structure:

I'm not that much into MySQL, so my question is: Is it possible to have a CASCADE DELETE, such that when I delete a MeassurementIteration, all MeassurementSet's and Meassurements that are coupled to the iteration will be deleted?

The code:

```<code>-- Last modification date: 2017-04-03 08:09:06.263

-- tables
-- Table: Meassurement
CREATE TABLE Meassurement (
    id int NOT NULL AUTO_INCREMENT,
    msWay varchar(75) NOT NULL,
    qosClass int NOT NULL,
    timeReceived timestamp NOT NULL,
    timeReceivedFarEnd timestamp NOT NULL,
    timeSent timestamp NOT NULL,
    timeSentFarEnd timestamp NULL,
    seq int NOT NULL,
    MeassurementSet_id int NOT NULL,
    CONSTRAINT Meassurement_pk PRIMARY KEY (id)
) ENGINE MEMORY COMMENT 'Contains data for a single meassurement';

-- Table: MeassurementIteration
CREATE TABLE MeassurementIteration (
    id int NOT NULL AUTO_INCREMENT,
    start timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    end timestamp NULL,
    active bool NOT NULL,
    CONSTRAINT MeassurementIteration_pk PRIMARY KEY (id)
);

-- Table: MeassurementSet
CREATE TABLE MeassurementSet (
    id int NOT NULL AUTO_INCREMENT,
    avgDelayRT double NULL,
    avgDelayTR double NULL,
    avgRTD double NULL,
    maxDelayRT double NULL,
    maxDelayTR double NULL,
    maxRTD double NULL,
    minRTD double NULL,
    minDelayRT double NULL,
    minDelayTR double NULL,
    qosClass int NOT NULL,
    stdDev double NULL,
    stdDevRT double NULL,
    stdDevTR double NULL,
    msWay varchar(75) NOT NULL,
    MeassurementIteration_id int NOT NULL,
    CONSTRAINT MeassurementSet_pk PRIMARY KEY (id)
) ENGINE MEMORY COMMENT 'Contains a set of meassurements specific to a qosclass and Meassurementway';

-- foreign keys
-- Reference: MeassurementSet_MeassurementIteration (table: MeassurementSet)
ALTER TABLE MeassurementSet
    ADD CONSTRAINT MeassurementSet_MeassurementIteration
    FOREIGN KEY MeassurementSet_MeassurementIteration (MeassurementIteration_id)
        REFERENCES MeassurementIteration (id) ON DELETE CASCADE;

-- Reference: Meassurement_MeassurementSet (table: Meassurement)
ALTER TABLE Meassurement
    ADD CONSTRAINT Meassurement_MeassurementSet
    FOREIGN KEY Meassurement_MeassurementSet (MeassurementSet_id)
        REFERENCES MeassurementSet (id) ON DELETE CASCADE;

-- End of file.
</code>```

Best regards.

答:
You cannot use ON DELETE CASCADE with ENGINE = MEMORY.
The foreign key is not supported.

Here a reference: (MySQL Doc.)[https://dev.mysql.com/doc/refman/5.6/en/memory-storage-engine.html]

```<code> Table 15.4 MEMORY Storage Engine Features
 ---------------------------------------------------
 Foreign key support    No
</code>```

You can check this too, another similar question.
MySql memory engine do not check on update foreign key?

Title: CASCADE Delete mysql

Body:
I'm creating a small 3-table database, essentially using it as a buffer for data, so it's using ENGINER = MEMORY. The database has the following structure:

I'm not that much into MySQL, so my question is: Is it possible to have a CASCADE DELETE, such that when I delete a MeassurementIteration, all MeassurementSet's and Meassurements that are coupled to the iteration will be deleted?

The code:

-- Last modification date: 2017-04-03 08:09:06.263

-- tables
-- Table: Meassurement
CREATE TABLE Meassurement (
    id int NOT NULL AUTO_INCREMENT,
    msWay varchar(75) NOT NULL,
    qosClass int NOT NULL,
    timeReceived timestamp NOT NULL,
    timeReceivedFarEnd timestamp NOT NULL,
    timeSent timestamp NOT NULL,
    timeSentFarEnd timestamp NULL,
    seq int NOT NULL,
    MeassurementSet_id int NOT NULL,
    CONSTRAINT Meassurement_pk PRIMARY KEY (id)
) ENGINE MEMORY COMMENT 'Contains data for a single meassurement';

-- Table: MeassurementIteration
CREATE TABLE MeassurementIteration (
    id int NOT NULL AUTO_INCREMENT,
    start timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    end timestamp NULL,
    active bool NOT NULL,
    CONSTRAINT MeassurementIteration_pk PRIMARY KEY (id)
);

-- Table: MeassurementSet
CREATE TABLE MeassurementSet (
    id int NOT NULL AUTO_INCREMENT,
    avgDelayRT double NULL,
    avgDelayTR double NULL,
    avgRTD double NULL,
    maxDelayRT double NULL,
    maxDelayTR double NULL,
    maxRTD double NULL,
    minRTD double NULL,
    minDelayRT double NULL,
    minDelayTR double NULL,
    qosClass int NOT NULL,
    stdDev double NULL,
    stdDevRT double NULL,
    stdDevTR double NULL,
    msWay varchar(75) NOT NULL,
    MeassurementIteration_id int NOT NULL,
    CONSTRAINT MeassurementSet_pk PRIMARY KEY (id)
) ENGINE MEMORY COMMENT 'Contains a set of meassurements specific to a qosclass and Meassurementway';

-- foreign keys
-- Reference: MeassurementSet_MeassurementIteration (table: MeassurementSet)
ALTER TABLE MeassurementSet
    ADD CONSTRAINT MeassurementSet_MeassurementIteration
    FOREIGN KEY MeassurementSet_MeassurementIteration (MeassurementIteration_id)
        REFERENCES MeassurementIteration (id) ON DELETE CASCADE;

-- Reference: Meassurement_MeassurementSet (table: Meassurement)
ALTER TABLE Meassurement
    ADD CONSTRAINT Meassurement_MeassurementSet
    FOREIGN KEY Meassurement_MeassurementSet (MeassurementSet_id)
        REFERENCES MeassurementSet (id) ON DELETE CASCADE;

-- End of file.

Best regards.

Body:
You cannot use ON DELETE CASCADE with ENGINE = MEMORY.
The foreign key is not supported.

Here a reference: (MySQL Doc.)[https://dev.mysql.com/doc/refman/5.6/en/memory-storage-engine.html]

 Table 15.4 MEMORY Storage Engine Features
 ---------------------------------------------------
 Foreign key support    No

You can check this too, another similar question.
MySql memory engine do not check on update foreign key?


问:
Error 'LoadImage Type' is not declared. It may be inaccessible due to its protection level
I got above error after copying and pasting some code from here, github.
Will you guys help me to fix it? my code:

```<code>Imports Emgu.CV                 'usual Emgu Cv imports
Imports Emgu.CV.CvEnum          '
Imports Emgu.CV.Structure       '
Imports Emgu.CV.UI
Public Class frmMain
    Private Sub btnOpenFile_Click(sender As Object, e As EventArgs) Handles btnOpenFile.Click
</code>```

The LoadImageType gives me some suggestions, I tried but didn't get helpful.

```<code>            imgOriginal = New Mat(ofdOpenFile.FileName, LoadImageType.Color)
        Catch ex As Exception
        CvInvoke.GaussianBlur(imgGrayscale, imgBlurred, New Size(5, 5), 1.5)
        CvInvoke.Canny(imgBlurred, imgCanny, 100, 200)
        ibOriginal.Image = imgOriginal              'update image boxes
        ibCanny.Image = imgCanny                    '
    End Sub
End Class
</code>```

this is the error:

答:
I notice you created your own class called LoadImageType.vb. However, LoadImageType is already a OpenCV enum. You get this error because you probably don't refer to this class at all or you don't initialize it (see also this link).

I would recommend you to remove this custom class that you created and use the OpenCV enum. This enum is located in the Emgu.CV.CvEnum namespace. Maybe specifically specify you want to use the CVEnum namespace:

```<code>imgOriginal = New Mat(ofdOpenFile.FileName, CvEnum.LoadImageType.Color)
'You can even try this
imgOriginal = New Mat(ofdOpenFile.FileName, Emgu.CV.CvEnum.LoadImageType.Color)
</code>```

If this doesn't work, why don't you try to see if you can specifically enter a integer? The LoadImageType enum is nothing else then a conversion to a integer (see docs). So for color, you should enter value 1. If this works, you know something goes wrong with using the enumeration:

```<code>imgOriginal = New Mat(ofdOpenFile.FileName, 1)
</code>```

If this still doesn't work, why don't you just use the imread method (see docs)? I always use that one without a LoadImageType enum and have no problems at all:

```<code>Dim img As Mat
img = CvInvoke.Imread(ofdOpenFile.FileName)
</code>```

Or if you specifically want to use LoadImageType you can also try:

```<code>Dim img As Mat
img = CvInvoke.Imread(ofdOpenFile.FileName, CvEnum.LoadImageType.Color)
</code>```

Body:
I got above error after copying and pasting some code from here, github.
Will you guys help me to fix it? my code:

Imports Emgu.CV                 'usual Emgu Cv imports
Imports Emgu.CV.CvEnum          '
Imports Emgu.CV.Structure       '
Imports Emgu.CV.UI
Public Class frmMain
    Private Sub btnOpenFile_Click(sender As Object, e As EventArgs) Handles btnOpenFile.Click

The LoadImageType gives me some suggestions, I tried but didn't get helpful.

            imgOriginal = New Mat(ofdOpenFile.FileName, LoadImageType.Color)
        Catch ex As Exception
        CvInvoke.GaussianBlur(imgGrayscale, imgBlurred, New Size(5, 5), 1.5)
        CvInvoke.Canny(imgBlurred, imgCanny, 100, 200)
        ibOriginal.Image = imgOriginal              'update image boxes
        ibCanny.Image = imgCanny                    '
    End Sub
End Class

this is the error:

Body:
I notice you created your own class called LoadImageType.vb. However, LoadImageType is already a OpenCV enum. You get this error because you probably don't refer to this class at all or you don't initialize it (see also this link).

I would recommend you to remove this custom class that you created and use the OpenCV enum. This enum is located in the Emgu.CV.CvEnum namespace. Maybe specifically specify you want to use the CVEnum namespace:

imgOriginal = New Mat(ofdOpenFile.FileName, CvEnum.LoadImageType.Color)
'You can even try this
imgOriginal = New Mat(ofdOpenFile.FileName, Emgu.CV.CvEnum.LoadImageType.Color)

If this doesn't work, why don't you try to see if you can specifically enter a integer? The LoadImageType enum is nothing else then a conversion to a integer (see docs). So for color, you should enter value 1. If this works, you know something goes wrong with using the enumeration:

imgOriginal = New Mat(ofdOpenFile.FileName, 1)

If this still doesn't work, why don't you just use the imread method (see docs)? I always use that one without a LoadImageType enum and have no problems at all:

Dim img As Mat
img = CvInvoke.Imread(ofdOpenFile.FileName)

Or if you specifically want to use LoadImageType you can also try:

Dim img As Mat
img = CvInvoke.Imread(ofdOpenFile.FileName, CvEnum.LoadImageType.Color)


问:
Laravel: Skip some params from route or call Controller@show without adding 'static' adding

Laravel: 5.4

It works, But I want to know if there are other pro-solutions.

I have a route like this

```<code>Route::get('{any}-a{id}', function($any, $id) {
   return ArticleController::show($id);
})->where(['id' => '[0-9]+', 'any' => '.*']);
</code>```

But this required public **static** function show($id)

Are there any other solution to call non-static function from Route, or just skip the $any params like ->compact('id') (in Route), or:
Route::get('#something-I-don't-know#-a{id}'), function(**$id**) { ... })?

I want to keep the non-static show function because it come from Route:resource of another Route: route('articles.show',$article->id). I don't want to add the $any param.

Thanks for your time and your answers :D

答:
You could always do this instead of calling static methods:

```<code>app()->make('App\Http\Controllers\ArticleController')->show($id);
</code>```

Full code would be like this:

```<code>Route::get('{any}-a{id}', function($any, $id) {
   return app()->make('App\Http\Controllers\ArticleController')->show($id);
})->where(['id' => '[0-9]+', 'any' => '.*']);
</code>```

Body:
Laravel: 5.4

It works, But I want to know if there are other pro-solutions.

I have a route like this

Route::get('{any}-a{id}', function($any, $id) {
   return ArticleController::show($id);
})->where(['id' => '[0-9]+', 'any' => '.*']);

But this required public **static** function show($id)

Are there any other solution to call non-static function from Route, or just skip the $any params like ->compact('id') (in Route), or:
Route::get('#something-I-don't-know#-a{id}'), function(**$id**) { ... })?

I want to keep the non-static show function because it come from Route:resource of another Route: route('articles.show',$article->id). I don't want to add the $any param.

Thanks for your time and your answers :D

Body:
You could always do this instead of calling static methods:

app()->make('App\Http\Controllers\ArticleController')->show($id);

Full code would be like this:

Route::get('{any}-a{id}', function($any, $id) {
   return app()->make('App\Http\Controllers\ArticleController')->show($id);
})->where(['id' => '[0-9]+', 'any' => '.*']);


问:
Editing crontab using a script
I am trying to write an embedded application upgrade script. I am running my application on Ubuntu on Beaglebone Black.

Right not, I am launching my application on power-up. To do this, I am running launch.sh script in crontab.

This script is as mentioned below:

```<code>until /root/aa_main; do
    echo "Application aa_main crashed with exit code $?. Respawning.." >&2
    echo "Crashed! $(date)" >> crashlog.txt
    sudo sync
    sudo reboot
done
</code>```

It basically, reboots the system if my application crashes, and crontab launches the application again on reboot.

The problem is that if I want to update the application. I have to perform following steps:

Disable launching of the above script with crontab -e

Reboot

Copy and replace aa_main

Enable launching of the same script with crontab -e

Reboot

I want to automate this process. How can I do it?
Is it possible to edit crontab using a script?

Thanks in advance

答:
You can use crontab command's other options to copy the crontab to a file, modify it and install the modify version from a script:

crontab -l would list the current crontab file, you can redirect this to a file of your choice and modify it

crontab <filename> would install the file specified by <filename> as the new crontab - use this option with your  modified file and you'll get the new modified crontab

Title: Editing crontab using a script

Body:
I am trying to write an embedded application upgrade script. I am running my application on Ubuntu on Beaglebone Black.

Right not, I am launching my application on power-up. To do this, I am running launch.sh script in crontab.

This script is as mentioned below:

until /root/aa_main; do
    echo "Application aa_main crashed with exit code $?. Respawning.." >&2
    echo "Crashed! $(date)" >> crashlog.txt
    sudo sync
    sudo reboot
done

It basically, reboots the system if my application crashes, and crontab launches the application again on reboot.

The problem is that if I want to update the application. I have to perform following steps:

Disable launching of the above script with crontab -e

Reboot

Copy and replace aa_main

Enable launching of the same script with crontab -e

Reboot

I want to automate this process. How can I do it?
Is it possible to edit crontab using a script?

Thanks in advance


问:
What is Repository Key in SonarQube Plugin ?
I develop a plugin for Sonarqube and I follow the sonarqube plugin code example. But I don't understand what is the REPO_KEY and REPO_NAME constant in this file

This Key is use in parameter of this function.

Is there a link with the xml file who define the rules ?

Thank you.

TF.

答:
The repository is the group of rules provided by the plugin. For example the Findbugs plugin defines a repository which is key is "findbugs" and display name is "Findbugs".

You can find more information about the XML format here: http://javadocs.sonarsource.org/6.3/apidocs/org/sonar/api/server/rule/RulesDefinitionXmlLoader.html


问:
Assigning continuous fill color to geom_bar
I am generating a bar chart from data that is in the following format:

```<code>count | month
------|-----------
1000  | 2012-01-01
10000 | 2012-02-01
</code>```

I am trying to assign continuous colors to my bar chart. I want a gradient of colors to be used as the fill color of the bars.

I am trying this:

```<code>ggplot(userData, aes(month, count)) +
    geom_bar(stat = "identity") +
    scale_x_date() +
    # scale_fill_gradient(low="blue", high="red") +
    scale_fill_continuous(low="blue", high="red", limits=c(0,6500000)) +
    labs(x= "Time", y="Count")
</code>```

However, I am not getting the desired result and the bars in the chart still stays gray as can be seen below:

I have tried with both scale_fill_continuous, and scale_fill_gradient, but without success.

I am not sure exactly what I am missing here.

答:
You haven't assigned the fill aesthetic to anything: aes(month, count, fill = count) should do the trick.

Complete code:

```<code>ggplot(userData, aes(month, count, fill = count)) +
    geom_bar(stat = "identity") +
    scale_x_date() +
    scale_fill_continuous(low="blue", high="red") +
    labs(x= "Time", y="Count")
</code>```

(limits are probably useless now, but feel free to add them back)

Body:
I am generating a bar chart from data that is in the following format:

count | month
------|-----------
1000  | 2012-01-01
10000 | 2012-02-01

I am trying to assign continuous colors to my bar chart. I want a gradient of colors to be used as the fill color of the bars.

I am trying this:

ggplot(userData, aes(month, count)) +
    geom_bar(stat = "identity") +
    scale_x_date() +
    # scale_fill_gradient(low="blue", high="red") +
    scale_fill_continuous(low="blue", high="red", limits=c(0,6500000)) +
    labs(x= "Time", y="Count")

However, I am not getting the desired result and the bars in the chart still stays gray as can be seen below:

I have tried with both scale_fill_continuous, and scale_fill_gradient, but without success.

I am not sure exactly what I am missing here.

Body:
You haven't assigned the fill aesthetic to anything: aes(month, count, fill = count) should do the trick.

Complete code:

ggplot(userData, aes(month, count, fill = count)) +
    geom_bar(stat = "identity") +
    scale_x_date() +
    scale_fill_continuous(low="blue", high="red") +
    labs(x= "Time", y="Count")

(limits are probably useless now, but feel free to add them back)


问:
How to handle a wait() method call in JUnit test case?
I have a method that has another method call whose definition has a SomeIntegerObject.wait() call. Now when I run my test case, due to this wait method, the test case keeps waiting and doesn't execute.

I tried adding a timeout at @Test annotation but that causes an exception like "test timed out".

The test method:

```<code>private PastingResult result;
public PastingResult pasteImages(IIOImage[] images, byte pasteProcessType){
     result = new PastingResult();
     _reprocessingProvider.setListLogicHandler(this);
     //--some more method calls--
    waitForResult(); //causes my test case to wait forever and pauses execution
    return result;
}
</code>```

Test case:

```<code>@Test
    public void testPasteImagesIIOImageArrayByte() throws Exception
    {
        ReprocessManager _reprocessingProvider1=Mockito.mock(ReprocessManager.class);
        Whitebox.setInternalState(imagePasterIfImpl, "_reprocessingProvider", _reprocessingProvider1);

        IIOImage[] images=new IIOImage[]{Mockito.mock(IIOImage.class),Mockito.mock(IIOImage.class)};
        byte pasteProcessType = 02;

        PastingResult result= imagePasterIfImpl.pasteImages(images, pasteProcessType);
        Mockito.verify(_reprocessingProvider1).setListLogicHandler(imagePasterIfImpl);
        System.out.println(result+"is the result");
    }
</code>```

Definition of waitForResult();

```<code>private Integer processingWaitMonitor = new Integer(0);
private void waitForResult() {
       // synchronize to wait on the Monitor..
       synchronized(processingWaitMonitor) {
           try {
               processingWaitMonitor.wait();
           }
           catch(Exception e) {
               System.out.println("Exception during Wait !"+e);
           }
       }
   }
</code>```

答:
The module which is going in waiting, put that in a new thread in junit test case. After intervals, check if thread is completed or not. Set a maximum timeout for intervals. After the time out happened, check for thread completion and take decision if you want to pass it or fail it.

For example:

```<code>private static final int MAX_WAIT_TIME = 20000; //total time out in milliseconds
private static final int WAIT_INTERVAL = 1000; //wait interval till MAX_WAIT_TIME

@Test
public void testPasteImagesIIOImageArrayByte() throws Exception
{
  Thread t = new MyThread();
  t.start();
  int totalWaitTime = 0;
  while ((!t.isCompleted()) && totalWaitTime <= MAX_WAIT_TIME) {
    try {
        totalWaitTime += WAIT_INTERVAL;
        Thread.sleep(WAIT_INTERVAL);
    } catch (java.lang.InterruptedException e) {
        //LOG OR THROW
    }
    if(!t.isCompleted()){
      if(t.hasExceptionOccurred()){
        //fail the case
      }else{
        //take your decision here, if you want to pass it or fail it
      }
    }
  }
}

class MyThead extends Thread{
  private volatile boolean isCompleted = false;
  private volatile Throwable exception = null;
  private volatile boolean hasExceptionOccured = false;

  public void run(){
    try{
        ReprocessManager _reprocessingProvider1=Mockito.mock(ReprocessManager.class);
        Whitebox.setInternalState(imagePasterIfImpl, "_reprocessingProvider", _reprocessingProvider1);

        IIOImage[] images=new IIOImage[]{Mockito.mock(IIOImage.class),Mockito.mock(IIOImage.class)};
        byte pasteProcessType = 02;

        PastingResult result= imagePasterIfImpl.pasteImages(images, pasteProcessType);
        Mockito.verify(_reprocessingProvider1).setListLogicHandler(imagePasterIfImpl);
        System.out.println(result+"is the result");

        synchronized(this){
          isCompleted = true;
        }
    }catch(Throwable ex){
        synchronized(this){
            exception = ex;
            hasExceptionOccured = true;
        }
    }
  }

  public synchronized boolean isCompleted(){
    return isCompleted;
  }

  public synchronized boolean hasExceptionOccurred(){
    return hasExceptionOccured;
  }

  public synchronized Throwable getExceptionOccurred(){
    return exception;
  }
}
</code>```

Body:
I have a method that has another method call whose definition has a SomeIntegerObject.wait() call. Now when I run my test case, due to this wait method, the test case keeps waiting and doesn't execute.

I tried adding a timeout at @Test annotation but that causes an exception like "test timed out".

The test method:

private PastingResult result;
public PastingResult pasteImages(IIOImage[] images, byte pasteProcessType){
     result = new PastingResult();
     _reprocessingProvider.setListLogicHandler(this);
     //--some more method calls--
    waitForResult(); //causes my test case to wait forever and pauses execution
    return result;
}

Test case:

@Test
    public void testPasteImagesIIOImageArrayByte() throws Exception
    {
        ReprocessManager _reprocessingProvider1=Mockito.mock(ReprocessManager.class);
        Whitebox.setInternalState(imagePasterIfImpl, "_reprocessingProvider", _reprocessingProvider1);

        IIOImage[] images=new IIOImage[]{Mockito.mock(IIOImage.class),Mockito.mock(IIOImage.class)};
        byte pasteProcessType = 02;

        PastingResult result= imagePasterIfImpl.pasteImages(images, pasteProcessType);
        Mockito.verify(_reprocessingProvider1).setListLogicHandler(imagePasterIfImpl);
        System.out.println(result+"is the result");
    }

Definition of waitForResult();

private Integer processingWaitMonitor = new Integer(0);
private void waitForResult() {
       // synchronize to wait on the Monitor..
       synchronized(processingWaitMonitor) {
           try {
               processingWaitMonitor.wait();
           }
           catch(Exception e) {
               System.out.println("Exception during Wait !"+e);
           }
       }
   }

Body:
The module which is going in waiting, put that in a new thread in junit test case. After intervals, check if thread is completed or not. Set a maximum timeout for intervals. After the time out happened, check for thread completion and take decision if you want to pass it or fail it.

For example:

private static final int MAX_WAIT_TIME = 20000; //total time out in milliseconds
private static final int WAIT_INTERVAL = 1000; //wait interval till MAX_WAIT_TIME

@Test
public void testPasteImagesIIOImageArrayByte() throws Exception
{
  Thread t = new MyThread();
  t.start();
  int totalWaitTime = 0;
  while ((!t.isCompleted()) && totalWaitTime <= MAX_WAIT_TIME) {
    try {
        totalWaitTime += WAIT_INTERVAL;
        Thread.sleep(WAIT_INTERVAL);
    } catch (java.lang.InterruptedException e) {
        //LOG OR THROW
    }
    if(!t.isCompleted()){
      if(t.hasExceptionOccurred()){
        //fail the case
      }else{
        //take your decision here, if you want to pass it or fail it
      }
    }
  }
}

class MyThead extends Thread{
  private volatile boolean isCompleted = false;
  private volatile Throwable exception = null;
  private volatile boolean hasExceptionOccured = false;

  public void run(){
    try{
        ReprocessManager _reprocessingProvider1=Mockito.mock(ReprocessManager.class);
        Whitebox.setInternalState(imagePasterIfImpl, "_reprocessingProvider", _reprocessingProvider1);

        IIOImage[] images=new IIOImage[]{Mockito.mock(IIOImage.class),Mockito.mock(IIOImage.class)};
        byte pasteProcessType = 02;

        PastingResult result= imagePasterIfImpl.pasteImages(images, pasteProcessType);
        Mockito.verify(_reprocessingProvider1).setListLogicHandler(imagePasterIfImpl);
        System.out.println(result+"is the result");

        synchronized(this){
          isCompleted = true;
        }
    }catch(Throwable ex){
        synchronized(this){
            exception = ex;
            hasExceptionOccured = true;
        }
    }
  }

  public synchronized boolean isCompleted(){
    return isCompleted;
  }

  public synchronized boolean hasExceptionOccurred(){
    return hasExceptionOccured;
  }

  public synchronized Throwable getExceptionOccurred(){
    return exception;
  }
}


问:
rendering the small columnrange intervalles as png image too
I am rendering 4 columnRange in my HighChart and facing the problem that the small intervalles (one minutes intervall for example A has 12:51-12:52 and 12:56-12:57 )
are not being rendered when printing the result as png image. Is there any configuration in HighCharts to get around that?

https://jsfiddle.net/LLExL/7288/

```<code>Highcharts.chart('container',
{
    chart: {
        type: 'columnrange',
        inverted: true,
        height: 192,
        spacingLeft: 10
    },
    credits: {
        enabled: false
    },
    title: {
        text: null,
        style: {
            "fontSize": "8px"
        }
    },
    subTitle: {
        text: null
    },
    legend: {
        enabled: false,
    },
    plotOptions: {
        series: {
            pointWidth: 30
        }
    },
    xAxis: {
        min: 1,
        max: 4,
        categories: ['', 'A', 'B', 'C', 'D'],
        title: {
            text: null
        },
        labels: {
            rotation: -45,
            style: {
                "fontSize": "7px"
            }
        },
        gridLineWidth: 0
    },
    yAxis: {
        type: 'datetime',
        title: {
            text: null
        },
        labels: {
            rotation: -45,
            style: {
                "fontSize": "6px"
            }
        },
        tickInterval: 1800000,
        gridLineWidth: 1
    },
    series: [{
        data: [{
                x: 1,
                low: 1483336800000,
                high: 1483336860000,
                color: '#66ccff'
            },
            {
                x: 2,
                low: 1483336860000,
                high: 1483337340000,
                color: '#ff9966'
            },
            {
                x: 1,
                low: 1483337340000,
                high: 1483337400000,
                color: '#66ccff'
            },
            {
                x: 2,
                low: 1483337400000,
                high: 1483337700000,
                color: '#ff9966'
            },
            {
                x: 1,
                low: 1483337700000,
                high: 1483339920000,
                color: '#66ccff'
            },
            {
                x: 3,
                low: 1483339920000,
                high: 1483341780000,
                color: '#79d279'
            },
            {
                x: 2,
                low: 1483341780000,
                high: 1483342260000,
                color: '#ff9966'
            },
            {
                x: 3,
                low: 1483342260000,
                high: 1483345080000,
                color: '#79d279'
            },
            {
                x: 1,
                low: 1483345080000,
                high: 1483345140000,
                color: '#66ccff'
            },
            {
                x: 3,
                low: 1483345140000,
                high: 1483346400000,
                color: '#79d279'
            },
            {
                x: 1,
                low: 1483346400000,
                high: 1483346460000,
                color: '#66ccff'
            },
            {
                x: 3,
                low: 1483346460000,
                high: 1483347420000,
                color: '#79d279'
            },
            {
                x: 1,
                low: 1483347420000,
                high: 1483347600000,
                color: '#66ccff'
            },
            {
                x: 2,
                low: 1483347600000,
                high: 1483347780000,
                color: '#ff9966'
            },
            {
                x: 1,
                low: 1483347780000,
                high: 1483348020000,
                color: '#66ccff'
            },
            {
                x: 3,
                low: 1483348020000,
                high: 1483348200000,
                color: '#79d279'
            },
            {
                x: 1,
                low: 1483348200000,
                high: 1483352460000,
                color: '#66ccff'
            },
            {
                x: 3,
                low: 1483352460000,
                high: 1483352640000,
                color: '#79d279'
            },
            {
                x: 1,
                low: 1483352640000,
                high: 1483352700000,
                color: '#66ccff'
            },
            {
                x: 3,
                low: 1483352700000,
                high: 1483353840000,
                color: '#79d279'
            },
            {
                x: 1,
                low: 1483353840000,
                high: 1483354920000,
                color: '#66ccff'
            },
            {
                x: 3,
                low: 1483354920000,
                high: 1483355160000,
                color: '#79d279'
            },
            {
                x: 1,
                low: 1483355160000,
                high: 1483359480000,
                color: '#66ccff'
            },
            {
                x: 3,
                low: 1483359480000,
                high: 1483361460000,
                color: '#79d279'
            },
            {
                x: 1,
                low: 1483361460000,
                high: 1483361520000,
                color: '#66ccff'
            },
            {
                x: 2,
                low: 1483361520000,
                high: 1483361580000,
                color: '#ff9966'
            },
            {
                x: 3,
                low: 1483361580000,
                high: 1483361760000,
                color: '#79d279'
            },
            {
                x: 1,
                low: 1483361760000,
                high: 1483361820000,
                color: '#66ccff'
            },
            {
                x: 2,
                low: 1483361820000,
                high: 1483362060000,
                color: '#ff9966'
            },
            {
                x: 1,
                low: 1483362060000,
                high: 1483364280000,
                color: '#66ccff'
            },
        ]
    }]
}
);
</code>```

答:
Increase width of the exporting image.

```<code>exporting: {
  chartOptions: {
    chart: {
      width: 1000
    }
  }
},
</code>```

example: https://jsfiddle.net/LLExL/7294/

Body:
I am rendering 4 columnRange in my HighChart and facing the problem that the small intervalles (one minutes intervall for example A has 12:51-12:52 and 12:56-12:57 )
are not being rendered when printing the result as png image. Is there any configuration in HighCharts to get around that?

https://jsfiddle.net/LLExL/7288/

Highcharts.chart('container',
{
    chart: {
        type: 'columnrange',
        inverted: true,
        height: 192,
        spacingLeft: 10
    },
    credits: {
        enabled: false
    },
    title: {
        text: null,
        style: {
            "fontSize": "8px"
        }
    },
    subTitle: {
        text: null
    },
    legend: {
        enabled: false,
    },
    plotOptions: {
        series: {
            pointWidth: 30
        }
    },
    xAxis: {
        min: 1,
        max: 4,
        categories: ['', 'A', 'B', 'C', 'D'],
        title: {
            text: null
        },
        labels: {
            rotation: -45,
            style: {
                "fontSize": "7px"
            }
        },
        gridLineWidth: 0
    },
    yAxis: {
        type: 'datetime',
        title: {
            text: null
        },
        labels: {
            rotation: -45,
            style: {
                "fontSize": "6px"
            }
        },
        tickInterval: 1800000,
        gridLineWidth: 1
    },
    series: [{
        data: [{
                x: 1,
                low: 1483336800000,
                high: 1483336860000,
                color: '#66ccff'
            },
            {
                x: 2,
                low: 1483336860000,
                high: 1483337340000,
                color: '#ff9966'
            },
            {
                x: 1,
                low: 1483337340000,
                high: 1483337400000,
                color: '#66ccff'
            },
            {
                x: 2,
                low: 1483337400000,
                high: 1483337700000,
                color: '#ff9966'
            },
            {
                x: 1,
                low: 1483337700000,
                high: 1483339920000,
                color: '#66ccff'
            },
            {
                x: 3,
                low: 1483339920000,
                high: 1483341780000,
                color: '#79d279'
            },
            {
                x: 2,
                low: 1483341780000,
                high: 1483342260000,
                color: '#ff9966'
            },
            {
                x: 3,
                low: 1483342260000,
                high: 1483345080000,
                color: '#79d279'
            },
            {
                x: 1,
                low: 1483345080000,
                high: 1483345140000,
                color: '#66ccff'
            },
            {
                x: 3,
                low: 1483345140000,
                high: 1483346400000,
                color: '#79d279'
            },
            {
                x: 1,
                low: 1483346400000,
                high: 1483346460000,
                color: '#66ccff'
            },
            {
                x: 3,
                low: 1483346460000,
                high: 1483347420000,
                color: '#79d279'
            },
            {
                x: 1,
                low: 1483347420000,
                high: 1483347600000,
                color: '#66ccff'
            },
            {
                x: 2,
                low: 1483347600000,
                high: 1483347780000,
                color: '#ff9966'
            },
            {
                x: 1,
                low: 1483347780000,
                high: 1483348020000,
                color: '#66ccff'
            },
            {
                x: 3,
                low: 1483348020000,
                high: 1483348200000,
                color: '#79d279'
            },
            {
                x: 1,
                low: 1483348200000,
                high: 1483352460000,
                color: '#66ccff'
            },
            {
                x: 3,
                low: 1483352460000,
                high: 1483352640000,
                color: '#79d279'
            },
            {
                x: 1,
                low: 1483352640000,
                high: 1483352700000,
                color: '#66ccff'
            },
            {
                x: 3,
                low: 1483352700000,
                high: 1483353840000,
                color: '#79d279'
            },
            {
                x: 1,
                low: 1483353840000,
                high: 1483354920000,
                color: '#66ccff'
            },
            {
                x: 3,
                low: 1483354920000,
                high: 1483355160000,
                color: '#79d279'
            },
            {
                x: 1,
                low: 1483355160000,
                high: 1483359480000,
                color: '#66ccff'
            },
            {
                x: 3,
                low: 1483359480000,
                high: 1483361460000,
                color: '#79d279'
            },
            {
                x: 1,
                low: 1483361460000,
                high: 1483361520000,
                color: '#66ccff'
            },
            {
                x: 2,
                low: 1483361520000,
                high: 1483361580000,
                color: '#ff9966'
            },
            {
                x: 3,
                low: 1483361580000,
                high: 1483361760000,
                color: '#79d279'
            },
            {
                x: 1,
                low: 1483361760000,
                high: 1483361820000,
                color: '#66ccff'
            },
            {
                x: 2,
                low: 1483361820000,
                high: 1483362060000,
                color: '#ff9966'
            },
            {
                x: 1,
                low: 1483362060000,
                high: 1483364280000,
                color: '#66ccff'
            },
        ]
    }]
}
);

Body:
Increase width of the exporting image.

exporting: {
  chartOptions: {
    chart: {
      width: 1000
    }
  }
},

example: https://jsfiddle.net/LLExL/7294/