问:
How to store an edittext value in a string array?
I am new to Android. Now I am developing a project. My project has 2 edittext, 1 button, and a custom listview. When I click the ADD button, I want to display my edittext data in a custom listview.

MainActivity.java

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

Button btn;
EditText edt1,edt2;
ListView itemsListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btn=(Button) findViewById(R.id.add_id);
    edt1=(EditText) findViewById(R.id.credit_id);
    edt2=(EditText) findViewById(R.id.gpa_id);
    itemsListView  = (ListView)findViewById(R.id.list_view_items);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CustomListAdapter adapter = new
CustomListAdapter(MainActivity.this, generateItemsList());
            itemsListView.setAdapter(adapter);
            edt1.setText("");
            edt2.setText("");
        }
    });
}
private ArrayList<Item> generateItemsList() {

    String itemName=edt1.getText().toString();
    String itemDescription=edt2.getText().toString();
    ArrayList<Item> list= new ArrayList<>();
    Item item=new Item(itemName,itemDescription);
    item.getItemName();
    item.getItemDescription();
    list.add(item);
    return list;
}
}
</code>```

CustomListAdapter.java

```<code>public class CustomListAdapter extends BaseAdapter {

private Context context;
private ArrayList<Item> items;
public CustomListAdapter(Context context, ArrayList<Item> items) {
    this.context = context;
    this.items = items;
}
@Override
public int getCount() {
    return items.size();
}
@Override
public Object getItem(int position) {
    return items.get(position);
}
@Override
public long getItemId(int position) {
    return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder;
    if (convertView == null) {
        convertView =
LayoutInflater.from(context).inflate(R.layout.layout_list_view_row_items,
parent, false);
        viewHolder = new ViewHolder(convertView);
        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }
    Item currentItem = (Item) getItem(position);
    viewHolder.itemName.setText(currentItem.getItemName());
    viewHolder.itemDescription.setText(currentItem.getItemDescription());
    return convertView;
}
private class ViewHolder {
    TextView itemName;
    TextView itemDescription;
    public ViewHolder(View view) {
        itemName = (TextView)view.findViewById(R.id.text_view_item_name);
        itemDescription =(TextView)view.findViewById(R.id.text_view_item_description);
    }
}
}
</code>```

答:
Corrected your method , please check

```<code>private ArrayList<Item> generateItemsList(){
    String itemName=edt1.getText().toString();
    String itemDescription=edt2.getText().toString();
    ArrayList<Item> list=new ArrayList<String>();

    Item item=new Item();
    item.setName(itemName);
    item.setDescription(itemDescription);
    list.add(item);

    return list;
}
</code>```

this method will return the current item name and item description in a list.

Declare a global arraylist to save multiple entries Like this

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

    Button btn;
    EditText edt1, edt2;
    ListView itemsListView;
    ArrayList<Item> list = new ArrayList<>();

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

        btn = (Button) findViewById(R.id.add_id);
        edt1 = (EditText) findViewById(R.id.credit_id);
        edt2 = (EditText) findViewById(R.id.gpa_id);
        itemsListView = (ListView) findViewById(R.id.list_view_items);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String itemName = edt1.getText().toString();
                String itemDescription = edt2.getText().toString();

                Item item = new Item(itemName, itemDescription);
                item.getItemName();
                item.getItemDescription();
                list.add(item);
                CustomListAdapter adapter = new
                        CustomListAdapter(MainActivity.this, list);
                itemsListView.setAdapter(adapter);
                edt1.setText("");
                edt2.setText("");
            }
        });
    }
}
</code>```

Body:
I am new to Android. Now I am developing a project. My project has 2 edittext, 1 button, and a custom listview. When I click the ADD button, I want to display my edittext data in a custom listview.

MainActivity.java

public class MainActivity extends AppCompatActivity {

Button btn;
EditText edt1,edt2;
ListView itemsListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btn=(Button) findViewById(R.id.add_id);
    edt1=(EditText) findViewById(R.id.credit_id);
    edt2=(EditText) findViewById(R.id.gpa_id);
    itemsListView  = (ListView)findViewById(R.id.list_view_items);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CustomListAdapter adapter = new
CustomListAdapter(MainActivity.this, generateItemsList());
            itemsListView.setAdapter(adapter);
            edt1.setText("");
            edt2.setText("");
        }
    });
}
private ArrayList<Item> generateItemsList() {

    String itemName=edt1.getText().toString();
    String itemDescription=edt2.getText().toString();
    ArrayList<Item> list= new ArrayList<>();
    Item item=new Item(itemName,itemDescription);
    item.getItemName();
    item.getItemDescription();
    list.add(item);
    return list;
}
}

CustomListAdapter.java

public class CustomListAdapter extends BaseAdapter {

private Context context;
private ArrayList<Item> items;
public CustomListAdapter(Context context, ArrayList<Item> items) {
    this.context = context;
    this.items = items;
}
@Override
public int getCount() {
    return items.size();
}
@Override
public Object getItem(int position) {
    return items.get(position);
}
@Override
public long getItemId(int position) {
    return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder;
    if (convertView == null) {
        convertView =
LayoutInflater.from(context).inflate(R.layout.layout_list_view_row_items,
parent, false);
        viewHolder = new ViewHolder(convertView);
        convertView.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) convertView.getTag();
    }
    Item currentItem = (Item) getItem(position);
    viewHolder.itemName.setText(currentItem.getItemName());
    viewHolder.itemDescription.setText(currentItem.getItemDescription());
    return convertView;
}
private class ViewHolder {
    TextView itemName;
    TextView itemDescription;
    public ViewHolder(View view) {
        itemName = (TextView)view.findViewById(R.id.text_view_item_name);
        itemDescription =(TextView)view.findViewById(R.id.text_view_item_description);
    }
}
}

Body:
Corrected your method , please check

private ArrayList<Item> generateItemsList(){
    String itemName=edt1.getText().toString();
    String itemDescription=edt2.getText().toString();
    ArrayList<Item> list=new ArrayList<String>();

    Item item=new Item();
    item.setName(itemName);
    item.setDescription(itemDescription);
    list.add(item);

    return list;
}

this method will return the current item name and item description in a list.

Declare a global arraylist to save multiple entries Like this

public class MainActivity extends AppCompatActivity {

    Button btn;
    EditText edt1, edt2;
    ListView itemsListView;
    ArrayList<Item> list = new ArrayList<>();

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

        btn = (Button) findViewById(R.id.add_id);
        edt1 = (EditText) findViewById(R.id.credit_id);
        edt2 = (EditText) findViewById(R.id.gpa_id);
        itemsListView = (ListView) findViewById(R.id.list_view_items);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String itemName = edt1.getText().toString();
                String itemDescription = edt2.getText().toString();

                Item item = new Item(itemName, itemDescription);
                item.getItemName();
                item.getItemDescription();
                list.add(item);
                CustomListAdapter adapter = new
                        CustomListAdapter(MainActivity.this, list);
                itemsListView.setAdapter(adapter);
                edt1.setText("");
                edt2.setText("");
            }
        });
    }
}


来源: stackexchange

问:
Java ModelMapper map an object in an object
I have the following DTO and VO:

VO

```<code>public class ProjectVO {
    private Date fechaInicio;
    private Date fechaFin;
}
</code>```

DTO

```<code>public class ProjectDTO {
   private String fechaInicio;
   private String fechaFin;
}
</code>```

And the following converter to convert the strings to dates:

```<code>Converter<String, Date> dateConverter = new Converter<String, Date>()
    {
        public Date convert(MappingContext<String, Date> context)
        {
            Date date;

            try {
                date = new SimpleDateFormat("dd/MM/yyyy").parse(context.getSource());
            } catch (ParseException e) {
                throw new DateFormatException();
            }

            return date;
        }
    };

modelMapper.addConverter(dateConverter);
</code>```

If I convert a single String to a date using modelmapper it'll work perfectly with this converter.

But now I need to convert my ProjectDTO object to a ProjectVO one and I am getting an error saying that it cannot convert a String to a Date. I suspect this is because the Date is inside the Project object. Am I right? How can I solve this?

Thanks.

答:
Okay it works like a charm and automatically detects it if I use this:

```<code>modelMapper.createTypeMap(String.class, Date.class);
</code>```

and then add the custom converter I created :)

ContentLicense: CC BY-SA 4.0

Body:
I have the following DTO and VO:

VO

public class ProjectVO {
    private Date fechaInicio;
    private Date fechaFin;
}

DTO

public class ProjectDTO {
   private String fechaInicio;
   private String fechaFin;
}

And the following converter to convert the strings to dates:

Converter<String, Date> dateConverter = new Converter<String, Date>()
    {
        public Date convert(MappingContext<String, Date> context)
        {
            Date date;

            try {
                date = new SimpleDateFormat("dd/MM/yyyy").parse(context.getSource());
            } catch (ParseException e) {
                throw new DateFormatException();
            }

            return date;
        }
    };

modelMapper.addConverter(dateConverter);

If I convert a single String to a date using modelmapper it'll work perfectly with this converter.

But now I need to convert my ProjectDTO object to a ProjectVO one and I am getting an error saying that it cannot convert a String to a Date. I suspect this is because the Date is inside the Project object. Am I right? How can I solve this?

Thanks.

Body:
Okay it works like a charm and automatically detects it if I use this:

modelMapper.createTypeMap(String.class, Date.class);

and then add the custom converter I created :)


问:
How to call model in Controller request $request
I have a query in my model, which I want to call in my controller (request $request). It's working fine when the controller parameter is controller($id). But how to pass it in $request controller.

teacher Model with Query:

```<code>class teacher extends Model
{
  public static function teacher($id)
  {
   return DB::table('teachers')
   ->leftjoin('religions', 'teachers.religion_id', '=', 'religions.id')
   ->leftjoin('areas', 'teachers.area_id', '=', 'areas.id')
   ->select('teachers.*','religions.*','areas.*')
   ->where('teachers.id',$id)
   ->first();
  }
</code>```

Controller which calls this model perfectly fine passing direct id:

```<code>public function report1($id)
{
    $teacher = Teacher::teacher($id);
    return View('teachers.report1' ,compact('teacher'));
}
</code>```

Controller where I want to call it:

```<code>public function printreports(Request $request)
{
    $teachers = $request->get('select2');
    return view('teachers.report1',compact('teachers'));
}
</code>```

Note: select2 contains teacher ids where I want to run model query.

答:
Supposing you are have an array of ids in your select2 request param, probably easiest way is to change query at teacher model as follows:</p>

```<code>use Illuminate\Support\Arr;

class teacher extends Model
{
  public static function teacher($id)
  {
   return DB::table('teachers')
   ->leftjoin('religions', 'teachers.religion_id', '=', 'religions.id')
   ->leftjoin('areas', 'teachers.area_id', '=', 'areas.id')
   ->select('teachers.*','religions.*','areas.*')
   ->whereIn('teachers.id', Arr::wrap($id))
   ->get();
  }
}
</code>```

Body:
I have a query in my model, which I want to call in my controller (request $request). It's working fine when the controller parameter is controller($id). But how to pass it in $request controller.

teacher Model with Query:

class teacher extends Model
{
  public static function teacher($id)
  {
   return DB::table('teachers')
   ->leftjoin('religions', 'teachers.religion_id', '=', 'religions.id')
   ->leftjoin('areas', 'teachers.area_id', '=', 'areas.id')
   ->select('teachers.*','religions.*','areas.*')
   ->where('teachers.id',$id)
   ->first();
  }

Controller which calls this model perfectly fine passing direct id:

public function report1($id)
{
    $teacher = Teacher::teacher($id);
    return View('teachers.report1' ,compact('teacher'));
}

Controller where I want to call it:

public function printreports(Request $request)
{
    $teachers = $request->get('select2');
    return view('teachers.report1',compact('teachers'));
}

Note: select2 contains teacher ids where I want to run model query.

Body:
Supposing you are have an array of ids in your select2 request param, probably easiest way is to change query at teacher model as follows:

use Illuminate\Support\Arr;

class teacher extends Model
{
  public static function teacher($id)
  {
   return DB::table('teachers')
   ->leftjoin('religions', 'teachers.religion_id', '=', 'religions.id')
   ->leftjoin('areas', 'teachers.area_id', '=', 'areas.id')
   ->select('teachers.*','religions.*','areas.*')
   ->whereIn('teachers.id', Arr::wrap($id))
   ->get();
  }
}


问:
Cannot find a version of 'com.google.code.findbugs:jsr305'

Cannot find a version of 'com.google.code.findbugs:jsr305' that
  satisfies the version constraints

```<code>   Dependency path 'Kmrider5:app:unspecified' --> 'com.google.code.findbugs:jsr305:3.0.2'
   Constraint path 'Kmrider5:app:unspecified' --> 'com.google.code.findbugs:jsr305' strictly '1.3.9' because of the following reason: debugRuntimeClasspath uses version 1.3.9
   Dependency path 'Kmrider5:app:unspecified' --> 'com.google.code.findbugs:jsr305:3.0.2'
   Constraint path 'Kmrider5:app:unspecified' --> 'com.google.code.findbugs:jsr305' strictly '1.3.9' because of the following reason: debugRuntimeClasspath uses version 1.3.9
   Dependency path 'Kmrider5:app:unspecified' --> 'com.google.code.findbugs:jsr305:3.0.2'
   Constraint path 'Kmrider5:app:unspecified' --> 'com.google.code.findbugs:jsr305' strictly '1.3.9' because of the following reason: debugRuntimeClasspath uses version 1.3.9
   Dependency path 'Kmrider5:app:unspecified' --> 'com.google.code.findbugs:jsr305:3.0.2'
   Constraint path 'Kmrider5:app:unspecified' --> 'com.google.code.findbugs:jsr305' strictly '1.3.9' because of the following reason: debugRuntimeClasspath uses version 1.3.9
   Dependency path 'Kmrider5:app:unspecified' --> 'com.google.code.findbugs:jsr305:3.0.2'
   Constraint path 'Kmrider5:app:unspecified' --> 'com.google.code.findbugs:jsr305' strictly '1.3.9' because of the following reason: debugRuntimeClasspath uses version 1.3.9
   Dependency path 'Kmrider5:app:unspecified' --> 'com.google.code.findbugs:jsr305:3.0.2'
   Constraint path 'Kmrider5:app:unspecified' --> 'com.google.code.findbugs:jsr305' strictly '1.3.9' because of the following reason: debugRuntimeClasspath uses version 1.3.9
   Dependency path 'Kmrider5:app:unspecified' --> 'com.android.support.test.espresso:espresso-core:3.0.2' --> 'com.google.code.findbugs:jsr305:2.0.1'
   Dependency path 'Kmrider5:app:unspecified' --> 'com.google.android.libraries.places:places:1.0.0' --> 'com.google.guava:guava:23.5-android' --> 'com.google.code.findbugs:jsr305:1.3.9'
</code>```

答:
That means you are importing some gradle libraries depending on 'com.google.code.findbugs:jsr305' but different versions.
You should evaluate whether to update libraries versions or exclude the implicit import of the findbugs library from some of them.

I got this error when I added Espresso to an already-created project and solved by excluding findbugs from the Espresso's libraries imports.

A solution

```<code>androidTestImplementation 'com.android.support.test.espresso:espresso-contrib:3.0.2', {
    exclude group: 'com.google.code.findbugs', module: 'jsr305'
}
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2', {
    exclude group: 'com.google.code.findbugs', module: 'jsr305'
}
</code>```

Body:
Cannot find a version of 'com.google.code.findbugs:jsr305' that
  satisfies the version constraints

   Dependency path 'Kmrider5:app:unspecified' --> 'com.google.code.findbugs:jsr305:3.0.2'
   Constraint path 'Kmrider5:app:unspecified' --> 'com.google.code.findbugs:jsr305' strictly '1.3.9' because of the following reason: debugRuntimeClasspath uses version 1.3.9
   Dependency path 'Kmrider5:app:unspecified' --> 'com.google.code.findbugs:jsr305:3.0.2'
   Constraint path 'Kmrider5:app:unspecified' --> 'com.google.code.findbugs:jsr305' strictly '1.3.9' because of the following reason: debugRuntimeClasspath uses version 1.3.9
   Dependency path 'Kmrider5:app:unspecified' --> 'com.google.code.findbugs:jsr305:3.0.2'
   Constraint path 'Kmrider5:app:unspecified' --> 'com.google.code.findbugs:jsr305' strictly '1.3.9' because of the following reason: debugRuntimeClasspath uses version 1.3.9
   Dependency path 'Kmrider5:app:unspecified' --> 'com.google.code.findbugs:jsr305:3.0.2'
   Constraint path 'Kmrider5:app:unspecified' --> 'com.google.code.findbugs:jsr305' strictly '1.3.9' because of the following reason: debugRuntimeClasspath uses version 1.3.9
   Dependency path 'Kmrider5:app:unspecified' --> 'com.google.code.findbugs:jsr305:3.0.2'
   Constraint path 'Kmrider5:app:unspecified' --> 'com.google.code.findbugs:jsr305' strictly '1.3.9' because of the following reason: debugRuntimeClasspath uses version 1.3.9
   Dependency path 'Kmrider5:app:unspecified' --> 'com.google.code.findbugs:jsr305:3.0.2'
   Constraint path 'Kmrider5:app:unspecified' --> 'com.google.code.findbugs:jsr305' strictly '1.3.9' because of the following reason: debugRuntimeClasspath uses version 1.3.9
   Dependency path 'Kmrider5:app:unspecified' --> 'com.android.support.test.espresso:espresso-core:3.0.2' --> 'com.google.code.findbugs:jsr305:2.0.1'
   Dependency path 'Kmrider5:app:unspecified' --> 'com.google.android.libraries.places:places:1.0.0' --> 'com.google.guava:guava:23.5-android' --> 'com.google.code.findbugs:jsr305:1.3.9'

Body:
That means you are importing some gradle libraries depending on 'com.google.code.findbugs:jsr305' but different versions.
You should evaluate whether to update libraries versions or exclude the implicit import of the findbugs library from some of them.

I got this error when I added Espresso to an already-created project and solved by excluding findbugs from the Espresso's libraries imports.

A solution

androidTestImplementation 'com.android.support.test.espresso:espresso-contrib:3.0.2', {
    exclude group: 'com.google.code.findbugs', module: 'jsr305'
}
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2', {
    exclude group: 'com.google.code.findbugs', module: 'jsr305'
}


问:
Not able to get data when form is submitted using phpmailer and later forwared
Simple PHP script to capture user form input and send me email.

Empty form gets submitted using phpmailer script i.e. Receiving email without user filled data. There is no SMTP error, Page get submitted and redirected to new Page. Request to please help. Sometimes email received also form has user filled data also, not sure why ?

```<code><?php

date_default_timezone_set('Etc/UTC');
 use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require './PHPMailer/src/PHPMailer.php';
require './PHPMailer/src/SMTP.php';
require './PHPMailer/src/Exception.php';

try {
$mail = new PHPMailer(true);

    $mail->SMTPDebug = 0;
     $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = "XXXXX@gmail.com";
    $mail->Password = "XXXXX";
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;

    $mail->setFrom('XXXXX@gmail.com', 'Mr Singh');
    $mail->addReplyTo('XXXXX@gmail.com', 'Mr Singh');
    $mail->addAddress('XXXXX@gmail.com', 'Mr Singh');

    $mail->Subject = 'PHPMailer Exceptions test';
$mail->isHTML(false);

        $mail->Body = <<<EOT
Email: {$_POST['name']}
Email: {$_POST['email']}
Mobile: {$_POST['mobile']}
EOT;

    $mail->send();
    header("Refresh:1; contact.html");
} catch (Exception $e) {
    echo $e->errorMessage();
} catch (\Exception $e) { //The leading slash means the Global PHP Exception class will be caught
    echo $e->getMessage();
}

?>
</code>```

答:
Thanks, Kept only if statement and its working now. Able to use use Gmail SMTP services. For Gmail had to enable less secure app in Gmail and changed password once.

```<code><?php

date_default_timezone_set('Etc/UTC');

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require './PHPMailer/src/PHPMailer.php';
require './PHPMailer/src/SMTP.php';
require './PHPMailer/src/Exception.php';

if (isset($_POST['submit']))
{

    $mail = new PHPMailer(true);

    $mail->SMTPDebug = 0;

    //Set the hostname of the mail server
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com'; // Which SMTP server to use.
    $mail->SMTPAuth = true; // Whether you need to login. This is almost always required.
    $mail->Username = "XXXXX@gmail.com"; // Your Gmail address.
    $mail->Password = "XXXXX"; // Your Gmail login password or App Specific Password.
    $mail->SMTPSecure = 'tls'; // Which security method to use. TLS is most secure.
    $mail->Port = 587; // Which port to use, 587 is the default port for TLS security.

    //Set who the message is to be sent from
    $mail->setFrom('XXXXXgmail.com', 'Mr Singh');
    //Set an alternative reply-to address
    $mail->addReplyTo('XXXXX@gmail.com', 'Mr Singh');
    //Set who the message is to be sent to
    $mail->addAddress('YYYYY@gmail.com', 'Mr Singh');

    $mail->Subject = 'Customer Enquiry Form';

    $mail->isHTML(false);

        $mail->Body = <<<EOT
        Email: {$_POST['name']}
        Email: {$_POST['email']}
        Mobile: {$_POST['mobile']}

EOT;

        $mail->send();
        header("Refresh:1; contact.html");

}  else {
    echo "Your form is not submitted yet please call for booking";
}
?>
</code>```

HTML Code

```<code><form class="form-horizontal" id="submit" action="PHPMailer.php" method="post">
.......    ** HTML CODE of Form  .......
<input value="submit" name="submit" type="submit">
</code>```

Body:
Simple PHP script to capture user form input and send me email.

Empty form gets submitted using phpmailer script i.e. Receiving email without user filled data. There is no SMTP error, Page get submitted and redirected to new Page. Request to please help. Sometimes email received also form has user filled data also, not sure why ?

<?php

date_default_timezone_set('Etc/UTC');
 use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require './PHPMailer/src/PHPMailer.php';
require './PHPMailer/src/SMTP.php';
require './PHPMailer/src/Exception.php';

try {
$mail = new PHPMailer(true);

    $mail->SMTPDebug = 0;
     $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = "XXXXX@gmail.com";
    $mail->Password = "XXXXX";
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;

    $mail->setFrom('XXXXX@gmail.com', 'Mr Singh');
    $mail->addReplyTo('XXXXX@gmail.com', 'Mr Singh');
    $mail->addAddress('XXXXX@gmail.com', 'Mr Singh');

    $mail->Subject = 'PHPMailer Exceptions test';
$mail->isHTML(false);

        $mail->Body = <<<EOT
Email: {$_POST['name']}
Email: {$_POST['email']}
Mobile: {$_POST['mobile']}
EOT;

    $mail->send();
    header("Refresh:1; contact.html");
} catch (Exception $e) {
    echo $e->errorMessage();
} catch (\Exception $e) { //The leading slash means the Global PHP Exception class will be caught
    echo $e->getMessage();
}

?>

Body:
Thanks, Kept only if statement and its working now. Able to use use Gmail SMTP services. For Gmail had to enable less secure app in Gmail and changed password once.

<?php

date_default_timezone_set('Etc/UTC');

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require './PHPMailer/src/PHPMailer.php';
require './PHPMailer/src/SMTP.php';
require './PHPMailer/src/Exception.php';

if (isset($_POST['submit']))
{

    $mail = new PHPMailer(true);

    $mail->SMTPDebug = 0;

    //Set the hostname of the mail server
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com'; // Which SMTP server to use.
    $mail->SMTPAuth = true; // Whether you need to login. This is almost always required.
    $mail->Username = "XXXXX@gmail.com"; // Your Gmail address.
    $mail->Password = "XXXXX"; // Your Gmail login password or App Specific Password.
    $mail->SMTPSecure = 'tls'; // Which security method to use. TLS is most secure.
    $mail->Port = 587; // Which port to use, 587 is the default port for TLS security.

    //Set who the message is to be sent from
    $mail->setFrom('XXXXXgmail.com', 'Mr Singh');
    //Set an alternative reply-to address
    $mail->addReplyTo('XXXXX@gmail.com', 'Mr Singh');
    //Set who the message is to be sent to
    $mail->addAddress('YYYYY@gmail.com', 'Mr Singh');

    $mail->Subject = 'Customer Enquiry Form';

    $mail->isHTML(false);

        $mail->Body = <<<EOT
        Email: {$_POST['name']}
        Email: {$_POST['email']}
        Mobile: {$_POST['mobile']}

EOT;

        $mail->send();
        header("Refresh:1; contact.html");

}  else {
    echo "Your form is not submitted yet please call for booking";
}
?>

HTML Code

<form class="form-horizontal" id="submit" action="PHPMailer.php" method="post">
.......    ** HTML CODE of Form  .......
<input value="submit" name="submit" type="submit">


问:
How do you limit the output of a foreach?
I need to create a website where one can bookmark properties and then only a couple of them get displayed on the homepage.
I already have the list of the bookmarked properties working using cookies, but im having problems with limiting the output when it comes to the display on the hoempage.</p>

```<code><h2>Previously seen properties</h2>
<?php
    if(isset($_COOKIE["bookmark"]))
    {//
        $total = 0;
        $cookie_data = stripslashes($_COOKIE['bookmark']);//removes backslashes
        $bookmark_data = json_decode($cookie_data, true);//converts JSON string to PHP variable
        foreach($bookmark_data as $keys => $values)
        {
    ?> <!---what will be displayed--->

        <div style="border:1px solid #ccc; border-radius:5px; padding:16px; margin-bottom:16px;width:300px; height:300px;">
            <img src="../01_Global/assets/img/Houses/'. $row['Image'] .'" alt="" class="img-responsive" >
            <p align="center"><strong><a href="productpage.php"> <?php echo $values["property_name"]; ?></a></strong></p>
            <h4 style="text-align:center;" class="text-danger" > <?php echo $values["property_price"]; ?></h4>

        </div>
    <?php
    }
    ?>
    <?php
    }
    else
    {
    echo '';
    }
    ?>
</code>```

答:
So a simple counter maintained in your existing loop would do it</p>

```<code><h2>Previously seen properties</h2>
<?php

if(isset($_COOKIE["bookmark"]))
{
    $total = 0;
    $cookie_data = stripslashes($_COOKIE['bookmark']);//removes backslashes
    $bookmark_data = json_decode($cookie_data, true);//converts JSON string to PHP variable

    // initialise the counter
    $cnt = 0;

    foreach($bookmark_data as $keys => $values) {
        if ($cnt == 2) {
            // only show 2
            break;
        }
        $cnt++;

?>
    <!---what will be displayed--->

        <div style="border:1px solid #ccc; border-radius:5px; padding:16px; margin-bottom:16px;width:300px; height:300px;">
            <img src="../01_Global/assets/img/Houses/'. $row['Image'] .'" alt="" class="img-responsive" >
            <p align="center"><strong><a href="productpage.php"> <?php echo $values["property_name"]; ?></a></strong></p>
            <h4 style="text-align:center;" class="text-danger" > <?php echo $values["property_price"]; ?></h4>
        </div>
<?php
    }
} else {
    echo '';
}
?>
</code>```

Body:
I need to create a website where one can bookmark properties and then only a couple of them get displayed on the homepage.
I already have the list of the bookmarked properties working using cookies, but im having problems with limiting the output when it comes to the display on the hoempage.

Previously seen properties

<?php
    if(isset($_COOKIE["bookmark"]))
    {//
        $total = 0;
        $cookie_data = stripslashes($_COOKIE['bookmark']);//removes backslashes
        $bookmark_data = json_decode($cookie_data, true);//converts JSON string to PHP variable
        foreach($bookmark_data as $keys => $values)
        {
    ?>

 <?php echo $values["property_name"]; ?>

 <?php echo $values["property_price"]; ?>

    <?php
    }
    ?>
    <?php
    }
    else
    {
    echo '';
    }
    ?>

Body:
So a simple counter maintained in your existing loop would do it

<h2>Previously seen properties</h2>
<?php

if(isset($_COOKIE["bookmark"]))
{
    $total = 0;
    $cookie_data = stripslashes($_COOKIE['bookmark']);//removes backslashes
    $bookmark_data = json_decode($cookie_data, true);//converts JSON string to PHP variable

    // initialise the counter
    $cnt = 0;

    foreach($bookmark_data as $keys => $values) {
        if ($cnt == 2) {
            // only show 2
            break;
        }
        $cnt++;

?>
    <!---what will be displayed--->

        <div style="border:1px solid #ccc; border-radius:5px; padding:16px; margin-bottom:16px;width:300px; height:300px;">
            <img src="../01_Global/assets/img/Houses/'. $row['Image'] .'" alt="" class="img-responsive" >
            <p align="center"><strong><a href="productpage.php"> <?php echo $values["property_name"]; ?></a></strong></p>
            <h4 style="text-align:center;" class="text-danger" > <?php echo $values["property_price"]; ?></h4>
        </div>
<?php
    }
} else {
    echo '';
}
?>


问:
Report of all deployments over 1 week and 1 month
I'm trying to get a report of everything that have been deployed in the last week and month using Azure Resource Graph, activity log, change history or Powershell but can't find any good way to do it.

I have tried using the Search-AzGraph command unsuccessfully and can't find any good way with any of the other things listed.

I'm trying to get a report with resource type, name, date, resource group, region and user for the last week and month.

答:
Please use the below command to find the deployment history with resource manager:

```<code>Get-AzResourceGroupDeployment -ResourceGroupName ExampleGroup
</code>```

More information here:

https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-deployment-operations#powershell

Body:
Please use the below command to find the deployment history with resource manager:

Get-AzResourceGroupDeployment -ResourceGroupName ExampleGroup

More information here:

https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-deployment-operations#powershell


问:
"Maximum update depth exceeded" in React functional component
I have a problem with a react functional component. When the react-apollo query is "on completed" executes a code to handle a token, and when finish send to another page (using history.push).

When run the code I get a infinite loop with this message: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops

I've tried comment history.push and the infinite loop does not happen again.

I comment all the logic in list-session component to avoid a recursive call, but it does not work (I checked thoroughly the code to confirm is not a recursive call).

I thing the problem is related with the lifecycle or with the history.push behavior

Ptt: I'm learning react on this moment

```<code>  const { setUserInfo, setUserId } = useContext(userContext);
  const { token } = match.params;

  const onCompleted = data => {
    if (data.validateUser.status) {
      setUserId(token);
      setUserInfo(data.validateUser.infoUser);
      localStorage.setItem("token", token);
      // history.push("/list-session");
    } else {
      history.push("/rare-page");
    }
  };

  return (
    <div className="Auth" data-testid="AuthPage">
      <Query
        query={VALIDATE_USER}
        variables={{ userId: token }}
        onCompleted={onCompleted}
      >
        {({ error }) => {
          if (error) return <Error />;
          return (
            <>
              <h2 data-testid="AuthState">Authenticating...</h2>
              <div className="spinner-border text-info" role="status">
                <span className="sr-only">Loading...</span>
              </div>
            </>
          );
        }}
      </Query>
    </div>
  );
}
</code>```

EDIT 1:
Added relevant code in the problem. I checked the component and no one of this make a recursive call, and no make a infinite setState call. The setState problem is the consecuence to another problem.

```<code>        <AnimatedSwitch
          atEnter={bounceTransition.atEnter}
          atLeave={bounceTransition.atLeave}
          atActive={bounceTransition.atActive}
          mapStyles={mapStyles}
          className="route-wrapper"
        >
          <Route exact path="/" component={NoCredentials} />
          <Route exact path="/token/:token" component={Auth} />
          <Route path="/list-session" component={Home} />
        </AnimatedSwitch>
</code>```

and this is the code in Home component:

```<code>const Home = () => {
  const [activeTab, setActiveTab] = useState("activeSessions");

  return (
    <ValidateToken>
      <Container className="bg-light">
        <div className="Home">
          <CreateSessionComponent />
          <Nav tabs>
            <NavItem>
              <NavLink
                className={classnames({
                  active: activeTab === "activeSessions"
                })}
                onClick={() => setActiveTab("activeSessions")}
              >
                Active Sessions
              </NavLink>
            </NavItem>
          </Nav>
          <TabContent activeTab={activeTab}>
            <TabPane tabId="activeSessions">
              {activeTab === "activeSessions" && (
                <div>
                  <SessionsListComponent status="ACTIVE" />
                </div>
              )}
            </TabPane>
          </TabPane>
          </TabContent>
        </div>
      </Container>
    </ValidateToken>
  );
};

export default Home;
</code>```

答:
try this it may work i think.

<Query
  query={VALIDATE_USER}
  variables={{ userId: token }}
  onCompleted={(e)=>onCompleted(e)} //onCompleted throws an event
>```

Body:
I have a problem with a react functional component. When the react-apollo query is "on completed" executes a code to handle a token, and when finish send to another page (using history.push).

When run the code I get a infinite loop with this message: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops

I've tried comment history.push and the infinite loop does not happen again.

I comment all the logic in list-session component to avoid a recursive call, but it does not work (I checked thoroughly the code to confirm is not a recursive call).

I thing the problem is related with the lifecycle or with the history.push behavior

Ptt: I'm learning react on this moment

  const { setUserInfo, setUserId } = useContext(userContext);
  const { token } = match.params;

  const onCompleted = data => {
    if (data.validateUser.status) {
      setUserId(token);
      setUserInfo(data.validateUser.infoUser);
      localStorage.setItem("token", token);
      // history.push("/list-session");
    } else {
      history.push("/rare-page");
    }
  };

  return (

      <Query
        query={VALIDATE_USER}
        variables={{ userId: token }}
        onCompleted={onCompleted}
      >
        {({ error }) => {
          if (error) return <Error />;
          return (
            <>

Authenticating...

                Loading...

            </>
          );
        }}
      </Query>

  );
}

EDIT 1:
Added relevant code in the problem. I checked the component and no one of this make a recursive call, and no make a infinite setState call. The setState problem is the consecuence to another problem.

        <AnimatedSwitch
          atEnter={bounceTransition.atEnter}
          atLeave={bounceTransition.atLeave}
          atActive={bounceTransition.atActive}
          mapStyles={mapStyles}
          className="route-wrapper"
        >
          <Route exact path="/" component={NoCredentials} />
          <Route exact path="/token/:token" component={Auth} />
          <Route path="/list-session" component={Home} />
        </AnimatedSwitch>

and this is the code in Home component:

const Home = () => {
  const [activeTab, setActiveTab] = useState("activeSessions");

  return (
    <ValidateToken>
      <Container className="bg-light">

          <CreateSessionComponent />

            <NavItem>
              <NavLink
                className={classnames({
                  active: activeTab === "activeSessions"
                })}
                onClick={() => setActiveTab("activeSessions")}
              >
                Active Sessions
              </NavLink>
            </NavItem>

          <TabContent activeTab={activeTab}>
            <TabPane tabId="activeSessions">
              {activeTab === "activeSessions" && (

                  <SessionsListComponent status="ACTIVE" />

              )}
            </TabPane>
          </TabPane>
          </TabContent>

      </Container>
    </ValidateToken>
  );
};

export default Home;


问:
Laravel - Merged collection different from Eloquent collection?
I am facing a problem with sorting and returning merged collections.

When i do:

```<code>$ads = Ad::where('status',1)->where('deleted_at',NULL)->paginate(30);
</code>```

it works
but when i merge this with another collection like

```<code>$one = Ad::where('status', 1)->get();
$two = Ad::where('status', 2)->get();
$ads = $one->merge($two);
$ads->paginate(30);
</code>```

it tells me that "paginate method does not exist" as well as "orderBy method does not exist"

are those collections different from the single returned ones?

答:
Pagination only works on the query builder and Eloquent query.

Laravel Pagination adjusts the MySQL Query to only retrieve the results from that specific page.

Because you already have the query result it can no longer be used to apply pagination. However you can still slice the collection to multiple parts for your pages.

In your case, since you use the same model, you better retrieve both results:

$ad = Ad::where('status', 1)->orWhere('status', 2)->paginate(20);
```

If you use different models, you can slice the collection as shown here:
stackoverflow - How can I paginate a merged collection in Laravel 5?

Body:
I am facing a problem with sorting and returning merged collections.

When i do:

$ads = Ad::where('status',1)->where('deleted_at',NULL)->paginate(30);

it works
but when i merge this with another collection like

$one = Ad::where('status', 1)->get();
$two = Ad::where('status', 2)->get();
$ads = $one->merge($two);
$ads->paginate(30);

it tells me that "paginate method does not exist" as well as "orderBy method does not exist"

are those collections different from the single returned ones?

Body:
Pagination only works on the query builder and Eloquent query.

Laravel Pagination adjusts the MySQL Query to only retrieve the results from that specific page.

Because you already have the query result it can no longer be used to apply pagination. However you can still slice the collection to multiple parts for your pages.

In your case, since you use the same model, you better retrieve both results:

$ad = Ad::where('status', 1)->orWhere('status', 2)->paginate(20);

If you use different models, you can slice the collection as shown here:
stackoverflow - How can I paginate a merged collection in Laravel 5?


问:
Swift crash with multiple async call
the application below crashes when the source code is executed in:
 u.VerificaPermesso(...), the application checks on a rest server of n calls node. The code is correct but crashes can you explain the reason to me? Calls are made to a rest node.js server that responds with a value of true or false and depending on that value is displayed or not.

Swift Code:

```<code>import UIKit

class TabBarViewController: UITabBarController {

    var u: User = User()
    /* Genero L'UITabBarController creando le ViewController ed inserendole in un array! */
    override func viewDidLoad() {
        super.viewDidLoad()
        var tabFrame = self.tabBar.frame
        tabFrame.size.height = 60
        self.tabBar.frame = tabFrame
        hideKeyboardWhenTappedAround()

        let MarcaTempoView = MarcaTempoViewController()
        MarcaTempoView.tabBarItem = UITabBarItem(title: "Marca Tempo", image: UIImage(named: "clock.png")?.scaleImage(toSize: CGSize(width: 10, height: 10)), tag: 0)

        let CantieriView = CantieriViewController()
        CantieriView.tabBarItem = UITabBarItem(title: "Cantieri", image: UIImage(named: "home.png")?.scaleImage(toSize: CGSize(width: 10, height: 10)), tag: 1)

        let ArticoliView = RicercaArticoliViewController()
        ArticoliView.tabBarItem = UITabBarItem(title: "Articoli", image: UIImage(named: "articoli.png")?.scaleImage(toSize: CGSize(width: 10, height: 10)), tag: 2)

        let UserView = UserViewController()
        UserView.tabBarItem = UITabBarItem(title: "Utente", image: UIImage(named: "user.png")?.scaleImage(toSize: CGSize(width: 10, height: 10)), tag: 3)

        let ClienteView = ClienteViewController()
        ClienteView.tabBarItem = UITabBarItem(title: "Clienti", image: UIImage(named: "risorse_umane.png")?.scaleImage(toSize: CGSize(width: 10, height: 10)), tag: 4)

        var viewControllerList = [MarcaTempoView, CantieriView, ArticoliView, ClienteView,UserView]

        DispatchQueue.main.async {

            //Controllo permesso accesso cantieri
            let u = User()

            //Controllo permesso accesso marcatempo
            u.VerificaPermesso(TipologiaPermesso: "marcatempo", completion: { result in
                DispatchQueue.main.async {
                     if(result == "false") {
                    viewControllerList.removeAll(where:{ $0 is MarcaTempoViewController })

                    self.viewControllers = viewControllerList
                    }
                }
            });

            u.VerificaPermesso(TipologiaPermesso: "cantieri", completion: { result in
                DispatchQueue.main.async {
                    if(result == "false") {
                       viewControllerList.removeAll(where:{ $0 is CantieriViewController })

                        self.viewControllers = viewControllerList
                    }
                }
            });

            //Controllo permesso accesso Articoli
            u.VerificaPermesso(TipologiaPermesso: "articoli", completion: { result in
                DispatchQueue.main.async {
                    if(result == "false") {
                         viewControllerList.removeAll(where:{ $0 is RicercaArticoliViewController })

                        self.viewControllers = viewControllerList
                    }
                }
            });

            //Controllo permesso accesso Clienti
            u.VerificaPermesso(TipologiaPermesso: "clienti", completion: { result in
                DispatchQueue.main.async {
                    if(result == "false") {
                       viewControllerList.removeAll(where:{ $0 is ClienteViewController })
                          self.viewControllers = viewControllerList
                    }
                }
            });

        }

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}
</code>```

答:
I guess the reason is unbalanced calls to the remove here

```<code>viewControllerList.remove(at: 1)
viewControllerList.remove(at: 5)
</code>```

meaning if array count is 6 when you remove say element at index 1 that means when you try to remove at 5  it will crash because max count now is 4

you can avoid using indices in remove e.x instead of viewControllerList.remove(at: 0)

```<code>viewControllerList.removeAll(where:{ $0 is MarcaTempoView })
</code>```

Title: Swift crash with multiple async call

Body:
the application below crashes when the source code is executed in:
 u.VerificaPermesso(...), the application checks on a rest server of n calls node. The code is correct but crashes can you explain the reason to me? Calls are made to a rest node.js server that responds with a value of true or false and depending on that value is displayed or not.

Swift Code:

import UIKit

class TabBarViewController: UITabBarController {

    var u: User = User()
    /* Genero L'UITabBarController creando le ViewController ed inserendole in un array! */
    override func viewDidLoad() {
        super.viewDidLoad()
        var tabFrame = self.tabBar.frame
        tabFrame.size.height = 60
        self.tabBar.frame = tabFrame
        hideKeyboardWhenTappedAround()

        let MarcaTempoView = MarcaTempoViewController()
        MarcaTempoView.tabBarItem = UITabBarItem(title: "Marca Tempo", image: UIImage(named: "clock.png")?.scaleImage(toSize: CGSize(width: 10, height: 10)), tag: 0)

        let CantieriView = CantieriViewController()
        CantieriView.tabBarItem = UITabBarItem(title: "Cantieri", image: UIImage(named: "home.png")?.scaleImage(toSize: CGSize(width: 10, height: 10)), tag: 1)

        let ArticoliView = RicercaArticoliViewController()
        ArticoliView.tabBarItem = UITabBarItem(title: "Articoli", image: UIImage(named: "articoli.png")?.scaleImage(toSize: CGSize(width: 10, height: 10)), tag: 2)

        let UserView = UserViewController()
        UserView.tabBarItem = UITabBarItem(title: "Utente", image: UIImage(named: "user.png")?.scaleImage(toSize: CGSize(width: 10, height: 10)), tag: 3)

        let ClienteView = ClienteViewController()
        ClienteView.tabBarItem = UITabBarItem(title: "Clienti", image: UIImage(named: "risorse_umane.png")?.scaleImage(toSize: CGSize(width: 10, height: 10)), tag: 4)

        var viewControllerList = [MarcaTempoView, CantieriView, ArticoliView, ClienteView,UserView]

        DispatchQueue.main.async {

            //Controllo permesso accesso cantieri
            let u = User()

            //Controllo permesso accesso marcatempo
            u.VerificaPermesso(TipologiaPermesso: "marcatempo", completion: { result in
                DispatchQueue.main.async {
                     if(result == "false") {
                    viewControllerList.removeAll(where:{ $0 is MarcaTempoViewController })

                    self.viewControllers = viewControllerList
                    }
                }
            });

            u.VerificaPermesso(TipologiaPermesso: "cantieri", completion: { result in
                DispatchQueue.main.async {
                    if(result == "false") {
                       viewControllerList.removeAll(where:{ $0 is CantieriViewController })

                        self.viewControllers = viewControllerList
                    }
                }
            });

            //Controllo permesso accesso Articoli
            u.VerificaPermesso(TipologiaPermesso: "articoli", completion: { result in
                DispatchQueue.main.async {
                    if(result == "false") {
                         viewControllerList.removeAll(where:{ $0 is RicercaArticoliViewController })

                        self.viewControllers = viewControllerList
                    }
                }
            });

            //Controllo permesso accesso Clienti
            u.VerificaPermesso(TipologiaPermesso: "clienti", completion: { result in
                DispatchQueue.main.async {
                    if(result == "false") {
                       viewControllerList.removeAll(where:{ $0 is ClienteViewController })
                          self.viewControllers = viewControllerList
                    }
                }
            });

        }

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

Body:
I guess the reason is unbalanced calls to the remove here

viewControllerList.remove(at: 1)
viewControllerList.remove(at: 5)

meaning if array count is 6 when you remove say element at index 1 that means when you try to remove at 5  it will crash because max count now is 4

you can avoid using indices in remove e.x instead of viewControllerList.remove(at: 0)

viewControllerList.removeAll(where:{ $0 is MarcaTempoView })


问:
Allowing admin users to edit website content
I've created a website and I want to have certain users who are able to log in and edit the content if they see something that needs changed. I'm using password_hash for the passwords.

But now I'm confused on how to let these users edit content on the website, say for example I have this bit of code:

```<code><div class="-container-white" style="padding:128px 16px" id="charities">
  <h3 class="-center">SUPPORTING CHARITIES</h3>

  <p>Over the years we have been helping raise money for a number of charities.</p>
  <p>These include:</p>
  <ul>
    <li>Cash For Kids</li>
    <li>Cancer Research</li>
</ul>

<p>We also have helped numerous organisations out by donating products they can use in their raffles</p>
<p> If you know of any charities or would like to discuss having products donated for raffles please do not hesitate to get in touch</p>

<p>We are proud to to support these charities and can not thank you, customers, enough for helping us do this</p>

  <div class="-row-padding -center" style="margin-top:64px">

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

Now the point of having these users is to make it easier for updating the website so if they find something wrong they can easily change it without having to ask me to go into the code and change it. What would I need to change in order to allow this to happen, i.e make this editable once one of the admin users are logged in.

This is my login page with the sql code if this helps:

```<code><?php
// Initialize the session
session_start();

// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
    header("location: welcome.php");
    exit;
}

// Include config file
require_once "config.php";

// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = "";

// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){

    // Check if username is empty
    if(empty(trim($_POST["username"]))){
        $username_err = "Please enter username.";
    } else{
        $username = trim($_POST["username"]);
    }

    // Check if password is empty
    if(empty(trim($_POST["password"]))){
        $password_err = "Please enter your password.";
    } else{
        $password = trim($_POST["password"]);
    }

    // Validate credentials
    if(empty($username_err) && empty($password_err)){
        // Prepare a select statement
        $sql = "SELECT id, email, password, last_name, first_name username, FROM admin_users WHERE username = ?";

        if($stmt = mysqli_prepare($link, $sql)){
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "s", $param_username);

            // Set parameters
            $param_username = $username;

            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
                // Store result
                mysqli_stmt_store_result($stmt);

                // Check if username exists, if yes then verify password
                if(mysqli_stmt_num_rows($stmt) == 1){
                    // Bind result variables
                    mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
                    if(mysqli_stmt_fetch($stmt)){
                        if(password_verify($password, $hashed_password)){
                            // Password is correct, so start a new session
                            session_start();

                            // Store data in session variables
                            $_SESSION["loggedin"] = true;
                            $_SESSION["id"] = $id;
                            $_SESSION["username"] = $username;

                            // Redirect user to welcome page
                            header("location: welcome.php");
                        } else{
                            // Display an error message if password is not valid
                            $password_err = "The password you entered was not valid.";
                        }
                    }
                } else{
                    // Display an error message if username doesn't exist
                    $username_err = "No account found with that username.";
                }
            } else{
                echo "Oops! Something went wrong. Please try again later.";
            }
        }

        // Close statement
        mysqli_stmt_close($stmt);
    }

    // Close connection
    mysqli_close($link);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
    <style type="text/css">
        body{ font: 14px sans-serif; }
        .wrapper{ width: 350px; padding: 20px; }
    </style>
</head>
<body>
    <div class="wrapper">
        <h2>Login</h2>
        <p>Please fill in your credentials to login.</p>
        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
            <div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
                <label>Username</label>
                <input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
                <span class="help-block"><?php echo $username_err; ?></span>
            </div>
            <div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
                <label>Password</label>
                <input type="password" name="password" class="form-control">
                <span class="help-block"><?php echo $password_err; ?></span>
            </div>
            <div class="form-group">
                <input type="submit" class="btn btn-primary" value="Login">
            </div>
        </form>
    </div>
</body>
</html>
</code>```

The welcome.php page is just standard page in place at the moment until I can get this working properly.

答:
Allowing logged in users to edit the HTML of your website so that it is changed for all other users of the website is a fairly complex thing to do.

You have a long way to go from where you are now to deliver that solution if that is what you are after.

Some of the things you would need to implement:

You need to identify which text on your site is editable and which not

Editable sections would need to be abstracted out of the HTML, either into flat-file storeage, or more likely a database, you are already using a sql database so that would make most sense, I'll assume this.

When building the page you would need to look-up the real text content from the database and embed it in your returned page.

You would need to identify on each page whether the viewer is a logged-in user or not and enable edit of text (i.e. dynamically switch from a standard div to a form textarea, or div editable="true" or something).

You would need to capture that text had been changed in some way for any given section (either a form submit, or more cleanly some javascript with ajax call to the server).

Validate the content changes on the server side and store them into the database.

Here's a reference as a starting point: https://css-tricks.com/php-for-beginners-building-your-first-simple-cms/

Body:
I've created a website and I want to have certain users who are able to log in and edit the content if they see something that needs changed. I'm using password_hash for the passwords.

But now I'm confused on how to let these users edit content on the website, say for example I have this bit of code:

SUPPORTING CHARITIES

Over the years we have been helping raise money for a number of charities.

These include:

Cash For Kids

Cancer Research

We also have helped numerous organisations out by donating products they can use in their raffles

 If you know of any charities or would like to discuss having products donated for raffles please do not hesitate to get in touch

We are proud to to support these charities and can not thank you, customers, enough for helping us do this

Now the point of having these users is to make it easier for updating the website so if they find something wrong they can easily change it without having to ask me to go into the code and change it. What would I need to change in order to allow this to happen, i.e make this editable once one of the admin users are logged in.

This is my login page with the sql code if this helps:

<?php
// Initialize the session
session_start();

// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
    header("location: welcome.php");
    exit;
}

// Include config file
require_once "config.php";

// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = "";

// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){

    // Check if username is empty
    if(empty(trim($_POST["username"]))){
        $username_err = "Please enter username.";
    } else{
        $username = trim($_POST["username"]);
    }

    // Check if password is empty
    if(empty(trim($_POST["password"]))){
        $password_err = "Please enter your password.";
    } else{
        $password = trim($_POST["password"]);
    }

    // Validate credentials
    if(empty($username_err) && empty($password_err)){
        // Prepare a select statement
        $sql = "SELECT id, email, password, last_name, first_name username, FROM admin_users WHERE username = ?";

        if($stmt = mysqli_prepare($link, $sql)){
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "s", $param_username);

            // Set parameters
            $param_username = $username;

            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
                // Store result
                mysqli_stmt_store_result($stmt);

                // Check if username exists, if yes then verify password
                if(mysqli_stmt_num_rows($stmt) == 1){
                    // Bind result variables
                    mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
                    if(mysqli_stmt_fetch($stmt)){
                        if(password_verify($password, $hashed_password)){
                            // Password is correct, so start a new session
                            session_start();

                            // Store data in session variables
                            $_SESSION["loggedin"] = true;
                            $_SESSION["id"] = $id;
                            $_SESSION["username"] = $username;

                            // Redirect user to welcome page
                            header("location: welcome.php");
                        } else{
                            // Display an error message if password is not valid
                            $password_err = "The password you entered was not valid.";
                        }
                    }
                } else{
                    // Display an error message if username doesn't exist
                    $username_err = "No account found with that username.";
                }
            } else{
                echo "Oops! Something went wrong. Please try again later.";
            }
        }

        // Close statement
        mysqli_stmt_close($stmt);
    }

    // Close connection
    mysqli_close($link);
}
?>

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Login</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">

Login

Please fill in your credentials to login.

        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
            <div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
                Username
                <input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
                <?php echo $username_err; ?>

            <div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
                Password
                <input type="password" name="password" class="form-control">
                <?php echo $password_err; ?>

                <input type="submit" class="btn btn-primary" value="Login">

        </form>

The welcome.php page is just standard page in place at the moment until I can get this working properly.


问:
label too long in yAxis with chartJs
I have a problem with labels too long on the Y axis with the module "chartjs" and "vuejs". I posted an image to illustrate the problem:

My code:

```<code><bar-chart
  :max="100"
  :xlabels="50"
  suffix="%"
  :dataset="{hoverBorderWidth: 10}"
  v-if="charts=='bar'"
  :data="data.percentsData"
  :colors="['#01E3AD']"
  :style="calcHeight(data.percentsData.length)"
  :download="survey_name + ' - ' +data.title"
  >
</bar-chart>
</code>```

答:
You can break the string over multiple lines. This is done by splitting the string into an array. Chart.js parses each array element as a single line.

Example:

let labels = [
    ['this is a very long label', 'broken across two lines'],
    'short label'
  ],
  myBarChart = new Chart(document.getElementById('chart'), {
    type: 'horizontalBar',
    data: {
      labels: labels,
      datasets: [{
        label: 'Series1',
        data: [1, 1]
      }]
    },
    options: {
      maintainAspectRatio: false
    }
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
<canvas id="chart"></canvas></code>```

Title: label too long in yAxis with chartJs

Body:
I have a problem with labels too long on the Y axis with the module "chartjs" and "vuejs". I posted an image to illustrate the problem:

My code:

<bar-chart
  :max="100"
  :xlabels="50"
  suffix="%"
  :dataset="{hoverBorderWidth: 10}"
  v-if="charts=='bar'"
  :data="data.percentsData"
  :colors="['#01E3AD']"
  :style="calcHeight(data.percentsData.length)"
  :download="survey_name + ' - ' +data.title"
  >
</bar-chart>

Body:
You can break the string over multiple lines. This is done by splitting the string into an array. Chart.js parses each array element as a single line.

Example:

let labels = [
    ['this is a very long label', 'broken across two lines'],
    'short label'
  ],
  myBarChart = new Chart(document.getElementById('chart'), {
    type: 'horizontalBar',
    data: {
      labels: labels,
      datasets: [{
        label: 'Series1',
        data: [1, 1]
      }]
    },
    options: {
      maintainAspectRatio: false
    }
  });

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
<canvas id="chart"></canvas>


问:
How to programmatically invoke MBeans operation of target process
I want to simulate what jconsole does by:

Identifying a running process that exposes jmx functionality (e.g: pid: 14796 FreshProject.jar)

Listing the available MBeans libraries (e.g: org.jacoco)

Invoking an operation (e.g: clicking dump)

I've tried using the simplejmx library as mentioned here but I am confused as to what hostName and port I should use. I tried passing localhost and 1099 as I've read these are the default values but it errors java.net.ConnectException: Connection refused: connect.

Please don't point me to a different sof post and close this as I most probably already read and tried it several times.

答:
I want to simulate what jconsole does

Have a look at the implementation of jconsole - see http://openjdk.java.net/tools/svc/jconsole/ and https://github.com/openjdk/jdk/tree/master/src/jdk.jconsole/share/classes

I am confused as to what hostName and port I should use. I tried passing localhost and 1099 as I've read these are the default values but it errors java.net.ConnectException: Connection refused: connect.

As per https://docs.oracle.com/en/java/javase/11/management/monitoring-and-management-using-jmx-technology.html by default there is no port. And JConsole uses Attach API - see https://github.com/openjdk/jdk/blob/master/src/jdk.jconsole/share/classes/sun/tools/jconsole/LocalVirtualMachine.java In this code you'll also find answer on

Identifying a running process that exposes jmx functionality

To connect via port you need to specify appropriate parameters. For example following Example.java

```<code>class Example {
    public static void main(String[] args) {
        while (true) {
        }
    }
}
</code>```

can be started as

```<code>java \
    -Dcom.sun.management.jmxremote.port=1099 \
    -Dcom.sun.management.jmxremote.authenticate=false \
    -Dcom.sun.management.jmxremote.ssl=false \
    Example
</code>```

Then

Listing the available MBeans

can be done as

```<code>import javax.management.MBeanServer;
import javax.management.MBeanServerConnection;
import javax.management.MBeanServerInvocationHandler;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import java.lang.management.ManagementFactory;
import java.util.Iterator;
import java.util.Set;

class GetMBeans {
    public static void main(final String[] args) throws Exception {
       final JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi");
       final JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
       final MBeanServerConnection connection = jmxc.getMBeanServerConnection();

       Set<ObjectInstance> instances = connection.queryMBeans(null, null);
       Iterator<ObjectInstance> iterator = instances.iterator();
       while (iterator.hasNext()) {
           ObjectInstance instance = iterator.next();
           System.out.println(instance.getClassName() + " " + instance.getObjectName());
       }
    }
}
</code>```

After start of the above Example also with JaCoCo

```<code>java \
    -Dcom.sun.management.jmxremote.port=1099 \
    -Dcom.sun.management.jmxremote.authenticate=false \
    -Dcom.sun.management.jmxremote.ssl=false \
    -javaagent:jacoco-0.8.4/lib/jacocoagent.jar=jmx=true \
    Example
</code>```

execution of javac GetMBeans.java && java GetMBeans | grep jacoco produces

```<code>org.jacoco.agent.rt.internal_035b120.Agent org.jacoco:type=Runtime
</code>```

Invoking an operation

is shown in JaCoCo documentation - see MBeanClient.java at https://www.jacoco.org/jacoco/trunk/doc/api.html

```<code>import javax.management.MBeanServer;
import javax.management.MBeanServerConnection;
import javax.management.MBeanServerInvocationHandler;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import java.lang.management.ManagementFactory;
import java.util.Iterator;
import java.util.Set;

class MBeanClient {
    public static void main(final String[] args) throws Exception {
       final JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi");
       final JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
       final MBeanServerConnection connection = jmxc.getMBeanServerConnection();

       final IProxy proxy = (IProxy) MBeanServerInvocationHandler.newProxyInstance(connection, new ObjectName("org.jacoco:type=Runtime"), IProxy.class, false);

       final byte[] data = proxy.getExecutionData(false);
       System.out.println("Got " + data.length + " bytes");
    }

    public interface IProxy {
        String getVersion();
        String getSessionId();
        void setSessionId(String id);
        byte[] getExecutionData(boolean reset);
        void dump(boolean reset);
        void reset();
    }
}
</code>```

execution of javac MBeanClient.java && java MBeanClient produces

```<code>Got 84 bytes
</code>```

Body:
I want to simulate what jconsole does

Have a look at the implementation of jconsole - see http://openjdk.java.net/tools/svc/jconsole/ and https://github.com/openjdk/jdk/tree/master/src/jdk.jconsole/share/classes

I am confused as to what hostName and port I should use. I tried passing localhost and 1099 as I've read these are the default values but it errors java.net.ConnectException: Connection refused: connect.

As per https://docs.oracle.com/en/java/javase/11/management/monitoring-and-management-using-jmx-technology.html by default there is no port. And JConsole uses Attach API - see https://github.com/openjdk/jdk/blob/master/src/jdk.jconsole/share/classes/sun/tools/jconsole/LocalVirtualMachine.java In this code you'll also find answer on

Identifying a running process that exposes jmx functionality

To connect via port you need to specify appropriate parameters. For example following Example.java

class Example {
    public static void main(String[] args) {
        while (true) {
        }
    }
}

can be started as

java \
    -Dcom.sun.management.jmxremote.port=1099 \
    -Dcom.sun.management.jmxremote.authenticate=false \
    -Dcom.sun.management.jmxremote.ssl=false \
    Example

Then

Listing the available MBeans

can be done as

import javax.management.MBeanServer;
import javax.management.MBeanServerConnection;
import javax.management.MBeanServerInvocationHandler;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import java.lang.management.ManagementFactory;
import java.util.Iterator;
import java.util.Set;

class GetMBeans {
    public static void main(final String[] args) throws Exception {
       final JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi");
       final JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
       final MBeanServerConnection connection = jmxc.getMBeanServerConnection();

       Set<ObjectInstance> instances = connection.queryMBeans(null, null);
       Iterator<ObjectInstance> iterator = instances.iterator();
       while (iterator.hasNext()) {
           ObjectInstance instance = iterator.next();
           System.out.println(instance.getClassName() + " " + instance.getObjectName());
       }
    }
}

After start of the above Example also with JaCoCo

java \
    -Dcom.sun.management.jmxremote.port=1099 \
    -Dcom.sun.management.jmxremote.authenticate=false \
    -Dcom.sun.management.jmxremote.ssl=false \
    -javaagent:jacoco-0.8.4/lib/jacocoagent.jar=jmx=true \
    Example

execution of javac GetMBeans.java && java GetMBeans | grep jacoco produces

org.jacoco.agent.rt.internal_035b120.Agent org.jacoco:type=Runtime

Invoking an operation

is shown in JaCoCo documentation - see MBeanClient.java at https://www.jacoco.org/jacoco/trunk/doc/api.html

import javax.management.MBeanServer;
import javax.management.MBeanServerConnection;
import javax.management.MBeanServerInvocationHandler;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import java.lang.management.ManagementFactory;
import java.util.Iterator;
import java.util.Set;

class MBeanClient {
    public static void main(final String[] args) throws Exception {
       final JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi");
       final JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
       final MBeanServerConnection connection = jmxc.getMBeanServerConnection();

       final IProxy proxy = (IProxy) MBeanServerInvocationHandler.newProxyInstance(connection, new ObjectName("org.jacoco:type=Runtime"), IProxy.class, false);

       final byte[] data = proxy.getExecutionData(false);
       System.out.println("Got " + data.length + " bytes");
    }

    public interface IProxy {
        String getVersion();
        String getSessionId();
        void setSessionId(String id);
        byte[] getExecutionData(boolean reset);
        void dump(boolean reset);
        void reset();
    }
}

execution of javac MBeanClient.java && java MBeanClient produces

Got 84 bytes


问:
how to use new line for BSD sed substitution
I have a sed command as follows:

```<code>sed -i 's/),(/),\n(/g' myfile
</code>```

myfile is like this:

```<code>(237),(238)
</code>```

The expected result is:

```<code>(237),
(238)
</code>```

The actual result is:

```<code>(237),n(238)
</code>```

I have tried many ways to write new line, but all failed. Is it possible to get the expected result?

I found that GNU sed works, but BSD sed not.

答:
for BSD sed, we can write new line as $'\n', so the command should be:

```<code>/usr/bin/sed 's/),(/),\'$'\n''(/g' myfile
</code>```

Body:
I have a sed command as follows:

sed -i 's/),(/),\n(/g' myfile

myfile is like this:

(237),(238)

The expected result is:

(237),
(238)

The actual result is:

(237),n(238)

I have tried many ways to write new line, but all failed. Is it possible to get the expected result?

I found that GNU sed works, but BSD sed not.

Body:
for BSD sed, we can write new line as $'\n', so the command should be:

/usr/bin/sed 's/),(/),\'$'\n''(/g' myfile


问:
Preg_match(_all) can't collect some data from Google
I'm creating a tool for my websites to see what position they are in Google on different keywords.

Now, I want to collect this part of their sourcecode:

```<code><a href="http://www.test.com/" class=l onmousedown="return clk(this.href,'','','','1','','0CBoQFjAA')">Linktitle in Google!</a>
</code>```

The problem is that the preg_match OR preg_match_all function doesn't match "onmousedown" or "this.href" or the ,'1' part of the link. And that is exactly the part i need...

Does anyone has an idea why this is, and more important.. how to solve this???

The code I use is obvious.. i even tried to use "/onmousedown/" or "/\'1\'/" but it didn't help.

Thank you very much!!!!

答:
Besides the ethical and possible legal implications of scraping Google, you should not be using regular expressions to extract portions of HTML. Regular expressions were not designed to parse HTML and are not equipped for the specific grammar.

Try using a HTML parser, such as DOMDocument. It was designed to parse HTML/XML.

ContentLicense: CC BY-SA 3.0

Body:
I'm creating a tool for my websites to see what position they are in Google on different keywords.

Now, I want to collect this part of their sourcecode:

Linktitle in Google!

The problem is that the preg_match OR preg_match_all function doesn't match "onmousedown" or "this.href" or the ,'1' part of the link. And that is exactly the part i need...

Does anyone has an idea why this is, and more important.. how to solve this???

The code I use is obvious.. i even tried to use "/onmousedown/" or "/\'1\'/" but it didn't help.

Thank you very much!!!!


问:
UTL_FILE not creating a file and not giving an error
I am running a concurrent program which runs a package.procedure, it is suppose to take output of a cursor and add it into a .csv file. Earlier it was running fine however when I am running now the file is not getting created in the server directory, instead it is dumping the o/p in the output file even though no code which dumps the file data in output file.

The directory exists and there are permissions to read, write and execute for this.

The log or o/p file does not give any error and we have exceptions defined.
I am using r12.1.3 and linux 6.

Thanks

答:
issue found. The reason was I was running the wrong concurrent program. Silly of me. Ran the correct program and now getting the o/p.

Thank you all for your help and comments.

Thanks


问:
Random number generator with strings
I have some code that sends a number that is pre-calculated to an Arduino.
instead of a pre-calculated number, I want a random number between a range of number, for example between the numbers 1 to 20, the random number is 18,
after the random number is found put it in a string so I can work with it.

I've tried many things on stack overflow but things are too complicated and I work with C#.
the code below is what I have right now,
I would prefer that it will send that random number to the Arduino

```<code>namespace MyLaserTurret
{

   public partial class Form1 : Form
    {
        public Stopwatch watch { get; set; }

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            watch = Stopwatch.StartNew();
            port.Open();
        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            writeToPort(new Point(e.X, e.Y));
        }

        public void writeToPort(Point coordinates)
        {
            if (watch.ElapsedMilliseconds > 15)
            {
                watch = Stopwatch.StartNew();

                port.Write(String.Format("X{0}Y{1}",
                (coordinates.X / (Size.Width / 180)),
                (coordinates.Y / (Size.Height / 180))));
            }

        }
    }
}
</code>```

答:
To create a random number as a string you use this code

```<code>    private Random random = new Random();

    public string RandomNumber(int min, int max)
    {
        return random.Next(min, max).ToString();
    }
</code>```

Please note that it is probably best practice to declare a "Random random = new Random();" as a class property because when a Random is created too closely together they will just keep having the same value

Title: Random number generator with strings

Body:
I have some code that sends a number that is pre-calculated to an Arduino.
instead of a pre-calculated number, I want a random number between a range of number, for example between the numbers 1 to 20, the random number is 18,
after the random number is found put it in a string so I can work with it.

I've tried many things on stack overflow but things are too complicated and I work with C#.
the code below is what I have right now,
I would prefer that it will send that random number to the Arduino

namespace MyLaserTurret
{

   public partial class Form1 : Form
    {
        public Stopwatch watch { get; set; }

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            watch = Stopwatch.StartNew();
            port.Open();
        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            writeToPort(new Point(e.X, e.Y));
        }

        public void writeToPort(Point coordinates)
        {
            if (watch.ElapsedMilliseconds > 15)
            {
                watch = Stopwatch.StartNew();

                port.Write(String.Format("X{0}Y{1}",
                (coordinates.X / (Size.Width / 180)),
                (coordinates.Y / (Size.Height / 180))));
            }

        }
    }
}

Body:
To create a random number as a string you use this code

    private Random random = new Random();

    public string RandomNumber(int min, int max)
    {
        return random.Next(min, max).ToString();
    }

Please note that it is probably best practice to declare a "Random random = new Random();" as a class property because when a Random is created too closely together they will just keep having the same value