答:
The jQuery show,hide and toggle functions simply alter the CSS display property to have either display: block; or display: none;.

To start with your element hidden just set the style attribute  style="display:none;".

Title: How to make HTML text hidden until clicked on


来源: stackexchange

ContentLicense: CC BY-SA 3.0

Title: How to turn a pandas dataframe row into a comma separated string

Body:
I need to iterate over each row of a pandas df and turn this into a comma separated string.

example:

df3 = DataFrame(np.random.randn(10, 5),
              columns=['a', 'b', 'c', 'd', 'e'])

          a         b         c         d         e
0 -0.158897 -0.749799  0.268921  0.070035  0.099600
1 -0.863654 -0.086814 -0.614562 -1.678850  0.980292
2 -0.098168  0.710652 -0.456274 -0.373153 -0.533463
3  1.001634 -0.736187 -0.812034  0.223062 -1.337972
4  0.173549 -0.576412 -1.016063 -0.217242  0.443794
5  0.273695  0.335562  0.778393 -0.668368  0.438880
6 -0.783824  1.439888  1.057639 -1.825481 -0.770953
7 -1.025004  0.155974  0.645023  0.993379 -0.812133
8  0.953448 -1.355628 -1.918317 -0.966472 -0.618744
9 -0.479297  0.295150 -0.294449  0.679416 -1.813078

I'd like to get for each row:

 '-0.158897,-0.749799,0.268921,0.070035,0.099600'
 '0.863654,-0.086814,-0.614562,-1.678850,0.980292'
... and so on

Body:
Use to_csv:

df = pd.DataFrame(np.random.randn(10, 5),
                  columns=['a', 'b', 'c', 'd', 'e'])
df.to_csv(header=None, index=False).strip('\n').split('\n')

['-1.60092768589,-0.746496859432,0.662527724304,-0.677984969682,1.70656657572',
 '-0.432306620615,-0.396499851892,0.564494290965,-1.01196068617,-0.630576490671',
 '-3.28916785414,0.627240166663,-0.359262938883,0.344156143177,-0.911269843378',
 '-0.272741450301,0.0594234886507,-2.72800253986,-0.821610087419,-0.0668212419497',
 '0.303490090149,-1.61344483051,0.117046351282,-1.46936429231,-0.66018613208',
 '-1.18157229705,-0.766519504863,0.386180129978,0.945274532852,-0.783459830884',
 '-1.27118723107,-1.12478330038,-0.625470220821,-0.453053132109,0.0641830786961',
 '-1.02657336234,-1.01556460318,0.445282883845,0.589873985417,-0.833648685855',
 '0.742343897524,-1.69644542886,-1.03886940911,0.511317569685,1.87084848086',
 '-0.159125435887,1.02522202275,0.254459603867,-0.487187861352,2.31900012693']

Note: this needs to be improved if you have \n in your cells.


问:
django "MyModel.user" must be a "User" instance
helloo

I have in DJANGO app two functions where I want to work in my views.py  the second function need the output from the first function to work.

my views.py(before) :

```<code>@login_required(login_url="login/")
def app_details(request,slug):
        if request.method == "POST":
            b = request.user.id
            test = request.POST.get('index')
            test_path_export=test+'add/path'
            my_task_name(test,test_path_export)
            save_alg(request.user,test_path_export)
        return render(request, 'details.html'...............................
</code>```

my_function_name.py

```<code>def my_function_name(input1,output1):
     ..................................
     ..................................
</code>```

myalg.py

```<code>from django.contrib.auth.models import User

def save_alg(user_id,input1):
    instance = MyModel.objects.create(user=user_id, field1=input1)
     ..................................
     ..................................
    instance.save()
</code>```

and all work functions(my_task_name,save_alg) works fine ...

now I want to create one function from this two functions to work in the some function because I want to add async tasks using celery in the future and if I have one function is very easy to use .delay.

I change my_function_name.py to:

```<code>def my_function_name(user_id,input1,output1):
     ..................................
     ..................................
    return save_alg(user_id,output1)
</code>```

and second try to

```<code>def my_function_name(user_id,input1,output1):
     ..................................
     ..................................
    save_alg(user_id,output1)
</code>```

and in my views.py:

```<code>@login_required(login_url="login/")
def app_details(request,slug):
        if request.method == "POST":
            b = request.user.id
            test = request.POST.get('index')
            test_path_export=test+'add/path'
            my_task_name(request.user,test,test_path_export)
        return render(request, 'details.html'...............................
</code>```

error message in line instance = MyModel.objects.create(user=user_id, field1=input1) :

```<code>self.field.remote_field.model._meta.object_name,
ValueError: Cannot assign "28": "MyModel.user" must be a "User" instance.
</code>```

I have add :

```<code>from django.contrib.auth.models import User
import user
</code>```

in all python files.

any idea how to fix this error ?

答:
user=foo assumes that foo is itself an instance of a User object. You're passing in a string that's supposed to be the user's ID:

```<code>instance = MyModel.objects.create(user_id=user_id, field1=input1)
                                      ^^^
</code>```

Either pass around a User object or change user= to user_id=.

Body:
helloo

I have in DJANGO app two functions where I want to work in my views.py  the second function need the output from the first function to work.

my views.py(before) :

@login_required(login_url="login/")
def app_details(request,slug):
        if request.method == "POST":
            b = request.user.id
            test = request.POST.get('index')
            test_path_export=test+'add/path'
            my_task_name(test,test_path_export)
            save_alg(request.user,test_path_export)
        return render(request, 'details.html'...............................

my_function_name.py

def my_function_name(input1,output1):
     ..................................
     ..................................

myalg.py

from django.contrib.auth.models import User

def save_alg(user_id,input1):
    instance = MyModel.objects.create(user=user_id, field1=input1)
     ..................................
     ..................................
    instance.save()

and all work functions(my_task_name,save_alg) works fine ...

now I want to create one function from this two functions to work in the some function because I want to add async tasks using celery in the future and if I have one function is very easy to use .delay.

I change my_function_name.py to:

def my_function_name(user_id,input1,output1):
     ..................................
     ..................................
    return save_alg(user_id,output1)

and second try to

def my_function_name(user_id,input1,output1):
     ..................................
     ..................................
    save_alg(user_id,output1)

and in my views.py:

@login_required(login_url="login/")
def app_details(request,slug):
        if request.method == "POST":
            b = request.user.id
            test = request.POST.get('index')
            test_path_export=test+'add/path'
            my_task_name(request.user,test,test_path_export)
        return render(request, 'details.html'...............................

error message in line instance = MyModel.objects.create(user=user_id, field1=input1) :

self.field.remote_field.model._meta.object_name,
ValueError: Cannot assign "28": "MyModel.user" must be a "User" instance.

I have add :

from django.contrib.auth.models import User
import user

in all python files.

any idea how to fix this error ?

Body:
user=foo assumes that foo is itself an instance of a User object. You're passing in a string that's supposed to be the user's ID:

instance = MyModel.objects.create(user_id=user_id, field1=input1)
                                      ^^^

Either pass around a User object or change user= to user_id=.


问:
Add properties to a complex datatype dynamically
I am working on a class with some properties like below in C#

```<code>public class SummaryDto
    {
        public string Name { get; set; }
        public string  GenericName { get; set; }
        public int Data2012 { get; set; }
        public int Data2013 { get; set; }
        public int Data2014 { get; set; }
        public int Data2015 { get; set; }
        public int Data2016 { get; set; }
        public int Data2017 { get; set; }

    }
</code>```

In the above class the properties Data2012, Data2013 and so on should be added dynamically based on the data in another object which just contains years in it.
May I know a good way to do it?

答:
```<code>public class SummaryDto
{
    public string Name { get; set; }
    public string  GenericName { get; set; }
    public Dictionary<int, int> Data { get; } = new Dictionary<int, int>();
}
</code>```

<p>I tried just like what Patrick Hoffman said above. This should do it. </p>

Body:
I am working on a class with some properties like below in C#

public class SummaryDto
    {
        public string Name { get; set; }
        public string  GenericName { get; set; }
        public int Data2012 { get; set; }
        public int Data2013 { get; set; }
        public int Data2014 { get; set; }
        public int Data2015 { get; set; }
        public int Data2016 { get; set; }
        public int Data2017 { get; set; }

    }

In the above class the properties Data2012, Data2013 and so on should be added dynamically based on the data in another object which just contains years in it.
May I know a good way to do it?

Body:
public class SummaryDto
{
    public string Name { get; set; }
    public string  GenericName { get; set; }
    public Dictionary<int, int> Data { get; } = new Dictionary<int, int>();
}

I tried just like what Patrick Hoffman said above. This should do it.


问:
introjs opening and highlighting modal window md-dialog
I'm using introjs and am wondering if there's a way for it to open up a modal window and highlight it as part of the tour.  How would that look in the JSON object?

Currently, I have a button that opens up the tour onclick:

```<code><md-button class="md-accent md-raised" ng-click="startIntro();"><i class="fa fa-play-circle" aria-hidden="true"></i> Take a Tour</md-button>
</code>```

My tour steps are defined in a JSON object in the client controller:

```<code>$scope.startIntro = function(){
        var intro = introJs();
          intro.setOptions({
            steps: [
              {
                intro: "Welcome to your Portal!  Here's how to navigate through this site."
              },
              {
                element: document.querySelectorAll('#small-btn')[1],
                intro: "Take a minute and fill out your Questionnaire.  It will prepare you for your first day."
              },
              {
                element: '#twitter',
                intro: "Follow us on social media!",
                position: 'top'
              }
            ]
          });
          intro.start();
      };
</code>```

As for my modal window, I'm using a md-button that brings up a md-dialog box:

```<code><md-button id="small-btn" class=" btn1" ng-click="showAdvanced($event)" >
        <md-tooltip md-direction="right">Questionnaire</md-tooltip>
        <md-icon ng-if="!data.sysID" ng-style="{'background-color':'#F44336'}" class="circle-border md-60">assignment</md-icon>
        <md-icon ng-if="data.sysID" ng-style="{'background-color':'#4CAF50'}" class="circle-border md-60">assignment_turned_in</md-icon>
      </md-button>
</code>```

Any suggestions?

答:
You can use onbeforechange event in intro.js (documented here: https://introjs.com/docs/intro/api/) to open the modal upon entering that step, and close the modal on leaving the step.

```<code>intro.onbeforechange(function(targetElement) {
  if (angular.element(targetElement).attr("id") === "step3") {
    $scope.openModal();
  }
  else {
    $scope.closeDialog();
  }
});
</code>```

You have to be careful that when you setup the introjs object using the setOptions call that your step actually exists in your template. To achieve this, you can use the "Pre-rendered Dialog" settings explained on the md-dialog demo (https://material.angularjs.org/latest/demo/dialog). This essentially means that your dialog exists in the DOM whether the modal is actually showing or not. You open this like so:

```<code>$mdDialog.show({
  parent: angular.element(document.body);,
  targetEvent: $event,
  contentElement: "#modaldialog"
});
</code>```

where #modaldialog is a div encapsulating your <md-dialog>.

Here is an example fiddle showing how this might work: https://plnkr.co/edit/r3Sd2Ti8pKn33A9DJ7R0

Body:
I'm using introjs and am wondering if there's a way for it to open up a modal window and highlight it as part of the tour.  How would that look in the JSON object?

Currently, I have a button that opens up the tour onclick:

<md-button class="md-accent md-raised" ng-click="startIntro();"> Take a Tour</md-button>

My tour steps are defined in a JSON object in the client controller:

$scope.startIntro = function(){
        var intro = introJs();
          intro.setOptions({
            steps: [
              {
                intro: "Welcome to your Portal!  Here's how to navigate through this site."
              },
              {
                element: document.querySelectorAll('#small-btn')[1],
                intro: "Take a minute and fill out your Questionnaire.  It will prepare you for your first day."
              },
              {
                element: '#twitter',
                intro: "Follow us on social media!",
                position: 'top'
              }
            ]
          });
          intro.start();
      };

As for my modal window, I'm using a md-button that brings up a md-dialog box:

<md-button id="small-btn" class=" btn1" ng-click="showAdvanced($event)" >
        <md-tooltip md-direction="right">Questionnaire</md-tooltip>
        <md-icon ng-if="!data.sysID" ng-style="{'background-color':'#F44336'}" class="circle-border md-60">assignment</md-icon>
        <md-icon ng-if="data.sysID" ng-style="{'background-color':'#4CAF50'}" class="circle-border md-60">assignment_turned_in</md-icon>
      </md-button>

Any suggestions?

Body:
You can use onbeforechange event in intro.js (documented here: https://introjs.com/docs/intro/api/) to open the modal upon entering that step, and close the modal on leaving the step.

intro.onbeforechange(function(targetElement) {
  if (angular.element(targetElement).attr("id") === "step3") {
    $scope.openModal();
  }
  else {
    $scope.closeDialog();
  }
});

You have to be careful that when you setup the introjs object using the setOptions call that your step actually exists in your template. To achieve this, you can use the "Pre-rendered Dialog" settings explained on the md-dialog demo (https://material.angularjs.org/latest/demo/dialog). This essentially means that your dialog exists in the DOM whether the modal is actually showing or not. You open this like so:

$mdDialog.show({
  parent: angular.element(document.body);,
  targetEvent: $event,
  contentElement: "#modaldialog"
});

where #modaldialog is a div encapsulating your <md-dialog>.

Here is an example fiddle showing how this might work: https://plnkr.co/edit/r3Sd2Ti8pKn33A9DJ7R0


问:
how to allow a plugin to store data
I plan to propose an application which allow developers to provide plugins for it.

In my scenario, plugins access the application data and methods through a web-services layer, and as a consequence, the developer can expect to store his plugin-data using this layer. We do not want to allow database modification for each plugin which would need it or even provide a direct access to the database.

The question is, do you know, or can you imagine, a system that would suit the need of allowing any kind of data to be store in our database in this context ?

The application is an ASP.NET application, database is SQL Server.

答:
Depending on the amount of data how about storing XML and passing that back and forth. Each plugin has a row in the database and a field for the XML allowing each plugin to control the data they need to store.

You would also be able to set up a web service which allows chunks of data to be returned based on a web service that receives xpath queries and returns the resultant data. If you have SQL Server 2005 or 2008 you would even be able to submit these queries directly into the sql server.
http://msdn.microsoft.com/en-us/library/ms345117(v=sql.90).aspx

If you want something more lightweight perhaps a json array?

Failing that maybe a key value pair collection for each plugin, essentially allowing them to load and save a dictionary

ContentLicense: CC BY-SA 2.5

Title: how to allow a plugin to store data


问:
TypeError: 'function' object is not iterable' Python 3
I'm trying to write a program that will open a text file from the web consisting of 10,000 words, then 'clean' the file to get rid of nonsense words, such as 'aa'. I eventually want to use these words to do other things so I want to add the non 'non-sense' words to be put into a new list. Every time i try to run this I run into the error code TypeError: 'function' object is not iterable.

```<code>import urllib.request

def readWordList():

response = urllib.request.urlopen("http://www.mit.edu/~ecprice/wordlist.10000")
html = response.read()
data = html.decode('utf-8').split()

return data

clean = readWordList()

def clean(aList):
    newList = []
    for word in aList:
        if range(len(word)) >= 2:
            newList.append(word)
    return newList

clean(clean)
</code>```

答:
Make up your mind: is clean supposed to be a list or a function?  You started as a list, but then replaced that with a function, and then told the function to clean itself.  Try this:

```<code>dirty_list = readWordList()
def clean(aList):
...

clean(dirty_list)
</code>```

Body:
I'm trying to write a program that will open a text file from the web consisting of 10,000 words, then 'clean' the file to get rid of nonsense words, such as 'aa'. I eventually want to use these words to do other things so I want to add the non 'non-sense' words to be put into a new list. Every time i try to run this I run into the error code TypeError: 'function' object is not iterable.

import urllib.request

def readWordList():

response = urllib.request.urlopen("http://www.mit.edu/~ecprice/wordlist.10000")
html = response.read()
data = html.decode('utf-8').split()

return data

clean = readWordList()

def clean(aList):
    newList = []
    for word in aList:
        if range(len(word)) >= 2:
            newList.append(word)
    return newList

clean(clean)

Body:
Make up your mind: is clean supposed to be a list or a function?  You started as a list, but then replaced that with a function, and then told the function to clean itself.  Try this:

dirty_list = readWordList()
def clean(aList):
...

clean(dirty_list)


问:
Dependency in Adjacent Elements while Updating 2d array (OpenMP)
I have a 2d array, say arr[SIZE][SIZE], which is updated in two for loops in the form:

```<code>for(int i = 0; i < SIZE; i++)
    for(int j = 0; j < SIZE; j++)
        arr[i][j] = new_value();
</code>```

that I am trying to parallelise using OpenMP.

There are two instances where this occurs, the first is the function new_value_1() which relies on arr[i+1][j] and arr[i][j+1] (the "edge of the array" issue is already taken care of), which I can happily parallelise using the chessboard technique:

```<code>for(int l = 0; l < 2; l++)
#pragma omp parallel for private(i, j)
    for(int i = 0; i < SIZE; i++)
        for(int j = (i + l) % 2; j < SIZE; j += 2)
            arr[i][j] = new_value_1();
</code>```

The issue comes with this second instance, new_value_2(), which relies upon:

```<code>arr[i+1][j],
arr[i-1][j],
arr[i][j+1],
arr[i][j-1]
</code>```

i.e. the adjacent elements in all directions.

Here, there is a dependency on the negative adjacent elements, so arr[0][2] = new_value_2() depends on the already updated value of arr[0][1] which would not be computed until the second l loop.

I was wondering if there was something I was missing in parallelising this way or if the issue is inherent with the way the algorithm works? If the former, any other approaches would be appreciated.

答:
I was wondering if there was something I was missing in parallelising this way or if the issue is inherent with the way the algorithm works?

Yes, you're missing something, but not along the lines you probably hoped.  Supposing that the idea is that the parallel version should compute the same result as the serial version, the checkerboard approach does not solve the problem even for the new_value_1() case.  Consider this layout of array elements:

```<code>xoxoxo
oxoxox
xoxoxo
oxoxox
</code>```

On the first of the two checkerboard passes, the 'x' elements are updated according to the original values of the 'o' elements -- so far, so good -- but on the second pass, the 'o' elements are updated based on the new values of the 'x' elements.  The data dependency is broken, yes, but the overall computation is not the same.  Of course, the same applies even more so to the new_value_2() computation.  The checkerboarding doesn't really help you.

If the former, any other approaches would be appreciated.

You could do the computation in shells.  For example, consider this labeling of the array elements:

```<code>0123
1234
2345
3456
</code>```

All the elements with the same label can be computed in parallel (for both new_value() functions), provided that all those with numerically lesser labels are computed first.  That might look something like this:

```<code>for(int l = 0; l < (2 * SIZE - 1); l++) {
    int iterations = (l < SIZE) ? (l + 1) : (2 * SIZE - (l + l));
    int i = (l < SIZE) ? l : (SIZE - 1);
    int j = (l < SIZE) ? 0 : (1 + l - SIZE);

    #pragma omp parallel for private(i, j, m)
    for(int m = 0; m < iterations; m++) {
        arr[i--][j++] = new_value_1();
    }
}
</code>```

You won't that way get as much of a benefit from parallelization, but that  is an inherent aspect of the way the serial computation works, at least for the new_value_2() case.

For the new_value_1() case, though, you might do a little better by going row by row:

```<code>for(int i = 0; i < SIZE; i++)
    #pragma omp parallel for private(j)
    for(int j = 0; j < SIZE; j++)
        arr[i][j] = new_value_1();
</code>```

Alternatively, for the new_value_1() case only, you could potentially get a good speedup by storing the results in a separate array:

```<code>#pragma omp parallel for private(i, j), collapse(2)
for(int i = 0; i < SIZE; i++)
    for(int j = 0; j < SIZE; j++)
        arr2[i][j] = new_value_1();
</code>```

If that requires you to copy the result back to the original array afterward then it might well not be worth it, but you could potentially avoid that by flipping back and forth between two arrays: compute from the first into the second, and then the next time around, compute from the second into the first ( if the problem [PSPACE] scaling permits having such an extended in-RAM allocation, i.e. it again comes at a [PTIME] cost, hopefully paid just once ).

Body:
I have a 2d array, say arr[SIZE][SIZE], which is updated in two for loops in the form:

for(int i = 0; i < SIZE; i++)
    for(int j = 0; j < SIZE; j++)
        arr[i][j] = new_value();

that I am trying to parallelise using OpenMP.

There are two instances where this occurs, the first is the function new_value_1() which relies on arr[i+1][j] and arr[i][j+1] (the "edge of the array" issue is already taken care of), which I can happily parallelise using the chessboard technique:

for(int l = 0; l < 2; l++)
#pragma omp parallel for private(i, j)
    for(int i = 0; i < SIZE; i++)
        for(int j = (i + l) % 2; j < SIZE; j += 2)
            arr[i][j] = new_value_1();

The issue comes with this second instance, new_value_2(), which relies upon:

arr[i+1][j],
arr[i-1][j],
arr[i][j+1],
arr[i][j-1]

i.e. the adjacent elements in all directions.

Here, there is a dependency on the negative adjacent elements, so arr[0][2] = new_value_2() depends on the already updated value of arr[0][1] which would not be computed until the second l loop.

I was wondering if there was something I was missing in parallelising this way or if the issue is inherent with the way the algorithm works? If the former, any other approaches would be appreciated.

Body:
I was wondering if there was something I was missing in parallelising this way or if the issue is inherent with the way the algorithm works?

Yes, you're missing something, but not along the lines you probably hoped.  Supposing that the idea is that the parallel version should compute the same result as the serial version, the checkerboard approach does not solve the problem even for the new_value_1() case.  Consider this layout of array elements:

xoxoxo
oxoxox
xoxoxo
oxoxox

On the first of the two checkerboard passes, the 'x' elements are updated according to the original values of the 'o' elements -- so far, so good -- but on the second pass, the 'o' elements are updated based on the new values of the 'x' elements.  The data dependency is broken, yes, but the overall computation is not the same.  Of course, the same applies even more so to the new_value_2() computation.  The checkerboarding doesn't really help you.

If the former, any other approaches would be appreciated.

You could do the computation in shells.  For example, consider this labeling of the array elements:

0123
1234
2345
3456

All the elements with the same label can be computed in parallel (for both new_value() functions), provided that all those with numerically lesser labels are computed first.  That might look something like this:

for(int l = 0; l < (2 * SIZE - 1); l++) {
    int iterations = (l < SIZE) ? (l + 1) : (2 * SIZE - (l + l));
    int i = (l < SIZE) ? l : (SIZE - 1);
    int j = (l < SIZE) ? 0 : (1 + l - SIZE);

    #pragma omp parallel for private(i, j, m)
    for(int m = 0; m < iterations; m++) {
        arr[i--][j++] = new_value_1();
    }
}

You won't that way get as much of a benefit from parallelization, but that  is an inherent aspect of the way the serial computation works, at least for the new_value_2() case.

For the new_value_1() case, though, you might do a little better by going row by row:

for(int i = 0; i < SIZE; i++)
    #pragma omp parallel for private(j)
    for(int j = 0; j < SIZE; j++)
        arr[i][j] = new_value_1();

Alternatively, for the new_value_1() case only, you could potentially get a good speedup by storing the results in a separate array:

#pragma omp parallel for private(i, j), collapse(2)
for(int i = 0; i < SIZE; i++)
    for(int j = 0; j < SIZE; j++)
        arr2[i][j] = new_value_1();

If that requires you to copy the result back to the original array afterward then it might well not be worth it, but you could potentially avoid that by flipping back and forth between two arrays: compute from the first into the second, and then the next time around, compute from the second into the first ( if the problem [PSPACE] scaling permits having such an extended in-RAM allocation, i.e. it again comes at a [PTIME] cost, hopefully paid just once ).


问:
Sparseness of 2D set
Define the sparseness of a set S of elements (x, y), with x, y real numbers, to be the minimal real number d, satisfying that, for any element v in S, the closed, punctured-ball centered at v, with radius d, is non empty (By punctured-ball, that is, the ball not including it's center). It is clear that such a d exists, and is unique, if S nonempty.

Find the sparseness of a given set.

Clearly, we have the naive quadratic-time solution.

答:
If I understand correctly, the naive solution is to take the distance closest point to each point, and the answer is the maximum of those minimums.

Build an MST (minimum spanning tree) of your points. (Formally, that is the MST of a complete graph, where points are vertices and the weight of an edge it the distance between corresponding points.) MST has a property: for each vertex, the smallest edge incident to it is in the MST. So it is enough to check only edges from the MST to find the answer.

The fastest way to build an MST of a set of points is to build at Delaunay triangulation on it and then find the MST of it using Kruskal's algorithm. Both steps take O(n log n) time, and that is the overall running time of the algorithm.

However, building Delaunay triangulation is rather complex, so consider searching for existing libraries rather than coding it from scratch.

Title: Sparseness of 2D set


问:
Arrow function closure within for loop
Given this:

```<code>var m = 5;

for (i = 0; i < m; i++) {
    add_row('row-'+(i+1), () => f(i))
}
</code>```

if I do an alert in my f the it will always output the value 5. I believe this is due to the same problem mention here for python:

lambda function don't closure the parameter in Python?

How is this problem solved in javascript?

答:
This is because add_row() is asynchronous.  It calls the callback you pass it sometime LATER when the operation finishes.  Meanwhile, the for loop has already finished.  One simple solution in ES6, is to use let with your for loop.  This creates a new and separate i variable for each run of the loop so when the callback is called sometime LATER, the variable i for that invocation of the loop is still at it was when the function was started.

If you were to insert some console.log() statements into your code like this:

```<code>var m = 3;

console.log("A");
for (i = 0; i < m; i++) {
    console.log("B" + i);
    add_row('row-'+(i+1), () => {
        console.log("C" + i);
        f(i);
    })
}
console.log("D");
</code>```

What you would see in the console is this:

```<code> A
 B0
 B1
 B2
 D
 C0
 C1
 C2
</code>```

Notice how "D" comes before any of the "Cx" lines.  That shows you how the asynchronous callback is called LATER after your for loop is done executing.

Please study that and when you fully understand the reasoning for that order, then you will finally understand an asynchronous callback.  Technically, the C0, C1 and C2 will be at the end, but could be in any order relative to each other.

Here's how you can use let for the for loop to create a separate variable i for each iteration of the loop so you will still have the appropriate value of i when the callback is called some time later:

```<code>for (let i = 0; i < m; i++) {
    add_row('row-'+(i+1), () => f(i))
}
</code>```

Before ES6, one could fix this by creating an extra closure which creates a new function scoped variable to "remember" the loop index separately for each invocation:

```<code>for (var i = 0; i < m; i++) {
    (function(index) {
        add_row('row-'+(index+1), () => f(index))
    })(i);
}
</code>```

Title: Arrow function closure within for loop

Body:
Given this:

var m = 5;

for (i = 0; i < m; i++) {
    add_row('row-'+(i+1), () => f(i))
}

if I do an alert in my f the it will always output the value 5. I believe this is due to the same problem mention here for python:

lambda function don't closure the parameter in Python?

How is this problem solved in javascript?

Body:
This is because add_row() is asynchronous.  It calls the callback you pass it sometime LATER when the operation finishes.  Meanwhile, the for loop has already finished.  One simple solution in ES6, is to use let with your for loop.  This creates a new and separate i variable for each run of the loop so when the callback is called sometime LATER, the variable i for that invocation of the loop is still at it was when the function was started.

If you were to insert some console.log() statements into your code like this:

var m = 3;

console.log("A");
for (i = 0; i < m; i++) {
    console.log("B" + i);
    add_row('row-'+(i+1), () => {
        console.log("C" + i);
        f(i);
    })
}
console.log("D");

What you would see in the console is this:

 A
 B0
 B1
 B2
 D
 C0
 C1
 C2

Notice how "D" comes before any of the "Cx" lines.  That shows you how the asynchronous callback is called LATER after your for loop is done executing.

Please study that and when you fully understand the reasoning for that order, then you will finally understand an asynchronous callback.  Technically, the C0, C1 and C2 will be at the end, but could be in any order relative to each other.

Here's how you can use let for the for loop to create a separate variable i for each iteration of the loop so you will still have the appropriate value of i when the callback is called some time later:

for (let i = 0; i < m; i++) {
    add_row('row-'+(i+1), () => f(i))
}

Before ES6, one could fix this by creating an extra closure which creates a new function scoped variable to "remember" the loop index separately for each invocation:

for (var i = 0; i < m; i++) {
    (function(index) {
        add_row('row-'+(index+1), () => f(index))
    })(i);
}


问:
Can I Limit The Moving With svg-pan-zoom?
I'm using svgpanzoom, but movement is unlimited. Is there a way to limit this? I do not want to limit the zoom, I want to limit the movement of svg.

Example:

After too much moving.

答: There is a demo with how it's possible to implement pan limit on github


问:
.getJSON only works on Flask Dev not IIS 8 when there is an html tag in value
I have the following client-side JavaScript code that works just fine when using python-Flask Dev server, irrespective what type of content $('#b_comment_selected').text() has. Here is the JS code.

```<code>function some_editing(){
$.getJSON($SCRIPT_ROOT + "/_edit_me",
{
content: $('#b_comment_selected').text(),
label: $('#b_label_selected' ).text()
},
function () { //do something}
)
}
</code>```

It also works when I run it on IIS and $('#b_comment_selected').text() does not contain any html tags. But the code does not work when there are html tags in $('#b_comment_selected').text(). The error I get in Chrome's console is a 403 Failed to load resource: the server responded with a status of 403 (HTTP/1.1 403 Forbidden)

My questions are:
why does it work in the flask dev environment?
Why does it not work on IIS?
And how to fix it?

If I had to guess it has to do with characters like < or > but I can't find a definitive answer to my set of questions.

答:
So the Solution was to replace the getJSON method with the ajax method, and this answered my third question "how to fix it?". And I think the first comment to the accepted answer in here jQuery - .getjson VS .ajax json
answers my first and second question, in the context of securities in place on IIS, but then again I am not hundred percent sure.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have the following client-side JavaScript code that works just fine when using python-Flask Dev server, irrespective what type of content $('#b_comment_selected').text() has. Here is the JS code.

function some_editing(){
$.getJSON($SCRIPT_ROOT + "/_edit_me",
{
content: $('#b_comment_selected').text(),
label: $('#b_label_selected' ).text()
},
function () { //do something}
)
}

It also works when I run it on IIS and $('#b_comment_selected').text() does not contain any html tags. But the code does not work when there are html tags in $('#b_comment_selected').text(). The error I get in Chrome's console is a 403 Failed to load resource: the server responded with a status of 403 (HTTP/1.1 403 Forbidden)

My questions are:
why does it work in the flask dev environment?
Why does it not work on IIS?
And how to fix it?

If I had to guess it has to do with characters like < or > but I can't find a definitive answer to my set of questions.


问:
PHP Extracting MYSQL Value Issue
I have 2 tables: users and transactions

In users I have: userid, name, email

And in transactions I have: id, idsender, idreceiver

I want to make a log-table showing all the transactions and I want them to be displayed like: Transaction ID - SENDER'S NAME - RECEIVER'S NAME

I tried like this but it doesn't seem to work, at "Receiver" it doesn't show anything .. :

```<code>echo "<table>";
echo "<tr>";
echo "<th>Transaction ID</th>";
echo "<th>Sender</th>";
echo "<th>Receiver</th>";
echo "</tr>";

    $resultuser = mysqli_query($conn, "SELECT * FROM users");
    $rowuser=mysqli_fetch_array($resultuser);

    $resulttrans = mysqli_query($conn, "SELECT * FROM transactions");
    $rowtrans=mysqli_fetch_array($resulttrans);

    $ress=mysqli_query($conn, "SELECT * FROM transactions");

            while($row=mysqli_fetch_array($ress)){
                echo "<tr>";
                echo "<td>".$row['id']."</td>";
                echo "<td>"." same as receiver"."</td>";
            $receiver=mysqli_query($conn, "SELECT name FROM users WHERE userid='" . $rowtrans['idreceiver'] . "'");
            $receivername = mysqli_fetch_array($receiver);

                echo "<td>". $receivername ."</td>";
                echo "</tr>";
            }
</code>```

答:
You are echoing from fetched array in $receivername = mysqli_fetch_array($receiver);

you should do echo "". $receivername['name'] ."	";

Note:
Fetched array from mysqli_fetch_array() can be echoed using indexes by number $receivername[0] or by string $receivername['name'], that is where you are missing here.

Title: PHP Extracting MYSQL Value Issue

Body:
I have 2 tables: users and transactions

In users I have: userid, name, email

And in transactions I have: id, idsender, idreceiver

I want to make a log-table showing all the transactions and I want them to be displayed like: Transaction ID - SENDER'S NAME - RECEIVER'S NAME

I tried like this but it doesn't seem to work, at "Receiver" it doesn't show anything .. :

echo "
";
echo "
";
echo "Transaction ID	";
echo "Sender	";
echo "Receiver	";
echo "
";

    $resultuser = mysqli_query($conn, "SELECT * FROM users");
    $rowuser=mysqli_fetch_array($resultuser);

    $resulttrans = mysqli_query($conn, "SELECT * FROM transactions");
    $rowtrans=mysqli_fetch_array($resulttrans);

    $ress=mysqli_query($conn, "SELECT * FROM transactions");

            while($row=mysqli_fetch_array($ress)){
                echo "
";
                echo "".$row['id']."	";
                echo ""." same as receiver"."	";
            $receiver=mysqli_query($conn, "SELECT name FROM users WHERE userid='" . $rowtrans['idreceiver'] . "'");
            $receivername = mysqli_fetch_array($receiver);

                echo "". $receivername ."	";
                echo "
";
            }

Body:
You are echoing from fetched array in $receivername = mysqli_fetch_array($receiver);

you should do echo "<td>". $receivername['name'] ."</td>";

Note:
Fetched array from mysqli_fetch_array() can be echoed using indexes by number $receivername[0] or by string $receivername['name'], that is where you are missing here.


答:
You create a variable called clean, immediately overwrite the name by declaring a function with the same name, then pass the function clean to itself.

Either change the function name, or the variable above with the same name.

Title: TypeError: 'function' object is not iterable' Python 3


问:
List append in pandas cell
I have a dataframe  which contains list item in a column.

Example:
df:

```<code>column1, column2, column3
1         'c'       ['d']
2         'x'       []
3         'foo'     ['car']
</code>```

so I want to append another item into column3

the result should be like this

```<code>column1, column2, column3
1         'c'       ['d','t']
2         'x'       ['t']
3         'foo'     ['car','t']
</code>```

Currently I use the method like this

```<code>df['column3']=df['column3'].apply(lambda x: x.append('t'))
</code>```

But the the column3 became

```<code>column1, column2, column3
1         'c'       none
2         'x'       none
3         'foo'     none
</code>```

Wonder how to do that using apply function

答:
Here's how to do it with apply().  Use + instead of append().

```<code>df.column3 = df.column3.apply(lambda x: x+['t'])
</code>```

Title: List append in pandas cell

Body:
I have a dataframe  which contains list item in a column.

Example:
df:

column1, column2, column3
1         'c'       ['d']
2         'x'       []
3         'foo'     ['car']

so I want to append another item into column3

the result should be like this

column1, column2, column3
1         'c'       ['d','t']
2         'x'       ['t']
3         'foo'     ['car','t']

Currently I use the method like this

df['column3']=df['column3'].apply(lambda x: x.append('t'))

But the the column3 became

column1, column2, column3
1         'c'       none
2         'x'       none
3         'foo'     none

Wonder how to do that using apply function

Body:
Here's how to do it with apply().  Use + instead of append().

df.column3 = df.column3.apply(lambda x: x+['t'])


问:
low priority and high priority implicits in scala
In following code from Scala's puzzlers, it seems that there is no conflict in implicits because TestAlarmHandler is more specific. I didn't understand the explanation though. Why is TestAlarmHandler is more specific than DefaultAlarmHandler?

```<code>object Scanner {
  trait Console { def display(item: String) }
  trait AlarmHandler extends (() => Unit)
  def scanItem(item: String)(implicit c: Console) {
    c.display(item)
  }
  def hitAlarmButton()(implicit ah: AlarmHandler) { ah() }
}

class OperatingMode {
  implicit val ConsoleRenderer = new Scanner.Console {
    def display(item: String) { println(s"Found a ${item}") }
  }
  implicit val DefaultAlarmHandler = new Scanner.AlarmHandler {
    def apply() { println("ALARM! ALARM!") }
  }
}
object NormalMode extends OperatingMode
object TestMode extends OperatingMode {
  override implicit val ConsoleRenderer = new Scanner.Console {
    def display(item: String) { println("Found a detonator") }
  }
  implicit val TestAlarmHandler = new Scanner.AlarmHandler {
    def apply() { println("Test successful. Well done!") }
  }
}
import NormalMode._
scala> Scanner scanItem "knife"
Found a knife
scala> Scanner.hitAlarmButton()
ALARM! ALARM!
import TestMode._
scala> Scanner scanItem "shoe"
Found a detonator
scala> Scanner.hitAlarmButton()
Test successful. Well done!
</code>```

答: That's because TestMode is subclass of OperationMode, and scala at first look for implicits in scope of TestMode and only if not found it will lookup up in hierarchy.   </p>

Body:
In following code from Scala's puzzlers, it seems that there is no conflict in implicits because TestAlarmHandler is more specific. I didn't understand the explanation though. Why is TestAlarmHandler is more specific than DefaultAlarmHandler?

object Scanner {
  trait Console { def display(item: String) }
  trait AlarmHandler extends (() => Unit)
  def scanItem(item: String)(implicit c: Console) {
    c.display(item)
  }
  def hitAlarmButton()(implicit ah: AlarmHandler) { ah() }
}

class OperatingMode {
  implicit val ConsoleRenderer = new Scanner.Console {
    def display(item: String) { println(s"Found a ${item}") }
  }
  implicit val DefaultAlarmHandler = new Scanner.AlarmHandler {
    def apply() { println("ALARM! ALARM!") }
  }
}
object NormalMode extends OperatingMode
object TestMode extends OperatingMode {
  override implicit val ConsoleRenderer = new Scanner.Console {
    def display(item: String) { println("Found a detonator") }
  }
  implicit val TestAlarmHandler = new Scanner.AlarmHandler {
    def apply() { println("Test successful. Well done!") }
  }
}
import NormalMode._
scala> Scanner scanItem "knife"
Found a knife
scala> Scanner.hitAlarmButton()
ALARM! ALARM!
import TestMode._
scala> Scanner scanItem "shoe"
Found a detonator
scala> Scanner.hitAlarmButton()
Test successful. Well done!


答:
Just use:

```<code>df['column3'] += ['t']
</code>```

Instead of apply. The problem is .append works in-place and returns None

You of course could do something silly if you really wanted to use .apply + lambda:

```<code>df.column3.apply(lambda x: x.append('t') or x)
</code>```

Title: List append in pandas cell

Body:
Just use:

df['column3'] += ['t']

Instead of apply. The problem is .append works in-place and returns None

You of course could do something silly if you really wanted to use .apply + lambda:

df.column3.apply(lambda x: x.append('t') or x)


问:
jquery uniform pixelmatrixdesign
I have a problem with slow computers/browsers, before rendering the styled uniform dropdowns, the users see the "normal" drops, and then it changes to the applied style.

I can´t find a callback function where i could show a div after the style is applied

答:
Have you placed your code in</p>

```<code>$(document).ready( function(){
    //Code here
})
</code>```

Title: jquery uniform pixelmatrixdesign

Body:
Have you placed your code in

$(document).ready( function(){
    //Code here
})


问:
Laravel Event on register won't display with socket
I am trying to Show new registered users in my browser, so users who are already logged in can see something like  "blabla has registered..."

First I created an Event class with its channel like this:

```<code>class UserSignedUp extends Event implements ShouldBroadcast
{
    use SerializesModels;

    public $user;

    public function __construct($user)
    {
        $this->user = $user;
    }

    public function broadcastOn()
    {
        return ['signed-up-channel'];
    }
}
</code>```

I used laravel auth scaffolding to built a Basic Login/Register System, so I went inside the Auth/RegisterController and added a function to call the Event if a user Registers like this:

```<code>protected function create(array $data)
{
    $this->user = [
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ];

    # fire event
    $this->broadcastSignedUpUsers($this->user);

    return User::create($this->user);
}

# Call UserSignedUp Event and show using node + socket.io
protected function broadcastSignedUpUsers($user)
{
    event(new UserSignedUp($user));
}
</code>```

I installed node.js, socket.io and redis.

```<code>I built following script to create a Server:

var server = require('http').Server();

var io = require('socket.io')(server);

// class declaration
var Redis = require('ioredis');

// Redis UserSignedUp Channel
var redisSignedUp = new Redis();

redisSignedUp.subscribe('signed-up-channel');

redisSignedUp.on('message', function(channel, message) {
    message = JSON.parse(message);
    console.log(message.data.user);
    io.emit(channel + ':' + message.event, message.data);
});

// run server on port 3000
server.listen(3000);
</code>```

I run that Server successfully with this command: node socket.js

Further I have this vue script to push the registered users in an array

```<code>var socket = io('http://192.168.3.114:3000');

new Vue({

    el: '#app',

   data: {
       users: []
   },

   ready: function() {
       socket.on('signed-up-channel:App\\Event\\UserSignedUp', function(data) {
           console.log(data);
           this.users.push(data.user);
       }.bind(this));
   }

});
</code>```

And in my blade view I have this li to show new registered users

```<code><li v-for="user in users">@{{ user.name }}</li>
</code>```

if I register using another browser that user is not displayed, but the users information gets display in my command line like this:
C:\xampp\htdocs\myApp (master)

λ node socket.js

  { name: 'asdasd',

  email: 'aascasc@asda.de',

  password:
  '$2y$10$yujB1ZSFEezVeZ77Jec67.Mws3qeD7bnx3QaVhJACXo58KBy3E3iG' }

答:
When I am using events with socket.io via redis I have to use the following traits: Dispatchable, InteractsWithSockets, SerializesModels.

These traits are in the docs

Implementation

```<code>class CampaignChanged extends Event implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $campaign;

    public function __construct(Campaign $campaign)
    {
        $this->campaign = $campaign;
    }

    public function broadcastOn()
    {
        return new Channel('campaign-changed');
    }
}
</code>```

socket.js

```<code>let app = require('express')();
let http = require('http').Server(app);
let io = require('socket.io')(http);
let Redis = require('ioredis');
let redis = new Redis();

redis.subscribe(['campaign-changed','canceled-bid','winning-bid','highest-bid','no-bids'], function(err, count) {});

redis.on('message', function(channel, message) {
    message = JSON.parse(message);
    if(channel === 'campaign-changed'){
        io.emit('campaign-changed:' + message.data.campaign.id, message.data);
    }
    else {
        io.emit(channel + ':' + message.data.item.id, message.data);
    }
});

http.listen(3000, function(){
    console.log('Listening on Port 3000');
});
</code>```

usage:

```<code>window.socket = io('http://192.168.10.10:3000');

socket.on("campaign-changed:"+this.campaign.id, message =>{
    this.campaign = message.campaign;
});
</code>```

Body:
I am trying to Show new registered users in my browser, so users who are already logged in can see something like  "blabla has registered..."

First I created an Event class with its channel like this:

class UserSignedUp extends Event implements ShouldBroadcast
{
    use SerializesModels;

    public $user;

    public function __construct($user)
    {
        $this->user = $user;
    }

    public function broadcastOn()
    {
        return ['signed-up-channel'];
    }
}

I used laravel auth scaffolding to built a Basic Login/Register System, so I went inside the Auth/RegisterController and added a function to call the Event if a user Registers like this:

protected function create(array $data)
{
    $this->user = [
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ];

    # fire event
    $this->broadcastSignedUpUsers($this->user);

    return User::create($this->user);
}

# Call UserSignedUp Event and show using node + socket.io
protected function broadcastSignedUpUsers($user)
{
    event(new UserSignedUp($user));
}

I installed node.js, socket.io and redis.

I built following script to create a Server:

var server = require('http').Server();

var io = require('socket.io')(server);

// class declaration
var Redis = require('ioredis');

// Redis UserSignedUp Channel
var redisSignedUp = new Redis();

redisSignedUp.subscribe('signed-up-channel');

redisSignedUp.on('message', function(channel, message) {
    message = JSON.parse(message);
    console.log(message.data.user);
    io.emit(channel + ':' + message.event, message.data);
});

// run server on port 3000
server.listen(3000);

I run that Server successfully with this command: node socket.js

Further I have this vue script to push the registered users in an array

var socket = io('http://192.168.3.114:3000');

new Vue({

    el: '#app',

   data: {
       users: []
   },

   ready: function() {
       socket.on('signed-up-channel:App\\Event\\UserSignedUp', function(data) {
           console.log(data);
           this.users.push(data.user);
       }.bind(this));
   }

});

And in my blade view I have this li to show new registered users

@{{ user.name }}

if I register using another browser that user is not displayed, but the users information gets display in my command line like this:
C:\xampp\htdocs\myApp (master)

λ node socket.js

  { name: 'asdasd',

  email: 'aascasc@asda.de',

  password:
  '$2y$10$yujB1ZSFEezVeZ77Jec67.Mws3qeD7bnx3QaVhJACXo58KBy3E3iG' }

Body:
When I am using events with socket.io via redis I have to use the following traits: Dispatchable, InteractsWithSockets, SerializesModels.

These traits are in the docs

Implementation

class CampaignChanged extends Event implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $campaign;

    public function __construct(Campaign $campaign)
    {
        $this->campaign = $campaign;
    }

    public function broadcastOn()
    {
        return new Channel('campaign-changed');
    }
}

socket.js

let app = require('express')();
let http = require('http').Server(app);
let io = require('socket.io')(http);
let Redis = require('ioredis');
let redis = new Redis();

redis.subscribe(['campaign-changed','canceled-bid','winning-bid','highest-bid','no-bids'], function(err, count) {});

redis.on('message', function(channel, message) {
    message = JSON.parse(message);
    if(channel === 'campaign-changed'){
        io.emit('campaign-changed:' + message.data.campaign.id, message.data);
    }
    else {
        io.emit(channel + ':' + message.data.item.id, message.data);
    }
});

http.listen(3000, function(){
    console.log('Listening on Port 3000');
});

usage:

window.socket = io('http://192.168.10.10:3000');

socket.on("campaign-changed:"+this.campaign.id, message =>{
    this.campaign = message.campaign;
});


问:
Is it possible for Visual Studio 2008 Automatically create XML Comments tags without "Generate XML documentation file" checked (VB.NET only)?
When in VS 2008 if a developer hits the ''' it generates the XML comment tags for you, but this only works when the project setting for "Generate XML documentation file" is checked.

Is there a way to tell VS to generate the XML Comment tags, regardless of the project setting?

I think it is possible that someone may want comments but not create a XML documentation file.

In this case I am exceeding the current Team Settings, yet other developers don't want me to change this project setting. This forces me to flip this back before checking in the project.

I have the same problem with other Project settings like "code Analysis".

This is only a problem for VB.NET projects.

答:
I know this is an old post however I have found a work around that may work for you depending if you team members just want the XML comments functionality and not the XML files.

1) In your project properties ensure that Generate XML documention file is checked.

2) Click the Build Events  button

3) Into the Post-build event command line box enter the command

Del "$(OutDir)$(ProjectName).xml"

Now after each build it will remove the XML comment file.

Note: For some reason if it exists from a previous build it will not delete it so manually delete it the first time.


问:
mySQL error datetime value error for str_to_date?
This error comes from this code which i can't figure out whats wrong;

#1411 - Incorrect datetime value: '11:00 PM' for function str_to_date

```<code>CREATE TABLE OWNS (
STUDNO       NUMERIC(9) NOT NULL,
ENAME         CHAR(30) NOT NULL,
TYPE          CHAR(15) NOT NULL,
OTIME         TIME,
ODATE         DATE,
ODRTN         VARCHAR(7) NOT NULL,
CONSTRAINT OWNS_FOREIGN_KEY FOREIGN KEY (STUDNO) REFERENCES STUD(STUDNO));

INSERT INTO OWNS (STUDNO, ENAME, TYPE, OTIME,ODATE, ODRTN)
VALUES(123456789,'The Lion King','Anti', str_to_date('11:00 PM', '%l:%i
%p'), STR_TO_DATE('16-jan-2011', '%d-%b-%y'), 3)
</code>```

Appreciate the help thanks!!!

答: Try '%h:%i %p' as your mask for the time instead. I've always used '%h' for hours.</p>

Body:
This error comes from this code which i can't figure out whats wrong;

#1411 - Incorrect datetime value: '11:00 PM' for function str_to_date

CREATE TABLE OWNS (
STUDNO       NUMERIC(9) NOT NULL,
ENAME         CHAR(30) NOT NULL,
TYPE          CHAR(15) NOT NULL,
OTIME         TIME,
ODATE         DATE,
ODRTN         VARCHAR(7) NOT NULL,
CONSTRAINT OWNS_FOREIGN_KEY FOREIGN KEY (STUDNO) REFERENCES STUD(STUDNO));

INSERT INTO OWNS (STUDNO, ENAME, TYPE, OTIME,ODATE, ODRTN)
VALUES(123456789,'The Lion King','Anti', str_to_date('11:00 PM', '%l:%i
%p'), STR_TO_DATE('16-jan-2011', '%d-%b-%y'), 3)

Appreciate the help thanks!!!


问:
Convert a SQL query result table to an HTML table for email
I am running a SQL query that returns a table of results. I want to send the table in an email using dbo.sp_send_dbMail.

Is there a straightforward way within SQL to turn a table into an HTML table? Currently, I'm manually constructing it using COALESCE and putting the results into a varchar that I use as the emailBody.

Is there a better way to do this?

答:
All the other answers use variables and SET operations. Here's a way to do it within a select statement. Just drop this in as a column in your existing select.</p>

```<code>    (SELECT
        '<table style=''font-family:"Verdana"; font-size: 10pt''>'
                    + '<tr bgcolor="#9DBED4"><th>col1</th><th>col2</th><th>col3</th><th>col4</th><th>col5</th></tr>'
                    + replace( replace( body, '<', '<' ), '>', '>' )
                    + '</table>'
    FROM
    (
        select cast( (
            select td = cast(col1 as varchar(5)) + '</td><td align="right">' + col2 + '</td><td>' + col3 + '</td><td align="right">' + cast(col4 as varchar(5)) + '</td><td align="right">' + cast(col5 as varchar(5)) + '</td>'
            from (
                    select col1  = col1,
                            col2 = col2,
                            col3 = col3,
                            col4 = col4,
                            col5 = col5
                    from m_LineLevel as onml
                    where onml.pkey = oni.pkey
                    ) as d
            for xml path( 'tr' ), type ) as varchar(max) ) as body
    ) as bodycte) as LineTable
</code>```

Body:
All the other answers use variables and SET operations. Here's a way to do it within a select statement. Just drop this in as a column in your existing select.

    (SELECT
        '<table style=''font-family:"Verdana"; font-size: 10pt''>'
                    + '<tr bgcolor="#9DBED4"><th>col1</th><th>col2</th><th>col3</th><th>col4</th><th>col5</th></tr>'
                    + replace( replace( body, '&lt;', '<' ), '&gt;', '>' )
                    + '</table>'
    FROM
    (
        select cast( (
            select td = cast(col1 as varchar(5)) + '</td><td align="right">' + col2 + '</td><td>' + col3 + '</td><td align="right">' + cast(col4 as varchar(5)) + '</td><td align="right">' + cast(col5 as varchar(5)) + '</td>'
            from (
                    select col1  = col1,
                            col2 = col2,
                            col3 = col3,
                            col4 = col4,
                            col5 = col5
                    from m_LineLevel as onml
                    where onml.pkey = oni.pkey
                    ) as d
            for xml path( 'tr' ), type ) as varchar(max) ) as body
    ) as bodycte) as LineTable


问:
Ansible smtp mail send
I'm trying to send a mail fron Ansible.

```<code>- hosts: all
  tasks:
  - mail:
      host: smtp.gmail.com

      port: 587

      username: ****@gmail.com

      password: *******

      to: John Smith ***@gmail.com

      subject: 'Ansible-report'

      body: 'System  has been successfully provisioned.'

    delegate_to: localhost
</code>```

but I get an error

fatal: [host1 -> localhost]: FAILED! => {"changed": false, "failed":
  true, "msg": "Authentication to smtp.gmail.com:587 failed, please
  check your username and/or password", "rc": 1}

I use the example from the official site http://docs.ansible.com/ansible/latest/mail_module.html

As I understand, SMTP authentication already exists in the source new module ANSIBLE.
File "/tmp/ansible_K94pcN/ansible_module_mail.py", line 304, in main
    smtp.login(username, password)

File "/usr/lib64/python2.7/smtplib.py", line 621, in login
    raise SMTPAuthenticationError(code, resp)

fatal: [host1 -> localhost]: FAILED! => {
      "changed": false,

```<code>"failed": true,

"invocation": {

    "module_args": {

        "attach": null,
        "bcc": null,
        "body": "System ubuntu has been successfully provisioned.",
        "cc": null,
        "charset": "us-ascii",
        "headers": null,
        "host": "smtp.gmail.com",
        "password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
        "port": 587,
        "secure": "starttls",
        "sender": "root",
        "subject": "Ansible-report",
        "subtype": "plain",
        "timeout": 20,
        "to": "Cristiano Ross <cristianooross@gmail.com>",
        "username": "victorradin9@gmail.com"
    }
},
"msg": "Authentication to smtp.gmail.com:587 failed, please check your usern              ame and/or password",
"rc": 1
</code>```

答:
The issue your facing is an authentication issue caused by using the correct username & password to send email from a Gmail account without an app specific password assigned.

You'll need to:

a) Setup '2 step authentication' for the sender gmail account.

b) Then you'll need to create an app specific password in your google account settings.

Using that newly generated app specific password you'll be able to send mail just like in the example below

```<code>   - mail:
     host: smtp.gmail.com
     port: 587
     secure: starttls
     charset: utf-8
     sender: victorradin9@gmail.com
     username: victorradin9@gmail.com
     password: your app password generated by google for you goes here
     to: 'cristianooross@gmail.com'
     subject: Ya u rite
</code>```

Title: Ansible smtp mail send

Body:
I'm trying to send a mail fron Ansible.

- hosts: all
  tasks:
  - mail:
      host: smtp.gmail.com

      port: 587

      username: ****@gmail.com

      password: *******

      to: John Smith ***@gmail.com

      subject: 'Ansible-report'

      body: 'System  has been successfully provisioned.'

    delegate_to: localhost

but I get an error

fatal: [host1 -> localhost]: FAILED! => {"changed": false, "failed":
  true, "msg": "Authentication to smtp.gmail.com:587 failed, please
  check your username and/or password", "rc": 1}

I use the example from the official site http://docs.ansible.com/ansible/latest/mail_module.html

As I understand, SMTP authentication already exists in the source new module ANSIBLE.
File "/tmp/ansible_K94pcN/ansible_module_mail.py", line 304, in main
    smtp.login(username, password)

File "/usr/lib64/python2.7/smtplib.py", line 621, in login
    raise SMTPAuthenticationError(code, resp)

fatal: [host1 -> localhost]: FAILED! => {
      "changed": false,

"failed": true,

"invocation": {

    "module_args": {

        "attach": null,
        "bcc": null,
        "body": "System ubuntu has been successfully provisioned.",
        "cc": null,
        "charset": "us-ascii",
        "headers": null,
        "host": "smtp.gmail.com",
        "password": "VALUE_SPECIFIED_IN_NO_LOG_PARAMETER",
        "port": 587,
        "secure": "starttls",
        "sender": "root",
        "subject": "Ansible-report",
        "subtype": "plain",
        "timeout": 20,
        "to": "Cristiano Ross <cristianooross@gmail.com>",
        "username": "victorradin9@gmail.com"
    }
},
"msg": "Authentication to smtp.gmail.com:587 failed, please check your usern              ame and/or password",
"rc": 1

Body:
The issue your facing is an authentication issue caused by using the correct username & password to send email from a Gmail account without an app specific password assigned.

You'll need to:

a) Setup '2 step authentication' for the sender gmail account.

b) Then you'll need to create an app specific password in your google account settings.

Using that newly generated app specific password you'll be able to send mail just like in the example below

   - mail:
     host: smtp.gmail.com
     port: 587
     secure: starttls
     charset: utf-8
     sender: victorradin9@gmail.com
     username: victorradin9@gmail.com
     password: your app password generated by google for you goes here
     to: 'cristianooross@gmail.com'
     subject: Ya u rite


问:
How to disable selenium server port to outside world?
When I run selenium on server:

```<code>java -jar /usr/lib/selenium/selenium-server-standalone-3.7.0.jar
</code>```

The port 4444 is opened on all network interfaces also to outside world. Is there a way to run it only on 127.0.0.1 so I can run test only internally?

答:
specify hub and nodes to setup your own selenium grid

```<code>selenium-standalone start -- -role hub
selenium-standalone start -- -role node -hub http://localhost:4444/grid/register
selenium-standalone start -- -role node -hub http://localhost:4444/grid/register -port 5556
</code>```

Body:
When I run selenium on server:

java -jar /usr/lib/selenium/selenium-server-standalone-3.7.0.jar

The port 4444 is opened on all network interfaces also to outside world. Is there a way to run it only on 127.0.0.1 so I can run test only internally?

Body:
specify hub and nodes to setup your own selenium grid

selenium-standalone start -- -role hub
selenium-standalone start -- -role node -hub http://localhost:4444/grid/register
selenium-standalone start -- -role node -hub http://localhost:4444/grid/register -port 5556


问:
How to read private messages with PRAW?
I'm creating a Reddit bot with praw, and I want to have the bot do things based on private messages sent to it. I searched the documentation for a bit, but couldn't find anything on reading private messages, only sending them. I want to get both the title and the content of the message. So how can I do this?</p>

答:
Didn't find it in the docs, but a friend who knows a bit of raw helped me out.

Use for message in r.inbox.messages() (where r is an instance of reddit) to get the messages.

Use message.text to get the content, and message.subject to get the title.

Title: How to read private messages with PRAW?


问:
Calculate Time Remaining
What's a good algorithm for determining the remaining time for something to complete?  I know how many total lines there are, and how many have completed already, how should I estimate the time remaining?</p>

答:
Make sure to manage perceived performance.

Although all the progress bars took exactly the same amount of time in the test, two characteristics made users think the process was faster, even if it wasn't:

progress bars that moved smoothly towards completion

progress bars that sped up towards the end

OwnerDisplayName: Aaron Smith

Title: Calculate Time Remaining

OwnerDisplayName: ajmastrean


问:
How do I find all the modules used by a Perl script?
I'm getting ready to try to deploy some code to multiple machines. As far as I know, using a Makefile.pm to track dependencies is the best way to ensure they are installed everywhere.  The problem I have is I'm not sure our Makefile.pm has been updated as this application has passed through a few different developers.

Is there any way to automatically parse through either my source or a few full runs of my program to determine exactly what versions of what modules my application is depending on?  On top of that, is there any way to filter it based on CPAN packages? (So that I only depend on Moose instead of every single module that comes with Moose.)

A third related question is, if you depend on a version of a module that is not the latest, what is the best way to have someone else install it? Should I start including entire localized Perl installations with my application?

答:
Just to be clear - you can not generically get a list of modules that the app depends on by code analysis alone. E.g. if your apps does eval { require $module; $module->import() }, where $module is passed via command line, then this can ONLY be detected by actually running the specific command line version with ALL the module values.

If you do wish to do this, you can figure out every module used by a combination of runs via:

Devel::Cover. Coverage reports would list 100% of modules used. But you don't get version #s.

Print %INC at every single possible exit point in the code as slu's answer said. This should probably be done in END{} block as well as __DIE__ handler to cover all possible exit points, and even then may be not fully 100% covering in generic case if somewhere within the program your __DIE__ handler gets overwritten.

Devel::Modlist (also mentioned by slu's answer) - the downside compared to Devel::Cover is that it does NOT seem to be able to aggregate a database across multiple sample runs like Devel::Cover does. On the plus side, it's purpose-built, so has a lot of very useful options (CPAN paths, versions).

Please note that the other module (Module::ScanDeps) does NOT seem to allow you to do runtime analysis based on arbitrary command line arguments (e.g. it seems at first glance to only allow you to execute the program with no arguments) and if that's true, is inferior to all the above 3 methods for any code that may possibly load modules dynamically.


问:
TimeZone in Strongloop API?
I am trying to defined timezone for specific region(India) in Strong loopback but I am unable to find a solution.

I am using this code to defined the timezone in strong loopback.

```<code> var moment = require('moment-timezone');
 var time_moment= moment().tz("Asia/Kolkata").format();
</code>```

I am also use another code to defined the timezone,
I defined the timezone in datasource.json but asusual is not working.

```<code>"host": "localhost",
"port": "3306",
"database": "test_check",
"username": "root",
"password": "",
"name": "new_file",
"connector": "mysql",
"timezone": "UTC+05:30"
</code>```

答:
since Loopback use mysql.js; you can set timezone based on the @@global.time_zone value.

you can add the timezone as follows:

```<code>"host": "localhost",
"port": "3306",
"database": "test_check",
"username": "root",
"password": "",
"name": "new_file",
"connector": "mysql",
"timezone": "Asia/Kolkata"
</code>```

Title: TimeZone in Strongloop API?

Body:
I am trying to defined timezone for specific region(India) in Strong loopback but I am unable to find a solution.

I am using this code to defined the timezone in strong loopback.

 var moment = require('moment-timezone');
 var time_moment= moment().tz("Asia/Kolkata").format();

I am also use another code to defined the timezone,
I defined the timezone in datasource.json but asusual is not working.

"host": "localhost",
"port": "3306",
"database": "test_check",
"username": "root",
"password": "",
"name": "new_file",
"connector": "mysql",
"timezone": "UTC+05:30"

Body:
since Loopback use mysql.js; you can set timezone based on the @@global.time_zone value.

you can add the timezone as follows:

"host": "localhost",
"port": "3306",
"database": "test_check",
"username": "root",
"password": "",
"name": "new_file",
"connector": "mysql",
"timezone": "Asia/Kolkata"


问:
Batch add LoadBalancers to AutoScaling Groups with CloudFormation
We have an AWS CloudFormation template that creates a single AutoScaling group and then adds LoadBalancers to it. Unfortunately there is a limit to how many LoadBalancers you can add at any  one time. Ten to be precise. Does anybody know if it is possible to batch add the LoadBalancers?
We have to stick with CloudFormation as it is supplied by the vendor of the Market Place AMI we are using, although we can tweak it slightly.</p>

答:
AWS Auto Scaling Limits does limit ASG attach or detach to at most 10 at a time. This is the source of that limit.

If you can, you would break the template into two parts: Part 1 would create only the ASG, and Part 2 would add 10 ELB at one time. Part 1 would export the ID of the ASG, which would be referenced in Part 2.

Then you you would need to write a script that would call the Part 2 template as many times as you like, while looping/waiting for the first 10 attachments to complete.

With this approach you could add up to the max of 50 ELBs per ASG.


问:
Spring controller: Content-Type for StreamingResponseBody
In search for the least amount of code to serve a BufferedImage (painted in a service-class) from a spring-mvc Controller, I came up with the following:

```<code>@GetMapping(value = "/image", produces = "image/png")
public StreamingResponseBody image() {
    BufferedImage canvas = service.createImage();
    return outputStream -> ImageIO.write(canvas, "png", outputStream);
}
</code>```

So far, so good - using the image in HTML via  works fine.

However, spring does not send any Content-Type header at all. Together with serving X-Content-Type-Options: nosniff in the response, this leads to garbage in the browser window when the image URL is opened directly.

How do I provide a content-type header in the most spring-friendly way (i.e. not using HttpServletResponse directly)?

答:
You can wrap it in a ResponseEntity<...>, this allows you to easily modify all the parameters in the response through the response builder:

```<code>@GetMapping(value = "/image", produces = "image/png")
public ResponseEntity<StreamingResponseBody> image() {
    BufferedImage canvas = service.createImage();

    StreamingResponseBody stream = outputStream ->
            ImageIO.write(canvas, "png", outputStream);

    return ResponseEntity.ok()
        .contentType(MediaType.IMAGE_PNG)
        .body(stream);
}
</code>```

Body:
In search for the least amount of code to serve a BufferedImage (painted in a service-class) from a spring-mvc Controller, I came up with the following:

@GetMapping(value = "/image", produces = "image/png")
public StreamingResponseBody image() {
    BufferedImage canvas = service.createImage();
    return outputStream -> ImageIO.write(canvas, "png", outputStream);
}

So far, so good - using the image in HTML via  works fine.

However, spring does not send any Content-Type header at all. Together with serving X-Content-Type-Options: nosniff in the response, this leads to garbage in the browser window when the image URL is opened directly.

How do I provide a content-type header in the most spring-friendly way (i.e. not using HttpServletResponse directly)?

Body:
You can wrap it in a ResponseEntity<...>, this allows you to easily modify all the parameters in the response through the response builder:

@GetMapping(value = "/image", produces = "image/png")
public ResponseEntity<StreamingResponseBody> image() {
    BufferedImage canvas = service.createImage();

    StreamingResponseBody stream = outputStream ->
            ImageIO.write(canvas, "png", outputStream);

    return ResponseEntity.ok()
        .contentType(MediaType.IMAGE_PNG)
        .body(stream);
}


问:
Tableview causes app to crash when dragged to the bottom
When scrolling further than the last post/item in the tableview, the app crashes and I get error message: "Unexpectedly found nil while unwrapping an Optional value". Like it's trying to find another post that isn't there, but i don't know why... Posts in the tableview appears just as they should.

I believe there is something wrong here:

```<code>    func tableView(_ tableView: UITableView, cellForRowAt indexpath: IndexPath) -> UITableViewCell {

    let post = posts[indexpath.row]

    if let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexpath) as? PostCell{
        cell.configureCell(post: post)

        return cell
    } else {
        return PostCell()
    }
}
</code>```

(when I remove the else part, I get this error: "Missing return in a function expected to return 'UITableViewCell' )

```<code>var posts = [Post]()
</code>```

Configuring cell:

```<code>func configureCell(post: Post) {

    self.post = post

    if post.altA.isEmpty == false {
        altALabel.text = post.altA["text"] as? String
        if let votes = post.altA["votes"]{
            self.altAVotesLbl.text = "\(votes)"
        }
    } else {
        print("No data found in Alt A")
    }

    if post.altB.isEmpty == false {
        altBLabel.text = post.altB["text"] as? String
        if let votes = post.altB["votes"]{
            self.altBVotesLbl.text = "\(votes)"
        }
    } else {
        print("No data found in Alt B")
    }

    if post.altD.isEmpty == false {
        altDLabel.text = post.altD["text"] as? String
        if let votes = post.altD["votes"]{
            self.altDVotesLbl.text = "\(votes)"
        }
    } else {
        print("No data found in Alt D")
        altDView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0)
        altDVotesView.removeFromSuperview()
        altDLabelView.removeFromSuperview()
    }

    if post.altC.isEmpty == false {
        altCLabel.text = post.altC["text"] as? String
        if let votes = post.altC["votes"]{
            self.altCVotesLbl.text = "\(votes)"
        }
    } else {
        print("No data found in Alt C")
        self.altCView.removeFromSuperview()
        self.botBtnsStackView.removeFromSuperview()
    }

import Foundation
</code>```

class Post {

```<code>private var _text: String!
private var _postKey: String!
private var _backgroundImg: Int!

private var _altA: Dictionary<String, Any>!
private var _altB: Dictionary<String, Any>!
private var _altC: Dictionary<String, Any>!
private var _altD: Dictionary<String, Any>!

//TEXT
var text: String {
    return _text
}

//BACKGROUND
var backgroundImg: Int{
    return _backgroundImg
}

//POSTKEY
var postKey: String{
    return _postKey
}

//ALTERNATIVES
var altA: Dictionary<String, Any> {
    return _altA
}

var altB: Dictionary<String, Any> {
    return _altB
}

var altC: Dictionary<String, Any> {
    return _altC
}

var altD: Dictionary<String, Any> {
    return _altD
}

init(postKey: String, postData: Dictionary<String, Any>) {
    self._postKey = postKey

    if let text = postData["text"]{
        self._text = text as! String
    } else {
        self._text = ""
    }

     if let backgroundImg = postData["backgroundImg"]{
        self._backgroundImg = backgroundImg as! Int
    }

    if let altA = postData["altA"]{
        self._altA = altA as! Dictionary<String, Any>
    }

    if let altB = postData["altB"]{
        self._altB = altB as! Dictionary<String, Any>
    }

    if let altC = postData["altC"]{
        self._altC = altC as! Dictionary<String, Any>
    } else {
        let emptyDictionary = [String: Any]()
        self._altC = emptyDictionary
    }

    if let altD = postData["altD"]{
        self._altD = altD as! Dictionary<String, Any>
    } else {
        let emptyDictionary = [String: Any]()
        self._altD = emptyDictionary
    }
}
</code>```

}

rest of the tableview code(nothing special about it):

```<code> func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return posts.count
}
</code>```

答:
It seems like it wasn't a good idea to remove the views from the superview. I replaced all the removeFromSuperview() methods by using isHidden = true, and it't now working.

for example: altDLabelView.removeFromSuperview() is now altDLabelView.isHidden = True

thanks for the help!

Body:
When scrolling further than the last post/item in the tableview, the app crashes and I get error message: "Unexpectedly found nil while unwrapping an Optional value". Like it's trying to find another post that isn't there, but i don't know why... Posts in the tableview appears just as they should.

I believe there is something wrong here:

    func tableView(_ tableView: UITableView, cellForRowAt indexpath: IndexPath) -> UITableViewCell {

    let post = posts[indexpath.row]

    if let cell = tableView.dequeueReusableCell(withIdentifier: "PostCell", for: indexpath) as? PostCell{
        cell.configureCell(post: post)

        return cell
    } else {
        return PostCell()
    }
}

(when I remove the else part, I get this error: "Missing return in a function expected to return 'UITableViewCell' )

var posts = [Post]()

Configuring cell:

func configureCell(post: Post) {

    self.post = post

    if post.altA.isEmpty == false {
        altALabel.text = post.altA["text"] as? String
        if let votes = post.altA["votes"]{
            self.altAVotesLbl.text = "\(votes)"
        }
    } else {
        print("No data found in Alt A")
    }

    if post.altB.isEmpty == false {
        altBLabel.text = post.altB["text"] as? String
        if let votes = post.altB["votes"]{
            self.altBVotesLbl.text = "\(votes)"
        }
    } else {
        print("No data found in Alt B")
    }

    if post.altD.isEmpty == false {
        altDLabel.text = post.altD["text"] as? String
        if let votes = post.altD["votes"]{
            self.altDVotesLbl.text = "\(votes)"
        }
    } else {
        print("No data found in Alt D")
        altDView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0)
        altDVotesView.removeFromSuperview()
        altDLabelView.removeFromSuperview()
    }

    if post.altC.isEmpty == false {
        altCLabel.text = post.altC["text"] as? String
        if let votes = post.altC["votes"]{
            self.altCVotesLbl.text = "\(votes)"
        }
    } else {
        print("No data found in Alt C")
        self.altCView.removeFromSuperview()
        self.botBtnsStackView.removeFromSuperview()
    }

import Foundation

class Post {

private var _text: String!
private var _postKey: String!
private var _backgroundImg: Int!

private var _altA: Dictionary<String, Any>!
private var _altB: Dictionary<String, Any>!
private var _altC: Dictionary<String, Any>!
private var _altD: Dictionary<String, Any>!

//TEXT
var text: String {
    return _text
}

//BACKGROUND
var backgroundImg: Int{
    return _backgroundImg
}

//POSTKEY
var postKey: String{
    return _postKey
}

//ALTERNATIVES
var altA: Dictionary<String, Any> {
    return _altA
}

var altB: Dictionary<String, Any> {
    return _altB
}

var altC: Dictionary<String, Any> {
    return _altC
}

var altD: Dictionary<String, Any> {
    return _altD
}

init(postKey: String, postData: Dictionary<String, Any>) {
    self._postKey = postKey

    if let text = postData["text"]{
        self._text = text as! String
    } else {
        self._text = ""
    }

     if let backgroundImg = postData["backgroundImg"]{
        self._backgroundImg = backgroundImg as! Int
    }

    if let altA = postData["altA"]{
        self._altA = altA as! Dictionary<String, Any>
    }

    if let altB = postData["altB"]{
        self._altB = altB as! Dictionary<String, Any>
    }

    if let altC = postData["altC"]{
        self._altC = altC as! Dictionary<String, Any>
    } else {
        let emptyDictionary = [String: Any]()
        self._altC = emptyDictionary
    }

    if let altD = postData["altD"]{
        self._altD = altD as! Dictionary<String, Any>
    } else {
        let emptyDictionary = [String: Any]()
        self._altD = emptyDictionary
    }
}

}

rest of the tableview code(nothing special about it):

 func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return posts.count
}


问:
typing brackets in code using kdev-python and Kubuntu 17.10
When writing Python code, I want automatic right-side brackets to be placed whenever I type a left-sided-bracket, with the cursor in-between the two so I can immediately type code in-between the brackets.

I watched a video that showed a programmer doing that, while using KDev-Python for KDevelop.  But I'm unfamiliar with that IDE, and even after googling the internet, and reading through it's pdf manual, can't figure out how to activate that feature.

History of install:  I installed KDevelop and KDev-Python both by typing this one install command: sudo apt install kdev-python under Konsole. (I didn't install KDevelop separately) I think both installed at that one time, because I have Python support, and KDevelop was there too. My Python interpreter is v 3.6.3, and included with Kubuntu 17.10 (along with a v2.7 interpreter).  I looked through the KDevelop plugins to see what was there, and [Python Support -- Python Language Support] was listed and activated.  That was the only plugin that mentioned Python.  And nothing explicitly mentioned kdev-python

答:
This is an optional feature in KTextEditor (as used in KDevelop, KATE and KWrite).

Settings -> Configure KDevelop -> Editor -> Editing -> "Enable Automatic Brackets".


问:
does anyone knows how to setup .nettiers with sharepoint 2010 please?
does anyone knows how to setup .nettiers with sharepoint 2010 please?</p>

答:
nettiers looks like a code templating engine for development, it reads database schemas to build your code model, and maybe an application layer.

Directly reading from the sharepoint database is not supported, so im not sure how useful nettiers will be. SPSite/SPWeb/SPList/SPListItem is what you should be using.

I would recommend initially just staying with Visual Studio 2010 for you development.


问:
HttpURLConnection crashes application
I want to receive and send data with a web server but the code does not work
What do I do for this code to work?

Note this code inside onCreate

```<code>try {

    URL url = new URL("http://myweb.com/");
    HttpURLConnection   connection = (HttpURLConnection) url.openConnection();
    InputStream Stream = connection.getInputStream();
    InputStreamReader reader = new InputStreamReader(Stream);
    BufferedReader b = new BufferedReader(reader);
    StringBuilder s = new StringBuilder();
    String str ="";

    while ((str = b.readLine())!=null)  {
        s.append(str);

    }
    String data = s.toString();
    TextView myText = (TextView) findViewById(R.id.Text);
    myText.setText(data);
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
</code>```

答:
Make sure that you do network-related tasks on a separate thread in Android. Also, check that you have the INTERNET permission set.

If you want to then update the UI from another thread, you have to use

```<code>runOnUiThread (new Runnable () {
    public void run() {
        //update ui in here
    }
}
</code>```

Title: HttpURLConnection crashes application

Body:
I want to receive and send data with a web server but the code does not work
What do I do for this code to work?

Note this code inside onCreate

try {

    URL url = new URL("http://myweb.com/");
    HttpURLConnection   connection = (HttpURLConnection) url.openConnection();
    InputStream Stream = connection.getInputStream();
    InputStreamReader reader = new InputStreamReader(Stream);
    BufferedReader b = new BufferedReader(reader);
    StringBuilder s = new StringBuilder();
    String str ="";

    while ((str = b.readLine())!=null)  {
        s.append(str);

    }
    String data = s.toString();
    TextView myText = (TextView) findViewById(R.id.Text);
    myText.setText(data);
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

Body:
Make sure that you do network-related tasks on a separate thread in Android. Also, check that you have the INTERNET permission set.

If you want to then update the UI from another thread, you have to use

runOnUiThread (new Runnable () {
    public void run() {
        //update ui in here
    }
}


问:
PLUpload Total Progress
I'm using PLUpload which is a great little tool that I have used a lot. My basic question is - how do I get a progress percentage of ALL the files combined. I have used the script below to output the percentage of individual files, but I can't work out how to give a running total for all.

```<code>UploadProgress: function(up, file) {
    $("#total").html(file.percent);
}
</code>```

The above gives the percentage of each file - counting from 1 to 100. That's simple and used in most of the examples. But...

```<code>UploadProgress: function(up, file) {
    $("#total").html(up.total.percent);
}
</code>```

I would have thought the above would just give me the total progress of all files but it doesn't, it just counts up to the percentage portion of each file. For example:

File1 counts 1-60

File2 counts 1-20

File3 counts 1-20

Giving the 100 total.

I'm not sure if this behavior is by design. I've Googled it to death and can't seem to find the answer.

答:
Ok, so I was being stupid.

up.total.percent DOES work for the total of all files as you would expect but ONLY if the upload is successful!

I haden't realised that the upload was failing at each file and therefor re-setting the counter each time.

Hop this helps someone.

Title: PLUpload Total Progress

Body:
I'm using PLUpload which is a great little tool that I have used a lot. My basic question is - how do I get a progress percentage of ALL the files combined. I have used the script below to output the percentage of individual files, but I can't work out how to give a running total for all.

UploadProgress: function(up, file) {
    $("#total").html(file.percent);
}

The above gives the percentage of each file - counting from 1 to 100. That's simple and used in most of the examples. But...

UploadProgress: function(up, file) {
    $("#total").html(up.total.percent);
}

I would have thought the above would just give me the total progress of all files but it doesn't, it just counts up to the percentage portion of each file. For example:

File1 counts 1-60

File2 counts 1-20

File3 counts 1-20

Giving the 100 total.

I'm not sure if this behavior is by design. I've Googled it to death and can't seem to find the answer.


问:
How to express the "new" operator of C++ logic in go?
I have a structure like this

```<code>type Node struct {
    data int
    next *Node
}

var root Node;
</code>```

I would like to create a tmp Node and pass the address to root.next, how to write this kind of logic in go?

```<code>root.next = Node
</code>```

答:
There are no constructors in Go. You just create an object by using the type name and you can set the fields at the same time.

```<code>tmp := Node {
    data: 1
}
root.next = &tmp
</code>```

You can also take a pointer to a new object.

```<code>tmp := &Node {
    data: 1
}
root.next = tmp
</code>```

And then put it all together.

```<code>root.next = &Node {
    data: 1
}
</code>```

There is also a new operator which is equivalent to &Node{} and therefore it is not very convienent as you need to assign field values later.

Body:
I have a structure like this

type Node struct {
    data int
    next *Node
}

var root Node;

I would like to create a tmp Node and pass the address to root.next, how to write this kind of logic in go?

root.next = Node

Body:
There are no constructors in Go. You just create an object by using the type name and you can set the fields at the same time.

tmp := Node {
    data: 1
}
root.next = &tmp

You can also take a pointer to a new object.

tmp := &Node {
    data: 1
}
root.next = tmp

And then put it all together.

root.next = &Node {
    data: 1
}

There is also a new operator which is equivalent to &Node{} and therefore it is not very convienent as you need to assign field values later.


问:
Exposing React Component Functions
What's the correct option to expose some react component functions based on best practices.

OPTION 1

Create the function externally of the component like:

```<code>export const someFunction = () => { //do something }

class MyComponent extends Component {}

export default MyComponent;
</code>```

Using the component above:

```<code>import MyComponent, { someFunction } from './components/myAwesomeComponent';

class ChildComponent extends Component {
    parentComponentFunction() {
       someFunction();
    }

    render() {
        <div>
            <MyComponent />
        </div>
    }
}
</code>```

OPTION 2

Create the function internally (common way) of the component like:

```<code>class MyComponent extends Component {
    someFunction() {
     //
    }
 }

export default MyComponent;
</code>```

Using the component above:

```<code>import MyComponent frrom './components/myAwesomeComponent';

class ChildComponent extends Component {

    parentComponentFunction() {
          this.refs.parentComponent.someFunction();
    }

    render() {
       <div>
         <MyComponent ref="parentComponent" />
       </div>
    }

}
</code>```

Option 3

Have no idea if it exists

Does it make sense or do you need a better example?

答:
If someFunction needs to reference this, then define it as a member function. Otherwise either keep it as a separate utility function or declare it as static function inside the class (option 3):

```<code>class MyComponent extends Component {

    // ...

    static someFunction() {
      // ...
    }
}

// usage: MyComponent.someFunction()
</code>```

Also there is a ESLint rule, that should control it: class-methods-use-this

Title: Exposing React Component Functions

Body:
What's the correct option to expose some react component functions based on best practices.

OPTION 1

Create the function externally of the component like:

export const someFunction = () => { //do something }

class MyComponent extends Component {}

export default MyComponent;

Using the component above:

import MyComponent, { someFunction } from './components/myAwesomeComponent';

class ChildComponent extends Component {
    parentComponentFunction() {
       someFunction();
    }

    render() {

            <MyComponent />

    }
}

OPTION 2

Create the function internally (common way) of the component like:

class MyComponent extends Component {
    someFunction() {
     //
    }
 }

export default MyComponent;

Using the component above:

import MyComponent frrom './components/myAwesomeComponent';

class ChildComponent extends Component {

    parentComponentFunction() {
          this.refs.parentComponent.someFunction();
    }

    render() {

         <MyComponent ref="parentComponent" />

    }

}

Option 3

Have no idea if it exists

Does it make sense or do you need a better example?

Body:
If someFunction needs to reference this, then define it as a member function. Otherwise either keep it as a separate utility function or declare it as static function inside the class (option 3):

class MyComponent extends Component {

    // ...

    static someFunction() {
      // ...
    }
}

// usage: MyComponent.someFunction()

Also there is a ESLint rule, that should control it: class-methods-use-this


问:
ORA-00932: inconsistent datatypes: expected - got CLOB in UNOIN
I Have this query that is a UNION of 2 queries, but even I take the same columns in both queries, when I execute it I got an error</p>

```<code>   SELECT  username,
                sid,
                serial# serial,
                osuser,
                seconds_in_wait,
                sql_address,
                sql_hash_value,
                sql_fulltext
        FROM V$SESSION se
        JOIN v$sql sq ON sq.ADDRESS = se.SQL_ADDRESS
        AND sq.HASH_VALUE = se.SQL_HASH_VALUE
        WHERE status = 'ACTIVE'
            AND username <> 'SYSTEM' AND username <> 'SYS'
            AND osuser <> 'NT AUTHORITY\SYSTEM'
            AND osuser <> 'SYSTEM'
            AND seconds_in_wait >= 500

 UNION
 SELECT  username,
                sid,
                serial# serial,
                osuser,
                seconds_in_wait,
                sql_address,
                sql_hash_value,
                sql_fulltext
from V$SESSION se
    join v$sql sq on sq.ADDRESS = se.SQL_ADDRESS and sq.HASH_VALUE = se.SQL_HASH_VALUE
where blocking_session is not NULL
AND seconds_in_wait >= 500
</code>```

答:
Why do you need a UNION to begin with? Your query is equivalent to:

```<code>   SELECT  username,
                sid,
                serial# serial,
                osuser,
                seconds_in_wait,
                sql_address,
                sql_hash_value,
                sql_fulltext
        FROM V$SESSION se
        JOIN v$sql sq ON sq.ADDRESS = se.SQL_ADDRESS
        AND sq.HASH_VALUE = se.SQL_HASH_VALUE
        WHERE seconds_in_wait >= 500
          AND (     status   =      'ACTIVE'
                AND username not in ('SYSTEM', 'SYS')
                AND osuser   not in ('NT AUTHORITY\SYSTEM', 'SYSTEM')
                OR
                blocking_session is not null
              )
;
</code>```

Then: if in a different problem you couldn't avoid UNION (rather than UNION ALL), the correct way to do it is to leave out the CLOB column at first; select all the other columns, perform the joins and the UNION (note that JOIN is distributive with respect to UNION, so it may be better to do the UNION first and only then the JOIN), and then JOIN back again to retrieve the CLOB column.

Body:
I Have this query that is a UNION of 2 queries, but even I take the same columns in both queries, when I execute it I got an error

   SELECT  username,
                sid,
                serial# serial,
                osuser,
                seconds_in_wait,
                sql_address,
                sql_hash_value,
                sql_fulltext
        FROM V$SESSION se
        JOIN v$sql sq ON sq.ADDRESS = se.SQL_ADDRESS
        AND sq.HASH_VALUE = se.SQL_HASH_VALUE
        WHERE status = 'ACTIVE'
            AND username <> 'SYSTEM' AND username <> 'SYS'
            AND osuser <> 'NT AUTHORITY\SYSTEM'
            AND osuser <> 'SYSTEM'
            AND seconds_in_wait >= 500

 UNION
 SELECT  username,
                sid,
                serial# serial,
                osuser,
                seconds_in_wait,
                sql_address,
                sql_hash_value,
                sql_fulltext
from V$SESSION se
    join v$sql sq on sq.ADDRESS = se.SQL_ADDRESS and sq.HASH_VALUE = se.SQL_HASH_VALUE
where blocking_session is not NULL
AND seconds_in_wait >= 500

Body:
Why do you need a UNION to begin with? Your query is equivalent to:

   SELECT  username,
                sid,
                serial# serial,
                osuser,
                seconds_in_wait,
                sql_address,
                sql_hash_value,
                sql_fulltext
        FROM V$SESSION se
        JOIN v$sql sq ON sq.ADDRESS = se.SQL_ADDRESS
        AND sq.HASH_VALUE = se.SQL_HASH_VALUE
        WHERE seconds_in_wait >= 500
          AND (     status   =      'ACTIVE'
                AND username not in ('SYSTEM', 'SYS')
                AND osuser   not in ('NT AUTHORITY\SYSTEM', 'SYSTEM')
                OR
                blocking_session is not null
              )
;

Then: if in a different problem you couldn't avoid UNION (rather than UNION ALL), the correct way to do it is to leave out the CLOB column at first; select all the other columns, perform the joins and the UNION (note that JOIN is distributive with respect to UNION, so it may be better to do the UNION first and only then the JOIN), and then JOIN back again to retrieve the CLOB column.