问:
UWP Binding to a property
I am making a UWP and cannot correctly grasp DataBinding and INotifyPropertyChanged
I am trying to bind some TextBox in a ContentDialog to properties in my code-behind cs file.

Here's my view model:

```<code>class UserViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    public string _fname { get; set; }
    public string _lname { get; set; }

    public string Fname
    {
        get { return _fname; }
        set
        {
            _fname = value;
            this.OnPropertyChanged();
        }
    }

    public string Lname
    {
        get { return _lname; }
        set
        {
            _lname = value;
            this.OnPropertyChanged();
        }
    }

    public void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}
</code>```

Code behind:

```<code>public sealed partial class MainPage : Page
{
    UserViewModel User { get; set; }

    public MainPage()
    {
        this.InitializeComponent();
        User = new UserViewModel();
    }
    ....
    ....
    private void SomeButton_Click(object sender, TappedRoutedEventArgs e)
    {
        //GetUserDetails is a static method that returns UserViewModel
        User = UserStore.GetUserDetails();

        //show the content dialog
        ContentDialogResult result = await UpdateUserDialog.ShowAsync();
    }
}
</code>```

Here's the XAML for the ContentDialog:

```<code><ContentDialog Name="UpdateUserDialog">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"></RowDefinition>
        <RowDefinition Height="Auto"></RowDefinition>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="1*"></ColumnDefinition>
        <ColumnDefinition Width="1*"></ColumnDefinition>
    </Grid.ColumnDefinitions>

    <TextBox Grid.Row="0"
        Grid.Column="0"
        Grid.ColumnSpan="2"
        Name="tbFirstNameUpdate"
        Text="{x:Bind Path=User.Fname, Mode=OneWay}"
        Style="{StaticResource SignUpTextBox}"/>

    <TextBox Grid.Row="1"
        Grid.Column="0"
        Grid.ColumnSpan="2"
        Name="tbLastNameUpdate"
        Text="{x:Bind Path=User.Lname, Mode=OneWay}"
        Style="{StaticResource SignUpTextBox}"/>
</ContentDialog>
</code>```

NOTE: Binding works well when I initialize the view model in the MainPage constructor itself like this:

```<code>User = new UserViewModel { Fname = "name", Lname = "name" };
</code>```

答:
You should set the DataContext property to the view model instance:

```<code>public MainPage()
{
    this.InitializeComponent();
    User = new UserViewModel();
    DataContext = User;
}
</code>```

See: https://learn.microsoft.com/en-us/windows/uwp/data-binding/data-binding-in-depth

Title: UWP Binding to a property

Body:
I am making a UWP and cannot correctly grasp DataBinding and INotifyPropertyChanged
I am trying to bind some TextBox in a ContentDialog to properties in my code-behind cs file.

Here's my view model:

class UserViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    public string _fname { get; set; }
    public string _lname { get; set; }

    public string Fname
    {
        get { return _fname; }
        set
        {
            _fname = value;
            this.OnPropertyChanged();
        }
    }

    public string Lname
    {
        get { return _lname; }
        set
        {
            _lname = value;
            this.OnPropertyChanged();
        }
    }

    public void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

Code behind:

public sealed partial class MainPage : Page
{
    UserViewModel User { get; set; }

    public MainPage()
    {
        this.InitializeComponent();
        User = new UserViewModel();
    }
    ....
    ....
    private void SomeButton_Click(object sender, TappedRoutedEventArgs e)
    {
        //GetUserDetails is a static method that returns UserViewModel
        User = UserStore.GetUserDetails();

        //show the content dialog
        ContentDialogResult result = await UpdateUserDialog.ShowAsync();
    }
}

Here's the XAML for the ContentDialog:

<ContentDialog Name="UpdateUserDialog">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"></RowDefinition>
        <RowDefinition Height="Auto"></RowDefinition>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="1*"></ColumnDefinition>
        <ColumnDefinition Width="1*"></ColumnDefinition>
    </Grid.ColumnDefinitions>

    <TextBox Grid.Row="0"
        Grid.Column="0"
        Grid.ColumnSpan="2"
        Name="tbFirstNameUpdate"
        Text="{x:Bind Path=User.Fname, Mode=OneWay}"
        Style="{StaticResource SignUpTextBox}"/>

    <TextBox Grid.Row="1"
        Grid.Column="0"
        Grid.ColumnSpan="2"
        Name="tbLastNameUpdate"
        Text="{x:Bind Path=User.Lname, Mode=OneWay}"
        Style="{StaticResource SignUpTextBox}"/>
</ContentDialog>

NOTE: Binding works well when I initialize the view model in the MainPage constructor itself like this:

User = new UserViewModel { Fname = "name", Lname = "name" };

Body:
You should set the DataContext property to the view model instance:

public MainPage()
{
    this.InitializeComponent();
    User = new UserViewModel();
    DataContext = User;
}

See: https://learn.microsoft.com/en-us/windows/uwp/data-binding/data-binding-in-depth


来源: stackexchange

问:
Rolling correlation between lists in R
I have two lists, listA and listB which I would like to calculate the correlation between them using a rolling window of size 4.

```<code>listA
    A   B   C   D
1)  1   3   4   6
2)  6   9   11  1
3)  1   3   4   5
4)  8   4   5   6
5)  9   9   4   6
6)  1   5   6   6
7)  9   3   6   4
8)  6   7   8   9

listB
    A   B   C   D
1)  1   3   4   3
2)  6   9   5   7
3)  1   1   4   5
4)  7   1   5   6
5)  9   9   3   6
6)  1   5   6   6
7)  9   9   6   4
8)  5   6   4   9
</code>```

Specifically I wish to calculate the cor(listA[1:4,1],listB[1:4,1]) using a rolling window of size 4 which means I'll have 5 values for the correlation between listA and listB for column A. Once this is done for column A I then would like to do the same for column B, C and D.

I have previously achieved this using 'rollapplyr' but the object I was working on was an XTS object and not two individual objects which for my simple little brain made it easier to comprehend.

```<code>'result <- rollapplyr(XTSobject, 4, cor, by.column = FALSE)'
</code>```

Can anyone suggest a way to do this between two lists?

ContentLicense: CC BY-SA 3.0

Title: Rolling correlation between lists in R

Body:
I have two lists, listA and listB which I would like to calculate the correlation between them using a rolling window of size 4.

listA
    A   B   C   D
1)  1   3   4   6
2)  6   9   11  1
3)  1   3   4   5
4)  8   4   5   6
5)  9   9   4   6
6)  1   5   6   6
7)  9   3   6   4
8)  6   7   8   9

listB
    A   B   C   D
1)  1   3   4   3
2)  6   9   5   7
3)  1   1   4   5
4)  7   1   5   6
5)  9   9   3   6
6)  1   5   6   6
7)  9   9   6   4
8)  5   6   4   9

Specifically I wish to calculate the cor(listA[1:4,1],listB[1:4,1]) using a rolling window of size 4 which means I'll have 5 values for the correlation between listA and listB for column A. Once this is done for column A I then would like to do the same for column B, C and D.

I have previously achieved this using 'rollapplyr' but the object I was working on was an XTS object and not two individual objects which for my simple little brain made it easier to comprehend.

'result <- rollapplyr(XTSobject, 4, cor, by.column = FALSE)'

Can anyone suggest a way to do this between two lists?

Body:
Let me randomly generate listA and listB  and work on them:

listA<-data.frame(matrix(rnorm(32), c(8,4)))
listB<-data.frame(matrix(rnorm(32), c(8,4)))

Then, prepare array for you results:

result<-array(NA, c(5,4))
dimnames(result)<-list(paste0(1:5, '-', 4:8), colnames(listA))

Loop-in-loop now:

for(i in 1:5){
 for (j in 1:4){
  result[i,j]<-cor(listA[i:(i+3),j], listB[i:(i+3),j])
   }
 }

Here is what I got:

result
             X1         X2         X3          X4
1-4 -0.24299058 -0.6359179 -0.3303014  0.46628496
2-5 -0.05606969 -0.9332142 -0.5414745  0.08460162
3-6  0.21371864 -0.5366821 -0.5799187  0.19306623
4-7  0.50005529 -0.4661710  0.2146866  0.49636429
5-8  0.52684198 -0.3768619  0.3599111 -0.93804204

The same could be achieved without looping by using the apply family instead.


问:
Is there any replicate function in Kotlin?
replicate(n:Int,x:T):List<T>  is a list of length n with x the value of every element.

I wrote a mutable version replicate as below:

```<code>fun <T> mutableReplicate(n:Int, x:T) : MutableList<T>{
    val xs = mutableListOf<T>()
    for (i in 1..n){
        xs.add(x)
    }
    return xs
}
</code>```

Is there any bulid-in immutable replicate function in Kotlin?

How to write ourselves an immutable replicate function in Kotlin?

答:
You can use List instantiation functions. They accept a function from the Index to the desired element, but you can also use them to create a List of constant values.

```<code>fun <T> replicate(n:Int,x:T):List<T> {
   return List(n) { x }
}
</code>```

Body:
replicate(n:Int,x:T):List<T>  is a list of length n with x the value of every element.

I wrote a mutable version replicate as below:

fun <T> mutableReplicate(n:Int, x:T) : MutableList<T>{
    val xs = mutableListOf<T>()
    for (i in 1..n){
        xs.add(x)
    }
    return xs
}

Is there any bulid-in immutable replicate function in Kotlin?

How to write ourselves an immutable replicate function in Kotlin?

Body:
You can use List instantiation functions. They accept a function from the Index to the desired element, but you can also use them to create a List of constant values.

fun <T> replicate(n:Int,x:T):List<T> {
   return List(n) { x }
}


问:
Find previous call - SQL
In my table of customer calls I have the following data:

```<code> ID | PHONE_NO | ASSET_ID | CALLTIME           | PREV_ID
====+==========+==========+====================+========
1256|0123456789|  69456321| 2017-04-10 14:32:11|
1257|0214566985|  48563256| 2017-04-11 09:08:47|
1258|0123456789|  69456321| 2017-04-12 10:58:12|    1256 <- prev call ID (phone_no+asset_id)
1259|0315654258|  98643215| 2017-04-15 22:14:36|
1260|0412365214|  69456321| 2017-04-18 18:32:54|    1258 <- prev call ID (asset_id)
</code>```

I need the query which will find if there was a call from the same customer in previous 10 days (this query should update PREV_ID column). The previous call is call from the same customer (means from the same PHONE_NO or with the same ASSET_ID) occured within 10 days prior to the current call. PREV_ID column has to contain the ID of previous call (the closest one because within 10 days there could be more of them from the same customer).

答:
Tested in Postgres, but should work in Oracle as well. Getting the previous calls for each call that has them:

```<code>SELECT c2.ID AS CALL_ID, c1.ID AS PREVIOUS_CALL_ID
FROM calls c1, calls c2
WHERE c1.ID < c2.ID
    AND (c1.PHONE_NO = c2.PHONE_NO
        OR c1.ASSET_ID = c2.ASSET_ID)
    AND c1.CALLTIME > c2.CALLTIME - INTERVAL '10' DAY
ORDER BY CALL_ID DESC, PREVIOUS_CALL_ID DESC;
</code>```

And updating the table with the new PREV_ID values:

```<code>UPDATE calls c2
SET PREV_ID = (
    SELECT c1.ID
    FROM calls c1
    WHERE c1.ID < c2.ID
        AND (c1.PHONE_NO = c2.PHONE_NO
            OR c1.ASSET_ID = c2.ASSET_ID)
        AND c1.CALLTIME > c2.CALLTIME - INTERVAL '10' DAY
    ORDER BY c1.ID DESC
    LIMIT 1)
WHERE c2.PREV_ID IS NULL;
</code>```

Title: Find previous call - SQL

Body:
In my table of customer calls I have the following data:

 ID | PHONE_NO | ASSET_ID | CALLTIME           | PREV_ID
====+==========+==========+====================+========
1256|0123456789|  69456321| 2017-04-10 14:32:11|
1257|0214566985|  48563256| 2017-04-11 09:08:47|
1258|0123456789|  69456321| 2017-04-12 10:58:12|    1256 <- prev call ID (phone_no+asset_id)
1259|0315654258|  98643215| 2017-04-15 22:14:36|
1260|0412365214|  69456321| 2017-04-18 18:32:54|    1258 <- prev call ID (asset_id)

I need the query which will find if there was a call from the same customer in previous 10 days (this query should update PREV_ID column). The previous call is call from the same customer (means from the same PHONE_NO or with the same ASSET_ID) occured within 10 days prior to the current call. PREV_ID column has to contain the ID of previous call (the closest one because within 10 days there could be more of them from the same customer).

Body:
Tested in Postgres, but should work in Oracle as well. Getting the previous calls for each call that has them:

SELECT c2.ID AS CALL_ID, c1.ID AS PREVIOUS_CALL_ID
FROM calls c1, calls c2
WHERE c1.ID < c2.ID
    AND (c1.PHONE_NO = c2.PHONE_NO
        OR c1.ASSET_ID = c2.ASSET_ID)
    AND c1.CALLTIME > c2.CALLTIME - INTERVAL '10' DAY
ORDER BY CALL_ID DESC, PREVIOUS_CALL_ID DESC;

And updating the table with the new PREV_ID values:

UPDATE calls c2
SET PREV_ID = (
    SELECT c1.ID
    FROM calls c1
    WHERE c1.ID < c2.ID
        AND (c1.PHONE_NO = c2.PHONE_NO
            OR c1.ASSET_ID = c2.ASSET_ID)
        AND c1.CALLTIME > c2.CALLTIME - INTERVAL '10' DAY
    ORDER BY c1.ID DESC
    LIMIT 1)
WHERE c2.PREV_ID IS NULL;


问:
Connecting Android with PHPMyAdmin
i'm having some trouble in connecting my android project to a database at phpmyadmin, can somebody help me how to connect my android project to phpmyadmin?

these are my java codes, it just need to fill the else at the bottom one:

```<code>import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Activity_SignUp extends AppCompatActivity{

private Button btnSubmit;
private EditText name;
private EditText uname;
private EditText pass;
private EditText jabatan;
private EditText confirm;

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_signup);

    btnSubmit = (Button) findViewById(R.id.btnSubmit);
    name = (EditText) findViewById(R.id.Name);
    jabatan = (EditText) findViewById(R.id.Jabatan);
    uname = (EditText) findViewById(R.id.UName);
    pass = (EditText) findViewById(R.id.Pass);
    confirm = (EditText) findViewById(R.id.Confirm);

    btnSubmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onClick_SignUp(v);

        }
    });
}

public void onClick_SignUp(View v){

    if (name.getText().toString().equals("")) {
        Toast.makeText(Activity_SignUp.this, "Name Must be Filled", Toast.LENGTH_SHORT).show();
    } else if (jabatan.getText().toString().equals("")) {
        Toast.makeText(Activity_SignUp.this, "Age Must be Filled", Toast.LENGTH_SHORT).show();
    } else if (uname.getText().toString().equals("")) {
        Toast.makeText(Activity_SignUp.this, "UserName must Be Filled", Toast.LENGTH_SHORT).show();
    } else if (pass.getText().toString().equals("")) {
        Toast.makeText(Activity_SignUp.this, "Password must be Filled", Toast.LENGTH_SHORT).show();
    } else if (confirm.getText().toString().equals("")) {
        Toast.makeText(Activity_SignUp.this, "Confirm Must be Filled", Toast.LENGTH_SHORT).show();
    } else if (!confirm.getText().toString().equals(pass.getText().toString())) {
        Toast.makeText(Activity_SignUp.this, "Confirm Doesn't match", Toast.LENGTH_SHORT).show();
    } else {

    }
}
}`
</code>```

this is my php file:

Service.php

```<code><?php

define('HOST','localhost');
define('USER','root');
define('PASS','');
define('DB','account');

$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');

$Nama = $_POST['Nama'];
$Jabatan = $_POST['Jabatan'];
$Username = $_POST['Username'];
$Password = $_POST['Password'];

$sql = "insert into account (Nama,Jabatan,Username,Password) values ('$Nama','$Jabatan','$Username','$Password')";
if(mysqli_query($con,$sql)){
  echo 'success';
}
else{
  echo 'failure';
}
mysqli_close($con);

?>
</code>```

dbConnect.php

```<code><?php
define('HOST','localhost');
define('USER','root');
define('PASS','');
define('DB','account');

$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
?>
</code>```

insert.php

```<code><?php

if($_SERVER['REQUEST_METHOD']=='POST'){

$Nama = $_POST['Nama'];
$Jabatan = $_POST['Jabatan'];
$Username = $_POST['Username'];
$Password = $_POST['Password'];

if($Nama == '' || $Jabatan == '' || $Username == '' || $Password == ''){

}else{

require_once('dbConnect.php');

$sql = "SELECT * FROM account WHERE Username='$Username'";

$check = mysqli_fetch_array(mysqli_query($con,$sql));

if(isset($check)){
echo 'Username already exist';
}else{
    $sql = "INSERT INTO account (Nama,Jabatan,Username,Password) VALUES('$Nama','$Jabatan','$Username','$Password')";

    if(mysqli_query($con,$sql)){
        echo 'successfully registered';
    }else{
        echo 'oops! Please try again!';
    }
}
    mysqli_close($con);
}
}else{
    echo 'error';
}
?>
</code>```

答:
If your Apache and MySql are running, you can access it using the ip address.
Get the Ip of your system running the services and put your android device on the same network then instead of http://localhost/.... Use the ip address
for example http://10.0.2.2/.... in your urls configurations</p>

Title: Connecting Android with PHPMyAdmin

Body:
i'm having some trouble in connecting my android project to a database at phpmyadmin, can somebody help me how to connect my android project to phpmyadmin?

these are my java codes, it just need to fill the else at the bottom one:

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Activity_SignUp extends AppCompatActivity{

private Button btnSubmit;
private EditText name;
private EditText uname;
private EditText pass;
private EditText jabatan;
private EditText confirm;

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_signup);

    btnSubmit = (Button) findViewById(R.id.btnSubmit);
    name = (EditText) findViewById(R.id.Name);
    jabatan = (EditText) findViewById(R.id.Jabatan);
    uname = (EditText) findViewById(R.id.UName);
    pass = (EditText) findViewById(R.id.Pass);
    confirm = (EditText) findViewById(R.id.Confirm);

    btnSubmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onClick_SignUp(v);

        }
    });
}

public void onClick_SignUp(View v){

    if (name.getText().toString().equals("")) {
        Toast.makeText(Activity_SignUp.this, "Name Must be Filled", Toast.LENGTH_SHORT).show();
    } else if (jabatan.getText().toString().equals("")) {
        Toast.makeText(Activity_SignUp.this, "Age Must be Filled", Toast.LENGTH_SHORT).show();
    } else if (uname.getText().toString().equals("")) {
        Toast.makeText(Activity_SignUp.this, "UserName must Be Filled", Toast.LENGTH_SHORT).show();
    } else if (pass.getText().toString().equals("")) {
        Toast.makeText(Activity_SignUp.this, "Password must be Filled", Toast.LENGTH_SHORT).show();
    } else if (confirm.getText().toString().equals("")) {
        Toast.makeText(Activity_SignUp.this, "Confirm Must be Filled", Toast.LENGTH_SHORT).show();
    } else if (!confirm.getText().toString().equals(pass.getText().toString())) {
        Toast.makeText(Activity_SignUp.this, "Confirm Doesn't match", Toast.LENGTH_SHORT).show();
    } else {

    }
}
}`

this is my php file:

Service.php

<?php

define('HOST','localhost');
define('USER','root');
define('PASS','');
define('DB','account');

$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');

$Nama = $_POST['Nama'];
$Jabatan = $_POST['Jabatan'];
$Username = $_POST['Username'];
$Password = $_POST['Password'];

$sql = "insert into account (Nama,Jabatan,Username,Password) values ('$Nama','$Jabatan','$Username','$Password')";
if(mysqli_query($con,$sql)){
  echo 'success';
}
else{
  echo 'failure';
}
mysqli_close($con);

?>

dbConnect.php

<?php
define('HOST','localhost');
define('USER','root');
define('PASS','');
define('DB','account');

$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
?>

insert.php

<?php

if($_SERVER['REQUEST_METHOD']=='POST'){

$Nama = $_POST['Nama'];
$Jabatan = $_POST['Jabatan'];
$Username = $_POST['Username'];
$Password = $_POST['Password'];

if($Nama == '' || $Jabatan == '' || $Username == '' || $Password == ''){

}else{

require_once('dbConnect.php');

$sql = "SELECT * FROM account WHERE Username='$Username'";

$check = mysqli_fetch_array(mysqli_query($con,$sql));

if(isset($check)){
echo 'Username already exist';
}else{
    $sql = "INSERT INTO account (Nama,Jabatan,Username,Password) VALUES('$Nama','$Jabatan','$Username','$Password')";

    if(mysqli_query($con,$sql)){
        echo 'successfully registered';
    }else{
        echo 'oops! Please try again!';
    }
}
    mysqli_close($con);
}
}else{
    echo 'error';
}
?>


问:
Unable to bring uploaded images into uploads file using php
After creating a form and typing the php code, i have a form where i am able to input a file, specifically an image, and without reciving any error messages, as well as getting the success message in my url, the image uploaded still can not be found in its destination folder.

Here is the HTML

```<code><form action="" class="navbar-form navbar-right" role="search">
                    <div class="form-group">
                        <input type="text" class="form-control" placeholder="Find Art Here">
                    </div>
                    <button type="submit" class="btn btn-primary">Search</button>
                </form>
</code>```

and here's the php

```<code><?php
if (isset($_POST['submit'])) {
$file = $_FILES['file'];

$fileName = $file['name'];
$fileTmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileError = $file['error'];
$fileType = $file['type'];

$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));

$allow = array('jpg', 'jpeg', 'png', 'pdf');

if (in_array($fileActualExt, $allow)) {
    if($fileError === 0){
        if($fileSize < 5000000) {
            $fileNameNew = uniqid('', true).".".$fileActualExt;
        $fileDestination = 'uplaods/'.$fileNameNew;
        move_uploaded_file($fileTmpName, $fileDestination);
            header("Location: index.php?uploadsucess");
        } else{
            echo "Your file is too big";
        }
    } else {
        echo "There was an error uplaoding your file!";
    }
} else{
    echo "You cannot upload files of this type!";
}
</code>```

}

Code is based and modified from this video : https://www.youtube.com/watch?v=JaRq73y5MJk

Any help would be much appreciated!

答:
The first thing you have to do is adding enctype="multipart/form-data" and method="post" to your form-tag:

```<code><form action="" method="post" enctype="multipart/form-data">
</code>```

If it then still doesn't work, check the upload_max_filesize and the post_max_size settings in your php.ini. If your file is too big, only move_uploaded_file() will return false, so check that function as well.

Body:
After creating a form and typing the php code, i have a form where i am able to input a file, specifically an image, and without reciving any error messages, as well as getting the success message in my url, the image uploaded still can not be found in its destination folder.

Here is the HTML

<form action="" class="navbar-form navbar-right" role="search">

                        <input type="text" class="form-control" placeholder="Find Art Here">

                    <button type="submit" class="btn btn-primary">Search</button>
                </form>

and here's the php

<?php
if (isset($_POST['submit'])) {
$file = $_FILES['file'];

$fileName = $file['name'];
$fileTmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileError = $file['error'];
$fileType = $file['type'];

$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));

$allow = array('jpg', 'jpeg', 'png', 'pdf');

if (in_array($fileActualExt, $allow)) {
    if($fileError === 0){
        if($fileSize < 5000000) {
            $fileNameNew = uniqid('', true).".".$fileActualExt;
        $fileDestination = 'uplaods/'.$fileNameNew;
        move_uploaded_file($fileTmpName, $fileDestination);
            header("Location: index.php?uploadsucess");
        } else{
            echo "Your file is too big";
        }
    } else {
        echo "There was an error uplaoding your file!";
    }
} else{
    echo "You cannot upload files of this type!";
}

}

Code is based and modified from this video : https://www.youtube.com/watch?v=JaRq73y5MJk

Any help would be much appreciated!

Body:
The first thing you have to do is adding enctype="multipart/form-data" and method="post" to your form-tag:

<form action="" method="post" enctype="multipart/form-data">

If it then still doesn't work, check the upload_max_filesize and the post_max_size settings in your php.ini. If your file is too big, only move_uploaded_file() will return false, so check that function as well.


问:
Is filling a grid with images so I could control location a good practice?
I'm trying to locate a few images on a grid, but when I try to do something like

```<code>panel = Label(root, image = img)
panel.grid(row = a, column = b)
</code>```

where a,b are values that should bring the image to the center of the grid, I always get the image on the top left corner, because empty columns/rows don't fill the space. So, using a friend's advice, I added a blank image and did something like

```<code>a = 0
b = 0

for img in ls2: # ls2 is a list containing instances of the blank image
    a += 1
    if a == 11:
        a = 1
        b += 1

    panel = Label(root, image = img)
    panel.grid(row = a, column = b)
</code>```

Now, when I'm trying to locate a new image on row = x, column = y it goes as I wanted and this is my current solution. My question is, is this a good way to enable me use the whole grid?

答:
Just found the place geometry manager. It is more explicit and lets me control the exact locations of my images inside the widget.

panel.place(x=100, y=100) gives pixel precision location which was what I looked for in the first place.

Body:
I'm trying to locate a few images on a grid, but when I try to do something like

panel = Label(root, image = img)
panel.grid(row = a, column = b)

where a,b are values that should bring the image to the center of the grid, I always get the image on the top left corner, because empty columns/rows don't fill the space. So, using a friend's advice, I added a blank image and did something like

a = 0
b = 0

for img in ls2: # ls2 is a list containing instances of the blank image
    a += 1
    if a == 11:
        a = 1
        b += 1

    panel = Label(root, image = img)
    panel.grid(row = a, column = b)

Now, when I'm trying to locate a new image on row = x, column = y it goes as I wanted and this is my current solution. My question is, is this a good way to enable me use the whole grid?


问:
HTTP Status 500-/index.jsp "/struts-tags" not found
Hi Can anyone help me out to resolve the error mentioned above.
I used a index.jsp file

```<code>    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
        <%@ taglib prefix="s" uri="/struts-tags"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Hello World</title>
    </head>
    <body>
        <h1>Hello World From Struts2</h1>
       <form action="hello">
          <label for="name">Please enter your name</label><br/>
          <input type="text" name="name"/>
          <input type="submit" value="Say Hello"/>
       </form>
    </body>
    </html>
</code>```

After writing all the classes and xml files,I have run the classes by tomcat server but got an error as follows

Can anyone help me out as I am new to Struts

答:
Try these:

Seems like you copied the libraries manually and directly into the folder WEB-INF/lib of the project and eclipse doesn't sense them, I suggest that you copy any necessary libraries into WEB-INF/lib only through eclipse. I had this issue previously and only a refresh of the project solved the problem.

add struts2-core.jar to the project
 download it here.
Select Project and right click, Click on the properties, Click on
libraries tab, Click on 'Add Jars', Add relevant jar for you.

Body:
Hi Can anyone help me out to resolve the error mentioned above.
I used a index.jsp file

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
        <%@ taglib prefix="s" uri="/struts-tags"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Hello World</title>

Hello World From Struts2

       <form action="hello">
          Please enter your name

          <input type="text" name="name"/>
          <input type="submit" value="Say Hello"/>
       </form>

After writing all the classes and xml files,I have run the classes by tomcat server but got an error as follows

Can anyone help me out as I am new to Struts


问:
Is it possible to concatenate all haarcascade *.xml into one file?
Is it possible to concatenate all haarcascade *.xml into one file ? I'd like to search faces in all possible situations.
If so, how to do that?

thanks!

答:
It may not be possible to concatenate them into one. But their results may be used in the same image for incresed accuracy. Import all of them in your code and detect features using all of them. But keep a check that the same feature is not detected multiple times. This can be easily done as we have the coordinates of each of the detected features.

Best of luck!


问:
Is it possible to store a list of ids as an attribute for an object in rails?
I'm trying to implement a voting system where users can upvote/downvote links posted by other users. A user can only vote on a link once, so before I execute upvote or downvote I need to check if the user has already voted and if they had already voted, wheather they upvoted or downvoted, so that I can disable the button for the other.

There are a few ways to do this. The most immediate solution that comes to me is to have two additional columns in the link model, one to store a list of ids of users that upvoted and the other to store a list of ids of users that downvoted.

Two concerns arise in my mind. One, is this even considered a good practice (in terms of database efficiency) and if it is the best way to do it, how do I store a list of ids as an attribute for the model? What would be the data type I need to enter for the migration?

答:
No, it is not a good practice storing votes as list of ids in a field. You are violating the 1NF of your database. 1NF wiki

Imagine this happening on a scale of millions of votes, not only is the storage inefficient, but also imagining fetching and scanning the whole list if you want to see if a voter voted for given object.

The better solution for this will be to have A "Vote" table with columns like "voter_id", "voted_for_id", "vote_value".

Proper indexes will ensure that you will be able to do most of your operations very efficiently even on very large data. e.g.:- finding number of upvotes/downvotes for a candidate or finding whether a person has already voted for a candidate etc.


问:
Set any range with userform
I am currently looking for a way to assign a range via UserForm. I've often encountered the example with the RefEdit, which unfortunately does not fit 100% to my problem.

Is there a way where the enduser can assigns a range with a textbox? The User should be asked in which column in his sheet the relevant numerical values are and on that basis, the macro should adjust the range.

For example:
The user types the range is in column H and there for the macro adjust to:

```<code>ws.Range("H2: H" & lastrow)
</code>```

答:
```<code>ws.Range(Var & "2:" & Var & lastrow)
</code>```

Title: Set any range with userform

Body:
I am currently looking for a way to assign a range via UserForm. I've often encountered the example with the RefEdit, which unfortunately does not fit 100% to my problem.

Is there a way where the enduser can assigns a range with a textbox? The User should be asked in which column in his sheet the relevant numerical values are and on that basis, the macro should adjust the range.

For example:
The user types the range is in column H and there for the macro adjust to:

ws.Range("H2: H" & lastrow)

Body: ws.Range(Var & "2:" & Var & lastrow)


问:
Testing AMD modules with tape/ES6 unit tests?
I have a web app using:

ES5

RequireJS

Underscore

Backbone

jQuery

I have tried setting up a new unit test suite using:

ES6

Tape

Babel6

My AMD module app/util/stringUtil.js:

```<code>define([], function() {
    'use strict';

    return {
        isBlank: function(str) {
            return _.isUndefined(str) || _.isNull(str) || _.isString(str) && str.trim().length === 0;
        }
    };
});
</code>```

My unit test in tapeTest.js:

```<code>import test from 'tape';
import sortUtil from 'app/util/stringUtil';

test('Testing stringUtil', (assert) => {

    assert.ok(stringUtil.isBlank('   ')),
        'Should be blank');

    assert.end();
});
</code>```

My .babelrc:

```<code>{
  "presets": ["es2015"]
}
</code>```

I run the test with tape:

```<code>tape -r babel-register tapeTest.js
</code>```

I get the following error:

```<code>app/util/stringUtil.js:1
(function (exports, require, module, __filename, __dirname) { define([], function () {
                                                              ^
ReferenceError: define is not defined
    at Object.<anonymous> (stringUtil.js:1:23)
    at Module._compile (module.js:434:26)
    at loader (node_modules/babel-register/lib/node.js:126:5)
    at Object.require.extensions.(anonymous function) [as .js] (node_modules/babel-register/lib/node.js:136:7)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (tapeTest.js:7:17)
    at Module._compile (module.js:434:26)
</code>```

I'm guessing tape doesn't recognize AMD modules? Can I fix this somehow? Maybe transpile AMD modules to CommonJS modules or something?

答:
You can load AMD modules inside node with requirejs :_)

Read here: http://requirejs.org/docs/node.html

You have to import require and do a little config, something like this:

```<code>'use strict';

const test = require('tape');
const requirejs = require('requirejs');

requirejs.config({
    baseUrl: __dirname,
    nodeRequire: require
});

test('Test something', function (assert) {
    requirejs(['app/util/stringUtil'], function   (stringUtil) {

        assert.ok(stringUtil.isBlank('   '), 'Should be blank');

        assert.end();
    });
});
</code>```

Body:
I have a web app using:

ES5

RequireJS

Underscore

Backbone

jQuery

I have tried setting up a new unit test suite using:

ES6

Tape

Babel6

My AMD module app/util/stringUtil.js:

define([], function() {
    'use strict';

    return {
        isBlank: function(str) {
            return _.isUndefined(str) || _.isNull(str) || _.isString(str) && str.trim().length === 0;
        }
    };
});

My unit test in tapeTest.js:

import test from 'tape';
import sortUtil from 'app/util/stringUtil';

test('Testing stringUtil', (assert) => {

    assert.ok(stringUtil.isBlank('   ')),
        'Should be blank');

    assert.end();
});

My .babelrc:

{
  "presets": ["es2015"]
}

I run the test with tape:

tape -r babel-register tapeTest.js

I get the following error:

app/util/stringUtil.js:1
(function (exports, require, module, __filename, __dirname) { define([], function () {
                                                              ^
ReferenceError: define is not defined
    at Object.<anonymous> (stringUtil.js:1:23)
    at Module._compile (module.js:434:26)
    at loader (node_modules/babel-register/lib/node.js:126:5)
    at Object.require.extensions.(anonymous function) [as .js] (node_modules/babel-register/lib/node.js:136:7)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (tapeTest.js:7:17)
    at Module._compile (module.js:434:26)

I'm guessing tape doesn't recognize AMD modules? Can I fix this somehow? Maybe transpile AMD modules to CommonJS modules or something?

Body:
You can load AMD modules inside node with requirejs :_)

Read here: http://requirejs.org/docs/node.html

You have to import require and do a little config, something like this:

'use strict';

const test = require('tape');
const requirejs = require('requirejs');

requirejs.config({
    baseUrl: __dirname,
    nodeRequire: require
});

test('Test something', function (assert) {
    requirejs(['app/util/stringUtil'], function   (stringUtil) {

        assert.ok(stringUtil.isBlank('   '), 'Should be blank');

        assert.end();
    });
});

ContentLicense: CC BY-SA 4.0


问:
PostgreSQL RETURNING fails with REGEXP_REPLACE
I'm running PostgreSQL 9.4 and are inserting a lot of records into my database. I use the RETURNING clause for further use after an insert.

When I simply run:

```<code>... RETURNING my_car, brand, color, contact
</code>```

everything works, but if I try to use REGEXP_REPLACE it fails:

```<code>... RETURNing my_car, brand, color, REGEXP_REPLACE(contact, '^(\+?|00)', '') AS contact
</code>```

it fails with:

```<code>ERROR: invalid regular expression: quantifier operand invalid
</code>```

If I simply run the query directly in PostgreSQL it does work and return a nice output.

答:
The current value of environment variable standard_conforming_strings is inconsequential here. You can see it if you prefix your query with SET standard_conforming_strings = true;, which will change nothing.

Passing in a regEx string unescaped from the client is the same as using E prefix from the command line: E'^(\+?|00)'.

In JavaScript \ is treated as a special symbol, and you simply always have to provide \\ to indicate the symbol, which is what needed for your regular expressions.

Other than that, pg-promise will escape everything correctly, here's an example:

```<code>db.any("INSERT INTO users(name) VALUES('hello') RETURNING REGEXP_REPLACE(name, $1, $2)", ['^(\\+?|00)', 'replaced'])
</code>```

To understand how the command-line works, prefix the regex string with E:

```<code>db.any("INSERT INTO users(name) VALUES('hello') RETURNING REGEXP_REPLACE(name, E$1, $2)", ['^(\\+?|00)', 'replaced'])
</code>```

And you will get the same error: invalid regular expression: quantifier operand invalid.

Body:
I'm running PostgreSQL 9.4 and are inserting a lot of records into my database. I use the RETURNING clause for further use after an insert.

When I simply run:

... RETURNING my_car, brand, color, contact

everything works, but if I try to use REGEXP_REPLACE it fails:

... RETURNing my_car, brand, color, REGEXP_REPLACE(contact, '^(\+?|00)', '') AS contact

it fails with:

ERROR: invalid regular expression: quantifier operand invalid

If I simply run the query directly in PostgreSQL it does work and return a nice output.

Body:
The current value of environment variable standard_conforming_strings is inconsequential here. You can see it if you prefix your query with SET standard_conforming_strings = true;, which will change nothing.

Passing in a regEx string unescaped from the client is the same as using E prefix from the command line: E'^(\+?|00)'.

In JavaScript \ is treated as a special symbol, and you simply always have to provide \\ to indicate the symbol, which is what needed for your regular expressions.

Other than that, pg-promise will escape everything correctly, here's an example:

db.any("INSERT INTO users(name) VALUES('hello') RETURNING REGEXP_REPLACE(name, $1, $2)", ['^(\\+?|00)', 'replaced'])

To understand how the command-line works, prefix the regex string with E:

db.any("INSERT INTO users(name) VALUES('hello') RETURNING REGEXP_REPLACE(name, E$1, $2)", ['^(\\+?|00)', 'replaced'])

And you will get the same error: invalid regular expression: quantifier operand invalid.


问:
Is there a way to trigger the browsers default "scroll to cursor" behaviour when when typing in a textfield?
I want to trigger the browsers default behaviour of jumping to the cursor when someone starts to write and the cursor is of screen.

At the moment, if I resize the cursor is off screen and I want to center the scrollbar on the cursor again after the resize.

When I resize and type the scrollbar automatically jumps to the right position. Is there a way to trigger that "jump to cursor" behaviour with vanilla javascript or jQuery?

答:
Hm try something like this:</p>

```<code>$('.element').keydown(function (event) {
    event.preventDefault();
    $(this).focus();
});
</code>```

Body:
Hm try something like this:

$('.element').keydown(function (event) {
    event.preventDefault();
    $(this).focus();
});


问:
Downloaded OCaml, get error "Bad CPU type in executable"
So I'm running Mac OS X Yosemite 10.10.5. I need to use OCaml 3.08.3 to run someone else's code (the code won't run with the latest version of OCaml...), and I downloaded the .dmg file here. The installation seemed to be fine, but whenever I run the command 'ocaml' in Terminal, I get

```<code>-bash: /usr/local/bin/ocaml: /usr/local/bin/ocamlrun: bad interpreter: Bad CPU type in executable
</code>```

Anyone know what's up? Would greatly appreciate any help.

答:
The version that you downloaded works only for Mac OS X 10.3 (Panther). It might work for some other versions, but it is not guaranteed. In MacOS, binaries compiled for one version, are often not compatible with other versions.

If you need a version of OCaml for which there is no binary distribution, you can always build it yourself, either manually (the hard way), or via the OPAM system.

Alternative solutions would be using Docker or a virtual machine.

Update

Also, the code that you're trying to compile doesn't really need exactly 3.08. It compiles perfectly fine on any version of a compiler, up to 4.04. The problem is that in a build system a fatal warning flag is turned on so that all warnings are translated to errors (a very bad practice of distributing software, I would like to say). The good news is that it can be easily fixed, just open Makefile in a text editor, and remove all occurrences of the following string -warn-error A.

Body:
So I'm running Mac OS X Yosemite 10.10.5. I need to use OCaml 3.08.3 to run someone else's code (the code won't run with the latest version of OCaml...), and I downloaded the .dmg file here. The installation seemed to be fine, but whenever I run the command 'ocaml' in Terminal, I get

-bash: /usr/local/bin/ocaml: /usr/local/bin/ocamlrun: bad interpreter: Bad CPU type in executable

Anyone know what's up? Would greatly appreciate any help.


问:
Could not execute build using Gradle distribution 'http://services.gradle.org/distributions/gradle-1.10-all.zip'
I am using Android studio 0.4.6.
Whenever I build it says Could not execute build using Gradle distribution 'http://services.gradle.org/distributions/gradle-1.10-all.zip'.

I am new for gradle.

This is my build.gradle

```<code>buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.8.+'
    }
}

allprojects {
    repositories {
        mavenCentral()
    }
}
</code>```

I have only one module and module's build.gradle is as follows

```<code>apply plugin: 'android'

    android {
        compileSdkVersion 19
        buildToolsVersion "19.0.1"

        defaultConfig {
            minSdkVersion 8
            targetSdkVersion 19
            versionCode 1
            versionName "1.0"
        }
        buildTypes {
            release {
                runProguard false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
            }
        }
    }

    dependencies {
        compile 'com.android.support:support-v4:19.0.1'
        compile 'com.android.support:appcompat-v7:19.0.1'
        compile fileTree(dir: 'libs', include: ['*.jar'])
    }
</code>```

What could be the issue?

答: Go through the complete stack trace of the error. In my case, the first line of the error was same as this. But the problem was, another Gradle build from the terminal was holding the lock, that prevented the eclipse to import/build.</p>

Body:
I am using Android studio 0.4.6.
Whenever I build it says Could not execute build using Gradle distribution 'http://services.gradle.org/distributions/gradle-1.10-all.zip'.

I am new for gradle.

This is my build.gradle

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.8.+'
    }
}

allprojects {
    repositories {
        mavenCentral()
    }
}

I have only one module and module's build.gradle is as follows

apply plugin: 'android'

    android {
        compileSdkVersion 19
        buildToolsVersion "19.0.1"

        defaultConfig {
            minSdkVersion 8
            targetSdkVersion 19
            versionCode 1
            versionName "1.0"
        }
        buildTypes {
            release {
                runProguard false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
            }
        }
    }

    dependencies {
        compile 'com.android.support:support-v4:19.0.1'
        compile 'com.android.support:appcompat-v7:19.0.1'
        compile fileTree(dir: 'libs', include: ['*.jar'])
    }

What could be the issue?


问:
i have a problem with exception "java.lang.ArrayIndexOutOfBoundsException"
i have a problem with exception "java.lang.ArrayIndexOutOfBoundsException"
i wrote a program which have src array of 48 length then processes it to take each 6 indexes to another array using method arrayCopy and print each dst array
for me it works fine it prints each 6 indexes from the initial array but at the end i get an exception help please . the algorithm is just a test because i want to use the arrayCopy in another algorithm so i don't need suggestion to change the algorithm . i hope it is clear fair enough </p>

```<code>  public static void main(String [] arg)
        {
            int[] src = new int[48];
            for(int j=0;j<src.length;j++)
            {
                src[j]=j+1;
                System.out.print(src[j]+" ");
            }
            System.out.println();
            int[] dst = new int[6];
            int from=0;
            for(int i=0;i<src.length;i++)
            {
                System.arraycopy(src, from, dst, 0, 6); // Copies 6 indexes from src starting at from into dst
                from=from+6;
                print(dst);
                System.out.println();
            }

            }

        public static void print(int [] dst)
        {
            for(int i=0;i<dst.length;i++)
                System.out.print(dst[i]+" ");
        }
</code>```

答:
Try this:

```<code>for(int i=0;i<src.length;i+=6)  // increment i by value 6
</code>```

Or use from in the for expression:

```<code>for(int from=0; from<src.length; from+=6) {
    System.arraycopy(src, from, dst, 0, 6);
    print(dst);
    System.out.println();
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
i have a problem with exception "java.lang.ArrayIndexOutOfBoundsException"
i wrote a program which have src array of 48 length then processes it to take each 6 indexes to another array using method arrayCopy and print each dst array
for me it works fine it prints each 6 indexes from the initial array but at the end i get an exception help please . the algorithm is just a test because i want to use the arrayCopy in another algorithm so i don't need suggestion to change the algorithm . i hope it is clear fair enough

  public static void main(String [] arg)
        {
            int[] src = new int[48];
            for(int j=0;j<src.length;j++)
            {
                src[j]=j+1;
                System.out.print(src[j]+" ");
            }
            System.out.println();
            int[] dst = new int[6];
            int from=0;
            for(int i=0;i<src.length;i++)
            {
                System.arraycopy(src, from, dst, 0, 6); // Copies 6 indexes from src starting at from into dst
                from=from+6;
                print(dst);
                System.out.println();
            }

            }

        public static void print(int [] dst)
        {
            for(int i=0;i<dst.length;i++)
                System.out.print(dst[i]+" ");
        }

Body:
Try this:

for(int i=0;i<src.length;i+=6)  // increment i by value 6

Or use from in the for expression:

for(int from=0; from<src.length; from+=6) {
    System.arraycopy(src, from, dst, 0, 6);
    print(dst);
    System.out.println();
}


问:
What's the difference between "p" and "po" in Xcode's LLDB debugger?
Example: I write the following string in my old project and a new, clear one:

```<code>UIInterfaceOrientation k = [UIApplication sharedApplication].statusBarOrientation;
</code>```

Console input/output for a clear project:

```<code>(lldb) po k
UIInterfaceOrientationLandscapeLeft
</code>```

And something awful in my old project if I write "po k" - a list of useless integers.

Additionally, I can't print most of the objects in the new project.

答:
p = print

po = print object

p prints value of primitive variable or value of a reference

po try to call -description for that object and print returned string

Body:
Example: I write the following string in my old project and a new, clear one:

UIInterfaceOrientation k = [UIApplication sharedApplication].statusBarOrientation;

Console input/output for a clear project:

(lldb) po k
UIInterfaceOrientationLandscapeLeft

And something awful in my old project if I write "po k" - a list of useless integers.

Additionally, I can't print most of the objects in the new project.


问:
Is it possible to add dynamically named properties to JavaScript object?
In JavaScript, I've created an object like so:

```<code>var data = {
    'PropertyA': 1,
    'PropertyB': 2,
    'PropertyC': 3
};
</code>```

Is it possible to add further properties to this object after its initial creation if the properties name is not determined until run time? i.e.

```<code>var propName = 'Property' + someUserInput
//imagine someUserInput was 'Z', how can I now add a 'PropertyZ' property to
//my object?
</code>```

答:
A nice way to access from dynamic string names that contain objects (for example object.subobject.property)

```<code>function ReadValue(varname)
{
    var v=varname.split(".");
    var o=window;
    if(!v.length)
        return undefined;
    for(var i=0;i<v.length-1;i++)
        o=o[v[i]];
    return o[v[v.length-1]];
}

function AssignValue(varname,value)
{
    var v=varname.split(".");
    var o=window;
    if(!v.length)
        return;
    for(var i=0;i<v.length-1;i++)
        o=o[v[i]];
    o[v[v.length-1]]=value;
}
</code>```

Example:

```<code>ReadValue("object.subobject.property");
WriteValue("object.subobject.property",5);
</code>```

eval works for read value, but write value is a bit harder.

A more advanced version (Create subclasses if they dont exists, and allows objects instead of global variables)

```<code>function ReadValue(varname,o=window)
{
    if(typeof(varname)==="undefined" || typeof(o)==="undefined" || o===null)
        return undefined;
    var v=varname.split(".");
    if(!v.length)
        return undefined;
    for(var i=0;i<v.length-1;i++)
    {
        if(o[v[i]]===null || typeof(o[v[i]])==="undefined")
            o[v[i]]={};
        o=o[v[i]];
    }
    if(typeof(o[v[v.length-1]])==="undefined")
        return undefined;
    else
        return o[v[v.length-1]];
}

function AssignValue(varname,value,o=window)
{
    if(typeof(varname)==="undefined" || typeof(o)==="undefined" || o===null)
        return;
    var v=varname.split(".");
    if(!v.length)
        return;
    for(var i=0;i<v.length-1;i++)
    {
        if(o[v[i]]===null || typeof(o[v[i]])==="undefined")
            o[v[i]]={};
        o=o[v[i]];
    }
    o[v[v.length-1]]=value;
}
</code>```

Example:

```<code>ReadValue("object.subobject.property",o);
WriteValue("object.subobject.property",5,o);
</code>```

This is the same that o.object.subobject.property

Body:
In JavaScript, I've created an object like so:

var data = {
    'PropertyA': 1,
    'PropertyB': 2,
    'PropertyC': 3
};

Is it possible to add further properties to this object after its initial creation if the properties name is not determined until run time? i.e.

var propName = 'Property' + someUserInput
//imagine someUserInput was 'Z', how can I now add a 'PropertyZ' property to
//my object?

Body:
A nice way to access from dynamic string names that contain objects (for example object.subobject.property)

function ReadValue(varname)
{
    var v=varname.split(".");
    var o=window;
    if(!v.length)
        return undefined;
    for(var i=0;i<v.length-1;i++)
        o=o[v[i]];
    return o[v[v.length-1]];
}

function AssignValue(varname,value)
{
    var v=varname.split(".");
    var o=window;
    if(!v.length)
        return;
    for(var i=0;i<v.length-1;i++)
        o=o[v[i]];
    o[v[v.length-1]]=value;
}

Example:

ReadValue("object.subobject.property");
WriteValue("object.subobject.property",5);

eval works for read value, but write value is a bit harder.

A more advanced version (Create subclasses if they dont exists, and allows objects instead of global variables)

function ReadValue(varname,o=window)
{
    if(typeof(varname)==="undefined" || typeof(o)==="undefined" || o===null)
        return undefined;
    var v=varname.split(".");
    if(!v.length)
        return undefined;
    for(var i=0;i<v.length-1;i++)
    {
        if(o[v[i]]===null || typeof(o[v[i]])==="undefined")
            o[v[i]]={};
        o=o[v[i]];
    }
    if(typeof(o[v[v.length-1]])==="undefined")
        return undefined;
    else
        return o[v[v.length-1]];
}

function AssignValue(varname,value,o=window)
{
    if(typeof(varname)==="undefined" || typeof(o)==="undefined" || o===null)
        return;
    var v=varname.split(".");
    if(!v.length)
        return;
    for(var i=0;i<v.length-1;i++)
    {
        if(o[v[i]]===null || typeof(o[v[i]])==="undefined")
            o[v[i]]={};
        o=o[v[i]];
    }
    o[v[v.length-1]]=value;
}

Example:

ReadValue("object.subobject.property",o);
WriteValue("object.subobject.property",5,o);

This is the same that o.object.subobject.property


问:
display row from database table and post it to another table . select row return 1 and not selected row return 0 into present status column
I want functionality as in the below image:

I want to display data from database table within a html table including checkbox beside every row and store those data into another table. Checked data and unchecked both will be stored but checked data return 1 and unchecked data return 0 in is_selected column. I am using SQL Server 2014 and my project ASP.NET_MVC(5) Visual Studio 2017.

View

```<code>@using AttendenceSystem.Models;
@model IEnumerable<CsteY4_T2_Students>

@{
    ViewBag.Title = "Multimedia Communication Students";
}

<div style="font-family:Arial">

    <h2>Multimedia Communication Students</h2>
    <form>

        <table border="1" id="tblList">
            <tr>
                <th>Student Id</th>
                <th>Student Name</th>
                <th>Present Status</th>
            </tr>

            @foreach (CsteY4_T2_Students cstey4t2studens in @Model)
            {
                <tr>
                    <td class="num">@cstey4t2studens.StudentId</td>
                    <td class="num">@cstey4t2studens.StudentName</td>
                    <td>
                        <input name="chkStudent" value="@cstey4t2studens.StudentId" type="checkbox" />
                    </td>
                </tr>

            }

        </table>
        <input type="submit"  id="btnSave" class="addValue" value="Save" />
    </form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

    <script type="text/javascript">

        $('.addValue').click(tallyValues);

    function tallyValues() {

            $('#btnSave').on('click', function () {
                var list = [];
                $('input[name="chkStudent"]').each(function () {
                    console.log($(this).val());
                    if ($(this).is(':checked')) {
                        list.push({ 'StudentId': $(this).val(), 'PresentValid': true })
                    }
                    else {
                        list.push({ 'StudentId': $(this).val(), 'PresentValid': false })
                    }
                });
                $.ajax({
                    type: "POST",
                    url: "../CsteY4T2Students/SaveStudent",
                    data: { list: list },
                    cache: false,
                    success: function (data) {
                        console.log('saved');
                    },
                    error: function (error) {
                        console.log('error');
                    },
                    complete: function () {

                    }
                });
            });
    };
</script>
</code>```

controller code:

```<code>        public class CsteY4T2StudentsController : Controller
        {
            // GET: CsteY4T2Students
            public ActionResult Cstey4t2students(string SubjectCode)
            {
                DataRetrive dataretrive = new DataRetrive();
                List<CsteY4_T2_Students> cstey4t2students=dataretrive.Cstey4t2studens.Where(sc => sc.SubjectCode == SubjectCode).ToList();
                return View(cstey4t2students);

            }
            public JsonResult SaveStudent(List<Student> list)
            {
                return Json(1, JsonRequestBehavior.AllowGet);
            }
        }
</code>```

Model Class:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace AttendenceSystem.Models
{
    [Table("tbleMultimediaCommunication")]
    public class Student
    {
        [Key]

        public int StudentId { get; set; }
        public bool PresentValid { get; set; }
    }
}
</code>```

答:
Based on what I understand here is a sample, haven't tested but should take you in right direction:

Your View - Added table ID, take a look at check box

```<code><table border="1" id="tblList">
    <tr>
    <th>Student Id</th>
    <th>Student Name</th>
    <th>Present Status</th>
    </tr>
    @foreach (CsteY4_T2_Students cstey4t2studens in @Model)
    {
    <tr>
    <td>@cstey4t2studens.StudentId</td>
    <td>@cstey4t2studens.StudentName</td>
    <td>
        <input name="chkStudent" value="@cstey4t2studens.StudentId" type="checkbox" />
    </td>
    </tr>
    }
</table>
<button type="button" id="btnSave">Save</button>
</code>```

Script in View

```<code>$(function () {

    $('#btnSave').on('click', function () {
        var list = [];
        $('input[name="chkStudent"]').each(function () {
            console.log($(this).val());
            if ($(this).is(':checked')) {
                list.push({ 'StudentId': $(this).val(), 'PresentValid': true })
            }
            else {
                list.push({ 'StudentId': $(this).val(), 'PresentValid': false })
            }
        });
        $.ajax({
            type: "POST",
            url: "../CsteY4T2Students/SaveStudent",
            data: { list: list },
            cache: false,
            success: function (data) {
                console.log('saved');
            },
            error: function (error) {
                console.log('error');
            },
            complete: function () {

            }
        });
    });
});
</code>```

In Controller

```<code> public JsonResult SaveStudent(List<Student> list)
    {
        return Json(1, JsonRequestBehavior.AllowGet);
    }
</code>```

Assuming you have StudentClass as below:

```<code>class Student
{
   public int StudentId {get;set;}
   public bool PresentValid {get;set}
}
</code>```

Body:
I want functionality as in the below image:

I want to display data from database table within a html table including checkbox beside every row and store those data into another table. Checked data and unchecked both will be stored but checked data return 1 and unchecked data return 0 in is_selected column. I am using SQL Server 2014 and my project ASP.NET_MVC(5) Visual Studio 2017.

View

@using AttendenceSystem.Models;
@model IEnumerable<CsteY4_T2_Students>

@{
    ViewBag.Title = "Multimedia Communication Students";
}

Multimedia Communication Students

    <form>

                Student Id
                Student Name
                Present Status

            @foreach (CsteY4_T2_Students cstey4t2studens in @Model)
            {

                    @cstey4t2studens.StudentId
                    @cstey4t2studens.StudentName

                        <input name="chkStudent" value="@cstey4t2studens.StudentId" type="checkbox" />

            }

        <input type="submit"  id="btnSave" class="addValue" value="Save" />
    </form>

controller code:

        public class CsteY4T2StudentsController : Controller
        {
            // GET: CsteY4T2Students
            public ActionResult Cstey4t2students(string SubjectCode)
            {
                DataRetrive dataretrive = new DataRetrive();
                List<CsteY4_T2_Students> cstey4t2students=dataretrive.Cstey4t2studens.Where(sc => sc.SubjectCode == SubjectCode).ToList();
                return View(cstey4t2students);

            }
            public JsonResult SaveStudent(List<Student> list)
            {
                return Json(1, JsonRequestBehavior.AllowGet);
            }
        }

Model Class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace AttendenceSystem.Models
{
    [Table("tbleMultimediaCommunication")]
    public class Student
    {
        [Key]

        public int StudentId { get; set; }
        public bool PresentValid { get; set; }
    }
}

Body:
Based on what I understand here is a sample, haven't tested but should take you in right direction:

Your View - Added table ID, take a look at check box

<table border="1" id="tblList">
    <tr>
    <th>Student Id</th>
    <th>Student Name</th>
    <th>Present Status</th>
    </tr>
    @foreach (CsteY4_T2_Students cstey4t2studens in @Model)
    {
    <tr>
    <td>@cstey4t2studens.StudentId</td>
    <td>@cstey4t2studens.StudentName</td>
    <td>
        <input name="chkStudent" value="@cstey4t2studens.StudentId" type="checkbox" />
    </td>
    </tr>
    }
</table>
<button type="button" id="btnSave">Save</button>

Script in View

$(function () {

    $('#btnSave').on('click', function () {
        var list = [];
        $('input[name="chkStudent"]').each(function () {
            console.log($(this).val());
            if ($(this).is(':checked')) {
                list.push({ 'StudentId': $(this).val(), 'PresentValid': true })
            }
            else {
                list.push({ 'StudentId': $(this).val(), 'PresentValid': false })
            }
        });
        $.ajax({
            type: "POST",
            url: "../CsteY4T2Students/SaveStudent",
            data: { list: list },
            cache: false,
            success: function (data) {
                console.log('saved');
            },
            error: function (error) {
                console.log('error');
            },
            complete: function () {

            }
        });
    });
});

In Controller

 public JsonResult SaveStudent(List<Student> list)
    {
        return Json(1, JsonRequestBehavior.AllowGet);
    }

Assuming you have StudentClass as below:

class Student
{
   public int StudentId {get;set;}
   public bool PresentValid {get;set}
}


问:
STS unable to resolve target type with java 8
I have the below code that errors out in STS(3.8.4) saying,

Type mismatch: cannot convert from Map<String,Object> to Map<? extends
  K,? extends V>

```<code>this.attributeMappings = new HashMap<>(attributeMappings!=null?attributeMappings:Collections.EMPTY_MAP);
</code>```

Where both the instances of attributeMappings are of type Map<String, Object>.

Ideally, this shouldn't be a problem with Java 8. Could someone help me to resolve it without making any changes to the source?

PS: The same happens with Eclipse Neon 3

答:
You should upgrade, this is an eclipse compiler issue (I've tried searching for it, but no luck) to Eclipse Oxygen let's say.

```<code>Map<String, Object> attributeMappings;

@SuppressWarnings("unchecked")
public void test(Map<String, Object> attributeMappings) {
    this.attributeMappings = new HashMap<>(attributeMappings != null
                 ? attributeMappings : Collections.EMPTY_MAP);
}
</code>```

This compiles just fine for me with javac-8 and in eclipse oxygen latest.

Also notice that you can replace Collections.EMPTY_MAP with Collections.emptyMap() and it will work also.

Body:
I have the below code that errors out in STS(3.8.4) saying,

Type mismatch: cannot convert from Map<String,Object> to Map<? extends
  K,? extends V>

this.attributeMappings = new HashMap<>(attributeMappings!=null?attributeMappings:Collections.EMPTY_MAP);

Where both the instances of attributeMappings are of type Map<String, Object>.

Ideally, this shouldn't be a problem with Java 8. Could someone help me to resolve it without making any changes to the source?

PS: The same happens with Eclipse Neon 3

Body:
You should upgrade, this is an eclipse compiler issue (I've tried searching for it, but no luck) to Eclipse Oxygen let's say.

Map<String, Object> attributeMappings;

@SuppressWarnings("unchecked")
public void test(Map<String, Object> attributeMappings) {
    this.attributeMappings = new HashMap<>(attributeMappings != null
                 ? attributeMappings : Collections.EMPTY_MAP);
}

This compiles just fine for me with javac-8 and in eclipse oxygen latest.

Also notice that you can replace Collections.EMPTY_MAP with Collections.emptyMap() and it will work also.


问:
Python create all possible combinations from a integer
I have integer for example "123", using this i want to create all possible combinations listed below.
123
12,3
1,23 and so on irrespective of the digits i have entered.
Is there any way possible using python for the same? I am not able to get any idea.</p>

答:
This would work:

```<code>import itertools

stuff = list('123')
for L in range(0, len(stuff)+1):
  for subset in itertools.combinations(stuff, L):
    print(subset)
</code>```

Output:

```<code>()
(1,)
(2,)
(3,)
(1, 2)
(1, 3)
(2, 3)
(1, 2, 3)
</code>```

Body:
This would work:

import itertools

stuff = list('123')
for L in range(0, len(stuff)+1):
  for subset in itertools.combinations(stuff, L):
    print(subset)

Output:

()
(1,)
(2,)
(3,)
(1, 2)
(1, 3)
(2, 3)
(1, 2, 3)


问:
PHP imagecopymerge() - one image is stretched
I'm am trying to add a 50px white margin down the right side of an image by creating an empty image that's 50px wider than the source image and then merging the source image onto it. The problem is that the source image just gets stretched sideways so it's 50px wider!
Maybe I'm using the wrong function to merge the images ...
here's my code

```<code>    $destImage = $filepath;
#echo "dest image = ".$destImage;
$sourceImage = imagecreatefrompng($filepath);
// dimensions
$src_wide = imagesx($sourceImage);
echo "src_wide=".$src_wide;
$src_high = imagesy($sourceImage);
// new image dimensions with right padding
$dst_wide = $src_wide+50;
echo "dst_wide=".$dst_wide;
$dst_high = $src_high;
// New resource image at new size
$dst = imagecreatetruecolor($dst_wide, $dst_high);
// set white padding color
$clear = array('red'=>255,'green'=>255,'blue'=>255);
// fill the image with the white padding color
$clear = imagecolorallocate( $dst, $clear["red"], $clear["green"], $clear["blue"]);
imagefill($dst, 0, 0, $clear);
// copy the original image on top of the new one
imagecopymerge($dst,$sourceImage,0,0,0,0,$src_wide,$src_high, 100);
imagepng($dst,$destImage,6);
imagedestroy($dst);
chmod($destImage,0775);
</code>```

what am I doing wrong here ??
thanks

答:
It's stretching because you are copying it to the full width of the destination image. Instead use</p>

```<code>imagecopyresampled($dst,$sourceImage,50,0,0,0,$src_wide,$src_high,$src_wide,$src_high);
</code>```

Body:
I'm am trying to add a 50px white margin down the right side of an image by creating an empty image that's 50px wider than the source image and then merging the source image onto it. The problem is that the source image just gets stretched sideways so it's 50px wider!
Maybe I'm using the wrong function to merge the images ...
here's my code

    $destImage = $filepath;
#echo "dest image = ".$destImage;
$sourceImage = imagecreatefrompng($filepath);
// dimensions
$src_wide = imagesx($sourceImage);
echo "src_wide=".$src_wide;
$src_high = imagesy($sourceImage);
// new image dimensions with right padding
$dst_wide = $src_wide+50;
echo "dst_wide=".$dst_wide;
$dst_high = $src_high;
// New resource image at new size
$dst = imagecreatetruecolor($dst_wide, $dst_high);
// set white padding color
$clear = array('red'=>255,'green'=>255,'blue'=>255);
// fill the image with the white padding color
$clear = imagecolorallocate( $dst, $clear["red"], $clear["green"], $clear["blue"]);
imagefill($dst, 0, 0, $clear);
// copy the original image on top of the new one
imagecopymerge($dst,$sourceImage,0,0,0,0,$src_wide,$src_high, 100);
imagepng($dst,$destImage,6);
imagedestroy($dst);
chmod($destImage,0775);

what am I doing wrong here ??
thanks

Body:
It's stretching because you are copying it to the full width of the destination image. Instead use

imagecopyresampled($dst,$sourceImage,50,0,0,0,$src_wide,$src_high,$src_wide,$src_high);


问:
XMPPError: bad-request - modify error create new user using smack library 4.1.8 and openfire
i have been developing a chat application using smack client library 4.1.8 and xmpp server(openfire server) but while trying to create new user using Accountmanger class it raises and exception "XMPPError: bad-request - modify"

```<code>XMPPTCPConnectionConfiguration conf = XMPPTCPConnectionConfiguration.builder()
                        .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
                        .setHost("127.0.0.1")
                        .setDebuggerEnabled(true)
                        .setPort(5222)
                        .setSendPresence(true)
                        .setServiceName("127.0.0.1")
                        .build();

                AbstractXMPPConnection conn2 = new XMPPTCPConnection(conf);

                //conn2.login();
                conn2.connect();

                AccountManager accountManager = AccountManager.getInstance(conn2);
                if (accountManager.supportsAccountCreation()) {
                    accountManager.sensitiveOperationOverInsecureConnection(true);
                    accountManager.createAccount("qidus", "123456");
                    conn2.login("qidus", "123456");

                }

            } catch (SmackException | IOException | XMPPException e) {
                e.printStackTrace();
            }
</code>```

and the exception is this

```<code>04:01:41 AM SENT (0): <iq to='127.0.0.1' id='aYej1-3' type='get'><query xmlns='jabber:iq:register'></query></iq>
</code>```

04:01:41 AM RECV (0):

```<code>org.jivesoftware.smack.XMPPException$XMPPErrorException: XMPPError: bad-request - modify
at org.jivesoftware.smack.XMPPException$XMPPErrorException.ifHasErrorThenThrow(XMPPException.java:135)
at org.jivesoftware.smack.PacketCollector.nextResultOrThrow(PacketCollector.java:232)
at org.jivesoftware.smack.PacketCollector.nextResultOrThrow(PacketCollector.java:213)
at org.jivesoftware.smackx.iqregister.AccountManager.getRegistrationInfo(AccountManager.java:332)
at org.jivesoftware.smackx.iqregister.AccountManager.supportsAccountCreation(AccountManager.java:144)
at chat.Chat$1.run(Chat.java:46)
</code>```

答: You also get this error or exception when the username which you are passing for account creation has the null value.So check your username also.</p>

Body:
i have been developing a chat application using smack client library 4.1.8 and xmpp server(openfire server) but while trying to create new user using Accountmanger class it raises and exception "XMPPError: bad-request - modify"

XMPPTCPConnectionConfiguration conf = XMPPTCPConnectionConfiguration.builder()
                        .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
                        .setHost("127.0.0.1")
                        .setDebuggerEnabled(true)
                        .setPort(5222)
                        .setSendPresence(true)
                        .setServiceName("127.0.0.1")
                        .build();

                AbstractXMPPConnection conn2 = new XMPPTCPConnection(conf);

                //conn2.login();
                conn2.connect();

                AccountManager accountManager = AccountManager.getInstance(conn2);
                if (accountManager.supportsAccountCreation()) {
                    accountManager.sensitiveOperationOverInsecureConnection(true);
                    accountManager.createAccount("qidus", "123456");
                    conn2.login("qidus", "123456");

                }

            } catch (SmackException | IOException | XMPPException e) {
                e.printStackTrace();
            }

and the exception is this

04:01:41 AM SENT (0): <iq to='127.0.0.1' id='aYej1-3' type='get'><query xmlns='jabber:iq:register'></query></iq>

04:01:41 AM RECV (0):

org.jivesoftware.smack.XMPPException$XMPPErrorException: XMPPError: bad-request - modify
at org.jivesoftware.smack.XMPPException$XMPPErrorException.ifHasErrorThenThrow(XMPPException.java:135)
at org.jivesoftware.smack.PacketCollector.nextResultOrThrow(PacketCollector.java:232)
at org.jivesoftware.smack.PacketCollector.nextResultOrThrow(PacketCollector.java:213)
at org.jivesoftware.smackx.iqregister.AccountManager.getRegistrationInfo(AccountManager.java:332)
at org.jivesoftware.smackx.iqregister.AccountManager.supportsAccountCreation(AccountManager.java:144)
at chat.Chat$1.run(Chat.java:46)


问:
Getting expression text
I want to pass the name of a property of a model to a method. Instead of using the name as string, I am using lambda expression as it is easy to make a typo, and also property names may be changed. Now if the property is a simple property (e.g: model.Name) I can get the name from the expression. But if it is a nested property (e.g: model.AnotherModel.Name) then how can I get full text ("AnotherModel.Name") from the expression. For example, I have the following classes:</p>

```<code>public class BaseModel
{
    public ChildModel Child { get; set; }
    public List<ChildModel> ChildList { get; set; }

    public BaseModel()
    {
        Child = new ChildModel();
        ChildList = new List<ChildModel>();
    }
}

public class ChildModel
{
    public string Name { get;set; }
}

public void GetExpressionText<T>(Expression<Func<T, object>> expression)
{
    string expText;
    //what to do??
    return expText;
}

GetExpressionText<BaseModel>(b => b.Child); //should return "Child"
GetExpressionText<BaseModel>(b => b.Child.Name); //should return "Child.Name"
GetExpressionText<BaseModel>(b => b.ChildList[0].Name); //should return "ChildList[0].Name"
</code>```

答:
This Should get you most of the way there:</p>

```<code>    public static string GetFullPath<T>(Expression<Func<T>> action)
    {
        var removeBodyPath = new Regex(@"value\((.*)\).");
        var result = action.Body.ToString();
        var replaced = removeBodyPath.Replace(result, String.Empty);
        var seperatedFiltered = replaced.Split('.').Skip(1).ToArray();
        return string.Join(".", seperatedFiltered);
    }
</code>```

Title: Getting expression text

Body:
I want to pass the name of a property of a model to a method. Instead of using the name as string, I am using lambda expression as it is easy to make a typo, and also property names may be changed. Now if the property is a simple property (e.g: model.Name) I can get the name from the expression. But if it is a nested property (e.g: model.AnotherModel.Name) then how can I get full text ("AnotherModel.Name") from the expression. For example, I have the following classes:

public class BaseModel
{
    public ChildModel Child { get; set; }
    public List<ChildModel> ChildList { get; set; }

    public BaseModel()
    {
        Child = new ChildModel();
        ChildList = new List<ChildModel>();
    }
}

public class ChildModel
{
    public string Name { get;set; }
}

public void GetExpressionText<T>(Expression<Func<T, object>> expression)
{
    string expText;
    //what to do??
    return expText;
}

GetExpressionText<BaseModel>(b => b.Child); //should return "Child"
GetExpressionText<BaseModel>(b => b.Child.Name); //should return "Child.Name"
GetExpressionText<BaseModel>(b => b.ChildList[0].Name); //should return "ChildList[0].Name"

Body:
This Should get you most of the way there:

    public static string GetFullPath<T>(Expression<Func<T>> action)
    {
        var removeBodyPath = new Regex(@"value\((.*)\).");
        var result = action.Body.ToString();
        var replaced = removeBodyPath.Replace(result, String.Empty);
        var seperatedFiltered = replaced.Split('.').Skip(1).ToArray();
        return string.Join(".", seperatedFiltered);
    }


问:
How can I change UITextField leftview frame
How can I change the position of the leftView in a UITextField?

I have tried this, but the leftView position does not change

```<code>UIView *view = [[UIView alloc]init];
[view setFrame:CGRectMake(10, 10, 15, 15)];
[view setBackgroundColor:[UIColor blackColor]];
[self.urlBar setLeftView:view];
[self.urlBar setLeftViewMode:UITextFieldViewModeAlways];
</code>```

答:
The following code will give you a padding (displacement) of 20 from left. </p>

```<code>@IBDesignable
class LeftImageTextField: UITextField {

let displacement: CGFloat = 20

required override public init(frame: CGRect) {
    super.init(frame: frame)
    sharedSetup()
}

required public init?(coder: NSCoder) {
    super.init(coder: coder)
    sharedSetup()
}

func sharedSetup() {
    self.leftViewMode = .always
    self.leftView = UIImageView(image: UIImage(named: "myImage"))
}

override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
    var textRect = super.leftViewRect(forBounds: bounds)
    textRect.origin.x += displacement
    return textRect
}

// placeholder position
override func textRect(forBounds bounds: CGRect) -> CGRect
{
    var textRect = super.textRect(forBounds: bounds)
    textRect.origin.x -= displacement
    return textRect
}

// text position
override func editingRect(forBounds bounds: CGRect) -> CGRect
{
    var textRect = super.editingRect(forBounds: bounds)
    textRect.origin.x -= displacement
    return textRect
}

override func placeholderRect(forBounds bounds: CGRect) -> CGRect
{
    return bounds
}

/**
 Changes to this parameter draw the border of `self` in the given width.
 */
@IBInspectable
var leftImage: UIImage? {
    didSet {
        self.leftView = UIImageView(image: leftImage)
    }
}
}
</code>```

Body:
How can I change the position of the leftView in a UITextField?

I have tried this, but the leftView position does not change

UIView *view = [[UIView alloc]init];
[view setFrame:CGRectMake(10, 10, 15, 15)];
[view setBackgroundColor:[UIColor blackColor]];
[self.urlBar setLeftView:view];
[self.urlBar setLeftViewMode:UITextFieldViewModeAlways];

Body:
The following code will give you a padding (displacement) of 20 from left.

@IBDesignable
class LeftImageTextField: UITextField {

let displacement: CGFloat = 20

required override public init(frame: CGRect) {
    super.init(frame: frame)
    sharedSetup()
}

required public init?(coder: NSCoder) {
    super.init(coder: coder)
    sharedSetup()
}

func sharedSetup() {
    self.leftViewMode = .always
    self.leftView = UIImageView(image: UIImage(named: "myImage"))
}

override func leftViewRect(forBounds bounds: CGRect) -> CGRect {
    var textRect = super.leftViewRect(forBounds: bounds)
    textRect.origin.x += displacement
    return textRect
}

// placeholder position
override func textRect(forBounds bounds: CGRect) -> CGRect
{
    var textRect = super.textRect(forBounds: bounds)
    textRect.origin.x -= displacement
    return textRect
}

// text position
override func editingRect(forBounds bounds: CGRect) -> CGRect
{
    var textRect = super.editingRect(forBounds: bounds)
    textRect.origin.x -= displacement
    return textRect
}

override func placeholderRect(forBounds bounds: CGRect) -> CGRect
{
    return bounds
}

/**
 Changes to this parameter draw the border of `self` in the given width.
 */
@IBInspectable
var leftImage: UIImage? {
    didSet {
        self.leftView = UIImageView(image: leftImage)
    }
}
}


问:
How can a weak map be implemented in ES5?
There is another question that asks the same, but I cannot grok the accepted answer.

The library in question appears to use Object.defineProperty to add a reference to the object to be stored (albeit indirectly via another object).

But... surely that would then mean the object cannot be garbage collected because of this link?

What am I missing?

Is it really possible to create an object and store it somewhere without maintaining a reference noticeable by the garbage collector? (Prior to ES2015)

The accepted answer:

It took me a while to grok the code, but then it hit me: the key
  itself is used to store a reference to the value.

For example, several layers into set it does

defProp(obj, globalID, { value: store }); where defProp has been
  defined to be Object.defineProperty, obj is the key, globalID is a
  guid and store is a storage object that contains the value.

Then down in get it looks up the value with

obj[globalID];

This is very clever. The WeakMap doesn't actually contain a reference
  to anything (weak or otherwise)-- it just sets up a policy of where to
  secretly store the value. The use of Object.defineProperty means that
  you won't accidentally discover the value storage-- you have to know
  the magic guid to look it up.

Since the key directly refers to the value (and the WeakMap doesn't
  refer to it), when all references to the key are gone, it gets GCed
  like normal.

The library in question.

答:
The code in the library in question is convoluted. But based on another, clearer, WeakMap implementation I have the following...

A WeakMap holds a weak reference to both the key and the value associated with it. This means the WeakMap does not affect in any way the garbage collection of with the key object or the value object.

On way to achieve this in ES5 is to add a (hidden if you want) property to the key used when it is "added" to the map and then do nothing else (ie do not add the key to an array or indeed do anything with it). In that way nothing refers to the key other than itself.

AFAICT WeakMap has a limited API for this reason. You cannot, for example, enumerate the items in a WeakMap because it holds no references to its contents!

Note that the key in a WeakMap cannot be a primitive (string, number, undefined, null, Symbol, boolean).

When using has or get, you can simply look for the secret property on the object supplied as the key.

If it is present, the WeakMap "contains" or "has" it; otherwise it doesn't.

For get, the secret property could contain a reference to the value associated with the key object, again, with no reference from WeakMap to the key object or the value object.

I think.


问:
Improving UDP reliability
I am building a small UDP based server. the server is based on .Net and uses the Socket class it self. I'm using completion ports through ReceiveMessageFromAsync, and the async send.

My problem is I'm loosing around 5%-10% of my traffic. Now i understand this is normal, but is there any way of improving this statistic?

答:
You might want to look at the answers to this question before rolling your own reliability layer on top of UDP... What do you use when you need reliable UDP?

Alternatively you can try and increase the amount of data that gets through by making the socket's send and recv buffers as large as possible by setting the appropriate socket options before you start to recv.

Title: Improving UDP reliability


问:
How to return this result using linq in entity framework( 2 foreign key mapping table)
I have a table that contains 2 foreign key that reference separately to 2 different table.
I would like to return the result of all person that has course of "Science".

How to retrieve the record back using LINQ?
This is what i gotten so far:

```<code>       return
        _ctx.Person
            .Include(u => u.Course
            .Where(ug=>ug.CourseName== "Science"));
</code>```

This is not working as it shows the error.

The Include path expression must refer to a navigation property
  defined on the type

```<code>public class Course
{
    public int CourseID {get; set;}
    public string CourseName {get; set;}

    public virtual ICollection<Person> Persons { get; set; }
}

public class Person
{
   public int PersonID {get; set;}
   public virtual ICollection<Course> Courses { get; set; }
}
</code>```

This is the mapping table. Only contains 2 foreign key from 2 different table.
I could not use this table inside the solution.As the code first won't generate this table as it doesn't contain it's own PK.

```<code>//This is not shown in the EntityFramework when generating Code First.
    public class PersonCouseMap
    {
      public int PersonID {get; set;}
      public int CourseID {get; set;}
    }
</code>```

Update : this works after I switched the entity.

```<code>return _ctx.Course
       .Include(u=>u.Person)
       .Where(ug=>ug.CourseName == "Sciene");
</code>```

Anyone can explain why it won't work the another way round.
I need to display a List of Person who have course of "Science",
not Course Science that has a list of user.

答:
The original query does not work because you've pushed the Where predicate inside the Include expression, which is not supported as indicated by the exception message.

The Include method is EF specific extension method used to eager load related data. It has nothing to do with the query filtering.

To apply the desired filter person that has course of "Science" you need Any based predicate since the Person.Courses is a collection:

```<code>return _ctx.Person
    .Where(p => p.Courses.Any(c => c.CourseName == "Science"));
</code>```

To include the related data in the result, combine it with Include call(s):

```<code>return _ctx.Person
    .Include(p => p.Courses)
    .Where(p => p.Courses.Any(c => c.CourseName == "Science"));
</code>```

Body:
I have a table that contains 2 foreign key that reference separately to 2 different table.
I would like to return the result of all person that has course of "Science".

How to retrieve the record back using LINQ?
This is what i gotten so far:

       return
        _ctx.Person
            .Include(u => u.Course
            .Where(ug=>ug.CourseName== "Science"));

This is not working as it shows the error.

The Include path expression must refer to a navigation property
  defined on the type

public class Course
{
    public int CourseID {get; set;}
    public string CourseName {get; set;}

    public virtual ICollection<Person> Persons { get; set; }
}

public class Person
{
   public int PersonID {get; set;}
   public virtual ICollection<Course> Courses { get; set; }
}

This is the mapping table. Only contains 2 foreign key from 2 different table.
I could not use this table inside the solution.As the code first won't generate this table as it doesn't contain it's own PK.

//This is not shown in the EntityFramework when generating Code First.
    public class PersonCouseMap
    {
      public int PersonID {get; set;}
      public int CourseID {get; set;}
    }

Update : this works after I switched the entity.

return _ctx.Course
       .Include(u=>u.Person)
       .Where(ug=>ug.CourseName == "Sciene");

Anyone can explain why it won't work the another way round.
I need to display a List of Person who have course of "Science",
not Course Science that has a list of user.

Body:
The original query does not work because you've pushed the Where predicate inside the Include expression, which is not supported as indicated by the exception message.

The Include method is EF specific extension method used to eager load related data. It has nothing to do with the query filtering.

To apply the desired filter person that has course of "Science" you need Any based predicate since the Person.Courses is a collection:

return _ctx.Person
    .Where(p => p.Courses.Any(c => c.CourseName == "Science"));

To include the related data in the result, combine it with Include call(s):

return _ctx.Person
    .Include(p => p.Courses)
    .Where(p => p.Courses.Any(c => c.CourseName == "Science"));


问:
Disable a button in a v-for loop using VueJS 2

I want to disable a button on click in a v-for loop in the following code :

```<code>  <div class="row" style="border:solid 1px lightgrey;" v-for="element,counter in tableParent.etat_voies">
    <div class="col-md-3"  >
      <button
      ref=buttonRef
      @click="forceState(element,counter-1,tableParent.type,tableParent.occ)"
      style="background: white">
        FORCE
      </button>
   </div>
  </div>
</code>```

I don't want to use Jquery

I could use a computed value to switch the disable property like this :

```<code>:disable="someComputedValue"
</code>```

The problem is that it disable all my buttons in the same time due to the v-for loop

I could also use the ref to get my button by ref using this.$refs.buttonRef
but I don't know how to add properties dynamically.

If anybody could help me with that.

```<code><template>
  <div class="col-md-6">
    <div class="panel panel-default">
      <div class="panel-heading">{{tableParent.type}} | {{tableParent.occ}}</div>
      <div class="panel-body">
        <div v-if="tableParent.type == 'MTF' ">
          <div class="row">
            <div class="col-md-4">Sortie</div>
            <div class="col-md-4">Mesure</div>
            <div class="col-md-4">Fréquence</div>
          </div>
          <div class="row" style="border:solid 1px lightgrey;" v-for="element1,counter in tableParent.mesure" >
            <div class="col-md-4" style="border-right:solid 1px lightgrey;">{{++counter}}</div>
            <div class="col-md-4" style="border-right:solid 1px lightgrey;">{{element1}}</div>
            <div class="col-md-4" >{{tableParent.frequence[--counter]}}</div>
          </div>
        </div>
        <div v-else>
          <div class="row">
            <div class="col-md-6">Sortie</div>
            <div class="col-md-6">Etat</div>
          </div>
          <div class="row" style="border:solid 1px lightgrey;" v-for="element,counter in tableParent.etat_voies">
            <div class="col-md-6" style="border-right:solid 1px lightgrey;">{{++counter}}</div>
            <div class="col-md-3"  v-if="element" style="background: green" ref=etat  >{{element}}</div>
            <div class="col-md-3" v-else style="background: red"  ref=etat  >{{element}}</div>

            <div class="col-md-3"  >
              <button
              ref=button
              @click="forceState(element,counter-1,tableParent.type,tableParent.occ)"
              style="background: white">
                FORCE
              </button>
           </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import axios from 'axios'
  export default {
    name: 'BoardState',
    props : {
        tableParent : Object,
    },
    data () {
      return {
        counter: 0,

      }
    },
    methods : {
      forceState : function(element,counter,typeCarte,typeOcc) {
        let value
        if (element == 0){
          value = "1"
          this.$refs.etat[counter].textContent = value
          this.$refs.etat[counter].style = "background: yellow"
        } else {
          value = "0"
          this.$refs.etat[counter].textContent = value
          this.$refs.etat[counter].style = "background: yellow"
        }

        this.disableButton[counter] = true
        this.$refs.button[counter].
        axios.get('/cgi/etat_es/' + typeCarte + '/' + typeOcc + '/' + counter + '/' + value)
          .then((response) => {
          }).then((error) => {
        })

      }
    },
    mounted: function () {
    },
  }
</script>
</code>```

答:
You might wanna add an object as referrence on what to button to disable.

Edit 1:

```<code>import axios from 'axios'
  export default {
    name: 'BoardState',
    props : {
        tableParent : Object,
    },
    data () {
      return {
        counter: 0,
        disableButton: []

      }
    },
    methods : {
      forceState : function(element,counter,typeCarte,typeOcc) {
        let value
        if (element == 0){
          value = "1"
          this.$refs.etat[counter].textContent = value
          this.$refs.etat[counter].style = "background: yellow"
        } else {
          value = "0"
          this.$refs.etat[counter].textContent = value
          this.$refs.etat[counter].style = "background: yellow"
        }

        Vue.set(this.disableButton, counter, true);
        this.$refs.button[counter].
        axios.get('/cgi/etat_es/' + typeCarte + '/' + typeOcc + '/' + counter + '/' + value)
          .then((response) => {
          }).then((error) => {
        })

      }
    },
    mounted: function () {
    },
  }
</code>```

And inside button element

```<code><button
      ref=buttonRef
      @click="forceState(element,counter-1,tableParent.type,tableParent.occ)"
      :disabled="disableButton[counter-1]"
      style="background: white">
        FORCE
</button>
</code>```

Body:
I want to disable a button on click in a v-for loop in the following code :

      <button
      ref=buttonRef
      @click="forceState(element,counter-1,tableParent.type,tableParent.occ)"
      style="background: white">
        FORCE
      </button>

I don't want to use Jquery

I could use a computed value to switch the disable property like this :

:disable="someComputedValue"

The problem is that it disable all my buttons in the same time due to the v-for loop

I could also use the ref to get my button by ref using this.$refs.buttonRef
but I don't know how to add properties dynamically.

If anybody could help me with that.

<template>

{{tableParent.type}} | {{tableParent.occ}}

Sortie

Mesure

Fréquence

{{++counter}}

{{element1}}

{{tableParent.frequence[--counter]}}

Sortie

Etat

{{++counter}}

{{element}}

{{element}}

              <button
              ref=button
              @click="forceState(element,counter-1,tableParent.type,tableParent.occ)"
              style="background: white">
                FORCE
              </button>

</template>

Body:
You might wanna add an object as referrence on what to button to disable.

Edit 1:

import axios from 'axios'
  export default {
    name: 'BoardState',
    props : {
        tableParent : Object,
    },
    data () {
      return {
        counter: 0,
        disableButton: []

      }
    },
    methods : {
      forceState : function(element,counter,typeCarte,typeOcc) {
        let value
        if (element == 0){
          value = "1"
          this.$refs.etat[counter].textContent = value
          this.$refs.etat[counter].style = "background: yellow"
        } else {
          value = "0"
          this.$refs.etat[counter].textContent = value
          this.$refs.etat[counter].style = "background: yellow"
        }

        Vue.set(this.disableButton, counter, true);
        this.$refs.button[counter].
        axios.get('/cgi/etat_es/' + typeCarte + '/' + typeOcc + '/' + counter + '/' + value)
          .then((response) => {
          }).then((error) => {
        })

      }
    },
    mounted: function () {
    },
  }

And inside button element

<button
      ref=buttonRef
      @click="forceState(element,counter-1,tableParent.type,tableParent.occ)"
      :disabled="disableButton[counter-1]"
      style="background: white">
        FORCE
</button>