问:
Conditionally skip subproject in multi-module Gradle build
Consider the following Gradle project structure:

```<code>- root
|- build.gradle
|- barProject
 |- build.gradle
|- fooProject
 |- build.gradle
</code>```

where the root build.gradle configures its subprojects like so:

```<code>subprojects {
    apply plugin: 'java'

    //bunch of other stuff
}
</code>```

Now when I call gradlew build on the root project it automatically configures both subprojects and then builds them - all well and good.

I also know that I can skip a specific task with various means (onlyIf(), [taskName].enabled = false, etc.) but when I utilize any of those on build Gradle still runs all the dependent tasks (compileJava, processResources, classes, etc.) until finally hitting build which it then skips.

My question is, is there any way to have Gradle stop and go to the next subproject right after the configuration phase?

EDIT:

To clarify; each subproject has a property called skip that is evaluated in the configuration phase.

Now when I call gradlew build on the root project I want Gradle to, ideally, check that property and if it's true then to completely skip the corresponding project.

```<code>Executing external task 'build'...

//check project.skip -> IF true -> skip project, go to :foo ELSE continue
:bar:compileJava
:bar:processResources UP-TO-DATE
:bar:classes
:bar:jar
:bar:startScripts
:bar:distTar
:bar:distZip
:bar:assemble
:bar:compileTestJava UP-TO-DATE
:bar:processTestResources UP-TO-DATE
:bar:testClasses UP-TO-DATE
:bar:test UP-TO-DATE
:bar:check UP-TO-DATE
:bar:build

//check project.skip -> IF true -> skip project, go to end ELSE continue
:foo:compileJava
:foo:processResources UP-TO-DATE
:foo:classes
:foo:jar
:foo:startScripts
:foo:distTar
:foo:distZip
:foo:assemble
:foo:compileTestJava UP-TO-DATE
:foo:processTestResources UP-TO-DATE
:foo:testClasses UP-TO-DATE
:foo:test UP-TO-DATE
:foo:check UP-TO-DATE
:foo:build

BUILD SUCCESSFUL
</code>```

I hope this makes more sense

答:
Well, first of all: An easy solution would be calling exactly the task(s) you need. In simple Gradle builds, task names are unique. However, in multi-project builds, each project can have a task with a specific name. This is the reason why Gradle introduced task paths. Task paths combine the unique project paths with the intra-project unique task names: :projectX:taskY.

Using project paths, you can easily specify the project-specific task you want to execute: :build for the build task in the root project and :<subproject>:build for the build task in a subproject. If a task name, e.g. build, is provided for a multi-project build, Gradle will search through any project (root and subs) for a task with the specified name and execute them all. This explains the current behaviour.

The task names for execution are managed by a StartParameter object of the Gradle Settings. These Settings can be modified in your settings.gradle file, where you also include subprojects:

```<code>include ':foo', ':bar'

startParameter.excludedTaskNames += ':foo:build'
</code>```

This line excludes the build task of the foo subproject from the execution. You could add the subproject task path (even independent from the task name) to the excluded task names, if a specific condition is met. But, I did not find a way to access the Settings in your build file, so this solution can not be used during configuration phase. However, if your condition is solely based on project / system properties, they can be accessed from settings.gradle.

Another solution for the configuration phase came to my mind, but it's basically what you already mentioned, because it simply skips the tasks:

```<code>if (project.skip) {
    project.tasks.all { task -> task.enabled = false }
}
</code>```

This way, all tasks from the project (not only the build task) will be skipped.

Please consider, that tasks can also be executed, because they create a dependency for another project. Even gradle :bar:build will execute the task :foo:jar and its task dependencies, if foo is a project dependency of bar. You can disable this behaviour with the Gradle command line options -a or --no-rebuild or the following entry in your settings.gradle:

```<code>startParameter.buildProjectDependencies = false
</code>```

Body:
Consider the following Gradle project structure:

- root
|- build.gradle
|- barProject
 |- build.gradle
|- fooProject
 |- build.gradle

where the root build.gradle configures its subprojects like so:

subprojects {
    apply plugin: 'java'

    //bunch of other stuff
}

Now when I call gradlew build on the root project it automatically configures both subprojects and then builds them - all well and good.

I also know that I can skip a specific task with various means (onlyIf(), [taskName].enabled = false, etc.) but when I utilize any of those on build Gradle still runs all the dependent tasks (compileJava, processResources, classes, etc.) until finally hitting build which it then skips.

My question is, is there any way to have Gradle stop and go to the next subproject right after the configuration phase?

EDIT:

To clarify; each subproject has a property called skip that is evaluated in the configuration phase.

Now when I call gradlew build on the root project I want Gradle to, ideally, check that property and if it's true then to completely skip the corresponding project.

Executing external task 'build'...

//check project.skip -> IF true -> skip project, go to :foo ELSE continue
:bar:compileJava
:bar:processResources UP-TO-DATE
:bar:classes
:bar:jar
:bar:startScripts
:bar:distTar
:bar:distZip
:bar:assemble
:bar:compileTestJava UP-TO-DATE
:bar:processTestResources UP-TO-DATE
:bar:testClasses UP-TO-DATE
:bar:test UP-TO-DATE
:bar:check UP-TO-DATE
:bar:build

//check project.skip -> IF true -> skip project, go to end ELSE continue
:foo:compileJava
:foo:processResources UP-TO-DATE
:foo:classes
:foo:jar
:foo:startScripts
:foo:distTar
:foo:distZip
:foo:assemble
:foo:compileTestJava UP-TO-DATE
:foo:processTestResources UP-TO-DATE
:foo:testClasses UP-TO-DATE
:foo:test UP-TO-DATE
:foo:check UP-TO-DATE
:foo:build

BUILD SUCCESSFUL

I hope this makes more sense

Body:
Well, first of all: An easy solution would be calling exactly the task(s) you need. In simple Gradle builds, task names are unique. However, in multi-project builds, each project can have a task with a specific name. This is the reason why Gradle introduced task paths. Task paths combine the unique project paths with the intra-project unique task names: :projectX:taskY.

Using project paths, you can easily specify the project-specific task you want to execute: :build for the build task in the root project and :<subproject>:build for the build task in a subproject. If a task name, e.g. build, is provided for a multi-project build, Gradle will search through any project (root and subs) for a task with the specified name and execute them all. This explains the current behaviour.

The task names for execution are managed by a StartParameter object of the Gradle Settings. These Settings can be modified in your settings.gradle file, where you also include subprojects:

include ':foo', ':bar'

startParameter.excludedTaskNames += ':foo:build'

This line excludes the build task of the foo subproject from the execution. You could add the subproject task path (even independent from the task name) to the excluded task names, if a specific condition is met. But, I did not find a way to access the Settings in your build file, so this solution can not be used during configuration phase. However, if your condition is solely based on project / system properties, they can be accessed from settings.gradle.

Another solution for the configuration phase came to my mind, but it's basically what you already mentioned, because it simply skips the tasks:

if (project.skip) {
    project.tasks.all { task -> task.enabled = false }
}

This way, all tasks from the project (not only the build task) will be skipped.

Please consider, that tasks can also be executed, because they create a dependency for another project. Even gradle :bar:build will execute the task :foo:jar and its task dependencies, if foo is a project dependency of bar. You can disable this behaviour with the Gradle command line options -a or --no-rebuild or the following entry in your settings.gradle:

startParameter.buildProjectDependencies = false


来源: stackexchange

问:
Creating a new table and setting the expiration date in bigquery using Python
This is my code that pulls the realtime database from firebase, formats it in a Json, uploads to the cloud and then to BQ.

```<code>#standardsql
import json
import boto
import gcs_oauth2_boto_plugin
import os
import shutil
import StringIO
import tempfile
import time
import argparse
import uuid

from firebase import firebase
from google.cloud import storage
from google.cloud.storage import blob
from google.cloud import bigquery

firebase = firebase.FirebaseApplication('https://dataworks-356fa.firebaseio.com/')
result = firebase.get('/connection_info', None)
id_keys = map(str, result.keys())

with open("firetobq.json", "w") as outfile:
  for id in id_keys:
    json.dump(result[id], outfile, indent=None)
    outfile.write("\n")

client = storage.Client(project='dataworks-356fa')
bucket = client.get_bucket('dataworks-356fa-backups')
blob = bucket.blob('firetobq.json')
with open('firetobq.json', 'rb') as f:
  blob.upload_from_file(f)

dataset = 'dataworks-356fa'
source = 'gs://dataworks-356fa-backups/firetobq.json'

def load_data_from_gcs(dataset, test12, source):
    bigquery_client = bigquery.Client(dataset)
    dataset = bigquery_client.dataset('FirebaseArchive')
    table = dataset.table('test12')
    job_name = str(uuid.uuid4())
    job1.create_disposition = 'WRITE_TRUNCATE'
    job1.begin()

    job= bigquery_client.load_table_from_storage(
        job_name, table, "gs://dataworks-356fa-backups/firetobq.json")
    job.source_format = 'NEWLINE_DELIMITED_JSON'

    job.begin()
    wait_for_job(job)

def wait_for_job(job):
    while True:
        job.reload()
        if job.state == 'DONE':
            if job.error_result:
                raise RuntimeError(job.errors)
            return
        time.sleep(1)

load_data_from_gcs(dataset, 'test12', source)
</code>```

How can I change this to instead of importing the data in table test12 to creating a new table and also having that table expire after 1 week. (Im pretty sure the command for setting the expiration date has to be in seconds. 1 week = 604800 seconds) I know how to set the expiration date via the command line but would rather have it done here automatically.

And this is the error I am receiving after adding job1.

```<code>Traceback (most recent call last):
  File "firebasetobq2.py", line 63, in <module>
    load_data_from_gcs(dataset, 'test12', source)
  File "firebasetobq2.py", line 44, in load_data_from_gcs
    job1.create_disposition = 'WRITE_TRUNCATE'
NameError: global name 'job1' is not defined
</code>```

答:
If you want to set an expiration time for your table, this might do the trick:

```<code>from datetime import datetime, timedelta
from google.cloud.bigquery.schema import SchemaField

def load_data_from_gcs(dataset,
                   table_name,
                   table_schema,
                   source,
                   source_format,
                   expiration_time):
    bigquery_client = bigquery.Client()
    dataset = bigquery_client.dataset(dataset)
    table = dataset.table(table_name)
    table.schema = table_schema
    table.expires = expiration_time
    if not table.created:
        table.create()

    job_name = str(uuid.uuid4())
    job= bigquery_client.load_table_from_storage(
        job_name, table, source)
    job.source_format = source_format

    job.begin()
    wait_for_job(job)

dataset = 'FirebaseArchive'
table_name = 'test12'
gcs_source = 'gs://dataworks-356fa-backups/firetobq.json'
source_format = 'NEWLINE_DELIMITED_JSON'
table.schema = [SchemaField(field1), SchemaField(field2), (...)]
expiration_time = datetime.now() + timedelta(seconds=604800)

load_data_from_gcs(dataset,
                   table_name,
                   table_schema,
                   gcs_source,
                   source_format,
                   expiration_time)
</code>```

Notice the only difference is the lines of code where it sets:

```<code>table.expires = expiration_time
</code>```

Whose value must be of type datetime (here defined as expiration_time = datetime.now() + timedelta(seconds=604800))

Not sure if it's possible to use schema auto-detection using the Python API but you still can send this information using the SchemaFields. For instance, if your table have two fields, user_id and job_id,  both being INTEGERS, then the schema would be:

```<code>table_schema = [SchemaField('user_id', field_type='INT64'),
                SchemaField('job_id', field_type='INT64')]
</code>```

More information on how schema works in BigQuery you can find here.

[EDIT]:

Just saw your other question, if you want to truncate the table and then write data to it, you can just do:

```<code>job.create_disposition = 'WRITE_TRUNCATE'
job.begin()
</code>```

In your load_data_from_gcs function. This will automatically delete the table and create a new one with the data from your storage file. You won't have to define a schema for that as it's already previously defined (therefore might be a much easier solution for you).

ContentLicense: CC BY-SA 3.0

Body:
This is my code that pulls the realtime database from firebase, formats it in a Json, uploads to the cloud and then to BQ.

#standardsql
import json
import boto
import gcs_oauth2_boto_plugin
import os
import shutil
import StringIO
import tempfile
import time
import argparse
import uuid

from firebase import firebase
from google.cloud import storage
from google.cloud.storage import blob
from google.cloud import bigquery

firebase = firebase.FirebaseApplication('https://dataworks-356fa.firebaseio.com/')
result = firebase.get('/connection_info', None)
id_keys = map(str, result.keys())

with open("firetobq.json", "w") as outfile:
  for id in id_keys:
    json.dump(result[id], outfile, indent=None)
    outfile.write("\n")

client = storage.Client(project='dataworks-356fa')
bucket = client.get_bucket('dataworks-356fa-backups')
blob = bucket.blob('firetobq.json')
with open('firetobq.json', 'rb') as f:
  blob.upload_from_file(f)

dataset = 'dataworks-356fa'
source = 'gs://dataworks-356fa-backups/firetobq.json'

def load_data_from_gcs(dataset, test12, source):
    bigquery_client = bigquery.Client(dataset)
    dataset = bigquery_client.dataset('FirebaseArchive')
    table = dataset.table('test12')
    job_name = str(uuid.uuid4())
    job1.create_disposition = 'WRITE_TRUNCATE'
    job1.begin()

    job= bigquery_client.load_table_from_storage(
        job_name, table, "gs://dataworks-356fa-backups/firetobq.json")
    job.source_format = 'NEWLINE_DELIMITED_JSON'

    job.begin()
    wait_for_job(job)

def wait_for_job(job):
    while True:
        job.reload()
        if job.state == 'DONE':
            if job.error_result:
                raise RuntimeError(job.errors)
            return
        time.sleep(1)

load_data_from_gcs(dataset, 'test12', source)

How can I change this to instead of importing the data in table test12 to creating a new table and also having that table expire after 1 week. (Im pretty sure the command for setting the expiration date has to be in seconds. 1 week = 604800 seconds) I know how to set the expiration date via the command line but would rather have it done here automatically.

And this is the error I am receiving after adding job1.

Traceback (most recent call last):
  File "firebasetobq2.py", line 63, in <module>
    load_data_from_gcs(dataset, 'test12', source)
  File "firebasetobq2.py", line 44, in load_data_from_gcs
    job1.create_disposition = 'WRITE_TRUNCATE'
NameError: global name 'job1' is not defined

Body:
If you want to set an expiration time for your table, this might do the trick:

from datetime import datetime, timedelta
from google.cloud.bigquery.schema import SchemaField

def load_data_from_gcs(dataset,
                   table_name,
                   table_schema,
                   source,
                   source_format,
                   expiration_time):
    bigquery_client = bigquery.Client()
    dataset = bigquery_client.dataset(dataset)
    table = dataset.table(table_name)
    table.schema = table_schema
    table.expires = expiration_time
    if not table.created:
        table.create()

    job_name = str(uuid.uuid4())
    job= bigquery_client.load_table_from_storage(
        job_name, table, source)
    job.source_format = source_format

    job.begin()
    wait_for_job(job)

dataset = 'FirebaseArchive'
table_name = 'test12'
gcs_source = 'gs://dataworks-356fa-backups/firetobq.json'
source_format = 'NEWLINE_DELIMITED_JSON'
table.schema = [SchemaField(field1), SchemaField(field2), (...)]
expiration_time = datetime.now() + timedelta(seconds=604800)

load_data_from_gcs(dataset,
                   table_name,
                   table_schema,
                   gcs_source,
                   source_format,
                   expiration_time)

Notice the only difference is the lines of code where it sets:

table.expires = expiration_time

Whose value must be of type datetime (here defined as expiration_time = datetime.now() + timedelta(seconds=604800))

Not sure if it's possible to use schema auto-detection using the Python API but you still can send this information using the SchemaFields. For instance, if your table have two fields, user_id and job_id,  both being INTEGERS, then the schema would be:

table_schema = [SchemaField('user_id', field_type='INT64'),
                SchemaField('job_id', field_type='INT64')]

More information on how schema works in BigQuery you can find here.

[EDIT]:

Just saw your other question, if you want to truncate the table and then write data to it, you can just do:

job.create_disposition = 'WRITE_TRUNCATE'
job.begin()

In your load_data_from_gcs function. This will automatically delete the table and create a new one with the data from your storage file. You won't have to define a schema for that as it's already previously defined (therefore might be a much easier solution for you).


问:
Pass multiple filenames from Cloud functions to Dataflow
As stated in my previous post I was trying to pass a single file's name from Cloud Function to Dataflow. What if I uploaded multiple files at a time in a GCS bucket? Is it possible to have a single Cloud Function capture and send all the filenames by using event.data? If not any other way I could get those file names in my Dataflow program?

Thank You

答: To run this in a single pipeline you would need to create a custom source that took a list of file names (or a single string that was the concatened file names, etc.) and then use that source with an appropriate runtime PipelineOption.</p>


问:
Getting list of network devices inside the Linux kernel
I've been looking through net/core/dev.c and other files to try to find out how to get the list of network devices that are currently configured and it's proving to be a little difficult to find.

The end goal is to be able to get network device statistics using dev_get_stats in dev.c, but I need to know the current interfaces so I can grab the net_device struct to pass in. I'm having to do this inside the kernel as I'm writing a module which adds in a new /proc/ entry which relates to some statistics from the current network devices so from what I can gather this must be done inside the kernel.

If someone could point me to how to get the interfaces it would be much appreciated.

答:
Given a struct net *net identifying the net namespace that you are interested in, you should grab the dev_base_lock and use for_each_netdev():

```<code>read_lock(&dev_base_lock);
for_each_netdev(net, dev) {
   /* Inspect dev */
}
read_unlock(&dev_base_lock);
</code>```

(In newer kernels, you can use RCU instead, but that is probably an overcomplication in this case).

To obtain the net namespace to use, you should be registering your proc file with register_pernet_subsys():

```<code>static const struct file_operations foostats_seq_fops = {
    .owner   = THIS_MODULE,
    .open    = foostats_seq_open,
    .read    = seq_read,
    .llseek  = seq_lseek,
    .release = foostats_seq_release,
};

static int foo_proc_init_net(struct net *net)
{
    if (!proc_net_fops_create(net, "foostats", S_IRUGO,
            &foostats_seq_fops))
        return -ENOMEM;
    return 0;
}

static void foo_proc_exit_net(struct net *net)
{
    proc_net_remove(net, "foostats");
}

static struct pernet_operations foo_proc_ops = {
    .init = foo_proc_init_net,
    .exit = foo_proc_exit_net,
};

register_pernet_subsys(&foo_proc_ops)
</code>```

In your foostats_seq_open() function, you take a reference on the net namespace, and drop it in the release function:

```<code>static int foostats_seq_open(struct inode *inode, struct file *file)
{
    int err;
    struct net *net;

    err = -ENXIO;
    net = get_proc_net(inode);
    if (net == NULL)
        goto err_net;

    err = single_open(file, foostats_seq_show, net);
    if (err < 0)
        goto err_open;

    return 0;

err_open:
    put_net(net);
err_net:
    return err;
}

static int foostats_seq_release(struct inode *inode, struct file *file)
{
    struct net *net = ((struct seq_file *)file->private_data)->private;

    put_net(net);
    return single_release(inode, file);
}
</code>```

The foostats_seq_show() function can then obtain the net, walk the devices, gather the statistics and produce the output:

```<code>static int sockstat6_seq_show(struct seq_file *seq, void *v)
{
    struct net *net = seq->private;
    struct net_device *dev;

    int foostat, barstat;

    read_lock(&dev_base_lock);
    for_each_netdev(net, dev) {
       /* Inspect dev */
    }
    read_unlock(&dev_base_lock);

    seq_printf(seq, "Foo: %d\n", foostat);
    seq_printf(seq, "Bar: %d\n", barstat);

    return 0;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Given a struct net *net identifying the net namespace that you are interested in, you should grab the dev_base_lock and use for_each_netdev():

read_lock(&dev_base_lock);
for_each_netdev(net, dev) {
   /* Inspect dev */
}
read_unlock(&dev_base_lock);

(In newer kernels, you can use RCU instead, but that is probably an overcomplication in this case).

To obtain the net namespace to use, you should be registering your proc file with register_pernet_subsys():

static const struct file_operations foostats_seq_fops = {
    .owner   = THIS_MODULE,
    .open    = foostats_seq_open,
    .read    = seq_read,
    .llseek  = seq_lseek,
    .release = foostats_seq_release,
};

static int foo_proc_init_net(struct net *net)
{
    if (!proc_net_fops_create(net, "foostats", S_IRUGO,
            &foostats_seq_fops))
        return -ENOMEM;
    return 0;
}

static void foo_proc_exit_net(struct net *net)
{
    proc_net_remove(net, "foostats");
}

static struct pernet_operations foo_proc_ops = {
    .init = foo_proc_init_net,
    .exit = foo_proc_exit_net,
};

register_pernet_subsys(&foo_proc_ops)

In your foostats_seq_open() function, you take a reference on the net namespace, and drop it in the release function:

static int foostats_seq_open(struct inode *inode, struct file *file)
{
    int err;
    struct net *net;

    err = -ENXIO;
    net = get_proc_net(inode);
    if (net == NULL)
        goto err_net;

    err = single_open(file, foostats_seq_show, net);
    if (err < 0)
        goto err_open;

    return 0;

err_open:
    put_net(net);
err_net:
    return err;
}

static int foostats_seq_release(struct inode *inode, struct file *file)
{
    struct net *net = ((struct seq_file *)file->private_data)->private;

    put_net(net);
    return single_release(inode, file);
}

The foostats_seq_show() function can then obtain the net, walk the devices, gather the statistics and produce the output:

static int sockstat6_seq_show(struct seq_file *seq, void *v)
{
    struct net *net = seq->private;
    struct net_device *dev;

    int foostat, barstat;

    read_lock(&dev_base_lock);
    for_each_netdev(net, dev) {
       /* Inspect dev */
    }
    read_unlock(&dev_base_lock);

    seq_printf(seq, "Foo: %d\n", foostat);
    seq_printf(seq, "Bar: %d\n", barstat);

    return 0;
}


问:
port name issue of those are defined in the BlackBox
Say there is a B Module in which A is a instance.

```<code>class B extends Module {
  …
  val u_A = Module(new A)
    // the way to hook u_A’s port is the issue
}
</code>```

The description of A Module:

```<code>class A extends Module {
  val io = IO(new Bundle{
    val a = Output(Bool())
  })
  io.a := true.B
}
</code>```

The declaration of A BlackBox:

```<code>class A extends BlackBox {
  val io = IO(new Bundle{
    val io_a = Output(Bool()) // HAVE to define port name with io_* prefix otherwise ...
  })
}
</code>```

You MUST define the port name in BlackBox with prefix of io_ otherwise the generated port list in B RTL won’t match to the A Module.
for the Module instantiation, the way to hook u_A’s port is

```<code>u_A.io.a
</code>```

for the BlackBox instantiation, the way to hook u_A’s port is

```<code>u_A.io.io_a
</code>```

Could you enlight me about whether there is a more convinience way?

答:
The mismatch between BlackBox and Module io emission is a legacy API for better integration with Verilog IP where the Chisel designer has little to no control over the Verilog. We are thinking about a more explicit and structured way to handle such "invisible" bundles that drop their prefix since there are other cases where they would be useful.

To answer your question though, there is a more convenient way. We are experimenting with what we call "multi IO modules" where you can use IO(...) multiple times inside of a Module to create ports. You don't actually need that feature here, but it gives us chisel3.experimental.ExtModule--an alternative to BlackBox. ExtModule does not silently drop the prefix so if you switch to extending it instead of BlackBox you will get the desired behavior.

Body:
Say there is a B Module in which A is a instance.

class B extends Module {
  …
  val u_A = Module(new A)
    // the way to hook u_A’s port is the issue
}

The description of A Module:

class A extends Module {
  val io = IO(new Bundle{
    val a = Output(Bool())
  })
  io.a := true.B
}

The declaration of A BlackBox:

class A extends BlackBox {
  val io = IO(new Bundle{
    val io_a = Output(Bool()) // HAVE to define port name with io_* prefix otherwise ...
  })
}

You MUST define the port name in BlackBox with prefix of io_ otherwise the generated port list in B RTL won’t match to the A Module.
for the Module instantiation, the way to hook u_A’s port is

u_A.io.a

for the BlackBox instantiation, the way to hook u_A’s port is

u_A.io.io_a

Could you enlight me about whether there is a more convinience way?


问:
how to know sitecore website using which search engine
There are couple of websites in our origination developed in sitecore using a mix of solr and lucene search. Is it possible to figure out which sites use which search engine without looking at the code? </p>

答: You can't, reliably, but you could find out through looking at the source. For instance, if there are instances of Coveo in the source code that's your answer, as Sitecore running it will show this. Further to this if a developer has created a component referencing Lucene or Solr by name, you could confirm it that way. Of course seeing the configs tell you everything but as you said you're trying to find out without gaining admin access.</p>


问:
Javascript: Bubble Sort
I have made a bubble sort algorithm (sorta) using JS. It works sometimes, but the problem is that it only iterates through the array once. Here is my code:</p>

```<code>function bubble(arr) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] > arr[i + 1]) {
      var a = arr[i]
      var b = arr[i + 1]
      arr[i] = b
      arr[i + 1] = a
    }
  }
  return arr;
}
</code>```

答:
```<code>function bubble(arr) {//You need Two Loops for Bubble sort
  for (var i = 0; i < arr.length; i++) {//Outer Loop
   for(var j=0; j < arr.length - 1; j++){//Inner Loop
    if (arr[j] > arr[j + 1]) {
      var a = arr[j]
      var b = arr[j + 1]
      arr[j] = b
      arr[j + 1] = a
     }
   }
  }
  return arr;
}
</code>```

Title: Javascript: Bubble Sort

Body:
I have made a bubble sort algorithm (sorta) using JS. It works sometimes, but the problem is that it only iterates through the array once. Here is my code:

function bubble(arr) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] > arr[i + 1]) {
      var a = arr[i]
      var b = arr[i + 1]
      arr[i] = b
      arr[i + 1] = a
    }
  }
  return arr;
}


问:
Value is not setted in React-redux-forms
Currently am passing the data to the Form component but it didn't reflected in my value field in Redux form . Actually i would like to do the ng-model(angular js) concept in redux forms . Here i attached my code ,

import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
import { connect } from 'react-redux';

import '../style.less'

class EditProfile extends Component {

 //here am getting the json value in 'info'
render() {
    const { handleSubmit, pristine, reset, submitting, errors, info } =      this.props;
   console.log("hello fname?---> "+info.fName);
    return (
      <form onSubmit={handleSubmit}>

          Full Name

          <Field className="text-box-one"
          name="fName"
          component="input"
          type="text"
          onChange={this.handleChange}
          value={info.fName}
          />

        <button
         className="save-btn btn"
         type="submit"
         disabled={pristine || submitting}>SAVE
         </button>

      </form>
    );
  }
}

export default reduxForm({
  form: 'editForm'
})(EditProfile)```

In the console am getting the value

If i use <input> instead of <Field> mean's am getting the value .

so , where i made a mistake ? can someone clarify me please .
[Am beginner to redux-forms].

答:
You're passing the value and handling changes explicitly, but it's recommended that redux-form handle it for you.

All you need is to pass your info as initialValues prop into the form and the form can handle it from there.

So on your page you should have something like this:

```<code><EditProfile
  initialValues={info}
  onSubmit={handleSubmit}
/>
</code>```

Then in your form this code should be enough

```<code>return (
  <form onSubmit={handleSubmit}>
     <div>
      <label
        className="full-name-business-n"
        htmlFor="fName">Full Name
      </label>

      <Field className="text-box-one"
        name="fName"
        component="input"
        type="text"
        // You don't need onChange unless you want to have a callback to do something with the value at the same time as it's persisting to redux store
        // onChange={this.handleChange}
        // value={info.fName}
      />

    </div>

    <button
       className="save-btn btn"
       type="submit"
       disabled={pristine || submitting}>SAVE
     </button>

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

You can see that your data is saving correctly if you open redux-dev-tools and see actions firing as you type.

By default you don't have access to your values as you type but you can achieve it by adding formValueSelector, but that's another story and most of the time I don't use it.

Body:
Currently am passing the data to the Form component but it didn't reflected in my value field in Redux form . Actually i would like to do the ng-model(angular js) concept in redux forms . Here i attached my code ,

import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
import { connect } from 'react-redux';

import '../style.less'

class EditProfile extends Component {

 //here am getting the json value in 'info'
render() {
    const { handleSubmit, pristine, reset, submitting, errors, info } =      this.props;
   console.log("hello fname?---> "+info.fName);
    return (
      <form onSubmit={handleSubmit}>

          Full Name

          <Field className="text-box-one"
          name="fName"
          component="input"
          type="text"
          onChange={this.handleChange}
          value={info.fName}
          />

        <button
         className="save-btn btn"
         type="submit"
         disabled={pristine || submitting}>SAVE
         </button>

      </form>
    );
  }
}

export default reduxForm({
  form: 'editForm'
})(EditProfile)

In the console am getting the value

If i use <input> instead of <Field> mean's am getting the value .

so , where i made a mistake ? can someone clarify me please .
[Am beginner to redux-forms].

Body:
You're passing the value and handling changes explicitly, but it's recommended that redux-form handle it for you.

All you need is to pass your info as initialValues prop into the form and the form can handle it from there.

So on your page you should have something like this:

<EditProfile
  initialValues={info}
  onSubmit={handleSubmit}
/>

Then in your form this code should be enough

return (
  <form onSubmit={handleSubmit}>
     <div>
      <label
        className="full-name-business-n"
        htmlFor="fName">Full Name
      </label>

      <Field className="text-box-one"
        name="fName"
        component="input"
        type="text"
        // You don't need onChange unless you want to have a callback to do something with the value at the same time as it's persisting to redux store
        // onChange={this.handleChange}
        // value={info.fName}
      />

    </div>

    <button
       className="save-btn btn"
       type="submit"
       disabled={pristine || submitting}>SAVE
     </button>

  </form>
);

You can see that your data is saving correctly if you open redux-dev-tools and see actions firing as you type.

By default you don't have access to your values as you type but you can achieve it by adding formValueSelector, but that's another story and most of the time I don't use it.


问:
Validate string input for DateTime::modify()
I have as scenario where the $string variable sent to DateTime::modify($string) is read from a database edited by users, how can i validate that $string is a proper string for DateTime::modify() ?

答:
Bit late to the party here, this works perfectly for me...

```<code>function isDateModifyValid($String)
{
    if (strlen($String) == 0) { return false; }
    $now = new \DateTime(null, new \DateTimeZone("UTC"));
    $rtn = false; // Default return value
    @$now->modify($String) && $rtn = true;
     // If modify($string) fails, $rtn won't set to true, else $rtn will set to true
    // ^ ^ @ suppress error
    return $rtn;
}

//TEST DATA
foreach (array("+1 hour", "+2 hour, -5 minutes", "12:00", "dsfv", "13:00, + 1 hour", "Yesterday, 12:00", "Neext weeekc", "Next month") as $testString)
{
    if (isDateModifyValid($testString))
    {
        echo "VALID ::: $testString\n";
    } else {
        echo "INVALID ::: $testString\n";
    }
}
</code>```

VALID ::: +1 hour
VALID ::: +2 hour, -5 minutes
VALID ::: 12:00
INVALID ::: dsfv
VALID ::: 13:00, + 1 hour
VALID ::: Yesterday, 12:00
INVALID ::: Neext weeekc
VALID ::: Next month

Body:
Bit late to the party here, this works perfectly for me...

function isDateModifyValid($String)
{
    if (strlen($String) == 0) { return false; }
    $now = new \DateTime(null, new \DateTimeZone("UTC"));
    $rtn = false; // Default return value
    @$now->modify($String) && $rtn = true;
     // If modify($string) fails, $rtn won't set to true, else $rtn will set to true
    // ^ ^ @ suppress error
    return $rtn;
}

//TEST DATA
foreach (array("+1 hour", "+2 hour, -5 minutes", "12:00", "dsfv", "13:00, + 1 hour", "Yesterday, 12:00", "Neext weeekc", "Next month") as $testString)
{
    if (isDateModifyValid($testString))
    {
        echo "VALID ::: $testString\n";
    } else {
        echo "INVALID ::: $testString\n";
    }
}

VALID ::: +1 hour
VALID ::: +2 hour, -5 minutes
VALID ::: 12:00
INVALID ::: dsfv
VALID ::: 13:00, + 1 hour
VALID ::: Yesterday, 12:00
INVALID ::: Neext weeekc
VALID ::: Next month


问:
Posting contents of a file using HttpClient?
I want to send the contents of a file as part of a http request using Apache HttpClient and I could not figure out how to pass on the file contents in the request body.</p>

答:
You didn't specify the format....

Most likely, you want to send a POST request, the contents will be multipart/form-data MIME type. This emulates what a browser sends from an <INPUT type="file" ...> form element. This requires some pretty sophisticated parsing on the server side to extract the multiple parts from the body and correctly extract the file data from the other fields (if any). Fortunately, commons-fileupload does this perfectly. The first answer regarding FilePart is exactly right.

Alternatively, you could simply post the raw contents of a file as the body of the request by using an InputStreamRequestEntity. This may be much simpler if you're writing your own server side to receive the data. The server side is as simple as streaming the request's InputStream to disk. I use this technique for uploads with Google Gears.

OwnerDisplayName: Vijay Dev

LastEditorDisplayName: Vijay Dev

OwnerDisplayName: tweakt


问:
Disable input when enter is pressed dynamically
I'm making a website where there will be a lot of input fields. Sort of like a scanner, I would like to disable each input when the enter is pressed.

I now have this:

<input (keyup.enter)="doSomething()"/>

But I would want to pass along the input itself so I can disable these inputs. (f.e. something like: doSomething(input) { input.attr.disabled = true; }

How can I get this input field in my doSomething function?

Note: I do not want to use something like <input #input ... since I have so many input fields. This will only create a lot of work.

All I want is that each time the enter is pressed in an input field, that it gets disabled (using only one function for all).

答:
Create a directive that listens for the keyup.enter on the input and then sets the disabled attribute on the input. This can be done with a directive like this:

@Directive({
  selector: 'input[disable-on-enter]',
})
export class DisableOnEnterDirective {
  @HostBinding('attr.disabled') isDisabled;
  @HostListener('keyup.enter') disableInput() {
   this.isDisabled = true ;
  }
}
```

<p>And it can be used like this:</p>

<pre class="lang-html prettyprint-override"><code><input disable-on-enter placeholder="Press enter to disable" />
</code>```

Demo

Body:
Create a directive that listens for the keyup.enter on the input and then sets the disabled attribute on the input. This can be done with a directive like this:

@Directive({
  selector: 'input[disable-on-enter]',
})
export class DisableOnEnterDirective {
  @HostBinding('attr.disabled') isDisabled;
  @HostListener('keyup.enter') disableInput() {
   this.isDisabled = true ;
  }
}

And it can be used like this:

<input disable-on-enter placeholder="Press enter to disable" />

Demo


问:
SciKit-Learn: Basic PCA Confusion
I'm trying to use SciKit-Learn to perform PCA on my dataset.  I currently have 2,208 rows and 53,741 columns (features).  So I want to use PCA to reduce the dimensionality of this dataset.

I'm following Hands-On Machine Learning with SciKit-Learn and TensorFlow:

```<code>from sklearn.decomposition import PCA
pca = PCA(n_components=0.95)
X_reduced = pca.fit_transform(X)
</code>```

As far as I understand, this should reduce the number of columns such that they, in total, explain 95% of the variance in my dataset.

Now I want to see how many features (columns) are left in X_reduced:

```<code>X_reduced.shape
(2208, 1)
</code>```

So it looks like a single feature accounts for at least 95% of the variance in my dataset...

1) This is very surprising, so I looked at how much the most important dimension contributes variance-wise:

```<code>pca = PCA(n_components = 1)
X2D = pca.fit_transform(X)
print pca.explained_variance_ratio_

[ 0.98544046]
</code>```

So it's 98.5%!

How do I figure out what this seemingly magical dimension is?

2) Don't I need to include my target Y values when doing PCA?

Thanks!

答:
This "seemingly magical dimension" is actually a linear combination of all your dimensions. PCA works by changing basis from your original column space to the space spanned by the eigenvectors of your data's covariance matrix.
You don't need the Y-values because PCA only needs the eigenvalues and eigenvectors of your data's covariance matrix.</p>

Title: SciKit-Learn: Basic PCA Confusion

Body:
I'm trying to use SciKit-Learn to perform PCA on my dataset.  I currently have 2,208 rows and 53,741 columns (features).  So I want to use PCA to reduce the dimensionality of this dataset.

I'm following Hands-On Machine Learning with SciKit-Learn and TensorFlow:

from sklearn.decomposition import PCA
pca = PCA(n_components=0.95)
X_reduced = pca.fit_transform(X)

As far as I understand, this should reduce the number of columns such that they, in total, explain 95% of the variance in my dataset.

Now I want to see how many features (columns) are left in X_reduced:

X_reduced.shape
(2208, 1)

So it looks like a single feature accounts for at least 95% of the variance in my dataset...

1) This is very surprising, so I looked at how much the most important dimension contributes variance-wise:

pca = PCA(n_components = 1)
X2D = pca.fit_transform(X)
print pca.explained_variance_ratio_

[ 0.98544046]

So it's 98.5%!

How do I figure out what this seemingly magical dimension is?

2) Don't I need to include my target Y values when doing PCA?

Thanks!


问:
Extended modelform not saving related table
I've extended a modelform but the related model isn't correctly saving to the database.
Below I'm only calling SupplyAddress() rather than creating and saving an instance of it via SupplyAddress.objects.create() However, if I try to do this then the related address (and user) hasn't been created yet to save against. What's the best way to save the user, Address and SupplyAddress?

models.py

```<code>class Address(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    house_name_number = models.CharField(max_length=255, verbose_name="house name or number")
    street_name = models.CharField(max_length=255)
    town_city = models.CharField(max_length=255)
    county = models.CharField(max_length=255)
    postcode = models.CharField(max_length=8)

    time_stamp = models.DateField(auto_now=True)

class SupplyAddress(models.Model):
    address = models.OneToOneField(Address)
    region = models.ForeignKey(Region, null=True)

    occupied = models.BooleanField()
</code>```

forms.py

```<code>class SupplyAddressForm(forms.ModelForm):

    occupied = forms.BooleanField()

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        data = self.cleaned_data
        supply_address = models.SupplyAddress(
            occupied=data['occupied'],
        )
        self.instance.supplyaddress = supply_address
        return self.instance

    class Meta:
        model = Address
        fields = ['house_name_number',
                  'street_name',
                  'town_city',
                  'county',
                  'same_address',
                  'move_in_date',
                  'postcode',
                  ]
</code>```

views.py

```<code>.....
address = form.save(commit=False)
        address.user = user
        address.save()
</code>```

答:
Edit your save method,</p>

```<code>class SupplyAddressForm(forms.ModelForm):

    occupied = forms.BooleanField()

    class Meta:
        model = Address
        fields = ['house_name_number',
                  'street_name',
                  'town_city',
                  'county',
                  'same_address',
                  'move_in_date',
                  'postcode',
                  ]

    def save(self, *args, **kwargs):
        data = self.cleaned_data
        supply_address = models.SupplyAddress.objects.create(occupied=data['occupied'])
        instance = super(SuppyAddressForm, self).save(*args, **kwargs)
        instance.supplyaddress = supply_address
        instance.save()
        return instance
</code>```

Body:
I've extended a modelform but the related model isn't correctly saving to the database.
Below I'm only calling SupplyAddress() rather than creating and saving an instance of it via SupplyAddress.objects.create() However, if I try to do this then the related address (and user) hasn't been created yet to save against. What's the best way to save the user, Address and SupplyAddress?

models.py

class Address(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    house_name_number = models.CharField(max_length=255, verbose_name="house name or number")
    street_name = models.CharField(max_length=255)
    town_city = models.CharField(max_length=255)
    county = models.CharField(max_length=255)
    postcode = models.CharField(max_length=8)

    time_stamp = models.DateField(auto_now=True)

class SupplyAddress(models.Model):
    address = models.OneToOneField(Address)
    region = models.ForeignKey(Region, null=True)

    occupied = models.BooleanField()

forms.py

class SupplyAddressForm(forms.ModelForm):

    occupied = forms.BooleanField()

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        data = self.cleaned_data
        supply_address = models.SupplyAddress(
            occupied=data['occupied'],
        )
        self.instance.supplyaddress = supply_address
        return self.instance

    class Meta:
        model = Address
        fields = ['house_name_number',
                  'street_name',
                  'town_city',
                  'county',
                  'same_address',
                  'move_in_date',
                  'postcode',
                  ]

views.py

.....
address = form.save(commit=False)
        address.user = user
        address.save()

Body:
Edit your save method,

class SupplyAddressForm(forms.ModelForm):

    occupied = forms.BooleanField()

    class Meta:
        model = Address
        fields = ['house_name_number',
                  'street_name',
                  'town_city',
                  'county',
                  'same_address',
                  'move_in_date',
                  'postcode',
                  ]

    def save(self, *args, **kwargs):
        data = self.cleaned_data
        supply_address = models.SupplyAddress.objects.create(occupied=data['occupied'])
        instance = super(SuppyAddressForm, self).save(*args, **kwargs)
        instance.supplyaddress = supply_address
        instance.save()
        return instance


问:
Jquery: Is there some way to make val() return an empty string instead of 'undefined' for an empty list?
With Jquery, is there some way to make val() return an empty string instead of 'undefined' when called against an empty list of elements?

E.g., I have this code:

```<code>var x = $('#my-textbox-id').not('.watermark').val();
</code>```

The idea is that I want to get the value of my textbox, but I want an empty string if it is currently showing the watermark (i don't want the watermark value!).

The selector works, but i don't want 'undefined' - I want an empty string ''.

答:
You can write (...).val() || "".

Only use this for text fields; it will also replace false or the number 0 with "".

Body:
With Jquery, is there some way to make val() return an empty string instead of 'undefined' when called against an empty list of elements?

E.g., I have this code:

var x = $('#my-textbox-id').not('.watermark').val();

The idea is that I want to get the value of my textbox, but I want an empty string if it is currently showing the watermark (i don't want the watermark value!).

The selector works, but i don't want 'undefined' - I want an empty string ''.


问:
Find position of last Non Null element in a list in C#
I have the following values in my MySQL DB

```<code>Date        High_Low_Price
5/18/2017   302
5/19/2017   315.3
5/22/2017   Null
5/23/2017   Null
5/24/2017   Null
5/25/2017   Null
5/26/2017   Null
5/29/2017   Null
</code>```

and I have create the a list in the below format

```<code>List<db1> StockData = new List<db1>();
db1 newStock = new db1();
newStock.High_Low_Price = (double)reader["High_Low_Price"];
StockData.Add(newStock);
</code>```

How can I find the position of the last not null element (i.e. i) in the list. When I mean last element I am refering to the 315.3 of High_Low_Price on the 5/19/2017.

the Null values in High_Low_Price column will keep varying in size. How would i then find the last date which has a value in this list ?

EDIT: i need two things, The Date and the position.

答:
Assuming that type of High_Low_Price is  nullable, like 'double?'</p>

```<code>var lastDate = StockData.Last(x => x.High_Low_Price.HasValue).Date;
</code>```

Body:
I have the following values in my MySQL DB

Date        High_Low_Price
5/18/2017   302
5/19/2017   315.3
5/22/2017   Null
5/23/2017   Null
5/24/2017   Null
5/25/2017   Null
5/26/2017   Null
5/29/2017   Null

and I have create the a list in the below format

List<db1> StockData = new List<db1>();
db1 newStock = new db1();
newStock.High_Low_Price = (double)reader["High_Low_Price"];
StockData.Add(newStock);

How can I find the position of the last not null element (i.e. i) in the list. When I mean last element I am refering to the 315.3 of High_Low_Price on the 5/19/2017.

the Null values in High_Low_Price column will keep varying in size. How would i then find the last date which has a value in this list ?

EDIT: i need two things, The Date and the position.

Body:
Assuming that type of High_Low_Price is  nullable, like 'double?'

var lastDate = StockData.Last(x => x.High_Low_Price.HasValue).Date;


问:
Which encoding to use in App.Config?
Following config file causes error because of & in 'url' value:

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key ="url" value ="http://www.example.com/?user=admin&password=1234"/>
  </appSettings>
</configuration>
</code>```

The question is which encoding to use for key/value in a config file ? (i.e Url Encoding ...)

答:
This is an XML file.  As such, you must XML-escape all reserved characters:

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key ="url" value ="http://www.example.com/?user=admin&password=1234"/>
  </appSettings>
</configuration>
</code>```

Programmatically you can perform this type of escaping using the System.Web.HttpUtility.HtmlEncode method.  Yes, its name suggests HTML specific encoding, but in my experience this is equivalent to XML escaping.

Title: Which encoding to use in App.Config?

Body:
Following config file causes error because of & in 'url' value:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key ="url" value ="http://www.example.com/?user=admin&password=1234"/>
  </appSettings>
</configuration>

The question is which encoding to use for key/value in a config file ? (i.e Url Encoding ...)

Body:
This is an XML file.  As such, you must XML-escape all reserved characters:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key ="url" value ="http://www.example.com/?user=admin&amp;password=1234"/>
  </appSettings>
</configuration>

Programmatically you can perform this type of escaping using the System.Web.HttpUtility.HtmlEncode method.  Yes, its name suggests HTML specific encoding, but in my experience this is equivalent to XML escaping.


答:
Also you can try something like this,</p>

```<code><input id="reply" name="reply" onKeyPress="enterpressalert(event)"/>

<script>
function enterpressalert(e){
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) { //Enter keycode
 e.target.disabled = true;
}
}
</script>
</code>```

Title: Disable input when enter is pressed dynamically

Body:
I'm making a website where there will be a lot of input fields. Sort of like a scanner, I would like to disable each input when the enter is pressed.

I now have this:

<input (keyup.enter)="doSomething()"/>

But I would want to pass along the input itself so I can disable these inputs. (f.e. something like: doSomething(input) { input.attr.disabled = true; }

How can I get this input field in my doSomething function?

Note: I do not want to use something like <input #input ... since I have so many input fields. This will only create a lot of work.

All I want is that each time the enter is pressed in an input field, that it gets disabled (using only one function for all).

Body:
Also you can try something like this,

<input id="reply" name="reply" onKeyPress="enterpressalert(event)"/>

<script>
function enterpressalert(e){
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) { //Enter keycode
 e.target.disabled = true;
}
}
</script>


问:
How to right fold using LINQ?
Using LINQ, we can perform a left fold on a list via Aggregate:

```<code>var numbers = new[] { 1, 2, 3, 4 };
var value = numbers.Aggregate((a, b) => a - b); // ((1 - 2) - 3) - 4 == -8
</code>```

Is there a similar way using LINQ to perform a right fold?

```<code>var value = numbers.Aggregate(???); // 1 - (2 - (3 - 4)) == -2
</code>```

答:
Right folding is essentially folding from right to left. We can replicate a right fold, if we Reverse the enumerable first, then perform a left fold via Aggregate:

```<code>var value = numbers.Reverse().Aggregate((a, b) => a - b);
</code>```

As an extension method:

```<code>public static TSource RightFold<TSource>(this IEnumerable<TSource> source,
    Func<TSource, TSource, TSource> func)
{
    return source.Reverse().Aggregate(func);
}
</code>```

Usage:

```<code>var value = numbers.RightFold((a, b) => a - b); // ((4 - 3) - 2) - 1 == -2
// 1 - (2 - (3 - 4)) == ((4 - 3) - 2) - 1
</code>```

Title: How to right fold using LINQ?

Body:
Using LINQ, we can perform a left fold on a list via Aggregate:

var numbers = new[] { 1, 2, 3, 4 };
var value = numbers.Aggregate((a, b) => a - b); // ((1 - 2) - 3) - 4 == -8

Is there a similar way using LINQ to perform a right fold?

var value = numbers.Aggregate(???); // 1 - (2 - (3 - 4)) == -2

Body:
Right folding is essentially folding from right to left. We can replicate a right fold, if we Reverse the enumerable first, then perform a left fold via Aggregate:

var value = numbers.Reverse().Aggregate((a, b) => a - b);

As an extension method:

public static TSource RightFold<TSource>(this IEnumerable<TSource> source,
    Func<TSource, TSource, TSource> func)
{
    return source.Reverse().Aggregate(func);
}

Usage:

var value = numbers.RightFold((a, b) => a - b); // ((4 - 3) - 2) - 1 == -2
// 1 - (2 - (3 - 4)) == ((4 - 3) - 2) - 1


问:
Error in composite key in Hibernate org.hibernate.MappingException: Could not determine type for: java.util.Set,
Friends I have stuck in a Problem in Hibernate composite key.
Error : org.hibernate.MappingException: Could not determine type for: java.util.Set, at table: IDP_UserManagerMapping, for columns: [org.hibernate.mapping.Column(idps)].I have Tried wit @transient and other things but not effective Please Help.

```<code>public class IDPUserManagerMapping implements Serializable {
    private Long id;
    private Users user;
    private Users manager;
    private Users assessor;

    @OneToMany(fetch = FetchType.LAZY)
    @JoinColumns({
        @JoinColumn(name="user_id" ,referencedColumnName = "user_id"),
        @JoinColumn(name="manager_id" ,referencedColumnName = "manager_id")
        ,@JoinColumn(name="assessor_id" ,referencedColumnName = "assessor_id")
    })
    @Cascade(CascadeType.ALL)
    private Set<IDPMaster> idps = null;

    @Id
    @SequenceGenerator(sequenceName="idp_usermanagermapping_id_seq",name="idp_usermanagermapping_id_seq_gen")
    @GeneratedValue(generator="idp_usermanagermapping_id_seq_gen")
    @Column(name="id",nullable=false,unique=true,updatable=false)
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }

    public Set<IDPMaster> getIdps() {
        return idps;
    }
    public void setIdps(Set<IDPMaster> idps) {
        this.idps = idps;
    }
        @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="user_id",nullable=false)
    public Users getUser() {
        return user;
    }
    public void setUser(Users user) {
        this.user = user;
    }

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="manager_id",nullable=false)
    public Users getManager() {
        return manager;
    }
    public void setManager(Users manager) {
        this.manager = manager;
    }

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="assessor_id")
    public Users getAssessor() {
        return assessor;
    }
    public void setAssessor(Users assessor) {
        this.assessor = assessor;
    }
    }
</code>```

Second Entity

```<code>public class IDPMaster implements Serializable {
    private Long id;
    private Users managerUser;
    private Users assessorUser;
    private Users idpUsers;
    @Id
    @SequenceGenerator(name="idp_master_id_seq_gen",sequenceName="idp_master_id_seq")
    @GeneratedValue(generator="idp_master_id_seq_gen")
    @Column(name="id",nullable=false,unique=true)
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="user_id",nullable=false)
    public Users getIdpUsers() {
        return idpUsers;
    }
    public void setIdpUsers(Users idpUsers) {
        this.idpUsers = idpUsers;
    }
    @OneToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="manager_id")
    public Users getManagerUser() {
        return managerUser;
    }
    public void setManagerUser(Users managerUser) {
        this.managerUser = managerUser;
    }

    @OneToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="assessor_id")
    public Users getAssessorUser() {
        return assessorUser;
    }
    public void setAssessorUser(Users assessorUser) {
        this.assessorUser = assessorUser;
    }
    }
</code>```

答:
You should move the annotations

```<code>@OneToMany(fetch = FetchType.LAZY)
    @JoinColumns({
        @JoinColumn(name="user_id" ,referencedColumnName = "user_id"),
        @JoinColumn(name="manager_id" ,referencedColumnName = "manager_id")
        ,@JoinColumn(name="assessor_id" ,referencedColumnName = "assessor_id")
    })
    @Cascade(CascadeType.ALL)
</code>```

from private Set<IDPMaster> idps = null;  to public Set<IDPMaster> getIdps() getter

Hibernate analyzes annotations by ID column and if you use annotations on getter there you should use getter annotations everywhere.

Body:
Friends I have stuck in a Problem in Hibernate composite key.
Error : org.hibernate.MappingException: Could not determine type for: java.util.Set, at table: IDP_UserManagerMapping, for columns: [org.hibernate.mapping.Column(idps)].I have Tried wit @transient and other things but not effective Please Help.

public class IDPUserManagerMapping implements Serializable {
    private Long id;
    private Users user;
    private Users manager;
    private Users assessor;

    @OneToMany(fetch = FetchType.LAZY)
    @JoinColumns({
        @JoinColumn(name="user_id" ,referencedColumnName = "user_id"),
        @JoinColumn(name="manager_id" ,referencedColumnName = "manager_id")
        ,@JoinColumn(name="assessor_id" ,referencedColumnName = "assessor_id")
    })
    @Cascade(CascadeType.ALL)
    private Set<IDPMaster> idps = null;

    @Id
    @SequenceGenerator(sequenceName="idp_usermanagermapping_id_seq",name="idp_usermanagermapping_id_seq_gen")
    @GeneratedValue(generator="idp_usermanagermapping_id_seq_gen")
    @Column(name="id",nullable=false,unique=true,updatable=false)
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }

    public Set<IDPMaster> getIdps() {
        return idps;
    }
    public void setIdps(Set<IDPMaster> idps) {
        this.idps = idps;
    }
        @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="user_id",nullable=false)
    public Users getUser() {
        return user;
    }
    public void setUser(Users user) {
        this.user = user;
    }

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="manager_id",nullable=false)
    public Users getManager() {
        return manager;
    }
    public void setManager(Users manager) {
        this.manager = manager;
    }

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="assessor_id")
    public Users getAssessor() {
        return assessor;
    }
    public void setAssessor(Users assessor) {
        this.assessor = assessor;
    }
    }

Second Entity

public class IDPMaster implements Serializable {
    private Long id;
    private Users managerUser;
    private Users assessorUser;
    private Users idpUsers;
    @Id
    @SequenceGenerator(name="idp_master_id_seq_gen",sequenceName="idp_master_id_seq")
    @GeneratedValue(generator="idp_master_id_seq_gen")
    @Column(name="id",nullable=false,unique=true)
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="user_id",nullable=false)
    public Users getIdpUsers() {
        return idpUsers;
    }
    public void setIdpUsers(Users idpUsers) {
        this.idpUsers = idpUsers;
    }
    @OneToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="manager_id")
    public Users getManagerUser() {
        return managerUser;
    }
    public void setManagerUser(Users managerUser) {
        this.managerUser = managerUser;
    }

    @OneToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="assessor_id")
    public Users getAssessorUser() {
        return assessorUser;
    }
    public void setAssessorUser(Users assessorUser) {
        this.assessorUser = assessorUser;
    }
    }

Body:
You should move the annotations

@OneToMany(fetch = FetchType.LAZY)
    @JoinColumns({
        @JoinColumn(name="user_id" ,referencedColumnName = "user_id"),
        @JoinColumn(name="manager_id" ,referencedColumnName = "manager_id")
        ,@JoinColumn(name="assessor_id" ,referencedColumnName = "assessor_id")
    })
    @Cascade(CascadeType.ALL)

from private Set<IDPMaster> idps = null;  to public Set<IDPMaster> getIdps() getter

Hibernate analyzes annotations by ID column and if you use annotations on getter there you should use getter annotations everywhere.


问:
Storing numeric values in Lucene 6.5.0
I need to Store the Numeric field in the Lucene docs, but Lucene 6.5.1 the signature of the NumericField is like

NumericDocValuesField(String name, long value)

In older lucene versions the method is like,

NumericField(String, Field.Store, boolean)

.
Can someone guide me how to store the numeric values in the document using lucene6.5.1.

Regards,

Raghavan

答:
Use special type oriented numeric fields:

```<code>IntField intField = new IntField("int_value", 100, Field.Store.YES);
LongField longField = new LongField("long_value", 100L, Field.Store.
YES);
FloatField floatField = new FloatField("float_value", 100.0F, Field.
Store.YES);
DoubleField doubleField = new DoubleField("double_value", 100.0D,
Field.Store.YES);
</code>```

You can store their values and sort them if you need. All of those field are indexable.

Title: Storing numeric values in Lucene 6.5.0

Body:
Use special type oriented numeric fields:

IntField intField = new IntField("int_value", 100, Field.Store.YES);
LongField longField = new LongField("long_value", 100L, Field.Store.
YES);
FloatField floatField = new FloatField("float_value", 100.0F, Field.
Store.YES);
DoubleField doubleField = new DoubleField("double_value", 100.0D,
Field.Store.YES);

You can store their values and sort them if you need. All of those field are indexable.


问:
Django Image Upload Form not valid
For some reason in django the form that I am trying to use is not considered valid. This code is taken almost directly from a site that claims that it works but is still not functional.
my code is as follows.

VIEWS

```<code>def display_update_image(request, pk):
if request.method == 'POST':
    form = ImageForm(request.POST, request.FILES)
    if form.is_valid():
        display = Display.objects.get(pk = pk)
        display.image = form.cleaned_data['image']
        display.save()
    return HttpResponseRedirect(reverse('displays'))
else :
    form = ImageForm()
return render(request, 'catalog/update_display_image.html', {'form': form})
</code>```

TEMPLATE (template name is update_display_image.html)

```<code><form method = "post" enctype = "multipart/form-data">{% csrf_token %}
<p>
    <input id = "id" type = "file" class = "" name = "image">
</p>
<input type = "submit" value = "Submit" />
</code>```

MODELS

```<code>class Display(models.Model):
    title = models.CharField(max_length = 50,)
    image = models.ImageField(upload_to = 'images')
    id = models.UUIDField(primary_key = True, default = uuid.uuid4, unique = True)

    def __str__(self):
        return self.title
</code>```

edit: forget to post Forms code sorry

```<code>class ImageForm(forms.Form):
    image = forms.ImageField()
</code>```

further edit: changing my forms class to this

```<code>class ImageForm(forms.Form):
    class Meta:
        model = Display
        fields = ('image',)
</code>```

Allows the form to be read as valid for some reason though I don't understand why. Unfortunately that causes my views method to be unable to function properly as it can no longer read

```<code>display.image = form.cleaned_data['image']
</code>```

答:
If you form class is a modelform: class ImageForm(forms.ModelForm): you can pass the instance to the form and save it.

```<code>def display_update_image(request, pk):
    if request.method == 'POST':
        display = Display.objects.get(pk = pk)
        form = ImageForm(request.POST, request.FILES, instance=display)
        if form.is_valid():
            form.save()
        return HttpResponseRedirect(reverse('displays'))
    else :
        form = ImageForm()
    return render(request, 'catalog/update_display_image.html', {'form': form})
</code>```

Title: Django Image Upload Form not valid

Body:
For some reason in django the form that I am trying to use is not considered valid. This code is taken almost directly from a site that claims that it works but is still not functional.
my code is as follows.

VIEWS

def display_update_image(request, pk):
if request.method == 'POST':
    form = ImageForm(request.POST, request.FILES)
    if form.is_valid():
        display = Display.objects.get(pk = pk)
        display.image = form.cleaned_data['image']
        display.save()
    return HttpResponseRedirect(reverse('displays'))
else :
    form = ImageForm()
return render(request, 'catalog/update_display_image.html', {'form': form})

TEMPLATE (template name is update_display_image.html)

<form method = "post" enctype = "multipart/form-data">{% csrf_token %}

    <input id = "id" type = "file" class = "" name = "image">

<input type = "submit" value = "Submit" />

MODELS

class Display(models.Model):
    title = models.CharField(max_length = 50,)
    image = models.ImageField(upload_to = 'images')
    id = models.UUIDField(primary_key = True, default = uuid.uuid4, unique = True)

    def __str__(self):
        return self.title

edit: forget to post Forms code sorry

class ImageForm(forms.Form):
    image = forms.ImageField()

further edit: changing my forms class to this

class ImageForm(forms.Form):
    class Meta:
        model = Display
        fields = ('image',)

Allows the form to be read as valid for some reason though I don't understand why. Unfortunately that causes my views method to be unable to function properly as it can no longer read

display.image = form.cleaned_data['image']

Body:
If you form class is a modelform: class ImageForm(forms.ModelForm): you can pass the instance to the form and save it.

def display_update_image(request, pk):
    if request.method == 'POST':
        display = Display.objects.get(pk = pk)
        form = ImageForm(request.POST, request.FILES, instance=display)
        if form.is_valid():
            form.save()
        return HttpResponseRedirect(reverse('displays'))
    else :
        form = ImageForm()
    return render(request, 'catalog/update_display_image.html', {'form': form})


问:
TIA Bloomberg converting from Excel Formulas - BDS() Bulk Data
https://www.bloomberg.com/professional/support/api-library/ if you look at the BLPAPI Core Developer Guide under 15.3 BDS(): BULK DATA (STATIC), the guide shows you a very simple BDS() conversion.

I'm trying to get the segment data. And this is the Excel formula I'm trying to convert:
BDS("MSFT","PG_REVENUE","PG_HIERARCHY_LEVEL=1","NUMBER_OF_PERIODS=-11","REVERSE_PERIOD_ORDER=N","PRODUCT_GEO_OVERRIDE=P","FUND_PER","FQ")

Here is my code:

```<code>from tia.bbg import LocalTerminal

ticker=['MSFT US Equity']
overrides=["PG_HIERARCHY_LEVEL=1","PRODUCT_GEO_OVERRIDE=P",'FUND_PER','FQ']

resp = LocalTerminal.get_reference_data(ticker,"PG_REVENUE",overrides)
a=resp.as_map()
</code>```

It seems no matter what I put into the overrides variable. I get the same output.

```<code>defaultdict(<type 'dict'>, {'MSFT US Equity': {'PG_REVENUE':                             Metric Name  Product Geographic Hierarchy Level  \
0               More Personal Computing                                   1
1   Productivity and Business Processes                                   1
2                     Intelligent Cloud                                   1
3                   Corporate and other                                   1
4                            Commercial                                   1
5                      Commercial Other                                   2
6                  Commercial Licensing                                   2
7                 Devices and Consumers                                   1
8                           D & C Other                                   2
9                        D & C Hardware                                   2
10                      D & C Licensing                                   2

    Period 1 Value  Period 2 Value  Period 3 Value  Period 4 Value  \
0     4.046000e+04    4.316000e+04    3.840700e+04   -2.424536e-14
1     2.648700e+04    2.643000e+04    2.697200e+04   -2.424536e-14
2     2.504200e+04    2.371500e+04    2.173200e+04   -2.424536e-14
3    -6.669000e+03    2.750000e+02   -2.780000e+02    4.030000e+02
4    -2.424536e-14   -2.424536e-14   -2.424536e-14    4.534600e+04
5    -2.424536e-14   -2.424536e-14   -2.424536e-14    5.660000e+03
6    -2.424536e-14   -2.424536e-14   -2.424536e-14    3.968600e+04
7    -2.424536e-14   -2.424536e-14   -2.424536e-14    3.210000e+04
8    -2.424536e-14   -2.424536e-14   -2.424536e-14    6.618000e+03
9    -2.424536e-14   -2.424536e-14   -2.424536e-14    6.461000e+03
10   -2.424536e-14   -2.424536e-14   -2.424536e-14    1.902100e+04

    Period 5 Value
0    -2.424536e-14
1    -2.424536e-14
2    -2.424536e-14
3    -4.850000e+02
4     4.177000e+04
5     4.644000e+03
6     3.712600e+04
7     3.243800e+04
8     6.203000e+03
9     6.740000e+03
10    1.949500e+04  }})
</code>```

I'm not sure how to get the output on a quarterly basis.

答:
Actually you don't have to use the quotation marks for the overrides.

overrides=[PG_HIERARCHY_LEVEL=1]

See the example jupyter notebook from the tia GitHub page:
http://nbviewer.jupyter.org/github/bpsmith/tia/blob/master/examples/v3api.ipynb

Body:
https://www.bloomberg.com/professional/support/api-library/ if you look at the BLPAPI Core Developer Guide under 15.3 BDS(): BULK DATA (STATIC), the guide shows you a very simple BDS() conversion.

I'm trying to get the segment data. And this is the Excel formula I'm trying to convert:
BDS("MSFT","PG_REVENUE","PG_HIERARCHY_LEVEL=1","NUMBER_OF_PERIODS=-11","REVERSE_PERIOD_ORDER=N","PRODUCT_GEO_OVERRIDE=P","FUND_PER","FQ")

Here is my code:

from tia.bbg import LocalTerminal

ticker=['MSFT US Equity']
overrides=["PG_HIERARCHY_LEVEL=1","PRODUCT_GEO_OVERRIDE=P",'FUND_PER','FQ']

resp = LocalTerminal.get_reference_data(ticker,"PG_REVENUE",overrides)
a=resp.as_map()

It seems no matter what I put into the overrides variable. I get the same output.

defaultdict(<type 'dict'>, {'MSFT US Equity': {'PG_REVENUE':                             Metric Name  Product Geographic Hierarchy Level  \
0               More Personal Computing                                   1
1   Productivity and Business Processes                                   1
2                     Intelligent Cloud                                   1
3                   Corporate and other                                   1
4                            Commercial                                   1
5                      Commercial Other                                   2
6                  Commercial Licensing                                   2
7                 Devices and Consumers                                   1
8                           D & C Other                                   2
9                        D & C Hardware                                   2
10                      D & C Licensing                                   2

    Period 1 Value  Period 2 Value  Period 3 Value  Period 4 Value  \
0     4.046000e+04    4.316000e+04    3.840700e+04   -2.424536e-14
1     2.648700e+04    2.643000e+04    2.697200e+04   -2.424536e-14
2     2.504200e+04    2.371500e+04    2.173200e+04   -2.424536e-14
3    -6.669000e+03    2.750000e+02   -2.780000e+02    4.030000e+02
4    -2.424536e-14   -2.424536e-14   -2.424536e-14    4.534600e+04
5    -2.424536e-14   -2.424536e-14   -2.424536e-14    5.660000e+03
6    -2.424536e-14   -2.424536e-14   -2.424536e-14    3.968600e+04
7    -2.424536e-14   -2.424536e-14   -2.424536e-14    3.210000e+04
8    -2.424536e-14   -2.424536e-14   -2.424536e-14    6.618000e+03
9    -2.424536e-14   -2.424536e-14   -2.424536e-14    6.461000e+03
10   -2.424536e-14   -2.424536e-14   -2.424536e-14    1.902100e+04

    Period 5 Value
0    -2.424536e-14
1    -2.424536e-14
2    -2.424536e-14
3    -4.850000e+02
4     4.177000e+04
5     4.644000e+03
6     3.712600e+04
7     3.243800e+04
8     6.203000e+03
9     6.740000e+03
10    1.949500e+04  }})

I'm not sure how to get the output on a quarterly basis.


问:
regex capture lines before certain keywords that may or may not be present
```<code>Changeset: 8675309
User: DOMAIN\JohnG
Date: 01/21/2004 21:03:45
Comment:  This check-in fixes issues in several features.  I also refactored some items in buf.c into a new file named bif.c because buf.c was too hard to parse.
Items:
   $/baz/proj/bif.c           Added
   $/baz/proj/buf.c          Modified, Renamed
Work Items:
   34527     The "Access Denied" message is not descriptive enough.
   35628     The UI flickers when I press the '8', 'y', 'Ctrl', and 'End' buttons at the same time.
Check-in Notes:
   Code Reviewer:  ShellM
   Performance Reviewer: ShellM
   Security Reviewer: ShellM
</code>```

I want to capture the two lines under Items. However Work Items may sometimes be missing, so Check-in Notes: would be where i stopped, and then sometimes BOTH would be missing so I would need to stop at the end of the string.

```<code>(?s)(?<=Items:).*(?(?=Work Items:)|(?=Check-in Notes:))
</code>```

this is what I have and it captures everything UP TO check-in notes which is wrong.

答:
Try following which is tested</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace ConsoleApplication64
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.txt";
        static List<string> sections = null;
        public enum State
        {
            NONE = -1,
            CHANGESET = 0,
            USER,
            DATE,
            COMMENT,
            ITEMS,
            WORK_ITEMS,
            CHECK_IN_NOTES
        }

        static void Main(string[] args)
        {
            sections = new List<string>() { "Changeset", "User", "Date", "Comment", "Items", "Work Items", "Check-In Notes" };
            string pattern = "^(?'section'[^:]+)";
            string inputLine = "";
            StreamReader reader = new StreamReader(FILENAME);
            State state = State.NONE;
            while ((inputLine = reader.ReadLine()) != null)
            {
                inputLine = inputLine.Trim();
                Match match = Regex.Match(inputLine, pattern);
                if (match.Success)
                {
                    int index = sections.IndexOf(match.Groups["section"].Value);
                    if(index >= 0) state = (State)index;
                }

                switch(state)
                {
                    case State.COMMENT :
                        Console.WriteLine(inputLine);
                        break;
                    case State.ITEMS :
                        Console.WriteLine(inputLine);
                        break;
                }

            }
            Console.ReadLine();
        }
    }

}
</code>```

Body:
Changeset: 8675309
User: DOMAIN\JohnG
Date: 01/21/2004 21:03:45
Comment:  This check-in fixes issues in several features.  I also refactored some items in buf.c into a new file named bif.c because buf.c was too hard to parse.
Items:
   $/baz/proj/bif.c           Added
   $/baz/proj/buf.c          Modified, Renamed
Work Items:
   34527     The "Access Denied" message is not descriptive enough.
   35628     The UI flickers when I press the '8', 'y', 'Ctrl', and 'End' buttons at the same time.
Check-in Notes:
   Code Reviewer:  ShellM
   Performance Reviewer: ShellM
   Security Reviewer: ShellM

I want to capture the two lines under Items. However Work Items may sometimes be missing, so Check-in Notes: would be where i stopped, and then sometimes BOTH would be missing so I would need to stop at the end of the string.

(?s)(?<=Items:).*(?(?=Work Items:)|(?=Check-in Notes:))

this is what I have and it captures everything UP TO check-in notes which is wrong.

Body:
Try following which is tested

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;

namespace ConsoleApplication64
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.txt";
        static List<string> sections = null;
        public enum State
        {
            NONE = -1,
            CHANGESET = 0,
            USER,
            DATE,
            COMMENT,
            ITEMS,
            WORK_ITEMS,
            CHECK_IN_NOTES
        }

        static void Main(string[] args)
        {
            sections = new List<string>() { "Changeset", "User", "Date", "Comment", "Items", "Work Items", "Check-In Notes" };
            string pattern = "^(?'section'[^:]+)";
            string inputLine = "";
            StreamReader reader = new StreamReader(FILENAME);
            State state = State.NONE;
            while ((inputLine = reader.ReadLine()) != null)
            {
                inputLine = inputLine.Trim();
                Match match = Regex.Match(inputLine, pattern);
                if (match.Success)
                {
                    int index = sections.IndexOf(match.Groups["section"].Value);
                    if(index >= 0) state = (State)index;
                }

                switch(state)
                {
                    case State.COMMENT :
                        Console.WriteLine(inputLine);
                        break;
                    case State.ITEMS :
                        Console.WriteLine(inputLine);
                        break;
                }

            }
            Console.ReadLine();
        }
    }

}


问:
Function accepting a generic Collection and returning an array of indices
I'm trying to write a function that accepts a generic Collection and a single element, then returns the index or indices of this element as an array. However, I'm getting an error at the return statement.

func findAll<T: Collection, U: Equatable>(_ items: T, _ find: U) -> [U] where T.Iterator.Element == U {
    var found = [Int]()
    for (index, item) in items.enumerated() {
        if item == find {
        found.append(index)
        }
    }
    return found
}```

答:
Ken's answer is good, but Collection can have an Index other than Int. If you try to use the indexes you get back, you many not be able to subscript with them.

Instead of [Int], you want [Self.Index]. So instead of enumerated, you want the more general zip:

```<code>extension Collection where Self.Element: Equatable {
    func indicesOfElements(equalTo element: Self.Element) -> [Self.Index] {
        return zip(self.indices, self)    // Zip together the index and element
            .filter { $0.1 == element }   // Find the ones that match
            .map { $0.0 }                 // Return the elements
    }
}

[1,2,3,4,1].indicesOfElements(equalTo: 1) // => [0,4]
</code>```

That said, a simpler approach would be:

```<code>extension Collection where Self.Element: Equatable {
    func indicesOfElements(equalTo element: Self.Element) -> [Self.Index] {
        return indices.filter { self[$0] == element }
    }
}
</code>```

To see the problem w/ subscripting, consider this:

```<code>let s = "abcabc"
let i = s.indicesOfElements(equalTo: "a").first!
s[i] // "a"

let j = findAll(s, "a").first!
s[j] // error: 'subscript' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion
</code>```

While a protocol extension is the preferred way to do this in Swift, this is directly convertible to the following generic function syntax:

```<code>func indicesOfElements<C: Collection>(in collection: C, equalTo element: C.Element) -> [C.Index]
    where C.Element: Equatable {
        return collection.indices.filter { collection[$0] == element }
}
</code>```

The following style is also equivalent, and has a slightly shallower learning curve (no need for filter.

```<code>func simplerIndicesOfElements<C: Collection>(in collection: C, equalTo element: C.Element) -> [C.Index]
    where C.Element: Equatable {

        var results: [C.Index] = []

        for index in collection.indices {
            if collection[index] == element {
                results.append(index)
            }
        }

        return results
}
</code>```

I believe even fairly new Swift developers should learn to read simple filter and map expressions (though these should aways be kept simple, even by experts!) But there is absolutely nothing wrong with learning simple for iteration first.

If you're just getting started, note the naming style here as well. Your initial example included two unnamed parameters. In many (most) cases this is poor Swift. In Swift we generally try to name our parameters such that they read fairly naturally in English. In findAll(xs, x) it's unclear what the parameters are or what the return value will be in. In indicesOfElements(in: xs, equalTo: x), all the information is available at the call site.

In Swift 3, this takes a lot more syntax than you probably expect:

```<code>func indicesOfElements<C: Collection>(in collection: C, equalTo element: C.Iterator.Element) -> [C.Index]
    where C.Iterator.Element: Equatable, C.Indices.Iterator.Element == C.Index {
    // ... Same body ...
}
</code>```

In Swift 3, associated types can't have additional constraints put on them. This seems a small thing, but it's huge. It means that there's no way to say Collection.Indices actually contains Collection.Index. And there's no way to create a Collection.Element (the type returned by subscripting the collection) that is promised to be the same as Collection.Iterator.Element (the type returned by iterating over the collection). This leads to a lot of C.Iterator... and where clauses that seem obvious like C.Indices.Iterator.Element == C.Index.

If you're near the start of your Swift journey, I'd probably skip over the generics entirely, and write this in terms of [Int]. A very common mistake by Swift programmers (new and "old") is to jump to generic programming before they have any need of it. But if you're at the stage where you're tackling generics, this is how you often have to write them in Swift 3. (Swift 4 is a dramatic improvement for generic programming.)

Body:
Ken's answer is good, but Collection can have an Index other than Int. If you try to use the indexes you get back, you many not be able to subscript with them.

Instead of [Int], you want [Self.Index]. So instead of enumerated, you want the more general zip:

extension Collection where Self.Element: Equatable {
    func indicesOfElements(equalTo element: Self.Element) -> [Self.Index] {
        return zip(self.indices, self)    // Zip together the index and element
            .filter { $0.1 == element }   // Find the ones that match
            .map { $0.0 }                 // Return the elements
    }
}

[1,2,3,4,1].indicesOfElements(equalTo: 1) // => [0,4]

That said, a simpler approach would be:

extension Collection where Self.Element: Equatable {
    func indicesOfElements(equalTo element: Self.Element) -> [Self.Index] {
        return indices.filter { self[$0] == element }
    }
}

To see the problem w/ subscripting, consider this:

let s = "abcabc"
let i = s.indicesOfElements(equalTo: "a").first!
s[i] // "a"

let j = findAll(s, "a").first!
s[j] // error: 'subscript' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion

While a protocol extension is the preferred way to do this in Swift, this is directly convertible to the following generic function syntax:

func indicesOfElements<C: Collection>(in collection: C, equalTo element: C.Element) -> [C.Index]
    where C.Element: Equatable {
        return collection.indices.filter { collection[$0] == element }
}

The following style is also equivalent, and has a slightly shallower learning curve (no need for filter.

func simplerIndicesOfElements<C: Collection>(in collection: C, equalTo element: C.Element) -> [C.Index]
    where C.Element: Equatable {

        var results: [C.Index] = []

        for index in collection.indices {
            if collection[index] == element {
                results.append(index)
            }
        }

        return results
}

I believe even fairly new Swift developers should learn to read simple filter and map expressions (though these should aways be kept simple, even by experts!) But there is absolutely nothing wrong with learning simple for iteration first.

If you're just getting started, note the naming style here as well. Your initial example included two unnamed parameters. In many (most) cases this is poor Swift. In Swift we generally try to name our parameters such that they read fairly naturally in English. In findAll(xs, x) it's unclear what the parameters are or what the return value will be in. In indicesOfElements(in: xs, equalTo: x), all the information is available at the call site.

In Swift 3, this takes a lot more syntax than you probably expect:

func indicesOfElements<C: Collection>(in collection: C, equalTo element: C.Iterator.Element) -> [C.Index]
    where C.Iterator.Element: Equatable, C.Indices.Iterator.Element == C.Index {
    // ... Same body ...
}

In Swift 3, associated types can't have additional constraints put on them. This seems a small thing, but it's huge. It means that there's no way to say Collection.Indices actually contains Collection.Index. And there's no way to create a Collection.Element (the type returned by subscripting the collection) that is promised to be the same as Collection.Iterator.Element (the type returned by iterating over the collection). This leads to a lot of C.Iterator... and where clauses that seem obvious like C.Indices.Iterator.Element == C.Index.

If you're near the start of your Swift journey, I'd probably skip over the generics entirely, and write this in terms of [Int]. A very common mistake by Swift programmers (new and "old") is to jump to generic programming before they have any need of it. But if you're at the stage where you're tackling generics, this is how you often have to write them in Swift 3. (Swift 4 is a dramatic improvement for generic programming.)


问:
Are infinite lists useful for any real world applications?
I've been using haskell for quite a while now, and I've read most of Real World Haskell and Learn You a Haskell. What I want to know is whether there is a point to a language using lazy evaluation, in particular the "advantage" of having infinite lists, is there a task which infinite lists make very easy, or even a task that is only possible with infinite lists?</p>

答:
One of my pragmatic favorites is cycle. cycle [False, True] generates the infinite list [False, True, False, True, False ...]. In particular, xs ! 0 = False, xs ! 1 = True, so this is just says whether or not the index of the element is odd or not. Where does this show up? Lot's of places, but here's one that any web developer ought to be familiar with: making tables that alternate shading from row to row.

The general pattern seen here is that if we want to do some operation on a finite list, rather than having to construct a specific finite list that will “do the thing we want,” we can use an infinite list that will work for all sizes of lists. camcann’s answer is in this vein.


问:
setting the categories using ajax in highcharts
trying to create a chart heatmap using highcharts library, i am using blacklabel plugin to set multilevel categories for x and y axis.

here is the blacklabel demo link.

```<code>https://jsfiddle.net/BlackLabel/TFhd7/
</code>```

if i hardcode the categories as per the demo, its working good, but i get the x axis categories, y axis categories and the data from the database. this is where i am facing issue.

my server side coding is c# with asp.net, and i am posting all ajax calls to request all the data.

can anyone help me with example how to set the multilevel categories dynamically with ajax call.

答:
blacklabel demo link https://jsfiddle.net/BlackLabel/TFhd7/

at the above link, xaxis categories are hardcoded.
below is the snippet from the above link.

```<code>categories: [{
        name: "Fruit",
        categories: ["Apple", "Banana", "Orange"]
    }, {
        name: "Vegetable",
        categories: ["Carrot", "Potato", "Tomato"]
    }, {
        name: "Fish",
        categories: ["Cod", "Salmon", "Tuna"]
    }]
</code>```

now i am trying to generate similar kind of json format by connecting to the DB and sending to the Javascript thru c#.

as i said in my first post that i am facing issues in setting the categories when i get it from the DB, if i hardcode as per the example it works good.

so the solution i found is...
1) return data into json from c# .
jsonconvert.serializeobject(data)

2) parse the data into json format at the success function of ajax call.
JSON.parse(response)

Body:
trying to create a chart heatmap using highcharts library, i am using blacklabel plugin to set multilevel categories for x and y axis.

here is the blacklabel demo link.

https://jsfiddle.net/BlackLabel/TFhd7/

if i hardcode the categories as per the demo, its working good, but i get the x axis categories, y axis categories and the data from the database. this is where i am facing issue.

my server side coding is c# with asp.net, and i am posting all ajax calls to request all the data.

can anyone help me with example how to set the multilevel categories dynamically with ajax call.

Body:
blacklabel demo link https://jsfiddle.net/BlackLabel/TFhd7/

at the above link, xaxis categories are hardcoded.
below is the snippet from the above link.

categories: [{
        name: "Fruit",
        categories: ["Apple", "Banana", "Orange"]
    }, {
        name: "Vegetable",
        categories: ["Carrot", "Potato", "Tomato"]
    }, {
        name: "Fish",
        categories: ["Cod", "Salmon", "Tuna"]
    }]

now i am trying to generate similar kind of json format by connecting to the DB and sending to the Javascript thru c#.

as i said in my first post that i am facing issues in setting the categories when i get it from the DB, if i hardcode as per the example it works good.

so the solution i found is...
1) return data into json from c# .
jsonconvert.serializeobject(data)

2) parse the data into json format at the success function of ajax call.
JSON.parse(response)


问:
a regex to parse BEM class selector with javascript
here my problem :

I want to split a string into an array of object.
My string is a BEM class selector like so :

where my string (without dot) would be splitted by matching '__' and '--'.

foo-bar--baz__foo--bar = ['foo-bar', '--baz', '__foo', '--bar']

foo-bar--baz = ['foo-bar', '--baz']

foo-bar__bar--baz = ['foo-bar', '__bar', '--baz']

foo = ['foo']

I tried with the following regex :

```<code>const regex = /([a-zA-Z0-9']+)(--[a-zA-Z0-9']+)(__[a-zA-Z0-9']+)/g;

while (match = reg.exec(string)) {
    var group1 = match[1];
    var group2 = match[2];
    var group3 = match[3];

    console.log(group1+'; '+group2+'; '+group3);
}
</code>```

but foo-bar--baz__foo--bar only output:

```<code>foo-bar --baz __foo
</code>```

and not the last --bar…

I cannot figure out why.

Also, maybe a better overall solution exist to solve my problem…

Thank's for the help

答:
I know nothing about BEM but splitting a string into an object is easy.  I have no idea if it's valid BEM.  It won't work with more items in the string.

var a = "foo-bar--baz__foo--bar"
var names = ["block","modifier","element","modifier"];
var arr = a.split(/--|__/g).map(function (el, i) {
  var obj = {};
  obj[names[i]] = el;
  return obj;
});
console.log(arr);```

Body:
here my problem :

I want to split a string into an array of object.
My string is a BEM class selector like so :

where my string (without dot) would be splitted by matching '__' and '--'.

foo-bar--baz__foo--bar = ['foo-bar', '--baz', '__foo', '--bar']

foo-bar--baz = ['foo-bar', '--baz']

foo-bar__bar--baz = ['foo-bar', '__bar', '--baz']

foo = ['foo']

I tried with the following regex :

const regex = /([a-zA-Z0-9']+)(--[a-zA-Z0-9']+)(__[a-zA-Z0-9']+)/g;

while (match = reg.exec(string)) {
    var group1 = match[1];
    var group2 = match[2];
    var group3 = match[3];

    console.log(group1+'; '+group2+'; '+group3);
}

but foo-bar--baz__foo--bar only output:

foo-bar --baz __foo

and not the last --bar…

I cannot figure out why.

Also, maybe a better overall solution exist to solve my problem…

Thank's for the help


问:
GIT re-merge files from dev to master
My master GIT branch seams to have some errors thus I'd like to recheck, re-merge or possibly clone my dev branch over the master branch so the master branch would be a copy of dev.

How can I do that?
Thx.

答:
Good question. I have wanted to do this before myself and I never did. My best guess might be to try the below. NOTE I'm not sure how well this will work for you since I have not done it myself.

```<code>git checkout master

git pull origin dev

git commit -a -m "reverted to dev"
</code>```

Doing it the above way will likely cause conflicts.

Title: GIT re-merge files from dev to master

Body:
Good question. I have wanted to do this before myself and I never did. My best guess might be to try the below. NOTE I'm not sure how well this will work for you since I have not done it myself.

git checkout master

git pull origin dev

git commit -a -m "reverted to dev"

Doing it the above way will likely cause conflicts.


问:
Getting [object HTMLLIElement] instead of text. Javascript function
Hello I have a simple javascript function that chooses a random list item in an unordered list with the press of a button. It works fine, the console spits out a random list item when the button is clicked but when I try to display it on the HTML page all I am getting is this weird [object HTMLLIElement] instead of the text.

The goal is to display the text inbetween the list item. When I click the button it chooses a random list item for example:
5
 but I would like for just the 5 to be displayed.

Here is the HTML:

```<code><ul id="list">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
</ul>

<button id="randomize">randomize</button>

<p id="result">hello</p>
</code>```

and the JS:

```<code>var randomize = document.getElementById("randomize");
var listItems = document.getElementById("list").getElementsByTagName("li");
var result = document.getElementById("result");

randomize.addEventListener("click", randomizeIt);

function randomizeIt () {
    var randomItem = listItems[Math.floor(Math.random() * listItems.length)];
    result.innerHTML = randomItem;
    console.log(randomItem);
}
</code>```

thanks in advance

答:
Well you set result to the li object, you have to get the text inside

```<code>result.innerHTML = randomItem.textContent;
</code>```

Body:
Hello I have a simple javascript function that chooses a random list item in an unordered list with the press of a button. It works fine, the console spits out a random list item when the button is clicked but when I try to display it on the HTML page all I am getting is this weird [object HTMLLIElement] instead of the text.

The goal is to display the text inbetween the list item. When I click the button it chooses a random list item for example:
5
 but I would like for just the 5 to be displayed.

Here is the HTML:

1

2

3

4

5

6

7

<button id="randomize">randomize</button>

hello

and the JS:

var randomize = document.getElementById("randomize");
var listItems = document.getElementById("list").getElementsByTagName("li");
var result = document.getElementById("result");

randomize.addEventListener("click", randomizeIt);

function randomizeIt () {
    var randomItem = listItems[Math.floor(Math.random() * listItems.length)];
    result.innerHTML = randomItem;
    console.log(randomItem);
}

thanks in advance

Body:
Well you set result to the li object, you have to get the text inside

result.innerHTML = randomItem.textContent;


问:
Big label in the button makes FlowPane grow
I made Button with max width of 300 and input a long text in it. Button got max size, but FlowPane, which also has max size of 300, grew in width. How comes that Button text is affecting FlowPane width? How to prevent it from happening?

Screenshot:

FlowPane is marked with yellow border.

Button settings:

FlowPane settings:

答:
Place the FlowPane inside an AnchorPane. Set the AnchorPane sizes to the FlowPane sizes. At the very least, set the left and right AnchorPane constraints of the FlowPane to 0.

Is FlowPane really the Node you want here?