问:
Error syntax near keyword 'primary' while creating table
Could you help in this error while creating table as below in SQL Server please?

```<code>create table employees (
    employeeid int identity(1,1) not null,
    name varchar(150) null,

    constraint pk_employees
         primary key clustered (employeeid asc)
                     with (statistics_norecompute = off, ignore_dup_key = off) on primary
) on primary
</code>```

I get this error:

Msg 156, Level 15, State 1, Line 2448

  Incorrect syntax near the keyword 'primary'

答:
Thats works:

create table employees (
                           employeeid int identity(1,1) not null,
                           name varchar(150) null,

                           constraint pk_employees
                               primary key clustered (employeeid asc)
                                   with (statistics_norecompute = off, ignore_dup_key = off) on [primary]
) on [primary]
```

primary is the keyword. You try to specify the name of a file group, and it must be surrounded by quotes.

Body:
Could you help in this error while creating table as below in SQL Server please?

create table employees (
    employeeid int identity(1,1) not null,
    name varchar(150) null,

    constraint pk_employees
         primary key clustered (employeeid asc)
                     with (statistics_norecompute = off, ignore_dup_key = off) on primary
) on primary

I get this error:

Msg 156, Level 15, State 1, Line 2448

  Incorrect syntax near the keyword 'primary'

Body:
Thats works:

create table employees (
                           employeeid int identity(1,1) not null,
                           name varchar(150) null,

                           constraint pk_employees
                               primary key clustered (employeeid asc)
                                   with (statistics_norecompute = off, ignore_dup_key = off) on [primary]
) on [primary]

primary is the keyword. You try to specify the name of a file group, and it must be surrounded by quotes.


来源: stackexchange

问:
How can I call the attach / detach events with a named function?
I have a function which needs to attach and detach a handler to the event "requestCompleted" of the OData model to get the URL from the header in order to download the data as an Excel file.

onClickAction: function (oEvent) {
    var model = this.getView().getModel();
    model.attachRequestCompleted(this.downloadODataAsExcel);
    var btnGo = this.getView().byId("btn");
    btnGo.firePress();
    model.detachRequestCompleted(this.downloadODataAsExcel, this);
},

downloadODataAsExcel: function (evt) {
    var url;
    url = evt.getParameters() && evt.getParameters().url;
    url = "/sap/opu/odata/sap/ZService/" + url + "&$format=xlsx";
    sap.m.URLHelper.redirect(url, true);
},
```

<p>I am trying to detach the event afterwards to prevent snowballing of the event which causes the file to download <strong>n+1</strong> times each time you click the download button.</p>

<hr>

<p><strong>Update:</strong> this is the code I ended up with</p>

<pre class="lang-js prettyprint-override"><code>onClickAction: function (oEvent) {
    var model = this.getView().getModel();
    model.attachRequestCompleted(this.downloadOdataAsExcel, this);
    var btnGo = this.getView().byId("btn");
    btnGo.firePress();
},

downloadODataAsExcel: function (evt) {
    var url;
    url = evt.getParameters() && evt.getParameters().url;
    url = "/sap/opu/odata/sap/Z_SERVICE/" + url + "&$format=xlsx";
    sap.m.URLHelper.redirect(url, true);
    var model = this.getView().getModel();
    model.detachRequestCompleted(this.downloadODataAsExcel, this);
}
</code>```

The detach needs to be within the function otherwise the listener will be detached before the requestCompleted event fires.

答:
Event handlers can be attached and detached by passing the same list of arguments to the methods. For example:

myModel.attachRequesCompleted(this.onRequestCompleted/*NO .bind*/, this); // Pass the oListener (this) as an argument instead
```
<pre class="lang-js prettyprint-override"><code>myModel.detachRequestCompleted(this.onRequestCompleted/*NO .bind*/, this); // Same list of arguments
</code>```

By "same list of arguments", I mean:

Do not pass an anonymous function directly as the event handler. It's impossible to reference it later when trying to detach it.

Do not pass the function directly using .bind because .bind creates a new function which, again, makes detaching it impossible.

Pass the same oListener reference. From the API description:

The passed function and listener object must match the ones used for event registration. (Source)

The same applies also for all attach* / detach* methods generated by the ManagedObject.

In your case, the handler couldn't be detached because the listener object, when attaching the handler, was undefined instead of this.

Alternatively, attachEventOnce can be also used.

```<code>myModel.attachEventOnce("requestCompleted", this.onRequestCompleted, this);
</code>```

Once the handler is called, it's detached automatically.

ContentLicense: CC BY-SA 4.0

Body:
I have a function which needs to attach and detach a handler to the event "requestCompleted" of the OData model to get the URL from the header in order to download the data as an Excel file.

onClickAction: function (oEvent) {
    var model = this.getView().getModel();
    model.attachRequestCompleted(this.downloadODataAsExcel);
    var btnGo = this.getView().byId("btn");
    btnGo.firePress();
    model.detachRequestCompleted(this.downloadODataAsExcel, this);
},

downloadODataAsExcel: function (evt) {
    var url;
    url = evt.getParameters() && evt.getParameters().url;
    url = "/sap/opu/odata/sap/ZService/" + url + "&$format=xlsx";
    sap.m.URLHelper.redirect(url, true);
},

I am trying to detach the event afterwards to prevent snowballing of the event which causes the file to download n+1 times each time you click the download button.

Update: this is the code I ended up with

onClickAction: function (oEvent) {
    var model = this.getView().getModel();
    model.attachRequestCompleted(this.downloadOdataAsExcel, this);
    var btnGo = this.getView().byId("btn");
    btnGo.firePress();
},

downloadODataAsExcel: function (evt) {
    var url;
    url = evt.getParameters() && evt.getParameters().url;
    url = "/sap/opu/odata/sap/Z_SERVICE/" + url + "&$format=xlsx";
    sap.m.URLHelper.redirect(url, true);
    var model = this.getView().getModel();
    model.detachRequestCompleted(this.downloadODataAsExcel, this);
}

The detach needs to be within the function otherwise the listener will be detached before the requestCompleted event fires.

Body:
Event handlers can be attached and detached by passing the same list of arguments to the methods. For example:

myModel.attachRequesCompleted(this.onRequestCompleted/*NO .bind*/, this); // Pass the oListener (this) as an argument instead

myModel.detachRequestCompleted(this.onRequestCompleted/*NO .bind*/, this); // Same list of arguments

By "same list of arguments", I mean:

Do not pass an anonymous function directly as the event handler. It's impossible to reference it later when trying to detach it.

Do not pass the function directly using .bind because .bind creates a new function which, again, makes detaching it impossible.

Pass the same oListener reference. From the API description:

The passed function and listener object must match the ones used for event registration. (Source)

The same applies also for all attach* / detach* methods generated by the ManagedObject.

In your case, the handler couldn't be detached because the listener object, when attaching the handler, was undefined instead of this.

Alternatively, attachEventOnce can be also used.

myModel.attachEventOnce("requestCompleted", this.onRequestCompleted, this);

Once the handler is called, it's detached automatically.


问:
Bootstrap 4 webjar css not working with Spring Boot + Thymeleaf
I am making a Spring Boot web app using Thymeleaf. I have been experimenting with Webjars to use things like JQuery and Bootstrap on my web page. Using Spring Boot 2.2.6.RELEASE, and attempting to use Bootstrap Webjar version 4.1.1-1.

I have several different webjars in my pom, but I realized that none of the css files are loading. The Javascript files from the webjars are loading fine, but none of the css is being applied. When looking in the web developer debugger tool, I can see the Javascript files are all there, but none of the css files are present.

Currently, I am specifically trying to get Bootstrap tabs to work, but obviously, without any of the Bootstrap styles, none of the Bootstrap features will work.

This is basically what my controller looks like:

```<code>import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class MyController {

  @RequestMapping(value = "/stats", method = {RequestMethod.GET, RequestMethod.POST})
  public String stats(
      Model model) {

    // some code adding simple attributes to the model

    return "stats";
  }
}
</code>```

I have this web configuration class:

```<code>import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry
        .addResourceHandler("/webjars/**")
        .addResourceLocations("classpath:/META-INF/resources/webjars/")
        .resourceChain(false);
  }
}
</code>```

A sample of my pom:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.6.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>

  <!-- artifact info... -->

  <properties>
    <java.version>1.8</java.version>
  </properties>

  <dependencies>

    <!-- some other dependencies -->

    <!-- Webjars -->
    <dependency>
      <groupId>org.webjars</groupId>
      <artifactId>bootstrap</artifactId>
      <version>4.4.1-1</version>
    </dependency>

    <dependency>
      <groupId>org.webjars</groupId>
      <artifactId>bootstrap-datepicker</artifactId>
      <version>1.7.1</version>
    </dependency>

    <dependency>
      <groupId>org.webjars</groupId>
      <artifactId>jquery</artifactId>
      <version>3.5.0</version>
    </dependency>

    <dependency>
      <groupId>org.webjars.npm</groupId>
      <artifactId>popper.js</artifactId>
      <version>1.16.1</version>
    </dependency>

    <dependency>
      <groupId>org.webjars</groupId>
      <artifactId>font-awesome</artifactId>
      <version>5.13.0</version>
    </dependency>

    <dependency>
      <groupId>org.webjars</groupId>
      <artifactId>webjars-locator</artifactId>
      <version>0.40</version>
    </dependency>

    <!-- Spring -->

    <!-- some other Spring deps... -->

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-configuration-processor</artifactId>
      <optional>true</optional>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>
</code>```

Here is a sample of my html page (stats.html):

```<code><!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8"/>
  <title>My Web App</title>

  <link th:rel="stylesheet" th:href="@{webjars/bootstrap/css/bootstrap.min.css}" type="text.css"/>
  <!--<link th:rel="stylesheet" th:href="@{webjars/bootstrap-datepicker/css/bootstrap-datepicker.min.css}" type="text/css"/>-->
  <link th:rel="stylesheet" th:href="@{webjars/bootstrap-datepicker/css/bootstrap-datepicker.standalone.css}" type="text/css"/>
  <link th:rel="stylesheet" th:href="@{webjars/font-awesome/css/all.css} " type="text/css"/>
  <link href="../static/css/custom-styles.css" rel="stylesheet" type="text/css"/>
</head>
<body>
  <script th:src="@{webjars/jquery/jquery.min.js}" type="text/javascript"></script>
  <script th:src="@{webjars/popper.js/1.14.3/umd/popper.min.js}" type="text/javascript"></script>
  <script th:src="@{webjars/bootstrap/js/bootstrap.min.js}" type="text/javascript"></script>
  <script th:src="@{webjars/bootstrap-datepicker/js/bootstrap-datepicker.min.js}" type="text/javascript"></script>

  <!-- Other simple web content... -->

  <!-- Example straight from Bootstrap 4 documentation https://getbootstrap.com/docs/4.4/components/navs/#tabs -->
  <ul class="nav nav-tabs" id="myTab" role="tablist">
    <li class="nav-item">
      <a class="nav-link active" id="home-tab" data-toggle="tab" href="#home" role="tab" aria-controls="home" aria-selected="true">Home</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" id="profile-tab" data-toggle="tab" href="#profile" role="tab" aria-controls="profile" aria-selected="false">Profile</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" id="contact-tab" data-toggle="tab" href="#contact" role="tab" aria-controls="contact" aria-selected="false">Contact</a>
    </li>
  </ul>

  <div class="tab-content" id="myTabContent">
    <div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab">...</div>
    <div class="tab-pane fade" id="profile" role="tabpanel" aria-labelledby="profile-tab">...</div>
    <div class="tab-pane fade" id="contact" role="tabpanel" aria-labelledby="contact-tab">...</div>
  </div>

</body>
</code>```

The tab titles (or nav-items) just get displayed as a normal unordered list, with all the actual tabs' contents being displayed all together below that.

As I said, as far as I can tell, the script files are getting loaded properly. I have a Bootstrap datepicker set up and working on the same page, but without the Bootstrap styles. I need to use the bootstrap-datepicker.standalone.css file, because bootstrap-datepicker.min.css doesn't work.

Things I have tried that did not work:

Deleting the WebConfig class

Moving the css links into the body of the HTML document

Putting a '/' in front of the @{webjars/...} in the link tags. That does technically work for the Javascript stuff, but it made no difference with the css links. Furthermore, I need to leave the leading '/' off so the app will use page relative links, or else the app doesn't work when deployed to our staging environment

Specifying the version inside the th:href like so: @{/webjars/bootstrap/4.1.1-1/css/bootstrap.min.css}

Taking other things out of the main HTML page until it's pretty much only testing the Bootstrap tabs (i.e. only importing the Bootstrap css and the Javascript files)

Removing the th: from the link element

The one thing I've done that does work is using the BootstrapCDN as seen on https://getbootstrap.com/ : <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

If I use that instead of the link I actually have in the HTML above, the styles are applied and everything works (as far as I can tell). However, I would like to know why I can't get the webjar to work, and if anyone else has had this problem. Or perhaps I am doing something obviously wrong which I am too close to see?

答:
Just had the same (or very similar) problem using Bootstrap 4.5.0 The below worked for me:

In pom I have:

```<code><dependency>
    <groupId>org.webjars</groupId>
    <artifactId>webjars-locator</artifactId>
    <version>0.40</version>
</dependency>
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>bootstrap</artifactId>
    <version>4.5.0</version>
</dependency>
</code>```

I do not have the @Configuration class - it actually started working when I removed it.

My html starts with:

```<code><!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" th:href="@{/webjars/bootstrap/css/bootstrap.min.css}" type="text/css"/>
    <script th:src="@{/webjars/bootstrap/js/bootstrap.min.js}"></script>
    <script th:src="@{/webjars/jquery/jquery.min.js}"></script>
</head>
</code>```

Hope this helps.

EDIT: Just had a look at your code again. You have type="text.css" instead of type="text/css"

B.

Body:
I am making a Spring Boot web app using Thymeleaf. I have been experimenting with Webjars to use things like JQuery and Bootstrap on my web page. Using Spring Boot 2.2.6.RELEASE, and attempting to use Bootstrap Webjar version 4.1.1-1.

I have several different webjars in my pom, but I realized that none of the css files are loading. The Javascript files from the webjars are loading fine, but none of the css is being applied. When looking in the web developer debugger tool, I can see the Javascript files are all there, but none of the css files are present.

Currently, I am specifically trying to get Bootstrap tabs to work, but obviously, without any of the Bootstrap styles, none of the Bootstrap features will work.

This is basically what my controller looks like:

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class MyController {

  @RequestMapping(value = "/stats", method = {RequestMethod.GET, RequestMethod.POST})
  public String stats(
      Model model) {

    // some code adding simple attributes to the model

    return "stats";
  }
}

I have this web configuration class:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry
        .addResourceHandler("/webjars/**")
        .addResourceLocations("classpath:/META-INF/resources/webjars/")
        .resourceChain(false);
  }
}

A sample of my pom:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.6.RELEASE</version>
    <relativePath/>
  </parent>

  <properties>
    <java.version>1.8</java.version>
  </properties>

  <dependencies>

    <dependency>
      <groupId>org.webjars</groupId>
      <artifactId>bootstrap</artifactId>
      <version>4.4.1-1</version>
    </dependency>

    <dependency>
      <groupId>org.webjars</groupId>
      <artifactId>bootstrap-datepicker</artifactId>
      <version>1.7.1</version>
    </dependency>

    <dependency>
      <groupId>org.webjars</groupId>
      <artifactId>jquery</artifactId>
      <version>3.5.0</version>
    </dependency>

    <dependency>
      <groupId>org.webjars.npm</groupId>
      <artifactId>popper.js</artifactId>
      <version>1.16.1</version>
    </dependency>

    <dependency>
      <groupId>org.webjars</groupId>
      <artifactId>font-awesome</artifactId>
      <version>5.13.0</version>
    </dependency>

    <dependency>
      <groupId>org.webjars</groupId>
      <artifactId>webjars-locator</artifactId>
      <version>0.40</version>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-configuration-processor</artifactId>
      <optional>true</optional>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>

Here is a sample of my html page (stats.html):

<!DOCTYPE html>

  <meta charset="UTF-8"/>
  <title>My Web App</title>

  <link th:rel="stylesheet" th:href="@{webjars/bootstrap/css/bootstrap.min.css}" type="text.css"/>

  <link th:rel="stylesheet" th:href="@{webjars/bootstrap-datepicker/css/bootstrap-datepicker.standalone.css}" type="text/css"/>
  <link th:rel="stylesheet" th:href="@{webjars/font-awesome/css/all.css} " type="text/css"/>
  <link href="../static/css/custom-styles.css" rel="stylesheet" type="text/css"/>

      Home

      Profile

      Contact

...

...

...

The tab titles (or nav-items) just get displayed as a normal unordered list, with all the actual tabs' contents being displayed all together below that.

As I said, as far as I can tell, the script files are getting loaded properly. I have a Bootstrap datepicker set up and working on the same page, but without the Bootstrap styles. I need to use the bootstrap-datepicker.standalone.css file, because bootstrap-datepicker.min.css doesn't work.

Things I have tried that did not work:

Deleting the WebConfig class

Moving the css links into the body of the HTML document

Putting a '/' in front of the @{webjars/...} in the link tags. That does technically work for the Javascript stuff, but it made no difference with the css links. Furthermore, I need to leave the leading '/' off so the app will use page relative links, or else the app doesn't work when deployed to our staging environment

Specifying the version inside the th:href like so: @{/webjars/bootstrap/4.1.1-1/css/bootstrap.min.css}

Taking other things out of the main HTML page until it's pretty much only testing the Bootstrap tabs (i.e. only importing the Bootstrap css and the Javascript files)

Removing the th: from the link element

The one thing I've done that does work is using the BootstrapCDN as seen on https://getbootstrap.com/ : <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

If I use that instead of the link I actually have in the HTML above, the styles are applied and everything works (as far as I can tell). However, I would like to know why I can't get the webjar to work, and if anyone else has had this problem. Or perhaps I am doing something obviously wrong which I am too close to see?

Body:
Just had the same (or very similar) problem using Bootstrap 4.5.0 The below worked for me:

In pom I have:

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>webjars-locator</artifactId>
    <version>0.40</version>
</dependency>
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>bootstrap</artifactId>
    <version>4.5.0</version>
</dependency>

I do not have the @Configuration class - it actually started working when I removed it.

My html starts with:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" th:href="@{/webjars/bootstrap/css/bootstrap.min.css}" type="text/css"/>
    <script th:src="@{/webjars/bootstrap/js/bootstrap.min.js}"></script>
    <script th:src="@{/webjars/jquery/jquery.min.js}"></script>
</head>

Hope this helps.

EDIT: Just had a look at your code again. You have type="text.css" instead of type="text/css"

B.


问:
How to extract attached credentials from a url?
In a URL like this:
'https://usertest:userpass@localhost:8080/mypath'. How do I extract the information such as username and password in python? For eg. the information I want to extract from the above URL would be usertest and userpass. I could extract these attached web credentials such as username and password using regex, but that seems to be a bit complicated and I am hoping if there is already a built-in solution for this. Any suggestion?

答:
```<code>from urllib.parse import urlparse

url = 'https://usertest:userpass@localhost:8080/mypath'
parsed = urlparse(url)
print(parsed.username)
print(parsed.password)
</code>```

Check the standard library

Body:
from urllib.parse import urlparse

url = 'https://usertest:userpass@localhost:8080/mypath'
parsed = urlparse(url)
print(parsed.username)
print(parsed.password)

Check the standard library


问:
Can I work multiple angular versions in my computer?
I have installed Angular 7.2.0 globally on my Windows machine. Path is C:\Users\me\AppData\Roaming\npm\node_modules\@angular\cli, and I need to run older projects like Angular 6.0.0. So do I need to install both of versions on my machine in order to run the project?

答:
npx way is good. In case if you don't have npx then you can direct use ng from node_modules like below

node_modules/@angular/cli/bin/ng serve
```


问:
SqlCommand.ExecuteScalar - specify a particular data item
I have a Stored Procedure which returns 10 columns of data. Using cmd.ExecuteScalar() returns the value of the 1st column from the 1st record.

How can I change this so that I can return different columns, by specifying their alias/dataitem name?

I want to be able to do something like:

```<code>Dim FirstName as String = cmd.ExecuteScalar("FirstName")
</code>```

答:
You should try the below code also.</p>

```<code>Private Sub YourFunctionName()
        Using con As System.Data.SqlClient.SqlConnection = New SqlConnection("YourConnection string")
            con.Open()
            Using cmd As SqlCommand = New SqlCommand
                Dim expression As String = "Parameter value"
                cmd.CommandType = CommandType.StoredProcedure
                cmd.CommandText = "Your Stored Procedure"
                cmd.Parameters.Add("Your Parameter Name", SqlDbType.VarChar).Value = expression
                cmd.Connection = con
                Using dr As IDataReader = cmd.ExecuteReader()
                    If dr.Read() Then
                        Dim str As String = dr("YourColumnName").ToString()
                    End If
                End Using
            End Using
        End Using
    End Sub
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a Stored Procedure which returns 10 columns of data. Using cmd.ExecuteScalar() returns the value of the 1st column from the 1st record.

How can I change this so that I can return different columns, by specifying their alias/dataitem name?

I want to be able to do something like:

Dim FirstName as String = cmd.ExecuteScalar("FirstName")

Body:
You should try the below code also.

Private Sub YourFunctionName()
        Using con As System.Data.SqlClient.SqlConnection = New SqlConnection("YourConnection string")
            con.Open()
            Using cmd As SqlCommand = New SqlCommand
                Dim expression As String = "Parameter value"
                cmd.CommandType = CommandType.StoredProcedure
                cmd.CommandText = "Your Stored Procedure"
                cmd.Parameters.Add("Your Parameter Name", SqlDbType.VarChar).Value = expression
                cmd.Connection = con
                Using dr As IDataReader = cmd.ExecuteReader()
                    If dr.Read() Then
                        Dim str As String = dr("YourColumnName").ToString()
                    End If
                End Using
            End Using
        End Using
    End Sub


问:
SQLite & INNER JOIN Query
Hi everyone I have this query where there are 3 tables in join. In Access it works, but in SQLite it gives me an error, how can I "adapt" the SQL command? thanks</p>

```<code>UPDATE (
    CategoriaTB
    INNER JOIN MagazzinoTB ON CategoriaTB.IDCategoria =
MagazzinoTB.IDCategoria
) INNER JOIN PersoneTB ON MagazzinoTB.IDPersone =
PersoneTB.IDPersone
SET MagazzinoTB.DataReso = "aaa"
WHERE ((
    (PersoneTB.CodicePer)="F")
    AND ((MagazzinoTB.Stato)=0)
    AND ((MagazzinoTB.DataVendita) Is Null)
)
</code>```

答:
Please use below query,</p>

```<code>UPDATE MagazzinoTB set DataReso = 'aaa' WHERE (IDCategoria, IDPersone)
IN (SELECT CategoriaTB.IDCategoria, PersoneTB.IDPersone FROM CategoriaTB
INNER JOIN MagazzinoTB ON
CategoriaTB.IDCategoria = MagazzinoTB.IDCategoria
INNER JOIN PersoneTB
ON MagazzinoTB.IDPersone = PersoneTB.IDPersone
WHERE (((PersoneTB.CodicePer)="F") AND ((MagazzinoTB.Stato)=0) AND
((MagazzinoTB.DataVendita) Is Null)));
</code>```

Title: SQLite & INNER JOIN Query

Body:
Hi everyone I have this query where there are 3 tables in join. In Access it works, but in SQLite it gives me an error, how can I "adapt" the SQL command? thanks

UPDATE (
    CategoriaTB
    INNER JOIN MagazzinoTB ON CategoriaTB.IDCategoria =
MagazzinoTB.IDCategoria
) INNER JOIN PersoneTB ON MagazzinoTB.IDPersone =
PersoneTB.IDPersone
SET MagazzinoTB.DataReso = "aaa"
WHERE ((
    (PersoneTB.CodicePer)="F")
    AND ((MagazzinoTB.Stato)=0)
    AND ((MagazzinoTB.DataVendita) Is Null)
)

Body:
Please use below query,

UPDATE MagazzinoTB set DataReso = 'aaa' WHERE (IDCategoria, IDPersone)
IN (SELECT CategoriaTB.IDCategoria, PersoneTB.IDPersone FROM CategoriaTB
INNER JOIN MagazzinoTB ON
CategoriaTB.IDCategoria = MagazzinoTB.IDCategoria
INNER JOIN PersoneTB
ON MagazzinoTB.IDPersone = PersoneTB.IDPersone
WHERE (((PersoneTB.CodicePer)="F") AND ((MagazzinoTB.Stato)=0) AND
((MagazzinoTB.DataVendita) Is Null)));


问:
Ant design Button shape and color are not applied
I installed ant design with npm

```<code>npm i --save antd
</code>```

Then I used Button from their components like  this

```<code>import { Button } from 'antd';
</code>```

```<code><Button type="primary" shape="circle">
                    hey
                </Button>
</code>```

The problem is that the button shape and type doesn't apply properly .
How can I fix this issue ?

答:
In your entry point (where you have the ReactDOM.render()) add at the top of the file the following:

import 'antd/dist/antd.css';
```

<p>Or if you're using <code>create-react-app</code>, in your <code>src/App.css</code>:</p>

<pre class="lang-css prettyprint-override"><code>@import '~antd/dist/antd.css';
</code>```

That will provide you the styling you need. Hope it helps!

Getting Started with Antd - Official Docs
Usage with Create React App - Official Docs

Body:
I installed ant design with npm

npm i --save antd

Then I used Button from their components like  this

import { Button } from 'antd';

<Button type="primary" shape="circle">
                    hey
                </Button>

The problem is that the button shape and type doesn't apply properly .
How can I fix this issue ?

Body:
In your entry point (where you have the ReactDOM.render()) add at the top of the file the following:

import 'antd/dist/antd.css';

Or if you're using create-react-app, in your src/App.css:

@import '~antd/dist/antd.css';

That will provide you the styling you need. Hope it helps!

Getting Started with Antd - Official Docs
Usage with Create React App - Official Docs


问:
jQuery ajax handling of 204 No Content
I am writing an jQuery ajax call to a RESTful server, for which the response to a valid PUT request is an HTTP 204 No Content. The response has a Content Type header of application/text but there is no content body. Because of this, it appears that the ajax call threats this as an error, and so the error function is called instead of done.

Is there a way to override this behaviour, and execute done for a 204 response regardless of the content body?

答:
Best way would be to make a call for statusCode in ajax. And make a runner code in specific statusCode.

```<code>new Promise((resolve, reject) => {
    var settings = {
            "URL": "<your link>",
            "method": "POST",
            "timeout": 0,
            "headers": {
            "Content-Type": "application/json"
            },
        "data": JSON.stringify({
            "email": email,
            "user_name": user_name,
        }),
        "statusCode": {
            200: function (data) {
                console.log("Request completed 200");
                resolve(data || {statusCode: 200});
            },
            201: function (data) {
                console.log("Request completed 201");
                resolve(data || {statusCode: 201});
            },
            204: function (data) {
                console.log("Request completed 204");
                resolve(data || { statusCode: 204});
            }
        }
    };

    $.ajax(settings)
});
</code>```

Title: jQuery ajax handling of 204 No Content

Body:
Best way would be to make a call for statusCode in ajax. And make a runner code in specific statusCode.

new Promise((resolve, reject) => {
    var settings = {
            "URL": "<your link>",
            "method": "POST",
            "timeout": 0,
            "headers": {
            "Content-Type": "application/json"
            },
        "data": JSON.stringify({
            "email": email,
            "user_name": user_name,
        }),
        "statusCode": {
            200: function (data) {
                console.log("Request completed 200");
                resolve(data || {statusCode: 200});
            },
            201: function (data) {
                console.log("Request completed 201");
                resolve(data || {statusCode: 201});
            },
            204: function (data) {
                console.log("Request completed 204");
                resolve(data || { statusCode: 204});
            }
        }
    };

    $.ajax(settings)
});


问:
How to set batch size in one micro-batch of spark structured streaming
I am reading streaming data from Kafka source, but all the data from kafka is read in a single micro batch.

```<code>spark.readStream.format("kafka").option("kafka.bootstrap.servers",bootstrap_servers).option("subscribe", topics).option("startingOffsets", "earliest").load()
</code>```

Which parameter or option is used to set max batch size in one micro-batch of spark structured streaming?

答:
use maxOffsetsPerTrigger to limit the no of messages.

as per spark doc "maxOffsetsPerTrigger  - Rate limit on maximum number of offsets processed per trigger interval. The specified total number of offsets will be proportionally split across topicPartitions of different volume."

Body:
I am reading streaming data from Kafka source, but all the data from kafka is read in a single micro batch.

spark.readStream.format("kafka").option("kafka.bootstrap.servers",bootstrap_servers).option("subscribe", topics).option("startingOffsets", "earliest").load()

Which parameter or option is used to set max batch size in one micro-batch of spark structured streaming?


问:
JSF - UISelectItems problem
Strange error i received from compiler:

```<code>Expected a child component type of UISelectItem/UISelectItems for component type javax.faces.SelectOne(siachoice).  Found javax.faces.component.UISelectItems.
</code>```

So, if he was expecting UISelectItems, and found UISelectItems, then where is the error?

My JSP implementation:

```<code><h:selectOneMenu id="siachoice" value="#{dbSelectBean.currentOption}">
                                <f:selectItems value="#{dbSelectBean.dbs}" />
                            </h:selectOneMenu>
</code>```

Method, where i am setting UISelectItem to UISelectItems:

```<code>private UISelectItems populateDatabases(String databaseString) {
    UISelectItems selects = new UISelectItems();
    List<UISelectItem> result = new ArrayList<UISelectItem>();
    StringTokenizer tokeniz = new StringTokenizer(databaseString, GlobalConstants.DELIMITER);
    while(tokeniz.hasMoreTokens()){
        String tempDB = tokeniz.nextToken();
        UISelectItem item = new UISelectItem();
        item.setItemValue(tempDB);
        item.setItemLabel(tempDB);
        result.add(item);
    }
    selects.setValue(result);

    return selects;
}
</code>```

Then, of course, i am setting it to the bean variable dbs.

Help?

答:
```<code><h:form>
<h:selectOneListbox size="5"  >

<f:selectItems  value="#{userManager.Test()}" />
</h:selectOneListbox>
</h:form>
</code>```

<hr>

```<code>import javax.faces.model.SelectItem;
import tn.com.ttnproject.entity.*;

@Name("userManager")
@Scope(ScopeType.CONVERSATION)
public class UserManager {
    public  List <SelectItem> listAllUsersNames;
    SelectItem element;
    public List<SelectItem> Test(){
        listAllUsersNames = new ArrayList<SelectItem>();
        for (int i=1;i<=10;i++)
        {
            element=new SelectItem(
                new Integer(i),
                i+".00 euros",
                "Produit à "+i+".00 euros");
            listAllUsersNames.add(element);
        }
        return listAllUsersNames;
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: JSF - UISelectItems problem

Body:
Strange error i received from compiler:

Expected a child component type of UISelectItem/UISelectItems for component type javax.faces.SelectOne(siachoice).  Found javax.faces.component.UISelectItems.

So, if he was expecting UISelectItems, and found UISelectItems, then where is the error?

My JSP implementation:

<h:selectOneMenu id="siachoice" value="#{dbSelectBean.currentOption}">
                                <f:selectItems value="#{dbSelectBean.dbs}" />
                            </h:selectOneMenu>

Method, where i am setting UISelectItem to UISelectItems:

private UISelectItems populateDatabases(String databaseString) {
    UISelectItems selects = new UISelectItems();
    List<UISelectItem> result = new ArrayList<UISelectItem>();
    StringTokenizer tokeniz = new StringTokenizer(databaseString, GlobalConstants.DELIMITER);
    while(tokeniz.hasMoreTokens()){
        String tempDB = tokeniz.nextToken();
        UISelectItem item = new UISelectItem();
        item.setItemValue(tempDB);
        item.setItemLabel(tempDB);
        result.add(item);
    }
    selects.setValue(result);

    return selects;
}

Then, of course, i am setting it to the bean variable dbs.

Help?

Body:
<h:form>
<h:selectOneListbox size="5"  >

<f:selectItems  value="#{userManager.Test()}" />
</h:selectOneListbox>
</h:form>

import javax.faces.model.SelectItem;
import tn.com.ttnproject.entity.*;

@Name("userManager")
@Scope(ScopeType.CONVERSATION)
public class UserManager {
    public  List <SelectItem> listAllUsersNames;
    SelectItem element;
    public List<SelectItem> Test(){
        listAllUsersNames = new ArrayList<SelectItem>();
        for (int i=1;i<=10;i++)
        {
            element=new SelectItem(
                new Integer(i),
                i+".00 euros",
                "Produit à "+i+".00 euros");
            listAllUsersNames.add(element);
        }
        return listAllUsersNames;
    }
}


问:
C problem with memory leaks (realloc function)
scanFolderPath - path of folder with files.

filesToScan - array of strings with the files name.

I have problem with the realloc line (the third line in the for loop). And I don't understand why! Thank you for helping programmers community ;)

```<code>char* filePath = malloc(0);
char* fileContent = 0;
char* partContent = 0;
FILE* fileToScan;
int i = 0, j = 0, virus = FALSE, flag = FALSE, counter = 0;
for (i = 0; i < amountOfFiles; i++)
{
    flag = FALSE;
    if (scanFolderPath != NULL && filesToScan[i] != NULL)
    {
        realloc(filePath, (sizeof(char) * (strlen(scanFolderPath) + 1 + strlen(filesToScan[i]))));
    }
    strcpy(filePath, "");
    getFilePath(filePath, scanFolderPath, filesToScan[i]);
    fileToScan = fopen(filePath, "rb");
    readFile(&fileContent, filePath);
    if (choice == '0')
    {
        virus = scanSingature(fileContent, virusSingature, getLength(fileToScan), virusSingatureLen);
        if (virus)
        {
            printf("%s - Infected!\n", filePath);
            fprintf(logsFile, "%s", filePath);
            fprintf(logsFile, "  Infected!\n");
        }
        else
        {
            printf("%s - Clean\n", filePath);
            fprintf(logsFile, ("%s", filePath));
            fprintf(logsFile, "  Clean\n");
        }
        fclose(fileToScan);
        strcpy(filePath, "");
    }
}
</code>```

答:
realloc returns new allocated block. You do not assign to anything so the reallocated memory is lost and your pointer is pointing to the invalid memory assuming realloc success).

The correct way of reallocating:

```<code>void *p = malloc(10);
void t;

/* ... */

t = realloc(p, 20);
if(t) p = t;            //check if the realloc was successful

/* ... */

free(p)
</code>```

Body:
scanFolderPath - path of folder with files.

filesToScan - array of strings with the files name.

I have problem with the realloc line (the third line in the for loop). And I don't understand why! Thank you for helping programmers community ;)

char* filePath = malloc(0);
char* fileContent = 0;
char* partContent = 0;
FILE* fileToScan;
int i = 0, j = 0, virus = FALSE, flag = FALSE, counter = 0;
for (i = 0; i < amountOfFiles; i++)
{
    flag = FALSE;
    if (scanFolderPath != NULL && filesToScan[i] != NULL)
    {
        realloc(filePath, (sizeof(char) * (strlen(scanFolderPath) + 1 + strlen(filesToScan[i]))));
    }
    strcpy(filePath, "");
    getFilePath(filePath, scanFolderPath, filesToScan[i]);
    fileToScan = fopen(filePath, "rb");
    readFile(&fileContent, filePath);
    if (choice == '0')
    {
        virus = scanSingature(fileContent, virusSingature, getLength(fileToScan), virusSingatureLen);
        if (virus)
        {
            printf("%s - Infected!\n", filePath);
            fprintf(logsFile, "%s", filePath);
            fprintf(logsFile, "  Infected!\n");
        }
        else
        {
            printf("%s - Clean\n", filePath);
            fprintf(logsFile, ("%s", filePath));
            fprintf(logsFile, "  Clean\n");
        }
        fclose(fileToScan);
        strcpy(filePath, "");
    }
}

Body:
realloc returns new allocated block. You do not assign to anything so the reallocated memory is lost and your pointer is pointing to the invalid memory assuming realloc success).

The correct way of reallocating:

void *p = malloc(10);
void t;

/* ... */

t = realloc(p, 20);
if(t) p = t;            //check if the realloc was successful

/* ... */

free(p)


问:
File.Copy Throwing throw "The filename, directory name, or volume label syntax is incorrect" error
i am trying to copy a file from staging folder to inbound folder . not sure what i m doing wrong</p>

```<code> File.Copy("//o1-app-03/na_dev$/STAGE/RMS.TXT", "//o1-app-03/na_dev$/INBOUND/RMS/");
</code>```

答:
Add desired destination file name to the second argument cause File.Copy has two parameters, both of them are file names:

```<code>public static void Copy (string sourceFileName, string destFileName);
</code>```

Body:
i am trying to copy a file from staging folder to inbound folder . not sure what i m doing wrong

 File.Copy("//o1-app-03/na_dev$/STAGE/RMS.TXT", "//o1-app-03/na_dev$/INBOUND/RMS/");

Body:
Add desired destination file name to the second argument cause File.Copy has two parameters, both of them are file names:

public static void Copy (string sourceFileName, string destFileName);


问:
Flutter make BG image as local stored image
I have the following code to set my background image as an asset image:

```<code>Container(
   decoration: new BoxDecoration(
      image: DecorationImage(
         image: AssetImage("assets/bg.png"),
      )
   ),
</code>```

I wanted to know if I previously stored an image to the device, how can I use it as a background image?

```<code>Future<File> _getLocalFile(String filename) async {
  String dir = (await getApplicationDocumentsDirectory()).path;
  File f = new File('$dir/$filename');
  return f;
}
</code>```

Thank you.

答:
FileImage will help:

```<code>CircleAvatar(
   backgroundImage: FileImage(File(this.filepath)),
),
</code>```

Body:
I have the following code to set my background image as an asset image:

Container(
   decoration: new BoxDecoration(
      image: DecorationImage(
         image: AssetImage("assets/bg.png"),
      )
   ),

I wanted to know if I previously stored an image to the device, how can I use it as a background image?

Future<File> _getLocalFile(String filename) async {
  String dir = (await getApplicationDocumentsDirectory()).path;
  File f = new File('$dir/$filename');
  return f;
}

Thank you.

Body:
FileImage will help:

CircleAvatar(
   backgroundImage: FileImage(File(this.filepath)),
),


答:
try

```<code>filePath = realloc(filePath, (sizeof(char) * (strlen(scanFolderPath) + 1 + strlen(filesToScan[i]))));
</code>```

that way the contents of filepath are reallocated, and the pointer is returned to filepath

Title: C problem with memory leaks (realloc function)

Body:
try

filePath = realloc(filePath, (sizeof(char) * (strlen(scanFolderPath) + 1 + strlen(filesToScan[i]))));

that way the contents of filepath are reallocated, and the pointer is returned to filepath


问:
Issue with detecting file moves using inotify.
I wanted to use inotify to monitor contents of a directory. Everything seems fine until I try to rename a file in the directory using mv command. I get IN_MOVED_FROM as expected but IN_MOVED_TO doesn't come.

Below is my test program. Compile with:

```<code>g++ -Wall -o test test.cpp
</code>```

Launch with:

```<code>./test dir_to_watch
</code>```

#include <cstdio>
#include <cstring>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/inotify.h>

int main (int argc, char *argv[])
{
  int inotify_fd = inotify_init();

  if (inotify_fd < 0)
  {
    fprintf(stderr, "Unable to init inotify: %m\n");
    return 1;
  }

  int watch_descriptor = inotify_add_watch(inotify_fd,
                       argv[1],
                       IN_ALL_EVENTS);

  if (watch_descriptor < 0)
  {
    fprintf(stderr, "Unable to add inotify watch: %m\n");
    return 1;
  }

  union
  {
    inotify_event event;
    char pad[1024];
  }
  buffer;

  struct events
  {
    int mask;
    const char *name;
  }
  events[] =
  {
    {IN_ACCESS         , "IN_ACCESS        "},
    {IN_ATTRIB         , "IN_ATTRIB        "},
    {IN_CLOSE_WRITE    , "IN_CLOSE_WRITE   "},
    {IN_CLOSE_NOWRITE  , "IN_CLOSE_NOWRITE "},
    {IN_CREATE         , "IN_CREATE        "},
    {IN_DELETE         , "IN_DELETE        "},
    {IN_DELETE_SELF    , "IN_DELETE_SELF   "},
    {IN_MODIFY         , "IN_MODIFY        "},
    {IN_MOVE_SELF      , "IN_MOVE_SELF     "},
    {IN_MOVED_FROM     , "IN_MOVED_FROM    "},
    {IN_MOVED_TO       , "IN_MOVED_TO      "},
    {IN_OPEN           , "IN_OPEN          "},
  };

  while (read(inotify_fd, &buffer, sizeof buffer) > 0)
  {
    for (unsigned i = 0; i < sizeof events / sizeof events[0]; i++)
    {
      if (events[i].mask & buffer.event.mask)
      {
    if (buffer.event.len)
    {
      printf("Inotify %s: %s\n", events[i].name, buffer.event.name);
    }
    else
    {
      printf("Inotify %s\n", events[i].name);
    }
      }
    }
  }
}
```

答:
Self solved: it turns out that inotify can return multiple events in a single read() call. So the corrected source code looks like this:

#include <cstdio>
#include <cstring>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/inotify.h>

int main (int argc, char *argv[])
{
  int inotify_fd = inotify_init();

  if (inotify_fd < 0)
  {
    fprintf(stderr, "Unable to init inotify: %m\n");
    return 1;
  }

  int watch_descriptor = inotify_add_watch(inotify_fd,
                       argv[1],
                       IN_ALL_EVENTS);

  if (watch_descriptor < 0)
  {
    fprintf(stderr, "Unable to add inotify watch: %m\n");
    return 1;
  }

  struct events
  {
    int mask;
    const char *name;
  }
  events[] =
  {
    {IN_ACCESS         , "IN_ACCESS        "},
    {IN_ATTRIB         , "IN_ATTRIB        "},
    {IN_CLOSE_WRITE    , "IN_CLOSE_WRITE   "},
    {IN_CLOSE_NOWRITE  , "IN_CLOSE_NOWRITE "},
    {IN_CREATE         , "IN_CREATE        "},
    {IN_DELETE         , "IN_DELETE        "},
    {IN_DELETE_SELF    , "IN_DELETE_SELF   "},
    {IN_MODIFY         , "IN_MODIFY        "},
    {IN_MOVE_SELF      , "IN_MOVE_SELF     "},
    {IN_MOVED_FROM     , "IN_MOVED_FROM    "},
    {IN_MOVED_TO       , "IN_MOVED_TO      "},
    {IN_OPEN           , "IN_OPEN          "},
  };

  ssize_t rd;
  char buffer[1024];

  while ((rd = read(inotify_fd, buffer, sizeof buffer)) > 0)
  {
    for (char *ptr = buffer; ptr != buffer + rd; ptr += sizeof(inotify_event) + reinterpret_cast<inotify_event*>(ptr)->len)
    {
      inotify_event *event = reinterpret_cast<inotify_event*>(ptr);

      for (unsigned i = 0; i < sizeof events / sizeof events[0]; i++)
      {
    if (events[i].mask & event->mask)
    {
      if (event->len)
      {
        printf("Inotify %d %s: %s\n", inotify_fd, events[i].name, event->name);
      }
      else
      {
        printf("Inotify %d %s\n", inotify_fd, events[i].name);
      }
    }
      }
    }
  }

  if (rd < 0)
  {
    fprintf(stderr, "inotify read %d event error: %m\n", inotify_fd);
    return 1;
  }
}
```

Body:
I wanted to use inotify to monitor contents of a directory. Everything seems fine until I try to rename a file in the directory using mv command. I get IN_MOVED_FROM as expected but IN_MOVED_TO doesn't come.

Below is my test program. Compile with:

g++ -Wall -o test test.cpp

Launch with:

./test dir_to_watch

#include <cstdio>
#include <cstring>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/inotify.h>

int main (int argc, char *argv[])
{
  int inotify_fd = inotify_init();

  if (inotify_fd < 0)
  {
    fprintf(stderr, "Unable to init inotify: %m\n");
    return 1;
  }

  int watch_descriptor = inotify_add_watch(inotify_fd,
                       argv[1],
                       IN_ALL_EVENTS);

  if (watch_descriptor < 0)
  {
    fprintf(stderr, "Unable to add inotify watch: %m\n");
    return 1;
  }

  union
  {
    inotify_event event;
    char pad[1024];
  }
  buffer;

  struct events
  {
    int mask;
    const char *name;
  }
  events[] =
  {
    {IN_ACCESS         , "IN_ACCESS        "},
    {IN_ATTRIB         , "IN_ATTRIB        "},
    {IN_CLOSE_WRITE    , "IN_CLOSE_WRITE   "},
    {IN_CLOSE_NOWRITE  , "IN_CLOSE_NOWRITE "},
    {IN_CREATE         , "IN_CREATE        "},
    {IN_DELETE         , "IN_DELETE        "},
    {IN_DELETE_SELF    , "IN_DELETE_SELF   "},
    {IN_MODIFY         , "IN_MODIFY        "},
    {IN_MOVE_SELF      , "IN_MOVE_SELF     "},
    {IN_MOVED_FROM     , "IN_MOVED_FROM    "},
    {IN_MOVED_TO       , "IN_MOVED_TO      "},
    {IN_OPEN           , "IN_OPEN          "},
  };

  while (read(inotify_fd, &buffer, sizeof buffer) > 0)
  {
    for (unsigned i = 0; i < sizeof events / sizeof events[0]; i++)
    {
      if (events[i].mask & buffer.event.mask)
      {
    if (buffer.event.len)
    {
      printf("Inotify %s: %s\n", events[i].name, buffer.event.name);
    }
    else
    {
      printf("Inotify %s\n", events[i].name);
    }
      }
    }
  }
}


问:
EF Core : Testing with InMemory Database has inconsistent behavior
I'm using the InMemory database to test my repository layer in my ASP .NET Core Web API application.
Thus I have an issue, in several tests, I setup data. But, with the same code, when I run the tests sometimes the data is present and sometimes it is not. I don't understand why.

I'm using XUnit Testing Framework.

Here is my test :

public class UserRepositoryTest
    {
        private ApplicationDbContext context;

        void setup()
        {
            var options = new DbContextOptionsBuilder<ApplicationDbContext>()
                .UseInMemoryDatabase(databaseName: "ApplicationDatabase")
                .Options;

            this.context = new ApplicationDbContext(options);
            this.context.Database.EnsureDeleted();
        }

        [Fact]
        void GetUserByUsernameTest()
        {
            this.setup();
            // Given
            var manager = new User {Username = "Ombrelin", Email = "test@test.fr"};
            context.Users.Add(manager);
            context.SaveChanges();

            // When
            var repo = new UserRepository(context);
            var user = repo.GetUserByUsername("Ombrelin");

            // Then
            Assert.Equal("Ombrelin", user.Username);
        }

        [Fact]
        void FindUsersByUsernameContainsTest()
        {
            this.setup();
            // Given
            var manager1 = new User {Username = "Arsène", Email = "test@test.fr"};
            var manager2 = new User {Username = "Jean Michel", Email = "test@test.fr"};
            context.Users.Add(manager1);
            context.Users.Add(manager2);
            context.SaveChanges();

            // When
            var repo = new UserRepository(context);
            var users = repo.findUsersByUsernameContains("Ars");

            // Then
            Assert.Single(users);
        }
```

Does anyone have a clue about this ?

Thanks in advance,

答:
You are reusing the same database context across multiple tests. Tests may run in parallel. Thus, when using the same database context tests may influence each other's outcome. To avoid this, you need to isolate the tests by letting them use a clean database context:

```<code>public class UserRepositoryTest
{
    [Fact]
    public void GetUserByUsernameTest()
    {

        var options = new DbContextOptionsBuilder<ApplicationDbContext>()
            .UseInMemoryDatabase(databaseName: $"ApplicationDatabase{Guid.NewGuid()}")
            .Options;

        using(var context = new ApplicationDbContext(options))
        {
            // Given
            var manager = new User { Username = "Ombrelin", Email = "test@test.fr" };
            context.Users.Add(manager);
            context.SaveChanges();

            // When
            var repo = new UserRepository(context);
            var user = repo.GetUserByUsername("Ombrelin");

            // Then
            Assert.Equal("Ombrelin", user.Username);
        }

    }
}
</code>```

By appending a unique id to the database name, you are ensuring, that tests are using a unique in-memory database. Obviously, this will make test execution slower. A lot of testers also use different contexts for seeding the data and performing the test:

```<code>public class UserRepositoryTest
{
    [Fact]
    public void GetUserByUsernameTestSeparateContexts()
    {

        var options = new DbContextOptionsBuilder<ApplicationDbContext>()
            .UseInMemoryDatabase(databaseName: $"ApplicationDatabase{Guid.NewGuid()}")
            .Options;

        using (var context = new ApplicationDbContext(options))
        {
            // Given
            var manager = new User { Username = "Ombrelin", Email = "test@test.fr" };
            context.Users.Add(manager);
            context.SaveChanges();

        }

        using (var context = new ApplicationDbContext(options))
        {
            // When
            var repo = new UserRepository(context);
            var user = repo.GetUserByUsername("Ombrelin");

            // Then
            Assert.Equal("Ombrelin", user.Username);
        }

    }
}
</code>```

This makes the tests more realistic, since functions, that are seeding the data, and functions, that are using the data, often use different contexts. Also keep in mind, that the InMemoryProvider is not a relational database. Therefore, it does not support some features of actual database servers such as referential integrity checks, TimeStamp, IsRowVersion and others. Check the MS documentation for details: here.

Body:
I'm using the InMemory database to test my repository layer in my ASP .NET Core Web API application.
Thus I have an issue, in several tests, I setup data. But, with the same code, when I run the tests sometimes the data is present and sometimes it is not. I don't understand why.

I'm using XUnit Testing Framework.

Here is my test :

public class UserRepositoryTest
    {
        private ApplicationDbContext context;

        void setup()
        {
            var options = new DbContextOptionsBuilder<ApplicationDbContext>()
                .UseInMemoryDatabase(databaseName: "ApplicationDatabase")
                .Options;

            this.context = new ApplicationDbContext(options);
            this.context.Database.EnsureDeleted();
        }

        [Fact]
        void GetUserByUsernameTest()
        {
            this.setup();
            // Given
            var manager = new User {Username = "Ombrelin", Email = "test@test.fr"};
            context.Users.Add(manager);
            context.SaveChanges();

            // When
            var repo = new UserRepository(context);
            var user = repo.GetUserByUsername("Ombrelin");

            // Then
            Assert.Equal("Ombrelin", user.Username);
        }

        [Fact]
        void FindUsersByUsernameContainsTest()
        {
            this.setup();
            // Given
            var manager1 = new User {Username = "Arsène", Email = "test@test.fr"};
            var manager2 = new User {Username = "Jean Michel", Email = "test@test.fr"};
            context.Users.Add(manager1);
            context.Users.Add(manager2);
            context.SaveChanges();

            // When
            var repo = new UserRepository(context);
            var users = repo.findUsersByUsernameContains("Ars");

            // Then
            Assert.Single(users);
        }

Does anyone have a clue about this ?

Thanks in advance,

Body:
You are reusing the same database context across multiple tests. Tests may run in parallel. Thus, when using the same database context tests may influence each other's outcome. To avoid this, you need to isolate the tests by letting them use a clean database context:

public class UserRepositoryTest
{
    [Fact]
    public void GetUserByUsernameTest()
    {

        var options = new DbContextOptionsBuilder<ApplicationDbContext>()
            .UseInMemoryDatabase(databaseName: $"ApplicationDatabase{Guid.NewGuid()}")
            .Options;

        using(var context = new ApplicationDbContext(options))
        {
            // Given
            var manager = new User { Username = "Ombrelin", Email = "test@test.fr" };
            context.Users.Add(manager);
            context.SaveChanges();

            // When
            var repo = new UserRepository(context);
            var user = repo.GetUserByUsername("Ombrelin");

            // Then
            Assert.Equal("Ombrelin", user.Username);
        }

    }
}

By appending a unique id to the database name, you are ensuring, that tests are using a unique in-memory database. Obviously, this will make test execution slower. A lot of testers also use different contexts for seeding the data and performing the test:

public class UserRepositoryTest
{
    [Fact]
    public void GetUserByUsernameTestSeparateContexts()
    {

        var options = new DbContextOptionsBuilder<ApplicationDbContext>()
            .UseInMemoryDatabase(databaseName: $"ApplicationDatabase{Guid.NewGuid()}")
            .Options;

        using (var context = new ApplicationDbContext(options))
        {
            // Given
            var manager = new User { Username = "Ombrelin", Email = "test@test.fr" };
            context.Users.Add(manager);
            context.SaveChanges();

        }

        using (var context = new ApplicationDbContext(options))
        {
            // When
            var repo = new UserRepository(context);
            var user = repo.GetUserByUsername("Ombrelin");

            // Then
            Assert.Equal("Ombrelin", user.Username);
        }

    }
}

This makes the tests more realistic, since functions, that are seeding the data, and functions, that are using the data, often use different contexts. Also keep in mind, that the InMemoryProvider is not a relational database. Therefore, it does not support some features of actual database servers such as referential integrity checks, TimeStamp, IsRowVersion and others. Check the MS documentation for details: here.


问:
Uncaught TypeError: Cannot read property 'style' of undefined at HTMLTableCellElement
I'm trying to do an exercise related to a chess game. I only must represent the chessboard with static X or Y as I have just done. However, I want to add an onClick for each box. The click must display me if I have clicked a black or white box and if it is free or busy. I get an exception when my onClick function is executed and I don't understand why. My solution is:

```<code>
<script>
      let scacchiera = [];

      function createTable() {
        var table = document.createElement("table");
        for (var i = 0; i < 8; i++) {
          var row = document.createElement("tr");
          for (var j = 0; j < 8; j++) {
            var column = document.createElement("td");
            if ((j % 2 === 1 && i % 2 == 1) || (j % 2 == 0 && i % 2 == 0)) {
              column.style.backgroundColor = "black";
              if (i < 3) {
                column.textContent = "X";
              }
              if (i > 4) {
                column.textContent = "O";
              }
            }
            column.addEventListener("click", function (column) {
              if (column.style.backgroundColor === "black") {
                if(column.textContent ==="X"){
                    alert("black box and X");
                }else{
                    alert("black box and Y");
                }
              } else {
                if(column.textContent ==="X"){
                    alert("white box and X");
                }else{
                    alert("white box and Y");
                }
              }
            });
            row.appendChild(column);
          }
          table.appendChild(row);
        }
        scacchiera = table;
        return scacchiera;
      }

      createTable();
      document.body.appendChild(scacchiera);
    </script>

</code>```

答:
Whenever event happens,Event object gets passed to the listener's handler.

In order to access the target element from event object we do e.currentTarget

So you are naming the parameter in handler as column, in order to get target element column.currentTarget but you should consider renaming the param to  e or other variable since its conflicting with already declared variables.

```<code>column.addEventListener("click", function (e) {
             let target=e.currentTarget
              if (target.style.backgroundColor === "black") {
                if(target.textContent ==="X"){
                    alert("black box and X");
                }else{
                    alert("black box and Y");
                }
              } else {
                if(target.textContent ==="X"){
                    alert("white box and X");
                }else{
                    alert("white box and Y");
                }
              }
            });
</code>```

Body:
Whenever event happens,Event object gets passed to the listener's handler.

In order to access the target element from event object we do e.currentTarget

So you are naming the parameter in handler as column, in order to get target element column.currentTarget but you should consider renaming the param to  e or other variable since its conflicting with already declared variables.

column.addEventListener("click", function (e) {
             let target=e.currentTarget
              if (target.style.backgroundColor === "black") {
                if(target.textContent ==="X"){
                    alert("black box and X");
                }else{
                    alert("black box and Y");
                }
              } else {
                if(target.textContent ==="X"){
                    alert("white box and X");
                }else{
                    alert("white box and Y");
                }
              }
            });


问:
Swapping contents of columns of same datatype from different tables in MySQL
I want to swap the column contents of same datatype from two different tables in MySQL.

Table 1

```<code>id value
1  aaa
2  bbb
3  ccc
</code>```

Table 2

```<code>id value
1  ddd
2  eee
3  fff
</code>```

And my new tables should be like this.

```<code>Table 1            Table 2

id value           id value
1  ddd             1  aaa
2  eee             2  bbb
3  fff             3  ccc
</code>```

Is there any way to do this in MySQL?

答:
Just do this, as commenters suggested:</p>

```<code>RENAME TABLE Table_1 TO tmp_table,
             Table_2 TO Table_1,
             tmp_table TO Table_2;
</code>```

Body:
I want to swap the column contents of same datatype from two different tables in MySQL.

Table 1

id value
1  aaa
2  bbb
3  ccc

Table 2

id value
1  ddd
2  eee
3  fff

And my new tables should be like this.

Table 1            Table 2

id value           id value
1  ddd             1  aaa
2  eee             2  bbb
3  fff             3  ccc

Is there any way to do this in MySQL?

Body:
Just do this, as commenters suggested:

RENAME TABLE Table_1 TO tmp_table,
             Table_2 TO Table_1,
             tmp_table TO Table_2;


问:
PHPUnit - 'No tests executed' when using configuration file

The Problem

To improve my quality of code, I've decided to try to learn how to test my code using Unit Testing instead of my mediocre-at-best testing solutions.

I decided to install PHPUnit using composer for a personal library that allows me to achieve common database functions. At first I didn't have a configuration file for PHPUnit and when I ran commands like:

```<code>$ phpunit tests/GeneralStringFunctions/GeneralStringFunctionsTest
</code>```

Please note that this is a terminal command, so I didn't include the .php extension. The GeneralStringFunctionsTest referred to above is actually a GeneralStringFunctionsTest.php file.

The output is what I expected:

Time: 31 ms, Memory: 2.75Mb

OK (1 test, 1 assertion)

I then tried to use a configuration file to automatically load the test suite instead of having to manually type in the file every time. I created a file called phpunit.xml in my root directory, and entered the following into the file: http://pastebin.com/0j0L4WBD:

```<code><?xml version = "1.0" encoding="UTF-8" ?>
<phpunit>
    <testsuites>
        <testsuite name="Tests">
            <directory>tests</directory>
        </testsuite>
    </testsuites>
</phpunit>
</code>```

Now, when I run the command:

```<code>phpunit
</code>```

I get the following output:

PHPUnit 4.5.0 by Sebastian Bergmann and contributors.

Configuration read from /Users/muyiwa/Projects/DatabaseHelper/phpunit.xml

Time: 16 ms, Memory: 1.50Mb

No tests executed!

In case it's helpful, my directory structure is as follows:

src - Top level directory (with all my source code)

tests - Top level directory (with all my tests, structured the same as my src folder)

vendor - Composer third party files

I also have the composer json and lock file, as well as the phpunit xml file in the top level as files.

Things I've Tried

Changing the directory in phpunit.xml to tests/GeneralStringFunctions

Changing the directory in phpunit.xml to ./tests

Moving the phpunit.xml file to the tests directory and then changing the directory to be ./ instead of tests.

Adding a suffix attribute to the directory tag in phpunit.xml to specify "Tests" as the explicit suffix.

答:
Came late to the party, but this info may help others.

Above solutions did not work for me. As of Laravel 7.x, by default, PHPUnit executes only PHP files which are suffixed with "Test.php". For example if you create a test, naming it CreateUser will not work, whereas naming it CreateUserTest will work.

To overcome the limitation, go to phpunit.xml and modify suffix attribute from directory elements:

```<code>...
<testsuite name="Unit">

    <!-- modify suffix -->
    <directory suffix=".php">./tests/Unit</directory>

</testsuite>
<testsuite name="Feature">

    <!-- modify suffix -->
    <directory suffix=".php">./tests/Feature</directory>

</testsuite>
...
</code>```

This will instruct PHPUnit to run all files with .php extension from directories. Note to clear app's cache after updating phpunit.xml:

```<code>php artisan config:cache
</code>```

Additional information about PHPUnit XML configuration can be found here: https://phpunit.de/manual/6.5/en/appendixes.configuration.html

Body:
The Problem

To improve my quality of code, I've decided to try to learn how to test my code using Unit Testing instead of my mediocre-at-best testing solutions.

I decided to install PHPUnit using composer for a personal library that allows me to achieve common database functions. At first I didn't have a configuration file for PHPUnit and when I ran commands like:

$ phpunit tests/GeneralStringFunctions/GeneralStringFunctionsTest

Please note that this is a terminal command, so I didn't include the .php extension. The GeneralStringFunctionsTest referred to above is actually a GeneralStringFunctionsTest.php file.

The output is what I expected:

Time: 31 ms, Memory: 2.75Mb

OK (1 test, 1 assertion)

I then tried to use a configuration file to automatically load the test suite instead of having to manually type in the file every time. I created a file called phpunit.xml in my root directory, and entered the following into the file: http://pastebin.com/0j0L4WBD:

<?xml version = "1.0" encoding="UTF-8" ?>
<phpunit>
    <testsuites>
        <testsuite name="Tests">
            <directory>tests</directory>
        </testsuite>
    </testsuites>
</phpunit>

Now, when I run the command:

phpunit

I get the following output:

PHPUnit 4.5.0 by Sebastian Bergmann and contributors.

Configuration read from /Users/muyiwa/Projects/DatabaseHelper/phpunit.xml

Time: 16 ms, Memory: 1.50Mb

No tests executed!

In case it's helpful, my directory structure is as follows:

src - Top level directory (with all my source code)

tests - Top level directory (with all my tests, structured the same as my src folder)

vendor - Composer third party files

I also have the composer json and lock file, as well as the phpunit xml file in the top level as files.

Things I've Tried

Changing the directory in phpunit.xml to tests/GeneralStringFunctions

Changing the directory in phpunit.xml to ./tests

Moving the phpunit.xml file to the tests directory and then changing the directory to be ./ instead of tests.

Adding a suffix attribute to the directory tag in phpunit.xml to specify "Tests" as the explicit suffix.

Body:
Came late to the party, but this info may help others.

Above solutions did not work for me. As of Laravel 7.x, by default, PHPUnit executes only PHP files which are suffixed with "Test.php". For example if you create a test, naming it CreateUser will not work, whereas naming it CreateUserTest will work.

To overcome the limitation, go to phpunit.xml and modify suffix attribute from directory elements:

...
<testsuite name="Unit">

    <!-- modify suffix -->
    <directory suffix=".php">./tests/Unit</directory>

</testsuite>
<testsuite name="Feature">

    <!-- modify suffix -->
    <directory suffix=".php">./tests/Feature</directory>

</testsuite>
...

This will instruct PHPUnit to run all files with .php extension from directories. Note to clear app's cache after updating phpunit.xml:

php artisan config:cache

Additional information about PHPUnit XML configuration can be found here: https://phpunit.de/manual/6.5/en/appendixes.configuration.html


问:
R: Replace NA with date value. If date value exists in both columns choose the earliest date
I am working with two data frames and have merged them thanks to the advice on other StackOverflow threads. Now I'm struggling to get the values from one column into the other column IF they meet certain conditions.

The date_first_followup column is almost null but does have some values in it due to historical usage. The Activity.Date.x column always has a date in it but it isn't always the same date value as the date_first_followup column.

What I need to do is to have R replace all of the NA's in the followup column with the dates in the Activity column. Whenever a row has values in both columns take the earliest date.

```<code>date_first_followup Activity.Date.X
NA                  NA
NA                  NA
6/30/2018           NA
4/13/2015           3/25/2015
NA                  NA
NA                  NA
NA                  3/21/2018
NA                  4/2/2018
NA                  4/13/2018
NA                  NA
4/13/2015           11/6/2016
</code>```

I don't know if how the fields are formatted affect the results but they start of as factors and I've tried various formatting options under as.Date() or even just leaving it as factor.

```<code>#Trying out a coalesce based solution.
#Use Coalesce to include follow up dates from activities whenever there isn't data already
#present in the followup field.
#
testVlookup_df$Activity.Date.x <- as.Date(testVlookup_df$Activity.Date.x, format = "%/m%/d%/Y")
testVlookup_df$date_first_followup <- as.Date(testVlookup_df$date_first_followup, format = "%m/%d/%Y")
#
testVlookup_df$date_first_followup <- dplyr::coalesce(testVlookup_df$date_first_followup, testVlookup_df$ctivity.Date.x)
</code>```

Other attempts

```<code>#12.10.19 attempting to ONLY pull activity dates in when the column is NULL OR when the column has a value that has a later date.
testVlookup_df$date_first_followup <- ifelse(is.null(testVlookup_df$date_first_followup) == TRUE,
                                             as.Date(testVlookup_df$Activity.Date.x, format = "%m/%d/%Y"),
                                             ifelse(isTRUE(as.Date(testVlookup_df$date_first_followup, format = "%m/%d/%Y") > as.Date(testVlookup_df$Activity.Date.x, format = "%m/%d/%Y")) == TRUE,
                                                    as.Date(testVlookup_df$Activity.Date.x, format = "%/d%/m%/Y"), NA)
)
</code>```

Another attempt

```<code>#12.12.19 58th attempt. Invert the ifelses

testVlookup_df$date_first_followup <-
  ifelse(
    isTRUE(
      as.integer(gsub("-", "", testVlookup_df$date_first_followup)) > as.integer(testVlookup_df$Activity.Date.x, "%Y/%m/%d")
    ) == TRUE,
    as.Date(testVlookup_df$date_first_followup, format = "%m/%d/%Y"),
    ifelse(
      is.null(testVlookup_df$date_first_followup) == TRUE,
      as.Date(testVlookup_df$Activity.Date.x, format = "%m/%d/%Y"),
      NA
    )
  )
class(testVlookup_df$date_first_followup)
</code>```

Yet another attempt

```<code>  #Attempts for if command  using elses. This seems to work but does not loop through the entire vector.
    # testVlookup_df$date_first_followup <- if(is.null(testVlookup_df$date_first_followup)){ as.Date(testVlookup_df$Activity.Date.x, format = "%m/%d/%Y")
    # } else {if(as.integer(testVlookup_df$date_first_followup) > as.integer(testVlookup_df$Activity.Date.x)) {as.Date(testVlookup_df$Activity.Date.x, format = "%m/%d/%Y")
    # } else { NA }
    # }
    # Got this message 'Warning message:In if (as.integer(testVlookup_df$date_first_followup) > as.integer(testVlookup_df$Activity.Date.x))
    # { : the condition has length > 1 and only the first element will be used' Looked it up. Tells me if and else can only be used for 1 argument will not loop. Need sapply or ifelse
</code>```

答:
```<code>I finished this project a few months ago. So here is what eneded up working.

# STORE DATES AS DATES
#Store activity and followup dates as actual dates
activities_uniq_df$Activity.Date <-as.Date(activities_uniq_df$Activity.Date, format = "%m/%d/%Y")
class(activities_uniq_df$Activity.Date)

main_df2$date_first_followup <-as.Date(main_df2$date_first_followup, format = "%m/%d/%Y")
class(main_df2$date_first_followup)

#Create a subset of the main activities_uniq dataframe that only contains "Follow Up" activities.

FollowUpSub <- activities_uniq_df[activities_uniq_df$Item == "Follow Up",]

### PULL ACTIVITY DATES from Activities dataset into Main dataset based on Case ID#.

#FOLLOW UPS

#1st pull all of the desired fields in
main_df2 <- merge(main_df2, FollowUpSub[ , c("Item", "Activity.Date", "Case.ID")],
                        by.x = "Matter.Case.ID.", by.y = "Case.ID", all.x = TRUE)

which( colnames(main_df2) == "Activity.Date")

#2nd Re-Format the activity and followup dates because the merge causes date to go back to factor
main_df2$Activity.Date.x <-as.Date(main_df2$Activity.Date, format = "%m/%d/%Y")
class(main_df2$Activity.Date)

main_df2$date_first_followup <-as.Date(main_df2$date_first_followup, format = "%m/%d/%Y")
class(main_df2$date_first_followup)

#class(main_df2$date_first_followup) <- "Date"

#Finally do the actual replacing process
main_df2$date_first_followup <- ifelse(is.na(main_df2$date_first_followup), main_df2$Activity.Date.x,
                                             ifelse(main_df2$date_first_followup > main_df2$Activity.Date.x,
                                                    main_df2$Activity.Date.x, main_df2$date_first_followup )
)

#The above step messes with followup date format again so may have to re-class it.
#Question does the format of dates affect what date is considered less than or greater than another?
class(main_df2$date_first_followup) <- "Date"

#Confirm successful replacements
main_df2[c(35:39, 7001), c(26, 104)]
names(main_df2[c(22, 104)])
</code>```

Body:
I am working with two data frames and have merged them thanks to the advice on other StackOverflow threads. Now I'm struggling to get the values from one column into the other column IF they meet certain conditions.

The date_first_followup column is almost null but does have some values in it due to historical usage. The Activity.Date.x column always has a date in it but it isn't always the same date value as the date_first_followup column.

What I need to do is to have R replace all of the NA's in the followup column with the dates in the Activity column. Whenever a row has values in both columns take the earliest date.

date_first_followup Activity.Date.X
NA                  NA
NA                  NA
6/30/2018           NA
4/13/2015           3/25/2015
NA                  NA
NA                  NA
NA                  3/21/2018
NA                  4/2/2018
NA                  4/13/2018
NA                  NA
4/13/2015           11/6/2016

I don't know if how the fields are formatted affect the results but they start of as factors and I've tried various formatting options under as.Date() or even just leaving it as factor.

#Trying out a coalesce based solution.
#Use Coalesce to include follow up dates from activities whenever there isn't data already
#present in the followup field.
#
testVlookup_df$Activity.Date.x <- as.Date(testVlookup_df$Activity.Date.x, format = "%/m%/d%/Y")
testVlookup_df$date_first_followup <- as.Date(testVlookup_df$date_first_followup, format = "%m/%d/%Y")
#
testVlookup_df$date_first_followup <- dplyr::coalesce(testVlookup_df$date_first_followup, testVlookup_df$ctivity.Date.x)

Other attempts

#12.10.19 attempting to ONLY pull activity dates in when the column is NULL OR when the column has a value that has a later date.
testVlookup_df$date_first_followup <- ifelse(is.null(testVlookup_df$date_first_followup) == TRUE,
                                             as.Date(testVlookup_df$Activity.Date.x, format = "%m/%d/%Y"),
                                             ifelse(isTRUE(as.Date(testVlookup_df$date_first_followup, format = "%m/%d/%Y") > as.Date(testVlookup_df$Activity.Date.x, format = "%m/%d/%Y")) == TRUE,
                                                    as.Date(testVlookup_df$Activity.Date.x, format = "%/d%/m%/Y"), NA)
)

Another attempt

#12.12.19 58th attempt. Invert the ifelses

testVlookup_df$date_first_followup <-
  ifelse(
    isTRUE(
      as.integer(gsub("-", "", testVlookup_df$date_first_followup)) > as.integer(testVlookup_df$Activity.Date.x, "%Y/%m/%d")
    ) == TRUE,
    as.Date(testVlookup_df$date_first_followup, format = "%m/%d/%Y"),
    ifelse(
      is.null(testVlookup_df$date_first_followup) == TRUE,
      as.Date(testVlookup_df$Activity.Date.x, format = "%m/%d/%Y"),
      NA
    )
  )
class(testVlookup_df$date_first_followup)

Yet another attempt

  #Attempts for if command  using elses. This seems to work but does not loop through the entire vector.
    # testVlookup_df$date_first_followup <- if(is.null(testVlookup_df$date_first_followup)){ as.Date(testVlookup_df$Activity.Date.x, format = "%m/%d/%Y")
    # } else {if(as.integer(testVlookup_df$date_first_followup) > as.integer(testVlookup_df$Activity.Date.x)) {as.Date(testVlookup_df$Activity.Date.x, format = "%m/%d/%Y")
    # } else { NA }
    # }
    # Got this message 'Warning message:In if (as.integer(testVlookup_df$date_first_followup) > as.integer(testVlookup_df$Activity.Date.x))
    # { : the condition has length > 1 and only the first element will be used' Looked it up. Tells me if and else can only be used for 1 argument will not loop. Need sapply or ifelse


问:
How can I have flutter's navigator push a route in the navigation bar instead if fullscreen
In Flutter, How do I push a screen so that it appears inside the tab, rather than full screen.

Here is my code:

```<code>Card(
  color: Colors.white,
  child: ListTile(
    title: Text("PRIVACY POLICY", style: Styles.textDark),
    trailing: Icon(Icons.arrow_forward_ios),
    onTap: () => Navigator.of(context).push(CupertinoPageRoute(builder: (context) => SinglePageTextView("PRIVACY POLICY", "/assets/privacy.txt"))),
  ),
)
</code>```

PS: I have tried the fullscreenDialog setting on CupertinoPageRoute, and it does nothing!

Source screen:

When tapped Privacy Policy, this shows up:

This is what I am trying to achieve (tab bar is still showing!):

Thanks in advance for the help.

答:
Maybe you could use an ExpansionTile to achieve your goal?</p>

```<code>ExpansionTile(
      title: Text("I'm expandable."),
      children: <Widget>[
        Text("Hello, here I am."),
      ],
    ),
</code>```

Body:
In Flutter, How do I push a screen so that it appears inside the tab, rather than full screen.

Here is my code:

Card(
  color: Colors.white,
  child: ListTile(
    title: Text("PRIVACY POLICY", style: Styles.textDark),
    trailing: Icon(Icons.arrow_forward_ios),
    onTap: () => Navigator.of(context).push(CupertinoPageRoute(builder: (context) => SinglePageTextView("PRIVACY POLICY", "/assets/privacy.txt"))),
  ),
)

PS: I have tried the fullscreenDialog setting on CupertinoPageRoute, and it does nothing!

Source screen:

When tapped Privacy Policy, this shows up:

This is what I am trying to achieve (tab bar is still showing!):

Thanks in advance for the help.

Body:
Maybe you could use an ExpansionTile to achieve your goal?

ExpansionTile(
      title: Text("I'm expandable."),
      children: <Widget>[
        Text("Hello, here I am."),
      ],
    ),


问:
Kohana 3.1 ORM: Empty model property value saved as 0 (zero) instead of NULL
I have two models, Product and Product_Methodology. In my product edit view I have a select form field to select one of many methodologies or none (empty first option). In my products table I have a INT(10) methodology_id property that gets saved with the id of the methodology selected from the select form field. Everything worked OK until today that I had to make an adjustment to the system in which since now selecting a methodology can be optional. So I changed the methodology_id field of the products table to allow NULL value and removed the not_empty validation rule on the model.

The problem is that now when I save the model selecting the empty option, instead of the expected NULL, I get a 0 (zero) value.

Any clue on this?
Thanks a lot and let me know if it's not so clear.

答:
Even if the submitted form field is blank it's a string with any empty value - not NULL.  This gets cast as 0 when saved to an INT field (at least in mysql).  To preserve a null value do something like this:</p>

```<code>$methodology_id = (empty($methodology_id) ? NULL : $methodology_id);
</code>```

Body:
Even if the submitted form field is blank it's a string with any empty value - not NULL.  This gets cast as 0 when saved to an INT field (at least in mysql).  To preserve a null value do something like this:

$methodology_id = (empty($methodology_id) ? NULL : $methodology_id);


问:
Error while installing angular CLI - cb() never called
I am facing an issue - continuously trying to install angular CLI globally. Can anybody please help what could be the possible answer to resolve this issue?

We can see that whenever I tried to install It shows install successfully but when I run command ng new project name it stuck a long time at installing packages and give me the following error although new project runs successfully.

答:
Run command npm i -g npm@latest

Run command npm i -g @angular/cli@latest


问:
How to test if a value is not equal to any valid choices
I am trying to up the value of the int in the key-value pair in a dictionary using the name[key] syntax. What is passed into the function is a string of various sizes. I iterate over the string with the foreach method and continue to get the following error:

System.ArgumentException : Value does not fall within the expected range.

The function is as follows:

```<code>public static IDictionary<char, int> Count(string sequence)
{
    IDictionary<char, int> Dna = new Dictionary<char, int>();
    Dna.Add('A', 0);
    Dna.Add('C', 0);
    Dna.Add('G', 0);
    Dna.Add('T', 0);

    foreach(char c in sequence)
    {
        if(c != 'A' || c != 'C' || c != 'G' || c != 'T')
        {
            throw new ArgumentException();
        }
        ++Dna[c];
    }

    return Dna;
}
</code>```

The stack trace identifies the line where the string is passed into it and line 20 which is the ++Dna[c] line.

I am still learning C#, only a few days into it.

I have tried several of the solutions posted but get the same error. What do I need to learn more, to understand this concept?

This is from an exercise on another site.

答:
Your condition is wrong. It should be</p>

```<code>if(c != 'A' && c != 'C' && c != 'G' && c != 'T')
{
  throw new ArgumentException();
}
</code>```

Body:
I am trying to up the value of the int in the key-value pair in a dictionary using the name[key] syntax. What is passed into the function is a string of various sizes. I iterate over the string with the foreach method and continue to get the following error:

System.ArgumentException : Value does not fall within the expected range.

The function is as follows:

public static IDictionary<char, int> Count(string sequence)
{
    IDictionary<char, int> Dna = new Dictionary<char, int>();
    Dna.Add('A', 0);
    Dna.Add('C', 0);
    Dna.Add('G', 0);
    Dna.Add('T', 0);

    foreach(char c in sequence)
    {
        if(c != 'A' || c != 'C' || c != 'G' || c != 'T')
        {
            throw new ArgumentException();
        }
        ++Dna[c];
    }

    return Dna;
}

The stack trace identifies the line where the string is passed into it and line 20 which is the ++Dna[c] line.

I am still learning C#, only a few days into it.

I have tried several of the solutions posted but get the same error. What do I need to learn more, to understand this concept?

This is from an exercise on another site.

Body:
Your condition is wrong. It should be

if(c != 'A' && c != 'C' && c != 'G' && c != 'T')
{
  throw new ArgumentException();
}


问:
TypeError: robots.map is not a function
I keep getting this error: TypeError: robots.map is not a function.
I reviewed the code several times can't find the bug.

import React from 'react';
import Card from './Card';
// import { robots } from './robots';

const CardList = ({ robots }) => {
    return(

            {
                robots.map((user, i) => {
                    return (
                        <Card
                            key={i}
                            id={robots[i].id}
                            name={robots[i].name}
                            email={robots[i].email}
                            />
                    );
                })

            }

    );
}

export default CardList;```
</div>
</div>
</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>App.js

import React, { Component } from 'react';
import CardList from './CardList';
import SearchBox from './SearchBox';
import { robots } from './robots';

class App extends Component {
    constructor(){
        super()
        this.state = {
            robots:'robots',
                searchfield: ''}
    }
    render(){
        return(
                <div className='tc'>
                    <h1 className=''>RoboFriends</h1>
                    <SearchBox />
                    <CardList robots={this.state.robots}/>
                </div>
        );

    }

}

export default App;</code>```

I updated the initial code with App.js that calls CardList.

I recently started learning react and I hope to develop an app that lets you search for a user which instantly filters and render the name typed in the search box.

答:
You're passing a string to be mapped, instead pass the robots list of objects and see the result.
These kind of errors are the result of passing something other than a list to be mapped</p>

Title: TypeError: robots.map is not a function

Body:
I keep getting this error: TypeError: robots.map is not a function.
I reviewed the code several times can't find the bug.

import React from 'react';
import Card from './Card';
// import { robots } from './robots';

const CardList = ({ robots }) => {
    return(

            {
                robots.map((user, i) => {
                    return (
                        <Card
                            key={i}
                            id={robots[i].id}
                            name={robots[i].name}
                            email={robots[i].email}
                            />
                    );
                })

            }

    );
}

export default CardList;

App.js

import React, { Component } from 'react';
import CardList from './CardList';
import SearchBox from './SearchBox';
import { robots } from './robots';

class App extends Component {
    constructor(){
        super()
        this.state = {
            robots:'robots',
                searchfield: ''}
    }
    render(){
        return(

RoboFriends

                    <SearchBox />
                    <CardList robots={this.state.robots}/>

        );

    }

}

export default App;

I updated the initial code with App.js that calls CardList.

I recently started learning react and I hope to develop an app that lets you search for a user which instantly filters and render the name typed in the search box.


问:
Repeat and Double elements in lists in Prolog
how can I write two predicates that are described below.

1) Define the double(X,Y) predicate, which is true if the list Y contains each of the elements X
repeated twice. Example: double([a,b],[a,a,b,b]) is true.

2) Define the predicate repeat(X,Y,N), which is true if the list Y contains each of the elements X
repeated N times. For example, for the question repeat([a,b],[a,a,a,b,b,b],3), Prolog answers true.

Could you give me the example of those predicates?

答:
```<code>double([], []).
double([X|Y], [X,X|Z]) :- double(Y,Z).

remove_if_same(_,R,0,R):- !.
remove_if_same(X,[X|Y],N,R) :- Nm1 is N-1,remove_if_same(X,Y,Nm1,R).
repeat([],[],_).
repeat([X|Xr],Y,N) :- remove_if_same(X,Y,N,R), repeat(Xr,R,N).
</code>```

How double works?
If you've got two empty lists, then that is true, there is nothing to double from the first argument.

Otherwise, you're taking the head from the first list, and 2 head elements from the second list. If all these are the same (so if all are X) you're checking with recursion rest of elements, so accordingly Y and Z. So you'll check once again if lists are empty and so on, and if on any of the steps sth is not possible you return false.

About the repeat predicate, it's quite similar in reasoning.
2 things that I should explain:

The ! mark will make that the command-line interface(like swipl) will not search for other results of the remove_if_same. It would work same if we pass it to the repeat.

remove_if_same statement uses the accumulator (the 4th argument) to return at the end of the search the list without N same elements.

Body:
double([], []).
double([X|Y], [X,X|Z]) :- double(Y,Z).

remove_if_same(_,R,0,R):- !.
remove_if_same(X,[X|Y],N,R) :- Nm1 is N-1,remove_if_same(X,Y,Nm1,R).
repeat([],[],_).
repeat([X|Xr],Y,N) :- remove_if_same(X,Y,N,R), repeat(Xr,R,N).

How double works?
If you've got two empty lists, then that is true, there is nothing to double from the first argument.

Otherwise, you're taking the head from the first list, and 2 head elements from the second list. If all these are the same (so if all are X) you're checking with recursion rest of elements, so accordingly Y and Z. So you'll check once again if lists are empty and so on, and if on any of the steps sth is not possible you return false.

About the repeat predicate, it's quite similar in reasoning.
2 things that I should explain:

The ! mark will make that the command-line interface(like swipl) will not search for other results of the remove_if_same. It would work same if we pass it to the repeat.

remove_if_same statement uses the accumulator (the 4th argument) to return at the end of the search the list without N same elements.


答:
If you want to count only the characters, which are equal to any from A, C, G or T sequence and throw an error for characters outside this range, you should use conditional logical AND && operator instead of conditional logical OR || in if statement

foreach (var c in sequence)
{
    if (c != 'A' && c != 'C' && c != 'G' && c != 'T')
    {
        throw new ArgumentException();
    }
    ++Dna[c];
}
```
<p>Also, instead of throwing an error, you can use <code>continue</code> statement to process the next iteration of <code>foreach</code> loop</p>
<pre class="lang-cs prettyprint-override"><code>if (c != 'A' && c != 'C' && c != 'G' && c != 'T')
{
    continue;
}
</code>```

Title: How to test if a value is not equal to any valid choices

Body:
If you want to count only the characters, which are equal to any from A, C, G or T sequence and throw an error for characters outside this range, you should use conditional logical AND && operator instead of conditional logical OR || in if statement

foreach (var c in sequence)
{
    if (c != 'A' && c != 'C' && c != 'G' && c != 'T')
    {
        throw new ArgumentException();
    }
    ++Dna[c];
}

Also, instead of throwing an error, you can use continue statement to process the next iteration of foreach loop

if (c != 'A' && c != 'C' && c != 'G' && c != 'T')
{
    continue;
}


问:
padding-bottom doesn't work for fixed positioned div in Firefox
Here's the simple code to reproduce:

#container {
  border: 5px dashed green;
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  padding: 3em;
  overflow-y: scroll;
}

#child {
  height: 1000px;
  border: 3px dashed red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div id="child"></div>
</div></code>```

Expected behavior

Chrome works this way.

Actual behavior in Firefox

Am I missing something about CSS or this is a bug in Firefox?

答:
Try This

#container {
  border: 5px dashed green;
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  overflow-y: scroll;
}

#child {
  height: 1000px;
  margin: 3em;
  border: 3px dashed red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div id="child"></div>
</div></code>```

Body:
Here's the simple code to reproduce:

#container {
  border: 5px dashed green;
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  padding: 3em;
  overflow-y: scroll;
}

#child {
  height: 1000px;
  border: 3px dashed red;
}

Expected behavior

Chrome works this way.

Actual behavior in Firefox

Am I missing something about CSS or this is a bug in Firefox?

Body:
Try This

#container {
  border: 5px dashed green;
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  overflow-y: scroll;
}

#child {
  height: 1000px;
  margin: 3em;
  border: 3px dashed red;
}

<div id="container">
  <div id="child"></div>
</div>