问:
Recursion trick in ShaderEffectSource fails when I destroy the source object in onStateChanged
I want a ShaderEffectSource called snapshotter that updates on every change of a source item, but when the source item is destroyed, I want snapshotter to retain the last state of the source item.

In my code I use a workaround for a Qt deficiency - setting snapshotter.sourceItem = snapshotter when the previous source item gets destroyed. This works fine when I destroy the old source item e.g. on key press. But when I do it in an onStateChanged handler, I get this error:

ShaderEffectSource: 'recursive' must be set to true when rendering recursively.

But I don't want to set recursive: true, because then snapshotter would start repainting as fast as possible, wasting a lot of processing power.

Any idea why that problem happens considering it works fine when using key press, and/or a workaround?

I realize I'm asking why a hacky solution fails in some cases, but since it works in some cases, I'd like to use the solution anyway as it's very useful.

My code: (main.qml)

```<code>import QtQuick 2.6
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480

    Loader {
        active: true
        id: loader
        sourceComponent:
            Rectangle {
                color: "red"
                border.color: "white"
                width: 100
                height: 100
                parent: row

                states: [
                    State {
                        // the condition is always true, in this example code
                        name: "theOnlyState"; when: width === 100
                    }
                ]
                onStateChanged: {
                    if(state === "theOnlyState") {
                        loader.active = false;
                    }
                }
            }
    }

    Row {
        id: row
        ShaderEffectSource {
            id: snapshotItem
            sourceItem: {
                if(loader.status === Loader.Ready) {
                    return loader.item;
                } else {
                    return snapshotItem;
                }
            }
            live: loader.status === Loader.Ready
            width: 100
            height: 100
        }
    }
}
</code>```

Note: I just had an idea: maybe setting recursive: true will not create the problem I mentioned, considering I'd only set it when live == false. Maybe Qt is smart enough not constantly redraw in that case. But I'm not sure how to check if that's true.

答:
As you found out yourself, when you have live = false and recursive = true it won't be redrawn all the time.

I think the problem of yours might arise due to the magic, QML uses for its state machine, going back and forth and so on...

As far as I understand your problem, you want to create an object, take a snapshot, and delete it right after that again.

This is easier achieved by using methods and signals than by some declarative state changes and so on.

Specifically you might be looking for scheduleUpdate() to render the next frame, without the need of setting live = true. The next thing you will be interested in is the signal: scheduledUpdateCompleted to delete your object again.

Something like this:

```<code>import QtQuick 2.0
import QtQuick.Controls 2.0
import QtGraphicalEffects 1.0
ApplicationWindow {
    width: 1024
    height: 800
    visible: true

    Button {
        text: 'Next'
        onClicked: {
            ses.sourceItem = prototype.createObject(ses)
        }
    }

    ShaderEffectSource {
        id: ses
        y: 100
        width: 50
        height: 50
        live: false
        onSourceItemChanged: if (sourceItem !== this) scheduleUpdate()
        onScheduledUpdateCompleted: {
            sourceItem.destroy()
            sourceItem = this
        }
    }

    Component {
        id: prototype
        Rectangle {
            width: 50
            height: 50
            color: Qt.rgba(Math.random(-1), Math.random(0), Math.random(1))
            visible: false
            Component.onCompleted: console.log('Created new Rectangle with color', color)
            Component.onDestruction: console.log('Destroy Rectangle with color', color)
        }
    }
}
</code>```

Remember: The sourceItem does not have to be visible to be rendered into an ShaderEffectSource. If it is not necessary for other reasons, I would keep it invisible, so it is not rendered twice.

Body:
I want a ShaderEffectSource called snapshotter that updates on every change of a source item, but when the source item is destroyed, I want snapshotter to retain the last state of the source item.

In my code I use a workaround for a Qt deficiency - setting snapshotter.sourceItem = snapshotter when the previous source item gets destroyed. This works fine when I destroy the old source item e.g. on key press. But when I do it in an onStateChanged handler, I get this error:

ShaderEffectSource: 'recursive' must be set to true when rendering recursively.

But I don't want to set recursive: true, because then snapshotter would start repainting as fast as possible, wasting a lot of processing power.

Any idea why that problem happens considering it works fine when using key press, and/or a workaround?

I realize I'm asking why a hacky solution fails in some cases, but since it works in some cases, I'd like to use the solution anyway as it's very useful.

My code: (main.qml)

import QtQuick 2.6
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480

    Loader {
        active: true
        id: loader
        sourceComponent:
            Rectangle {
                color: "red"
                border.color: "white"
                width: 100
                height: 100
                parent: row

                states: [
                    State {
                        // the condition is always true, in this example code
                        name: "theOnlyState"; when: width === 100
                    }
                ]
                onStateChanged: {
                    if(state === "theOnlyState") {
                        loader.active = false;
                    }
                }
            }
    }

    Row {
        id: row
        ShaderEffectSource {
            id: snapshotItem
            sourceItem: {
                if(loader.status === Loader.Ready) {
                    return loader.item;
                } else {
                    return snapshotItem;
                }
            }
            live: loader.status === Loader.Ready
            width: 100
            height: 100
        }
    }
}

Note: I just had an idea: maybe setting recursive: true will not create the problem I mentioned, considering I'd only set it when live == false. Maybe Qt is smart enough not constantly redraw in that case. But I'm not sure how to check if that's true.

Body:
As you found out yourself, when you have live = false and recursive = true it won't be redrawn all the time.

I think the problem of yours might arise due to the magic, QML uses for its state machine, going back and forth and so on...

As far as I understand your problem, you want to create an object, take a snapshot, and delete it right after that again.

This is easier achieved by using methods and signals than by some declarative state changes and so on.

Specifically you might be looking for scheduleUpdate() to render the next frame, without the need of setting live = true. The next thing you will be interested in is the signal: scheduledUpdateCompleted to delete your object again.

Something like this:

import QtQuick 2.0
import QtQuick.Controls 2.0
import QtGraphicalEffects 1.0
ApplicationWindow {
    width: 1024
    height: 800
    visible: true

    Button {
        text: 'Next'
        onClicked: {
            ses.sourceItem = prototype.createObject(ses)
        }
    }

    ShaderEffectSource {
        id: ses
        y: 100
        width: 50
        height: 50
        live: false
        onSourceItemChanged: if (sourceItem !== this) scheduleUpdate()
        onScheduledUpdateCompleted: {
            sourceItem.destroy()
            sourceItem = this
        }
    }

    Component {
        id: prototype
        Rectangle {
            width: 50
            height: 50
            color: Qt.rgba(Math.random(-1), Math.random(0), Math.random(1))
            visible: false
            Component.onCompleted: console.log('Created new Rectangle with color', color)
            Component.onDestruction: console.log('Destroy Rectangle with color', color)
        }
    }
}

Remember: The sourceItem does not have to be visible to be rendered into an ShaderEffectSource. If it is not necessary for other reasons, I would keep it invisible, so it is not rendered twice.


来源: stackexchange

问:
Creating a table of counts by some factor level in R
I have some data of foods eaten on different days.

```<code>day <- c(1,1,1,1,2,2,2,3,3,3,3,3)
food <- c('pizza','pizza','taco','snake','snake','taco','taco','pizza','taco','pizza','taco','snake')
all <- data.frame(day, food)
</code>```

I'd like to create a table with food on the x axis, day on the y axis, and the number of foods per day in the matrices such that

```<code>food.list <- unique(all$food)
 day.list <- unique(all$day )
output <- data.frame(c(2,1,1),c(0,2,1),c(2,2,1))
output
      1 2 3
pizza 2 0 2
taco  1 2 2
snake 1 1 1
</code>```

What is a straightforward way to solve this problem?

答:
Sorry but what's wrong with table?

```<code>day = c(1,1,1,1,2,2,2,3,3,3,3,3)
food = c('pizza','pizza','taco','snake','snake','taco','taco','pizza','taco','pizza','taco','snake')
table(food, day)

      day
food    1 2 3
  pizza 2 0 2
  snake 1 1 1
  taco  1 2 2
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have some data of foods eaten on different days.

day <- c(1,1,1,1,2,2,2,3,3,3,3,3)
food <- c('pizza','pizza','taco','snake','snake','taco','taco','pizza','taco','pizza','taco','snake')
all <- data.frame(day, food)

I'd like to create a table with food on the x axis, day on the y axis, and the number of foods per day in the matrices such that

food.list <- unique(all$food)
 day.list <- unique(all$day )
output <- data.frame(c(2,1,1),c(0,2,1),c(2,2,1))
output
      1 2 3
pizza 2 0 2
taco  1 2 2
snake 1 1 1

What is a straightforward way to solve this problem?

Body:
Sorry but what's wrong with table?

day = c(1,1,1,1,2,2,2,3,3,3,3,3)
food = c('pizza','pizza','taco','snake','snake','taco','taco','pizza','taco','pizza','taco','snake')
table(food, day)

      day
food    1 2 3
  pizza 2 0 2
  snake 1 1 1
  taco  1 2 2


问:
Azure search filtering performance over Edm.Int32 and Collection(Edm.String)
I'm using Azure Search on my e-commerce site, and now want to implement filtering.

I've faced issue with performance. I have index with products. Each product belong to category. Each category can have nested subcategories.
My business purpose is when customer is on category page i need to show products even from subcategories, so i have doubts about how to store this relation(products to categories) in azure products index.
I'm considering two possibilities:

I can store only products category id in field with type Edm.Int32. Then when customer goes to this category i query to my sql server to get all subcategory ids and then construct my query to index like this

categoryId eq 34 or categoryId eq 36 or categoryId eq 37 ...

Other way is to create field with type Collection(Edm.String) and to store products category id and nested categories ids in this field and then my query to index would look like this

categoryIds/any(c: c eq '35')

So which way will be faster?

答: Option #2 is likely faster since the number of documents in the index will be far fewer, but the only way to be sure is to run some experiments with your data and queries. Overall query performance is going to depend on other factors like whether you're doing full-text search, faceting, geo-spatial, etc.</p>


问:
Extracting information from a a java core dump with jmap(1.5)
Long story short, some coworkers are running a pretty old setup(oc4j jdk1.5.6 in x86_64) with an application which happens to be mission critical. They recently have tried to deploy a new version of the application, but as soon as they do the java process(es) throw a core dump and die.

The problem is, the core dumps seem to be fine, gdb can open them, but jmap and other tools refuse to process them:

```<code># /usr/java/jdk1.5.0_06/bin/jmap /usr/java/jdk1.5.0_06/bin/java core
Attaching to core core from executable /usr/java/jdk1.5.0_06/bin/java, please wait...
Error attaching to core file: Can't attach to the core file
</code>```

And newer versions throw a exception:

```<code># jdk1.6.0_45/bin/jmap /usr/java/jdk1.5.0_06/bin/java core
Attaching to core core from executable /usr/java/jdk1.5.0_06/bin/java, please wait...
Exception in thread "main" java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at sun.tools.jmap.JMap.runTool(JMap.java:179)
        at sun.tools.jmap.JMap.main(JMap.java:110)
Caused by: sun.jvm.hotspot.runtime.VMVersionMismatchException: Supported versions are 20.45-b01. Target VM is 1.5.0_06-b05
        at sun.jvm.hotspot.runtime.VM.checkVMVersion(VM.java:224)
        at sun.jvm.hotspot.runtime.VM.<init>(VM.java:287)
        at sun.jvm.hotspot.runtime.VM.initialize(VM.java:357)
        at sun.jvm.hotspot.bugspot.BugSpotAgent.setupVM(BugSpotAgent.java:594)
        at sun.jvm.hotspot.bugspot.BugSpotAgent.go(BugSpotAgent.java:494)
        at sun.jvm.hotspot.bugspot.BugSpotAgent.attach(BugSpotAgent.java:348)
        at sun.jvm.hotspot.tools.Tool.start(Tool.java:169)
        at sun.jvm.hotspot.tools.PMap.main(PMap.java:67)
        ... 6 more
</code>```

gdb offers little information without symbols:

```<code>Reading symbols from /usr/java/jdk1.5.0_06/bin/java...(no debugging symbols found)...done.

[New Thread 9841]
[New Thread 31442]
[New Thread 31441]
...
Core was generated by `/usr/java/jdk1.5.0_06/bin/java -server -XX:+UseConcMarkSweepGC -XX:MaxHeapFreeR'.
Program terminated with signal 6, Aborted.
#0  0x0000003bbf030285 in ?? ()
(gdb) bt
#0  0x0000003bbf030285 in ?? ()
#1  0x0000003bbf031d30 in ?? ()
#2  0x0000000000000000 in ?? ()
</code>```

The only valuable information I've gathered from the core is that most threads
are blocked(I'm far from being a gdb guru):

```<code>  35 Thread 10093  0x0000003bbfc0b1c0 in pthread_cond_timedwait@@GLIBC_2.3.2 ()
   from /lib64/libpthread.so.0
  34 Thread 10097  0x0000003bbfc0b1c0 in pthread_cond_timedwait@@GLIBC_2.3.2 ()
   from /lib64/libpthread.so.0
  33 Thread 10099  0x0000003bbfc0b1c0 in pthread_cond_timedwait@@GLIBC_2.3.2 ()
   from /lib64/libpthread.so.0
</code>```

Besides, I don't know if it's really relevant. The app is almost always heavily loaded, and my bet is that there were some lock contention already but since it's another's team app my knowledge about it it's pretty shallow.

I guess this is a long shot, but is there something that we can do to get a java thread dump or something like that? Do Sun used to offer debuginfo of the jdk as I guess is avalaible now with openjdk?

Thanks in advance.

UPDATE: The other team has resolved the issue without getting info from the core dump, just by trial and error after successfully replicating the problem in a test system. I'm still intrigued about the thing: how to debug an ancient java core dump which jmap can't process, it might be valuable info for the future, althought it seems is that there is no solution to that problem. Probably the JVM memory got corrupted and that's why jmap can't process it.

答:
You can add the following JVM option when starting your application, that will allow you to run any command you specify if a fatal JVM error occurs:

```<code>-XX:OnError="<cmd args>"
</code>```

For instance, you could run a command (or a script) that will perform certain actions like get a heap or thread dump.

Body:
Long story short, some coworkers are running a pretty old setup(oc4j jdk1.5.6 in x86_64) with an application which happens to be mission critical. They recently have tried to deploy a new version of the application, but as soon as they do the java process(es) throw a core dump and die.

The problem is, the core dumps seem to be fine, gdb can open them, but jmap and other tools refuse to process them:

# /usr/java/jdk1.5.0_06/bin/jmap /usr/java/jdk1.5.0_06/bin/java core
Attaching to core core from executable /usr/java/jdk1.5.0_06/bin/java, please wait...
Error attaching to core file: Can't attach to the core file

And newer versions throw a exception:

# jdk1.6.0_45/bin/jmap /usr/java/jdk1.5.0_06/bin/java core
Attaching to core core from executable /usr/java/jdk1.5.0_06/bin/java, please wait...
Exception in thread "main" java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at sun.tools.jmap.JMap.runTool(JMap.java:179)
        at sun.tools.jmap.JMap.main(JMap.java:110)
Caused by: sun.jvm.hotspot.runtime.VMVersionMismatchException: Supported versions are 20.45-b01. Target VM is 1.5.0_06-b05
        at sun.jvm.hotspot.runtime.VM.checkVMVersion(VM.java:224)
        at sun.jvm.hotspot.runtime.VM.<init>(VM.java:287)
        at sun.jvm.hotspot.runtime.VM.initialize(VM.java:357)
        at sun.jvm.hotspot.bugspot.BugSpotAgent.setupVM(BugSpotAgent.java:594)
        at sun.jvm.hotspot.bugspot.BugSpotAgent.go(BugSpotAgent.java:494)
        at sun.jvm.hotspot.bugspot.BugSpotAgent.attach(BugSpotAgent.java:348)
        at sun.jvm.hotspot.tools.Tool.start(Tool.java:169)
        at sun.jvm.hotspot.tools.PMap.main(PMap.java:67)
        ... 6 more

gdb offers little information without symbols:

Reading symbols from /usr/java/jdk1.5.0_06/bin/java...(no debugging symbols found)...done.

[New Thread 9841]
[New Thread 31442]
[New Thread 31441]
...
Core was generated by `/usr/java/jdk1.5.0_06/bin/java -server -XX:+UseConcMarkSweepGC -XX:MaxHeapFreeR'.
Program terminated with signal 6, Aborted.
#0  0x0000003bbf030285 in ?? ()
(gdb) bt
#0  0x0000003bbf030285 in ?? ()
#1  0x0000003bbf031d30 in ?? ()
#2  0x0000000000000000 in ?? ()

The only valuable information I've gathered from the core is that most threads
are blocked(I'm far from being a gdb guru):

  35 Thread 10093  0x0000003bbfc0b1c0 in pthread_cond_timedwait@@GLIBC_2.3.2 ()
   from /lib64/libpthread.so.0
  34 Thread 10097  0x0000003bbfc0b1c0 in pthread_cond_timedwait@@GLIBC_2.3.2 ()
   from /lib64/libpthread.so.0
  33 Thread 10099  0x0000003bbfc0b1c0 in pthread_cond_timedwait@@GLIBC_2.3.2 ()
   from /lib64/libpthread.so.0

Besides, I don't know if it's really relevant. The app is almost always heavily loaded, and my bet is that there were some lock contention already but since it's another's team app my knowledge about it it's pretty shallow.

I guess this is a long shot, but is there something that we can do to get a java thread dump or something like that? Do Sun used to offer debuginfo of the jdk as I guess is avalaible now with openjdk?

Thanks in advance.

UPDATE: The other team has resolved the issue without getting info from the core dump, just by trial and error after successfully replicating the problem in a test system. I'm still intrigued about the thing: how to debug an ancient java core dump which jmap can't process, it might be valuable info for the future, althought it seems is that there is no solution to that problem. Probably the JVM memory got corrupted and that's why jmap can't process it.

Body:
You can add the following JVM option when starting your application, that will allow you to run any command you specify if a fatal JVM error occurs:

-XX:OnError="<cmd args>"

For instance, you could run a command (or a script) that will perform certain actions like get a heap or thread dump.


问:
Fluent NHibernate failing to create session factory with SQLCE
I'm trying out my very first project with Fluent NHibernate (any NHibernate flavor for that matter). I've been unable to get past the point of creating a Session Factory object as I'm running in to the following exception:

```<code>InnerException: NHibernate.HibernateException
                      Message=The IDbCommand and IDbConnection implementation in the assembly System.Data.SqlServerCe could not be found. Ensure that the assembly System.Data.SqlServerCe is located in the application directory or in the Global Assembly Cache. If the assembly is in the GAC, use <qualifyAssembly/> element in the application configuration file to specify the full name of the assembly.
                      Source=NHibernate
                      StackTrace:
                           at NHibernate.Driver.ReflectionBasedDriver..ctor(String driverAssemblyName, String connectionTypeName, String commandTypeName)
                           at NHibernate.Driver.SqlServerCeDriver..ctor()
                      InnerException:
</code>```

I'm using the latest FluentNHibernate binaries. VS 2010, on Window 7 x64. I've set the System.Data.SqlServerCe assembly to "Copy Local" changed the project's target platform to x86.

The fluent config is:

```<code>var config  = Fluently.Configure()
                        .Database(MsSqlCeConfiguration.Standard.ShowSql().ConnectionString(cnxString))
                        .Mappings(m => m.FluentMappings.AddFromAssemblyOf<SyncContract>());

if (!File.Exists(dbPath))
{
     var engine = new System.Data.SqlServerCe.SqlCeEngine(cnxString);
     engine.CreateDatabase();

     config.ExposeConfiguration(c => new SchemaExport(c).Create(false, true));
}
return config;
</code>```

Note: engine.CreateDatabase() works fine.

Any help/ideas please?

答:
Ok, figured it out.

Copy Local didn't apply to the test project I was using and consequently, the libs didn't get copied to the bin folder of the test project. Added all the libraries as references to the test project and set copy local on them to get this to work.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying out my very first project with Fluent NHibernate (any NHibernate flavor for that matter). I've been unable to get past the point of creating a Session Factory object as I'm running in to the following exception:

InnerException: NHibernate.HibernateException
                      Message=The IDbCommand and IDbConnection implementation in the assembly System.Data.SqlServerCe could not be found. Ensure that the assembly System.Data.SqlServerCe is located in the application directory or in the Global Assembly Cache. If the assembly is in the GAC, use <qualifyAssembly/> element in the application configuration file to specify the full name of the assembly.
                      Source=NHibernate
                      StackTrace:
                           at NHibernate.Driver.ReflectionBasedDriver..ctor(String driverAssemblyName, String connectionTypeName, String commandTypeName)
                           at NHibernate.Driver.SqlServerCeDriver..ctor()
                      InnerException:

I'm using the latest FluentNHibernate binaries. VS 2010, on Window 7 x64. I've set the System.Data.SqlServerCe assembly to "Copy Local" changed the project's target platform to x86.

The fluent config is:

var config  = Fluently.Configure()
                        .Database(MsSqlCeConfiguration.Standard.ShowSql().ConnectionString(cnxString))
                        .Mappings(m => m.FluentMappings.AddFromAssemblyOf<SyncContract>());

if (!File.Exists(dbPath))
{
     var engine = new System.Data.SqlServerCe.SqlCeEngine(cnxString);
     engine.CreateDatabase();

     config.ExposeConfiguration(c => new SchemaExport(c).Create(false, true));
}
return config;

Note: engine.CreateDatabase() works fine.

Any help/ideas please?


问:
How to combine mulitple column adding '-' and removing '-' with value is NULL
this is my Data

```<code>col1    col2    col col3    col4    col5    col6
42      A       11  18      89      16      empty
42      B       12  empty   89      14      C
36      8       9   empty   empty   2       empty
</code>```

this is the Script I'm running

```<code>select col1 + COALESCE ([col2]+'-','')
+COALESCE([col3]+'-','')+COALESCE([col4]+'-','')
+COALESCE([col5]+'-','')+COALESCE([col6],'') as totalCol
FROM ...
</code>```

This is what I get

```<code>totalCol
42A-11-18-89-16-
42B-12- -89-14-C
368-9- - -2 -
</code>```

This is what I want

```<code>totalCol
42A-11-18-89-16
42B-12-89-14-C
368-9-2
</code>```

答:
Assuming you have contrived the data to illustrate the issue (because you have col in your data, but don't use col in your query), you can easily do it this way.  A dash (-) is added after all non-null data.  Then, we pull all but the last character (since it will always be a dash).

I also added more code to create the data, so that you can copy/run the whole query and see that it works.

```<code>declare @tbl table (
  col1 varchar(10) null,
  col2 varchar(10) null,
  col3 varchar(10) null,
  col4 varchar(10) null,
  col5 varchar(10) null,
  col6 varchar(10) null,
  col7 varchar(10) null
)

insert into @tbl values
('42', 'A', '11', '18', '89', '16', null),
('42', 'B', '12', null, '89', '14', 'C'),
('36', '8', '9', null, null, '2', null)

select left(x.concat_val, len(x.concat_val) - 1) as totalCol
from (
       select isnull(col1 + '-', '') +
              isnull(col2 + '-', '') +
              isnull(col3 + '-', '') +
              isnull(col4 + '-', '') +
              isnull(col5 + '-', '') +
              isnull(col6 + '-', '') +
              isnull(col7 + '-', '') as concat_val
       from @tbl
     ) as x
</code>```

Here's the returned data:

```<code>totalCol
-----------------------------------------------------------------------------
42-A-11-18-89-16
42-B-12-89-14-C
36-8-9-2
</code>```

Body:
this is my Data

col1    col2    col col3    col4    col5    col6
42      A       11  18      89      16      empty
42      B       12  empty   89      14      C
36      8       9   empty   empty   2       empty

this is the Script I'm running

select col1 + COALESCE ([col2]+'-','')
+COALESCE([col3]+'-','')+COALESCE([col4]+'-','')
+COALESCE([col5]+'-','')+COALESCE([col6],'') as totalCol
FROM ...

This is what I get

totalCol
42A-11-18-89-16-
42B-12- -89-14-C
368-9- - -2 -

This is what I want

totalCol
42A-11-18-89-16
42B-12-89-14-C
368-9-2

Body:
Assuming you have contrived the data to illustrate the issue (because you have col in your data, but don't use col in your query), you can easily do it this way.  A dash (-) is added after all non-null data.  Then, we pull all but the last character (since it will always be a dash).

I also added more code to create the data, so that you can copy/run the whole query and see that it works.

declare @tbl table (
  col1 varchar(10) null,
  col2 varchar(10) null,
  col3 varchar(10) null,
  col4 varchar(10) null,
  col5 varchar(10) null,
  col6 varchar(10) null,
  col7 varchar(10) null
)

insert into @tbl values
('42', 'A', '11', '18', '89', '16', null),
('42', 'B', '12', null, '89', '14', 'C'),
('36', '8', '9', null, null, '2', null)

select left(x.concat_val, len(x.concat_val) - 1) as totalCol
from (
       select isnull(col1 + '-', '') +
              isnull(col2 + '-', '') +
              isnull(col3 + '-', '') +
              isnull(col4 + '-', '') +
              isnull(col5 + '-', '') +
              isnull(col6 + '-', '') +
              isnull(col7 + '-', '') as concat_val
       from @tbl
     ) as x

Here's the returned data:

totalCol
-----------------------------------------------------------------------------
42-A-11-18-89-16
42-B-12-89-14-C
36-8-9-2


问:
How do I change onclick attributes in javascript?
I have HTML that displays a button and a paragraph. When you click on the paragraph, it indicates whether the paragraph has been clicked on an odd or even amount of times. I'm trying to get the button to expand the paragraph to include a count of how many times the paragraph has been clicked, and revert back to it's original text when the button is clicked again. For some reason, I don't think my button properly communicates with the paragraph. Here's my code:

```<code> var doClickCount = false;
 var clickCounter = 0
 function toggleParagraphCounter(event) {
     var clickMeEvenTimes = true;
     doClickCount = true;
     if (doClickCount === true) {
        function clickMe() {
      var para1 = document.getElementById("para1");
      if (clickMeEvenTimes) {
        clickCounter += 1;
        para1.style = "color:green";
        para1.innerHTML = "Click this paragraph." +
        " It has been clicked an odd number of times.\
        Clicked" + clickCounter + "times with counting enabled." ;
      }
      else {
        clickCounter += 1;
        para1.style = "font-size:0.9em";
        para1.innerHTML = "Click this paragraph." +
        " It has been clicked an even number of times.\
        Clicked" + clickCounter + "times with counting enabled.";
      }
      clickMeEvenTimes = !clickMeEvenTimes;
  }
 }  else {
    function clickMe() {
      var para1 = document.getElementById("para1");
      if (clickMeEvenTimes) {
        para1.style = "color:green";
        para1.innerHTML = "Click this paragraph." +
        " It has been clicked an odd number of times.";
      }
      else {
        para1.style = "font-size:0.9em";
        para1.innerHTML = "Click this paragraph." +
        " It has been clicked an even number of times.";
      }
      clickMeEvenTimes = !clickMeEvenTimes;
  }
 }

 }
</code>```

What else could I do to try and solve this?

答:
Hey so here's the code that worked: </p>

```<code> var doClickCount = false;
 var clickCounter = 0

 function countPar1 () {
      var para1 = document.getElementById("para1");
      if (clickMeEvenTimes) {
        clickCounter += 1;
        para1.style = "color:green";
        para1.innerHTML = "Click this paragraph." +
        " It has been clicked an odd number of times.\
        Clicked " + clickCounter + " times with counting enabled." ;
      }
      else {
        clickCounter += 1;
        para1.style = "font-size:0.9em";
        para1.innerHTML = "Click this paragraph." +
        " It has been clicked an even number of times.\
        Clicked " + clickCounter + " times with counting enabled.";
      }
      clickMeEvenTimes = !clickMeEvenTimes;
 }

 function toggleParagraphCounter(event) {
 doClickCount =! doClickCount;
     if (doClickCount) {
document.getElementById("para1").onclick = function() {
    countPar1();
};
 }  else {
 document.getElementById("para1").onclick = function() {
     clickMe();
   };

    }
 }
</code>```

Body:
I have HTML that displays a button and a paragraph. When you click on the paragraph, it indicates whether the paragraph has been clicked on an odd or even amount of times. I'm trying to get the button to expand the paragraph to include a count of how many times the paragraph has been clicked, and revert back to it's original text when the button is clicked again. For some reason, I don't think my button properly communicates with the paragraph. Here's my code:

 var doClickCount = false;
 var clickCounter = 0
 function toggleParagraphCounter(event) {
     var clickMeEvenTimes = true;
     doClickCount = true;
     if (doClickCount === true) {
        function clickMe() {
      var para1 = document.getElementById("para1");
      if (clickMeEvenTimes) {
        clickCounter += 1;
        para1.style = "color:green";
        para1.innerHTML = "Click this paragraph." +
        " It has been clicked an odd number of times.\
        Clicked" + clickCounter + "times with counting enabled." ;
      }
      else {
        clickCounter += 1;
        para1.style = "font-size:0.9em";
        para1.innerHTML = "Click this paragraph." +
        " It has been clicked an even number of times.\
        Clicked" + clickCounter + "times with counting enabled.";
      }
      clickMeEvenTimes = !clickMeEvenTimes;
  }
 }  else {
    function clickMe() {
      var para1 = document.getElementById("para1");
      if (clickMeEvenTimes) {
        para1.style = "color:green";
        para1.innerHTML = "Click this paragraph." +
        " It has been clicked an odd number of times.";
      }
      else {
        para1.style = "font-size:0.9em";
        para1.innerHTML = "Click this paragraph." +
        " It has been clicked an even number of times.";
      }
      clickMeEvenTimes = !clickMeEvenTimes;
  }
 }

 }

What else could I do to try and solve this?

Body:
Hey so here's the code that worked:

 var doClickCount = false;
 var clickCounter = 0

 function countPar1 () {
      var para1 = document.getElementById("para1");
      if (clickMeEvenTimes) {
        clickCounter += 1;
        para1.style = "color:green";
        para1.innerHTML = "Click this paragraph." +
        " It has been clicked an odd number of times.\
        Clicked " + clickCounter + " times with counting enabled." ;
      }
      else {
        clickCounter += 1;
        para1.style = "font-size:0.9em";
        para1.innerHTML = "Click this paragraph." +
        " It has been clicked an even number of times.\
        Clicked " + clickCounter + " times with counting enabled.";
      }
      clickMeEvenTimes = !clickMeEvenTimes;
 }

 function toggleParagraphCounter(event) {
 doClickCount =! doClickCount;
     if (doClickCount) {
document.getElementById("para1").onclick = function() {
    countPar1();
};
 }  else {
 document.getElementById("para1").onclick = function() {
     clickMe();
   };

    }
 }


问:
Unexpected output from URLEncoder in Java
I am trying to encode a URL parameter.

For example when I am encoding

qOddENxeLxL+13drGKYUgA==\n

using URL Encoder tool

It gives the following output which works when I request API

qOddENxeLxL%2B13drGKYUgA%3D%3D%5Cn

But when I am encoding URL from my Java code (Android) using URLEncoder.encode("qOddENxeLxL+13drGKYUgA==\n", "UTF-8");

It gives me the following result

qOddENxeLxL%252B13drGKYUgA%253D%253D%250A

I tried using other Encoding schemes too but could not produce the same result.

答:
The issue is because the \n is being interpreted as a new line character. Java will treat \ inside a string as starting an escape sequence.
You have to escape it in order to get the same thing as in the URL you provided.

```<code>System.out.println(URLEncoder.encode("qOddENxeLxL+13drGKYUgA==\\n", "UTF-8"));
</code>```

This will provide the same result:

```<code>qOddENxeLxL%2B13drGKYUgA%3D%3D%5Cn
</code>```

Body:
The issue is because the \n is being interpreted as a new line character. Java will treat \ inside a string as starting an escape sequence.
You have to escape it in order to get the same thing as in the URL you provided.

System.out.println(URLEncoder.encode("qOddENxeLxL+13drGKYUgA==\\n", "UTF-8"));

This will provide the same result:

qOddENxeLxL%2B13drGKYUgA%3D%3D%5Cn


问:
R subset of data frame for cohort analysis
I have following data in the data frame df

```<code>persons  year
personA  2015
personB  2016
personC  2015
personB  2015
</code>```

how do I use subset function in R to filter personB who is in 2015 and 2016
I am using following Code, but does not work

```<code>df1 <- subset(df, (year==2015 & year ==2016))
</code>```

答:
I'd use dplyr for this as it's much easier than in base R.

```<code>library(dplyr)
df %>% group_by(persons) %>% filter(n() == 2)
</code>```

This groups the rows by person and then retains only groups with two members (both years).

Body:
I have following data in the data frame df

persons  year
personA  2015
personB  2016
personC  2015
personB  2015

how do I use subset function in R to filter personB who is in 2015 and 2016
I am using following Code, but does not work

df1 <- subset(df, (year==2015 & year ==2016))

Body:
I'd use dplyr for this as it's much easier than in base R.

library(dplyr)
df %>% group_by(persons) %>% filter(n() == 2)

This groups the rows by person and then retains only groups with two members (both years).


问:
How is a DryIoc container setup if you need different instances of same interface?
I am trying to use DryIoc with a .NET Web API 2 site to create my controllers. I have a situation where my controller needs a processor and the processor needs two instances of a storage class. Here is the basics:

```<code>public interface IStorage
{
    IEnumerable<string> List();
    void Add(string file);
    void Remove(string file);
}

public class FileSystemStorage : IStorage
{
    // Implement to store on file system.
}

public class S3Storage : IStorage
{
    // Implement to store in S3 bucket.
}

public interface IProcessor
{
    void Process();
}

public class Processor(IStorage sourceStorage, IStorage targetStorage)
{ // Implement a process that interacts with both storages }

public class ProcessController : ApiController
{
    private readonly IProcessor processor;
    public ProcessController(IProcessor processor)
    {
        this.processor = processor;
    }
}
</code>```

So, I need to have my IOC container (DryIoc) use two different classes for the interface IStorage. So, what I'd like is to setup IOC for something like this:

```<code>var sourceStorage = new FileSystemStorage();
var targetStorage = new S3Storage();
var processor = new Processor(sourceStorage, targetStorage);
// And then have DryIoc dependency resolver create
// controller with this processor.
</code>```

However, the normal way to register just won't work:

```<code>var c = new Container().WithWebApi(config);

// Need two different implementations...
c.Register<IStorage, ???>();

// And even if I had two instances, how would
// the processor know which one to use for what parameter?
c.Register<IProcessor, Processor>();
</code>```

I'm new to dependency injection containers and most of the docs are very abstract; I'm not grokking them. How is this done?

答:
Direct way is identify registrations of different storage implementations with different keys, and instruct processor what is what:

```<code>c.Register<IStorage, Foo>(serviceKey: "in");
c.Register<IStorage, Bar>(serviceKey: "out");
c.Register<IProcessor, Processor>(made: Parameters.Of
    .Name("source", serviceKey: "in")
    .Name("target", serviceKey: "out"));
</code>```

Problem, that it is a fragile approach cause changing parameter names will break the setup.

May be, you need to review why you have two identical interface params with different responsibilities, and distinguish their roles with more fitting absractions/interfaces.

Body:
I am trying to use DryIoc with a .NET Web API 2 site to create my controllers. I have a situation where my controller needs a processor and the processor needs two instances of a storage class. Here is the basics:

public interface IStorage
{
    IEnumerable<string> List();
    void Add(string file);
    void Remove(string file);
}

public class FileSystemStorage : IStorage
{
    // Implement to store on file system.
}

public class S3Storage : IStorage
{
    // Implement to store in S3 bucket.
}

public interface IProcessor
{
    void Process();
}

public class Processor(IStorage sourceStorage, IStorage targetStorage)
{ // Implement a process that interacts with both storages }

public class ProcessController : ApiController
{
    private readonly IProcessor processor;
    public ProcessController(IProcessor processor)
    {
        this.processor = processor;
    }
}

So, I need to have my IOC container (DryIoc) use two different classes for the interface IStorage. So, what I'd like is to setup IOC for something like this:

var sourceStorage = new FileSystemStorage();
var targetStorage = new S3Storage();
var processor = new Processor(sourceStorage, targetStorage);
// And then have DryIoc dependency resolver create
// controller with this processor.

However, the normal way to register just won't work:

var c = new Container().WithWebApi(config);

// Need two different implementations...
c.Register<IStorage, ???>();

// And even if I had two instances, how would
// the processor know which one to use for what parameter?
c.Register<IProcessor, Processor>();

I'm new to dependency injection containers and most of the docs are very abstract; I'm not grokking them. How is this done?

Body:
Direct way is identify registrations of different storage implementations with different keys, and instruct processor what is what:

c.Register<IStorage, Foo>(serviceKey: "in");
c.Register<IStorage, Bar>(serviceKey: "out");
c.Register<IProcessor, Processor>(made: Parameters.Of
    .Name("source", serviceKey: "in")
    .Name("target", serviceKey: "out"));

Problem, that it is a fragile approach cause changing parameter names will break the setup.

May be, you need to review why you have two identical interface params with different responsibilities, and distinguish their roles with more fitting absractions/interfaces.


问:
Created nuget package's dll can not be accessable from package's loaded project
I want to create a nuget package of my .net core class library.

I copied the nuget.exe file to the root folder of my Solution

Run nuget spec and Solution.nuspec file created. I modified it as below:

```<code><?xml version="1.0"?>
<package >
<metadata>
<id>Solution</id>
<version>1.0.0</version>
<authors>cc Team</authors>
<owners>cc</owners>
<licenseUrl></licenseUrl>
<projectUrl></projectUrl>
<iconUrl></iconUrl>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description></description>
<releaseNotes></releaseNotes>
<copyright>Copyright 2017</copyright>
<tags>c# .net</tags>
<dependencies>
    <dependency id="NETStandard.Library" version="1.6.1" />
</dependencies>
<references>
    <reference file="Solution.dll" />
</references>
</metadata>
<files>
<file src="Solution.dll" target="lib\netstandard1.6\Solution.dll"/>
</code>```

file's node src value outpupath of my solution. (bin\Release\netstandard1.6\Solution.dll)

Run nuget pack Solution.nuspec and  Solution.nupkg file created.

I put it to my package source.

Create a new .net core class library and select my Solution nuget package from local package source. It added to my project. There is no error or warning. But When I try to access a class from my Solution nuget package, it couldn't be found.I dowloaded  'Nuget Package Explorer' and opened my Solution.nupkg. Icould see Solution.dll and Solution.pdb file under lib --> netstandart1.6.

Then I searched about the error and found this :

```<code>"scripts": {
"postcompile": [
  "dotnet pack --no-build --configuration %compile:Configuration%"
]
}
</code>```

After compile my Solution project it creates Solution.1.0.0-0.nupkg file and Solution.1.0.0-0.symbols. I put it to my local package source but these packages are not listed in the 'Nuget Package Manager'.

Do you have any idea?

答:
After I clean 'C:\Users\XXX.nuget\packages\Solution' folder and add package again fix my problem.

Because there is bad formatted nutget package which I tried before.

Body:
I want to create a nuget package of my .net core class library.

I copied the nuget.exe file to the root folder of my Solution

Run nuget spec and Solution.nuspec file created. I modified it as below:

<?xml version="1.0"?>
<package >
<metadata>
<id>Solution</id>
<version>1.0.0</version>
<authors>cc Team</authors>
<owners>cc</owners>
<licenseUrl></licenseUrl>
<projectUrl></projectUrl>
<iconUrl></iconUrl>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<description></description>
<releaseNotes></releaseNotes>
<copyright>Copyright 2017</copyright>
<tags>c# .net</tags>
<dependencies>
    <dependency id="NETStandard.Library" version="1.6.1" />
</dependencies>
<references>
    <reference file="Solution.dll" />
</references>
</metadata>
<files>
<file src="Solution.dll" target="lib\netstandard1.6\Solution.dll"/>

file's node src value outpupath of my solution. (bin\Release\netstandard1.6\Solution.dll)

Run nuget pack Solution.nuspec and  Solution.nupkg file created.

I put it to my package source.

Create a new .net core class library and select my Solution nuget package from local package source. It added to my project. There is no error or warning. But When I try to access a class from my Solution nuget package, it couldn't be found.I dowloaded  'Nuget Package Explorer' and opened my Solution.nupkg. Icould see Solution.dll and Solution.pdb file under lib --> netstandart1.6.

Then I searched about the error and found this :

"scripts": {
"postcompile": [
  "dotnet pack --no-build --configuration %compile:Configuration%"
]
}

After compile my Solution project it creates Solution.1.0.0-0.nupkg file and Solution.1.0.0-0.symbols. I put it to my local package source but these packages are not listed in the 'Nuget Package Manager'.

Do you have any idea?


问:
How to link image into html using the intellij idea IDE?
I have got a simple html page on intellij idea that uses a java class to display the webpage on the localhost:9002/.

I am using the bootstrap library and my images are not been parsed on my webpage properly.

I am looking for someone to specify the correct directory of images within intellij and if any changes should be made to the standard image link in my html.

My image link is as follows:

```<code><a class="navbar-brand" href="ShoppingPortal.html"><img src="logo.png" alt="Company logo" style="width:225px;height:35px; padding-bottom: 2px;"></a>
</code>```

Any ideas???

Thanks

答:
If the image is in the same directory as your .html file then adding a forward slash -> src="/logo.png" should work.

If you are going to have more than one image it might be worth while adding an images directory to your root and then updating the src src="/images/logo.png"

Body:
I have got a simple html page on intellij idea that uses a java class to display the webpage on the localhost:9002/.

I am using the bootstrap library and my images are not been parsed on my webpage properly.

I am looking for someone to specify the correct directory of images within intellij and if any changes should be made to the standard image link in my html.

My image link is as follows:

Any ideas???

Thanks


问:
Build maven multimodule project in JAR
I have a parent Maven project (pom packaging) and 4 Maven modules (jar packaging) as children of that. Is there any way/plugin to create a importable dependency of the parent project including all the children? I mean that I want to create some kind of abstraction, so when somebody wants to import my project, it won't be necessary to import a specific childermodule (the module that he will use), he will just import the whole project (all the children modules)</p>

答:
The Maven parent project corresponds with inheritance. It is meant the children projects to inherit the settings, so you do not have to repeat them and you may set all the common stuff in a single place.

On other side, the convenience Maven project containing dependencies corresponds with composition.

You should not mix these two things together. Parent project is a common super-class of your modules. This convenience project you wish to have is a collection containing all your modules as dependencies. You should not want the theAnimal class to depend on all the animals.

Just accept the fact that you need two separate Maven projects:

the parent (if you need it), and

the convenience project for transitive dependencies.

The solution for your problem is described e.g. here: 3.6.1. Grouping Dependencies

If you have a set of dependencies which are logically grouped together. You can create a project with pom packaging that groups dependencies together. For example, let’s assume that your application uses Hibernate... Every project which uses Hibernate might also have a dependency on the Spring Framework and a MySQL JDBC driver. Instead of having to include these dependencies in every project that uses Hibernate, Spring, and MySQL you could create a special POM that does nothing more than declare a set of common dependencies. You could create a project called persistence-deps (short for Persistence Dependencies), and have every project that needs to do persistence depend on this convenience project.

Title: Build maven multimodule project in JAR


问:
C# GUI Programming Starting
So....I've never really done much in the way of GUI programming apps. Namely because for school ive been stuck in C++ land. But since Im graduating in December I thought it'd be nice (while im looking for a job) to study something I've wanted to look into for awhile. And please dont mark this as "subjective" im just simply asking what I need to "know" to get started.

Namely GUI programming. Im not used to it....nor have I really ever been. It's not something they focus on in school (for instance my senior design was a webcam mouse thing, but had very little in the way of GUI)

I've seen alot about C# being the superior GUI programming tool for fast development.....but I dont really know whats out there. I know "of" QT, and Im used to C++. However Im not too familiar with what the "choice" GUI language is. I do like programming on Windows however most of my stuff has been in Unix here lately (Mostly because of my OS class).

I dont know anything about .net, and i've heard of something called WPF? Is that part of .net.....or.....what? Im just a bit confused at where to start.

Thanks

答:
Yeah.... C# is a great tool for GUI.... My condition was same like yours when I started.... My suggestion is get into it.... Make some simple GUIs.... Its fun to make simple apps like say Calculator!

There are very good tutorials available on internet.... You are just a Google away from them.... And For everyproblem, There is Stack Overflow! :)

All the best!!

You can check this too: C# GUI primer tutorial

Title: C# GUI Programming Starting


问:
Python: writing to CSV in a for-loop, conditionally adding value in particular column
Here's an example of the contents of my CSV file:

```<code>Fruit, colour, ripe,

apple, green,,
banana, yellow,,
pineapple, green,,
plum, purple,,
</code>```

I want to loop through the contents of the CSV file and according to a test (extrinsic to the CSV data, using an input value supplied to the enclosing function), end up with something like this:

```<code>Fruit, colour, ripe,

apple, green, true,
banana, yellow,,
pineapple, green,,
plum, purple, true,
</code>```

My current code looks like this:

```<code>csv_data = csv.reader(open('./data/fruit_data.csv', 'r'))
for row in csv_data:
    fruit = row[0]
    if fruit == input:
    # Here, write 'true' in the 'ripe' column.
</code>```

It's easy enough to add new data in one go, using the CSV module or pandas, but here I need to add the data iteratively. It seems that I can't change the CSV file in place(?), but if I write out to a different CSV file, it's going to overwrite on each match within the loop, so it'll only reflect that value.

答:
You have, basically, two approaches:

1- Open a second text file before your loop then loop through each row of the initial file and append rows to the second file. After all rows are done, close the initial file. Example: How do you append to a file?

2- Read in everything from the initial csv. Then make changes to the object you created (I highly recommend using Pandas for this). Then write out to a csv. Here's an example of that method:

```<code>import pandas as pd
import numpy as np

# read in the csv
csv_data = pd.read_csv('./data/fruit_data.csv')

# I'm partial to the numpy where logic when creating a new column based
# on if/then logic on an existing column
csv_data['ripe'] = np.where(csv_data['fruit']==input, True, False)

# write out the csv
csv_data.to_csv('./data/outfile.csv')
</code>```

The choice between 1 and 2 should really come down to scale. If your csv is so big that you can't read it all in and manipulate it the way you want, then you should molest it line by line. If you can read the whole thing in and then manipulate it with Pandas, your life will be MUCH easier.

Body:
Here's an example of the contents of my CSV file:

Fruit, colour, ripe,

apple, green,,
banana, yellow,,
pineapple, green,,
plum, purple,,

I want to loop through the contents of the CSV file and according to a test (extrinsic to the CSV data, using an input value supplied to the enclosing function), end up with something like this:

Fruit, colour, ripe,

apple, green, true,
banana, yellow,,
pineapple, green,,
plum, purple, true,

My current code looks like this:

csv_data = csv.reader(open('./data/fruit_data.csv', 'r'))
for row in csv_data:
    fruit = row[0]
    if fruit == input:
    # Here, write 'true' in the 'ripe' column.

It's easy enough to add new data in one go, using the CSV module or pandas, but here I need to add the data iteratively. It seems that I can't change the CSV file in place(?), but if I write out to a different CSV file, it's going to overwrite on each match within the loop, so it'll only reflect that value.

Body:
You have, basically, two approaches:

1- Open a second text file before your loop then loop through each row of the initial file and append rows to the second file. After all rows are done, close the initial file. Example: How do you append to a file?

2- Read in everything from the initial csv. Then make changes to the object you created (I highly recommend using Pandas for this). Then write out to a csv. Here's an example of that method:

import pandas as pd
import numpy as np

# read in the csv
csv_data = pd.read_csv('./data/fruit_data.csv')

# I'm partial to the numpy where logic when creating a new column based
# on if/then logic on an existing column
csv_data['ripe'] = np.where(csv_data['fruit']==input, True, False)

# write out the csv
csv_data.to_csv('./data/outfile.csv')

The choice between 1 and 2 should really come down to scale. If your csv is so big that you can't read it all in and manipulate it the way you want, then you should molest it line by line. If you can read the whole thing in and then manipulate it with Pandas, your life will be MUCH easier.


问:
Centralized handling for HTTP errors in Angular 4
I want to inform the user if an HTTP request fails, without having to write additional code for every HTTP request.

I had a working prototype for angular 2:

```<code>@Injectable()
export class MyErrorHandler extends ErrorHandler {

  constructor() {
    super(false);
  }

  handleError(error: any) {
    this.tellUser(error);
    super.handleError(error);
  }

  tellUser(error: any) {
    // dig for the root cause
    if (error.rejection) {
      error = error.rejection;
    }
    if (error instanceof ViewWrappedError) {
       error = error.originalError;
    }

    let message;
    if (error instanceof Response) {
      // TODO: localize and display nicely
      const messages = {
        0: "Could not connect to server",
      }
      message = messages[error.status] || ("The server reported a system error (HTTP " + error.status + ")");
    } else {
      message = "A system error occurred.";
    }
    console.warn(message);
  }
}
</code>```

but the ViewWrappedError has been replaced in Angular 4 by

```<code>export function viewWrappedDebugError(err: any, context: DebugContext): Error {
  if (!(err instanceof Error)) {
    // errors that are not Error instances don't have a stack,
    // so it is ok to wrap them into a new Error object...
    err = new Error(err.toString());
  }
  _addDebugContext(err, context);
  return err;
}
</code>```

Which, by virtue of invoking toString on the HttpResponse, makes it hard to query the status code ...

I'd have expected angular to provide a public, well supported API for centralized error handling. Is there really no way to centrally handle HTTP errors other than parsing error messages?

Update: I'd prefer if a component could easily override the centralized error handling.

答:
I'm centralizing this kind of logic inside a BaseService, and then inherit every service from It. Angular 2 doesn't provide Http Interceptors as the previous version, making this kind of stuff difficult to handle.

```<code>import { Injectable } from '@angular/core';
import { Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { NotificationService } from '********';

@Injectable()
export class BaseService {
  protected url: string;
  protected http: Http;

  constructor(http: Http, protected notification: NotificationService) {
    this.http = http;
  }

  protected extractData(res: Response) {
      //
      // Depende do formato da response, algumas APIs retornam um objeto data e dentro deste o conteudo propriamente dito
      // Em minhas APIs sempre retorno diretamente o objeto que desejo
      //
      return res.json();
  }

  protected handleError(error: Response | any) {
    let erros: string[] = [];

    switch (error.status) {
      case 400:
        let res = error.json();

    //
    // Depende do formato, minhas APIs sempre retornar um objeto com array errors quando tenho 400
    //
        for (let index = 0; index < res.errors.length; index++) {
          let msg = res.errors[index];
          erros.push(msg);
        };

        this.notification.showMultipleWarn(erros);
        break;
      case 404:
    this.notification.showWarning('O recurso requisitado não existe.');
    break;
      case 406:
      case 409:
      case 500:
        this.notification.showError('Ocorreu um erro inesperado.');
        break;
      default:
        this.notification.showError('Ocorreu um erro inesperado.');
        break;
    }

    return Observable.throw(new Error(error.status));
  }
}
</code>```

Here's my blog post explaining some way to handle this less verbosely: Receitas Angular2: Interceptando erros HTTP de forma Global

The post is written in portuguese, but the code could give you some hints. I'm using this approach in some huge projects right now, and It's working fine.

Body:
I want to inform the user if an HTTP request fails, without having to write additional code for every HTTP request.

I had a working prototype for angular 2:

@Injectable()
export class MyErrorHandler extends ErrorHandler {

  constructor() {
    super(false);
  }

  handleError(error: any) {
    this.tellUser(error);
    super.handleError(error);
  }

  tellUser(error: any) {
    // dig for the root cause
    if (error.rejection) {
      error = error.rejection;
    }
    if (error instanceof ViewWrappedError) {
       error = error.originalError;
    }

    let message;
    if (error instanceof Response) {
      // TODO: localize and display nicely
      const messages = {
        0: "Could not connect to server",
      }
      message = messages[error.status] || ("The server reported a system error (HTTP " + error.status + ")");
    } else {
      message = "A system error occurred.";
    }
    console.warn(message);
  }
}

but the ViewWrappedError has been replaced in Angular 4 by

export function viewWrappedDebugError(err: any, context: DebugContext): Error {
  if (!(err instanceof Error)) {
    // errors that are not Error instances don't have a stack,
    // so it is ok to wrap them into a new Error object...
    err = new Error(err.toString());
  }
  _addDebugContext(err, context);
  return err;
}

Which, by virtue of invoking toString on the HttpResponse, makes it hard to query the status code ...

I'd have expected angular to provide a public, well supported API for centralized error handling. Is there really no way to centrally handle HTTP errors other than parsing error messages?

Update: I'd prefer if a component could easily override the centralized error handling.

Body:
I'm centralizing this kind of logic inside a BaseService, and then inherit every service from It. Angular 2 doesn't provide Http Interceptors as the previous version, making this kind of stuff difficult to handle.

import { Injectable } from '@angular/core';
import { Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { NotificationService } from '********';

@Injectable()
export class BaseService {
  protected url: string;
  protected http: Http;

  constructor(http: Http, protected notification: NotificationService) {
    this.http = http;
  }

  protected extractData(res: Response) {
      //
      // Depende do formato da response, algumas APIs retornam um objeto data e dentro deste o conteudo propriamente dito
      // Em minhas APIs sempre retorno diretamente o objeto que desejo
      //
      return res.json();
  }

  protected handleError(error: Response | any) {
    let erros: string[] = [];

    switch (error.status) {
      case 400:
        let res = error.json();

    //
    // Depende do formato, minhas APIs sempre retornar um objeto com array errors quando tenho 400
    //
        for (let index = 0; index < res.errors.length; index++) {
          let msg = res.errors[index];
          erros.push(msg);
        };

        this.notification.showMultipleWarn(erros);
        break;
      case 404:
    this.notification.showWarning('O recurso requisitado não existe.');
    break;
      case 406:
      case 409:
      case 500:
        this.notification.showError('Ocorreu um erro inesperado.');
        break;
      default:
        this.notification.showError('Ocorreu um erro inesperado.');
        break;
    }

    return Observable.throw(new Error(error.status));
  }
}

Here's my blog post explaining some way to handle this less verbosely: Receitas Angular2: Interceptando erros HTTP de forma Global

The post is written in portuguese, but the code could give you some hints. I'm using this approach in some huge projects right now, and It's working fine.


问:
How can I add a query string parameter to a link generated in Ruby?
I want to send a data from an X view to a Y view, using a link.
Then, in the Y view, I want to display the data I send from the X view:

/app/views/x.html.erb:

```<code><%= link_to 'A', y_path('data if A') %>
<%= link_to 'B', y_path('data if B') %>
</code>```

/app/views/y.html.erb:

```<code>#I show the data that I receive as parameter in the link
</code>```

What do I have to do to do this?

答:
First assign the correct value to your links:

```<code># x.html.erb

<%= link_to 'A', y_path(value: 'data if A') %>
<%= link_to 'B', y_path(value: 'data if B') %>
</code>```

Then assign the value you get from the link in the controller:

```<code># y_controller.rb

def y
  @value = params[:value]
end
</code>```

Finally, show the value using @value in your view:

```<code># y.html.erb

<%= @value %>
</code>```

Body:
I want to send a data from an X view to a Y view, using a link.
Then, in the Y view, I want to display the data I send from the X view:

/app/views/x.html.erb:

<%= link_to 'A', y_path('data if A') %>
<%= link_to 'B', y_path('data if B') %>

/app/views/y.html.erb:

#I show the data that I receive as parameter in the link

What do I have to do to do this?

Body:
First assign the correct value to your links:

# x.html.erb

<%= link_to 'A', y_path(value: 'data if A') %>
<%= link_to 'B', y_path(value: 'data if B') %>

Then assign the value you get from the link in the controller:

# y_controller.rb

def y
  @value = params[:value]
end

Finally, show the value using @value in your view:

# y.html.erb

<%= @value %>


问:
Snapshot for different SQL Server Version
Can I create a snapshot from SQL Server 2012 on a SQL Server 2008 R2 Server?
The goal is to build reporting and queries without locking the live database.
I need only a DB copy (Getdate()-1)</p>

答:
No, the SQL Server 2012 snapshot has specific SQL Server 2012 features in it that are not compatible with SQL Server 2008 R2. These are incompatibilities that you will not see. They are deep in the SQL Server engine. You cannot do this.

It's a similar concept to trying to restore a SQL Server 2012 database backup to a SQL Server 2008 R2 instance. The higher database version cannot backstep to a lower version.

You need to use a SQL Server of the same level or higher (I believe or higher) for your snapshot server.


问:
unable to solve rspec issue for a remote file resource
I tried to write rspec for one of my remote_file resource. But I am unsuccessful to make it.

My concept is using remote_file it should download a remote file which is a zip file. What happen is rspec is expecting more after It downloaded remotely.

This is my resource declaration:

```<code>remote_file zip_file_location do
  source http://google.com
  mode '0754'
  action :create
end
</code>```

This is my rspec test:

```<code>it 'creates a remote_file ' do
    expect(chef_run).to create_remote_file(::File.join(Chef::Config[:file_cache_path], 'sonarqube-5.6.6.zip'))
end
</code>```

答:
This is your resource

```<code>remote_file 'sonarqube-5.6.6.zip' do
 source 'http://google.com/'
 action :create
 mode 00755
end
</code>```

and this is rspec for your resource

```<code>it 'creates a remote_file ' do
  expect(chef_run).to create_remote_file('sonarqube-5.6.6.zip').with(
      source: "http://google.com",
      mode: 00755
  )
end
</code>```

If you want to have configuration value from attributes/default.rb for location of your saved file you must mock this in your rspec file:

```<code>describe 'lecturio_ds::webfrontend' do
  context 'When all attributes are default, on an unspecified platform'  do
  let(:chef_run) do
    ChefSpec::SoloRunner.new do |node|
      node.set['file_cache_path'] = '/tmp'
    end.converge(described_recipe)
  end
# place for your spec
end
</code>```

and after that you can verify it create_remote_file('/tmp/sonarqube-5.6.6.zip').

I don't understand why you use in your rspec file File.join there.

Body:
I tried to write rspec for one of my remote_file resource. But I am unsuccessful to make it.

My concept is using remote_file it should download a remote file which is a zip file. What happen is rspec is expecting more after It downloaded remotely.

This is my resource declaration:

remote_file zip_file_location do
  source http://google.com
  mode '0754'
  action :create
end

This is my rspec test:

it 'creates a remote_file ' do
    expect(chef_run).to create_remote_file(::File.join(Chef::Config[:file_cache_path], 'sonarqube-5.6.6.zip'))
end

Body:
This is your resource

remote_file 'sonarqube-5.6.6.zip' do
 source 'http://google.com/'
 action :create
 mode 00755
end

and this is rspec for your resource

it 'creates a remote_file ' do
  expect(chef_run).to create_remote_file('sonarqube-5.6.6.zip').with(
      source: "http://google.com",
      mode: 00755
  )
end

If you want to have configuration value from attributes/default.rb for location of your saved file you must mock this in your rspec file:

describe 'lecturio_ds::webfrontend' do
  context 'When all attributes are default, on an unspecified platform'  do
  let(:chef_run) do
    ChefSpec::SoloRunner.new do |node|
      node.set['file_cache_path'] = '/tmp'
    end.converge(described_recipe)
  end
# place for your spec
end

and after that you can verify it create_remote_file('/tmp/sonarqube-5.6.6.zip').

I don't understand why you use in your rspec file File.join there.


问:
Using column value as array index in doctrine
I am using doctrine 2.1 in order to create a model for settings table:

```<code>id |  arg  |  value  |  category
1  |  name |  foo    |  general_settings
2  |  desc |  bar    |  general_settings
</code>```

Suppose that I have a lot of setting for different categories. In order to get all the setting  for a specific category I do something like this:

```<code>$q = Doctrine_Query::create()
    ->from('Setting p')
    ->where('p.category = ?', $category_name);
</code>```

Everything works fine at this point. Well.. the question of $64,000 is:
Do exist a data access alternative that allow me to read the result as below?

```<code>$resultSet = $q->execute();

//the magic here could be use the -arg- column as index
$requested_setting = $resulSet['name']

//print the setting value
echo $requested_setting['value'];  //should prints "foo"

//another way
echo $resulSet['desc']['value']; //should prints "bar"
</code>```

答:
FYI when using createQueryBuilder in your EntityRepository, you can directly specify the INDEX BY along with the alias:

```<code>$this->createQueryBuilder('p', 'p.id')
</code>```

This avoids handling manually the from which is automatically handled in EntityRepositories.

Body:
I am using doctrine 2.1 in order to create a model for settings table:

id |  arg  |  value  |  category
1  |  name |  foo    |  general_settings
2  |  desc |  bar    |  general_settings

Suppose that I have a lot of setting for different categories. In order to get all the setting  for a specific category I do something like this:

$q = Doctrine_Query::create()
    ->from('Setting p')
    ->where('p.category = ?', $category_name);

Everything works fine at this point. Well.. the question of $64,000 is:
Do exist a data access alternative that allow me to read the result as below?

$resultSet = $q->execute();

//the magic here could be use the -arg- column as index
$requested_setting = $resulSet['name']

//print the setting value
echo $requested_setting['value'];  //should prints "foo"

//another way
echo $resulSet['desc']['value']; //should prints "bar"

Body:
FYI when using createQueryBuilder in your EntityRepository, you can directly specify the INDEX BY along with the alias:

$this->createQueryBuilder('p', 'p.id')

This avoids handling manually the from which is automatically handled in EntityRepositories.


问:
My C program won't converted int to char into mqtt broker message by execvp
Somehow my conversion from int to char is not accepted by execvp. It won't write any text in my bash. But if i state -> Data = "134"; it works. Seems like the conversion is an issue and that the function acknowledge this.

How do I solve the issue? in the end I want to send my digital values where str is.

```<code>int set1 = 134;
int set2 = 2;
int set3 = 3;

char *Data;
Data = (char) set1;

char *str[80];
strcpy(str, "some,");
strcat(str, "text,");
strcat(str, Data);

char *name[] = {
    "mosquitto_pub",
    "-d",
    "-t",
    "SomeName",
    "-m",
    str,
    NULL
};
execvp(name[0], name);
</code>```

答:
```<code>int set1 = 134;
int set2 = 2;
int set3 = 3;

char con[80];
char *Data;
sprintf(con, "%d", set1); /*Thanks to hardillb*/
Data = con;

char *str[80];
strcpy(str, "some,");
strcat(str, "text,");
strcat(str, Data);

char *name[] = {
    "mosquitto_pub",
    "-d",
    "-t",
    "SomeName",
    "-m",
    str,
    NULL
};
execvp(name[0], name);
</code>```

Body:
Somehow my conversion from int to char is not accepted by execvp. It won't write any text in my bash. But if i state -> Data = "134"; it works. Seems like the conversion is an issue and that the function acknowledge this.

How do I solve the issue? in the end I want to send my digital values where str is.

int set1 = 134;
int set2 = 2;
int set3 = 3;

char *Data;
Data = (char) set1;

char *str[80];
strcpy(str, "some,");
strcat(str, "text,");
strcat(str, Data);

char *name[] = {
    "mosquitto_pub",
    "-d",
    "-t",
    "SomeName",
    "-m",
    str,
    NULL
};
execvp(name[0], name);


问:
Extracting information from a a java core dump with jmap(1.5)
Long story short, some coworkers are running a pretty old setup(oc4j jdk1.5.6 in x86_64) with an application which happens to be mission critical. They recently have tried to deploy a new version of the application, but as soon as they do the java process(es) throw a core dump and die.

The problem is, the core dumps seem to be fine, gdb can open them, but jmap and other tools refuse to process them:

```<code># /usr/java/jdk1.5.0_06/bin/jmap /usr/java/jdk1.5.0_06/bin/java core
Attaching to core core from executable /usr/java/jdk1.5.0_06/bin/java, please wait...
Error attaching to core file: Can't attach to the core file
</code>```

And newer versions throw a exception:

```<code># jdk1.6.0_45/bin/jmap /usr/java/jdk1.5.0_06/bin/java core
Attaching to core core from executable /usr/java/jdk1.5.0_06/bin/java, please wait...
Exception in thread "main" java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at sun.tools.jmap.JMap.runTool(JMap.java:179)
        at sun.tools.jmap.JMap.main(JMap.java:110)
Caused by: sun.jvm.hotspot.runtime.VMVersionMismatchException: Supported versions are 20.45-b01. Target VM is 1.5.0_06-b05
        at sun.jvm.hotspot.runtime.VM.checkVMVersion(VM.java:224)
        at sun.jvm.hotspot.runtime.VM.<init>(VM.java:287)
        at sun.jvm.hotspot.runtime.VM.initialize(VM.java:357)
        at sun.jvm.hotspot.bugspot.BugSpotAgent.setupVM(BugSpotAgent.java:594)
        at sun.jvm.hotspot.bugspot.BugSpotAgent.go(BugSpotAgent.java:494)
        at sun.jvm.hotspot.bugspot.BugSpotAgent.attach(BugSpotAgent.java:348)
        at sun.jvm.hotspot.tools.Tool.start(Tool.java:169)
        at sun.jvm.hotspot.tools.PMap.main(PMap.java:67)
        ... 6 more
</code>```

gdb offers little information without symbols:

```<code>Reading symbols from /usr/java/jdk1.5.0_06/bin/java...(no debugging symbols found)...done.

[New Thread 9841]
[New Thread 31442]
[New Thread 31441]
...
Core was generated by `/usr/java/jdk1.5.0_06/bin/java -server -XX:+UseConcMarkSweepGC -XX:MaxHeapFreeR'.
Program terminated with signal 6, Aborted.
#0  0x0000003bbf030285 in ?? ()
(gdb) bt
#0  0x0000003bbf030285 in ?? ()
#1  0x0000003bbf031d30 in ?? ()
#2  0x0000000000000000 in ?? ()
</code>```

The only valuable information I've gathered from the core is that most threads
are blocked(I'm far from being a gdb guru):

```<code>  35 Thread 10093  0x0000003bbfc0b1c0 in pthread_cond_timedwait@@GLIBC_2.3.2 ()
   from /lib64/libpthread.so.0
  34 Thread 10097  0x0000003bbfc0b1c0 in pthread_cond_timedwait@@GLIBC_2.3.2 ()
   from /lib64/libpthread.so.0
  33 Thread 10099  0x0000003bbfc0b1c0 in pthread_cond_timedwait@@GLIBC_2.3.2 ()
   from /lib64/libpthread.so.0
</code>```

Besides, I don't know if it's really relevant. The app is almost always heavily loaded, and my bet is that there were some lock contention already but since it's another's team app my knowledge about it it's pretty shallow.

I guess this is a long shot, but is there something that we can do to get a java thread dump or something like that? Do Sun used to offer debuginfo of the jdk as I guess is avalaible now with openjdk?

Thanks in advance.

UPDATE: The other team has resolved the issue without getting info from the core dump, just by trial and error after successfully replicating the problem in a test system. I'm still intrigued about the thing: how to debug an ancient java core dump which jmap can't process, it might be valuable info for the future, althought it seems is that there is no solution to that problem. Probably the JVM memory got corrupted and that's why jmap can't process it.

答: jmap is not going to help you debug a core dump. The JVM dumps core when either it has a bug or you have JNI code with a problem. Organizations with mission-critical applications should, sadly, see upgrading from unsupported versions of the JVM as mission-critical, or be prepared to pay Oracle a fortune for help.</p>

Body:
Long story short, some coworkers are running a pretty old setup(oc4j jdk1.5.6 in x86_64) with an application which happens to be mission critical. They recently have tried to deploy a new version of the application, but as soon as they do the java process(es) throw a core dump and die.

The problem is, the core dumps seem to be fine, gdb can open them, but jmap and other tools refuse to process them:

# /usr/java/jdk1.5.0_06/bin/jmap /usr/java/jdk1.5.0_06/bin/java core
Attaching to core core from executable /usr/java/jdk1.5.0_06/bin/java, please wait...
Error attaching to core file: Can't attach to the core file

And newer versions throw a exception:

# jdk1.6.0_45/bin/jmap /usr/java/jdk1.5.0_06/bin/java core
Attaching to core core from executable /usr/java/jdk1.5.0_06/bin/java, please wait...
Exception in thread "main" java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at sun.tools.jmap.JMap.runTool(JMap.java:179)
        at sun.tools.jmap.JMap.main(JMap.java:110)
Caused by: sun.jvm.hotspot.runtime.VMVersionMismatchException: Supported versions are 20.45-b01. Target VM is 1.5.0_06-b05
        at sun.jvm.hotspot.runtime.VM.checkVMVersion(VM.java:224)
        at sun.jvm.hotspot.runtime.VM.<init>(VM.java:287)
        at sun.jvm.hotspot.runtime.VM.initialize(VM.java:357)
        at sun.jvm.hotspot.bugspot.BugSpotAgent.setupVM(BugSpotAgent.java:594)
        at sun.jvm.hotspot.bugspot.BugSpotAgent.go(BugSpotAgent.java:494)
        at sun.jvm.hotspot.bugspot.BugSpotAgent.attach(BugSpotAgent.java:348)
        at sun.jvm.hotspot.tools.Tool.start(Tool.java:169)
        at sun.jvm.hotspot.tools.PMap.main(PMap.java:67)
        ... 6 more

gdb offers little information without symbols:

Reading symbols from /usr/java/jdk1.5.0_06/bin/java...(no debugging symbols found)...done.

[New Thread 9841]
[New Thread 31442]
[New Thread 31441]
...
Core was generated by `/usr/java/jdk1.5.0_06/bin/java -server -XX:+UseConcMarkSweepGC -XX:MaxHeapFreeR'.
Program terminated with signal 6, Aborted.
#0  0x0000003bbf030285 in ?? ()
(gdb) bt
#0  0x0000003bbf030285 in ?? ()
#1  0x0000003bbf031d30 in ?? ()
#2  0x0000000000000000 in ?? ()

The only valuable information I've gathered from the core is that most threads
are blocked(I'm far from being a gdb guru):

  35 Thread 10093  0x0000003bbfc0b1c0 in pthread_cond_timedwait@@GLIBC_2.3.2 ()
   from /lib64/libpthread.so.0
  34 Thread 10097  0x0000003bbfc0b1c0 in pthread_cond_timedwait@@GLIBC_2.3.2 ()
   from /lib64/libpthread.so.0
  33 Thread 10099  0x0000003bbfc0b1c0 in pthread_cond_timedwait@@GLIBC_2.3.2 ()
   from /lib64/libpthread.so.0

Besides, I don't know if it's really relevant. The app is almost always heavily loaded, and my bet is that there were some lock contention already but since it's another's team app my knowledge about it it's pretty shallow.

I guess this is a long shot, but is there something that we can do to get a java thread dump or something like that? Do Sun used to offer debuginfo of the jdk as I guess is avalaible now with openjdk?

Thanks in advance.

UPDATE: The other team has resolved the issue without getting info from the core dump, just by trial and error after successfully replicating the problem in a test system. I'm still intrigued about the thing: how to debug an ancient java core dump which jmap can't process, it might be valuable info for the future, althought it seems is that there is no solution to that problem. Probably the JVM memory got corrupted and that's why jmap can't process it.


问:
Prolog: How to create all possible permutations with repetition give a list of objects
First of all, excuse me for being a noob at Prolog.
All I want to achieve is to
Create a predicate that
 - for objects [0,1]
 - Given a desired Length (for example 3)
 - Finds all possible permutations (with repetition) of given Length (0 can be added multiple times, 1 can be added multiple times, no problem if I have a list of same objects for example...)

Example:

```<code>? myPermutation(3, [0,1], L).
L = [0,0,0]
next->
L = [0,0,1]
next->
L = [0,1,0]
next->
L = [0,1,1]
....
next->
L = [1,1,1]
</code>```

Can someone please help me with that?
Thanks a lot...

Hint: I am thinking something using the delete predicate... Something like giving the List of Objects and question Prolog for all the possible ways to delete an object from [0,1].

答:
I think your approach is a bit complicated. You could simply write something like:

```<code>eval([],_).
eval([H|T],Set):-member(H,Set),eval(T,Set).

myPermutation(N, Set, L):-length(L,N), eval(L,Set).
</code>```

The above solution uses the length/2 predicate to set the length of the output list and calls eval/2 predicate which just iterates recursively the lists and forces each element of the list to be member of the given Set.
Example:

```<code>?- myPermutation(3, [0,1], L).
L = [0, 0, 0] ;
L = [0, 0, 1] ;
L = [0, 1, 0] ;
L = [0, 1, 1] ;
L = [1, 0, 0] ;
L = [1, 0, 1] ;
L = [1, 1, 0] ;
L = [1, 1, 1].
</code>```

Also you can make more general queries like:

```<code>?- myPermutation(3, S, [0,0,1]).
S = [0, 1|_G3426] ;
S = [0, _G3425, 1|_G3429] ;
S = [0, _G3425, _G3428, 1|_G3432] ;
S = [0, _G3425, _G3428, _G3431, 1|_G3435] ;
S = [0, _G3425, _G3428, _G3431, _G3434, 1|_G3438] .
(and goes on...)
</code>```

Body:
First of all, excuse me for being a noob at Prolog.
All I want to achieve is to
Create a predicate that
 - for objects [0,1]
 - Given a desired Length (for example 3)
 - Finds all possible permutations (with repetition) of given Length (0 can be added multiple times, 1 can be added multiple times, no problem if I have a list of same objects for example...)

Example:

? myPermutation(3, [0,1], L).
L = [0,0,0]
next->
L = [0,0,1]
next->
L = [0,1,0]
next->
L = [0,1,1]
....
next->
L = [1,1,1]

Can someone please help me with that?
Thanks a lot...

Hint: I am thinking something using the delete predicate... Something like giving the List of Objects and question Prolog for all the possible ways to delete an object from [0,1].

Body:
I think your approach is a bit complicated. You could simply write something like:

eval([],_).
eval([H|T],Set):-member(H,Set),eval(T,Set).

myPermutation(N, Set, L):-length(L,N), eval(L,Set).

The above solution uses the length/2 predicate to set the length of the output list and calls eval/2 predicate which just iterates recursively the lists and forces each element of the list to be member of the given Set.
Example:

?- myPermutation(3, [0,1], L).
L = [0, 0, 0] ;
L = [0, 0, 1] ;
L = [0, 1, 0] ;
L = [0, 1, 1] ;
L = [1, 0, 0] ;
L = [1, 0, 1] ;
L = [1, 1, 0] ;
L = [1, 1, 1].

Also you can make more general queries like:

?- myPermutation(3, S, [0,0,1]).
S = [0, 1|_G3426] ;
S = [0, _G3425, 1|_G3429] ;
S = [0, _G3425, _G3428, 1|_G3432] ;
S = [0, _G3425, _G3428, _G3431, 1|_G3435] ;
S = [0, _G3425, _G3428, _G3431, _G3434, 1|_G3438] .
(and goes on...)


问:
Solr Cloud 6.4.0 Document routing compositeID does not route to another shard
I am completely confused about what is going on in my SolrCloud setup. That said, you see I am new to the topic.

My current setup for testing is:
I have created a SolrCloud on a single server (I do not have more for testing in the moment). I use the embedded Zookeeper.
I have three shards on three nodes with two replica in each one. Every node has a different IP (8984,7574,7575).

I set up a collection with

```<code>curl 'http://localhost:8984/solr/admin/collections?action=CREATE&name=mycollection&numShards=3&replicationFactor=2&collection.configName=myconfigset&router.name=compositeId'
</code>```

When I index some Documents with

```<code>curl 'http://localhost:8984/solr/mycollection/update/csv?update.chain=all-into-one&commit=true&separator=%09&encapsulator=%00&header=true&trim=true&f.itau_name3.split=true&f.itau_name3.separator=;&f.itau_lnx3.split=true&f.itau_lnx3.separator=;&f.itau_af3.split=true&f.itau_af3.separator=;&f.itau_init3.split=true&f.itau_init3.separator=;' --data-binary @file.txt -H 'Content-type:text/plain; charset=utf-8'
</code>```

the routing works ... sometimes. It seems to depend on the prefix/compositeID I use:

When I use r1!<uniquekey>, r2!<uniquekey>, r3!<uniquekey> a query : with _route_=r1! returns documents with r1 and r2 prefix. _route_=r3! seems to be correctly routed. In the very same setup (after clearing the index and reindexing) the same with year1!, year2!, year3! as prefixes works. A query with q=*:*&_route_=year1! etc. only returns results of the respective route-prefix.

Can somebody help me to find out what's going on here?
Are there any restrictions on what how to construct the route-prefix?

答:
you did not show  your full query, but, I suspect this might be happening:

when you query with route=r1! you are not adding an fq=r_field:r1

route=r1! only tells Solr what shard to query, but this does not exclude other r field values (like r2 and r3) that are ALSO indexed in that same shard, that is why you need to add the fq

Does this make sense?

Body:
I am completely confused about what is going on in my SolrCloud setup. That said, you see I am new to the topic.

My current setup for testing is:
I have created a SolrCloud on a single server (I do not have more for testing in the moment). I use the embedded Zookeeper.
I have three shards on three nodes with two replica in each one. Every node has a different IP (8984,7574,7575).

I set up a collection with

curl 'http://localhost:8984/solr/admin/collections?action=CREATE&name=mycollection&numShards=3&replicationFactor=2&collection.configName=myconfigset&router.name=compositeId'

When I index some Documents with

curl 'http://localhost:8984/solr/mycollection/update/csv?update.chain=all-into-one&commit=true&separator=%09&encapsulator=%00&header=true&trim=true&f.itau_name3.split=true&f.itau_name3.separator=;&f.itau_lnx3.split=true&f.itau_lnx3.separator=;&f.itau_af3.split=true&f.itau_af3.separator=;&f.itau_init3.split=true&f.itau_init3.separator=;' --data-binary @file.txt -H 'Content-type:text/plain; charset=utf-8'

the routing works ... sometimes. It seems to depend on the prefix/compositeID I use:

When I use r1!<uniquekey>, r2!<uniquekey>, r3!<uniquekey> a query : with _route_=r1! returns documents with r1 and r2 prefix. _route_=r3! seems to be correctly routed. In the very same setup (after clearing the index and reindexing) the same with year1!, year2!, year3! as prefixes works. A query with q=*:*&_route_=year1! etc. only returns results of the respective route-prefix.

Can somebody help me to find out what's going on here?
Are there any restrictions on what how to construct the route-prefix?


问:
How do I dynamically access a property inside an angularjs directive?
I have a directive when given an array it creates check boxes for that list of items using the Name as the label for the checkbox.

Html

```<code><div>
<a style="float:right; margin-bottom: 5px;" ng-click="selectNone()" href="#">Select None</a>
<a style="float:right; margin-bottom: 5px;margin-left: 10px" ng-click="selectAll()" href="#">Select All</a>

<div class="cleared"></div>

<div class="form-input form-list">
    <label ng-repeat="item in valuelist | orderBy:'Name'">
        <input type="checkbox" checklist-model="model" checklist-value="item" /> {{item.Name}}<br />
    </label>
</div>
</code>```

JS

```<code>    'use strict';

growllApp.directive('checkboxlist', [function () {
    return {
        restrict: 'E',
        templateUrl: 'scripts/modules/checkboxlist.template.html',
        controller: 'checkboxlistController',
        scope: {
            model: "=",
            value: "=",
            valuelist: "="
        }
    }
}]);

growllApp.controller('checkboxlistController', ['$scope', '$routeParams', '$location', '$cookieStore', function ($scope, $routeParams, $location, $cookieStore) {
    $scope.selectAll = function () {
        $scope.model = angular.copy($scope.valuelist);
    };

    $scope.selectNone = function () {
        $scope.model = [];
    };
}]);
</code>```

Using the directive

```<code><checkboxlist ng-show="applyToProducts" model="coupon.Products" value="Name" valuelist="productsList"></checkboxlist>
</code>```

All this works fine in most scenarios.  However, I have a scenario where the array I'm passing in has objects in it that do not have the property "Name" but instead have the property "Title".

How do I use the attribute I have in the directive called "value" for the part that determines the label.

So in the directive html instead of saying {{item.Name}} how can I specify {{item.Title}} by passing in that the property name is title in certain cases?

答:
You can change the 'value' attribute of your directive to '@' (it means the value will be sent as a string to your directive. You can read more in this article )

```<code>scope: {
        model: "=",
        value: "@",
        valuelist: "="
    }
</code>```

and to get the object's property, you can do:

```<code>  {{item[value]}}
</code>```

Body:
I have a directive when given an array it creates check boxes for that list of items using the Name as the label for the checkbox.

Html

Select None
Select All

        <input type="checkbox" checklist-model="model" checklist-value="item" /> {{item.Name}}

JS

    'use strict';

growllApp.directive('checkboxlist', [function () {
    return {
        restrict: 'E',
        templateUrl: 'scripts/modules/checkboxlist.template.html',
        controller: 'checkboxlistController',
        scope: {
            model: "=",
            value: "=",
            valuelist: "="
        }
    }
}]);

growllApp.controller('checkboxlistController', ['$scope', '$routeParams', '$location', '$cookieStore', function ($scope, $routeParams, $location, $cookieStore) {
    $scope.selectAll = function () {
        $scope.model = angular.copy($scope.valuelist);
    };

    $scope.selectNone = function () {
        $scope.model = [];
    };
}]);

Using the directive

<checkboxlist ng-show="applyToProducts" model="coupon.Products" value="Name" valuelist="productsList"></checkboxlist>

All this works fine in most scenarios.  However, I have a scenario where the array I'm passing in has objects in it that do not have the property "Name" but instead have the property "Title".

How do I use the attribute I have in the directive called "value" for the part that determines the label.

So in the directive html instead of saying {{item.Name}} how can I specify {{item.Title}} by passing in that the property name is title in certain cases?

Body:
You can change the 'value' attribute of your directive to '@' (it means the value will be sent as a string to your directive. You can read more in this article )

scope: {
        model: "=",
        value: "@",
        valuelist: "="
    }

and to get the object's property, you can do:

  {{item[value]}}


问:
Bukkit event for hunger?
I am trying to make a plugin that removes hunger from Minecraft.  However, I cannot find the event for it!

Is there an event called when a player loses hunger?

Something like PlayerHungerChangeEvent?

答: Yes, there is the FoodLevelChangeEvent</p>

Title: Bukkit event for hunger?

Body: Yes, there is the FoodLevelChangeEvent


问:
Is there a way to open a file in a shared folder using the file id(FILE_ID_DESCRIPTOR) obtained from GetFileInformationByHandle()
Currently, i'm using the following functions to open the file using its id.

```<code>volHandle = CreateFile(pVolName, ...);
fileHandle = OpenFileById(volHandle, &id, ...)
</code>```

The id(FILE_ID_DESCRIPTOR) is obtained from GetFinalPathNameByHandle().

This works for local files but when I tried it on a file in a shared folder(either from windows or unix machine), I get invalid volHandle.

Are there ways to open a file on a shared folder using its id(FILE_ID_DESCRIPTOR)?

答:
From the documentation for OpenFileById, emphasis mine:

In Windows 8 and Windows Server 2012, this function is supported by the following technologies.

Technology    Supported

Server Message Block (SMB) 3.0 protocol - No

In other words, you can't open a file by ID number over the network, only on a local file system.

Body:
Currently, i'm using the following functions to open the file using its id.

volHandle = CreateFile(pVolName, ...);
fileHandle = OpenFileById(volHandle, &id, ...)

The id(FILE_ID_DESCRIPTOR) is obtained from GetFinalPathNameByHandle().

This works for local files but when I tried it on a file in a shared folder(either from windows or unix machine), I get invalid volHandle.

Are there ways to open a file on a shared folder using its id(FILE_ID_DESCRIPTOR)?


问:
How to connect Arduino Micro to Ethernet module ENC28J66 and run EtherCard BackSoon example?
I have arduino micro (oryginal) like this: https://www.arduino.cc/en/Main/ArduinoBoardMicro and clone of ethernet bord with ENC28J66 chipset.

Pin configuration on ethernet board:

CKOUT

/INT

/WOL

SO

SI

SCK

/CS

/RESET

VCC (5V) (it is also possible to use 3.3V after soldering one place)

GND

I have try to run example BackSoon for EtherCard library with few combination of conection but this gave me 'Failed to access Ethernet controller'

Then i set it like this:
Micro | ENC28J60

SCK - SCK

MISO - SO

MOSI - SI

SS - CS

5V - VCC

GND - GND

10 PIN - INT

This config don't generate access error but DHCP failed. DHCP server configuration is good for sure.
Even if i set static IP address there is no respons on this IP from http like in example.

Full code of my try for dhcp:

```<code>#include <EtherCard.h>
#define STATIC 0  // set to 1 to disable DHCP (adjust myip/gwip values below)

#if STATIC
// ethernet interface ip address
static byte myip[] = { 172,16,10,222 };
// gateway ip address
static byte gwip[] = { 172,16,10,1 };
#endif

// ethernet mac address - must be unique on your network
static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 };

byte Ethernet::buffer[500]; // tcp/ip send and receive buffer

const char page[] PROGMEM =
"HTTP/1.0 503 Service Unavailable\r\n"
"Content-Type: text/html\r\n"
"Retry-After: 600\r\n"
"\r\n"
"<html>"
  "<head><title>"
    "Service Temporarily Unavailable"
  "</title></head>"
  "<body>"
    "<h3>This service is currently unavailable</h3>"
    "<p><em>"
      "The main server is currently off-line.<br />"
      "Please try again later."
    "</em></p>"
  "</body>"
"</html>"
;

void setup(){
  Serial.begin(57600);
  while (!Serial) ;
  Serial.println("\n[backSoon]");

  if (ether.begin(sizeof Ethernet::buffer, mymac,10) == 0)
    Serial.println( "Failed to access Ethernet controller");
#if STATIC
  ether.staticSetup(myip, gwip);
#else
  if (!ether.dhcpSetup())
    Serial.println("DHCP failed");
#endif

  ether.printIp("IP:  ", ether.myip);
  ether.printIp("GW:  ", ether.gwip);
  ether.printIp("DNS: ", ether.dnsip);
}

void loop(){
  // wait for an incoming TCP packet, but ignore its contents
  if (ether.packetLoop(ether.packetReceive())) {
    Serial.println("got one!");
    memcpy_P(ether.tcpOffset(), page, sizeof page);
    ether.httpServerReply(sizeof page - 1);
  }
}
</code>```

Serial response:

```<code>[backSoon]
DHCP failed
IP:  0.0.0.0
GW:  0.0.0.0
DNS: 0.0.0.0
</code>```

Can someone help me to propellery connect one to another and run any sample (like BackSoon)?

Is it possibile to use Micro and ENC28J60 together?
Is it possibile to use EtherCard library for them?

答:
Long time is passed from your question, but I hope this can help someone.

Micro - Ethernet

SCK - SCK

MISO - SO

MOSI - SI

PIN 8 - CS (8 is the default value for ethercard, 10 in your code)

5V - VCC

GND - GND

Body:
I have arduino micro (oryginal) like this: https://www.arduino.cc/en/Main/ArduinoBoardMicro and clone of ethernet bord with ENC28J66 chipset.

Pin configuration on ethernet board:

CKOUT

/INT

/WOL

SO

SI

SCK

/CS

/RESET

VCC (5V) (it is also possible to use 3.3V after soldering one place)

GND

I have try to run example BackSoon for EtherCard library with few combination of conection but this gave me 'Failed to access Ethernet controller'

Then i set it like this:
Micro | ENC28J60

SCK - SCK

MISO - SO

MOSI - SI

SS - CS

5V - VCC

GND - GND

10 PIN - INT

This config don't generate access error but DHCP failed. DHCP server configuration is good for sure.
Even if i set static IP address there is no respons on this IP from http like in example.

Full code of my try for dhcp:

#include <EtherCard.h>
#define STATIC 0  // set to 1 to disable DHCP (adjust myip/gwip values below)

#if STATIC
// ethernet interface ip address
static byte myip[] = { 172,16,10,222 };
// gateway ip address
static byte gwip[] = { 172,16,10,1 };
#endif

// ethernet mac address - must be unique on your network
static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 };

byte Ethernet::buffer[500]; // tcp/ip send and receive buffer

const char page[] PROGMEM =
"HTTP/1.0 503 Service Unavailable\r\n"
"Content-Type: text/html\r\n"
"Retry-After: 600\r\n"
"\r\n"
""
  "<title>"
    "Service Temporarily Unavailable"
  "</title>"
  ""
    "
This service is currently unavailable
"
    "
"
      "The main server is currently off-line.
"
      "Please try again later."
    "
"
  ""
""
;

void setup(){
  Serial.begin(57600);
  while (!Serial) ;
  Serial.println("\n[backSoon]");

  if (ether.begin(sizeof Ethernet::buffer, mymac,10) == 0)
    Serial.println( "Failed to access Ethernet controller");
#if STATIC
  ether.staticSetup(myip, gwip);
#else
  if (!ether.dhcpSetup())
    Serial.println("DHCP failed");
#endif

  ether.printIp("IP:  ", ether.myip);
  ether.printIp("GW:  ", ether.gwip);
  ether.printIp("DNS: ", ether.dnsip);
}

void loop(){
  // wait for an incoming TCP packet, but ignore its contents
  if (ether.packetLoop(ether.packetReceive())) {
    Serial.println("got one!");
    memcpy_P(ether.tcpOffset(), page, sizeof page);
    ether.httpServerReply(sizeof page - 1);
  }
}

Serial response:

[backSoon]
DHCP failed
IP:  0.0.0.0
GW:  0.0.0.0
DNS: 0.0.0.0

Can someone help me to propellery connect one to another and run any sample (like BackSoon)?

Is it possibile to use Micro and ENC28J60 together?
Is it possibile to use EtherCard library for them?