问:
How to pass mvc view in template url in type script file in angular 4
i am using angular 4 in mvc architecture . wheneve i gona pass mvc view in template url in the app.component.ts file it shows some error.
can i pass the mvc view in the type script file or i have to create a html file in app folder.

import { Component } from '@angular/core';

@Component({
    selector: 'my-app',
    templateUrl: '/Home/Index.cshtml',
})
export class AppComponent  {
    name = '';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div id="Registeration">
    <my-app>Loading AppComponent content here ...</my-app>
    <input type="text" [(ngmodel)]="name"/>
    <p>{{name}}</p>

</div></code>```

答:
Possible solution

app.component.ts

```<code>@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
</code>```

app.component.html

```<code><child-cmp></child-cmp> <------ selector of child component
</code>```

child.component.ts

```<code>@Component({
  selector: 'child-cmp',         <----pass this selector to view this component
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})

name = 'child';
</code>```

Put your  index.cshtml file in child.component.html

child.component.html

```<code><div id="Registeration">
    <input type="text" [(ngmodel)]="name"/>
    <p>{{name}}</p>
</div>
</code>```

Body:
i am using angular 4 in mvc architecture . wheneve i gona pass mvc view in template url in the app.component.ts file it shows some error.
can i pass the mvc view in the type script file or i have to create a html file in app folder.

import { Component } from '@angular/core';

@Component({
    selector: 'my-app',
    templateUrl: '/Home/Index.cshtml',
})
export class AppComponent  {
    name = '';
}

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

    <my-app>Loading AppComponent content here ...</my-app>
    <input type="text" [(ngmodel)]="name"/>

{{name}}

Body:
Possible solution

app.component.ts

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

app.component.html

<child-cmp></child-cmp> <------ selector of child component

child.component.ts

@Component({
  selector: 'child-cmp',         <----pass this selector to view this component
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})

name = 'child';

Put your  index.cshtml file in child.component.html

child.component.html

<div id="Registeration">
    <input type="text" [(ngmodel)]="name"/>
    <p>{{name}}</p>
</div>


来源: stackexchange

问:
What is the most elegant way to remove a listener from a list from a callback
Suppose I have the following listener

```<code>interface MyListener {
    fun onResult(result: Int)
}
</code>```

and that my class holds a list of this listener

```<code>val MyListenerList = ArrayList<MyListener>()
</code>```

My doubt is: if someone that registered the listener wants to unregister it (remove it from the list) when the callback (onResult) is fired, what is the most elegant way to do it, having in mind that calling it directly while the list iteration is running will cause a ConcurrentModificationException?

答:
Don't iterate over MyListenerList, make a copy of MyListenerList and iterate over the copy. That way the removal can occur on MyListenerList without causing a ConcurrentModificationException.

For example:

```<code>ArrayList(MyListenerList).forEach { it.onRemove(n) }
</code>```

or

```<code>MyListenerList.toArray().forEach { it.onRemove(n) }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Suppose I have the following listener

interface MyListener {
    fun onResult(result: Int)
}

and that my class holds a list of this listener

val MyListenerList = ArrayList<MyListener>()

My doubt is: if someone that registered the listener wants to unregister it (remove it from the list) when the callback (onResult) is fired, what is the most elegant way to do it, having in mind that calling it directly while the list iteration is running will cause a ConcurrentModificationException?

Body:
Don't iterate over MyListenerList, make a copy of MyListenerList and iterate over the copy. That way the removal can occur on MyListenerList without causing a ConcurrentModificationException.

For example:

ArrayList(MyListenerList).forEach { it.onRemove(n) }

or

MyListenerList.toArray().forEach { it.onRemove(n) }


问:
RxJava Combine Sequence Of Requests

The Problem

I have two Apis. Api 1 gives me a List of Items and Api 2 gives me more detailed Information for each of the items I got from Api 1. The way I solved it so far results in bad Performance.

The Question

Efficent and fast solution to this Problem with the help of Retrofit and RxJava.

My Approach

At the Moment my Solution Looks like this:

Step 1: Retrofit executes Single<ArrayList<Information>> from Api 1.

Step 2: I iterate through this Items and make a request for each to Api 2.

Step 3: Retrofit Returns Sequentially executes Single<ExtendedInformation> for
each item

Step 4: After all calls form Api 2 completely executed I create a new Object for all Items combining the Information and Extended Information.

My Code

```<code> public void addExtendedInformations(final Information[] informations) {
        final ArrayList<InformationDetail> informationDetailArrayList = new ArrayList<>();
        final JSONRequestRatingHelper.RatingRequestListener ratingRequestListener = new JSONRequestRatingHelper.RatingRequestListener() {
            @Override
            public void onDownloadFinished(Information baseInformation, ExtendedInformation extendedInformation) {
                informationDetailArrayList.add(new InformationDetail(baseInformation, extendedInformation));
                if (informationDetailArrayList.size() >= informations.length){
                    listener.onAllExtendedInformationLoadedAndCombined(informationDetailArrayList);
                }
            }
        };

        for (Information information : informations) {
            getExtendedInformation(ratingRequestListener, information);
        }
    }

    public void getRatingsByTitle(final JSONRequestRatingHelper.RatingRequestListener ratingRequestListener, final Information information) {
        Single<ExtendedInformation> repos = service.findForTitle(information.title);
        disposable.add(repos.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribeWith(new DisposableSingleObserver<ExtendedInformation>() {
            @Override
            public void onSuccess(ExtendedInformation extendedInformation) {
                    ratingRequestListener.onDownloadFinished(information, extendedInformation);
            }

            @Override
            public void onError(Throwable e) {
                ExtendedInformation extendedInformation = new ExtendedInformation();
                ratingRequestListener.onDownloadFinished(extendedInformation, information);
            }
        }));
    }

    public interface RatingRequestListener {

        void onDownloadFinished(Information information, ExtendedInformation extendedInformation);

    }
</code>```

答:
tl;dr use concatMapEager or flatMap and execute sub-calls asynchronously or on a schedulers.

long story

I'm not an android developer, so my question will be limited to pure RxJava (version 1 and version 2).

If I get the picture right the needed flow is :

```<code>some query param
  \--> Execute query on API_1 -> list of items
          |-> Execute query for item 1 on API_2 -> extended info of item1
          |-> Execute query for item 2 on API_2 -> extended info of item1
          |-> Execute query for item 3 on API_2 -> extended info of item1
          ...
          \-> Execute query for item n on API_2 -> extended info of item1
  \----------------------------------------------------------------------/
      |
      \--> stream (or list) of extended item info for the query param
</code>```

Assuming Retrofit generated the clients for

```<code>interface Api1 {
    @GET("/api1") Observable<List<Item>> items(@Query("param") String param);
}

interface Api2 {
    @GET("/api2/{item_id}") Observable<ItemExtended> extendedInfo(@Path("item_id") String item_id);
}
</code>```

If the order of the item is not important, then it is possible to use flatMap only:

```<code>api1.items(queryParam)
    .flatMap(itemList -> Observable.fromIterable(itemList)))
    .flatMap(item -> api2.extendedInfo(item.id()))
    .subscribe(...)
</code>```

But only if the retrofit builder is configured with

Either with the async adapter (calls will be queued in the okhttp internal executor). I personally think this is not a good idea, because you don't have control over this executor.

```<code>.addCallAdapterFactory(RxJava2CallAdapterFactory.createAsync()
</code>```

Or with the scheduler based adapter (calls will be scheduled on the RxJava scheduler). It would my preferred option, because you explicitly choose which scheduler is used, it will be most likely the IO scheduler, but you are free to try a different one.

```<code>.addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
</code>```

The reason is that flatMap will subscribe to each observable created by api2.extendedInfo(...) and merge them in the resulting observable. So results will appear in the order they are received.

If the retrofit client is not set to be async or set to run on a scheduler, it is possible to set one :

```<code>api1.items(queryParam)
    .flatMap(itemList -> Observable.fromIterable(itemList)))
    .flatMap(item -> api2.extendedInfo(item.id()).subscribeOn(Schedulers.io()))
    .subscribe(...)
</code>```

This structure is almost identical to the previous one execpts it indicates locally on which scheduler each api2.extendedInfo is supposed to run.

It is possible to tune the maxConcurrency parameter of flatMap to control how many request you want to perform at the same time. Although I'd be cautious on this one, you don't want run all queries at the same time. Usually the default maxConcurrency is good enough (128).

Now if order of the original query matter. concatMap is usually the operator that does the same thing as flatMap in order but sequentially, which turns out to be slow if the code need to wait for all sub-queries to be performed. The solution though is one step further with concatMapEager, this one will subscribe to observable in order, and buffer the results as needed.

Assuming retrofit clients are async or ran on a specific scheduler :

```<code>api1.items(queryParam)
    .flatMap(itemList -> Observable.fromIterable(itemList)))
    .concatMapEager(item -> api2.extendedInfo(item.id()))
    .subscribe(...)
</code>```

Or if the scheduler has to be set locally :

```<code>api1.items(queryParam)
    .flatMap(itemList -> Observable.fromIterable(itemList)))
    .concatMapEager(item -> api2.extendedInfo(item.id()).subscribeOn(Schedulers.io()))
    .subscribe(...)
</code>```

It is also possible to tune the concurrency in this operator.

Additionally if the Api is returning Flowable, it is possible to use .parallel that is still in beta at this time in RxJava 2.1.7. But then results are not in order and I don't know a way (yet?) to order them without sorting after.

```<code>api.items(queryParam) // Flowable<Item>
   .parallel(10)
   .runOn(Schedulers.io())
   .map(item -> api2.extendedInfo(item.id()))
   .sequential();     // Flowable<ItemExtended>
</code>```

Title: RxJava Combine Sequence Of Requests

Body:
The Problem

I have two Apis. Api 1 gives me a List of Items and Api 2 gives me more detailed Information for each of the items I got from Api 1. The way I solved it so far results in bad Performance.

The Question

Efficent and fast solution to this Problem with the help of Retrofit and RxJava.

My Approach

At the Moment my Solution Looks like this:

Step 1: Retrofit executes Single<ArrayList<Information>> from Api 1.

Step 2: I iterate through this Items and make a request for each to Api 2.

Step 3: Retrofit Returns Sequentially executes Single<ExtendedInformation> for
each item

Step 4: After all calls form Api 2 completely executed I create a new Object for all Items combining the Information and Extended Information.

My Code

 public void addExtendedInformations(final Information[] informations) {
        final ArrayList<InformationDetail> informationDetailArrayList = new ArrayList<>();
        final JSONRequestRatingHelper.RatingRequestListener ratingRequestListener = new JSONRequestRatingHelper.RatingRequestListener() {
            @Override
            public void onDownloadFinished(Information baseInformation, ExtendedInformation extendedInformation) {
                informationDetailArrayList.add(new InformationDetail(baseInformation, extendedInformation));
                if (informationDetailArrayList.size() >= informations.length){
                    listener.onAllExtendedInformationLoadedAndCombined(informationDetailArrayList);
                }
            }
        };

        for (Information information : informations) {
            getExtendedInformation(ratingRequestListener, information);
        }
    }

    public void getRatingsByTitle(final JSONRequestRatingHelper.RatingRequestListener ratingRequestListener, final Information information) {
        Single<ExtendedInformation> repos = service.findForTitle(information.title);
        disposable.add(repos.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribeWith(new DisposableSingleObserver<ExtendedInformation>() {
            @Override
            public void onSuccess(ExtendedInformation extendedInformation) {
                    ratingRequestListener.onDownloadFinished(information, extendedInformation);
            }

            @Override
            public void onError(Throwable e) {
                ExtendedInformation extendedInformation = new ExtendedInformation();
                ratingRequestListener.onDownloadFinished(extendedInformation, information);
            }
        }));
    }

    public interface RatingRequestListener {

        void onDownloadFinished(Information information, ExtendedInformation extendedInformation);

    }

Body:
tl;dr use concatMapEager or flatMap and execute sub-calls asynchronously or on a schedulers.

long story

I'm not an android developer, so my question will be limited to pure RxJava (version 1 and version 2).

If I get the picture right the needed flow is :

some query param
  \--> Execute query on API_1 -> list of items
          |-> Execute query for item 1 on API_2 -> extended info of item1
          |-> Execute query for item 2 on API_2 -> extended info of item1
          |-> Execute query for item 3 on API_2 -> extended info of item1
          ...
          \-> Execute query for item n on API_2 -> extended info of item1
  \----------------------------------------------------------------------/
      |
      \--> stream (or list) of extended item info for the query param

Assuming Retrofit generated the clients for

interface Api1 {
    @GET("/api1") Observable<List<Item>> items(@Query("param") String param);
}

interface Api2 {
    @GET("/api2/{item_id}") Observable<ItemExtended> extendedInfo(@Path("item_id") String item_id);
}

If the order of the item is not important, then it is possible to use flatMap only:

api1.items(queryParam)
    .flatMap(itemList -> Observable.fromIterable(itemList)))
    .flatMap(item -> api2.extendedInfo(item.id()))
    .subscribe(...)

But only if the retrofit builder is configured with

Either with the async adapter (calls will be queued in the okhttp internal executor). I personally think this is not a good idea, because you don't have control over this executor.

.addCallAdapterFactory(RxJava2CallAdapterFactory.createAsync()

Or with the scheduler based adapter (calls will be scheduled on the RxJava scheduler). It would my preferred option, because you explicitly choose which scheduler is used, it will be most likely the IO scheduler, but you are free to try a different one.

.addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))

The reason is that flatMap will subscribe to each observable created by api2.extendedInfo(...) and merge them in the resulting observable. So results will appear in the order they are received.

If the retrofit client is not set to be async or set to run on a scheduler, it is possible to set one :

api1.items(queryParam)
    .flatMap(itemList -> Observable.fromIterable(itemList)))
    .flatMap(item -> api2.extendedInfo(item.id()).subscribeOn(Schedulers.io()))
    .subscribe(...)

This structure is almost identical to the previous one execpts it indicates locally on which scheduler each api2.extendedInfo is supposed to run.

It is possible to tune the maxConcurrency parameter of flatMap to control how many request you want to perform at the same time. Although I'd be cautious on this one, you don't want run all queries at the same time. Usually the default maxConcurrency is good enough (128).

Now if order of the original query matter. concatMap is usually the operator that does the same thing as flatMap in order but sequentially, which turns out to be slow if the code need to wait for all sub-queries to be performed. The solution though is one step further with concatMapEager, this one will subscribe to observable in order, and buffer the results as needed.

Assuming retrofit clients are async or ran on a specific scheduler :

api1.items(queryParam)
    .flatMap(itemList -> Observable.fromIterable(itemList)))
    .concatMapEager(item -> api2.extendedInfo(item.id()))
    .subscribe(...)

Or if the scheduler has to be set locally :

api1.items(queryParam)
    .flatMap(itemList -> Observable.fromIterable(itemList)))
    .concatMapEager(item -> api2.extendedInfo(item.id()).subscribeOn(Schedulers.io()))
    .subscribe(...)

It is also possible to tune the concurrency in this operator.

Additionally if the Api is returning Flowable, it is possible to use .parallel that is still in beta at this time in RxJava 2.1.7. But then results are not in order and I don't know a way (yet?) to order them without sorting after.

api.items(queryParam) // Flowable<Item>
   .parallel(10)
   .runOn(Schedulers.io())
   .map(item -> api2.extendedInfo(item.id()))
   .sequential();     // Flowable<ItemExtended>

ContentLicense: CC BY-SA 4.0


问:
Replace environment variables in standalone.xml when using a mysql service on openshift
I have a WildFly 10 pod and a mysql 5.7 pod running in Openshift V3. I would like to use environment variables in my standalone.xml as I was used in Openshift V2 to configure my mysql datasource.

I followed this guide: https://github.com/openshift-s2i/s2i-wildfly

I added a .s2i folder and created there a file called: environment.

I added to the 'environment' file the following key:

```<code>MYSQL_DATABASE=<DATABASE_NAME>
</code>```

The <DATABASE_NAME> is of course replaced with the real database name.

In my standalone.xml I have:

```<code><subsystem xmlns="urn:jboss:domain:datasources:4.0">
    <datasources>
        <datasource jta="false" jndi-name="java:/<DATABASE_NAME>" pool-name="pool_name" enabled="true" use-ccm="false">
            <connection-url>jdbc:mysql://MYSQL_SERVICE_HOST:MYSQL_SERVICE_PORT/<DATABASE_NAME>?useSSL=false</connection-url>
            <driver-class>com.mysql.jdbc.Driver</driver-class>
            <driver>mysql</driver>
            <security>
                <user-name>MYSQL_USER</user-name>
                <password>MYSQL_PASSWORD </password>
            </security>
            <validation>
                <valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLValidConnectionChecker"/>
                <background-validation>true</background-validation>
                <exception-sorter class-name="org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLExceptionSorter"/>
            </validation>
        </datasource>
        <drivers>
            <driver name="mysql" module="com.mysql.jdbc">
                <driver-class>com.mysql.jdbc.Driver</driver-class>
            </driver>
        </drivers>
    </datasources>
</subsystem>
</code>```

When replacing the environment variables by the real values, the mysql connection works and wildfly boots up with success.

What am I doing wrong?

I also prefixed each environment variable in standalone.xml with the dollar sign but still no luck...

答:
In Openshift (for wildfly) you should use this approach to use environment variables:

${env.DATABASE_NAME}

eg:

First you need to add these variables in the DeploymentConfig:

```<code>MYSQL_USER=<mysql_username>
MYSQL_PASSWORD=<mysql_password>
</code>```

If you have created a service named msyql in the same project/naspace of Wildfly's pod you could skip the settings of this other two environment variables:

```<code>MYSQL_SERVICE_HOST=<mysql_host>
MYSQL_SERVICE_PORT=<mysql_port>
</code>```

This because every pod started will have a set of injected environment variables of the other services created before it (like hosts, ports, etc etc).

Then you can configure the datasource:

<subsystem xmlns="urn:jboss:domain:datasources:4.0">
    <datasources>
        <datasource jta="false" jndi-name="java:/${env.DATABASE_NAME}" pool-name="pool_name" enabled="true" use-ccm="false">
            <connection-url>jdbc:mysql://${env.MYSQL_SERVICE_HOST}:${env.MYSQL_SERVICE_PORT}/<DATABASE_NAME>?useSSL=false</connection-url>
            <driver-class>com.mysql.jdbc.Driver</driver-class>
            <driver>mysql</driver>
            <security>
                <user-name>${env.MYSQL_USER}</user-name>
                <password>${env.MYSQL_PASSWORD}</password>
            </security>
            <validation>
                <valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLValidConnectionChecker"/>
                <background-validation>true</background-validation>
                <exception-sorter class-name="org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLExceptionSorter"/>
            </validation>
        </datasource>
        <drivers>
            <driver name="mysql" module="com.mysql.jdbc">
                <driver-class>com.mysql.jdbc.Driver</driver-class>
            </driver>
        </drivers>
    </datasources>
</subsystem>
```

NOTE: I suggest to use the DeploymentConfig environments variables instead of using static variables in the enviroments file in .s2i so you can use the same source repository for different Openshift environments/projects/namespaces (dev, test, integration, prod).

Body:
I have a WildFly 10 pod and a mysql 5.7 pod running in Openshift V3. I would like to use environment variables in my standalone.xml as I was used in Openshift V2 to configure my mysql datasource.

I followed this guide: https://github.com/openshift-s2i/s2i-wildfly

I added a .s2i folder and created there a file called: environment.

I added to the 'environment' file the following key:

MYSQL_DATABASE=<DATABASE_NAME>

The <DATABASE_NAME> is of course replaced with the real database name.

In my standalone.xml I have:

<subsystem xmlns="urn:jboss:domain:datasources:4.0">
    <datasources>
        <datasource jta="false" jndi-name="java:/<DATABASE_NAME>" pool-name="pool_name" enabled="true" use-ccm="false">
            <connection-url>jdbc:mysql://MYSQL_SERVICE_HOST:MYSQL_SERVICE_PORT/<DATABASE_NAME>?useSSL=false</connection-url>
            <driver-class>com.mysql.jdbc.Driver</driver-class>
            <driver>mysql</driver>
            <security>
                <user-name>MYSQL_USER</user-name>
                <password>MYSQL_PASSWORD </password>
            </security>
            <validation>
                <valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLValidConnectionChecker"/>
                <background-validation>true</background-validation>
                <exception-sorter class-name="org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLExceptionSorter"/>
            </validation>
        </datasource>
        <drivers>
            <driver name="mysql" module="com.mysql.jdbc">
                <driver-class>com.mysql.jdbc.Driver</driver-class>
            </driver>
        </drivers>
    </datasources>
</subsystem>

When replacing the environment variables by the real values, the mysql connection works and wildfly boots up with success.

What am I doing wrong?

I also prefixed each environment variable in standalone.xml with the dollar sign but still no luck...

Body:
In Openshift (for wildfly) you should use this approach to use environment variables:

${env.DATABASE_NAME}

eg:

First you need to add these variables in the DeploymentConfig:

MYSQL_USER=<mysql_username>
MYSQL_PASSWORD=<mysql_password>

If you have created a service named msyql in the same project/naspace of Wildfly's pod you could skip the settings of this other two environment variables:

MYSQL_SERVICE_HOST=<mysql_host>
MYSQL_SERVICE_PORT=<mysql_port>

This because every pod started will have a set of injected environment variables of the other services created before it (like hosts, ports, etc etc).

Then you can configure the datasource:

<subsystem xmlns="urn:jboss:domain:datasources:4.0">
    <datasources>
        <datasource jta="false" jndi-name="java:/${env.DATABASE_NAME}" pool-name="pool_name" enabled="true" use-ccm="false">
            <connection-url>jdbc:mysql://${env.MYSQL_SERVICE_HOST}:${env.MYSQL_SERVICE_PORT}/<DATABASE_NAME>?useSSL=false</connection-url>
            <driver-class>com.mysql.jdbc.Driver</driver-class>
            <driver>mysql</driver>
            <security>
                <user-name>${env.MYSQL_USER}</user-name>
                <password>${env.MYSQL_PASSWORD}</password>
            </security>
            <validation>
                <valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLValidConnectionChecker"/>
                <background-validation>true</background-validation>
                <exception-sorter class-name="org.jboss.jca.adapters.jdbc.extensions.mysql.MySQLExceptionSorter"/>
            </validation>
        </datasource>
        <drivers>
            <driver name="mysql" module="com.mysql.jdbc">
                <driver-class>com.mysql.jdbc.Driver</driver-class>
            </driver>
        </drivers>
    </datasources>
</subsystem>

NOTE: I suggest to use the DeploymentConfig environments variables instead of using static variables in the enviroments file in .s2i so you can use the same source repository for different Openshift environments/projects/namespaces (dev, test, integration, prod).


问:
Select element by data attribute
Wish to update some HTML with JSON, and don't want a full blown template engine like handlebars, etc.  Thought I would just assign a data value and iterate over, but I am receiving errors.  Reference https://api.jqueryui.com/data-selector/, however, maybe not applicable with jQuery 3?  How can I select the elements which have a data attribute?

Side note.  While not my question, my end goal is to update the HTML with an object which contains name/values equal to the values of the data attributes I have listed below.  Please comment if there is a better way to do so.  Thanks

```<code><table class='table' id="default-template">
    <tr><td>Server IP</td><td data-name="server"></td></tr>
    <tr><td>Server Port</td><td data-name="port"></td></tr>
    <tr><td>Reconnect Timeout (seconds)</td><td data-name="reconnectTimeout"></td></tr>
    <tr><td>Response Timeout (seconds)</td><td data-name="responseTimeout"></td></tr>
    <tr><td>Verbose Log</td><td data-name="verboseLog"></td></tr>
    <tr><td>Device Static IP</td><td data-name="ip_address"></td></tr>
    <tr><td>Router IP</td><td data-name="router_ip"></td></tr>
    <tr><td>Domain Name Server IP</td><td data-name="domain_name_server_ip"></td></tr>
</table>
</code>```

$('#default-template').find('td:data(name)').each(function(i){
    console.log(i,this);
});
```

display.js:20 {ip_address: "10.120.11.30/24", router_ip: "10.120.11.1", domain_name_server_ip: "10.120.11.1", server: "12.34.56.78", port: "1337", …}

  jquery-3.2.1.js:1580 Uncaught Error: Syntax error, unrecognized expression:   unsupported pseudo: data

      at Function.Sizzle.error (jquery-3.2.1.js:1580)

      at PSEUDO (jquery-3.2.1.js:1927)

      at matcherFromTokens (jquery-3.2.1.js:2476)

      at Sizzle.compile (jquery-3.2.1.js:2630)

      at Sizzle.select (jquery-3.2.1.js:2716)

      at Function.Sizzle [as find] (jquery-3.2.1.js:884)

      at jQuery.fn.init.find (jquery-3.2.1.js:2922)

      at Object.success (display.js:21)

      at fire (jquery-3.2.1.js:3317)

      at Object.fireWith [as resolveWith] (jquery-3.2.1.js:3447)

  Sizzle.error @ jquery-3.2.1.js:1580

  PSEUDO @ jquery-3.2.1.js:1927

  matcherFromTokens @ jquery-3.2.1.js:2476

  Sizzle.compile @ jquery-3.2.1.js:2630

  Sizzle.select @ jquery-3.2.1.js:2716

  Sizzle @ jquery-3.2.1.js:884

  find @ jquery-3.2.1.js:2922

  success @ display.js:21

  fire @ jquery-3.2.1.js:3317

  fireWith @ jquery-3.2.1.js:3447

  done @ jquery-3.2.1.js:9272

  (anonymous) @ jquery-3.2.1.js:9514

  XMLHttpRequest.send (async)

  send @ jquery-3.2.1.js:9566

  ajax @ jquery-3.2.1.js:9173

  (anonymous) @ display.js:16

  dispatch @ jquery-3.2.1.js:5206

  elemData.handle @ jquery-3.2.1.js:5014

答:
Just change it to:

```<code>$('#default-template td[data-name]').each(function(i){
    console.log(i,this);
});
</code>```

That's all that's needed.

Title: Select element by data attribute

Body:
Wish to update some HTML with JSON, and don't want a full blown template engine like handlebars, etc.  Thought I would just assign a data value and iterate over, but I am receiving errors.  Reference https://api.jqueryui.com/data-selector/, however, maybe not applicable with jQuery 3?  How can I select the elements which have a data attribute?

Side note.  While not my question, my end goal is to update the HTML with an object which contains name/values equal to the values of the data attributes I have listed below.  Please comment if there is a better way to do so.  Thanks

Server IP

Server Port

Reconnect Timeout (seconds)

Response Timeout (seconds)

Verbose Log

Device Static IP

Router IP

Domain Name Server IP

$('#default-template').find('td:data(name)').each(function(i){
    console.log(i,this);
});

display.js:20 {ip_address: "10.120.11.30/24", router_ip: "10.120.11.1", domain_name_server_ip: "10.120.11.1", server: "12.34.56.78", port: "1337", …}

  jquery-3.2.1.js:1580 Uncaught Error: Syntax error, unrecognized expression:   unsupported pseudo: data

      at Function.Sizzle.error (jquery-3.2.1.js:1580)

      at PSEUDO (jquery-3.2.1.js:1927)

      at matcherFromTokens (jquery-3.2.1.js:2476)

      at Sizzle.compile (jquery-3.2.1.js:2630)

      at Sizzle.select (jquery-3.2.1.js:2716)

      at Function.Sizzle [as find] (jquery-3.2.1.js:884)

      at jQuery.fn.init.find (jquery-3.2.1.js:2922)

      at Object.success (display.js:21)

      at fire (jquery-3.2.1.js:3317)

      at Object.fireWith [as resolveWith] (jquery-3.2.1.js:3447)

  Sizzle.error @ jquery-3.2.1.js:1580

  PSEUDO @ jquery-3.2.1.js:1927

  matcherFromTokens @ jquery-3.2.1.js:2476

  Sizzle.compile @ jquery-3.2.1.js:2630

  Sizzle.select @ jquery-3.2.1.js:2716

  Sizzle @ jquery-3.2.1.js:884

  find @ jquery-3.2.1.js:2922

  success @ display.js:21

  fire @ jquery-3.2.1.js:3317

  fireWith @ jquery-3.2.1.js:3447

  done @ jquery-3.2.1.js:9272

  (anonymous) @ jquery-3.2.1.js:9514

  XMLHttpRequest.send (async)

  send @ jquery-3.2.1.js:9566

  ajax @ jquery-3.2.1.js:9173

  (anonymous) @ display.js:16

  dispatch @ jquery-3.2.1.js:5206

  elemData.handle @ jquery-3.2.1.js:5014

Body:
Just change it to:

$('#default-template td[data-name]').each(function(i){
    console.log(i,this);
});

That's all that's needed.


问:
Show hide multiple divs based on select value
Looking for some jQuery to help hide and reveal content in a simple form I'm creating.

Picking options 1-3 in the select field should show one of the three data response divs as well as reveal the content in the rest of the form (data-form-order 2).

I think data attributes would be a good route to go down but a little unsure of where to start.

```<code><form>
  <div data-form-order="1">

    <div id="opening-question">
      <select id="select-box">
      <option value="0">- please select -</option>
      <option value="1">Option 1</option>
      <option value="2">Option 2</option>
      <option value="3">Option 3</option>
    </select>
    </div>

    <div data-response="op1">
      This is content for option 1.
    </div>
    <div data-response="op2">
      This is content for option 2.
    </div>
    <div data-response="op3">
      This is content for option 3.
    </div>
  </div>

  <div data-form-order="2" id="other-questions">
    Rest of form content. This area should show when option values 1-3 are selected in the select field.
  </div>
</form>
</code>```

答:
I would suggest using classes for this, there is no need for data attributes.

$(function() {
    $('#select-box').change(function(){
        if($('#select-box').val() == '1') {
            $('.response1').show();
            $('.response2').hide();
            $('.response3').hide();
            $('#content').show();
        }
        else if($('#select-box').val() == '2') {
            $('.response1').hide();
            $('.response2').show();
            $('.response3').hide();
            $('#content').show();
        }
        else if($('#select-box').val() == '3') {
            $('.response1').hide();
            $('.response2').hide();
            $('.response3').show();
            $('#content').show();
        }
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.response1, .response2, .response3 {
  display: none;
}

#content {
  display: none;
}</code>```

<form>

      <select id="select-box">
      <option value="0">- please select -</option>
      <option value="1">Option 1</option>
      <option value="2">Option 2</option>
      <option value="3">Option 3</option>
    </select>

      This is content for option 1.

      This is content for option 2.

      This is content for option 3.

    Rest of form content. This area should show when option values 1-3 are selected in the select field.

</form>```

Body:
Looking for some jQuery to help hide and reveal content in a simple form I'm creating.

Picking options 1-3 in the select field should show one of the three data response divs as well as reveal the content in the rest of the form (data-form-order 2).

I think data attributes would be a good route to go down but a little unsure of where to start.

<form>

      <select id="select-box">
      <option value="0">- please select -</option>
      <option value="1">Option 1</option>
      <option value="2">Option 2</option>
      <option value="3">Option 3</option>
    </select>

      This is content for option 1.

      This is content for option 2.

      This is content for option 3.

    Rest of form content. This area should show when option values 1-3 are selected in the select field.

</form>

Body:
I would suggest using classes for this, there is no need for data attributes.

$(function() {
    $('#select-box').change(function(){
        if($('#select-box').val() == '1') {
            $('.response1').show();
            $('.response2').hide();
            $('.response3').hide();
            $('#content').show();
        }
        else if($('#select-box').val() == '2') {
            $('.response1').hide();
            $('.response2').show();
            $('.response3').hide();
            $('#content').show();
        }
        else if($('#select-box').val() == '3') {
            $('.response1').hide();
            $('.response2').hide();
            $('.response3').show();
            $('#content').show();
        }
    });
});

.response1, .response2, .response3 {
  display: none;
}

#content {
  display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <div data-form-order="1">

    <div id="opening-question">
      <select id="select-box">
      <option value="0">- please select -</option>
      <option value="1">Option 1</option>
      <option value="2">Option 2</option>
      <option value="3">Option 3</option>
    </select>
    </div>

    <div class='response1' data-response="op1">
      This is content for option 1.
    </div>
    <div class='response2' data-response="op2">
      This is content for option 2.
    </div>
    <div class='response3' data-response="op3">
      This is content for option 3.
    </div>
  </div>

  <div id='content' data-form-order="2" id="other-questions">
    Rest of form content. This area should show when option values 1-3 are selected in the select field.
  </div>
</form>


问:
SPLIT URL in PHP
I have below URL in my code and i want to split it and get the number from it

For example from the below URL  need to fetch 123456

https://review-test.com/#/c/123456/

I have tried this and it is not working

```<code>$completeURL  = https://review-test.com/#/c/123456/  ;

  list($url, $number) = explode('#c', preg_replace('/^.*\/+/', '', $completeURL));
</code>```

答:
If you wan to get the /c/123456/ params you will need to execute the following:

```<code>$url = 'https://review-test.com/#/c/123456/';
$url_fragment = parse_url($url, PHP_URL_FRAGMENT);
$fragments = explode('/', $url_fragment);
$fragments = array_filter(array_map('trim', $fragments));
$fragments = array_values($fragments);
</code>```

The PHP_URL_FRAGMENT will return a component of the url after #

After parse_url you will end up with a string like this: '/c/123456/'

The explode('/', $url_fragment); function will return an array with empty indexes where '/' was extracted

In order to remove empty indexes array_filter($fragments); the
array_map with trim option will remove excess spaces. It does not
apply in this case but in real case scenario you better trim.

Now if you var_dump the result you can see that the array needs to
be reindexed array_values($fragments)

Title: SPLIT URL in PHP

Body:
I have below URL in my code and i want to split it and get the number from it

For example from the below URL  need to fetch 123456

https://review-test.com/#/c/123456/

I have tried this and it is not working

$completeURL  = https://review-test.com/#/c/123456/  ;

  list($url, $number) = explode('#c', preg_replace('/^.*\/+/', '', $completeURL));

Body:
If you wan to get the /c/123456/ params you will need to execute the following:

$url = 'https://review-test.com/#/c/123456/';
$url_fragment = parse_url($url, PHP_URL_FRAGMENT);
$fragments = explode('/', $url_fragment);
$fragments = array_filter(array_map('trim', $fragments));
$fragments = array_values($fragments);

The PHP_URL_FRAGMENT will return a component of the url after #

After parse_url you will end up with a string like this: '/c/123456/'

The explode('/', $url_fragment); function will return an array with empty indexes where '/' was extracted

In order to remove empty indexes array_filter($fragments); the
array_map with trim option will remove excess spaces. It does not
apply in this case but in real case scenario you better trim.

Now if you var_dump the result you can see that the array needs to
be reindexed array_values($fragments)


问:
EF Core: Soft delete with shadow properties and query filters
I've created an interface to try to do a soft delete, mixing shadow properties and query filters. But it's not working.

```<code>public interface IDeletableEntity {}
</code>```

And then in my model builder

```<code> builder.Model.GetEntityTypes()
                .Where(entityType => typeof(IDeletableEntity).IsAssignableFrom(entityType.ClrType))
                .ToList()
                .ForEach(entityType =>
                {
                    builder.Entity(entityType.ClrType).Property<Boolean>("IsDeleted");
                    builder.Entity(entityType.ClrType).HasQueryFilter(e => EF.Property<Boolean>(e, "IsDeleted") == false);
                });
</code>```

But the line with the query filter doesn't compile. The error I got is "cannot convert lambda expression to type 'lambda expression' because it is not a delegate type"

If I do this it's working.

```<code>builder.Entity<MyEntity>().HasQueryFilter(m => EF.Property<Boolean>(m, "IsDeleted") == false);
</code>```

there are any way to do this? It's in order to have an Interface with IDeletableEntity and not have to do it, in every Entity that I want to use a soft delete Entity

Many thanks in advance,

答:
HasQueryFilter of the non generic EntityTypeBuilder (as opposed to the generic EntityTypeBuilder<TEntity>) is almost unusable because there is no easy way to create the expected LambdaExpression.

One solution is to build the lambda expression by hand using the Expression class methods:

```<code>.ForEach(entityType =>
{
    builder.Entity(entityType.ClrType).Property<Boolean>("IsDeleted");
    var parameter = Expression.Parameter(entityType.ClrType, "e");
    var body = Expression.Equal(
        Expression.Call(typeof(EF), nameof(EF.Property), new[] { typeof(bool) }, parameter, Expression.Constant("IsDeleted")),
    Expression.Constant(false));
    builder.Entity(entityType.ClrType).HasQueryFilter(Expression.Lambda(body, parameter));
});
</code>```

Another one is to use a prototype expression

```<code>Expression<Func<object, bool>> filter =
    e => EF.Property<bool>(e, "IsDeleted") == false;
</code>```

and use a parameter replacer to bind the parameter with actual type:

```<code>.ForEach(entityType =>
{
    builder.Entity(entityType.ClrType).Property<Boolean>("IsDeleted");
    var parameter = Expression.Parameter(entityType.ClrType, "e");
    var body = filter.Body.ReplaceParameter(filter.Parameters[0], parameter);
    builder.Entity(entityType.ClrType).HasQueryFilter(Expression.Lambda(body, parameter));
});
</code>```

where ReplaceParameter is one of the custom helper extension method I'm using for expression tree manipulation:

```<code>public static partial class ExpressionUtils
{
    public static Expression ReplaceParameter(this Expression expr, ParameterExpression source, Expression target) =>
        new ParameterReplacer { Source = source, Target = target }.Visit(expr);

    class ParameterReplacer : System.Linq.Expressions.ExpressionVisitor
    {
        public ParameterExpression Source;
        public Expression Target;
        protected override Expression VisitParameter(ParameterExpression node) => node == Source ? Target : node;
    }
}
</code>```

But most natural solution in my opinion is to move the configuration code in a generic method and call it via reflection. For instance:

```<code>static void ConfigureSoftDelete<T>(ModelBuilder builder)
    where T : class, IDeletableEntity
{
    builder.Entity<T>().Property<Boolean>("IsDeleted");
    builder.Entity<T>().HasQueryFilter(e => EF.Property<bool>(e, "IsDeleted") == false);
}
</code>```

and then

```<code>.ForEach(entityType => GetType()
    .GetMethod(nameof(ConfigureSoftDelete), BindingFlags.NonPublic | BindingFlags.Static)
    .MakeGenericMethod(entityType.ClrType)
    .Invoke(null, new object[] { builder })
);
</code>```

Body:
I've created an interface to try to do a soft delete, mixing shadow properties and query filters. But it's not working.

public interface IDeletableEntity {}

And then in my model builder

 builder.Model.GetEntityTypes()
                .Where(entityType => typeof(IDeletableEntity).IsAssignableFrom(entityType.ClrType))
                .ToList()
                .ForEach(entityType =>
                {
                    builder.Entity(entityType.ClrType).Property<Boolean>("IsDeleted");
                    builder.Entity(entityType.ClrType).HasQueryFilter(e => EF.Property<Boolean>(e, "IsDeleted") == false);
                });

But the line with the query filter doesn't compile. The error I got is "cannot convert lambda expression to type 'lambda expression' because it is not a delegate type"

If I do this it's working.

builder.Entity<MyEntity>().HasQueryFilter(m => EF.Property<Boolean>(m, "IsDeleted") == false);

there are any way to do this? It's in order to have an Interface with IDeletableEntity and not have to do it, in every Entity that I want to use a soft delete Entity

Many thanks in advance,

Body:
HasQueryFilter of the non generic EntityTypeBuilder (as opposed to the generic EntityTypeBuilder<TEntity>) is almost unusable because there is no easy way to create the expected LambdaExpression.

One solution is to build the lambda expression by hand using the Expression class methods:

.ForEach(entityType =>
{
    builder.Entity(entityType.ClrType).Property<Boolean>("IsDeleted");
    var parameter = Expression.Parameter(entityType.ClrType, "e");
    var body = Expression.Equal(
        Expression.Call(typeof(EF), nameof(EF.Property), new[] { typeof(bool) }, parameter, Expression.Constant("IsDeleted")),
    Expression.Constant(false));
    builder.Entity(entityType.ClrType).HasQueryFilter(Expression.Lambda(body, parameter));
});

Another one is to use a prototype expression

Expression<Func<object, bool>> filter =
    e => EF.Property<bool>(e, "IsDeleted") == false;

and use a parameter replacer to bind the parameter with actual type:

.ForEach(entityType =>
{
    builder.Entity(entityType.ClrType).Property<Boolean>("IsDeleted");
    var parameter = Expression.Parameter(entityType.ClrType, "e");
    var body = filter.Body.ReplaceParameter(filter.Parameters[0], parameter);
    builder.Entity(entityType.ClrType).HasQueryFilter(Expression.Lambda(body, parameter));
});

where ReplaceParameter is one of the custom helper extension method I'm using for expression tree manipulation:

public static partial class ExpressionUtils
{
    public static Expression ReplaceParameter(this Expression expr, ParameterExpression source, Expression target) =>
        new ParameterReplacer { Source = source, Target = target }.Visit(expr);

    class ParameterReplacer : System.Linq.Expressions.ExpressionVisitor
    {
        public ParameterExpression Source;
        public Expression Target;
        protected override Expression VisitParameter(ParameterExpression node) => node == Source ? Target : node;
    }
}

But most natural solution in my opinion is to move the configuration code in a generic method and call it via reflection. For instance:

static void ConfigureSoftDelete<T>(ModelBuilder builder)
    where T : class, IDeletableEntity
{
    builder.Entity<T>().Property<Boolean>("IsDeleted");
    builder.Entity<T>().HasQueryFilter(e => EF.Property<bool>(e, "IsDeleted") == false);
}

and then

.ForEach(entityType => GetType()
    .GetMethod(nameof(ConfigureSoftDelete), BindingFlags.NonPublic | BindingFlags.Static)
    .MakeGenericMethod(entityType.ClrType)
    .Invoke(null, new object[] { builder })
);


问:
Haskell recursive function add to the end of a list
I have a recursive Haskell function that takes a number n and generates a list that is n long of squared numbers from 1 up.

The code works but instead of the list for n=3 being [9,4,1] I want it to be [1,4,9].

```<code>sqNList :: Int -> [Int]
sqNList 0  = []
sqNList n  = n*n : sqNList (n-1)
</code>```

I've tried swappig the : for a ++ but then the pattern matching doesn't work. I have only just started Haskell today so may be obvious

答:
The best approach is to implement sqNList in terms of a helper function that counts from 1 up to n.  That way you can just generate the list in the correct order in the first place.

```<code>sqNList :: Int -> [Int]
sqNList n = sqNListHelper 1 n

sqNListHelper :: Int -> Int -> [Int]
sqNListHelper current end = ...
</code>```

There are a wide variety of more sophisticated approaches, but this is the easiest approach to debug/test interactively that also has you figuring out how to do everything yourself.

More sophisticated approaches can include list comprehensions or composing functions like map and enumFromTo to build up the logic from simpler pieces.

Body:
I have a recursive Haskell function that takes a number n and generates a list that is n long of squared numbers from 1 up.

The code works but instead of the list for n=3 being [9,4,1] I want it to be [1,4,9].

sqNList :: Int -> [Int]
sqNList 0  = []
sqNList n  = n*n : sqNList (n-1)

I've tried swappig the : for a ++ but then the pattern matching doesn't work. I have only just started Haskell today so may be obvious

Body:
The best approach is to implement sqNList in terms of a helper function that counts from 1 up to n.  That way you can just generate the list in the correct order in the first place.

sqNList :: Int -> [Int]
sqNList n = sqNListHelper 1 n

sqNListHelper :: Int -> Int -> [Int]
sqNListHelper current end = ...

There are a wide variety of more sophisticated approaches, but this is the easiest approach to debug/test interactively that also has you figuring out how to do everything yourself.

More sophisticated approaches can include list comprehensions or composing functions like map and enumFromTo to build up the logic from simpler pieces.


问:
Django BooleanField not returning value on post if default is given
I have this model:-

```<code>class ModelA(models.Model):
    billing_same_as_mailing = models.BooleanField(default=True, label='...')
</code>```

And this form:-

```<code>class ModelAForm(forms.ModelForm):
    class Meta:
        model = ModelA
        fields = ['billing_same_as_mailing']
</code>```

And in my template I have tried the field with:-
    {{ form.billing_same_as_mailing }}

Now when I post, the value of billing_same_as_mailing is always false in the cleaned_data.
But if I set the default value of the BooleanField as False in the model, everything works fine.

Now when I inspect the checkbox element on the browser, this is what I get:-
With default=False:-

```<code><input class="" id="billing_same_as_mailing" name="billing_same_as_mailing" type="checkbox">
</code>```

With default=True:-

```<code><input checked="checked" class="" id="id_billing_same_as_mailing" name="billing_same_as_mailing" type="checkbox" value="">
</code>```

Why is this happening??

答:
You need to set value="on" So the input element looks like this -

<input type="checkbox" class="icheckbox" id="id_billing_same_as_mailing"  name="billing_same_as_mailing" {% if form.billing_same_as_mailing.value %} checked="checked" {% endif %} value="on">

I tried rendering the form using one of the default options Django provides and logging request.POST in the view. For a Boolean Field it is {u'billing_same_as_mailing' : [u'on']}.

Since this is a model form, if we ensure that request.POST looks like what ModelAForm expects, it will map it to corresponding fields. You can use this method to check if you need to modify other input elements too

Body:
I have this model:-

class ModelA(models.Model):
    billing_same_as_mailing = models.BooleanField(default=True, label='...')

And this form:-

class ModelAForm(forms.ModelForm):
    class Meta:
        model = ModelA
        fields = ['billing_same_as_mailing']

And in my template I have tried the field with:-
    {{ form.billing_same_as_mailing }}

Now when I post, the value of billing_same_as_mailing is always false in the cleaned_data.
But if I set the default value of the BooleanField as False in the model, everything works fine.

Now when I inspect the checkbox element on the browser, this is what I get:-
With default=False:-

<input class="" id="billing_same_as_mailing" name="billing_same_as_mailing" type="checkbox">

With default=True:-

<input checked="checked" class="" id="id_billing_same_as_mailing" name="billing_same_as_mailing" type="checkbox" value="">

Why is this happening??


答:
The easiest approach that consumes probably the least amount of memory is to work with an accumulator: a parameter you pass and update through every recursive call.

Right now you use n as an accumulator, and decrement that, but we can decide to use an accumulator i instead that starts at 1, and keeps incrementing:

```<code>helper :: Int -> Int -> [Int]
helper i n | i > n = []
           | otherwise = i*i : helper (i+1) n</code>```

Now we of course have to call it with i = 1 ourselves, which is not ideal, but we can use a where clause that scopes the helper in the sqNList:

```<code>sqNList :: Int -> [Int]
sqNList n = helper 1 n
    where helper :: Int -> Int -> [Int]
          helper i n | i > n = []
                     | otherwise = i*i : helper (i+1) n</code>```

Now we can improve this a bit. For instanc there is no need to pass n through the helper calls, since it does not change, and is defined at the top level:

```<code>sqNList :: Int -> [Int]
sqNList n = helper 1
    where helper :: Int -> [Int]
          helper i | i > n = []
                   | otherwise = i*i : helper (i+1)</code>```

There is furthermore no need to only work with Ints: we can use any type a for which Num a and Ord a:

```<code>sqNList :: (Num a, Ord a) => a -> [a]
sqNList n = helper 1
    where helper i | i > n = []
                   | otherwise = i*i : helper (i+1)</code>```

Title: Haskell recursive function add to the end of a list

Body:
The easiest approach that consumes probably the least amount of memory is to work with an accumulator: a parameter you pass and update through every recursive call.

Right now you use n as an accumulator, and decrement that, but we can decide to use an accumulator i instead that starts at 1, and keeps incrementing:

helper :: Int -> Int -> [Int]
helper i n | i > n = []
           | otherwise = i*i : helper (i+1) n

Now we of course have to call it with i = 1 ourselves, which is not ideal, but we can use a where clause that scopes the helper in the sqNList:

sqNList :: Int -> [Int]
sqNList n = helper 1 n
    where helper :: Int -> Int -> [Int]
          helper i n | i > n = []
                     | otherwise = i*i : helper (i+1) n

Now we can improve this a bit. For instanc there is no need to pass n through the helper calls, since it does not change, and is defined at the top level:

sqNList :: Int -> [Int]
sqNList n = helper 1
    where helper :: Int -> [Int]
          helper i | i > n = []
                   | otherwise = i*i : helper (i+1)

There is furthermore no need to only work with Ints: we can use any type a for which Num a and Ord a:

sqNList :: (Num a, Ord a) => a -> [a]
sqNList n = helper 1
    where helper i | i > n = []
                   | otherwise = i*i : helper (i+1)


问:
How to get data from parsedJSON reactJS
I'm setting up a basic WebApp here using ReactJS. Right now I can add data to my database using POST request no problem, the thing, my backend response sends me a JSON with all the data that I passed and the _id in the database. I need to get this _id and save it in my state so I can pass it along to the next URL in my WebApp. That's the code for my POST request :

```<code>  SubmitClick(){

    if (this.state.password !== this.state.reTypepassword){
      alert('Passwords do not match. Please check your data !');
    } else {
      //console.log(this.state); //debug only
      fetch('http://localhost:4000/users/', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          //'Authorization': 'Basic YWRtaW46c3VwZXJzZWNyZXQ=',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          email: this.state.email,
          first_name: this.state.first_name,
          last_name: this.state.last_name,
          personal_phone: this.state.personal_phone,
          password: this.state.password
        })
      })
      .then(response => response.json())
      .then(parsedJSON => console.log(parsedJSON._id))
      .catch(error => alert('Check your data', error))
      .then(this.props.history.push('/get')) // change page layout and URL
    }
    console.log(this.state.id); //debug to see if the _id is saved in my state
  }
</code>```

Here is my constructor:

```<code>  constructor(props){
    super(props);
    this.state={
      email:'',
      first_name:'',
      last_name:'',
      personal_phone:'',
      password:'',
      reTypepassword:'',
      id:''
    }
  }
</code>```

I tried calling a function after parsedJSON that used this.setState(), using function(parsedJSON){this.state.id : parsedJSON._id}. I tried with a new function like this:

```<code>  changeID(parsedJSON){
    this.setState({id : parsedJSON._id})
  }
</code>```

and changing the .then(parsedJSON => console.log(parsedJSON._id)) to .then(parsedJSON => this.cahngeID(parsedJSON)). But none of then worked...

I left the code with .then(parsedJSON => console.log(parsedJSON._id)) so can make sure that I can see this value, and in my console it`s printed perfectly.

Here is a example of the response send by my backend:    {"email":"testing@gmail.com","first_name":"TESTER","last_name":"Testing","personal_phone":"(55) 2020-5252","password":"12345","_id":"5a27f511cd7d7a0db8ab65b9"}

How can I get the "_id" from my response?

答:
At the end of your constructor add this line of code:

```<code>this.SubmitClick = this.SubmitClick.bind(this);
</code>```

because JavaScript does not bind the instance value of 'this' to our methods.

Title: How to get data from parsedJSON reactJS

Body:
I'm setting up a basic WebApp here using ReactJS. Right now I can add data to my database using POST request no problem, the thing, my backend response sends me a JSON with all the data that I passed and the _id in the database. I need to get this _id and save it in my state so I can pass it along to the next URL in my WebApp. That's the code for my POST request :

  SubmitClick(){

    if (this.state.password !== this.state.reTypepassword){
      alert('Passwords do not match. Please check your data !');
    } else {
      //console.log(this.state); //debug only
      fetch('http://localhost:4000/users/', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          //'Authorization': 'Basic YWRtaW46c3VwZXJzZWNyZXQ=',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          email: this.state.email,
          first_name: this.state.first_name,
          last_name: this.state.last_name,
          personal_phone: this.state.personal_phone,
          password: this.state.password
        })
      })
      .then(response => response.json())
      .then(parsedJSON => console.log(parsedJSON._id))
      .catch(error => alert('Check your data', error))
      .then(this.props.history.push('/get')) // change page layout and URL
    }
    console.log(this.state.id); //debug to see if the _id is saved in my state
  }

Here is my constructor:

  constructor(props){
    super(props);
    this.state={
      email:'',
      first_name:'',
      last_name:'',
      personal_phone:'',
      password:'',
      reTypepassword:'',
      id:''
    }
  }

I tried calling a function after parsedJSON that used this.setState(), using function(parsedJSON){this.state.id : parsedJSON._id}. I tried with a new function like this:

  changeID(parsedJSON){
    this.setState({id : parsedJSON._id})
  }

and changing the .then(parsedJSON => console.log(parsedJSON._id)) to .then(parsedJSON => this.cahngeID(parsedJSON)). But none of then worked...

I left the code with .then(parsedJSON => console.log(parsedJSON._id)) so can make sure that I can see this value, and in my console it`s printed perfectly.

Here is a example of the response send by my backend:    {"email":"testing@gmail.com","first_name":"TESTER","last_name":"Testing","personal_phone":"(55) 2020-5252","password":"12345","_id":"5a27f511cd7d7a0db8ab65b9"}

How can I get the "_id" from my response?

Body:
At the end of your constructor add this line of code:

this.SubmitClick = this.SubmitClick.bind(this);

because JavaScript does not bind the instance value of 'this' to our methods.


问:
R - gsub issues when writing csv
I am trying to gsub() the code below:

"\r\n\t\t\t\t\t\t\t\t\tThird tier -  England\t\t\t\t\t\t\t\t"

So far I have used

```<code>Player_data$Player_League_Level = gsub('\n','',gsub('\t','',gsub('\r','',Player_data$Player_League_Level)))
</code>```

Which produces:   "Third tier -  England"

However when I write the data.frame into a csv. The data produced looks like this in Excel:

Third tierÂ -Â Â England

How do I remove the 'Â' for when I write the data.frame into a csv.

答:
The characters in your string "Third tierÂ -Â Â England" looks like Non-ASCII characters. In this case, you could remove Non-ASCII characters, as below:</p>

```<code>iconv("Third tierÂ -Â Â England", "latin1", "ASCII", sub="")
#[1] "Third tier -  England"
</code>```

Title: R - gsub issues when writing csv

Body:
I am trying to gsub() the code below:

"\r\n\t\t\t\t\t\t\t\t\tThird tier -  England\t\t\t\t\t\t\t\t"

So far I have used

Player_data$Player_League_Level = gsub('\n','',gsub('\t','',gsub('\r','',Player_data$Player_League_Level)))

Which produces:   "Third tier -  England"

However when I write the data.frame into a csv. The data produced looks like this in Excel:

Third tierÂ -Â Â England

How do I remove the 'Â' for when I write the data.frame into a csv.

Body:
The characters in your string "Third tierÂ -Â Â England" looks like Non-ASCII characters. In this case, you could remove Non-ASCII characters, as below:

iconv("Third tierÂ -Â Â England", "latin1", "ASCII", sub="")
#[1] "Third tier -  England"


问:
call linkbutton event on page load in asp.net
I am calling the link button event on page load which is not working as there is no sender for the click.
but when I tried to create a new object it gives an error.</p>

```<code> lnkFirst_Click(new object(),new CommandEventArgs());
</code>```

答:
I'm guessing you are using Webforms.

By default your "linkbutton event" does not exist.
You need to create a method for it (usually with an Object/EventArgs as argument)

```<code>void lnkFirst_Click(Object sender, EventArgs e){}
</code>```

After that, you add a handler to call that function (You will probably want to add that on the page load), which is triggered when the request was called with a click on the linkbutton.

```<code>lnkFirst.Click += new EventHandler(this.lnkFirst_Click);
</code>```

To call it manually, you can do:

```<code>lnkFirst_Click(lnkFirst, null);
//or
lnkFirst_Click(null, null);
</code>```

That depends on if you NEED or not to use the Object Sender or the EventArgs e.

Of course you can also rename the lnkFirst_Click method to whathever name you want.

Body:
I am calling the link button event on page load which is not working as there is no sender for the click.
but when I tried to create a new object it gives an error.

 lnkFirst_Click(new object(),new CommandEventArgs());

Body:
I'm guessing you are using Webforms.

By default your "linkbutton event" does not exist.
You need to create a method for it (usually with an Object/EventArgs as argument)

void lnkFirst_Click(Object sender, EventArgs e){}

After that, you add a handler to call that function (You will probably want to add that on the page load), which is triggered when the request was called with a click on the linkbutton.

lnkFirst.Click += new EventHandler(this.lnkFirst_Click);

To call it manually, you can do:

lnkFirst_Click(lnkFirst, null);
//or
lnkFirst_Click(null, null);

That depends on if you NEED or not to use the Object Sender or the EventArgs e.

Of course you can also rename the lnkFirst_Click method to whathever name you want.


问:
Highlight difference between two step data (derived from histogram) in R
:-)

I have two datasets where I derived histogram data from. These are both saved in two seperate arrays. The current sourcecode can be found below, along with the current plot.

```<code># DEMO file for the awesome stackoverflow community
require(plotrix)

# clear the global environment ----
rm(list=ls())

# Assign demo data ----
data_T  <- c(rep(1,5),rep(2,10),rep(3,8),rep(4,2),rep(5,7),rep(6,2),rep(7,13),rep(9,7))
data_P  <- c(rep(1,1),rep(2,4),rep(3,1),rep(4,7),rep(5,12),rep(6,10),rep(7,9),rep(10,2))

# Setting the limits of the result data ----
uxlimit                     <- 10
lxlimit                     <- 0
classes                     <- (uxlimit-lxlimit)
xtics                       <- seq(lxlimit,uxlimit)
uylimit                     <- 20
lylimit                     <- 0
yrange                      <- seq(lylimit,uylimit, by = 5)

# filter out of necessary ----
data_T [ data_T > uxlimit ] <- NaN
data_T [ data_T < lxlimit ] <- NaN
data_T                      <- na.omit(data_T)

# Setting the x-label and y-label according to the requested spectrum ----
xlabel                      <- "x-value / x-unit"
ylabel                      <- "y-value / y-unit"

# generate histogram data ----
data_T_hist <- hist(data_T,
                    breaks = seq(lxlimit,uxlimit,l = classes+1),
                    plot = F)

data_P_hist <- hist(data_P,
                    breaks = seq(lxlimit,uxlimit,l = classes+1),
                    plot = F)

# Plot data_T_hist ----
plot(data_T_hist$breaks,
     c(data_T_hist$counts,0),
     xlab=xlabel,
     ylab=ylabel,
     ylim = c(lylimit,uylimit),
     xlim = c(lxlimit,uxlimit),
     main="Histogram data",
     axes=F,
     type="s",
     col="red",
     lwd=4,
     panel.first = grid(nx=NULL, ny=NULL))

# Plot data_P_hist ----
lines(data_P_hist$breaks,
      c(data_P_hist$counts,0),
        xlab=xlabel,
        ylab=ylabel,
        ylim = c(lylimit,uylimit),
        xlim = c(lxlimit, uxlimit),
        type="s",
        col="blue",
        lwd=4,
        lty=2)

# Frame all plots with a solid border ----
box(which = "plot", lty = "solid")

# Add legend to the top right of all plots ----
legend("topright",
       c("data_T_hist", "data_P_hist"),
       col=c("red","blue"),
       bg = "white",
       lwd=4)

# Setting the axes right ----
axis(1, at=xtics, labels=NULL, tick = TRUE)
axis(2, at=yrange, labels=yrange, las=1)

# FINISHED! ----
message ("Finished!")
</code>```

The resulting plot is like this (and should be reproducable by you):
I cant link images yet, so here is the link

So, this is okay for now.

However, I want to highlight the difference in the histograms visually. Of course I can calculate the difference, which is good because I need  that too, but I also want to highlight the differences to show the the interesting areas. The final picture should look something like this Again the link

I would not necessarily need a color-discrimination between positive and negative difference, it would be nice though. I have no idea how to shade the areas in between the step data.

Can someone help me with this? One more thing, due to some restrictions, I am not allowed to use too many additional packages. I am using "R version 3.1.1 (2014-07-10) -- "Sock it to Me""

Thank you so much in advance!

答:
To discriminate between positive and negative difference, I added a little condition to the code. It's working like a charm! The complete code is below</p>

```<code># DEMO file for the awesome stackoverflow community

# TikzDevice is required to produce .tex files ----
require(plotrix)

# clear the global environment ----
rm(list=ls())

# Assign demo data ----
data_T  <- c(rep(1,5),rep(2,10),rep(3,8),rep(4,2),rep(5,7),rep(6,2),rep(7,13),rep(9,7))
data_P  <- c(rep(1,1),rep(2,4),rep(3,1),rep(4,7),rep(5,12),rep(6,10),rep(7,9),rep(10,2))

# Setting the limits of the result data ----
uxlimit                     <- 10
lxlimit                     <- 0
classes                     <- (uxlimit-lxlimit)
xtics                       <- seq(lxlimit,uxlimit)
uylimit                     <- 20
lylimit                     <- 0
yrange                      <- seq(lylimit,uylimit, by = 5)

# filter out of necessary ----
data_T [ data_T > uxlimit ] <- NaN
data_T [ data_T < lxlimit ] <- NaN
data_T                      <- na.omit(data_T)

# Setting the x-label and y-label according to the requested spectrum ----
xlabel                      <- "x-value / x-unit"
ylabel                      <- "y-value / y-unit"

# generate histogram data ----
data_T_hist <- hist(data_T,
                    breaks = seq(lxlimit,uxlimit,l = classes+1),
                    plot = F)

data_P_hist <- hist(data_P,
                    breaks = seq(lxlimit,uxlimit,l = classes+1),
                    plot = F)

# Plot data_T_hist ----
plot(data_T_hist$breaks,
     c(data_T_hist$counts,0),
     xlab=xlabel,
     ylab=ylabel,
     ylim = c(lylimit,uylimit),
     xlim = c(lxlimit,uxlimit),
     main="Histogram data",
     axes=F,
     type="s",
     col="red",
     lwd=4,
     panel.first = grid(nx=NULL, ny=NULL))

#Get pairwise min
y_low <-c(pmin(data_T_hist$counts, data_P_hist$counts),0)

#Get pairwise max
y_high <- c(pmax(data_T_hist$counts, data_P_hist$counts),0)

for(i in 2:length(xtics)-1){
  if (data_T_hist$counts[i] < data_P_hist$counts[i]) {
    colselect <- "powderblue"
  } else {
    colselect <- "sienna1"
  }
  rect(xtics[i], y_low[i], xtics[i+1],y_high[i], col=colselect, border = NA)
}

# Plot data_P_hist ----
lines(data_P_hist$breaks,
      c(data_P_hist$counts,0),
        xlab=xlabel,
        ylab=ylabel,
        ylim = c(lylimit,uylimit),
        xlim = c(lxlimit, uxlimit),
        type="s",
        col="blue",
        lwd=4,
        lty=2)

# Plot data_P_hist again to keep borders in the background
lines(data_T_hist$breaks,
      c(data_T_hist$counts,0),
      xlab=xlabel,
      ylab=ylabel,
      ylim = c(lylimit,uylimit),
      xlim = c(lxlimit, uxlimit),
      type="s",
      col="red",
      lwd=4,
      lty=2)

# Frame all plots with a solid border ----
box(which = "plot", lty = "solid")

# Add legend to the top right of all plots ----
legend("topright",
       c("data_T_hist", "data_P_hist"),
       col=c("red","blue"),
       bg = "white",
       lwd=4)

# Setting the axes right ----
axis(1, at=xtics, labels=NULL, tick = TRUE)
axis(2, at=yrange, labels=yrange, las=1)

# FINISHED! ----
message ("Finished!")
</code>```

Body:
:-)

I have two datasets where I derived histogram data from. These are both saved in two seperate arrays. The current sourcecode can be found below, along with the current plot.

# DEMO file for the awesome stackoverflow community
require(plotrix)

# clear the global environment ----
rm(list=ls())

# Assign demo data ----
data_T  <- c(rep(1,5),rep(2,10),rep(3,8),rep(4,2),rep(5,7),rep(6,2),rep(7,13),rep(9,7))
data_P  <- c(rep(1,1),rep(2,4),rep(3,1),rep(4,7),rep(5,12),rep(6,10),rep(7,9),rep(10,2))

# Setting the limits of the result data ----
uxlimit                     <- 10
lxlimit                     <- 0
classes                     <- (uxlimit-lxlimit)
xtics                       <- seq(lxlimit,uxlimit)
uylimit                     <- 20
lylimit                     <- 0
yrange                      <- seq(lylimit,uylimit, by = 5)

# filter out of necessary ----
data_T [ data_T > uxlimit ] <- NaN
data_T [ data_T < lxlimit ] <- NaN
data_T                      <- na.omit(data_T)

# Setting the x-label and y-label according to the requested spectrum ----
xlabel                      <- "x-value / x-unit"
ylabel                      <- "y-value / y-unit"

# generate histogram data ----
data_T_hist <- hist(data_T,
                    breaks = seq(lxlimit,uxlimit,l = classes+1),
                    plot = F)

data_P_hist <- hist(data_P,
                    breaks = seq(lxlimit,uxlimit,l = classes+1),
                    plot = F)

# Plot data_T_hist ----
plot(data_T_hist$breaks,
     c(data_T_hist$counts,0),
     xlab=xlabel,
     ylab=ylabel,
     ylim = c(lylimit,uylimit),
     xlim = c(lxlimit,uxlimit),
     main="Histogram data",
     axes=F,
     type="s",
     col="red",
     lwd=4,
     panel.first = grid(nx=NULL, ny=NULL))

# Plot data_P_hist ----
lines(data_P_hist$breaks,
      c(data_P_hist$counts,0),
        xlab=xlabel,
        ylab=ylabel,
        ylim = c(lylimit,uylimit),
        xlim = c(lxlimit, uxlimit),
        type="s",
        col="blue",
        lwd=4,
        lty=2)

# Frame all plots with a solid border ----
box(which = "plot", lty = "solid")

# Add legend to the top right of all plots ----
legend("topright",
       c("data_T_hist", "data_P_hist"),
       col=c("red","blue"),
       bg = "white",
       lwd=4)

# Setting the axes right ----
axis(1, at=xtics, labels=NULL, tick = TRUE)
axis(2, at=yrange, labels=yrange, las=1)

# FINISHED! ----
message ("Finished!")

The resulting plot is like this (and should be reproducable by you):
I cant link images yet, so here is the link

So, this is okay for now.

However, I want to highlight the difference in the histograms visually. Of course I can calculate the difference, which is good because I need  that too, but I also want to highlight the differences to show the the interesting areas. The final picture should look something like this Again the link

I would not necessarily need a color-discrimination between positive and negative difference, it would be nice though. I have no idea how to shade the areas in between the step data.

Can someone help me with this? One more thing, due to some restrictions, I am not allowed to use too many additional packages. I am using "R version 3.1.1 (2014-07-10) -- "Sock it to Me""

Thank you so much in advance!

Body:
To discriminate between positive and negative difference, I added a little condition to the code. It's working like a charm! The complete code is below

# DEMO file for the awesome stackoverflow community

# TikzDevice is required to produce .tex files ----
require(plotrix)

# clear the global environment ----
rm(list=ls())

# Assign demo data ----
data_T  <- c(rep(1,5),rep(2,10),rep(3,8),rep(4,2),rep(5,7),rep(6,2),rep(7,13),rep(9,7))
data_P  <- c(rep(1,1),rep(2,4),rep(3,1),rep(4,7),rep(5,12),rep(6,10),rep(7,9),rep(10,2))

# Setting the limits of the result data ----
uxlimit                     <- 10
lxlimit                     <- 0
classes                     <- (uxlimit-lxlimit)
xtics                       <- seq(lxlimit,uxlimit)
uylimit                     <- 20
lylimit                     <- 0
yrange                      <- seq(lylimit,uylimit, by = 5)

# filter out of necessary ----
data_T [ data_T > uxlimit ] <- NaN
data_T [ data_T < lxlimit ] <- NaN
data_T                      <- na.omit(data_T)

# Setting the x-label and y-label according to the requested spectrum ----
xlabel                      <- "x-value / x-unit"
ylabel                      <- "y-value / y-unit"

# generate histogram data ----
data_T_hist <- hist(data_T,
                    breaks = seq(lxlimit,uxlimit,l = classes+1),
                    plot = F)

data_P_hist <- hist(data_P,
                    breaks = seq(lxlimit,uxlimit,l = classes+1),
                    plot = F)

# Plot data_T_hist ----
plot(data_T_hist$breaks,
     c(data_T_hist$counts,0),
     xlab=xlabel,
     ylab=ylabel,
     ylim = c(lylimit,uylimit),
     xlim = c(lxlimit,uxlimit),
     main="Histogram data",
     axes=F,
     type="s",
     col="red",
     lwd=4,
     panel.first = grid(nx=NULL, ny=NULL))

#Get pairwise min
y_low <-c(pmin(data_T_hist$counts, data_P_hist$counts),0)

#Get pairwise max
y_high <- c(pmax(data_T_hist$counts, data_P_hist$counts),0)

for(i in 2:length(xtics)-1){
  if (data_T_hist$counts[i] < data_P_hist$counts[i]) {
    colselect <- "powderblue"
  } else {
    colselect <- "sienna1"
  }
  rect(xtics[i], y_low[i], xtics[i+1],y_high[i], col=colselect, border = NA)
}

# Plot data_P_hist ----
lines(data_P_hist$breaks,
      c(data_P_hist$counts,0),
        xlab=xlabel,
        ylab=ylabel,
        ylim = c(lylimit,uylimit),
        xlim = c(lxlimit, uxlimit),
        type="s",
        col="blue",
        lwd=4,
        lty=2)

# Plot data_P_hist again to keep borders in the background
lines(data_T_hist$breaks,
      c(data_T_hist$counts,0),
      xlab=xlabel,
      ylab=ylabel,
      ylim = c(lylimit,uylimit),
      xlim = c(lxlimit, uxlimit),
      type="s",
      col="red",
      lwd=4,
      lty=2)

# Frame all plots with a solid border ----
box(which = "plot", lty = "solid")

# Add legend to the top right of all plots ----
legend("topright",
       c("data_T_hist", "data_P_hist"),
       col=c("red","blue"),
       bg = "white",
       lwd=4)

# Setting the axes right ----
axis(1, at=xtics, labels=NULL, tick = TRUE)
axis(2, at=yrange, labels=yrange, las=1)

# FINISHED! ----
message ("Finished!")


问:
Google cloud storage does not let me remove bucket with huge data
I have around 200 gb of data on a google cloud coldline bucket. When i try to remove it, it keeps preparing forever.

Any way to remove the bucket ?

答:
Try the gsutil tool if you have been trying with the Console and it did not work. To do so, you can just open Google Cloud Shell (most left button in the top right corner of the Console) and type a command like:

```<code>gsutil -m rm -r gs://[BUCKET_NAME]
</code>```

It may take a while, but with the -r flag you will be deleting first the contents of the bucket recursively, and later delete the bucket itself. The -m flag performs parallel removes, to speed up the process.

Body:
Try the gsutil tool if you have been trying with the Console and it did not work. To do so, you can just open Google Cloud Shell (most left button in the top right corner of the Console) and type a command like:

gsutil -m rm -r gs://[BUCKET_NAME]

It may take a while, but with the -r flag you will be deleting first the contents of the bucket recursively, and later delete the bucket itself. The -m flag performs parallel removes, to speed up the process.


问:
How to add a project to the gerrit code review tool?
How do I manually add a project to the gerrit code review tool?

I've seen some examples that execute a gerrit binary but my installation doesn't appear to have one of these.

答:
For older Gerrit versions, you need to use the ssh interface.  Set up your public key in the web interface then run:

```<code>ssh -p <port> <user>@<gerrit-host> gerrit --help
</code>```

This will list you the available commands.  What you actually need to run to create your project is:

```<code>ssh -p <port> <user>@<gerrit-host> gerrit create-project -n <project-name>
</code>```

In Gerrit 2.3 and newer, you may alternatively create projects from the UI, by going to Admin->Projects->Create New Project.

Body:
For older Gerrit versions, you need to use the ssh interface.  Set up your public key in the web interface then run:

ssh -p <port> <user>@<gerrit-host> gerrit --help

This will list you the available commands.  What you actually need to run to create your project is:

ssh -p <port> <user>@<gerrit-host> gerrit create-project -n <project-name>

In Gerrit 2.3 and newer, you may alternatively create projects from the UI, by going to Admin->Projects->Create New Project.


问:
How to push public GitHub repo to private repo using PhpStorm?
I'm using PhpStorm to create a custom WordPress plugin.  I cloned the CMB2 repo from GitHub into my plugin directory and saved the directory as CMB2.  The files and directory are saved on my local machine without issue, and the WordPress local instance has no problem finding files required from the CMB2 directory.

I then committed my custom plugin to a private GitHub repo that I host.  The CMB2 directory was part of the commit.  However, the private repo only shows the directory name without any files contained therein.  As such, when I install the plugin to a production WordPress instance, all required files in the CMB2 directory fail because CMB2 is empty.

I did git status on the CMB2 folder and shows that it was committed.  What other steps should be taken to ensure the contents of CMB2 are properly committed?

答:
When you clone a repository using git, it is put under a separate repository. From your description, it seems like your plugin resides in one git repository, and the CMB2 resides in a different nested one. So when you push, changes done to your plugin code goes to your GitHub repository, but changes in the CMB2 don't go anywhere.

You could check where the repository root is using the git rev-parse --show-toplevel command. Run it inside CMB2 folder, and then inside your plugin folder. They will most likely return you different roots.

If ti is the case, and you have two repositories, but still you want to include CMB2 contents into your primary repo, delete the CMB2/.git folder.

But do you really need to include CMB2 code into your plugin? Seems there are better ways e.g. https://github.com/CMB2/CMB2/issues/624


问:
Bundling not working in MVC5 when I turn on release mode
I have the following bundle configured in BundleConfig.cs:

```<code>bundles.Add(new StyleBundle("~/bundles/css").Include(
                      "~/assets/bootstrap/css/bootstrap.css",
                      "~/assets/css/global/all.css"));
</code>```

and I reference it using the following:

```<code>@Styles.Render("~/bundles/css")
</code>```

When I'm in debug mode (web.config compilation debug="true") it works as expected in that it renders both css files as normal ie:

```<code><link href="/assets/bootstrap/css/bootstrap.css" rel="stylesheet"/>
<link href="/assets/css/global/all.css" rel="stylesheet"/>
</code>```

However when I set debug="false" the above behaviour still occurs in that it does recognise the files, however it's just rendering them as normal.

To confirm bundling can definitely work I've enabled optimizations in BundleConfig ie BundleTable.EnableOptimizations = true;

Whenever I do the above, it bundles the css and appears as expected ie:

```<code><link href="/bundles/css?v=WBKHkZAJly7jUzHrVDT8SwfaQE-CA9dbOUQUlLKadNE1" rel="stylesheet"/>
</code>```

EDIT:

A few people have mentioned that adding the following code to my BundleConfig.cs file will achieve what I am after:

```<code>#if DEBUG
            BundleTable.EnableOptimizations = false;
#else
            BundleTable.EnableOptimizations = true;
#endif
</code>```

I understand and appreciate this response, however according to the documentation, the default behaviour of MVC bundling is to bundle in release mode but not in debug mode. I don't see why I should need to add extra code to make it do this when it should be doing it already.

EDIT 2

I've a confession to make.  It turns out I had the web.config from the Views folder opened and not the main web.config.  I changed the setting in the main web.config and this works just fine for me. I blame ReSharper

答:
Another possible issue is that inside of your Global.asax.cs file in the Application_Start() method, you're missing the call to your BundleConfig.

For example, assuming your method is using the default name RegisterBundles(BundleCollection bundles) then inside of your Global.asax.cs file, you'll want to add BundleConfig.RegisterBundles(BundleTable.Bundles); in the Application_Start() method.

So your Global.asax.cs file might look something like this:

```<code>using System;
using System.Collection.Generic;
using System.Linq;
using System.Web;
using System.Http;
using System.Mvc;
using System.Routing;
using System.Optimization;

namespace MyProject
{
    public class MvcApplication : System.Web.HttpApplication
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);

        // ** This line right below might be what you are missing **
        BundleConfig.RegisterBundles(BundleTable.Bundles);

    }
}
</code>```

Body:
I have the following bundle configured in BundleConfig.cs:

bundles.Add(new StyleBundle("~/bundles/css").Include(
                      "~/assets/bootstrap/css/bootstrap.css",
                      "~/assets/css/global/all.css"));

and I reference it using the following:

@Styles.Render("~/bundles/css")

When I'm in debug mode (web.config compilation debug="true") it works as expected in that it renders both css files as normal ie:

<link href="/assets/bootstrap/css/bootstrap.css" rel="stylesheet"/>
<link href="/assets/css/global/all.css" rel="stylesheet"/>

However when I set debug="false" the above behaviour still occurs in that it does recognise the files, however it's just rendering them as normal.

To confirm bundling can definitely work I've enabled optimizations in BundleConfig ie BundleTable.EnableOptimizations = true;

Whenever I do the above, it bundles the css and appears as expected ie:

<link href="/bundles/css?v=WBKHkZAJly7jUzHrVDT8SwfaQE-CA9dbOUQUlLKadNE1" rel="stylesheet"/>

EDIT:

A few people have mentioned that adding the following code to my BundleConfig.cs file will achieve what I am after:

#if DEBUG
            BundleTable.EnableOptimizations = false;
#else
            BundleTable.EnableOptimizations = true;
#endif

I understand and appreciate this response, however according to the documentation, the default behaviour of MVC bundling is to bundle in release mode but not in debug mode. I don't see why I should need to add extra code to make it do this when it should be doing it already.

EDIT 2

I've a confession to make.  It turns out I had the web.config from the Views folder opened and not the main web.config.  I changed the setting in the main web.config and this works just fine for me. I blame ReSharper

Body:
Another possible issue is that inside of your Global.asax.cs file in the Application_Start() method, you're missing the call to your BundleConfig.

For example, assuming your method is using the default name RegisterBundles(BundleCollection bundles) then inside of your Global.asax.cs file, you'll want to add BundleConfig.RegisterBundles(BundleTable.Bundles); in the Application_Start() method.

So your Global.asax.cs file might look something like this:

using System;
using System.Collection.Generic;
using System.Linq;
using System.Web;
using System.Http;
using System.Mvc;
using System.Routing;
using System.Optimization;

namespace MyProject
{
    public class MvcApplication : System.Web.HttpApplication
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);

        // ** This line right below might be what you are missing **
        BundleConfig.RegisterBundles(BundleTable.Bundles);

    }
}


问:
How to use Windsor IoC in ASP.net Core 2
How can I use Castle Windsor as an IOC instead of the default .net core IOC container?

I have built a service resolver that depends on WindsorContainer to resolve services.

Something like:

```<code>public class ServiceResolver
{
    private static WindsorContainer container;
    public ServiceResolver()
    {
        container = new WindsorContainer();
        // a method to register components in container
        RegisterComponents(container);
    }

    public IList<T> ResolveAll<T>()
    {
        return container.ResolveAll<T>().ToList();
    }
}
</code>```

Can not figure out how to let my .net core 2 web API use this resolver as a replacement for IServiceCollection.

答:
For others Reference In addition to the solution Nkosi provided.

There is a nuget package called Castle.Windsor.MsDependencyInjection that will provide you with the following method:

```<code>WindsorRegistrationHelper.CreateServiceProvider(WindsorContainer,IServiceCollection);
</code>```

Which's returned type is IServiceProvider and you will not need to create you own wrapper.

So the solution will be like:

```<code>public class ServiceResolver{
    private static WindsorContainer container;
    private static IServiceProvider serviceProvider;

    public ServiceResolver(IServiceCollection services) {
        container = new WindsorContainer();
        //Register your components in container
        //then
        serviceProvider = WindsorRegistrationHelper.CreateServiceProvider(container, services);
    }

    public IServiceProvider GetServiceProvider() {
        return serviceProvider;
    }
}
</code>```

and in Startup...

```<code>public IServiceProvider ConfigureServices(IServiceCollection services) {
    services.AddMvc();
    // Add other framework services

    // Add custom provider
    var container = new ServiceResolver(services).GetServiceProvider();
    return container;
}
</code>```

Body:
How can I use Castle Windsor as an IOC instead of the default .net core IOC container?

I have built a service resolver that depends on WindsorContainer to resolve services.

Something like:

public class ServiceResolver
{
    private static WindsorContainer container;
    public ServiceResolver()
    {
        container = new WindsorContainer();
        // a method to register components in container
        RegisterComponents(container);
    }

    public IList<T> ResolveAll<T>()
    {
        return container.ResolveAll<T>().ToList();
    }
}

Can not figure out how to let my .net core 2 web API use this resolver as a replacement for IServiceCollection.

Body:
For others Reference In addition to the solution Nkosi provided.

There is a nuget package called Castle.Windsor.MsDependencyInjection that will provide you with the following method:

WindsorRegistrationHelper.CreateServiceProvider(WindsorContainer,IServiceCollection);

Which's returned type is IServiceProvider and you will not need to create you own wrapper.

So the solution will be like:

public class ServiceResolver{
    private static WindsorContainer container;
    private static IServiceProvider serviceProvider;

    public ServiceResolver(IServiceCollection services) {
        container = new WindsorContainer();
        //Register your components in container
        //then
        serviceProvider = WindsorRegistrationHelper.CreateServiceProvider(container, services);
    }

    public IServiceProvider GetServiceProvider() {
        return serviceProvider;
    }
}

and in Startup...

public IServiceProvider ConfigureServices(IServiceCollection services) {
    services.AddMvc();
    // Add other framework services

    // Add custom provider
    var container = new ServiceResolver(services).GetServiceProvider();
    return container;
}


问:
Make flex items wrap after third item on mobile
I have set a row of thumbnails using flex and this works fine, they are centered vertically on desktop. How can I have on mobile screen 3 images in the first row and 2 images in the second row? Images in second row should be aligned to the left.

div {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}
img {
  padding: 10px 5px;
  margin: auto;
}
@media only screen and (max-width: 480px) {
  div {
    flex-wrap: wrap;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <img src="http://placehold.it/150/220" alt="" />
  <img src="http://placehold.it/200/250" alt="" />
  <img src="http://placehold.it/240/100" alt="" />
  <img src="http://placehold.it/250/220" alt="" />
  <img src="http://placehold.it/200/270" alt="" />
</div></code>```

http://codepen.io/anon/pen/akLbzV

答:
If you can't use width or flex-basis (for ex. because your elements have varying widths and you need space-between) and you're OK with using extra
, you can do something like this:

```<code><div>
  <img src="http://placehold.it/150/220" alt="" />
  <img src="http://placehold.it/200/250" alt="" />
  <img src="http://placehold.it/240/100" alt="" />
  <div class="flex-break"/>
  <img src="http://placehold.it/250/220" alt="" />
  <img src="http://placehold.it/200/270" alt="" />
</div>
</code>```

CSS:

```<code>.flex-wrap {
   width: 100%;
}

@media only screen and (min-width: 481px) {
  display: none;
}
</code>```

It's not the most beautiful solution but it solves the problem.

Body:
I have set a row of thumbnails using flex and this works fine, they are centered vertically on desktop. How can I have on mobile screen 3 images in the first row and 2 images in the second row? Images in second row should be aligned to the left.

div {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}
img {
  padding: 10px 5px;
  margin: auto;
}
@media only screen and (max-width: 480px) {
  div {
    flex-wrap: wrap;
  }
}

http://codepen.io/anon/pen/akLbzV

Body:
If you can't use width or flex-basis (for ex. because your elements have varying widths and you need space-between) and you're OK with using extra <div/>, you can do something like this:

<div>
  <img src="http://placehold.it/150/220" alt="" />
  <img src="http://placehold.it/200/250" alt="" />
  <img src="http://placehold.it/240/100" alt="" />
  <div class="flex-break"/>
  <img src="http://placehold.it/250/220" alt="" />
  <img src="http://placehold.it/200/270" alt="" />
</div>

CSS:

.flex-wrap {
   width: 100%;
}

@media only screen and (min-width: 481px) {
  display: none;
}

It's not the most beautiful solution but it solves the problem.


问:
How to compare with a string array and string
I want to compare one string with the string array because I need to match a phone number if it starts with some specific number then I need to do something.

Here is what I'm doing now. But I want to make this simpler.

```<code>string[] startNumList = new string[] {"4", "5", "6", "7", "8" };
foreach (string x in startNumList)
{
      if(request.ReferenceNumber.StartsWith(x))
       {
            //do something
       }
 }
</code>```

I was jut wondering if this is possible to do the same with one line LINQ.
Thanks in advance.

答:
It's hard to give a definitive answer to this sort of question, but I'd go with this:</p>

```<code>var matchingStartNumber = startNumList.FirstOrDefault(x => request.ReferenceNumber.StartsWith(x));
if (matchingStartNumber != null)
{
    // Do stuff with startNum
}
</code>```

Body:
I want to compare one string with the string array because I need to match a phone number if it starts with some specific number then I need to do something.

Here is what I'm doing now. But I want to make this simpler.

string[] startNumList = new string[] {"4", "5", "6", "7", "8" };
foreach (string x in startNumList)
{
      if(request.ReferenceNumber.StartsWith(x))
       {
            //do something
       }
 }

I was jut wondering if this is possible to do the same with one line LINQ.
Thanks in advance.

Body:
It's hard to give a definitive answer to this sort of question, but I'd go with this:

var matchingStartNumber = startNumList.FirstOrDefault(x => request.ReferenceNumber.StartsWith(x));
if (matchingStartNumber != null)
{
    // Do stuff with startNum
}


问:
Is there a way to execute JavaScript in Perl?
I've worked some years now in Perl building Web scrapers, and given the problem that spam represents, and how scraping Web pages would turn out to be much more easier to those folks if, for example, Perl's LWP::UserAgent could handle its cup of JavaScript, I'm amazed no one has built a JS engine for it yet.

What am I missing here?

Thanks in advance. Regards.

PS: I'm not a spammer. Just curious.

答: Would you mean something like JavaScript::SpiderMonkey, a Perl interface to a JavaScript engine used by Mozilla?</p>

ContentLicense: CC BY-SA 2.5


问:
How to cut uuid in golang?
In order to make semi-random slugs, I'd like to use first 8 characters of uuid. So I have

```<code>import (
    fmt
    "github.com/satori/go.uuid"
)

    u1 := uuid.NewV4()
    fmt.Println("u1 :", u1)

    runes := []rune(u1)
    slug := string(runes[0:7])
</code>```

But in compile time I get this error:

cannot convert u1 (type uuid.UUID) to type []rune

How can I fix it?

答:
There is no need to convert the UUID to a []rune. That UUID type is stored in a binary representation as a [16]byte. There is a UUID.String() method which you can use to convert to a string, then slice it.

```<code> slug := u1.String()[:7]
</code>```

Title: How to cut uuid in golang?

Body:
In order to make semi-random slugs, I'd like to use first 8 characters of uuid. So I have

import (
    fmt
    "github.com/satori/go.uuid"
)

    u1 := uuid.NewV4()
    fmt.Println("u1 :", u1)

    runes := []rune(u1)
    slug := string(runes[0:7])

But in compile time I get this error:

cannot convert u1 (type uuid.UUID) to type []rune

How can I fix it?

Body:
There is no need to convert the UUID to a []rune. That UUID type is stored in a binary representation as a [16]byte. There is a UUID.String() method which you can use to convert to a string, then slice it.

 slug := u1.String()[:7]