问:
How to write a recursive function to search for a key in a binary tree using in-order traversal in C?
I am trying to write a recursive function that, given the root of a binary tree and a key, searches for the key using in-order traversal.  The function returns NULL if the node with the key isn't found; otherwise it returns the node containing the key.

What I'm having trouble with is returning the node that contains the key.  Every time I call the function and the key is in the binary tree, the function returns NULL.  It feels like the result keeps getting overwritten by the initialization in the first line in the function.

Here's the in-order search function:

```<code>typedef struct treeNode
{
    int data;
    struct treeNode *left, *right;
} TreeNode, *TreeNodePtr;

typedef struct
{
    TreeNodePtr root;
} BinaryTree;

TreeNodePtr inOrderKey(TreeNodePtr root, int key)
{
    TreeNodePtr node = NULL;

    if (root != NULL)
    {
        node = inOrderKey(root->left, key);
        if(key == root->data)
        {
           node = root;
           return node;
        }
        node = inOrderKey(root->right, key);
    }

    return node;
}
</code>```

Here's the main function:

```<code>int main()
{
    FILE * in = fopen("numbst.txt", "r");

    BinaryTree bst;
    bst.root = NULL;

    int num;

    fscanf(in, "%d", &num);
    while (num != 0)
    {
        if (bst.root == NULL)
            bst.root = newTreeNode(num);
        else
        {
            TreeNodePtr node = findOrInsert(bst, num);
        }
        fscanf(in, "%d", &num);
    }

    printf("\nThe in-order traversal is: ");
    inOrder(bst.root);
    printf("\nThe pre-order traversal is: ");
    preOrder(bst.root);

    TreeNodePtr keyNode;
    int count = 0;
    keyNode = inOrderKey(bst.root, 9);
    if (keyNode != NULL)
        count = 1;
    else
        count = 0;

    if (count == 1)
        printf("\n\n%d exists in the binary tree. In order traversal was used.\n", 9);
    else
        printf("\n\n%d doesn't exist in the binary tree. In order traversal was used.\n", 9);
        return 0;
}
</code>```

The in-order traversal of the binary tree I'm working with is: 1 2 3 4 5 7 9 21

The pre-order traversal of the binary tree is: 4 1 2 3 7 5 21 9

I'm testing the function using 9 and 31.

答:
This code:

```<code>    node = inOrderKey(root->left, key);
    if(key == root->data)
    {
       node = root;
       return node;
    }
    node = inOrderKey(root->right, key);
</code>```

first uses inOrderKey to search the left subtree. Then it ignores the result.

Then it tests whether the current node contains the key. If it does, it returns to its caller. If the caller was itself (this is in a recursive call, not the original), the caller likely ignores the result.

Then it uses inOrderKey to search the right tree. Then it returns the result.]

Ultimately, the node containing the key will be returned only if it was in the rightmost path. If it is in the left subtree of any node, it will be ignored.

To fix this, after each call to inOrderKey, test whether the returned value is a null pointer. If it is not, return it immediately instead of going on.

Body:
I am trying to write a recursive function that, given the root of a binary tree and a key, searches for the key using in-order traversal.  The function returns NULL if the node with the key isn't found; otherwise it returns the node containing the key.

What I'm having trouble with is returning the node that contains the key.  Every time I call the function and the key is in the binary tree, the function returns NULL.  It feels like the result keeps getting overwritten by the initialization in the first line in the function.

Here's the in-order search function:

typedef struct treeNode
{
    int data;
    struct treeNode *left, *right;
} TreeNode, *TreeNodePtr;

typedef struct
{
    TreeNodePtr root;
} BinaryTree;

TreeNodePtr inOrderKey(TreeNodePtr root, int key)
{
    TreeNodePtr node = NULL;

    if (root != NULL)
    {
        node = inOrderKey(root->left, key);
        if(key == root->data)
        {
           node = root;
           return node;
        }
        node = inOrderKey(root->right, key);
    }

    return node;
}

Here's the main function:

int main()
{
    FILE * in = fopen("numbst.txt", "r");

    BinaryTree bst;
    bst.root = NULL;

    int num;

    fscanf(in, "%d", &num);
    while (num != 0)
    {
        if (bst.root == NULL)
            bst.root = newTreeNode(num);
        else
        {
            TreeNodePtr node = findOrInsert(bst, num);
        }
        fscanf(in, "%d", &num);
    }

    printf("\nThe in-order traversal is: ");
    inOrder(bst.root);
    printf("\nThe pre-order traversal is: ");
    preOrder(bst.root);

    TreeNodePtr keyNode;
    int count = 0;
    keyNode = inOrderKey(bst.root, 9);
    if (keyNode != NULL)
        count = 1;
    else
        count = 0;

    if (count == 1)
        printf("\n\n%d exists in the binary tree. In order traversal was used.\n", 9);
    else
        printf("\n\n%d doesn't exist in the binary tree. In order traversal was used.\n", 9);
        return 0;
}

The in-order traversal of the binary tree I'm working with is: 1 2 3 4 5 7 9 21

The pre-order traversal of the binary tree is: 4 1 2 3 7 5 21 9

I'm testing the function using 9 and 31.

Body:
This code:

    node = inOrderKey(root->left, key);
    if(key == root->data)
    {
       node = root;
       return node;
    }
    node = inOrderKey(root->right, key);

first uses inOrderKey to search the left subtree. Then it ignores the result.

Then it tests whether the current node contains the key. If it does, it returns to its caller. If the caller was itself (this is in a recursive call, not the original), the caller likely ignores the result.

Then it uses inOrderKey to search the right tree. Then it returns the result.]

Ultimately, the node containing the key will be returned only if it was in the rightmost path. If it is in the left subtree of any node, it will be ignored.

To fix this, after each call to inOrderKey, test whether the returned value is a null pointer. If it is not, return it immediately instead of going on.


来源: stackexchange

问:
How to efficiently maintain a tag count in Postgres?
I'm developing a tagging system where each user has a list of tags associated with them, and I'm storing them in a text[] column. Here's an example:

```<code>user_id: int4    tags: text[]
-------------    ------------
1                [ 'apple', 'banana', 'carrot', 'jelly' ]
2                [ 'jelly', 'zebra' ]
</code>```

My server has a route called update-tags that replaces a user's tags with a new list.

Now, I would like to be able to efficiently query for the entire list of tags and the count associated with each. The aforementioned example would return:

```<code>tag: text      count: int4
---------      -----------
'apple'        1
'banana'       1
'carrot'       1
'jelly'        2
'zebra'        1
</code>```

Assuming there were 10 million users, and each user had around 100 tags associated with them, and there were 10,000 tags total (ballpark numbers), doing a full-table scan of all users and de-duping all their tags is cost-prohibitive.

Tags for users change very rarely, but they are queried very often. I would like to optimize for read-speed and not write-speed.

Also, the tag counts do not have to be 100% accurate, but eventually consistent instead.

The use of triggers seems along the right path. I initially had the thought that whenever a user's tags column changed, to have a trigger to increment / decrement the counts, but what if many of the replacements were the same? Wouldn't it drift off over time? Is there a better way?

答:
Also, the tag counts do not have to be 100% accurate, but eventually consistent instead.

I don't think that this leeway really gets you anything with PostgreSQL, unless you set up logical replication, I don't see how that offers any advantages here.

I also think the insert, update, and delete trigger which update a table with (tag pk, count) fields is the right path.  The disadvantage is that if two sessions are trying to change the count of the same tag at the same time, one would have to block till the other committed.  But since you say such changes should be very rare, I don't think this would be too much of a problem.  You could also get deadlocks if you don't update rows of the tag table in a consistent order.

but what if many of the replacements were the same? Wouldn't it drift off over time?

I don't see where any drift would come from, if implemented correctly.

ContentLicense: CC BY-SA 4.0

Body:
I'm developing a tagging system where each user has a list of tags associated with them, and I'm storing them in a text[] column. Here's an example:

user_id: int4    tags: text[]
-------------    ------------
1                [ 'apple', 'banana', 'carrot', 'jelly' ]
2                [ 'jelly', 'zebra' ]

My server has a route called update-tags that replaces a user's tags with a new list.

Now, I would like to be able to efficiently query for the entire list of tags and the count associated with each. The aforementioned example would return:

tag: text      count: int4
---------      -----------
'apple'        1
'banana'       1
'carrot'       1
'jelly'        2
'zebra'        1

Assuming there were 10 million users, and each user had around 100 tags associated with them, and there were 10,000 tags total (ballpark numbers), doing a full-table scan of all users and de-duping all their tags is cost-prohibitive.

Tags for users change very rarely, but they are queried very often. I would like to optimize for read-speed and not write-speed.

Also, the tag counts do not have to be 100% accurate, but eventually consistent instead.

The use of triggers seems along the right path. I initially had the thought that whenever a user's tags column changed, to have a trigger to increment / decrement the counts, but what if many of the replacements were the same? Wouldn't it drift off over time? Is there a better way?


问:
Cross-Browser, Cross-Platform native messaging using Xamarin Mac, C#
I tried to recreate the example to connect to my Xamarin Mac application using a chrome extension I will use as backbone for all other browsers, but it didn't work with the following error:

Error when communicating with the native messaging host.

The documentation seems straightforward on paper, but isn't that simple in the real life.

Here are my Read and listen functions (great examples there,https://github.com/anewtonlevey/NativeMessaging):

```<code>    public void Listen()
    {

        JObject data;
        while ((data = Read()) != null)
        {
            ProcessReceivedMessage(data);
        }

    }

    private JObject Read()
    {
        try
        {
            Stream stdin = Console.OpenStandardInput();

            byte[] lengthBytes = new byte[4];
            stdin.Read(lengthBytes, 0, 4);

            var buffer = new char[BitConverter.ToInt32(lengthBytes, 0)];

            using (var reader = new StreamReader(stdin)) while (reader.Peek() >= 0) reader.Read(buffer, 0, buffer.Length);
            return JsonConvert.DeserializeObject<JObject>(new string(buffer));

        }
        catch (Exception e)
        {
            Console.WriteLine("Read error: {0}", e);
            return null;
        }
    }
</code>```

From my main function , I call them using the following:

```<code>        host = new ExtendedHost();

        host.Listen();
</code>```

To note that I am using native messaging from Xamarin forms for a macOS application, as from my point of view, it might be the endianness, as the following documentation suggests:

Error when communicating with the native messaging host:

https://developer.chrome.com/extensions/nativeMessaging#native-messaging-host-protocol

Another window of my C# app seems to want to open when I am sending the message from the web extension, meaning that the error seems to occur at the reading step.

Help much appreciated.

Thanks.

Edit:

I suggested endianness as the documentation suggest that the response should be correct as well or would render the whole process corrupted, as suggested in the native messaging protocol doc, but it is not the issue for sure as I should still be able to parse the data sent:

https://developer.chrome.com/apps/nativeMessaging#native-messaging-host-protocol

I saw that the response has something to do with it, and that the function used to send message(as it was suggested that error in response could cause an overall error) would cause the issue, or that Console.StandardInput() doesn't work as suggested, but I don't think so as well.

My thought is that trying to attach to the running app caused the issue as I used ps aux | grep app_name, and put the path within the host file.

Here is the mention in the protocol:

Native messaging protocol
Chrome starts each native messaging host in a separate process and communicates with it using standard input (stdin) and standard output (stdout).

I also saw this answer from Xan in another post that Native messaging can't attach to running processes and Chrome should launch the process:

Talk to MacOSX app from Chrome Extension

Not to forget that I am using the native messaging API with Xamarin macOS in Debug mode, and that my app is a macOS app.

More informations are welcome on that subject, such as:

a way to get a path to the app which Chrome can use with its native messaging API

a solution to get this path programmatically, which would work on all platforms if possible as Console.WriteLine(Path.Combine(Assembly.GetExecutingAssembly().Location)); didn't do the trick.

Of course, if this is what you think is causing the issue.

Thanks in advance!

EDIT:

When sending output to stderr, I got the following error:

Read error: System.NotSupportedException: Stream does not support reading
  at System.IO.FileStream.Read (System.Byte[] array, System.Int32 offset, System.Int32 count) [0x0002e] in /Library/Frameworks/Xamarin.Mac.framework/Versions/Current/src/Xamarin.Mac/mcs/class/corlib/System.IO/FileStream.cs:493

Could it be that Console.OpenStandardInput doesn't work cross platform?
And if so, what could be another method to parse the standard input, as I saw that pipes could work, but I am not sure if they can deployed in a cross-platform fashion.

I didn't got any error or output when reading, only the above error at starting of the app.
For me, OpenStandardInput seems to be the culprit.

Any thoughts appreciated! Thanks

答:
Basically, the first 32 bits sent from the extension corresponds to the message length, in native order.

Since the first 32 bits are of type int, and I tried to parse JSON objects, Error when communicating with the native messaging host is raised. The documentation mentions that the issue resides within a broken Native Messaging protocol.

The worst part is that I saw it on the Python example, but thought that this was implemented by the programmer who did it.

I stumbled upon this thread on Stack Overflow which helped confirm, (Chrome App fails to communicate with native host on windows).

To debug Chrome in a much more verbose fashion, launch Chrome with --enable-logging=stderr --v=1 in the command line, and all stderr will be outputted there.

The documentation is mentioning it, but the examples found here and there using C# don't include them.

If I have time, I will confirm that this was the issue by editing this answer, and provide code for getting this to work on Visual Studio for macOS.

Edit

I managed to have this to work a few days ago. I modified the code so that it works without the while loop, as the StreamReader reads stdin until the end, thus not requesting a while loop (this caused my previous code to hang).
The SendMessage method also differs from other seen in other examples. Fewer lines, and works just fine.

My working example:

```<code>public void Listen()
{

    JObject data;

    //while ((data = Read()) != null)
    //{
    //    ProcessReceivedMessage(data);
    //}

    if((data = Read()) != null)
    {
        string message = ProcessReceivedMessage(data);
        SendMessage(message);
    }
}

    private JObject Read()
    {

        Stream stdin = Console.OpenStandardInput();

        byte[] lengthBytes = new byte[4];
        stdin.Read(lengthBytes, 0, lengthBytes.Length);

        char[] buffer = new char[BitConverter.ToInt32(lengthBytes, 0)];

        var reader = new StreamReader(stdin);
        //int messageLength =
        reader.Read(buffer, 0, buffer.Length);

        return JsonConvert.DeserializeObject<JObject>(new string(buffer));
    }

    public void SendMessage(JToken data)
    {
        var bytes = Encoding.UTF8.GetBytes(data.ToString(Formatting.None));
        var lengthBytes = BitConverter.GetBytes(bytes.Length);
        var stdout = Console.OpenStandardOutput();

        stdout.Write(lengthBytes, 0, 4);
        stdout.Write(bytes, 0, bytes.Length);
        stdout.Flush();
    }
</code>```

Body:
I tried to recreate the example to connect to my Xamarin Mac application using a chrome extension I will use as backbone for all other browsers, but it didn't work with the following error:

Error when communicating with the native messaging host.

The documentation seems straightforward on paper, but isn't that simple in the real life.

Here are my Read and listen functions (great examples there,https://github.com/anewtonlevey/NativeMessaging):

    public void Listen()
    {

        JObject data;
        while ((data = Read()) != null)
        {
            ProcessReceivedMessage(data);
        }

    }

    private JObject Read()
    {
        try
        {
            Stream stdin = Console.OpenStandardInput();

            byte[] lengthBytes = new byte[4];
            stdin.Read(lengthBytes, 0, 4);

            var buffer = new char[BitConverter.ToInt32(lengthBytes, 0)];

            using (var reader = new StreamReader(stdin)) while (reader.Peek() >= 0) reader.Read(buffer, 0, buffer.Length);
            return JsonConvert.DeserializeObject<JObject>(new string(buffer));

        }
        catch (Exception e)
        {
            Console.WriteLine("Read error: {0}", e);
            return null;
        }
    }

From my main function , I call them using the following:

        host = new ExtendedHost();

        host.Listen();

To note that I am using native messaging from Xamarin forms for a macOS application, as from my point of view, it might be the endianness, as the following documentation suggests:

Error when communicating with the native messaging host:

https://developer.chrome.com/extensions/nativeMessaging#native-messaging-host-protocol

Another window of my C# app seems to want to open when I am sending the message from the web extension, meaning that the error seems to occur at the reading step.

Help much appreciated.

Thanks.

Edit:

I suggested endianness as the documentation suggest that the response should be correct as well or would render the whole process corrupted, as suggested in the native messaging protocol doc, but it is not the issue for sure as I should still be able to parse the data sent:

https://developer.chrome.com/apps/nativeMessaging#native-messaging-host-protocol

I saw that the response has something to do with it, and that the function used to send message(as it was suggested that error in response could cause an overall error) would cause the issue, or that Console.StandardInput() doesn't work as suggested, but I don't think so as well.

My thought is that trying to attach to the running app caused the issue as I used ps aux | grep app_name, and put the path within the host file.

Here is the mention in the protocol:

Native messaging protocol
Chrome starts each native messaging host in a separate process and communicates with it using standard input (stdin) and standard output (stdout).

I also saw this answer from Xan in another post that Native messaging can't attach to running processes and Chrome should launch the process:

Talk to MacOSX app from Chrome Extension

Not to forget that I am using the native messaging API with Xamarin macOS in Debug mode, and that my app is a macOS app.

More informations are welcome on that subject, such as:

a way to get a path to the app which Chrome can use with its native messaging API

a solution to get this path programmatically, which would work on all platforms if possible as Console.WriteLine(Path.Combine(Assembly.GetExecutingAssembly().Location)); didn't do the trick.

Of course, if this is what you think is causing the issue.

Thanks in advance!

EDIT:

When sending output to stderr, I got the following error:

Read error: System.NotSupportedException: Stream does not support reading
  at System.IO.FileStream.Read (System.Byte[] array, System.Int32 offset, System.Int32 count) [0x0002e] in /Library/Frameworks/Xamarin.Mac.framework/Versions/Current/src/Xamarin.Mac/mcs/class/corlib/System.IO/FileStream.cs:493

Could it be that Console.OpenStandardInput doesn't work cross platform?
And if so, what could be another method to parse the standard input, as I saw that pipes could work, but I am not sure if they can deployed in a cross-platform fashion.

I didn't got any error or output when reading, only the above error at starting of the app.
For me, OpenStandardInput seems to be the culprit.

Any thoughts appreciated! Thanks

Body:
Basically, the first 32 bits sent from the extension corresponds to the message length, in native order.

Since the first 32 bits are of type int, and I tried to parse JSON objects, Error when communicating with the native messaging host is raised. The documentation mentions that the issue resides within a broken Native Messaging protocol.

The worst part is that I saw it on the Python example, but thought that this was implemented by the programmer who did it.

I stumbled upon this thread on Stack Overflow which helped confirm, (Chrome App fails to communicate with native host on windows).

To debug Chrome in a much more verbose fashion, launch Chrome with --enable-logging=stderr --v=1 in the command line, and all stderr will be outputted there.

The documentation is mentioning it, but the examples found here and there using C# don't include them.

If I have time, I will confirm that this was the issue by editing this answer, and provide code for getting this to work on Visual Studio for macOS.

Edit

I managed to have this to work a few days ago. I modified the code so that it works without the while loop, as the StreamReader reads stdin until the end, thus not requesting a while loop (this caused my previous code to hang).
The SendMessage method also differs from other seen in other examples. Fewer lines, and works just fine.

My working example:

public void Listen()
{

    JObject data;

    //while ((data = Read()) != null)
    //{
    //    ProcessReceivedMessage(data);
    //}

    if((data = Read()) != null)
    {
        string message = ProcessReceivedMessage(data);
        SendMessage(message);
    }
}

    private JObject Read()
    {

        Stream stdin = Console.OpenStandardInput();

        byte[] lengthBytes = new byte[4];
        stdin.Read(lengthBytes, 0, lengthBytes.Length);

        char[] buffer = new char[BitConverter.ToInt32(lengthBytes, 0)];

        var reader = new StreamReader(stdin);
        //int messageLength =
        reader.Read(buffer, 0, buffer.Length);

        return JsonConvert.DeserializeObject<JObject>(new string(buffer));
    }

    public void SendMessage(JToken data)
    {
        var bytes = Encoding.UTF8.GetBytes(data.ToString(Formatting.None));
        var lengthBytes = BitConverter.GetBytes(bytes.Length);
        var stdout = Console.OpenStandardOutput();

        stdout.Write(lengthBytes, 0, 4);
        stdout.Write(bytes, 0, bytes.Length);
        stdout.Flush();
    }


问:
How to get hex web String from JavaFX ColorPicker color?
I have Color chosen in JavaFX ColorPicker. Now I need to save it as hex string. I found this method, but for JavaFX it is not applicable. JavaFX has its own Color class without getRGB() method, that could be used as mediatory convertion.</p>

答:
this one
worked for me</p>

```<code>MyColorPicker.getValue().toString().substring(2)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
this one
worked for me

MyColorPicker.getValue().toString().substring(2)


问:
UIScrollView is not zooming
I'm having issue with the zooming feature of UIScrollView. It does not work at all. I have read similar posts and none of the fixes others used seem to work for me. My viewController references UIScrollViewDelegate, I have an instance variable for UIScrollView, I declare my subview to be the delegate object of UIScrollView, and I have the implementation for (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView. Here's my loadView function:

```<code>(void)loadView
{
    CGRect frame = CGRectMake(0, 0, 320, 480);

    scrollView = [[UIScrollView alloc] initWithFrame:frame];
    [scrollView setScrollEnabled:YES];

    CGRect reallyBigRect;
    reallyBigRect.origin = CGPointZero;
    reallyBigRect.size.width = frame.size.width * 2.0;
    reallyBigRect.size.height = frame.size.height * 2.0;
    [scrollView setContentSize:reallyBigRect.size];

    CGPoint offset;
    offset.x = frame.size.width * 0.5;
    offset.y = frame.size.height * 0.5;
    [scrollView setContentOffset:offset];

    [scrollView setMinimumZoomScale:1];
    [scrollView setMaximumZoomScale:5];
    [scrollView setUserInteractionEnabled:YES];
    self.scrollView.delegate = self;

    self.view = scrollView;

    views = [[HypnosisView alloc] initWithFrame:reallyBigRect];

    [scrollView addSubview:views];

    [self.view setBackgroundColor:[UIColor clearColor]];

}
</code>```

This code allows me to scroll just fine but zooming is nonexistent.

Hope to hear from someone,
Dave

答:
This post highlights the three things that are necessary to enable zooming:

You need a delegate that implements UIScrollViewDelegate and is set to delegate on your UIScrollView instance

On your delegate you have to implement one method: viewForZoomingInScrollView: (which must return the content view
  you're interested in zooming). You can also implement
  scrollViewDidEndZooming:withView:atScale: optionally.

On your UIScrollView instance, you have to set the minimumZoomScale and the maximumZoomScale to be different (they
  are 1.0 by default).

From your sample code, we can see #1 and #3 are implemented. Therefore, it's likely that #2 is the problem. Double check the code for implementing the viewForZoomingInScrollView method, or ideally include it in the code above.

Title: UIScrollView is not zooming

Body:
I'm having issue with the zooming feature of UIScrollView. It does not work at all. I have read similar posts and none of the fixes others used seem to work for me. My viewController references UIScrollViewDelegate, I have an instance variable for UIScrollView, I declare my subview to be the delegate object of UIScrollView, and I have the implementation for (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView. Here's my loadView function:

(void)loadView
{
    CGRect frame = CGRectMake(0, 0, 320, 480);

    scrollView = [[UIScrollView alloc] initWithFrame:frame];
    [scrollView setScrollEnabled:YES];

    CGRect reallyBigRect;
    reallyBigRect.origin = CGPointZero;
    reallyBigRect.size.width = frame.size.width * 2.0;
    reallyBigRect.size.height = frame.size.height * 2.0;
    [scrollView setContentSize:reallyBigRect.size];

    CGPoint offset;
    offset.x = frame.size.width * 0.5;
    offset.y = frame.size.height * 0.5;
    [scrollView setContentOffset:offset];

    [scrollView setMinimumZoomScale:1];
    [scrollView setMaximumZoomScale:5];
    [scrollView setUserInteractionEnabled:YES];
    self.scrollView.delegate = self;

    self.view = scrollView;

    views = [[HypnosisView alloc] initWithFrame:reallyBigRect];

    [scrollView addSubview:views];

    [self.view setBackgroundColor:[UIColor clearColor]];

}

This code allows me to scroll just fine but zooming is nonexistent.

Hope to hear from someone,
Dave


问:
Form Recognizer invalid model status
We tried Form Recognizer custom training, with these steps (API 2.0)

https://pnagarjuna.wordpress.com/2020/01/07/azure-form-recognizer-service-custom-model-training-steps/

The Training modell is success (201), but after Check Custom Model Status we got this error

```<code>{  "modelInfo": {    "modelId": "f17bd306-3c6a-4067-8ef1-5f2e6ced79e1",    "status": "invalid",    "createdDateTime": "2020-02-05T17:24:30Z",    "lastUpdatedDateTime": "2020-02-05T17:24:31Z"  },  "trainResult": {    "trainingDocuments": [],    "errors": [{      "code": "2014",      "message": "No valid blobs found in the specified Azure blob container. Please conform to the document format/size/page/dimensions requirements."    }]  }}
We also check
</code>```

https://learn.microsoft.com/en-us/azure/cognitive-services/form-recognizer/overview#custom-model
and everything is okay.

How can go further?

Thank you!

Gabor

答:
Thank you for reporting this.
Any chance you can switch from policy defined SAS token (one with sig={signature}) to sas token with explicit permissions? (one with sp={permissionenum})</p>

Title: Form Recognizer invalid model status

Body:
We tried Form Recognizer custom training, with these steps (API 2.0)

https://pnagarjuna.wordpress.com/2020/01/07/azure-form-recognizer-service-custom-model-training-steps/

The Training modell is success (201), but after Check Custom Model Status we got this error

{  "modelInfo": {    "modelId": "f17bd306-3c6a-4067-8ef1-5f2e6ced79e1",    "status": "invalid",    "createdDateTime": "2020-02-05T17:24:30Z",    "lastUpdatedDateTime": "2020-02-05T17:24:31Z"  },  "trainResult": {    "trainingDocuments": [],    "errors": [{      "code": "2014",      "message": "No valid blobs found in the specified Azure blob container. Please conform to the document format/size/page/dimensions requirements."    }]  }}
We also check

https://learn.microsoft.com/en-us/azure/cognitive-services/form-recognizer/overview#custom-model
and everything is okay.

How can go further?

Thank you!

Gabor


问:
Subclass a list and modify its append method
I am trying to create a custom list. Here is the class code I currently have:

```<code>class Path(list):
    """
    A path from the voltage source to ground.
    The path will be the components involved, and not the
    connections.
    """
    def append(self, value):
        if not isinstance(value, Component):
            raise RuntimeError("Only components can be added.")
        elif value in self.path: # <-- how to check if it's in the current list?
            pass
        else:
            super().__append__(value)
</code>```

super().__append__(value) is not a valid method to call. What would be a proper way to overwrite the list's append method in this custom list?

答:
append isn't a special method (as you noticed when you defined your own), it doesn't have dunders (__) on either side. super().append(value) is the call to make to call list's identically named method.

To your other comment, test elif value in self:; you are a list, you don't have an attribute named path containing a list  (or you shouldn't), so you use self like one.

Body:
I am trying to create a custom list. Here is the class code I currently have:

class Path(list):
    """
    A path from the voltage source to ground.
    The path will be the components involved, and not the
    connections.
    """
    def append(self, value):
        if not isinstance(value, Component):
            raise RuntimeError("Only components can be added.")
        elif value in self.path: # <-- how to check if it's in the current list?
            pass
        else:
            super().__append__(value)

super().__append__(value) is not a valid method to call. What would be a proper way to overwrite the list's append method in this custom list?


问:
Vuejs dependency collection
im reading source code of Vue.js

i cant understand this part in defineReactive function which turns a property into setter and getter.

my question is :

why would vue add 2 dependency when the property is an object?(see code below ,#1 and #2 are 2 different dependency)

```<code>const dep = new Dep()

let childOb = !shallow && observe(val)

Object.defineProperty(obj, key, {

    enumerable: true,

    configurable: true,

    get: function reactiveGetter () {

        const value = getter ? getter.call(obj) : val

        if (Dep.target) {

            dep.depend()// #1

        if (childOb) {

            childOb.dep.depend() //#2

       }

    if (Array.isArray(value)) {

        dependArray(value)

   }

 }

return value

}

}
</code>```

答:
The #1 dep is used to notify about an assignment, like o.name = 'new name'

#2 is used to notify non-assignment changes, including set, delete and array apis(push, pop etc)

Title: Vuejs dependency collection

Body:
im reading source code of Vue.js

i cant understand this part in defineReactive function which turns a property into setter and getter.

my question is :

why would vue add 2 dependency when the property is an object?(see code below ,#1 and #2 are 2 different dependency)

const dep = new Dep()

let childOb = !shallow && observe(val)

Object.defineProperty(obj, key, {

    enumerable: true,

    configurable: true,

    get: function reactiveGetter () {

        const value = getter ? getter.call(obj) : val

        if (Dep.target) {

            dep.depend()// #1

        if (childOb) {

            childOb.dep.depend() //#2

       }

    if (Array.isArray(value)) {

        dependArray(value)

   }

 }

return value

}

}


问:
Concatenating video clip with static image causes buffer errors
I'm trying to concatenate a 15 second clip of a video (MOVIE.mp4) with 5 seconds (no audio) of an image (IMAGE.jpg) using FFmpeg.

Something seems to be wrong with my filtergraph, although I'm unable to determine what. The command I've put together is the following:

ffmpeg \
-loop 1 -t 5 -I IMAGE.jpg \
-t 15 -I MOVIE.mp4 \
-filter_complex "[0:v]scale=480:640[1_v];anullsrc[1_a];[1:v][1:a][1_v][1_a]concat=n=2:v=1:a=1[out]" \
-map "[out]" \
-strict experimental tst_full.mp4
```

<p>Unfortunately, this seems to be creating some strange results:</p>

<ol>
<li><p>On my personal computer (<code>FFmpeg 4.2.1</code>) it correctly concatenates the movie with the static image; however, the static image lasts for an unbounded length of time. (After entering <code>ctrl-C</code>, the movie is still viewable, but is of an extremely long length--e.g., 35 min--depending on when I interrupt the process.)</p></li>
<li><p>On a remote machine where I need to do the ultimate video processing (<code>FFmpeg 2.8.15-0ubuntu0.16.04.1</code>), the command does not terminate, and instead, I get cascading errors of the following form:</p></li>
</ol>

```Past duration 0.611458 too large
...
[output stream 0:0 @ 0x21135a0] 100 buffers queued in output stream 0:0, something may be wrong.
...
[output stream 0:0 @ 0x21135a0] 100000 buffers queued in output stream 0:0, something may be wrong.
```

I haven't been able to find much documentation that elucidates what these errors mean, so I don't know what's going wrong.

答:
As Gyan pointed out, you only have to add atrim to your audio:

anullsrc,atrim=0:5[silent-audio]

Instead of scale you could use scale2ref and setsar to automatically make your image the same size and aspect ratio as the video.

```<code>ffmpeg \
-loop 1 -t 5 -i IMAGE.jpg \
-t 15 -i MOVIE.mp4 \
-filter_complex "[0:v][1:v]scale2ref[img][v];[img]setsar=1[img]; \
anullsrc,atrim=0:5[silent-audio];[v][1:a][img]
[silent-audio]concat=n=2:v=1:a=1[out]" \
-map "[out]" \
-strict experimental tst_full.mp4
</code>```

Alternatively you could use anullsrc as a 3rd input:

```<code>ffmpeg \
-t 15 -i MOVIE.mp4 \
-loop 1 -t 5 -i IMAGE.jpg \
-f lavfi -t 5 -i anullsrc \
-filter_complex "[1:v][0:v]scale2ref[img][v];\
[img]setsar=1[img];[v][0:a][img][2:a]concat=n=2:v=1:a=1[out]" \
-map "[out]" \
-strict experimental tst_full.mp4
</code>```

Body:
I'm trying to concatenate a 15 second clip of a video (MOVIE.mp4) with 5 seconds (no audio) of an image (IMAGE.jpg) using FFmpeg.

Something seems to be wrong with my filtergraph, although I'm unable to determine what. The command I've put together is the following:

ffmpeg \
-loop 1 -t 5 -I IMAGE.jpg \
-t 15 -I MOVIE.mp4 \
-filter_complex "[0:v]scale=480:640[1_v];anullsrc[1_a];[1:v][1:a][1_v][1_a]concat=n=2:v=1:a=1[out]" \
-map "[out]" \
-strict experimental tst_full.mp4

Unfortunately, this seems to be creating some strange results:

On my personal computer (FFmpeg 4.2.1) it correctly concatenates the movie with the static image; however, the static image lasts for an unbounded length of time. (After entering ctrl-C, the movie is still viewable, but is of an extremely long length--e.g., 35 min--depending on when I interrupt the process.)

On a remote machine where I need to do the ultimate video processing (FFmpeg 2.8.15-0ubuntu0.16.04.1), the command does not terminate, and instead, I get cascading errors of the following form:

Past duration 0.611458 too large
...
[output stream 0:0 @ 0x21135a0] 100 buffers queued in output stream 0:0, something may be wrong.
...
[output stream 0:0 @ 0x21135a0] 100000 buffers queued in output stream 0:0, something may be wrong.

I haven't been able to find much documentation that elucidates what these errors mean, so I don't know what's going wrong.

Body:
As Gyan pointed out, you only have to add atrim to your audio:

anullsrc,atrim=0:5[silent-audio]

Instead of scale you could use scale2ref and setsar to automatically make your image the same size and aspect ratio as the video.

ffmpeg \
-loop 1 -t 5 -i IMAGE.jpg \
-t 15 -i MOVIE.mp4 \
-filter_complex "[0:v][1:v]scale2ref[img][v];[img]setsar=1[img]; \
anullsrc,atrim=0:5[silent-audio];[v][1:a][img]
[silent-audio]concat=n=2:v=1:a=1[out]" \
-map "[out]" \
-strict experimental tst_full.mp4

Alternatively you could use anullsrc as a 3rd input:

ffmpeg \
-t 15 -i MOVIE.mp4 \
-loop 1 -t 5 -i IMAGE.jpg \
-f lavfi -t 5 -i anullsrc \
-filter_complex "[1:v][0:v]scale2ref[img][v];\
[img]setsar=1[img];[v][0:a][img][2:a]concat=n=2:v=1:a=1[out]" \
-map "[out]" \
-strict experimental tst_full.mp4


问:
no such table: wagtailcore_site
I'm hosting two websites on ubuntu server and both having postgresql, the first one is working prefect but the second give me this error

no such table: wagtailcore_site Request Method:   GET

Django Version:   2.2.10 Exception

Type: OperationalError Exception Value:    no such table:

wagtailcore_site Exception

Location: /home/project2/.venv/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py

in execute, line 383 Python

Executable:   /home/project2/.venv/bin/python3.7m Python Version: 3.7.3

database settings for first website:

```<code>    DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'project_one',
        'USER': 'project_one',
        'PASSWORD': '123',
        'HOST': '127.0.0.1',
        'PORT': '',
    }
}
</code>```

database settings for second website:

```<code>    DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'project_two',
        'USER': 'project_two',
        'PASSWORD': '123',
        'HOST': '127.0.0.1',
        'PORT': '',
    }
}
</code>```

from the error it seems that django try to run sqllite instead of postgresql, I dont know why !

Notes:

python manage.py migrate command working without any problem whith the second database.

SQL lite is working, the problem only with postgresql in the second project.

I'm using nginx and gunicorn.

I think the problem maybe with the HOST and PORT settings in both settings maybe they conflicting each other? ( I try change the port and host also but didn't solve it)

thanks.

答:
My bad, I have two gunicorn files for both websites and I was restarting gunicorn for first websites not the second one.

Which mean there is no errors in the code above.. The problem only in restarting gunicorn.

Title: no such table: wagtailcore_site

Body:
I'm hosting two websites on ubuntu server and both having postgresql, the first one is working prefect but the second give me this error

no such table: wagtailcore_site Request Method:   GET

Django Version:   2.2.10 Exception

Type: OperationalError Exception Value:    no such table:

wagtailcore_site Exception

Location: /home/project2/.venv/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py

in execute, line 383 Python

Executable:   /home/project2/.venv/bin/python3.7m Python Version: 3.7.3

database settings for first website:

    DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'project_one',
        'USER': 'project_one',
        'PASSWORD': '123',
        'HOST': '127.0.0.1',
        'PORT': '',
    }
}

database settings for second website:

    DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'project_two',
        'USER': 'project_two',
        'PASSWORD': '123',
        'HOST': '127.0.0.1',
        'PORT': '',
    }
}

from the error it seems that django try to run sqllite instead of postgresql, I dont know why !

Notes:

python manage.py migrate command working without any problem whith the second database.

SQL lite is working, the problem only with postgresql in the second project.

I'm using nginx and gunicorn.

I think the problem maybe with the HOST and PORT settings in both settings maybe they conflicting each other? ( I try change the port and host also but didn't solve it)

thanks.


问:
ListPicker Message.Attach error in Caliburn.Micro
I'm having the following XAML code on WP7:

```<code><toolkit:ListPicker x:Name="ListPickerBwFactors" ItemsSource="{Binding BwFactors}"
                            cal:Message.Attach="[Event SelectionChanged]=[Action ChangeBinarizeFactor(ListPickerBwFactors.ItemSelected)]">
</toolkit:ListPicker>
</code>```

I'm getting the error:Target must be a FrameworkElement or a CollectionViewSource

All I want to do is to pass to my VM, the SelectedItem from ListPicker.
What am I doing wrong ?

答:
The current version of Silverlight on the WP7 is based off Silverlight 3, one of the major restrictions was that you could only Bind to dependency properties on a FrameworkElement or a CollectionViewSource (as opposed to say a DependencyObject in WPF).

The reason you're seeing that error for this piece of code is that behind the scenes the Message.Attach attached dependency property makes use of Behaviors, (specifically ActionMessage) which aren't FrameworkElements.

Caliburn is trying to set up a Binding from ListPickerBwFactors.ItemSelected to the Parameter of the ActionMessage and failing. It basically means parameters in Caliburn aren't much use at the moment. You'll need to bind the SelectedItem to a property on the ViewModel instead.

On the bright side, the "Mango" release of WP7 will update Silverlight on the phone to 4, where this problem is resolved.

Body:
I'm having the following XAML code on WP7:

<toolkit:ListPicker x:Name="ListPickerBwFactors" ItemsSource="{Binding BwFactors}"
                            cal:Message.Attach="[Event SelectionChanged]=[Action ChangeBinarizeFactor(ListPickerBwFactors.ItemSelected)]">
</toolkit:ListPicker>

I'm getting the error:Target must be a FrameworkElement or a CollectionViewSource

All I want to do is to pass to my VM, the SelectedItem from ListPicker.
What am I doing wrong ?


问:
Name ' ' ignored for PRIMARY KEY [MySql MariaDB 10.4.11]
I have a problem with those lines on my MAC, on mariaDB 10.4.11 version.

```<code>DROP DATABASE IF EXISTS Employe_Programmeurs;
CREATE DATABASE Employe_Programmeurs;
USE Employe_Programmeurs;

CREATE TABLE Employe(
    noEmp      INT(5),
    nom        VARCHAR(10),
    prenom     VARCHAR(10),
    CONSTRAINT pk_Employe_noEmp PRIMARY KEY (noEmp)
);
</code>```

It tells me that :

And when I enter those lines on Windows, it works without warning and I can see them in the SHOW CREATE TABLE.
On Mac, it doesn't show me the CONSTRAINT of this Primary key on SHOW CREATE TABLE.

I updated, downgraded, but still no solution.

答:
As @Akina mentioned, for PRIMARY KEY indexes, you can specify a name for the index, but it will be silently ignored, its name will always be PRIMARY.

And my problem was that I had 2 different versions (10.4.6) on windows and (10.4.11) on mac.

So basically, the 10.4.6 version of MariaDB didn’t show any warnings and they changed that in 10.4.11, by putting this warning.

Body:
I have a problem with those lines on my MAC, on mariaDB 10.4.11 version.

DROP DATABASE IF EXISTS Employe_Programmeurs;
CREATE DATABASE Employe_Programmeurs;
USE Employe_Programmeurs;

CREATE TABLE Employe(
    noEmp      INT(5),
    nom        VARCHAR(10),
    prenom     VARCHAR(10),
    CONSTRAINT pk_Employe_noEmp PRIMARY KEY (noEmp)
);

It tells me that :

And when I enter those lines on Windows, it works without warning and I can see them in the SHOW CREATE TABLE.
On Mac, it doesn't show me the CONSTRAINT of this Primary key on SHOW CREATE TABLE.

I updated, downgraded, but still no solution.


问:
Sublime text 3, pygame display is empty
I recently installed sublime text 3 and have been moving over from pycharm to sublime but have run into some difficulties with pygame. I installed python 3 and got it working, then fresh installed pygame, but when I brought over some code and ran it I got an empty pygame screen. Which looked like this:

I was filling the screen black and drawing a red rectangle yet none of it displayed. I am sure the program works because I tested it on both pygame and repl.it. But in case it would help here is the code for the project:

```<code>import pygame
import sys

pygame.init()

display_width = 600
display_height = 600
screen = pygame.display.set_mode((display_width, display_height))

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    screen.fill((0, 0, 0))
    pygame.draw.rect(screen, (255, 0, 0), ((300, 300), (20, 20)))
    pygame.display.update()
</code>```

I think it has to do with something I am not setting up with sublime. Help appreciated. Thx.

答:
It turns out pygame is not compatible with Mac OS Mojave so you need to use the new dev build to get it to work.

Use pip install pygame==2.0.0.dev4

Title: Sublime text 3, pygame display is empty

Body:
I recently installed sublime text 3 and have been moving over from pycharm to sublime but have run into some difficulties with pygame. I installed python 3 and got it working, then fresh installed pygame, but when I brought over some code and ran it I got an empty pygame screen. Which looked like this:

I was filling the screen black and drawing a red rectangle yet none of it displayed. I am sure the program works because I tested it on both pygame and repl.it. But in case it would help here is the code for the project:

import pygame
import sys

pygame.init()

display_width = 600
display_height = 600
screen = pygame.display.set_mode((display_width, display_height))

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    screen.fill((0, 0, 0))
    pygame.draw.rect(screen, (255, 0, 0), ((300, 300), (20, 20)))
    pygame.display.update()

I think it has to do with something I am not setting up with sublime. Help appreciated. Thx.


问:
Form doesn't submit without refresh (please Vanilla JS only)
I know this is a bit tricky because I can't actually post the JS or HTML code but I'll try my best to describe it.

So basically I created a table with JS on the HTML.
Then I use "submit" and "form" in the html to submit content onto the table. The content is retrieved with fetch and an API.

The issue I have is that while it all works well, the data doesn't appear on the table without me having to refresh the browser. I'd the data to appear as soon as I click the submit button.

Cheers and thanks in advance

答:
Its obvious and correct to dont show new records because table just can show last result of request .
For your goal you can reload just table tag with ajax or other ways for example you can refresh table tag x second after click on submit button.(x should be enough big that new records has time to submit).</p>


问:
Passing compiler options in CMake command line
I know how to pass compiler options using the cmake command:

```<code>set(CMAKE_CXX_FLAGS "-Wall -Wno-dev -Wl,-rpath=/home/abcd/libs/")
</code>```

Is there also a way to pass the options from the command line that will override the CMakeLists.txt options? Something like:

```<code>cmake -Wl,-rpath=/home/abcd/newlibs/ path/to/CMakeLists.txt
</code>```

or

```<code>cmake -D CMAKE_CXX_FLAGS="-Wno-dev -Wl,-rpath=/home/abcd/libs/" path/to/CMakeLists.txt
</code>```

My main problem is that I want to know how to append flags and how to override existing compiler flags from the command line.

答:
Perhaps this would work -

```<code>cmake -DCMAKE_CXX_FLAGS="$(CMAKE_CXX_FLAGS) -DYOUR_CUSTOM_DEFINE=1" <rest of original cmake cmdline>
</code>```

like Tomaz mentioned above.
-m

Body:
I know how to pass compiler options using the cmake command:

set(CMAKE_CXX_FLAGS "-Wall -Wno-dev -Wl,-rpath=/home/abcd/libs/")

Is there also a way to pass the options from the command line that will override the CMakeLists.txt options? Something like:

cmake -Wl,-rpath=/home/abcd/newlibs/ path/to/CMakeLists.txt

or

cmake -D CMAKE_CXX_FLAGS="-Wno-dev -Wl,-rpath=/home/abcd/libs/" path/to/CMakeLists.txt

My main problem is that I want to know how to append flags and how to override existing compiler flags from the command line.

Body:
Perhaps this would work -

cmake -DCMAKE_CXX_FLAGS="$(CMAKE_CXX_FLAGS) -DYOUR_CUSTOM_DEFINE=1" <rest of original cmake cmdline>

like Tomaz mentioned above.
-m


问:
How to decorate an existing Java object's method?
EDIT: I've described our solution at https://stackoverflow.com/a/60235242/3236516

I have a java object. It is an instance of one of many subclasses that extend an abstract class. I would like to modify one of its methods such that it runs some additional code before calling the original method. My goal is conceptually the same as a pointcut in AspectJ.

It is fine if I create some modified version of the original object rather than mutating the original. It is also fine if the solution involves bytecode manipulation.

Prior Work

I've considered creating a proxy via JavaAssist. The trouble is that ProxyFactory's create method expects that I know the constructor input types in advance. I don't. I can create my object without calling the constructor via Objenesis, but then the resulting proxy object will have null values for any values set by the constructor. This means my resulting object will behave differently from the original whenever a value set by the constructor is directly referenced.

Context

We are using Flink via AWS Kinesis Data Analytics to transform some streaming data. We would like to include some common code at the beginning of all of our StreamOperator's open() methods without having to modify each operator. One use case for this is to ensure a custom metrics agent is running on each instance an operator is running on.

答:
Answer from original asker: We solved the problem by creating a ByteBuddy proxy for StreamExecutionEnvironment that intercepted calls to getStreamGraph and recast (using reflection) each node's jobVertexClass to a class that extended the original class type, but included our custom logic. Because different classes require different parameters, we instantiated the proxy without calling a constructor by using Objenesis. To solve the problem of private fields normally set in the constructor being left null, we used reflection to alter the visibility of all private fields and then copied every field value from the original object to the proxy object.

We did not pursue the agent solution proposed by Rafael Winterhalter because it requires the ability to run the agent setup code on every worker instance, which is analogous to the original problem of wanting to start a metrics agent on each worker machine. Though I did not state this in my original question, the code creating the proxy objects occurs on the Flink job management machine, not the worker machines.


问:
Trying to understand RSACryptoServiceProvider key and message length relationship
I'm trying to better understand the cryptography classes in .Net and I have a situation that I do not understand clearly. I'm following a stripped down version of this RSACryptoServiceProvider example.

my shortened version is this:

```<code>string plainText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse dapibus.";
var byteConverter = new UnicodeEncoding();

//Works with longer string length
using var rsa = RSA.Create();
byte[] encrypted2 = rsa.Encrypt(byteConverter.GetBytes(plainText), RSAEncryptionPadding.OaepSHA1);

//fails if string's length is too long
using var rsa2 = new RSACryptoServiceProvider();
byte[] encrypted = rsa2.Encrypt(byteConverter.GetBytes(plainText), false);
</code>```

If you cut the string off at "elit" like so:

```<code>string plainText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
</code>```

then both work.

When I use the provider's overload constructor and give it an ample key size like so:

```<code>using var rsa2 = new RSACryptoServiceProvider(2048);
</code>```

then it can encrypt the full string's length.

What is the relationship between the key size and message length? What's the best way to determine what size key I need and why does the RSA. Create a method have no issues with the string's length?

答:
RSACryptoServiceProvider simply implements the schemes as specified in PKCS#1 v2.0 and beyond (PKCS#1 2.2 being the current version). I've specified the overhead and left over payloads here. It's language / runtime agnostic.

Although PKCS#1 v1.5 padding has less overhead, OAEP is more secure (it has a security proof for RSA) and should normally be used. PKCS#1 v1.5 only has 11 overhead bytes for a random component of 61 bits total. However, good practice would really require double the random component - for an overhead of 11 + 8 = 19 bytes.

Body:
I'm trying to better understand the cryptography classes in .Net and I have a situation that I do not understand clearly. I'm following a stripped down version of this RSACryptoServiceProvider example.

my shortened version is this:

string plainText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse dapibus.";
var byteConverter = new UnicodeEncoding();

//Works with longer string length
using var rsa = RSA.Create();
byte[] encrypted2 = rsa.Encrypt(byteConverter.GetBytes(plainText), RSAEncryptionPadding.OaepSHA1);

//fails if string's length is too long
using var rsa2 = new RSACryptoServiceProvider();
byte[] encrypted = rsa2.Encrypt(byteConverter.GetBytes(plainText), false);

If you cut the string off at "elit" like so:

string plainText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";

then both work.

When I use the provider's overload constructor and give it an ample key size like so:

using var rsa2 = new RSACryptoServiceProvider(2048);

then it can encrypt the full string's length.

What is the relationship between the key size and message length? What's the best way to determine what size key I need and why does the RSA. Create a method have no issues with the string's length?


问:
Angular 8: Nested Reactive Form in sub-component not working
I'm using Angular 8 Nested Reactive Form in a child component, but it does not work. I have searched the official Angular documentation, but I can not find any example on this.

My solution is available at stackblitz.com. I'm unable to show companyName for each company and address details for each address. Any ideas?

According to Kara Ericksons talk about “Angular Forms” at the Angular Connect 2017 it should be straight forward...

Her video Nested Forms in Angular between 35:31-36:51

In parent.component.html

```<code><form [formGroup]="form">

    <div *ngFor="let address of addresses">
        <app-child [address]="address"></app-child>
    </div>

    <button type="submit">Save</button>

</form>
</code>```

In parent.component.ts

```<code>export class ParentComponent implements OnInit {

  form = new FormGroup({});

  addresses : Address[] = [
    new Address("Street 1", "City 1"),
    new Address("Street 2", "City 2"),
    new Address("Street 3", "City 3"),
  ]

  constructor() { }

  ngOnInit() {
  }
}

</code>```

In child.component.html

```<code><div formGroupName="address">

     <input formControlName="street">
     <input formControlName="city">

</div>

</code>```

In child.component.ts

```<code>@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.less']
})
export class ChildComponent implements OnInit {

  @Input() address: Address;
  form: FormGroup;

  constructor(parent: FormGroupDirective) {
    this.form = parent.form;
  }

  ngOnInit() {
    this.form.addControl('address', new FormGroup({
      street: new FormControl()
      city: new FormControl()

    }));
  }
}

</code>```

答:
Did you forgot to add parent FormGroup to viewProviders to your child component? Like this: </p>

```<code>@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.less'],
  viewProviders: [
    {
      provide: ParentComponent,
      useExisting: FormGroupDirective
    }
  ]
})
</code>```

Body:
I'm using Angular 8 Nested Reactive Form in a child component, but it does not work. I have searched the official Angular documentation, but I can not find any example on this.

My solution is available at stackblitz.com. I'm unable to show companyName for each company and address details for each address. Any ideas?

According to Kara Ericksons talk about “Angular Forms” at the Angular Connect 2017 it should be straight forward...

Her video Nested Forms in Angular between 35:31-36:51

In parent.component.html

<form [formGroup]="form">

        <app-child [address]="address"></app-child>

    <button type="submit">Save</button>

</form>

In parent.component.ts

export class ParentComponent implements OnInit {

  form = new FormGroup({});

  addresses : Address[] = [
    new Address("Street 1", "City 1"),
    new Address("Street 2", "City 2"),
    new Address("Street 3", "City 3"),
  ]

  constructor() { }

  ngOnInit() {
  }
}

In child.component.html

     <input formControlName="street">
     <input formControlName="city">

In child.component.ts

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.less']
})
export class ChildComponent implements OnInit {

  @Input() address: Address;
  form: FormGroup;

  constructor(parent: FormGroupDirective) {
    this.form = parent.form;
  }

  ngOnInit() {
    this.form.addControl('address', new FormGroup({
      street: new FormControl()
      city: new FormControl()

    }));
  }
}

Body:
Did you forgot to add parent FormGroup to viewProviders to your child component? Like this:

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.less'],
  viewProviders: [
    {
      provide: ParentComponent,
      useExisting: FormGroupDirective
    }
  ]
})


问:
PHP Variables made with foreach
I have several variables coming from an array in $POST_['array'] i wish to make some kind of loop for example foreach that makes, for every value in the variable a variable name of it and assigns the value for it.

For example if i have

```<code>$POST_['name'];
$POST_['last'];
$POST_['age'];
$POST_['sex'];
</code>```

I want the loop to create each variable from the array inside the $_POST with the name of the variable like the following:

```<code>$name = 'John';
$last = 'Doe';
$age = '32';
$sex = 'male';
</code>```

NOTE - The array is coming from a serialized jquery string that puts together all the variables and values in a form into one big string.

Is this possible?

答:
Why not use a foreach?

```<code>foreach($_POST as $key=>$val){
    ${$key} = $val;
}
</code>```

Title: PHP Variables made with foreach

Body:
I have several variables coming from an array in $POST_['array'] i wish to make some kind of loop for example foreach that makes, for every value in the variable a variable name of it and assigns the value for it.

For example if i have

$POST_['name'];
$POST_['last'];
$POST_['age'];
$POST_['sex'];

I want the loop to create each variable from the array inside the $_POST with the name of the variable like the following:

$name = 'John';
$last = 'Doe';
$age = '32';
$sex = 'male';

NOTE - The array is coming from a serialized jquery string that puts together all the variables and values in a form into one big string.

Is this possible?

Body:
Why not use a foreach?

foreach($_POST as $key=>$val){
    ${$key} = $val;
}


问:
filtering documents using multi properties (refrenced and nrml) in mongoose and express using request query
so I want to get sales that are available in a specific date and by price (min,max) and place(wilaya,daira and commune),so the booking is a reference in sale and contains the date property and contacte contains the place where is the sale.

```<code>const contacteSchema = new mongoose.schema({
    telephone:[{
            type:Number,
            minlength:10,
            maxlength:10,
            required:true
    }],
    adress:{
        wilaya:{
            type:String,
            minlength:5,
            maxlength:20,
            required:true
        },
        daira:{
            type:String,
            minlength:5,
            maxlength:50,
            required:true
        },
        commune:{
            type:String,
            minlength:5,
            maxlength:50,
            required:true
        },
        rue:{
            type:String,
            minlength:5,
            maxlength:50,
            required:true
        }
    }

});

const Contacte = mongoose.model('Contacte',contacteSchema)
</code>```

this is the booking model

```<code>const bookingSchema = new mongoose.schema({
    date:{
        type: Date,
        minlength:10,
        maxlength:10,
        required:true,
    },
    total:{
        type:Number,
        minlength:5,
        maxlength:50,
        required:true
    },
    confirmationsale:{
        type:Boolean,
        default:false
    },
    client:{
        type: mongoose.Schema.Types.ObjectId,
        ref:'Client'
    },
    sale:{
        type: mongoose.Schema.Types.ObjectId,
        required:true,
        ref:'Sale'
    },
    services:[{
        type: mongoose.Schema.Types.ObjectId,
        ref:'SaleService'
    }]
});

const Booking = mongoose.model('Booking',bookingSchema)
</code>```

this is the sale model

```<code>var saleSchema = new mongoose.Schema({
    name:{
        type:String,
        minlength:5,
        maxlength:50,
        required:true
    },
    description:{
        type:String,
        minlength:5,
        maxlength:255,
    },
    rating:{
        type:Number,
        minlength:1,
        maxlength:255,
        default:0,
    },
    price:{
        type:Number,
        minlength:5,
        maxlength:50,
        required:true
    },
    login:{
        type:mongoose.Schema.Types.ObjectId,
        ref:'Login'
    },
    contacte:{
        type:mongoose.Schema.Types.ObjectId,
        ref:'Contacte'
    },
    services:[{
        type:mongoose.Schema.Types.ObjectId,
        ref:'SaleService'
    }],
    pictures:[{
        type:mongoose.Schema.Types.ObjectId,
        ref:'Picture'
    }],
    bookins:[{
        type:mongoose.Schema.Types.ObjectId,
        ref:'Booking'
    }]
});

var Sale = mongoose.model('Sale',saleSchema);
</code>```

this is the router.get method for searching and filtering sales

```<code>router.get('/get/sale', async (req, res)=>{

    let skip = parseInt(req.query.offset);
    let nPerPage = parseInt(req.query.limit);
    let sortby = req.query.sort;
    let orderby = req.query.order;
    let date = new Date(req.query.date);
    let wilaya = req.query.wilaya;
    let daira = req.query.daira;
    let commune = req.query.commune;
    let pricemax = req.query.pricemax;
    let pricemin = req.query.pricemin;

    let salemodel = await Sale.find({
        $or:[{
                bookins: {
                    $in : [{
                        'booking.date' : {
                             $ne: date
                        },
                    }]
                }
            },
            {
                $and:[
                    {'contacte.wilaya':wilaya},
                    {'contacte.daira':daira},
                    {'contacte.commune':commune}
                ]
            },
            {
                $and:[
                    {
                        'price': {
                            $lte: pricemax
                        }
                    },
                    {
                        'price': {
                            $gte: pricemin
                        }
                    }
                ]
            }
        ]
    })
    .populate('login email picture -password -username -type')
    .populate('contacte')
    .sort([[sortby, orderby]])
    .skip(skip > 0 ? (skip+1) : 0).limit(nPerPage)
    .exec();
    if(!salemodel) return res.status(404).send('invalid sale');
});
</code>```

Is it correct or do I have to modify some code or have to get rid of it ?

答: so it wont work coz what i want is a filtered search based on the query and here we have to afford the picemin and max and the wilaya and daira and commune to get it so instead i am building a filter based on the query, for example if i have the price min and max only i will add a filter for that by using a object and adding the filter and same for other params.</p>

Body:
so I want to get sales that are available in a specific date and by price (min,max) and place(wilaya,daira and commune),so the booking is a reference in sale and contains the date property and contacte contains the place where is the sale.

const contacteSchema = new mongoose.schema({
    telephone:[{
            type:Number,
            minlength:10,
            maxlength:10,
            required:true
    }],
    adress:{
        wilaya:{
            type:String,
            minlength:5,
            maxlength:20,
            required:true
        },
        daira:{
            type:String,
            minlength:5,
            maxlength:50,
            required:true
        },
        commune:{
            type:String,
            minlength:5,
            maxlength:50,
            required:true
        },
        rue:{
            type:String,
            minlength:5,
            maxlength:50,
            required:true
        }
    }

});

const Contacte = mongoose.model('Contacte',contacteSchema)

this is the booking model

const bookingSchema = new mongoose.schema({
    date:{
        type: Date,
        minlength:10,
        maxlength:10,
        required:true,
    },
    total:{
        type:Number,
        minlength:5,
        maxlength:50,
        required:true
    },
    confirmationsale:{
        type:Boolean,
        default:false
    },
    client:{
        type: mongoose.Schema.Types.ObjectId,
        ref:'Client'
    },
    sale:{
        type: mongoose.Schema.Types.ObjectId,
        required:true,
        ref:'Sale'
    },
    services:[{
        type: mongoose.Schema.Types.ObjectId,
        ref:'SaleService'
    }]
});

const Booking = mongoose.model('Booking',bookingSchema)

this is the sale model

var saleSchema = new mongoose.Schema({
    name:{
        type:String,
        minlength:5,
        maxlength:50,
        required:true
    },
    description:{
        type:String,
        minlength:5,
        maxlength:255,
    },
    rating:{
        type:Number,
        minlength:1,
        maxlength:255,
        default:0,
    },
    price:{
        type:Number,
        minlength:5,
        maxlength:50,
        required:true
    },
    login:{
        type:mongoose.Schema.Types.ObjectId,
        ref:'Login'
    },
    contacte:{
        type:mongoose.Schema.Types.ObjectId,
        ref:'Contacte'
    },
    services:[{
        type:mongoose.Schema.Types.ObjectId,
        ref:'SaleService'
    }],
    pictures:[{
        type:mongoose.Schema.Types.ObjectId,
        ref:'Picture'
    }],
    bookins:[{
        type:mongoose.Schema.Types.ObjectId,
        ref:'Booking'
    }]
});

var Sale = mongoose.model('Sale',saleSchema);

this is the router.get method for searching and filtering sales

router.get('/get/sale', async (req, res)=>{

    let skip = parseInt(req.query.offset);
    let nPerPage = parseInt(req.query.limit);
    let sortby = req.query.sort;
    let orderby = req.query.order;
    let date = new Date(req.query.date);
    let wilaya = req.query.wilaya;
    let daira = req.query.daira;
    let commune = req.query.commune;
    let pricemax = req.query.pricemax;
    let pricemin = req.query.pricemin;

    let salemodel = await Sale.find({
        $or:[{
                bookins: {
                    $in : [{
                        'booking.date' : {
                             $ne: date
                        },
                    }]
                }
            },
            {
                $and:[
                    {'contacte.wilaya':wilaya},
                    {'contacte.daira':daira},
                    {'contacte.commune':commune}
                ]
            },
            {
                $and:[
                    {
                        'price': {
                            $lte: pricemax
                        }
                    },
                    {
                        'price': {
                            $gte: pricemin
                        }
                    }
                ]
            }
        ]
    })
    .populate('login email picture -password -username -type')
    .populate('contacte')
    .sort([[sortby, orderby]])
    .skip(skip > 0 ? (skip+1) : 0).limit(nPerPage)
    .exec();
    if(!salemodel) return res.status(404).send('invalid sale');
});

Is it correct or do I have to modify some code or have to get rid of it ?


问:
What is the literal expression of NaN in Neo4j Cypher?
How do I express NaN as a literal in a Cypher query?

Situation

I have a NaN value in a database:

```<code>match (a) with max(a.CONCENTRATION) as m return m
</code>```

will return

```<code>m
---
NaN
</code>```

Cypher reference in Neo4j mentioned that this is possible as the result of special value being stored:

The special value java.lang.Double.NaN is regarded as being larger than all other numbers.

What I tried

However, now that it's in there, I don't know how to match them in search, because you get the following error

input

```<code>match (a) where a.CONCENTRATION = NaN return a limit 10
</code>```

error

```<code>Variable `NaN` not defined (line 1, column 35 (offset: 34))
</code>```

Other references

Cypher reference in Neo4j doesn't mention NaN literal, unless I missed it.

I've googled 'Cypher NaN' but the closest thing I got is how to add inf/NaN, which wasn't directly addressed (How to add infinity, NaN, or null values to a double[] property on a node in Cypher/Neo4j).

答:
This works in Neo4j 3.5:

MATCH (a)
WHERE TOSTRING(a.CONCENTRATION) = 'NaN'
RETURN a
LIMIT 10;

Body:
How do I express NaN as a literal in a Cypher query?

Situation

I have a NaN value in a database:

match (a) with max(a.CONCENTRATION) as m return m

will return

m
---
NaN

Cypher reference in Neo4j mentioned that this is possible as the result of special value being stored:

The special value java.lang.Double.NaN is regarded as being larger than all other numbers.

What I tried

However, now that it's in there, I don't know how to match them in search, because you get the following error

input

match (a) where a.CONCENTRATION = NaN return a limit 10

error

Variable `NaN` not defined (line 1, column 35 (offset: 34))

Other references

Cypher reference in Neo4j doesn't mention NaN literal, unless I missed it.

I've googled 'Cypher NaN' but the closest thing I got is how to add inf/NaN, which wasn't directly addressed (How to add infinity, NaN, or null values to a double[] property on a node in Cypher/Neo4j).


问:
Select data from specific row of grouped and joined table in MySQL
I have two tables, customers and orders which are inner joined. A customer can have several orders associated with them. In my selection, I then group by customers.id. I need to select the most recent order of each customer, but also the amount of money spent in that order. Currently, I can select the most recent order_date but do not know how to select the amount in the same row as the order_date.

This is my current query:

```<code>SELECT
    first_name,
    last_name,
    email,
    MAX(order_date) AS recent_order,
    amount -- this needs to select amount associated with recent_order
FROM customers
JOIN orders
    ON customers.id = orders.customer_id
GROUP BY customers.id;
</code>```

The query selects the most recent date, but does not select the amount associated with the most recent order_date.

Table declarations:

```<code>CREATE TABLE customers (
    id INT AUTO_INCREMENT PRIMARY KEY,
    first_name VARCHAR(100),
    last_name VARCHAR(100),
    email VARCHAR(100)
);

CREATE TABLE orders (
    id INT AUTO_INCREMENT PRIMARY KEY,
    order_date DATE,
    amount DECIMAL(8,2),
    customer_id INT,
    FOREIGN KEY(customer_id) REFERENCES customers(id)
);
</code>```

答:
```<code>SELECT
    first_name,
    last_name,
    email,
    MAX(order_date) AS recent_order,
    (SELECT amount FROM orders WHERE order_date = MAX(order_date) AND customers.id = orders.customer_id) as amount
FROM customers
JOIN orders
    ON customers.id = orders.customer_id
GROUP BY customers.id;
</code>```

<p>OR </p>

```<code>SELECT
    first_name,
    last_name,
    email,
    order_date AS recent_order,
    amount AS recent_order_amount
FROM customers
JOIN orders
    ON customers.id = orders.customer_id

GROUP BY customers.id
ORDER BY orders.order_date DESC;
</code>```

Body:
I have two tables, customers and orders which are inner joined. A customer can have several orders associated with them. In my selection, I then group by customers.id. I need to select the most recent order of each customer, but also the amount of money spent in that order. Currently, I can select the most recent order_date but do not know how to select the amount in the same row as the order_date.

This is my current query:

SELECT
    first_name,
    last_name,
    email,
    MAX(order_date) AS recent_order,
    amount -- this needs to select amount associated with recent_order
FROM customers
JOIN orders
    ON customers.id = orders.customer_id
GROUP BY customers.id;

The query selects the most recent date, but does not select the amount associated with the most recent order_date.

Table declarations:

CREATE TABLE customers (
    id INT AUTO_INCREMENT PRIMARY KEY,
    first_name VARCHAR(100),
    last_name VARCHAR(100),
    email VARCHAR(100)
);

CREATE TABLE orders (
    id INT AUTO_INCREMENT PRIMARY KEY,
    order_date DATE,
    amount DECIMAL(8,2),
    customer_id INT,
    FOREIGN KEY(customer_id) REFERENCES customers(id)
);

Body:
SELECT
    first_name,
    last_name,
    email,
    MAX(order_date) AS recent_order,
    (SELECT amount FROM orders WHERE order_date = MAX(order_date) AND customers.id = orders.customer_id) as amount
FROM customers
JOIN orders
    ON customers.id = orders.customer_id
GROUP BY customers.id;

OR

SELECT
    first_name,
    last_name,
    email,
    order_date AS recent_order,
    amount AS recent_order_amount
FROM customers
JOIN orders
    ON customers.id = orders.customer_id

GROUP BY customers.id
ORDER BY orders.order_date DESC;


问:
How to write a recursive function to search for a key in a binary tree using in-order traversal in C?
I am trying to write a recursive function that, given the root of a binary tree and a key, searches for the key using in-order traversal.  The function returns NULL if the node with the key isn't found; otherwise it returns the node containing the key.

What I'm having trouble with is returning the node that contains the key.  Every time I call the function and the key is in the binary tree, the function returns NULL.  It feels like the result keeps getting overwritten by the initialization in the first line in the function.

Here's the in-order search function:

```<code>typedef struct treeNode
{
    int data;
    struct treeNode *left, *right;
} TreeNode, *TreeNodePtr;

typedef struct
{
    TreeNodePtr root;
} BinaryTree;

TreeNodePtr inOrderKey(TreeNodePtr root, int key)
{
    TreeNodePtr node = NULL;

    if (root != NULL)
    {
        node = inOrderKey(root->left, key);
        if(key == root->data)
        {
           node = root;
           return node;
        }
        node = inOrderKey(root->right, key);
    }

    return node;
}
</code>```

Here's the main function:

```<code>int main()
{
    FILE * in = fopen("numbst.txt", "r");

    BinaryTree bst;
    bst.root = NULL;

    int num;

    fscanf(in, "%d", &num);
    while (num != 0)
    {
        if (bst.root == NULL)
            bst.root = newTreeNode(num);
        else
        {
            TreeNodePtr node = findOrInsert(bst, num);
        }
        fscanf(in, "%d", &num);
    }

    printf("\nThe in-order traversal is: ");
    inOrder(bst.root);
    printf("\nThe pre-order traversal is: ");
    preOrder(bst.root);

    TreeNodePtr keyNode;
    int count = 0;
    keyNode = inOrderKey(bst.root, 9);
    if (keyNode != NULL)
        count = 1;
    else
        count = 0;

    if (count == 1)
        printf("\n\n%d exists in the binary tree. In order traversal was used.\n", 9);
    else
        printf("\n\n%d doesn't exist in the binary tree. In order traversal was used.\n", 9);
        return 0;
}
</code>```

The in-order traversal of the binary tree I'm working with is: 1 2 3 4 5 7 9 21

The pre-order traversal of the binary tree is: 4 1 2 3 7 5 21 9

I'm testing the function using 9 and 31.

答:
[edited - updated to use in order traversal]

Traverse left. If key not found, then check root, if key doesn't match, then recurse right.

```<code>TreeNodePtr inOrderKey(TreeNodePtr root, int key)
{
    TreeNodePtr node = NULL;
    if (root)
    {
        node = inOrderKey(root->left, key);
        if (node) {
            return node;
        }
        if (key == root->data)
        {
           return root;
        }
        node = inOrderKey(root->right, key);
    }
    return node;
}
</code>```

Body:
I am trying to write a recursive function that, given the root of a binary tree and a key, searches for the key using in-order traversal.  The function returns NULL if the node with the key isn't found; otherwise it returns the node containing the key.

What I'm having trouble with is returning the node that contains the key.  Every time I call the function and the key is in the binary tree, the function returns NULL.  It feels like the result keeps getting overwritten by the initialization in the first line in the function.

Here's the in-order search function:

typedef struct treeNode
{
    int data;
    struct treeNode *left, *right;
} TreeNode, *TreeNodePtr;

typedef struct
{
    TreeNodePtr root;
} BinaryTree;

TreeNodePtr inOrderKey(TreeNodePtr root, int key)
{
    TreeNodePtr node = NULL;

    if (root != NULL)
    {
        node = inOrderKey(root->left, key);
        if(key == root->data)
        {
           node = root;
           return node;
        }
        node = inOrderKey(root->right, key);
    }

    return node;
}

Here's the main function:

int main()
{
    FILE * in = fopen("numbst.txt", "r");

    BinaryTree bst;
    bst.root = NULL;

    int num;

    fscanf(in, "%d", &num);
    while (num != 0)
    {
        if (bst.root == NULL)
            bst.root = newTreeNode(num);
        else
        {
            TreeNodePtr node = findOrInsert(bst, num);
        }
        fscanf(in, "%d", &num);
    }

    printf("\nThe in-order traversal is: ");
    inOrder(bst.root);
    printf("\nThe pre-order traversal is: ");
    preOrder(bst.root);

    TreeNodePtr keyNode;
    int count = 0;
    keyNode = inOrderKey(bst.root, 9);
    if (keyNode != NULL)
        count = 1;
    else
        count = 0;

    if (count == 1)
        printf("\n\n%d exists in the binary tree. In order traversal was used.\n", 9);
    else
        printf("\n\n%d doesn't exist in the binary tree. In order traversal was used.\n", 9);
        return 0;
}

The in-order traversal of the binary tree I'm working with is: 1 2 3 4 5 7 9 21

The pre-order traversal of the binary tree is: 4 1 2 3 7 5 21 9

I'm testing the function using 9 and 31.

Body:
[edited - updated to use in order traversal]

Traverse left. If key not found, then check root, if key doesn't match, then recurse right.

TreeNodePtr inOrderKey(TreeNodePtr root, int key)
{
    TreeNodePtr node = NULL;
    if (root)
    {
        node = inOrderKey(root->left, key);
        if (node) {
            return node;
        }
        if (key == root->data)
        {
           return root;
        }
        node = inOrderKey(root->right, key);
    }
    return node;
}


问:
Convert a list of words to a list of integers in scikit-learn
I want to convert a list of words to a list of integers in scikit-learn, and do so for a corpus that consists of a list of lists of words. E.g. the corpus can be a bunch of sentences.

I can do as follows using  sklearn.feature_extraction.text.CountVectorizer, but is there any simpler way? I suspect I may be missing some CountVectorizer functionalities, as it's a common pre-processing step in natural language processing. In this code I first fit CountVectorizer, then I have to iterate over each words of each list of words to generate the list of integers.

```<code>import sklearn
import sklearn.feature_extraction
import numpy as np

def reverse_dictionary(dict):
    '''
    http://stackoverflow.com/questions/483666/python-reverse-inverse-a-mapping
    '''
    return {v: k for k, v in dict.items()}

vectorizer = sklearn.feature_extraction.text.CountVectorizer(min_df=1)

corpus = ['This is the first document.',
        'This is the second second document.',
        'And the third one.',
        'Is this the first document? This is right.',]

X = vectorizer.fit_transform(corpus).toarray()

tokenizer = vectorizer.build_tokenizer()
output_corpus = []
for line in corpus:
    line = tokenizer(line.lower())
    output_line = np.empty_like(line, dtype=np.int)
    for token_number, token in np.ndenumerate(line):
        output_line[token_number] = vectorizer.vocabulary_.get(token)
    output_corpus.append(output_line)
print('output_corpus: {0}'.format(output_corpus))

word2idx = vectorizer.vocabulary_
print('word2idx: {0}'.format(word2idx))

idx2word = reverse_dictionary(word2idx)
print('idx2word: {0}'.format(idx2word))
</code>```

outputs:

```<code>output_corpus: [array([9, 3, 7, 2, 1]), # 'This is the first document.'
                array([9, 3, 7, 6, 6, 1]), # 'This is the second second document.'
                array([0, 7, 8, 4]), # 'And the third one.'
                array([3, 9, 7, 2, 1, 9, 3, 5])] # 'Is this the first document? This is right.'
word2idx: {u'and': 0, u'right': 5, u'third': 8, u'this': 9, u'is': 3, u'one': 4,
           u'second': 6, u'the': 7, u'document': 1, u'first': 2}
idx2word: {0: u'and', 1: u'document', 2: u'first', 3: u'is', 4: u'one', 5: u'right',
           6: u'second', 7: u'the', 8: u'third', 9: u'this'}
</code>```

答:
For a given text, the CountVectorizer is meant to return a vector that is the count of each word.

E.g. for the corpus:
corpus = ["the cat", "the dog"], the vectorizer will find 3 different words, thus it will output vectors of dimension 3 where "the" would correspond to the first dimension, "cat" to the second one, and "dog" to the third one. For instance, "the cat" would be transformed to [1, 1, 0], "the dog" to [1, 0, 1], and sentences with repeated words would have larger values (e.g. "the cat cat" → [1, 2, 0]).

For what you want to to, you would have a good time with the Zeugma package. You would just have to do the following (after runnning pip install zeugma in a terminal):

>>> from zeugma import TextsToSequences
>>> sequencer = TextsToSequences()
>>> sequencer.fit_transform(["this is a sentence.", "and another one."])
array([[1, 2, 3, 4], [5, 6, 7]], dtype=object)
```

<p>And you can always access the "index to word mapping: with</p>

```>>> sequencer.index_word
{1: 'this', 2: 'is', 3: 'a', 4: 'sentence', 5: 'and', 6: 'another', 7: 'one'}
```

<p>From there you can transform any new sentence with this mapping:</p>

```>>> sequencer.transform(["a sentence"])
array([[3, 4]])
```

I hope it helps!

Body:
I want to convert a list of words to a list of integers in scikit-learn, and do so for a corpus that consists of a list of lists of words. E.g. the corpus can be a bunch of sentences.

I can do as follows using  sklearn.feature_extraction.text.CountVectorizer, but is there any simpler way? I suspect I may be missing some CountVectorizer functionalities, as it's a common pre-processing step in natural language processing. In this code I first fit CountVectorizer, then I have to iterate over each words of each list of words to generate the list of integers.

import sklearn
import sklearn.feature_extraction
import numpy as np

def reverse_dictionary(dict):
    '''
    http://stackoverflow.com/questions/483666/python-reverse-inverse-a-mapping
    '''
    return {v: k for k, v in dict.items()}

vectorizer = sklearn.feature_extraction.text.CountVectorizer(min_df=1)

corpus = ['This is the first document.',
        'This is the second second document.',
        'And the third one.',
        'Is this the first document? This is right.',]

X = vectorizer.fit_transform(corpus).toarray()

tokenizer = vectorizer.build_tokenizer()
output_corpus = []
for line in corpus:
    line = tokenizer(line.lower())
    output_line = np.empty_like(line, dtype=np.int)
    for token_number, token in np.ndenumerate(line):
        output_line[token_number] = vectorizer.vocabulary_.get(token)
    output_corpus.append(output_line)
print('output_corpus: {0}'.format(output_corpus))

word2idx = vectorizer.vocabulary_
print('word2idx: {0}'.format(word2idx))

idx2word = reverse_dictionary(word2idx)
print('idx2word: {0}'.format(idx2word))

outputs:

output_corpus: [array([9, 3, 7, 2, 1]), # 'This is the first document.'
                array([9, 3, 7, 6, 6, 1]), # 'This is the second second document.'
                array([0, 7, 8, 4]), # 'And the third one.'
                array([3, 9, 7, 2, 1, 9, 3, 5])] # 'Is this the first document? This is right.'
word2idx: {u'and': 0, u'right': 5, u'third': 8, u'this': 9, u'is': 3, u'one': 4,
           u'second': 6, u'the': 7, u'document': 1, u'first': 2}
idx2word: {0: u'and', 1: u'document', 2: u'first', 3: u'is', 4: u'one', 5: u'right',
           6: u'second', 7: u'the', 8: u'third', 9: u'this'}

Body:
For a given text, the CountVectorizer is meant to return a vector that is the count of each word.

E.g. for the corpus:
corpus = ["the cat", "the dog"], the vectorizer will find 3 different words, thus it will output vectors of dimension 3 where "the" would correspond to the first dimension, "cat" to the second one, and "dog" to the third one. For instance, "the cat" would be transformed to [1, 1, 0], "the dog" to [1, 0, 1], and sentences with repeated words would have larger values (e.g. "the cat cat" → [1, 2, 0]).

For what you want to to, you would have a good time with the Zeugma package. You would just have to do the following (after runnning pip install zeugma in a terminal):

>>> from zeugma import TextsToSequences
>>> sequencer = TextsToSequences()
>>> sequencer.fit_transform(["this is a sentence.", "and another one."])
array([[1, 2, 3, 4], [5, 6, 7]], dtype=object)

And you can always access the "index to word mapping: with

>>> sequencer.index_word
{1: 'this', 2: 'is', 3: 'a', 4: 'sentence', 5: 'and', 6: 'another', 7: 'one'}

From there you can transform any new sentence with this mapping:

>>> sequencer.transform(["a sentence"])
array([[3, 4]])

I hope it helps!


问:
add a new column in the data frame
If I want to add a new column to the data frame, which is the divisor of the first two columns, is this the right way to do it?</p>

```<code>Newcolumn <- sum(Data$column1)/sum(Data$column2)
NewcolumnCol<- data.frame(Newcolumn,col.names=Newcolumn)
allData <- merge(Newcolumn, Data)
</code>```

答:
We can use transform instead of mergeing to directly create the column and update the 'Data'

```<code>Data <- transform(Data, NewColumn = sum(column1)/sum(column2))
</code>```

Or simply create the new column by assignment

```<code>Data$NewColumn <- with(Data, sum(column1)/sum(column2))
</code>```

The division of sum of two columns returns a single  and that gets recycled to the number of rows of the dataset with the assignment.

merge is mostly done when we have two datasets with one or more columns to match while doing the assignment.  Here, it is not the case

Title: add a new column in the data frame

Body:
If I want to add a new column to the data frame, which is the divisor of the first two columns, is this the right way to do it?

Newcolumn <- sum(Data$column1)/sum(Data$column2)
NewcolumnCol<- data.frame(Newcolumn,col.names=Newcolumn)
allData <- merge(Newcolumn, Data)

Body:
We can use transform instead of mergeing to directly create the column and update the 'Data'

Data <- transform(Data, NewColumn = sum(column1)/sum(column2))

Or simply create the new column by assignment

Data$NewColumn <- with(Data, sum(column1)/sum(column2))

The division of sum of two columns returns a single  and that gets recycled to the number of rows of the dataset with the assignment.

merge is mostly done when we have two datasets with one or more columns to match while doing the assignment.  Here, it is not the case


问:
Is there a fixed point representation available in C or Assembly
As far as I know, representing a fraction in C relies on floats and doubles which are in floating point representation.

Assume I'm trying to represent 1.5 which is a fixed point number (only one digit to the right of the radix point). Is there a way to represent such number in C or even assembly using a fixed point data type?

Are there even any fixed point instructions on x86 (or other architectures) which would operate on such type?

答: Every integral type can be used as a fixed point type.  A favorite of mine is to use int64_t with an implied 8 digit shift, e.g. you store 1.5 as 150000000 (1.5e8).  You'll have to analyze your use case to decide on an underlying type and how many digits to shift (that is, assuming you use base-10 scaling, which most people do).  But 64 bits scaled by 10^8 is a pretty reasonable starting point with a broad range of uses.


问:
WPF custom TabItem disappears upon restyle?
I have a TabControl with a custom TabItem. The view xaml looks like this.

<UserControl x:Class="PeripheryModule.Views.MainTabView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:PeripheryModule.Controls"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <TabControl>

            <TabItem Header="TabItem 4" />
            <local:CustomTabItem Header="Testing" />

        </TabControl>
    </Grid>
</UserControl>
```

<p>the CustomTabItem.xaml file looks like this</p>

<pre class="lang-xml prettyprint-override"><code><ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:PeripheryModule.Controls">

    <Style TargetType="{x:Type local:CustomTabItem}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:CustomTabItem}">
                    <Border Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}">
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

</ResourceDictionary>
</code>```

and the CustomTabItem.xaml.cs file looks like this

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace PeripheryModule.Controls
{
    public class CustomTabItem : TabItem
    {
        static CustomTabItem()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomTabItem), new FrameworkPropertyMetadata(typeof(CustomTabItem)));
        }
    }
}
</code>```

I get no errors thrown, all that happens is the tabItem simply doesn't show up. It will, however, show up if i comment out the DefaultStyleKeyProperty line in CustomTabItem.aspx.cs.

I've probably got this all set up wrong anyways. Ultimate goal is to have closeable tabs.

答:
As Schalk points out, the DefaultStyleKeyProperty identifies the key to the default Style, which must be contained in a Resource dictionary under a Themes folder. So if you move/rename your CustomTabItem.xaml to be under Themes\Generic.xaml, then it should load and be applied.

You can also create different versions of your styles based on the system themes, by adding files named AeroNormalColor.xaml, Classic.xaml, etc to the Themes folder. These files would need to have copies of your Style also, presumably with visual tweaks.

You can download the default Styles for the native controls from here. This would allow you to copy the default Style for TabItem and tweak it to your needs.

Or you could do something like in this question, where the close button is added to the HeaderTemplate.

Body:
I have a TabControl with a custom TabItem. The view xaml looks like this.

<UserControl x:Class="PeripheryModule.Views.MainTabView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:PeripheryModule.Controls"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <TabControl>

            <TabItem Header="TabItem 4" />
            <local:CustomTabItem Header="Testing" />

        </TabControl>
    </Grid>
</UserControl>

the CustomTabItem.xaml file looks like this

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:PeripheryModule.Controls">

</ResourceDictionary>

and the CustomTabItem.xaml.cs file looks like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace PeripheryModule.Controls
{
    public class CustomTabItem : TabItem
    {
        static CustomTabItem()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomTabItem), new FrameworkPropertyMetadata(typeof(CustomTabItem)));
        }
    }
}

I get no errors thrown, all that happens is the tabItem simply doesn't show up. It will, however, show up if i comment out the DefaultStyleKeyProperty line in CustomTabItem.aspx.cs.

I've probably got this all set up wrong anyways. Ultimate goal is to have closeable tabs.


问:
Print Python output into two columns
Trying to replicate a basic column command in a Python program to print a list of States to the user via the command line:

```<code>us_states_list_with_population = [
("Alabama" , "AL" , 4903185),
("Montana" , "MT" , 1068778),
("Alaska" , "AK" , 731545),
...

]

for state_name , state_abbreviation , num_counties in us_states_list_with_population:
    print(state_name + " (" + state_abbreviation + ")")
</code>```

Is there an easy way to split the output into two or three columns to make this shorter and more readable?

Desired output would be something like:

```<code>Alabama (AL)        Alaska (AK)
Montana (MT)        California (CA)
...
</code>```

Versus:

```<code>Alabama (AL)
Alaska (AK)
Montana (MT)
California (CA)
...
</code>```

答:
To achieve your desired OUTPUT you can try this.

```<code>us_states_list_with_population = [
("Alabama" , "AL" , 4903185),
("Montana" , "MT" , 1068778),
("Alaska" , "AK" , 731545),
]

row = []
num_of_columns = 2
for state_name , state_abbreviation , num_counties in us_states_list_with_population:
    row.append(f'{state_name} ({state_abbreviation})')
    if len(row) == num_of_columns:
        print(("\t").join(row))
        row.clear()
print(("\t").join(row)) # print last row if there is a remainder
</code>```

Or if you want to learn more prettier tabulates check @cricket_007 comments.

Title: Print Python output into two columns

Body:
Trying to replicate a basic column command in a Python program to print a list of States to the user via the command line:

us_states_list_with_population = [
("Alabama" , "AL" , 4903185),
("Montana" , "MT" , 1068778),
("Alaska" , "AK" , 731545),
...

]

for state_name , state_abbreviation , num_counties in us_states_list_with_population:
    print(state_name + " (" + state_abbreviation + ")")

Is there an easy way to split the output into two or three columns to make this shorter and more readable?

Desired output would be something like:

Alabama (AL)        Alaska (AK)
Montana (MT)        California (CA)
...

Versus:

Alabama (AL)
Alaska (AK)
Montana (MT)
California (CA)
...

Body:
To achieve your desired OUTPUT you can try this.

us_states_list_with_population = [
("Alabama" , "AL" , 4903185),
("Montana" , "MT" , 1068778),
("Alaska" , "AK" , 731545),
]

row = []
num_of_columns = 2
for state_name , state_abbreviation , num_counties in us_states_list_with_population:
    row.append(f'{state_name} ({state_abbreviation})')
    if len(row) == num_of_columns:
        print(("\t").join(row))
        row.clear()
print(("\t").join(row)) # print last row if there is a remainder

Or if you want to learn more prettier tabulates check @cricket_007 comments.