问:
How to lock the result of the output cell, once it meets a criteria, from subsequent value change in the input cell in Google Sheets?
I'm looking to solve this situation:

Depending on the value —variable in time— in B1 (input cell), print a specific "status" in the output cell (D1).

With 3 possible status:

1st: "VALID"

2nd: "PENDING"

3rd: "APPROVED"

with the 3 main properties:

A1 = value fixed (doesn't change in time)

B1 = value changing in time

C1 = string "APPROVED" (to be inputted manually)

D1 = output cell

Following this formula:

```<code>=IFS(len(C1),"APPROVED",B1>A1,"VALID",B1<=A1,"PENDING",TRUE,"ERROR")
</code>```

What I'm trying to do is:

As soon as B1>A1 ("VALID" status) changes to B1<=A1 ("PENDING" status), have the D1 cell status "PENDING" locked to "PENDING".
I.e. not reverting to "VALID" if/when B1<=A1 changes back to B1>A1.

Additionally, only unlocking the "PENDING" status to the "APPROVED" status if the condition for the Status "APPROVED" (len(C1)-manually inputting the string "APPROVED" into C1) is met subsequently.

Here a simple example of expected result:

At T1 (say, May 27 2019, 12:15pm):

B1>A1 -> Status= VALID

A1 = 1.2 (in A1, fixed number)

B1 = 1.5 (in B1, number variable in time)

C1 = (empty cell)

D1 = VALID

At T2 (say, May 27 2019, 1:15pm):

B1<=A1 -> Status= PENDING

A1 = 1.2 (say May 27 2019, 12:15pm)

B1 = 1.2 (or 1.1) (in B1, number variable in time)

C1 =  (empty cell)

D1 = PENDING

At T3 (say, May 27 2019, 2:15pm):

B1>A1 -> Status= PENDING (no revert back to VALID despite B1 reverting to B1>A1)

A1 = 1.2 (in A1, fixed number)

B1 = 1.4 (in B1, number variable in time)

C1 = (empty cell)

D1 = PENDING

At T4 (say, May 27 2019, 3:15pm):

A1 = 1.2 (in A1, fixed number)

B1 = 1.4 or 1.1 (in B1, number variable in time)

D1 = APPROVED (because of manual input of any character into C1)

C1 = (any lenght of character into C1)

(User manually input any character/string into C1 -> Status= APPROVED (because of len(C1), the PENDING Status gets unlocked to APPROVED status)

At T3 is the issue I'm currently facing.

With this formula:

```<code>=IFS(len(C1),"APPROVED",B1>A1,"VALID",B1<=A1,"PENDING",TRUE,"ERROR")
</code>```

The "PENDING" status (gained from T2) reverts back to "VALID"

How can one lock the "PENDING" status as soon as B1>A1 ("VALID" status) changes to B1<=A1 ("PENDING" status)?

Then unlock the "PENDING" status when the "APPROVED" string is manually typed into D1?

New question:
Can we color and bold code the status as well?

For example:

Cells A22 to A25 in the sheet below.

Sheet here:

https://docs.google.com/spreadsheets/d/1UjjMnLmNbEDUfXjeCIOgBZwYqTeXdm_t_4N45OL0k6I/edit#gid=0

Thanks a lot for your help!

答:
To add colors and boldness to text Status, I've added the .setFontColor and .setFontWeight arguments to app script code:</p>

```<code>/**
* Colors specific words
*
* @param arg2:  Colors "VALID" Status to orange, "PENDING" Status to gree, and "APPROVED" to purple
*
* @customfunction
*/

function COLORWORDS(arg2) {

  var app = SpreadsheetApp;
  var activeSheet = app.getActiveSpreadsheet().getActiveSheet();

  var fixedvalueCell = activeSheet.getRange(1, 1).getValue();
  var changingvalueCell = activeSheet.getRange(1, 2).getValue();
  var approveCell = activeSheet.getRange(1, 3).getValue();
  var statusCell = activeSheet.getRange(1, 4).getValue();

  if
    (approveCell !== "") {
    activeSheet.getRange(1, 4).setValue("APPROVED").setFontColor("#7F00FF").setFontWeight("bold");
  }
    else if
    (changingvalueCell <= fixedvalueCell) {
    activeSheet.getRange(1, 4).setValue("PENDING").setFontColor("#7FFF00").setFontWeight("bold");
  }
    else {
    activeSheet.getRange(1, 4).setValue("VALID").setFontColor("#FF3D0D").setFontWeight("bold");
  }

  var result = arg2;

  return result;

}
</code>```

Body:
I'm looking to solve this situation:

Depending on the value —variable in time— in B1 (input cell), print a specific "status" in the output cell (D1).

With 3 possible status:

1st: "VALID"

2nd: "PENDING"

3rd: "APPROVED"

with the 3 main properties:

A1 = value fixed (doesn't change in time)

B1 = value changing in time

C1 = string "APPROVED" (to be inputted manually)

D1 = output cell

Following this formula:

=IFS(len(C1),"APPROVED",B1>A1,"VALID",B1<=A1,"PENDING",TRUE,"ERROR")

What I'm trying to do is:

As soon as B1>A1 ("VALID" status) changes to B1<=A1 ("PENDING" status), have the D1 cell status "PENDING" locked to "PENDING".
I.e. not reverting to "VALID" if/when B1<=A1 changes back to B1>A1.

Additionally, only unlocking the "PENDING" status to the "APPROVED" status if the condition for the Status "APPROVED" (len(C1)-manually inputting the string "APPROVED" into C1) is met subsequently.

Here a simple example of expected result:

At T1 (say, May 27 2019, 12:15pm):

B1>A1 -> Status= VALID

A1 = 1.2 (in A1, fixed number)

B1 = 1.5 (in B1, number variable in time)

C1 = (empty cell)

D1 = VALID

At T2 (say, May 27 2019, 1:15pm):

B1<=A1 -> Status= PENDING

A1 = 1.2 (say May 27 2019, 12:15pm)

B1 = 1.2 (or 1.1) (in B1, number variable in time)

C1 =  (empty cell)

D1 = PENDING

At T3 (say, May 27 2019, 2:15pm):

B1>A1 -> Status= PENDING (no revert back to VALID despite B1 reverting to B1>A1)

A1 = 1.2 (in A1, fixed number)

B1 = 1.4 (in B1, number variable in time)

C1 = (empty cell)

D1 = PENDING

At T4 (say, May 27 2019, 3:15pm):

A1 = 1.2 (in A1, fixed number)

B1 = 1.4 or 1.1 (in B1, number variable in time)

D1 = APPROVED (because of manual input of any character into C1)

C1 = (any lenght of character into C1)

(User manually input any character/string into C1 -> Status= APPROVED (because of len(C1), the PENDING Status gets unlocked to APPROVED status)

At T3 is the issue I'm currently facing.

With this formula:

=IFS(len(C1),"APPROVED",B1>A1,"VALID",B1<=A1,"PENDING",TRUE,"ERROR")

The "PENDING" status (gained from T2) reverts back to "VALID"

How can one lock the "PENDING" status as soon as B1>A1 ("VALID" status) changes to B1<=A1 ("PENDING" status)?

Then unlock the "PENDING" status when the "APPROVED" string is manually typed into D1?

New question:
Can we color and bold code the status as well?

For example:

Cells A22 to A25 in the sheet below.

Sheet here:

https://docs.google.com/spreadsheets/d/1UjjMnLmNbEDUfXjeCIOgBZwYqTeXdm_t_4N45OL0k6I/edit#gid=0

Thanks a lot for your help!

Body:
To add colors and boldness to text Status, I've added the .setFontColor and .setFontWeight arguments to app script code:

/**
* Colors specific words
*
* @param arg2:  Colors "VALID" Status to orange, "PENDING" Status to gree, and "APPROVED" to purple
*
* @customfunction
*/

function COLORWORDS(arg2) {

  var app = SpreadsheetApp;
  var activeSheet = app.getActiveSpreadsheet().getActiveSheet();

  var fixedvalueCell = activeSheet.getRange(1, 1).getValue();
  var changingvalueCell = activeSheet.getRange(1, 2).getValue();
  var approveCell = activeSheet.getRange(1, 3).getValue();
  var statusCell = activeSheet.getRange(1, 4).getValue();

  if
    (approveCell !== "") {
    activeSheet.getRange(1, 4).setValue("APPROVED").setFontColor("#7F00FF").setFontWeight("bold");
  }
    else if
    (changingvalueCell <= fixedvalueCell) {
    activeSheet.getRange(1, 4).setValue("PENDING").setFontColor("#7FFF00").setFontWeight("bold");
  }
    else {
    activeSheet.getRange(1, 4).setValue("VALID").setFontColor("#FF3D0D").setFontWeight("bold");
  }

  var result = arg2;

  return result;

}


来源: stackexchange

问:
Azure App Service - write to filesystem - ASP.NET web application
I have an ASP.NET web application, created in Visual Studio 2017.

In the application there is a form, where the users can upload files. When files are uploaded, I process them and I save them on the filesystem:

```<code>var photo = Request.Files["file"];
photo.SaveAs("D:\\home");
</code>```

Everything works perfect locally, but it's not working when I deploy the App on Azure App Services.

I read that, on Azure, the path

```<code>D:\home
</code>```

should be writable.

But when I try the code I get this error:

```<code>Access to the path 'd:\home\test_image.JPG' is denied.
</code>```

答:
Use %TEMP%, which on Azure App Service (Windows) resolves to d:\local. That's the local machine disk, not network storage, so significantly faster. It gets wiped on app restart so code accordingly.

var tempDirectoryPath = Environment.GetEnvironmentVariable("TEMP");
var filePath = Path.Combine(tempDirectoryPath, Request.Files["file"]);
```

If you want durability use Blob Storage instead.

ContentLicense: CC BY-SA 3.0

Body:
I have an ASP.NET web application, created in Visual Studio 2017.

In the application there is a form, where the users can upload files. When files are uploaded, I process them and I save them on the filesystem:

var photo = Request.Files["file"];
photo.SaveAs("D:\\home");

Everything works perfect locally, but it's not working when I deploy the App on Azure App Services.

I read that, on Azure, the path

D:\home

should be writable.

But when I try the code I get this error:

Access to the path 'd:\home\test_image.JPG' is denied.

Body:
Use %TEMP%, which on Azure App Service (Windows) resolves to d:\local. That's the local machine disk, not network storage, so significantly faster. It gets wiped on app restart so code accordingly.

var tempDirectoryPath = Environment.GetEnvironmentVariable("TEMP");
var filePath = Path.Combine(tempDirectoryPath, Request.Files["file"]);

If you want durability use Blob Storage instead.

ContentLicense: CC BY-SA 4.0


问:
If condition is getting skipped even if the condition is true
I am using an If statement inside a for loop but the If statement is getting skipped even after the condition is met

```<code>x=raw_input().split(" ")
c=[]
for a in x:
    b=1
    if a<0:
        print "Please enter a number greater than or equal to 0"
    else:
        if(a==1 or a==0 ):
            print "1"
    for i in range(1,int(a)+1):
            b=b*i
    c.append(str(b))

print ",".join(c)
</code>```

the program is to find factorial, i am getting the result. If someone enters a negative number, it should not return a factorial but this does. I just want to know why is the if and else conditions getting skipped.

答:
You might want to convert the input into int before doing int operations. Change this

```<code>x=raw_input().split(" ")
</code>```

to

```<code>x=map(int, raw_input().split(" "))
</code>```

Body:
I am using an If statement inside a for loop but the If statement is getting skipped even after the condition is met

x=raw_input().split(" ")
c=[]
for a in x:
    b=1
    if a<0:
        print "Please enter a number greater than or equal to 0"
    else:
        if(a==1 or a==0 ):
            print "1"
    for i in range(1,int(a)+1):
            b=b*i
    c.append(str(b))

print ",".join(c)

the program is to find factorial, i am getting the result. If someone enters a negative number, it should not return a factorial but this does. I just want to know why is the if and else conditions getting skipped.

Body:
You might want to convert the input into int before doing int operations. Change this

x=raw_input().split(" ")

to

x=map(int, raw_input().split(" "))


问:
changing fontsize from `10px` to `14px` to `18px` with a single shortcut
I am creating a plugin for TinyMCE5 that toggles the fontsize of the selected text between 10px, 14px and 18px. (The fontsize by defaut is 14px)

This is my try:

```<code>editor.addCommand('customfontsize_command', function () {
var content = tinymce.activeEditor.selection.getContent();
var node = tinymce.activeEditor.selection.getNode();
var fontsize = tinymce.activeEditor.dom.getStyle(node, 'font-size', true);

fontsize = fontsize.split("p", 1)
fontsize--;

if (fontsize > 0 && fontsize <= 100) { // only work for first time
    switch (fontsize) {
        case 18:
            fontsize = 14;
            break;
        case 10:
            fontsize = 8;
            break;
        case 8:
            fontsize = 18;
            break;
        default:
            fontsize = 14;
    }

    fontsize = fontsize + "px";
    tinymce.activeEditor.execCommand('fontsize', false, fontsize);
}
}); // end customfontsize_command
editor.addShortcut('alt+a', 'customfontsize_command_desc', 'customfontsize_command');
</code>```

But it only works for the first time I do my shortcut.

I also tried this but with the same result:

```<code>if (fontsize > 10 && fontsize <= 14) {
    fontsize = 10;
} else if (fontsize <= 10) {
    fontsize = 18;
} else {
    fontsize = 14;
}
</code>```

I can make this work with 2 different shorcuts like this, but I would prefer a single shortcut that toggles between  the 3 sizes:

```<code>editor.addCommand('small_size', function () {
    var content = tinymce.activeEditor.selection.getContent();
    var node = tinymce.activeEditor.selection.getNode();
    var fontsize = tinymce.activeEditor.dom.getStyle(node, 'font-size', true);

    fontsize = fontsize.split("p", 1)
    fontsize = 10
    fontsize = fontsize + "px";
    tinymce.activeEditor.execCommand('fontsize', false, fontsize);

}); // end customfontsize_command

editor.addCommand('big_size', function () {
    var content = tinymce.activeEditor.selection.getContent();
    var node = tinymce.activeEditor.selection.getNode();
    var fontsize = tinymce.activeEditor.dom.getStyle(node, 'font-size', true);

    fontsize = fontsize.split("p", 1)
    fontsize = 18
    fontsize = fontsize + "px";
    tinymce.activeEditor.execCommand('fontsize', false, fontsize);

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

答:
Try this, </p>

```<code>fontsize = (fontsize <= 10) ? 18 : ((fontsize > 10 && fontsize <= 14) ? 10 : 14);
</code>```

Body:
I am creating a plugin for TinyMCE5 that toggles the fontsize of the selected text between 10px, 14px and 18px. (The fontsize by defaut is 14px)

This is my try:

editor.addCommand('customfontsize_command', function () {
var content = tinymce.activeEditor.selection.getContent();
var node = tinymce.activeEditor.selection.getNode();
var fontsize = tinymce.activeEditor.dom.getStyle(node, 'font-size', true);

fontsize = fontsize.split("p", 1)
fontsize--;

if (fontsize > 0 && fontsize <= 100) { // only work for first time
    switch (fontsize) {
        case 18:
            fontsize = 14;
            break;
        case 10:
            fontsize = 8;
            break;
        case 8:
            fontsize = 18;
            break;
        default:
            fontsize = 14;
    }

    fontsize = fontsize + "px";
    tinymce.activeEditor.execCommand('fontsize', false, fontsize);
}
}); // end customfontsize_command
editor.addShortcut('alt+a', 'customfontsize_command_desc', 'customfontsize_command');

But it only works for the first time I do my shortcut.

I also tried this but with the same result:

if (fontsize > 10 && fontsize <= 14) {
    fontsize = 10;
} else if (fontsize <= 10) {
    fontsize = 18;
} else {
    fontsize = 14;
}

I can make this work with 2 different shorcuts like this, but I would prefer a single shortcut that toggles between  the 3 sizes:

editor.addCommand('small_size', function () {
    var content = tinymce.activeEditor.selection.getContent();
    var node = tinymce.activeEditor.selection.getNode();
    var fontsize = tinymce.activeEditor.dom.getStyle(node, 'font-size', true);

    fontsize = fontsize.split("p", 1)
    fontsize = 10
    fontsize = fontsize + "px";
    tinymce.activeEditor.execCommand('fontsize', false, fontsize);

}); // end customfontsize_command

editor.addCommand('big_size', function () {
    var content = tinymce.activeEditor.selection.getContent();
    var node = tinymce.activeEditor.selection.getNode();
    var fontsize = tinymce.activeEditor.dom.getStyle(node, 'font-size', true);

    fontsize = fontsize.split("p", 1)
    fontsize = 18
    fontsize = fontsize + "px";
    tinymce.activeEditor.execCommand('fontsize', false, fontsize);

}); // end customfontsize_command

Body:
Try this,

fontsize = (fontsize <= 10) ? 18 : ((fontsize > 10 && fontsize <= 14) ? 10 : 14);


问:
How to cluster my data with a custom distance matrix using smile library's CLARANS method
I want cluster my data with a custom distance matrix rather than the built-in algorithms (i.e Euclidean). And there seems to be no clear way of doing it.

I've tried to add some of my code to the demos in the Smile project. Also tried to do it with testing in my project, here's a chunk of the code:

```<code>        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = vrpJsonFromFile.readLine()) != null) {
            sb.append(line).append("\n");
        }
        JSONArray jsonArray = new JSONObject(sb.toString()).getJSONArray("services");
        Double[][] data = new Double[jsonArray.length()][2];
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject address = jsonArray.getJSONObject(i).getJSONObject("address");
            data[i][0] = Double.parseDouble(address.getString("lon"));
            data[i][1] = Double.parseDouble(address.getString("lat"));
        }

        // here
        Distance<Double[]> distance1 = (x, y) -> Math.sqrt(Math.pow(y[1]-x[1],2) + Math.pow(y[0]-x[0], 2));
        CLARANS<Double[]> clarans = new CLARANS<>(data, distance1, 3);
        System.out.println(clarans);
</code>```

This code creates a CLARANS clustering with the Euclidean algorithm (see the line below the //here comment). I should change it with my own distance matrix and I hope there is a way of doing that in Smile.

答:
You can likely use

```<code>Distance<Integer> d = (i,j) -> matrix[i][j];
</code>```

to cluster the object numbers, not their vectors.

But it may be worth looking at ELKI instead that has predefined classes for distance matrixes, and uses optimized representations for sets of objects rather than having to use expensive boxed Integer as in the lambda above. Because i and j are boxed integers, this requires additional memory indirection (and cache misses) for each distance computation, that can reduce performance a lot. It also has the better FastCLARANS algorithm, as well as FastPAM that are supposedly O(k) times faster.

Body:
I want cluster my data with a custom distance matrix rather than the built-in algorithms (i.e Euclidean). And there seems to be no clear way of doing it.

I've tried to add some of my code to the demos in the Smile project. Also tried to do it with testing in my project, here's a chunk of the code:

        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = vrpJsonFromFile.readLine()) != null) {
            sb.append(line).append("\n");
        }
        JSONArray jsonArray = new JSONObject(sb.toString()).getJSONArray("services");
        Double[][] data = new Double[jsonArray.length()][2];
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject address = jsonArray.getJSONObject(i).getJSONObject("address");
            data[i][0] = Double.parseDouble(address.getString("lon"));
            data[i][1] = Double.parseDouble(address.getString("lat"));
        }

        // here
        Distance<Double[]> distance1 = (x, y) -> Math.sqrt(Math.pow(y[1]-x[1],2) + Math.pow(y[0]-x[0], 2));
        CLARANS<Double[]> clarans = new CLARANS<>(data, distance1, 3);
        System.out.println(clarans);

This code creates a CLARANS clustering with the Euclidean algorithm (see the line below the //here comment). I should change it with my own distance matrix and I hope there is a way of doing that in Smile.

Body:
You can likely use

Distance<Integer> d = (i,j) -> matrix[i][j];

to cluster the object numbers, not their vectors.

But it may be worth looking at ELKI instead that has predefined classes for distance matrixes, and uses optimized representations for sets of objects rather than having to use expensive boxed Integer as in the lambda above. Because i and j are boxed integers, this requires additional memory indirection (and cache misses) for each distance computation, that can reduce performance a lot. It also has the better FastCLARANS algorithm, as well as FastPAM that are supposedly O(k) times faster.


问:
Setting PHP tmp dir - PHP upload not working
I'm working on file upload via a webpage with a progress bar using Valums file uploader. Almost everything works fine, but I'm not able to change the default tmp directory, where the file is stored during the upload.

Files should be stored in /upload directory and not in default system /tmp directory, because /tmp is mounted in a RAM disk which has its size limited to 4 MB and user will be uploading files around 10 MB.

I've searched lots of webpages, but none of solutions worked.
I've set temp directory in php.ini:

```<code>upload_tmp_dir =/upload
</code>```

I've set permissions to the /upload dir, and apache is owner of the file, so the directory is definitely writable by PHP.

I've set the target path in file uploader to /upload, because I want the files to be stored after the upload also in this directory. The final result is small files are being uploaded successfuly, but files larger than 4 MB fail to upload-the only reason of this behaviour that comes to my mind is that files are stored in /tmp during upload. To be sure, I've checked it with sys_get_temp_dir() and the result was /tmp-so PHP ignores my php.ini directive or there is some other way to set where files are stored during upload.

Oh, and the last information: open_basedir isn't set, so the PHP access to disk is only limited by file permissions.

答:
My problem was selinux...

Go sestatus.

If Current mode: enforcing then chcon -R -t httpd_sys_rw_content_t /var/www/html

Body:
I'm working on file upload via a webpage with a progress bar using Valums file uploader. Almost everything works fine, but I'm not able to change the default tmp directory, where the file is stored during the upload.

Files should be stored in /upload directory and not in default system /tmp directory, because /tmp is mounted in a RAM disk which has its size limited to 4 MB and user will be uploading files around 10 MB.

I've searched lots of webpages, but none of solutions worked.
I've set temp directory in php.ini:

upload_tmp_dir =/upload

I've set permissions to the /upload dir, and apache is owner of the file, so the directory is definitely writable by PHP.

I've set the target path in file uploader to /upload, because I want the files to be stored after the upload also in this directory. The final result is small files are being uploaded successfuly, but files larger than 4 MB fail to upload-the only reason of this behaviour that comes to my mind is that files are stored in /tmp during upload. To be sure, I've checked it with sys_get_temp_dir() and the result was /tmp-so PHP ignores my php.ini directive or there is some other way to set where files are stored during upload.

Oh, and the last information: open_basedir isn't set, so the PHP access to disk is only limited by file permissions.


问:
When declare collection type column in Entity, difference instance or none

@OneToMany
List<Something> list;

@OneToMany
List<Something> list2 = new ArrayList<>();
```

In Èntity, people are declaring in two ways, what is the difference?

答:
Spring Data/JPA always makes sure to return a non-null collection. I think this is because to reduce NULL check needed if it return NULL instead of Empty collection.

So it is a good hygiene to maintain a non-null collection for instead of null. At it works well when you unit test these entities, no need to bother when nothing comes from the database.

Moreover take a look at spring documentation says for Null Handling for repositories

Body:
@OneToMany
List<Something> list;

@OneToMany
List<Something> list2 = new ArrayList<>();

In Èntity, people are declaring in two ways, what is the difference?


答:
```<code>x="-2 3 6 -3".split(" ")
c=[]
for a in x:
    b=1
    if int(a)<0:
        print ("Please enter a number greater than or equal to 0" )
        continue
    else:
        if(a==1 or a==0 ):
            print ("1"  )
    for i in range(1,int(a)+1):
            b=b*i
    c.append(str(b))

print (",".join(c))
</code>```

o/p:

```<code>Please enter a number greater than or equal to 0
Please enter a number greater than or equal to 0
6,720
</code>```

Two changes, int(a) in if condition and if you wish not to calculate the factorial for negative numbers then add continue

Title: If condition is getting skipped even if the condition is true

Body:
x="-2 3 6 -3".split(" ")
c=[]
for a in x:
    b=1
    if int(a)<0:
        print ("Please enter a number greater than or equal to 0" )
        continue
    else:
        if(a==1 or a==0 ):
            print ("1"  )
    for i in range(1,int(a)+1):
            b=b*i
    c.append(str(b))

print (",".join(c))

o/p:

Please enter a number greater than or equal to 0
Please enter a number greater than or equal to 0
6,720

Two changes, int(a) in if condition and if you wish not to calculate the factorial for negative numbers then add continue


问:
match two lists by common value (id)
I want create a new list such that the keys are used to match the roles.

For example two lists:

[['9', u'bob'], ['18', u'alice']]

[['1', 'officer'], ['2', 'nurse'], ['9', 'teacher'],['18', 'unknown']]

I'd like a new list that is:

[['9', u'bob', 'teacher'], ['18', u'alice' 'unknown']] or

[[u'bob', 'teacher'], [u'alice' 'unknown']]

答:
Here's a simple solution -

```<code>  list_1 = [[9, u'bob'], [18, u'alice']]
  list_2 = [[1, 'officer'], [2, 'nurse'], [9, 'teacher'],[18, 'unknown']]
  new_list = []
  for i in list_1:
      for j in list_2:
          if i[0]==j[0]:
              new_list.append([i[1],j[1]])
</code>```

Here's the one-liner for the same, but it puts elements in tuple -

```<code>  >> [(x[1], y[1]) for x in list_1 for y in list_2 if x[0] == y[0]]

  [('bob', 'teacher'), ('alice', 'unknown')]
</code>```

To get a list of lists -

```<code>  >> [list(elem) for elem in [(x[1], y[1]) for x in list_1 for y in list_2 if x[0] == y[0]]]

  [['bob', 'teacher'], ['alice', 'unknown']]
</code>```

Title: match two lists by common value (id)

Body:
Here's a simple solution -

  list_1 = [[9, u'bob'], [18, u'alice']]
  list_2 = [[1, 'officer'], [2, 'nurse'], [9, 'teacher'],[18, 'unknown']]
  new_list = []
  for i in list_1:
      for j in list_2:
          if i[0]==j[0]:
              new_list.append([i[1],j[1]])

Here's the one-liner for the same, but it puts elements in tuple -

  >> [(x[1], y[1]) for x in list_1 for y in list_2 if x[0] == y[0]]

  [('bob', 'teacher'), ('alice', 'unknown')]

To get a list of lists -

  >> [list(elem) for elem in [(x[1], y[1]) for x in list_1 for y in list_2 if x[0] == y[0]]]

  [['bob', 'teacher'], ['alice', 'unknown']]


问:
Getting Forward to play nice with pow and subdomains
I have a Rails app foobar with various subdomains set up, for example, admin. I use pow to test the app locally, and things work just fine: admin.foobar.test/users correctly routes to Admin::UsersController.

However, when trying to get it to work with Forward, I can only get it to point to the top level namespace. It doesn't matter whether I do forward admin.foobar.test, forward foobar.test, or forward test, in all cases, foobar.fwd.wf/users and admin.foobard.fwd.wf/users raise 404s because it's trying to find the /users route at the top level, rather than within the admin namespace.

The workaround I have for now is redefining my subdomain routes at the top level, but that is obviously a quick hack, not a viable long term fix.

I've already read https://forwardhq.com/announcements/05-forward-now-supports-wildcard-subdomains. It does not work.

答:
Found the answer on this question: Rails 4 subdomains does not work on production

The default TLD length is 1, but when using Forward, the TLD is .fwd.wf. The fix is therefore to add the following to development.rb:

config.action_dispatch.tld_length = 2
```


问:
Window close does not close program, even with a function calling sys.exit() bound to the window's close_event. What might cause this?
The program below sets up a graph and displays a blue box each time the user clicks.
A user can make more boxes using the right-click popup menu. When I implemented the popup menu (thus allowing multiple blue boxes) the program stopped closing on the window close. I connected a deleteAll() method to the canvas to force a sys.exit() on close, but the program still stays open. What am I doing wrong?     </p>

```<code>#**************************************************************************#
# Set up a graph. A click creates a blue box. More blue boxes can be made
# by choosing "Make a new box" from right/click menu.
#**************************************************************************#

import wx
import matplotlib
matplotlib.use('WX')
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.figure import Figure
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigCanv
from pylab import *

#**************************************************************************#
class MainCanvas(wx.Frame):
    """ Class to set up graph """
    def __init__(self):
        wx.Frame.__init__(self,None,-1, 'Make Blue Boxes',size=(550,350))

    #**********************************************************************#
    def setupGraph(self):
        """ Set up window and graph """
        self.definePlot()
        self.canvas = FigCanv(self, -1, self.figure)
        self.setSizer()

    #**********************************************************************#
    def definePlot(self):
        """ Define attributes of graph """
        self.SetBackgroundColour(wx.NamedColor("WHITE"))
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)

    #**********************************************************************#
    def setSizer(self):
        """ Set the size of the graph """
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()

#**************************************************************************#
class BlueBox(MainCanvas):
    """ Class to set up BlueBox """
    def __init__(self):
        MainCanvas.__init__(self)

    #**********************************************************************#
    def setupBlueBox(self):
        """ Blue box set up """
        self.blueBox = patches.Rectangle((0, 0), 0.05, 0.05,
                fc = "Blue", visible = False, zorder = 3)
        # Set zorder so new boxes are in front of old
        if len(self.listDT)>1:
            oldz = self.listDT[len(self.listDT)-2].blueBox.get_zorder() + 3
            self.listDT[len(self.listDT)-1].blueBox.set_zorder(oldz)

        self.axes.add_patch(self.blueBox)

    #**********************************************************************#
    def onPick(self, event):
        """ Behavior when graph is clicked """
        # Refresh BlueBox position and coordinate text
        self.refreshBlueBox(event)
        # Set the current BlueBox visible
        self.listDT[len(self.listDT)-1].setVisible()

    #**********************************************************************#
    def refreshBlueBox(self, event):
        """ Blue box refresh    """
        # Center the BlueBox (Point Box) over the mouse click location
        self.blueBox.set_x(event.xdata - .5 * self.blueBox.get_width())
        self.blueBox.set_y(event.ydata - .5 * self.blueBox.get_height())

    #**********************************************************************#
    def setVisible(self):
        """ Make BlueBox visible and refresh canvas """
        self.blueBox.set_visible(True)
        self.figure.canvas.draw()

    #**********************************************************************#
    def setGraphAttributes(self, axes, figure, listDT):
        """ Tell each BlueBox about the graph attributes it needs """
        self.axes = axes
        self.figure = figure
        self.listDT = listDT

#**************************************************************************#
class MyPopupMenu(BlueBox):
    """ Class to handle right clicks """
    def __init__(self):
        BlueBox.__init__(self)

    #**********************************************************************#
    def setup(self):
        """ Set up graph and BlueBox """
        self.setupGraph()
        # Bind right clicks to open the popup menu
        self.canvas.Bind(wx.EVT_RIGHT_DOWN,
                self.createPopupMenu)

        # Create lists for BlueBoxs and binding IDs
        self.listDT = []
        self.listBID = []

        self.popupCreateNew = wx.NewId()
        self.menu = wx.Menu()
        self.cn = self.menu.Append(self.popupCreateNew,
                "Make a new box")
        self.Bind(wx.EVT_MENU, self.createNew, self.cn)

        # Make the first BlueBox
        self.newBox()

        # Connect close events to delete everything
        self.figure.canvas.mpl_connect('close_event', self.deleteAll)

    #**********************************************************************#
    def deleteAll(self, event):
        """ Close out of the program cleanly """
        self.Destroy()
        sys.exit(0)

    #**********************************************************************#
    def createPopupMenu(self, event):
        """ Create all parts of the right-click popup menu """
        self.PopupMenu(self.menu)

    #**********************************************************************#
    def newBox(self):
        """ Make a new BlueBox """
        self.listDT.append(BlueBox())
        self.listDT[len(self.listDT)-1].setGraphAttributes(self.axes,
                self.figure, self.listDT)
        self.listDT[len(self.listDT)-1].setupBlueBox()
        self.listBID.append(self.figure.canvas.mpl_connect('button_press_event',
                self.listDT[len(self.listDT)-1].onPick))

    #**********************************************************************#
    def createNew(self, event):
        """ Create a new BlueBox """
        event.Skip()
        self.newBox()
        if len(self.listBID) > 1:
            self.figure.canvas.mpl_disconnect(self.listBID[len(self.listBID)-2])

#**************************************************************************#
class app(wx.App):
    """ Create and show all """
    def OnInit(self):
        self.mpm = MyPopupMenu()
        self.mpm.setup()
        self.frame = self.mpm.Show()
        return True

#**************************************************************************#
# Run the program
#**************************************************************************#
app = app(0)
app.MainLoop()
</code>```

答:
The binding to the close event and the close event function (deleteAll()) needed to be in the class where the graph was being created.

The working code is below.

```<code>#**************************************************************************#
# Set up a graph. A click creates a blue box. More blue boxes can be made
# by choosing "Make a new box" from right/click menu.
#**************************************************************************#

import wx
import matplotlib
matplotlib.use('WX')
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.figure import Figure
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigCanv
from pylab import *

#**************************************************************************#
class MainCanvas(wx.Frame):
    """ Class to set up graph """
    def __init__(self):
        wx.Frame.__init__(self,None,-1, 'Make Blue Boxes',size=(550,350))
        self.Bind(wx.EVT_CLOSE, self.deleteAll)

    #**********************************************************************#
    def deleteAll(self,event):
        sys.exit()

    #**********************************************************************#
    def setupGraph(self):
        """ Set up window and graph """
        self.definePlot()
        self.canvas = FigCanv(self, -1, self.figure)
        self.setSizer()

    #**********************************************************************#
    def definePlot(self):
        """ Define attributes of graph """
        self.SetBackgroundColour(wx.NamedColor("WHITE"))
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)

    #**********************************************************************#
    def setSizer(self):
        """ Set the size of the graph """
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()

#**************************************************************************#
class BlueBox(MainCanvas):
    """ Class to set up BlueBox """
    def __init__(self):
        MainCanvas.__init__(self)

    #**********************************************************************#
    def setupBlueBox(self):
        """ Blue box set up """
        self.blueBox = patches.Rectangle((0, 0), 0.05, 0.05,
                fc = "Blue", visible = False, zorder = 3)
        # Set zorder so new boxes are in front of old
        if len(self.listDT)>1:
            oldz = self.listDT[len(self.listDT)-2].blueBox.get_zorder() + 3
            self.listDT[len(self.listDT)-1].blueBox.set_zorder(oldz)

        self.axes.add_patch(self.blueBox)

    #**********************************************************************#
    def onPick(self, event):
        """ Behavior when graph is clicked """
        # Refresh BlueBox position and coordinate text
        self.refreshBlueBox(event)
        # Set the current BlueBox visible
        self.listDT[len(self.listDT)-1].setVisible()

    #**********************************************************************#
    def refreshBlueBox(self, event):
        """ Blue box refresh    """
        # Center the BlueBox (Point Box) over the mouse click location
        self.blueBox.set_x(event.xdata - .5 * self.blueBox.get_width())
        self.blueBox.set_y(event.ydata - .5 * self.blueBox.get_height())

    #**********************************************************************#
    def setVisible(self):
        """ Make BlueBox visible and refresh canvas """
        self.blueBox.set_visible(True)
        self.figure.canvas.draw()

    #**********************************************************************#
    def setGraphAttributes(self, axes, figure, listDT):
        """ Tell each BlueBox about the graph attributes it needs """
        self.axes = axes
        self.figure = figure
        self.listDT = listDT

#**************************************************************************#
class MyPopupMenu(BlueBox):
    """ Class to handle right clicks """
    def __init__(self):
        BlueBox.__init__(self)

    #**********************************************************************#
    def setup(self):
        """ Set up graph and BlueBox """
        self.setupGraph()
        # Bind right clicks to open the popup menu
        self.canvas.Bind(wx.EVT_RIGHT_DOWN,
                self.createPopupMenu)

        # Create lists for BlueBoxs and binding IDs
        self.listDT = []
        self.listBID = []

        self.popupCreateNew = wx.NewId()
        self.menu = wx.Menu()
        self.cn = self.menu.Append(self.popupCreateNew,
                "Make a new box")
        self.Bind(wx.EVT_MENU, self.createNew, self.cn)

        # Make the first BlueBox
        self.newBox()

    #**********************************************************************#
    def createPopupMenu(self, event):
        """ Create all parts of the right-click popup menu """
        self.PopupMenu(self.menu)

    #**********************************************************************#
    def newBox(self):
        """ Make a new BlueBox """
        self.listDT.append(BlueBox())
        self.listDT[len(self.listDT)-1].setGraphAttributes(self.axes,
                self.figure, self.listDT)
        self.listDT[len(self.listDT)-1].setupBlueBox()
        self.listBID.append(self.figure.canvas.mpl_connect('button_press_event',
                self.listDT[len(self.listDT)-1].onPick))

    #**********************************************************************#
    def createNew(self, event):
        """ Create a new BlueBox """
        event.Skip()
        self.newBox()
        if len(self.listBID) > 1:
            self.figure.canvas.mpl_disconnect(self.listBID[len(self.listBID)-2])

#**************************************************************************#
class app(wx.App):
    """ Create and show all """
    def OnInit(self):
        self.mpm = MyPopupMenu()
        self.mpm.setup()
        self.frame = self.mpm.Show()
        return True

#**************************************************************************#
# Run the program
#**************************************************************************#
app = app(0)
app.MainLoop()
</code>```

Body:
The program below sets up a graph and displays a blue box each time the user clicks.
A user can make more boxes using the right-click popup menu. When I implemented the popup menu (thus allowing multiple blue boxes) the program stopped closing on the window close. I connected a deleteAll() method to the canvas to force a sys.exit() on close, but the program still stays open. What am I doing wrong?

#**************************************************************************#
# Set up a graph. A click creates a blue box. More blue boxes can be made
# by choosing "Make a new box" from right/click menu.
#**************************************************************************#

import wx
import matplotlib
matplotlib.use('WX')
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.figure import Figure
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigCanv
from pylab import *

#**************************************************************************#
class MainCanvas(wx.Frame):
    """ Class to set up graph """
    def __init__(self):
        wx.Frame.__init__(self,None,-1, 'Make Blue Boxes',size=(550,350))

    #**********************************************************************#
    def setupGraph(self):
        """ Set up window and graph """
        self.definePlot()
        self.canvas = FigCanv(self, -1, self.figure)
        self.setSizer()

    #**********************************************************************#
    def definePlot(self):
        """ Define attributes of graph """
        self.SetBackgroundColour(wx.NamedColor("WHITE"))
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)

    #**********************************************************************#
    def setSizer(self):
        """ Set the size of the graph """
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()

#**************************************************************************#
class BlueBox(MainCanvas):
    """ Class to set up BlueBox """
    def __init__(self):
        MainCanvas.__init__(self)

    #**********************************************************************#
    def setupBlueBox(self):
        """ Blue box set up """
        self.blueBox = patches.Rectangle((0, 0), 0.05, 0.05,
                fc = "Blue", visible = False, zorder = 3)
        # Set zorder so new boxes are in front of old
        if len(self.listDT)>1:
            oldz = self.listDT[len(self.listDT)-2].blueBox.get_zorder() + 3
            self.listDT[len(self.listDT)-1].blueBox.set_zorder(oldz)

        self.axes.add_patch(self.blueBox)

    #**********************************************************************#
    def onPick(self, event):
        """ Behavior when graph is clicked """
        # Refresh BlueBox position and coordinate text
        self.refreshBlueBox(event)
        # Set the current BlueBox visible
        self.listDT[len(self.listDT)-1].setVisible()

    #**********************************************************************#
    def refreshBlueBox(self, event):
        """ Blue box refresh    """
        # Center the BlueBox (Point Box) over the mouse click location
        self.blueBox.set_x(event.xdata - .5 * self.blueBox.get_width())
        self.blueBox.set_y(event.ydata - .5 * self.blueBox.get_height())

    #**********************************************************************#
    def setVisible(self):
        """ Make BlueBox visible and refresh canvas """
        self.blueBox.set_visible(True)
        self.figure.canvas.draw()

    #**********************************************************************#
    def setGraphAttributes(self, axes, figure, listDT):
        """ Tell each BlueBox about the graph attributes it needs """
        self.axes = axes
        self.figure = figure
        self.listDT = listDT

#**************************************************************************#
class MyPopupMenu(BlueBox):
    """ Class to handle right clicks """
    def __init__(self):
        BlueBox.__init__(self)

    #**********************************************************************#
    def setup(self):
        """ Set up graph and BlueBox """
        self.setupGraph()
        # Bind right clicks to open the popup menu
        self.canvas.Bind(wx.EVT_RIGHT_DOWN,
                self.createPopupMenu)

        # Create lists for BlueBoxs and binding IDs
        self.listDT = []
        self.listBID = []

        self.popupCreateNew = wx.NewId()
        self.menu = wx.Menu()
        self.cn = self.menu.Append(self.popupCreateNew,
                "Make a new box")
        self.Bind(wx.EVT_MENU, self.createNew, self.cn)

        # Make the first BlueBox
        self.newBox()

        # Connect close events to delete everything
        self.figure.canvas.mpl_connect('close_event', self.deleteAll)

    #**********************************************************************#
    def deleteAll(self, event):
        """ Close out of the program cleanly """
        self.Destroy()
        sys.exit(0)

    #**********************************************************************#
    def createPopupMenu(self, event):
        """ Create all parts of the right-click popup menu """
        self.PopupMenu(self.menu)

    #**********************************************************************#
    def newBox(self):
        """ Make a new BlueBox """
        self.listDT.append(BlueBox())
        self.listDT[len(self.listDT)-1].setGraphAttributes(self.axes,
                self.figure, self.listDT)
        self.listDT[len(self.listDT)-1].setupBlueBox()
        self.listBID.append(self.figure.canvas.mpl_connect('button_press_event',
                self.listDT[len(self.listDT)-1].onPick))

    #**********************************************************************#
    def createNew(self, event):
        """ Create a new BlueBox """
        event.Skip()
        self.newBox()
        if len(self.listBID) > 1:
            self.figure.canvas.mpl_disconnect(self.listBID[len(self.listBID)-2])

#**************************************************************************#
class app(wx.App):
    """ Create and show all """
    def OnInit(self):
        self.mpm = MyPopupMenu()
        self.mpm.setup()
        self.frame = self.mpm.Show()
        return True

#**************************************************************************#
# Run the program
#**************************************************************************#
app = app(0)
app.MainLoop()

Body:
The binding to the close event and the close event function (deleteAll()) needed to be in the class where the graph was being created.

The working code is below.

#**************************************************************************#
# Set up a graph. A click creates a blue box. More blue boxes can be made
# by choosing "Make a new box" from right/click menu.
#**************************************************************************#

import wx
import matplotlib
matplotlib.use('WX')
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.figure import Figure
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigCanv
from pylab import *

#**************************************************************************#
class MainCanvas(wx.Frame):
    """ Class to set up graph """
    def __init__(self):
        wx.Frame.__init__(self,None,-1, 'Make Blue Boxes',size=(550,350))
        self.Bind(wx.EVT_CLOSE, self.deleteAll)

    #**********************************************************************#
    def deleteAll(self,event):
        sys.exit()

    #**********************************************************************#
    def setupGraph(self):
        """ Set up window and graph """
        self.definePlot()
        self.canvas = FigCanv(self, -1, self.figure)
        self.setSizer()

    #**********************************************************************#
    def definePlot(self):
        """ Define attributes of graph """
        self.SetBackgroundColour(wx.NamedColor("WHITE"))
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)

    #**********************************************************************#
    def setSizer(self):
        """ Set the size of the graph """
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()

#**************************************************************************#
class BlueBox(MainCanvas):
    """ Class to set up BlueBox """
    def __init__(self):
        MainCanvas.__init__(self)

    #**********************************************************************#
    def setupBlueBox(self):
        """ Blue box set up """
        self.blueBox = patches.Rectangle((0, 0), 0.05, 0.05,
                fc = "Blue", visible = False, zorder = 3)
        # Set zorder so new boxes are in front of old
        if len(self.listDT)>1:
            oldz = self.listDT[len(self.listDT)-2].blueBox.get_zorder() + 3
            self.listDT[len(self.listDT)-1].blueBox.set_zorder(oldz)

        self.axes.add_patch(self.blueBox)

    #**********************************************************************#
    def onPick(self, event):
        """ Behavior when graph is clicked """
        # Refresh BlueBox position and coordinate text
        self.refreshBlueBox(event)
        # Set the current BlueBox visible
        self.listDT[len(self.listDT)-1].setVisible()

    #**********************************************************************#
    def refreshBlueBox(self, event):
        """ Blue box refresh    """
        # Center the BlueBox (Point Box) over the mouse click location
        self.blueBox.set_x(event.xdata - .5 * self.blueBox.get_width())
        self.blueBox.set_y(event.ydata - .5 * self.blueBox.get_height())

    #**********************************************************************#
    def setVisible(self):
        """ Make BlueBox visible and refresh canvas """
        self.blueBox.set_visible(True)
        self.figure.canvas.draw()

    #**********************************************************************#
    def setGraphAttributes(self, axes, figure, listDT):
        """ Tell each BlueBox about the graph attributes it needs """
        self.axes = axes
        self.figure = figure
        self.listDT = listDT

#**************************************************************************#
class MyPopupMenu(BlueBox):
    """ Class to handle right clicks """
    def __init__(self):
        BlueBox.__init__(self)

    #**********************************************************************#
    def setup(self):
        """ Set up graph and BlueBox """
        self.setupGraph()
        # Bind right clicks to open the popup menu
        self.canvas.Bind(wx.EVT_RIGHT_DOWN,
                self.createPopupMenu)

        # Create lists for BlueBoxs and binding IDs
        self.listDT = []
        self.listBID = []

        self.popupCreateNew = wx.NewId()
        self.menu = wx.Menu()
        self.cn = self.menu.Append(self.popupCreateNew,
                "Make a new box")
        self.Bind(wx.EVT_MENU, self.createNew, self.cn)

        # Make the first BlueBox
        self.newBox()

    #**********************************************************************#
    def createPopupMenu(self, event):
        """ Create all parts of the right-click popup menu """
        self.PopupMenu(self.menu)

    #**********************************************************************#
    def newBox(self):
        """ Make a new BlueBox """
        self.listDT.append(BlueBox())
        self.listDT[len(self.listDT)-1].setGraphAttributes(self.axes,
                self.figure, self.listDT)
        self.listDT[len(self.listDT)-1].setupBlueBox()
        self.listBID.append(self.figure.canvas.mpl_connect('button_press_event',
                self.listDT[len(self.listDT)-1].onPick))

    #**********************************************************************#
    def createNew(self, event):
        """ Create a new BlueBox """
        event.Skip()
        self.newBox()
        if len(self.listBID) > 1:
            self.figure.canvas.mpl_disconnect(self.listBID[len(self.listBID)-2])

#**************************************************************************#
class app(wx.App):
    """ Create and show all """
    def OnInit(self):
        self.mpm = MyPopupMenu()
        self.mpm.setup()
        self.frame = self.mpm.Show()
        return True

#**************************************************************************#
# Run the program
#**************************************************************************#
app = app(0)
app.MainLoop()


问:
how can I post to api running on remote desktop?
I'm creating a python flask api on remote desktop and running it on localhost of remote desktop.
Is there anyway I can access this api from my local machine?
We are working in a team and I want to share this with my team members, but this is confidential and not to be deployed on open server.
We want to post and get the result with every member's local machine from api runnnig on remote desktop.
Both of our local machines and remote desktop are windows10.
Sorry for being abstract but I'm searching for any way out. Thanks.</p>

答:
Well, you should open your way to this API. You'll have to set up a VPN or IP address filter in the server so you can access the server from your network while still have it secured on the Internet. You can also setup a simpler proxy if you prefer it. I'll not cover the details on how to setup a VPN or proxy since it can get pretty extensive, but a Google search will help you out find the best alternative for you.

AFAIK, the Remote Desktop Protocol does not allow for any kind of VPN. However, if you can switch to TeamViewer, it does have an easy to setup VPN system that will allow you to get into the network with few configuration. Once a VPN is configured, it will work like if you were in the same network as the server, so from there you can access your API from your host machine by just going to the IP address of the server.

Do notice the security policies of whoever owns the server, since you can get into trouble if you don't have permission to enable some access from the outside. Security goes always in front of comfort.


问:
VSCode IntelliSense proposes a .h file but marks it not found
I can't compile a simple stupid demo "project" using visual Studio Code.

As I'm trying to enrich my knowledge portfolio, I trying to learn the basics manually, as to speak I try to compile code manually, without that the Visual Studio Enterprise IDE does all automatically. So I decided to use Visual Studio Code on Mac + clang++ for a simple demo project.

My problem is: I have a Workspace. In this workspace, I have some directories. One Of those directories called Functions and Headers contains again directories: debug, release, include, src. In the src directory, I have the functions.cpp file containing two dummy methods:

```<code>int add(int x, int y)
{
    return x + y;
}

int subtract(int x, int y)
{
    return x - y;
}
</code>```

and in the main.cpp:

```<code>#include "functions.h"

int main()
{
    int x = add(1, 3);
    int y = subtract(5,1);
    return 0;
}
</code>```

In my include folder I have two method declarations:

```<code>int add(int x, int y);
int subtract(int x, int y);
</code>```

The interesting point is: When I'm in main.cpp and I type #include " then IntelliSense finds the functions.h and proposes that file to me.
Also, the method calls are highlighted correctly. But: after including the file, Visual Studio Code marks the file read and says: functions.h file not found.

Is that a visual Studio Code bug? Because I also had a look on the settings and the settings seems ok (see picture).

Clang writes:

```<code>Ginos-MBP:src ginovalentinopensuni$ clang++ functions.cpp main.cpp main.cpp:2:10: fatal error: 'functions.h' file not found
#include "functions.h"
         ^~~~~~~~~~~~~ 1 error generated.
</code>```

Do I miss something or am I doing something wrong? I also looked at the other similar questions here, but there was nothing helpful.

Pictures:

答:
Indeed. The VSCode include path that allowed #include "functions.h" to be autocompleted has no bearing on what is a valid path to the compiler. There are two ways to address this:

Fix the path in the source file

Since you are including the header functions.h from the ./src directory, try instead writing:

```<code>#include "../include/functions.h"

int main()
{
    int x = add(1, 3);
    int y = subtract(5,1);
    return 0;
}
</code>```

This should work. Unless a specific include path is given to the compiler, clang++, like most other C++ compilers, will interpret the path relative to the location of the source file. In this case, it needs to go up a directory and then into the include directory in order to locate the functions.h header file.

Add an include path to that of clang++

From reading the clang++ man page, it can be ascertained that the -I flag may be used to specify an additional include path for the compiler to search to find header files. So, assuming that the command was run from the ./ directory, one jump out of the src directory and the root of the project:

clang++ src/main.cpp -I./include
```

would also address the issue at hand.

Body:
I can't compile a simple stupid demo "project" using visual Studio Code.

As I'm trying to enrich my knowledge portfolio, I trying to learn the basics manually, as to speak I try to compile code manually, without that the Visual Studio Enterprise IDE does all automatically. So I decided to use Visual Studio Code on Mac + clang++ for a simple demo project.

My problem is: I have a Workspace. In this workspace, I have some directories. One Of those directories called Functions and Headers contains again directories: debug, release, include, src. In the src directory, I have the functions.cpp file containing two dummy methods:

int add(int x, int y)
{
    return x + y;
}

int subtract(int x, int y)
{
    return x - y;
}

and in the main.cpp:

#include "functions.h"

int main()
{
    int x = add(1, 3);
    int y = subtract(5,1);
    return 0;
}

In my include folder I have two method declarations:

int add(int x, int y);
int subtract(int x, int y);

The interesting point is: When I'm in main.cpp and I type #include " then IntelliSense finds the functions.h and proposes that file to me.
Also, the method calls are highlighted correctly. But: after including the file, Visual Studio Code marks the file read and says: functions.h file not found.

Is that a visual Studio Code bug? Because I also had a look on the settings and the settings seems ok (see picture).

Clang writes:

Ginos-MBP:src ginovalentinopensuni$ clang++ functions.cpp main.cpp main.cpp:2:10: fatal error: 'functions.h' file not found
#include "functions.h"
         ^~~~~~~~~~~~~ 1 error generated.

Do I miss something or am I doing something wrong? I also looked at the other similar questions here, but there was nothing helpful.

Pictures:

Body:
Indeed. The VSCode include path that allowed #include "functions.h" to be autocompleted has no bearing on what is a valid path to the compiler. There are two ways to address this:

Fix the path in the source file

Since you are including the header functions.h from the ./src directory, try instead writing:

#include "../include/functions.h"

int main()
{
    int x = add(1, 3);
    int y = subtract(5,1);
    return 0;
}

This should work. Unless a specific include path is given to the compiler, clang++, like most other C++ compilers, will interpret the path relative to the location of the source file. In this case, it needs to go up a directory and then into the include directory in order to locate the functions.h header file.

Add an include path to that of clang++

From reading the clang++ man page, it can be ascertained that the -I flag may be used to specify an additional include path for the compiler to search to find header files. So, assuming that the command was run from the ./ directory, one jump out of the src directory and the root of the project:

clang++ src/main.cpp -I./include

would also address the issue at hand.


问:
Laravel 'WHERE' function in query breaks API?
I'm trying to make Gantt's chart using DHTMLX Gantt API.

The goal is to show only certain Gantt's lines to certain users. So for example: if I open a contract it shows me the Gantt's chart of that contract, but if I have permission for ex: purchases, then it should only show me the line with certain permission ID which is in the DB table Task.

Now the problem is somewhere around this function:

```<code>    public function getOne($id){
      $tasks = new Task();
      $links = new Link();

      return response()->json([
          "data" => $tasks->where('relation_id', $id)->where('permission', 2)->get(),
          "links" => $links->all()
      ]);
    }
</code>```

The 'relation_id' works fine and shows only a single project, but when I try to add another WHERE it just breaks without errors and doesn't load the chart information.

I think it has to do something with the JSON as if I do just send this query on any other page without inserting into GANTT (just as JSON) it shows me the correct information.

So basically I need to make that query work with this API, I have no clue about why 1 extra line of statement would break it.

I also tried the WHERE statement like this:

```<code>"data" => $tasks->where([['relation_id', '=', $id],['permission','=',2]])->get()
</code>```

Here is the link to the Gantt chart: link

I followed the steps in their documentation to start: link

答:
Try using parameter grouping, explained here: https://laravel.com/docs/master/queries#parameter-grouping. So it’ll look something like:

$tasks->where(function($query) {
    $query->where(‘relation_id’, $id)
               ->where(‘permission’, 2);
})->get();
```

<p>You also don’t need to have the “=” as this is understood by Laravel in the where statement if you leave it out (it’s only necessary for the other binary operations).</p>

<p>So I say all of this, but why are you creating a new task and then filtering it with a where statement? You should be getting all of the tasks and filtering them that way. For example:</p>

<pre class="lang-php prettyprint-override"><code>$tasks = Task::where(...)->get();
$links = Link::get();

return response()->json([‘tasks’ => $tasks, ‘links’ => $links]);
</code>```

This is easier and should give you the result you’re looking for. Hope this helps!

Body:
I'm trying to make Gantt's chart using DHTMLX Gantt API.

The goal is to show only certain Gantt's lines to certain users. So for example: if I open a contract it shows me the Gantt's chart of that contract, but if I have permission for ex: purchases, then it should only show me the line with certain permission ID which is in the DB table Task.

Now the problem is somewhere around this function:

    public function getOne($id){
      $tasks = new Task();
      $links = new Link();

      return response()->json([
          "data" => $tasks->where('relation_id', $id)->where('permission', 2)->get(),
          "links" => $links->all()
      ]);
    }

The 'relation_id' works fine and shows only a single project, but when I try to add another WHERE it just breaks without errors and doesn't load the chart information.

I think it has to do something with the JSON as if I do just send this query on any other page without inserting into GANTT (just as JSON) it shows me the correct information.

So basically I need to make that query work with this API, I have no clue about why 1 extra line of statement would break it.

I also tried the WHERE statement like this:

"data" => $tasks->where([['relation_id', '=', $id],['permission','=',2]])->get()

Here is the link to the Gantt chart: link

I followed the steps in their documentation to start: link

Body:
Try using parameter grouping, explained here: https://laravel.com/docs/master/queries#parameter-grouping. So it’ll look something like:

$tasks->where(function($query) {
    $query->where(‘relation_id’, $id)
               ->where(‘permission’, 2);
})->get();

You also don’t need to have the “=” as this is understood by Laravel in the where statement if you leave it out (it’s only necessary for the other binary operations).

So I say all of this, but why are you creating a new task and then filtering it with a where statement? You should be getting all of the tasks and filtering them that way. For example:

$tasks = Task::where(...)->get();
$links = Link::get();

return response()->json([‘tasks’ => $tasks, ‘links’ => $links]);

This is easier and should give you the result you’re looking for. Hope this helps!


问:
css & html child not affected by container dimensions
I have this part of code:

```<code><ul>
    <li>First item</li>
    <li>second item
        <ul>
            <li>child</li>
            <li>child</li>
        </ul>
    </li>
</ul>
</code>```

It is a menu on my webpage. It is printed like this by CMS.
For now, menu looks like this:

```<code>item1 | item2 | item3 | item4
            childItem3 | childItem3 | childItem3
</code>```

What i wanna do is style child items with CSS to start right in place where main menu starts, so it looks like this:

```<code>item1 | item2 | item3 | item4
childItem3 | childItem3 | childItem3
</code>```

How can i achieve this?

@edit:

here is the CSS i use. I made this very simple and it works fine (I've had problem with placing submenu under menu, but position:absolute repaired it)

```<code>#menu ul {
        position: relative;
}

#menu ul li {
    display: inline-block;
}

#menu ul li ul {
    position: absolute;
}
</code>```

答:
Without seeing your code, I would set the container of your outer ul to relative, then set your nested ul to position:absolute and give it a suitable top value to push it under the outer list.

EDIT: This is how you could change your CSS to achieve what you want:

```<code>ul { position: relative; }

ul li { float:left; }

ul li ul { position: absolute; display:none; }

ul li:hover ul { left:0px; top:20px; display:inline; }
</code>```

Obviously this has been simplified as you example CSS was. Working example: http://jsfiddle.net/ZfLwD/

Body:
I have this part of code:

First item

second item

child

child

It is a menu on my webpage. It is printed like this by CMS.
For now, menu looks like this:

item1 | item2 | item3 | item4
            childItem3 | childItem3 | childItem3

What i wanna do is style child items with CSS to start right in place where main menu starts, so it looks like this:

item1 | item2 | item3 | item4
childItem3 | childItem3 | childItem3

How can i achieve this?

@edit:

here is the CSS i use. I made this very simple and it works fine (I've had problem with placing submenu under menu, but position:absolute repaired it)

#menu ul {
        position: relative;
}

#menu ul li {
    display: inline-block;
}

#menu ul li ul {
    position: absolute;
}

Body:
Without seeing your code, I would set the container of your outer ul to relative, then set your nested ul to position:absolute and give it a suitable top value to push it under the outer list.

EDIT: This is how you could change your CSS to achieve what you want:

ul { position: relative; }

ul li { float:left; }

ul li ul { position: absolute; display:none; }

ul li:hover ul { left:0px; top:20px; display:inline; }

Obviously this has been simplified as you example CSS was. Working example: http://jsfiddle.net/ZfLwD/


问:
Gmail Drafts: Not able to delete the attachment
I am generating Draft email from Python and attaching the files. (I am using the code from here)

Problem: If I delete the attachment from the draft email and send it, the attachment get's sent.

Step 1: Drafts generated by Python script

Step 2: Removed the attachment by manually deleting it.

Step 3: This is the received email, (the attachment is present)

Not sure how to fix it. Is this a bug or Gmail behaving as expected. Any help is appreciated.

答:
If you thoroughly read the documentation about Working with Drafts

Drafts represent unsent messages with the DRAFT system label applied.
  The message contained within the draft cannot be edited once created,
  but it can be replaced. In this sense, the draft resource is simply a
  container that provides a stable ID because the underlying message IDs
  change every time the message is replaced.

That could be the reason.

OwnerDisplayName: Ravi


问:
Use glob or regex pattern for rollup.js externals
Is it possible to use a glob or regex pattern for the externals in my rollup config? With this config:

```<code>export default {
  ...
  external: [
    'prop-types',
    'react',
    'prettier/standalone',
    'prettier/parser-babylon',
    'react-syntax-highlighter/prism-light',
    'react-syntax-highlighter/languages/prism/jsx',
    'react-syntax-highlighter/styles/prism/tomorrow',
    'react-element-to-string'
  ],
  ...
};
</code>```

I would like to do something like:

```<code>export default {
  ...
  external: [
    'prop-types',
    'react',
    'prettier/**',
    'react-syntax-highlighter/**',
    'react-element-to-string'
  ],
  ...
};
</code>```

答:
This is not possible at the moment. You can however use a function to achieve something similar:

```<code>export default {
  ...
  external(id) {
    return [
      'prop-types',
      'react',
      'prettier',
      'react-syntax-highlighter',
      'react-element-to-string'
    ].includes(id.split('/')[0]);
  },
  ...
};
</code>```

You should avoid costly computations in this function as it will be called a lot (once for every import in every file to be precise).

Another option is to add the rollup-pluginutils package as a dependency which contains a createFilter function for glob support:

```<code>import { createFilter } from 'rollup-pluginutils';

const external = createFilter([
  'prop-types',
  'react',
  'prettier/**',
  'react-syntax-highlighter/**',
  'react-element-to-string'
], null, {resolve: false});
// {resolve: false} will make sure these filters are not passed to
// path.resolve first and resolved against the current working directory

export default {
  ...
  external,
  ...
};
</code>```

Body:
Is it possible to use a glob or regex pattern for the externals in my rollup config? With this config:

export default {
  ...
  external: [
    'prop-types',
    'react',
    'prettier/standalone',
    'prettier/parser-babylon',
    'react-syntax-highlighter/prism-light',
    'react-syntax-highlighter/languages/prism/jsx',
    'react-syntax-highlighter/styles/prism/tomorrow',
    'react-element-to-string'
  ],
  ...
};

I would like to do something like:

export default {
  ...
  external: [
    'prop-types',
    'react',
    'prettier/**',
    'react-syntax-highlighter/**',
    'react-element-to-string'
  ],
  ...
};

Body:
This is not possible at the moment. You can however use a function to achieve something similar:

export default {
  ...
  external(id) {
    return [
      'prop-types',
      'react',
      'prettier',
      'react-syntax-highlighter',
      'react-element-to-string'
    ].includes(id.split('/')[0]);
  },
  ...
};

You should avoid costly computations in this function as it will be called a lot (once for every import in every file to be precise).

Another option is to add the rollup-pluginutils package as a dependency which contains a createFilter function for glob support:

import { createFilter } from 'rollup-pluginutils';

const external = createFilter([
  'prop-types',
  'react',
  'prettier/**',
  'react-syntax-highlighter/**',
  'react-element-to-string'
], null, {resolve: false});
// {resolve: false} will make sure these filters are not passed to
// path.resolve first and resolved against the current working directory

export default {
  ...
  external,
  ...
};


问:
How to make SaveAs in its original path folder instead of "My document"
So basically I got this working with the code below to save a file with date as name by default.

```<code>Sub 巨集8()
'
    Dim xDlg As Dialog
    Dim xTitle As String
    On Error Resume Next
    xTitle = ActiveDocument.BuiltInDocumentProperties("Title").Value
    xTitle = xTitle & "- " & Format((Year(Now() + 1) Mod 100), "20##") & "" & _
        Format((Month(Now() + 1) Mod 100), "0#") & "" & _
        Format((Day(Now()) Mod 100), "0#")
    Set xDlg = Dialogs(wdDialogFileSaveAs)
    xDlg.Name = xTitle
    xDlg.Show
End Sub
</code>```

However the path is set to SaveAs at "My Document" how do i change it to be saved in the document original path , something like...

XXXX = Options.DefaultFilePath(wdStartupPath)

答:
This will work:

```<code>Sub 巨集8()

Dim xDlg As Dialog
Dim xTitle As String
On Error Resume Next
xTitle = ActiveDocument.BuiltinDocumentProperties("Title").Value
xTitle = xTitle & "- " & Format((Year(Now() + 1) Mod 100), "20##") & "" & _
    Format((Month(Now() + 1) Mod 100), "0#") & "" & _
    Format((Day(Now()) Mod 100), "0#")
Set xDlg = Dialogs(wdDialogFileSaveAs)
xDlg.Name = ActiveDocument.Path & "\" & xTitle
xDlg.Show

End Sub
</code>```

I have used Activedocument.Path property to find the current path.

Body:
So basically I got this working with the code below to save a file with date as name by default.

Sub 巨集8()
'
    Dim xDlg As Dialog
    Dim xTitle As String
    On Error Resume Next
    xTitle = ActiveDocument.BuiltInDocumentProperties("Title").Value
    xTitle = xTitle & "- " & Format((Year(Now() + 1) Mod 100), "20##") & "" & _
        Format((Month(Now() + 1) Mod 100), "0#") & "" & _
        Format((Day(Now()) Mod 100), "0#")
    Set xDlg = Dialogs(wdDialogFileSaveAs)
    xDlg.Name = xTitle
    xDlg.Show
End Sub

However the path is set to SaveAs at "My Document" how do i change it to be saved in the document original path , something like...

XXXX = Options.DefaultFilePath(wdStartupPath)

Body:
This will work:

Sub 巨集8()

Dim xDlg As Dialog
Dim xTitle As String
On Error Resume Next
xTitle = ActiveDocument.BuiltinDocumentProperties("Title").Value
xTitle = xTitle & "- " & Format((Year(Now() + 1) Mod 100), "20##") & "" & _
    Format((Month(Now() + 1) Mod 100), "0#") & "" & _
    Format((Day(Now()) Mod 100), "0#")
Set xDlg = Dialogs(wdDialogFileSaveAs)
xDlg.Name = ActiveDocument.Path & "\" & xTitle
xDlg.Show

End Sub

I have used Activedocument.Path property to find the current path.


问:
Running blackberry app into multiple emulators at the same time
I am developing a blackberry application and I'm trying to get to devices to communicate. I am trying out the SocketDemo app and it shed light into the socket process (which is no different from any other platform so far).

Only problem is I can't test the app since I can't get the app into two different emulators. How do I accomplish this?

答:
If you do not need to hook the second simulator into the debugger (for breakpoint setting, etc), then getting your application to run simultaneously on two simulators can be done fairly easily.

Build your application, and run it from the JDE; standard procedure.

Then, outside the JDE, start another simulator (it cannot be the same one), and, when that's up and running, choose FILE->LOAD JAVA APPLICATION from the second simulator's window menu. Select the .COD of the application you just built. The application will then be installed onto the second simulator, and will either start automatically, or you can start it by clicking on its icon (depending on how your project is set up).

With two simulators on the same machine, with applications that need to communicate through the network, it may be needed to change the ports in the .BAT file that launches the second simulator, before starting it -- otherwise, the second simulator may not be able to bind to the same ports on the machine.

Indeed, with some simulator models, you will not be able to do this unless the second simulator is from a different simulator package (different directory), because the process grabs a lock when it runs.

If you are using a built-in simulator package that only contains one simulator, you can download a second simulator, ideally a different model, from RIM's developer site: http://www.blackberry.com/developers/downloads/simulators/


问:
How do you scroll to the position of the cursor in a textarea?
JS Fiddle Demo

HTML

```<code><textarea rows='5'>
sdfasjfalsfjasf;klasdfklaksdfkjlasdfkjlasdjkfadls;fjklasdfjklasdkjlfaskljdfkalsjdfjlkasdfkjlasdkjlfasfkl;ajklsdfjklasdfkjlaskjldfaskjlfkljsadkjlfaskjldfkjlasdfkjlasdjklfaskljdfkjlasfkjlasdkjlfasjklfajklsdfjklasdfjlkadjsdfasjfalsfjasf;klasdfklaksdfkjlasdfkjlasdjkfadls;fjklasdfjklasdkjlfaskljdfkalsjdfjlkasdfkjlasdkjlfasfkl;ajklsdfjklasdfkjlaskjldfaskjlfkljsadkjlfaskjldfkjlasdfkjlasdjklfaskljdfkjlasfkjlasdkjlfasjklfajklsdfjklasdfjlkadjsdfasjfalsfjasf;klasdfklaksdfkjlasdfkjlasdjkfadls;fjklasdfjklasdkjlfaskljdfkalsjdfjlkasdfkjlasdkjlfasfkl;ajklsdfjklasdfkjlaskjldfaskjlfkljsadkjlfaskjldfkjlasdfkjlasdjklfaskljdfkjlasfkjlasdkjlfasjklfajklsdfjklasdfjlkadjsdfasjfalsfjasf;klasdfklaksdfkjlasdfkjlasdjkfadls;fjklasdfjklasdkjlfaskljdfkalsjdfjlkasdfkjlasdkjlfasfkl;ajklsdfjklasdfkjlaskjldfaskjlfkljsadkjlfaskjldfkjlasdfkjlasdjklfaskljdfkjlasfkjlasdkjlfasjklfajklsdfjklasdfjlkadj
</textarea>

<br />
<button id='scroll-to-cursor'>Scroll to Cursor</button>
</code>```

JavaScript

```<code>$('#scroll-to-cursor').on('click', function() {
    // ?
});
</code>```

Desired Outcome

Click somewhere in the textarea to place cursor.

Scroll away so cursor isn't visible.

Click "Scroll to Cursor" button.

Textarea scrolls to the position of the cursor

Note: I'm using jQuery.

The only way I could figure out how to scroll is to use jQuery's scrollTop
function. It sets the scroll position to "the number of pixels that are hidden from view above the scrollable area".

I've diagrammed the problem below. Passing in the length of that red line (in pixels) to scrollTop should do the trick. But I can't figure out how to get the length of the line.

答:
This is my spin on things.

I found that Audi Nugraha’s solution worked when testing, but not when I tried it in an Electron application.

A solution which did work for me was to position the cursor to the beginning and then blur/focus.

```<code>textarea.selectionEnd = textarea.selectionStart = position;
textarea.blur();
textarea.focus();
</code>```

I have incorporated the above into a function:

```<code>function scrollTextarea(textarea,position) {
    textarea.selectionEnd = textarea.selectionStart = position;
    textarea.blur();
    textarea.focus();
}
</code>```

Body:
JS Fiddle Demo

HTML

<textarea rows='5'>
sdfasjfalsfjasf;klasdfklaksdfkjlasdfkjlasdjkfadls;fjklasdfjklasdkjlfaskljdfkalsjdfjlkasdfkjlasdkjlfasfkl;ajklsdfjklasdfkjlaskjldfaskjlfkljsadkjlfaskjldfkjlasdfkjlasdjklfaskljdfkjlasfkjlasdkjlfasjklfajklsdfjklasdfjlkadjsdfasjfalsfjasf;klasdfklaksdfkjlasdfkjlasdjkfadls;fjklasdfjklasdkjlfaskljdfkalsjdfjlkasdfkjlasdkjlfasfkl;ajklsdfjklasdfkjlaskjldfaskjlfkljsadkjlfaskjldfkjlasdfkjlasdjklfaskljdfkjlasfkjlasdkjlfasjklfajklsdfjklasdfjlkadjsdfasjfalsfjasf;klasdfklaksdfkjlasdfkjlasdjkfadls;fjklasdfjklasdkjlfaskljdfkalsjdfjlkasdfkjlasdkjlfasfkl;ajklsdfjklasdfkjlaskjldfaskjlfkljsadkjlfaskjldfkjlasdfkjlasdjklfaskljdfkjlasfkjlasdkjlfasjklfajklsdfjklasdfjlkadjsdfasjfalsfjasf;klasdfklaksdfkjlasdfkjlasdjkfadls;fjklasdfjklasdkjlfaskljdfkalsjdfjlkasdfkjlasdkjlfasfkl;ajklsdfjklasdfkjlaskjldfaskjlfkljsadkjlfaskjldfkjlasdfkjlasdjklfaskljdfkjlasfkjlasdkjlfasjklfajklsdfjklasdfjlkadj
</textarea>

<button id='scroll-to-cursor'>Scroll to Cursor</button>

JavaScript

$('#scroll-to-cursor').on('click', function() {
    // ?
});

Desired Outcome

Click somewhere in the textarea to place cursor.

Scroll away so cursor isn't visible.

Click "Scroll to Cursor" button.

Textarea scrolls to the position of the cursor

Note: I'm using jQuery.

The only way I could figure out how to scroll is to use jQuery's scrollTop
function. It sets the scroll position to "the number of pixels that are hidden from view above the scrollable area".

I've diagrammed the problem below. Passing in the length of that red line (in pixels) to scrollTop should do the trick. But I can't figure out how to get the length of the line.

Body:
This is my spin on things.

I found that Audi Nugraha’s solution worked when testing, but not when I tried it in an Electron application.

A solution which did work for me was to position the cursor to the beginning and then blur/focus.

textarea.selectionEnd = textarea.selectionStart = position;
textarea.blur();
textarea.focus();

I have incorporated the above into a function:

function scrollTextarea(textarea,position) {
    textarea.selectionEnd = textarea.selectionStart = position;
    textarea.blur();
    textarea.focus();
}


答:
You are not creating a new task so stop using new, you need to go with query()

```<code>$tasks = Task::query();
$links = Link::query();

$tasks->where(['relation_id' => $id, 'permission' => 2])->get();
</code>```

Title: Laravel 'WHERE' function in query breaks API?

Body:
You are not creating a new task so stop using new, you need to go with query()

$tasks = Task::query();
$links = Link::query();

$tasks->where(['relation_id' => $id, 'permission' => 2])->get();


问:
How to get the PATH environment-variable separator in Python?
When multiple directories need to be concatenated, as in an executable search path, there is an os-dependent separator character.  For Windows it's ';', for Linux it's ':'.  Is there a way in Python to get which character to split on?

In the discussions to this question How do I find out my python path using python? , it is suggested that os.sep will do it. That answer is wrong, since it is the separator for components of a directory or filename and equates to '\\' or '/'.

答:
This is a sample path for your working directory/specific folder -

```<code> import os
 my = os.pathsep+ "testImages" + os.pathsep + "imageHidden.png"
 print(my)
</code>```

Output for Linux-

:testImages:imageHidden.png

Output for Windows-

;testImages;imageHidden.png

Body:
This is a sample path for your working directory/specific folder -

 import os
 my = os.pathsep+ "testImages" + os.pathsep + "imageHidden.png"
 print(my)

Output for Linux-

:testImages:imageHidden.png

Output for Windows-

;testImages;imageHidden.png


问:
How to pass form values to route
I'm having trouble passing a value from a form to a route.

```<code>{!! Form::open(['method'=>'POST', 'action'=> 'ReportController@index']) !!}

<div class="radio">
     <label><input type="radio" name="report_option" class="report_option" value="call_details">Call Details</label>
</div>
</code>```

Route::post('reports/{report}', 'ReportController@index');

答:
Change your route

```<code> Route::post('reports/{id}', 'ReportController@index')->name('viewreport');
</code>```

In your controller

```<code>public function index(Request $request,$id)
{
  // $id is the route value and $request contain other form values passed in the body of the request
}
</code>```

In your view

```<code> <form action="{{route('viewreport',['id'=>$report->id])}}" method="post">
</code>```

Title: How to pass form values to route

Body:
I'm having trouble passing a value from a form to a route.

{!! Form::open(['method'=>'POST', 'action'=> 'ReportController@index']) !!}

     <input type="radio" name="report_option" class="report_option" value="call_details">Call Details

Route::post('reports/{report}', 'ReportController@index');

Body:
Change your route

 Route::post('reports/{id}', 'ReportController@index')->name('viewreport');

In your controller

public function index(Request $request,$id)
{
  // $id is the route value and $request contain other form values passed in the body of the request
}

In your view

 <form action="{{route('viewreport',['id'=>$report->id])}}" method="post">


问:
I have SafeAreaView at root of my app but I want a full screen backgroundColor (including the top and bottom of safeAreaView ) at few screens in app
I am using SafeAreaView in the root of my project App.js. But some screens need full white background from top to bottom. Since I am using SafeAreaView in root every screen view starts after SafeAreaView even making a view with absolute position of the height of the SafeAreaView doesn't work like this:

```<code>render() {
  return (
    <View style={styles.container}>
      <View style={[styles.hideSafeAreaView, { top: 0 }]} />
      {/*....*/}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: whiteTextColor,
    padding: 12
  },
  hideSafeAreaView: {
    position: "absolute",
    backgroundColor: whiteTextColor,
    right: 0,
    left: 0,
    height: 44
  }
});
</code>```

This is my app.js

```<code>render() {
  return (
    <ImageBackground style={styles.container} source={APP_BACKGROUND_IMAGE}>
      <SafeAreaView style={styles.container}>
        <AppNavigator />
      </SafeAreaView>
    </ImageBackground>
  );
}
</code>```

Thanks in advance.

答: I found a simple trick to do this. I removed SafeAreaView form root component and made a custom Header of height 44. I used this reusable Header in all files where I wanted SafeAreaView to work.</p>

Body:
I am using SafeAreaView in the root of my project App.js. But some screens need full white background from top to bottom. Since I am using SafeAreaView in root every screen view starts after SafeAreaView even making a view with absolute position of the height of the SafeAreaView doesn't work like this:

render() {
  return (
    <View style={styles.container}>
      <View style={[styles.hideSafeAreaView, { top: 0 }]} />
      {/*....*/}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: whiteTextColor,
    padding: 12
  },
  hideSafeAreaView: {
    position: "absolute",
    backgroundColor: whiteTextColor,
    right: 0,
    left: 0,
    height: 44
  }
});

This is my app.js

render() {
  return (
    <ImageBackground style={styles.container} source={APP_BACKGROUND_IMAGE}>
      <SafeAreaView style={styles.container}>
        <AppNavigator />
      </SafeAreaView>
    </ImageBackground>
  );
}

Thanks in advance.


问:
Excel doesn't close
I do everything. But "excel.exe" process doesn't close.
If doExcel.Visible = true, window's excel close. But not process. Why?

```<code>Excel.Application excel = new Excel.Application();
Excel.Workbooks books = excel.Workbooks;
Excel.Workbook book = books.Add();
Excel.Sheets sheets = book.Sheets;
Excel.Worksheet sheet = sheets.Item[1];
foreach (Contract c in list){
     //sheet.Cells[i, 1] = some str;}
book.Close(true, @"some path");
books.Close();
excel.Quit();
Marshal.ReleaseComObject(sheet);
Marshal.FinalReleaseComObject(sheet);
Marshal.ReleaseComObject(sheets);
Marshal.FinalReleaseComObject(sheets);
Marshal.ReleaseComObject(book);
Marshal.FinalReleaseComObject(book);
Marshal.ReleaseComObject(books);
Marshal.FinalReleaseComObject(books);
Marshal.ReleaseComObject(excel);
Marshal.FinalReleaseComObject(excel);

GC.Collect();
GC.WaitForPendingFinalizers();
Console.Read();
</code>```

答:
This work for me:

Release (no Debug)

```<code>using Microsoft.Office.Interop.Excel;
//..
Excel.Application excel = new Excel.Application();
Workbook book = excel.Workbooks.Add();
Worksheet sheet = book.Sheets.Item[1];
try
{
    //int i = 2;
    //foreach ()
    //{
    //sheet.Cells[i, 1] = ...;
    //i++;
    //}
}
catch { }
finally
{
    book.Close(true, @"path");
    excel.Quit();
}
Console.Read();
</code>```

if Debug - doesn't work.

Title: Excel doesn't close

Body:
I do everything. But "excel.exe" process doesn't close.
If doExcel.Visible = true, window's excel close. But not process. Why?

Excel.Application excel = new Excel.Application();
Excel.Workbooks books = excel.Workbooks;
Excel.Workbook book = books.Add();
Excel.Sheets sheets = book.Sheets;
Excel.Worksheet sheet = sheets.Item[1];
foreach (Contract c in list){
     //sheet.Cells[i, 1] = some str;}
book.Close(true, @"some path");
books.Close();
excel.Quit();
Marshal.ReleaseComObject(sheet);
Marshal.FinalReleaseComObject(sheet);
Marshal.ReleaseComObject(sheets);
Marshal.FinalReleaseComObject(sheets);
Marshal.ReleaseComObject(book);
Marshal.FinalReleaseComObject(book);
Marshal.ReleaseComObject(books);
Marshal.FinalReleaseComObject(books);
Marshal.ReleaseComObject(excel);
Marshal.FinalReleaseComObject(excel);

GC.Collect();
GC.WaitForPendingFinalizers();
Console.Read();

Body:
This work for me:

Release (no Debug)

using Microsoft.Office.Interop.Excel;
//..
Excel.Application excel = new Excel.Application();
Workbook book = excel.Workbooks.Add();
Worksheet sheet = book.Sheets.Item[1];
try
{
    //int i = 2;
    //foreach ()
    //{
    //sheet.Cells[i, 1] = ...;
    //i++;
    //}
}
catch { }
finally
{
    book.Close(true, @"path");
    excel.Quit();
}
Console.Read();

if Debug - doesn't work.


问:
didSelectRowAt is not working with my UITableViewController
I am having trouble with my UITableVieController. It is not correctly calling my didSelectRowAt function. I have multiple sections in my UITableView but another section of my code with the same exact code is working perfectly fine and I can not figure out why this is not working

I have already checked if my table view has the correct delegate and data source and it does.

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

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return section == 0 ? 1 : songList.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "InfoCell", for: indexPath) as! InfoCell

            cell.playlistImage.image = playlistImage
            cell.name.text = selectedPlaylist
            cell.nuberOfSongs.text = "Number of Songs: \(playlistCount)"

            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "SongCell", for: indexPath) as! SongCell
            cell.SongTitle.text = songList[indexPath.row]
            cell.SongArtist.text = artistList[indexPath.row]
            cell.SongImage.image = imageList[indexPath.row]
            return cell
        }
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        if indexPath.section != 0 {

            selectedItem = mediaList[indexPath.row]

            play(selectedItem: selectedItem)

            performSegue(withIdentifier: "showPlayer", sender: self)

            tableView.deselectRow(at: indexPath, animated: true)
        }

    }
</code>```

This is all of my code for creating the sections and the rows that go in those sections. It also contains the code for didSelectRowAt but that function is not being called at all.

答:
Are you providing a UITapGestureRecogniser to your superview of the UITableView, if this is the case then the didSelectRowAt method of UITableview won't work because your superview is receiving the touch instead of tableview cell.

For this, you can add a delegate to your UITapGestureRecogniser like this :

```<code>let tap = UITapGestureRecognizer(target: self, action: #selector(selectorFunction))
tap.delegate = self
superview.addGestureRecognizer(tap)
</code>```

After this just conform your viewcontroller to this delegate

```<code>extension YourViewController : UIGestureRecognizerDelegate
{
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        if (touch.view?.isDescendant(of: yourTableView))!
        {
            return false
        }
        return true
    }
}
</code>```

Body:
I am having trouble with my UITableVieController. It is not correctly calling my didSelectRowAt function. I have multiple sections in my UITableView but another section of my code with the same exact code is working perfectly fine and I can not figure out why this is not working

I have already checked if my table view has the correct delegate and data source and it does.

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

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return section == 0 ? 1 : songList.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "InfoCell", for: indexPath) as! InfoCell

            cell.playlistImage.image = playlistImage
            cell.name.text = selectedPlaylist
            cell.nuberOfSongs.text = "Number of Songs: \(playlistCount)"

            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "SongCell", for: indexPath) as! SongCell
            cell.SongTitle.text = songList[indexPath.row]
            cell.SongArtist.text = artistList[indexPath.row]
            cell.SongImage.image = imageList[indexPath.row]
            return cell
        }
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        if indexPath.section != 0 {

            selectedItem = mediaList[indexPath.row]

            play(selectedItem: selectedItem)

            performSegue(withIdentifier: "showPlayer", sender: self)

            tableView.deselectRow(at: indexPath, animated: true)
        }

    }

This is all of my code for creating the sections and the rows that go in those sections. It also contains the code for didSelectRowAt but that function is not being called at all.

Body:
Are you providing a UITapGestureRecogniser to your superview of the UITableView, if this is the case then the didSelectRowAt method of UITableview won't work because your superview is receiving the touch instead of tableview cell.

For this, you can add a delegate to your UITapGestureRecogniser like this :

let tap = UITapGestureRecognizer(target: self, action: #selector(selectorFunction))
tap.delegate = self
superview.addGestureRecognizer(tap)

After this just conform your viewcontroller to this delegate

extension YourViewController : UIGestureRecognizerDelegate
{
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        if (touch.view?.isDescendant(of: yourTableView))!
        {
            return false
        }
        return true
    }
}


问:
SQL equality showing incorrect results
I am having simple issue with my SQL studio. I am selecting 2 fields:

```<code>  SELECT Project, OperationName
  FROM [LESTO].[UserData].[Orders]
  where project='SLS002701'
</code>```

And the following result is:

Obviously there is OperationName that is called ОПАКОВАНЕ/PACKING. But when I try:

```<code>SELECT Project, OperationName
FROM [LESTO].[UserData].[Orders]
where OperationName = 'ОПАКОВАНЕ/PACKING'
</code>```

There is no result (0). How is this possible?

答:
Try with

```<code>SELECT Project, OperationName
FROM [LESTO].[UserData].[Orders]
where OperationName = N'ОПАКОВАНЕ/PACKING'
</code>```

For nvarchar you require N' when non-Unicode characters.

Title: SQL equality showing incorrect results

Body:
I am having simple issue with my SQL studio. I am selecting 2 fields:

  SELECT Project, OperationName
  FROM [LESTO].[UserData].[Orders]
  where project='SLS002701'

And the following result is:

Obviously there is OperationName that is called ОПАКОВАНЕ/PACKING. But when I try:

SELECT Project, OperationName
FROM [LESTO].[UserData].[Orders]
where OperationName = 'ОПАКОВАНЕ/PACKING'

There is no result (0). How is this possible?

Body:
Try with

SELECT Project, OperationName
FROM [LESTO].[UserData].[Orders]
where OperationName = N'ОПАКОВАНЕ/PACKING'

For nvarchar you require N' when non-Unicode characters.


问:
Grails JSON Marshaller Shows a Different Date value than Original Date
In my Grails app, the original date read from the database is equal to:

```<code>{ endDate=2015-10-19 19:00:00.0}
</code>```

While the JSON result is:

```<code>{"endDate": "2015-10-19T16:00:00Z"}
</code>```

I think this is maybe related to time zone conversion. How could I show the original date without any timezone conversions in JSON?

答:
Working on an old application that is built with grails 2.3.11 in which for some unbeknownst reason @Dónal's solution wasn't working. Fortunately, I found an easier/more straightforward approach to register a custom marshaller on mrhaki's blog.

So, I made a copy of the default DateMarshaller that resides in org.codehaus.groovy.grails.web.converters.marshaller.json and modified the date formatter in my custom DateMarshaller and then registered the marshaller using the snippet below, taken from mrhaki's post.

```<code>dateMarshaller(ObjectMarshallerRegisterer) {
    // Assign custom marshaller instance.
    marshaller = new DateMarshaller()

    // Set converter class type.
    converterClass = JSON

    // Optional set priority. Default value is 0.
    priority = 1
}
</code>```

Just make sure that your Custom Marshaller has a higher priority than the default one. Works like a charm!

Body:
In my Grails app, the original date read from the database is equal to:

{ endDate=2015-10-19 19:00:00.0}

While the JSON result is:

{"endDate": "2015-10-19T16:00:00Z"}

I think this is maybe related to time zone conversion. How could I show the original date without any timezone conversions in JSON?

Body:
Working on an old application that is built with grails 2.3.11 in which for some unbeknownst reason @Dónal's solution wasn't working. Fortunately, I found an easier/more straightforward approach to register a custom marshaller on mrhaki's blog.

So, I made a copy of the default DateMarshaller that resides in org.codehaus.groovy.grails.web.converters.marshaller.json and modified the date formatter in my custom DateMarshaller and then registered the marshaller using the snippet below, taken from mrhaki's post.

dateMarshaller(ObjectMarshallerRegisterer) {
    // Assign custom marshaller instance.
    marshaller = new DateMarshaller()

    // Set converter class type.
    converterClass = JSON

    // Optional set priority. Default value is 0.
    priority = 1
}

Just make sure that your Custom Marshaller has a higher priority than the default one. Works like a charm!