问:
Python-tesseract installation on Ubuntu
I am trying to install python-tesseract 0.9-0.5  from a deb file on Ubuntu 15.04, but it gives several errors.
This is what I do:

1- I open the path of the file on terminal and write

```<code>sudo dpkg -i python-tesseract_0.9-0.5ubuntu2_i386.deb
</code>```

2- After this, the console shows several errors:

```<code>Selecting previously unselected package python-tesseract.
(Reading database ... 349994 files and directories currently installed.)

Preparing to unpack python-tesseract_0.9-0.5ubuntu2_i386.deb ...

Unpacking python-tesseract (0.9-0.5ubuntu2) ...
dpkg: dependency problems prevent configuration of python-tesseract:
 python-tesseract depends on python (<< 2.8).
 python-tesseract depends on python (>= 2.7~).
 python-tesseract depends on liblept4.
 python-tesseract depends on libopencv-core2.4; however:
  Package libopencv-core2.4:i386 is not installed.
 python-tesseract depends on libtesseract3; however:

dpkg: error processing package python-tesseract (--install):
 dependency problems - leaving unconfigured
Errors were encountered while processing:
 python-tesseract
</code>```

3- Just for checking, I open the installation file and extracted the tesseract.py class, and used alone in python.
I opened it this way:

```<code>python tesseract.py
</code>```

, but I got this:

```<code>Traceback (most recent call last):
  File "tesseract.py", line 28, in <module>
    _tesseract = swig_import_helper()
  File "tesseract.py", line 20, in swig_import_helper
    import _tesseract
ImportError: No module named _tesseract
</code>```

The thing is that I want to use tesseract functions on python for an optical character recognition application, and I have understood that the best wrapper for this is python-tesseract (is not the same that pytesseract, I think).

My question is: How can I to install python-tesseract on Ubuntu 15.04? Thanks a lot

答:
Use this link for installation

once you do that,
here is the code

```<code>from PIL import Image
img="pathToYourImage/img.jpeg"
text = pytesseract.image_to_string(Image.open(img))
print(text)

</code>```

Title: Python-tesseract installation on Ubuntu

Body:
I am trying to install python-tesseract 0.9-0.5  from a deb file on Ubuntu 15.04, but it gives several errors.
This is what I do:

1- I open the path of the file on terminal and write

sudo dpkg -i python-tesseract_0.9-0.5ubuntu2_i386.deb

2- After this, the console shows several errors:

Selecting previously unselected package python-tesseract.
(Reading database ... 349994 files and directories currently installed.)

Preparing to unpack python-tesseract_0.9-0.5ubuntu2_i386.deb ...

Unpacking python-tesseract (0.9-0.5ubuntu2) ...
dpkg: dependency problems prevent configuration of python-tesseract:
 python-tesseract depends on python (<< 2.8).
 python-tesseract depends on python (>= 2.7~).
 python-tesseract depends on liblept4.
 python-tesseract depends on libopencv-core2.4; however:
  Package libopencv-core2.4:i386 is not installed.
 python-tesseract depends on libtesseract3; however:

dpkg: error processing package python-tesseract (--install):
 dependency problems - leaving unconfigured
Errors were encountered while processing:
 python-tesseract

3- Just for checking, I open the installation file and extracted the tesseract.py class, and used alone in python.
I opened it this way:

python tesseract.py

, but I got this:

Traceback (most recent call last):
  File "tesseract.py", line 28, in <module>
    _tesseract = swig_import_helper()
  File "tesseract.py", line 20, in swig_import_helper
    import _tesseract
ImportError: No module named _tesseract

The thing is that I want to use tesseract functions on python for an optical character recognition application, and I have understood that the best wrapper for this is python-tesseract (is not the same that pytesseract, I think).

My question is: How can I to install python-tesseract on Ubuntu 15.04? Thanks a lot

Body:
Use this link for installation

once you do that,
here is the code

from PIL import Image
img="pathToYourImage/img.jpeg"
text = pytesseract.image_to_string(Image.open(img))
print(text)


来源: stackexchange

问:
Ad hoc data and repository pattern
What is the recommended way to return ad hoc (custom case by case) data from repository which don't fit any model entities or which extend some?

The 101 example would be the ubiquitous hello word application: a blog system. Suppose you want to load a list of posts where post entry has some additional information which does not exists in the Post entity. Let’s say it is the number of comments and the date and time of the last comment. This would be highly trivial if one was using the plain old SQL and reading data directly from the database. How am I supposed to do it optimally using the repository pattern if I cannot afford loading the entire collections of Comments for each Post, and I want to do it in one database hit? Is there any commonly used pattern for this situation? Now imagine that you have moderately complex web application where each page needs a slightly different custom data, and loading full hierarchies is not possible (performance, memory requirements etc).

Some random ideas:

Add a list of properties to each model which could be populated by the custom data.

Subclass model entities case by case, and create custom readers for each subclass.

Use LINQ, compose ad hoc queries and read anonymous classes.

Note: I’ve asked a similar question recently, but it seemed to be too general and did not attract much attention.

Example:

Based on suggestions in answers below, I am adding a more concrete example. Here is the situation I was trying to describe:

```<code>IEnumarable<Post> posts = repository.GetPostsByPage(1);
foreach (Post post in posts)
{

    // snip: push post title, content, etc. to view

    // determine the post count and latest comment date
    int commentCount = post.Comments.Count();
    DateTime newestCommentDate = post.Comments.Max(c => c.Date);

    // snip: push the count and date to view

}
</code>```

If I don’t do anything extra and use an off the shelf ORM, this will result to n+1 queries or possibly one query loading all posts and comments. But optimally, I would like to be able to just execute one SQL which would return one row for each post including the post title, body etc. and the comment count and most recent comment date in the same. This is trivial in SQL. The problem is that my repository won’t be able to read and fit this type of data into the model. Where do the max dates and the counts go?

I’m not asking how to do that. You can always do it somehow: add extra methods to the repository, add new classes, special entities, use LINQ etc., but I guess my question is the following. How come the repository pattern and the proper model driven development are so widely accepted, but yet they don’t seem to address this seemingly very common and basic case.

答:
Can't say I really see what the problem is, just firing in the air here:

Add a specific entity to encapsulate the info yo want

Add a property Comments to the Post. (I don't see why this would require you to fetch all comments - you can just fetch the comments for the particular post you're loading)

Use lazy loading to only fetch the comments when you access the property

I think you would have a greater chance of seeing your question answered if you would make platform, language and O/R mapper specific (seems to be .NET C# or VB, since you mentioned LINQ. LINQ 2 SQL? Entity framework? Something else?)

OwnerDisplayName: Jan Zich

ContentLicense: CC BY-SA 2.5

Title: Ad hoc data and repository pattern

Body:
What is the recommended way to return ad hoc (custom case by case) data from repository which don't fit any model entities or which extend some?

The 101 example would be the ubiquitous hello word application: a blog system. Suppose you want to load a list of posts where post entry has some additional information which does not exists in the Post entity. Let’s say it is the number of comments and the date and time of the last comment. This would be highly trivial if one was using the plain old SQL and reading data directly from the database. How am I supposed to do it optimally using the repository pattern if I cannot afford loading the entire collections of Comments for each Post, and I want to do it in one database hit? Is there any commonly used pattern for this situation? Now imagine that you have moderately complex web application where each page needs a slightly different custom data, and loading full hierarchies is not possible (performance, memory requirements etc).

Some random ideas:

Add a list of properties to each model which could be populated by the custom data.

Subclass model entities case by case, and create custom readers for each subclass.

Use LINQ, compose ad hoc queries and read anonymous classes.

Note: I’ve asked a similar question recently, but it seemed to be too general and did not attract much attention.

Example:

Based on suggestions in answers below, I am adding a more concrete example. Here is the situation I was trying to describe:

IEnumarable<Post> posts = repository.GetPostsByPage(1);
foreach (Post post in posts)
{

    // snip: push post title, content, etc. to view

    // determine the post count and latest comment date
    int commentCount = post.Comments.Count();
    DateTime newestCommentDate = post.Comments.Max(c => c.Date);

    // snip: push the count and date to view

}

If I don’t do anything extra and use an off the shelf ORM, this will result to n+1 queries or possibly one query loading all posts and comments. But optimally, I would like to be able to just execute one SQL which would return one row for each post including the post title, body etc. and the comment count and most recent comment date in the same. This is trivial in SQL. The problem is that my repository won’t be able to read and fit this type of data into the model. Where do the max dates and the counts go?

I’m not asking how to do that. You can always do it somehow: add extra methods to the repository, add new classes, special entities, use LINQ etc., but I guess my question is the following. How come the repository pattern and the proper model driven development are so widely accepted, but yet they don’t seem to address this seemingly very common and basic case.

LastEditorDisplayName: Jan Zich

OwnerDisplayName: Kurt Schelfthout

LastEditorDisplayName: Christophe Herreman


问:
Implement N-ary Tree in c
I'm trying to implement a N-ary tree in C. I know how to implement if I decide how many childs would have earlier. But my problem is, i want to make it dynamic (i want to resize the children and child size)

```<code>struct node
{
    char * type;
    struct node **child;
    int children;
    int id;
};
</code>```

this is my struct and i want to do that with a pointer of pointer.
How can i implement the insertion function?

```<code>        struct node **toKeep = (*root)->child;
        (*root)->children+=1;
        (*root)->child =malloc(sizeof(struct node*)*
        (*root)->child = toKeep;
        size_t i;
        for (i= 0; i < (*root)->children; i++)
        {
            if ((*root)->child[i] == NULL)
            {
                (*root)->child[i] = newNode(type, id);
                printf("%d \n", (*root)->child[i]->id);
                break;
            }
        }
</code>```

i tried this to keep existing nodes but im unable to add more than 2 nodes ? What can cause the problem or is there a better way to write it?

答:
This is prefaced by my top comments.

Since I couldn't understand the intent of your code fragment, I refactored the code based on a trie example I've done before. It may or may not be what you're looking for, but, at least, the dynamic child list code should give you an idea:

```<code>#include <stdlib.h>

typedef struct node node_t;
struct node {
    char *type;

    node_t *parent;
    node_t **child;
    int children;

    int id;
};

// naryfind -- find matching child node based on id
node_t *
naryfind(node_t *par,int id)
{
    size_t cldidx;
    node_t *cld;
    node_t *match;

    match = NULL;

    for (cldidx = 0;  cldidx < par->children;  ++cldidx) {
        cld = par->child[cldidx];

        // skip empty slot
        // NOTE: this will probably never happen based on naryattach
        if (cld == NULL)
            continue;

        if (cld->id == id) {
            match = cld;
            break;
        }
    }

    return match;
}

// narynew -- get new node
node_t *
narynew(int id)
{
    node_t *node;

    node = calloc(1,sizeof(node_t));
    node->id = id;

    return node;
}

// naryattach -- attach new child node
node_t *
naryattach(node_t *par,int id)
{
    size_t cldidx;
    node_t *cld;

    // increase size of array
    cldidx = par->children++;
    par->child = realloc(par->child,sizeof(node_t *) * par->children);

    // allocate new node
    cld = narynew(id);

    // cross-link parent and child
    cld->parent = par;
    par->child[cldidx] = cld;

    return cld;
}

// naryfindx -- find matching child node (create new node if none found)
node_t *
naryfindx(node_t *par,int id)
{
    node_t *cld;

    // find existing node
    cld = naryfind(par,id);

    // create new node if it doesn't already exist
    if (cld == NULL)
        cld = naryattach(par,id);

    return cld;
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Implement N-ary Tree in c

Body:
I'm trying to implement a N-ary tree in C. I know how to implement if I decide how many childs would have earlier. But my problem is, i want to make it dynamic (i want to resize the children and child size)

struct node
{
    char * type;
    struct node **child;
    int children;
    int id;
};

this is my struct and i want to do that with a pointer of pointer.
How can i implement the insertion function?

        struct node **toKeep = (*root)->child;
        (*root)->children+=1;
        (*root)->child =malloc(sizeof(struct node*)*
        (*root)->child = toKeep;
        size_t i;
        for (i= 0; i < (*root)->children; i++)
        {
            if ((*root)->child[i] == NULL)
            {
                (*root)->child[i] = newNode(type, id);
                printf("%d \n", (*root)->child[i]->id);
                break;
            }
        }

i tried this to keep existing nodes but im unable to add more than 2 nodes ? What can cause the problem or is there a better way to write it?

Body:
This is prefaced by my top comments.

Since I couldn't understand the intent of your code fragment, I refactored the code based on a trie example I've done before. It may or may not be what you're looking for, but, at least, the dynamic child list code should give you an idea:

#include <stdlib.h>

typedef struct node node_t;
struct node {
    char *type;

    node_t *parent;
    node_t **child;
    int children;

    int id;
};

// naryfind -- find matching child node based on id
node_t *
naryfind(node_t *par,int id)
{
    size_t cldidx;
    node_t *cld;
    node_t *match;

    match = NULL;

    for (cldidx = 0;  cldidx < par->children;  ++cldidx) {
        cld = par->child[cldidx];

        // skip empty slot
        // NOTE: this will probably never happen based on naryattach
        if (cld == NULL)
            continue;

        if (cld->id == id) {
            match = cld;
            break;
        }
    }

    return match;
}

// narynew -- get new node
node_t *
narynew(int id)
{
    node_t *node;

    node = calloc(1,sizeof(node_t));
    node->id = id;

    return node;
}

// naryattach -- attach new child node
node_t *
naryattach(node_t *par,int id)
{
    size_t cldidx;
    node_t *cld;

    // increase size of array
    cldidx = par->children++;
    par->child = realloc(par->child,sizeof(node_t *) * par->children);

    // allocate new node
    cld = narynew(id);

    // cross-link parent and child
    cld->parent = par;
    par->child[cldidx] = cld;

    return cld;
}

// naryfindx -- find matching child node (create new node if none found)
node_t *
naryfindx(node_t *par,int id)
{
    node_t *cld;

    // find existing node
    cld = naryfind(par,id);

    // create new node if it doesn't already exist
    if (cld == NULL)
        cld = naryattach(par,id);

    return cld;
}


问:
CosmosDB source returning DF-SYS-01
I've built some pipelines and had success importing data from most of my CosmosDB tables, but this one constantly gives me an error which I don't understand. I think it might be caused by table structure, but would highly appreciate second opinion and possible solutions.

Table item:

```<code>{
"id": "someGuid",
"name": "someString",
"pins": [
    {
        "type": "someString",
        "latitude": 47.03923,
        "longitude": -122.89136,
        "name": "someString"
    },
    {
        "type": "someString",
        "latitude": 28.53823,
        "longitude": -81.37739,
        "name": "someString"
    }
],
"_rid": "vj04AOrfr2s8CT0AAAAAAA==",
"_self": "dbs/vj04AA==/colls/vj04AOrfr2s=/docs/vj04AOrfr2s8CT0AAAAAAA==/",
"_etag": "\"ac00ddc8-0000-0700-0000-5e7428230000\"",
"_attachments": "attachments/",
"_ts": 1584670755
}
</code>```

Columns are identified correct in Source.Projection Tab where pins are []string, but source can't be loaded ((

```<code>"{"message":"at : (StructType(StructField(area,StringType,true), StructField(date,StringType,true), StructField(resultType,StringType,true), StructField(results,ArrayType(StringType,true),true), StructField(test,StringType,true)),StringType) (of class scala.Tuple2). Details:at : (StructType(StructField(area,StringType,true), StructField(date,StringType,true), StructField(resultType,StringType,true), StructField(results,ArrayType(StringType,true),true), StructField(test,StringType,true)),StringType) (of class scala.Tuple2)","failureType":"UserError","target":"Pins","errorCode":"DFExecutorUserError"}"
</code>```

答: Was able to solve it by : 1. restarting ADF session  2. Resetting schema for data source - it automatically picked correct schema. Hopefully this answer will help someone in the feature.</p>

Title: CosmosDB source returning DF-SYS-01

Body:
I've built some pipelines and had success importing data from most of my CosmosDB tables, but this one constantly gives me an error which I don't understand. I think it might be caused by table structure, but would highly appreciate second opinion and possible solutions.

Table item:

{
"id": "someGuid",
"name": "someString",
"pins": [
    {
        "type": "someString",
        "latitude": 47.03923,
        "longitude": -122.89136,
        "name": "someString"
    },
    {
        "type": "someString",
        "latitude": 28.53823,
        "longitude": -81.37739,
        "name": "someString"
    }
],
"_rid": "vj04AOrfr2s8CT0AAAAAAA==",
"_self": "dbs/vj04AA==/colls/vj04AOrfr2s=/docs/vj04AOrfr2s8CT0AAAAAAA==/",
"_etag": "\"ac00ddc8-0000-0700-0000-5e7428230000\"",
"_attachments": "attachments/",
"_ts": 1584670755
}

Columns are identified correct in Source.Projection Tab where pins are []string, but source can't be loaded ((

"{"message":"at : (StructType(StructField(area,StringType,true), StructField(date,StringType,true), StructField(resultType,StringType,true), StructField(results,ArrayType(StringType,true),true), StructField(test,StringType,true)),StringType) (of class scala.Tuple2). Details:at : (StructType(StructField(area,StringType,true), StructField(date,StringType,true), StructField(resultType,StringType,true), StructField(results,ArrayType(StringType,true),true), StructField(test,StringType,true)),StringType) (of class scala.Tuple2)","failureType":"UserError","target":"Pins","errorCode":"DFExecutorUserError"}"


问:
How do you provide a default type for generics?
I have a class that currently has several methods that take integer parameters. These integers map to operations that the application can perform. I'd like to make the class generic so that the consumers of the class can provide an enum type that they have with all the operations in it, then the methods will take parameters of that enum type. However, I want them to be able to not specify a generic type at all, and have it default back to integers with no change in syntax from the current way. Is this possible?</p>

答:
I'm sure you've moved on from this, however I was working through a similar issue and found this solution that uses a context of "using" I was not familiar with.  They need to put it in their namespace, so its not completely perfect.</p>

```<code>namespace mygeneric
{
    public class SecurityContext<T>
    {

    }
}

namespace mytest
{
    using SecurityContext = mygeneric.SecurityContext<int>;
    using mygeneric;

    enum MyContexts
    {
        User,
        Admin
    }
    class MyTest
    {
        SecurityContext myDefaultContext;
        SecurityContext<MyContexts> mySpecialContext;
    }
}
</code>```

Body:
I'm sure you've moved on from this, however I was working through a similar issue and found this solution that uses a context of "using" I was not familiar with.  They need to put it in their namespace, so its not completely perfect.

namespace mygeneric
{
    public class SecurityContext<T>
    {

    }
}

namespace mytest
{
    using SecurityContext = mygeneric.SecurityContext<int>;
    using mygeneric;

    enum MyContexts
    {
        User,
        Admin
    }
    class MyTest
    {
        SecurityContext myDefaultContext;
        SecurityContext<MyContexts> mySpecialContext;
    }
}


问:
Is there a way to make this code less taxing on the computer?
I have some python to convert a Decimal number into a Hexadecimal, however, my computer takes forever and shuts off before the code even finishes. Is there a way to compact this code to less lines? I have Python 3.8.3 downloaded. The python is in a plain text (but .py) file and I am running it through terminal on macOS High Sierra (v10.13.6).

```<code>import math

dec = float(input("Decimal: "))

while(math.floor(dec/16) >= 0):
  x = "Hex: "
  rem = dec/16 - math.floor(dec/16)
  myHex = rem*16
  if myHex > 9 :
    if myHex == 10 :
      x += "A"

    if myHex == 11 :
      x += "B"

    if myHex == 12 :
      x += "C"

    if myHex == 13 :
      x += "D"

    if myHex == 14 :
      x += "E"

    if myHex == 15 :
      x += "F"

  else :
    x += str(myHex)

print (x)
</code>```

答:
You can just use the struct module:

```<code>import struct

f = float(input("> "))
print(hex(struct.unpack('<I', struct.pack('<f', f))[0]))
</code>```

Input:

```<code>> 234.345
</code>```

Output:

```<code>0x436a5852
</code>```

Body:
I have some python to convert a Decimal number into a Hexadecimal, however, my computer takes forever and shuts off before the code even finishes. Is there a way to compact this code to less lines? I have Python 3.8.3 downloaded. The python is in a plain text (but .py) file and I am running it through terminal on macOS High Sierra (v10.13.6).

import math

dec = float(input("Decimal: "))

while(math.floor(dec/16) >= 0):
  x = "Hex: "
  rem = dec/16 - math.floor(dec/16)
  myHex = rem*16
  if myHex > 9 :
    if myHex == 10 :
      x += "A"

    if myHex == 11 :
      x += "B"

    if myHex == 12 :
      x += "C"

    if myHex == 13 :
      x += "D"

    if myHex == 14 :
      x += "E"

    if myHex == 15 :
      x += "F"

  else :
    x += str(myHex)

print (x)

Body:
You can just use the struct module:

import struct

f = float(input("> "))
print(hex(struct.unpack('<I', struct.pack('<f', f))[0]))

Input:

> 234.345

Output:

0x436a5852


问:
How to remove leading zero from %m for x axis in ggplot2
How can I remove leading zeros from the x axis labels WITHOUT MANUALLY adding custom labels?</p>

```<code>   p + scale_x_date(date_labels = "%m/%d", #this generated dates like: 02/15, 03/15, etc
                 date_breaks = "1 week",
                 expand = expand_scale(0,0))
</code>```

答:
You can do this with a simple change to your strftime format string. However, it depends on your platform (Unix or Windows).

Windows

Insert a pound sign (#) before the m:

p + scale_x_date(date_labels = "%#m/%d", #this generated dates like: 2/15, 3/15, etc
                 date_breaks = "1 week",
                 expand = expand_scale(0,0))
```
<h3>Unix</h3>
<p>Insert a minus sign (<code>-</code>) before the <code>m</code>:</p>
<pre class="lang-r prettyprint-override"><code>p + scale_x_date(date_labels = "%-m/%d", #this generated dates like: 2/15, 3/15, etc
                 date_breaks = "1 week",
                 expand = expand_scale(0,0))
</code>```

Body:
How can I remove leading zeros from the x axis labels WITHOUT MANUALLY adding custom labels?

   p + scale_x_date(date_labels = "%m/%d", #this generated dates like: 02/15, 03/15, etc
                 date_breaks = "1 week",
                 expand = expand_scale(0,0))

Body:
You can do this with a simple change to your strftime format string. However, it depends on your platform (Unix or Windows).

Windows

Insert a pound sign (#) before the m:

p + scale_x_date(date_labels = "%#m/%d", #this generated dates like: 2/15, 3/15, etc
                 date_breaks = "1 week",
                 expand = expand_scale(0,0))

Unix

Insert a minus sign (-) before the m:

p + scale_x_date(date_labels = "%-m/%d", #this generated dates like: 2/15, 3/15, etc
                 date_breaks = "1 week",
                 expand = expand_scale(0,0))


问:
How to access the Altorouter instance in my views
I'm new to php, I would like to have access to the $router instance in my views so that I can use the route names with $router->generate() in the view but I don't know how to do it?
I use Altorouter like this:

Index.php

```<code>$router = new AltoRouter();
$router->map( 'GET', '/post/[:id]/', 'PostController#find' );
$match = $router->match();

        if ($match === false) {
            throw new \Exception($error->404());
        } else {
            list($controller, $action) = explode('#', $match['target']);
            if (is_callable(array($controller, $action))) {
                $obj = new $controller();
                call_user_func_array(array($obj, $action), array($match['params']));
            } else {
                throw new \Exception($error->500());
            }
        }
</code>```

PostController.php

```<code>public function find($args)
    {
        $post = $this->PostModal->find($args[id]);
        // View
        View::render('post/show', compact('post'));
    }
</code>```

My class View.php which manages the views

```<code>public static function render(string $path, array $variables = [])
    {
        extract($variables);
        ob_start();

        require 'views/' . $path . '.html.php';
        $pageContent = ob_get_clean();

        require 'views/layouts/layout.html.php';
    }
</code>```

答:
If you have the same problem as me, I resolved by adding

```<code>global $router;
</code>```

in the render

Body:
I'm new to php, I would like to have access to the $router instance in my views so that I can use the route names with $router->generate() in the view but I don't know how to do it?
I use Altorouter like this:

Index.php

$router = new AltoRouter();
$router->map( 'GET', '/post/[:id]/', 'PostController#find' );
$match = $router->match();

        if ($match === false) {
            throw new \Exception($error->404());
        } else {
            list($controller, $action) = explode('#', $match['target']);
            if (is_callable(array($controller, $action))) {
                $obj = new $controller();
                call_user_func_array(array($obj, $action), array($match['params']));
            } else {
                throw new \Exception($error->500());
            }
        }

PostController.php

public function find($args)
    {
        $post = $this->PostModal->find($args[id]);
        // View
        View::render('post/show', compact('post'));
    }

My class View.php which manages the views

public static function render(string $path, array $variables = [])
    {
        extract($variables);
        ob_start();

        require 'views/' . $path . '.html.php';
        $pageContent = ob_get_clean();

        require 'views/layouts/layout.html.php';
    }

Body:
If you have the same problem as me, I resolved by adding

global $router;

in the render


问:
in akka-http, how to match a path segment with an optional end slash?
this path directive of akka http matches /hello

```<code>lazy val userRoutes: Route = cors() {
  path(Segment) { p => ... }
</code>```

how can I match both /hello and /hello/ (optional end slash)?

After reading the doc https://doc.akka.io/docs/akka-http/current/routing-dsl/directives/path-directives/index.html#pathdirectives
I've tried as follows, but it does not compile:

```<code>lazy val userRoutes: Route = cors() {
  rawPathPrefix(Slash ~ Segment ~ pathEndOrSingleSlash) { p => ... }
</code>```

答:
Akka-Http provides path directives using which you can solve the following.

```<code>val route =
  pathPrefix("hello") {
    pathEndOrSingleSlash {
      complete("/hello")
    }
  }
</code>```

https://doc.akka.io/docs/akka-http/current/routing-dsl/directives/path-directives/pathEndOrSingleSlash.html

Body:
this path directive of akka http matches /hello

lazy val userRoutes: Route = cors() {
  path(Segment) { p => ... }

how can I match both /hello and /hello/ (optional end slash)?

After reading the doc https://doc.akka.io/docs/akka-http/current/routing-dsl/directives/path-directives/index.html#pathdirectives
I've tried as follows, but it does not compile:

lazy val userRoutes: Route = cors() {
  rawPathPrefix(Slash ~ Segment ~ pathEndOrSingleSlash) { p => ... }

Body:
Akka-Http provides path directives using which you can solve the following.

val route =
  pathPrefix("hello") {
    pathEndOrSingleSlash {
      complete("/hello")
    }
  }

https://doc.akka.io/docs/akka-http/current/routing-dsl/directives/path-directives/pathEndOrSingleSlash.html


问:
Getting pdf data from cloudinary and saving it in flutter
I have been using cloudinary to store my pdf files the use firebase as my backend. However, am having this issue with it. When I use http.get on the link provided by cloudinary https://res.cloudinary.com/cloudname/raw/upload/vxxxxxxxxxxx/xxxxxxxxxxxxxxxxxxxx I get ascii data instead of the pdf file. I have tried to write the data as string to a file with .pdf extension that has not worked. I have tried to convert it to bytes then write to the file as bytes and that has not worked either. Any help on how I can save this file on android using flutter It would be a great help.

```<code>    await http.post('https://api.cloudinary.com/v1_1/${DotEnv().env['cloud_name']}/raw/upload',body: { "file": "data:raw/pdf;base64,$pdf", "upload_preset": DotEnv().env['upload_preset']} );
    var response = await http.get('https://res.cloudinary.com/<cloudname>/raw/upload/v1590958359/gsvxe4zp7bb6yyldrccu');
    final directory = await getApplicationDocumentsDirectory();
    final path2 = directory.path;

    File x = File('$path2/trial.pdf');
    x.writeAsString(response.body);
</code>```

Here is the code as I currently have it. pdf in this case is the base64 encoding of the pdf. The link I have here in http.get is from a file I had already uploaded.

答:
Thanks for adding the additional details.

Firstly, I would recommend you change the resource_type from raw to image. In addition, please update the MIME type in your Base64 Data URI to application/pdf.

The URL you then get from Cloudinary upon a successful upload will be to a PDF resource which means you can download it with a simple cURL request or via any HTTP library.

For example, using the secure_url to the asset returned in the Upload API Response to download the file to my_test_file.pdf -

```<code>curl -s https://res.cloudinary.com/demo/image/upload/multi_page_pdf.pdf --output my_test_file.pdf
</code>```

Body:
I have been using cloudinary to store my pdf files the use firebase as my backend. However, am having this issue with it. When I use http.get on the link provided by cloudinary https://res.cloudinary.com/cloudname/raw/upload/vxxxxxxxxxxx/xxxxxxxxxxxxxxxxxxxx I get ascii data instead of the pdf file. I have tried to write the data as string to a file with .pdf extension that has not worked. I have tried to convert it to bytes then write to the file as bytes and that has not worked either. Any help on how I can save this file on android using flutter It would be a great help.

    await http.post('https://api.cloudinary.com/v1_1/${DotEnv().env['cloud_name']}/raw/upload',body: { "file": "data:raw/pdf;base64,$pdf", "upload_preset": DotEnv().env['upload_preset']} );
    var response = await http.get('https://res.cloudinary.com/<cloudname>/raw/upload/v1590958359/gsvxe4zp7bb6yyldrccu');
    final directory = await getApplicationDocumentsDirectory();
    final path2 = directory.path;

    File x = File('$path2/trial.pdf');
    x.writeAsString(response.body);

Here is the code as I currently have it. pdf in this case is the base64 encoding of the pdf. The link I have here in http.get is from a file I had already uploaded.

Body:
Thanks for adding the additional details.

Firstly, I would recommend you change the resource_type from raw to image. In addition, please update the MIME type in your Base64 Data URI to application/pdf.

The URL you then get from Cloudinary upon a successful upload will be to a PDF resource which means you can download it with a simple cURL request or via any HTTP library.

For example, using the secure_url to the asset returned in the Upload API Response to download the file to my_test_file.pdf -

curl -s https://res.cloudinary.com/demo/image/upload/multi_page_pdf.pdf --output my_test_file.pdf


问:
Javascript context issue using Object.create() and function.apply doesn't seem to work?

I am running into the error with object context when trying to use Object.create.  This is a very simple example, but this is what I am doing:

```<code>var object1 = {
func1: function(functionArg){
    ...
    functionArg();
}
}

var object2 = {
func2: {
    value: function(){
        this.memberVariable = 1;
        ...
        this.func1(this.func3)
    }
}

func3: {
    value: function(){
        if(this.memberVariable == 1){};
        ...
    }
}
}

var newObject = Object.create(object1,object2);
newObject.func2();
</code>```

The Result of expression 'this.memberVariable' [undefined] is not an object.

To remember this problem, I thought that I could use apply to give the correct context to the function.  So I replaced object1 with something like:

```<code>var object1 = {
func1: function(functionArg){
    var thisObject = this;
    var functionArgApply = function(){
        functionArg.apply(thisObject,arguments);
    };
    ...
    functionArgApply();
}
}
</code>```

Now I get an error saying Result of expression 'functionArg.apply' [undefined] is not a function.  I assume that's because object2 is using value notation.  I tried changing it to functionArg.value.apply but got the same result.  Should this work?

答:
Either functionArg is a string, in which case you have to use bracket notation:

```<code>func1: function(functionArg){
    ...
    this[functionArg]();
}
</code>```

or it is a function reference, which case it should be

```<code>functionArg.apply(this)
</code>```

It depends on what func3 is in this line: this.func1(func3). As it stands, func3 is not defined.

In any case, this.functionArg is wrong, you have no property functionArg defined anywhere.

ContentLicense: CC BY-SA 3.0

Body:
I am running into the error with object context when trying to use Object.create.  This is a very simple example, but this is what I am doing:

var object1 = {
func1: function(functionArg){
    ...
    functionArg();
}
}

var object2 = {
func2: {
    value: function(){
        this.memberVariable = 1;
        ...
        this.func1(this.func3)
    }
}

func3: {
    value: function(){
        if(this.memberVariable == 1){};
        ...
    }
}
}

var newObject = Object.create(object1,object2);
newObject.func2();

The Result of expression 'this.memberVariable' [undefined] is not an object.

To remember this problem, I thought that I could use apply to give the correct context to the function.  So I replaced object1 with something like:

var object1 = {
func1: function(functionArg){
    var thisObject = this;
    var functionArgApply = function(){
        functionArg.apply(thisObject,arguments);
    };
    ...
    functionArgApply();
}
}

Now I get an error saying Result of expression 'functionArg.apply' [undefined] is not a function.  I assume that's because object2 is using value notation.  I tried changing it to functionArg.value.apply but got the same result.  Should this work?

Body:
Either functionArg is a string, in which case you have to use bracket notation:

func1: function(functionArg){
    ...
    this[functionArg]();
}

or it is a function reference, which case it should be

functionArg.apply(this)

It depends on what func3 is in this line: this.func1(func3). As it stands, func3 is not defined.

In any case, this.functionArg is wrong, you have no property functionArg defined anywhere.


问:
Are always all Data Fields of the Built-In Topics sent according to the DDS/RTPS Specification?
I'm trying to understand the RTPS and DDS Specification a bit better.

The RTPS Specification talks about "data changes" and how they are propagated, but does not exactly specify "what" is propagated (as in does it know what is transmitted and sends only the changes, or does it see the data as black box and always sends the whole thing). Now I assume that this is implementation specific.

But I want to know what behavior is dictated specifically for the built-in Topics.
The DDS Specification defines the Data Types (i.e. the Data Field Names, Type, and meaning) of several built-in Topics. Can we assume that if a single Data field is changed, all other unchanged Data Fields are also sent?

答:
The RTPS Specification talks about "data changes" and how they are
  propagated, but does not exactly specify "what" is propagated

Although it may not be immediately apparent, the RTPS specification does exactly specify what is propagated, in "Chapter 10 Serialized Payload Representation". It mentions the different standardized types of representations like CDR and CDR2 which have several variations including big endian and little endian versions. None of these formats are implementation specific, because that would hamper the desired interoperability between different DDS implementations.

The details of the formats are further explained in the DDS-XTYPES specification, specifically section 7.4 which is referenced in several places in that Chapter 10 that I mentioned. On its turn, the XTypes spec references some older specification that defines CDR.

That said, it is complicated to read through all those specs so let me answer your other question

Can we assume that if a single Data field is changed, all other
  unchanged Data Fields are also sent?

That is mostly correct. Updates to DDS data, for both built-in types as well as user-defined types, are done with all the fields communicated "atomically". This means that receivers of the updates will not have to worry about maintaining some kind of state to which some partial updates have to be applied to determine the actual current state.

However, an exception to this are values that are defined as "optional". The reason for this is not so much because those values have not changed since the previous update, but because those fields are considered non-mandatory. <s>As far as I know, the built-in types do not have such optional fields defined.</s> Indeed XTypes Annex D: DDS Built-in Topic Data Types has updated the built-in Topics definitions and includes some optional fields.

Also, some of the encodings allow omission of values if they are equal to the specified default value. In this case too, it is not the "unchanged" aspect that causes the omission(s), but the fact that they are equal to the default value.

Sometimes the approach of atomic updates poses a concern, typically when certain fields in a type are updated much more frequently than others. This is usually a sign that the data model has not been designed in the right way.

The built-in Topics specifically that you mention do not have this problem though. They are not expected to be updated frequently, if at all.


问:
Why does setting leading and trailing anchor does not work but width does?
I can't figure out why setting leading and trailing anchor to a view does not work, but when I set width it does work.
I have a UIStackView inside a UIScrollView, this is how I set my UIScrollView:

```<code>private func setupScrollView() {
    addSubview(scrollView)
    NSLayoutConstraint.activate([
        scrollView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
        scrollView.trailingAnchor.constraint(equalTo: self.trailingAnchor),
        scrollView.topAnchor.constraint(equalTo: backButton.bottomAnchor),
        scrollView.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor),
    ])
}
</code>```

and this is how I set my UIStackView:

```<code>        private func setupTextfieldsStack() {
        scrollView.addSubview(textfieldsStack)
        let height = UIScreen.main.bounds.height * 0.35
        NSLayoutConstraint.activate([
            textfieldsStack.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 16),
            textfieldsStack.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: -16),
            textfieldsStack.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 8),
            textfieldsStack.heightAnchor.constraint(equalToConstant: height)
        ])
    }
</code>```

For some reason, the UIStackView only takes about half of the screen, but, when changing scrollView.leading to self.leading and for the trailing as well, that does work, and the UIStackView gets stretched to fit almost the full width of the screen.
Setting the width to be 0.95 of the UIScreen bounds also works.

So, my question is, why when I use self it does work but scrollView does not?
I do call setupScrollView before setupTextfieldsStack and the scrollView renders correctly.

答:
When setting up constraints between a scroll view and its subviews, these constraints will, by default, be used to calculate the contentSize of the scroll view (i.e. to define the scrolling behavior), but does not place any constraint the size of the subview.

In Technical Note TN2154, they say:

In general, Auto Layout considers the top, left, bottom, and right edges of a view to be the visible edges. That is, if you pin a view to the left edge of its superview, you’re really pinning it to the minimum x-value of the superview’s bounds. Changing the bounds origin of the superview does not change the position of the view.

The UIScrollView class scrolls its content by changing the origin of its bounds. To make this work with Auto Layout, the top, left, bottom, and right edges within a scroll view now mean the edges of its content view.

The constraints on the subviews of the scroll view must result in a size to fill, which is then interpreted as the content size of the scroll view. (This should not be confused with the intrinsicContentSize method used for Auto Layout.) To size the scroll view’s frame with Auto Layout, constraints must either be explicit regarding the width and height of the scroll view, or the edges of the scroll view must be tied to views outside of its subtree.

Note that you can make a subview of the scroll view appear to float (not scroll) over the other scrolling content by creating constraints between the view and a view outside the scroll view’s subtree, such as the scroll view’s superview.

That advice of solving this problem by adding constraints between the scroll view’s subviews and “a view outside the scroll view’s subtree” is a little out of date. In iOS 9, they introduced some layout guides that solve this problem, namely the contentLayoutGuide and the frameLayoutGuide. The former is used to define the scroll view’s contentSize (i.e. the scrolling behavior) and the latter is used to define the subview’s frame relative to that of the scroll view.

So, when adding subviews to a scroll view, you generally want to set all four top, bottom, leading, and trailing constraints to the scroll view’s contentLayoutGuide (so it scrolls correctly). Then define the leading and trailing anchors to the scroll view’s frameLayoutGuide (to ensure the subview has the appropriate width):

```<code>NSLayoutConstraint.activate([
    textfieldsStack.leadingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.leadingAnchor, constant: 16),
    textfieldsStack.trailingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.trailingAnchor, constant: -16),
    textfieldsStack.topAnchor.constraint(equalTo: scrollView.contentLayoutGuide.topAnchor, constant: 8),
    textfieldsStack.bottomAnchor.constraint(equalTo: scrollView.contentLayoutGuide.bottomAnchor, constant: -8),

    textfieldsStack.leadingAnchor.constraint(equalTo: scrollView.frameLayoutGuide.leadingAnchor, constant: 16),
    textfieldsStack.trailingAnchor.constraint(equalTo: scrollView.frameLayoutGuide.trailingAnchor, constant: -16)
])
</code>```

Body:
I can't figure out why setting leading and trailing anchor to a view does not work, but when I set width it does work.
I have a UIStackView inside a UIScrollView, this is how I set my UIScrollView:

private func setupScrollView() {
    addSubview(scrollView)
    NSLayoutConstraint.activate([
        scrollView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
        scrollView.trailingAnchor.constraint(equalTo: self.trailingAnchor),
        scrollView.topAnchor.constraint(equalTo: backButton.bottomAnchor),
        scrollView.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor),
    ])
}

and this is how I set my UIStackView:

        private func setupTextfieldsStack() {
        scrollView.addSubview(textfieldsStack)
        let height = UIScreen.main.bounds.height * 0.35
        NSLayoutConstraint.activate([
            textfieldsStack.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 16),
            textfieldsStack.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor, constant: -16),
            textfieldsStack.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 8),
            textfieldsStack.heightAnchor.constraint(equalToConstant: height)
        ])
    }

For some reason, the UIStackView only takes about half of the screen, but, when changing scrollView.leading to self.leading and for the trailing as well, that does work, and the UIStackView gets stretched to fit almost the full width of the screen.
Setting the width to be 0.95 of the UIScreen bounds also works.

So, my question is, why when I use self it does work but scrollView does not?
I do call setupScrollView before setupTextfieldsStack and the scrollView renders correctly.

Body:
When setting up constraints between a scroll view and its subviews, these constraints will, by default, be used to calculate the contentSize of the scroll view (i.e. to define the scrolling behavior), but does not place any constraint the size of the subview.

In Technical Note TN2154, they say:

In general, Auto Layout considers the top, left, bottom, and right edges of a view to be the visible edges. That is, if you pin a view to the left edge of its superview, you’re really pinning it to the minimum x-value of the superview’s bounds. Changing the bounds origin of the superview does not change the position of the view.

The UIScrollView class scrolls its content by changing the origin of its bounds. To make this work with Auto Layout, the top, left, bottom, and right edges within a scroll view now mean the edges of its content view.

The constraints on the subviews of the scroll view must result in a size to fill, which is then interpreted as the content size of the scroll view. (This should not be confused with the intrinsicContentSize method used for Auto Layout.) To size the scroll view’s frame with Auto Layout, constraints must either be explicit regarding the width and height of the scroll view, or the edges of the scroll view must be tied to views outside of its subtree.

Note that you can make a subview of the scroll view appear to float (not scroll) over the other scrolling content by creating constraints between the view and a view outside the scroll view’s subtree, such as the scroll view’s superview.

That advice of solving this problem by adding constraints between the scroll view’s subviews and “a view outside the scroll view’s subtree” is a little out of date. In iOS 9, they introduced some layout guides that solve this problem, namely the contentLayoutGuide and the frameLayoutGuide. The former is used to define the scroll view’s contentSize (i.e. the scrolling behavior) and the latter is used to define the subview’s frame relative to that of the scroll view.

So, when adding subviews to a scroll view, you generally want to set all four top, bottom, leading, and trailing constraints to the scroll view’s contentLayoutGuide (so it scrolls correctly). Then define the leading and trailing anchors to the scroll view’s frameLayoutGuide (to ensure the subview has the appropriate width):

NSLayoutConstraint.activate([
    textfieldsStack.leadingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.leadingAnchor, constant: 16),
    textfieldsStack.trailingAnchor.constraint(equalTo: scrollView.contentLayoutGuide.trailingAnchor, constant: -16),
    textfieldsStack.topAnchor.constraint(equalTo: scrollView.contentLayoutGuide.topAnchor, constant: 8),
    textfieldsStack.bottomAnchor.constraint(equalTo: scrollView.contentLayoutGuide.bottomAnchor, constant: -8),

    textfieldsStack.leadingAnchor.constraint(equalTo: scrollView.frameLayoutGuide.leadingAnchor, constant: 16),
    textfieldsStack.trailingAnchor.constraint(equalTo: scrollView.frameLayoutGuide.trailingAnchor, constant: -16)
])


问:
Why is "cursor:pointer" effect in CSS not working
I set cursor: pointer for .about > span, but when my mouse hovers on those texts in , the cursor does not change into pointer mode. I would like to know why it is not working.

HTML:

```<code> <div id="firstdiv">
      <div id="intro">
          <h1 id="name">YOU CHIA LAI</h1>
              <ul>
                  <li class="about">I am a Master of <span>Architecture</span>
                   candidate at Rice University.
                  </li>
                  <li class="about">I am also interested in <span>photography</span> &
                  <span>web design</span>.</li>
                  <li class="about">I wish you can know more <span>about</span> me.
                  </li>
             </ul>
      </div>
  </div>
</code>```

CSS:

```<code>#firstdiv {
    position:fixed;
    top:0;
    left:0;
    right:0;
    height:100%;
    width:100%;
    margin:auto;
    background:#E6E6E6;
    text-align:center;
    font-size:0;
    z-index:-2
}
.about > span {
    cursor:pointer;
    font-family:Eurofurence Light;
    padding:0 0 3px 0;
    color:#01DFA5;
}
</code>```

答:
The solution that worked for me is using forward slash instead of backslash when 'calling' out from a local directory.

instead of backslash:

cursor: url("C:\Users\Ken\projects\JavascriptGames\images\bird.png"), auto;```
</div>
</div>

Note: When I use backslash I am getting a net::ERR_FILE_NOT_FOUND </p>

<p>I changed it to forwardslash:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>cursor: url("C:/Users/Ken/projects/JavascriptGames/images/bird.png"), auto;</code>```

Note: When I use forward slash, the custom cursor style executes successfully.

This behavior regarding backslashes and forward slashes could probably be explained in this StackOverflow answer: Strange backslash and behavior in CSS

Body:
I set cursor: pointer for .about > span, but when my mouse hovers on those texts in , the cursor does not change into pointer mode. I would like to know why it is not working.

HTML:

YOU CHIA LAI

I am a Master of Architecture
                   candidate at Rice University.

I am also interested in photography &
                  web design.

I wish you can know more about me.

CSS:

#firstdiv {
    position:fixed;
    top:0;
    left:0;
    right:0;
    height:100%;
    width:100%;
    margin:auto;
    background:#E6E6E6;
    text-align:center;
    font-size:0;
    z-index:-2
}
.about > span {
    cursor:pointer;
    font-family:Eurofurence Light;
    padding:0 0 3px 0;
    color:#01DFA5;
}

Body:
The solution that worked for me is using forward slash instead of backslash when 'calling' out from a local directory.

instead of backslash:

cursor: url("C:\Users\Ken\projects\JavascriptGames\images\bird.png"), auto;

Note: When I use backslash I am getting a net::ERR_FILE_NOT_FOUND

I changed it to forwardslash:

cursor: url("C:/Users/Ken/projects/JavascriptGames/images/bird.png"), auto;

Note: When I use forward slash, the custom cursor style executes successfully.

This behavior regarding backslashes and forward slashes could probably be explained in this StackOverflow answer: Strange backslash and behavior in CSS


问:
Running Home Assistant (HASSIO) locally without an internet connection
I am new to Home Assistant and I currently have a disc image of the software installed on a Raspberry Pi 3b. I have managed to get this up and running successfully by connecting my PI to an internet connection via an ethernet cable and connecting my laptop to the same network wirelessly. The problem I am facing is that I wish to run this locally without an internet connection and simply connecting my laptop to the PI with the Ethernet cable does not seem to be working. I have tried looking around for support but I cannot seem to find much on the matter. </p>

答:
Home Assistant's default port is 8123 not 8023.

If there is a direct connection between your laptop and the Raspberry Pi then the chance is high that mDNS won't not work. Thus, homeassistant.local is not reachable.

Add a static IP address for your Home Assistant host and your laptop.


问:
How to get pass this error "Value cannot be null. Parameter name: entity"
```<code>        private void button1_Click(object sender, EventArgs e)
    {

        DataClasses1DataContext dc = new DataClasses1DataContext();
        var rec = dc.reportsSents.FirstOrDefault();
        int rowCount = dc.reportsSents.Count();

        if (rec != null)
            {

            for(int i = 0; i <= rowCount;)
                {

                    var matchedCaseNumber = (from CaseNumberKey in dc.GetTable<reportsSent>()
                                     select CaseNumberKey).FirstOrDefault();

                    (new MyReportRenderer()).RenderTest(Convert.ToString(matchedCaseNumber));

                    dc.reportsSents.DeleteOnSubmit(matchedCaseNumber);
                    dc.SubmitChanges();

                    i = (i +1);

                }

             }
</code>```

When the code above is executed I get this error:

Value cannot be null. Parameter name:
  entity

and matchedCaseNumber is highlighted in this line:

dc.reportsSents.DeleteOnSubmit(matchedCaseNumber);

What does this mean and why am I getting it.  What I am trying to do is pass MatchedCaseNumber to the method and then delete it after the method is executed and then step through the table.  Any help would be appreciated.

Thanks.

答:
You have

```<code>var matchedCaseNumber = (...).FirstOrDefault();

dc.reportsSents.DeleteOnSubmit(matchedCaseNumber);
</code>```

So what if matchedCaseNumber is null?  The OrDefault makes that possible.

Change that 2nd line into:

```<code>if (matchedCaseNumber != null)
    dc.reportsSents.DeleteOnSubmit(matchedCaseNumber);
</code>```

Also,

```<code>int rowCount = dc.reportsSents.Count();

for(int i = 0; i <= rowCount;)
{
   ...
   i = (i +1);
}
</code>```

should probably become:

```<code>for(int i = 0; i < rowCount; i += 1)  // note: NOT <=
{
    ...
}
</code>```

You are looping rowCount+1 times. And there really is no point in moving the increment of i out of the loop statement. Don't confuse/hinder opitimizers.

Body:
        private void button1_Click(object sender, EventArgs e)
    {

        DataClasses1DataContext dc = new DataClasses1DataContext();
        var rec = dc.reportsSents.FirstOrDefault();
        int rowCount = dc.reportsSents.Count();

        if (rec != null)
            {

            for(int i = 0; i <= rowCount;)
                {

                    var matchedCaseNumber = (from CaseNumberKey in dc.GetTable<reportsSent>()
                                     select CaseNumberKey).FirstOrDefault();

                    (new MyReportRenderer()).RenderTest(Convert.ToString(matchedCaseNumber));

                    dc.reportsSents.DeleteOnSubmit(matchedCaseNumber);
                    dc.SubmitChanges();

                    i = (i +1);

                }

             }

When the code above is executed I get this error:

Value cannot be null. Parameter name:
  entity

and matchedCaseNumber is highlighted in this line:

dc.reportsSents.DeleteOnSubmit(matchedCaseNumber);

What does this mean and why am I getting it.  What I am trying to do is pass MatchedCaseNumber to the method and then delete it after the method is executed and then step through the table.  Any help would be appreciated.

Thanks.

Body:
You have

var matchedCaseNumber = (...).FirstOrDefault();

dc.reportsSents.DeleteOnSubmit(matchedCaseNumber);

So what if matchedCaseNumber is null?  The OrDefault makes that possible.

Change that 2nd line into:

if (matchedCaseNumber != null)
    dc.reportsSents.DeleteOnSubmit(matchedCaseNumber);

Also,

int rowCount = dc.reportsSents.Count();

for(int i = 0; i <= rowCount;)
{
   ...
   i = (i +1);
}

should probably become:

for(int i = 0; i < rowCount; i += 1)  // note: NOT <=
{
    ...
}

You are looping rowCount+1 times. And there really is no point in moving the increment of i out of the loop statement. Don't confuse/hinder opitimizers.


问:
MongoDB findOne funtion returns null when comparing with id
I am using the following code to get the details of a user when I pass their id as a parameter:

```<code>   server.get("/users/:id", (req, res) => {
        const itemId = req.params.id;

        dbCollection.findOne({ _id: itemId }, (error, result) => {
            if (error) throw error;
            // return item
            res.json(result);
        });
    });
</code>```

However, this doesn't seem to work, as whenever I run the code, I get returned with a null value.
My question is not the same as many previously asked questions because I have ObjectId('randomId') as my id, and not a string. How can I fix my code?

答:
req.params.id comes as a string while your _id is an ObjectId so this won't work since MongoDB requires type equality first, you need to cast the value:

```<code>const itemId = mongoose.Types.ObjectId(req.params.id);
</code>```

Body:
I am using the following code to get the details of a user when I pass their id as a parameter:

   server.get("/users/:id", (req, res) => {
        const itemId = req.params.id;

        dbCollection.findOne({ _id: itemId }, (error, result) => {
            if (error) throw error;
            // return item
            res.json(result);
        });
    });

However, this doesn't seem to work, as whenever I run the code, I get returned with a null value.
My question is not the same as many previously asked questions because I have ObjectId('randomId') as my id, and not a string. How can I fix my code?

Body:
req.params.id comes as a string while your _id is an ObjectId so this won't work since MongoDB requires type equality first, you need to cast the value:

const itemId = mongoose.Types.ObjectId(req.params.id);


问:
Unable to import AWS infrastructure configurartion using terraformer
I am trying to import existing AWS infra configuration using google's terraformer and I am unsuccessful due to AWS provider authentication problem. My AWS credentials are MFA enabled and hence i have to use session token.  I failed to find options to enable terraformer to use aws session token params. </p>

<p>Here is the debug logs for the terraformer program.  Could someone help me with this please.  The below is generating empty tf files and states. </p>

```<code>Master $ terraformer import aws --resources=vpc  --regions=eu-central-1 -c -v
2020/06/02 23:17:53 aws importing region eu-central-1
2020/06/02 23:17:53 aws importing... vpc
2020-06-02T23:17:53.525+0530 [INFO]  plugin: configuring client automatic mTLS
2020-06-02T23:17:53.593+0530 [DEBUG] plugin: starting plugin: path=.terraform/plugins/darwin_amd64/terraform-provider-aws_v2.64.0_x4 args=[.terraform/plugins/darwin_amd64/terraform-provider-aws_v2.64.0_x4]
2020-06-02T23:17:53.597+0530 [DEBUG] plugin: plugin started: path=.terraform/plugins/darwin_amd64/terraform-provider-aws_v2.64.0_x4 pid=47500
2020-06-02T23:17:53.597+0530 [DEBUG] plugin: waiting for RPC address: path=.terraform/plugins/darwin_amd64/terraform-provider-aws_v2.64.0_x4
2020-06-02T23:17:54.254+0530 [INFO]  plugin.terraform-provider-aws_v2.64.0_x4: configuring server automatic mTLS: timestamp=2020-06-02T23:17:54.253+0530
2020-06-02T23:17:54.329+0530 [DEBUG] plugin: using plugin: version=5
2020-06-02T23:17:54.329+0530 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4: plugin address: network=unix address=/var/folders/jj/2w6phyrs1fj68ks7ry714z000000gn/T/plugin871781403 timestamp=2020-06-02T23:17:54.328+0530
2020-06-02T23:17:54.586+0530 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4: 2020/06/02 23:17:54 [INFO] No assume_role block read from configuration
2020-06-02T23:17:54.586+0530 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4: 2020/06/02 23:17:54 [INFO] Building AWS auth structure
2020-06-02T23:17:54.586+0530 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4: 2020/06/02 23:17:54 [INFO] Setting AWS metadata API timeout to 100ms
2020-06-02T23:17:56.003+0530 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4: 2020/06/02 23:17:55 [INFO] Ignoring AWS metadata API endpoint at default location as it doesn't return any instance-id
2020-06-02T23:17:56.010+0530 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4: 2020/06/02 23:17:56 [INFO] AWS Auth provider used: "EnvProvider"
2020-06-02T23:17:56.013+0530 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4: 2020/06/02 23:17:56 [DEBUG] Trying to get account information via sts:GetCallerIdentity
2020-06-02T23:17:57.577+0530 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4: 2020/06/02 23:17:57 [DEBUG] Trying to get account information via sts:GetCallerIdentity
2020-06-02T23:17:59.652+0530 [DEBUG] plugin: plugin process exited: path=.terraform/plugins/darwin_amd64/terraform-provider-aws_v2.64.0_x4 pid=47500
2020-06-02T23:17:59.652+0530 [DEBUG] plugin: plugin exited
2020/06/02 23:17:59 aws Connecting....
2020/06/02 23:17:59 aws save vpc
2020/06/02 23:17:59 aws save tfstate for vpc
</code>```

答:
I managed to resolve the problem by explicitily setting the environment variable AWS_SHARED_CREDENTIALS_FILE=~/.aws/credential

Without the above additional env my setup failed.

Body:
I am trying to import existing AWS infra configuration using google's terraformer and I am unsuccessful due to AWS provider authentication problem. My AWS credentials are MFA enabled and hence i have to use session token.  I failed to find options to enable terraformer to use aws session token params.

Here is the debug logs for the terraformer program.  Could someone help me with this please.  The below is generating empty tf files and states.

Master $ terraformer import aws --resources=vpc  --regions=eu-central-1 -c -v
2020/06/02 23:17:53 aws importing region eu-central-1
2020/06/02 23:17:53 aws importing... vpc
2020-06-02T23:17:53.525+0530 [INFO]  plugin: configuring client automatic mTLS
2020-06-02T23:17:53.593+0530 [DEBUG] plugin: starting plugin: path=.terraform/plugins/darwin_amd64/terraform-provider-aws_v2.64.0_x4 args=[.terraform/plugins/darwin_amd64/terraform-provider-aws_v2.64.0_x4]
2020-06-02T23:17:53.597+0530 [DEBUG] plugin: plugin started: path=.terraform/plugins/darwin_amd64/terraform-provider-aws_v2.64.0_x4 pid=47500
2020-06-02T23:17:53.597+0530 [DEBUG] plugin: waiting for RPC address: path=.terraform/plugins/darwin_amd64/terraform-provider-aws_v2.64.0_x4
2020-06-02T23:17:54.254+0530 [INFO]  plugin.terraform-provider-aws_v2.64.0_x4: configuring server automatic mTLS: timestamp=2020-06-02T23:17:54.253+0530
2020-06-02T23:17:54.329+0530 [DEBUG] plugin: using plugin: version=5
2020-06-02T23:17:54.329+0530 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4: plugin address: network=unix address=/var/folders/jj/2w6phyrs1fj68ks7ry714z000000gn/T/plugin871781403 timestamp=2020-06-02T23:17:54.328+0530
2020-06-02T23:17:54.586+0530 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4: 2020/06/02 23:17:54 [INFO] No assume_role block read from configuration
2020-06-02T23:17:54.586+0530 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4: 2020/06/02 23:17:54 [INFO] Building AWS auth structure
2020-06-02T23:17:54.586+0530 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4: 2020/06/02 23:17:54 [INFO] Setting AWS metadata API timeout to 100ms
2020-06-02T23:17:56.003+0530 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4: 2020/06/02 23:17:55 [INFO] Ignoring AWS metadata API endpoint at default location as it doesn't return any instance-id
2020-06-02T23:17:56.010+0530 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4: 2020/06/02 23:17:56 [INFO] AWS Auth provider used: "EnvProvider"
2020-06-02T23:17:56.013+0530 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4: 2020/06/02 23:17:56 [DEBUG] Trying to get account information via sts:GetCallerIdentity
2020-06-02T23:17:57.577+0530 [DEBUG] plugin.terraform-provider-aws_v2.64.0_x4: 2020/06/02 23:17:57 [DEBUG] Trying to get account information via sts:GetCallerIdentity
2020-06-02T23:17:59.652+0530 [DEBUG] plugin: plugin process exited: path=.terraform/plugins/darwin_amd64/terraform-provider-aws_v2.64.0_x4 pid=47500
2020-06-02T23:17:59.652+0530 [DEBUG] plugin: plugin exited
2020/06/02 23:17:59 aws Connecting....
2020/06/02 23:17:59 aws save vpc
2020/06/02 23:17:59 aws save tfstate for vpc


问:
Swift validation allow all alphabets letters but no special characters or numbers
I have a TextField and I want users to type only letters, English, German, French, Cyrillic etc... alphabets, but no numbers or special characters(emojis). Spaces are allowed. How can I achieve this?

```<code>TextField("First Name", text: $firstName, onEditingChanged: { change in
    // validate
})
</code>```

I have seen a lot of similar questions but they take care only of English alphabets.

```<code>extension String {
    var containsLetters : Bool {
        let lettersAndSpaces = CharacterSet.letters.union(CharacterSet.whitespaces)
        return self.rangeOfCharacter(from: lettersAndSpaces) != nil
    }
}
</code>```

答:
What about CharacterSet?

You can use the existing one for letters and combine it with another that has spaces. https://developer.apple.com/documentation/foundation/characterset/1780390-letters

Then you can check your string with rangeOfCharacter(from:): https://developer.apple.com/documentation/foundation/nsstring/1411930-rangeofcharacter

Body:
I have a TextField and I want users to type only letters, English, German, French, Cyrillic etc... alphabets, but no numbers or special characters(emojis). Spaces are allowed. How can I achieve this?

TextField("First Name", text: $firstName, onEditingChanged: { change in
    // validate
})

I have seen a lot of similar questions but they take care only of English alphabets.

extension String {
    var containsLetters : Bool {
        let lettersAndSpaces = CharacterSet.letters.union(CharacterSet.whitespaces)
        return self.rangeOfCharacter(from: lettersAndSpaces) != nil
    }
}


问:
How to catch click event with addEventListener
I am having a modal with button inside. Unfortunatly, it's not properly working. During the build I got an error : TypeError: Cannot read property 'addEventListener' of null

Below is the code:

```<code>import React from "react";
import { Modal } from "react-bootstrap";
import '../../assets/styles/Login.css';

class LoginRegisterModal extends React.Component {
    constructor(props, context) {
        super(props);
        this.state = {show: false};
    }

    componentDidMount(){
      const signUpButton = document.getElementById('signUp');
      const signInButton = document.getElementById('signIn');
      const container = document.getElementById('container');

      signUpButton.addEventListener('click', () => {
        container.classList.add('right-panel-active');
      });

      signInButton.addEventListener('click', () => {
        container.classList.remove('right-panel-active');
      });
    }

    ....
    render() {

        const styleModal = {
            marginTop: "15%",
            marginLeft: "30%",
            padding: 0,
            width:770,
            height:480,
            backgroundColor:"#ffffffff",
            borderRadius:21.5,
        }

        return (
        <Modal show={this.state.show} style={styleModal} >
          <div class="container" id="container">
            <div>
            .....
            </div>
            <div class="overlay-container">
              <div class="overlay">
                <div class="overlay-panel overlay-left">
                    <h1>Sign in.</h1>
                    <p>
                      Nice to see you again.Login and continue the journey.
                    </p>
                    <button class="ghost" id="signIn">Sign In</button>
                </div>
                <div class="overlay-panel overlay-right">
                    <h1>Hey, new friend!</h1>
                    <p>New to the Village? Sign up and start your journey</p>
                    <button class="ghost" id="signUp">Sign Up</button>
                </div>
              </div>
            </div>
          </div>
        </Modal>
        );
    }
}

export default LoginRegisterModal;
</code>```

I have tried adding a if condition before the addListener but it's just fixing the error but not working.

Also I have tried to replace by onClick instead but it's not working the code

```<code>    signUpButton = () => {
        container.classList.add('right-panel-active');
    }
</code>```

but container is not known..

Any idea?

Thanks

答: Your code should be inside component did mount method componentDidMount(). That's because when you look for a element with id "signUp" it doesn't exist yet. I don't encourage you to do what you are doing. A better approach would be <button onClick={myMethod}>

Body:
I am having a modal with button inside. Unfortunatly, it's not properly working. During the build I got an error : TypeError: Cannot read property 'addEventListener' of null

Below is the code:

import React from "react";
import { Modal } from "react-bootstrap";
import '../../assets/styles/Login.css';

class LoginRegisterModal extends React.Component {
    constructor(props, context) {
        super(props);
        this.state = {show: false};
    }

    componentDidMount(){
      const signUpButton = document.getElementById('signUp');
      const signInButton = document.getElementById('signIn');
      const container = document.getElementById('container');

      signUpButton.addEventListener('click', () => {
        container.classList.add('right-panel-active');
      });

      signInButton.addEventListener('click', () => {
        container.classList.remove('right-panel-active');
      });
    }

    ....
    render() {

        const styleModal = {
            marginTop: "15%",
            marginLeft: "30%",
            padding: 0,
            width:770,
            height:480,
            backgroundColor:"#ffffffff",
            borderRadius:21.5,
        }

        return (
        <Modal show={this.state.show} style={styleModal} >

            .....

Sign in.

                      Nice to see you again.Login and continue the journey.

                    <button class="ghost" id="signIn">Sign In</button>

Hey, new friend!

New to the Village? Sign up and start your journey

                    <button class="ghost" id="signUp">Sign Up</button>

        </Modal>
        );
    }
}

export default LoginRegisterModal;

I have tried adding a if condition before the addListener but it's just fixing the error but not working.

Also I have tried to replace by onClick instead but it's not working the code

    signUpButton = () => {
        container.classList.add('right-panel-active');
    }

but container is not known..

Any idea?

Thanks


问:
mongodb load document and increment counter
Maybe this sounds bit strange but i will ask it.

In my application i store posts in my collection called posts. It looks like this

```<code>{
   _id: 123,
   name: "somename",
   surname: "somesurname",
   img: "path/to/img",
   views: 0
}
</code>```

So is it possible in mongodb to increase the views everytime that document gets loaded? Or do i need an workaround?

My other solution is after i fetch all data with .find() or .aggregate() to map all the _ids and execute an update query with $in to increase everywhere the views by 1. I hope you know what i mean.

But i think its kinda in-efficient, because i need 2 querys. I was also thinking about, instead of using querys like .find(), to use update querys and return the new document with new: true. Is this possible, can somebody help me here?

答:
There is nothing 100% native OTB within MongoDB, but here are some approaches I recommend:

Option 1: Application Data Layer (Recommended)

Standardize this on the data layer of your application. On every access operation (that you deem to be a notable "view"), remember the IDs of the retrieved posts, and after you server the request, run a multi-update to increment this number.

This "multi-update" approach will make sure that you're minimizing your increment update ops. You can even "remember" these in memory and run the updates in batch just once in a while (assuming you're OK that "views" might be out of date by a few minutes).

You do not want to have your API wait on this data increment operation, because you will slow down all your read operations. If you need to return data with updated numbers, then updated them in memory before returning, but still do the DB views update after serving the request.

Why I strongly recommend this option: there will always be cases when you'll read the post, but not want to increment the "view" counter, like when you're doing internal analytics, or checking data for other internal operations. There are also cases when you'll just do an update, which is not a strict "view", but you'll want to update the view counter, because you're still serving the result for "viewing". So maintaining logical "Data Layer" control over what is really a view, is a very good practice.

Option 2: Use Mongo Stitch

If you were using something like Mongo Stitch (https://docs.mongodb.com/stitch/), this offers such functionality naturally (https://docs.mongodb.com/stitch/triggers/#database-trigger), but then you might as well handle much of your application with this additional layer (if it's even available to you).

Option 3: Use MongoDB Stored JavaScript

In SQL DBs you would use triggers, and the closest thing in "raw" MongoDB is "Stored JavaScript", BUT there is no natural way (AFAIK) to trigger this stored JS on document access, so you'd have to integrate this into something like Option 1 anyway, so it's just a noteworthy solution mention.

Body:
Maybe this sounds bit strange but i will ask it.

In my application i store posts in my collection called posts. It looks like this

{
   _id: 123,
   name: "somename",
   surname: "somesurname",
   img: "path/to/img",
   views: 0
}

So is it possible in mongodb to increase the views everytime that document gets loaded? Or do i need an workaround?

My other solution is after i fetch all data with .find() or .aggregate() to map all the _ids and execute an update query with $in to increase everywhere the views by 1. I hope you know what i mean.

But i think its kinda in-efficient, because i need 2 querys. I was also thinking about, instead of using querys like .find(), to use update querys and return the new document with new: true. Is this possible, can somebody help me here?


问:
I wrote code exactly as shown from a Firebase tutorial and it doesn't work
so here's the tutorial that I watched: https://www.youtube.com/watch?v=LOeioOKUKI8&t=865s
basically I'm trying to do local hosting of a webpage through Firebase and it keeps failing and this is the error I get on my BASH console.

```<code>i  functions: Preparing to emulate functions.
i  hosting: Serving hosting files from: public
✔  hosting: Local server: http://localhost:5000
Warning: You're using Node.js v12.1.0 but the Google Cloud Functions runtime is only available in Node.js 6 (Deprecated), Node.js 8, and Node.js 10 (Beta). Therefore, results from running emulated functions may not match production behavior.
⚠  functions: Failed to load functions source code. Ensure that you have the latest SDK by running npm i --save firebase-functions inside the functions directory.
⚠  functions: Error from emulator. Error parsing triggers: Cannot find module 'consolidate'

Try running "npm install" in your functions directory before deploying.
</code>```

I did do npm install in my functions directory and I also did npm i --save firebase-functions inside my functions directory.

```<code>const functions = require('firebase-functions');
const firebase = require('firebase-admin');
const express = require('express');
const engines = require('consolidate');

const firebaseApp = firebase.initializeApp(
     functions.config().firebase

);

function getFacts() {
const ref = firebaseApp.database().ref('facts');
return ref.once('value').then(snap => snap.val());
}

const app = express();
app.engine('hbs', engines.handlebars);
app.set('views', './views');
app.set('view engine', 'hbs');

app.get('/', (request, response) => {
    response.set('Cache-Control', 'public, max-age=300, s-
    maxage=600');
    getFacts().then(facts => {
    response.render('index', { facts });
});
});

exports.app = functions.https.onRequest(app);
</code>```

答:
In your 'functions' directory, run:

npm i handlebars consolidate --save
```

This will install both dependencies that you can then use by requiring them in your code.

Body:
so here's the tutorial that I watched: https://www.youtube.com/watch?v=LOeioOKUKI8&t=865s
basically I'm trying to do local hosting of a webpage through Firebase and it keeps failing and this is the error I get on my BASH console.

i  functions: Preparing to emulate functions.
i  hosting: Serving hosting files from: public
✔  hosting: Local server: http://localhost:5000
Warning: You're using Node.js v12.1.0 but the Google Cloud Functions runtime is only available in Node.js 6 (Deprecated), Node.js 8, and Node.js 10 (Beta). Therefore, results from running emulated functions may not match production behavior.
⚠  functions: Failed to load functions source code. Ensure that you have the latest SDK by running npm i --save firebase-functions inside the functions directory.
⚠  functions: Error from emulator. Error parsing triggers: Cannot find module 'consolidate'

Try running "npm install" in your functions directory before deploying.

I did do npm install in my functions directory and I also did npm i --save firebase-functions inside my functions directory.

const functions = require('firebase-functions');
const firebase = require('firebase-admin');
const express = require('express');
const engines = require('consolidate');

const firebaseApp = firebase.initializeApp(
     functions.config().firebase

);

function getFacts() {
const ref = firebaseApp.database().ref('facts');
return ref.once('value').then(snap => snap.val());
}

const app = express();
app.engine('hbs', engines.handlebars);
app.set('views', './views');
app.set('view engine', 'hbs');

app.get('/', (request, response) => {
    response.set('Cache-Control', 'public, max-age=300, s-
    maxage=600');
    getFacts().then(facts => {
    response.render('index', { facts });
});
});

exports.app = functions.https.onRequest(app);

Body:
In your 'functions' directory, run:

npm i handlebars consolidate --save

This will install both dependencies that you can then use by requiring them in your code.


问:
How do I pick the nearest element in an array in Swift?
I was surprised I could not find a thread on this, but I need to check a series of arrays for a specific value, and if not present, check if the value falls between the max and min value, and then choose the closest, most negative value to assign to a variable.

I attempted to accomplish this with the function below, but it yields a compiler error: Cannot call value of non-function type "Float!"

Is there any way to overcome the compiler error, or should I try a different approach?

```<code>func nearestElement(powerD : Float, array : [Float]) -> Float {

    var n = 0
    var nearestElement : Float!

    while array[n] <= powerD {

        n++;
    }

    nearestElement = array[n] // error: Cannot call value of non-function type "Float!"

    return nearestElement;
}
</code>```

I'd like to then call nearestElement() when I check each array, within arrayContains():

```<code>func arrayContains(array: [Float], powerD : Float) {

    var nearestElement : Float!

    if array.minElement() < powerD && powerD < array.maxElement() {

        if array.contains(powerD) {

            contactLensSpherePower = vertexedSpherePower

        } else {

            contactLensSpherePower = nearestElement(powerD, array)
        }
    }
}
</code>```

答:
Optimised solution using higher order functions: </p>

```<code> func closestMatch(values: [Int64], inputValue: Int64) -> Int64? {
    return (values.reduce(values[0]) { abs($0-inputValue) < abs($1-inputValue) ? $0 : $1 })
}
</code>```

<p>Swift is advancing with every version to optimise the performance and efficiency. With higher order functions finding the closest match in an array of values is much easier with this implementation. Change the type of value as per your need. </p>

Body:
I was surprised I could not find a thread on this, but I need to check a series of arrays for a specific value, and if not present, check if the value falls between the max and min value, and then choose the closest, most negative value to assign to a variable.

I attempted to accomplish this with the function below, but it yields a compiler error: Cannot call value of non-function type "Float!"

Is there any way to overcome the compiler error, or should I try a different approach?

func nearestElement(powerD : Float, array : [Float]) -> Float {

    var n = 0
    var nearestElement : Float!

    while array[n] <= powerD {

        n++;
    }

    nearestElement = array[n] // error: Cannot call value of non-function type "Float!"

    return nearestElement;
}

I'd like to then call nearestElement() when I check each array, within arrayContains():

func arrayContains(array: [Float], powerD : Float) {

    var nearestElement : Float!

    if array.minElement() < powerD && powerD < array.maxElement() {

        if array.contains(powerD) {

            contactLensSpherePower = vertexedSpherePower

        } else {

            contactLensSpherePower = nearestElement(powerD, array)
        }
    }
}

Body:
Optimised solution using higher order functions:

 func closestMatch(values: [Int64], inputValue: Int64) -> Int64? {
    return (values.reduce(values[0]) { abs($0-inputValue) < abs($1-inputValue) ? $0 : $1 })
}

Swift is advancing with every version to optimise the performance and efficiency. With higher order functions finding the closest match in an array of values is much easier with this implementation. Change the type of value as per your need.


问:
Ajax call not executing as expected
I have an ajax call that is not executing how I would expect. I am receiving an error from the browser of "jquery-1.10.2.js:8157 Uncaught TypeError: Cannot read property 'FileGuid' of undefined". I have break points in my CS file at the start of both the GetExportData and Download functions but neither one of them are ever hit. </p>

```<code>function generateExportFile() {
        var datefrom = $('#tab_MHSubpay_datefrom').ejDatePicker("getValue");
        var dateto = $('#tab_MHSubpay_dateto').ejDatePicker("getValue");
        var show = $('#tab_MHSubpay_show').ejDropDownList("getSelectedValue");
        var service = $('#tab_MHSubpay_serviceType').ejDropDownList("getSelectedValue");
        var phase = $('#tab_MHSubpay_phaseCode').ejDropDownList("getSelectedValue");

        $('#accwpopup').ejWaitingPopup({
            showOnInit: true,
            text: "Generating file...",
            target: "#tbldata"
        });

        debugger;
        $.ajax({
            cache: false,
            url: '@Url.Action("GetExportData", "MHSubpay")',
            data: {
                datefrom: datefrom,
                dateto: dateto,
                show: show,
                service: service,
                phase: phase
            },
            success: function (data) {
                $('#accwpopup').ejWaitingPopup('destroy');
                window.location = '@Url.Action("Download", "MHSubpay")?fileGuid=' + data.Data.FileGuid + '&filename=' + data.Data.FileName;
            },
            error: function (data) {
                $('#accwpopup').ejWaitingPopup('destroy');
                showMessage("An error ocurred trying to generate the file", false);
            },
            async: false
        });
    }
</code>```

答:
The affected line is this, because this is the only line where you try to access the FileGuid property:

window.location = '@Url.Action("Download", "MHSubpay")?fileGuid=' + data.Data.FileGuid + '&filename=' + data.Data.FileName;
```

<p>More specifically this part of the line:</p>

<pre class="lang-js prettyprint-override"><code>data.Data.FileGuid
</code>```

Based on that the Ajax request executes successfully, but the response doesn't have a Data propery.

What I'd do is I'd put a console.log(data) at the first line of the success method to see what's in the response body.

Sidenote: this is JavaScript code which runs in the browser, so it doesn't make much sense to put breakpoints in this CS file which runs on the server side.

Title: Ajax call not executing as expected

Body:
I have an ajax call that is not executing how I would expect. I am receiving an error from the browser of "jquery-1.10.2.js:8157 Uncaught TypeError: Cannot read property 'FileGuid' of undefined". I have break points in my CS file at the start of both the GetExportData and Download functions but neither one of them are ever hit.

function generateExportFile() {
        var datefrom = $('#tab_MHSubpay_datefrom').ejDatePicker("getValue");
        var dateto = $('#tab_MHSubpay_dateto').ejDatePicker("getValue");
        var show = $('#tab_MHSubpay_show').ejDropDownList("getSelectedValue");
        var service = $('#tab_MHSubpay_serviceType').ejDropDownList("getSelectedValue");
        var phase = $('#tab_MHSubpay_phaseCode').ejDropDownList("getSelectedValue");

        $('#accwpopup').ejWaitingPopup({
            showOnInit: true,
            text: "Generating file...",
            target: "#tbldata"
        });

        debugger;
        $.ajax({
            cache: false,
            url: '@Url.Action("GetExportData", "MHSubpay")',
            data: {
                datefrom: datefrom,
                dateto: dateto,
                show: show,
                service: service,
                phase: phase
            },
            success: function (data) {
                $('#accwpopup').ejWaitingPopup('destroy');
                window.location = '@Url.Action("Download", "MHSubpay")?fileGuid=' + data.Data.FileGuid + '&filename=' + data.Data.FileName;
            },
            error: function (data) {
                $('#accwpopup').ejWaitingPopup('destroy');
                showMessage("An error ocurred trying to generate the file", false);
            },
            async: false
        });
    }

Body:
The affected line is this, because this is the only line where you try to access the FileGuid property:

window.location = '@Url.Action("Download", "MHSubpay")?fileGuid=' + data.Data.FileGuid + '&filename=' + data.Data.FileName;

More specifically this part of the line:

data.Data.FileGuid

Based on that the Ajax request executes successfully, but the response doesn't have a Data propery.

What I'd do is I'd put a console.log(data) at the first line of the success method to see what's in the response body.

Sidenote: this is JavaScript code which runs in the browser, so it doesn't make much sense to put breakpoints in this CS file which runs on the server side.


问:
How to deploy pinax with virtualenv?
I developed one application with Pinax http://pinaxproject.com/. I created project by  pinax-admin setup_project mysite -b social in my local virtualenv, i want to deploy my project to my Centos server, so how to setup the libraries ? you know i setup many libraries by pinax-admin setup_project mysite -b social and all libraries are installed into my local virtualenv.

答: Generally you create a new virtualenv on your server and install your dependencies into it. The documentation recommends zc.buildout: http://pinaxproject.com/docs/dev/buildout/.

Title: How to deploy pinax with virtualenv?


问:
Changes in PHP.INI for OpenLiteSpeed not working
In a OpenLiteSpeed server I used php_info() to find the path to php.ini

Loaded Configuration File    /usr/local/lsws/lsphp73/etc/php/7.3/litespeed/php.ini

Then I edited max_input_vars and tried several ways to restart OpenLiteSpeed to apply the changes, but nothing is working.

php_info() shows the old value of max_input_vars

答: As told by @qtwrk pkill lsphp fixed the problem


问:
Asp.Net MVC SSO - Deny Access to DB User
I am introducing SSO to a legacy application. One existing functionality that I need to manage is to check if a user can access the application after they have signed in. Previously, if they logged in, their account would be checked against a db table and they would be logged out of the system with a message saying they had to contact support if their access was denied. I am looking for the same functionality if possible on new SSO login. So, a snippet of the code below. Any suggestions would be appreciated.</p>

```<code> Notifications = new OpenIdConnectAuthenticationNotifications
            {
                AuthenticationFailed = OnAuthenticationFailed,
                SecurityTokenValidated = (context) =>
                {
                    ClaimsIdentity identity = context.AuthenticationTicket.Identity;

                    // check the database if the user is locked from accessing the system
                    var userEmail = identity.FindFirst("preferred_username").Value;

                    var currentUser = UsersTable.Where(user => user.Email == userEmail);

                    if (currentUser != null )
                    {
                        if (currentUser.AccessLocked)
                        {
                            at this point I need to prevent the user for using the system. My preferred option would be to
                            Force logout, and redirect back to the login page, with a message saying that user access is locked

                            The other option
                            // 2 - Add Roles on each of the controller (IsActive) and add a Claim Role Type for a user who does have access
                            identity.AddClaim(new Claim(ClaimTypes.Role, "IsActive"));
                            I have tried this, but I get stuck in a authorisation loop when the user doesn not have the Role
                        }
                    }
                }
            }
</code>```

答:
The difference after integrating SSO is that you now have 2 step behaviour:

Authentication is outsourced to the SSO system for multiple apps, and the user may only have rights to a subset of these

You then apply Application Specific Authorization to see whether the user has rights to use a particular app or particular views

The most standard solution is to avoid signing the user out, which is likely to lead to a redirect loop or other technical complexity. Instead you should aim to redirect such users to an Access Denied Page within the app.

In C# I would use a filter + claims based solution to achieve these goals, as you suggest. However, you need to avoid using an 'authentication filter', whose failure action is to redirect the user.

Body:
I am introducing SSO to a legacy application. One existing functionality that I need to manage is to check if a user can access the application after they have signed in. Previously, if they logged in, their account would be checked against a db table and they would be logged out of the system with a message saying they had to contact support if their access was denied. I am looking for the same functionality if possible on new SSO login. So, a snippet of the code below. Any suggestions would be appreciated.

 Notifications = new OpenIdConnectAuthenticationNotifications
            {
                AuthenticationFailed = OnAuthenticationFailed,
                SecurityTokenValidated = (context) =>
                {
                    ClaimsIdentity identity = context.AuthenticationTicket.Identity;

                    // check the database if the user is locked from accessing the system
                    var userEmail = identity.FindFirst("preferred_username").Value;

                    var currentUser = UsersTable.Where(user => user.Email == userEmail);

                    if (currentUser != null )
                    {
                        if (currentUser.AccessLocked)
                        {
                            at this point I need to prevent the user for using the system. My preferred option would be to
                            Force logout, and redirect back to the login page, with a message saying that user access is locked

                            The other option
                            // 2 - Add Roles on each of the controller (IsActive) and add a Claim Role Type for a user who does have access
                            identity.AddClaim(new Claim(ClaimTypes.Role, "IsActive"));
                            I have tried this, but I get stuck in a authorisation loop when the user doesn not have the Role
                        }
                    }
                }
            }


问:
Mongoose Unique index not working!
I'm trying to let MongoDB detect a duplicate value based on its index. I think this is possible in MongoDB, but through the Mongoose wrapper things appear to be broken. So for something like this:

```<code>User = new Schema ({
  email: {type: String, index: {unique: true, dropDups: true}}
})
</code>```

I can save 2 users with the same email. Darn.

The same issue has been expressed here: https://github.com/LearnBoost/mongoose/issues/56, but that thread is old and lead to nowhere.

For now, I'm manually making a call to the db to find the user. That call is not expensive since "email" is indexed. But it would still be nice to let it be handled natively.

Does anyone have a solution to this?

答:
Removing all documents from the collection:

```<code>db.users.remove({})
</code>```

And a restart, as others mentioned, worked for me

Title: Mongoose Unique index not working!

Body:
I'm trying to let MongoDB detect a duplicate value based on its index. I think this is possible in MongoDB, but through the Mongoose wrapper things appear to be broken. So for something like this:

User = new Schema ({
  email: {type: String, index: {unique: true, dropDups: true}}
})

I can save 2 users with the same email. Darn.

The same issue has been expressed here: https://github.com/LearnBoost/mongoose/issues/56, but that thread is old and lead to nowhere.

For now, I'm manually making a call to the db to find the user. That call is not expensive since "email" is indexed. But it would still be nice to let it be handled natively.

Does anyone have a solution to this?

Body:
Removing all documents from the collection:

db.users.remove({})

And a restart, as others mentioned, worked for me


问:
Anzure Search ingestion events
I'd like to know if Azure Search offers any ability to trigger an Azure Function when a document gets indexed or inserted into Azure search or if there are any other events I can take advantage of.

I'd like to avoid a timed event which continuously scans Azure search for new documents.

答: Unfortunately, there isn't a great way to do this today. Eugene's suggestion will work, but isn't super efficient and also does indeed have the limitation of the document might not actually make it to the index if something else goes wrong later in the indexer. Please vote on the following uservoice item which is related to implementation for triggered events for Azure Cognitive Search if you are interested in seeing a more well defined option for this scenario: https://feedback.azure.com/forums/263029-azure-search/suggestions/10095111-azure-search-alerts</p>

Title: Anzure Search ingestion events