问:
CUDA/C - Using malloc in kernel functions gives strange results
I'm new to CUDA/C and new to stack overflow. This is my first question.

I'm trying to allocate memory dynamically in a kernel function, but the results are unexpected.
I read using malloc() in a kernel can lower performance a lot, but I need it anyway so I first tried with a simple int ** array just to test the possibility, then I'll actually need to allocate more complex structs.

In my main I used cudaMalloc() to allocate the space for the array of int *, and then I used malloc() for every thread in the kernel function to allocate the array for every index of the outer array. I then used another thread to check the result, but it doesn't always work.

Here's main code:

```<code>#define N_CELLE 1024*2
#define L_CELLE 512

extern "C" {

int main(int argc, char **argv) {
  int *result = (int *)malloc(sizeof(int));
  int *d_result;
  int size_numbers = N_CELLE * sizeof(int *);
  int **d_numbers;

  cudaMalloc((void **)&d_numbers, size_numbers);
  cudaMalloc((void **)&d_result, sizeof(int *));

  kernel_one<<<2, 1024>>>(d_numbers);
  cudaDeviceSynchronize();
  kernel_two<<<1, 1>>>(d_numbers, d_result);

  cudaMemcpy(result, d_result, sizeof(int), cudaMemcpyDeviceToHost);

  printf("%d\n", *result);

  cudaFree(d_numbers);
  cudaFree(d_result);
  free(result);
}

}
</code>```

I used extern "C"because I could't compile while importing my header, which is not used in this example code. I pasted it since I don't know if this may be relevant or not.

This is kernel_one code:

```<code>__global__ void kernel_one(int **d_numbers) {
  int i = threadIdx.x + blockIdx.x * blockDim.x;
  d_numbers[i] = (int *)malloc(L_CELLE*sizeof(int));
  for(int j=0; j<L_CELLE;j++)
    d_numbers[i][j] = 1;
}
</code>```

And this is kernel_two code:

```<code>__global__ void kernel_two(int **d_numbers, int *d_result) {
  int temp = 0;
  for(int i=0; i<N_CELLE; i++) {
    for(int j=0; j<L_CELLE;j++)
      temp += d_numbers[i][j];
  }
  *d_result = temp;
}
</code>```

Everything works fine (aka the count is correct) until I use less than 1024*2*512 total blocks in device memory. For example, if I #define N_CELLE 1024*4 the program starts giving "random" results, such as negative numbers.
Any idea of what the problem could be?
Thanks anyone!

答:
I don't know anything about CUDA but these are severe bugs:

You cannot convert from int** to void**. They are not compatible types. Casting doesn't solve the problem, but hides it.

&d_numbers gives the address of a pointer to pointer which is wrong. It is of type int***.

Both of the above bugs result in undefined behavior. If your program somehow seems to works in some condition, that's just by pure (bad) luck only.

Body:
I'm new to CUDA/C and new to stack overflow. This is my first question.

I'm trying to allocate memory dynamically in a kernel function, but the results are unexpected.
I read using malloc() in a kernel can lower performance a lot, but I need it anyway so I first tried with a simple int ** array just to test the possibility, then I'll actually need to allocate more complex structs.

In my main I used cudaMalloc() to allocate the space for the array of int *, and then I used malloc() for every thread in the kernel function to allocate the array for every index of the outer array. I then used another thread to check the result, but it doesn't always work.

Here's main code:

#define N_CELLE 1024*2
#define L_CELLE 512

extern "C" {

int main(int argc, char **argv) {
  int *result = (int *)malloc(sizeof(int));
  int *d_result;
  int size_numbers = N_CELLE * sizeof(int *);
  int **d_numbers;

  cudaMalloc((void **)&d_numbers, size_numbers);
  cudaMalloc((void **)&d_result, sizeof(int *));

  kernel_one<<<2, 1024>>>(d_numbers);
  cudaDeviceSynchronize();
  kernel_two<<<1, 1>>>(d_numbers, d_result);

  cudaMemcpy(result, d_result, sizeof(int), cudaMemcpyDeviceToHost);

  printf("%d\n", *result);

  cudaFree(d_numbers);
  cudaFree(d_result);
  free(result);
}

}

I used extern "C"because I could't compile while importing my header, which is not used in this example code. I pasted it since I don't know if this may be relevant or not.

This is kernel_one code:

__global__ void kernel_one(int **d_numbers) {
  int i = threadIdx.x + blockIdx.x * blockDim.x;
  d_numbers[i] = (int *)malloc(L_CELLE*sizeof(int));
  for(int j=0; j<L_CELLE;j++)
    d_numbers[i][j] = 1;
}

And this is kernel_two code:

__global__ void kernel_two(int **d_numbers, int *d_result) {
  int temp = 0;
  for(int i=0; i<N_CELLE; i++) {
    for(int j=0; j<L_CELLE;j++)
      temp += d_numbers[i][j];
  }
  *d_result = temp;
}

Everything works fine (aka the count is correct) until I use less than 1024*2*512 total blocks in device memory. For example, if I #define N_CELLE 1024*4 the program starts giving "random" results, such as negative numbers.
Any idea of what the problem could be?
Thanks anyone!


来源: stackexchange

问:
How do I reference the databound control from an ObjectDataSource event?
Take for example a DetailsView control with an ObjectDataSource as its datasource.

Normally in the DetailsView.ItemUpdated event I would grab a reference to the details view by casting the sender:

```<code>DetailsView dv = (DetailsView)sender;
</code>```

In certain situations it becomes necessary to handle the event inside the ObjectDataSource.ItemUpdated event. In this case sender is now of type ObjectDataSource. What I want to be able to do is write clean code that isnt hardcoded like

```<code>Label label1 = DetailsView1.FindControl("Label1");
</code>```

I looked over the documentation and also did some searches but couldnt find how I would write some code like the following:

```<code>protected void ObjectDataSource1_Inserted(object sender, ObjectDataSourceStatusEventArgs e)
{
   ObjectDataSource ods = (ObjectDataSource)sender;
   DetailsView dv = (DetailsView)ods.SOMETHING_HERE;
}
</code>```

Does anyone know what I should be putting in the SOMETHING_HERE in the snippet above?

答:
That's happen because the "OnInserted" event is suppose to be an event examine the values of a return value or output parameters, or to determine whether an exception was thrown after an Insert operation has completed. The return value, output parameters, and exception handling properties are available from the ObjectDataSourceStatusEventArgs object that is associated with the event.

What you can do here is just call ObjectDataSource.select() that returns the view in this case but I don't think it's a good choice.
You should review you business logic and try to manage it somewhere it makes more sense

Anyway your code should look like the below:

```<code>ObjectDataSource ods = YourDataSource.select();
DetailsView dv = (DetailsView)ods;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Take for example a DetailsView control with an ObjectDataSource as its datasource.

Normally in the DetailsView.ItemUpdated event I would grab a reference to the details view by casting the sender:

DetailsView dv = (DetailsView)sender;

In certain situations it becomes necessary to handle the event inside the ObjectDataSource.ItemUpdated event. In this case sender is now of type ObjectDataSource. What I want to be able to do is write clean code that isnt hardcoded like

Label label1 = DetailsView1.FindControl("Label1");

I looked over the documentation and also did some searches but couldnt find how I would write some code like the following:

protected void ObjectDataSource1_Inserted(object sender, ObjectDataSourceStatusEventArgs e)
{
   ObjectDataSource ods = (ObjectDataSource)sender;
   DetailsView dv = (DetailsView)ods.SOMETHING_HERE;
}

Does anyone know what I should be putting in the SOMETHING_HERE in the snippet above?

Body:
That's happen because the "OnInserted" event is suppose to be an event examine the values of a return value or output parameters, or to determine whether an exception was thrown after an Insert operation has completed. The return value, output parameters, and exception handling properties are available from the ObjectDataSourceStatusEventArgs object that is associated with the event.

What you can do here is just call ObjectDataSource.select() that returns the view in this case but I don't think it's a good choice.
You should review you business logic and try to manage it somewhere it makes more sense

Anyway your code should look like the below:

ObjectDataSource ods = YourDataSource.select();
DetailsView dv = (DetailsView)ods;


问:
How to Upload Any file from internal or External Storage in Xamarin?
I have written code for Picking Image & Uploading Image and getting a particular image with it's location in emulator but how do i access any file from Android File System using Xamarin so what should i use to do that ?.</p>

```<code>namespace XAFileUpload_2._0
{
    [Activity(Label = "XAFileUpload 2.0", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {

        //Pick Id to know the pick item no.
        public static readonly int PickImageId = 1000;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);

            Button button = FindViewById<Button>(Resource.Id.Browse);
            button.Click += BrowseButtonOnClick;

        }

        void BrowseButtonOnClick(object sender, EventArgs eventArs)
        {
            Intent = new Intent();
            Intent.SetType("image/*");
            Intent data = Intent.SetAction(Intent.ActionGetContent);

            try
            {
                StartActivityForResult(Intent.CreateChooser(Intent, "Select Picture"), PickImageId);
            }
            catch (ActivityNotFoundException ex)
            {
                Toast.MakeText(this, "Please install a File Manager.", ToastLength.Long).Show();
            }
            catch (Exception ex)
            {
                Toast.MakeText(this, "Error occured ", ToastLength.Long).Show();
            }
        }

        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            if ((requestCode == PickImageId) && (resultCode == Result.Ok) && (data != null))
            {
                UploadFile(data);

            }
        }

        void UploadFile(Intent data)
        {
            ICursor cursor = null;

            try
            {
                Button upButton = FindViewById<Button>(Resource.Id.Upload);

                // assuming image
                var docID = DocumentsContract.GetDocumentId(data.Data);
                var id = docID.Split(':')[1];
                var whereSelect = MediaStore.Images.ImageColumns.Id + "=?";
                var projections = new string[] { MediaStore.Images.ImageColumns.Data };
                // Try internal storage first
                cursor = ContentResolver.Query(MediaStore.Images.Media.InternalContentUri, projections, whereSelect, new string[] { id }, null);
                if (cursor.Count == 0)
                {
                    // not found on internal storage, try external storage
                    cursor = ContentResolver.Query(MediaStore.Images.Media.ExternalContentUri, projections, whereSelect, new string[] { id }, null);
                }
                var colData = cursor.GetColumnIndexOrThrow(MediaStore.Images.ImageColumns.Data);
                cursor.MoveToFirst();
                var fullPathToImage = cursor.GetString(colData);
                string fpti = cursor.GetString(colData);

                string address = "http://192.168.3.157:82/Values/DownFile";

                upButton.Click += (sender, args) =>
                {
                    try
                    {
                        ProgressDialog progressDialog = new ProgressDialog(this);
                        progressDialog.SetTitle("Please wait...");
                        progressDialog.SetCancelable(false);

                        Task.Run(() =>
                        {

                            RunOnUiThread(() =>
                            {
                                progressDialog.Show();
                            });

                            using (WebClient client = new WebClient())
                            {
                                client.UploadFile(address, fullPathToImage);

                            }

                            RunOnUiThread(() =>
                            {

                                progressDialog.Dismiss();

                                string msg = "Upload Completed";
                                Toast.MakeText(this, msg, ToastLength.Long).Show();

                            });
                        });
                    }
                    catch (Exception ex)
                    {
                        Log.Error("MediaPath", ex.Message);
                    }
                };
            }
            catch (Exception ex)
            {
                Log.Error("MediaPath", ex.Message);
            }
            finally
            {

                cursor?.Close();
                cursor?.Dispose();
            }
        }
    }
}
</code>```

答:
Have a look at the following:</p>

```<code>string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string filename = Path.Combine(path, "myfile.txt");

using (var streamWriter = new StreamWriter(filename, true))
{
    streamWriter.WriteLine(DateTime.UtcNow);
}

using (var streamReader = new StreamReader(filename))
{
    string content = streamReader.ReadToEnd();
    System.Diagnostics.Debug.WriteLine(content);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have written code for Picking Image & Uploading Image and getting a particular image with it's location in emulator but how do i access any file from Android File System using Xamarin so what should i use to do that ?.

namespace XAFileUpload_2._0
{
    [Activity(Label = "XAFileUpload 2.0", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {

        //Pick Id to know the pick item no.
        public static readonly int PickImageId = 1000;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);

            Button button = FindViewById<Button>(Resource.Id.Browse);
            button.Click += BrowseButtonOnClick;

        }

        void BrowseButtonOnClick(object sender, EventArgs eventArs)
        {
            Intent = new Intent();
            Intent.SetType("image/*");
            Intent data = Intent.SetAction(Intent.ActionGetContent);

            try
            {
                StartActivityForResult(Intent.CreateChooser(Intent, "Select Picture"), PickImageId);
            }
            catch (ActivityNotFoundException ex)
            {
                Toast.MakeText(this, "Please install a File Manager.", ToastLength.Long).Show();
            }
            catch (Exception ex)
            {
                Toast.MakeText(this, "Error occured ", ToastLength.Long).Show();
            }
        }

        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            if ((requestCode == PickImageId) && (resultCode == Result.Ok) && (data != null))
            {
                UploadFile(data);

            }
        }

        void UploadFile(Intent data)
        {
            ICursor cursor = null;

            try
            {
                Button upButton = FindViewById<Button>(Resource.Id.Upload);

                // assuming image
                var docID = DocumentsContract.GetDocumentId(data.Data);
                var id = docID.Split(':')[1];
                var whereSelect = MediaStore.Images.ImageColumns.Id + "=?";
                var projections = new string[] { MediaStore.Images.ImageColumns.Data };
                // Try internal storage first
                cursor = ContentResolver.Query(MediaStore.Images.Media.InternalContentUri, projections, whereSelect, new string[] { id }, null);
                if (cursor.Count == 0)
                {
                    // not found on internal storage, try external storage
                    cursor = ContentResolver.Query(MediaStore.Images.Media.ExternalContentUri, projections, whereSelect, new string[] { id }, null);
                }
                var colData = cursor.GetColumnIndexOrThrow(MediaStore.Images.ImageColumns.Data);
                cursor.MoveToFirst();
                var fullPathToImage = cursor.GetString(colData);
                string fpti = cursor.GetString(colData);

                string address = "http://192.168.3.157:82/Values/DownFile";

                upButton.Click += (sender, args) =>
                {
                    try
                    {
                        ProgressDialog progressDialog = new ProgressDialog(this);
                        progressDialog.SetTitle("Please wait...");
                        progressDialog.SetCancelable(false);

                        Task.Run(() =>
                        {

                            RunOnUiThread(() =>
                            {
                                progressDialog.Show();
                            });

                            using (WebClient client = new WebClient())
                            {
                                client.UploadFile(address, fullPathToImage);

                            }

                            RunOnUiThread(() =>
                            {

                                progressDialog.Dismiss();

                                string msg = "Upload Completed";
                                Toast.MakeText(this, msg, ToastLength.Long).Show();

                            });
                        });
                    }
                    catch (Exception ex)
                    {
                        Log.Error("MediaPath", ex.Message);
                    }
                };
            }
            catch (Exception ex)
            {
                Log.Error("MediaPath", ex.Message);
            }
            finally
            {

                cursor?.Close();
                cursor?.Dispose();
            }
        }
    }
}

Body:
Have a look at the following:

string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string filename = Path.Combine(path, "myfile.txt");

using (var streamWriter = new StreamWriter(filename, true))
{
    streamWriter.WriteLine(DateTime.UtcNow);
}

using (var streamReader = new StreamReader(filename))
{
    string content = streamReader.ReadToEnd();
    System.Diagnostics.Debug.WriteLine(content);
}


问:
How to show html table always on top
I am creating table

#myUL li a {
  background-color: #f6f6f6;
  padding: 5px;
  width: 100%;
  text-decoration: none;
  font-size: 14px;
  color: black;
  display: block;
}

#myUL li a.header {
  background-color: #e2e2e2;
  cursor: default;
}

#myUL li a:hover:not(.header) {
  background-color: #eee;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="myInput" list="myUL" onclick="openingList()" onkeyup="openingList()" style="width:90%; ">
<ul id="myUL" hidden=true>
  <li>

  </li>
</ul></code>```

On click of input tag is myUL is opening. Now I implemented this on the top of some box. Now the problem is when I am clicking, myUL is not displaying fully because it is getting hide because of box. How Can show this always on top.

Note :

Applying z-index is also not working.

Typing in input is also not working.

Can anybody help me to fix this.

答:
add</p>

```<code>#myUL li a {
    position: absolute;
}
</code>```

Title: How to show html table always on top

Body:
I am creating table

#myUL li a {
  background-color: #f6f6f6;
  padding: 5px;
  width: 100%;
  text-decoration: none;
  font-size: 14px;
  color: black;
  display: block;
}

#myUL li a.header {
  background-color: #e2e2e2;
  cursor: default;
}

#myUL li a:hover:not(.header) {
  background-color: #eee;
}

<input type="text" id="myInput" list="myUL" onclick="openingList()" onkeyup="openingList()" style="width:90%; ">

On click of input tag is myUL is opening. Now I implemented this on the top of some box. Now the problem is when I am clicking, myUL is not displaying fully because it is getting hide because of box. How Can show this always on top.

Note :

Applying z-index is also not working.

Typing in input is also not working.

Can anybody help me to fix this.

Body:
add

#myUL li a {
    position: absolute;
}


问:
ExpressJS change route without refresh
Hey I have a website run with Express.js and Handlebars that has a navbar and sidebar that stays the same for all the pages. When I route it only changes the page container which is {{{body}}}.

Is there a way I can just load the content of the routes without the page actually refreshing and reloading the nav and sidebar?

I'm currently using this for routing.

```<code>router.get('/', checkAuthentication, function(req, res){
  res.render('index');
});
</code>```

Any help would be nice as I'm quite new with node.

I want only the container to load not the whole url/page

答:
you can send the data you need to the client using:

res.send(JSON.stringify(Obj);```
</div>
</div>
</p>

<p>and in the ajax success function you need to:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>JSON.parse(dataSentFromServer);</code>```

and render the data using handlebars in the success function or another function that you call

Title: ExpressJS change route without refresh

Body:
Hey I have a website run with Express.js and Handlebars that has a navbar and sidebar that stays the same for all the pages. When I route it only changes the page container which is {{{body}}}.

Is there a way I can just load the content of the routes without the page actually refreshing and reloading the nav and sidebar?

I'm currently using this for routing.

router.get('/', checkAuthentication, function(req, res){
  res.render('index');
});

Any help would be nice as I'm quite new with node.

I want only the container to load not the whole url/page

Body:
you can send the data you need to the client using:

res.send(JSON.stringify(Obj);

and in the ajax success function you need to:

JSON.parse(dataSentFromServer);

and render the data using handlebars in the success function or another function that you call


问:
Python for starters - TypeError: '<' not supported between instances of 'str' and 'int'
Thank you so much for reading my first post.

Started learning Python 3.6.1 - got stuck at the starter - what's wrong with following code:

```<code>print('Hi there! What is your name?')
myName = input()
print("Hello "   +  myName +  ' its good to met you. My name is Kendo.')

print('how old are you?')
myAge = input()
if myAge < 15:
    print('go to bed, kiddo')
elif myAge > 95:
    print('Sup, grandma')
elif myAge > 1000:
    print('Lol, stop kidding me')
</code>```

答:
Input returns a string object in python 3. You are trying to see if a string is smaller or greater than an integer. This does not work.

from the python 3.6 documentation
https://docs.python.org/3/library/functions.html#input
input([prompt])
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

try:

```<code>myAge= int(myAge)
</code>```

Do however note that when when you give any non numerical character as input in the myAge = input()this will raise an other error. Since you can't force for non numerical characters into an integer.

Body:
Thank you so much for reading my first post.

Started learning Python 3.6.1 - got stuck at the starter - what's wrong with following code:

print('Hi there! What is your name?')
myName = input()
print("Hello "   +  myName +  ' its good to met you. My name is Kendo.')

print('how old are you?')
myAge = input()
if myAge < 15:
    print('go to bed, kiddo')
elif myAge > 95:
    print('Sup, grandma')
elif myAge > 1000:
    print('Lol, stop kidding me')

Body:
Input returns a string object in python 3. You are trying to see if a string is smaller or greater than an integer. This does not work.

from the python 3.6 documentation
https://docs.python.org/3/library/functions.html#input
input([prompt])
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.

try:

myAge= int(myAge)

Do however note that when when you give any non numerical character as input in the myAge = input()this will raise an other error. Since you can't force for non numerical characters into an integer.


问:
stored procedure returning value
using this code :

```<code>ALTER PROCEDURE [dbo].[get](@i int)
AS
BEGIN
    declare @ADate datetime
    select @ADate = ADate
    from table
    where i=@i
    and DateDiff(day ,getDate(), aDate  ) > 0
    and aDate is not null
    order by aDate asc
    return select @ADAte
END
</code>```

this returns 0 (or system 0 date time, which is not the desired result from the data base).

execute code

```<code>Declare @res datetime

exec @res = get 3

print @res
</code>```

why?

答:
Stored Procedures in SQL Server can only RETURN integers.  If you need to return anything other than a single integer, then you should use one of these methods (some explained by the previous answers):

Use a SELECT in your procedure

Use an OUTPUT Parameter

Use a User Defined Function instead

Title: stored procedure returning value

Body:
using this code :

ALTER PROCEDURE [dbo].[get](@i int)
AS
BEGIN
    declare @ADate datetime
    select @ADate = ADate
    from table
    where i=@i
    and DateDiff(day ,getDate(), aDate  ) > 0
    and aDate is not null
    order by aDate asc
    return select @ADAte
END

this returns 0 (or system 0 date time, which is not the desired result from the data base).

execute code

Declare @res datetime

exec @res = get 3

print @res

why?


问:
how get current text size in css
I'm tring to write a css that for all string that I can put on increase these strings about 3px. I don't know how can I do this, I think something like this:

```<code>.increaseSize {
getSize()+3px;
}
</code>```

Anyone can help me?

答:
You can use it like the following example:

div {
  font-size: 1em;
}
span.increase {
  font-size: calc(100% + 3px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  Hello <span class="increase">World</span>
</div></code>```

With the % unit you can get the actual font size of the element. Now you can use calc (browser compatibility) to add the 3px to the current font-size.

You shouldn't calculate the font-size yourself for responsive web-design. You can / should use relative units like em, rem or % to achieve responsive font-size.

Title: how get current text size in css

Body:
I'm tring to write a css that for all string that I can put on increase these strings about 3px. I don't know how can I do this, I think something like this:

.increaseSize {
getSize()+3px;
}

Anyone can help me?

Body:
You can use it like the following example:

div {
  font-size: 1em;
}
span.increase {
  font-size: calc(100% + 3px);
}

<div>
  Hello <span class="increase">World</span>
</div>

With the % unit you can get the actual font size of the element. Now you can use calc (browser compatibility) to add the 3px to the current font-size.

You shouldn't calculate the font-size yourself for responsive web-design. You can / should use relative units like em, rem or % to achieve responsive font-size.


问:
set content-type to utf-8 with angularjs $http
I'm uploading a form with files, text etc to the appengine blobstore:

```<code>$http({
    method: 'POST',
    url: the_url,
    transformRequest: formDataObject,
    data: event,
    headers: {'Content-Type': undefined}
})
</code>```

The request sends successfully with the follwing header:

```<code>Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryYeRxOO7y3qHNWd83
</code>```

When I try setting the content-type to "multipart/form-data;charset=UTF-8" I lose the boundary and get an error in the response: Bad content type. Please use multipart.

What is the correct way to add the UTF-8 charset?

答:
the charset must be set after all like:
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryYeRxOO7y3qHNWd83; charset=UTF-8</p>

Body:
I'm uploading a form with files, text etc to the appengine blobstore:

$http({
    method: 'POST',
    url: the_url,
    transformRequest: formDataObject,
    data: event,
    headers: {'Content-Type': undefined}
})

The request sends successfully with the follwing header:

Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryYeRxOO7y3qHNWd83

When I try setting the content-type to "multipart/form-data;charset=UTF-8" I lose the boundary and get an error in the response: Bad content type. Please use multipart.

What is the correct way to add the UTF-8 charset?


问:
Do I need to add thread locking to simple variables?
Let's say I have an object for which multiple threads can read/write to the state and someValue variables. Do I need to add locking if these variables are types like int, double, enums etc.?

```<code>enum State: String {
  case one
  case two
}

class Object {
  var state: State
  var someValue: Double
}
</code>```

答:
Yes you do.

Imagine the situation where two threads are trying to add 1 to someValue. A thread does this by:

read someValue into a register

Add 1

write someValue back

If both threads do operation 1 before either does operation 3, you will get a different answer than if one thread does all three operations before the other thread does operation 1.

There are also more subtle issues, in that an optimising compiler might not write the modified value back from the register for some time - if at all. Also, modern CPUs have multiple cores each with its own cache. The CPU writing a value back to memory doesn't guarantee it gets to memory straight away. It may just get as far as the core's cache. You need what's called a memory barrier to ensure that everything gets neatly written back to main memory.

On the larger scale, you'll need locking to ensure consistency between the variables in your class. So, if the state is meant to represent some property of someValue e.g. is it an integer or not, you'll need locking to ensure everybody always has a consistent view i.e.

modify someValue

test the new value

set state accordingly.

The above three operations have to appear to be atomic, or if the object is examined after operation 1 but before operation 3, it will be in an inconsistent state.

Body:
Let's say I have an object for which multiple threads can read/write to the state and someValue variables. Do I need to add locking if these variables are types like int, double, enums etc.?

enum State: String {
  case one
  case two
}

class Object {
  var state: State
  var someValue: Double
}


问:
Angular2 Hashtag routing to Anchor doesnt move page
So I used the following post to figure out how to add a fragment to the url.

Angular2 Routing with Hashtag to page anchor

And the fragment gets added fine, however the page doesn't move to the resulting anchor. I have tried using both the name and id attribute on the destination div, but neither seem to work.

I'm using Angular Version 2.0.0-rc.3, and router version 3.0.0-alpha.6.

Thanks!

```<code><a [routerLink]="[]" fragment="destination">Go TO DIV</a>

<div id='destination'>
    <h2>Destination</h2>
</div>
</code>```

There is enough space between the 2 elements to tell if the page actually moves.

And as said before, the url correctly adds #destination to itself.

答:
This workaround should do the trick</p>

```<code><div [routerLink]="[]" fragment="destination">
  <a href="#destination">Go TO DIV</a>
</div>
</code>```

Body:
So I used the following post to figure out how to add a fragment to the url.

Angular2 Routing with Hashtag to page anchor

And the fragment gets added fine, however the page doesn't move to the resulting anchor. I have tried using both the name and id attribute on the destination div, but neither seem to work.

I'm using Angular Version 2.0.0-rc.3, and router version 3.0.0-alpha.6.

Thanks!

Go TO DIV

Destination

There is enough space between the 2 elements to tell if the page actually moves.

And as said before, the url correctly adds #destination to itself.

Body:
This workaround should do the trick

<div [routerLink]="[]" fragment="destination">
  <a href="#destination">Go TO DIV</a>
</div>


问:
What is cost function in neural network?
Could someone please explain to me why it is so important the cost function in a neural network, what is its purpose?

Note: I'm just introducing me to the subject of neural networks, but failed to understand it perfectly.

答: Cost function returns a scalar value called 'cost' , that tells how good or bad your model is. There are several cost functions that can be used. Less cost represent a good model. The reason cost functions are used in neural networks is that 'cost is used by models to improve' </p>


问:
SharePoint 2013 people picker retrieves user's old information
I have imported users from AD and keep syncing them for a while. Today two of users' display names have been changed on AD and SharePoint synced them correctly. Just to be sure, I checked users from User Profile Service App which looks OK. New names are appearing correctly.

Yet when I try to add a list item and select user from people picker, I get old user info. This also happens when I try to insert a list item programmatically.

Tried to delete users from SharePoint, however I still get same old users. Do you have any idea for solving this situation?

Thanks in advance.

答: I found the solution. There was an another User Profile Service Application which was not used and not properly configured. Weird point is, that malconfigured app was not listed on service applications. I found it by using Get-SPServiceApplication cmdlet and removed it. After removal, did a full synchronization and voila! Now I can get current information.


问:
ko.utils.arrayFirst = function (array, predicate, predicateOwner) { /* .. */ }
what does predicateOwner mean , i couldn't find an answer ?!

like this:

How to use indexOf in KnockoutJS

or that

https://gist.github.com/hyle/8840a083bcd1325a59ca

答:
Last parameter of arrayFirst - is context that would be assigned to predicate's scope:

var array = ko.observableArray([1,2,3]);
var context = "Hello";
var result = ko.utils.arrayFirst(array(), function(item) {
  // 'this' is equal 'context'
  console.log(this);
  return item === 2;
}, context);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script></code>```

Body:
Last parameter of arrayFirst - is context that would be assigned to predicate's scope:

var array = ko.observableArray([1,2,3]);
var context = "Hello";
var result = ko.utils.arrayFirst(array(), function(item) {
  // 'this' is equal 'context'
  console.log(this);
  return item === 2;
}, context);

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>


问:
Android Studio cannot resolve symbol byteArrayInputStream
I have a method that looks like this:

```<code>public void init(byte[] signedPDF) throws IOException {
    doc = PDDocument.load(new byteArrayInputStream(signedPDF));
}
</code>```

Android Studio displays an error: Cannot resolve symbol byteArrayInputStream.

I tried adding the import manually:

```<code>import java.io.ByteArrayInputStream;
</code>```

Yet, it is greyed out and still not working.

I tried restarting Andorid Studio, cleaning, building project again.

I even tried ivalidate cahches/Restart from the File menu.

Nothing works.

I read all the related posts on stackoverflow and nothing seems to help.

EDIT:

Thanks to @ImAtWar for pointing out at my mistake.

Look at his answer.

It should have been doc = PDDocument.load(new ByteArrayInputStream(signedPDF));

Notice the capital B in ByteArrayInputStream.

I made the mistake because I'm used to using Eclipse which is not case sensitive when doing auto-complete. So, when the ByteArrayInputStream class didn't show up on auto-complete I decided to type it manually and made a mistake.

答:
Shouldnt it be new ByteArrayInputStream?

All the classes, interfaces, packages, methods and fields of java programming language are given according to java naming convention.

In Standard Java naming conventions Objects and class names should start with uppercase character.

Body:
I have a method that looks like this:

public void init(byte[] signedPDF) throws IOException {
    doc = PDDocument.load(new byteArrayInputStream(signedPDF));
}

Android Studio displays an error: Cannot resolve symbol byteArrayInputStream.

I tried adding the import manually:

import java.io.ByteArrayInputStream;

Yet, it is greyed out and still not working.

I tried restarting Andorid Studio, cleaning, building project again.

I even tried ivalidate cahches/Restart from the File menu.

Nothing works.

I read all the related posts on stackoverflow and nothing seems to help.

EDIT:

Thanks to @ImAtWar for pointing out at my mistake.

Look at his answer.

It should have been doc = PDDocument.load(new ByteArrayInputStream(signedPDF));

Notice the capital B in ByteArrayInputStream.

I made the mistake because I'm used to using Eclipse which is not case sensitive when doing auto-complete. So, when the ByteArrayInputStream class didn't show up on auto-complete I decided to type it manually and made a mistake.


问:
About object's property name
How to add a property to an object when the property name come from a var?</p>

```<code>var obj={};
var propName="realName";
obj.propName; //wrong
obj."realName"; //wrong
</code>```

答:
You can use square bracket notation:</p>

```<code>var obj = {};
var propName = "realName";
obj[propName] = "foo";  // Same as `obj.realName = "foo";`
</code>```

Title: About object's property name

Body:
How to add a property to an object when the property name come from a var?

var obj={};
var propName="realName";
obj.propName; //wrong
obj."realName"; //wrong

Body:
You can use square bracket notation:

var obj = {};
var propName = "realName";
obj[propName] = "foo";  // Same as `obj.realName = "foo";`


问:
Clear padding in column product info Bootstrap 3
I have site and using Bootstrap 3. I have problem with my product grid. I need to remove padding from my product list.
www.shop11.kg
Sorry my English.
Thanks

```<code><div class="tab-content">
<!-- Start gridview products -->
<div id="grid-view" class="tab-pane fade in active" role="tabpanel">
    <div class="row">
        <!-- Start Single profuct -->
        <div class="col-md-3 col-sm-4 col-lg-3 col-xs-12">
            <div class="single-product">
                <div class="product-thumb">
                    <a href="/product/1264">
                        <img class="front-img" src="/public/images/noimage/noimage_262.jpeg" alt="img">
                    </a>
                </div>
                <div class="product-info">
                    <div class="pro-title">
                        <h4>
                            <a href="/product/1264" title="ARIEL COLOR Стиральный порошок для цветного белья автомат 15 кг ">
                                ARIEL COLOR Стиральный порошок для цветного белья автомат 15 кг
                            </a>
                        </h4>
                    </div>
                    <div class="pro-price-ratting">
                        <div class="price-box">
                            <span class="price">1580 сом</span>
                        </div>
                    </div>
                    <div class="product-action">
                        <a href="javascript:void(0);" class="pro-btn add-to-cart">Купить</a>
                    </div>
                </div>
            </div>
        </div>
        <!-- End Single profuct -->
    </div>
</div>
<!-- End gridview products -->
</code>```

答:
You can give css like

```<code>.cp-right-products .tab-pane .col-md-3:nth-child(4n+1) {
  clear: both;
}
</code>```

in tablet view you can give css like

```<code>.cp-right-products .tab-pane .col-md-3:nth-child(3n+1) {
  clear: both;
}
</code>```

then all items will be arrange properly.

Body:
I have site and using Bootstrap 3. I have problem with my product grid. I need to remove padding from my product list.
www.shop11.kg
Sorry my English.
Thanks

                                ARIEL COLOR Стиральный порошок для цветного белья автомат 15 кг

                            1580 сом

                        Купить

Body:
You can give css like

.cp-right-products .tab-pane .col-md-3:nth-child(4n+1) {
  clear: both;
}

in tablet view you can give css like

.cp-right-products .tab-pane .col-md-3:nth-child(3n+1) {
  clear: both;
}

then all items will be arrange properly.


问:
Serial Port Data Received Event Handler Reliability
I am using the Serial Port functionality in C# to communicate with a piece of hardware. Everything writes fine to the serial port, and the serial port is always connected.

For some reason the Serial Port Data Received Handler doesn't always read data coming up (every 1 out of 8 times it fails to read anything or call the event function itself). Everything is fine on the other side. I am only receiving one letter from the serial port which is 1, 2, 3, etc

Here is my code:

Serial Setup:

```<code>    //Create new serial port
    SerialPort SerPort = new SerialPort("COM4");

    private void SetupSerial()
    {
        SerPort.BaudRate = 9600;
        SerPort.Parity = Parity.None;
        SerPort.StopBits = StopBits.One;
        SerPort.DataBits = 8;
        SerPort.Handshake = Handshake.None;
        SerPort.ReadTimeout = 4000;
        SerPort.WriteTimeout = 6000;
        SerPort.Open();
        SerPort.DataReceived += new SerialDataReceivedEventHandler(HandleSerialData);

        lblStatus.Text = "Successfully connected to COM port with no errors!";

    }
</code>```

My Write to Serial function:

```<code>       private void WriteToSerial( string data )
    {
        byte[] MyMessage = Encoding.UTF8.GetBytes(data);
        SerPort.Write(MyMessage, 0, MyMessage.Length);

        string time = "[" + DateTime.Now.ToString("HH:mm") + "]";

        bool debug = chkDebug.Checked;
        if (debug ) f.DebugText = time + " Wrote bytes to serial: " + data;
    }
</code>```

My Recieve event function:

```<code>    //Called everytime serial data is recieved
    private void HandleSerialData(object sender, SerialDataReceivedEventArgs e)
    {
        try
        {
            //Store recieved data in variable
            SerialPort sp = (SerialPort)sender;
            string data = sp.ReadExisting().ToString();

            bool debug = chkDebug.Checked;

            string time = "[" + DateTime.Now.ToString("HH:mm") + "]";
            if( debug ) f.DebugText = time + " Recieved serial data: " + data;

            switch ( data )
            {
                case "1":
                //If Battery is already on
                if( Battery1[0] == "ON")
                {
                    Battery1[0] = "OFF"; //ON or OFF
                    Battery1[2] = DateTime.Now.ToString("h:mm tt"); //End time
                    WriteLogFile("1");
                    lblST1.Text = "n/a";
                    lblET1.Text = "n/a";
                    if (debug) f.DebugText = time + " Battery 1 testing switched OFF.";
                }
                else
                {
                    Battery1[0] = "ON"; //ON or OFF
                    Battery1[1] = DateTime.Now.ToString("h:mm tt"); //Start time
                    Battery1[5] = DateTime.Now.ToString("d/MM/yyyy"); //Start date
                    plcRespond = true;
                    lblST1.Text = Battery1[1];
                        if (debug) f.DebugText = time + " Battery 1 testing switched ON.";
                }
                break;

                case "2":
                //If Battery is already on
                if (Battery2[0] == "ON")
                {
                    Battery2[0] = "OFF";
                    Battery2[2] = DateTime.Now.ToString("h:mm tt"); //End time
                    WriteLogFile("2");
                    lblST2.Text = "n/a";
                    lblET2.Text = "n/a";
                        if (debug) f.DebugText = time + " Battery 2 testing switched OFF.";
                }
                else
                {
                    Battery2[0] = "ON"; //ON or OFF
                    Battery2[1] = DateTime.Now.ToString("h:mm tt"); //Start time
                    Battery2[5] = DateTime.Now.ToString("d/MM/yyyy"); //Start date
                    plcRespond = true;
                    lblST2.Text = Battery2[1];
                        if (debug) f.DebugText = time + " Battery 2 testing switched ON.";
                }
                break;

                case "3":
                //If Battery is already on
                if (Battery3[0] == "ON")
                {
                    Battery3[0] = "OFF"; //ON or OFF
                    Battery3[2] = DateTime.Now.ToString("h:mm tt"); //End time
                    WriteLogFile("3");
                    lblST3.Text = "n/a";
                    lblET3.Text = "n/a";
                        if (debug) f.DebugText = time + " Battery 3 testing switched OFF.";
                }
                else
                {
                    Battery3[0] = "ON"; //ON or OFF
                    Battery3[1] = DateTime.Now.ToString("h:mm tt"); //Start time
                    Battery3[5] = DateTime.Now.ToString("d/MM/yyyy"); //Start date
                    plcRespond = true;
                    lblST3.Text = Battery3[1];
                        if (debug) f.DebugText = time + " Battery 3 testing switched ON.";
                }
                break;

                case "4":
                //If Battery is already on
                if (Battery4[0] == "ON")
                {
                    Battery4[0] = "OFF"; //ON or OFF
                    Battery4[2] = DateTime.Now.ToString("h:mm tt"); //End time
                    WriteLogFile("4");
                    lblST4.Text = "n/a";
                    lblET4.Text = "n/a";
                        if (debug) f.DebugText = time + " Battery 4 testing switched OFF.";
                }
                else
                {
                    Battery4[0] = "ON"; //ON or OFF
                    Battery4[1] = DateTime.Now.ToString("h:mm tt"); //Start time
                    Battery4[5] = DateTime.Now.ToString("d/MM/yyyy"); //Start date
                    plcRespond = true;
                    lblST4.Text = Battery4[1];
                        if (debug) f.DebugText = time + " Battery 4 testing switched ON.";
                }
                break;

                case "5":
                //If Battery is already on
                if (Battery5[0] == "ON")
                {
                    Battery5[0] = "OFF"; //ON or OFF
                    Battery5[2] = DateTime.Now.ToString("h:mm tt"); //End time
                    WriteLogFile("5");
                    lblST5.Text = "n/a";
                    lblET5.Text = "n/a";
                        if (debug) f.DebugText = time + " Battery 5 testing switched OFF.";
                    }
                else
                {
                    Battery5[0] = "ON"; //ON or OFF
                    Battery5[1] = DateTime.Now.ToString("h:mm tt"); //Start time
                    Battery5[5] = DateTime.Now.ToString("d/MM/yyyy"); //Start date
                    plcRespond = true;
                    lblST5.Text = Battery5[1];
                        if (debug) f.DebugText = time + " Battery 5 testing switched ON.";
                }
                break;

                case "6":
                //If Battery is already on
                if (Battery6[0] == "ON")
                {
                    Battery6[0] = "OFF"; //ON or OFF
                    Battery6[2] = DateTime.Now.ToString("h:mm tt"); //End time
                    WriteLogFile("6");
                    lblST6.Text = "n/a";
                    lblET6.Text = "n/a";
                        if (debug) f.DebugText = time + " Battery 6 testing switched OFF.";
                }
                else
                {
                    Battery6[0] = "ON"; //ON or OFF
                    Battery6[1] = DateTime.Now.ToString("h:mm tt"); //Start time
                    Battery6[5] = DateTime.Now.ToString("d/MM/yyyy"); //Start date
                    plcRespond = true;
                    lblST6.Text = Battery6[1];
                        if (debug) f.DebugText = time + " Battery 6 testing switched ON.";
                }
                break;
            }

            SerPort.DiscardInBuffer();
            SerPort.DiscardOutBuffer();

        }
        catch (Exception ex)
        {
            MessageBox.Show("Error recieving COM data! " + ex.Message);
        }
    }
</code>```

Is there a better way of reading serial data not using the ReadExisting? Or using a more reliable function?

答:
I have had problem in the past with ReadExisting. I don't know what happens in ReadExisting if more data arrives while the buffer is being read.

In serial port even handlers I use the following code. Because it determines the length to read first, new data arriving will be read during the next function call so the buffer can be emptied at the rate data is sent.

```<code>private void HandleSerialData(object sender, SerialDataReceivedEventArgs e)
{
    int lengthToRead = sp.BytesToRead;
    byte[] rxBytes = new byte[lengthToRead];
    sp.Read(rxBytes, 0, lengthToRead);
    functionThatInterpratesData(rxBytes);
}
</code>```

This also has the benefit of being re-usable because you convert the byte array to a string or however you have encoded it separately.

I would create a function to convert you byte array to a string (lots of examples on SO) and another one to handle the case statement.

Body:
I am using the Serial Port functionality in C# to communicate with a piece of hardware. Everything writes fine to the serial port, and the serial port is always connected.

For some reason the Serial Port Data Received Handler doesn't always read data coming up (every 1 out of 8 times it fails to read anything or call the event function itself). Everything is fine on the other side. I am only receiving one letter from the serial port which is 1, 2, 3, etc

Here is my code:

Serial Setup:

    //Create new serial port
    SerialPort SerPort = new SerialPort("COM4");

    private void SetupSerial()
    {
        SerPort.BaudRate = 9600;
        SerPort.Parity = Parity.None;
        SerPort.StopBits = StopBits.One;
        SerPort.DataBits = 8;
        SerPort.Handshake = Handshake.None;
        SerPort.ReadTimeout = 4000;
        SerPort.WriteTimeout = 6000;
        SerPort.Open();
        SerPort.DataReceived += new SerialDataReceivedEventHandler(HandleSerialData);

        lblStatus.Text = "Successfully connected to COM port with no errors!";

    }

My Write to Serial function:

       private void WriteToSerial( string data )
    {
        byte[] MyMessage = Encoding.UTF8.GetBytes(data);
        SerPort.Write(MyMessage, 0, MyMessage.Length);

        string time = "[" + DateTime.Now.ToString("HH:mm") + "]";

        bool debug = chkDebug.Checked;
        if (debug ) f.DebugText = time + " Wrote bytes to serial: " + data;
    }

My Recieve event function:

    //Called everytime serial data is recieved
    private void HandleSerialData(object sender, SerialDataReceivedEventArgs e)
    {
        try
        {
            //Store recieved data in variable
            SerialPort sp = (SerialPort)sender;
            string data = sp.ReadExisting().ToString();

            bool debug = chkDebug.Checked;

            string time = "[" + DateTime.Now.ToString("HH:mm") + "]";
            if( debug ) f.DebugText = time + " Recieved serial data: " + data;

            switch ( data )
            {
                case "1":
                //If Battery is already on
                if( Battery1[0] == "ON")
                {
                    Battery1[0] = "OFF"; //ON or OFF
                    Battery1[2] = DateTime.Now.ToString("h:mm tt"); //End time
                    WriteLogFile("1");
                    lblST1.Text = "n/a";
                    lblET1.Text = "n/a";
                    if (debug) f.DebugText = time + " Battery 1 testing switched OFF.";
                }
                else
                {
                    Battery1[0] = "ON"; //ON or OFF
                    Battery1[1] = DateTime.Now.ToString("h:mm tt"); //Start time
                    Battery1[5] = DateTime.Now.ToString("d/MM/yyyy"); //Start date
                    plcRespond = true;
                    lblST1.Text = Battery1[1];
                        if (debug) f.DebugText = time + " Battery 1 testing switched ON.";
                }
                break;

                case "2":
                //If Battery is already on
                if (Battery2[0] == "ON")
                {
                    Battery2[0] = "OFF";
                    Battery2[2] = DateTime.Now.ToString("h:mm tt"); //End time
                    WriteLogFile("2");
                    lblST2.Text = "n/a";
                    lblET2.Text = "n/a";
                        if (debug) f.DebugText = time + " Battery 2 testing switched OFF.";
                }
                else
                {
                    Battery2[0] = "ON"; //ON or OFF
                    Battery2[1] = DateTime.Now.ToString("h:mm tt"); //Start time
                    Battery2[5] = DateTime.Now.ToString("d/MM/yyyy"); //Start date
                    plcRespond = true;
                    lblST2.Text = Battery2[1];
                        if (debug) f.DebugText = time + " Battery 2 testing switched ON.";
                }
                break;

                case "3":
                //If Battery is already on
                if (Battery3[0] == "ON")
                {
                    Battery3[0] = "OFF"; //ON or OFF
                    Battery3[2] = DateTime.Now.ToString("h:mm tt"); //End time
                    WriteLogFile("3");
                    lblST3.Text = "n/a";
                    lblET3.Text = "n/a";
                        if (debug) f.DebugText = time + " Battery 3 testing switched OFF.";
                }
                else
                {
                    Battery3[0] = "ON"; //ON or OFF
                    Battery3[1] = DateTime.Now.ToString("h:mm tt"); //Start time
                    Battery3[5] = DateTime.Now.ToString("d/MM/yyyy"); //Start date
                    plcRespond = true;
                    lblST3.Text = Battery3[1];
                        if (debug) f.DebugText = time + " Battery 3 testing switched ON.";
                }
                break;

                case "4":
                //If Battery is already on
                if (Battery4[0] == "ON")
                {
                    Battery4[0] = "OFF"; //ON or OFF
                    Battery4[2] = DateTime.Now.ToString("h:mm tt"); //End time
                    WriteLogFile("4");
                    lblST4.Text = "n/a";
                    lblET4.Text = "n/a";
                        if (debug) f.DebugText = time + " Battery 4 testing switched OFF.";
                }
                else
                {
                    Battery4[0] = "ON"; //ON or OFF
                    Battery4[1] = DateTime.Now.ToString("h:mm tt"); //Start time
                    Battery4[5] = DateTime.Now.ToString("d/MM/yyyy"); //Start date
                    plcRespond = true;
                    lblST4.Text = Battery4[1];
                        if (debug) f.DebugText = time + " Battery 4 testing switched ON.";
                }
                break;

                case "5":
                //If Battery is already on
                if (Battery5[0] == "ON")
                {
                    Battery5[0] = "OFF"; //ON or OFF
                    Battery5[2] = DateTime.Now.ToString("h:mm tt"); //End time
                    WriteLogFile("5");
                    lblST5.Text = "n/a";
                    lblET5.Text = "n/a";
                        if (debug) f.DebugText = time + " Battery 5 testing switched OFF.";
                    }
                else
                {
                    Battery5[0] = "ON"; //ON or OFF
                    Battery5[1] = DateTime.Now.ToString("h:mm tt"); //Start time
                    Battery5[5] = DateTime.Now.ToString("d/MM/yyyy"); //Start date
                    plcRespond = true;
                    lblST5.Text = Battery5[1];
                        if (debug) f.DebugText = time + " Battery 5 testing switched ON.";
                }
                break;

                case "6":
                //If Battery is already on
                if (Battery6[0] == "ON")
                {
                    Battery6[0] = "OFF"; //ON or OFF
                    Battery6[2] = DateTime.Now.ToString("h:mm tt"); //End time
                    WriteLogFile("6");
                    lblST6.Text = "n/a";
                    lblET6.Text = "n/a";
                        if (debug) f.DebugText = time + " Battery 6 testing switched OFF.";
                }
                else
                {
                    Battery6[0] = "ON"; //ON or OFF
                    Battery6[1] = DateTime.Now.ToString("h:mm tt"); //Start time
                    Battery6[5] = DateTime.Now.ToString("d/MM/yyyy"); //Start date
                    plcRespond = true;
                    lblST6.Text = Battery6[1];
                        if (debug) f.DebugText = time + " Battery 6 testing switched ON.";
                }
                break;
            }

            SerPort.DiscardInBuffer();
            SerPort.DiscardOutBuffer();

        }
        catch (Exception ex)
        {
            MessageBox.Show("Error recieving COM data! " + ex.Message);
        }
    }

Is there a better way of reading serial data not using the ReadExisting? Or using a more reliable function?

Body:
I have had problem in the past with ReadExisting. I don't know what happens in ReadExisting if more data arrives while the buffer is being read.

In serial port even handlers I use the following code. Because it determines the length to read first, new data arriving will be read during the next function call so the buffer can be emptied at the rate data is sent.

private void HandleSerialData(object sender, SerialDataReceivedEventArgs e)
{
    int lengthToRead = sp.BytesToRead;
    byte[] rxBytes = new byte[lengthToRead];
    sp.Read(rxBytes, 0, lengthToRead);
    functionThatInterpratesData(rxBytes);
}

This also has the benefit of being re-usable because you convert the byte array to a string or however you have encoded it separately.

I would create a function to convert you byte array to a string (lots of examples on SO) and another one to handle the case statement.


问:
using repo other then pypi with pip
I am having trouble understanding how pip works in a specific environment. The thing is that I am trying to install OpenStack using ansible-openstack deployment method. It provides playbooks to prepare the complete environment and install all components. Deployment fails at the step when python modules should be installed from a private repo (it is being built during previous deployment steps). This repo is nothing else as nginx server exposing directories with python wheels via http protocol. When OpenStack nodes are reaching over to this repo with pip in order to install packages, they seem not to find any of the packages that satisfy their constraints (I am not posting the whole command using the requirement file, but required versions are there). Each node has similarly looking HOME/./pip/pip.conf:

```<code>    [global]
    no-index = true
    pre = True
    timeout = 120
    trusted-host =
            172.21.51.152

    [install]
    upgrade = True
    find-links =
            http://172.21.51.152:8181/os-releases/14.0.7/
</code>```

where 172.21.51.152 is that repo that is supposed to replace PyPI.

When playbook tasks that should install packages are running they all fail with similar error:

root@control1-galera-container-434df170:~# pip install MySQL-python
Collecting MySQL-python
  Could not find a version that satisfies the requirement MySQL-python (from versions: )
No matching distribution found for MySQL-python

even though the file is there and I can wget it from the URL where the file is located.

```<code>    ls /var/www/repo/os-releases/14.0.7/ | grep -i mysql_python
    mysql_python-1.2.5-cp27-cp27mu-linux_x86_64.whl
</code>```

I checked with tcpdump what kind of request pip is sending when "pip install" command is used. It sends a GET get to http://172.21.51.152:8181/os-releases/14.0.7/ where all wheel files are. Server replies with the index.html file:

```<code>    <html>\r\n
    <head><title>Index of /</title></head>\r\n
    <body bgcolor="white">\r\n
    <h1>Index of /</h1><hr>```../\r\n
    links/
    openstackgit/
    os-releases/
    pkg-cache/
    pools/
    venvs/
    ```<hr></body>\r\n
    </html>\r\n
</code>```

After getting this reply pip seems to be satisfied with the outcome and decides that the package it was looking for is not there. I am trying to figure out if that is expected behaviour and there is something wrong with that repo or if pip is being launched with insufficient configuration that doesn't allow it to perform the search.

I tried to delete the pip.conf altogether and pip worked normally just downloading files from PyPI. What am I missing here in order to make it work from the private repository?

Thanks for you help!

答:
FWIW, I had the very same symptom Danil described:

```<code>root@control1-galera-container-434df170:~# pip install MySQL-python
Collecting MySQL-python Could not find a version that satisfies the requirement MySQL-python (from versions: )
No matching distribution found for MySQL-python
</code>```

The root cause in my case was a (restrictive) umask setting of 077.

```<code># root@controller1
$ umask  # octal
0077
$ umask -S  # symbolic
u=rwx,g=,o=
</code>```

The default seems to be 022 (symbolic: u=rwx,g=rx,o=rx), details at https://en.wikipedia.org/wiki/Umask

This umask of 077 affects the nginx config files (which, for example, set the
'autoindex' behavior, which is needed to serve the python wheels):

```<code># root@controller1-repo-container-e0445a8f
$ cd /etc/nginx/sites-available/
$ ll openstack-slushee.vhost
-rw------- 1 root root [...] openstack-slushee.vhost
</code>```

If also affects the python packages:

```<code># root@controller1-repo-container-e0445a8f
$ cd /var/www/repo/pools/ubuntu-16.04-x86_64/mysql_python/
$ ll mysql_python-1.2.5-cp27-cp27mu-linux_x86_64.whl
-rw------- 1 nginx root [...] mysql_python-1.2.5-cp27-cp27mu-linux_x86_64.whl
</code>```

And these python packages get requested from the other containers in an openstack-ansible setup:

```<code># root@controller1-galera-container-564eedea
$ cat .pip/pip.conf
[...]
[install]
upgrade = True
find-links =
    http://172.29.236.11:8181/os-releases/15.1.2/ubuntu-16.04-x86_64/
</code>```

And ultimately, it affects the file which specifies the python package versions:

```<code># root@controller1-repo-container-e0445a8f
$ cd /var/www/repo/os-releases/15.1.2/ubuntu-16.04-x86_64/
$ ll requirements_absolute_requirements.txt
-rw------- 1 root root [...] requirements_absolute_requirements.txt
</code>```

You will notice that nginx complains a lot in its error log:

```<code># root@controller1-repo-container-e0445a8f
$ grep -i error /var/log/nginx/openstack-slushee.error.log | grep -i mysql
2017/07/03 10:30:34 [error] 17458\#17458: *642 open()
"/var/www/repo/os-releases/15.1.2/ubuntu-16.04-x86_64/
mysql_python-1.2.5-cp27-cp27mu-linux_x86_64.whl" failed
(13: Permission denied), client: 172.29.236.11,
server: openstack-slushee,
request: "GET /os-releases/15.1.2/ubuntu-16.04-x86_64/
mysql_python-1.2.5-cp27-cp27mu-linux_x86_64.whl HTTP/1.1",
host: "172.29.236.11:8181"
</code>```

Long story short, set the umask to a less restrictive mode before starting openstack-ansible:

```<code>$ umask 0022
</code>```

Side notes:

here's the discussion where I want to figure out how to handle umask in openstack-ansible: http://lists.openstack.org/pipermail/openstack-operators/2017-July/013892.html

this question might have been better suited at https://ask.openstack.org/en/questions/

Title: using repo other then pypi with pip

Body:
I am having trouble understanding how pip works in a specific environment. The thing is that I am trying to install OpenStack using ansible-openstack deployment method. It provides playbooks to prepare the complete environment and install all components. Deployment fails at the step when python modules should be installed from a private repo (it is being built during previous deployment steps). This repo is nothing else as nginx server exposing directories with python wheels via http protocol. When OpenStack nodes are reaching over to this repo with pip in order to install packages, they seem not to find any of the packages that satisfy their constraints (I am not posting the whole command using the requirement file, but required versions are there). Each node has similarly looking HOME/./pip/pip.conf:

    [global]
    no-index = true
    pre = True
    timeout = 120
    trusted-host =
            172.21.51.152

    [install]
    upgrade = True
    find-links =
            http://172.21.51.152:8181/os-releases/14.0.7/

where 172.21.51.152 is that repo that is supposed to replace PyPI.

When playbook tasks that should install packages are running they all fail with similar error:

root@control1-galera-container-434df170:~# pip install MySQL-python
Collecting MySQL-python
  Could not find a version that satisfies the requirement MySQL-python (from versions: )
No matching distribution found for MySQL-python

even though the file is there and I can wget it from the URL where the file is located.

    ls /var/www/repo/os-releases/14.0.7/ | grep -i mysql_python
    mysql_python-1.2.5-cp27-cp27mu-linux_x86_64.whl

I checked with tcpdump what kind of request pip is sending when "pip install" command is used. It sends a GET get to http://172.21.51.152:8181/os-releases/14.0.7/ where all wheel files are. Server replies with the index.html file:

    \r\n
    <title>Index of /</title>\r\n
    \r\n

Index of /

../\r\n
    links/
    openstackgit/
    os-releases/
    pkg-cache/
    pools/
    venvs/

\r\n
    \r\n

After getting this reply pip seems to be satisfied with the outcome and decides that the package it was looking for is not there. I am trying to figure out if that is expected behaviour and there is something wrong with that repo or if pip is being launched with insufficient configuration that doesn't allow it to perform the search.

I tried to delete the pip.conf altogether and pip worked normally just downloading files from PyPI. What am I missing here in order to make it work from the private repository?

Thanks for you help!

Body:
FWIW, I had the very same symptom Danil described:

root@control1-galera-container-434df170:~# pip install MySQL-python
Collecting MySQL-python Could not find a version that satisfies the requirement MySQL-python (from versions: )
No matching distribution found for MySQL-python

The root cause in my case was a (restrictive) umask setting of 077.

# root@controller1
$ umask  # octal
0077
$ umask -S  # symbolic
u=rwx,g=,o=

The default seems to be 022 (symbolic: u=rwx,g=rx,o=rx), details at https://en.wikipedia.org/wiki/Umask

This umask of 077 affects the nginx config files (which, for example, set the
'autoindex' behavior, which is needed to serve the python wheels):

# root@controller1-repo-container-e0445a8f
$ cd /etc/nginx/sites-available/
$ ll openstack-slushee.vhost
-rw------- 1 root root [...] openstack-slushee.vhost

If also affects the python packages:

# root@controller1-repo-container-e0445a8f
$ cd /var/www/repo/pools/ubuntu-16.04-x86_64/mysql_python/
$ ll mysql_python-1.2.5-cp27-cp27mu-linux_x86_64.whl
-rw------- 1 nginx root [...] mysql_python-1.2.5-cp27-cp27mu-linux_x86_64.whl

And these python packages get requested from the other containers in an openstack-ansible setup:

# root@controller1-galera-container-564eedea
$ cat .pip/pip.conf
[...]
[install]
upgrade = True
find-links =
    http://172.29.236.11:8181/os-releases/15.1.2/ubuntu-16.04-x86_64/

And ultimately, it affects the file which specifies the python package versions:

# root@controller1-repo-container-e0445a8f
$ cd /var/www/repo/os-releases/15.1.2/ubuntu-16.04-x86_64/
$ ll requirements_absolute_requirements.txt
-rw------- 1 root root [...] requirements_absolute_requirements.txt

You will notice that nginx complains a lot in its error log:

# root@controller1-repo-container-e0445a8f
$ grep -i error /var/log/nginx/openstack-slushee.error.log | grep -i mysql
2017/07/03 10:30:34 [error] 17458\#17458: *642 open()
"/var/www/repo/os-releases/15.1.2/ubuntu-16.04-x86_64/
mysql_python-1.2.5-cp27-cp27mu-linux_x86_64.whl" failed
(13: Permission denied), client: 172.29.236.11,
server: openstack-slushee,
request: "GET /os-releases/15.1.2/ubuntu-16.04-x86_64/
mysql_python-1.2.5-cp27-cp27mu-linux_x86_64.whl HTTP/1.1",
host: "172.29.236.11:8181"

Long story short, set the umask to a less restrictive mode before starting openstack-ansible:

$ umask 0022

Side notes:

here's the discussion where I want to figure out how to handle umask in openstack-ansible: http://lists.openstack.org/pipermail/openstack-operators/2017-July/013892.html

this question might have been better suited at https://ask.openstack.org/en/questions/


问:
How do I delete a line from the table in index page when I press the delete button without deleting it from the database
How do I delete a line from the table in index page when I press the delete button without deleting it from the database.
i'm using asp.net mvc5 with visual studio 2017 and sql server 2016.

```<code>// GET: Information/Delete/5
    public ActionResult Delete(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Information information = db.Informations.Find(id);
        if (information == null)
        {
            return HttpNotFound();
        }
        return View(information);
    }

    // POST: Information/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        Information information = db.Informations.Find(id);
        db.Informations.Remove(information);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}
</code>```

}

this code delete the selected row from database. i want to delete it just from index page.
Please could anyone give me any hint.

答:
If you delete it only from the Index page, the row will appear again when the page is loaded.

However, you can delete it using jquery.

In your Index View write this:

```<code><script>
    $(".class").on("click", function(){   //if your element has a class
         $(this).remove();
    })
    $("#id").on("click", function(){     //if your element has an id
         $(this).remove();
    })
</script>
</code>```

Body:
How do I delete a line from the table in index page when I press the delete button without deleting it from the database.
i'm using asp.net mvc5 with visual studio 2017 and sql server 2016.

// GET: Information/Delete/5
    public ActionResult Delete(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Information information = db.Informations.Find(id);
        if (information == null)
        {
            return HttpNotFound();
        }
        return View(information);
    }

    // POST: Information/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        Information information = db.Informations.Find(id);
        db.Informations.Remove(information);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}

}

this code delete the selected row from database. i want to delete it just from index page.
Please could anyone give me any hint.

Body:
If you delete it only from the Index page, the row will appear again when the page is loaded.

However, you can delete it using jquery.

In your Index View write this:

<script>
    $(".class").on("click", function(){   //if your element has a class
         $(this).remove();
    })
    $("#id").on("click", function(){     //if your element has an id
         $(this).remove();
    })
</script>


问:
Subset df on string condition
I want to subset df on an unknown condition (say, randomly defined as in the example below):

```<code>df <- data.frame(a=1:10, b = 10:1)
condition <- paste0(sample(letters[1:2],1), sample(c("<",">"),1), sample(1:10,1))
</code>```

I can do this with eval, which, vox populi, is suboptimal:

```<code>subset(df, eval(parse(text=condition)))
</code>```

Is there an alternative to eval(parse)?

答:
If there can be some constraints introduced, such as the dataframe only having numeric columns, and only linear conditions, you could formulate the decision on condition as dot products:</p>

```<code># a > b
condition.mat <- c(1, -1)
condition.const <- 0

# b > 4
# condition.mat <- c(0, 1)
# condition.const <- 4

dec <- as.matrix(df) %*% condition.mat - condition.const
sel <- dec > 0

print(df[sel,])
</code>```

Title: Subset df on string condition

Body:
I want to subset df on an unknown condition (say, randomly defined as in the example below):

df <- data.frame(a=1:10, b = 10:1)
condition <- paste0(sample(letters[1:2],1), sample(c("<",">"),1), sample(1:10,1))

I can do this with eval, which, vox populi, is suboptimal:

subset(df, eval(parse(text=condition)))

Is there an alternative to eval(parse)?

Body:
If there can be some constraints introduced, such as the dataframe only having numeric columns, and only linear conditions, you could formulate the decision on condition as dot products:

# a > b
condition.mat <- c(1, -1)
condition.const <- 0

# b > 4
# condition.mat <- c(0, 1)
# condition.const <- 4

dec <- as.matrix(df) %*% condition.mat - condition.const
sel <- dec > 0

print(df[sel,])


问:
Swift - Replace extra line breaks in server generated CSV file
I have created a statistics controller for administrators to export back-end information from a database. The controller has several fields with UIPickers to filter data and a button to send a request to the server, where the API (written in C#) takes care of the export.

The data is currently being exported to a CSV and added back to my controller. The problem is that the attached file contains one extra line break after every line of data. The CSV looks perfect on the Windows machine, though.

If this a Windows / Unix problem where line breaks are handled differently, what can I do to fix this? I want all those extra lines to be gone before the user actually opens the file as a spreadsheet.

On my windows machine

```<code>Created by: ""
Created on: ""

Name,Date,Score
Jack Sparrow,2017-07-03-14:48:58,80
Jack Sparrow,2017-07-03-14:49:33,100
</code>```

On my Mac and iPhone

```<code>Created by: ""

Created on: ""

Name,Date,Score

Jack Sparrow,2017-07-03-14:48:58,80

Jack Sparrow,2017-07-03-14:49:33,100
</code>```

答:
If you want to remove the empty lines alltogether, you can use a simple string replacement function.</p>

```<code>let array = string.enumerateLines { line, _ in linesArray.append(line) }
let result = array.filter { !$0.isEmpty }.joined(separator: "\n")
</code>```

Body:
I have created a statistics controller for administrators to export back-end information from a database. The controller has several fields with UIPickers to filter data and a button to send a request to the server, where the API (written in C#) takes care of the export.

The data is currently being exported to a CSV and added back to my controller. The problem is that the attached file contains one extra line break after every line of data. The CSV looks perfect on the Windows machine, though.

If this a Windows / Unix problem where line breaks are handled differently, what can I do to fix this? I want all those extra lines to be gone before the user actually opens the file as a spreadsheet.

On my windows machine

Created by: ""
Created on: ""

Name,Date,Score
Jack Sparrow,2017-07-03-14:48:58,80
Jack Sparrow,2017-07-03-14:49:33,100

On my Mac and iPhone

Created by: ""

Created on: ""

Name,Date,Score

Jack Sparrow,2017-07-03-14:48:58,80

Jack Sparrow,2017-07-03-14:49:33,100

Body:
If you want to remove the empty lines alltogether, you can use a simple string replacement function.

let array = string.enumerateLines { line, _ in linesArray.append(line) }
let result = array.filter { !$0.isEmpty }.joined(separator: "\n")


问:
Changing a trained network to keep only a subset of its output
Suppose I have a trained TensorFlow classification network for 20 classes as in PASCAL VOC 2007: aeroplane, bicycle, ..., car, cat, ..., person, ..., tvmonitor.

Now, I would like to have a sub-network for only a subset of the classes, e.g., 3 classes: car, cat, person.

Then, I can use this network for testing or for re-training/fine-tuning on a new dataset, only for the 3 classes.

It should be possible to extract this sub-network out of the original network, since it is only the last layer that will change. We need to discard the neurons/weights for the discarded classes.

My question: Is there an easy way to do this in TensorFlow?
It will be great if you can point to some sample code or similar solution.
I have googled, but have not come across any mention of this.

The symmetric problem, expanding the number of classes without discarding the original weights, can potentially be useful for some people, but my current focus is the one above.

答:
If you want to only keep the output for a few slices, you could simply extract the corresponding slices from the last layer.

For example, let's assume the last layer is fully connected. Its weights are a tensor of size num_previous x num_output.

You want to keep only a few of these outputs, says output 1, 22, and 42. You can get the weights of your new fully connected layer as:

```<code>outputs_to_keep = [1, 22, 42]
new_W = tf.transpose(tf.gather(tf.transpose(old_W), outputs_to_keep))
</code>```

Body:
If you want to only keep the output for a few slices, you could simply extract the corresponding slices from the last layer.

For example, let's assume the last layer is fully connected. Its weights are a tensor of size num_previous x num_output.

You want to keep only a few of these outputs, says output 1, 22, and 42. You can get the weights of your new fully connected layer as:

outputs_to_keep = [1, 22, 42]
new_W = tf.transpose(tf.gather(tf.transpose(old_W), outputs_to_keep))


问:
android datePicker with different API
In my android app I created a datepicker, the problem is if my application is running on the emulator "Nexus api 23" the result is the following:

If my application is running on my phone Note 1 with API 16 the result is like the following:

答: Did you accomplish to this problem?</p>

Title: android datePicker with different API

Body: Did you accomplish to this problem?


问:
Angular2 Routing with Hashtag to page anchor
I wish to add some links on my Angular2 page, that when click, will jump to specific positions within that page, like what normal hashtags do. So the links would be something like

```<code>/users/123#userInfo
/users/123#userPhoto
/users/123#userLikes
</code>```

etc.

I don't think I need HashLocationStrategy, as I'm fine with the normal Angular2 way, but if I add  directly, the link would actually jump to the root, not somewhere on the same page. Any direction is appreciated, thanks.

答:
Since the fragment property still doesn't provide anchor scrolling, this workaround did the trick for me:</p>

```<code><div [routerLink]="['somepath']" fragment="Test">
  <a href="#Test">Jump to 'Test' anchor </a>
</div>
</code>```

Body:
I wish to add some links on my Angular2 page, that when click, will jump to specific positions within that page, like what normal hashtags do. So the links would be something like

/users/123#userInfo
/users/123#userPhoto
/users/123#userLikes

etc.

I don't think I need HashLocationStrategy, as I'm fine with the normal Angular2 way, but if I add  directly, the link would actually jump to the root, not somewhere on the same page. Any direction is appreciated, thanks.

Body:
Since the fragment property still doesn't provide anchor scrolling, this workaround did the trick for me:

<div [routerLink]="['somepath']" fragment="Test">
  <a href="#Test">Jump to 'Test' anchor </a>
</div>


问:
node 7.10 - does it support await?
I am on node 7.10:

```<code>$ node --version
v7.10.0
</code>```

I thought it supports await.

```<code> let result = await Weather.findOne(options, function(err, weather) {

    if (err) {
        res.set('Content-Type', 'application/json');
        return res.status(200).send('Error occurs: ' + err);
    }

    if (weather) {
        res.set('Content-Type', 'application/json');
        return res.status(200).send(key + ' already exist.');
    }

    return weather;
});

console.log(result);
</code>```

Error message:

```<code>let result = await Weather.findOne(options, function(err, weather) {
                       ^^^^^^^
SyntaxError: Unexpected identifier
    at createScript (vm.js:53:10)
    at Object.runInThisContext (vm.js:95:10)
    at Module._compile (module.js:543:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/var/www/html/projects/citizen-sense-dustbox-data-streams/es5/v4/app.js:33:15)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/var/www/html/projects/citizen-sense-dustbox-data-streams/es5/v4/bin/www:7:11)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10)
    at run (bootstrap_node.js:427:7)
    at startup (bootstrap_node.js:151:9)
    at bootstrap_node.js:542:3
</code>```

It does not seem supported in node 7.10? Or am I doing something wrong?

Any ideas?

答:
I have v7.10.0 and await/async are definitely supported in that version. I think it was added in 7.4, not sure though.

```<code>ubuntu@ubuntu:~$ node --version
v7.10.0
</code>```

When I run:

```<code>const getDate = async () => {
    return new Date()
}
const printDate = async () => {
    const date = await getDate()
    return date
}
printDate().then(console.log).catch(console.error)
</code>```

I get:

```<code>2017-07-04T09:04:27.311Z
</code>```

Edit:
Just fyi, async/await didn't actually make it into ES7. It will most likely make it into this years edition of ECMAScript, though. https://github.com/tc39/proposals/blob/master/finished-proposals.md

Title: node 7.10 - does it support await?

Body:
I am on node 7.10:

$ node --version
v7.10.0

I thought it supports await.

 let result = await Weather.findOne(options, function(err, weather) {

    if (err) {
        res.set('Content-Type', 'application/json');
        return res.status(200).send('Error occurs: ' + err);
    }

    if (weather) {
        res.set('Content-Type', 'application/json');
        return res.status(200).send(key + ' already exist.');
    }

    return weather;
});

console.log(result);

Error message:

let result = await Weather.findOne(options, function(err, weather) {
                       ^^^^^^^
SyntaxError: Unexpected identifier
    at createScript (vm.js:53:10)
    at Object.runInThisContext (vm.js:95:10)
    at Module._compile (module.js:543:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/var/www/html/projects/citizen-sense-dustbox-data-streams/es5/v4/app.js:33:15)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/var/www/html/projects/citizen-sense-dustbox-data-streams/es5/v4/bin/www:7:11)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10)
    at run (bootstrap_node.js:427:7)
    at startup (bootstrap_node.js:151:9)
    at bootstrap_node.js:542:3

It does not seem supported in node 7.10? Or am I doing something wrong?

Any ideas?

Body:
I have v7.10.0 and await/async are definitely supported in that version. I think it was added in 7.4, not sure though.

ubuntu@ubuntu:~$ node --version
v7.10.0

When I run:

const getDate = async () => {
    return new Date()
}
const printDate = async () => {
    const date = await getDate()
    return date
}
printDate().then(console.log).catch(console.error)

I get:

2017-07-04T09:04:27.311Z

Edit:
Just fyi, async/await didn't actually make it into ES7. It will most likely make it into this years edition of ECMAScript, though. https://github.com/tc39/proposals/blob/master/finished-proposals.md


问:
How to add a NOT NULLABLE column with a foreign key to an existing table that already contains data?
An example for this problem:

Imagine you have a table projects. The table projects already
  contains data. Now you want to add a project_type_id column to the
  table, that can't be NULL and has a foreign key to the project_types
  table.

The database sees the project_type_id can't be NULL, so it inserts a
  0 in the column for all the existing rows. The 0 does not exist in
  the project_types table, so the foreign key constraint fails. This
  means you can't add the foreign key.

I thought about adding a first "default" row to the project_types table and link all the projects to that type. This isn't a good solution, because the user has to change all the types from "default" to the correct type.

What is your solution for this problem?

答:
I think the best way to solve this issue is:

Create a new migration in order to add project_type_id column to projects table:

```<code>php artisan make:migration add_project_type_column_to_projects_table --table=projects

 public function up()
{
    Schema::table('projects', function (Blueprint $table) {
        $table->integer("project_type_id")->unsigned();
    });
}

public function down()
{
    Schema::table('projects', function (Blueprint $table) {
        $table->dropColumn("project_type_id");
    });
}
</code>```

It's going to add 0 value as default in each column but no problem because it's not foreign key yet.

2.Define the relationship between Project and ProjectType models

```<code>//Your Project class

class Project extends Model
{
 protected $fillable=["your columns..."];

 public function type()
  {
    return $this->belongsTo(ProjectType::class);
  }
}

//Your ProjectType class

class ProjectType extends Model
{
  protected $fillable=["Your columns..."];

  public function projects()
  {
    return $this->hasMany(Project::class);
  }
}
</code>```

Now you must go and set the correct values for project_type_id either manually or from your admin panel.

Now your column is ready to be set as foreign key, so go ahead and make a new migration to set the project_type_id as foreign key.

```<code>php artisan make:migration set_project_type_id_column_as_foreign_key --table=projects

public function up()
{
    Schema::table('projects', function (Blueprint $table) {
        $table->foreign("project_type_id")
            ->references("id")
            ->on("project_types")
            ->onDelete("cascade")//is up to you
            ->onUpdate("cascade");// is up to you
    });
}
 public function down()
{
    Schema::table('projects', function (Blueprint $table) {
        $table->dropForeign("projects_project_type_id_foreign"); //This one could be different
    });
}
</code>```

Now your table has a new (NOT NULLABLE) foreign key with correct values.

Body:
I think the best way to solve this issue is:

Create a new migration in order to add project_type_id column to projects table:

php artisan make:migration add_project_type_column_to_projects_table --table=projects

 public function up()
{
    Schema::table('projects', function (Blueprint $table) {
        $table->integer("project_type_id")->unsigned();
    });
}

public function down()
{
    Schema::table('projects', function (Blueprint $table) {
        $table->dropColumn("project_type_id");
    });
}

It's going to add 0 value as default in each column but no problem because it's not foreign key yet.

2.Define the relationship between Project and ProjectType models

//Your Project class

class Project extends Model
{
 protected $fillable=["your columns..."];

 public function type()
  {
    return $this->belongsTo(ProjectType::class);
  }
}

//Your ProjectType class

class ProjectType extends Model
{
  protected $fillable=["Your columns..."];

  public function projects()
  {
    return $this->hasMany(Project::class);
  }
}

Now you must go and set the correct values for project_type_id either manually or from your admin panel.

Now your column is ready to be set as foreign key, so go ahead and make a new migration to set the project_type_id as foreign key.

php artisan make:migration set_project_type_id_column_as_foreign_key --table=projects

public function up()
{
    Schema::table('projects', function (Blueprint $table) {
        $table->foreign("project_type_id")
            ->references("id")
            ->on("project_types")
            ->onDelete("cascade")//is up to you
            ->onUpdate("cascade");// is up to you
    });
}
 public function down()
{
    Schema::table('projects', function (Blueprint $table) {
        $table->dropForeign("projects_project_type_id_foreign"); //This one could be different
    });
}

Now your table has a new (NOT NULLABLE) foreign key with correct values.


问:
UWP Bluetooth ConnectAsync error to Raspberry Pi. Element not found
I'm making a Windows UWP app that uses RFCOMM to communicate to a Raspberry Pi. Both my Windows laptop and Raspberry Pi are already connected and paired (manually). I know the bluetooth address of the Raspberry Pi and the channel it's using and these values are hardcoded into the parameters for ConnectAsync(...).

When ConnectAsync(...) is called, the Raspberry Pi does receive a connection and it prints the line "accepted connection from ('Windows bluetooth address', 1). However, the exception "An exception of type 'System.Exception' occurred in mscorlib.ni.dll but was not handled in user code. Additional information: Element not found. (Exception from HRESULT: 0x80070490)" happens at where ConnectAsync(...) is called, and the message is never delivered to the Raspberry Pi.

Windows Code (as the client, trying to send message to the Raspberry Pi):

```<code>StreamSocket socket = new StreamSocket();
await socket.ConnectAsync(new HostName(bluetoothAddress), "1"); // the format of bluetoothAddress is 'AB:CD:AB:CD:AB:CD'

Stream streamOut = socket.OutputStream.AsStreamForWrite();
StreamWriter writer = new StreamWriter(streamOut);
await writer.WriteLineAsync(message);
await writer.FlushAsync();
</code>```

Raspberry Pi (as Python Server):

```<code>import bluetooth

server_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )

port = 1
server_sock.bind(("",port))
server_sock.listen(1)

client_sock,address = server_sock.accept()
print("Accepted connection from ",address)

data = client_sock.recv(1024)
print("received [%s]" % data)
</code>```

When I replace the "1" in ConnectAsync(...) with bluetoothAddress, a 'Value does not fall within the expected range' exception appears.

答:
The second parameter "remoteServiceName" of the method socket.ConnectAsync() should be RfcommDeviceService.ConnectionServiceName.

For more information you can reference Bluetooth RFCOMM chat sample.

Body:
I'm making a Windows UWP app that uses RFCOMM to communicate to a Raspberry Pi. Both my Windows laptop and Raspberry Pi are already connected and paired (manually). I know the bluetooth address of the Raspberry Pi and the channel it's using and these values are hardcoded into the parameters for ConnectAsync(...).

When ConnectAsync(...) is called, the Raspberry Pi does receive a connection and it prints the line "accepted connection from ('Windows bluetooth address', 1). However, the exception "An exception of type 'System.Exception' occurred in mscorlib.ni.dll but was not handled in user code. Additional information: Element not found. (Exception from HRESULT: 0x80070490)" happens at where ConnectAsync(...) is called, and the message is never delivered to the Raspberry Pi.

Windows Code (as the client, trying to send message to the Raspberry Pi):

StreamSocket socket = new StreamSocket();
await socket.ConnectAsync(new HostName(bluetoothAddress), "1"); // the format of bluetoothAddress is 'AB:CD:AB:CD:AB:CD'

Stream streamOut = socket.OutputStream.AsStreamForWrite();
StreamWriter writer = new StreamWriter(streamOut);
await writer.WriteLineAsync(message);
await writer.FlushAsync();

Raspberry Pi (as Python Server):

import bluetooth

server_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )

port = 1
server_sock.bind(("",port))
server_sock.listen(1)

client_sock,address = server_sock.accept()
print("Accepted connection from ",address)

data = client_sock.recv(1024)
print("received [%s]" % data)

When I replace the "1" in ConnectAsync(...) with bluetoothAddress, a 'Value does not fall within the expected range' exception appears.


问:
Using JavaScript to perform a GET request without AJAX
Out of curiosity, I'm wondering about the best (easiest, fastest, shortest, etc; make your pick) way to perform a GET request in JavaScript without using AJAX or any external libraries.

It must work cross-browser and it's not allowed to distort the hosting web page visually or affect it's functionality in any way.

I don't care about headers in the request, just the url-part. I also don't care about the result of the request. I just want the server to do something as a side effect when it receives this request, so firing it is all that matters. If your solution requires the servers to return something in particular, that's ok as well.

I'll post my own suggestion as a possible answer, but I would love it if someone could find a better way!

答:
```<code>function GET(url) {
  var head = document.getElementsByTagName('head')[0];
  var n = document.createElement('script');
  n.src = url;
  n.type = 'text/javascript';
  n.onload = function() { // this is not really mandatory, but removes the tag when finished.
    head.removeChild(n);
  };
  head.appendChild(n);
}
</code>```