问:
I try API request post with body type raw to get a token but need understand what is wrong
My method to get tokenKey is :

```<code>        HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
        httpRequest.Method = "POST";
        httpRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36 OPR/52.0.2871.99";

        string tokenResponse = null;

        HttpClient client = new HttpClient();

        HttpResponseMessage response = null;
        try
        {
            client.DefaultRequestHeaders.Add("x-api-key", "key");
            if (method.Equals("POST"))
            {

                httpRequest.Accept = "application/json";
                httpRequest.ContentType = "application/json";

                var data = @"{""username"":@"""+ login + @""",""password"" :@"""+ password + @"""}";

                using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
                {
                    streamWriter.Write(data);
                }

                var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                  tokenResponse = streamReader.ReadToEnd();
                }
            }
       }
catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }

        return tokenResponse;
</code>```

after  var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
this error msg: The underlying connection was closed: Unexpected error on a send.

x-api-key is okay but i don't put the original as the username and password
i do it easy with postman
postman request done

Can anyone help me understand where I'm going wrong?

答: See documentation, how to use HttpWebRequest and how to write body properly to request. I think the problem is with a request stream.</p>

Body:
My method to get tokenKey is :

        HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
        httpRequest.Method = "POST";
        httpRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36 OPR/52.0.2871.99";

        string tokenResponse = null;

        HttpClient client = new HttpClient();

        HttpResponseMessage response = null;
        try
        {
            client.DefaultRequestHeaders.Add("x-api-key", "key");
            if (method.Equals("POST"))
            {

                httpRequest.Accept = "application/json";
                httpRequest.ContentType = "application/json";

                var data = @"{""username"":@"""+ login + @""",""password"" :@"""+ password + @"""}";

                using (var streamWriter = new StreamWriter(httpRequest.GetRequestStream()))
                {
                    streamWriter.Write(data);
                }

                var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                  tokenResponse = streamReader.ReadToEnd();
                }
            }
       }
catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }

        return tokenResponse;

after  var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
this error msg: The underlying connection was closed: Unexpected error on a send.

x-api-key is okay but i don't put the original as the username and password
i do it easy with postman
postman request done

Can anyone help me understand where I'm going wrong?


来源: stackexchange

问:
How to tell if a website is static or dynamic?
My prof said that dynamic pages get created by the computer, while static pages are created by the user.

Thank you so much!

答:
The difference between static pages and dynamic pages.

a static page has a generic URL suffix, such as .htm, .html, .shtml, and does not contain "?";

Websites using dynamic page skills can perform more functions such as user registration, login, online survey, user management, order management, etc.;

Application and web languages:

Static web pages: HTML, JavaScript, CSS, etc.

Dynamic Web Pages: PHP, CGI, AJAX, ASP, ASP.NET, etc.

Dynamic web pages are used where information changes frequently, such as stock prices, weather information, news and sports news.

Static web pages have fixed content, while dynamic web pages can have changing content.

Static web pages must be modified manually, while changes to a dynamic page can be loaded through an application whose resources are stored in a database.

Static web pages only use a web server, while dynamic web pages use a web server, an application server, and a database.

ContentLicense: CC BY-SA 4.0


问:
How do I change the bool variable in the parent process when Ctrl+Z is pressed?
I am trying to implement a custom shell in linux from scratch. In this, I am building two features apart from other basic ones: when user presses ctrl+c, then my custom shell stops executing whatever command it is executing at that moment, and when the user presses ctrl+z, then my custom shell moves the currently executing command to the background.

Here are the bare bones code and implementation details:

```<code>//global variable for storing child process id
pid_t child_pid = -1;
//global variable for storing parent process id
pid_t parent_pid = getpid();
//global variable for storing bg flag
bool bg = false;

void sigintHandler(int dummy) {
    kill(child_pid, SIGKILL);
    printf("\n");
}

void sigtstpHandler(int dummy) {
    pid_t present_pid = getpid();
    if(present_pid == parent_pid) {
        bg = true;
    }
}

int main() {

    while (true) {
        signal(SIGINT, sigintHandler);
        signal(SIGTSTP, sigtstpHandler);

        cout < ">>";
        //take command from user

        child_pid = fork();
        if(child_pid == 0) {
            //code for child process
        }
        else {
            if(!bg)
                wait(&child status);
        }
    }

    return 0;
}
</code>```

What I am trying to do is that when the user presses ctrl+z, the code should enter the sigtstpHandler function, and if it is in the parent process, change the value of the bg to true so that it stops waiting for the child process to terminate. However, this is not working. Whenever I press Ctrl+Z, the code just hangs apparently or something. Can someone please explain what I am doing wrong? And how to make the parent process stop waiting when ctrl+z is pressed?

答:
By default, after the signal handler completes (and returns) the process will go back and 'restart' whatever system call it was doing.  So in this case, the parent was in the wait(&child status) call, so it will go back and continue waiting; it will not check the bg flag again.

If you want the signal to interrupt the wait call, you need to use sigaction instead of signal so you can specify the flags, and in particular, do not set the SA_RESTART flag.  Then, you also need to check the return value of the wait call, and if it is -1 and errno == EINTR you need to re-check the bg flag and do the right thing.

Body:
I am trying to implement a custom shell in linux from scratch. In this, I am building two features apart from other basic ones: when user presses ctrl+c, then my custom shell stops executing whatever command it is executing at that moment, and when the user presses ctrl+z, then my custom shell moves the currently executing command to the background.

Here are the bare bones code and implementation details:

//global variable for storing child process id
pid_t child_pid = -1;
//global variable for storing parent process id
pid_t parent_pid = getpid();
//global variable for storing bg flag
bool bg = false;

void sigintHandler(int dummy) {
    kill(child_pid, SIGKILL);
    printf("\n");
}

void sigtstpHandler(int dummy) {
    pid_t present_pid = getpid();
    if(present_pid == parent_pid) {
        bg = true;
    }
}

int main() {

    while (true) {
        signal(SIGINT, sigintHandler);
        signal(SIGTSTP, sigtstpHandler);

        cout < ">>";
        //take command from user

        child_pid = fork();
        if(child_pid == 0) {
            //code for child process
        }
        else {
            if(!bg)
                wait(&child status);
        }
    }

    return 0;
}

What I am trying to do is that when the user presses ctrl+z, the code should enter the sigtstpHandler function, and if it is in the parent process, change the value of the bg to true so that it stops waiting for the child process to terminate. However, this is not working. Whenever I press Ctrl+Z, the code just hangs apparently or something. Can someone please explain what I am doing wrong? And how to make the parent process stop waiting when ctrl+z is pressed?


问:
How do i use captcha in the asp.net application for test input in simple way
I'm working on asp.net web application where I need to use CAPTCHA to test input enter into textbox please let me know very simple way to implement CAPTCHA in asp.net.</p>

答:
Create a handler (ashx).

Generate a random string, save that string into session, then use GDI+ to draw an image and sent it to response with content type is image/...

On captcha validation, load previous string from session and do the comparison.

ContentLicense: CC BY-SA 3.0


问:
API gateway - message "select an integration response." when creating stack using cloudformation
This is what I am expecting to see in API Gateway after creating the stack.

But this is what's actually happen.

In the method response, it shows message "select an integration response.", but
I did add the model in the method response, and "HTTP status: Proxy" should be shown

What's going on?

resources.json

```<code>{
    "AWSTemplateFormatVersion": "2010-09-09",

    "Resources": {
      "HelloWorldApi": {
        "Type": "AWS::ApiGateway::RestApi",
        "Properties": {
          "Name": "hello-api",
          "Description": "API used for practice",
          "FailOnWarnings": true
        }
      },
      "getBannerMethod": {
        "Type": "AWS::ApiGateway::Method",
        "DependsOn": ["HelloWorldApi"],
        "Properties": {
          "RestApiId": {
            "Ref": "HelloWorldApi"
          },
          "ResourceId": {
            "Ref": "BannerResource"
          },
          "HttpMethod": "GET",
          "MethodResponses":[
            {
              "ResponseModels" : {"application/json" : "Empty"},
              "ResponseParameters":{
                "method.response.header.Access-Control-Allow-Origin": "'*'"
              },
              "StatusCode" : "200"
            },
            {
              "StatusCode": "500"
            }
          ],
          "AuthorizationType": "NONE",
          "Integration": {
            "Credentials": {
              "Fn::ImportValue": {
                "Fn::Sub": "${RolesStack}-ApiGatewayRoleArn"
              }
            },
            "IntegrationHttpMethod": "POST",
            "Type": "AWS_PROXY",
            "Uri": {
              "Fn::Join": ["",
                [
                  "arn:aws:apigateway:",
                  {
                    "Ref": "AWS::Region"
                  },
                  ":lambda:path/2015-03-31/functions/",
                  {
                    "Fn::GetAtt": ["getBannerHandler", "Arn"]
                  },
                  "/invocations"
                ]
              ]
            }
          }
        }
      }
    }
  }

</code>```

答:
For those looking for the quick hack workaround to get it working from the console (like me).

I found the answer here: https://github.com/hashicorp/terraform-provider-aws/issues/11561

The only way to fix this issue is to login to the AWS Console and the do the following:

Go to "Integration request" and then uncheck "Use Lambda Proxy integration" and then check it again.

After performing the above steps the Method response correctly shows the mapped model.

Body:
This is what I am expecting to see in API Gateway after creating the stack.

But this is what's actually happen.

In the method response, it shows message "select an integration response.", but
I did add the model in the method response, and "HTTP status: Proxy" should be shown

What's going on?

resources.json

{
    "AWSTemplateFormatVersion": "2010-09-09",

    "Resources": {
      "HelloWorldApi": {
        "Type": "AWS::ApiGateway::RestApi",
        "Properties": {
          "Name": "hello-api",
          "Description": "API used for practice",
          "FailOnWarnings": true
        }
      },
      "getBannerMethod": {
        "Type": "AWS::ApiGateway::Method",
        "DependsOn": ["HelloWorldApi"],
        "Properties": {
          "RestApiId": {
            "Ref": "HelloWorldApi"
          },
          "ResourceId": {
            "Ref": "BannerResource"
          },
          "HttpMethod": "GET",
          "MethodResponses":[
            {
              "ResponseModels" : {"application/json" : "Empty"},
              "ResponseParameters":{
                "method.response.header.Access-Control-Allow-Origin": "'*'"
              },
              "StatusCode" : "200"
            },
            {
              "StatusCode": "500"
            }
          ],
          "AuthorizationType": "NONE",
          "Integration": {
            "Credentials": {
              "Fn::ImportValue": {
                "Fn::Sub": "${RolesStack}-ApiGatewayRoleArn"
              }
            },
            "IntegrationHttpMethod": "POST",
            "Type": "AWS_PROXY",
            "Uri": {
              "Fn::Join": ["",
                [
                  "arn:aws:apigateway:",
                  {
                    "Ref": "AWS::Region"
                  },
                  ":lambda:path/2015-03-31/functions/",
                  {
                    "Fn::GetAtt": ["getBannerHandler", "Arn"]
                  },
                  "/invocations"
                ]
              ]
            }
          }
        }
      }
    }
  }


问:
Pydantic mangling input
In the following example, I can't understand why pydantic is mangling the type input.

from pydantic import BaseModel
from typing import Union, List

class Foo(BaseModel):
    bar: Union[str, dict, List[dict]]

f = Foo(bar=[{'foo': 'bar', 'stuff': 'things'}])
assert f.bar == {'foo': 'stuff'}
```

Why is the type changing from a list to a dict and further mangling the keys into a key value pair? Don't know if this is pydantic specific or just typing issues.

And as a followup, what can I do to fix this so that the types aren't mangled.

答:
Answer came from asking in the repo.

Basically this was fixed in the most recent version of pydantic if you include a smart union config value.

from pydantic import BaseModel
from typing import Union, List

class Foo(BaseModel, smart_union=True):
    bar: Union[str, dict, List[dict]]

f = Foo(bar=[{'foo': 'bar', 'stuff': 'things'}])
assert f.bar == [{'foo': 'bar', 'stuff': 'things'}]
```

Title: Pydantic mangling input

Body:
In the following example, I can't understand why pydantic is mangling the type input.

from pydantic import BaseModel
from typing import Union, List

class Foo(BaseModel):
    bar: Union[str, dict, List[dict]]

f = Foo(bar=[{'foo': 'bar', 'stuff': 'things'}])
assert f.bar == {'foo': 'stuff'}

Why is the type changing from a list to a dict and further mangling the keys into a key value pair? Don't know if this is pydantic specific or just typing issues.

And as a followup, what can I do to fix this so that the types aren't mangled.


问:
Anylogic: How to create an objective function using values of two dataset (for optimization experiment)?
In my Anylogic model I have a population of agents (4 terminals) were trucks arrive at, are being served and depart from. The terminals have two parameters (numberOfGates and servicetime) which influence the departures per hour of trucks leaving the terminals. Now I want to tune these two parameters, so that the amount of departures per hour is closest to reality (I know the actual departures per hour). I already have two datasets within each terminal agent, one with de amount of departures per hour that I simulate, and one with the observedDepartures from the data.

I already compare these two datasets in plots for every terminal:

Now I want to create an optimization experiment to tune the numberOfGates and servicetime of the terminals so that the departure dataset is the closest to the observedDepartures dataset. Does anyone know how to do create a(n) (objective) function for this optimization experiment the easiest way?

When I add a variable diff that is updated every hour by abs( departures - observedDepartures) and put root.diff in the optimization experiment, it gives me the eq(null) is not allowed. Use isNull() instead error, in a line that reads the database for the observedDepartures (see last picture), but it works when I run the simulation normally, it only gives this error when running the optimization experiment (I don't know why).

答:
A Calibration experiment already does (in a more mathematically correct way) what you are trying to do, using the in-built difference function to calculate the 'area between two curves' (which is what the optimisation is trying to minimise). You don't need to calculate differences or anything yourself. (There are two variants of the function to compare either two Data Sets (your case) or a Data Set and a Table Function (useful if your empirical data is not at the same time points as your synthetic simulated data).)

In your case it (the objective function) will need to be a sum of the differences between the empirical and simulated datasets for the 4 terminals (or possibly a weighted sum if the fit for some terminals is considered more important than for others).

So your objective is something like

```<code>difference(root.terminals(0).departures, root.terminals(0).observedDepartures)
+ difference(root.terminals(1).departures, root.terminals(1).observedDepartures)
+ difference(root.terminals(2).departures, root.terminals(2).observedDepartures)
+ difference(root.terminals(3).departures, root.terminals(2).observedDepartures)
</code>```

(It would be better to calculate this for an arbitrary population of terminals in a function but this is the 'raw shape' of the code.)

A Calibration experiment is actually just a wizard which creates an Optimization experiment set up in a particular way (with a UI and all settings/code already created for you), so you can just use that objective in your existing Optimization experiment (but it won't have a built-in useful UI like a Calibration experiment). This also means you can still set this up in the Personal Learning Edition too (which doesn't have the Calibration experiment).

Body:
A Calibration experiment already does (in a more mathematically correct way) what you are trying to do, using the in-built difference function to calculate the 'area between two curves' (which is what the optimisation is trying to minimise). You don't need to calculate differences or anything yourself. (There are two variants of the function to compare either two Data Sets (your case) or a Data Set and a Table Function (useful if your empirical data is not at the same time points as your synthetic simulated data).)

In your case it (the objective function) will need to be a sum of the differences between the empirical and simulated datasets for the 4 terminals (or possibly a weighted sum if the fit for some terminals is considered more important than for others).

So your objective is something like

difference(root.terminals(0).departures, root.terminals(0).observedDepartures)
+ difference(root.terminals(1).departures, root.terminals(1).observedDepartures)
+ difference(root.terminals(2).departures, root.terminals(2).observedDepartures)
+ difference(root.terminals(3).departures, root.terminals(2).observedDepartures)

(It would be better to calculate this for an arbitrary population of terminals in a function but this is the 'raw shape' of the code.)

A Calibration experiment is actually just a wizard which creates an Optimization experiment set up in a particular way (with a UI and all settings/code already created for you), so you can just use that objective in your existing Optimization experiment (but it won't have a built-in useful UI like a Calibration experiment). This also means you can still set this up in the Personal Learning Edition too (which doesn't have the Calibration experiment).


问:
Wordpress loop - how to count items
Is there a way to get a number of items within Wordpress loop code:

```<code><?php while (have_posts()) : the_post(); ?>
</code>```

This loop lists the posts. I need to add certain classes to first 3 depending on the total number of them.

答:
The easiest would be wc_get_loop_prop( 'total' )

If you want to get it in a template and you don't have access to the loop variable, like in your example.

Title: Wordpress loop - how to count items

Body:
Is there a way to get a number of items within Wordpress loop code:

<?php while (have_posts()) : the_post(); ?>

This loop lists the posts. I need to add certain classes to first 3 depending on the total number of them.


问:
Selenium click not always working
I have some tests which click on a tab, however the click is not always performed.

The xpath is correct as most of the times the test works

It is not a timing issue as I ve used thread.sleep() and other methods to ensure that the element is visible before clicking

The test believes that it is performing the click as it is not throwing an ElementNotFoundException or any other exceptions when 'performing' the click. The test fails later on after the click since the tab content would not have changed.

Further Info
I am using Selenium 2.44.0 to implement tests in Java which run on Chrome 44.0.2403.107 m.

Is there something else that I can do or could this be an issue with selenium?

答:
I have a similar problem. Tried all solutions from the top answer. Sometimes they work, sometimes don't.

But running code in an infinite loop works always.

For example, we need to click on element-two which is not visible until element-one is clicked.

```<code>WebDriverWait wait = new WebDriverWait(webDriver, 10);
while (true){
    try {
        WebElement elementOne =
              wait.until(ExpectedConditions.elementToBeClickable(By.id("element-one")));
        elementOne.click();
        WebElement elementTwo =
              wait.until(ExpectedConditions.elementToBeClickable(By.id("element-two")));
        elementTwo.click();
        break;
    } catch (Exception e){
        //log
    }

}
</code>```

Title: Selenium click not always working

Body:
I have a similar problem. Tried all solutions from the top answer. Sometimes they work, sometimes don't.

But running code in an infinite loop works always.

For example, we need to click on element-two which is not visible until element-one is clicked.

WebDriverWait wait = new WebDriverWait(webDriver, 10);
while (true){
    try {
        WebElement elementOne =
              wait.until(ExpectedConditions.elementToBeClickable(By.id("element-one")));
        elementOne.click();
        WebElement elementTwo =
              wait.until(ExpectedConditions.elementToBeClickable(By.id("element-two")));
        elementTwo.click();
        break;
    } catch (Exception e){
        //log
    }

}


问:
How to link executable to dylib to make the program relocable - preferable using cmake
I have a simple application that creates dylib and executable and links the 2 of them togather

```<code>cmake_minimum_required (VERSION 3.4)
project (SampleApplication)
add_library(SampleSharedLibrary SHARED some.cpp)
add_executable(SampleApplication main.cpp)
target_link_libraries(SampleApplication SampleSharedLibrary)
</code>```

The problem is that when I copy the files to other directory

```<code>cp bin/* other_directory/
</code>```

it stops working with error

dyld: Library not loaded: @rpath/libSampleSharedLibrary.dylib

  Referenced from: /some_path/other_directory/./SampleApplication

  Reason: image not found
  Abort trap: 6

Other informations:

cmake version 3.7.2

otool -D libSampleSharedLibrary.dylib

libSampleSharedLibrary.dylib:

@rpath/libSampleSharedLibrary.dylib

I did some googling and I just can't find a way to achieve this in cmake - either I'm using wrong properties or maybe I don't get the syntax right. I found some posts that adviced using instal_name_tool but I would rather stick to just cmake as I think it should be doable just in cmake. I figured out the solution should be to either use "@executable_path" (or @loader_path) as install_name in dylib, or stick to rpath in dylib and add rpath to executable with "@executable_path"

So my question is how to create in cmake relocatable dylib and executable pair. A working cmake code example would be perfect. If you are fluent in this area and you can find a few ways to do it I would appreciate if you listed them with some explanation.

答:
I know this question is very old, but I'm putting this answer out here for those that will stumble upon the same problem so that they don't end up spending hours on the problem like I did.

Since you are on macOS, add the following lines before the add_library and add_executable lines.

```<code>set(CMAKE_INSTALL_RPATH "@loader_path")
set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
</code>```

For a solution that works for both Linux and macOS, Use the following instead:

```<code>if(UNIX)
    if(APPLE)
        set(CMAKE_INSTALL_RPATH "@loader_path")
    else()
        set(CMAKE_INSTALL_RPATH "$ORIGIN")
    endif()
    set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)
    set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
endif()
</code>```

To alter the path relative to your executable (e.g. to use the lib directory), simple append the path to the exisiting one. E.g. @loader_path/lib and $ORIGIN/lib etc...

Body:
I have a simple application that creates dylib and executable and links the 2 of them togather

cmake_minimum_required (VERSION 3.4)
project (SampleApplication)
add_library(SampleSharedLibrary SHARED some.cpp)
add_executable(SampleApplication main.cpp)
target_link_libraries(SampleApplication SampleSharedLibrary)

The problem is that when I copy the files to other directory

cp bin/* other_directory/

it stops working with error

dyld: Library not loaded: @rpath/libSampleSharedLibrary.dylib

  Referenced from: /some_path/other_directory/./SampleApplication

  Reason: image not found
  Abort trap: 6

Other informations:

cmake version 3.7.2

otool -D libSampleSharedLibrary.dylib

libSampleSharedLibrary.dylib:

@rpath/libSampleSharedLibrary.dylib

I did some googling and I just can't find a way to achieve this in cmake - either I'm using wrong properties or maybe I don't get the syntax right. I found some posts that adviced using instal_name_tool but I would rather stick to just cmake as I think it should be doable just in cmake. I figured out the solution should be to either use "@executable_path" (or @loader_path) as install_name in dylib, or stick to rpath in dylib and add rpath to executable with "@executable_path"

So my question is how to create in cmake relocatable dylib and executable pair. A working cmake code example would be perfect. If you are fluent in this area and you can find a few ways to do it I would appreciate if you listed them with some explanation.

Body:
I know this question is very old, but I'm putting this answer out here for those that will stumble upon the same problem so that they don't end up spending hours on the problem like I did.

Since you are on macOS, add the following lines before the add_library and add_executable lines.

set(CMAKE_INSTALL_RPATH "@loader_path")
set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)

For a solution that works for both Linux and macOS, Use the following instead:

if(UNIX)
    if(APPLE)
        set(CMAKE_INSTALL_RPATH "@loader_path")
    else()
        set(CMAKE_INSTALL_RPATH "$ORIGIN")
    endif()
    set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)
    set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
endif()

To alter the path relative to your executable (e.g. to use the lib directory), simple append the path to the exisiting one. E.g. @loader_path/lib and $ORIGIN/lib etc...


问:
How can I solve "No module named 'pyi_splash'" after using pyinstaller?
I'm trying to add a splashscreen to my app using pyinstaller by this:

```<code>pyinstaller.exe --onefile --splash=Splash_screen.png --icon=Icon.ico JIGOverview.pyw
</code>```

this opens the splashscreen but it never closes so then I try to add this code to my Python code:

```<code>import pyi_splash
pyi_splash.update_text('UI Loaded ...')
pyi_splash.close()

</code>```

but I get a "No module named 'pyi_splash'" error. How do I add this module to my code?

答:
Add the --hidden-import option:</p>
```<code>pyinstaller.exe --onefile --splash=Splash_screen.png --icon=Icon.ico --hidden-import=pyi_splash JIGOverview.pyw
</code>```

Body:
I'm trying to add a splashscreen to my app using pyinstaller by this:

pyinstaller.exe --onefile --splash=Splash_screen.png --icon=Icon.ico JIGOverview.pyw

this opens the splashscreen but it never closes so then I try to add this code to my Python code:

import pyi_splash
pyi_splash.update_text('UI Loaded ...')
pyi_splash.close()

but I get a "No module named 'pyi_splash'" error. How do I add this module to my code?

Body:
Add the --hidden-import option:

pyinstaller.exe --onefile --splash=Splash_screen.png --icon=Icon.ico --hidden-import=pyi_splash JIGOverview.pyw


问:
What features are people looking forward to in .Net 4.0 - 4.1
I am very interested in learning what features people are interested in in the forthcoming .net framework(s)?

Whether these be new classes or new controls I am curious to know people views.

答:
The promise of alot better Sharepoint developer tools and support, 'cause when you have to work in it currently, it's a bit of a pain.

Just the deployment options they plan on having will save some headaches.

So I'm optimistic they have listened to the groans from the developer community.

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: curtisk


问:
How to use pyspark to do some calculations of a csv file?
I am working on one CSV file below using PySpark(on databricks), but I am not sure how to get the total scan (event name) duration time. Assume one scan per time.

timestamp
event
value

1
2020-11-17_19:15:33.438102
scan
start

2
2020-11-17_19:18:33.433002
scan
end

3
2020-11-17_20:05:21.538125
scan
start

4
2020-11-17_20:13:08.528102
scan
end

5
2020-11-17_21:23:19.635104
pending
start

6
2020-11-17_21:33:26.572123
pending
end

7
2020-11-17_22:05:29.738105
pending
start

.........

Below are some of my thoughts:

first get scan start time

```<code>scan_start = df[(df['event'] == 'scan') & (df['value'] == 'start')]

scan_start_time = scan_start['timestamp']
</code>```

get scan end time

```<code>scan_end = df[(df['event'] == 'scan') & (df['value'] == 'end')]

scan_end_time = scan_start['timestamp']
</code>```

the duration of each scan

```<code>each_duration = scan_end_time.values - scan_start_time.values
</code>```

total duration

```<code>total_duration_ns = each_duration.sum()
</code>```

But, I am not sure how to do the calculation in PySpark.

First, do we need to create a schema to pre-define the column name 'timestamp' type in timestamp? (Assume all the column types (timestamp, event, value) are in str type)

On the other hand, assume we have multiple(1000+files) similar to the above CSV files stored in databricks, how can we create a reusable code for all the CSV files. Eventually, create one table to store info of the total scan_duration.

Can someone please share with me some code in PySpark?
Thank you so much

答:
This code will compute for each row the difference between the current timestamp and the timestamp in the previous row.

I'm creating a dataframe for reproducibility.

```<code>from pyspark.sql import SparkSession, Window
from pyspark.sql.types import *
from pyspark.sql.functions import regexp_replace, col, lag
import pandas as pd

spark = SparkSession.builder.appName("DataFarme").getOrCreate()
data = pd.DataFrame(
    {
        "timestamp": ["2020-11-17_19:15:33.438102","2020-11-17_19:18:33.433002","2020-11-17_20:05:21.538125","2020-11-17_20:13:08.528102"],
        "event": ["scan","scan","scan","scan"],
        "value": ["start","end","start","end"]
    }
)
df=spark.createDataFrame(data)
df.show()
# +--------------------+-----+-----+
# |           timestamp|event|value|
# +--------------------+-----+-----+
# |2020-11-17_19:15:...| scan|start|
# |2020-11-17_19:18:...| scan|  end|
# |2020-11-17_20:05:...| scan|start|
# |2020-11-17_20:13:...| scan|  end|
# +--------------------+-----+-----+
</code>```

Convert "timestamp" column to TimestampType() to be able to compute differences:

```<code>df=df.withColumn("timestamp",
regexp_replace(col("timestamp"),"_"," "))
df.show(truncate=False)
# +——————————-------------———+---——+—---—+
# |timestamp                 |event|value|
# +————————————-------------—+---——+—---—+
# |2020-11-17 19:15:33.438102|scan |start|
# |2020-11-17 19:18:33.433002|scan |end  |
# |2020-11-17 20:05:21.538125|scan |start|
# |2020-11-17 20:13:08.528102|scan |end  |
# +——————————-------------———+---——+---——+

df = df.withColumn("timestamp",
regexp_replace(col("timestamp"),"_"," ").cast(TimestampType()))
df.dtypes
#  [('timestamp', 'timestamp'), ('event', 'string'), ('value', 'string')]
</code>```

Use pyspark.sql.functions.lag function that returns the value of the previous row (offset=1 by default).
See also How to calculate the difference between rows in PySpark? or Applying a Window function to calculate differences in pySpark

```<code>df.withColumn("lag_previous", col("timestamp").cast("long") - lag('timestamp').over(
    Window.orderBy('timestamp')).cast("long")).show(truncate=False)
# WARN WindowExec: No Partition Defined for Window operation! Moving all data to a single partition, this can cause serious performance degradation.
</code>```

Using Window without partition gives a warning.

It is better to partition the dataframe for the Window operation, I partitioned here by type of event:

```<code>df.withColumn("lag_previous", col("timestamp").cast("long") - lag('timestamp').over(
    Window.partitionBy("event").orderBy('timestamp')).cast("long")).show(truncate=False)
# +———————————-------------——+---——+—---—+—------—————+
# |timestamp                 |event|value|lag_previous|
# +———————————-------------——+---——+---——+------——————+
# |2020-11-17 19:15:33.438102|scan |start|null        |
# |2020-11-17 19:18:33.433002|scan |end  |180         |
# |2020-11-17 20:05:21.538125|scan |start|2808        |
# |2020-11-17 20:13:08.528102|scan |end  |467         |
# +—————-------------————————+---——+—---—+—------—————+
</code>```

From this table you can filter out the rows with "end" value to get the total durations.

Body:
I am working on one CSV file below using PySpark(on databricks), but I am not sure how to get the total scan (event name) duration time. Assume one scan per time.

timestamp
event
value

1
2020-11-17_19:15:33.438102
scan
start

2
2020-11-17_19:18:33.433002
scan
end

3
2020-11-17_20:05:21.538125
scan
start

4
2020-11-17_20:13:08.528102
scan
end

5
2020-11-17_21:23:19.635104
pending
start

6
2020-11-17_21:33:26.572123
pending
end

7
2020-11-17_22:05:29.738105
pending
start

.........

Below are some of my thoughts:

first get scan start time

scan_start = df[(df['event'] == 'scan') & (df['value'] == 'start')]

scan_start_time = scan_start['timestamp']

get scan end time

scan_end = df[(df['event'] == 'scan') & (df['value'] == 'end')]

scan_end_time = scan_start['timestamp']

the duration of each scan

each_duration = scan_end_time.values - scan_start_time.values

total duration

total_duration_ns = each_duration.sum()

But, I am not sure how to do the calculation in PySpark.

First, do we need to create a schema to pre-define the column name 'timestamp' type in timestamp? (Assume all the column types (timestamp, event, value) are in str type)

On the other hand, assume we have multiple(1000+files) similar to the above CSV files stored in databricks, how can we create a reusable code for all the CSV files. Eventually, create one table to store info of the total scan_duration.

Can someone please share with me some code in PySpark?
Thank you so much

Body:
This code will compute for each row the difference between the current timestamp and the timestamp in the previous row.

I'm creating a dataframe for reproducibility.

from pyspark.sql import SparkSession, Window
from pyspark.sql.types import *
from pyspark.sql.functions import regexp_replace, col, lag
import pandas as pd

spark = SparkSession.builder.appName("DataFarme").getOrCreate()
data = pd.DataFrame(
    {
        "timestamp": ["2020-11-17_19:15:33.438102","2020-11-17_19:18:33.433002","2020-11-17_20:05:21.538125","2020-11-17_20:13:08.528102"],
        "event": ["scan","scan","scan","scan"],
        "value": ["start","end","start","end"]
    }
)
df=spark.createDataFrame(data)
df.show()
# +--------------------+-----+-----+
# |           timestamp|event|value|
# +--------------------+-----+-----+
# |2020-11-17_19:15:...| scan|start|
# |2020-11-17_19:18:...| scan|  end|
# |2020-11-17_20:05:...| scan|start|
# |2020-11-17_20:13:...| scan|  end|
# +--------------------+-----+-----+

Convert "timestamp" column to TimestampType() to be able to compute differences:

df=df.withColumn("timestamp",
regexp_replace(col("timestamp"),"_"," "))
df.show(truncate=False)
# +——————————-------------———+---——+—---—+
# |timestamp                 |event|value|
# +————————————-------------—+---——+—---—+
# |2020-11-17 19:15:33.438102|scan |start|
# |2020-11-17 19:18:33.433002|scan |end  |
# |2020-11-17 20:05:21.538125|scan |start|
# |2020-11-17 20:13:08.528102|scan |end  |
# +——————————-------------———+---——+---——+

df = df.withColumn("timestamp",
regexp_replace(col("timestamp"),"_"," ").cast(TimestampType()))
df.dtypes
#  [('timestamp', 'timestamp'), ('event', 'string'), ('value', 'string')]

Use pyspark.sql.functions.lag function that returns the value of the previous row (offset=1 by default).
See also How to calculate the difference between rows in PySpark? or Applying a Window function to calculate differences in pySpark

df.withColumn("lag_previous", col("timestamp").cast("long") - lag('timestamp').over(
    Window.orderBy('timestamp')).cast("long")).show(truncate=False)
# WARN WindowExec: No Partition Defined for Window operation! Moving all data to a single partition, this can cause serious performance degradation.

Using Window without partition gives a warning.

It is better to partition the dataframe for the Window operation, I partitioned here by type of event:

df.withColumn("lag_previous", col("timestamp").cast("long") - lag('timestamp').over(
    Window.partitionBy("event").orderBy('timestamp')).cast("long")).show(truncate=False)
# +———————————-------------——+---——+—---—+—------—————+
# |timestamp                 |event|value|lag_previous|
# +———————————-------------——+---——+---——+------——————+
# |2020-11-17 19:15:33.438102|scan |start|null        |
# |2020-11-17 19:18:33.433002|scan |end  |180         |
# |2020-11-17 20:05:21.538125|scan |start|2808        |
# |2020-11-17 20:13:08.528102|scan |end  |467         |
# +—————-------------————————+---——+—---—+—------—————+

From this table you can filter out the rows with "end" value to get the total durations.


问:
Fibronacci sequence spitting wrong number
I have created a function that sumbs up all odd fibronacci numbers up to a given number, and for the most part it works all for except one number.  For example sumFibs(10) should return 10 becuz all Fib #s <= 10 are 1,1,3 and 5.

If I do sumFibs(75024); I get 135721 instead of the expected value is 60696. For every other number it works perfectly and am scratching my head to solve it

function sumFibs(num) {

  let thunderAss = [];
  let currDmp = 0;
  let nxtRmp = 1;
  var pushNxt = 0;
  // push into array
  for (let x = 0; x < num; x++) {
    if (x <= 1) {
      console.log("lets go");
      thunderAss.push(1); // 2l almond milk
    } else {
      thunderAss.push(thunderAss[x - 1] + thunderAss[x - 2]);
      console.log(x, " x is factor");
    }
  }
  console.log(thunderAss);

  let cuntNuts = 0;
  for (let x = 0; x < num; x++) {
    if (cuntNuts < num) {
      if (thunderAss[x] % 2 == 0) {} else {
        cuntNuts += thunderAss[x];
      }
    } else {
      break;
    }
  }
  console.log("CN: ", cuntNuts);
  return cuntNuts;
}
sumFibs(75024); // 60696 but 135721
sumFibs(4);```

答:
You are adding the num first Fibonacci numbers instead of the Fibonacci numbers less than or equal to num.

In my solution here, I do the correct thing and get the correct answer:

function* fibonacci()
{
    let x = 0;
    let y = 1;

    while (true) {
        yield x;
        [x, y] = [y, x+y];
    }
}

function sum_odd_fibonacci(max)
{
    const fib_seq = fibonacci();

    let s = 0;
    let n;
    while ( (n=fib_seq.next().value) <= max) {
        if (n % 2 == 1) {
            s += n;
        }
    }

    return s;
}

console.log(sum_odd_fibonacci(75024));
```


问:
Swiftui Async image not loading when frame size is below 500
Been banging my head against the wall for weeks now! This code returns a gray square, but if I change the frame size to width 500, height 500 then it works. This doesn't make any sense, I can't reproduce the error.

Any frame size below 500 will show a grey background and no image, been deleting and starting from scratch multiple times, it must be a bug?

```<code>Section {
    VStack {
        AsyncImage(url: URL(string: picture.downloadUrl)) { image in
        image
            .resizable()
            .scaledToFit()
        } placeholder: {
            Color.gray.opacity(0.1)
        }
        .frame(width: 200, height: 200)
        .cornerRadius(6)
    }
}
</code>```

答:
Have you tried putting the .frame() on the returned image itself?

```<code>AsyncImage(url: URL(string: picture.downloadUrl)) { image in
    image
        .resizable()
        .scaledToFit()
        .frame(width: 200, height: 200)
    } placeholder: {
        Color.gray.opacity(0.1)
    }
</code>```

Body:
Been banging my head against the wall for weeks now! This code returns a gray square, but if I change the frame size to width 500, height 500 then it works. This doesn't make any sense, I can't reproduce the error.

Any frame size below 500 will show a grey background and no image, been deleting and starting from scratch multiple times, it must be a bug?

Section {
    VStack {
        AsyncImage(url: URL(string: picture.downloadUrl)) { image in
        image
            .resizable()
            .scaledToFit()
        } placeholder: {
            Color.gray.opacity(0.1)
        }
        .frame(width: 200, height: 200)
        .cornerRadius(6)
    }
}

Body:
Have you tried putting the .frame() on the returned image itself?

AsyncImage(url: URL(string: picture.downloadUrl)) { image in
    image
        .resizable()
        .scaledToFit()
        .frame(width: 200, height: 200)
    } placeholder: {
        Color.gray.opacity(0.1)
    }


问:
Assign a value to a cell from another cell
I would like to assign one value from a specific cell from another value of a specific cell from the same dataframe.

I have tried the following:

```<code>df.loc[i_list[0]][first_empty_column_unique] = df.iloc[i][index_of_duplicate_element]
</code>```

but I am getting the following error:

```<code>SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
</code>```

I have tried also to copy the df as follows:

```<code>elements = df.iloc[i][[index_of_duplicate_element]].copy()
df.loc[i_list[0]][first_empty_column_unique] = elements
</code>```

but I am still getting the error.

Which is the correct way of copying from one cell to another in my case?

答:
Generally with loc you should write .loc[x, y] instead of .loc[x][y] (same for iloc):

```<code>df.loc[i_list[0], first_empty_column_unique] = df.iloc[i, index_of_duplicate_element]
</code>```

Body:
I would like to assign one value from a specific cell from another value of a specific cell from the same dataframe.

I have tried the following:

df.loc[i_list[0]][first_empty_column_unique] = df.iloc[i][index_of_duplicate_element]

but I am getting the following error:

SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame

I have tried also to copy the df as follows:

elements = df.iloc[i][[index_of_duplicate_element]].copy()
df.loc[i_list[0]][first_empty_column_unique] = elements

but I am still getting the error.

Which is the correct way of copying from one cell to another in my case?

Body:
Generally with loc you should write .loc[x, y] instead of .loc[x][y] (same for iloc):

df.loc[i_list[0], first_empty_column_unique] = df.iloc[i, index_of_duplicate_element]


问:
Laravel IN Validation or Validation by ENUM Values
I'm initiating in Laravel.
I searched and not found how to validate data with some ENUM values. On below code I need that type must be just DEFAULT or SOCIAL. One or other:

```<code>$validator = Validator::make(Input::only(['username', 'password', 'type']), [
    'type' => '', // DEFAULT or SOCIAL values
    'username' => 'required|min:6|max:255',
    'password' => 'required|min:6|max:255'
]);
</code>```

Is possible?

答:
Laravel 9+

https://laravel.com/docs/10.x/validation#rule-enum

use App\Enums\ServerStatus;
use Illuminate\Validation\Rules\Enum;

$request->validate([
    'status' => [new Enum(ServerStatus::class)],
]);
```
<p>Enum:</p>
<pre class="lang-php prettyprint-override"><code>namespace App\Enums;

enum ServerStatus: string {
    case ACTIVE = 'active';
    case INACTIVE = 'inactive';
}
</code>```

Required PHP 8.1+

Body:
I'm initiating in Laravel.
I searched and not found how to validate data with some ENUM values. On below code I need that type must be just DEFAULT or SOCIAL. One or other:

$validator = Validator::make(Input::only(['username', 'password', 'type']), [
    'type' => '', // DEFAULT or SOCIAL values
    'username' => 'required|min:6|max:255',
    'password' => 'required|min:6|max:255'
]);

Is possible?

Body:
Laravel 9+

https://laravel.com/docs/10.x/validation#rule-enum

use App\Enums\ServerStatus;
use Illuminate\Validation\Rules\Enum;

$request->validate([
    'status' => [new Enum(ServerStatus::class)],
]);

Enum:

namespace App\Enums;

enum ServerStatus: string {
    case ACTIVE = 'active';
    case INACTIVE = 'inactive';
}

Required PHP 8.1+


问:
Argument 1:Cannot convert from NetSatis.Entities.interfaces.ientity to fluentvalidation.ivalidationcontext
```<code>public static class ValidatorTool
{
    public static bool Validate(IValidator validator,IEntity entity)
    {
        bool result = true;
        var validationResult = validator.Validate(entity);
        if (!validationResult.IsValid)
        {
            string message = null;
            foreach (var error in validationResult.Errors)
            {
                message += error.ErrorMessage+System.Environment.NewLine;
            }
            MessageBox.Show(message);
            result = false;
        }
        return result;
</code>```

I am trying to use validator tools but one day ago i dont get any errors about this entity thing but now i am taking an error about entity, What should i do in order to not get an error

答:
This is a change on FluentValidation 9, the code below will work:</p>
```<code>var context = new ValidationContext<IEntity>(request);
var validationResult = validator.Validate(context);
</code>```

Body:
public static class ValidatorTool
{
    public static bool Validate(IValidator validator,IEntity entity)
    {
        bool result = true;
        var validationResult = validator.Validate(entity);
        if (!validationResult.IsValid)
        {
            string message = null;
            foreach (var error in validationResult.Errors)
            {
                message += error.ErrorMessage+System.Environment.NewLine;
            }
            MessageBox.Show(message);
            result = false;
        }
        return result;

I am trying to use validator tools but one day ago i dont get any errors about this entity thing but now i am taking an error about entity, What should i do in order to not get an error

Body:
This is a change on FluentValidation 9, the code below will work:

var context = new ValidationContext<IEntity>(request);
var validationResult = validator.Validate(context);


问:
Redis Installation fails with "Newer version of jemalloc required" when running make command
Redis installation on RHEL fails when running make command. Below is the output</p>
```<code>cd src && make all
make[1]: Entering directory `/root/Downloads/redis-3.2.0/src'
    CC adlist.o
In file included from adlist.c:34:
zmalloc.h:50:31: error: jemalloc/jemalloc.h: No such file or directory
zmalloc.h:55:2: error: #error "Newer version of jemalloc required"
make[1]: *** [adlist.o] Error 1
make[1]: Leaving directory `/root/Downloads/redis-3.2.0/src'
make: *** [all] Error 2
</code>```

答:
You should use Ubuntu PPA</p>
```<code>$ sudo add-apt-repository ppa:redislabs/redis
$ sudo apt-get update
$ sudo apt-get install redis
</code>```

Body:
Redis installation on RHEL fails when running make command. Below is the output

cd src && make all
make[1]: Entering directory `/root/Downloads/redis-3.2.0/src'
    CC adlist.o
In file included from adlist.c:34:
zmalloc.h:50:31: error: jemalloc/jemalloc.h: No such file or directory
zmalloc.h:55:2: error: #error "Newer version of jemalloc required"
make[1]: *** [adlist.o] Error 1
make[1]: Leaving directory `/root/Downloads/redis-3.2.0/src'
make: *** [all] Error 2

Body:
You should use Ubuntu PPA

$ sudo add-apt-repository ppa:redislabs/redis
$ sudo apt-get update
$ sudo apt-get install redis


问:
How to color in progress on project tracker Excel?

I'm working on a project tracker in Excel and as you can see on the bottom right hand side is a progress bar that shows the duration of each project. Blue means in progress and populates the length of the project and the orange is %completed of it which is a visual of column AD. The problem is that I cannot get the %completed to color right. For example, durations that are only a day long: if I have 100% in column AD it will not only color the square its designated to, but two more blocks to the right making it look as if it is a 3 day long task. In addition, if I set 50% for example in the first task, it will cover about 90% of the bar. Here is the formula i use in conditional formatting.

Orange:=AND($AD14>5%, $Z14<=AF$5,ROUNDDOWN(NETWORKDAYS($Z14,$AA14)*$AD14,0)+$Z14+1>=AF$5)
Blue:=AND(NOT(ISBLANK($Z13)),$Z13<=AF$10,$AA13>=AF$10)

Are there better formulas, more particularly for the orange % task completed? Thanks!

答:
I create a vba solution, looks like

code is:

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
  Dim shp As Shape
  Dim rngTrefferStart As Range
  Dim rngTrefferEnde As Range
  Dim rngBereich As Range

  If Target.Column = 3 Then

   With Tabelle1

    Set rngTrefferStart = .Rows(2).Find(what:=CDate(Target.Offset(0, -1).Value), lookat:=xlWhole)
    If Not rngTrefferStart Is Nothing Then

     Set rngTrefferEnde = .Rows(2).Find(what:=CDate(Target.Value), lookat:=xlWhole)
     If Not rngTrefferEnde Is Nothing Then

      Set rngBereich = .Range(.Cells(Target.Row, rngTrefferStart.Column), .Cells(Target.Row, rngTrefferEnde.Column))
      ShapeEntfernen rngBereich

      If Target.Value = "" Then ShapeEntfernen rngTrefferStart: Exit Sub

         Set shp = rngBereich.Worksheet.Shapes.AddShape(msoShapeRectangle, _
                Left:=rngTrefferStart.Left, _
                Top:=Target.Top, _
                Width:=rngBereich.Width, _
                Height:=rngTrefferStart.Height)

              shp.Fill.ForeColor.RGB = RGB(255, 0, 0)

              shp.TextFrame2.TextRange.Text = .Cells(Target.Row, 1).Value
              shp.TextFrame2.VerticalAnchor = msoAnchorMiddle
              shp.TextFrame2.HorizontalAnchor = msoAnchorNone
              ShapeAktualisieren rngBereich, .Cells(Target.Row, 1).Value, .Cells(Target.Row, 4).Value
     End If
    End If

  End With

  End If

 If Target.Column = 1 Then
  With Tabelle1
  Set rngTrefferStart = .Rows(2).Find(what:=Target.Offset(0, 1).Value, lookat:=xlWhole)
    If Not rngTrefferStart Is Nothing Then

     Set rngTrefferEnde = .Rows(2).Find(what:=Target.Offset(0, 2), lookat:=xlWhole)
     If Not rngTrefferEnde Is Nothing Then

     Set rngBereich = .Range(.Cells(Target.Row, rngTrefferStart.Column), .Cells(Target.Row, rngTrefferEnde.Column))
      ShapeAktualisieren rngBereich, .Cells(Target.Row, 1).Value, .Cells(Target.Row, 4).Value
     End If
     End If
  End With

 End If

  If Target.Column = 4 Then
  With Tabelle1
   Set rngTrefferStart = .Rows(2).Find(what:=Target.Offset(0, -2).Value, lookat:=xlWhole)
    If Not rngTrefferStart Is Nothing Then

     Set rngTrefferEnde = .Rows(2).Find(what:=Target.Offset(0, -1).Value, lookat:=xlWhole)
     If Not rngTrefferEnde Is Nothing Then

      Set rngBereich = .Range(.Cells(Target.Row, rngTrefferStart.Column), .Cells(Target.Row, rngTrefferEnde.Column))
      ShapeAktualisieren rngBereich, .Cells(Target.Row, 1).Value, .Cells(Target.Row, 4).Value

     End If

  End If
  End With
  End If

 End Sub

Sub ShapeEntfernen(rngBereich As Range)
 Dim shp As Shape

 For Each shp In Tabelle1.Shapes
  If InStr(shp.Name, "Drop") = 0 Then
  If Not Intersect(shp.TopLeftCell, rngBereich) Is Nothing Then

      shp.Delete
    End If
  End If

 Next shp

End Sub

Sub ShapeAktualisieren(rngBereich As Range, strZimmer As String, strZustand As String)
 Dim shp As Shape

 For Each shp In Tabelle1.Shapes
 If InStr(shp.Name, "Drop") = 0 Then
  If Not Intersect(shp.TopLeftCell, rngBereich) Is Nothing Then
    shp.TextFrame2.TextRange.Text = strZimmer
    shp.TextFrame2.VerticalAnchor = msoAnchorMiddle
    shp.TextFrame2.HorizontalAnchor = msoAnchorNone

    Select Case strZustand
     Case "Früh"
      shp.Fill.ForeColor.RGB = RGB(146, 208, 80)
     Case "Spät"
      shp.Fill.ForeColor.RGB = RGB(255, 0, 0)
     Case "Frei"
      shp.Fill.ForeColor.RGB = RGB(255, 255, 0)
     Case Else
     shp.Fill.ForeColor.RGB = RGB(120, 120, 120)
    End Select

  End If
  End If

 Next shp

End Sub
</code>```

Body:
I create a vba solution, looks like

code is:

Private Sub Worksheet_Change(ByVal Target As Range)
  Dim shp As Shape
  Dim rngTrefferStart As Range
  Dim rngTrefferEnde As Range
  Dim rngBereich As Range

  If Target.Column = 3 Then

   With Tabelle1

    Set rngTrefferStart = .Rows(2).Find(what:=CDate(Target.Offset(0, -1).Value), lookat:=xlWhole)
    If Not rngTrefferStart Is Nothing Then

     Set rngTrefferEnde = .Rows(2).Find(what:=CDate(Target.Value), lookat:=xlWhole)
     If Not rngTrefferEnde Is Nothing Then

      Set rngBereich = .Range(.Cells(Target.Row, rngTrefferStart.Column), .Cells(Target.Row, rngTrefferEnde.Column))
      ShapeEntfernen rngBereich

      If Target.Value = "" Then ShapeEntfernen rngTrefferStart: Exit Sub

         Set shp = rngBereich.Worksheet.Shapes.AddShape(msoShapeRectangle, _
                Left:=rngTrefferStart.Left, _
                Top:=Target.Top, _
                Width:=rngBereich.Width, _
                Height:=rngTrefferStart.Height)

              shp.Fill.ForeColor.RGB = RGB(255, 0, 0)

              shp.TextFrame2.TextRange.Text = .Cells(Target.Row, 1).Value
              shp.TextFrame2.VerticalAnchor = msoAnchorMiddle
              shp.TextFrame2.HorizontalAnchor = msoAnchorNone
              ShapeAktualisieren rngBereich, .Cells(Target.Row, 1).Value, .Cells(Target.Row, 4).Value
     End If
    End If

  End With

  End If

 If Target.Column = 1 Then
  With Tabelle1
  Set rngTrefferStart = .Rows(2).Find(what:=Target.Offset(0, 1).Value, lookat:=xlWhole)
    If Not rngTrefferStart Is Nothing Then

     Set rngTrefferEnde = .Rows(2).Find(what:=Target.Offset(0, 2), lookat:=xlWhole)
     If Not rngTrefferEnde Is Nothing Then

     Set rngBereich = .Range(.Cells(Target.Row, rngTrefferStart.Column), .Cells(Target.Row, rngTrefferEnde.Column))
      ShapeAktualisieren rngBereich, .Cells(Target.Row, 1).Value, .Cells(Target.Row, 4).Value
     End If
     End If
  End With

 End If

  If Target.Column = 4 Then
  With Tabelle1
   Set rngTrefferStart = .Rows(2).Find(what:=Target.Offset(0, -2).Value, lookat:=xlWhole)
    If Not rngTrefferStart Is Nothing Then

     Set rngTrefferEnde = .Rows(2).Find(what:=Target.Offset(0, -1).Value, lookat:=xlWhole)
     If Not rngTrefferEnde Is Nothing Then

      Set rngBereich = .Range(.Cells(Target.Row, rngTrefferStart.Column), .Cells(Target.Row, rngTrefferEnde.Column))
      ShapeAktualisieren rngBereich, .Cells(Target.Row, 1).Value, .Cells(Target.Row, 4).Value

     End If

  End If
  End With
  End If

 End Sub

Sub ShapeEntfernen(rngBereich As Range)
 Dim shp As Shape

 For Each shp In Tabelle1.Shapes
  If InStr(shp.Name, "Drop") = 0 Then
  If Not Intersect(shp.TopLeftCell, rngBereich) Is Nothing Then

      shp.Delete
    End If
  End If

 Next shp

End Sub

Sub ShapeAktualisieren(rngBereich As Range, strZimmer As String, strZustand As String)
 Dim shp As Shape

 For Each shp In Tabelle1.Shapes
 If InStr(shp.Name, "Drop") = 0 Then
  If Not Intersect(shp.TopLeftCell, rngBereich) Is Nothing Then
    shp.TextFrame2.TextRange.Text = strZimmer
    shp.TextFrame2.VerticalAnchor = msoAnchorMiddle
    shp.TextFrame2.HorizontalAnchor = msoAnchorNone

    Select Case strZustand
     Case "Früh"
      shp.Fill.ForeColor.RGB = RGB(146, 208, 80)
     Case "Spät"
      shp.Fill.ForeColor.RGB = RGB(255, 0, 0)
     Case "Frei"
      shp.Fill.ForeColor.RGB = RGB(255, 255, 0)
     Case Else
     shp.Fill.ForeColor.RGB = RGB(120, 120, 120)
    End Select

  End If
  End If

 Next shp

End Sub


问:
What is the difference among eval(parse()), eval(str2lang()), eval(str2expression()), and eval(call()[[1]])?
I'm writing a function to extract a variable provided as a string from either a given data.frame df or the environment env. Initially, I had been using the eval(parse(text=s), df, env) construction to do this, but I learned that there are more efficient alternatives. Other options include:

eval(str2lang(s), df, env)

eval(str2expression(s), df, env)

eval(call(s)[[1]], df, env)

There may be a get solution as well, but I don't know if it can check to see if the variable is in df first before turning to env if it isn't.

Using microbenchmark, it seems that call is the fastest:

library(microbenchmark)

x1 = 1
df = data.frame(x2 = 2)

microbenchmark(call = eval(call('x1')[[1]], df),
               parse = eval(parse(text='x1'), df),
               str2lang = eval(str2lang('x1'), df),
               str2exp = eval(str2expression('x1'), df),
               check = "identical")
#> Unit: microseconds
#>      expr    min      lq     mean  median      uq     max neval cld
#>      call  1.128  1.2115  1.60815  1.4585  1.6360   4.659   100  a
#>     parse 39.183 39.8705 46.60755 40.2405 42.0415 135.462   100   b
#>  str2lang  2.235  2.3570  3.26144  2.5995  2.8925  24.641   100  a
#>   str2exp  2.230  2.3200  2.81387  2.4780  2.6970  10.312   100  a

microbenchmark(call = eval(call('x2')[[1]], df),
               parse = eval(parse(text='x2'), df),
               str2lang = eval(str2lang('x2'), df),
               str2exp = eval(str2expression('x2'), df),
               check = "identical")
#> Unit: microseconds
#>      expr    min     lq     mean  median      uq     max neval cld
#>      call  1.124  1.194  1.47770  1.3675  1.5795   9.031   100  a
#>     parse 38.254 38.762 40.21497 38.9630 39.3120 116.510   100   b
#>  str2lang  2.214  2.304  2.55036  2.3960  2.6530  10.639   100  a
#>   str2exp  2.238  2.331  2.50011  2.4210  2.6515   3.619   100  a
```

Created on 2020-04-23 by the reprex package (v0.3.0)

I'm therefore inclined to use call but I want to make sure there wouldn't be any unintended consequences of doing so rather than using the other solutions. In other words, in what situations (within the context I'm using them in) would the four methods not give the same answer, leading one to favor one over the others?

答:
Both call and as.symbol are fine, I think as.symbol is preferable. as.symbol is unambiguous R terminology (as.name was S terminology) and is as fast as call.  A call can contain any R object, including symbols and other calls, plus documentation is all over the place. Because the strings could contain punctuation we can not be sure at which point str2lang, or str2expression fail or what error message might pop up.

Checking if variables exist in an environment is safer than doing so for data.frames.

Differences

a look under the hood reveals main differences are in their classes:

l = list(w = as.symbol("x"), x = str2lang("x"), y = str2expression("x"), z = call("x"))
rbind(sapply(l, class), sapply(l, typeof), sapply(l, is.language))
     w        x        y            z
[1,] "name"   "name"   "expression" "call"
[2,] "symbol" "symbol" "expression" "language"
[3,] "TRUE"   "TRUE"   "TRUE"       "TRUE"
```
<p>A good starting point is the R Language Definition, and for examples the Expressions chapter in Hadley Wickham's <em>Advanced R</em> (source), followed by reading <code>?call</code>, <code>?parse</code>, <code>rlang::call2</code>.</p>
<h3>What are they?</h3>
<p>In <em>Evaluating the Design of the R Language</em> (source) the following definition is given: <br><br>
                                Arguments of <em>calls</em> are <em>expressions</em> which may be named by a symbol <del>name</del>.</p>
<ul>
<li><strong>Expression</strong> - <em>an action</em> or <em>actions</em>.</li>
<li><strong>Call</strong> - represent the <em>action of calling a function</em>.</li>
<li><strong>Symbols (Name)</strong> - <em>refer</em> to R objects (2.1.3)</li>
</ul>
<h2>Which one to use when?</h2>
<p>From the <code>?call</code> documentation:</p>
<blockquote>
<p>Instead of <code>as.call(<string>)</code>, consider using <code>str2lang(*)</code> which is an efficient version of <code>parse(text=*)</code>. <code>call()</code> and <code>as.call()</code>, are much preferable to <code>parse()</code> based approaches.</p>
</blockquote>
<p>Using <code>pryr::show_c_source(.Internal(str2lang(s)))</code> we can see that <code>str2lang</code> and <code>str2expression</code> both call
the C function <code>do_str2lang</code> but differ in their argument. This difference can be found in <code>?parse</code>:</p>
<ul>
<li><code>str2expression</code>, equal to <code>parse(text = "x", keep.source = F)</code> is always an expression.</li>
<li><code>str2lang("x")</code>, equal to <code>parse(text = "x", keep.source = F)[[1]]</code> can evaluate to a call <strong>OR</strong> a symbol, <code>NULL</code>, numeric, integer or logical, i.e. <em>a call or simpler</em>.</li>
</ul>
<p>In the <em>R Language Definition</em> it is mentioned that expressions are only evaluated when passed to <code>eval</code>, other language objects may get evaluated in some unexpected cases. What these cases are, I could not find.</p>
<p>We can throw some edge cases at all approaches to see when which might fail:</p>
<ul>
<li><code>"\""</code> wrongly parsed quote when reading in data?</li>
<li><code>" "</code> empty variable? space in variable name?</li>
<li><code>"_"</code> illegal token (legacy assignment operator) issues?</li>
<li>backtick</li>
<li>NA</li>
</ul>
<pre class="lang-r prettyprint-override"><code># if it breaks, show how it breaks
do <- function(x, ...) tryCatch(eval(x, ..1, ..2), error = function(t) t$message)
check <- function(x, ...){
  list(
    do(call(x)[[1]], ...),
    do(as.symbol(x), ...),
    do(str2lang(x), ...),
    do(str2expression(x), ...)
  )
}

# test 1: some variables do not exist
e <- new.env() ; e$x1 <- 5
df = data.frame(x2 = 3)
no_var <- lapply(list("x1", "x2", "\"", " ", "_", "`", NA_character_), check, df, e)

# test 2: some variables exist
e <- new.env() ; e$x1 = 5; e$`_` = 2 ; e$"\"" = 5; e$`NA` <- 5
df = data.frame(x2 = 3, " " = 7, "_" = 2)
var <- lapply(list("x1", "x2", "\"", " ", "_", "`", NA_character_), check, df, e)

# difference in outcomes in
var[3:7]
no_var[3:7]
</code>```

When variables do not exist:
as.symbol and call always reach eval, str2lang and str2expression fail early in all cases. str2expression differs from str2lang when an empty string is given.

When variables exist:
as.symbol and call succeed in cases 3, 4, 7 while str2lang and str2expression throw errors.

On a sidenote, be careful with storing variables in data.frames, they are easy to corrupt.

```<code>names(data.frame(" " = 1, "_" = 2, "\"" = 3, "`" = 4))
[1] "X."   "X_"   "X..1" "X..2"
</code>```

Body:
I'm writing a function to extract a variable provided as a string from either a given data.frame df or the environment env. Initially, I had been using the eval(parse(text=s), df, env) construction to do this, but I learned that there are more efficient alternatives. Other options include:

eval(str2lang(s), df, env)

eval(str2expression(s), df, env)

eval(call(s)[[1]], df, env)

There may be a get solution as well, but I don't know if it can check to see if the variable is in df first before turning to env if it isn't.

Using microbenchmark, it seems that call is the fastest:

library(microbenchmark)

x1 = 1
df = data.frame(x2 = 2)

microbenchmark(call = eval(call('x1')[[1]], df),
               parse = eval(parse(text='x1'), df),
               str2lang = eval(str2lang('x1'), df),
               str2exp = eval(str2expression('x1'), df),
               check = "identical")
#> Unit: microseconds
#>      expr    min      lq     mean  median      uq     max neval cld
#>      call  1.128  1.2115  1.60815  1.4585  1.6360   4.659   100  a
#>     parse 39.183 39.8705 46.60755 40.2405 42.0415 135.462   100   b
#>  str2lang  2.235  2.3570  3.26144  2.5995  2.8925  24.641   100  a
#>   str2exp  2.230  2.3200  2.81387  2.4780  2.6970  10.312   100  a

microbenchmark(call = eval(call('x2')[[1]], df),
               parse = eval(parse(text='x2'), df),
               str2lang = eval(str2lang('x2'), df),
               str2exp = eval(str2expression('x2'), df),
               check = "identical")
#> Unit: microseconds
#>      expr    min     lq     mean  median      uq     max neval cld
#>      call  1.124  1.194  1.47770  1.3675  1.5795   9.031   100  a
#>     parse 38.254 38.762 40.21497 38.9630 39.3120 116.510   100   b
#>  str2lang  2.214  2.304  2.55036  2.3960  2.6530  10.639   100  a
#>   str2exp  2.238  2.331  2.50011  2.4210  2.6515   3.619   100  a

Created on 2020-04-23 by the reprex package (v0.3.0)

I'm therefore inclined to use call but I want to make sure there wouldn't be any unintended consequences of doing so rather than using the other solutions. In other words, in what situations (within the context I'm using them in) would the four methods not give the same answer, leading one to favor one over the others?

Body:
Both call and as.symbol are fine, I think as.symbol is preferable. as.symbol is unambiguous R terminology (as.name was S terminology) and is as fast as call.  A call can contain any R object, including symbols and other calls, plus documentation is all over the place. Because the strings could contain punctuation we can not be sure at which point str2lang, or str2expression fail or what error message might pop up.

Checking if variables exist in an environment is safer than doing so for data.frames.

Differences

a look under the hood reveals main differences are in their classes:

l = list(w = as.symbol("x"), x = str2lang("x"), y = str2expression("x"), z = call("x"))
rbind(sapply(l, class), sapply(l, typeof), sapply(l, is.language))
     w        x        y            z
[1,] "name"   "name"   "expression" "call"
[2,] "symbol" "symbol" "expression" "language"
[3,] "TRUE"   "TRUE"   "TRUE"       "TRUE"

A good starting point is the R Language Definition, and for examples the Expressions chapter in Hadley Wickham's Advanced R (source), followed by reading ?call, ?parse, rlang::call2.

What are they?

In Evaluating the Design of the R Language (source) the following definition is given:

                                Arguments of calls are expressions which may be named by a symbol name.

Expression - an action or actions.

Call - represent the action of calling a function.

Symbols (Name) - refer to R objects (2.1.3)

Which one to use when?

From the ?call documentation:

Instead of as.call(<string>), consider using str2lang(*) which is an efficient version of parse(text=*). call() and as.call(), are much preferable to parse() based approaches.

Using pryr::show_c_source(.Internal(str2lang(s))) we can see that str2lang and str2expression both call
the C function do_str2lang but differ in their argument. This difference can be found in ?parse:

str2expression, equal to parse(text = "x", keep.source = F) is always an expression.

str2lang("x"), equal to parse(text = "x", keep.source = F)[[1]] can evaluate to a call OR a symbol, NULL, numeric, integer or logical, i.e. a call or simpler.

In the R Language Definition it is mentioned that expressions are only evaluated when passed to eval, other language objects may get evaluated in some unexpected cases. What these cases are, I could not find.

We can throw some edge cases at all approaches to see when which might fail:

"\"" wrongly parsed quote when reading in data?

" " empty variable? space in variable name?

"_" illegal token (legacy assignment operator) issues?

backtick

NA

# if it breaks, show how it breaks
do <- function(x, ...) tryCatch(eval(x, ..1, ..2), error = function(t) t$message)
check <- function(x, ...){
  list(
    do(call(x)[[1]], ...),
    do(as.symbol(x), ...),
    do(str2lang(x), ...),
    do(str2expression(x), ...)
  )
}

# test 1: some variables do not exist
e <- new.env() ; e$x1 <- 5
df = data.frame(x2 = 3)
no_var <- lapply(list("x1", "x2", "\"", " ", "_", "`", NA_character_), check, df, e)

# test 2: some variables exist
e <- new.env() ; e$x1 = 5; e$`_` = 2 ; e$"\"" = 5; e$`NA` <- 5
df = data.frame(x2 = 3, " " = 7, "_" = 2)
var <- lapply(list("x1", "x2", "\"", " ", "_", "`", NA_character_), check, df, e)

# difference in outcomes in
var[3:7]
no_var[3:7]

When variables do not exist:
as.symbol and call always reach eval, str2lang and str2expression fail early in all cases. str2expression differs from str2lang when an empty string is given.

When variables exist:
as.symbol and call succeed in cases 3, 4, 7 while str2lang and str2expression throw errors.

On a sidenote, be careful with storing variables in data.frames, they are easy to corrupt.

names(data.frame(" " = 1, "_" = 2, "\"" = 3, "`" = 4))
[1] "X."   "X_"   "X..1" "X..2"


问:
Reading and writing RGB files using OpenCV
New to python and OpenCV. I'm using OpenCV to read a jpg, I then write it to a file as hex data, I read the file back again and construct a numpy array and use imshow to show the image, but it looks different from the original image. Why did the image color get blue?

file1.py:

```<code>import cv2
import numpy as np

img = cv2.imread('D:\cat.jpg')

cv2.imshow('img', img)     #Shows the image
cv2.waitKey(3000)

with open('D:\catHex', 'wb') as f:
    f.write(img)
    f.close()
</code>```

file2.py:

```<code>import cv2
import numpy as np

img = np.zeros((640,640,3), np.uint8)
row = 0
col = 0

with open('D:\catHex', 'rb') as f:

    while(row < 640):

        img[row,col,2] = ord(f.read(1))
        img[row,col,1] = ord(f.read(1))
        img[row,col,0] = ord(f.read(1))

        col = col + 1
        if(col == 640):
            col = 0
            row = row + 1

    cv2.imshow('img',img)
    cv2.waitKey(3000)
</code>```

答:
You are swapping the Red and Blue channels when reading the image in your second script, therefore, the image looks blue. The following should work as expected:

```<code>img[row,col,0] = ord(f.read(1))
img[row,col,1] = ord(f.read(1))
img[row,col,2] = ord(f.read(1))
</code>```

Also you could write your while loop in the following more pythonesque way with for-loops:

```<code>for row in range(640):
    for col in range(640):
        img[row,col,0] = ord(f.read(1))
        img[row,col,1] = ord(f.read(1))
        img[row,col,2] = ord(f.read(1))

    cv2.imshow('img',img)
    cv2.waitKey(3000)
</code>```

Body:
New to python and OpenCV. I'm using OpenCV to read a jpg, I then write it to a file as hex data, I read the file back again and construct a numpy array and use imshow to show the image, but it looks different from the original image. Why did the image color get blue?

file1.py:

import cv2
import numpy as np

img = cv2.imread('D:\cat.jpg')

cv2.imshow('img', img)     #Shows the image
cv2.waitKey(3000)

with open('D:\catHex', 'wb') as f:
    f.write(img)
    f.close()

file2.py:

import cv2
import numpy as np

img = np.zeros((640,640,3), np.uint8)
row = 0
col = 0

with open('D:\catHex', 'rb') as f:

    while(row < 640):

        img[row,col,2] = ord(f.read(1))
        img[row,col,1] = ord(f.read(1))
        img[row,col,0] = ord(f.read(1))

        col = col + 1
        if(col == 640):
            col = 0
            row = row + 1

    cv2.imshow('img',img)
    cv2.waitKey(3000)

Body:
You are swapping the Red and Blue channels when reading the image in your second script, therefore, the image looks blue. The following should work as expected:

img[row,col,0] = ord(f.read(1))
img[row,col,1] = ord(f.read(1))
img[row,col,2] = ord(f.read(1))

Also you could write your while loop in the following more pythonesque way with for-loops:

for row in range(640):
    for col in range(640):
        img[row,col,0] = ord(f.read(1))
        img[row,col,1] = ord(f.read(1))
        img[row,col,2] = ord(f.read(1))

    cv2.imshow('img',img)
    cv2.waitKey(3000)


问:
MongoDB returning field as null
I am currently working on an application connected to a MongoDB instance. I am having trouble where the 'id' field of my object is not being returned to me within the application but is being returned as null.

The schema has an 'entity' as defined below:

```<code>{
        "entity_id": String,
        "parent": String,
        "relevance": boolean
}
</code>```

I'm querying the collection using the Java Sync Driver (4.4.1) like so:

```<code>try {
    Entity testDoc = collection.find(eq("entity_id", entity_id)).first();
    if (testDoc != null) {
        //add entity to a list
    }
} catch (Exception e) {
    LOGGER.log(Level.SEVERE, "Failed to get Entity", e);
}
</code>```

For some reason this will give me every field in the object when I query EXCEPT the entity_id. I keep getting this returned as:

entity_id= null

Two things stick out to me. The first being that every other field is a String (originally the Id was a UUID object but I simplified while troubleshooting) and they still return if it's other fields. The second being that there is a whitespace before this null value as if it's being formatted. Other null values return as field=null instead of field= null

I was looking to see if there is some security setting preventing things from being labeled as *_id or *id from being returned but I have found no such instance.

Edit: Here is the Entity Pojo for clarity

```<code>public class Entity {

@BsonProperty(value = "entity_id")
private String entityID;
@BsonProperty(value = "parent")
private String parent;
@Deprecated
@BsonProperty(value = "relevance")
private boolean relevance;

public Entity() {}

public Entity(String entityID, String parent, Boolean relevance) {
    this.entityID = entityID;
    this.parent = parent;
    this.relevance = relevance;
}

public String getEntityID() {
    return entityID;
}

public void setEntityID(String entityID) {
    this.entityID = entityID;
}

public String getParent() {
    return parent;
}

public void setParent(String parent) {
    this.parent = parent;
}

public boolean isRelevant() {
    return relevance;
}

public void relevance(boolean relevance) {
    this.relevance = relevance;
}
</code>```

}

答:
So update for anyone watching this, it appears to have been an issue with my Eclipse IDE.

I reimported the project into IntelliJ Community Edition and rebuilt the Maven project, etc... After doing so, the test cases passed and my entityID returns in the query. Hopefully if anyone else runs into this issue they can do something similar.

Title: MongoDB returning field as null

Body:
I am currently working on an application connected to a MongoDB instance. I am having trouble where the 'id' field of my object is not being returned to me within the application but is being returned as null.

The schema has an 'entity' as defined below:

{
        "entity_id": String,
        "parent": String,
        "relevance": boolean
}

I'm querying the collection using the Java Sync Driver (4.4.1) like so:

try {
    Entity testDoc = collection.find(eq("entity_id", entity_id)).first();
    if (testDoc != null) {
        //add entity to a list
    }
} catch (Exception e) {
    LOGGER.log(Level.SEVERE, "Failed to get Entity", e);
}

For some reason this will give me every field in the object when I query EXCEPT the entity_id. I keep getting this returned as:

entity_id= null

Two things stick out to me. The first being that every other field is a String (originally the Id was a UUID object but I simplified while troubleshooting) and they still return if it's other fields. The second being that there is a whitespace before this null value as if it's being formatted. Other null values return as field=null instead of field= null

I was looking to see if there is some security setting preventing things from being labeled as *_id or *id from being returned but I have found no such instance.

Edit: Here is the Entity Pojo for clarity

public class Entity {

@BsonProperty(value = "entity_id")
private String entityID;
@BsonProperty(value = "parent")
private String parent;
@Deprecated
@BsonProperty(value = "relevance")
private boolean relevance;

public Entity() {}

public Entity(String entityID, String parent, Boolean relevance) {
    this.entityID = entityID;
    this.parent = parent;
    this.relevance = relevance;
}

public String getEntityID() {
    return entityID;
}

public void setEntityID(String entityID) {
    this.entityID = entityID;
}

public String getParent() {
    return parent;
}

public void setParent(String parent) {
    this.parent = parent;
}

public boolean isRelevant() {
    return relevance;
}

public void relevance(boolean relevance) {
    this.relevance = relevance;
}

}


问:
Differentiating absolute value functions using sympy in python won't return an answer
I'm trying to find the maximum points of curvature of a tanh(x) function, but the mathematical definition for curvature contains an absolute value function. I've specified that x must be real-valued which resolves sympy returning an imaginary function for the derivative of the curvature. However when trying to solve for k'(x)=0 using the sym.solve() method python will simply continue running and not return an answer at all.

```<code>x = sym.symbols('x', real=True)

# below are parameters I found from curve fitting raw data elsewhere that are just converted to sympy variables

a = sym.Float(a)
b = sym.Float(b)
c = sym.Float(c)
d = sym.Float(d)

# function in question
def f(x):
    return a * sym.tanh(b * x + c) + d

def fprime(x):
    return sym.diff(f(x),x,1)

def f2prime(x):
    return sym.diff(f(x),x,2)

f1 = fprime(x)
f2 = f2prime(x)

# mathematical definition of curvature
def kappa(f1,f2):
    return sym.Abs(f2) / ( 1 + f1**2 )**(3/2)

def kprime(f1,f2):
    return sym.diff(kappa(f1,f2),x,1)

k1 = kprime(f1,f2)
print(k1)
</code>```

One combination of the constants a,b,c,d=[-2.40402847 -3.20154993  0.51489147 -8.05771537] and k1 was

```<code>0.324273723818531*(1 - tanh(0.514891472285591 - 3.2015499273203*x)**2)*((1 - tanh(0.514891472285591 - 3.2015499273203*x)**2)**2 + 0.0168810800591381)**(-2.5)*(6.40309985464061*tanh(0.514891472285591 - 3.2015499273203*x)**2 - 6.40309985464061)*tanh(0.514891472285591 - 3.2015499273203*x)*Abs((tanh(3.2015499273203*x - 0.514891472285591)**2 - 1)*tanh(3.2015499273203*x - 0.514891472285591)) + 0.108091241272844*((3.2015499273203 - 3.2015499273203*tanh(3.2015499273203*x - 0.514891472285591)**2)*(tanh(3.2015499273203*x - 0.514891472285591)**2 - 1) + (6.40309985464061 - 6.40309985464061*tanh(3.2015499273203*x - 0.514891472285591)**2)*tanh(3.2015499273203*x - 0.514891472285591)**2)*((1 - tanh(0.514891472285591 - 3.2015499273203*x)**2)**2 + 0.0168810800591381)**(-1.5)*sign((tanh(3.2015499273203*x - 0.514891472285591)**2 - 1)*tanh(3.2015499273203*x - 0.514891472285591))
</code>```

Then trying to solve this for x using print(sym.solve(k1),x) could never return an answer.

答:
It's a pretty high-order nonlinear equation. Try nsolve:

```<code>>>> nsolve(k1, -.5)
-0.427127686132521
</code>```

Body:
I'm trying to find the maximum points of curvature of a tanh(x) function, but the mathematical definition for curvature contains an absolute value function. I've specified that x must be real-valued which resolves sympy returning an imaginary function for the derivative of the curvature. However when trying to solve for k'(x)=0 using the sym.solve() method python will simply continue running and not return an answer at all.

x = sym.symbols('x', real=True)

# below are parameters I found from curve fitting raw data elsewhere that are just converted to sympy variables

a = sym.Float(a)
b = sym.Float(b)
c = sym.Float(c)
d = sym.Float(d)

# function in question
def f(x):
    return a * sym.tanh(b * x + c) + d

def fprime(x):
    return sym.diff(f(x),x,1)

def f2prime(x):
    return sym.diff(f(x),x,2)

f1 = fprime(x)
f2 = f2prime(x)

# mathematical definition of curvature
def kappa(f1,f2):
    return sym.Abs(f2) / ( 1 + f1**2 )**(3/2)

def kprime(f1,f2):
    return sym.diff(kappa(f1,f2),x,1)

k1 = kprime(f1,f2)
print(k1)

One combination of the constants a,b,c,d=[-2.40402847 -3.20154993  0.51489147 -8.05771537] and k1 was

0.324273723818531*(1 - tanh(0.514891472285591 - 3.2015499273203*x)**2)*((1 - tanh(0.514891472285591 - 3.2015499273203*x)**2)**2 + 0.0168810800591381)**(-2.5)*(6.40309985464061*tanh(0.514891472285591 - 3.2015499273203*x)**2 - 6.40309985464061)*tanh(0.514891472285591 - 3.2015499273203*x)*Abs((tanh(3.2015499273203*x - 0.514891472285591)**2 - 1)*tanh(3.2015499273203*x - 0.514891472285591)) + 0.108091241272844*((3.2015499273203 - 3.2015499273203*tanh(3.2015499273203*x - 0.514891472285591)**2)*(tanh(3.2015499273203*x - 0.514891472285591)**2 - 1) + (6.40309985464061 - 6.40309985464061*tanh(3.2015499273203*x - 0.514891472285591)**2)*tanh(3.2015499273203*x - 0.514891472285591)**2)*((1 - tanh(0.514891472285591 - 3.2015499273203*x)**2)**2 + 0.0168810800591381)**(-1.5)*sign((tanh(3.2015499273203*x - 0.514891472285591)**2 - 1)*tanh(3.2015499273203*x - 0.514891472285591))

Then trying to solve this for x using print(sym.solve(k1),x) could never return an answer.

Body:
It's a pretty high-order nonlinear equation. Try nsolve:

>>> nsolve(k1, -.5)
-0.427127686132521


问:
GCP (Google Cloud) VM - Can't send email via Python script with SMTP
So I set up a GCP VM with Ubuntu, from where I want to send regular reports through my mail provider with a python script. The smtp port is 587, and to my understanding the port was formerly closed in GCP environments but should now be available.

My script looks like this:

```<code>import smtplib,ssl
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import formatdate
from email import encoders
import time

timestr = time.strftime('(%Y-%m-%d)')
username='me@mydomain.de'
password='secretpw'
send_from = 'me@mydomain.de'
send_to = 'recipient@herdomain.com'
body = 'hello'

msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = send_to
msg['Date'] = formatdate(localtime = True)
msg['Subject'] = 'important email'
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.ionos.de')
port = '587'
smtp = smtplib.SMTP('smtp.ionos.de')
smtp.ehlo()
smtp.starttls()
smtp.login(username,password)
smtp.sendmail(send_from, send_to.split(','), msg.as_string())
smtp.quit()
</code>```

On execution, the machine takes some time before outputting a timeout:

```<code>Traceback (most recent call last):
  File "test.py", line 25, in <module>
    server = smtplib.SMTP('smtp.ionos.de')
  File "/usr/lib/python3.8/smtplib.py", line 255, in __init__
    (code, msg) = self.connect(host, port)
  File "/usr/lib/python3.8/smtplib.py", line 339, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "/usr/lib/python3.8/smtplib.py", line 310, in _get_socket
    return socket.create_connection((host, port), timeout,
  File "/usr/lib/python3.8/socket.py", line 808, in create_connection
    raise err
  File "/usr/lib/python3.8/socket.py", line 796, in create_connection
    sock.connect(sa)
TimeoutError: [Errno 110] Connection timed out
</code>```

I can, however, ping smtp.ionos.de as well as telnet smtp.ionos.de 587 form the cl with result of a working ping and connection.

I also tried this with other email providers including gmail and get stuck with the exact same outcome.

Anyone? Help appreciated, thanks.

答:
Here is a full example tested with a GCP Cloud Function.  No libs are needed in requirements.txt.  This uses Python 3.9.  The code uses an App Password because normal users require 2FA.</p>
```<code>import smtplib
import ssl

def send_email(request):
    """Responds to any HTTP request.
    Args:
        request (flask.Request): HTTP request object.
    Returns:
        The response text or any set of values that can be turned into a
        Response object using
        `make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>`.
    """
    gmail_user = 'user@gmail.com'
    gmail_password = 'YOURPASSWORD'

    sent_from = gmail_user
    to = ['foo@bar.com']
    subject = 'Test e-mail from Python'
    body = 'Test e-mail body'

    email_text = """\
    From: %s
    To: %s
    Subject: %s
    %s
    """ % (sent_from, ", ".join(to), subject, body)

    context = ssl.create_default_context()
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls(context=context)
    server.login(gmail_user, gmail_password)
    server.sendmail(sent_from, to, body)
    server.close()
    print('Email sent (print)!')
    return f'Email sent (return)!'
</code>```

Body:
So I set up a GCP VM with Ubuntu, from where I want to send regular reports through my mail provider with a python script. The smtp port is 587, and to my understanding the port was formerly closed in GCP environments but should now be available.

My script looks like this:

import smtplib,ssl
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import formatdate
from email import encoders
import time

timestr = time.strftime('(%Y-%m-%d)')
username='me@mydomain.de'
password='secretpw'
send_from = 'me@mydomain.de'
send_to = 'recipient@herdomain.com'
body = 'hello'

msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = send_to
msg['Date'] = formatdate(localtime = True)
msg['Subject'] = 'important email'
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.ionos.de')
port = '587'
smtp = smtplib.SMTP('smtp.ionos.de')
smtp.ehlo()
smtp.starttls()
smtp.login(username,password)
smtp.sendmail(send_from, send_to.split(','), msg.as_string())
smtp.quit()

On execution, the machine takes some time before outputting a timeout:

Traceback (most recent call last):
  File "test.py", line 25, in <module>
    server = smtplib.SMTP('smtp.ionos.de')
  File "/usr/lib/python3.8/smtplib.py", line 255, in __init__
    (code, msg) = self.connect(host, port)
  File "/usr/lib/python3.8/smtplib.py", line 339, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "/usr/lib/python3.8/smtplib.py", line 310, in _get_socket
    return socket.create_connection((host, port), timeout,
  File "/usr/lib/python3.8/socket.py", line 808, in create_connection
    raise err
  File "/usr/lib/python3.8/socket.py", line 796, in create_connection
    sock.connect(sa)
TimeoutError: [Errno 110] Connection timed out

I can, however, ping smtp.ionos.de as well as telnet smtp.ionos.de 587 form the cl with result of a working ping and connection.

I also tried this with other email providers including gmail and get stuck with the exact same outcome.

Anyone? Help appreciated, thanks.

Body:
Here is a full example tested with a GCP Cloud Function.  No libs are needed in requirements.txt.  This uses Python 3.9.  The code uses an App Password because normal users require 2FA.

import smtplib
import ssl

def send_email(request):
    """Responds to any HTTP request.
    Args:
        request (flask.Request): HTTP request object.
    Returns:
        The response text or any set of values that can be turned into a
        Response object using
        `make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>`.
    """
    gmail_user = 'user@gmail.com'
    gmail_password = 'YOURPASSWORD'

    sent_from = gmail_user
    to = ['foo@bar.com']
    subject = 'Test e-mail from Python'
    body = 'Test e-mail body'

    email_text = """\
    From: %s
    To: %s
    Subject: %s
    %s
    """ % (sent_from, ", ".join(to), subject, body)

    context = ssl.create_default_context()
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls(context=context)
    server.login(gmail_user, gmail_password)
    server.sendmail(sent_from, to, body)
    server.close()
    print('Email sent (print)!')
    return f'Email sent (return)!'


问:
How to insert some text within the input using Selenium and Python
In a webpage I have the following element:

```<code><div id="learning_form" class="learning_form">
                <table cellspacing="0" cellpadding="0">
                    <tbody><tr><td><input type="text" id="answer" autocapitalize="off" autocorrect="off" autocomplete="off" placeholder="Odpowiedź" style="width: 360px;"></td></tr>
                </tbody></table>
                <div id="check"><h4 style="text-align: center;">Sprawdź</h4></div>
                <div id="special_characters"><div> </div><div> </div></div>
            </div>
</code>```

How I can insert text here using selenium in python?
I tried using:

```<code>driver.find_element(By.ID,"learning_form").send_keys("some text")
</code>```

but it doesn't work.

Snapshot of the element:

答:
To send a character sequence to the element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.learning_form#learning_form input#answer[placeholder='Odpowiedź']"))).send_keys("OłJeż")
</code>```

Using XPATH:

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='learning_form' and @id='learning_form']//input[@id='answer' and @placeholder='Odpowiedź']"))).send_keys("OłJeż")
</code>```

Note: You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Body:
In a webpage I have the following element:

<input type="text" id="answer" autocapitalize="off" autocorrect="off" autocomplete="off" placeholder="Odpowiedź" style="width: 360px;">

Sprawdź

How I can insert text here using selenium in python?
I tried using:

driver.find_element(By.ID,"learning_form").send_keys("some text")

but it doesn't work.

Snapshot of the element:

Body:
To send a character sequence to the element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.learning_form#learning_form input#answer[placeholder='Odpowiedź']"))).send_keys("OłJeż")

Using XPATH:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='learning_form' and @id='learning_form']//input[@id='answer' and @placeholder='Odpowiedź']"))).send_keys("OłJeż")

Note: You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


问:
Odoo.sh Editor on Jupyter : pdb.set_trace raises BdbQuit Error
Using my odoo.sh project (v13.0.2) > EDITOR-Tab , which redirects me to mywebsite.odoo.com/odoo-sh/editor/lab, when i want to debug using import pdb; pdb.set_trace(), it raises a BdbQuit Error :

```<code>  File "/usr/lib/python3.6/bdb.py", line 113, in
  dispatch_exception
    if self.quitting: raise BdbQuit
</code>```

In the past versions : v13.0.1.xxx, i could use pdb.set_trace() to debug my python code. How to solve this issue ?

答:
rpdb is a remote debugger based on pdb. It re-routes stdin and stdout to a socket handler, so that you can debug server processes (remotely).

In Odoo.sh > yourstagingBranch, click on the SHELL-tab:

```<code>mywebsite-oerp-staging-5070461 [staging/v13.0]:~$ pip3 install rpdb
</code>```

In Odoo.sh > yourstagingBranch, click on the EDITOR-tab:

IN ODOO-EDITOR:

At the top of your python file, add:

    import rpdb
```
<ul>
<li>In the function (def subscribe) to be inspected, add:</li>
</ul>
<pre class="lang-py prettyprint-override"><code>    def subscribe(self, event, **post):
        # code before
        rpdb.set_trace()
        # code after
</code>```

Click on menu Tab : Odoo>Update current module : alternatively, open a new Terminal window and execute this command: odoo-bin -u website_sale --stop-after-init

```<code>    mywebsite-oerp-staging-5070461 [staging/v13.0]: odoo-bin -u website_sale --stop-after-init
</code>```

After having restarted Odoo (all modules loaded), execute this command in the other Terminal window: nc 127.0.0.1 4444

```<code>    mywebsite-oerp-staging-5070461 [staging/v13.0]: ~$ nc 127.0.0.1 4444
</code>```

We can then use the common pdb commands:

l(ist): Lists the lines surrounding the current line

w(here): Displays the file and line number where we currently are

s(tep): Step into the function at the current line

n(ext): Continue execution until the next line in the current function is reached or it returns. (The difference between next and step is that step stops inside a called function, while next executes called functions at (nearly) full speed, only stopping at the next line in the current function.)

a(rgs): Print the argument list of the current function

p(rint) variablename : Print value of variablename

quit : To quit rPdb

More info : https://itnext.io/debugging-your-code-in-python-pdb-vs-rpdb-e7bb918a8ac3
Official documentation (commands) : https://docs.python.org/3/library/pdb.html

#######

OR, alternatively : Using this post How to debug python CLI that takes stdin? :

in Odoo.sh>EDITOR (Jupyter Lab): Open a first Terminal and create these two fifos which will be used as stdin/stdout to use pdb :

```<code> mkfifo fifo_stdin

 mkfifo fifo_stdout

 cat fifo_stdout & cat > fifo_stdin
</code>```

...which makes appear a prompt cursor. Keep this Terminal Tab opened.

Write these 2 lines at the top of the Python script to be debugged :

```<code> import pdb
 mypdb=pdb.Pdb(stdin=open('fifo_stdin','r'), stdout=open('fifo_stdout','w'))
</code>```

In this Python script, call set_trace() on your customized mypdb:

```<code>def _get_total_amount(self):
   total_amount = sum(self._get_base_order_lines(program).mapped('price_total'))
   mypdb.set_trace()
   return total_amount
</code>```

...

Body:
Using my odoo.sh project (v13.0.2) > EDITOR-Tab , which redirects me to mywebsite.odoo.com/odoo-sh/editor/lab, when i want to debug using import pdb; pdb.set_trace(), it raises a BdbQuit Error :

  File "/usr/lib/python3.6/bdb.py", line 113, in
  dispatch_exception
    if self.quitting: raise BdbQuit

In the past versions : v13.0.1.xxx, i could use pdb.set_trace() to debug my python code. How to solve this issue ?

Body:
rpdb is a remote debugger based on pdb. It re-routes stdin and stdout to a socket handler, so that you can debug server processes (remotely).

In Odoo.sh > yourstagingBranch, click on the SHELL-tab:

mywebsite-oerp-staging-5070461 [staging/v13.0]:~$ pip3 install rpdb

In Odoo.sh > yourstagingBranch, click on the EDITOR-tab:

IN ODOO-EDITOR:

At the top of your python file, add:

    import rpdb

In the function (def subscribe) to be inspected, add:

    def subscribe(self, event, **post):
        # code before
        rpdb.set_trace()
        # code after

Click on menu Tab : Odoo>Update current module : alternatively, open a new Terminal window and execute this command: odoo-bin -u website_sale --stop-after-init

    mywebsite-oerp-staging-5070461 [staging/v13.0]: odoo-bin -u website_sale --stop-after-init

After having restarted Odoo (all modules loaded), execute this command in the other Terminal window: nc 127.0.0.1 4444

    mywebsite-oerp-staging-5070461 [staging/v13.0]: ~$ nc 127.0.0.1 4444

We can then use the common pdb commands:

l(ist): Lists the lines surrounding the current line

w(here): Displays the file and line number where we currently are

s(tep): Step into the function at the current line

n(ext): Continue execution until the next line in the current function is reached or it returns. (The difference between next and step is that step stops inside a called function, while next executes called functions at (nearly) full speed, only stopping at the next line in the current function.)

a(rgs): Print the argument list of the current function

p(rint) variablename : Print value of variablename

quit : To quit rPdb

More info : https://itnext.io/debugging-your-code-in-python-pdb-vs-rpdb-e7bb918a8ac3
Official documentation (commands) : https://docs.python.org/3/library/pdb.html

#######

OR, alternatively : Using this post How to debug python CLI that takes stdin? :

in Odoo.sh>EDITOR (Jupyter Lab): Open a first Terminal and create these two fifos which will be used as stdin/stdout to use pdb :

 mkfifo fifo_stdin

 mkfifo fifo_stdout

 cat fifo_stdout & cat > fifo_stdin

...which makes appear a prompt cursor. Keep this Terminal Tab opened.

Write these 2 lines at the top of the Python script to be debugged :

 import pdb
 mypdb=pdb.Pdb(stdin=open('fifo_stdin','r'), stdout=open('fifo_stdout','w'))

In this Python script, call set_trace() on your customized mypdb:

def _get_total_amount(self):
   total_amount = sum(self._get_base_order_lines(program).mapped('price_total'))
   mypdb.set_trace()
   return total_amount

...