问:
file upload script in php not working
My php code for file upload is not working. I have tried it in various ways. My code is given below:

HTML Code:

```<code><form action="assets/php/regc.php" method="POST" name="rform" enctype="multipart/form-data">
<input name="photo" type="file" placeholder="Attach Photo" required="required"/><br>
<input type="submit" value="upload" name="" />

</form>

PHP Code:
<?php
$pic=$_FILES["photo"]["name"];

$location="assets/";
$myfile= $location.basename($_FILES["photo"]["name"]);

if(isset($_FILES["photo"]["name"]))
{
    $ok=move_uploaded_file($_FILES["photo"]["tmp_name"], $myfile);
    if($ok)
    {
    echo "success";
    }

    else
    {
    echo "Failed";
    }
}
?>
</code>```

答:
```<code><form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>

<?php
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    // Check if image file is a actual image or fake image
    if(isset($_POST["submit"])) {
        $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
        if($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;
        } else {
            echo "File is not an image.";
            $uploadOk = 0;
        }
    }
    ?>
</code>```

<p>in your input tag also pass id </p>

Title: file upload script in php not working

Body:
My php code for file upload is not working. I have tried it in various ways. My code is given below:

HTML Code:

<form action="assets/php/regc.php" method="POST" name="rform" enctype="multipart/form-data">
<input name="photo" type="file" placeholder="Attach Photo" required="required"/>

<input type="submit" value="upload" name="" />

</form>

PHP Code:
<?php
$pic=$_FILES["photo"]["name"];

$location="assets/";
$myfile= $location.basename($_FILES["photo"]["name"]);

if(isset($_FILES["photo"]["name"]))
{
    $ok=move_uploaded_file($_FILES["photo"]["tmp_name"], $myfile);
    if($ok)
    {
    echo "success";
    }

    else
    {
    echo "Failed";
    }
}
?>

Body:
<form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>

<?php
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    // Check if image file is a actual image or fake image
    if(isset($_POST["submit"])) {
        $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
        if($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;
        } else {
            echo "File is not an image.";
            $uploadOk = 0;
        }
    }
    ?>

in your input tag also pass id


来源: stackexchange

问:
Toast not working in Service
I try to create my first Service, of course without success. But this app successfully compiled and not give any error in AndroidMonitor.
In short, buttons no react for pressing.
I added to Android Manifest required line:

```<code><service android:name=".MyService"></service>
</code>```

ClientActivity

```<code>package com.example.servicetest;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ClientActivity extends Activity {
    private Button btnStartService;
    private Button btnStopService;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnStartService = (Button) findViewById(R.id.btnStartService);
        btnStopService = (Button) findViewById(R.id.btnStopService);
        initButtonsOnClick();
    }

    private void initButtonsOnClick() {
        OnClickListener listener = new OnClickListener() {
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.btnStartService:
                        startMyService();
                        break;
                    case R.id.btnStopService:
                        stopMyService();
                        break;
                    default:
                        break;
                }
            }
        };
        btnStartService.setOnClickListener(listener);
        btnStopService.setOnClickListener(listener);
    }

    private void startMyService() {
        Intent serviceIntent = new Intent(this, MyService.class);
        startService(serviceIntent);
    }

    private void stopMyService() {
        Intent serviceIntent = new Intent(this, MyService.class);
        stopService(serviceIntent);
    }
}
</code>```

MyService

```<code>package com.example.servicetest;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import java.util.Timer;
import java.util.TimerTask;
import android.widget.Toast;

public class MyService extends Service {
    private Toast toast;
    private Timer timer;
    private TimerTask timerTask;
    private class MyTimerTask extends TimerTask {
        @Override
        public void run() {
             Toast.makeText(getApplicationContext(), "Your service is still working", Toast.LENGTH_SHORT).show();
        }
    }

    private void writeToLogs(String message) {
        Log.d("HelloServices", message);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        writeToLogs("Called onCreate() method.");
        timer = new Timer();
        Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT).show();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        writeToLogs("Called onStartCommand() methond");
        clearTimerSchedule();
        initTask();
        timer.scheduleAtFixedRate(timerTask, 4 * 1000, 4 * 1000);
        Toast.makeText(getApplicationContext(), "Your service has been started", Toast.LENGTH_SHORT).show();
        return super.onStartCommand(intent, flags, startId);
    }

    private void clearTimerSchedule() {
        if(timerTask != null) {
            timerTask.cancel();
            timer.purge();
        }
    }

    private void initTask() {
        timerTask = new MyTimerTask();
    }

    @Override
    public void onDestroy() {
        writeToLogs("Called onDestroy() method");
        clearTimerSchedule();
        Toast.makeText(getApplicationContext(), "Your service has been stopped", Toast.LENGTH_SHORT).show();
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}
</code>```

答:
```<code>public class MyService extends Service {

    private Timer timer;
    private TimerTask timerTask;

    @Override
    public void onCreate() {
        super.onCreate();
        startTimer();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
//        startTimer();
//        sendNotification();
        return START_STICKY;
    }

    public void startTimer() {
        //set a new Timer
        timer = new Timer();

        //initialize the TimerTask's job
        initializeTimerTask();

        //schedule the timer, to wake up every 10 second
        timer.schedule(timerTask, 5000, 5000); //
    }

    /**
     * it sets the timer to print the counter every x seconds
     */
    public void initializeTimerTask() {
        timerTask = new TimerTask() {
            public void run() {
//                Log.e("in timer", "in timer ++++  " + (counter++));

                Handler handler = new Handler(Looper.getMainLooper());
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                ""+ (counter++),
                                Toast.LENGTH_SHORT).show();
                    }
                });
//                Toast.makeText(SensorService.this, ""+ (counter++), Toast.LENGTH_SHORT).show();
            }
        };
    }

    /**
     * not needed
     */
    public void stoptimertask() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}
</code>```

Use this for button click

```<code>public class ClientActivity extends Activity {

    private Button btnStartService;
    private Button btnStopService;

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

        btnStartService = (Button) findViewById(R.id.btnStartService);
        btnStopService = (Button) findViewById(R.id.btnStopService);

        btnStartService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent serviceIntent = new Intent(this, MyService.class);
                startService(serviceIntent);
            }
        });

        btnStopService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent serviceIntent = new Intent(this, MyService.class);
                stopService(serviceIntent);
            }
        });
    }

}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Toast not working in Service

Body:
I try to create my first Service, of course without success. But this app successfully compiled and not give any error in AndroidMonitor.
In short, buttons no react for pressing.
I added to Android Manifest required line:

<service android:name=".MyService"></service>

ClientActivity

package com.example.servicetest;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ClientActivity extends Activity {
    private Button btnStartService;
    private Button btnStopService;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnStartService = (Button) findViewById(R.id.btnStartService);
        btnStopService = (Button) findViewById(R.id.btnStopService);
        initButtonsOnClick();
    }

    private void initButtonsOnClick() {
        OnClickListener listener = new OnClickListener() {
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.btnStartService:
                        startMyService();
                        break;
                    case R.id.btnStopService:
                        stopMyService();
                        break;
                    default:
                        break;
                }
            }
        };
        btnStartService.setOnClickListener(listener);
        btnStopService.setOnClickListener(listener);
    }

    private void startMyService() {
        Intent serviceIntent = new Intent(this, MyService.class);
        startService(serviceIntent);
    }

    private void stopMyService() {
        Intent serviceIntent = new Intent(this, MyService.class);
        stopService(serviceIntent);
    }
}

MyService

package com.example.servicetest;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import java.util.Timer;
import java.util.TimerTask;
import android.widget.Toast;

public class MyService extends Service {
    private Toast toast;
    private Timer timer;
    private TimerTask timerTask;
    private class MyTimerTask extends TimerTask {
        @Override
        public void run() {
             Toast.makeText(getApplicationContext(), "Your service is still working", Toast.LENGTH_SHORT).show();
        }
    }

    private void writeToLogs(String message) {
        Log.d("HelloServices", message);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        writeToLogs("Called onCreate() method.");
        timer = new Timer();
        Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT).show();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        writeToLogs("Called onStartCommand() methond");
        clearTimerSchedule();
        initTask();
        timer.scheduleAtFixedRate(timerTask, 4 * 1000, 4 * 1000);
        Toast.makeText(getApplicationContext(), "Your service has been started", Toast.LENGTH_SHORT).show();
        return super.onStartCommand(intent, flags, startId);
    }

    private void clearTimerSchedule() {
        if(timerTask != null) {
            timerTask.cancel();
            timer.purge();
        }
    }

    private void initTask() {
        timerTask = new MyTimerTask();
    }

    @Override
    public void onDestroy() {
        writeToLogs("Called onDestroy() method");
        clearTimerSchedule();
        Toast.makeText(getApplicationContext(), "Your service has been stopped", Toast.LENGTH_SHORT).show();
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}

Body:
public class MyService extends Service {

    private Timer timer;
    private TimerTask timerTask;

    @Override
    public void onCreate() {
        super.onCreate();
        startTimer();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
//        startTimer();
//        sendNotification();
        return START_STICKY;
    }

    public void startTimer() {
        //set a new Timer
        timer = new Timer();

        //initialize the TimerTask's job
        initializeTimerTask();

        //schedule the timer, to wake up every 10 second
        timer.schedule(timerTask, 5000, 5000); //
    }

    /**
     * it sets the timer to print the counter every x seconds
     */
    public void initializeTimerTask() {
        timerTask = new TimerTask() {
            public void run() {
//                Log.e("in timer", "in timer ++++  " + (counter++));

                Handler handler = new Handler(Looper.getMainLooper());
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                ""+ (counter++),
                                Toast.LENGTH_SHORT).show();
                    }
                });
//                Toast.makeText(SensorService.this, ""+ (counter++), Toast.LENGTH_SHORT).show();
            }
        };
    }

    /**
     * not needed
     */
    public void stoptimertask() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}

Use this for button click

public class ClientActivity extends Activity {

    private Button btnStartService;
    private Button btnStopService;

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

        btnStartService = (Button) findViewById(R.id.btnStartService);
        btnStopService = (Button) findViewById(R.id.btnStopService);

        btnStartService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent serviceIntent = new Intent(this, MyService.class);
                startService(serviceIntent);
            }
        });

        btnStopService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent serviceIntent = new Intent(this, MyService.class);
                stopService(serviceIntent);
            }
        });
    }

}


问:
How to eliminate inefficiency of django query in a loop?
How can the following code be made more efficient (e.g., how to replace the loop with a query)?

def get_question(datetime_now, questions_queryset, user):
    best_schedule = None
    best_question = None
    # HOW TO ELIMINATE THE FOLLOWING LOOP AND REPLACE WITH A QUERY?
    for question in questions_queryset:
        try:
            schedule = (Schedule.objects
                        .filter(question=question, user=user)
                        .latest(field_name='datetime_added')
        except ObjectDoesNotExist:
            schedule = None
        if (schedule and (schedule.date_show_next >= datetime_now) and
                ((not best_schedule) or
                 (schedule.datetime_added >= best_schedule.datetime_added))):
            best_schedule = schedule
            best_question = question

    return best_question
```

<p><br/>
<br/>
models.py</p>

<pre class="lang-python prettyprint-override"><code>from django.contrib.auth.models import User
from django.db.models import DateTimeField, ForeignKey, Model, TextField

class Question(Model):
    question = TextField()

class Schedule(Model):
    datetime_added = DateTimeField(auto_now_add=True)
    datetime_show_next = DateTimeField(null=True, default=None)
    question = ForeignKey(Question)
    user = ForeignKey(User, null=True)
</code>```

答:
You could use Subquery like in this answer https://stackoverflow.com/a/43883397/3627387 or with use of Prefetch https://stackoverflow.com/a/31237026/3627387

Here is one way to achieve this with Prefetch:

```<code>schedules_prefetch = Prefetch(
        'schedule_set',
        queryset=Schedule.objects.filter(user=user))
for question in questions_queryset.prefetch_related(schedules_prefetch):
    try:
        # using max here so it wouldn't do another DB hit
        schedule = max(question.schedule_set.all(),
                       key=lambda x: x.datetime_added)
    except ValueError:
        schedule = None
</code>```

Here is an example using Subquery(it might not actually work, but will give you the general idea):

```<code>from django.db.models import OuterRef, Subquery
schedules = (Schedule.objects
             .filter(user=user, question=OuterRef('pk'))
             .order_by('datetime_added'))
questions_queryset = (questions_queryset
                    .annotate(latest_schedule=Subquery(schedules[:1])))
for question in questions_queryset:
    schedule = question.latest_schedule
</code>```

Body:
How can the following code be made more efficient (e.g., how to replace the loop with a query)?

def get_question(datetime_now, questions_queryset, user):
    best_schedule = None
    best_question = None
    # HOW TO ELIMINATE THE FOLLOWING LOOP AND REPLACE WITH A QUERY?
    for question in questions_queryset:
        try:
            schedule = (Schedule.objects
                        .filter(question=question, user=user)
                        .latest(field_name='datetime_added')
        except ObjectDoesNotExist:
            schedule = None
        if (schedule and (schedule.date_show_next >= datetime_now) and
                ((not best_schedule) or
                 (schedule.datetime_added >= best_schedule.datetime_added))):
            best_schedule = schedule
            best_question = question

    return best_question

models.py

from django.contrib.auth.models import User
from django.db.models import DateTimeField, ForeignKey, Model, TextField

class Question(Model):
    question = TextField()

class Schedule(Model):
    datetime_added = DateTimeField(auto_now_add=True)
    datetime_show_next = DateTimeField(null=True, default=None)
    question = ForeignKey(Question)
    user = ForeignKey(User, null=True)

Body:
You could use Subquery like in this answer https://stackoverflow.com/a/43883397/3627387 or with use of Prefetch https://stackoverflow.com/a/31237026/3627387

Here is one way to achieve this with Prefetch:

schedules_prefetch = Prefetch(
        'schedule_set',
        queryset=Schedule.objects.filter(user=user))
for question in questions_queryset.prefetch_related(schedules_prefetch):
    try:
        # using max here so it wouldn't do another DB hit
        schedule = max(question.schedule_set.all(),
                       key=lambda x: x.datetime_added)
    except ValueError:
        schedule = None

Here is an example using Subquery(it might not actually work, but will give you the general idea):

from django.db.models import OuterRef, Subquery
schedules = (Schedule.objects
             .filter(user=user, question=OuterRef('pk'))
             .order_by('datetime_added'))
questions_queryset = (questions_queryset
                    .annotate(latest_schedule=Subquery(schedules[:1])))
for question in questions_queryset:
    schedule = question.latest_schedule


问:
python selenium unable to click on a tag
I'm trying to click on this button shown below named “Segment Metrix 2.0 Consumer Target Profile report“

and I found corresponding HTML as shown below.

I tried to write code as below:

```<code>elem = driver.find_elements_by_xpath("//*[contains(text(), 'Segment Metrix 2.0 Consumer Target Profile report ')]")
print (elem)
</code>```

it gives me:

```<code>[<selenium.webdriver.remote.webelement.WebElement (session="daf65f4e5ed0485027d04eed8db8aca7", element="0.8079987809618281-1")>]
</code>```

But I can't click on it by adding elem[0].click(), it throws me an "element not visible" error. What should I do?

答:
You can wait for the element to be visible</p>

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

elem = driver.find_elements_by_xpath("//*[contains(text(), 'Segment Metrix 2.0 Consumer Target Profile report ')]")
WebDriverWait(driver, 10).until(EC.visibility_of(elem[0]))
elem[0].click()
</code>```

Body:
I'm trying to click on this button shown below named “Segment Metrix 2.0 Consumer Target Profile report“

and I found corresponding HTML as shown below.

I tried to write code as below:

elem = driver.find_elements_by_xpath("//*[contains(text(), 'Segment Metrix 2.0 Consumer Target Profile report ')]")
print (elem)

it gives me:

[<selenium.webdriver.remote.webelement.WebElement (session="daf65f4e5ed0485027d04eed8db8aca7", element="0.8079987809618281-1")>]

But I can't click on it by adding elem[0].click(), it throws me an "element not visible" error. What should I do?

Body:
You can wait for the element to be visible

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

elem = driver.find_elements_by_xpath("//*[contains(text(), 'Segment Metrix 2.0 Consumer Target Profile report ')]")
WebDriverWait(driver, 10).until(EC.visibility_of(elem[0]))
elem[0].click()


问:
array value not being properly emptied on a button click
The goal I am trying to achieved is that when one of the two buttons(btn 1 or btn 2) are clicked the array needs to reset(emptied) and when button add is clicked value 1 needs to be pushed to the array. Here is what I came up so far:

$(document).ready(function(){
   var array = []
   $("#btn_1").click(function(){
       array = []
       add_to_array(array);
   })
   $("#btn_2").click(function(){
       array = []
       add_to_array(array);
   })
})

function add_to_array(array){

    $("#add").click(function(){

     array.push(1)
     alert(array)
   })
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn_1">
empty array: btn 1
</button>

<button id="btn_2">
empty array: btn 2
</button>

<button id="add">
Add
</button></code>```

The problem I am facing: when I click either btn 1 or btn 2 more than once followed by add button, alert shows up the number of times I clicked btn1 or btn 2.

What I am looking for instead is, no matter how many times I click either btn 1 or btn2 I want alert two show up only once. Do you think what I am trying to achieve is achievable?

答:
Arrays can be emptied in multiple ways:

```<code>var arr =[];
arr.push(1);
//to empty an array
console.log(arr[0]);
arr.length=0;
console.log(arr);
</code>```

Output would be:

1 []

Body:
The goal I am trying to achieved is that when one of the two buttons(btn 1 or btn 2) are clicked the array needs to reset(emptied) and when button add is clicked value 1 needs to be pushed to the array. Here is what I came up so far:

$(document).ready(function(){
   var array = []
   $("#btn_1").click(function(){
       array = []
       add_to_array(array);
   })
   $("#btn_2").click(function(){
       array = []
       add_to_array(array);
   })
})

function add_to_array(array){

    $("#add").click(function(){

     array.push(1)
     alert(array)
   })
}

<button id="btn_1">
empty array: btn 1
</button>

<button id="btn_2">
empty array: btn 2
</button>

<button id="add">
Add
</button>

The problem I am facing: when I click either btn 1 or btn 2 more than once followed by add button, alert shows up the number of times I clicked btn1 or btn 2.

What I am looking for instead is, no matter how many times I click either btn 1 or btn2 I want alert two show up only once. Do you think what I am trying to achieve is achievable?

Body:
Arrays can be emptied in multiple ways:

var arr =[];
arr.push(1);
//to empty an array
console.log(arr[0]);
arr.length=0;
console.log(arr);

Output would be:

1 []


问:
Get maximum from absolute values returning signed value
Supposing I have a class

```<code>Public Class Foo
    Property fooProp1 as Single
    Property fooProp2 as Single
    Property fooProp3 as Single
End Class
</code>```

to find the absolut maximum of a property (which contains positive or negative values) in a Collection(Of Foo) I can do:

```<code>Collection.Max(Function(x As foo) Math.Abs(x.fooProp1))
</code>```

and it returns the greater absolute value WITHOUT sign.

The question is how can I do to get the number WITH sign?

Thanks in advance.
RG

答:
```<code>Collection.Select(Function(x) a.fooProp1).Aggregate(Function(a, b)
                                                    If(Math.Abs(a) > Math.Abs(b), a, b))
</code>```

Body:
Supposing I have a class

Public Class Foo
    Property fooProp1 as Single
    Property fooProp2 as Single
    Property fooProp3 as Single
End Class

to find the absolut maximum of a property (which contains positive or negative values) in a Collection(Of Foo) I can do:

Collection.Max(Function(x As foo) Math.Abs(x.fooProp1))

and it returns the greater absolute value WITHOUT sign.

The question is how can I do to get the number WITH sign?

Thanks in advance.
RG


问:
How can i freeze UIView at the top?
I have a UIView under the UITableView, so that the UIView will also scrolling down  when i scroll the tableview.

I have tried the move the UIView out of the UITableView but it is not allow, how can i keep the UIView at the top even when i scrolling the UITableView?

答:
You can try this: take a UIView as a superview and inside that add your tableview and description view as subviews.

```<code>Parent View
~> Add Desc View at top with 1:5 height ratio of Parent
~> Then add your tableview below desc view with 4:5 height ratio of Parent
</code>```

You can vary that ratio to fit your need.
So conclusion: put both your views in another uiview. So your parent view now has 2 subviews, 1 uiview and 1 tableview. That would allow the view to be at top as well as allow the tableview to scroll.

Please Check This Image For Hierarchy Of UIViews

Title: How can i freeze UIView at the top?

Body:
You can try this: take a UIView as a superview and inside that add your tableview and description view as subviews.

Parent View
~> Add Desc View at top with 1:5 height ratio of Parent
~> Then add your tableview below desc view with 4:5 height ratio of Parent

You can vary that ratio to fit your need.
So conclusion: put both your views in another uiview. So your parent view now has 2 subviews, 1 uiview and 1 tableview. That would allow the view to be at top as well as allow the tableview to scroll.

Please Check This Image For Hierarchy Of UIViews


问:
Why is the non-type partial specialization tuple not taken?
I am attempting to achieve the following (using C++17 features):

```<code>#include <type_traits>

template<auto value_>
using constant_t = std::integral_constant<decltype(value_), value_>;

template<typename ... > class Tuple {};

template<auto ... values_>
class Tuple<constant_t<values_> ... > {};

int main(void)
{
    Tuple<int, int, char> types;
    Tuple<1, 2, 3> values;
}
</code>```

Which gives me the following error in g++-7.1.0

main.cpp: In function ‘int main()’:
main.cpp:15:18: error: type/value mismatch at argument 1 in template parameter list for ‘template<class ...> class Tuple’
     Tuple<1, 2, 3> values;
              ^
main.cpp:15:18: note:   expected a type, got ‘1’
main.cpp:15:18: error: type/value mismatch at argument 1 in template parameter list for ‘template<class ...> class Tuple’
main.cpp:15:18: note:   expected a type, got ‘2’
main.cpp:15:18: error: type/value mismatch at argument 1 in template parameter list for ‘template<class ...> class Tuple’
main.cpp:15:18: note:   expected a type, got ‘3’
```

Can anyone explain why the partial specialization does not activate for the Tuple<1, 2, 3>?

答:
1, 2 and 3 are not types. Your specialization doesn't (and can't) change the primary template to accept values, so you can't magically pass values where types were expected before.

If you want a template that accepts values, an alias template can do that instead of the specialization:

```<code>template<auto... values_>
using VTuple = Tuple<constant_t<values_>... >;
</code>```

But it is a separate template.

Body:
I am attempting to achieve the following (using C++17 features):

#include <type_traits>

template<auto value_>
using constant_t = std::integral_constant<decltype(value_), value_>;

template<typename ... > class Tuple {};

template<auto ... values_>
class Tuple<constant_t<values_> ... > {};

int main(void)
{
    Tuple<int, int, char> types;
    Tuple<1, 2, 3> values;
}

Which gives me the following error in g++-7.1.0

main.cpp: In function ‘int main()’:
main.cpp:15:18: error: type/value mismatch at argument 1 in template parameter list for ‘template<class ...> class Tuple’
     Tuple<1, 2, 3> values;
              ^
main.cpp:15:18: note:   expected a type, got ‘1’
main.cpp:15:18: error: type/value mismatch at argument 1 in template parameter list for ‘template<class ...> class Tuple’
main.cpp:15:18: note:   expected a type, got ‘2’
main.cpp:15:18: error: type/value mismatch at argument 1 in template parameter list for ‘template<class ...> class Tuple’
main.cpp:15:18: note:   expected a type, got ‘3’

Can anyone explain why the partial specialization does not activate for the Tuple<1, 2, 3>?

Body:
1, 2 and 3 are not types. Your specialization doesn't (and can't) change the primary template to accept values, so you can't magically pass values where types were expected before.

If you want a template that accepts values, an alias template can do that instead of the specialization:

template<auto... values_>
using VTuple = Tuple<constant_t<values_>... >;

But it is a separate template.


问:
Moving files on different volumes in .NET
Apparently I can't move files on different volumes using Directory.Move.

I have read that I have to copy each file individually to the destination, then delete the source directory.

Do I have any other option?

答:
Try to use this:

```<code>public static void RobustMove(string sourceDirectory, string destDirectory)
{
    //move if directories are on the same volume
    if (Path.GetPathRoot(source) == Path.GetPathRoot(destination))
    {
        Directory.Move(source, destination);
    }
    else
    {
        CopyDirectoryRecursive(source, destination);
        Directory.Delete(source, true);
    }
}
</code>```

You will find CopyDirectoryRecursive function here:

This should be working until you use spanned volume or symbol links to another physical disk.

To be even more robust you can improve this function to use Move until System.IO .Exception is thrown and then to switch to copying and deleting.

OwnerDisplayName: Blankman

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Blankman

Body:
Try to use this:

public static void RobustMove(string sourceDirectory, string destDirectory)
{
    //move if directories are on the same volume
    if (Path.GetPathRoot(source) == Path.GetPathRoot(destination))
    {
        Directory.Move(source, destination);
    }
    else
    {
        CopyDirectoryRecursive(source, destination);
        Directory.Delete(source, true);
    }
}

You will find CopyDirectoryRecursive function here:

This should be working until you use spanned volume or symbol links to another physical disk.

To be even more robust you can improve this function to use Move until System.IO .Exception is thrown and then to switch to copying and deleting.


问:
How to transform list of objects into one row object in java
I have a class A having private members like below.

```<code>class A {
  String type;
}
</code>```

The above class will come as list objects List . Now  i have Another  class B

```<code>Class B {
  String type1;
  String type2;
  String type3;
  String type4;
  String type5;
  String type6;
  String type7;
  String type8;
}
</code>```

So  Now How i have to iterate through List  and get the (type(s)) data one by one and then put it into Class B as single object like first one will go to Type1 , second one  ---> type2, third one--- > type3 ....., so on.
Note : There will be only 8 types in class A as a list . so we will have exactly 8 types in Class B and i have thought on reflection so please tell how do i use it, if this is the only option.

答:
If you can change the class B as:

```<code>class B
{
    String[] types;
}
</code>```

Then we can do:

```<code>int i = 0;
for(A aObject:aList){
    bObject.types[i] = aObject.type;
}
</code>```

Else we can add all types like this:

```<code>bObject.type1 = aList.get(0).type;
bObject.type2 = aList.get(1).type;
</code>```

and so on.

Body:
I have a class A having private members like below.

class A {
  String type;
}

The above class will come as list objects List . Now  i have Another  class B

Class B {
  String type1;
  String type2;
  String type3;
  String type4;
  String type5;
  String type6;
  String type7;
  String type8;
}

So  Now How i have to iterate through List  and get the (type(s)) data one by one and then put it into Class B as single object like first one will go to Type1 , second one  ---> type2, third one--- > type3 ....., so on.
Note : There will be only 8 types in class A as a list . so we will have exactly 8 types in Class B and i have thought on reflection so please tell how do i use it, if this is the only option.

Body:
If you can change the class B as:

class B
{
    String[] types;
}

Then we can do:

int i = 0;
for(A aObject:aList){
    bObject.types[i] = aObject.type;
}

Else we can add all types like this:

bObject.type1 = aList.get(0).type;
bObject.type2 = aList.get(1).type;

and so on.


问:
MySQL : Better Solution To Nested If
I have the link :
Types Of Triangle

My answer is:

SELECT IF (A = B AND A = C AND B = C, 'Equilateral', IF((A = B OR A = C OR B = C) AND (A + B) > C, 'Isosceles', IF (A != B AND A != C AND B != C AND (A + B) > C, 'Scalene', 'Not A Triangle'))) FROM TRIANGLES

So far, its correct but somehow I have used a messy nested IF.

My question is, is there a better way to solve in terms of elegance and efficiency? I'm kinda familiar with SQL queries for years now but its something that I seldom use since I'm more into front end development.

Thanks.

答:
You need to use a CASE statement and not a IF:</p>

```<code>SELECT
CASE WHEN (A = B AND A = C) then 'Equilateral'
WHEN ((A = B OR A = C OR B = C) AND (A + B) > C) then 'Isosceles'
WHEN (A != B AND A != C AND B != C AND (A + B) > C) then 'Scalene'
ELSE 'Not A Triangle'
END AS "Type of Triangle"
FROM TRIANGLES
</code>```

Title: MySQL : Better Solution To Nested If

Body:
You need to use a CASE statement and not a IF:

SELECT
CASE WHEN (A = B AND A = C) then 'Equilateral'
WHEN ((A = B OR A = C OR B = C) AND (A + B) > C) then 'Isosceles'
WHEN (A != B AND A != C AND B != C AND (A + B) > C) then 'Scalene'
ELSE 'Not A Triangle'
END AS "Type of Triangle"
FROM TRIANGLES


问:
Hibernate 5 :- org.hibernate.MappingException: Unknown entity
I am getting the error message org.hibernate.MappingException: Unknown entity when i am trying to integrate hibernate 5.0 with mysql

This seems to be an issue with hibernate5.0.0 and 5.0.1 . This works fine with hibernate 4.3.9

Maven dependices

```<code><dependency>
    <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.0.0.Final</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.36</version>
</dependency>
</code>```

hibernate.cfg.xml

```<code><session-factory>

    <!-- Database connection settings -->
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3307/SampleDB
    </property>
    <property name="connection.username">root</property>
    <property name="connection.password"></property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>

    <!-- Drop and re-create the database schema on startup -->
    <property name="hbm2ddl.auto">create</property>

    <mapping class="UserA.User"></mapping>

</session-factory>
</code>```

HibernateMain.java code

```<code>package UserA;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.mapping.Map;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.service.ServiceRegistry;

public class HibernateMain {

    public static void main(String[] args) {

        Configuration configuration = new Configuration();
        configuration.configure();
        ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();

        SessionFactory sf = configuration.buildSessionFactory(sr);

        User user1 = new User();
        user1.setUserName("Arpit");
        user1.setUserMessage("Hello world from arpit");
        user1.setUserId(22);

        Session ss = sf.openSession();
        ss.beginTransaction();
        // saving objects to session
        ss.save(user1);
        ss.getTransaction().commit();
        ss.close();

    }

}
</code>```

User.java

```<code>package UserA;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity(name="User_table")
public class User {
    @Id
    int userId;
    @Column(name = "User_Name")
    String userName;

    @Column(name = "User_Message")
    String userMessage;

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserMessage() {
        return userMessage;
    }

    public void setUserMessage(String userMessage) {
        this.userMessage = userMessage;
    }

}
</code>```

答:
I was facing the same issue & I searched for almost 2 hours and tried with different possible ways like replacing old hibernate jars&changing the db table schema. But finally got the solution as below;

```<code> //This line to be replaced with below commented line
 SessionFactory factory = new Configuration().configure().buildSessionFactory();
</code>```

Replace above for

```<code>Configuration config = new Configuration().configure();
ServiceRegistry servReg = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
SessionFactory factory = config.buildSessionFactory(servReg);
</code>```

It will then work fine..

Body:
I am getting the error message org.hibernate.MappingException: Unknown entity when i am trying to integrate hibernate 5.0 with mysql

This seems to be an issue with hibernate5.0.0 and 5.0.1 . This works fine with hibernate 4.3.9

Maven dependices

<dependency>
    <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.0.0.Final</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.36</version>
</dependency>

hibernate.cfg.xml

<session-factory>

    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3307/SampleDB
    </property>
    <property name="connection.username">root</property>
    <property name="connection.password"></property>

    <property name="connection.pool_size">1</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

    <property name="show_sql">true</property>

    <property name="hbm2ddl.auto">create</property>

    <mapping class="UserA.User"></mapping>

</session-factory>

HibernateMain.java code

package UserA;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.mapping.Map;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.service.ServiceRegistry;

public class HibernateMain {

    public static void main(String[] args) {

        Configuration configuration = new Configuration();
        configuration.configure();
        ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();

        SessionFactory sf = configuration.buildSessionFactory(sr);

        User user1 = new User();
        user1.setUserName("Arpit");
        user1.setUserMessage("Hello world from arpit");
        user1.setUserId(22);

        Session ss = sf.openSession();
        ss.beginTransaction();
        // saving objects to session
        ss.save(user1);
        ss.getTransaction().commit();
        ss.close();

    }

}

User.java

package UserA;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity(name="User_table")
public class User {
    @Id
    int userId;
    @Column(name = "User_Name")
    String userName;

    @Column(name = "User_Message")
    String userMessage;

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserMessage() {
        return userMessage;
    }

    public void setUserMessage(String userMessage) {
        this.userMessage = userMessage;
    }

}

Body:
I was facing the same issue & I searched for almost 2 hours and tried with different possible ways like replacing old hibernate jars&changing the db table schema. But finally got the solution as below;

 //This line to be replaced with below commented line
 SessionFactory factory = new Configuration().configure().buildSessionFactory();

Replace above for

Configuration config = new Configuration().configure();
ServiceRegistry servReg = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
SessionFactory factory = config.buildSessionFactory(servReg);

It will then work fine..


问:
Reading Mifare card via web app using Android device's NFC
I want to find out if this is possible, to have a web app read off information from a Mifare card, by tapping the card against a NFC-enabled Android device.

I have been searching this for quite some time, and it seems like as of now it's only limited to experimental implementation - https://whatwebcando.today/nfc.html

Or am I truly better off with a native Android app?

Edit:
Thanks to all who replied. We have been trying out the Web NFC API as specified here https://w3c.github.io/web-nfc/, turned on the experimental features of Chrome on the Android device, but it always return a null value when we tap the Mifare card on the device. Are we missing out any steps, or is it really a technical limitation of the API at this moment, since it's still not considered as a stable specification?

答:
I think on mid-term even WebNFC will be restricted to (reading & writing) NDEF messages, similar to what Apple is currently doing on iOS.
So if you want to read info like UID or raw data out of a MIFARE card, you need to write a native app. Be aware that MIFARE (Classic) is not supported by all phones, even when they have NFC.
If you want to use a framework like ionic or Cordova, you can also use the NDEF plugin (https://github.com/chariotsolutions/phonegap-nfc) </p>

ContentLicense: CC BY-SA 4.0


问:
Connect to remote websocket angularjs
I am trying to connect to a remote push API websocket (in the client / browser, not in the backend) and log the live data in the console. I have been searching for a while and can't find any examples of this.

This is the API I'm trying to connect to: https://poloniex.com/support/api/

I want to subscribe to the ticker channel and log the data in console.

I have istalled socket.io in order to accomplish this, and here is the code I have so far:

var socket = io.connect('wss://api.poloniex.com ');
io.on('connection', function(socket){
  socket.join('ticker');
});```

Chrome inspector is showing error, repeatedly every second or two: https://api.poloniex.com%20/socket.io/?EIO=3&transport=polling&t=LqCBLTn net::ERR_NAME_NOT_RESOLVED

How can I get live data from this websocket API?

答:
You have a space in the URL: 'wss://api.poloniex.com '

net::ERR_NAME_NOT_RESOLVED indicates that the host name couldn't be resolved. So you should look at the host name you're trying to reach. api.poloniex.com%20 could not be resolved because you probably don't have a domain registered with a .com%20 TLD! Simply remove the space in the first line of your snippet and, assuming your DNS records are setup accordingly, you shouldn't get net::ERR_NAME_NOT_RESOLVED anymore.

Title: Connect to remote websocket angularjs

Body:
I am trying to connect to a remote push API websocket (in the client / browser, not in the backend) and log the live data in the console. I have been searching for a while and can't find any examples of this.

This is the API I'm trying to connect to: https://poloniex.com/support/api/

I want to subscribe to the ticker channel and log the data in console.

I have istalled socket.io in order to accomplish this, and here is the code I have so far:

var socket = io.connect('wss://api.poloniex.com ');
io.on('connection', function(socket){
  socket.join('ticker');
});

Chrome inspector is showing error, repeatedly every second or two: https://api.poloniex.com%20/socket.io/?EIO=3&transport=polling&t=LqCBLTn net::ERR_NAME_NOT_RESOLVED

How can I get live data from this websocket API?


问:
Java for loop exceeds limits. Android
I'm doing a project in Android Studio and am getting a null pointer exception when I definitely shouldn't be. Here is the problem code:

```<code>public class PlayActivity extends AppCompatActivity{
boolean[][] cellClicked = new boolean[3][3];
boolean player1 = false;
boolean player2 = true;
boolean currentPlayer;
ImageView[][] cells = new ImageView[3][3];

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) throws NullPointerException{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_play);
    currentPlayer = player1;
    cells[0][0] = (ImageView) findViewById(R.id.cell_0);
    cells[0][1] = (ImageView) findViewById(R.id.cell_1);
    cells[0][2] = (ImageView) findViewById(R.id.cell_2);
    cells[1][0] = (ImageView) findViewById(R.id.cell_3);
    cells[1][1] = (ImageView) findViewById(R.id.cell_4);
    cells[1][2] = (ImageView) findViewById(R.id.cell_5);
    cells[2][0] = (ImageView) findViewById(R.id.cell_6);
    cells[2][1] = (ImageView) findViewById(R.id.cell_7);
    cells[2][2] = (ImageView) findViewById(R.id.cell_8);

    try {
        for(int i = 0; i < 3; i++) {
            for(int j = 0; i < 3; j++) {
                setListeners(i, j);
            }
        }
    } catch(NullPointerException e){
        throw new NullPointerException("cant access element");
    }

}
private void setListeners(int i, int j){
    final int row = i;
    final int col = j;
    cells[row][col].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!cellClicked[row][col]) {
                makeMove(cells[row][col], row, col);
            }
        }
    });
}
</code>```

When I run the app, as soon as I navigate to PlayActivity, the app crashes. When I look at the log errors, it shows:

```<code>FATAL EXCEPTION: main
 Process: net.drmcb.tictactoe, PID: 29345
 java.lang.RuntimeException: Unable to start activity ComponentInfo{net.drmcb.tictactoe/net.drmcb.tictactoe.PlayActivity}: java.lang.ArrayIndexOutOfBoundsException: length=3; index=3
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988)
     at android.app.ActivityThread.-wrap14(ActivityThread.java)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:154)
     at android.app.ActivityThread.main(ActivityThread.java:6682)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
  Caused by: java.lang.ArrayIndexOutOfBoundsException: length=3; index=3
     at net.drmcb.tictactoe.PlayActivity.setListeners(PlayActivity.java:55)
     at net.drmcb.tictactoe.PlayActivity.onCreate(PlayActivity.java:44)
     at android.app.Activity.performCreate(Activity.java:6942)
     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2880)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988)
     at android.app.ActivityThread.-wrap14(ActivityThread.java)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:154)
     at android.app.ActivityThread.main(ActivityThread.java:6682)
     at java.lang.reflect.Method.invoke(Native Method)
</code>```

The lines the errors are referring to are 44: setListeners(i, j); and  55:

```<code>cells[row][col].setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (!cellClicked[row][col]) {
            makeMove(cells[row][col], row, col);
        }
    }
});
</code>```

I commented out all the code in makeMoves() so that's not the problem.

In my for loops encasing the call to setListeners(), the i < 3 part is highlighted and when I hover over it, it tells me "Condition 'i < 3' is always true"...

In attempting to debug this for the last several hours, I have the following questions:

Why does the for loop exceed it's i < 3 conditional?

Why does any reference to cells.length or cells[0].length break the code?

答:
Basically your j was able to increment up to 3 because your i < 3 in

```<code>for(int j = 0; i < 3; j++) {
</code>```

will always be true because i is 0.
As what Yazan said, just correct your i < 3 to j < 3 and it will be fine.

 This also tells us to properly name our variables to avoid this kind of problems.

Title: Java for loop exceeds limits. Android

Body:
I'm doing a project in Android Studio and am getting a null pointer exception when I definitely shouldn't be. Here is the problem code:

public class PlayActivity extends AppCompatActivity{
boolean[][] cellClicked = new boolean[3][3];
boolean player1 = false;
boolean player2 = true;
boolean currentPlayer;
ImageView[][] cells = new ImageView[3][3];

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) throws NullPointerException{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_play);
    currentPlayer = player1;
    cells[0][0] = (ImageView) findViewById(R.id.cell_0);
    cells[0][1] = (ImageView) findViewById(R.id.cell_1);
    cells[0][2] = (ImageView) findViewById(R.id.cell_2);
    cells[1][0] = (ImageView) findViewById(R.id.cell_3);
    cells[1][1] = (ImageView) findViewById(R.id.cell_4);
    cells[1][2] = (ImageView) findViewById(R.id.cell_5);
    cells[2][0] = (ImageView) findViewById(R.id.cell_6);
    cells[2][1] = (ImageView) findViewById(R.id.cell_7);
    cells[2][2] = (ImageView) findViewById(R.id.cell_8);

    try {
        for(int i = 0; i < 3; i++) {
            for(int j = 0; i < 3; j++) {
                setListeners(i, j);
            }
        }
    } catch(NullPointerException e){
        throw new NullPointerException("cant access element");
    }

}
private void setListeners(int i, int j){
    final int row = i;
    final int col = j;
    cells[row][col].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!cellClicked[row][col]) {
                makeMove(cells[row][col], row, col);
            }
        }
    });
}

When I run the app, as soon as I navigate to PlayActivity, the app crashes. When I look at the log errors, it shows:

FATAL EXCEPTION: main
 Process: net.drmcb.tictactoe, PID: 29345
 java.lang.RuntimeException: Unable to start activity ComponentInfo{net.drmcb.tictactoe/net.drmcb.tictactoe.PlayActivity}: java.lang.ArrayIndexOutOfBoundsException: length=3; index=3
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988)
     at android.app.ActivityThread.-wrap14(ActivityThread.java)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:154)
     at android.app.ActivityThread.main(ActivityThread.java:6682)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
  Caused by: java.lang.ArrayIndexOutOfBoundsException: length=3; index=3
     at net.drmcb.tictactoe.PlayActivity.setListeners(PlayActivity.java:55)
     at net.drmcb.tictactoe.PlayActivity.onCreate(PlayActivity.java:44)
     at android.app.Activity.performCreate(Activity.java:6942)
     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2880)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2988)
     at android.app.ActivityThread.-wrap14(ActivityThread.java)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1631)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:154)
     at android.app.ActivityThread.main(ActivityThread.java:6682)
     at java.lang.reflect.Method.invoke(Native Method)

The lines the errors are referring to are 44: setListeners(i, j); and  55:

cells[row][col].setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (!cellClicked[row][col]) {
            makeMove(cells[row][col], row, col);
        }
    }
});

I commented out all the code in makeMoves() so that's not the problem.

In my for loops encasing the call to setListeners(), the i < 3 part is highlighted and when I hover over it, it tells me "Condition 'i < 3' is always true"...

In attempting to debug this for the last several hours, I have the following questions:

Why does the for loop exceed it's i < 3 conditional?

Why does any reference to cells.length or cells[0].length break the code?

Body:
Basically your j was able to increment up to 3 because your i < 3 in

for(int j = 0; i < 3; j++) {

will always be true because i is 0.
As what Yazan said, just correct your i < 3 to j < 3 and it will be fine.

 This also tells us to properly name our variables to avoid this kind of problems.


问:
Cannot find module 'bcrypt'
I am getting error Cannot find module 'bcrypt' in nodejs application

I have tried to install it using npm install bcrypt  but still getting the issue.

```<code>node app.js
</code>```

Error message:

```<code>Dec 30 2015 5:22:18 PM+05:30 - info: Connected to database:
postgres://testdb:see2@$W@localhost/testdb

Dec 30 2015 5:22:18 PM+05:30 - error: Error: Cannot find module 'bcrypt'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (D:\...\server\modules\user\model
s\user.js:11:14)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
</code>```

答:
Before using npm install, change the package.json file dependencies, i.e.

```<code>"bcrypt":"0.7.6"
</code>```

to

```<code>"bcrypt":"*"
</code>```

Title: Cannot find module 'bcrypt'

Body:
I am getting error Cannot find module 'bcrypt' in nodejs application

I have tried to install it using npm install bcrypt  but still getting the issue.

node app.js

Error message:

Dec 30 2015 5:22:18 PM+05:30 - info: Connected to database:
postgres://testdb:see2@$W@localhost/testdb

Dec 30 2015 5:22:18 PM+05:30 - error: Error: Cannot find module 'bcrypt'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (D:\...\server\modules\user\model
s\user.js:11:14)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)

Body:
Before using npm install, change the package.json file dependencies, i.e.

"bcrypt":"0.7.6"

to

"bcrypt":"*"


问:
How to run Python script on USB flash-drive insertion
My goal is to run a Python script on USB flash-drive insertion. I have written a udev rule and a shell script that is called in that rule.

udev rule:    /etc/udev/rules.d/10-usb.rules

```<code>KERNEL=="sd*[!0-9]|sr*", ENV{ID_SERIAL}!="?*", SUBSYSTEMS=="usb", RUN+="/home/Hypotheron/Desktop/script.sh"
</code>```

script.sh:

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

echo 'Hello, world.' > /home/Hypotheron/Desktop/foo.txt
#/home/Hypotheron/Desktop/job.py & exit
</code>```

The first line of my Python file is:

```<code>#!/usr/bin/python
</code>```

I also did these following commands:

```<code>chmod +x job.py
chmod +x script.sh
</code>```

In the script.sh when the line writing to foo.txt is uncommented the foo.txt file is created every flash-drive insertion.

When I comment that line and uncomment the line running the Python file it doesn't work.

Running the script.sh through terminal works in both cases but when inserting a flash-drive only the foo.txt case works.

Any help would be appreciated.

答:
```<code>   RUN{type}
       Add a program to the list of programs to be executed after
       processing all the rules for a specific event, depending on "type":

       "program"
           Execute an external program specified as the assigned value. If
           no absolute path is given, the program is expected to live in
           /lib/udev; otherwise, the absolute path must be specified.

           This is the default if no type is specified.

       "builtin"
           As program, but use one of the built-in programs rather than an
           external one.

       The program name and following arguments are separated by spaces.
       Single quotes can be used to specify arguments with spaces.

       This can only be used for very short-running foreground tasks.
       Running an event process for a long period of time may block all
       further events for this or a dependent device.

       Starting daemons or other long-running processes is not appropriate
       for udev; the forked processes, detached or not, will be
       unconditionally killed after the event handling has finished.
</code>```

From the udev man page, pay special attention to the last 2 paragraphs.

My guess, is that you have discovered the unconditional killing part

Edit 1 Year later:

I revisited this after someone voted it up and I have resolved the issues, which are, that root (who is running this process) does not have an X terminal entry essential for certain things like notify-send or starting a Gui program and there still remains the killing of the process after the event, as mentioned previously.

The following sends a notification to the terminal and starts a wxPython Gui program, when a usb device is inserted.

The script:

```<code>#!/bin/sh
DISPLAY=:0
export DISPLAY
/usr/bin/notify-send "Usb Device detected" "Starting Reminder program" | at now
/usr/bin/python3 /home/rolf/reminders/reminders2.1.0/reminder.py | at now
</code>```

by defining DISPLAY we get around root's issue of no X term entry

by passing the commands that we wish to run, to the at program with the instruction to run it now, we avoid the udev killing of the process.

The /lib/udev/rules.d/10-usbinsert.rules file:

```<code>KERNEL=="sd*[!0-9]|sr*", ENV{ID_SERIAL}!="?*", SUBSYSTEMS=="usb", RUN+="/usr/bin/sudo -u rolf /home/rolf/script.sh &"
</code>```

I hope this helps or gets you moving in the right direction.

Body:
My goal is to run a Python script on USB flash-drive insertion. I have written a udev rule and a shell script that is called in that rule.

udev rule:    /etc/udev/rules.d/10-usb.rules

KERNEL=="sd*[!0-9]|sr*", ENV{ID_SERIAL}!="?*", SUBSYSTEMS=="usb", RUN+="/home/Hypotheron/Desktop/script.sh"

script.sh:

#!/bin/sh

echo 'Hello, world.' > /home/Hypotheron/Desktop/foo.txt
#/home/Hypotheron/Desktop/job.py & exit

The first line of my Python file is:

#!/usr/bin/python

I also did these following commands:

chmod +x job.py
chmod +x script.sh

In the script.sh when the line writing to foo.txt is uncommented the foo.txt file is created every flash-drive insertion.

When I comment that line and uncomment the line running the Python file it doesn't work.

Running the script.sh through terminal works in both cases but when inserting a flash-drive only the foo.txt case works.

Any help would be appreciated.

Body:
   RUN{type}
       Add a program to the list of programs to be executed after
       processing all the rules for a specific event, depending on "type":

       "program"
           Execute an external program specified as the assigned value. If
           no absolute path is given, the program is expected to live in
           /lib/udev; otherwise, the absolute path must be specified.

           This is the default if no type is specified.

       "builtin"
           As program, but use one of the built-in programs rather than an
           external one.

       The program name and following arguments are separated by spaces.
       Single quotes can be used to specify arguments with spaces.

       This can only be used for very short-running foreground tasks.
       Running an event process for a long period of time may block all
       further events for this or a dependent device.

       Starting daemons or other long-running processes is not appropriate
       for udev; the forked processes, detached or not, will be
       unconditionally killed after the event handling has finished.

From the udev man page, pay special attention to the last 2 paragraphs.

My guess, is that you have discovered the unconditional killing part

Edit 1 Year later:

I revisited this after someone voted it up and I have resolved the issues, which are, that root (who is running this process) does not have an X terminal entry essential for certain things like notify-send or starting a Gui program and there still remains the killing of the process after the event, as mentioned previously.

The following sends a notification to the terminal and starts a wxPython Gui program, when a usb device is inserted.

The script:

#!/bin/sh
DISPLAY=:0
export DISPLAY
/usr/bin/notify-send "Usb Device detected" "Starting Reminder program" | at now
/usr/bin/python3 /home/rolf/reminders/reminders2.1.0/reminder.py | at now

by defining DISPLAY we get around root's issue of no X term entry

by passing the commands that we wish to run, to the at program with the instruction to run it now, we avoid the udev killing of the process.

The /lib/udev/rules.d/10-usbinsert.rules file:

KERNEL=="sd*[!0-9]|sr*", ENV{ID_SERIAL}!="?*", SUBSYSTEMS=="usb", RUN+="/usr/bin/sudo -u rolf /home/rolf/script.sh &"

I hope this helps or gets you moving in the right direction.


问:
creating a new pandas dataframe based on groups
The csv (sample below) shows the absolute error for an item for a given week (week_end_date). As the csv shows, an item belongs to a department, and a department has multiple items:

What I want to do is to create a new dataframe which has the following fields:

```<code>mdse_dept_ref_i     week_end_date      average_ABSError      num_items_in_department
</code>```

Here is what I am able to do:

```<code>new_df = df.loc[df['mdse_dept_ref_i'] == 47]
num_items = new_df.groupby('week_end_date').size()

avg_abs_error = new_df.groupby(['week_end_date'])['ABSError'].mean()
new_df = num_items.to_frame().join(avg_abs_error.to_frame())
</code>```

But, I don't know how to do this automatically for all the departments to create a single dataframe, because eventually I want to see how the number of items in a department is affecting the average error, and also be able to see the worst performing departments. Also, when I do a groupby('week_end_date'), the week_end_date becomes an index, whereas I would like it to be a field in the new dataframe, so that I can use it while plotting. Can someone please help me?

Body:
The csv (sample below) shows the absolute error for an item for a given week (week_end_date). As the csv shows, an item belongs to a department, and a department has multiple items:

What I want to do is to create a new dataframe which has the following fields:

mdse_dept_ref_i     week_end_date      average_ABSError      num_items_in_department

Here is what I am able to do:

new_df = df.loc[df['mdse_dept_ref_i'] == 47]
num_items = new_df.groupby('week_end_date').size()

avg_abs_error = new_df.groupby(['week_end_date'])['ABSError'].mean()
new_df = num_items.to_frame().join(avg_abs_error.to_frame())

But, I don't know how to do this automatically for all the departments to create a single dataframe, because eventually I want to see how the number of items in a department is affecting the average error, and also be able to see the worst performing departments. Also, when I do a groupby('week_end_date'), the week_end_date becomes an index, whereas I would like it to be a field in the new dataframe, so that I can use it while plotting. Can someone please help me?

Body:
I think you need groupby + agg, then rename columns and last join to original df:

df1 = df.groupby(['mdse_dept_ref_i','week_end_date'])['ABSError'].agg(['size','mean'])
d = {'size':'total', 'mean':'ABSError mean'}
df1 = df1.rename(columns=d)
print (df1)
                               total  ABSError mean
mdse_dept_ref_i week_end_date
47              3/25/17            3      39.988728
80              3/25/17            1       1.791748
204             3/25/17            1   12975.863000

df = df.join(df1, on=['mdse_dept_ref_i','week_end_date'])
print (df)
   mdse_item_i  mdse_clas_i  mdse_dept_ref_i  actual_sls week_end_date  \
0     19084539           30               47           0       3/25/17
1     19517957           43               47           3       3/25/17
2     19378250            0              204        1644       3/25/17
3     19704764           43               47           0       3/25/17
4     19119951            8               80          17       3/25/17

   rnn_fcst_sls forecast_release_date      ABSError  total  ABSError mean
0     48.520298               3/31/17     48.520298      3      39.988728
1     44.795605               3/31/17     41.795605      3      39.988728
2  14619.863000               3/31/17  12975.863000      1   12975.863000
3     29.650280               3/31/17     29.650280      3      39.988728
4     18.791748               3/31/17      1.791748      1       1.791748


问:
Python UTF8 encoding
I have looked at other questions around Python and encoding but not quite found the solution to my problem. Here it is:

I have a small script which attempts to compare 2 lists of files:

A list given in a text file, which is supposed to be encoded in UTF8 (at least Notepad++ detects it as such).

A list from a directory which I build like this:

```<code>local = [f.encode('utf-8') for f in listdir(dir) ]
</code>```

However, for some characters, I do not get the same representation: when looking in a HEX editor, I find that in 1, the  character é is given by 65 cc whereas in 2 it is given by c3 a9 ...

What I would like is to have them to the same encoding, whatever it is.

答:
At the top of your file add these

```<code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
</code>```

Hope this helps..!

Title: Python UTF8 encoding

Body:
I have looked at other questions around Python and encoding but not quite found the solution to my problem. Here it is:

I have a small script which attempts to compare 2 lists of files:

A list given in a text file, which is supposed to be encoded in UTF8 (at least Notepad++ detects it as such).

A list from a directory which I build like this:

local = [f.encode('utf-8') for f in listdir(dir) ]

However, for some characters, I do not get the same representation: when looking in a HEX editor, I find that in 1, the  character é is given by 65 cc whereas in 2 it is given by c3 a9 ...

What I would like is to have them to the same encoding, whatever it is.

Body:
At the top of your file add these

#!/usr/bin/env python
# -*- coding: utf-8 -*-

Hope this helps..!


问:
file upload script in php not working
My php code for file upload is not working. I have tried it in various ways. My code is given below:

HTML Code:

```<code><form action="assets/php/regc.php" method="POST" name="rform" enctype="multipart/form-data">
<input name="photo" type="file" placeholder="Attach Photo" required="required"/><br>
<input type="submit" value="upload" name="" />

</form>

PHP Code:
<?php
$pic=$_FILES["photo"]["name"];

$location="assets/";
$myfile= $location.basename($_FILES["photo"]["name"]);

if(isset($_FILES["photo"]["name"]))
{
    $ok=move_uploaded_file($_FILES["photo"]["tmp_name"], $myfile);
    if($ok)
    {
    echo "success";
    }

    else
    {
    echo "Failed";
    }
}
?>
</code>```

答:
Try This Way:</p>

```<code>    <?php
   if(isset($_FILES['image'])){
      $errors= array();
      $file_name = $_FILES['image']['name'];
      $file_size = $_FILES['image']['size'];
      $file_tmp = $_FILES['image']['tmp_name'];
      $file_type = $_FILES['image']['type'];
      $file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));

      $expensions= array("jpeg","jpg","png");

      if(in_array($file_ext,$expensions)=== false){
         $errors[]="extension not allowed, please choose a JPEG or PNG file.";
      }

      if($file_size > 2097152) {
         $errors[]='File size must be excately 2 MB';
      }

      if(empty($errors)==true) {
         move_uploaded_file($file_tmp,"images/".$file_name);
         echo "Success";
      }else{
         print_r($errors);
      }
   }
?>
<html>
   <body>

      <form action = "" method = "POST" enctype = "multipart/form-data">
         <input type = "file" name = "image" />
         <input type = "submit"/>

         <ul>
            <li>Sent file: <?php echo $_FILES['image']['name'];  ?>
            <li>File size: <?php echo $_FILES['image']['size'];  ?>
            <li>File type: <?php echo $_FILES['image']['type'] ?>
         </ul>

      </form>

   </body>
</html>
</code>```

Title: file upload script in php not working

Body:
My php code for file upload is not working. I have tried it in various ways. My code is given below:

HTML Code:

<form action="assets/php/regc.php" method="POST" name="rform" enctype="multipart/form-data">
<input name="photo" type="file" placeholder="Attach Photo" required="required"/>

<input type="submit" value="upload" name="" />

</form>

PHP Code:
<?php
$pic=$_FILES["photo"]["name"];

$location="assets/";
$myfile= $location.basename($_FILES["photo"]["name"]);

if(isset($_FILES["photo"]["name"]))
{
    $ok=move_uploaded_file($_FILES["photo"]["tmp_name"], $myfile);
    if($ok)
    {
    echo "success";
    }

    else
    {
    echo "Failed";
    }
}
?>

Body:
Try This Way:

    <?php
   if(isset($_FILES['image'])){
      $errors= array();
      $file_name = $_FILES['image']['name'];
      $file_size = $_FILES['image']['size'];
      $file_tmp = $_FILES['image']['tmp_name'];
      $file_type = $_FILES['image']['type'];
      $file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));

      $expensions= array("jpeg","jpg","png");

      if(in_array($file_ext,$expensions)=== false){
         $errors[]="extension not allowed, please choose a JPEG or PNG file.";
      }

      if($file_size > 2097152) {
         $errors[]='File size must be excately 2 MB';
      }

      if(empty($errors)==true) {
         move_uploaded_file($file_tmp,"images/".$file_name);
         echo "Success";
      }else{
         print_r($errors);
      }
   }
?>
<html>
   <body>

      <form action = "" method = "POST" enctype = "multipart/form-data">
         <input type = "file" name = "image" />
         <input type = "submit"/>

         <ul>
            <li>Sent file: <?php echo $_FILES['image']['name'];  ?>
            <li>File size: <?php echo $_FILES['image']['size'];  ?>
            <li>File type: <?php echo $_FILES['image']['type'] ?>
         </ul>

      </form>

   </body>
</html>


问:
How to add public API to a Rails app?
I'd like to open my Rails 2.3 app (hosted on Heroku) to developers. I thought of two ways of doing this:

Using the respond_to |format| of the app, and a before_filter only allowing authorized developers API keys

Using a second Heroku account dedicated to the API, sharing the original app's database. Now, what would be better: Rails, Sinatra, or Grape?

I know this is a vague question. Do you have any good articles or architectural patterns that could help me?

Thanks,

Kevin

答:
I would add a new route

website.com/api/widget/

website.com/api/another_service/

And make a controller where seems natural under the API rout.

I would then make a module with before filters that checked however you want to check API keys.

```<code>class WidgetController < ActionController::Base
    include 'api_keyable'
    :before_filer :validate_api_key

    def create
        #However you create a widget from the params.
        # respond to XML, YAML, JSON, whatever
    end

end
</code>```

if you later find you want to handle website.com/api/widgets on one app and website.com/api/wadgets on the other, your end users will never know and your code shouldn't need to change much.

Title: How to add public API to a Rails app?

Body:
I would add a new route

website.com/api/widget/

website.com/api/another_service/

And make a controller where seems natural under the API rout.

I would then make a module with before filters that checked however you want to check API keys.

class WidgetController < ActionController::Base
    include 'api_keyable'
    :before_filer :validate_api_key

    def create
        #However you create a widget from the params.
        # respond to XML, YAML, JSON, whatever
    end

end

if you later find you want to handle website.com/api/widgets on one app and website.com/api/wadgets on the other, your end users will never know and your code shouldn't need to change much.


问:
Sql conditional sum computation on other column value check
i have following sql query.

```<code>SELECT (SELECT ISNULL(SUM(Qty),0)
From Bills
JOIN BillMaster on Bills.BillNumber = BillMaster.BillNumber
where SessionID = '" + DBHandler.SessionID(Date) + "'
and BillMaster.ShiftID = " + SHiftID + "
and Bills.ProductID = products.id ) [qty],
products.price , products.name
FROM products.
</code>```

In "Bills" table there is column "isDeal". I want that sum will execute only when "isDeal" = 0
I attached Bills table screenshot in which it can be seen that there is column "isDeal"
and i am attaching output report where i want that when isDeal = 0 then sum will compute other wise sum shouldn't compute

so how can i compute this ?

答:
other method :</p>

```<code>SELECT ISNULL(f2.Qty, 0) qty, f1.price , f1.name
FROM products f1
outer apply
( select SUM(Qty) qty
  From Bills
  inner JOIN BillMaster on Bills.BillNumber = BillMaster.BillNumber
  where SessionID = '" + DBHandler.SessionID(Date) + "'
  and BillMaster.ShiftID = " + SHiftID + "
  and Bills.ProductID = f1.id and IsDeal =0
) f2
</code>```

Body:
i have following sql query.

SELECT (SELECT ISNULL(SUM(Qty),0)
From Bills
JOIN BillMaster on Bills.BillNumber = BillMaster.BillNumber
where SessionID = '" + DBHandler.SessionID(Date) + "'
and BillMaster.ShiftID = " + SHiftID + "
and Bills.ProductID = products.id ) [qty],
products.price , products.name
FROM products.

In "Bills" table there is column "isDeal". I want that sum will execute only when "isDeal" = 0
I attached Bills table screenshot in which it can be seen that there is column "isDeal"
and i am attaching output report where i want that when isDeal = 0 then sum will compute other wise sum shouldn't compute

so how can i compute this ?

Body:
other method :

SELECT ISNULL(f2.Qty, 0) qty, f1.price , f1.name
FROM products f1
outer apply
( select SUM(Qty) qty
  From Bills
  inner JOIN BillMaster on Bills.BillNumber = BillMaster.BillNumber
  where SessionID = '" + DBHandler.SessionID(Date) + "'
  and BillMaster.ShiftID = " + SHiftID + "
  and Bills.ProductID = f1.id and IsDeal =0
) f2


问:
WinForms, picturebox's image overlapping custom painted drawings
I have a custom user control with a picture box on it. Then, draw a circle on the control in Paint event.

```<code>var size = TextRenderer.MeasureText(this.UnreadCount.ToString(), lblDisplayname.Font);
var rec = new Rectangle(0, 0, size.Width, size.Width);
var smallFont = new Font(lblDisplayname.Font.Name, lblDisplayname.Font.Size - 1);
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.FormatFlags = StringFormatFlags.DirectionRightToLeft;
format.LineAlignment = StringAlignment.Center;

using (LinearGradientBrush b = new LinearGradientBrush(
    rec,
    Color.FromArgb(242, 37, 37),
    Color.FromArgb(178, 30, 30),
    45F))
{
    e.Graphics.FillEllipse(b, rec);
    e.Graphics.DrawString(this.UnreadCount.ToString(), smallFont, Brushes.White, rec, format);
}
</code>```

Then, later in the implementation, I set the image of the control's picture box.

```<code>MyControl ctrl = new MyControl();
ctrl.picImage.Image = Image.FromFile(imagePath);
ctrl.Refresh();
</code>```

The issue is that: the picture box's image overlap the drawn circle.
current issue
Requirement is that: The circle is needed to display fully overlapping the image. What might be causing my issue?

答:
The following fuction will return a user control with your requirements ,Posting the code for you to understand the parent child relationship.

Either the graphics has to be drawn on top of the image container or on another transparent container that is on top of the image.

The below sample has 2 panels ,panel1 and panel2 where panel 2 is a child of panel.
Panel1 is the background image and panel 2 has the graphics.Hope it helps.

```<code>    private UserControl create_MyControl( string  filenamepath)
    {
        //Create User Control

        UserControl MyControl = new UserControl();
        //Mention the size of control
        MyControl.Size = new Size(100, 100);
        //Create a panel to hold the background image that you wanted in the picture box
        Panel panel1 = new Panel();
        //dock the panel1 to fill the control background
        panel1.Dock = DockStyle.Fill;
        MyControl.Controls.Add(panel1);
        //Create another panel as overlay for panel1
        Panel panel2 = new Panel();
        //dock the panel2 to fill the panel1;
        panel2.Dock = DockStyle.Fill;
        //Add panel2 as child of panel1
        panel1.Controls.Add(panel2);
        //Set panel2 background as transparent
        panel2.BackColor = Color.Transparent;
        // To replicate the variables that you have!
        Label lblDisplayname = new Label();
        lblDisplayname.Font = new Font("Arial", 24, FontStyle.Regular);
        lblDisplayname.Size = panel2.Size;
        lblDisplayname.TextAlign = ContentAlignment.TopCenter;
        lblDisplayname.Text = "25";
        lblDisplayname.Dock = DockStyle.Fill;
        panel2.Controls.Add(lblDisplayname);

        panel1.BackgroundImage = Image.FromFile(filenamepath);
        panel1.BackgroundImageLayout = ImageLayout.Stretch;

        //In Panel2 paint event put your code for stuff
        panel2.Paint += (s, e) =>
        {

            var size = TextRenderer.MeasureText("Hello", lblDisplayname.Font);
            var rec = new Rectangle(0, 0, size.Width, size.Width);

            var smallFont = new Font(lblDisplayname.Font.Name, lblDisplayname.Font.Size - 1);
            StringFormat format = new StringFormat();
            format.Alignment = StringAlignment.Center;
            format.FormatFlags = StringFormatFlags.DirectionRightToLeft;
            format.LineAlignment = StringAlignment.Center;

            using (System.Drawing.Drawing2D.LinearGradientBrush b = new System.Drawing.Drawing2D.LinearGradientBrush(
                rec,
                Color.FromArgb(242, 37, 37),
                Color.FromArgb(178, 30, 30),
                45F))
            {
                e.Graphics.FillEllipse(b, rec);
                e.Graphics.DrawString("Hello", smallFont, Brushes.White, rec, format);
            }
        };

        return MyControl;
    }
</code>```

Body:
I have a custom user control with a picture box on it. Then, draw a circle on the control in Paint event.

var size = TextRenderer.MeasureText(this.UnreadCount.ToString(), lblDisplayname.Font);
var rec = new Rectangle(0, 0, size.Width, size.Width);
var smallFont = new Font(lblDisplayname.Font.Name, lblDisplayname.Font.Size - 1);
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.FormatFlags = StringFormatFlags.DirectionRightToLeft;
format.LineAlignment = StringAlignment.Center;

using (LinearGradientBrush b = new LinearGradientBrush(
    rec,
    Color.FromArgb(242, 37, 37),
    Color.FromArgb(178, 30, 30),
    45F))
{
    e.Graphics.FillEllipse(b, rec);
    e.Graphics.DrawString(this.UnreadCount.ToString(), smallFont, Brushes.White, rec, format);
}

Then, later in the implementation, I set the image of the control's picture box.

MyControl ctrl = new MyControl();
ctrl.picImage.Image = Image.FromFile(imagePath);
ctrl.Refresh();

The issue is that: the picture box's image overlap the drawn circle.
current issue
Requirement is that: The circle is needed to display fully overlapping the image. What might be causing my issue?

Body:
The following fuction will return a user control with your requirements ,Posting the code for you to understand the parent child relationship.

Either the graphics has to be drawn on top of the image container or on another transparent container that is on top of the image.

The below sample has 2 panels ,panel1 and panel2 where panel 2 is a child of panel.
Panel1 is the background image and panel 2 has the graphics.Hope it helps.

    private UserControl create_MyControl( string  filenamepath)
    {
        //Create User Control

        UserControl MyControl = new UserControl();
        //Mention the size of control
        MyControl.Size = new Size(100, 100);
        //Create a panel to hold the background image that you wanted in the picture box
        Panel panel1 = new Panel();
        //dock the panel1 to fill the control background
        panel1.Dock = DockStyle.Fill;
        MyControl.Controls.Add(panel1);
        //Create another panel as overlay for panel1
        Panel panel2 = new Panel();
        //dock the panel2 to fill the panel1;
        panel2.Dock = DockStyle.Fill;
        //Add panel2 as child of panel1
        panel1.Controls.Add(panel2);
        //Set panel2 background as transparent
        panel2.BackColor = Color.Transparent;
        // To replicate the variables that you have!
        Label lblDisplayname = new Label();
        lblDisplayname.Font = new Font("Arial", 24, FontStyle.Regular);
        lblDisplayname.Size = panel2.Size;
        lblDisplayname.TextAlign = ContentAlignment.TopCenter;
        lblDisplayname.Text = "25";
        lblDisplayname.Dock = DockStyle.Fill;
        panel2.Controls.Add(lblDisplayname);

        panel1.BackgroundImage = Image.FromFile(filenamepath);
        panel1.BackgroundImageLayout = ImageLayout.Stretch;

        //In Panel2 paint event put your code for stuff
        panel2.Paint += (s, e) =>
        {

            var size = TextRenderer.MeasureText("Hello", lblDisplayname.Font);
            var rec = new Rectangle(0, 0, size.Width, size.Width);

            var smallFont = new Font(lblDisplayname.Font.Name, lblDisplayname.Font.Size - 1);
            StringFormat format = new StringFormat();
            format.Alignment = StringAlignment.Center;
            format.FormatFlags = StringFormatFlags.DirectionRightToLeft;
            format.LineAlignment = StringAlignment.Center;

            using (System.Drawing.Drawing2D.LinearGradientBrush b = new System.Drawing.Drawing2D.LinearGradientBrush(
                rec,
                Color.FromArgb(242, 37, 37),
                Color.FromArgb(178, 30, 30),
                45F))
            {
                e.Graphics.FillEllipse(b, rec);
                e.Graphics.DrawString("Hello", smallFont, Brushes.White, rec, format);
            }
        };

        return MyControl;
    }


问:
Generate row table from this customised static row
I have some trouble tring to achieve the creation of one row from JS in my table. I do not know why?

My static row:

```<code><tr>
  <td>
    Bob
  </td>
  <td class="text-right text-nowrap">
    <button class="btn btn-xs btn-info">edit</button>
    <button class="btn btn-xs btn-warning">
      <span class="glyphicon glyphicon-trash"></span>
    </button>
  </td>
</tr>
</code>```

The second code is when generated in my add function:

```<code>let row = "<tr>"
    + "<td>"
       + "<a href='#'>"+ person.name +"</a>"
    + "</td>"
    + "<td class='text-right text-nowrap'>"
       +  "<button class='btn btn-xs btn-info'>edit</button>"
       +  "<button class='btn btn-xs btn-warning'>"
          +  "<span class='glyphicon glyphicon-trash'></span>"
       +  "</button>"
    +  "</td>"
    +  "</tr>"
</code>```

答:
There is no div around table rows. How are you accessing the table from Javascript. See the following snippet.

I have added

```<code><div id = "table">
</code>```

and used the

```<code>JQuery on ready function,
</code>```

to wait till the page loads,
and append the row to the proper table "div" using append function.

var row = "
" +
    ""
       + " Aadi "
    + "	"
    + ""
       +  "<button class='btn btn-xs btn-info'>edit</button>"
       +  "<button class='btn btn-xs btn-warning'>"
          +  ""
       +  "</button>"
    +  "	" + "
"

    $( document ).ready(function() {
        $('#table tbody').append(row);
    });

    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='table'>

<table>
 <tbody>
<tr>
  <td>
    Bob
  </td>
  <td class="text-right text-nowrap">
    <button class="btn btn-xs btn-info">edit</button>
    <button class="btn btn-xs btn-warning">
      <span class="glyphicon glyphicon-trash"></span>
    </button>
  </td>
</tr>
</tbody>
</table>
</div></code>```

Body:
I have some trouble tring to achieve the creation of one row from JS in my table. I do not know why?

My static row:

    Bob

    <button class="btn btn-xs btn-info">edit</button>
    <button class="btn btn-xs btn-warning">

    </button>

The second code is when generated in my add function:

let row = "
"
    + ""
       + ""+ person.name +""
    + "	"
    + ""
       +  "<button class='btn btn-xs btn-info'>edit</button>"
       +  "<button class='btn btn-xs btn-warning'>"
          +  ""
       +  "</button>"
    +  "	"
    +  "
"

Body:
There is no div around table rows. How are you accessing the table from Javascript. See the following snippet.

I have added

<div id = "table">

and used the

JQuery on ready function,

to wait till the page loads,
and append the row to the proper table "div" using append function.

var row = "<tr>" +
    "<td>"
       + "<a href='#'> Aadi </a>"
    + "</td>"
    + "<td class='text-right text-nowrap'>"
       +  "<button class='btn btn-xs btn-info'>edit</button>"
       +  "<button class='btn btn-xs btn-warning'>"
          +  "<span class='glyphicon glyphicon-trash'></span>"
       +  "</button>"
    +  "</td>" + "</tr>"

    $( document ).ready(function() {
        $('#table tbody').append(row);
    });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='table'>

<table>
 <tbody>
<tr>
  <td>
    Bob
  </td>
  <td class="text-right text-nowrap">
    <button class="btn btn-xs btn-info">edit</button>
    <button class="btn btn-xs btn-warning">
      <span class="glyphicon glyphicon-trash"></span>
    </button>
  </td>
</tr>
</tbody>
</table>
</div>


问:
Loop through fields when creating sqlalchemy object
I am trying to loop through a dict that I received via json and save the results to a database via sqlalchemy. I've kept the field names the same as the key names from the dict. It seems repetitive to list each field and dict over and over. But when I try to use something like c.keys() it does not work. If that were the case I could do:
    for key in c.keys():
        customer.key = c[key]

But that does not work. My current code is:

```<code>for c in response['Customers']:
    customer = Customer()
    customer.ID = c['ID']
    customer.Name = c['Name']
    customer.Currency = c['Currency']
    customer.PaymentTerm = c['PaymentTerm']
    customer.Discount = c['Discount']
    customer.TaxRule = c['TaxRule']
    customer.Carrier = c['Carrier']
    session.add(customer)
session.commit()
</code>```

答:
You could just unpack your dictionaries as arguments to __init__, given that you've not overridden the default constructor provided by Declarative that does exactly what the other answer does; it sets the attributes from the keyword arguments:

```<code>for c in response['Customers']:
    session.add(Customer(**c))

session.commit()
</code>```

Body:
I am trying to loop through a dict that I received via json and save the results to a database via sqlalchemy. I've kept the field names the same as the key names from the dict. It seems repetitive to list each field and dict over and over. But when I try to use something like c.keys() it does not work. If that were the case I could do:
    for key in c.keys():
        customer.key = c[key]

But that does not work. My current code is:

for c in response['Customers']:
    customer = Customer()
    customer.ID = c['ID']
    customer.Name = c['Name']
    customer.Currency = c['Currency']
    customer.PaymentTerm = c['PaymentTerm']
    customer.Discount = c['Discount']
    customer.TaxRule = c['TaxRule']
    customer.Carrier = c['Carrier']
    session.add(customer)
session.commit()

Body:
You could just unpack your dictionaries as arguments to __init__, given that you've not overridden the default constructor provided by Declarative that does exactly what the other answer does; it sets the attributes from the keyword arguments:

for c in response['Customers']:
    session.add(Customer(**c))

session.commit()


问:
How can I create a div in jQuery that I can scroll left to right in
I am creating a movie search engine. So far when I type in a movie into my input I receive a list of movies as shown in the screenshot below.

The way my movies are shown. I have to scroll down to see more

Instead I want my images to be represented similar to how they are in google.

The way google shows its movies. You have to scroll right to see more, but the page remains static, only the movies change as you scroll

Hopefully someone can help. Thanks in advance!

答:
 document.getElementById("content").style.overflowX = "scroll";
document.getElementById("content").style.width = "200px";```

Try this in your js.

Body:
 document.getElementById("content").style.overflowX = "scroll";
document.getElementById("content").style.width = "200px";

Try this in your js.