问:
What's the best way to save trivial user states (e.g. dismissed welcome msg) in database?
Should I use (create) a column for every new state? Or one field with a bunch of comma separated states (alternatively a json obj)? Any suggestions welcome.

UPDATE

First let me day thanks for the answers. I just want to clear up, what options I see:

Put a column for every state in the user row (initial plan) / Can get messy with lots of states (in the future)

Put one column with json/xml data in the user row / Easy to maintain (no db change required), but doesn't feel right

Have a dedicated states table (thx lhiles)/ Sounds cool, how would this table look like?

I'm looking for pros/cons of the different implementations. Again: Thanks!

答:
Create a column for each state. This is proper data normalization.

With a column for each state you can retrieve as few or as many states as needed for the current operation.

All of the states returned will be contained in a single row with each column named. This makes referencing each state value very easy.

It allows you to easily add constraints to each state as needed. (State X can only contain '1' or '2'.)

It allows you to easily query states across users. (How many users have set a state value to 'X'?)


来源: stackexchange

问:
which is the best way to implement: two separate array or array in array?
I need an advice!
I have an array of objects with many students data(more then 200 students). So, now, i want to implement lesson for this students, so, every day, i will push an array with data inside every array of students. Later i will work with all lesson data!
So my question is:
a) Is the best way to push array inside of every students array?
b) Or make another array with  unique _id, and later filter lesson by students _id?

So, i'm looking for performance and speed...

答:
As I understood from your architecture, a suitable option will be moving lessons to a separate collection and storing lesson._id in students[].lessons. You can reach it by using ref property in your mongoose schema.

Here's the example:

lessons collection data:

```<code>[
  {
    "_id": ObjectId("5a934e000102030405000001"),
    "name": "First lesson"
  },
  {
    "_id": ObjectId("5a934e000102030405000002"),
    "name": "Second lesson"
  }
]
</code>```

groups collection data:

```<code>[
  {
    "_id": ObjectId("5a934e000102030405000003"),
    "name": "Group 1",
    "students": [
      {
        "_id": ObjectId("5a934e000102030405000004"),
        "name": "John",
        "lessons": [ObjectId("5a934e000102030405000001")]
      },
      {
        "_id": ObjectId("5a934e000102030405000005"),
        "name": "James",
        "lessons": [ObjectId("5a934e000102030405000001"), ObjectId("5a934e000102030405000002")]
      }
    ]
  }
]
</code>```

But I would also moved every student to separate students collection if it is possible (if you currently have students as array field).

ContentLicense: CC BY-SA 4.0

Body:
As I understood from your architecture, a suitable option will be moving lessons to a separate collection and storing lesson._id in students[].lessons. You can reach it by using ref property in your mongoose schema.

Here's the example:

lessons collection data:

[
  {
    "_id": ObjectId("5a934e000102030405000001"),
    "name": "First lesson"
  },
  {
    "_id": ObjectId("5a934e000102030405000002"),
    "name": "Second lesson"
  }
]

groups collection data:

[
  {
    "_id": ObjectId("5a934e000102030405000003"),
    "name": "Group 1",
    "students": [
      {
        "_id": ObjectId("5a934e000102030405000004"),
        "name": "John",
        "lessons": [ObjectId("5a934e000102030405000001")]
      },
      {
        "_id": ObjectId("5a934e000102030405000005"),
        "name": "James",
        "lessons": [ObjectId("5a934e000102030405000001"), ObjectId("5a934e000102030405000002")]
      }
    ]
  }
]

But I would also moved every student to separate students collection if it is possible (if you currently have students as array field).


问:
Does gem log unrecognised options with whitespace?
I'm seeing a somewhat peculiar error in Jenkins where a gem is being invoked correctly, but the error is spitting out an option with a whitespace character between the options identifier (--) and the option name (checksum).

```<code>gemname publish_artifact --version 0.1.0 --checksum 01fakechecksum89 --repository release

publish_artifact: unrecognised option -- checksum
</code>```

I checked the Jenkins node and the option is available. I haven't run the command because the deployment is not mine to make, I'm just on the ops team and am not really that familiar with Ruby yet.

I ran a command with a fake option for a different gem and got a different error response.

```<code>$ yard list --fakename blah
[warn]: Unrecognized/invalid option: --fakename
</code>```

Notice no whitespace between the option specifier and the name. I'm digging into the Jenkins pipeline configuration because it is quite complex, and maybe the command is getting butchered between the master and the node, but it just doesn't make much sense to me.

答: It turned out to be a rather misleading error. The problem was that gem failed to update to the newest version. The older version didn't have the checksum option.

Body:
I'm seeing a somewhat peculiar error in Jenkins where a gem is being invoked correctly, but the error is spitting out an option with a whitespace character between the options identifier (--) and the option name (checksum).

gemname publish_artifact --version 0.1.0 --checksum 01fakechecksum89 --repository release

publish_artifact: unrecognised option -- checksum

I checked the Jenkins node and the option is available. I haven't run the command because the deployment is not mine to make, I'm just on the ops team and am not really that familiar with Ruby yet.

I ran a command with a fake option for a different gem and got a different error response.

$ yard list --fakename blah
[warn]: Unrecognized/invalid option: --fakename

Notice no whitespace between the option specifier and the name. I'm digging into the Jenkins pipeline configuration because it is quite complex, and maybe the command is getting butchered between the master and the node, but it just doesn't make much sense to me.


问:
Is it possible to intercept Console output?
I call a method, say, FizzBuzz(), over which I have no control.  This method outputs a bunch of stuff to the Console using Console.WriteLine.

Is it possible for me to intercept the output being generated by the FizzBuzz method?
Note that my application is a Console app itself.

答:
Yes, very much possible:

```<code>var consoleOut = new StringWriter();
Console.SetOut(consoleOut);
Console.WriteLine("This is intercepted."); // This is not written to console
File.WriteAllText("ConsoleOutput.txt", consoleOut.ToString());
</code>```

Later on if you want to stop intercepting the console output, use modification below:

```<code>var stdOut = Console.Out;
// Above interceptor code here..
Console.SetOut(stdOut); // Now all output start going back to console window
</code>```

Or the OpenStandardOutput does the same without the need to save the standard stream first:

```<code>// Above interceptor code here..
var standardOutput = new StreamWriter(Console.OpenStandardOutput());
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput); // Now all output starts flowing back to console
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Yes, very much possible:

var consoleOut = new StringWriter();
Console.SetOut(consoleOut);
Console.WriteLine("This is intercepted."); // This is not written to console
File.WriteAllText("ConsoleOutput.txt", consoleOut.ToString());

Later on if you want to stop intercepting the console output, use modification below:

var stdOut = Console.Out;
// Above interceptor code here..
Console.SetOut(stdOut); // Now all output start going back to console window

Or the OpenStandardOutput does the same without the need to save the standard stream first:

// Above interceptor code here..
var standardOutput = new StreamWriter(Console.OpenStandardOutput());
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput); // Now all output starts flowing back to console


问:
Merge two c# object(json) lists as parent child
I have a json string which looks as below:

```<code>[
  {
     "id": 1,
    "title": "Hello"
  },
  {
    "id": 2,
    "title": "test"
  }
]

[
  {
     "id": 1,
    "parentId": 1,
    "prop1": "sdsdsdt",
    "prop1l": "3dsdsd",
    "v": "fsssd sd"
  },
   {
     "id": 2,
    "parentId": 1,
    "prop1": "sdsdsdt",
    "prop1l": "3dsdsd",
    "v": "fsssd sd"
  },
    {
     "id": 3,
    "parentId": 2,
    "prop1": "sdsdsdt",
    "prop2": "3dsdsd",
    "prop3": "fsssd sd"
  }
]
</code>```

I can serialize it into two classes (list) as below:

```<code>public class Parent
{
    public int id { get; set; }
    public string title { get; set; }
}

public class Child
{
    public int id { get; set; }
    public int parentId { get; set; }
    public string prop1 { get; set; }
    public string prop2 { get; set; }
    public string prop3 { get; set; }
}
</code>```

Now I want to create third collection where I can merge children under parent object. I know I can do with for loop in parent and look for children for parentId in Child. I wonder if there is a better way? So I can get these as below list:

```<code>public class Merged
{
    public int id { get; set; }
    public string title { get; set; }
    public list<Child> children{get;set;}
}
</code>```

答:
After you serialized your collections, you can use LINQ GroupBy method:

```<code>var parentList = new List<Parent>(); //your serialized parent list
var childList = new List<Child>(); //your serialized child list

var mergedList = parentList
    .GroupJoin(
        childList, p => p.id, ch => ch.parentId, (p, ch) => new Merged {
            id = p.id,
            title = p.title,
            children = ch.ToList()
        })
    .ToList();
</code>```

Body:
I have a json string which looks as below:

[
  {
     "id": 1,
    "title": "Hello"
  },
  {
    "id": 2,
    "title": "test"
  }
]

[
  {
     "id": 1,
    "parentId": 1,
    "prop1": "sdsdsdt",
    "prop1l": "3dsdsd",
    "v": "fsssd sd"
  },
   {
     "id": 2,
    "parentId": 1,
    "prop1": "sdsdsdt",
    "prop1l": "3dsdsd",
    "v": "fsssd sd"
  },
    {
     "id": 3,
    "parentId": 2,
    "prop1": "sdsdsdt",
    "prop2": "3dsdsd",
    "prop3": "fsssd sd"
  }
]

I can serialize it into two classes (list) as below:

public class Parent
{
    public int id { get; set; }
    public string title { get; set; }
}

public class Child
{
    public int id { get; set; }
    public int parentId { get; set; }
    public string prop1 { get; set; }
    public string prop2 { get; set; }
    public string prop3 { get; set; }
}

Now I want to create third collection where I can merge children under parent object. I know I can do with for loop in parent and look for children for parentId in Child. I wonder if there is a better way? So I can get these as below list:

public class Merged
{
    public int id { get; set; }
    public string title { get; set; }
    public list<Child> children{get;set;}
}

Body:
After you serialized your collections, you can use LINQ GroupBy method:

var parentList = new List<Parent>(); //your serialized parent list
var childList = new List<Child>(); //your serialized child list

var mergedList = parentList
    .GroupJoin(
        childList, p => p.id, ch => ch.parentId, (p, ch) => new Merged {
            id = p.id,
            title = p.title,
            children = ch.ToList()
        })
    .ToList();


问:
Is it possible to browse all directories in file system using mysql?
I'm currently studying SQL injection, and I wonder if it's possible to display all the directories using an SQL injection in MySQL? I mean, I know, that there's a load_file() function that allows to display a file, but what about directories (their contents)? Does it takes to upload some kind of shell or there's a better solution to display all the contents?</p>

答:
The LOAD_FILE() function will not read directories. It only reads regular files.

Here's a link to the specific line of code that checks if the file you tried to open is a regular file, and if it isn't, return an error.
https://github.com/mysql/mysql-server/blob/8.0/sql/item_strfunc.cc#L3498

```<code>  if (!MY_S_ISREG(stat_info.st_mode)) {
    my_error(ER_TEXTFILE_NOT_READABLE, MYF(0), file_name->c_ptr());
    mysql_file_close(file, MYF(0));
    DBUG_ASSERT(maybe_null);
    return error_str();
  }
</code>```

We can also demonstrate. I created a file "/tmp/world" and put the word "hello" into it.

I can read the file:

```<code> MySQL  localhost:33060+ ssl  SQL > select load_file('/tmp/world');
+-------------------------+
| load_file('/tmp/world') |
+-------------------------+
| hello
                  |
+-------------------------+
1 row in set (0.0007 sec)
</code>```

But I can't read the directory:

```<code> MySQL  localhost:33060+ ssl  SQL > select load_file('/tmp');
ERROR: 1085: The file '/tmp' must be in the database directory or be readable by all
</code>```

This error isn't clear about the real reason it can't read the file. It just returns a general error corresponding to the code constant ER_TEXTFILE_NOT_READABLE.

Body:
The LOAD_FILE() function will not read directories. It only reads regular files.

Here's a link to the specific line of code that checks if the file you tried to open is a regular file, and if it isn't, return an error.
https://github.com/mysql/mysql-server/blob/8.0/sql/item_strfunc.cc#L3498

  if (!MY_S_ISREG(stat_info.st_mode)) {
    my_error(ER_TEXTFILE_NOT_READABLE, MYF(0), file_name->c_ptr());
    mysql_file_close(file, MYF(0));
    DBUG_ASSERT(maybe_null);
    return error_str();
  }

We can also demonstrate. I created a file "/tmp/world" and put the word "hello" into it.

I can read the file:

 MySQL  localhost:33060+ ssl  SQL > select load_file('/tmp/world');
+-------------------------+
| load_file('/tmp/world') |
+-------------------------+
| hello
                  |
+-------------------------+
1 row in set (0.0007 sec)

But I can't read the directory:

 MySQL  localhost:33060+ ssl  SQL > select load_file('/tmp');
ERROR: 1085: The file '/tmp' must be in the database directory or be readable by all

This error isn't clear about the real reason it can't read the file. It just returns a general error corresponding to the code constant ER_TEXTFILE_NOT_READABLE.


问:
Image hyperlink dimensions wrong
I am trying to add a hyperlink to an image and it works fine, but when I hover over the ... node in Chrome Dev Tools, it shows the wrong dimensions.

Dev Tools shows that the dimensions are 512x18 and it also shows the box model is nudged below the image by about 5 pixels or so.

I don't understand why this is happening or what is going on here. If I have a 512x512 pixel image, I want the hyperlink dimensions to be 512x512 pixels.

```
</div>
</div>
</p>

<p>I tried adding <code>WIDTH</code> and <code>HEIGHT</code> attributes to the image, but that didn't work. It seemed like the only way to get it to work was to add a defined CSS size to the surrounding <code><A>...</A></code> hyperlink element.</p>

```STYLE="display: inline-block; width: 512px; height: 512px"
```

Is there any other way of doing this without having to hardcode the dimensions of the image?

答:
Add "display: inline-flex;" on the anchor tag, you will get same dimensions of the image for anchor tag. I have added it inline in below snippet but you can move this property to your CSS file :</p>

```<code><A HREF="https://via.placeholder.com/512" style="display:inline-flex;"><IMG ALT="Text" SRC="https://via.placeholder.com/512"/></A>
</code>```

Title: Image hyperlink dimensions wrong

Body:
I am trying to add a hyperlink to an image and it works fine, but when I hover over the ... node in Chrome Dev Tools, it shows the wrong dimensions.

Dev Tools shows that the dimensions are 512x18 and it also shows the box model is nudged below the image by about 5 pixels or so.

I don't understand why this is happening or what is going on here. If I have a 512x512 pixel image, I want the hyperlink dimensions to be 512x512 pixels.

I tried adding WIDTH and HEIGHT attributes to the image, but that didn't work. It seemed like the only way to get it to work was to add a defined CSS size to the surrounding ... hyperlink element.

STYLE="display: inline-block; width: 512px; height: 512px"

Is there any other way of doing this without having to hardcode the dimensions of the image?

Body:
Add "display: inline-flex;" on the anchor tag, you will get same dimensions of the image for anchor tag. I have added it inline in below snippet but you can move this property to your CSS file :

<A HREF="https://via.placeholder.com/512" style="display:inline-flex;"><IMG ALT="Text" SRC="https://via.placeholder.com/512"/></A>


问:
Python List assignment seems like it gets carried away
```<code>a=[1] # here is a comment to the right
print("as expected, a=", a)

b=a
print("as expected, b=", b)

a[0]=2

print("as expected, now a=", a)

print("NOT EXPECTED TO CHANGE now b=", b)
</code>```

答:
lists are mutable ... both a and b point to the same list, so changing a will also change b

if you do not want this behaviour assign a copy of a to b

```<code>b = a[:]
</code>```

if you had used an immutable datatype (like a string or number) when you change it it assigns a completely new variable to b and works ... but mutable datatypes wont work like this

Body:
lists are mutable ... both a and b point to the same list, so changing a will also change b

if you do not want this behaviour assign a copy of a to b

b = a[:]

if you had used an immutable datatype (like a string or number) when you change it it assigns a completely new variable to b and works ... but mutable datatypes wont work like this


问:
Get a particular cell value from HTML table using JavaScript
I want to get each cell value from an HTML table using JavaScript when pressing submit button.

How to get HTML table cell values?

答:
Here is perhaps the simplest way to obtain the value of a single cell.

```<code>document.querySelector("#table").children[0].children[r].children[c].innerText
</code>```

where r is the row index and c is the column index

Therefore, to obtain all cell data and put it in a multi-dimensional array:

```<code>var tableData = [];
Array.from(document.querySelector("#table").children[0].children).forEach(function(tr){tableData.push(Array.from(tr.children).map(cell => cell.innerText))});
var cell = tableData[1][2];//2nd row, 3rd column
</code>```

To access a specific cell's data in this multi-dimensional array, use the standard syntax: array[rowIndex][columnIndex].

Body:
Here is perhaps the simplest way to obtain the value of a single cell.

document.querySelector("#table").children[0].children[r].children[c].innerText

where r is the row index and c is the column index

Therefore, to obtain all cell data and put it in a multi-dimensional array:

var tableData = [];
Array.from(document.querySelector("#table").children[0].children).forEach(function(tr){tableData.push(Array.from(tr.children).map(cell => cell.innerText))});
var cell = tableData[1][2];//2nd row, 3rd column

To access a specific cell's data in this multi-dimensional array, use the standard syntax: array[rowIndex][columnIndex].


问:
sites_query = connection.execute("SELECT domain FROM django_site") psycopg2 has no attribute execute
When I try to start gunicorn, I am getting this error:

File "/home/django-project/projectfolder/settings.py", line 270, in
      ALLOWED_HOSTS = get_allowed_hosts(DATABASES['default'])
    File "/home/django-project/projectfolder/allowed_hosts.py", line 16, in get_allowed_hosts
      sites_query = connection.execute("SELECT domain FROM django_site")
  AttributeError: 'psycopg2.extensions.connection' object has no attribute 'execute

```<code>from .settings import *

DEBUG = False

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'projectname_settings',
        'USER': '******',
        'PASSWORD': '******',
        'HOST': 'localhost',
        'PORT': '',
    }
}

ALLOWED_HOSTS = [
    "mydomain.com",
] + get_allowed_hosts(DATABASES['default'])
</code>```

Allowed_hosts.py

```<code>def get_allowed_hosts(db_params):
    connection = None

    if db_params['ENGINE'] == 'django.db.backends.postgresql_psycopg2':
        import psycopg2
        connection = psycopg2.connect(user=db_params['USER'],
                                      password=db_params['PASSWORD'],
                                      host=db_params['HOST'],
                                      port=db_params['PORT'],
                                      database=db_params['NAME'])
    elif db_params['ENGINE'] == 'django.db.backends.sqlite3':
        import sqlite3
        connection = sqlite3.connect(db_params['NAME'])

    if connection is not None:
        sites_query = connection.execute("SELECT domain FROM django_site")
        sites_result = sites_query.fetchall()
        sites = ["." + site[0] for site in sites_result]
        print("Allowed hosts")
        print(sites)
        return sites
</code>```

答:
You sould use cursor object to execute query:

```<code>cursor = connection.cursor()
sites_query = cursor.execute("SELECT domain FROM django_site")
sites_result = cursor.fetchall()
</code>```

Don't forget to close connection after get data:

```<code>cursor.close()
connection.close()
</code>```

Body:
When I try to start gunicorn, I am getting this error:

File "/home/django-project/projectfolder/settings.py", line 270, in
      ALLOWED_HOSTS = get_allowed_hosts(DATABASES['default'])
    File "/home/django-project/projectfolder/allowed_hosts.py", line 16, in get_allowed_hosts
      sites_query = connection.execute("SELECT domain FROM django_site")
  AttributeError: 'psycopg2.extensions.connection' object has no attribute 'execute

from .settings import *

DEBUG = False

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'projectname_settings',
        'USER': '******',
        'PASSWORD': '******',
        'HOST': 'localhost',
        'PORT': '',
    }
}

ALLOWED_HOSTS = [
    "mydomain.com",
] + get_allowed_hosts(DATABASES['default'])

Allowed_hosts.py

def get_allowed_hosts(db_params):
    connection = None

    if db_params['ENGINE'] == 'django.db.backends.postgresql_psycopg2':
        import psycopg2
        connection = psycopg2.connect(user=db_params['USER'],
                                      password=db_params['PASSWORD'],
                                      host=db_params['HOST'],
                                      port=db_params['PORT'],
                                      database=db_params['NAME'])
    elif db_params['ENGINE'] == 'django.db.backends.sqlite3':
        import sqlite3
        connection = sqlite3.connect(db_params['NAME'])

    if connection is not None:
        sites_query = connection.execute("SELECT domain FROM django_site")
        sites_result = sites_query.fetchall()
        sites = ["." + site[0] for site in sites_result]
        print("Allowed hosts")
        print(sites)
        return sites

Body:
You sould use cursor object to execute query:

cursor = connection.cursor()
sites_query = cursor.execute("SELECT domain FROM django_site")
sites_result = cursor.fetchall()

Don't forget to close connection after get data:

cursor.close()
connection.close()


问:
invalid resource in a windows cuda project
I've ported a cuda project from linux to windows (basically just added few defines and typedefs in the header file). I'm using visual studio 2008, and the cuda runtime api custom build rules from the SDK. The code is c, not c++ (and I'm compiling /TC not /TP)

I'm having scope issues that I didn't have in linux. Global variables in my header file aren't shared between the .c files and .cu files.

I've created a simplified project, and here is all of the code:

main.h:

```<code>#ifndef MAIN_H
#define MAIN_H

#include <stdio.h>
#include <cuda.h>
#include <cuda_runtime.h>

cudaEvent_t cudaEventStart;

#if defined __cplusplus
extern "C" void func(void);
#else
extern void func(void);
#endif

#endif
</code>```

main.c:

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

int main(void)
{
    int iDevice = 0;

    cudaSetDevice(iDevice);
    cudaFree(0);
    cudaGetDevice(&iDevice);
    printf("device: %d\n", iDevice);

    cudaEventCreate(&cudaEventStart);
    printf("create event: %d\n", (int) cudaEventStart);

    func();

    cudaEventDestroy(cudaEventStart);
    printf("destroy event: %d\n", (int) cudaEventStart);

    return cudaThreadExit();
}
</code>```

kernel.cu:

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

void func()
{
    printf("event in cu: %d\n", (int) cudaEventStart);
}
</code>```

output:

```<code>device: 0
create event: 44199920
event in cu: 0
event destroy: 441999920
</code>```

Any ideas about what I am doing wrong here? How do I need to change my setup so that it works in visual studio? Ideally, I'd like a setup that works multi-platform.

CUDA 3.2, GTX 480, 64-bit Win7, 263.06 general

答:
I modified my simplified example (with success) by including the .cu file in the header and removing the forward declarations of the .cu file function.

main.h:

```<code>#include <stdio.h>
#include <cuda.h>
#include <cuda_runtime.h>

#include "kernel.cu"

cudaEvent_t cudaEventStart;
</code>```

main.c:

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

int main(void)
{
    int iDevice = 0;

    cudaSetDevice(iDevice);
    cudaFree(0);
    cudaGetDevice(&iDevice);
    printf("device: %d\n", iDevice);

    cudaEventCreate(&cudaEventStart);
    printf("create event: %d\n", (int) cudaEventStart);

    func();

    cudaEventDestroy(cudaEventStart);
    printf("destroy event: %d\n", (int) cudaEventStart);

    return cudaThreadExit();
}
</code>```

kernel.cu:

```<code>#ifndef KERNEL_CU
#define KERNEL_CU

#include "main.h"

void func(void);

void func()
{
    printf("event in cu: %d\n", (int) cudaEventStart);
}

#endif
</code>```

output:

```<code>device: 0
create event: 42784024
event in cu: 42784024
event destroy: 42784024
</code>```

About to see if it works in my real project, and whether the solution is portable back to linux.

Body:
I've ported a cuda project from linux to windows (basically just added few defines and typedefs in the header file). I'm using visual studio 2008, and the cuda runtime api custom build rules from the SDK. The code is c, not c++ (and I'm compiling /TC not /TP)

I'm having scope issues that I didn't have in linux. Global variables in my header file aren't shared between the .c files and .cu files.

I've created a simplified project, and here is all of the code:

main.h:

#ifndef MAIN_H
#define MAIN_H

#include <stdio.h>
#include <cuda.h>
#include <cuda_runtime.h>

cudaEvent_t cudaEventStart;

#if defined __cplusplus
extern "C" void func(void);
#else
extern void func(void);
#endif

#endif

main.c:

#include "main.h"

int main(void)
{
    int iDevice = 0;

    cudaSetDevice(iDevice);
    cudaFree(0);
    cudaGetDevice(&iDevice);
    printf("device: %d\n", iDevice);

    cudaEventCreate(&cudaEventStart);
    printf("create event: %d\n", (int) cudaEventStart);

    func();

    cudaEventDestroy(cudaEventStart);
    printf("destroy event: %d\n", (int) cudaEventStart);

    return cudaThreadExit();
}

kernel.cu:

#include "main.h"

void func()
{
    printf("event in cu: %d\n", (int) cudaEventStart);
}

output:

device: 0
create event: 44199920
event in cu: 0
event destroy: 441999920

Any ideas about what I am doing wrong here? How do I need to change my setup so that it works in visual studio? Ideally, I'd like a setup that works multi-platform.

CUDA 3.2, GTX 480, 64-bit Win7, 263.06 general

Body:
I modified my simplified example (with success) by including the .cu file in the header and removing the forward declarations of the .cu file function.

main.h:

#include <stdio.h>
#include <cuda.h>
#include <cuda_runtime.h>

#include "kernel.cu"

cudaEvent_t cudaEventStart;

main.c:

#include "main.h"

int main(void)
{
    int iDevice = 0;

    cudaSetDevice(iDevice);
    cudaFree(0);
    cudaGetDevice(&iDevice);
    printf("device: %d\n", iDevice);

    cudaEventCreate(&cudaEventStart);
    printf("create event: %d\n", (int) cudaEventStart);

    func();

    cudaEventDestroy(cudaEventStart);
    printf("destroy event: %d\n", (int) cudaEventStart);

    return cudaThreadExit();
}

kernel.cu:

#ifndef KERNEL_CU
#define KERNEL_CU

#include "main.h"

void func(void);

void func()
{
    printf("event in cu: %d\n", (int) cudaEventStart);
}

#endif

output:

device: 0
create event: 42784024
event in cu: 42784024
event destroy: 42784024

About to see if it works in my real project, and whether the solution is portable back to linux.


问:
Sustainsys SAML2 Sample for ASP.NET Core WebAPI without Identity
Does anyone have a working sample for Sustainsys Saml2 library for ASP.NET Core WebAPI only project (no Mvc) and what's more important without ASP Identity? The sample provided on github strongly relies on MVC and SignInManager which I do not need nor want to use.

I added Saml2 authentication and at first it worked fine with my IdP (I also checked the StubIdP provided by Sustainsys) for first few steps so:

IdP metadata get properly loaded

My API properly redirects to sign-in page

Sign-in page redirects to /Saml2/Acs page, and I see in the logs that it parses the result successfully

However I don't know how to move forward from there and extract user login and additional claims (my IdP provided also an e-mail, and it is included in SAML response which I confirmed in the logs).

Following some samples found on the web and modyfing a little bit the MVC Sample from GitHub I did the following:

In Startup.cs:

...
.AddSaml2(Saml2Defaults.Scheme,
                       options =>
                       {
                           options.SPOptions.EntityId = new EntityId("...");
                           options.SPOptions.ServiceCertificates.Add(...));
                           options.SPOptions.Logger = new SerilogSaml2Adapter();
                           options.SPOptions.ReturnUrl = new Uri(Culture.Invariant($"https://localhost:44364/Account/Callback?returnUrl=%2F"));

                           var idp =
                               new IdentityProvider(new EntityId("..."), options.SPOptions)
                               {
                                   LoadMetadata = true,
                                   AllowUnsolicitedAuthnResponse = true, // At first /Saml2/Acs page throwed an exception that response was unsolicited so I set it to true
                                   MetadataLocation = "...",
                                   SingleSignOnServiceUrl = new Uri("...") // I need to set it explicitly because my IdP returns different url in the metadata
                               };
                           options.IdentityProviders.Add(idp);
                       });
```

<p>In AccountContoller.cs (I tried to follow a somewhat similar situation described at how to implement google login in .net core without an entityframework provider):
</p>

```[Route("[controller]")]
[ApiController]
public class AccountController : ControllerBase
{
    private readonly ILog _log;

    public AccountController(ILog log)
    {
        _log = log;
    }

    [HttpGet("Login")]
    [AllowAnonymous]
    public IActionResult Login(string returnUrl)
    {
        return new ChallengeResult(
            Saml2Defaults.Scheme,
            new AuthenticationProperties
            {
                // It looks like this parameter is ignored, so I set ReturnUrl in Startup.cs
                RedirectUri = Url.Action(nameof(LoginCallback), new { returnUrl })
            });
    }

    [HttpGet("Callback")]
    [AllowAnonymous]
    public async Task<IActionResult> LoginCallback(string returnUrl)
    {

        var authenticateResult = await HttpContext.AuthenticateAsync(Constants.Auth.Schema.External);

        _log.Information("Authenticate result: {@authenticateResult}", authenticateResult);

// I get false here and no information on claims etc.
        if (!authenticateResult.Succeeded)
        {
            return Unauthorized();
        }

// HttpContext.User does not contain any data either

// code below is not executed
        var claimsIdentity = new ClaimsIdentity(Constants.Auth.Schema.Application);
claimsIdentity.AddClaim(authenticateResult.Principal.FindFirst(ClaimTypes.NameIdentifier));

        _log.Information("Logged in user with following claims: {@Claims}", authenticateResult.Principal.Claims);

        await HttpContext.SignInAsync(Constants.Auth.Schema.Application, new ClaimsPrincipal(claimsIdentity));

        return LocalRedirect(returnUrl);
    }
```

TLDR: Configuration for SAML in my ASP.NET Core WebApi project looks fine, and I get success response with proper claims which I checked in the logs. I do not know how to extract this data (either return url is wrong or my callback method should work differently). Also, it is puzzling why successfuly redirect from SSO Sign-In page is treated as "unsolicited", maybe this is the problem?

Thanks for any assistance

答:
For anyone who still needs assistance on this issue, I pushed a full working example to github which uses a .Net Core WebAPI for backend and an Angular client using the WebAPI. you can find the example from here:

https://github.com/hmacat/Saml2WebAPIAndAngularSpaExample

Body:
Does anyone have a working sample for Sustainsys Saml2 library for ASP.NET Core WebAPI only project (no Mvc) and what's more important without ASP Identity? The sample provided on github strongly relies on MVC and SignInManager which I do not need nor want to use.

I added Saml2 authentication and at first it worked fine with my IdP (I also checked the StubIdP provided by Sustainsys) for first few steps so:

IdP metadata get properly loaded

My API properly redirects to sign-in page

Sign-in page redirects to /Saml2/Acs page, and I see in the logs that it parses the result successfully

However I don't know how to move forward from there and extract user login and additional claims (my IdP provided also an e-mail, and it is included in SAML response which I confirmed in the logs).

Following some samples found on the web and modyfing a little bit the MVC Sample from GitHub I did the following:

In Startup.cs:

...
.AddSaml2(Saml2Defaults.Scheme,
                       options =>
                       {
                           options.SPOptions.EntityId = new EntityId("...");
                           options.SPOptions.ServiceCertificates.Add(...));
                           options.SPOptions.Logger = new SerilogSaml2Adapter();
                           options.SPOptions.ReturnUrl = new Uri(Culture.Invariant($"https://localhost:44364/Account/Callback?returnUrl=%2F"));

                           var idp =
                               new IdentityProvider(new EntityId("..."), options.SPOptions)
                               {
                                   LoadMetadata = true,
                                   AllowUnsolicitedAuthnResponse = true, // At first /Saml2/Acs page throwed an exception that response was unsolicited so I set it to true
                                   MetadataLocation = "...",
                                   SingleSignOnServiceUrl = new Uri("...") // I need to set it explicitly because my IdP returns different url in the metadata
                               };
                           options.IdentityProviders.Add(idp);
                       });

In AccountContoller.cs (I tried to follow a somewhat similar situation described at how to implement google login in .net core without an entityframework provider):

[Route("[controller]")]
[ApiController]
public class AccountController : ControllerBase
{
    private readonly ILog _log;

    public AccountController(ILog log)
    {
        _log = log;
    }

    [HttpGet("Login")]
    [AllowAnonymous]
    public IActionResult Login(string returnUrl)
    {
        return new ChallengeResult(
            Saml2Defaults.Scheme,
            new AuthenticationProperties
            {
                // It looks like this parameter is ignored, so I set ReturnUrl in Startup.cs
                RedirectUri = Url.Action(nameof(LoginCallback), new { returnUrl })
            });
    }

    [HttpGet("Callback")]
    [AllowAnonymous]
    public async Task<IActionResult> LoginCallback(string returnUrl)
    {

        var authenticateResult = await HttpContext.AuthenticateAsync(Constants.Auth.Schema.External);

        _log.Information("Authenticate result: {@authenticateResult}", authenticateResult);

// I get false here and no information on claims etc.
        if (!authenticateResult.Succeeded)
        {
            return Unauthorized();
        }

// HttpContext.User does not contain any data either

// code below is not executed
        var claimsIdentity = new ClaimsIdentity(Constants.Auth.Schema.Application);
claimsIdentity.AddClaim(authenticateResult.Principal.FindFirst(ClaimTypes.NameIdentifier));

        _log.Information("Logged in user with following claims: {@Claims}", authenticateResult.Principal.Claims);

        await HttpContext.SignInAsync(Constants.Auth.Schema.Application, new ClaimsPrincipal(claimsIdentity));

        return LocalRedirect(returnUrl);
    }

TLDR: Configuration for SAML in my ASP.NET Core WebApi project looks fine, and I get success response with proper claims which I checked in the logs. I do not know how to extract this data (either return url is wrong or my callback method should work differently). Also, it is puzzling why successfuly redirect from SSO Sign-In page is treated as "unsolicited", maybe this is the problem?

Thanks for any assistance


问:
What is inconsistent use of tabs and spaces in indentation?
I am making a python program that reads an image and creates a level according to every pixel's color.
Although , when i run it, I'm getting this error "inconsistent use of tabs and spaces in indentation" at line 139. It's quite frustrating because I can't figure out why it is wrong.

I've already tried changing the indentation size to 2, 4 and 8 but it fixed nothing

Here's my code

```<code>#Libraries
import Image
from os import system
from random import randint

#Object class
class object:
    def __init__(self, x , y, facing, image, type):
        self.x = x
        self.y = y
        self.facing = facing
        self.image = image
        self.type = type

#Game variables
entities = []
score = 0
pixels = []

#Read image
pic = Image.open("level1.png", mode="r")

#Get image size
width = pic.size[0]
height = pic.size[1]
picload = pic.load()

#Create pixel array
for y in range(height):
  for x in range(width):
    pixels.append(picload[x, y])

#Read all pixels
x = 0
y = 0

for i in range(len(pixels)):

  #Change x y coordinates
  x += 1
  if x % height == 0:
    x = 0
    y += 1

  pixel = pixels[i]

  r = pixel[0]
  g = pixel[1]
  b = pixel[2]
  a = pixel[3]

  #Create object based on pixel info
  #If pixel is black
  if r >= 200 and g >= 200 and b >= 200: entities.append(x, y, "r", "■", "wall")
  #If pixel is red
  elif r >= 200 and g <= 50 and b <= 50: entities.append(x, y, "r", "•", "food")
  #if pixel is blue
  elif r <= 50 and g <= 50 and b >= 200: entities.append(x, y, "r", "☺", "player")

#Running the level
while True:

    #output
  print("Output:", output)
  output = ""
  print("Score:", score)

  for y in range(height):
      print("")
      for x in range(width):

          drawed = False
          for i in range(len(entities)):
              entity = entities[i]
              if entity.x == x and entity.y == y and drawed == False:
                  drawed = True
                  print(entity.image, end = "")

          if not drawed: print(".", end="")

    #input

  dir = input("\n\n####################\nWASD: ").lower()

    #processing

    #movement
  for i in range(len(entities)):
      entity = entities[i]
      ii = i
      if entity.type == "player":

        if dir == "w":
            entity.y -= 1
            entity.facing = "u"

        elif dir == "s":
            entity.y += 1
            entity.facing = "d"

        elif dir == "a":
            entity.x -= 1
            entity.facing = "l"

        elif dir == "d":
            entity.x += 1
            entity.facing = "r"

        for h in range(len(entities)):
            centity = entities[h]
            if entity.x == centity.x and entity.y == centity.y and not ii == h:

                if dir == "w":entity.y += 1

                elif dir == "s":entity.y -= 1

                elif dir == "a":entity.x += 1

                elif dir == "d": entity.x -=1

    #colisions
  for h in range(len(entities)):
    entity = entities[h]
    f = entity.facing

    cx = entity.x
    cy = entity.y

    if f == "r": cx += 1
    elif f == "l": cx -= 1
    elif f == "u": cy -= 1
    elif f == "d": cy += 1

    for i in range(len(entities)):
        centity = entities[i]
        if centity.x == cx and centity.y == cy:
        print("a")

  #Clear terminal
    system("clear")
</code>```

答:
You have to keep indentation same through out the code

#Object class
class object:
    def __init__(self, x , y, facing, image, type):
        self.x = x
        self.y = y
        self.facing = facing
        self.image = image
        self.type = type
```

<p>Here indentation is 4 spaces, but <br></p>

<pre class="lang-py prettyprint-override"><code>#Create pixel array
for y in range(height):
  for x in range(width):
    pixels.append(picload[x, y])
</code>```

here you have 2 space as indentation , this was the error.
You should just use tab to keep indentation same everywhere.

Body:
I am making a python program that reads an image and creates a level according to every pixel's color.
Although , when i run it, I'm getting this error "inconsistent use of tabs and spaces in indentation" at line 139. It's quite frustrating because I can't figure out why it is wrong.

I've already tried changing the indentation size to 2, 4 and 8 but it fixed nothing

Here's my code

#Libraries
import Image
from os import system
from random import randint

#Object class
class object:
    def __init__(self, x , y, facing, image, type):
        self.x = x
        self.y = y
        self.facing = facing
        self.image = image
        self.type = type

#Game variables
entities = []
score = 0
pixels = []

#Read image
pic = Image.open("level1.png", mode="r")

#Get image size
width = pic.size[0]
height = pic.size[1]
picload = pic.load()

#Create pixel array
for y in range(height):
  for x in range(width):
    pixels.append(picload[x, y])

#Read all pixels
x = 0
y = 0

for i in range(len(pixels)):

  #Change x y coordinates
  x += 1
  if x % height == 0:
    x = 0
    y += 1

  pixel = pixels[i]

  r = pixel[0]
  g = pixel[1]
  b = pixel[2]
  a = pixel[3]

  #Create object based on pixel info
  #If pixel is black
  if r >= 200 and g >= 200 and b >= 200: entities.append(x, y, "r", "■", "wall")
  #If pixel is red
  elif r >= 200 and g <= 50 and b <= 50: entities.append(x, y, "r", "•", "food")
  #if pixel is blue
  elif r <= 50 and g <= 50 and b >= 200: entities.append(x, y, "r", "☺", "player")

#Running the level
while True:

    #output
  print("Output:", output)
  output = ""
  print("Score:", score)

  for y in range(height):
      print("")
      for x in range(width):

          drawed = False
          for i in range(len(entities)):
              entity = entities[i]
              if entity.x == x and entity.y == y and drawed == False:
                  drawed = True
                  print(entity.image, end = "")

          if not drawed: print(".", end="")

    #input

  dir = input("\n\n####################\nWASD: ").lower()

    #processing

    #movement
  for i in range(len(entities)):
      entity = entities[i]
      ii = i
      if entity.type == "player":

        if dir == "w":
            entity.y -= 1
            entity.facing = "u"

        elif dir == "s":
            entity.y += 1
            entity.facing = "d"

        elif dir == "a":
            entity.x -= 1
            entity.facing = "l"

        elif dir == "d":
            entity.x += 1
            entity.facing = "r"

        for h in range(len(entities)):
            centity = entities[h]
            if entity.x == centity.x and entity.y == centity.y and not ii == h:

                if dir == "w":entity.y += 1

                elif dir == "s":entity.y -= 1

                elif dir == "a":entity.x += 1

                elif dir == "d": entity.x -=1

    #colisions
  for h in range(len(entities)):
    entity = entities[h]
    f = entity.facing

    cx = entity.x
    cy = entity.y

    if f == "r": cx += 1
    elif f == "l": cx -= 1
    elif f == "u": cy -= 1
    elif f == "d": cy += 1

    for i in range(len(entities)):
        centity = entities[i]
        if centity.x == cx and centity.y == cy:
        print("a")

  #Clear terminal
    system("clear")

Body:
You have to keep indentation same through out the code

#Object class
class object:
    def __init__(self, x , y, facing, image, type):
        self.x = x
        self.y = y
        self.facing = facing
        self.image = image
        self.type = type

Here indentation is 4 spaces, but

#Create pixel array
for y in range(height):
  for x in range(width):
    pixels.append(picload[x, y])

here you have 2 space as indentation , this was the error.
You should just use tab to keep indentation same everywhere.


答:
In python (as in many languages, with the notable exception of C/C++), names are references to values. When you write a = b, you make a refer to the same value as b, you don't copy its contents.

Use b = list(a) to create a copy (or see deepcopy for more complex objects)

Title: Python List assignment seems like it gets carried away

Body:
a=[1] # here is a comment to the right
print("as expected, a=", a)

b=a
print("as expected, b=", b)

a[0]=2

print("as expected, now a=", a)

print("NOT EXPECTED TO CHANGE now b=", b)


问:
how to add a dot (.) inside a field name?
When I run this command :

```<code>db.runCommand(

  {
    aggregate:"myColl",
    pipeline:[
      {
        $group:{
          _id:{os_name:"$os_name",os_version:"$os_version"},
          "events.login":{$sum:"$events.login"},
          count:{$sum:NumberInt(1)}}
      }
    ],
    cursor:{}
  }

 )
</code>```

I receive the error:

The field name 'events.login' cannot contain '.'

How can i do to keep the '.' in the returned field name (ie: events.login)

答:
It's not quiet clear what you're trying to do, So look at these :

Error :

The field name 'events.login' cannot contain '.'

It's because as in $group stage when it creates a new field on each document for a given name, You'll not be able to create it like this : "events.login" means cannot create a sub-doc it has to be an object to a top level field events basically you can not use . notation, So to make it work you need to have one more stage like this :

```<code>db.collection.aggregate([{
    $group: {
        _id: { os_name: "$os_name", os_version: "$os_version" },
        "events": { $sum: "$events.login" },
        count: { $sum: NumberInt(1) }
    }
}, { $addFields: { 'events.login': '$events' } }])
</code>```

Test : MongoDB-Playground

If in a case you need to update login field inside events field & to retain all other fields inside events, try below query which would get last document in iteration of each _id (this will last document inserted to DB on that _id criteria) & append login to it :

```<code>db.collection.aggregate([{
    $group: {
        _id: { os_name: "$os_name", os_version: "$os_version" },
        "login": { $sum: "$events.login" }, 'events': { $last: '$events' },
        count: { $sum: NumberInt(1) }
    }
}, { $addFields: { 'events.login': '$login' } }, { $project: { login: 0 } }])
</code>```

Test : MongoDB-Playground

Body:
When I run this command :

db.runCommand(

  {
    aggregate:"myColl",
    pipeline:[
      {
        $group:{
          _id:{os_name:"$os_name",os_version:"$os_version"},
          "events.login":{$sum:"$events.login"},
          count:{$sum:NumberInt(1)}}
      }
    ],
    cursor:{}
  }

 )

I receive the error:

The field name 'events.login' cannot contain '.'

How can i do to keep the '.' in the returned field name (ie: events.login)

Body:
It's not quiet clear what you're trying to do, So look at these :

Error :

The field name 'events.login' cannot contain '.'

It's because as in $group stage when it creates a new field on each document for a given name, You'll not be able to create it like this : "events.login" means cannot create a sub-doc it has to be an object to a top level field events basically you can not use . notation, So to make it work you need to have one more stage like this :

db.collection.aggregate([{
    $group: {
        _id: { os_name: "$os_name", os_version: "$os_version" },
        "events": { $sum: "$events.login" },
        count: { $sum: NumberInt(1) }
    }
}, { $addFields: { 'events.login': '$events' } }])

Test : MongoDB-Playground

If in a case you need to update login field inside events field & to retain all other fields inside events, try below query which would get last document in iteration of each _id (this will last document inserted to DB on that _id criteria) & append login to it :

db.collection.aggregate([{
    $group: {
        _id: { os_name: "$os_name", os_version: "$os_version" },
        "login": { $sum: "$events.login" }, 'events': { $last: '$events' },
        count: { $sum: NumberInt(1) }
    }
}, { $addFields: { 'events.login': '$login' } }, { $project: { login: 0 } }])

Test : MongoDB-Playground


问:
waitForNavigation hanging for no reason
I try to click the next page button to iterate different pages, but after click, the script hangs there forever, code as below.

Why waitForNavigation never finishes?

```<code>async function main() {
  const br = await pptr.launch({headless: false, defaultViewport: null});
  const page = await br.newPage();

  await page.goto(
    'https://www.escentual.com/catalogsearch/result/?q=face',
    {waitUntil: 'networkidle2'}
  );

  for (var i=0; i<10; ++i) {   // click next-page button 10 times,
    await Promise.all([
      page.waitForNavigation({waitUntil: 'load', timeout: 100000}),
      page.click('#adj-nav-container > div.category-products > div.toolbar > div > div.amount > div > ol > li.next > a'),  // next-page css
    ]);
    console.log(`waited, url=${page.url()}`);
  }
  await br.close();
}

main();
</code>```

答:
There is a overlay on top of the element you're trying to click. You should either close that overlay or just use the HTMLElement.click:

page.$eval('#adj-nav-container > div.category-products > div.toolbar > div > div.amount > div > ol > li.next > a', el => el.click())
```

<p>Alternatively, you can just change the page number in the website's URL:</p>

```https://www.escentual.com/catalogsearch/result/index/?p=1&q=face
https://www.escentual.com/catalogsearch/result/index/?p=2&q=face
...
```

<hr>

<h3>Detecting overlay</h3>

<p>Here is one way of detecting whether the element is behind an overlay. <code>document.elementFromPoint</code> gets a coordinate and returns the topmost element of that coordinate. We get the selected element's coordinate with <code>boundingBox()</code> method, and then compare it with the top most element of that coordinate. If they're the same, it means the element is not behind an overlay or another element. </p>

<p>Example:</p>

<pre class="lang-js prettyprint-override"><code>let targetElement = await page.$('#adj-nav-container > div.category-products > div.toolbar > div > div.amount > div > ol > li.next > a');
let {x, y} = await targetElement.boundingBox();

let isOnTop = await page.evaluate((x,y, selectedElement) => {
    let topElement = document.elementFromPoint(x,y);
    return topElement === selectedElement;
}, x, y, targetElement);

if (isOnTop)
    console.log("Element is not behind overlay");
</code>```

Title: waitForNavigation hanging for no reason

Body:
I try to click the next page button to iterate different pages, but after click, the script hangs there forever, code as below.

Why waitForNavigation never finishes?

async function main() {
  const br = await pptr.launch({headless: false, defaultViewport: null});
  const page = await br.newPage();

  await page.goto(
    'https://www.escentual.com/catalogsearch/result/?q=face',
    {waitUntil: 'networkidle2'}
  );

  for (var i=0; i<10; ++i) {   // click next-page button 10 times,
    await Promise.all([
      page.waitForNavigation({waitUntil: 'load', timeout: 100000}),
      page.click('#adj-nav-container > div.category-products > div.toolbar > div > div.amount > div > ol > li.next > a'),  // next-page css
    ]);
    console.log(`waited, url=${page.url()}`);
  }
  await br.close();
}

main();

Body:
There is a overlay on top of the element you're trying to click. You should either close that overlay or just use the HTMLElement.click:

page.$eval('#adj-nav-container > div.category-products > div.toolbar > div > div.amount > div > ol > li.next > a', el => el.click())

Alternatively, you can just change the page number in the website's URL:

https://www.escentual.com/catalogsearch/result/index/?p=1&q=face
https://www.escentual.com/catalogsearch/result/index/?p=2&q=face
...

Detecting overlay

Here is one way of detecting whether the element is behind an overlay. document.elementFromPoint gets a coordinate and returns the topmost element of that coordinate. We get the selected element's coordinate with boundingBox() method, and then compare it with the top most element of that coordinate. If they're the same, it means the element is not behind an overlay or another element.

Example:

let targetElement = await page.$('#adj-nav-container > div.category-products > div.toolbar > div > div.amount > div > ol > li.next > a');
let {x, y} = await targetElement.boundingBox();

let isOnTop = await page.evaluate((x,y, selectedElement) => {
    let topElement = document.elementFromPoint(x,y);
    return topElement === selectedElement;
}, x, y, targetElement);

if (isOnTop)
    console.log("Element is not behind overlay");


问:
How do I correctly define a function having numpy arrays as argument and return type?
As I see it, there are two options.(Here numpy is imported as np)

1. Using a lambda expression

This can be used when we are dealing with a simple function. Say I want to implement the function f:(x,y) = (x^2, x+y). Then I would expect some like this to work:

f = lambda x,y : x**2, x + y

f = lambda x,y : (x**2, x + y)

when i call print(f(np.array([[1],[3]],float))) or print(f(np.array([1,3],float))). But I cannot get any variant of these lambda expressions to work.

2. Defining a "proper" function

This however, does work:

```<code>def f(vec):
    return np.array([vec[0] ** 2, vec[0] + vec[1]])
</code>```

But is the syntax optimal? And how would I do it if i don't want the above "proper" function to be vectorized. In total, how do i define a numpy-array valued function taking numpy-array values?

答:
It really doesn't matter whether you use lambda or def, or do the calculation with locally defined variables.  If using functions, the number of input arguments has to match the definition.

But let's demonstrate with simple interactive examples

Define two variables:

```<code>In [121]: x, y = 1,3
In [122]: x**2, x+y
Out[122]: (1, 4)             # returns a tuple
</code>```

Define a list:

```<code>In [125]: vec = [1,3]
In [126]: vec[0]**2, vec[0]+vec[1]
Out[126]: (1, 4)             # same tuple
</code>```

or an array:

```<code>In [127]: arr = np.array([1,3])
</code>```

[126] would work with this too, but indexing an array is slower.

Arrays are best when we do things with the whole array, not just with elements.  For example we can square all terms of the array, or sum them.

```<code>In [128]: arr**2, arr.sum()
Out[128]: (array([1, 9]), 4)
</code>```

These calculations would work with an array of any size, not just a shape (2,).

Any of the above tuples could be converted to array:

```<code>In [133]: np.array([x**2, x+y])
Out[133]: array([1, 4])
</code>```

Body:
As I see it, there are two options.(Here numpy is imported as np)

1. Using a lambda expression

This can be used when we are dealing with a simple function. Say I want to implement the function f:(x,y) = (x^2, x+y). Then I would expect some like this to work:

f = lambda x,y : x**2, x + y

f = lambda x,y : (x**2, x + y)

when i call print(f(np.array([[1],[3]],float))) or print(f(np.array([1,3],float))). But I cannot get any variant of these lambda expressions to work.

2. Defining a "proper" function

This however, does work:

def f(vec):
    return np.array([vec[0] ** 2, vec[0] + vec[1]])

But is the syntax optimal? And how would I do it if i don't want the above "proper" function to be vectorized. In total, how do i define a numpy-array valued function taking numpy-array values?

Body:
It really doesn't matter whether you use lambda or def, or do the calculation with locally defined variables.  If using functions, the number of input arguments has to match the definition.

But let's demonstrate with simple interactive examples

Define two variables:

In [121]: x, y = 1,3
In [122]: x**2, x+y
Out[122]: (1, 4)             # returns a tuple

Define a list:

In [125]: vec = [1,3]
In [126]: vec[0]**2, vec[0]+vec[1]
Out[126]: (1, 4)             # same tuple

or an array:

In [127]: arr = np.array([1,3])

[126] would work with this too, but indexing an array is slower.

Arrays are best when we do things with the whole array, not just with elements.  For example we can square all terms of the array, or sum them.

In [128]: arr**2, arr.sum()
Out[128]: (array([1, 9]), 4)

These calculations would work with an array of any size, not just a shape (2,).

Any of the above tuples could be converted to array:

In [133]: np.array([x**2, x+y])
Out[133]: array([1, 4])


问:
How to expand array values stored as properties in Kusto
I have a property bag (json object) that unfortunately has an array of objects by dynamically named properties, rather than an actual array. There are other properties in the bag as well. For example:

```<code>{
  "something": "whatever",
  "another": "doesn't matter",
  "thing1": "value1",
  "thing2": "value2",
  "thing3": "value3"
}
</code>```

Ultimately I'd like to have one row per thing:

```<code>value1
value2
value3
</code>```

I know I can use mv-expand to convert an array or property bag into multiple rows, but I'm not sure how to

Keep only the properties where key starts with "thing"

Discard the key, keeping only the value

In case it's important, the number of things per property bag varies greatly. Usually it's only one, but sometimes it's 10-20 and rarely it could be 100 or more.

答:
you could try using mv-apply for that:

```<code>datatable(d:dynamic)
[
    dynamic({"something":"whatever","another":"doesn'tmatter","thing1":"value1","thing2":"value2","thing3":"value3"}),
    dynamic({"somethingelse":"whatever2","another":"doesn'tmatter2","thing1":"value12","thing2":"value22","thing3":"value32"}),
]
| mv-apply d on (
    extend key = tostring(bag_keys(d)[0])
    | where key startswith "thing"
    | project value = d[key]
)
</code>```

which returns:

```<code>| value   |
|---------|
| value1  |
| value2  |
| value3  |
| value12 |
| value22 |
| value32 |
</code>```

Body:
I have a property bag (json object) that unfortunately has an array of objects by dynamically named properties, rather than an actual array. There are other properties in the bag as well. For example:

{
  "something": "whatever",
  "another": "doesn't matter",
  "thing1": "value1",
  "thing2": "value2",
  "thing3": "value3"
}

Ultimately I'd like to have one row per thing:

value1
value2
value3

I know I can use mv-expand to convert an array or property bag into multiple rows, but I'm not sure how to

Keep only the properties where key starts with "thing"

Discard the key, keeping only the value

In case it's important, the number of things per property bag varies greatly. Usually it's only one, but sometimes it's 10-20 and rarely it could be 100 or more.

Body:
you could try using mv-apply for that:

datatable(d:dynamic)
[
    dynamic({"something":"whatever","another":"doesn'tmatter","thing1":"value1","thing2":"value2","thing3":"value3"}),
    dynamic({"somethingelse":"whatever2","another":"doesn'tmatter2","thing1":"value12","thing2":"value22","thing3":"value32"}),
]
| mv-apply d on (
    extend key = tostring(bag_keys(d)[0])
    | where key startswith "thing"
    | project value = d[key]
)

which returns:

| value   |
|---------|
| value1  |
| value2  |
| value3  |
| value12 |
| value22 |
| value32 |


问:
Movie searching site using TMDb and axios npm
I'm trying to make a movie searching site using TMDb and axios npm. What am I doing wrong?
Search works fine, but I can't access the movies themselves.

$(document).ready(() => {
  $('#searchForm').on('submit', (e) => {
    let searchText = $('#searchText').val();
    getMovies(searchText);
    e.preventDefault();
  });
});

function getMovies(searchText) {
  axios.get('https://api.themoviedb.org/3/search/movie?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US&query=' + searchText)
    .then((response) => {
      console.log(response);
      let movies = response.data.Search;
      let output = '';
      $.each(movies, (index, movie) => {
        output += `

${movie.original_title}

              Movie Details

        `;
      });

      $('#movies').html(output);
    })
    .catch((err) => {
      console.log(err);
    });
}

function movieSelected(id) {
  sessionStorage.setItem('id', id);
  window.location = 'movie.html';
  return false;
}

function getMovie() {
  let id = sessionStorage.getItem('id');

  axios.get('https://api.themoviedb.org/3/movie/' + id + '?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US')
    .then((response) => {
      console.log(response);
      let movie = response.data;

      let output = `

${movie.Title}

Genre: ${movie.genres.Name}

Released: ${movie.release_date}

Rated: ${movie.vote_average}

Review: ${movie.overview}

Plot

            ${movie.Plot}

            View TMDb
            Go Back To Search

      `;

      $('#movie').html(output);
    })
    .catch((err) => {
      console.log(err);
    });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#movies img,
#movie img {
  width: 100%;
}

@media(min-width:960px) {
  #movies .col-md-3 .well {
    height: 390px;
  }
  #movies .col-md-3 img {
    height: 240px;
  }
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>MovieInfo</title>
  <link href="css/bootstrap.min.css" rel="stylesheet" />
  <link href="css/style.css" rel="stylesheet" />

        MovieInfo

Search For Any Movie

      <form id="searchForm">
        <input type="text" class="form-control" id="searchText" placeholder="Search Movies...">
      </form>

```

--More details, because I have more code:

Search works fine, but I can't access the movies themselves.
Search works fine, but I can't access the movies themselves.
Search works fine, but I can't access the movies themselves.
Search works fine, but I can't access the movies themselves.

答:
This will help you click here, Now it is working. There was very small bug, which I mentioned to you.

And also fixed the image not showing issue.

Body:
I'm trying to make a movie searching site using TMDb and axios npm. What am I doing wrong?
Search works fine, but I can't access the movies themselves.

$(document).ready(() => {
  $('#searchForm').on('submit', (e) => {
    let searchText = $('#searchText').val();
    getMovies(searchText);
    e.preventDefault();
  });
});

function getMovies(searchText) {
  axios.get('https://api.themoviedb.org/3/search/movie?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US&query=' + searchText)
    .then((response) => {
      console.log(response);
      let movies = response.data.Search;
      let output = '';
      $.each(movies, (index, movie) => {
        output += `

${movie.original_title}

              Movie Details

        `;
      });

      $('#movies').html(output);
    })
    .catch((err) => {
      console.log(err);
    });
}

function movieSelected(id) {
  sessionStorage.setItem('id', id);
  window.location = 'movie.html';
  return false;
}

function getMovie() {
  let id = sessionStorage.getItem('id');

  axios.get('https://api.themoviedb.org/3/movie/' + id + '?api_key=d80a54a0422d5fff6149c48741c8bece&language=en-US')
    .then((response) => {
      console.log(response);
      let movie = response.data;

      let output = `

${movie.Title}

Genre: ${movie.genres.Name}

Released: ${movie.release_date}

Rated: ${movie.vote_average}

Review: ${movie.overview}

Plot

            ${movie.Plot}

            View TMDb
            Go Back To Search

      `;

      $('#movie').html(output);
    })
    .catch((err) => {
      console.log(err);
    });
}

#movies img,
#movie img {
  width: 100%;
}

@media(min-width:960px) {
  #movies .col-md-3 .well {
    height: 390px;
  }
  #movies .col-md-3 img {
    height: 240px;
  }
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>MovieInfo</title>
  <link href="css/bootstrap.min.css" rel="stylesheet" />
  <link href="css/style.css" rel="stylesheet" />

        MovieInfo

Search For Any Movie

      <form id="searchForm">
        <input type="text" class="form-control" id="searchText" placeholder="Search Movies...">
      </form>

--More details, because I have more code:

Search works fine, but I can't access the movies themselves.
Search works fine, but I can't access the movies themselves.
Search works fine, but I can't access the movies themselves.
Search works fine, but I can't access the movies themselves.


问:
Overuse of try and except in python code when using regex
I think i am over using try and except in my code. It's pretty much everywhere, where i have regexp matching. If it does not find the regex, it throws an exception, so i use the try and except to capture this to prevent my code from crashing. Example of what i'm talking about.

```<code>try:
    Output = "John Bob Charlie"
    match = re.search(r'John', Output, re.M|re.I) #use try/except, to stop unmatch causing crash
except:
    print("Darn, no John")
</code>```

Is there a better way of doing this or is this normal?? I'm new to Python and coming from Perl, a simple

```<code>if match{
print('we have found John')
}
</code>```

Was all i needed.

Thanks in advance

答:
I would say use exception for the cases where there is an exception (something unknown or unexpected). For example, you are calling an external API to fetch some data and the API throws an exception.

In your case, you should just go with:

```<code>if not match:
    return ('Darn, no John')
# here you can do whatever you want to do with Output variable.
</code>```

Body:
I think i am over using try and except in my code. It's pretty much everywhere, where i have regexp matching. If it does not find the regex, it throws an exception, so i use the try and except to capture this to prevent my code from crashing. Example of what i'm talking about.

try:
    Output = "John Bob Charlie"
    match = re.search(r'John', Output, re.M|re.I) #use try/except, to stop unmatch causing crash
except:
    print("Darn, no John")

Is there a better way of doing this or is this normal?? I'm new to Python and coming from Perl, a simple

if match{
print('we have found John')
}

Was all i needed.

Thanks in advance

Body:
I would say use exception for the cases where there is an exception (something unknown or unexpected). For example, you are calling an external API to fetch some data and the API throws an exception.

In your case, you should just go with:

if not match:
    return ('Darn, no John')
# here you can do whatever you want to do with Output variable.


问:
css margin: auto issue in footer
My problem is to split the space inside my footer bar in 3 part (each with same width)

footer {
  width: 100%;
  /*breite: 100%*/
  padding: 0;
  margin: 0;
  background-color: darkcyan;
  /*Hintergrundfarbe*/
  margin-bottom: 0;
  bottom: 0;
}

.footer-items {
  width: 80%;
  margin: auto;
  display: flex;
  /*bringt alle Teile in eine Linie*/
  text-align: center;
  /*zentriert ganzen Text im footer*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="footer-items">

  <div class="company-items">
    <h3 class="company">Company</h3>
    <ul>
      <li>Text1</li>
      <li>Text2</li>
      <li>Text3</li>
    </ul>
  </div>

  <div class="social-items">
    <h3 class="social">Social</h3>
    <ul>
      <li><a>Twitter</a></li>
      <li><a>Instagram</a></li>
      <li><a>Reddit</a></li>
    </ul>
  </div>

  <div class="other-items">
    <h3 class="text">Text4</h3>
    <ul>
      <li><a>other1</a></li>
      <li><a>other2</a></li>
    </ul>
  </div>

</div></code>```

If I try to do sth like margin-left: 33% for my 3 items in footer this is not gonna work.

thanks for your help

答: Have you tried using display: grid like so. You can define 3 columns for each of the footer items and give it a width of 1fr or 1 fraction grid-template-columns:1fr 1fr 1fr;. You can also define a grid gap for instead of margin.

Title: css margin: auto issue in footer

Body:
My problem is to split the space inside my footer bar in 3 part (each with same width)

footer {
  width: 100%;
  /*breite: 100%*/
  padding: 0;
  margin: 0;
  background-color: darkcyan;
  /*Hintergrundfarbe*/
  margin-bottom: 0;
  bottom: 0;
}

.footer-items {
  width: 80%;
  margin: auto;
  display: flex;
  /*bringt alle Teile in eine Linie*/
  text-align: center;
  /*zentriert ganzen Text im footer*/
}

Company

Text1

Text2

Text3

Social

Twitter

Instagram

Reddit

Text4

other1

other2

If I try to do sth like margin-left: 33% for my 3 items in footer this is not gonna work.

thanks for your help


答:
This does not work, because re.search returns None if the expression is not found.

Instead of try-except use if:

```<code>Output = "John Bob Charlie"
match = re.search(r'John', Output, re.M|re.I)
if not match:
    print("Darn, no John")
</code>```

Title: Overuse of try and except in python code when using regex

Body:
This does not work, because re.search returns None if the expression is not found.

Instead of try-except use if:

Output = "John Bob Charlie"
match = re.search(r'John', Output, re.M|re.I)
if not match:
    print("Darn, no John")


问:
Colorbox shows under flash
I am using jQuery's colorbox to open up an iframe on a page. On the page there are two flash SWFs. When I click the button that opens the colorbox, those flash SWFs appear over the top of my colorbox div. I've checked the CSS properties of the colorbox, and the overlay has position:absolute and z-index:999. I have given the SWFs a z-index:0 property, but they still show over the top of the colorbox. This happens in Firefox, IE, and Chrome.

答:
For those using the iframe embed code from Youtube or Vimeo, you have to approach it differently. I used the events onOpen and onClosed to hide and show back the iframe. Here's an example:

```<code>$('.selector').colorbox({
    inline: true,
    href: '.step.'+target,
    rel: 'steps',
    onOpen: function(){
        $('iframe').css('visibility','hidden');
    },
    onClosed: function(){
    $('iframe').css('visibility','visible');
    },
    loop: false,
    opacity: 0.5
});
</code>```

I guess it also works if you want to apply it to your embed or object tag as a quick solution.

ContentLicense: CC BY-SA 2.5

Title: Colorbox shows under flash

Body:
For those using the iframe embed code from Youtube or Vimeo, you have to approach it differently. I used the events onOpen and onClosed to hide and show back the iframe. Here's an example:

$('.selector').colorbox({
    inline: true,
    href: '.step.'+target,
    rel: 'steps',
    onOpen: function(){
        $('iframe').css('visibility','hidden');
    },
    onClosed: function(){
    $('iframe').css('visibility','visible');
    },
    loop: false,
    opacity: 0.5
});

I guess it also works if you want to apply it to your embed or object tag as a quick solution.


问:
Count lines with integers in them using bash and wc -l
A utility on my Linux machine outputs a log to 'stdout'.
In each line, there is either a String or an Integer, it looks like the following:

```<code>[ERROR] resource busy, retrying
0989282882
[DEBUG] starting process with pid 4028
7918361566
1037491392
[DEBUG] starting process with pid 4056
2873187983
7853738301
1290312037
[DEBUG] done with init
1872989829
[DEBUG] cleaning up
8917982882
</code>```

(In reality it is way longer)

I want to count the lines that have integers in them.

I already used: program | grep DEBUG | wc -l to get the debug count (same for ERROR)

But how can I count the integers? They don't have anything static like the strings, that I could grep...

答:
You can use grep after specifying a regular expression to identify integers.

For this particular case,
grep -E "^[0-9]+" | wc -l
should work.

Here,

^ means the start of the line

[0-9] means any number from 0 to 9

+ means one or more such digits

Body:
A utility on my Linux machine outputs a log to 'stdout'.
In each line, there is either a String or an Integer, it looks like the following:

[ERROR] resource busy, retrying
0989282882
[DEBUG] starting process with pid 4028
7918361566
1037491392
[DEBUG] starting process with pid 4056
2873187983
7853738301
1290312037
[DEBUG] done with init
1872989829
[DEBUG] cleaning up
8917982882

(In reality it is way longer)

I want to count the lines that have integers in them.

I already used: program | grep DEBUG | wc -l to get the debug count (same for ERROR)

But how can I count the integers? They don't have anything static like the strings, that I could grep...


问:
ModuleNotFoundError in Jupyter while pip freeze shows its installed
I created a virtual environment, installed pandas and some other libraries, changed the ipython kernel and then opened jupyter inside my virtual environment. Pandas and other libraries worked fine.

Then i installed fastai in my virtualenv, but it shows ModuleNotFoundError in Jupyter only. It works fine in terminal, when i run !pip freeze inside Jupyter it lists 'fastai', when i try to install it in jupyter with '!pip install fastai' it shows 'Requirement already satisfied' but importing it still gives me 'ModuleNotFoundError'.  Check this image for example

All answers on SO to this question are for people who haven't changed their jupyter kernel to their environment or who have had other issues, but i couldn't find my issue.

答:
You have to add the virtualenv to the kernel. Nice discussion is here (Execute Python script within Jupyter notebook using a specific virtualenv).

Assuming virtualenv is working fine (jupyter-notebook and fastai are working), these are the additional steps, I might have tried. In the second line (below) change the "--name=NameOfVirtualEnv" appropriately with the name of your virtualenv.

pip install --user ipykernel
python -m ipykernel install --user --name=NameOfVirtualEnv
```

After that once you start the Jupyter notebook, you will see the "New" dropdown to the right side .. there you will have your virtual environment with the fastai.

Please let me know the outcome. Curious if it worked for you.

Body:
You have to add the virtualenv to the kernel. Nice discussion is here (Execute Python script within Jupyter notebook using a specific virtualenv).

Assuming virtualenv is working fine (jupyter-notebook and fastai are working), these are the additional steps, I might have tried. In the second line (below) change the "--name=NameOfVirtualEnv" appropriately with the name of your virtualenv.

pip install --user ipykernel
python -m ipykernel install --user --name=NameOfVirtualEnv

After that once you start the Jupyter notebook, you will see the "New" dropdown to the right side .. there you will have your virtual environment with the fastai.

Please let me know the outcome. Curious if it worked for you.


问:
laravel route::resource can't find edit function in my controller
When I call my edit function I get a 404|not found page.

this is the code in my View

```<code><a href="{{ route('admin.edit', $user->id) }}">
     <button type="button" class="btn btn-primary btn-sm crudbtn">Edit</button>
</a>
</code>```

This is the code in my web.php

```<code> route::namespace('Admin')->prefix('admin')->middleware(['auth', 'auth.admin'])->name('admin.')->group(function(){
    route::resource('/', 'AdminController');
});
</code>```

This is my edit function in my AdminController

```<code>public function edit($id)
{
    if(Auth::user()->id == $id){
        return redirect()->route('admin.index');
    }

    return view('admin.edit')->with(['user' => user::find($id), 'roles' => Role::all()]);
}
</code>```

And this is the output of my php artisan route:list

```<code>+--------+-----------+------------------------+------------------+------------------------------------------------------------------------+---------------------+
| Domain | Method    | URI                    | Name             | Action                                                                 | Middleware          |
+--------+-----------+------------------------+------------------+------------------------------------------------------------------------+---------------------+
|        | GET|HEAD  | /                      |                  | Closure                                                                | web                 |
|        | POST      | admin                  | admin.store      | App\Http\Controllers\Admin\AdminController@store                       | web,auth,auth.admin |
|        | GET|HEAD  | admin                  | admin.index      | App\Http\Controllers\Admin\AdminController@index                       | web,auth,auth.admin |
|        | GET|HEAD  | admin/create           | admin.create     | App\Http\Controllers\Admin\AdminController@create                      | web,auth,auth.admin |
|        | DELETE    | admin/{}               | admin.destroy    | App\Http\Controllers\Admin\AdminController@destroy                     | web,auth,auth.admin |
|        | PUT|PATCH | admin/{}               | admin.update     | App\Http\Controllers\Admin\AdminController@update                      | web,auth,auth.admin |
|        | GET|HEAD  | admin/{}               | admin.show       | App\Http\Controllers\Admin\AdminController@show                        | web,auth,auth.admin |
|        | GET|HEAD  | admin/{}/edit          | admin.edit       | App\Http\Controllers\Admin\AdminController@edit                        | web,auth,auth.admin |
</code>```

When i call my index function the proper page is loaded, but I can't figure out why my edit function cant' be found. What am I missing or doing wrong?

答:
Try </p>

```<code>route::namespace('Admin')->middleware(['auth', 'auth.admin'])->group(function(){
    route::resource('admin', 'AdminController');
});
</code>```

Body:
When I call my edit function I get a 404|not found page.

this is the code in my View

id) }}">
     <button type="button" class="btn btn-primary btn-sm crudbtn">Edit</button>

This is the code in my web.php

 route::namespace('Admin')->prefix('admin')->middleware(['auth', 'auth.admin'])->name('admin.')->group(function(){
    route::resource('/', 'AdminController');
});

This is my edit function in my AdminController

public function edit($id)
{
    if(Auth::user()->id == $id){
        return redirect()->route('admin.index');
    }

    return view('admin.edit')->with(['user' => user::find($id), 'roles' => Role::all()]);
}

And this is the output of my php artisan route:list

+--------+-----------+------------------------+------------------+------------------------------------------------------------------------+---------------------+
| Domain | Method    | URI                    | Name             | Action                                                                 | Middleware          |
+--------+-----------+------------------------+------------------+------------------------------------------------------------------------+---------------------+
|        | GET|HEAD  | /                      |                  | Closure                                                                | web                 |
|        | POST      | admin                  | admin.store      | App\Http\Controllers\Admin\AdminController@store                       | web,auth,auth.admin |
|        | GET|HEAD  | admin                  | admin.index      | App\Http\Controllers\Admin\AdminController@index                       | web,auth,auth.admin |
|        | GET|HEAD  | admin/create           | admin.create     | App\Http\Controllers\Admin\AdminController@create                      | web,auth,auth.admin |
|        | DELETE    | admin/{}               | admin.destroy    | App\Http\Controllers\Admin\AdminController@destroy                     | web,auth,auth.admin |
|        | PUT|PATCH | admin/{}               | admin.update     | App\Http\Controllers\Admin\AdminController@update                      | web,auth,auth.admin |
|        | GET|HEAD  | admin/{}               | admin.show       | App\Http\Controllers\Admin\AdminController@show                        | web,auth,auth.admin |
|        | GET|HEAD  | admin/{}/edit          | admin.edit       | App\Http\Controllers\Admin\AdminController@edit                        | web,auth,auth.admin |

When i call my index function the proper page is loaded, but I can't figure out why my edit function cant' be found. What am I missing or doing wrong?

Body:
Try

route::namespace('Admin')->middleware(['auth', 'auth.admin'])->group(function(){
    route::resource('admin', 'AdminController');
});


问:
CodingBat starOut, why using substring won't work correctly
I am solving coding challenge on CodingBat.com. Here is the question:

Given a string and a non-empty word string, return a version of the
  original String where all chars have been replaced by pluses ("+"),
  except for appearances of the word string which are preserved
  unchanged.

```<code>plusOut("12xy34", "xy") → "++xy++"
plusOut("12xy34", "1") → "1+++++"
plusOut("12xy34xyabcxy", "xy") → "++xy++xy+++xy"
</code>```

Here is my attempted solution:

```<code>public String plusOut(String str, String word)
{
  String ret = "";
  for (int i = 0; i < str.length() - word.length() + 1; ++i) {
    if (str.substring(i, i + word.length()).equals(word))
      ret += word;
    else
      ret += "+";
  }
  return ret;
}
</code>```

But is giving wrong outputs: giving too many plus signs. I don't understand why this shouldn't work. I suspect that the substring method is not returning enough matches, so the plus sign is appended. But I don't see why this maybe so.

答:
I would use a StringBuilder to construct the result to avoid creating multiple String objects as String in java is immutable:</p>

```<code>public String plusOut(String str, String word) {
  StringBuilder result = new StringBuilder(str);
  int len = str.length(), wordLen = word.length(), index = 0;
  while(index < len){
    if ( (index <= len-wordLen) && (str.substring(index, index+wordLen).equals(word))){
      index += wordLen;
      continue;
    }
    result.setCharAt(index++, '+');
  }
  return result.toString();
}
</code>```

Body:
I am solving coding challenge on CodingBat.com. Here is the question:

Given a string and a non-empty word string, return a version of the
  original String where all chars have been replaced by pluses ("+"),
  except for appearances of the word string which are preserved
  unchanged.

plusOut("12xy34", "xy") → "++xy++"
plusOut("12xy34", "1") → "1+++++"
plusOut("12xy34xyabcxy", "xy") → "++xy++xy+++xy"

Here is my attempted solution:

public String plusOut(String str, String word)
{
  String ret = "";
  for (int i = 0; i < str.length() - word.length() + 1; ++i) {
    if (str.substring(i, i + word.length()).equals(word))
      ret += word;
    else
      ret += "+";
  }
  return ret;
}

But is giving wrong outputs: giving too many plus signs. I don't understand why this shouldn't work. I suspect that the substring method is not returning enough matches, so the plus sign is appended. But I don't see why this maybe so.

Body:
I would use a StringBuilder to construct the result to avoid creating multiple String objects as String in java is immutable:

public String plusOut(String str, String word) {
  StringBuilder result = new StringBuilder(str);
  int len = str.length(), wordLen = word.length(), index = 0;
  while(index < len){
    if ( (index <= len-wordLen) && (str.substring(index, index+wordLen).equals(word))){
      index += wordLen;
      continue;
    }
    result.setCharAt(index++, '+');
  }
  return result.toString();
}


问:
How to output the result of a chain of commands for a given input with bash
In reference to this question I still struggle the following single-liner to work

```<code>kubectl get ns | while read -r line; do  echo `$line | grep Term | cut -d' ' -f1`; done
</code>```

I would expect to print out the result of $line | grep Term | cut -d' ' -f1 however it prints out an empty line (echo) and then executes the result of $line | grep Term | cut -d' ' -f1

```<code>bash: NAME: command not found

bash: cert-manager: command not found

bash: configmap-4262: command not found

bash: configmap-4430: command not found

</code>```

Same results with a slightly different approach:

```<code>kubectl get ns | while read -r line; do ns=`$line | grep Term | cut -d' ' -f1`; echo $ns; done
</code>```

What I actually want to achieve is to use the result of $line | grep Term | cut -d' as an input of a shell script e.g.

```<code>do ns=`$line | grep Term | cut -d' ' -f1`; ./delete-kube-ns.sh $ns;
</code>```

or

```<code>$line | grep Term | cut -d' ' -f1` | xargs ./delete-kube-ns.sh
</code>```

答:
Any combo of grep and cut (and head, tall, etc, as well as sed) suggests a reimplementation in Awk. Saving one external process is a minor optimization, but this often invites additional simple improvements. For example, should the regex cover the whole line, or is it only really supposed to look for matches in the first field? That's not impossible with grep, either, of course, but quite easy in Awk.

kubectl get ns |
awk '/Term/ { print $1 }'
```

<p>If you only wanted to look for <code>Term</code> in the first field, that's <code>'$1 ~ /Term/ { ...</code></p>

<p>You can extend this with a pipe to </p>

```... | xargs ./delete-kube-ns.sh
```

if that's your end goal.

Body:
In reference to this question I still struggle the following single-liner to work

kubectl get ns | while read -r line; do  echo `$line | grep Term | cut -d' ' -f1`; done

I would expect to print out the result of $line | grep Term | cut -d' ' -f1 however it prints out an empty line (echo) and then executes the result of $line | grep Term | cut -d' ' -f1

bash: NAME: command not found

bash: cert-manager: command not found

bash: configmap-4262: command not found

bash: configmap-4430: command not found

Same results with a slightly different approach:

kubectl get ns | while read -r line; do ns=`$line | grep Term | cut -d' ' -f1`; echo $ns; done

What I actually want to achieve is to use the result of $line | grep Term | cut -d' as an input of a shell script e.g.

do ns=`$line | grep Term | cut -d' ' -f1`; ./delete-kube-ns.sh $ns;

or

$line | grep Term | cut -d' ' -f1` | xargs ./delete-kube-ns.sh

Body:
Any combo of grep and cut (and head, tall, etc, as well as sed) suggests a reimplementation in Awk. Saving one external process is a minor optimization, but this often invites additional simple improvements. For example, should the regex cover the whole line, or is it only really supposed to look for matches in the first field? That's not impossible with grep, either, of course, but quite easy in Awk.

kubectl get ns |
awk '/Term/ { print $1 }'

If you only wanted to look for Term in the first field, that's '$1 ~ /Term/ { ...

You can extend this with a pipe to

... | xargs ./delete-kube-ns.sh

if that's your end goal.


问:
:hover CSS is not working?
I have created a CSS class as follows:

```<code>div.ycontent div.ppclisting { background-color:#cccccc; }
div.ycontent div.ppclisting:hover { background-color:#FFE5DF; }
</code>```

I have applied the above style in one of my page, which is working quite fine in Firefox, IE 7.0+ and in other latest browsers. But When I am applying the same style in another page then its not working.

Can anyone tell me what could be the reason? why its not working in another page.

答: Just had a similar problem. Make sure you're stacking correctly! That is, the z-index.</p>

Title: :hover CSS is not working?

Body:
I have created a CSS class as follows:

div.ycontent div.ppclisting { background-color:#cccccc; }
div.ycontent div.ppclisting:hover { background-color:#FFE5DF; }

I have applied the above style in one of my page, which is working quite fine in Firefox, IE 7.0+ and in other latest browsers. But When I am applying the same style in another page then its not working.

Can anyone tell me what could be the reason? why its not working in another page.


问:
Restrict geocode autocomplete to a contry
I need help with google places autocomplete API. I am getting the autocomplete address and lat and long from the API. Without restriction to a country the code works fine and I get the desired address, lat and long. However when I try to add country restriction, the lat and long fails to send along with my form.

Here is the working code without country restriction:

JS

```<code><script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places"></script>
    <script>
        function initialize() {
          var input = document.getElementById('searchTextField');
          var autocomplete = new google.maps.places.Autocomplete(input);
            google.maps.event.addListener(autocomplete, 'place_changed', function () {
                var place = autocomplete.getPlace();
                document.getElementById('searchTextField').value = place.name;
                document.getElementById('latitude').value = place.geometry.location.lat();
                document.getElementById('longitude').value = place.geometry.location.lng();
            });
        }
        google.maps.event.addDomListener(window, 'load', initialize);
    </script>
</code>```

Here is the code with country restriction that I need help with:

```<code><script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places"></script>
    <script>
        function initialize() {

        autocomplete = new google.maps.places.Autocomplete(
    /** @type {!HTMLInputElement} */(document.getElementById('searchTextField')),
    {types: ['geocode'],
    componentRestrictions: {country: 'us'}});

          var input = document.getElementById('searchTextField');

 var autocomplete = new google.maps.places.Autocomplete(input, options);

            google.maps.event.addListener(autocomplete, 'place_changed', function () {
                var place = autocomplete.getPlace();
                document.getElementById('searchTextField').value = place.name;
                document.getElementById('latitude').value = place.geometry.location.lat();
                document.getElementById('longitude').value = place.geometry.location.lng();
            });
        }
        google.maps.event.addDomListener(window, 'load', initialize);
    </script>
</code>```

Here's the lines that's causing the problem:

```<code>autocomplete = new google.maps.places.Autocomplete(
    /** @type {!HTMLInputElement} */(document.getElementById('searchTextField')),
    {types: ['geocode'],
    componentRestrictions: {country: 'us'}});
</code>```

My form:

```<code><html>
<head>
<title>Address Demo</title>
 </head>
<body>
<form action="address.php" method="GET">

<div class="container">
<div class="panel panel-primary">
<div class="panel-heading" style="background-color:#00CDCD">
<h2 class="panel-title">Address</h2>
</div>
<div class="panel-body">
<input name="address" id="searchTextField" placeholder="Enter area name" type="text" class="form-control" required>
<input type="hidden" name="latii" id="latitude">
<input type="hidden" name="lngii" id="longitude">
<input type="submit" name="submit" value="SUBMIT" class="bookingbtn top-10 bottom-20">
</div>
</div>
</form>

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

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

address.php

```<code><?php

$address = $_GET['address'];
$latii = $_GET['latii'];
$lngii = $_GET['lngii'];

echo "$address </br>";
echo "$latii </br>";
echo "$lngii";

?>
</code>```

Thanks for your help in advance.

答:
I finally got it to work. Thanks to the answer here How to limit google autocomplete results to City and Country only.

My working code is:

```<code><script>
        function initialize() {
    var options = {
  types: ['geocode'],
  componentRestrictions: {country: "us"}
 };
          var input = document.getElementById('searchTextField');
          var autocomplete = new google.maps.places.Autocomplete(input, options);
            google.maps.event.addListener(autocomplete, 'place_changed', function () {
                var place = autocomplete.getPlace();
                document.getElementById('searchTextField').value = place.name;
                document.getElementById('latitude').value = place.geometry.location.lat();
                document.getElementById('longitude').value = place.geometry.location.lng();
            });
        }
        google.maps.event.addDomListener(window, 'load', initialize);
    </script>
</code>```

Body:
I need help with google places autocomplete API. I am getting the autocomplete address and lat and long from the API. Without restriction to a country the code works fine and I get the desired address, lat and long. However when I try to add country restriction, the lat and long fails to send along with my form.

Here is the working code without country restriction:

JS

Here is the code with country restriction that I need help with:

Here's the lines that's causing the problem:

autocomplete = new google.maps.places.Autocomplete(
    /** @type {!HTMLInputElement} */(document.getElementById('searchTextField')),
    {types: ['geocode'],
    componentRestrictions: {country: 'us'}});

My form:

<title>Address Demo</title>

<form action="address.php" method="GET">

Address

<input name="address" id="searchTextField" placeholder="Enter area name" type="text" class="form-control" required>
<input type="hidden" name="latii" id="latitude">
<input type="hidden" name="lngii" id="longitude">
<input type="submit" name="submit" value="SUBMIT" class="bookingbtn top-10 bottom-20">

</form>

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

address.php

<?php

$address = $_GET['address'];
$latii = $_GET['latii'];
$lngii = $_GET['lngii'];

echo "$address
";
echo "$latii
";
echo "$lngii";

?>

Thanks for your help in advance.

Body:
I finally got it to work. Thanks to the answer here How to limit google autocomplete results to City and Country only.

My working code is:

<script>
        function initialize() {
    var options = {
  types: ['geocode'],
  componentRestrictions: {country: "us"}
 };
          var input = document.getElementById('searchTextField');
          var autocomplete = new google.maps.places.Autocomplete(input, options);
            google.maps.event.addListener(autocomplete, 'place_changed', function () {
                var place = autocomplete.getPlace();
                document.getElementById('searchTextField').value = place.name;
                document.getElementById('latitude').value = place.geometry.location.lat();
                document.getElementById('longitude').value = place.geometry.location.lng();
            });
        }
        google.maps.event.addDomListener(window, 'load', initialize);
    </script>


问:
Need kubectl jsonpath parameter to get array entry indexed by string
I have some scripts that pipe "kubectl ... -o json" to "jq".  I've been converting many of those occurrences to use the "jsonpath" parameter to kubectl so I can skip the jq step.

There's one set of these that I've been unable to convert, because of punctuation issues.  The original line looks something like this:

```<code>kubectl ... -o json | jq -r '.data["application.properties"]'
</code>```

In the json, there is a "data" map whose keys can have periods in the names, so I have to index it as an array, with the name as the key.  This works fine using jq.

The simple-minded conversion of this to jsonpath looks something like this:

```<code>kubectl ... -o=jsonpath="{.data["application.properties"]}"
</code>```

This fails with:

```<code>error: error parsing jsonpath {.data[application.properties]}, invalid array index application.properties
</code>```

This doesn't appear to be a quoting problem, as it is clearly detecting what my attempted array index is, it just won't let me use it.

Is there any way to do this entirely with jsonpath?

答:
The trick is to convert

```<code>{.data["application.properties"]}
</code>```

To:

```<code>{.data.application\.properties}
</code>```

(with quoting as required)

Body:
I have some scripts that pipe "kubectl ... -o json" to "jq".  I've been converting many of those occurrences to use the "jsonpath" parameter to kubectl so I can skip the jq step.

There's one set of these that I've been unable to convert, because of punctuation issues.  The original line looks something like this:

kubectl ... -o json | jq -r '.data["application.properties"]'

In the json, there is a "data" map whose keys can have periods in the names, so I have to index it as an array, with the name as the key.  This works fine using jq.

The simple-minded conversion of this to jsonpath looks something like this:

kubectl ... -o=jsonpath="{.data["application.properties"]}"

This fails with:

error: error parsing jsonpath {.data[application.properties]}, invalid array index application.properties

This doesn't appear to be a quoting problem, as it is clearly detecting what my attempted array index is, it just won't let me use it.

Is there any way to do this entirely with jsonpath?

Body:
The trick is to convert

{.data["application.properties"]}

To:

{.data.application\.properties}

(with quoting as required)