问:
pandas DataFrame: how to sentence into words and select rows that have more than 10 words?
I have a DataFrame with each row a sentence. However the sentences are not the same length. I want to select those rows which contains more than 10 words, something like

```<code>df = df.loc[len(df[src].str.split()) > 10]
</code>```

But this will raise the Error of Key being True. How to do that?

答:
Try with series.str.len():

```<code>df[df['src'].str.split().str.len() > 10]
</code>```

Body:
I have a DataFrame with each row a sentence. However the sentences are not the same length. I want to select those rows which contains more than 10 words, something like

df = df.loc[len(df[src].str.split()) > 10]

But this will raise the Error of Key being True. How to do that?

Body:
Try with series.str.len():

df[df['src'].str.split().str.len() > 10]


来源: stackexchange

问:
OpenJDK 10 rejects all SSL certificates
I installed OpenJDK 10. What I did was just unpack it, set the PATH variable and the JAVA_HOME variable.

Java even rejects the certificate of google.de (and all others I tried). I tested this by some dummy class that tries to connect. Outcome is:

```<code>C:\Users\Alexander\Downloads>java SSLPoke google.de 443
sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
        at java.base/sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:385)
        at java.base/sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:290)
        at java.base/sun.security.validator.Validator.validate(Validator.java:264)
        at java.base/sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:343)
        at java.base/sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:226)
        at java.base/sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:133)
        at java.base/sun.security.ssl.ClientHandshaker.checkServerCerts(ClientHandshaker.java:1947)
        at java.base/sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1777)
        at java.base/sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:264)
        at java.base/sun.security.ssl.Handshaker.processLoop(Handshaker.java:1098)
        at java.base/sun.security.ssl.Handshaker.processRecord(Handshaker.java:1026)
        at java.base/sun.security.ssl.SSLSocketImpl.processInputRecord(SSLSocketImpl.java:1137)
        at java.base/sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1074)
        at java.base/sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973)
        at java.base/sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1402)
        at java.base/sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:733)
        at java.base/sun.security.ssl.AppOutputStream.write(AppOutputStream.java:67)
        at java.base/sun.security.ssl.AppOutputStream.write(AppOutputStream.java:81)
        at SSLPoke.main(SSLPoke.java:31)
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
        at java.base/sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
        at java.base/sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
        at java.base/java.security.cert.CertPathBuilder.build(CertPathBuilder.java:297)
        at java.base/sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)
        ... 18 more
</code>```

Found a lot on the net how to add special certs to java but i think in my java installation something is wrong in general.

So my question is what could cause such a thing???

答:
You should verify root certificates inside the cacerts keystore. The file is stored in JAVA_HOME/jre/lib/security/cacerts (or JAVA_HOME/lib/security/cacerts in newer Java versions). As per OpenJDK 10 Now Includes Root CA Certificates post you can use keytool command to count them:

>jdk-10\bin\keytool -cacerts -list | find "Certificate" /c
Enter keystore password:  changeit
80
```

Most likely your Java installation is corrupted and you should reinstall. Do note that OpenJDK is provided by multiple vendors and it could be that you are using an installer which doesn't install the root certificates.

ContentLicense: CC BY-SA 4.0

Title: OpenJDK 10 rejects all SSL certificates

Body:
I installed OpenJDK 10. What I did was just unpack it, set the PATH variable and the JAVA_HOME variable.

Java even rejects the certificate of google.de (and all others I tried). I tested this by some dummy class that tries to connect. Outcome is:

C:\Users\Alexander\Downloads>java SSLPoke google.de 443
sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
        at java.base/sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:385)
        at java.base/sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:290)
        at java.base/sun.security.validator.Validator.validate(Validator.java:264)
        at java.base/sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:343)
        at java.base/sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:226)
        at java.base/sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:133)
        at java.base/sun.security.ssl.ClientHandshaker.checkServerCerts(ClientHandshaker.java:1947)
        at java.base/sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1777)
        at java.base/sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:264)
        at java.base/sun.security.ssl.Handshaker.processLoop(Handshaker.java:1098)
        at java.base/sun.security.ssl.Handshaker.processRecord(Handshaker.java:1026)
        at java.base/sun.security.ssl.SSLSocketImpl.processInputRecord(SSLSocketImpl.java:1137)
        at java.base/sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1074)
        at java.base/sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973)
        at java.base/sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1402)
        at java.base/sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:733)
        at java.base/sun.security.ssl.AppOutputStream.write(AppOutputStream.java:67)
        at java.base/sun.security.ssl.AppOutputStream.write(AppOutputStream.java:81)
        at SSLPoke.main(SSLPoke.java:31)
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
        at java.base/sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
        at java.base/sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
        at java.base/java.security.cert.CertPathBuilder.build(CertPathBuilder.java:297)
        at java.base/sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)
        ... 18 more

Found a lot on the net how to add special certs to java but i think in my java installation something is wrong in general.

So my question is what could cause such a thing???

Body:
You should verify root certificates inside the cacerts keystore. The file is stored in JAVA_HOME/jre/lib/security/cacerts (or JAVA_HOME/lib/security/cacerts in newer Java versions). As per OpenJDK 10 Now Includes Root CA Certificates post you can use keytool command to count them:

>jdk-10\bin\keytool -cacerts -list | find "Certificate" /c
Enter keystore password:  changeit
80

Most likely your Java installation is corrupted and you should reinstall. Do note that OpenJDK is provided by multiple vendors and it could be that you are using an installer which doesn't install the root certificates.


问:
Bootstrap collapse scroll to bottom issue
I have a bootstrap collapse panel. In there I have placed toggle link bottom of the content so it will go down and up when click that link.

The problem

I have a long list of content. I need to move users to top when they click toggle. But in here, when I expand the menu and click collapse, it will go all the way to bottom of the page. Instead of I need to move users to the top of the page. I tried to set offset top but no luck.

Any idea?

My Jquery

```<code>$('html,body').animate({
     scrollTop: $(".collapsed").offset().top
 },500);
</code>```

jsfiddle

答:
You can achieve the scrolling by attaching an event-listener to the toggle-element and then checking the classes of the pannel-collapse element.</p>

```<code>$('#accordion .panel-heading a').on('click', function (event) {
  let panelCollapse = $(this).closest('.panel').find('.panel-collapse');
  if (!panelCollapse.hasClass('collapse')) {
    $('html, body').animate({
      scrollTop: panelCollapse.offset().top
    }, 500);
  }
});
</code>```

Body:
I have a bootstrap collapse panel. In there I have placed toggle link bottom of the content so it will go down and up when click that link.

The problem

I have a long list of content. I need to move users to top when they click toggle. But in here, when I expand the menu and click collapse, it will go all the way to bottom of the page. Instead of I need to move users to the top of the page. I tried to set offset top but no luck.

Any idea?

My Jquery

$('html,body').animate({
     scrollTop: $(".collapsed").offset().top
 },500);

jsfiddle

Body:
You can achieve the scrolling by attaching an event-listener to the toggle-element and then checking the classes of the pannel-collapse element.

$('#accordion .panel-heading a').on('click', function (event) {
  let panelCollapse = $(this).closest('.panel').find('.panel-collapse');
  if (!panelCollapse.hasClass('collapse')) {
    $('html, body').animate({
      scrollTop: panelCollapse.offset().top
    }, 500);
  }
});


问:
Importing module when tkitner button is pressed
I have a program which involves several classes as frames in tkinter. I have a separate file that uses pygame and is a chess game. I want to be able to load this file up and execute it when I press a certain tkinter button in one of the frames and to then close this file. I am aware that importing the module at the beginning of the tkinter file runs it immediately which is not what I need. I only want it to run when the button is pressed.

I have attempted to use other modules which do not work. I have tried using functions which also did not work.

I expect to be able to run the chess file when the button is pressed, instead of immediately as this holding file is ran.
However, when run the chess file executes immediately and this other file does not even run.

答:
If you enclose your main Python code in if __name__ == "__main__":, then it will run only if the file is executed, not loaded as the module. It's a common practice.

And if you make your spam.py like that:

```<code>def main():
    do_things_here

if __name__ == "__main__":
    main()
</code>```

You can just import spam at the beginning with nothing happening and do spam.main() when you want to execute it.

But if you really want to load modules dynamically, exec("import " + module_name)

Body:
If you enclose your main Python code in if __name__ == "__main__":, then it will run only if the file is executed, not loaded as the module. It's a common practice.

And if you make your spam.py like that:

def main():
    do_things_here

if __name__ == "__main__":
    main()

You can just import spam at the beginning with nothing happening and do spam.main() when you want to execute it.

But if you really want to load modules dynamically, exec("import " + module_name)


问:
Can't open some DBF files in PHP
I have a php script that uses dbase to open dbf files.
I found that I can't open some of this files and I don't know why.

The error that I got is:

dbase_open(): unable to open database

But I can open other files without problem.

I've tried open it with DBF Viewer and then exporting it again and it works then, but I can't do that with php.

I don't know if it could be a charset problem or a version problem, but files seem equal, in Visual FoxPro.

What should i check?

答:
The problem was a column with type Timestamp dbase for php doesn't allow this type.
The solution was convert timestamp to date

Title: Can't open some DBF files in PHP


问:
Ansible Docker exec failed with docker not found in path?
Using docker with ansible, the simulation of a docker exec process failed with an awkward error

```<code>---
- hosts: centos
  become: true
  tasks:
    - name: create jenkins container
      docker_container:
        name: my_jenkins
        image: jenkins

    - name: add container to inventory
      add_host:
        name: my_jenkins
        ansible_connection: docker
        ansible_user: jenkins
      changed_when: false

    - name: create directory for ssh keys
      delegate_to: my_jenkins
      file:
        path: "/var/jenkins_home/.ssh/jupiter"
        state: directory
</code>```

error

```<code>TASK [create directory for ssh keys] ***********************************************************************************
fatal: [apollo]: FAILED! => {"msg": "docker command not found in PATH"}
</code>```

答:
"docker command not found in PATH" means that Ansible tried to execute the docker command but the docker executable could not be found. echo $PATH to see the current dir. paths that are searched for executable.

Given that Ansible is able to complete step 1 and 2, my assumption is that the docker daemon did indeed install successfully. So

Add the path to the Docker daemon to the systems $PATH Install.

Docker into a path that is already included in the $PATH.

Hope this helps out.

Body:
Using docker with ansible, the simulation of a docker exec process failed with an awkward error

---
- hosts: centos
  become: true
  tasks:
    - name: create jenkins container
      docker_container:
        name: my_jenkins
        image: jenkins

    - name: add container to inventory
      add_host:
        name: my_jenkins
        ansible_connection: docker
        ansible_user: jenkins
      changed_when: false

    - name: create directory for ssh keys
      delegate_to: my_jenkins
      file:
        path: "/var/jenkins_home/.ssh/jupiter"
        state: directory

error

TASK [create directory for ssh keys] ***********************************************************************************
fatal: [apollo]: FAILED! => {"msg": "docker command not found in PATH"}


Title: rest every two rows of the same column in sql and and convert the result in seconds

Body:
I need help with my Hive table .

   DATE               |    ID     |    RESTDATESINSECONDS

 2019-03-28 10:05:27        1             (2019-03-28 10:05:38)-(2019-03-28 10:05:27)
 2019-03-28 10:05:38        1             (2019-03-28 10:14:14)- (2019-03-28 10:05:38)
 2019-03-28 10:14:14        1             (2019-03-28 10:14:16) -(2019-03-28 10:14:14)
 2019-03-28 10:14:16        1             (2019-03-28 10:14:46) -(2019-03-28 10:14:16)
 2019-03-28 10:14:46        1             (2019-03-28 10:15:30) -(2019-03-28 10:15:30)
 2019-03-28 10:15:30        1                """
     """                    """              """

I have two hundred thousand rows. I would like to return this as:

   DATE               |    ID     |    RESTDATESINSECONDS

 2019-03-28 10:05:27        1             11
 2019-03-28 10:05:38        1             516
 2019-03-28 10:14:14        1             2
 2019-03-28 10:14:16        1             30
 2019-03-28 10:14:46        1             44
 2019-03-28 10:15:30        1             ""

I have tried all kinds of parenthesis and counts, but everything I try throws different errors for syntax! Does anyone have any ideas?

Many Thanks :)

Body:
with cte_test_table
as
(select * from
  ( values('2019-03-28 10:05:27',1)
         ,('2019-03-28 10:05:38',1)
         ,('2019-03-28 10:14:14',1)
         ,('2019-03-28 10:14:16',1)
         ,('2019-03-28 10:14:46',1)
         ,('2019-03-28 10:15:30',1)
  ) as t([Date],ID)
)

select ID, [Date]
,datediff(ss,[Date],LAG ([Date], 1, [Date]) over (partition by ID order by [Date] desc)) as RESTDATESINSECONDS
from cte_test_table
order by [Date]


问:
reusable view in iOS
I need to display different data at the different instance in a page with respect a list selection on the same page. Is there any mechanism like fragment is in ios. how to solve this. I need to display a list of horizontal items at the bottom and with respect, the selection the content on the page should be changed.</p>

答: You can use Collection view and in cell of collection-view , you can create pages with scrollview. Also you can create manage collection-view as horizontal/vertical.</p>

Title: reusable view in iOS


问:
Cucumber Test steps not showing in J-Unit while in console steps have run successfully
I'm currently trying to create my first Cucumber tests. In Java Eclipse I have created a 'Feature file' with the following content:

```<code>Feature: Login functionality DemoQA.com

Scenario: Verify if user is able to login to the DemoQA website
    Given A user is on DemoQA.com
    When User clicks MyAccount link
    Then User is taken to Login Page
    When User enters valid username and password
    Then User is able to login
</code>```

I also created the following testrunner file:

```<code>@RunWith(Cucumber.class)
@CucumberOptions(
        features = "src/test/Features/",
        glue = {"Tests"}
        )
public class CucumberRunner {
}
</code>```

I also created my Stepdefinitions:

public class LoginStepDefinitions {

```<code>@Given("A user is on DemoQA.com")
public void a_user_is_on_DemoQA_com() {

     System.setProperty("webdriver.gecko.driver","C:\\geckodriver-v0.10.0-win64\\geckodriver.exe");

         WebDriver driver = new FirefoxDriver();
         WebDriverWait wait = new WebDriverWait(driver, 50);

         String url = "https://demoqa.com";

            //Launch the Online Store Website
            driver.get(url);

try {

            wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\"logo-events\"]/a/img")));
            driver.findElement(By.xpath("//*[@id=\"logo-events\"]/a/img"));
            System.out.println("User has succesfully opened DemoQA.com");

             }

catch (Exception e) {
            System.out.println("User was not able to open DemoQA.com");

            }

}

@When("User clicks MyAccount link")
public void user_clicks_MyAccount_link() {
    // Write code here that turns the phrase above into concrete actions
    System.out.println("User clicks on the MyAccount link");
}

@Then("User is taken to Login Page")
public void user_is_taken_to_Login_Page() {
    System.out.println("User is succesfully taken to MyAccount login");
}

@When("User enters valid username and password")
public void user_enters_valid_username_and_password() {
    System.out.println("User enters valid credentials for MyAccount login");
}

@Then("User is able to login")
public void user_is_able_to_login() {
    // Write code here that turns the phrase above into concrete actions
    System.out.println("User is succesfully logged in");
}
</code>```

}

When I run my script as a Junit test, the console succesfully executes the test and shows the result:

```<code>User has succesfully opened DemoQA.com
[32m.[0mUser clicks on the MyAccount link
[32m.[0mUser is succesfully taken to MyAccount login
[32m.[0mUser enters valid credentials for MyAccount login
[32m.[0mUser is succesfully logged in
[32m.[0m
1 Scenarios ([32m1 passed[0m)
5 Steps ([32m5 passed[0m)
0m7.706s
</code>```

But when opening the JUnit tab two things happen:

1) Teststeps don't seem to be shown:

2) When I doubleclick the Feature / Scenario steps I get a message:

Test Class not found in selected project

Having read some of the other posts around this subject, my first thought was that my feature file was not located in the correct folder, but I have moved it almost everywhere now and it does not seem to make any difference.

This is my current structure in Eclipse:

Can anybody help me out please? Thx!

答: I have solved the issue myself by adding the following line in the @cucumberoptions of my Runner file: junit = "--step-notifications" . After adding this line in the runner file, my testssteps also appear in the Junit result. Question can be closed </p>

Body:
I'm currently trying to create my first Cucumber tests. In Java Eclipse I have created a 'Feature file' with the following content:

Feature: Login functionality DemoQA.com

Scenario: Verify if user is able to login to the DemoQA website
    Given A user is on DemoQA.com
    When User clicks MyAccount link
    Then User is taken to Login Page
    When User enters valid username and password
    Then User is able to login

I also created the following testrunner file:

@RunWith(Cucumber.class)
@CucumberOptions(
        features = "src/test/Features/",
        glue = {"Tests"}
        )
public class CucumberRunner {
}

I also created my Stepdefinitions:

public class LoginStepDefinitions {

@Given("A user is on DemoQA.com")
public void a_user_is_on_DemoQA_com() {

     System.setProperty("webdriver.gecko.driver","C:\\geckodriver-v0.10.0-win64\\geckodriver.exe");

         WebDriver driver = new FirefoxDriver();
         WebDriverWait wait = new WebDriverWait(driver, 50);

         String url = "https://demoqa.com";

            //Launch the Online Store Website
            driver.get(url);

try {

            wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\"logo-events\"]/a/img")));
            driver.findElement(By.xpath("//*[@id=\"logo-events\"]/a/img"));
            System.out.println("User has succesfully opened DemoQA.com");

             }

catch (Exception e) {
            System.out.println("User was not able to open DemoQA.com");

            }

}

@When("User clicks MyAccount link")
public void user_clicks_MyAccount_link() {
    // Write code here that turns the phrase above into concrete actions
    System.out.println("User clicks on the MyAccount link");
}

@Then("User is taken to Login Page")
public void user_is_taken_to_Login_Page() {
    System.out.println("User is succesfully taken to MyAccount login");
}

@When("User enters valid username and password")
public void user_enters_valid_username_and_password() {
    System.out.println("User enters valid credentials for MyAccount login");
}

@Then("User is able to login")
public void user_is_able_to_login() {
    // Write code here that turns the phrase above into concrete actions
    System.out.println("User is succesfully logged in");
}

}

When I run my script as a Junit test, the console succesfully executes the test and shows the result:

User has succesfully opened DemoQA.com
[32m.[0mUser clicks on the MyAccount link
[32m.[0mUser is succesfully taken to MyAccount login
[32m.[0mUser enters valid credentials for MyAccount login
[32m.[0mUser is succesfully logged in
[32m.[0m
1 Scenarios ([32m1 passed[0m)
5 Steps ([32m5 passed[0m)
0m7.706s

But when opening the JUnit tab two things happen:

1) Teststeps don't seem to be shown:

2) When I doubleclick the Feature / Scenario steps I get a message:

Test Class not found in selected project

Having read some of the other posts around this subject, my first thought was that my feature file was not located in the correct folder, but I have moved it almost everywhere now and it does not seem to make any difference.

This is my current structure in Eclipse:

Can anybody help me out please? Thx!


问:
 overflow:auto does not show scrollbar until resize
I have a  element on my form that looks like this:

```<code><div style="overflow-y:auto;overflow-x:hidden;height:100%;width:100%">
</code>```

In IE7 when the page first renders, there are no scrollbars. However, if I resize the page (even just 1 pixel) the scroll bars appear properly.

Is there something I can do so that the scrollbars show properly when the page first displays?

答:
I used overflow: scroll and it fixed my issue with the disappearing scrollbar on load. My tables are dynamically created and should scroll automatically when the page loads as I have enough data to start with.

I didn't have to make any other changes. Now it works in all three browsers IE7, IE8 and FF.

ContentLicense: CC BY-SA 2.5

Title: <div> overflow:auto does not show scrollbar until resize

Body:
I have a  element on my form that looks like this:

In IE7 when the page first renders, there are no scrollbars. However, if I resize the page (even just 1 pixel) the scroll bars appear properly.

Is there something I can do so that the scrollbars show properly when the page first displays?

ContentLicense: CC BY-SA 3.0


问:
Is there a way to restrict container access for user in Docker?
I'm using a Docker machine to host some process such as game servers with friends. I want to give access to CLI of some containers for some users (and only for that), so that they cannot interfer eachothers. I don't want those to be roots on this server.

A solution might be to create users, allow them to perform certains commands in adequation with their containers (such as sudo docker attach ) and let them do everything. I would like to know if there is another, better and proper way to do it so.

Do you have done any experimentation of this kind ?

Thanks.

答:
Sadly as standing there

Why doesn't Docker support multi-tenancy?

docker doesn't support multi-tenancy so you cannot isolate users from each other.

Edit: one of the possible solutions is to create SSH server in every container and then let your users to connect directly via SSH to container instead of using host machine.


问:
What is the SQL query to calculate average lease time?
I need to calculate an average lease time of my cars grouped by a brand.

For simplicity, I have the following LEASE table in my DB:

```<code>carMake | startDateTime | endDateTime
</code>```

My unfinished SQL query looks like:

```<code>SELECT lease.carMake
FROM lease
WHERE lease.startDateTime <= {?endDate} AND lease.endDateTime >= {?startDate}
SUM ... ???
GROUP BY lease.carMake ;
</code>```

Example:

```<code>carMake |   startDateTime   | endDateTime
MB        01.01.2018 00:00     01.01.2019 00:00
BMW       07.06.2018 21:00     01.01.2019 00:00
MB        06.06.2018 00:00     07.06.2018 00:00
</code>```

Result with query range between 06.06.2018 and 07.06.2018:

```<code>carMake | avgTime
MB        36 hours
BMW       3 hours
</code>```

Database is PostgreSQL

答:
This can be solved with a timestamp range quite easily.

First we calculate the overlapping interval between the desired time and the lease time, from that we can calculate the average in hours:

```<code>select carmake, avg(extract(epoch from upper(duration) - lower(duration)) / 3600) as hours
from (
  select carmake,
         tsrange(startdatetime, enddatetime, '[]') * tsrange(timestamp '2018-06-06 00:00:00', timestamp '2018-06-08 00:00:00', '[)') duration
  from lease
) t
group by carmake;
</code>```

The trick is the intersection operator * for the tsrange.

Online example: https://rextester.com/KYXB18998

Body:
I need to calculate an average lease time of my cars grouped by a brand.

For simplicity, I have the following LEASE table in my DB:

carMake | startDateTime | endDateTime

My unfinished SQL query looks like:

SELECT lease.carMake
FROM lease
WHERE lease.startDateTime <= {?endDate} AND lease.endDateTime >= {?startDate}
SUM ... ???
GROUP BY lease.carMake ;

Example:

carMake |   startDateTime   | endDateTime
MB        01.01.2018 00:00     01.01.2019 00:00
BMW       07.06.2018 21:00     01.01.2019 00:00
MB        06.06.2018 00:00     07.06.2018 00:00

Result with query range between 06.06.2018 and 07.06.2018:

carMake | avgTime
MB        36 hours
BMW       3 hours

Database is PostgreSQL

Body:
This can be solved with a timestamp range quite easily.

First we calculate the overlapping interval between the desired time and the lease time, from that we can calculate the average in hours:

select carmake, avg(extract(epoch from upper(duration) - lower(duration)) / 3600) as hours
from (
  select carmake,
         tsrange(startdatetime, enddatetime, '[]') * tsrange(timestamp '2018-06-06 00:00:00', timestamp '2018-06-08 00:00:00', '[)') duration
  from lease
) t
group by carmake;

The trick is the intersection operator * for the tsrange.

Online example: https://rextester.com/KYXB18998


问:
XSLT is not compiling due to Internal Server Error
I am using XSLT 1.0 and I am trying to check it's for well formedness.

my XSLT is as below:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
   <xsl:template match="*">
      <div style="position: relative; top: 0px;">
         <xsl:if test="//PQMessage[.!='']">
            <div>
               <img align="absmiddle" src="contactImages/messageBox/exclamationICON.gif" />
               <b>
                  <xsl:value-of select="//PQMessage" />
               </b>
            </div>
         </xsl:if>
         <div style="position: relative; left: 0px; top: 10px; height: 220px; color2: #590a18; background-image: url( contactImages/claimLineInfobox.gif );background-repeat: no-repeat;">
            <img src="contactImages/divisionsCenter.gif" style="position: relative; left: 14px; top: 4px; " alt="dividerbar" />
            <xsl:apply-templates select="//divisions" />
         </div>
         <div id="BrokerListResults" style="position: relative; left: 0px; top: 20px; width: 960px; height: 400px; color2: #590a18; background-image: url( contactImages/listofDivisionBrokersbox.gif );background-repeat: no-repeat;" />
      </div>
   </xsl:template>
   <xsl:template match="divisions">
      <xsl:variable name="userProvidedEffDate" select="number(concat(substring(//userProvidedEffDate, 7, 4), substring(//userProvidedEffDate, 1, 2), substring(//userProvidedEffDate, 4, 2)))" />
      <xsl:copy>
         <xsl:apply-templates select="division" />
      </xsl:copy>
      <div id="divisionsListAA" style="position:relative; top:0px; left:10px; width:907px;">
         <table id="DivisionTableHead" class="PQTable" border="0" cellpadding="0px" cellspacing="0px" style="position:relative; width:890px; font-size:11pt;">
            <tr style=" position:relative; background-color:#FAF6F2; font-weight:bold;">
               <td width="50px" />
               <td style=" width:162px; ">Division #</td>
               <td style=" width:162px; ">Effective Date</td>
               <td style=" width:162px; ">Expiration Date</td>
               <td style=" width:112px; ">Business Unit</td>
               <td style=" width:81px; ">Program</td>
               <td style=" width:81px; ">Carrier</td>
               <td style=" width:81px; ">Region</td>
            </tr>
         </table>
         <table id="DivisionTable" class="PQTable stripeRow" border="0" cellpadding="0px" cellspacing="0px" style="position:relative; width:890px; font-size:11pt;">
            <xsl:apply-templates select="division" />
         </table>
      </div>
   </xsl:template>
   <xsl:template match="division">
      <xsl:if test="([number(concat(substring(GroupEffDt, 7, 4), substring(GroupEffDt, 1, 2), substring(GroupEffDt, 4, 2))) <= $userProvidedEffDate                                       and number(concat(substring(GroupExpDt, 7, 4), substring(GroupExpDt, 1, 2), substring(GroupExpDt, 4, 2))) >= $userProvidedEffDate])">
         <tr>
            <td width="50px">
               <div onclick="resetAmisysDivisionDisplay(this);">
                  <input type="checkbox" id="checkbox" style="cursor: pointer;" />
                  <div id="DivisionDetailArea" style="display: none;" />
               </div>
            </td>
            <td width="162px">
               <xsl:value-of select="GroupNumber" />
            </td>
            <td width="162px">
               <xsl:value-of select="GroupEffDt" />
            </td>
            <td width="162px">
               <xsl:value-of select="GroupExpDt" />
            </td>
            <td width="112px">
               <xsl:value-of select="substring(groupLOB,1,2)" />
            </td>
            <td width="81px">
               <xsl:value-of select="substring(groupLOB,4,2)" />
            </td>
            <td width="81px">
               <xsl:value-of select="substring(groupLOB,7,2)" />
            </td>
            <td width="81px">
               <xsl:value-of select="substring(groupLOB,10,2)" />
            </td>
         </tr>
      </xsl:if>
   </xsl:template>
</xsl:stylesheet>
</code>```

When I try to compile the above xsl online(http://www.utilities-online.info/xsltransformation/#.XPEFsogza71), I am getting the below error:

```<code>Internal Server Error: <html><head><title>Error</title></head><body>Internal Server Error</body></html>
</code>```

It appears that the XSL file not well formed one. I am unable to figure out the actual problem.

What could be the mistake here? Could you please help me?

答:
As suggested in comments, you should get a tool that provides detailed error reports rather than rely on other people debugging your code.

As it happens, you have at least two errors on line 44:

```<code><xsl:if test="([number(concat(substring(GroupEffDt, 7, 4), substring(GroupEffDt, 1, 2), substring(GroupEffDt, 4, 2))) <= $userProvidedEffDate                                       and number(concat(substring(GroupExpDt, 7, 4), substring(GroupExpDt, 1, 2), substring(GroupExpDt, 4, 2))) >= $userProvidedEffDate])">
</code>```

the variable userProvidedEffDate has not been defined;

the expression is invalid because of your use of square brackets.

Neither of these has anything to do with your XSLT being well-formed.

Body:
I am using XSLT 1.0 and I am trying to check it's for well formedness.

my XSLT is as below:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
   <xsl:template match="*">

         <xsl:if test="//PQMessage[.!='']">

                  <xsl:value-of select="//PQMessage" />

         </xsl:if>

            <xsl:apply-templates select="//divisions" />

   </xsl:template>
   <xsl:template match="divisions">
      <xsl:variable name="userProvidedEffDate" select="number(concat(substring(//userProvidedEffDate, 7, 4), substring(//userProvidedEffDate, 1, 2), substring(//userProvidedEffDate, 4, 2)))" />
      <xsl:copy>
         <xsl:apply-templates select="division" />
      </xsl:copy>

               Division #
               Effective Date
               Expiration Date
               Business Unit
               Program
               Carrier
               Region

            <xsl:apply-templates select="division" />

   </xsl:template>
   <xsl:template match="division">
      <xsl:if test="([number(concat(substring(GroupEffDt, 7, 4), substring(GroupEffDt, 1, 2), substring(GroupEffDt, 4, 2))) <= $userProvidedEffDate                                       and number(concat(substring(GroupExpDt, 7, 4), substring(GroupExpDt, 1, 2), substring(GroupExpDt, 4, 2))) >= $userProvidedEffDate])">

                  <input type="checkbox" id="checkbox" style="cursor: pointer;" />

               <xsl:value-of select="GroupNumber" />

               <xsl:value-of select="GroupEffDt" />

               <xsl:value-of select="GroupExpDt" />

               <xsl:value-of select="substring(groupLOB,1,2)" />

               <xsl:value-of select="substring(groupLOB,4,2)" />

               <xsl:value-of select="substring(groupLOB,7,2)" />

               <xsl:value-of select="substring(groupLOB,10,2)" />

      </xsl:if>
   </xsl:template>
</xsl:stylesheet>

When I try to compile the above xsl online(http://www.utilities-online.info/xsltransformation/#.XPEFsogza71), I am getting the below error:

Internal Server Error: <title>Error</title>Internal Server Error

It appears that the XSL file not well formed one. I am unable to figure out the actual problem.

What could be the mistake here? Could you please help me?

Body:
As suggested in comments, you should get a tool that provides detailed error reports rather than rely on other people debugging your code.

As it happens, you have at least two errors on line 44:

<xsl:if test="([number(concat(substring(GroupEffDt, 7, 4), substring(GroupEffDt, 1, 2), substring(GroupEffDt, 4, 2))) &lt;= $userProvidedEffDate                                       and number(concat(substring(GroupExpDt, 7, 4), substring(GroupExpDt, 1, 2), substring(GroupExpDt, 4, 2))) &gt;= $userProvidedEffDate])">

the variable userProvidedEffDate has not been defined;

the expression is invalid because of your use of square brackets.

Neither of these has anything to do with your XSLT being well-formed.


问:
Are Swift constants lazy by default?
Something I still not quite understand about Swift ... let's say I want a property that instantiates a class in a base class used for several sub classes, e.g. ...

```<code>let horse = Horse();
</code>```

Is horse instantiated right after app/class initialisation or when the property is accessed for the first time?

On the other hand using lazy var guarantees that the property is only instantiated the first time it is accessed ...

```<code>lazy var horse = Horse()
</code>```

But then horse is not a constant. So in this case if I access horse multiple times I would get multiple instances of horse created, right?

What if I wanted both, a lazy property that is also a constant?

答:
Well, a bit late, but I think you can create a lazy property as constant using private(set) . Consider the example below :

```<code>import Foundation

struct GPS: CustomStringConvertible {
    let name: String

    init(name: String) {
        self.name = name
        print("GPS Initialised")
    }

    var description: String {
        return name
    }
}

struct Car {
    private(set) lazy var gps = GPS(name: "One")

    init() {
        print("Car Initialised")
    }
}

var someCar = Car()
print(someCar.gps) // Comment/Uncomment this to see lazy in action
//someCar.gps = GPS("Two") // This will create a compilation error
//
</code>```

However, if you remove the private(set), it(gps variable inside Car) will become a variable again which can be mutated.

You can uncomment the last line after removing the private(set) to verify the same

Title: Are Swift constants lazy by default?

Body:
Something I still not quite understand about Swift ... let's say I want a property that instantiates a class in a base class used for several sub classes, e.g. ...

let horse = Horse();

Is horse instantiated right after app/class initialisation or when the property is accessed for the first time?

On the other hand using lazy var guarantees that the property is only instantiated the first time it is accessed ...

lazy var horse = Horse()

But then horse is not a constant. So in this case if I access horse multiple times I would get multiple instances of horse created, right?

What if I wanted both, a lazy property that is also a constant?

Body:
Well, a bit late, but I think you can create a lazy property as constant using private(set) . Consider the example below :

import Foundation

struct GPS: CustomStringConvertible {
    let name: String

    init(name: String) {
        self.name = name
        print("GPS Initialised")
    }

    var description: String {
        return name
    }
}

struct Car {
    private(set) lazy var gps = GPS(name: "One")

    init() {
        print("Car Initialised")
    }
}

var someCar = Car()
print(someCar.gps) // Comment/Uncomment this to see lazy in action
//someCar.gps = GPS("Two") // This will create a compilation error
//

However, if you remove the private(set), it(gps variable inside Car) will become a variable again which can be mutated.

You can uncomment the last line after removing the private(set) to verify the same


问:
Is it okay to put hooks inside a confirm dialog?
In the documentation for Hooks, it mentions that you shouldn't use hooks inside of conditionals, whether they be for loops or if statements. However, I need to put hooks inside of a confirm dialog to in order to confirm with an user that they want to close the modal they are currently working in, and that goes against the hooks documentation so I'm concerned with the side effects of it, despite the fact it works fine. Here's a rough example of the logic(it's a bit buggier than my actual usecase, because the modal isn't showing up in codesandbox, but that's not the issue haha)

https://codesandbox.io/s/hooks-inside-a-confirm-dgvxp

答: I don't see anything wrong in your code in accordance with the doc. You're free to go !</p>


问:
How to empty form fields after onSubmit in React JS
I am trying to empty/clear my form fields after I click submit button using onSubmit event handler in react js

This is my code and it do the work well (submitting form) but not clearing the inputs even after I set states

This is my react App.js

```<code>import React, { Component } from "react";
import "bootstrap/dist/css/bootstrap.css";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

import CreateToDo from "./components/creat-todo.component";
import EditToDo from "./components/edit-todos.component";
import ToDoList from "./components/todos-list.component";

class App extends Component {
  render() {
    return (
      <Router>
        <div className="container">

          <nav className="navbar navbar-expand-lg navbar-light bg-light">
            <Link to="/" className="navbar-brand">MERN-Stack Todo App</Link>
            <div className="collapase navbar-collapse">
              <ul className="navbar-nav mr-auto">
                <li className="navbar-item">
                  <Link to="/" className="nav-link">ToDos</Link>
                </li>
                <li className="navbar-item">
                  <Link to="/create" className="nav-link">Create ToDos</Link>
                </li>
              </ul>
            </div>
          </nav>

          <h2>MERN-Stack Todo App</h2>
          {/* when localhost starts without any additional url extensions */}
          {/* TODO list component should be loaded exactly */}
          <Route path="/" exact component={ToDoList} />
          <Route path="/edit/:id" component={EditToDo} />
          <Route path="/create" component={CreateToDo} />
        </div>
      </Router>
    );
  }
}

export default App;
</code>```

This is creat-todo.component.jsx component

```<code>import React, { Component } from "react";
import axios from 'axios';

export default class CreateToDo extends Component {
  constructor(props) {
    super(props);

    this.state = {
      todo_description: "",
      todo_responsible: "",
      todo_priority: "",
      todo_completed: false
    };

    this.onChangeToDoDescription = this.onChangeToDoDescription.bind(this);
    this.onChangeToDoPriority = this.onChangeToDoPriority.bind(this);
    this.onChangeToDoResponsible = this.onChangeToDoResponsible.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
  }

  onChangeToDoDescription(e) {
    this.setState({
      todo_description: e.target.value
    });
  }

  onChangeToDoResponsible(e) {
    this.setState({
      todo_responsible: e.target.value
    });
  }

  onChangeToDoPriority(e) {
    this.setState({
      todo_priority: e.target.value
    });
  }

  onSubmit(e) {
    e.preventDefault();

    console.log(`Form Submitted`);
    console.log(`Todo Description: ${this.state.todo_description}`);
    console.log(`Todo Responsible: ${this.state.todo_responsible}`);
    console.log(`Todo Priority: ${this.state.todo_priority}`);
    console.log(`Todo Completed: ${this.state.todo_completed}`);

    const newToDo = {
        todo_description: this.state.todo_description,
        todo_responsible: this.state.todo_responsible,
        todo_priority: this.state.todo_priority,
        todo_completed: this.state.todo_completed,
    }

    axios.post('http://localhost:4000/todos/add', newToDo)
    .then(res => {
        console.log(res.data);
    });

    this.setState = {
      todo_description: "",
      todo_responsible: "",
      todo_priority: "",
      todo_completed: false
    };
  }

  render() {
    return (
      <div style={{ marginTop: 20 }}>
        <form onSubmit={this.onSubmit}>
          <div className="form-group">
            <label htmlFor="description">Description: </label>
            <input
              value={this.state.todo_description}
              onChange={this.onChangeToDoDescription}
              type="text"
              className="form-control"
              id="description"
              aria-describedby="emailHelp"
              placeholder="Enter email"
            />
          </div>

          <div className="form-group">
            <label htmlFor="description">Responsible: </label>
            <input
              value={this.state.todo_responsible}
              onChange={this.onChangeToDoResponsible}
              type="text"
              className="form-control"
              id="description"
              aria-describedby="emailHelp"
              placeholder="Enter email"
            />
          </div>

          <div className="form-check">
            <input
              className="form-check-input"
              type="radio"
              name="priorityOptions"
              id="priorityLow"
              value="Low"
              checked={this.state.todo_priority === 'Low'}
              onChange={this.onChangeToDoPriority}
            />
            <label className="form-check-label" htmlFor="priorityLow">
              Low
            </label>

            <br/>

            <input
              className="form-check-input"
              type="radio"
              name="priorityOptions"
              id="priorityMedium"
              value="Medium"
              checked={this.state.todo_priority === 'Medium'}
              onChange={this.onChangeToDoPriority}
            />
            <label className="form-check-label" htmlFor="priorityMedium">
              Medium
            </label>

            <br/>

            <input
              className="form-check-input"
              type="radio"
              name="priorityOptions"
              id="priorityHigh"
              value="High"
              checked={this.state.todo_priority === 'High'}
              onChange={this.onChangeToDoPriority}
            />
            <label className="form-check-label" htmlFor="priorityHigh">
              High
            </label>

            <br />

            <button type="submit" onSubmit={this.onSubmit} className="btn btn-primary btn-sm">Save ToDo</button>

          </div>
        </form>
      </div>
    );
  }
}
</code>```

Can someone tell me what's wrong?

答:
it should be function with object.

```<code>this.setState({
      todo_description: "",
      todo_responsible: "",
      todo_priority: "",
      todo_completed: false
    });
</code>```

URL: https://codesandbox.io/s/angry-kirch-o6mte

Body:
I am trying to empty/clear my form fields after I click submit button using onSubmit event handler in react js

This is my code and it do the work well (submitting form) but not clearing the inputs even after I set states

This is my react App.js

import React, { Component } from "react";
import "bootstrap/dist/css/bootstrap.css";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

import CreateToDo from "./components/creat-todo.component";
import EditToDo from "./components/edit-todos.component";
import ToDoList from "./components/todos-list.component";

class App extends Component {
  render() {
    return (
      <Router>

            <Link to="/" className="navbar-brand">MERN-Stack Todo App</Link>

                  <Link to="/" className="nav-link">ToDos</Link>

                  <Link to="/create" className="nav-link">Create ToDos</Link>

MERN-Stack Todo App

          {/* when localhost starts without any additional url extensions */}
          {/* TODO list component should be loaded exactly */}
          <Route path="/" exact component={ToDoList} />
          <Route path="/edit/:id" component={EditToDo} />
          <Route path="/create" component={CreateToDo} />

      </Router>
    );
  }
}

export default App;

This is creat-todo.component.jsx component

import React, { Component } from "react";
import axios from 'axios';

export default class CreateToDo extends Component {
  constructor(props) {
    super(props);

    this.state = {
      todo_description: "",
      todo_responsible: "",
      todo_priority: "",
      todo_completed: false
    };

    this.onChangeToDoDescription = this.onChangeToDoDescription.bind(this);
    this.onChangeToDoPriority = this.onChangeToDoPriority.bind(this);
    this.onChangeToDoResponsible = this.onChangeToDoResponsible.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
  }

  onChangeToDoDescription(e) {
    this.setState({
      todo_description: e.target.value
    });
  }

  onChangeToDoResponsible(e) {
    this.setState({
      todo_responsible: e.target.value
    });
  }

  onChangeToDoPriority(e) {
    this.setState({
      todo_priority: e.target.value
    });
  }

  onSubmit(e) {
    e.preventDefault();

    console.log(`Form Submitted`);
    console.log(`Todo Description: ${this.state.todo_description}`);
    console.log(`Todo Responsible: ${this.state.todo_responsible}`);
    console.log(`Todo Priority: ${this.state.todo_priority}`);
    console.log(`Todo Completed: ${this.state.todo_completed}`);

    const newToDo = {
        todo_description: this.state.todo_description,
        todo_responsible: this.state.todo_responsible,
        todo_priority: this.state.todo_priority,
        todo_completed: this.state.todo_completed,
    }

    axios.post('http://localhost:4000/todos/add', newToDo)
    .then(res => {
        console.log(res.data);
    });

    this.setState = {
      todo_description: "",
      todo_responsible: "",
      todo_priority: "",
      todo_completed: false
    };
  }

  render() {
    return (

        <form onSubmit={this.onSubmit}>

            Description:
            <input
              value={this.state.todo_description}
              onChange={this.onChangeToDoDescription}
              type="text"
              className="form-control"
              id="description"
              aria-describedby="emailHelp"
              placeholder="Enter email"
            />

            Responsible:
            <input
              value={this.state.todo_responsible}
              onChange={this.onChangeToDoResponsible}
              type="text"
              className="form-control"
              id="description"
              aria-describedby="emailHelp"
              placeholder="Enter email"
            />

            <input
              className="form-check-input"
              type="radio"
              name="priorityOptions"
              id="priorityLow"
              value="Low"
              checked={this.state.todo_priority === 'Low'}
              onChange={this.onChangeToDoPriority}
            />

              Low

            <input
              className="form-check-input"
              type="radio"
              name="priorityOptions"
              id="priorityMedium"
              value="Medium"
              checked={this.state.todo_priority === 'Medium'}
              onChange={this.onChangeToDoPriority}
            />

              Medium

            <input
              className="form-check-input"
              type="radio"
              name="priorityOptions"
              id="priorityHigh"
              value="High"
              checked={this.state.todo_priority === 'High'}
              onChange={this.onChangeToDoPriority}
            />

              High

            <button type="submit" onSubmit={this.onSubmit} className="btn btn-primary btn-sm">Save ToDo</button>

        </form>

    );
  }
}

Can someone tell me what's wrong?

Body:
it should be function with object.

this.setState({
      todo_description: "",
      todo_responsible: "",
      todo_priority: "",
      todo_completed: false
    });

URL: https://codesandbox.io/s/angry-kirch-o6mte


问:
Locating OEPs in Packed EXE Files
Are there any general rules on how to realiably locate OEPs (Original Entry Points) for packed .exe files, please? What OEP clues  are there to search for in debugged assembly language?

Say there is a Windows .exe file packed with PC-Guard 5.06.0400 and I wish to unpack it. Therefore, the key condition is finding the OEP within the freshly extracted block of code.

I would use the common debugger OllyDBG to do that.

答:
It's hard to point out any simple strategy and claim that it will work in general, because the business of packer tools is to make OEP finding a very hard problem.  Besides, with a good packer, finding the OEP is still not enough.  That being said, I do have some suggestions.

I would suggest that you read this paper on the Justin unpacker, they use heuristics that were reasonably effective at the time, and that you might be able to get some mileage from.  They will at least reduce the number of candidate entry points to a manageable number:

A study of the packer problem and its solutions (2008)
by Fanglu Guo ,  Peter Ferrie ,  Tzi-cker Chiueh

There are also some web-analysis pages that can tell you a lot about your packed program.  For example, the malware analyzer at:
http://eureka.cyber-ta.org/

Here's another one that is currently down, but has done a reasonable job in the past, and I presume will be up again soon):
http://bitblaze.cs.berkeley.edu/renovo.html

Title: Locating OEPs in Packed EXE Files


Title: python string convert into json for the bankstatement

Body:
This my input

string = '07/08/2018 07/08/2018 IMPS DR-1763308000000116-PYTM0123456-917 592674 5,000.00 39,325.93'

I need output like

{'date1':'07/08/2018','date2':'07/08/2018','remark':'IMPS DR-1763308000000116-PYTM0123456-917 592674','credit':'5,000.00','balance' : '39,325.93' }

I tried

result = { 'date1': list1[0], 'date2': list1[1], 'balance': list1[-1]}
print(result)

output

{'date1': '07/08/2018', 'date2': '07/08/2018', 'balance': '39,325.93'}

Body:
Try this:

words = string.split(" ")
values = words[:2] + [" ".join(words[2:-2])] +  words[-2:]
keys = ["date1", "date2", "remark", "credit", "balance"]
result = {}
for i in range(5):
    result[keys[i]] = values[i]

print(result)

Output:

{'date1': '07/08/2018',
 'date2': '07/08/2018',
 'remark': 'IMPS DR-1763308000000116-PYTM0123456-917 592674',
 'credit': '5,000.00',
 'balance': '39,325.93'}


问:
Why does VS Code use a different Terminal than the standard Mac Terminal and how do I change it?
I just installed Dart Sass with the intention of replacing Ruby Sass, which is deprecated.

Now when I check the version of Sass using the Terminal in Visual Studio Code, I get Ruby Sass 3.7.3:

But when I check the version of Sass in a regular Terminal window, I get 1.20.1 compiled with dart2js 2.2.0:

Why is this different and how do I get VS Code to use the same settings as the main terminal?

In case it's helpful, my terminal setting in VS Code is /bin/bash/:

Also, in case it's helpful, when I echo $PATH at the two different terminals, I get different results.

答:
I "solved" this problem by uninstalling Ruby Sass:

```<code>sudo gem uninstall sass
</code>```

I still don't understand how VS Code was using a different version of Sass in its terminal, but at least this is resolved.

Body:
I "solved" this problem by uninstalling Ruby Sass:

sudo gem uninstall sass

I still don't understand how VS Code was using a different version of Sass in its terminal, but at least this is resolved.


问:
gtrends r package - the number of hits over time changes sometimes
I'm having some trouble using the gtrends r package. I'm using "R Studio Version 1.1.463", running the "R version 3.5.1.".

When I'm searching for a specific keyword, sometimes the historical series of the hits changes a lot. Here is an example:

```<code>library(gtrendsR)

cr_br_prev1<-gtrends(keyword = c("Previdência"), geo = "BR", time = "2015-01-01 2018-12-26", gprop = c("web"),category = 37)
head(cr_br_prev1$interest_over_time$hits)

cr_br_prev2<-gtrends(keyword = c("Previdência"), geo = "BR", time = "2015-01-01 2018-12-26", gprop = c("web"),category = 37)
head(cr_br_prev2$interest_over_time$hits)

cr_br_prev3<-gtrends(keyword = c("Previdência"), geo = "BR", time = "2015-01-01 2018-12-26", gprop = c("web"),category = 37)
head(cr_br_prev3$interest_over_time$hits)
</code>```

The answer I get for this simple code is the following:

```<code>> library(gtrendsR)
>
> cr_br_prev1<-gtrends(keyword = c("Previdência"), geo = "BR", time = "2015-01-01 2018-12-26", gprop = c("web"),category = 37)
> head(cr_br_prev1$interest_over_time$hits)
[1]  0  0 24 46 24 24
>
> cr_br_prev2<-gtrends(keyword = c("Previdência"), geo = "BR", time = "2015-01-01 2018-12-26", gprop = c("web"),category = 37)
> head(cr_br_prev2$interest_over_time$hits)
[1]  0  0 24 46 24 24
>
> cr_br_prev3<-gtrends(keyword = c("Previdência"), geo = "BR", time = "2015-01-01 2018-12-26", gprop = c("web"),category = 37)
> head(cr_br_prev3$interest_over_time$hits)
[1]  70  34  51 100  67  35
</code>```

As you can see, the configuration of each search is exactly the same. But the hits series change at the third one (I showing just the first terms with the "head" function, but there is changes at the whole historical series of the "hits"). This is happening kind of randomly for others searchs I'm doing too, even asking for another kind of output, as the "interest_by_region$hits" option.

I searched on Google Trends website how the data is built, and I understand that the historical series of the "hits" could change, once the "hits" reveals the relative popularity or a keyword that is normalized in the range 0-100. But should the structure of the data change as at my example?

Am I losing something?

I aprecciate any help!

Thanks a lot!

答:
I had the same concern like that. Your code literally has no flaw. It seems that Google randomly extracts a subset of the actual search frequencies to calculate index for faster response. However, a famous paper in Finance area (see p.1467 footnote 4 in Da et al.(2011) shows that this problem would be insignificant if you had longer time span.
Honestly, this problem is serious when you only request a short time span. In your case, I still have no solution to it.

Body:
I'm having some trouble using the gtrends r package. I'm using "R Studio Version 1.1.463", running the "R version 3.5.1.".

When I'm searching for a specific keyword, sometimes the historical series of the hits changes a lot. Here is an example:

library(gtrendsR)

cr_br_prev1<-gtrends(keyword = c("Previdência"), geo = "BR", time = "2015-01-01 2018-12-26", gprop = c("web"),category = 37)
head(cr_br_prev1$interest_over_time$hits)

cr_br_prev2<-gtrends(keyword = c("Previdência"), geo = "BR", time = "2015-01-01 2018-12-26", gprop = c("web"),category = 37)
head(cr_br_prev2$interest_over_time$hits)

cr_br_prev3<-gtrends(keyword = c("Previdência"), geo = "BR", time = "2015-01-01 2018-12-26", gprop = c("web"),category = 37)
head(cr_br_prev3$interest_over_time$hits)

The answer I get for this simple code is the following:

> library(gtrendsR)
>
> cr_br_prev1<-gtrends(keyword = c("Previdência"), geo = "BR", time = "2015-01-01 2018-12-26", gprop = c("web"),category = 37)
> head(cr_br_prev1$interest_over_time$hits)
[1]  0  0 24 46 24 24
>
> cr_br_prev2<-gtrends(keyword = c("Previdência"), geo = "BR", time = "2015-01-01 2018-12-26", gprop = c("web"),category = 37)
> head(cr_br_prev2$interest_over_time$hits)
[1]  0  0 24 46 24 24
>
> cr_br_prev3<-gtrends(keyword = c("Previdência"), geo = "BR", time = "2015-01-01 2018-12-26", gprop = c("web"),category = 37)
> head(cr_br_prev3$interest_over_time$hits)
[1]  70  34  51 100  67  35

As you can see, the configuration of each search is exactly the same. But the hits series change at the third one (I showing just the first terms with the "head" function, but there is changes at the whole historical series of the "hits"). This is happening kind of randomly for others searchs I'm doing too, even asking for another kind of output, as the "interest_by_region$hits" option.

I searched on Google Trends website how the data is built, and I understand that the historical series of the "hits" could change, once the "hits" reveals the relative popularity or a keyword that is normalized in the range 0-100. But should the structure of the data change as at my example?

Am I losing something?

I aprecciate any help!

Thanks a lot!


问:
Writing string to specific dir using chaquopy 4.0.0
I am trying a proof of concept here:
Using Chaquopy 4.0.0 (I use python 2.7.15), I am trying to write a string to file in a specific folder (getFilesDir()) using Python, then reading in via Android.

To check whether the file was written, I am checking for the file's length (see code below).

I am expecting to get any length latger than 0 (to verify that the file indeed has been written to the specific location), but I keep getting 0.
Any help would be greatly appreciated!!

main.py:

import os.path
save_path = "/data/user/0/$packageName/files/"
name_of_file = raw_input("test")
completeName = os.path.join(save_path, name_of_file+".txt")
file1 = open(completeName, "w")
toFile = raw_input("testAsWell")
file1.write(toFile)
file1.close()
```

<p>OnCreate:</p>

<pre class="lang-java prettyprint-override"><code>if (! Python.isStarted()) {
    Python.start(new AndroidPlatform(this));
    File file = new File(getFilesDir(), "test.txt");
    Log.e("TEST", String.valueOf(file.length()));
}```
```

答:
It's not clear whether you've based your app on the console example, so I'll give an answer for both cases.

If you have based your app on the console example, then the code in onCreate will run before the code in main.py, and the file won't exist the first time you start the activity. It should exist the second time: if it still doesn't, try using the Android Studio file explorer to see what's in the files directory.

If you haven't based your app on the console example, then you'll need to execute main.py manually, like this:

```<code>Python.getInstance().getModule("main");
</code>```

Also, without the input UI which the console example provides, you won't be able to read anything from stdin. So you'll need to do one of the following:

Base your app on the console example; or

Replace the raw_input calls with a hard-coded file name and content; or

Create a normal Android UI with a text box or something, and get input from the user that way.

Body:
I am trying a proof of concept here:
Using Chaquopy 4.0.0 (I use python 2.7.15), I am trying to write a string to file in a specific folder (getFilesDir()) using Python, then reading in via Android.

To check whether the file was written, I am checking for the file's length (see code below).

I am expecting to get any length latger than 0 (to verify that the file indeed has been written to the specific location), but I keep getting 0.
Any help would be greatly appreciated!!

main.py:

import os.path
save_path = "/data/user/0/$packageName/files/"
name_of_file = raw_input("test")
completeName = os.path.join(save_path, name_of_file+".txt")
file1 = open(completeName, "w")
toFile = raw_input("testAsWell")
file1.write(toFile)
file1.close()

OnCreate:

if (! Python.isStarted()) {
    Python.start(new AndroidPlatform(this));
    File file = new File(getFilesDir(), "test.txt");
    Log.e("TEST", String.valueOf(file.length()));
}```

Body:
It's not clear whether you've based your app on the console example, so I'll give an answer for both cases.

If you have based your app on the console example, then the code in onCreate will run before the code in main.py, and the file won't exist the first time you start the activity. It should exist the second time: if it still doesn't, try using the Android Studio file explorer to see what's in the files directory.

If you haven't based your app on the console example, then you'll need to execute main.py manually, like this:

Python.getInstance().getModule("main");

Also, without the input UI which the console example provides, you won't be able to read anything from stdin. So you'll need to do one of the following:

Base your app on the console example; or

Replace the raw_input calls with a hard-coded file name and content; or

Create a normal Android UI with a text box or something, and get input from the user that way.


问:
Video Conversion (a la youtube)
So we were going to make a website allowing users to upload video. The website is going to be in PHP/MySQL. Are there any converters out there available for PHP to convert a video from a given format to flash to display on the web page to play?

Basically we would have a file on the server in say .avi format, or quicktime format. How do I grab it from the server, convert it to flash and display it on the php page to play?

Also, does can I use the video capabilities of HTML5 with PHP to make any of this easier?

答:
You can use the VideoToolkit php class, that uses ffmpeg and mencoder to convert the videos.
http://www.phpclasses.org/package/3747-PHP-Manipulate-and-convert-videos-with-ffmpeg-program.html</p>

Title: Video Conversion (a la youtube)


问:
Add file from working directory into code
Is there a 'shortcut' way to add a file in the code in pycharm? I have this structure everything is in a folder called 'myFolder' that you  cannot see on the picture.

Using e.g. Visual Code I was able to reference the file like this:

```<code>df = pd.read_csv('in/test_DS.csv', sep=';', encoding='iso-8859-1')
</code>```

is there a similar way in Pycharm or do I have to do full reference?

答: There is currently no such feature, but there is a corresponding feature request https://youtrack.jetbrains.com/issue/PY-33254 which is In Progress and expected to be in 2019.2 version.

Body:
Is there a 'shortcut' way to add a file in the code in pycharm? I have this structure everything is in a folder called 'myFolder' that you  cannot see on the picture.

Using e.g. Visual Code I was able to reference the file like this:

df = pd.read_csv('in/test_DS.csv', sep=';', encoding='iso-8859-1')

is there a similar way in Pycharm or do I have to do full reference?


问:
gcc linker script difference between *(.rodata*) and *(.rodata.*)
We have a linker script where a part of the .text section has the read only data input section specified as:

```<code>.text:
{
    ...
    *(.rodata .rodata* .gnu.linkonce.r.*)
    ...
}
</code>```

However, other input sections that have a trailing wildcard usually have a . between name and wildcard. Like: *(.text .text.* .gnu.linkonce.t.*)

Is there a difference in how the linker treats .'s and wildcard combinations or is there no difference?

Should the .rodata* actually be .rodata.*?

答:
.text* is simply shorter than the more explicit .text .text.*, though not equivalent. It would pick up other sections like .text_foo. This can be intended (to make it more independent of the compiler convention maybe?) or not.

https://sourceware.org/binutils/docs/ld/Input-Section-Wildcards.html

The .* sections are generated by gcc if you pass -ffunction-sections. The same holds for data and -fdata-sections.

Body:
We have a linker script where a part of the .text section has the read only data input section specified as:

.text:
{
    ...
    *(.rodata .rodata* .gnu.linkonce.r.*)
    ...
}

However, other input sections that have a trailing wildcard usually have a . between name and wildcard. Like: *(.text .text.* .gnu.linkonce.t.*)

Is there a difference in how the linker treats .'s and wildcard combinations or is there no difference?

Should the .rodata* actually be .rodata.*?


问:
'java.lang.String' is deprecated in Android
I have write simple TAG like this:

```<code>private static final String TAG = "MainActivity";
</code>```

String is deprecated

Is there any alternative way available to use String?

答:
As per comment in this java-lang-string-is-deprecated-in-android-studio question,

Remove folder .AndroidStudioX.X in your User folder and Restart IDE.

NOTE: AndroidStudioX.X means if you are using Android Studio version
  3.4 then .AndroidStudio3.4 will be there.

Path will be like Windows : C:\Users\<PCNAME>\.AndroidStudio3.4

Linux/Ubuntu : /home/yourname/.AndroidStudio3.4

Hope it will be helpful to you.

Body:
I have write simple TAG like this:

private static final String TAG = "MainActivity";

String is deprecated

Is there any alternative way available to use String?


问:
Can I get value from variable whose value is stored in another variable?
In JDBC PreProcessor I get records from database and assume that one of column is saved to variable "DESCRIPTION"

In BeanShell PreProcessor I do something like this:

```<code>String descriptionFirstResult ="DESCRIPTION_"+number
</code>```

to get specific number of row and then I save this result to vars.

```<code>vars.put("DescriptionFirstResult",descriptionFirstResult);
</code>```

At the end I want to check if value from database is the same as value from response and in Response Assertion I do:

Text Response -> Substring

```<code>"description": "${${DescriptionFirstResult}}"
</code>```

And I get
Assertion failure message: Test failed: text expected to contain /"description": ${${DescriptionFirstResult}}/

Why is it wrong and what should I change to get correct result?

答:
You might have a look at jmeter functions. __V let you evaluate variable names. In your case it could look like this:

```<code>"description": "${__V(${DescriptionFirstResult})}"
</code>```

If the value of ${DescriptionFirstResult} equals "D1" this function would look for a variable D1 and return the value of D1 as the result.

Body:
In JDBC PreProcessor I get records from database and assume that one of column is saved to variable "DESCRIPTION"

In BeanShell PreProcessor I do something like this:

String descriptionFirstResult ="DESCRIPTION_"+number

to get specific number of row and then I save this result to vars.

vars.put("DescriptionFirstResult",descriptionFirstResult);

At the end I want to check if value from database is the same as value from response and in Response Assertion I do:

Text Response -> Substring

"description": "${${DescriptionFirstResult}}"

And I get
Assertion failure message: Test failed: text expected to contain /"description": ${${DescriptionFirstResult}}/

Why is it wrong and what should I change to get correct result?

Body:
You might have a look at jmeter functions. __V let you evaluate variable names. In your case it could look like this:

"description": "${__V(${DescriptionFirstResult})}"

If the value of ${DescriptionFirstResult} equals "D1" this function would look for a variable D1 and return the value of D1 as the result.


问:
Converting conditional subtour elimination of CVRP into normal ones
I am trying to eliminate the if condition constraints from the following CVRP formulation.

I tried some big M methods on paper but failed to come up with a proper reformulation. Can you please help me to find a solution?

Thanks!

答:
You can split the equation into two inequalities and the apply the big-M method:

```<code>ui + qj <= uj + M(1-xij)
ui + qj >= uj - M(1-xij)
</code>```

Models with big-M constants tend to be weak and numerically instable, so I suggest to select the constant as small as possible (i.e. make M depend on ij, if possible). To learn more about that have a look at the Perils of "Big M".

Body:
You can split the equation into two inequalities and the apply the big-M method:

ui + qj <= uj + M(1-xij)
ui + qj >= uj - M(1-xij)

Models with big-M constants tend to be weak and numerically instable, so I suggest to select the constant as small as possible (i.e. make M depend on ij, if possible). To learn more about that have a look at the Perils of "Big M".


问:
aws glue / pyspark - how to create Athena table programmatically using Glue
I am running a script in AwsGlue which loads the data from s3, does some transformation and saves the results to S3. I am trying to add one more step to this routine. I want to create a new table in an existing database in Athena.

I cannot find any similar example in AWS documentation. The results are just written down to S3 in the examples I came across.
Is this possible in Glue?

There is some example of the code. How should it be modified to create the Athena table with the output results?

```<code>import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from awsglue.context import GlueContext
from awsglue.job import Job
from awsglue.dynamicframe import DynamicFrame

from pyspark.sql import SparkSession
from pyspark.context import SparkContext
from pyspark.sql.functions import *
from pyspark.sql import SQLContext
from pyspark.sql.types import *

args = getResolvedOptions(sys.argv, ['JOB_NAME'])
sc = SparkContext()
glueContext = GlueContext(sc)
spark = glueContext.spark_session
job = Job(glueContext)
job.init(args['JOB_NAME'], args)

datasource0 = glueContext.create_dynamic_frame.from_catalog(database = "dataset", table_name = "table_1", transformation_ctx = "datasource0")
applymapping1 = ApplyMapping.apply(frame = datasource0, mappings = [("id", "long", "id", "long"), ("description", "string", "description", "string")], transformation_ctx = "applymapping1")
resolvechoice2 = ResolveChoice.apply(frame = applymapping1, choice = "make_struct", transformation_ctx = "resolvechoice2")
dropnullfields3 = DropNullFields.apply(frame = resolvechoice2, transformation_ctx = "dropnullfields3")
datasink4 = glueContext.write_dynamic_frame.from_options(frame = dropnullfields3, connection_type = "s3", connection_options = {"path": "s3://..."}, format = "parquet", transformation_ctx = "datasink4")

*create Athena table with the output results*

job.commit()
</code>```

答:
I can think of two ways to do this. One is using the sdk to get a reference to the athena API and use it to execute a query with the create table statement, as seen at this blog post

An alternative way which might be more interesting is using the Glue API to create a crawler for your S3 bucket and then execute the crawler.

With the second approach your table is catalogued and you can use it not only from athena, but also from EMR, or Redshift spectrum.

Body:
I am running a script in AwsGlue which loads the data from s3, does some transformation and saves the results to S3. I am trying to add one more step to this routine. I want to create a new table in an existing database in Athena.

I cannot find any similar example in AWS documentation. The results are just written down to S3 in the examples I came across.
Is this possible in Glue?

There is some example of the code. How should it be modified to create the Athena table with the output results?

import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from awsglue.context import GlueContext
from awsglue.job import Job
from awsglue.dynamicframe import DynamicFrame

from pyspark.sql import SparkSession
from pyspark.context import SparkContext
from pyspark.sql.functions import *
from pyspark.sql import SQLContext
from pyspark.sql.types import *

args = getResolvedOptions(sys.argv, ['JOB_NAME'])
sc = SparkContext()
glueContext = GlueContext(sc)
spark = glueContext.spark_session
job = Job(glueContext)
job.init(args['JOB_NAME'], args)

datasource0 = glueContext.create_dynamic_frame.from_catalog(database = "dataset", table_name = "table_1", transformation_ctx = "datasource0")
applymapping1 = ApplyMapping.apply(frame = datasource0, mappings = [("id", "long", "id", "long"), ("description", "string", "description", "string")], transformation_ctx = "applymapping1")
resolvechoice2 = ResolveChoice.apply(frame = applymapping1, choice = "make_struct", transformation_ctx = "resolvechoice2")
dropnullfields3 = DropNullFields.apply(frame = resolvechoice2, transformation_ctx = "dropnullfields3")
datasink4 = glueContext.write_dynamic_frame.from_options(frame = dropnullfields3, connection_type = "s3", connection_options = {"path": "s3://..."}, format = "parquet", transformation_ctx = "datasink4")

*create Athena table with the output results*

job.commit()


问:
select all checkbox be default if the route.path includes /add
In my Vue code, I have a list of check-boxes, so whenever I add a new usergroup, by default all check-boxes should be selected except the disabled one. I have to condition and function code, but not sure where to include the function. Whenever I add a new usergroup, by default all checkbox should be selected.

I have the method, but need to know where and how to call it.

```<code><li><a @click.prevent="selectAll" id="cardSelectAllAId">
    SelectAll</a></li>

  <single-checkbox class="checkbox "
             inputId="card.data.id"
                 v-if="card.data.id"
         @change="change(card.data)"
         :value="card.data.selected"
    :disabled="!card.data.licenseEnabled">

  selectAll() {
   for (let i = 0; i < this.cards.length; i += 1) {
    if (this.cards[i].selected !== undefined) {
     this.cards[i].selected = true;
    }
  },

  default() {
  const currentRoute = this.$route.path;
  for (let i = 0; i < this.features.length; i += 1) {
    if (currentRoute.includes('/admin/users/usergroup/add/')) {
      this.features[i].selected = true;
    } else {
      this.features[i].selected = false;
    }
  }
},
</code>```

I also need a method to not include disabled check box in select all function.

答:
i fixed it the solution is to add v-bind in the checkbox and call the method in computed

```<code>     v-bind:class="{ 'checkbox' : isdefault }".
</code>```

but still i have one bug,
while selecting all , the disabled checkbox is also gets selected , i need to fix that not to include disabled checkbox in the selection.

Body:
In my Vue code, I have a list of check-boxes, so whenever I add a new usergroup, by default all check-boxes should be selected except the disabled one. I have to condition and function code, but not sure where to include the function. Whenever I add a new usergroup, by default all checkbox should be selected.

I have the method, but need to know where and how to call it.

    SelectAll

  <single-checkbox class="checkbox "
             inputId="card.data.id"
                 v-if="card.data.id"
         @change="change(card.data)"
         :value="card.data.selected"
    :disabled="!card.data.licenseEnabled">

  selectAll() {
   for (let i = 0; i < this.cards.length; i += 1) {
    if (this.cards[i].selected !== undefined) {
     this.cards[i].selected = true;
    }
  },

  default() {
  const currentRoute = this.$route.path;
  for (let i = 0; i < this.features.length; i += 1) {
    if (currentRoute.includes('/admin/users/usergroup/add/')) {
      this.features[i].selected = true;
    } else {
      this.features[i].selected = false;
    }
  }
},

I also need a method to not include disabled check box in select all function.

Body:
i fixed it the solution is to add v-bind in the checkbox and call the method in computed

     v-bind:class="{ 'checkbox' : isdefault }".

but still i have one bug,
while selecting all , the disabled checkbox is also gets selected , i need to fix that not to include disabled checkbox in the selection.


问:
ARM bare-metal program compilation -control flash writes
I'm trying to compile some C code to run on an ARMv6 simulator, with FLASH memory starting @ 0x0 and RAM starting at 0x800000. Right now, I can pass binary files off the the simulator just fine...

However, I want the instructions generated to not include any writes to flash memory, and only operate within RAM memory (after copying RAM). Is this possible?

I am using the GNU toolchain to compile.

This is my current linker script:

```<code>MEMORY
{
    rom(rx) : ORIGIN = 0x00000000, LENGTH = 0x00800000
    ram(!rx) : ORIGIN = 0x40000000, LENGTH = 0x00800000
    h : ORIGIN = 0x40000000, LENGTH = 0x00400000
}

SECTIONS
{
    .text : { *(.text*) } > rom
    .bss : { *(.bss*) } > ram
    .heap : { *(.heap*) } > h
}

    end = ORIGIN(h) + LENGTH(h);

_stacktop = ORIGIN(ram) + LENGTH(ram);
</code>```

答:
Your build linker script (normally a .ld file) determines the locations of your device's memory and how the linker sections are mapped to that.   Your link map should not include writable sections in read-only memory, that will fail.

[Added after linker script added to question]

You linker script seems unusual in lacking a .data section:

```<code>.data : { *(.data) } > ram
</code>```

Without that it is not clear what the linker will do with static initialised data.

Also your question states that the RAM starts at 0x800000, but the linker script clearly locates it at 0x40000000.  Perhaps this misunderstanding of your memory map is leading you to erroneously believe that writes to the ROM region are occurring?

Body:
I'm trying to compile some C code to run on an ARMv6 simulator, with FLASH memory starting @ 0x0 and RAM starting at 0x800000. Right now, I can pass binary files off the the simulator just fine...

However, I want the instructions generated to not include any writes to flash memory, and only operate within RAM memory (after copying RAM). Is this possible?

I am using the GNU toolchain to compile.

This is my current linker script:

MEMORY
{
    rom(rx) : ORIGIN = 0x00000000, LENGTH = 0x00800000
    ram(!rx) : ORIGIN = 0x40000000, LENGTH = 0x00800000
    h : ORIGIN = 0x40000000, LENGTH = 0x00400000
}

SECTIONS
{
    .text : { *(.text*) } > rom
    .bss : { *(.bss*) } > ram
    .heap : { *(.heap*) } > h
}

    end = ORIGIN(h) + LENGTH(h);

_stacktop = ORIGIN(ram) + LENGTH(ram);

Body:
Your build linker script (normally a .ld file) determines the locations of your device's memory and how the linker sections are mapped to that.   Your link map should not include writable sections in read-only memory, that will fail.

[Added after linker script added to question]

You linker script seems unusual in lacking a .data section:

.data : { *(.data) } > ram

Without that it is not clear what the linker will do with static initialised data.

Also your question states that the RAM starts at 0x800000, but the linker script clearly locates it at 0x40000000.  Perhaps this misunderstanding of your memory map is leading you to erroneously believe that writes to the ROM region are occurring?


问:
Custom error setting being ignored for locations denied in the web.config
In a ASP.Net 4 and MVC2 application we have an odd configuration error.

The web.config looks something like this:

```<code><configuration>
    <location path="blockedpath">
        <system.web>
            <authorization>
                <deny users="*" />
            </authorization>
        </system.web>
    </location>
    <system.web>
        <customErrors mode="On" defaultRedirect="~/Error.aspx" />
    </system.web>
</configuration>
</code>```

Visiting the blocked location is correctly denied, but gives a verbose error message from IIS that we don't want.

Why doesn't it serve up the configured custom error?

Can we control what page it does serve up when page access is denied by config?

答:
If this is IIS7 then it looks like IIS is hijacking the response. Try this:</p>

```<code><configuration>
  <system.webServer>
    <httpErrors existingResponse="PassThrough" />
  </system.webServer>
</configuration>
</code>```

Body:
In a ASP.Net 4 and MVC2 application we have an odd configuration error.

The web.config looks something like this:

<configuration>
    <location path="blockedpath">
        <system.web>
            <authorization>
                <deny users="*" />
            </authorization>
        </system.web>
    </location>
    <system.web>
        <customErrors mode="On" defaultRedirect="~/Error.aspx" />
    </system.web>
</configuration>

Visiting the blocked location is correctly denied, but gives a verbose error message from IIS that we don't want.

Why doesn't it serve up the configured custom error?

Can we control what page it does serve up when page access is denied by config?

Body:
If this is IIS7 then it looks like IIS is hijacking the response. Try this:

<configuration>
  <system.webServer>
    <httpErrors existingResponse="PassThrough" />
  </system.webServer>
</configuration>


问:
AJAX failed to load server with a status of 500
I have taken an example from the internet of working laravel with ajax. But it gives me the 500 internal server error:

jquery.min.js:4 GET 127.0.0.1:8000/search?search=p 500 (Internal Server Error) send @ jquery.min.js:4 ajax @ jquery.min.js:4 (anonymous) @ (index):39 dispatch @ jquery.min.js:3 r.handle @ jquery.min.js:3

This is the code for controller called SearchController

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SearchController extends Controller
{
    public function index()
    {
        return view('search.search');
    }

    public function search(Request $request)
    {
        if($request->ajax())
        {
            $output="";
            $products=DB::table('products')->where('title','LIKE','%'.$request->search."%")->get();
            if($products)
            {
                foreach ($products as $key => $product) {
                    $output.='<tr>'.
                                '<td>'.$product->id.'</td>'.
                                '<td>'.$product->title.'</td>'.
                                '<td>'.$product->description.'</td>'.
                                '<td>'.$product->price.'</td>'.
                               '</tr>';
                }
                return Response($output);
            }
        }
    }
}
</code>```

Code in web.php

```<code>Route::get('/','SearchController@index');
Route::get('/search','SearchController@search');
</code>```

Code of blade file

```<code><!DOCTYPE html>
<html>
    <head>
        <meta id="token" name="_token" content="{{ csrf_token() }}">
        <title>Live Search</title>
        <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    </head>
    <body>
        <div class="container">
        <div class="row">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3>Products info </h3>
                </div>
                <div class="panel-body">
                    <div class="form-group">
                        <input type="text" class="form-controller" id="search" name="search"></input>
                    </div>
                    <table class="table table-bordered table-hover">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Product Name</th>
                                <th>Description</th>
                                <th>Price</th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        </div>
        <script type="text/javascript">
            $('#search').on('keyup',function(){
                $value=$(this).val();
                $.ajax({
                    type : 'get',
                    url : '{{URL::to('search')}}',
                    data:{'search':$value},
                    success:function(data){
                        $('tbody').html(data);
                    }
                });
            });
        </script>
        <script type="text/javascript">
        $.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });
        </script>
    </body>
</html>
</code>```

It should display the record when the key is pressed but it gives error 500 internal server error

Screenshot with GET method
AJAX ERROR WITH GET

Screenshot with POST method
AJAX ERROR WITH POST

答:
The problem is, There is no DB imported.
So Just write

```<code>use DB;
</code>```

in the controller

Body:
I have taken an example from the internet of working laravel with ajax. But it gives me the 500 internal server error:

jquery.min.js:4 GET 127.0.0.1:8000/search?search=p 500 (Internal Server Error) send @ jquery.min.js:4 ajax @ jquery.min.js:4 (anonymous) @ (index):39 dispatch @ jquery.min.js:3 r.handle @ jquery.min.js:3

This is the code for controller called SearchController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SearchController extends Controller
{
    public function index()
    {
        return view('search.search');
    }

    public function search(Request $request)
    {
        if($request->ajax())
        {
            $output="";
            $products=DB::table('products')->where('title','LIKE','%'.$request->search."%")->get();
            if($products)
            {
                foreach ($products as $key => $product) {
                    $output.='
'.
                                ''.$product->id.'	'.
                                ''.$product->title.'	'.
                                ''.$product->description.'	'.
                                ''.$product->price.'	'.
                               '
';
                }
                return Response($output);
            }
        }
    }
}

Code in web.php

Route::get('/','SearchController@index');
Route::get('/search','SearchController@search');

Code of blade file

<!DOCTYPE html>

        <meta id="token" name="_token" content="{{ csrf_token() }}">
        <title>Live Search</title>
        <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

Products info

                        <input type="text" class="form-controller" id="search" name="search"></input>

                                ID
                                Product Name
                                Description
                                Price

It should display the record when the key is pressed but it gives error 500 internal server error

Screenshot with GET method
AJAX ERROR WITH GET

Screenshot with POST method
AJAX ERROR WITH POST

Body:
The problem is, There is no DB imported.
So Just write

use DB;

in the controller


问:
How to use the Knex CLI
I have installed Knex in my Node project and all is wonderful and great... so far...

Now I dig deeper into Knex and am confronted with migrations.  All the docs I found talk about running commands like "knex migrate:latest", etc.  What I get as a result when I try to run such commands from the (Windows) command line is an error telling me that 'knex' is an unknown command.

I am not a npm and Nodes expert, just enough to get the basics running.  When digging into the knex node package I find some configuration for a cli.js file under a 'bin' section in the 'package.json'.  I do not understand these configurations, even reading the npm documentation about this 'bin' section does not make it clearer to me.

So here my question:
I am on Windows 10 and have installed a package like 'knex' local to my project.  Knex comes with a cli.  What do I need to do to call that cli from my console?

答: First type in "npx knex" to access options and commands available to the knex module. To be able to make use of the Knex cli that comes bundled with it, you then have to access the knex module from whatever path you intend creating the file from. For example, let's say I was in the migrations directory and the node_modules folder is one path higher, I would access the Knex module in it this way '../node_modules/.bin/knex migrate:make create-user-table.js' to be able to create a 'create-user-table.js', migration file. I hope I'm clear enough.</p>

Title: How to use the Knex CLI


问:
How to use array filter criteria agaist object in lodash?
How to filter object ageist another object in lodash? but the criteria object is array..

```<code>var form = { type: ['xyz', 'abc'], name: 'pre-1' }

var items = [
 { type: 'xyz', name: 'pre-1' },
 { type: 'abc', name: 'pre-1' },
 { type: 'xyz', name: 'pre-2' },
]

const results = lodash.filter(items, form);
</code>```

The results should be xyz and abc:

```<code>results = [{ type: 'xyz', name: 'pre-1' }, { type: 'abc', name: 'pre-1' }]
</code>```

Is it something I can do using filter method?

答:
Check if form.name === item.name, and if so use Array.includes() to check if the item.type appears in form.type.

Note: I've used the vanilla JS filter and includes methods, but you can substitute them with lodash's _.filter() and _.includes().

const form = { type: ['xyz', 'abc'], name: 'pre-1' }

const items = [{"type":"xyz","name":"pre-1"},{"type":"abc","name":"pre-1"},{"type":"xyz","name":"pre-2"}]

const result = items.filter(item =>
  form.name === item.name && form.type.includes(item.type)
)

console.log(result)```
</div>
</div>
</p>

<p>Another option with lodash is to use <code>_.intersectionWith()</code>, and in the comperator function check if the item's name is identical to the form's name, and the type exists in the types.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const form = { type: ['xyz', 'abc'], name: 'pre-1' }

const items = [{"type":"xyz","name":"pre-1"},{"type":"abc","name":"pre-1"},{"type":"xyz","name":"pre-2"}]

const result = _.intersectionWith(items, form.type, (item, type) =>
  form.name === item.name && item.type === type
)

console.log(result)</code>```

```

Body:
How to filter object ageist another object in lodash? but the criteria object is array..

var form = { type: ['xyz', 'abc'], name: 'pre-1' }

var items = [
 { type: 'xyz', name: 'pre-1' },
 { type: 'abc', name: 'pre-1' },
 { type: 'xyz', name: 'pre-2' },
]

const results = lodash.filter(items, form);

The results should be xyz and abc:

results = [{ type: 'xyz', name: 'pre-1' }, { type: 'abc', name: 'pre-1' }]

Is it something I can do using filter method?

Body:
Check if form.name === item.name, and if so use Array.includes() to check if the item.type appears in form.type.

Note: I've used the vanilla JS filter and includes methods, but you can substitute them with lodash's _.filter() and _.includes().

const form = { type: ['xyz', 'abc'], name: 'pre-1' }

const items = [{"type":"xyz","name":"pre-1"},{"type":"abc","name":"pre-1"},{"type":"xyz","name":"pre-2"}]

const result = items.filter(item =>
  form.name === item.name && form.type.includes(item.type)
)

console.log(result)

Another option with lodash is to use _.intersectionWith(), and in the comperator function check if the item's name is identical to the form's name, and the type exists in the types.

const form = { type: ['xyz', 'abc'], name: 'pre-1' }

const items = [{"type":"xyz","name":"pre-1"},{"type":"abc","name":"pre-1"},{"type":"xyz","name":"pre-2"}]

const result = _.intersectionWith(items, form.type, (item, type) =>
  form.name === item.name && item.type === type
)

console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>


问:
Generate a custom log with dynamic variables in Tsung
I am using tsung 1.7 and in my configuration I am sending a series of HTTP requests to a server which responds with a json of the format

```<code>Recv:1559218599.939782:<0.9056.0>:HTTP/1.1 200 OK
content-type: application/json; charset=utf-8
content-length: 103
date: Thu, 30 May 2019 12:16:39 GMT

{"jsonrpc":"2.0","result":"0xc157d5234e32b0caba423b26278d724ba084ab20068d29cc02185e921f8b8035","id":1}
</code>```

I need to log to an external file just the timestamp at the first line and the content of the json key "result".

I know with dynamic variables is possible to access information from the server response. Do you know if is possible to log such information on a file?

答:
If you know erlang, you can write erlang function which writes the dynamic variables into the file and call the function in tsung.

When a substitution is requested, the substitution mark-up is replaced by the result of the call to the Erlang function: Module:Function({Pid, DynData}) where Pid is the Erlang process id of the current virtual user and DynData the list of all Dynamic variables (Warn: before version 1.1.0, the argument was just the Pid!).

Body:
I am using tsung 1.7 and in my configuration I am sending a series of HTTP requests to a server which responds with a json of the format

Recv:1559218599.939782:<0.9056.0>:HTTP/1.1 200 OK
content-type: application/json; charset=utf-8
content-length: 103
date: Thu, 30 May 2019 12:16:39 GMT

{"jsonrpc":"2.0","result":"0xc157d5234e32b0caba423b26278d724ba084ab20068d29cc02185e921f8b8035","id":1}

I need to log to an external file just the timestamp at the first line and the content of the json key "result".

I know with dynamic variables is possible to access information from the server response. Do you know if is possible to log such information on a file?


问:
What is CvBlobTrackerAuto class in OpenCV?
I am trying to understand blobtrack.cpp code provided as a sample code with OpenCV. In this code class named CvBlobTrackerAuto is used. I tried to find some documentation about this class but it does not provide a detailed explanation.

I am particularly interested in

CvBlobTrackerAuto::Process(IplImage *pImg, IplImage *pMask = NULL) function. What does this do and what is the task of this mask used here?

Thank you in advance

答:
I've been working with CvBlobTrackerAuto in the last few weeks. Here are some of things I have figured out.

CvBlobTrackerAuto::Process is used to process the last captured image in order to update the tracking information (blob ids and positions). Actually, CvBlobTrackerAuto is an abstract class since it doesn't provide an implementation for CvBlobTrackerAuto::Process. The only concrete implementation there is (as far as I can tell) is CvBlobTrackerAuto1, which can be found in blobtrackingauto.cpp.

What CvBlobTrackerAuto1::Process does is to implement the following pipeline:

Foreground detection: this produces a binary mask corresponding to the foreground.

Blob tracking: updates the position of blobs. It may use mean shift, particle filters or a combination of these.

Post processing: (I'm not sure of what this section does).

Blob deletion: it is "experimental and simple" according to a comment in there. It deletes blobs which have been too small or near the image borders in the last frames.

Blob detection: detects new blobs. See enteringblobdetection.cpp.

Trajectory generation: (not sure of what it does).

Track analysis: (not sure of what it does. But I do remember having read the code and deciding that it had no influence on blob tracking, so I disabled it.)

In this particular implementation of CvBlobTrackerAuto::Process, the pMask parameter is used for nothing at all. It has a default value of NULL and it is assigned to a variable once, only to be overwritten some lines later.

The OpenCv sample to be found in samples/c/blobtrack_sample.cpp is built around this CvBlobTrackerAuto1 class, providing different options to each module in the pipeline.

I hope it helps.