问:
Logging to file in Scala/akka: ClassNotFoundException: akka.event.slf4j.Slf4jLoggingFilter
I have searched quite a bit but could not find a working solution. Could someone please help me?

```<code>akka {
     event-handlers = ["akka.event.slf4j.Slf4jEventHandler"]
     loggers = ["akka.event.slf4j.Slf4jLogger"]
     loglevel = "DEBUG"
     logging-filter = "akka.event.slf4j.Slf4jLoggingFilter"
     stdout-loglevel = "WARNING"
     actor {
       debug {
         receive = on
         lifecycle = off
       }
     }
}
</code>```

and I have added the following to build.sbt in the hope that one of them solves the issue:

```<code>libraryDependencies ++= Seq (
  "com.typesafe.akka" %% "akka-actor" % "2.4.1",   // akka actors
  "ch.qos.logback" % "logback-classic" % "1.1.3",  //logback, in order to log to file
  "com.typesafe.scala-logging" % "scala-logging-slf4j_2.11" % "2.1.2",
  "com.typesafe.akka" % "akka-slf4j_2.11" % "2.4.1",   // needed for logback to work
  // and my other dependencies
)
</code>```

and I have tried with different suggestions I found for logback.xml, the last of which is:

```<code><configuration>
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>logs/filename.log</file>
        <encoder>
            <pattern>%date %level %msg%n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
            <maxIndex>10</maxIndex>
            <FileNamePattern>logs/filename.log.%i.gz</FileNamePattern>
        </rollingPolicy>
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <maxFileSize>20MB</maxFileSize>
        </triggeringPolicy>
    </appender>
    <root level="info">
        <appender-ref ref="FILE" />
    </root>
</configuration>
</code>```

EDIT: My complete dependencies are as follows (ps: I currently have both lift and salat for de/serialization, but that's a different story):

```<code>libraryDependencies ++= Seq (
  "org.scala-lang" % "scalap" % scalaVersion.value,
  "com.typesafe.akka" %% "akka-actor" % "2.4.1",
  "ch.qos.logback" % "logback-classic" % "1.1.3",
  "com.typesafe.scala-logging" % "scala-logging-slf4j_2.11" % "2.1.2",
  "com.typesafe.akka" %% "akka-slf4j" % "2.4.1",
  "com.github.sstone" %% "amqp-client" % "1.5",
  "net.liftweb" %% "lift-json" % "2.6.2",
  "net.liftweb" %% "lift-json-ext" % "2.6.2",
  "org.scalatest" %% "scalatest" % "2.2.4" % "test",
  "com.novus" %% "salat" % "1.9.9"
)
</code>```

答:
The best way to solve these kind of problems is always see the dependency tree and figure out whats going on there, (its very important be it maven or sbt)

See how many slf4j dependencies you have. (I can see conflicting dependencies slf4j-api:1.6.0, slf4j-api:1.7.2, slf4j-api:1.7.12)

```<code>sbt dependencyTree

[info]   +-com.novus:salat_2.11:1.9.9 [S]
[info]   | +-com.novus:salat-core_2.11:1.9.9 [S]
[info]   | | +-com.novus:salat-util_2.11:1.9.9 [S]
[info]   | | | +-org.scala-lang:scalap:2.11.5
[info]   | | | | +-org.scala-lang:scala-compiler:2.11.5 [S]
[info]   | | | |   +-org.scala-lang.modules:scala-parser-combinators_2.11:1.0.1 (evicted by: 1.0.3)
[info]   | | | |   +-org.scala-lang.modules:scala-parser-combinators_2.11:1.0.3 [S]
[info]   | | | |   +-org.scala-lang.modules:scala-xml_2.11:1.0.1 (evicted by: 1.0.3)
[info]   | | | |   +-org.scala-lang.modules:scala-xml_2.11:1.0.3 [S]
[info]   | | | |   +-org.scala-lang:scala-reflect:2.11.5 [S]
[info]   | | | |
[info]   | | | +-org.slf4j:slf4j-api:1.6.0 (evicted by: 1.7.12)
[info]   | | | +-org.slf4j:slf4j-api:1.7.12
[info]   | | | +-org.slf4j:slf4j-api:1.7.2 (evicted by: 1.7.12)

[info]   +-ch.qos.logback:logback-classic:1.1.3
[info]   | +-ch.qos.logback:logback-core:1.1.3
[info]   | +-org.slf4j:slf4j-api:1.7.12
[info]   | +-org.slf4j:slf4j-api:1.7.7 (evicted by: 1.7.12)

[info]   | | +-org.mongodb:casbah-core_2.11:2.7.1 [S]
[info]   | |   +-com.github.nscala-time:nscala-time_2.11:1.0.0 [S]
[info]   | |   | +-joda-time:joda-time:2.3
[info]   | |   | +-org.joda:joda-convert:1.2
[info]   | |   |
[info]   | |   +-org.mongodb:casbah-commons_2.11:2.7.1 [S]
[info]   | |   | +-com.github.nscala-time:nscala-time_2.11:1.0.0 [S]
[info]   | |   | | +-joda-time:joda-time:2.3
[info]   | |   | | +-org.joda:joda-convert:1.2
[info]   | |   | |
[info]   | |   | +-org.mongodb:mongo-java-driver:2.12.1
[info]   | |   | +-org.slf4j:slf4j-api:1.6.0 (evicted by: 1.7.12)
[info]   | |   | +-org.slf4j:slf4j-api:1.7.12
[info]   | |   |
[info]   | |   +-org.mongodb:casbah-query_2.11:2.7.1 [S]
[info]   | |   | +-com.github.nscala-time:nscala-time_2.11:1.0.0 [S]
[info]   | |   | | +-joda-time:joda-time:2.3
[info]   | |   | | +-org.joda:joda-convert:1.2
[info]   | |   | |
[info]   | |   | +-org.mongodb:casbah-commons_2.11:2.7.1 [S]
[info]   | |   | | +-com.github.nscala-time:nscala-time_2.11:1.0.0 [S]
[info]   | |   | | | +-joda-time:joda-time:2.3
[info]   | |   | | | +-org.joda:joda-convert:1.2
[info]   | |   | | |
[info]   | |   | | +-org.mongodb:mongo-java-driver:2.12.1
[info]   | |   | | +-org.slf4j:slf4j-api:1.6.0 (evicted by: 1.7.12)
[info]   | |   | | +-org.slf4j:slf4j-api:1.7.12
[info]   | |   | |
[info]   | |   | +-org.slf4j:slf4j-api:1.6.0 (evicted by: 1.7.12)
[info]   | |   | +-org.slf4j:slf4j-api:1.7.12
[info]   | |   |
[info]   | |   +-org.slf4j:slf4j-api:1.6.0 (evicted by: 1.7.12)
[info]   | |   +-org.slf4j:slf4j-api:1.7.12

[info]   | +-com.novus:salat-util_2.11:1.9.9 [S]
[info]   |   +-org.scala-lang:scalap:2.11.5
[info]   |   | +-org.scala-lang:scala-compiler:2.11.5 [S]
[info]   |   |   +-org.scala-lang.modules:scala-parser-combinators_2.11:1.0.1 (evicted by: 1.0.3)
[info]   |   |   +-org.scala-lang.modules:scala-parser-combinators_2.11:1.0.3 [S]
[info]   |   |   +-org.scala-lang.modules:scala-xml_2.11:1.0.1 (evicted by: 1.0.3)
[info]   |   |   +-org.scala-lang.modules:scala-xml_2.11:1.0.3 [S]
[info]   |   |   +-org.scala-lang:scala-reflect:2.11.5 [S]
[info]   |   |
[info]   |   +-org.slf4j:slf4j-api:1.6.0 (evicted by: 1.7.12)
[info]   |   +-org.slf4j:slf4j-api:1.7.12
[info]   |   +-org.slf4j:slf4j-api:1.7.2 (evicted by: 1.7.12)

[info]   +-com.typesafe.scala-logging:scala-logging-slf4j_2.11:2.1.2 [S]
[info]   | +-com.typesafe.scala-logging:scala-logging-api_2.11:2.1.2 [S]
[info]   | +-org.scala-lang:scala-reflect:2.11.5 [S]
[info]   | +-org.slf4j:slf4j-api:1.7.12
[info]   | +-org.slf4j:slf4j-api:1.7.7 (evicted by: 1.7.12)

[info]   +-net.liftweb:lift-json-ext_2.11:2.6.2 [S]
[info]   | +-commons-codec:commons-codec:1.6
[info]   | +-joda-time:joda-time:2.1 (evicted by: 2.3)
[info]   | +-joda-time:joda-time:2.3
[info]   | +-net.liftweb:lift-common_2.11:2.6.2 [S]
[info]   | | +-org.scala-lang.modules:scala-parser-combinators_2.11:1.0.1 (evicted by: 1.0.3)
[info]   | | +-org.scala-lang.modules:scala-parser-combinators_2.11:1.0.3 [S]
[info]   | | +-org.scala-lang.modules:scala-xml_2.11:1.0.1 (evicted by: 1.0.3)
[info]   | | +-org.scala-lang.modules:scala-xml_2.11:1.0.3 [S]
[info]   | | +-org.slf4j:slf4j-api:1.6.0 (evicted by: 1.7.12)
[info]   | | +-org.slf4j:slf4j-api:1.7.12
[info]   | | +-org.slf4j:slf4j-api:1.7.2 (evicted by: 1.7.12)
</code>```

And to know what version is used,

```<code>$ sbt dependencyList
[info] org.slf4j:slf4j-api:1.7.12
</code>```

That way you can control which version you want and which you want to exclude,

eg. to exclude the slf4j-api version that salat uses

```<code>"com.novus" %% "salat" % "1.9.9" exclude("org.slf4j","slf4j-api")
</code>```

Note

add addSbtPlugin("net.virtual-void" % "sbt-dependency-graph" % "0.8.2") to project/plugins.sbt to use sbt dependencyTree.

https://github.com/jrudolph/sbt-dependency-graph#usage-instructions

Body:
I have searched quite a bit but could not find a working solution. Could someone please help me?

akka {
     event-handlers = ["akka.event.slf4j.Slf4jEventHandler"]
     loggers = ["akka.event.slf4j.Slf4jLogger"]
     loglevel = "DEBUG"
     logging-filter = "akka.event.slf4j.Slf4jLoggingFilter"
     stdout-loglevel = "WARNING"
     actor {
       debug {
         receive = on
         lifecycle = off
       }
     }
}

and I have added the following to build.sbt in the hope that one of them solves the issue:

libraryDependencies ++= Seq (
  "com.typesafe.akka" %% "akka-actor" % "2.4.1",   // akka actors
  "ch.qos.logback" % "logback-classic" % "1.1.3",  //logback, in order to log to file
  "com.typesafe.scala-logging" % "scala-logging-slf4j_2.11" % "2.1.2",
  "com.typesafe.akka" % "akka-slf4j_2.11" % "2.4.1",   // needed for logback to work
  // and my other dependencies
)

and I have tried with different suggestions I found for logback.xml, the last of which is:

<configuration>
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>logs/filename.log</file>
        <encoder>
            <pattern>%date %level %msg%n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
            <maxIndex>10</maxIndex>
            <FileNamePattern>logs/filename.log.%i.gz</FileNamePattern>
        </rollingPolicy>
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <maxFileSize>20MB</maxFileSize>
        </triggeringPolicy>
    </appender>
    <root level="info">
        <appender-ref ref="FILE" />
    </root>
</configuration>

EDIT: My complete dependencies are as follows (ps: I currently have both lift and salat for de/serialization, but that's a different story):

libraryDependencies ++= Seq (
  "org.scala-lang" % "scalap" % scalaVersion.value,
  "com.typesafe.akka" %% "akka-actor" % "2.4.1",
  "ch.qos.logback" % "logback-classic" % "1.1.3",
  "com.typesafe.scala-logging" % "scala-logging-slf4j_2.11" % "2.1.2",
  "com.typesafe.akka" %% "akka-slf4j" % "2.4.1",
  "com.github.sstone" %% "amqp-client" % "1.5",
  "net.liftweb" %% "lift-json" % "2.6.2",
  "net.liftweb" %% "lift-json-ext" % "2.6.2",
  "org.scalatest" %% "scalatest" % "2.2.4" % "test",
  "com.novus" %% "salat" % "1.9.9"
)

Body:
The best way to solve these kind of problems is always see the dependency tree and figure out whats going on there, (its very important be it maven or sbt)

See how many slf4j dependencies you have. (I can see conflicting dependencies slf4j-api:1.6.0, slf4j-api:1.7.2, slf4j-api:1.7.12)

sbt dependencyTree

[info]   +-com.novus:salat_2.11:1.9.9 [S]
[info]   | +-com.novus:salat-core_2.11:1.9.9 [S]
[info]   | | +-com.novus:salat-util_2.11:1.9.9 [S]
[info]   | | | +-org.scala-lang:scalap:2.11.5
[info]   | | | | +-org.scala-lang:scala-compiler:2.11.5 [S]
[info]   | | | |   +-org.scala-lang.modules:scala-parser-combinators_2.11:1.0.1 (evicted by: 1.0.3)
[info]   | | | |   +-org.scala-lang.modules:scala-parser-combinators_2.11:1.0.3 [S]
[info]   | | | |   +-org.scala-lang.modules:scala-xml_2.11:1.0.1 (evicted by: 1.0.3)
[info]   | | | |   +-org.scala-lang.modules:scala-xml_2.11:1.0.3 [S]
[info]   | | | |   +-org.scala-lang:scala-reflect:2.11.5 [S]
[info]   | | | |
[info]   | | | +-org.slf4j:slf4j-api:1.6.0 (evicted by: 1.7.12)
[info]   | | | +-org.slf4j:slf4j-api:1.7.12
[info]   | | | +-org.slf4j:slf4j-api:1.7.2 (evicted by: 1.7.12)

[info]   +-ch.qos.logback:logback-classic:1.1.3
[info]   | +-ch.qos.logback:logback-core:1.1.3
[info]   | +-org.slf4j:slf4j-api:1.7.12
[info]   | +-org.slf4j:slf4j-api:1.7.7 (evicted by: 1.7.12)

[info]   | | +-org.mongodb:casbah-core_2.11:2.7.1 [S]
[info]   | |   +-com.github.nscala-time:nscala-time_2.11:1.0.0 [S]
[info]   | |   | +-joda-time:joda-time:2.3
[info]   | |   | +-org.joda:joda-convert:1.2
[info]   | |   |
[info]   | |   +-org.mongodb:casbah-commons_2.11:2.7.1 [S]
[info]   | |   | +-com.github.nscala-time:nscala-time_2.11:1.0.0 [S]
[info]   | |   | | +-joda-time:joda-time:2.3
[info]   | |   | | +-org.joda:joda-convert:1.2
[info]   | |   | |
[info]   | |   | +-org.mongodb:mongo-java-driver:2.12.1
[info]   | |   | +-org.slf4j:slf4j-api:1.6.0 (evicted by: 1.7.12)
[info]   | |   | +-org.slf4j:slf4j-api:1.7.12
[info]   | |   |
[info]   | |   +-org.mongodb:casbah-query_2.11:2.7.1 [S]
[info]   | |   | +-com.github.nscala-time:nscala-time_2.11:1.0.0 [S]
[info]   | |   | | +-joda-time:joda-time:2.3
[info]   | |   | | +-org.joda:joda-convert:1.2
[info]   | |   | |
[info]   | |   | +-org.mongodb:casbah-commons_2.11:2.7.1 [S]
[info]   | |   | | +-com.github.nscala-time:nscala-time_2.11:1.0.0 [S]
[info]   | |   | | | +-joda-time:joda-time:2.3
[info]   | |   | | | +-org.joda:joda-convert:1.2
[info]   | |   | | |
[info]   | |   | | +-org.mongodb:mongo-java-driver:2.12.1
[info]   | |   | | +-org.slf4j:slf4j-api:1.6.0 (evicted by: 1.7.12)
[info]   | |   | | +-org.slf4j:slf4j-api:1.7.12
[info]   | |   | |
[info]   | |   | +-org.slf4j:slf4j-api:1.6.0 (evicted by: 1.7.12)
[info]   | |   | +-org.slf4j:slf4j-api:1.7.12
[info]   | |   |
[info]   | |   +-org.slf4j:slf4j-api:1.6.0 (evicted by: 1.7.12)
[info]   | |   +-org.slf4j:slf4j-api:1.7.12

[info]   | +-com.novus:salat-util_2.11:1.9.9 [S]
[info]   |   +-org.scala-lang:scalap:2.11.5
[info]   |   | +-org.scala-lang:scala-compiler:2.11.5 [S]
[info]   |   |   +-org.scala-lang.modules:scala-parser-combinators_2.11:1.0.1 (evicted by: 1.0.3)
[info]   |   |   +-org.scala-lang.modules:scala-parser-combinators_2.11:1.0.3 [S]
[info]   |   |   +-org.scala-lang.modules:scala-xml_2.11:1.0.1 (evicted by: 1.0.3)
[info]   |   |   +-org.scala-lang.modules:scala-xml_2.11:1.0.3 [S]
[info]   |   |   +-org.scala-lang:scala-reflect:2.11.5 [S]
[info]   |   |
[info]   |   +-org.slf4j:slf4j-api:1.6.0 (evicted by: 1.7.12)
[info]   |   +-org.slf4j:slf4j-api:1.7.12
[info]   |   +-org.slf4j:slf4j-api:1.7.2 (evicted by: 1.7.12)

[info]   +-com.typesafe.scala-logging:scala-logging-slf4j_2.11:2.1.2 [S]
[info]   | +-com.typesafe.scala-logging:scala-logging-api_2.11:2.1.2 [S]
[info]   | +-org.scala-lang:scala-reflect:2.11.5 [S]
[info]   | +-org.slf4j:slf4j-api:1.7.12
[info]   | +-org.slf4j:slf4j-api:1.7.7 (evicted by: 1.7.12)

[info]   +-net.liftweb:lift-json-ext_2.11:2.6.2 [S]
[info]   | +-commons-codec:commons-codec:1.6
[info]   | +-joda-time:joda-time:2.1 (evicted by: 2.3)
[info]   | +-joda-time:joda-time:2.3
[info]   | +-net.liftweb:lift-common_2.11:2.6.2 [S]
[info]   | | +-org.scala-lang.modules:scala-parser-combinators_2.11:1.0.1 (evicted by: 1.0.3)
[info]   | | +-org.scala-lang.modules:scala-parser-combinators_2.11:1.0.3 [S]
[info]   | | +-org.scala-lang.modules:scala-xml_2.11:1.0.1 (evicted by: 1.0.3)
[info]   | | +-org.scala-lang.modules:scala-xml_2.11:1.0.3 [S]
[info]   | | +-org.slf4j:slf4j-api:1.6.0 (evicted by: 1.7.12)
[info]   | | +-org.slf4j:slf4j-api:1.7.12
[info]   | | +-org.slf4j:slf4j-api:1.7.2 (evicted by: 1.7.12)

And to know what version is used,

$ sbt dependencyList
[info] org.slf4j:slf4j-api:1.7.12

That way you can control which version you want and which you want to exclude,

eg. to exclude the slf4j-api version that salat uses

"com.novus" %% "salat" % "1.9.9" exclude("org.slf4j","slf4j-api")

Note

add addSbtPlugin("net.virtual-void" % "sbt-dependency-graph" % "0.8.2") to project/plugins.sbt to use sbt dependencyTree.

https://github.com/jrudolph/sbt-dependency-graph#usage-instructions


来源: stackexchange

问:
Matlab get all possible combinations less than a value
I have a matrix as follows:

```<code>id      value
=============
 1       0.5
 2       0.5
 3       0.8
 4       0.3
 5       0.2
</code>```

From this array, I wish to find all the possible combinations that have a sum less than or equal to 1. That is,

```<code>result
======
1 2
1 4 5
2 4 5
3 5
1 5
1 4
2 4
2 5
...
</code>```

In order to get the above result, my idea has been to initially compute all the possibilities of finding sum of elements in the array, like so:

```<code>for ii = 1 : length(a) % compute number of possibilities
     no_of_possibilities = no_of_possibilities + nchoosek(length(a),ii);
end
</code>```

Once this is done, then loop through all possible combinations.
I would like to know if there's an easier way of doing this.

答:
Here is potential solution, using inefficient steps, but borrowing efficient code from various SO answers. Credit goes to those original peeps.

```<code>data = [0.5, 0.5, 0.8, 0.3, 0.2];
</code>```

First get all combinations of indices, not necessarily using all values.

```<code>combs = bsxfun(@minus, nchoosek(1:numel(data)+numel(data)-1,numel(data)), 0:numel(data)-1);
</code>```

Then get rid of repeated indices in each combination, regardless of index order

```<code>[ii, ~, vv] = find(sort(combs,2));
uniq = accumarray(ii(:), vv(:), [], @(x){unique(x.')});
</code>```

Next get unique combinations, regardless of index order... NOTE: You can do this step much more efficiently by restructuring the steps, but it'll do.

```<code>B = cellfun(@mat2str,uniq,'uniformoutput',false);
[~,ia] = unique(B);
uniq=uniq(ia);
</code>```

Now sum all values in data based on cell array (uniq) of index combinations

```<code>idx = cumsum(cellfun('length', uniq));
x = diff(bsxfun(@ge, [0; idx(:)], 1:max(idx)));
x = sum(bsxfun(@times, x', 1:numel(uniq)), 2);  %'// Produce subscripts
y = data([uniq{:}]);                               % // Obtain values
sums_data = accumarray(x, y);
</code>```

And finally only keep the index combinations that sum to <= 1

```<code>allCombLessThanVal = uniq(sums_data<=1)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a matrix as follows:

id      value
=============
 1       0.5
 2       0.5
 3       0.8
 4       0.3
 5       0.2

From this array, I wish to find all the possible combinations that have a sum less than or equal to 1. That is,

result
======
1 2
1 4 5
2 4 5
3 5
1 5
1 4
2 4
2 5
...

In order to get the above result, my idea has been to initially compute all the possibilities of finding sum of elements in the array, like so:

for ii = 1 : length(a) % compute number of possibilities
     no_of_possibilities = no_of_possibilities + nchoosek(length(a),ii);
end

Once this is done, then loop through all possible combinations.
I would like to know if there's an easier way of doing this.

Body:
Here is potential solution, using inefficient steps, but borrowing efficient code from various SO answers. Credit goes to those original peeps.

data = [0.5, 0.5, 0.8, 0.3, 0.2];

First get all combinations of indices, not necessarily using all values.

combs = bsxfun(@minus, nchoosek(1:numel(data)+numel(data)-1,numel(data)), 0:numel(data)-1);

Then get rid of repeated indices in each combination, regardless of index order

[ii, ~, vv] = find(sort(combs,2));
uniq = accumarray(ii(:), vv(:), [], @(x){unique(x.')});

Next get unique combinations, regardless of index order... NOTE: You can do this step much more efficiently by restructuring the steps, but it'll do.

B = cellfun(@mat2str,uniq,'uniformoutput',false);
[~,ia] = unique(B);
uniq=uniq(ia);

Now sum all values in data based on cell array (uniq) of index combinations

idx = cumsum(cellfun('length', uniq));
x = diff(bsxfun(@ge, [0; idx(:)], 1:max(idx)));
x = sum(bsxfun(@times, x', 1:numel(uniq)), 2);  %'// Produce subscripts
y = data([uniq{:}]);                               % // Obtain values
sums_data = accumarray(x, y);

And finally only keep the index combinations that sum to <= 1

allCombLessThanVal = uniq(sums_data<=1)


问:
Same method with two different names?
I wold like to use same method but two different names.

For example:

```<code>def func(a):
    print a

def func2(a):
    print a

n= "yes"
func(n)
func2(n)
</code>```

answer should be:

```<code>"yes"
"yes"
</code>```

Would there be any way I can do:

```<code>def fun(a) or func2(a):
    print a
</code>```

or something like this?

答:
```

def func(a):
    print("a")

n= "yes"

def fun(a):
    func(a)

func(n)

```

Title: Same method with two different names?

Body:
I wold like to use same method but two different names.

For example:

def func(a):
    print a

def func2(a):
    print a

n= "yes"
func(n)
func2(n)

answer should be:

"yes"
"yes"

Would there be any way I can do:

def fun(a) or func2(a):
    print a

or something like this?


问:
Testing a handler that connects to db in go
I have a handler which connects to a db and retrieves the records. I wrote a test case for that and it goes this way:

main_test.go

```<code>package main

import (
  "os"
  "fmt"
  "testing"
  "net/http"
  "net/http/httptest"
)

var a App

func TestMain(m *testing.M) {
    a = App{}
    a.InitializeDB(fmt.Sprintf("postgres://****:****@localhost/db?sslmode=disable"))
    code := m.Run()
    os.Exit(code)
}

func TestRulesetGet(t *testing.T) {

    req, err := http.NewRequest("GET", "/1/sig/", nil)
    if err != nil {
        t.Fatal(err)
    }
    // We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
    rr := httptest.NewRecorder()
    handler := http.HandlerFunc(a.Get)
    handler.ServeHTTP(rr, req)

    // Check the response body is what we expect.

    if len(rr.Body.String()) != 0 {
      fmt.Println("Status OK : ", http.StatusOK)
        fmt.Println("handler returned body: got ",
            rr.Body.String())
    }
}
</code>```

I feel like this is a very basic test case where I'm just checking the response length (This is because I expect a slice). I'm not really sure whether this is the right way to write a test case. Please point out some loop holes so that I could write a solid test cases for my remaining handlers. And also, I'm not using the actual Error, and Fatal methods for checking the errors.

答:
If it works then it's not wrong, but it doesn't validate much, only that the response body is non-empty - not even that it's successful. I'm not sure why it prints out http.StatusOK, which is a constant, and doesn't tell you what the status code in the response was.

Personally when I do this level of test I check, at the very least, that the response code is as expected, the response body unmarshals correctly (if it's JSON or XML), the response data is basically sane, etc. For more complex payloads I might use a golden file test. For critical code I might use a fuzz (aka monte carlo) test. For performance-critical code I'll likely add benchmarks and load tests. There are practically infinite ways to test code. You'll have to figure out what your needs are and how to meet them.

Body:
I have a handler which connects to a db and retrieves the records. I wrote a test case for that and it goes this way:

main_test.go

package main

import (
  "os"
  "fmt"
  "testing"
  "net/http"
  "net/http/httptest"
)

var a App

func TestMain(m *testing.M) {
    a = App{}
    a.InitializeDB(fmt.Sprintf("postgres://****:****@localhost/db?sslmode=disable"))
    code := m.Run()
    os.Exit(code)
}

func TestRulesetGet(t *testing.T) {

    req, err := http.NewRequest("GET", "/1/sig/", nil)
    if err != nil {
        t.Fatal(err)
    }
    // We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
    rr := httptest.NewRecorder()
    handler := http.HandlerFunc(a.Get)
    handler.ServeHTTP(rr, req)

    // Check the response body is what we expect.

    if len(rr.Body.String()) != 0 {
      fmt.Println("Status OK : ", http.StatusOK)
        fmt.Println("handler returned body: got ",
            rr.Body.String())
    }
}

I feel like this is a very basic test case where I'm just checking the response length (This is because I expect a slice). I'm not really sure whether this is the right way to write a test case. Please point out some loop holes so that I could write a solid test cases for my remaining handlers. And also, I'm not using the actual Error, and Fatal methods for checking the errors.


问:
IEnumerable parser class design
I'm creating a class that can read from a dicom file. This is basically a binary file filled with a lot of objects. I want to create a solid class that can do this. So I've designed the following.

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

namespace Medicom
{
    public class DDocument : IEnumerable<DDataElement>
    {
        /// <summary>
        /// Creates a new DDocument from a file.
        /// </summary>
        /// <param name="path">The path of the file to load </param>
        /// <returns>An DDocument that contains the Dicom information from the file</returns>
        public static DDocument Load(string path)
        {
            return DDocument.Load(new FileStream(path, FileMode.Open));
        }

        /// <summary>
        /// Creates a new XDocument instance by using the specified stream.
        /// </summary>
        /// <param name="stream">The stream that contains the Dicom information.</param>
        /// <returns>An DDocument that contains the Dicom information from the stream.</returns>
        public static DDocument Load(Stream stream)
        {
            //Logic here to read the whole stream and List<DDataElement> Data with all the data
        }

        /// <summary>
        /// Gets or sets a list with MetaInformation containing DDataElements
        /// </summary>
        public List<DDataElement> Data
        {
            get;
            set;
        }

        /// <summary>
        /// Returns an enumerator that can be used to iterate through the DDocument
        /// </summary>
        /// <returns>An IEnumerator that can be used to iterate through the DDocument</returns>
        public IEnumerator<DDataElement> GetEnumerator()
        {
            foreach (DDataElement dataElement in Data)
            {
                yield return dataElement;
            }
        }
    }
}
</code>```

I wanted to know what you think of it. Are there any changes you would make in this class?

答: There are a number of open source JAVA-based DICOM implementations like dcm4che2. Have you considered porting their implementation?</p>

ContentLicense: CC BY-SA 2.5

Title: IEnumerable parser class design

Body:
I'm creating a class that can read from a dicom file. This is basically a binary file filled with a lot of objects. I want to create a solid class that can do this. So I've designed the following.

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

namespace Medicom
{
    public class DDocument : IEnumerable<DDataElement>
    {
        ///
        /// Creates a new DDocument from a file.
        ///
        /// <param name="path">The path of the file to load </param>
        /// <returns>An DDocument that contains the Dicom information from the file</returns>
        public static DDocument Load(string path)
        {
            return DDocument.Load(new FileStream(path, FileMode.Open));
        }

        ///
        /// Creates a new XDocument instance by using the specified stream.
        ///
        /// <param name="stream">The stream that contains the Dicom information.</param>
        /// <returns>An DDocument that contains the Dicom information from the stream.</returns>
        public static DDocument Load(Stream stream)
        {
            //Logic here to read the whole stream and List<DDataElement> Data with all the data
        }

        ///
        /// Gets or sets a list with MetaInformation containing DDataElements
        ///
        public List<DDataElement> Data
        {
            get;
            set;
        }

        ///
        /// Returns an enumerator that can be used to iterate through the DDocument
        ///
        /// <returns>An IEnumerator that can be used to iterate through the DDocument</returns>
        public IEnumerator<DDataElement> GetEnumerator()
        {
            foreach (DDataElement dataElement in Data)
            {
                yield return dataElement;
            }
        }
    }
}

I wanted to know what you think of it. Are there any changes you would make in this class?


问:
Join Statement using Query builder with multiple where clause
I have a Query builder statement below and I would want to introduce another condition to the query. However, I can not get this right.

This query works fine;

```<code>$content = DB::table('subscribed_services as a')
->join('scheduled_messages as b', 'a.id', '=', 'b.subscribed_services_id')
->join('subscription_services_msisdn as c', 'a.id', '=', 'c.subscribed_services_id')
->whereRaw('DATE(b.scheduled_at) = CURDATE()')
->selectRaw('b.message, c. phone_number, a.username, a.password')
->distinct()
->get();
</code>```

I would want to introduce another where statement; this ->whereRaw('DATE(c.sent_time) != CURDATE()'). Meaning the query above should only pick values where subscription_services_msisdn.sent_time DATE(c.sent_time) IS NOT EQUAL to Current Date CURDATE().

Anyone lead me here. Regards.

答:
You can chain as many where conditions as you want, so just add another whereRaw to the chain:

```<code>$content = DB::table('subscribed_services as a')
    ->join('scheduled_messages as b', 'a.id', '=', 'b.subscribed_services_id')
    ->join('subscription_services_msisdn as c', 'a.id', '=', 'c.subscribed_services_id')
    ->whereRaw('DATE(b.scheduled_at) = CURDATE()')
    ->whereRaw('DATE(c.sent_time) <> CURDATE()')
    ->selectRaw('b.message, c. phone_number, a.username, a.password')
    ->distinct()
    ->get();
</code>```

Body:
I have a Query builder statement below and I would want to introduce another condition to the query. However, I can not get this right.

This query works fine;

$content = DB::table('subscribed_services as a')
->join('scheduled_messages as b', 'a.id', '=', 'b.subscribed_services_id')
->join('subscription_services_msisdn as c', 'a.id', '=', 'c.subscribed_services_id')
->whereRaw('DATE(b.scheduled_at) = CURDATE()')
->selectRaw('b.message, c. phone_number, a.username, a.password')
->distinct()
->get();

I would want to introduce another where statement; this ->whereRaw('DATE(c.sent_time) != CURDATE()'). Meaning the query above should only pick values where subscription_services_msisdn.sent_time DATE(c.sent_time) IS NOT EQUAL to Current Date CURDATE().

Anyone lead me here. Regards.

Body:
You can chain as many where conditions as you want, so just add another whereRaw to the chain:

$content = DB::table('subscribed_services as a')
    ->join('scheduled_messages as b', 'a.id', '=', 'b.subscribed_services_id')
    ->join('subscription_services_msisdn as c', 'a.id', '=', 'c.subscribed_services_id')
    ->whereRaw('DATE(b.scheduled_at) = CURDATE()')
    ->whereRaw('DATE(c.sent_time) <> CURDATE()')
    ->selectRaw('b.message, c. phone_number, a.username, a.password')
    ->distinct()
    ->get();


问:
Retrieving many-to-many results from GORM
I am mapping my database using gorm.

I have two tables (service and resource) with a many-to-many relationship. I am modelling them in code as such:

```<code>type Service struct {
    BaseModel
    Name      string     `gorm:"not null;unique_index"`
    Resources []Resource `gorm:"many2many:service_resource"`
}

type Resource struct {
    BaseModel
    Name string `gorm:"not null;unique_index"`
}
</code>```

Using gorm's AutoMigrate the following tables are created:

(I also executed a raw SQL query to add the id primary key in the mapping table.)

To create a new service, I use the following code:

```<code>service := Service{
    Name: "core",
    Resources: []Resource{
        {Name: "ec2"},
        {Name: "dynamo"},
    },
}
db.Create(&service)
</code>```

This creates all the resources along with the service and fills in the relationship between them in the service_resource table just fine, as expected.

However, my problem is when I'm querying for the services. I use the following code to retrieve all services:

```<code>services := []model.Service{}
db.Find(&services)
</code>```

This returns successfully with the services array populated, but the Resources array of each service is empty:

```<code>"services": [
    {
        "ID": 1,
        "Name": "core",
        "Resources": null
    },
    ...
]
</code>```

I was under the assumption that gorm would populate it automatically. Is there some step that I'm missing?

答:
You need to Preload the resources field before querying for services:

```<code>services := []model.Service{}
db.Preload("Resources").Find(&services) // error checking ommited
</code>```

This correctly populates the Resources field of every service.

Body:
I am mapping my database using gorm.

I have two tables (service and resource) with a many-to-many relationship. I am modelling them in code as such:

type Service struct {
    BaseModel
    Name      string     `gorm:"not null;unique_index"`
    Resources []Resource `gorm:"many2many:service_resource"`
}

type Resource struct {
    BaseModel
    Name string `gorm:"not null;unique_index"`
}

Using gorm's AutoMigrate the following tables are created:

(I also executed a raw SQL query to add the id primary key in the mapping table.)

To create a new service, I use the following code:

service := Service{
    Name: "core",
    Resources: []Resource{
        {Name: "ec2"},
        {Name: "dynamo"},
    },
}
db.Create(&service)

This creates all the resources along with the service and fills in the relationship between them in the service_resource table just fine, as expected.

However, my problem is when I'm querying for the services. I use the following code to retrieve all services:

services := []model.Service{}
db.Find(&services)

This returns successfully with the services array populated, but the Resources array of each service is empty:

"services": [
    {
        "ID": 1,
        "Name": "core",
        "Resources": null
    },
    ...
]

I was under the assumption that gorm would populate it automatically. Is there some step that I'm missing?

Body:
You need to Preload the resources field before querying for services:

services := []model.Service{}
db.Preload("Resources").Find(&services) // error checking ommited

This correctly populates the Resources field of every service.


问:
Is there a way to keep a weak reference on an object and control its lifetime as well?

shared_ptr/weak_ptr allow to keep a weak reference on an object but I can't prevent someone who receives a weak to convert it and store it as a shared. So I lose the control of the object lifetime .

unique_ptr is ok to control the lifetime of the object, but does not have a weak reference mechanism.

I couldn't find a standard way to have the benefits of lifetime control and weak reference at the same time. I can't believe that I'm the only one to encounter this problem.

Is there anything in the standard or in boost that would allow this behavior?
Or is there a pattern allowing this without rewriting a complete smart_ptr class?

答:
You are asking for the impossible.

An object cannot be safely accessed by code that cannot extend the lifetime of the object to cover the time during which it is accessing the object.

To permit external code to access an object, you must also permit that code to extend the object's lifetime to cover the time in which it is accessing the object.


问:
Angular 4 - webpack: Failed to compile
When I try npm install everything seems to work fine, but then ng serve return error. I was trying almost everything, but nothing works. Maybe there is a problem with versions of angular? The same project is working on another computer. Any suggestions what is wrong?

```<code>ERROR in   Error: Child compilation failed:
  Entry module not found: Error: Can't resolve '/Users/myUser/Desktop/to/Project/frontend/src/index.html' in '/Users/myUser/Desk  top/to/Project/frontend/node_modules/@angular/cli/models/webpack-configs':
  Error: Can't resolve '/Users/myUser/Desktop/to/Project/frontend/src/index.html' in '/Users/myUser/Desktop/to/Project/frontend/node  _modules/@angular/cli/models/webpack-configs'

  - compiler.js:76
    [frontend]/[html-webpack-plugin]/lib/compiler.js:76:16

  - Compiler.js:291 Compiler.<anonymous>
    [frontend]/[webpack]/lib/Compiler.js:291:10

  - Compiler.js:494
    [frontend]/[webpack]/lib/Compiler.js:494:13

  - Tapable.js:138 next
    [frontend]/[tapable]/lib/Tapable.js:138:11

  - CachePlugin.js:62 Compiler.<anonymous>
    [frontend]/[webpack]/lib/CachePlugin.js:62:5

  - Tapable.js:142 Compiler.applyPluginsAsyncSeries
    [frontend]/[tapable]/lib/Tapable.js:142:13

  - Compiler.js:491
    [frontend]/[webpack]/lib/Compiler.js:491:10

  - Tapable.js:131 Compilation.applyPluginsAsyncSeries
    [frontend]/[tapable]/lib/Tapable.js:131:46

  - Compilation.js:645 self.applyPluginsAsync.err
    [frontend]/[webpack]/lib/Compilation.js:645:19

  - Tapable.js:131 Compilation.applyPluginsAsyncSeries
    [frontend]/[tapable]/lib/Tapable.js:131:46

  - Compilation.js:636 self.applyPluginsAsync.err
    [frontend]/[webpack]/lib/Compilation.js:636:11

  - Tapable.js:131 Compilation.applyPluginsAsyncSeries
    [frontend]/[tapable]/lib/Tapable.js:131:46

  - Compilation.js:631 self.applyPluginsAsync.err
    [frontend]/[webpack]/lib/Compilation.js:631:10

  - Tapable.js:131 Compilation.applyPluginsAsyncSeries
    [frontend]/[tapable]/lib/Tapable.js:131:46

  - Compilation.js:627 sealPart2
    [frontend]/[webpack]/lib/Compilation.js:627:9

  - Tapable.js:131 Compilation.applyPluginsAsyncSeries
    [frontend]/[tapable]/lib/Tapable.js:131:46

webpack: Failed to compile.
</code>```

答:
Moved solution from question to answer:

SOLUTION:

I added index.html to my structure of files and everything is working properly.

Title: Angular 4 - webpack: Failed to compile

Body:
When I try npm install everything seems to work fine, but then ng serve return error. I was trying almost everything, but nothing works. Maybe there is a problem with versions of angular? The same project is working on another computer. Any suggestions what is wrong?

ERROR in   Error: Child compilation failed:
  Entry module not found: Error: Can't resolve '/Users/myUser/Desktop/to/Project/frontend/src/index.html' in '/Users/myUser/Desk  top/to/Project/frontend/node_modules/@angular/cli/models/webpack-configs':
  Error: Can't resolve '/Users/myUser/Desktop/to/Project/frontend/src/index.html' in '/Users/myUser/Desktop/to/Project/frontend/node  _modules/@angular/cli/models/webpack-configs'

  - compiler.js:76
    [frontend]/[html-webpack-plugin]/lib/compiler.js:76:16

  - Compiler.js:291 Compiler.<anonymous>
    [frontend]/[webpack]/lib/Compiler.js:291:10

  - Compiler.js:494
    [frontend]/[webpack]/lib/Compiler.js:494:13

  - Tapable.js:138 next
    [frontend]/[tapable]/lib/Tapable.js:138:11

  - CachePlugin.js:62 Compiler.<anonymous>
    [frontend]/[webpack]/lib/CachePlugin.js:62:5

  - Tapable.js:142 Compiler.applyPluginsAsyncSeries
    [frontend]/[tapable]/lib/Tapable.js:142:13

  - Compiler.js:491
    [frontend]/[webpack]/lib/Compiler.js:491:10

  - Tapable.js:131 Compilation.applyPluginsAsyncSeries
    [frontend]/[tapable]/lib/Tapable.js:131:46

  - Compilation.js:645 self.applyPluginsAsync.err
    [frontend]/[webpack]/lib/Compilation.js:645:19

  - Tapable.js:131 Compilation.applyPluginsAsyncSeries
    [frontend]/[tapable]/lib/Tapable.js:131:46

  - Compilation.js:636 self.applyPluginsAsync.err
    [frontend]/[webpack]/lib/Compilation.js:636:11

  - Tapable.js:131 Compilation.applyPluginsAsyncSeries
    [frontend]/[tapable]/lib/Tapable.js:131:46

  - Compilation.js:631 self.applyPluginsAsync.err
    [frontend]/[webpack]/lib/Compilation.js:631:10

  - Tapable.js:131 Compilation.applyPluginsAsyncSeries
    [frontend]/[tapable]/lib/Tapable.js:131:46

  - Compilation.js:627 sealPart2
    [frontend]/[webpack]/lib/Compilation.js:627:9

  - Tapable.js:131 Compilation.applyPluginsAsyncSeries
    [frontend]/[tapable]/lib/Tapable.js:131:46

webpack: Failed to compile.


问:
How to add borders to multiple ranges in VBA?
I have been trying to add borders to two ranges on two different worksheets.
In my case, sheet one has 14 rows whereas the second worksheet has 30 rows. Each worksheet has the same amount of columns. When I run my code, the first worksheet works fine but the second worksheet only has 14 rows that are bordered and the other 16 are left without a border. Why isn't my code bordering the last 16 columns of my second worksheet?</p>

```<code>Sub lines()

Dim wb As Worksheet
Dim wb2 As Worksheet
Dim arrBorders As Variant, vBorder As Variant

Set wb = Worksheets("wb Summary")
Set wb2 = Worksheets("wb2 Summary")
arrBorders = Array(xlEdgeLeft, xlEdgeTop, xlEdgeBottom, _
                       xlEdgeRight, xlInsideVertical, xlInsideHorizontal)

With wb.Range("A2:H" & Cells(Rows.Count, "H").End(xlUp).Row)
    For Each vBorder In arrBorders
    With .Borders(vBorder)
     .LineStyle = xlContinuous

                .Weight = xlThin
            End With
        Next
    End With

With wb2.Range("A2:H" & Cells(Rows.Count, "H").End(xlUp).Row)
    For Each vBorder In arrBorders
    With .Borders(vBorder)
     .LineStyle = xlContinuous
                .Weight = xlThin
            End With
        Next
    End With

End Sub
</code>```

答:
You need to fully reference the sheets. I think you can also shorten your code by avoiding the loops.</p>

```<code>Sub lines()

Dim wb As Worksheet
Dim wb2 As Worksheet

Set wb = Worksheets("wb Summary")
Set wb2 = Worksheets("wb2 Summary")

With wb.Range("A2:H" & wb.Cells(wb.Rows.Count, "H").End(xlUp).Row)
    .Borders.LineStyle = xlContinuous
    .Borders.Weight = xlThin
End With

With wb2.Range("A2:H" & wb2.Cells(wb2.Rows.Count, "H").End(xlUp).Row)
    .Borders.LineStyle = xlContinuous
    .Borders.Weight = xlThin
End With

End Sub
</code>```

Body:
I have been trying to add borders to two ranges on two different worksheets.
In my case, sheet one has 14 rows whereas the second worksheet has 30 rows. Each worksheet has the same amount of columns. When I run my code, the first worksheet works fine but the second worksheet only has 14 rows that are bordered and the other 16 are left without a border. Why isn't my code bordering the last 16 columns of my second worksheet?

Sub lines()

Dim wb As Worksheet
Dim wb2 As Worksheet
Dim arrBorders As Variant, vBorder As Variant

Set wb = Worksheets("wb Summary")
Set wb2 = Worksheets("wb2 Summary")
arrBorders = Array(xlEdgeLeft, xlEdgeTop, xlEdgeBottom, _
                       xlEdgeRight, xlInsideVertical, xlInsideHorizontal)

With wb.Range("A2:H" & Cells(Rows.Count, "H").End(xlUp).Row)
    For Each vBorder In arrBorders
    With .Borders(vBorder)
     .LineStyle = xlContinuous

                .Weight = xlThin
            End With
        Next
    End With

With wb2.Range("A2:H" & Cells(Rows.Count, "H").End(xlUp).Row)
    For Each vBorder In arrBorders
    With .Borders(vBorder)
     .LineStyle = xlContinuous
                .Weight = xlThin
            End With
        Next
    End With

End Sub

Body:
You need to fully reference the sheets. I think you can also shorten your code by avoiding the loops.

Sub lines()

Dim wb As Worksheet
Dim wb2 As Worksheet

Set wb = Worksheets("wb Summary")
Set wb2 = Worksheets("wb2 Summary")

With wb.Range("A2:H" & wb.Cells(wb.Rows.Count, "H").End(xlUp).Row)
    .Borders.LineStyle = xlContinuous
    .Borders.Weight = xlThin
End With

With wb2.Range("A2:H" & wb2.Cells(wb2.Rows.Count, "H").End(xlUp).Row)
    .Borders.LineStyle = xlContinuous
    .Borders.Weight = xlThin
End With

End Sub


问:
how to call two apis in one typeahead selection
I am using the angular typeahead:-

```<code><label>USER</label>
     <input type="text" name="user" ng-model="a.user" autocomplete="off" typeahead="a for a in getAllUsers($viewValue);getAllStaffs($viewValue)" typeahead-loading="loadingCodes" typeahead-no-results="noResults">
</code>```

My directive Code:-

```<code>scope.getAllUsers = function(key) {
    var obj = {
        "key": key
    }
    if (key.length >= 2) {
        return ApiServices.getAllUsers(obj).then(function(response) {
            return response.data.map(function(item) {
                return item;
            });
        });
    } else {
        return false;
    }
};

scope.getAllStaffs = function(key) {
    var obj = {
        "key": key
    }
    if (key.length >= 2) {
        return ApiServices.getAllStaffs(obj).then(function(response) {
            return response.data.map(function(item) {
                return item;
            });
        });
    } else {
        return false;
    }
};
</code>```

There are two functions:- One is used for fetching users name and one is used for fetching staffs name. I want both this functions to call on the same input.
But the typeahead is getting list of staff members only. Is there any way to get both list populated in the same input.

答:
Define a new function that does both requests and merges the results.</p>

```<code>scope.getAllNames = function(key) {
    var obj = {
        "key": key
    }

    function extract(resp) {
        return resp.data.slice(0)
    }
    if (key.length >= 2) {
        return Promise.all([
          ApiServices.getAllUsers(obj).then(extract),
          ApiServices.getAllStaffs(obj).then(extract)
        ])
        .then(function(results) {
            return [].concat.apply([], results)
        });
    } else {
        return false;
    }

}
</code>```

Body:
I am using the angular typeahead:-

USER
     <input type="text" name="user" ng-model="a.user" autocomplete="off" typeahead="a for a in getAllUsers($viewValue);getAllStaffs($viewValue)" typeahead-loading="loadingCodes" typeahead-no-results="noResults">

My directive Code:-

scope.getAllUsers = function(key) {
    var obj = {
        "key": key
    }
    if (key.length >= 2) {
        return ApiServices.getAllUsers(obj).then(function(response) {
            return response.data.map(function(item) {
                return item;
            });
        });
    } else {
        return false;
    }
};

scope.getAllStaffs = function(key) {
    var obj = {
        "key": key
    }
    if (key.length >= 2) {
        return ApiServices.getAllStaffs(obj).then(function(response) {
            return response.data.map(function(item) {
                return item;
            });
        });
    } else {
        return false;
    }
};

There are two functions:- One is used for fetching users name and one is used for fetching staffs name. I want both this functions to call on the same input.
But the typeahead is getting list of staff members only. Is there any way to get both list populated in the same input.

Body:
Define a new function that does both requests and merges the results.

scope.getAllNames = function(key) {
    var obj = {
        "key": key
    }

    function extract(resp) {
        return resp.data.slice(0)
    }
    if (key.length >= 2) {
        return Promise.all([
          ApiServices.getAllUsers(obj).then(extract),
          ApiServices.getAllStaffs(obj).then(extract)
        ])
        .then(function(results) {
            return [].concat.apply([], results)
        });
    } else {
        return false;
    }

}


问:
AWS S3 MimeMessage files generated by SES cause 403 when accessed by java SDK
So I've been working with this problem all day, and I can't seem to find the cause of this issue.

I have an action in SES that will forward all emails at a specific subdomain to a specific bucket. These messages can be downloaded fine and contain all necessary information when interacted with in the console, but fail to be retrieved by using getObject() in the Java SDK.

I can confirm that the SDK credentials work correctly, as I can download other files from the same bucket, even with the same key prefix through my code.

That proves my bucket policy is set up correctly. The entry dealing with the getObject permission looks like this:

```<code>{
    "Sid": "EmailsAccess",
    "Effect": "Allow",
    "Principal": "*",
    "Action": [
        "s3:DeleteObject",
        "s3:GetObject"
    ],
    "Resource": "arn:aws:s3:::foo-bucket-foo/foo-prefix-foo/*"
}
</code>```

I'm sure that the root cause of the issue has to do with the owner, since that is defined as "aws-ses+publishing.us-east-1.prod" in each file generated by SES. Why is that causing my code to bring up 403s? Is there any way to change a file's owner, or is there a more elegant solution?

答:
I found the issue being that the accounts used in the SDK were a different set of accounts from the bucket owner, and did not have permission to view those specific messages.

Following  this guide would have solved the issue, but we decided to go another route and are trying to log in using the bucket owner accounts.

Body:
So I've been working with this problem all day, and I can't seem to find the cause of this issue.

I have an action in SES that will forward all emails at a specific subdomain to a specific bucket. These messages can be downloaded fine and contain all necessary information when interacted with in the console, but fail to be retrieved by using getObject() in the Java SDK.

I can confirm that the SDK credentials work correctly, as I can download other files from the same bucket, even with the same key prefix through my code.

That proves my bucket policy is set up correctly. The entry dealing with the getObject permission looks like this:

{
    "Sid": "EmailsAccess",
    "Effect": "Allow",
    "Principal": "*",
    "Action": [
        "s3:DeleteObject",
        "s3:GetObject"
    ],
    "Resource": "arn:aws:s3:::foo-bucket-foo/foo-prefix-foo/*"
}

I'm sure that the root cause of the issue has to do with the owner, since that is defined as "aws-ses+publishing.us-east-1.prod" in each file generated by SES. Why is that causing my code to bring up 403s? Is there any way to change a file's owner, or is there a more elegant solution?


问:
Creating a new list when a condition is met with a value pair and a list
Very first question ever on here. I have tried to find a solution for about a week now but I'm finally down to having to ask. I'm open to suggestions for the title of this question also.

I'm using python3

I have a csv file (legend.csv) that contains 2 headers(keys), one for numbers and one for abbreviations.

Each abbr has a corresponding number and this is represented in the csv file.

I also have a list of names (list.txt), the first part of the names are usually an abbr of some sort.

The idea behind the program is: I want to analyze the csv file and add the number that corresponds to the abbr in the names from the list.txt. The output should be a new text file if possible.

```<code>example of list.txt:
    addg-stuff
    cbdd-stuff
    abc-stuff
    add-stuff

example of legend.csv:
    number,abbr
    0001,addg
    0002,cbdd
    0003,abc
    0004,add

example of desired output:
    0003-abc-stuff
    0001-addg-stuff
    0004-add-stuff
    0002-cbdd-stuff
</code>```

the following finds the abbr but I'm stuck on how to add the corresponding number to the name.
Easiest way to cross-reference a CSV file with a text file for common strings

The link above is where I found how to pull the matching strings but not sure where to go from here.

```<code>   import csv
   with open("legend.csv") as csvfile:
       reader = csv.reader(csvfile)
       searchstring = {row[1] for row in reader}
       num = {row[0] for row in reader}
   with open("list.txt") as txtfile:
       for names in txtfile:
           for i in searchstrings:
               if i in name:
                   matching = (name) #not sure where to go from here. If matching is printed, the names are found that contain the abbr.
</code>```

Definitely new to this, just started messing with python for a month or so.
Any help would be much appreciated, especially if you have any good resources for situations like this or python in general.

答:
You can try this:

```<code>import csv

f1 = open('legend.csv')
f1 = csv.reader(f1) #splitting at instances of commas
f1 = list(f1)

f2 = open('list.txt').read().splitlines() #reading every line in the txt file

for i in f2:
   for b in f1[1:]:
       if i.split("-")[0] == b[1]:
          print str(b[0])+"-"+i
</code>```

Output:

```<code>0001-addg-stuff
0002-cbdd-stuff
0003-abc-stuff
0004-add-stuff
</code>```

In the double for-loop, the algorithm takes a line from the txt file and then a line from the csv file. Note that the f1[1:] is list slicing. That means that we start after the header in the csv file, which for us is not helpful in solving the problem. From there, the algorithm tries to determine if the abbreviation is contained in the first part of the line, in this case stored as i. If so, the number and line are printed in the style of the of your desired output.

Body:
Very first question ever on here. I have tried to find a solution for about a week now but I'm finally down to having to ask. I'm open to suggestions for the title of this question also.

I'm using python3

I have a csv file (legend.csv) that contains 2 headers(keys), one for numbers and one for abbreviations.

Each abbr has a corresponding number and this is represented in the csv file.

I also have a list of names (list.txt), the first part of the names are usually an abbr of some sort.

The idea behind the program is: I want to analyze the csv file and add the number that corresponds to the abbr in the names from the list.txt. The output should be a new text file if possible.

example of list.txt:
    addg-stuff
    cbdd-stuff
    abc-stuff
    add-stuff

example of legend.csv:
    number,abbr
    0001,addg
    0002,cbdd
    0003,abc
    0004,add

example of desired output:
    0003-abc-stuff
    0001-addg-stuff
    0004-add-stuff
    0002-cbdd-stuff

the following finds the abbr but I'm stuck on how to add the corresponding number to the name.
Easiest way to cross-reference a CSV file with a text file for common strings

The link above is where I found how to pull the matching strings but not sure where to go from here.

   import csv
   with open("legend.csv") as csvfile:
       reader = csv.reader(csvfile)
       searchstring = {row[1] for row in reader}
       num = {row[0] for row in reader}
   with open("list.txt") as txtfile:
       for names in txtfile:
           for i in searchstrings:
               if i in name:
                   matching = (name) #not sure where to go from here. If matching is printed, the names are found that contain the abbr.

Definitely new to this, just started messing with python for a month or so.
Any help would be much appreciated, especially if you have any good resources for situations like this or python in general.

Body:
You can try this:

import csv

f1 = open('legend.csv')
f1 = csv.reader(f1) #splitting at instances of commas
f1 = list(f1)

f2 = open('list.txt').read().splitlines() #reading every line in the txt file

for i in f2:
   for b in f1[1:]:
       if i.split("-")[0] == b[1]:
          print str(b[0])+"-"+i

Output:

0001-addg-stuff
0002-cbdd-stuff
0003-abc-stuff
0004-add-stuff

In the double for-loop, the algorithm takes a line from the txt file and then a line from the csv file. Note that the f1[1:] is list slicing. That means that we start after the header in the csv file, which for us is not helpful in solving the problem. From there, the algorithm tries to determine if the abbreviation is contained in the first part of the line, in this case stored as i. If so, the number and line are printed in the style of the of your desired output.


问:
How to update the Hibernate Entity Record when only few fields of entity obj are modified and remaining fields should not be null
is there any other different solution for this code.
for every pojo class we have to check that modified data coming from browser and we will store only modified data into the database.

see below billingTax  obj is coming from browser which is updated data
and billingtaxDbObject obj is retrieved from database and we will check with if condition whether updated data is changed or not

if pojo class has 20 fields, we have to write 20 if conditions
if pojo class has 5 fields, we have to write 5 if conditions

instead of writing if conditions for checking wheter data is modified or nor is there any other simplest way?

```<code>@Override

    public BillingTax update(BillingTax billingTax) throws DataInsufficientException, RecordNotFoundException {
        log.debug("BillingTaxServiceImpl.update()....................");
    try {

        if (billingTax == null)
            throw new DataInsufficientException("billingTax object is null");

        BillingTax billingtaxDbObject = get(billingTax.getId());

        if (billingtaxDbObject == null)
            throw new RecordNotFoundException("billingTax object is not found in database");

        if (billingTax.getTaxApplyType() != null
                && !billingTax.getTaxApplyType().equals(billingtaxDbObject.getTaxApplyType()))
            billingtaxDbObject.setTaxApplyType(billingTax.getTaxApplyType());

        if (billingTax.getCode() != null && !billingTax.getCode().trim().equalsIgnoreCase("null")
                && !billingTax.getCode().equalsIgnoreCase(billingtaxDbObject.getCode()))
            billingtaxDbObject.setCode(billingTax.getCode());

        if (billingTax.getName() != null && !billingTax.getName().trim().equalsIgnoreCase("null")
                && !billingTax.getName().equalsIgnoreCase(billingtaxDbObject.getName()))
            billingtaxDbObject.setName(billingTax.getName());

        if (billingTax.getDescription() != null && !billingTax.getDescription().trim().equalsIgnoreCase("null")
                && !billingTax.getDescription().equalsIgnoreCase(billingtaxDbObject.getDescription()))
            billingtaxDbObject.setDescription(billingTax.getDescription());

        if (billingTax.getServiceTypeForTax() != null
                && !billingTax.getServiceTypeForTax().equals(billingtaxDbObject.getServiceTypeForTax()))
            billingtaxDbObject.setServiceTypeForTax(billingTax.getServiceTypeForTax());

        if (billingTax.getTaxValue() != null && !billingTax.getTaxValue().equals("null")
                && !billingTax.getTaxValue().equals(billingtaxDbObject.getTaxValue()))
            billingtaxDbObject.setTaxValue(billingTax.getTaxValue());

        if (billingTax.getStatus() != null && !billingTax.getStatus().equals(billingtaxDbObject.getStatus()))
            billingtaxDbObject.setStatus(billingTax.getStatus());

        if (billingTax.getOrderNo() != null && !billingTax.getOrderNo().equals("null")
                && !billingTax.getOrderNo().equals(billingtaxDbObject.getOrderNo()))
            billingtaxDbObject.setOrderNo(billingTax.getOrderNo());

        if (billingTax.getId() != null && !billingTax.getId().trim().equalsIgnoreCase(billingtaxDbObject.getId())
                && !billingTax.getId().equalsIgnoreCase(billingtaxDbObject.getId()))
            billingtaxDbObject.setId(billingTax.getId());

        if (billingTax.getStartDate()!= null && !billingTax.getStartDate().equals(billingtaxDbObject.getStartDate()))
            billingtaxDbObject.setStartDate(billingTax.getStartDate());

        if (billingTax.getEndDate()!= null && !billingTax.getEndDate().equals(billingtaxDbObject.getEndDate()))
            billingtaxDbObject.setEndDate(billingTax.getEndDate());

        billingtaxDbObject.setUpdatedDate(new Date());
        return billingTaxDAO.update(billingtaxDbObject);

    } catch (Exception e) {
        log.error("BillingTaxServiceImpl.update()....................exception:" + e.getMessage());
        throw e;
    }
}
</code>```

答:
```<code>public class CopyConverter<T> {

    private List<String> errorMessages = new ArrayList<>();
    private int countSuccess = 0;

    public  CopyConverter<T> convert(T source, T target, Set<String> ignoreFields){
        copyProperties(source,target,ignoreFields);
        return this;
    }

    public boolean hasError(){
        return errorMessages.isEmpty();
    }

    public List<String> getErrorMessages(){
        return errorMessages;
    }

    private boolean copyProperties(T source ,T target , Set<String> ignoreFields) {

        Objects.requireNonNull(source , "..error message...");
        Objects.requireNonNull(target , "..error message...");

        try {
            Map<String, Field> fieldNameMapping = buildFiledMap(target.getClass().
                                                       getDeclaredFields());
            ignoreFields = (ignoreFields == null ? new HashSet<>() : ignoreFields);

            for (Map.Entry<String, Field> fieldEntry : fieldNameMapping.entrySet()) {
                if (ignoreFields.contains(fieldEntry.getKey())) {
                    continue;
                }
                Field field = fieldEntry.getValue();
                field.setAccessible(true);
                Object sourceValue = field.get(source);
                Object targetValue = field.get(source);

                if (isChangedAsString(sourceValue, targetValue)) {
                    field.set(target, sourceValue);
                    continue;
                }
                if (isChangedAsObject(sourceValue, targetValue)) {
                    field.set(target, sourceValue);
                }
                countSuccess++;
            }
        } catch (Exception e) {
            errorMessages.add(".......");
            log.info(....);
        }
        return countSuccess == 0;
    }

    private Map<String, Field> buildFiledMap(Field[] fields) {
        Map<String, Field> fieldMap = new HashMap<>(fields.length);
        //Stream.of(fields).collect(Collectors.toMap())
        for (Field field : fields) {
            fieldMap.put(field.getName(), field);
        }
        return fieldMap;
    }

    private boolean isChangedAsObject(Object obj1, Object obj2) {
        return (obj1 == null && obj2 != null) || (obj1 != null && !obj1.equals(obj1));
    }

    private boolean isChangedAsString(Object obj1, Object obj2) {
        if (obj1 instanceof String && obj2 instanceof String) {
            String value1 = (String) obj1;
            String value2 = (String) obj2;
            return value1 != null &&
                    !value1.trim().equalsIgnoreCase("null") &&//strange check
                    !value1.equalsIgnoreCase(value2);
        }
        return false;
    }
}
</code>```

Body:
is there any other different solution for this code.
for every pojo class we have to check that modified data coming from browser and we will store only modified data into the database.

see below billingTax  obj is coming from browser which is updated data
and billingtaxDbObject obj is retrieved from database and we will check with if condition whether updated data is changed or not

if pojo class has 20 fields, we have to write 20 if conditions
if pojo class has 5 fields, we have to write 5 if conditions

instead of writing if conditions for checking wheter data is modified or nor is there any other simplest way?

@Override

    public BillingTax update(BillingTax billingTax) throws DataInsufficientException, RecordNotFoundException {
        log.debug("BillingTaxServiceImpl.update()....................");
    try {

        if (billingTax == null)
            throw new DataInsufficientException("billingTax object is null");

        BillingTax billingtaxDbObject = get(billingTax.getId());

        if (billingtaxDbObject == null)
            throw new RecordNotFoundException("billingTax object is not found in database");

        if (billingTax.getTaxApplyType() != null
                && !billingTax.getTaxApplyType().equals(billingtaxDbObject.getTaxApplyType()))
            billingtaxDbObject.setTaxApplyType(billingTax.getTaxApplyType());

        if (billingTax.getCode() != null && !billingTax.getCode().trim().equalsIgnoreCase("null")
                && !billingTax.getCode().equalsIgnoreCase(billingtaxDbObject.getCode()))
            billingtaxDbObject.setCode(billingTax.getCode());

        if (billingTax.getName() != null && !billingTax.getName().trim().equalsIgnoreCase("null")
                && !billingTax.getName().equalsIgnoreCase(billingtaxDbObject.getName()))
            billingtaxDbObject.setName(billingTax.getName());

        if (billingTax.getDescription() != null && !billingTax.getDescription().trim().equalsIgnoreCase("null")
                && !billingTax.getDescription().equalsIgnoreCase(billingtaxDbObject.getDescription()))
            billingtaxDbObject.setDescription(billingTax.getDescription());

        if (billingTax.getServiceTypeForTax() != null
                && !billingTax.getServiceTypeForTax().equals(billingtaxDbObject.getServiceTypeForTax()))
            billingtaxDbObject.setServiceTypeForTax(billingTax.getServiceTypeForTax());

        if (billingTax.getTaxValue() != null && !billingTax.getTaxValue().equals("null")
                && !billingTax.getTaxValue().equals(billingtaxDbObject.getTaxValue()))
            billingtaxDbObject.setTaxValue(billingTax.getTaxValue());

        if (billingTax.getStatus() != null && !billingTax.getStatus().equals(billingtaxDbObject.getStatus()))
            billingtaxDbObject.setStatus(billingTax.getStatus());

        if (billingTax.getOrderNo() != null && !billingTax.getOrderNo().equals("null")
                && !billingTax.getOrderNo().equals(billingtaxDbObject.getOrderNo()))
            billingtaxDbObject.setOrderNo(billingTax.getOrderNo());

        if (billingTax.getId() != null && !billingTax.getId().trim().equalsIgnoreCase(billingtaxDbObject.getId())
                && !billingTax.getId().equalsIgnoreCase(billingtaxDbObject.getId()))
            billingtaxDbObject.setId(billingTax.getId());

        if (billingTax.getStartDate()!= null && !billingTax.getStartDate().equals(billingtaxDbObject.getStartDate()))
            billingtaxDbObject.setStartDate(billingTax.getStartDate());

        if (billingTax.getEndDate()!= null && !billingTax.getEndDate().equals(billingtaxDbObject.getEndDate()))
            billingtaxDbObject.setEndDate(billingTax.getEndDate());

        billingtaxDbObject.setUpdatedDate(new Date());
        return billingTaxDAO.update(billingtaxDbObject);

    } catch (Exception e) {
        log.error("BillingTaxServiceImpl.update()....................exception:" + e.getMessage());
        throw e;
    }
}


问:
Changing class name without loosing changes in the class
guys can anyone help me i have a weird situation,
i have created an entity using j hipster and it created classes with that name and data base table as well, now my question is how can just change my class name.
i made some changes in the classes and i don't want to loose those changes

how could i change only the class name without loosing those changes

what i tried is How to modify existing entity generated with jhipster?

after this all code changes are gone, so with loosing code changes how can i do it?

答:
This is not an answer, but I faced the same issue lot of times, Usually I do this manually, trust me its not a lot of work.

General Steps.

Step 1: In the .jhipster folder, replace the classname.json file with your file new class name. Replace relationships if any.

Step 2: Change domain, repository, service(if exist), resource.

Step 3: Change the ui code.

This is a find/replace job just need to be more careful thats it.

There is one tricky way though.

Step 1: Create a new branch, if using git

Step 2: Create a new new_class_name.json file in the .jhipster project.

Step 3: Copy the json from old_class_name.json file in the new_class_name.json

Step 4: run the command "yo jhipster:entity new_class_name"

Step 5: This will create all the new files.

Step 6: Copy paste your changes in the new one.

Step 7: Delete old files.

I usually follow the first one. Trust me its not that difficult.


问:
Drawing graphics in ExtJs
First off I want to point out that I'm very new to the ExtJs library. I want to create an image through the use of some drawing/canvas API. The image I want to create is similar to the below image.

I'm wondering if this is possible through javascript/Extjs because I haven't been able to find anything online that makes this clear. If you can think of a different kind of approach I would appreciate that as well.

答: As far as I know ExtJS 3.x does not have any API that would facilitate canvas drawing. As Josiah says, you need to stick with plain JavaScript API for that, but you can still use ExtJS to manage your Elements and Components.</p>

Title: Drawing graphics in ExtJs


问:
Removing keyword from list after matching the keyword with answer
I'm trying to keep score after certain keywords are matched with output from a chatbot. I got it to count a score for every match, but I dont want to match it again if there will be a match with the same keyword. I'm  trying to do this by removing the keyword from the list, but it continues to add score.

i.e. I want to add score if chatbot say hi, but only once.

I'm tring this

```<code>public void SendQuestionToRobot()
{

    if (string.IsNullOrEmpty(inputField.text) == false)
    {

        string answer = bot.getOutput(inputField.text);

        robotOutput.text = answer;

        inputField.text = "press enter to type";

        List<string> sPattern = new List<string> { "hi", "a painkiller" };

        foreach (string s in sPattern)
        {

            if (Regex.IsMatch(answer, s, RegexOptions.IgnoreCase))
            {
                controller.score += 5;
                sPattern.Remove(s);
                break;
            }
        }

    }
}
</code>```

and

```<code>public void SendQuestionToRobot()
{

    if (string.IsNullOrEmpty(inputField.text) == false)
    {

        string answer = bot.getOutput(inputField.text);

        robotOutput.text = answer;

        inputField.text = "press enter to type";

        List<string> sPattern = new List<string> { "hi", "a painkiller" };

        foreach (string s in sPattern)
        {

            if (Regex.IsMatch(answer, s, RegexOptions.IgnoreCase))
            {
                controller.score += 5;
                break;
            }
        }
        foreach (string s in sPattern)
        {

            if (Regex.IsMatch(answer, s, RegexOptions.IgnoreCase))
            {
                sPattern.Remove(s);

            }
        }
    }
}
</code>```

but in both cases the score continues to be added

答:
As is often the case: if you eliminate the loop, you eliminate the chance of writing a buggy loop. Don't write a loop at all!

```<code>string match = sPattern.FirstOrDefault(
  s => Regex.IsMatch(answer, s, RegexOptions.IgnoreCase));
if (match != null) {
  controller.score += 5;
  sPattern.Remove(match);
}
</code>```

No loop; no loop problems.

Body:
I'm trying to keep score after certain keywords are matched with output from a chatbot. I got it to count a score for every match, but I dont want to match it again if there will be a match with the same keyword. I'm  trying to do this by removing the keyword from the list, but it continues to add score.

i.e. I want to add score if chatbot say hi, but only once.

I'm tring this

public void SendQuestionToRobot()
{

    if (string.IsNullOrEmpty(inputField.text) == false)
    {

        string answer = bot.getOutput(inputField.text);

        robotOutput.text = answer;

        inputField.text = "press enter to type";

        List<string> sPattern = new List<string> { "hi", "a painkiller" };

        foreach (string s in sPattern)
        {

            if (Regex.IsMatch(answer, s, RegexOptions.IgnoreCase))
            {
                controller.score += 5;
                sPattern.Remove(s);
                break;
            }
        }

    }
}

and

public void SendQuestionToRobot()
{

    if (string.IsNullOrEmpty(inputField.text) == false)
    {

        string answer = bot.getOutput(inputField.text);

        robotOutput.text = answer;

        inputField.text = "press enter to type";

        List<string> sPattern = new List<string> { "hi", "a painkiller" };

        foreach (string s in sPattern)
        {

            if (Regex.IsMatch(answer, s, RegexOptions.IgnoreCase))
            {
                controller.score += 5;
                break;
            }
        }
        foreach (string s in sPattern)
        {

            if (Regex.IsMatch(answer, s, RegexOptions.IgnoreCase))
            {
                sPattern.Remove(s);

            }
        }
    }
}

but in both cases the score continues to be added

Body:
As is often the case: if you eliminate the loop, you eliminate the chance of writing a buggy loop. Don't write a loop at all!

string match = sPattern.FirstOrDefault(
  s => Regex.IsMatch(answer, s, RegexOptions.IgnoreCase));
if (match != null) {
  controller.score += 5;
  sPattern.Remove(match);
}

No loop; no loop problems.


问:
Angular logging click 2 times on one click
I'm trying to create 2 buttons, power on and power off, that have click events for their respected statuses. I have them as radio buttons, but i wanted them to be submitted on click without a submit button, like a switch. So i decide to just have them as pseudo forms, and add click listeners to each to release the event data.

I was testing this by logging the click, and when i click on, the console logs 2 clicks, despite clicking it once.

component snippet

```<code>onClick(data: any) {
        console.log('click');
}
</code>```

html snippet

```<code><div class="btn-group" data-toggle="buttons">
                <label
                    class="power-toggle on btn btn-lg btn-success"
                    (click)="onClick($event)"
                >
                    <input type="radio" name="power" value="power-on" autocomplete="off">
                        ON
                </label>
                <label
                    class="power-toggle off btn btn-lg btn-danger active"
                    (click)="onClick('off')"
                >
                    <input type="radio" name="power" value="power-off" autocomplete="off" checked>
                        OFF
                </label>
            </div>
</code>```

why is this happening? how can i fix it? is there a way to submit the radio value as is without a submit button or turning the button into a submit button?

答:
You need to bind the click function to the input and not the label.

Please find the plunker example here : https://plnkr.co/edit/Fmhs8xQupAynJfmwtk5y

```<code><div class="btn-group" data-toggle="buttons">
                <label
                    class="power-toggle on btn btn-lg btn-success"

                >
                    <input (click)="onClick($event)" type="radio" name="power" value="power-on" autocomplete="off">
                        ON
                </label>

                <label
                    class="power-toggle off btn btn-lg btn-danger active"

                >
                    <input (click)="onClick('off')"  type="radio" name="power" value="power-off" autocomplete="off" checked>
                        OFF
                </label>
            </div>
</code>```

Body:
I'm trying to create 2 buttons, power on and power off, that have click events for their respected statuses. I have them as radio buttons, but i wanted them to be submitted on click without a submit button, like a switch. So i decide to just have them as pseudo forms, and add click listeners to each to release the event data.

I was testing this by logging the click, and when i click on, the console logs 2 clicks, despite clicking it once.

component snippet

onClick(data: any) {
        console.log('click');
}

html snippet

                    <input type="radio" name="power" value="power-on" autocomplete="off">
                        ON

                    <input type="radio" name="power" value="power-off" autocomplete="off" checked>
                        OFF

why is this happening? how can i fix it? is there a way to submit the radio value as is without a submit button or turning the button into a submit button?

Body:
You need to bind the click function to the input and not the label.

Please find the plunker example here : https://plnkr.co/edit/Fmhs8xQupAynJfmwtk5y

<div class="btn-group" data-toggle="buttons">
                <label
                    class="power-toggle on btn btn-lg btn-success"

                >
                    <input (click)="onClick($event)" type="radio" name="power" value="power-on" autocomplete="off">
                        ON
                </label>

                <label
                    class="power-toggle off btn btn-lg btn-danger active"

                >
                    <input (click)="onClick('off')"  type="radio" name="power" value="power-off" autocomplete="off" checked>
                        OFF
                </label>
            </div>


问:
While first index is an array?
I can tell I'm falling through my while loop, from frame 3 to 4.

Am I not checking the condition in my while loop correctly?

```<code>function steamrollArray(arr) {
  var R2 = [];
  while (arr[0].isArray) {
    console.log(arr[0]);
    R2.push(arr[0]);
    return R2;
  }
  return R2;
}

steamrollArray([[["a"]], [["b"]]]); // should return ["a", "b"].
steamrollArray([1, [2], [3, [[4]]]]); // should return [1, 2, 3, 4].
steamrollArray([1, [], [3, [[4]]]]); // should return [1, 3, 4].
steamrollArray([1, {}, [3, [[4]]]]); // should return [1, {}, 3, 4].
</code>```

Step 3 to 4

答:
Your code seems to have some logic bugs (besides the syntactic error in not using Array.isArray). To achieve the desired result, you can use recursion like below:

function steamrollArray(arr) {
  var R2 = [];

  for (var element of arr) {
    var nextElements = [];

    while (Array.isArray(element)) {
      nextElements = element.slice(1);
      element = element[0];
    }

    if (!element) continue;

    R2.push(element);
    var rolledNextElements = steamrollArray(nextElements);
    R2 = R2.concat(rolledNextElements);
  }

  return R2;
}

console.log(steamrollArray([[["a"]], [["b"]]]));
console.log(steamrollArray([1, [2], [3, [[4]]]]));
console.log(steamrollArray([1, [], [3, [[4]]]]));
console.log(steamrollArray([1, {}, [3, [[4]]]]));```

Title: While first index is an array?

Body:
I can tell I'm falling through my while loop, from frame 3 to 4.

Am I not checking the condition in my while loop correctly?

function steamrollArray(arr) {
  var R2 = [];
  while (arr[0].isArray) {
    console.log(arr[0]);
    R2.push(arr[0]);
    return R2;
  }
  return R2;
}

steamrollArray([[["a"]], [["b"]]]); // should return ["a", "b"].
steamrollArray([1, [2], [3, [[4]]]]); // should return [1, 2, 3, 4].
steamrollArray([1, [], [3, [[4]]]]); // should return [1, 3, 4].
steamrollArray([1, {}, [3, [[4]]]]); // should return [1, {}, 3, 4].

Step 3 to 4


问:
Convert a Large JSON file into multiple JSON files with maximum 1000 lines
I'm trying to parse a large JSON file with ever increasing data into smaller files with a maximum of 1000 lines using Python.

So far I've managed to print upto a thousand lines, but now I'm stuck where to go next:

```<code>with open(input_file) as f:
count = 0
data = (lines for lines in f if count < 1000)
for x in data:
    count +=1
    print (x + str(count))
</code>```

Since this needs to be a scalable solution, any other ideas on how I could do this better ?

EDIT:
 The inner structure of the JSON is similar to the following:
{"newsletter_optin": 1, "language": "gv", "country": "UY", "username": "xy32", "email": "xyz@gm.com", "user_id": 138123918}

I am working on a project where my mentor wants me to split a Large file with millions of JSON lines into mini files of 1000 lines each.

答:
JSON files have an inner structure, so you can't just break it on any line, because the result would not be a valid JSON. Since JSON files are a combination of dictionaries and list nested within one another it makes the most sense to break the JSON separating elements of the same list.

here is an example:

```<code>{'Big JSON':[{'little JSON1':values},{'little JSON2':values}]}
</code>```

This could be broken up to

```<code>{'Big JSON':[{'little JSON1':values}]}
</code>```

and

```<code>{'Big JSON':[{'little JSON2':values}]}
</code>```

The exact code for breaking the JSON up depends on the inner structure of your JSON file. But it is important that each of your files be a stand alone valid JSON file

Body:
I'm trying to parse a large JSON file with ever increasing data into smaller files with a maximum of 1000 lines using Python.

So far I've managed to print upto a thousand lines, but now I'm stuck where to go next:

with open(input_file) as f:
count = 0
data = (lines for lines in f if count < 1000)
for x in data:
    count +=1
    print (x + str(count))

Since this needs to be a scalable solution, any other ideas on how I could do this better ?

EDIT:
 The inner structure of the JSON is similar to the following:
{"newsletter_optin": 1, "language": "gv", "country": "UY", "username": "xy32", "email": "xyz@gm.com", "user_id": 138123918}

I am working on a project where my mentor wants me to split a Large file with millions of JSON lines into mini files of 1000 lines each.

Body:
JSON files have an inner structure, so you can't just break it on any line, because the result would not be a valid JSON. Since JSON files are a combination of dictionaries and list nested within one another it makes the most sense to break the JSON separating elements of the same list.

here is an example:

{'Big JSON':[{'little JSON1':values},{'little JSON2':values}]}

This could be broken up to

{'Big JSON':[{'little JSON1':values}]}

and

{'Big JSON':[{'little JSON2':values}]}

The exact code for breaking the JSON up depends on the inner structure of your JSON file. But it is important that each of your files be a stand alone valid JSON file


问:
Android: Distinct and GroupBy in ContentResolver
What would be the correct way to add DISTINCT and/or GROUPBY to ContentResolver-based queries?

Right now I have to create custom URI for each special case.

Is there a better way?

(I still program for 1.5 as lowest common denominator)

答:
In your overridden ContentProvider query method have a specific URI mapping to using distinct.

Then use SQLiteQueryBuilder and call the setDistinct(boolean) method.

```<code>@Override
public Cursor query(Uri uri, String[] projection, String selection,
        String[] selectionArgs, String sortOrder)
{
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

    boolean useDistinct = false;

    switch (sUriMatcher.match(uri))
    {
    case YOUR_URI_DISTINCT:
        useDistinct = true;
    case YOUR_URI:
        qb.setTables(YOUR_TABLE_NAME);
        qb.setProjectionMap(sYourProjectionMap);
        break;

    default:
        throw new IllegalArgumentException("Unknown URI " + uri);
    }

    // If no sort order is specified use the default
    String orderBy;
    if (TextUtils.isEmpty(sortOrder))
    {
        orderBy = DEFAULT_SORT_ORDER;
    }
    else
    {
        orderBy = sortOrder;
    }
    // Get the database and run the query
    SQLiteDatabase db = mDBHelper.getReadableDatabase();
            // THIS IS THE IMPORTANT PART!
    qb.setDistinct(useDistinct);
    Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);

    if (c != null)
    {
        // Tell the cursor what uri to watch, so it knows when its source data changes
        c.setNotificationUri(getContext().getContentResolver(), uri);
    }

    return c;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In your overridden ContentProvider query method have a specific URI mapping to using distinct.

Then use SQLiteQueryBuilder and call the setDistinct(boolean) method.

@Override
public Cursor query(Uri uri, String[] projection, String selection,
        String[] selectionArgs, String sortOrder)
{
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

    boolean useDistinct = false;

    switch (sUriMatcher.match(uri))
    {
    case YOUR_URI_DISTINCT:
        useDistinct = true;
    case YOUR_URI:
        qb.setTables(YOUR_TABLE_NAME);
        qb.setProjectionMap(sYourProjectionMap);
        break;

    default:
        throw new IllegalArgumentException("Unknown URI " + uri);
    }

    // If no sort order is specified use the default
    String orderBy;
    if (TextUtils.isEmpty(sortOrder))
    {
        orderBy = DEFAULT_SORT_ORDER;
    }
    else
    {
        orderBy = sortOrder;
    }
    // Get the database and run the query
    SQLiteDatabase db = mDBHelper.getReadableDatabase();
            // THIS IS THE IMPORTANT PART!
    qb.setDistinct(useDistinct);
    Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);

    if (c != null)
    {
        // Tell the cursor what uri to watch, so it knows when its source data changes
        c.setNotificationUri(getContext().getContentResolver(), uri);
    }

    return c;
}


问:
How can I see raw mongoDB queries with Mongoid
I followed this page to see mongoDB queries. As a result I could see Moped log.

But I can't see raw mongoDB queries.

How can I display MongoDB queries in the rails console/server

I did like the below.

```<code># in [rails root]/config/environments/development.rb
Mongoid.logger.level = Logger::DEBUG
Moped.logger.level = Logger::DEBUG
Mongoid.logger = Logger.new("#{Rails.root}/log/mongoid_development.log")
Moped.logger = Logger.new("#{Rails.root}/log/moped_development.log")

# in [rails root]/log/mongoid_development.log
# show nothing.

# in [rails root]/log/moped_development.log
MOPED: [ip address]:27017 QUERY        database=[database name] collection=[collection name] selector={"$query"=>{"screen_name"=>"ts_3156"}, "$orderby"=>{:_id=>1}} flags=[:slave_ok] limit=-1 skip=0 batch_size=nil fields=nil (54.6286ms)
</code>```

How can I see raw mongoDB queries with Mongoid?

I want to see like the below.

```<code>db.[collection name].find({ $query: {"screen_name"=>"ts_3156"}, $orderby: {:_id=>1} })
</code>```

I can see raw mongoDB queries in /var/log/mongo/mongo.log.

But I want to see raw queries in ORM(Mongoid)'s log.

答:
I think I got an answer.  This is follow dsims answer and also from what I've seen in the documentation regarding logging.

I have an initialize file (config/initializers/mongoid.rb) and in there I have:

```<code>Mongoid.logger = Logger.new($stdout)
Mongo::Logger.logger = Logger.new($stdout)
</code>```

It dumps out the mongo info the console.  You probably want to change this for a production environment.  But while developing I like to be able to see what the DB is doing.  Especially because I'm brand new to MongoDb.

Body:
I followed this page to see mongoDB queries. As a result I could see Moped log.

But I can't see raw mongoDB queries.

How can I display MongoDB queries in the rails console/server

I did like the below.

# in [rails root]/config/environments/development.rb
Mongoid.logger.level = Logger::DEBUG
Moped.logger.level = Logger::DEBUG
Mongoid.logger = Logger.new("#{Rails.root}/log/mongoid_development.log")
Moped.logger = Logger.new("#{Rails.root}/log/moped_development.log")

# in [rails root]/log/mongoid_development.log
# show nothing.

# in [rails root]/log/moped_development.log
MOPED: [ip address]:27017 QUERY        database=[database name] collection=[collection name] selector={"$query"=>{"screen_name"=>"ts_3156"}, "$orderby"=>{:_id=>1}} flags=[:slave_ok] limit=-1 skip=0 batch_size=nil fields=nil (54.6286ms)

How can I see raw mongoDB queries with Mongoid?

I want to see like the below.

db.[collection name].find({ $query: {"screen_name"=>"ts_3156"}, $orderby: {:_id=>1} })

I can see raw mongoDB queries in /var/log/mongo/mongo.log.

But I want to see raw queries in ORM(Mongoid)'s log.

Body:
I think I got an answer.  This is follow dsims answer and also from what I've seen in the documentation regarding logging.

I have an initialize file (config/initializers/mongoid.rb) and in there I have:

Mongoid.logger = Logger.new($stdout)
Mongo::Logger.logger = Logger.new($stdout)

It dumps out the mongo info the console.  You probably want to change this for a production environment.  But while developing I like to be able to see what the DB is doing.  Especially because I'm brand new to MongoDb.


问:
sass @for within @each, where @for is using key, value pair of @each
I was not able to find the answer to my question: WTF - why?!

Variables

```<code>$breakpointNames: (xs, sm, md, lg, xl);
$breakpointSizes: (480px, 667px, 845px, 1024px, 1280px);
$breakpoints: createMapOutOfLists($breakpointNames, $breakpointSizes);
$masonryLayoutColumnsCount: (2, 2, 3, 4, 4);
$masonryLayoutColumns: createMapOutOfLists($breakpointNames,
$masonryLayoutColumnsCount);
</code>```

Mixin

```<code>@mixin media($min, $max: false) {
    @if $max == false {
        @if $min == xs {
            @media (min-width: 0px) {
                @content;
            }
        }
        @media (min-width: #{map-get($breakpoints,$min)}) {
            @content;
        }
    } @else if $min == 0 {
        @media (max-width: (#{map-get($breakpoints,$max)} - 1)) {
            @content;
        }
    } @else {
        @media (min-width: #{map-get($breakpoints,$min)}) and (max-width: (#{map-get($breakpoints,$max)} - 1)) {
            @content;
        }
    }
}
</code>```

I wrote this:

```<code>@each $breakpoint, $column-count in $masonryLayoutColumns {
    @include media($breakpoint) {
        .masonry-tile {
            width: 100% / $column-count;
        }
    }

    @for $i from 1 through $column-count {
        @include media($breakpoint) {
            .masonry-tile:nth-child(#{$i}) {
                -webkit-order: $i;
                order: $i;
            }
        }
    }
}
</code>```

That threw following Error:

```<code>Error in plugin 'sass'
Message:
../../../app/Resources/assets/sass/functions/_map_generators.scss
Error: 2 is not an integer.
    on line 4 of
../../../app/Resources/assets/sass/functions/_map_generators.scss
>> merge($map, (#{nth($listOfKeys, $index)}: #{nth($listOfValues, $index)}));
------------------------------------------^
</code>```

That the error is at a wrong place or maybe entirely wrong, is another issue and currently irrelevant - to me - right now.

After some time of searching without results and trying to fix it on my own, I got it to work with the following:

```<code>@for $index from 1 through length($masonryLayoutColumns) {
    $breakpoint: nth($breakpointSizes, $index);
    $column-count: nth($masonryLayoutColumnsCount, $index);

    @include media($breakpoint) {
        .masonry-tile {
            width: 100% / $column-count;
        }
    }

    @for $i from 1 through $column-count {
        @include media($breakpoint) {
            .masonry-tile:nth-child(#{$i}) {
                -webkit-order: $i;
                order: $i;
            }
        }
    }
}
</code>```

Okay, that works, but I don't like it.
I prefer the first version.

Is there a good reason why the first version is not working? Or is it a bug?

Thanks in advance!

答:
The only reason your code didn't work is because you must be passing a string in the map that you are creating.

$column-count should be an integer, in order to do your width manipulation  (width: 100% / $column-count;)

I have attached a sample pen, with integer data, which will resolve your issue.

```<code>$masonryLayoutColumns: (
  '760px': 8,
  '990px': 12,
  '1024px': 16
);

@each $breakpoint, $column-count in $masonryLayoutColumns {
    @media(min-width: $breakpoint) {
        .masonry-tile {
            width: 100% / $column-count;
        }
    }

    @for $i from 1 through $column-count {
        @media(min-width: $breakpoint) {
            .masonry-tile:nth-child(#{$i}) {
                -webkit-order: $i;
                order: $i;
            }
        }
    }
}
</code>```

https://codepen.io/anon/pen/LLBPaP

Note: I don't have your mixin's so I am just writing a generic media query.

Body:
I was not able to find the answer to my question: WTF - why?!

Variables

$breakpointNames: (xs, sm, md, lg, xl);
$breakpointSizes: (480px, 667px, 845px, 1024px, 1280px);
$breakpoints: createMapOutOfLists($breakpointNames, $breakpointSizes);
$masonryLayoutColumnsCount: (2, 2, 3, 4, 4);
$masonryLayoutColumns: createMapOutOfLists($breakpointNames,
$masonryLayoutColumnsCount);

Mixin

@mixin media($min, $max: false) {
    @if $max == false {
        @if $min == xs {
            @media (min-width: 0px) {
                @content;
            }
        }
        @media (min-width: #{map-get($breakpoints,$min)}) {
            @content;
        }
    } @else if $min == 0 {
        @media (max-width: (#{map-get($breakpoints,$max)} - 1)) {
            @content;
        }
    } @else {
        @media (min-width: #{map-get($breakpoints,$min)}) and (max-width: (#{map-get($breakpoints,$max)} - 1)) {
            @content;
        }
    }
}

I wrote this:

@each $breakpoint, $column-count in $masonryLayoutColumns {
    @include media($breakpoint) {
        .masonry-tile {
            width: 100% / $column-count;
        }
    }

    @for $i from 1 through $column-count {
        @include media($breakpoint) {
            .masonry-tile:nth-child(#{$i}) {
                -webkit-order: $i;
                order: $i;
            }
        }
    }
}

That threw following Error:

Error in plugin 'sass'
Message:
../../../app/Resources/assets/sass/functions/_map_generators.scss
Error: 2 is not an integer.
    on line 4 of
../../../app/Resources/assets/sass/functions/_map_generators.scss
>> merge($map, (#{nth($listOfKeys, $index)}: #{nth($listOfValues, $index)}));
------------------------------------------^

That the error is at a wrong place or maybe entirely wrong, is another issue and currently irrelevant - to me - right now.

After some time of searching without results and trying to fix it on my own, I got it to work with the following:

@for $index from 1 through length($masonryLayoutColumns) {
    $breakpoint: nth($breakpointSizes, $index);
    $column-count: nth($masonryLayoutColumnsCount, $index);

    @include media($breakpoint) {
        .masonry-tile {
            width: 100% / $column-count;
        }
    }

    @for $i from 1 through $column-count {
        @include media($breakpoint) {
            .masonry-tile:nth-child(#{$i}) {
                -webkit-order: $i;
                order: $i;
            }
        }
    }
}

Okay, that works, but I don't like it.
I prefer the first version.

Is there a good reason why the first version is not working? Or is it a bug?

Thanks in advance!

Body:
The only reason your code didn't work is because you must be passing a string in the map that you are creating.

$column-count should be an integer, in order to do your width manipulation  (width: 100% / $column-count;)

I have attached a sample pen, with integer data, which will resolve your issue.

$masonryLayoutColumns: (
  '760px': 8,
  '990px': 12,
  '1024px': 16
);

@each $breakpoint, $column-count in $masonryLayoutColumns {
    @media(min-width: $breakpoint) {
        .masonry-tile {
            width: 100% / $column-count;
        }
    }

    @for $i from 1 through $column-count {
        @media(min-width: $breakpoint) {
            .masonry-tile:nth-child(#{$i}) {
                -webkit-order: $i;
                order: $i;
            }
        }
    }
}

https://codepen.io/anon/pen/LLBPaP

Note: I don't have your mixin's so I am just writing a generic media query.