问:
Rx Netty: Async client keeps getting "Content stream is already disposed" error
In the code below I'm trying to build a simple async HTTP client using Rx Netty that makes 75 POST requests to an api. The problem I'm having is that I keep getting a "java.lang.IllegalStateException: Content stream is already disposed." error.

What am I doing wrong here? Is it related to this: https://github.com/ReactiveX/RxNetty/issues/264

```<code>NioEventLoopGroup provider = new NioEventLoopGroup();

HttpClient<ByteBuf, ByteBuf> client = new HttpClientBuilder<ByteBuf, ByteBuf>("my-api.com", 80)
    .eventloop(provider)
    .build();

Gson gson = new Gson();

Observable.range(1, 75, Schedulers.from(provider))
    .flatMap(count -> {
      Data data = new Data("test" + count);

      return client.submit(
          HttpClientRequest.createPost("/create")
              .withHeader("Authorization", AUTH_HEADER)
              .withHeader("Content-Type", "application/json")
              .withContent(gson.toJson(data))
      );
    })
    .flatMap(response -> {
      return response.getContent().map((ByteBuf content) -> {
        return gson.fromJson(content.toString(Charset.defaultCharset()), OtherData.class);
      });
    })
    .subscribe(
        data -> logger.info("item done"),
        err -> {
          logger.error("Error", err);

          provider.shutdownGracefully();
        },
        () -> {
          logger.info("done");
          provider.shutdownGracefully();
        }
    );
</code>```

答:
I've realised that when you do response.getContent() it needs to be done inside a map rather than a flatMap. For example:

```<code>NioEventLoopGroup provider = new NioEventLoopGroup();

HttpClient<ByteBuf, ByteBuf> client = new HttpClientBuilder<ByteBuf,
ByteBuf>("my-api.com", 80)
.eventloop(provider)
.build();

Gson gson = new Gson();

Observable.range(1, 75, Schedulers.from(provider))
.flatMap(count -> {
  Data data = new Data("test" + count);

  return client.submit(
      HttpClientRequest.createPost("/create")
          .withHeader("Authorization", AUTH_HEADER)
          .withHeader("Content-Type", "application/json")
          .withContent(gson.toJson(data))
  );
})
// map not flatMap
.map(response -> {
  return response.getContent().map((ByteBuf content) -> {
    return gson.fromJson(content.toString(Charset.defaultCharset()), OtherData.class);
  });
})
.subscribe(
    data -> logger.info("item done"),
    err -> {
      logger.error("Error", err);

      provider.shutdownGracefully();
    },
    () -> {
      logger.info("done");
      provider.shutdownGracefully();
    }
);
</code>```

Body:
In the code below I'm trying to build a simple async HTTP client using Rx Netty that makes 75 POST requests to an api. The problem I'm having is that I keep getting a "java.lang.IllegalStateException: Content stream is already disposed." error.

What am I doing wrong here? Is it related to this: https://github.com/ReactiveX/RxNetty/issues/264

NioEventLoopGroup provider = new NioEventLoopGroup();

HttpClient<ByteBuf, ByteBuf> client = new HttpClientBuilder<ByteBuf, ByteBuf>("my-api.com", 80)
    .eventloop(provider)
    .build();

Gson gson = new Gson();

Observable.range(1, 75, Schedulers.from(provider))
    .flatMap(count -> {
      Data data = new Data("test" + count);

      return client.submit(
          HttpClientRequest.createPost("/create")
              .withHeader("Authorization", AUTH_HEADER)
              .withHeader("Content-Type", "application/json")
              .withContent(gson.toJson(data))
      );
    })
    .flatMap(response -> {
      return response.getContent().map((ByteBuf content) -> {
        return gson.fromJson(content.toString(Charset.defaultCharset()), OtherData.class);
      });
    })
    .subscribe(
        data -> logger.info("item done"),
        err -> {
          logger.error("Error", err);

          provider.shutdownGracefully();
        },
        () -> {
          logger.info("done");
          provider.shutdownGracefully();
        }
    );

Body:
I've realised that when you do response.getContent() it needs to be done inside a map rather than a flatMap. For example:

NioEventLoopGroup provider = new NioEventLoopGroup();

HttpClient<ByteBuf, ByteBuf> client = new HttpClientBuilder<ByteBuf,
ByteBuf>("my-api.com", 80)
.eventloop(provider)
.build();

Gson gson = new Gson();

Observable.range(1, 75, Schedulers.from(provider))
.flatMap(count -> {
  Data data = new Data("test" + count);

  return client.submit(
      HttpClientRequest.createPost("/create")
          .withHeader("Authorization", AUTH_HEADER)
          .withHeader("Content-Type", "application/json")
          .withContent(gson.toJson(data))
  );
})
// map not flatMap
.map(response -> {
  return response.getContent().map((ByteBuf content) -> {
    return gson.fromJson(content.toString(Charset.defaultCharset()), OtherData.class);
  });
})
.subscribe(
    data -> logger.info("item done"),
    err -> {
      logger.error("Error", err);

      provider.shutdownGracefully();
    },
    () -> {
      logger.info("done");
      provider.shutdownGracefully();
    }
);


来源: stackexchange

问:
How do I get hardware info such as CPU name, total RAM, etc. with VB6?
Title pretty much explains it all. I need to get some hardware information such as CPU info, and total RAM with VB6. Ideally, it would return something like this for the CPU:

Intel Core 2 Quad Q8500 2.66 GHz

and for the RAM something simple like an integer for the amount of MB the computer has total.

答:
RAM - GetPhysicallyInstalledSystemMemory (GlobalMemoryStatusEx on earlier versions)

CPU - GetSystemInfo (not in the desired friendly form, I'm afraid).  There is a very extensive discussion of more detailed CPU info retrieval here.

ContentLicense: CC BY-SA 2.5


问:
How to validate one dropdown if the other dropdown is not selected and vice versa?
I have a form with 2 multi select dropdowns for list of country and list of sites....

I do form validation using jQuery Validate plugin....

scenario to achieve: if one dropdown is selected then i want the form to be submitted irrespective of second dropdown selected or not....

current scenario of issue I face: even if one dropdown is selected form is not submitting..form submits only if second dropdown is selected

I came across the depends attribute inside validate function..but it is not working either....

I am trying it for my 2 dropdowns with ids list_country and list_site

below is my code:

```<code>$('#feed_form').validate({ // initialize the plugin
        rules: {
            list_country: {
                required: {
                    depends: function () { return $('#list_site').val() == null }
                }
            },
            list_site: {
                required: {
                    depends: function () { return $('#list_country').val() == null }
                }
            },
            list_trend: {
                required: true
            }
        },
        ignore: ":hidden:not(select)"
    });
</code>```

form markup (source code as it is written in YII framework in php)

```<code><form name="feed_form" id="feed_form" action="../minUser/DisplayUsers" method="post">       <div class="row">
            <div class="span3"><strong>Country:</strong></div>
            <div class="span3">
                   <select class="required multi_select" multiple="multiple" style="width:100%" onchange="js:$("#list_country_chzn").removeClass("error_container");" name="list_country[]" id="list_country">
<option value="666666">All</option>
<option value="5">xyz1</option>
<option value="5">xyz2</option>
<option value="5">xyz3</option>
<option value="5">xyz4</option>
<option value="5">xyz5</option>
<option value="5">xyz6</option>
</select>           </div>
        </div>
        <div class="row">
            <div class="span3"><strong>Site:</strong></div>
            <div class="span3">
                   <select class="required multi_select" multiple="multiple" style="width:100%" onchange="js:$("#list_site_chzn").removeClass("error_container");" name="list_site[]" id="list_site">
<option value="666666">All</option>
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
<option value="4">d</option>
</select>            </div>
        </div>
        <div class="row">
            <div class="span3"><strong>Trend:</strong></div>
            <div class="span3">
                   <select class="required" style="width:100%" name="list_trend" id="list_trend">
<option value="">--Select Trend--</option>
<option value="1">Yes</option>
<option value="2">No</option>
</select>            </div>
        </div>
        <div class="row">
            <div class="span3">
            <div class="row buttons" align="left" style="margin-top:15px;">
                <input name="search_feed_form" class="btn btn-info" onclick="return checkVerifyForm();" type="submit" value="Search" />            </div>
            </div>
        </div>
    </div>
<!--end outermost box widget-->
</form>
</code>```

答:
Your code seems to be working, unless I'm missing something.

$(function() {

  $('#mySuperCoolForm').validate({ // initialize the plugin
        rules: {
            list_country: {
                required: {
                    depends: function () { return $('#list_site').val() == null }
                }
            },
            list_site: {
                required: {
                    depends: function () { return $('#list_country').val() == null }
                }
            },
            list_trend: {
                required: true
            }
        },
        ignore: ":hidden:not(select)"
    });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<form id="mySuperCoolForm">
  <fieldset>
    <legend>Select some stuff</legend>
    <select name="list_site" id="list_site" multiple="multiple">
                <option>thing 1</option>
                <option>thing 2</option>
                <option>thing 3</option>
                <option>thing 4</option>
                <option>thing 5</option>
            </select>
    <select name="list_country" id="list_country" multiple="multiple">
                <option>thing 1</option>
                <option>thing 2</option>
                <option>thing 3</option>
                <option>thing 4</option>
                <option>thing 5</option>
            </select>
    <input type="submit" />
  </fieldset>
</form></code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a form with 2 multi select dropdowns for list of country and list of sites....

I do form validation using jQuery Validate plugin....

scenario to achieve: if one dropdown is selected then i want the form to be submitted irrespective of second dropdown selected or not....

current scenario of issue I face: even if one dropdown is selected form is not submitting..form submits only if second dropdown is selected

I came across the depends attribute inside validate function..but it is not working either....

I am trying it for my 2 dropdowns with ids list_country and list_site

below is my code:

$('#feed_form').validate({ // initialize the plugin
        rules: {
            list_country: {
                required: {
                    depends: function () { return $('#list_site').val() == null }
                }
            },
            list_site: {
                required: {
                    depends: function () { return $('#list_country').val() == null }
                }
            },
            list_trend: {
                required: true
            }
        },
        ignore: ":hidden:not(select)"
    });

form markup (source code as it is written in YII framework in php)

<form name="feed_form" id="feed_form" action="../minUser/DisplayUsers" method="post">

Country:

                   <select class="required multi_select" multiple="multiple" style="width:100%" onchange="js:$("#list_country_chzn").removeClass("error_container");" name="list_country[]" id="list_country">
<option value="666666">All</option>
<option value="5">xyz1</option>
<option value="5">xyz2</option>
<option value="5">xyz3</option>
<option value="5">xyz4</option>
<option value="5">xyz5</option>
<option value="5">xyz6</option>
</select>

Site:

                   <select class="required multi_select" multiple="multiple" style="width:100%" onchange="js:$("#list_site_chzn").removeClass("error_container");" name="list_site[]" id="list_site">
<option value="666666">All</option>
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
<option value="4">d</option>
</select>

Trend:

                   <select class="required" style="width:100%" name="list_trend" id="list_trend">
<option value="">--Select Trend--</option>
<option value="1">Yes</option>
<option value="2">No</option>
</select>

                <input name="search_feed_form" class="btn btn-info" onclick="return checkVerifyForm();" type="submit" value="Search" />

</form>

Body:
Your code seems to be working, unless I'm missing something.

$(function() {

  $('#mySuperCoolForm').validate({ // initialize the plugin
        rules: {
            list_country: {
                required: {
                    depends: function () { return $('#list_site').val() == null }
                }
            },
            list_site: {
                required: {
                    depends: function () { return $('#list_country').val() == null }
                }
            },
            list_trend: {
                required: true
            }
        },
        ignore: ":hidden:not(select)"
    });

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<form id="mySuperCoolForm">
  <fieldset>
    <legend>Select some stuff</legend>
    <select name="list_site" id="list_site" multiple="multiple">
                <option>thing 1</option>
                <option>thing 2</option>
                <option>thing 3</option>
                <option>thing 4</option>
                <option>thing 5</option>
            </select>
    <select name="list_country" id="list_country" multiple="multiple">
                <option>thing 1</option>
                <option>thing 2</option>
                <option>thing 3</option>
                <option>thing 4</option>
                <option>thing 5</option>
            </select>
    <input type="submit" />
  </fieldset>
</form>


问:
Assign value to optional dictionary in Swift
I'm finding some surprising behavior with optional dictionaries in Swift.

```<code>var foo:Dictionary<String, String>?

if (foo == nil) {
    foo = ["bar": "baz"]
}
else {
    // Following line errors with "'Dictionary<String, String>?' does
    // not have a member named 'subscript'"
    foo["qux"] = "quux"
}
</code>```

I've played with this a lot, trying to figure out what I might be missing, but nothing seems to make this code work as expected short of making the dictionary not optional. What am I missing?

The closest I can get is the following, but of course it's ridiculous.

```<code>var foo:Dictionary<String, String>?

if (foo == nil) {
    foo = ["bar": "baz"]
}
else if var foofoo = foo {
    foofoo["qux"] = "quux"
    foo = foofoo
}
</code>```

答:
This is because your Dictionary is optional. If it's nil, you won't add an entry to it.

You can do this way:

```<code>var dict: [String : String]?
if let dict = dict {
  dict["key"] = "value" // add a value to an existing dictionary
} else {
  dict = ["key" : "value"] // create a dictionary with this value in it
}
</code>```

Or, if you are given an optional dictionary, for example HTTPHeaders - which in AlamoFire is a [String : String] dictionary - and you want to either add a value if it's non-nil, or create it with this value if it's nil, you could do like so:

```<code>let headers: HTTPHeaders? // this is an input parameter in a function for example

var customHeaders: HTTPHeaders = headers ?? [:] // nil coalescing
customHeaders["key"] = "value"
</code>```

Body:
I'm finding some surprising behavior with optional dictionaries in Swift.

var foo:Dictionary<String, String>?

if (foo == nil) {
    foo = ["bar": "baz"]
}
else {
    // Following line errors with "'Dictionary<String, String>?' does
    // not have a member named 'subscript'"
    foo["qux"] = "quux"
}

I've played with this a lot, trying to figure out what I might be missing, but nothing seems to make this code work as expected short of making the dictionary not optional. What am I missing?

The closest I can get is the following, but of course it's ridiculous.

var foo:Dictionary<String, String>?

if (foo == nil) {
    foo = ["bar": "baz"]
}
else if var foofoo = foo {
    foofoo["qux"] = "quux"
    foo = foofoo
}

Body:
This is because your Dictionary is optional. If it's nil, you won't add an entry to it.

You can do this way:

var dict: [String : String]?
if let dict = dict {
  dict["key"] = "value" // add a value to an existing dictionary
} else {
  dict = ["key" : "value"] // create a dictionary with this value in it
}

Or, if you are given an optional dictionary, for example HTTPHeaders - which in AlamoFire is a [String : String] dictionary - and you want to either add a value if it's non-nil, or create it with this value if it's nil, you could do like so:

let headers: HTTPHeaders? // this is an input parameter in a function for example

var customHeaders: HTTPHeaders = headers ?? [:] // nil coalescing
customHeaders["key"] = "value"


问:
Simple docker containers: Build dedicated image or mount config as volume?
I'm putting together a docker-compose.yml file to run the multiple services for a project I'm working on. This project has a Magento and Wordpress website residing under the same domain, with that "same domain" aspect requiring a very simple nginx container to route requests to either service.

So I have this architected as 4 containers (visualisation):

A "magento" container, using an in-house project-specific image.

A "wordpress" container, using an in-house project-specific image.

A "db" container running mysql:5.6, with the init db dumps mounted at /docker-entrypoint-initdb.d.

A "router" container running nginx:alpine with a custom config mounted at /etc/nginx/nginx.conf. This functions as a reverse-proxy with two location directives set up. location / routes to "magento", and location /blog routes to "wordpress".

I want to keep things simple and avoid building unnecessary custom images, but in the context of the "router" I'm not sure what I'm doing is the best approach, or if that would be better off as a project-specific image.

I'm leaning toward my current approach of mounting a custom config into the nginx:alpine container, because the configuration is specific to the stack that's running – it wouldn't make sense as a single standalone container.

So the two methods, without a custom image we have the following in docker-compose.yml

```<code>      router:
        image: nginx:alpine
        networks:
          - projectnet
        ports:
          - "80:80"
        volumes:
           - "./router/nginx.conf:/etc/nginx/nginx.conf"
</code>```

Otherwise, we have a Dockerfile containing the following, as I've seen suggested across the internet and in other StackOverflow responses.

```<code>    FROM nginx:alpine

    ADD nginx.conf /etc/nginx/
</code>```

Does anybody have arguments for/against either approach?

答:
If you 'bake in' the nginx config (your second approach)

```<code>ADD nginx.conf /etc/nginx/
</code>```

it makes your docker containers more portable - i.e. they can be downloaded and run on any server capable of running docker and it will just work.

If you use option 1, mounting the config file at run time, then you are transferring one of your dependencies to outside of your container. This makes it a dependency that must be managed outside of docker.

In my opinion it is best to put as many dependencies inside your dockerfiles as possible because it makes them more portable and more automated (great for CI Pipelines for example)

There are reasons for mounting files at run time and these are usually centred around environmentally specific settings (although these can largely be overcome within docker too) or 'sensitive' files that application developers shouldn't or couldn't have access to. For example ssl certificates, database passwords, etc

Body:
I'm putting together a docker-compose.yml file to run the multiple services for a project I'm working on. This project has a Magento and Wordpress website residing under the same domain, with that "same domain" aspect requiring a very simple nginx container to route requests to either service.

So I have this architected as 4 containers (visualisation):

A "magento" container, using an in-house project-specific image.

A "wordpress" container, using an in-house project-specific image.

A "db" container running mysql:5.6, with the init db dumps mounted at /docker-entrypoint-initdb.d.

A "router" container running nginx:alpine with a custom config mounted at /etc/nginx/nginx.conf. This functions as a reverse-proxy with two location directives set up. location / routes to "magento", and location /blog routes to "wordpress".

I want to keep things simple and avoid building unnecessary custom images, but in the context of the "router" I'm not sure what I'm doing is the best approach, or if that would be better off as a project-specific image.

I'm leaning toward my current approach of mounting a custom config into the nginx:alpine container, because the configuration is specific to the stack that's running – it wouldn't make sense as a single standalone container.

So the two methods, without a custom image we have the following in docker-compose.yml

      router:
        image: nginx:alpine
        networks:
          - projectnet
        ports:
          - "80:80"
        volumes:
           - "./router/nginx.conf:/etc/nginx/nginx.conf"

Otherwise, we have a Dockerfile containing the following, as I've seen suggested across the internet and in other StackOverflow responses.

    FROM nginx:alpine

    ADD nginx.conf /etc/nginx/

Does anybody have arguments for/against either approach?

Body:
If you 'bake in' the nginx config (your second approach)

ADD nginx.conf /etc/nginx/

it makes your docker containers more portable - i.e. they can be downloaded and run on any server capable of running docker and it will just work.

If you use option 1, mounting the config file at run time, then you are transferring one of your dependencies to outside of your container. This makes it a dependency that must be managed outside of docker.

In my opinion it is best to put as many dependencies inside your dockerfiles as possible because it makes them more portable and more automated (great for CI Pipelines for example)

There are reasons for mounting files at run time and these are usually centred around environmentally specific settings (although these can largely be overcome within docker too) or 'sensitive' files that application developers shouldn't or couldn't have access to. For example ssl certificates, database passwords, etc


问:
No unique service maching interface error in Spring Boot Cloud Foundry error
I am trying to follow this tutorial https://github.com/cf-platform-eng/spring-boot-cities/tree/master/cities-service to run my spring boot application in Cloud Foundry. I have local bosh-lite installation

My Spring Boot application connects to postgresql as database. I am trying to connect to the Postgresql instance running on my local (host machine )

My application works fine locally if deployed to a local tomcat.
But when i deploy the app to bosh-lite it fails with the following error "No unique service maching interface error ". My code is excatly the same as what is mentioned in the tutorial except i am using Maven to build my code.

```<code>    2017-06-07T22:29:54.44+0530 [App/0] OUT Caused by: org.springframework.cloud.CloudException: No unique service matching interface javax.sql.DataSource found. Expected 1, found 0
2017-06-07T22:29:54.44+0530 [App/0] OUT     at org.springframework.cloud.Cloud.getSingletonServiceConnector(Cloud.java:149) ~[spring-cloud-core-1.2.3.RELEASE.jar!/:na]
2017-06-07T22:29:54.44+0530 [App/0] OUT     at org.saurav.cf.casestudy.employee.db.DataSourceConfiguration.dataSource(DataSourceConfiguration.java:20) ~[classes/:na]
2017-06-07T22:29:54.44+0530 [App/0] OUT     at org.saurav.cf.casestudy.employee.db.DataSourceConfiguration$$EnhancerBySpringCGLIB$$847aab5e.CGLIB$dataSource$0(<generated>) ~[classes/:na]
2017-06-07T22:29:54.44+0530 [App/0] OUT     at org.saurav.cf.casestudy.employee.db.DataSourceConfiguration$$EnhancerBySpringCGLIB$$847aab5e$$FastClassBySpringCGLIB$$2ad81e2b.invoke(<generated>) ~[classes/:na]
2017-06-07T22:29:54.44+0530 [App/0] OUT     at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.3.8.RELEASE.jar!/:4.3.8.RELEASE]
2017-06-07T22:29:54.44+0530 [App/0] OUT     at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358) ~[spring-context-4.3.8.RELEASE.jar!/:4.3.8.RELEASE]
2017-06-07T22:29:54.44+0530 [App/0] OUT     at org.saurav.cf.casestudy.employee.db.DataSourceConfiguration$$EnhancerBySpringCGLIB$$847aab5e.dataSource(<generated>) ~[classes/:na]
2017-06-07T22:29:54.44+0530 [App/0] OUT     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]
</code>```

My connection to postgres works fine. And the same app works fine if i don't use spring cloud connector and read the value normally from application.properties.

My pom.xml`(Has dependencies for spring boot cloud connector and postgrsql driver )

```<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.saurav.cf.casestudy</groupId>
    <artifactId>employeerest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>employeerest</name>
    <description>Demo project for Spring Boot</description>

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

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <!--  <start-class>org.saurav.cf.casestudy.employee.EmployeerestApplication</start-class> -->
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-hateoas</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

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

</dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>

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

<dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.14</version>
      </dependency>

    </dependencies>

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

</project>
</code>```

`

[UPDATE]
as per Scott's answers below i had a look at the requirements for a UPS to be picked up cloud connector.Since mine is an user provided provided service so i cannot have tags and label. But i added the jdbc urls.
Now my app is failing with the below error

```<code> Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
</code>```

For this i have set "spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect"  in my application.properties but still it does not work

I have also checked that my DB is running and db settings in my service instance is correct.

Below is my service instance content`

```<code>"VCAP_SERVICES": {
  "user-provided": [
   {
    "credentials": {
     "jdbcUrl": "jdbc:postgresql://10.0.2.2:5432/employee",
     "username": "postgres",
     "password": "admin",
     "postgresUri": "postgresql://10.0.2.2:5432/employee",
     "uri": "postgresql://10.0.2.2:5432/employee"
    },
    "label": "user-provided",
    "name": "postgresql-cf-service",
    "syslog_drain_url": "",
    "tags": [],
    "volume_mounts": []
   }
  ]
 }
</code>```

`
Best Regards,
Saurav

答:
Just to summarize the overall solution for other readers.

If you have a scenario where you want to have a spring boot application talk to a database (hosted in other machine) and then run the application from cloud foundry. Then follow some of the tips below.

Once you deploy your Spring Boot application and want to use Spring Boot cloud connector make sure you have all the proper dependencies in your classpath (spring-boot-cloud-connector and  jar.

If you want to bind a service instance with the application .Make sure the credentials adhere to this specification http://cloud.spring.io/spring-cloud-connectors/spring-cloud-cloud-foundry-connector.html#_postgresql

In the service instance parameters make sure you use the uri parameter not depend on the username and password to construct the uri

Make sure your database instance is actually running and you have created application service groups to allow outbound communication from your cloud foundry app. https://docs.cloudfoundry.org/concepts/asg.html#viewing

Steps 3 and 4 were the mistakes i made. Once corrected the application works fine.

Best Regards,
Saurav

Body:
I am trying to follow this tutorial https://github.com/cf-platform-eng/spring-boot-cities/tree/master/cities-service to run my spring boot application in Cloud Foundry. I have local bosh-lite installation

My Spring Boot application connects to postgresql as database. I am trying to connect to the Postgresql instance running on my local (host machine )

My application works fine locally if deployed to a local tomcat.
But when i deploy the app to bosh-lite it fails with the following error "No unique service maching interface error ". My code is excatly the same as what is mentioned in the tutorial except i am using Maven to build my code.

    2017-06-07T22:29:54.44+0530 [App/0] OUT Caused by: org.springframework.cloud.CloudException: No unique service matching interface javax.sql.DataSource found. Expected 1, found 0
2017-06-07T22:29:54.44+0530 [App/0] OUT     at org.springframework.cloud.Cloud.getSingletonServiceConnector(Cloud.java:149) ~[spring-cloud-core-1.2.3.RELEASE.jar!/:na]
2017-06-07T22:29:54.44+0530 [App/0] OUT     at org.saurav.cf.casestudy.employee.db.DataSourceConfiguration.dataSource(DataSourceConfiguration.java:20) ~[classes/:na]
2017-06-07T22:29:54.44+0530 [App/0] OUT     at org.saurav.cf.casestudy.employee.db.DataSourceConfiguration$$EnhancerBySpringCGLIB$$847aab5e.CGLIB$dataSource$0(<generated>) ~[classes/:na]
2017-06-07T22:29:54.44+0530 [App/0] OUT     at org.saurav.cf.casestudy.employee.db.DataSourceConfiguration$$EnhancerBySpringCGLIB$$847aab5e$$FastClassBySpringCGLIB$$2ad81e2b.invoke(<generated>) ~[classes/:na]
2017-06-07T22:29:54.44+0530 [App/0] OUT     at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.3.8.RELEASE.jar!/:4.3.8.RELEASE]
2017-06-07T22:29:54.44+0530 [App/0] OUT     at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358) ~[spring-context-4.3.8.RELEASE.jar!/:4.3.8.RELEASE]
2017-06-07T22:29:54.44+0530 [App/0] OUT     at org.saurav.cf.casestudy.employee.db.DataSourceConfiguration$$EnhancerBySpringCGLIB$$847aab5e.dataSource(<generated>) ~[classes/:na]
2017-06-07T22:29:54.44+0530 [App/0] OUT     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_131]

My connection to postgres works fine. And the same app works fine if i don't use spring cloud connector and read the value normally from application.properties.

My pom.xml`(Has dependencies for spring boot cloud connector and postgrsql driver )

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.saurav.cf.casestudy</groupId>
    <artifactId>employeerest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>employeerest</name>
    <description>Demo project for Spring Boot</description>

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

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>

    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-hateoas</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

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

</dependency>

        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>

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

<dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.14</version>
      </dependency>

    </dependencies>

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

</project>

`

[UPDATE]
as per Scott's answers below i had a look at the requirements for a UPS to be picked up cloud connector.Since mine is an user provided provided service so i cannot have tags and label. But i added the jdbc urls.
Now my app is failing with the below error

 Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

For this i have set "spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect"  in my application.properties but still it does not work

I have also checked that my DB is running and db settings in my service instance is correct.

Below is my service instance content`

"VCAP_SERVICES": {
  "user-provided": [
   {
    "credentials": {
     "jdbcUrl": "jdbc:postgresql://10.0.2.2:5432/employee",
     "username": "postgres",
     "password": "admin",
     "postgresUri": "postgresql://10.0.2.2:5432/employee",
     "uri": "postgresql://10.0.2.2:5432/employee"
    },
    "label": "user-provided",
    "name": "postgresql-cf-service",
    "syslog_drain_url": "",
    "tags": [],
    "volume_mounts": []
   }
  ]
 }

`
Best Regards,
Saurav


问:
Angular 2 ng-required
I made a model-driven form in angular 2, and one of the input fields must show up only if a checkbox above is unchecked.I did this with *ngIf.
My question is how can I set that input required only if the checkbox is unchecked? In angular 1.x i could make this happen with the ng-required="condition" in the view.

Here is the html:

//the checkbox

```<code><div class="checkbox col-sm-9">
   <label>
     <input type="checkbox"  id="getCompanyAddress" style="cursor: pointer;" [formControl]="form.controls['address']" >Use the company address
  </label>
</div>
</code>```

// the option input:

```<code><div *ngIf="form.value.address == false" class="form-group" [ngClass] = "{'has-error':!form.controls['address'].valid && form.controls['address'].touched}" >
 <label for="add_gestion_adress" class="col-sm-3 control-label">Address
 </label>
  <div class="col-sm-9"><textarea rows="1" id="add_gestion_adress" class="form-control" name="add_gestion_adress" [formControl]="form.controls['address']" ></textarea>
  </div>
</div>
</code>```

//and the model code:

```<code>   form: FormGroup;
    constructor(fb:FormBuilder){
      this.form = fb.group({
        'name': [null,Validators.compose([Validators.required, Validators.minLength(1)])],
        'type': ["en gros",Validators.compose([Validators.required, Validators.minLength(2)])],
        'person':[null,Validators.compose([Validators.required, Validators.minLength(1)])],
        'address':[false,Validators.compose([Validators.minLength(1)])],
        'locality':[null, Validators.compose([Validators.required])],
        'county':[null,Validators.compose([Validators.required])],
        'country':[null,Validators.compose([Validators.required])]
      })

    }
</code>```

答:
```<code><textarea [required]="your angular expression">
</code>```

The above works in the latest version of Angular 4

Title: Angular 2 ng-required

Body:
I made a model-driven form in angular 2, and one of the input fields must show up only if a checkbox above is unchecked.I did this with *ngIf.
My question is how can I set that input required only if the checkbox is unchecked? In angular 1.x i could make this happen with the ng-required="condition" in the view.

Here is the html:

//the checkbox

     <input type="checkbox"  id="getCompanyAddress" style="cursor: pointer;" [formControl]="form.controls['address']" >Use the company address

// the option input:

 Address

<textarea rows="1" id="add_gestion_adress" class="form-control" name="add_gestion_adress" [formControl]="form.controls['address']" ></textarea>

//and the model code:

   form: FormGroup;
    constructor(fb:FormBuilder){
      this.form = fb.group({
        'name': [null,Validators.compose([Validators.required, Validators.minLength(1)])],
        'type': ["en gros",Validators.compose([Validators.required, Validators.minLength(2)])],
        'person':[null,Validators.compose([Validators.required, Validators.minLength(1)])],
        'address':[false,Validators.compose([Validators.minLength(1)])],
        'locality':[null, Validators.compose([Validators.required])],
        'county':[null,Validators.compose([Validators.required])],
        'country':[null,Validators.compose([Validators.required])]
      })

    }

Body:
<textarea [required]="your angular expression">

The above works in the latest version of Angular 4


问:
Is there an "exists" function for jQuery?
How can I check the existence of an element in jQuery?

The current code that I have is this:

```<code>if ($(selector).length > 0) {
    // Do something
}
</code>```

Is there a more elegant way to approach this? Perhaps a plugin or a function?

答:
If you used

```<code>jQuery.fn.exists = function(){return ($(this).length > 0);}
if ($(selector).exists()) { }
</code>```

you would imply that chaining was possible when it is not.

This would be better:

```<code>jQuery.exists = function(selector) {return ($(selector).length > 0);}
if ($.exists(selector)) { }
</code>```

Alternatively, from the FAQ:

```<code>if ( $('#myDiv').length ) { /* Do something */ }
</code>```

You could also use the following. If there are no values in the jQuery object array then getting the first item in the array would return undefined.

```<code>if ( $('#myDiv')[0] ) { /* Do something */ }
</code>```

OwnerDisplayName: gomercobs

Body:
How can I check the existence of an element in jQuery?

The current code that I have is this:

if ($(selector).length > 0) {
    // Do something
}

Is there a more elegant way to approach this? Perhaps a plugin or a function?

LastEditorDisplayName: gomercobs

Body:
If you used

jQuery.fn.exists = function(){return ($(this).length > 0);}
if ($(selector).exists()) { }

you would imply that chaining was possible when it is not.

This would be better:

jQuery.exists = function(selector) {return ($(selector).length > 0);}
if ($.exists(selector)) { }

Alternatively, from the FAQ:

if ( $('#myDiv').length ) { /* Do something */ }

You could also use the following. If there are no values in the jQuery object array then getting the first item in the array would return undefined.

if ( $('#myDiv')[0] ) { /* Do something */ }

OwnerDisplayName: Jon Erickson

LastEditorDisplayName: Jon Erickson


问:
Does a foreign key reduce redundancy if all the columns are referenced?
I've read that one of the benefits of normalization is to reduce redundancy in the DB. But I'm wondering, if you end up referencing all the columns in the target table?

For example, if I have a Video table that references a Genre table, the Genre table might very likely have a single column with a dozen fairly static values like 'Horror' 'Sci-Fi' 'Romance' etc.

In a case like this, does it save any space to separate the two, or is the only benefit making it so you can update all referencing rows from one place?

答:
Saving space is one benefit to separating the 2 tables.  Like it was said before, putting a Genre_ID in place of an actual value such as "Horror" or "Adventure" will save space.

In my opinion, the better part of doing this to to enforce integrity.  If you put in the text values in the Video table, what prevents you from changing the value accidentally?  Now some rows may have "Adventure" or "Action/Adventure" and so on.  By having 2 tables and referencing with a foreign key, you're going to have better control over what values can be a genre.

In summary, don't worry about the fact that you reference all the columns, especially if a table has very few columns.  If you decide to add an ID field, or just keep the 1 column table as a list of "acceptable values", your goal should be to enforce integrity first, and save space or I/O costs second.


问:
Numbers bigger than 8 bytes in C
I am writing some code to deal with numbers in C which are bigger than 8 bytes in size (don't fit into unsigned long). In this example I will use 16 bytes (128 bits) as the width. The numbers are unsigned and integers (no decimal places). They are stored as an array of unsigned chars eg:

```<code>unsigned char n[16];
</code>```

I have managed to get addition to work (it works like an unsigned number in C so if you had a number which was 0xffffffffffffffffffffffffffffffff (2**128) and you were to add 1 you would get 0. I have managed to get addition to work, but I cannot get subtraction to work. I would assume it would be similar code to addition, but I don't seem to be able to get it to work.

Addition code:

```<code>//a and b are numbers
unsigned char *add(unsigned char *a, unsigned char *b){
    unsigned char *c = malloc(NUM_SIZE);
    //d is the carry and c is the output number
    unsigned short d = 0;

    if(!c){
        return NULL;
    }
    for(int i = 0; i < NUM_SIZE; i++){
        c[i] = 0;
    }
    for(int i = NUM_SIZE * 2 - 1; i >= 0; i--){
        d += a[i % NUM_SIZE] + b[i % NUM_SIZE];
        c[i % NUM_SIZE] = d % 256;
        d >>= 8;
    }
    return c;
}
</code>```

NUM_SIZE is defined as 16 (the width of the number in bytes)

What I have tried:

```<code>//changing the signs to minuses
d -= a[i % NUM_SIZE] - b[i % NUM_SIZE];

//changing the some signs to minuses
d -= a[i % NUM_SIZE] + b[i % NUM_SIZE];
//or
d += a[i % NUM_SIZE] - b[i % NUM_SIZE];

//looping through the number backwards
for(int i = 0; i < NUM_SIZE * 2; i++)
</code>```

答:
There may be some __int128_t. But if your compiler does not support it you define a struct with hi and lo with the biggest type you have. In c++ you can also add operators similar to the operators you know from the other int_t-s.

```<code>typedef struct uint128 {
    uint64_t lo, hi; // lo comes first if you want to use little-endian else hi comes first
} uint128_t;
</code>```

If you want to double the size, you use uint128_t in a similar struct.

Edit:
A simple function to increase the int128:

```<code>int128_t& int128_increase(int128_t& value) {
    // increase the low part, it is 0 if it was overflown
    // so increase hi
    if (!(++value.lo)) {
        ++value.hi;
    };
    return value;
};
</code>```

Edit:
A runtime scaled version of ints, I use words, because it is faster in accessing memory:

```<code>typedef struct uint_dynamic {
    // the length as a multiple of the wordsize
    size_t length;
    size_t* words;
} uint_dynamic_t;

uint_dynamic_t& uint_dynamic_increase(uint_dynamic_t& value) {
    size_t* ptr = value.words; size_t i = value.length;
    while(i && !(++*ptr)) { ++ptr; --i; };
    return value;
};
</code>```

Or if you want some constant size, put it clearly into a struct.

```<code>#define uint_fixed_SIZE (16 / sizeof(size_t))
typedef struct uint_fixed {
    size_t words[uint_fixed_SIZE];
} uint_fixed_t;

uint_fixed_t& uint_fixed_increase(uint_fixed_t& value) {
    size_t* ptr = value.words; size_t i = uint_fixed_SIZE;
    while(i && !(++*ptr)) { ++ptr; --i; };
    return value;
};
</code>```

This can be rewritten as a #define-macro, where you replace the specific values by a parameter. Which has similar functionality, by defining specific values and including a file:

File fixed_int.h

```<code>// note that here is no #ifndef FILE_H or #pragma once
// to reuse the file

#define _concat1(a, b) a ## b
#define _concat(a, b) _concat1(a, b)
#define _size (-((-fixed_int_size) / sizeof(size_t) / 8))
#ifndef fixed_int_name
    #define _name concat(uint_, fixed_int_size)
#else
    #define _name fixed_int_name
#endif
#define _name_(member) _concat(_concat(_name, _), member)

typedef struct _name {
    size_t words[_size];
} _name_(t);

_name_(t)& _name_(increase)(_name_(t)& value) {
    size_t* ptr = value.words; size_t i = _size;
    while(i && !(++*ptr)) { ++ptr; --i; };
    return value;
};

// undef all defines!
#undef _concat1
#undef _concat
#undef _size
#undef _name
#undef _name_
</code>```

File my_ints.h

```<code>//...

// the following lines define the type uint128_t and the function uint_128_t& uint128_increase(uint128_t&)
#define fixed_int_name uint128 // is optional
#define fixed_int_size 128
#include"fixed_int.h"
#undef fixed_int_size
#undef fixed_int_name

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

Title: Numbers bigger than 8 bytes in C

Body:
I am writing some code to deal with numbers in C which are bigger than 8 bytes in size (don't fit into unsigned long). In this example I will use 16 bytes (128 bits) as the width. The numbers are unsigned and integers (no decimal places). They are stored as an array of unsigned chars eg:

unsigned char n[16];

I have managed to get addition to work (it works like an unsigned number in C so if you had a number which was 0xffffffffffffffffffffffffffffffff (2**128) and you were to add 1 you would get 0. I have managed to get addition to work, but I cannot get subtraction to work. I would assume it would be similar code to addition, but I don't seem to be able to get it to work.

Addition code:

//a and b are numbers
unsigned char *add(unsigned char *a, unsigned char *b){
    unsigned char *c = malloc(NUM_SIZE);
    //d is the carry and c is the output number
    unsigned short d = 0;

    if(!c){
        return NULL;
    }
    for(int i = 0; i < NUM_SIZE; i++){
        c[i] = 0;
    }
    for(int i = NUM_SIZE * 2 - 1; i >= 0; i--){
        d += a[i % NUM_SIZE] + b[i % NUM_SIZE];
        c[i % NUM_SIZE] = d % 256;
        d >>= 8;
    }
    return c;
}

NUM_SIZE is defined as 16 (the width of the number in bytes)

What I have tried:

//changing the signs to minuses
d -= a[i % NUM_SIZE] - b[i % NUM_SIZE];

//changing the some signs to minuses
d -= a[i % NUM_SIZE] + b[i % NUM_SIZE];
//or
d += a[i % NUM_SIZE] - b[i % NUM_SIZE];

//looping through the number backwards
for(int i = 0; i < NUM_SIZE * 2; i++)

Body:
There may be some __int128_t. But if your compiler does not support it you define a struct with hi and lo with the biggest type you have. In c++ you can also add operators similar to the operators you know from the other int_t-s.

typedef struct uint128 {
    uint64_t lo, hi; // lo comes first if you want to use little-endian else hi comes first
} uint128_t;

If you want to double the size, you use uint128_t in a similar struct.

Edit:
A simple function to increase the int128:

int128_t& int128_increase(int128_t& value) {
    // increase the low part, it is 0 if it was overflown
    // so increase hi
    if (!(++value.lo)) {
        ++value.hi;
    };
    return value;
};

Edit:
A runtime scaled version of ints, I use words, because it is faster in accessing memory:

typedef struct uint_dynamic {
    // the length as a multiple of the wordsize
    size_t length;
    size_t* words;
} uint_dynamic_t;

uint_dynamic_t& uint_dynamic_increase(uint_dynamic_t& value) {
    size_t* ptr = value.words; size_t i = value.length;
    while(i && !(++*ptr)) { ++ptr; --i; };
    return value;
};

Or if you want some constant size, put it clearly into a struct.

#define uint_fixed_SIZE (16 / sizeof(size_t))
typedef struct uint_fixed {
    size_t words[uint_fixed_SIZE];
} uint_fixed_t;

uint_fixed_t& uint_fixed_increase(uint_fixed_t& value) {
    size_t* ptr = value.words; size_t i = uint_fixed_SIZE;
    while(i && !(++*ptr)) { ++ptr; --i; };
    return value;
};

This can be rewritten as a #define-macro, where you replace the specific values by a parameter. Which has similar functionality, by defining specific values and including a file:

File fixed_int.h

// note that here is no #ifndef FILE_H or #pragma once
// to reuse the file

#define _concat1(a, b) a ## b
#define _concat(a, b) _concat1(a, b)
#define _size (-((-fixed_int_size) / sizeof(size_t) / 8))
#ifndef fixed_int_name
    #define _name concat(uint_, fixed_int_size)
#else
    #define _name fixed_int_name
#endif
#define _name_(member) _concat(_concat(_name, _), member)

typedef struct _name {
    size_t words[_size];
} _name_(t);

_name_(t)& _name_(increase)(_name_(t)& value) {
    size_t* ptr = value.words; size_t i = _size;
    while(i && !(++*ptr)) { ++ptr; --i; };
    return value;
};

// undef all defines!
#undef _concat1
#undef _concat
#undef _size
#undef _name
#undef _name_

File my_ints.h

//...

// the following lines define the type uint128_t and the function uint_128_t& uint128_increase(uint128_t&)
#define fixed_int_name uint128 // is optional
#define fixed_int_size 128
#include"fixed_int.h"
#undef fixed_int_size
#undef fixed_int_name

//...


问:
Add Date and Time Values? & how to query from one query's results into another query
What I would like to accomplish is updating this query to be able to auto pull the the current day like  getdate function perhaps, so that the date wouldn't have to be manually updated daily.

```<code>use n

select id, type, name, log_time , start_time , documents_created , pages_created, processed, processed_time
from N_LF_OCR_LOG
where
--name like 'C-INV00410249%' -- CI11667474 (6).pdf'
log_time between  '2017-3-07 00:00:00.000' and '2017-3-07 23:59:00.000'
and documents_created <> 0
or  ( documents_created is null and log_time between '2017-3-07 00:00:00.000' and '2017-3-07 23:59:00.000'  )
order by log_time
</code>```

Then from the executed results, I'd like another query to query those results to show when:
Any Results from the TYPE column > named 'email ocr in type & universal production’
where the ‘documents_created & pages_created’ numbers do not match. (see picture below)

Also report if following those rows ‘NULL’ file is missing or less than 7 files.

答:
Here is a good way to create a test case when you post on SO.
Link to your SQL query I modified your AND/OR boolean logic to what I believe you were trying to accomplish and added comments as well.

Adding the current date to the filters is done through the expressions:

Midnight of today is created by converting getdate() to a date which drops the time portion

CONVERT(date, getdate())

11:59PM of today is a little more complex, but basically converting a datetime to the float representation, dropping the time portion and adding the specific time of '23:59' back to it

CONVERT(datetime,floor(CONVERT(float,getdate()))) + '23:59:00'

Part 2, I don't believe you need to create another query on top of the results to get what you are looking for.  You can simply add the additional conditions and you will be able to filter to the types you want with the created filters as well.

If you do want to query your results over again, you need to create a WITH clause and then you can perform the "second" query like this:

```<code>-- first query
WITH my_subquery as (
    SELECT 1 as num
    FROM tbl)

-- second query
SELECT max(num)
FROM my_subquery
</code>```

EDIT
As requested, here is a link to the first query (without type filter and page created filter) and here is a link to the second query (with type filter and page created filter).

Body:
What I would like to accomplish is updating this query to be able to auto pull the the current day like  getdate function perhaps, so that the date wouldn't have to be manually updated daily.

use n

select id, type, name, log_time , start_time , documents_created , pages_created, processed, processed_time
from N_LF_OCR_LOG
where
--name like 'C-INV00410249%' -- CI11667474 (6).pdf'
log_time between  '2017-3-07 00:00:00.000' and '2017-3-07 23:59:00.000'
and documents_created <> 0
or  ( documents_created is null and log_time between '2017-3-07 00:00:00.000' and '2017-3-07 23:59:00.000'  )
order by log_time

Then from the executed results, I'd like another query to query those results to show when:
Any Results from the TYPE column > named 'email ocr in type & universal production’
where the ‘documents_created & pages_created’ numbers do not match. (see picture below)

Also report if following those rows ‘NULL’ file is missing or less than 7 files.

Body:
Here is a good way to create a test case when you post on SO.
Link to your SQL query I modified your AND/OR boolean logic to what I believe you were trying to accomplish and added comments as well.

Adding the current date to the filters is done through the expressions:

Midnight of today is created by converting getdate() to a date which drops the time portion

CONVERT(date, getdate())

11:59PM of today is a little more complex, but basically converting a datetime to the float representation, dropping the time portion and adding the specific time of '23:59' back to it

CONVERT(datetime,floor(CONVERT(float,getdate()))) + '23:59:00'

Part 2, I don't believe you need to create another query on top of the results to get what you are looking for.  You can simply add the additional conditions and you will be able to filter to the types you want with the created filters as well.

If you do want to query your results over again, you need to create a WITH clause and then you can perform the "second" query like this:

-- first query
WITH my_subquery as (
    SELECT 1 as num
    FROM tbl)

-- second query
SELECT max(num)
FROM my_subquery

EDIT
As requested, here is a link to the first query (without type filter and page created filter) and here is a link to the second query (with type filter and page created filter).


问:
Check if something in a dictionary is the same as the max value in that dictionary?
How can I check if something in a dictionary is the same as the max in that dictionary. In other words, get all the max values instead of the max value with lowest position.
I have this code which returns the max variable name and value:

```<code>d = {'g_dirt4': g_dirt4, 'g_destiny2': g_destiny2, 'g_southpark': g_southpark, 'g_codww2': g_codww2, 'g_bfront2': g_bfront2, 'g_reddead2': g_reddead2, 'g_fifa18': g_fifa18, 'g_motogp17': g_motogp17, 'g_elderscrolls': g_elderscrolls, 'g_crashbandicoot': g_crashbandicoot}
print("g_dirt4", g_dirt4, "g_destiny2", g_destiny2, "g_southpark", g_southpark, "g_codww2", g_codww2, "g_bfront2", g_bfront2, "g_reddead2", g_reddead2, "g_fifa18", g_fifa18, "g_motogp17", g_motogp17, "g_elderscrolls", g_elderscrolls, "g_crashbandicoot", g_crashbandicoot)
print (max(d.items(), key=lambda x: x[1]))
</code>```

Now it prints the variable with the highest value plus the value itself, but what if there are two or three variables with the same max value? I would like to print all of the max values.

Edit:

The user has to fill in a form, which adds values to the variables in the dictionary. When the user is done, there will be one, two or more variables with the highest value. For example, the code gives me this:

2017-06-08 15:05:43 g_dirt4 9 g_destiny2 8 g_southpark 5 g_codww2 8 g_bfront2 8 g_reddead2 7 g_fifa18 8 g_motogp17 9 g_elderscrolls 5 g_crashbandicoot 6
2017-06-08 15:05:43 ('g_dirt4', 9)
```

Now it tells me that g_dirt4 has the highest value of 9, but if you look at motogp17, it also had 9 but it doesn't get printed because it's at a higher position in the dictionary. So how do I print them both? And what if it has 3 variables with the same max value?

答:
You could do something like this:

```<code>max_value = (max(d.items(), key=lambda x: x[1]))[1]
max_list = [max_value]

for key, value in d.items():
    if value == max_value:
        max_list.append((key, value))

print(max_list)
</code>```

This will get the maximum value, then loop through all the keys and values in your dictionary and add all the ones matching that max value to a list. Then you print the list and it should print all of them.

Body:
How can I check if something in a dictionary is the same as the max in that dictionary. In other words, get all the max values instead of the max value with lowest position.
I have this code which returns the max variable name and value:

d = {'g_dirt4': g_dirt4, 'g_destiny2': g_destiny2, 'g_southpark': g_southpark, 'g_codww2': g_codww2, 'g_bfront2': g_bfront2, 'g_reddead2': g_reddead2, 'g_fifa18': g_fifa18, 'g_motogp17': g_motogp17, 'g_elderscrolls': g_elderscrolls, 'g_crashbandicoot': g_crashbandicoot}
print("g_dirt4", g_dirt4, "g_destiny2", g_destiny2, "g_southpark", g_southpark, "g_codww2", g_codww2, "g_bfront2", g_bfront2, "g_reddead2", g_reddead2, "g_fifa18", g_fifa18, "g_motogp17", g_motogp17, "g_elderscrolls", g_elderscrolls, "g_crashbandicoot", g_crashbandicoot)
print (max(d.items(), key=lambda x: x[1]))

Now it prints the variable with the highest value plus the value itself, but what if there are two or three variables with the same max value? I would like to print all of the max values.

Edit:

The user has to fill in a form, which adds values to the variables in the dictionary. When the user is done, there will be one, two or more variables with the highest value. For example, the code gives me this:

2017-06-08 15:05:43 g_dirt4 9 g_destiny2 8 g_southpark 5 g_codww2 8 g_bfront2 8 g_reddead2 7 g_fifa18 8 g_motogp17 9 g_elderscrolls 5 g_crashbandicoot 6
2017-06-08 15:05:43 ('g_dirt4', 9)

Now it tells me that g_dirt4 has the highest value of 9, but if you look at motogp17, it also had 9 but it doesn't get printed because it's at a higher position in the dictionary. So how do I print them both? And what if it has 3 variables with the same max value?

Body:
You could do something like this:

max_value = (max(d.items(), key=lambda x: x[1]))[1]
max_list = [max_value]

for key, value in d.items():
    if value == max_value:
        max_list.append((key, value))

print(max_list)

This will get the maximum value, then loop through all the keys and values in your dictionary and add all the ones matching that max value to a list. Then you print the list and it should print all of them.


问:
Laravel Eloquent - Get all records of child relation model
My data model is this:
Users > Offices > Organization

This is my model

```<code>class Organization extends Model  {

    protected $table = 'organizations';

    public function offices()
    {
        return $this->hasMany('App\Models\Office');
    }

    public function users()
    {
        return $this->offices()->users();
    }
....
</code>```

So.. I want to get all users from an organization (of all the offices).
But I don't know how to do something like

```<code>$this->offices()->users();
</code>```

(Avoiding user a manual collection or map to do that)

Thanks!

答:
So, you have organization ID. You can load all users by using whereHas():

```<code>$users = User::whereHas('office', function ($q) use ($organizationId) {
        $q->where('organization_id', $organizationId);
    })
    ->get();
</code>```

Make sure office() relationship is defined correctly in User model:

```<code>public function office()
{
    return $this->belongsTo('App\Office');
}
</code>```

Alternatively, you could define hasManyThrough() relationship:

```<code>public function users()
{
    return $this->hasManyThrough('App\Office', 'App\User');
}
</code>```

And use it:

```<code>$organization->users()
</code>```

Body:
My data model is this:
Users > Offices > Organization

This is my model

class Organization extends Model  {

    protected $table = 'organizations';

    public function offices()
    {
        return $this->hasMany('App\Models\Office');
    }

    public function users()
    {
        return $this->offices()->users();
    }
....

So.. I want to get all users from an organization (of all the offices).
But I don't know how to do something like

$this->offices()->users();

(Avoiding user a manual collection or map to do that)

Thanks!

Body:
So, you have organization ID. You can load all users by using whereHas():

$users = User::whereHas('office', function ($q) use ($organizationId) {
        $q->where('organization_id', $organizationId);
    })
    ->get();

Make sure office() relationship is defined correctly in User model:

public function office()
{
    return $this->belongsTo('App\Office');
}

Alternatively, you could define hasManyThrough() relationship:

public function users()
{
    return $this->hasManyThrough('App\Office', 'App\User');
}

And use it:

$organization->users()


问:
Getting "given config server set name: NewConfigRS differs from known set name: OldConfigRS" message when calling "show dbs"
I have recently setup a sharded cluster in Mongo with only one replica set that already had data on it.  I re-used 4 other servers that were previously in a cluster for the config replica set and the mongos server (only one mongos for now).

I'm using Mongo Cloud Manager and everything seems to be running fine.  When I try to show dbs or run a simple find query on a collection, I get this message:

```<code>Error: listDatabases failed:{
    "code" : 8,
    "ok" : 0,
    "errmsg" : "given config server set name: NewConfigRS differs
                from known set name: OldConfigRS"
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
Mongo.prototype.getDBs@src/mongo/shell/mongo.js:62:1
shellHelper.show@src/mongo/shell/utils.js:755:19
shellHelper@src/mongo/shell/utils.js:645:15
@(shell):1:1
</code>```

I've checked the mongos config file.  configDB looks correct:

```<code>sharding:
  configDB: NewConfigRS/conf1:27019,conf2:27019,conf3:27019
</code>```

I can connect to and run queries on the replica set directly without issue.

Mongo version: 3.2.10

What am I missing?

答: It sounds like one of your replica sets, probably the config servers, have been not been updated correctly. You should double-check the replica set name saved in the configuration (i.e. in the local database) against the replica set named in the mongod configuration (e.g. in the mongod.conf file).

Body:
I have recently setup a sharded cluster in Mongo with only one replica set that already had data on it.  I re-used 4 other servers that were previously in a cluster for the config replica set and the mongos server (only one mongos for now).

I'm using Mongo Cloud Manager and everything seems to be running fine.  When I try to show dbs or run a simple find query on a collection, I get this message:

Error: listDatabases failed:{
    "code" : 8,
    "ok" : 0,
    "errmsg" : "given config server set name: NewConfigRS differs
                from known set name: OldConfigRS"
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
Mongo.prototype.getDBs@src/mongo/shell/mongo.js:62:1
shellHelper.show@src/mongo/shell/utils.js:755:19
shellHelper@src/mongo/shell/utils.js:645:15
@(shell):1:1

I've checked the mongos config file.  configDB looks correct:

sharding:
  configDB: NewConfigRS/conf1:27019,conf2:27019,conf3:27019

I can connect to and run queries on the replica set directly without issue.

Mongo version: 3.2.10

What am I missing?


问:
Maven build failure for my service
(Maven build failure for my service):Maven Install is giving me this error. and also there is no settings.xml file in .m2 folder.

```<code>[INFO] Adapter CSI_ORDERTRACK_STATUS Bundle ............... SUCCESS [  0.581 s]

[INFO] Adapter CSI_ORDERTRACK_STATUS Bundle Dependencies .. SUCCESS [  0.011 s]

[INFO] Adapter CSI_ORDERTRACK_STATUS Bundle Service ....... FAILURE [01:12 min]

[INFO] Adapter CSI_ORDERTRACK_STATUS SWM Zip .............. SKIPPED

[INFO] Adapter CSI_ORDERTRACK_STATUS SWM Package .......... SKIPPED

[INFO] ------------------------------------------------------------------------

[INFO] BUILD FAILURE
------------------------------------------------------------------------

[ERROR] Failed to execute goal on project CSI_ORDERTRACK_STATUS-service: Could not resolve dependencies for project maf.service:CSI_ORDERTRACK_STATUS-service:jar:200.0.14: Failed to collect dependencies at maf:adapter-ordertrackdb:jar:200.0.14: Failed to read artifact descriptor for maf:adapter-ordertrackdb:jar:200.0.14: Could not transfer artifact maf:adapter-ordertrackdb:pom:200.0.14 from/to central (https://repo.maven.apache.org/maven2): connect timed out -> [Help 1]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
</code>```

[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException
    200.0.14 dependency Service_pom is given below:

```<code><groupId>maf.service</groupId>
<artifactId>CSI_ORDERTRACK_STATUS-service</artifactId>
<version>200.0.14</version>
<packaging>jar</packaging>
<name>Adapter CSI_ORDERTRACK_STATUS Bundle Service</name>
<dependencies>
    <dependency>
        <groupId>maf</groupId>
        <artifactId>adapter-ordertrackdb</artifactId>
        <version>200.0.14</version>
    </dependency>
    <dependency>
</code>```

答:
Have you tried running Maven in offline mode?
mvn -o install

By default Maven will try to fetch external dependencies from central.

Try to build af:adapter-ordertrackdb:pom:200.0.14 first (non recursive - mvn -N install), and then try Maven install.

If you could supply the pom's it could be helpful.

Title: Maven build failure for my service

Body:
(Maven build failure for my service):Maven Install is giving me this error. and also there is no settings.xml file in .m2 folder.

[INFO] Adapter CSI_ORDERTRACK_STATUS Bundle ............... SUCCESS [  0.581 s]

[INFO] Adapter CSI_ORDERTRACK_STATUS Bundle Dependencies .. SUCCESS [  0.011 s]

[INFO] Adapter CSI_ORDERTRACK_STATUS Bundle Service ....... FAILURE [01:12 min]

[INFO] Adapter CSI_ORDERTRACK_STATUS SWM Zip .............. SKIPPED

[INFO] Adapter CSI_ORDERTRACK_STATUS SWM Package .......... SKIPPED

[INFO] ------------------------------------------------------------------------

[INFO] BUILD FAILURE
------------------------------------------------------------------------

[ERROR] Failed to execute goal on project CSI_ORDERTRACK_STATUS-service: Could not resolve dependencies for project maf.service:CSI_ORDERTRACK_STATUS-service:jar:200.0.14: Failed to collect dependencies at maf:adapter-ordertrackdb:jar:200.0.14: Failed to read artifact descriptor for maf:adapter-ordertrackdb:jar:200.0.14: Could not transfer artifact maf:adapter-ordertrackdb:pom:200.0.14 from/to central (https://repo.maven.apache.org/maven2): connect timed out -> [Help 1]
[ERROR] For more information about the errors and possible solutions, please read the following articles:

[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException
    200.0.14 dependency Service_pom is given below:

<groupId>maf.service</groupId>
<artifactId>CSI_ORDERTRACK_STATUS-service</artifactId>
<version>200.0.14</version>
<packaging>jar</packaging>
<name>Adapter CSI_ORDERTRACK_STATUS Bundle Service</name>
<dependencies>
    <dependency>
        <groupId>maf</groupId>
        <artifactId>adapter-ordertrackdb</artifactId>
        <version>200.0.14</version>
    </dependency>
    <dependency>


问:
Implement multiple selects with jQuery UI Selectable
can anyone help me use the jquery ui selectable library to perform the following functions:

Allow a user to select multiple items with a mouse click

De-select an item if it is already selected with a mouse click

答:
Have you checked the demo page for selectable? You can already do this. To select multiple items, just hold control. This is similar to how you would work with files. Is using "Ctrl+Click" not good enough?

Demo Code Here:

```<code><style>
    #feedback { font-size: 1.4em; }
    #selectable .ui-selecting { background: #FECA40; }
    #selectable .ui-selected { background: #F39814; color: white; }
    #selectable { list-style-type: none; margin: 0; padding: 0; width: 60%; }
    #selectable li { margin: 3px; padding: 0.4em; font-size: 1.4em; height: 18px; }
    </style>
    <script>
    $(function() {
        $( "#selectable" ).selectable();
    });
    </script>

<div class="demo">

<ol id="selectable">
    <li class="ui-widget-content">Item 1</li>
    <li class="ui-widget-content">Item 2</li>
    <li class="ui-widget-content">Item 3</li>
    <li class="ui-widget-content">Item 4</li>
    <li class="ui-widget-content">Item 5</li>
    <li class="ui-widget-content">Item 6</li>
    <li class="ui-widget-content">Item 7</li>
</ol>

</div>
</code>```

Body:
Have you checked the demo page for selectable? You can already do this. To select multiple items, just hold control. This is similar to how you would work with files. Is using "Ctrl+Click" not good enough?

Demo Code Here:

<style>
    #feedback { font-size: 1.4em; }
    #selectable .ui-selecting { background: #FECA40; }
    #selectable .ui-selected { background: #F39814; color: white; }
    #selectable { list-style-type: none; margin: 0; padding: 0; width: 60%; }
    #selectable li { margin: 3px; padding: 0.4em; font-size: 1.4em; height: 18px; }
    </style>
    <script>
    $(function() {
        $( "#selectable" ).selectable();
    });
    </script>

<div class="demo">

<ol id="selectable">
    <li class="ui-widget-content">Item 1</li>
    <li class="ui-widget-content">Item 2</li>
    <li class="ui-widget-content">Item 3</li>
    <li class="ui-widget-content">Item 4</li>
    <li class="ui-widget-content">Item 5</li>
    <li class="ui-widget-content">Item 6</li>
    <li class="ui-widget-content">Item 7</li>
</ol>

</div>


问:
How to save mpi profile summary report in matlab
I want to save the details of each worker as it is seen in the mpiprofile summary report. Profsave does not give all the details very clearly for the report generated by the mpiprofile viewer option.

Is there any other way to save the report?

答:
One way I figured to do something similar is the following.

I am assuming you are using "pmode" because as far as my understanding goes, you need to run on "pmode" to run mpiprofile.

So this is how it goes.

Saving

Save the mpiprofile info inside each worker(or it is often called lab from my understanding).

mpiprofile mpistruct;

Then you transfer to the client using the following command

pmode lab2client mpistruct;

Then save the mpistruct into a .mat file

save('mpistruct');

Loading:
When you are trying to view the mpiprofile result:

Load the mpi file

load('mpistruct.mat');

Run mpiprofile viewer

mpiprofile('viewer', mpistruct);

This should pop up the browser.

Note. Above code was tested with 2015b.

(I wrote the same exact answer to Matlab community. I copied for your convenience.)


问:
Signing an iOS app with another certificate
I currently have my app deployed on the Apple Store and I had to create a new certificate for some reasons.

Now, I need to update my app on the store but I had to sign it with my new certificate.

My question is, if I sign my application with a different certificate, will the app store update the existing one on my phone or consider the application like a new application ?

Plus, if it updates the application, will my data stored in the local storage be kept ?

Thanks in advance.

答:
You can sign with another certificate. Think of company with multiple developers: they can have multiple appStore certificates.

The data stored in local storage will be kept as long as the bundle identifier stays the same.

ContentLicense: CC BY-SA 4.0


问:
How to remove the ',' when converting Javascript object to .csv file?
I need to convert javascript some objects like this:

```<code>{available :null
avg: null
current:116
max:null
min:null
status:"Pending, Charged Off"
balance:-166085.77}
</code>```

using other people's js code and adding a little bit my code for get API, which including two functions the first one is for converting:

```<code>$scope.convertArrayOfObjectsToCSV = function (args) {
        var result, ctr, keys, columnDelimiter, lineDelimiter, data;

        data = args.data || null;
        if (data == null || !data.length) {
            return null;
        }

        columnDelimiter = args.columnDelimiter || ',';
        lineDelimiter = args.lineDelimiter || '\n';

        keys = Object.keys(data[0]);

        result = '';
        result += keys.join(columnDelimiter);
        result += lineDelimiter;

        data.forEach(function(item) {
            ctr = 0;
            keys.forEach(function(key) {
                if (ctr > 0) result += columnDelimiter;

                result += item[key];
                ctr++;
            });
            result += lineDelimiter;
        });

        return result;
    }
</code>```

the second one is for downloading :

```<code>$scope.downloadCSV = function (args) {
        var data, filename, link;
        //my code:
        $http.get(
                 apis[$scope.selectedKeys[0]]
            ).success(function (data) {
                    $scope.data = data;
        })
        var stringData = angular.toJson($scope.data.items);
        $scope.newData = JSON.parse(stringData);
        console.log($scope.newData);
        //my code end
        var csv = $scope.convertArrayOfObjectsToCSV({
            data: $scope.newData
        });
        if (csv == null) return;

        // filename = args.filename || 'export.csv';
        filename =  $scope.selectedKeys[0] + '.csv';

        if (!csv.match(/^data:text\/csv/i)) {
            csv = 'data:text/csv;charset=utf-8,' + csv;
        }
        data = encodeURI(csv);

        link = document.createElement('a');
        link.setAttribute('href', data);
        link.setAttribute('download', filename);
        link.click();
    }
</code>```

It works fine, only one problem is when some columns with the comma like this in object: status:"Pending, Charged Off" will be converted in to another column in csv file. I think I need to do something with this line:

```<code>columnDelimiter = args.columnDelimiter || ',';
</code>```

but do not know how to do? Can any one help? Thank you in advanced!

答:
An homemade-solution can be use quotation marks.</p>

```<code>$scope.convertArrayOfObjectsToCSV = function (args) {
        var result, ctr, keys, columnDelimiter, lineDelimiter, data;

    data = args.data || null;
    if (data == null || !data.length) {
        return null;
    }

    columnDelimiter = args.columnDelimiter || ',';
    lineDelimiter = args.lineDelimiter || '\n';

    keys = Object.keys(data[0]);

    result = '';
    result += keys.join(columnDelimiter);
    result += lineDelimiter;

    data.forEach(function(item) {
        ctr = 0;
        keys.forEach(function(key) {
            if (ctr > 0) result += columnDelimiter;

            result += '"' + item[key].replace('\"', """) + '"';
            ctr++;
        });
        result += lineDelimiter;
    });

    return result;
}
</code>```

Body:
I need to convert javascript some objects like this:

{available :null
avg: null
current:116
max:null
min:null
status:"Pending, Charged Off"
balance:-166085.77}

using other people's js code and adding a little bit my code for get API, which including two functions the first one is for converting:

$scope.convertArrayOfObjectsToCSV = function (args) {
        var result, ctr, keys, columnDelimiter, lineDelimiter, data;

        data = args.data || null;
        if (data == null || !data.length) {
            return null;
        }

        columnDelimiter = args.columnDelimiter || ',';
        lineDelimiter = args.lineDelimiter || '\n';

        keys = Object.keys(data[0]);

        result = '';
        result += keys.join(columnDelimiter);
        result += lineDelimiter;

        data.forEach(function(item) {
            ctr = 0;
            keys.forEach(function(key) {
                if (ctr > 0) result += columnDelimiter;

                result += item[key];
                ctr++;
            });
            result += lineDelimiter;
        });

        return result;
    }

the second one is for downloading :

$scope.downloadCSV = function (args) {
        var data, filename, link;
        //my code:
        $http.get(
                 apis[$scope.selectedKeys[0]]
            ).success(function (data) {
                    $scope.data = data;
        })
        var stringData = angular.toJson($scope.data.items);
        $scope.newData = JSON.parse(stringData);
        console.log($scope.newData);
        //my code end
        var csv = $scope.convertArrayOfObjectsToCSV({
            data: $scope.newData
        });
        if (csv == null) return;

        // filename = args.filename || 'export.csv';
        filename =  $scope.selectedKeys[0] + '.csv';

        if (!csv.match(/^data:text\/csv/i)) {
            csv = 'data:text/csv;charset=utf-8,' + csv;
        }
        data = encodeURI(csv);

        link = document.createElement('a');
        link.setAttribute('href', data);
        link.setAttribute('download', filename);
        link.click();
    }

It works fine, only one problem is when some columns with the comma like this in object: status:"Pending, Charged Off" will be converted in to another column in csv file. I think I need to do something with this line:

columnDelimiter = args.columnDelimiter || ',';

but do not know how to do? Can any one help? Thank you in advanced!

Body:
An homemade-solution can be use quotation marks.

$scope.convertArrayOfObjectsToCSV = function (args) {
        var result, ctr, keys, columnDelimiter, lineDelimiter, data;

    data = args.data || null;
    if (data == null || !data.length) {
        return null;
    }

    columnDelimiter = args.columnDelimiter || ',';
    lineDelimiter = args.lineDelimiter || '\n';

    keys = Object.keys(data[0]);

    result = '';
    result += keys.join(columnDelimiter);
    result += lineDelimiter;

    data.forEach(function(item) {
        ctr = 0;
        keys.forEach(function(key) {
            if (ctr > 0) result += columnDelimiter;

            result += '"' + item[key].replace('\"', "&quot;") + '"';
            ctr++;
        });
        result += lineDelimiter;
    });

    return result;
}


问:
Combining records with same order id in mysql php
I have 2 tables, customers and orders, i would like to display all orders for each customer on a page. From orders when there are 2 orders belonging to same customer id i would like combine them into 1 div so there are shown together. Do i need to create 2 queries and loops to achieve this? E.g. 1 loop to get orders and another loop inside it, check if order id is a duplicate get the record. Please advise me and give me any ideas you might have thanks in advance.

Sample Tables
Customer Table
Customer ID, Customer Name

1, Jason

2, Joe

Order Table

Order ID, Customer ID, Order Details

1, 1, Pen

2, 1, Watch

3, 2, Mirror

What I would like to achieve:

Customer_ID, Customer_Name, Customer_Order

1, Jason,

Pen, Watch

2, Joe,

Mirror.

答:
you can use join for obtain all  the info you need<br>
eg for customer 1 </p>

```<code>select c.Customer_ID, c.Customer_Name, o.Customer_Order
from Customer c
inner join Order o on o.Customer_ID = c.Customer_ID
where and  c.Customer_ID = 1
</code>```

Body:
you can use join for obtain all  the info you need

eg for customer 1

select c.Customer_ID, c.Customer_Name, o.Customer_Order
from Customer c
inner join Order o on o.Customer_ID = c.Customer_ID
where and  c.Customer_ID = 1


问:
getting a gridview and dropdownlist to remember their states after navigate away and back button scriptmanager
i have a page filling a gridview which is all working fine.

the grid is basically the result of a search .. the filters for which are a number of dropdowns and a couple of textboxes
the data from the grid and dropdowns are saved in the session and the whole page lives inside an updatepanel

when i navigate away from the page (as it happens by clicking a link inside the grid) and then back button to it, all the droppers are back to their unselected values and the grid is nowhere to be seen..

i understand that this is because of the scriptmanager doesnt do 'standard' postbacks so the browser doesnt realise what has happened.

however i have set the EnableHistory to true in the scriptmanager

is there an easy way to get this to remember without dropping the updatepanel/scriptmanager?

also to complicate things further the scriptmanger /updatepanel is actually in a master page. so not really sure how i can get the navigate bits to work in the scriptmanager..
clearly i am a bit confuised and any help that someone could provide would be happily received

thanks
nat

答:
Another answer that worked well for me:

-on the gridview, add this: OnPageIndexChanging="Gridview2_PageIndexChanging"

-in the code (I'm using VB), add:

```<code>Protected Sub Gridview2_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
    Session("page") = e.NewPageIndex
End Sub
</code>```

-in the Page_Load sub, add:

```<code>GridView2.PageIndex = Session("page")
</code>```

That was much simpler than the other solutions I found out there...

Body:
Another answer that worked well for me:

-on the gridview, add this: OnPageIndexChanging="Gridview2_PageIndexChanging"

-in the code (I'm using VB), add:

Protected Sub Gridview2_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
    Session("page") = e.NewPageIndex
End Sub

-in the Page_Load sub, add:

GridView2.PageIndex = Session("page")

That was much simpler than the other solutions I found out there...


问:
Spark join dataframes & datasets
I have a DataFrame called Link with a dynamic amount of fields/columns in a Row.
Some fields however had the structure [ClassName]Id that contain an id

[ClassName]Id's are always of type String

I have a couple of Datasets each of a different type [ClassName]
Each Dataset has at least fields id (String) and typeName (String), which is always filled with the String value of the [ClassName]

e.g. If I would have 3 DataSets of type A, B and C

Link:

+----+-----+-----+-----+
 | id | AId | BId | CId |
 +----+-----+-----+-----+
 | XX | A01 | B02 | C04 |
 | XY | null| B05 | C07 |

A:

+-----+----------+-----+-----+
 | id  | typeName | ... | ... |
 +-----+----------+-----+-----+
 | A01 | A        | ... | ... |

B:

+-----+----------+-----+-----+
 | id  | typeName | ... | ... |
 +-----+----------+-----+-----+
 | B02 | B        | ... | ... |

The preferred end result would be the Link Dataframe where each Id is either replace or appended by a field called [ClassName] With the original object encapsulated.

Result:

+----+----------------+----------------+----------------+
 | id | A              | B              | C              |
 +----+----------------+----------------+----------------+
 | XX | A(A01, A, ...) | B(B02, B, ...) | C(C04, C, ...) |
 | XY | null           | B(B05, B, ...) | C(C07, C, ...) |

Things I've tried

Recursive Call on joinWith.
The first call succeeds returning a tuple/Row where the first element is the original Row and the second the matched [ClassName]
However the second iteration starts nesting these results.
Trying to 'unnest' these results using map either results in Encoder hell (since the resulting Row is not a fixed type) or the Encoding is so complex that it results in a catalyst error

join as RDD Can't work this one out yet.

Any ideas are welcome.

答:
So I figured out how I could do what I want.
I made some changes for it to work for me, but it's a
For reference purpose I will show my steps, maybe it can be useful for someone in the future?

First I declare a datatype that shares all properties of A, B, C, etc. that I'm Interested in and make the classes extend from this super type

case class Base(id: String, typeName: String)
case class A(override val id: String, override val typeName: String) extends Base(id, typeName)
```

<ol start="2">
<li>Next I load the link <code>Dataframe</code></li>
</ol>

<pre class="lang-scala prettyprint-override"><code>val linkDataFrame = spark.read.parquet("[path]")
</code>```

I want to convert this DataFrame in something joinable, this means creating a placeholder for the joined sources and a way to convert all the single Id fields (AId, BId, etc) into a Map of source -> id's. Spark has a sql map method that is useful. Also we need to convert the Base class to a StructType for use in the encoder. Tried multiple ways, but couldn't circumvent specific declaration (otherwise casting errors)

val linkDataFrame = spark.read.parquet("[path]")

case class LinkReformatted(ids: Map[String, Long], sources: Map[String, Base])

// Maps each column ending with Id into a Map of (columnname1 (-Id), value1, columnname2 (-Id), value2)
val mapper = linkDataFrame.columns.toList
  .filter(
    _.matches("(?i).*Id$")
  )
  .flatMap(
    c => List(lit(c.replaceAll("(?i)Id$", "")), col(c))
)

val baseStructType = ScalaReflection.schemaFor[Base].dataType.asInstanceOf[StructType]
```

<ol start="4">
<li>All these parts made it possible to create a new <code>DataFrame</code> with the Id's all in one field called <strong>ids</strong> and a placeholder for the <strong>sources</strong> in an empty <code>Map[String, Base]</code></li>
</ol>

<pre class="lang-scala prettyprint-override"><code>val linkDatasetReformatted = linkDataFrame.select(
    map(mapper: _*).alias("ids")
  )
  .withColumn("sources", lit(null).cast(MapType(StringType, baseStructType)))
  .as[LinkReformatted]
</code>```

The next step was to join all source Datasets (A,B, etc) to this reformatted Link dataset. A lot of stuff happens in this tailrecursive method

@tailrec
def recursiveJoinBases(sourceDataset: Dataset[LinkReformatted], datasets: List[Dataset[Base]]): Dataset[LinkReformatted] = datasets match {
  case Nil => sourceDataset // Nothing left to join, return it
  case baseDataset :: remainingDatasets => {

    val typeName = baseDataset.head.typeName // extract the type from base (each field hase same value)
    val masterName = "source" // something to name the source

    val joinedDataset = sourceDataset.as(masterName) // joining source
      .joinWith(
      baseDataset.as(typeName), // with a base A,B, etc
      col(s"$typeName.id") === col(s"$masterName.ids.$typeName"), // join on source.ids.[typeName]
      "left_outer"
    )
      .map {
        case (source, base) => {
          val newSources = if (source.sources == null) Map(typeName -> base) else source.sources + (typeName -> base) // append or create map of sources
          source.copy(sources = newSources)
        }
      }
      .as[LinkReformatted]
    recursiveJoinBases(joinedDataset, remainingDatasets)
  }
}
```

You now end up with a Dataset of LinkReformatted records where for each corresponding typeName -> id in the ids field is a corresponding  typeName -> Base in the sources field.
For me that was enough. I could extract everything I needed using some map function over this final Dataset

I hope this somewhat helps. I understand it's not the exact solution I was asking about, nor is it all very straightforward.

Title: Spark join dataframes & datasets

Body:
So I figured out how I could do what I want.
I made some changes for it to work for me, but it's a
For reference purpose I will show my steps, maybe it can be useful for someone in the future?

First I declare a datatype that shares all properties of A, B, C, etc. that I'm Interested in and make the classes extend from this super type

case class Base(id: String, typeName: String)
case class A(override val id: String, override val typeName: String) extends Base(id, typeName)

Next I load the link Dataframe

val linkDataFrame = spark.read.parquet("[path]")

I want to convert this DataFrame in something joinable, this means creating a placeholder for the joined sources and a way to convert all the single Id fields (AId, BId, etc) into a Map of source -> id's. Spark has a sql map method that is useful. Also we need to convert the Base class to a StructType for use in the encoder. Tried multiple ways, but couldn't circumvent specific declaration (otherwise casting errors)

val linkDataFrame = spark.read.parquet("[path]")

case class LinkReformatted(ids: Map[String, Long], sources: Map[String, Base])

// Maps each column ending with Id into a Map of (columnname1 (-Id), value1, columnname2 (-Id), value2)
val mapper = linkDataFrame.columns.toList
  .filter(
    _.matches("(?i).*Id$")
  )
  .flatMap(
    c => List(lit(c.replaceAll("(?i)Id$", "")), col(c))
)

val baseStructType = ScalaReflection.schemaFor[Base].dataType.asInstanceOf[StructType]

All these parts made it possible to create a new DataFrame with the Id's all in one field called ids and a placeholder for the sources in an empty Map[String, Base]

val linkDatasetReformatted = linkDataFrame.select(
    map(mapper: _*).alias("ids")
  )
  .withColumn("sources", lit(null).cast(MapType(StringType, baseStructType)))
  .as[LinkReformatted]

The next step was to join all source Datasets (A,B, etc) to this reformatted Link dataset. A lot of stuff happens in this tailrecursive method

@tailrec
def recursiveJoinBases(sourceDataset: Dataset[LinkReformatted], datasets: List[Dataset[Base]]): Dataset[LinkReformatted] = datasets match {
  case Nil => sourceDataset // Nothing left to join, return it
  case baseDataset :: remainingDatasets => {

    val typeName = baseDataset.head.typeName // extract the type from base (each field hase same value)
    val masterName = "source" // something to name the source

    val joinedDataset = sourceDataset.as(masterName) // joining source
      .joinWith(
      baseDataset.as(typeName), // with a base A,B, etc
      col(s"$typeName.id") === col(s"$masterName.ids.$typeName"), // join on source.ids.[typeName]
      "left_outer"
    )
      .map {
        case (source, base) => {
          val newSources = if (source.sources == null) Map(typeName -> base) else source.sources + (typeName -> base) // append or create map of sources
          source.copy(sources = newSources)
        }
      }
      .as[LinkReformatted]
    recursiveJoinBases(joinedDataset, remainingDatasets)
  }
}

You now end up with a Dataset of LinkReformatted records where for each corresponding typeName -> id in the ids field is a corresponding  typeName -> Base in the sources field.
For me that was enough. I could extract everything I needed using some map function over this final Dataset

I hope this somewhat helps. I understand it's not the exact solution I was asking about, nor is it all very straightforward.


问:
Textview still visible even if listview gets an item
I have an imageview, 2 textviews that needs to appear when the listview is empty. I want the 2nd textview to be clickable
as well. Here is my code -

```<code><ImageView
        android:id="@android:id/empty"
        android:layout_width="120sp"
        android:layout_height="130sp"
        android:layout_gravity="center"
        android:gravity="center"
        android:src="@drawable/flower" />

    <TextView
        android:id="@android:id/empty"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:paddingTop="120sp"
        android:text="Warning" />

    <TextView
        android:id="@android:id/empty"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:paddingTop="200sp"
        android:text="Click Me" />
</code>```

The image view disappears when the list view gets an item but the text views are still visible.
How can I make these 2 textviews disappear when the list view gets an item? Also how can I make my second text view clickable?

答:
To make textView clickable you can setOnClickListener to that textView like this:

```<code>view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
        }
    });
</code>```

Body:
I have an imageview, 2 textviews that needs to appear when the listview is empty. I want the 2nd textview to be clickable
as well. Here is my code -

<ImageView
        android:id="@android:id/empty"
        android:layout_width="120sp"
        android:layout_height="130sp"
        android:layout_gravity="center"
        android:gravity="center"
        android:src="@drawable/flower" />

    <TextView
        android:id="@android:id/empty"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:paddingTop="120sp"
        android:text="Warning" />

    <TextView
        android:id="@android:id/empty"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:paddingTop="200sp"
        android:text="Click Me" />

The image view disappears when the list view gets an item but the text views are still visible.
How can I make these 2 textviews disappear when the list view gets an item? Also how can I make my second text view clickable?

Body:
To make textView clickable you can setOnClickListener to that textView like this:

view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
        }
    });