问:
How do you deal with maven-3 timestamped snapshots efficiently?
Now that maven-3 did drop support for the <uniqueVersion>false</uniqueVersion> for snapshot artefacts it seems that you really need to use timestamped SNAPSHOTS. Especially m2eclipse, which does use maven 3 internally seems to be affected with it, update-snapshots does not work when the SNAPSHOTS are not unique.

It seemed best practice before to set all snapshots to uniqueVersion=false

Now, it seems no big problem to switch to the timestamped version, after all they are managed by a central nexus repository, which is able to delete old snapshots in regular intervalls.

The problem are the local developer workstations. Their local repository quickly does grow very large with unique snapshots.

How to deal with this problem ?

Right now i see the folowing possible solutions:

Ask the developers to purge the repository in regular intervals (which leads to lots of fustration, as it takes long time to delete and even longer to download everything needed)

Set up some script which does delete all SNAPSHOT directories from the local repository and ask developers to run that script from time to time (better than the first, but still takes quite some time to run and download current snapshots)

use the dependency:purge-local-repository plugin (Does have problems when run from eclipse, due to open files, needs to be run from each project)

set up nexus on every workstation and set up a job to clean old snapshots (best result, but I don't want to maintain 50+ nexus servers, plus memory is always tight on developer workstations)

stop using SNAPSHOTS at all

What is the best way to keep your local repository from filling up your hard drive space ?

Update:

To verify the beaviour and to give more info i setup a small nexus server, build two projects (a and b) and try:

a:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>de.glauche</groupId>
  <artifactId>a</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <distributionManagement>
    <snapshotRepository>
        <id>nexus</id>
        <name>nexus</name>
        <url>http://server:8081/nexus/content/repositories/snapshots</url>
    </snapshotRepository>
  </distributionManagement>

</project>
</code>```

b:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>de.glauche</groupId>
  <artifactId>b</artifactId>
  <version>0.0.1-SNAPSHOT</version>
    <distributionManagement>
    <snapshotRepository>
        <id>nexus</id>
        <name>nexus</name>
        <url>http://server:8081/nexus/content/repositories/snapshots/</url>
    </snapshotRepository>
  </distributionManagement>
 <repositories>
    <repository>
        <id>nexus</id>
        <name>nexus</name>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
        <url>http://server:8081/nexus/content/repositories/snapshots/</url>
    </repository>
 </repositories>
  <dependencies>
    <dependency>
        <groupId>de.glauche</groupId>
        <artifactId>a</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>
  </dependencies>
</project>
</code>```

Now, when i use maven and run "deploy" on "a", i'll have

```<code>a-0.0.1-SNAPSHOT.jar
a-0.0.1-20101204.150527-6.jar
a-0.0.1-SNAPSHOT.pom
a-0.0.1-20101204.150527-6.pom
</code>```

in the local repository. With a new timestamp version each time i run the deploy target. The same happens when i try to update Snapshots from the nexus server (close "a" Project, delete it from local repository, build "b")

In an environment where lots of snapshots get build (think hudson server ...), the local reposioty fills up with old versions fast

Update 2:

To test how and why this is failing i did some more tests. Each test is run against clean everything (de/glauche gets delete from both machines and nexus)

mvn deploy with maven 2.2.1 :

local repository on machine A does contain snapshot.jar + snapshot-timestamp.jar

BUT: only one timestamped jar in nexus, metadata reads:

```<code><?xml version="1.0" encoding="UTF-8"?>
<metadata>
  <groupId>de.glauche</groupId>
  <artifactId>a</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <versioning>
    <snapshot>
      <timestamp>20101206.200039</timestamp>

      <buildNumber>1</buildNumber>
    </snapshot>
    <lastUpdated>20101206200039</lastUpdated>
  </versioning>
</metadata>
</code>```

run update dependencies (on machine B) in m2eclipse (embedded m3 final) -> local repository has snapshot.jar + snapshot-timestamp.jar :(

run package goal with external maven 2.2.1 -> local repository has snapshot.jar + snapshot-timestamp.jar :(

Ok, next try with maven 3.0.1 (after removing all traces of project a)

local repository on machine A looks better, only one one non-timestamped jar

only one timestamped jar in nexus, metadata reads:

  de.glauche
  a
  0.0.1-SNAPSHOT

```<code><snapshot>
  <timestamp>20101206.201808</timestamp>
  <buildNumber>3</buildNumber>
</snapshot>
<lastUpdated>20101206201808</lastUpdated>
<snapshotVersions>
  <snapshotVersion>
    <extension>jar</extension>
    <value>0.0.1-20101206.201808-3</value>
    <updated>20101206201808</updated>
  </snapshotVersion>
  <snapshotVersion>
    <extension>pom</extension>
    <value>0.0.1-20101206.201808-3</value>
    <updated>20101206201808</updated>
  </snapshotVersion>
</snapshotVersions>
</code>```

run update dependencies (on machine B) in m2eclipse (embedded m3 final) -> local repository has snapshot.jar + snapshot-timestamp.jar :(

run package goal with external maven 2.2.1 -> local repository has snapshot.jar + snapshot-timestamp.jar :(

So, to recap: The "deploy" goal in maven3 works better than in 2.2.1, the local repository on the creating machine looks fine.
But, the receiver always ends up with lots of timestamed versions ...

What am i doing wrong ?

Update 3

I also did test various other configurations, first replace nexus with artifactory -> same behaviour. Then use linux maven 3 clients to download the snapshots from the repository manager -> local repository still has timestamped snapshots :(

答:
As far as the remote repository piece of this,  I think the previous answers that discuss a purging of SNAPSHOTs on a regular interval will work.  But no one has addressed the local-developer workstation synchronization part of your question.

We have not started using Maven3 yet, so we've yet to see SNAPSHOTs starting to build up on local machines.

But we have had different problems with m2eclipse.  When we have "Workspace Resolution" enabled and the project exists within our workspace, source updates usually keep us on the bleeding edge.  But we've found it's very difficult to get m2eclipse to update itself with recently published artifacts in Nexus.  We're experiencing similar problems within our team and it's particularly problematic because we have a very large project graph... there are a lot of dependencies that won't be in your workspace but will be getting SNAPSHOTs published frequently.

I'm pretty sure this boils back to an issue in m2eclipse where it doesn't handle SNAPSHOTs exactly as it should.  You can see in the Maven console within eclipse where m2eclipse tells you it's skipping the update of a recently published SNAPSHOT because it's got a cached version.  If you do a -U from a run configuration or from the command line, Maven will pick up the metadata change.  But an "Update Snapshots..." selection should tell m2eclipse to have Maven expire this cache.  It doesn't appear to be getting passed along.  There appears to be a bug out there that is filed for this if you're interested in voting for it:
https://issues.sonatype.org/browse/MNGECLIPSE-2608

You made mention of this in a comment somewhere.

The best workaround for this problem seems to be having developers purge their local workstations when things start to break down from within m2eclipse.  Similar solution to a different problem...  Others have reported problems with Maven 2.2.1 and 3 backing m2eclipse, and I've seen the same.

I would hope if you're using Maven3 you can configure it to only pull the latest SNAPSHOT, and cache that for the amount of time the repository says (or until you expire it by hand).  Hopefully then you won't need to have a bunch of SNAPSHOTs sitting in your local repository.

That is unless you're talking about a build server that is manually doing a mvn install on them.  As far as how to prevent SNAPSHOTs from building up on an environment like a build server, we've kind of dodged that bullet by having each build use its own workspace and local repository (though, in Maven 2.2.1, certain things such as POMs seem to always come out of the ~/.m2/repository)  The extra SNAPSHOTs really only stick around for a single build and then they get dropped (and downloaded again from scratch).  So we've seen this approach does end up eating up more space to begin with, but it tends to remain more stable than having everything resolved out of a single repository.  This option (on Hudson) is called "Use private Maven repository" and is under the Advanced button of the Build section on project configurations when you've selected to build with Maven.  Here is the help description for that option:

Normally, Hudson uses the local Maven
  repository as determined by Maven —
  the exact process seems to be
  undocumented, but it's
  ~/.m2/repository and can be overridden
  by  in
  ~/.m2/settings.xml (see the reference
  for more details.) This normally means
  that all the jobs that are executed on
  the same node shares a single Maven
  repository. The upside of this is that
  you can save the disk space, but the
  downside of this is that sometimes
  those builds could interfere with each
  other. For example, you might end up
  having builds incorrectly succeed,
  just because your have all the
  dependencies in your local repository,
  despite that fact that none of the
  repositories in POM might have them.

There are also some reported problems
  regarding having concurrent Maven
  processes trying to use the same local
  repository.

When this option is checked, Hudson
  will tell Maven to use
  $WORKSPACE/.repository as the local
  Maven repository. This means each job
  will get its own isolated Maven
  repository just for itself. It fixes
  the above problems, at the expense of
  additional disk space consumption.

When using this option, consider
  setting up a Maven artifact manager so
  that you don't have to hit remote
  Maven repositories too often.

If you'd prefer to activate this mode
  in all the Maven jobs executed on
  Hudson, refer to the technique
  described here.

Hope this helps - if it doesn't address your problem please let me know where I missed.

Body:
Now that maven-3 did drop support for the <uniqueVersion>false</uniqueVersion> for snapshot artefacts it seems that you really need to use timestamped SNAPSHOTS. Especially m2eclipse, which does use maven 3 internally seems to be affected with it, update-snapshots does not work when the SNAPSHOTS are not unique.

It seemed best practice before to set all snapshots to uniqueVersion=false

Now, it seems no big problem to switch to the timestamped version, after all they are managed by a central nexus repository, which is able to delete old snapshots in regular intervalls.

The problem are the local developer workstations. Their local repository quickly does grow very large with unique snapshots.

How to deal with this problem ?

Right now i see the folowing possible solutions:

Ask the developers to purge the repository in regular intervals (which leads to lots of fustration, as it takes long time to delete and even longer to download everything needed)

Set up some script which does delete all SNAPSHOT directories from the local repository and ask developers to run that script from time to time (better than the first, but still takes quite some time to run and download current snapshots)

use the dependency:purge-local-repository plugin (Does have problems when run from eclipse, due to open files, needs to be run from each project)

set up nexus on every workstation and set up a job to clean old snapshots (best result, but I don't want to maintain 50+ nexus servers, plus memory is always tight on developer workstations)

stop using SNAPSHOTS at all

What is the best way to keep your local repository from filling up your hard drive space ?

Update:

To verify the beaviour and to give more info i setup a small nexus server, build two projects (a and b) and try:

a:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>de.glauche</groupId>
  <artifactId>a</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <distributionManagement>
    <snapshotRepository>
        <id>nexus</id>
        <name>nexus</name>
        <url>http://server:8081/nexus/content/repositories/snapshots</url>
    </snapshotRepository>
  </distributionManagement>

</project>

b:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>de.glauche</groupId>
  <artifactId>b</artifactId>
  <version>0.0.1-SNAPSHOT</version>
    <distributionManagement>
    <snapshotRepository>
        <id>nexus</id>
        <name>nexus</name>
        <url>http://server:8081/nexus/content/repositories/snapshots/</url>
    </snapshotRepository>
  </distributionManagement>
 <repositories>
    <repository>
        <id>nexus</id>
        <name>nexus</name>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
        <url>http://server:8081/nexus/content/repositories/snapshots/</url>
    </repository>
 </repositories>
  <dependencies>
    <dependency>
        <groupId>de.glauche</groupId>
        <artifactId>a</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>
  </dependencies>
</project>

Now, when i use maven and run "deploy" on "a", i'll have

a-0.0.1-SNAPSHOT.jar
a-0.0.1-20101204.150527-6.jar
a-0.0.1-SNAPSHOT.pom
a-0.0.1-20101204.150527-6.pom

in the local repository. With a new timestamp version each time i run the deploy target. The same happens when i try to update Snapshots from the nexus server (close "a" Project, delete it from local repository, build "b")

In an environment where lots of snapshots get build (think hudson server ...), the local reposioty fills up with old versions fast

Update 2:

To test how and why this is failing i did some more tests. Each test is run against clean everything (de/glauche gets delete from both machines and nexus)

mvn deploy with maven 2.2.1 :

local repository on machine A does contain snapshot.jar + snapshot-timestamp.jar

BUT: only one timestamped jar in nexus, metadata reads:

<?xml version="1.0" encoding="UTF-8"?>
<metadata>
  <groupId>de.glauche</groupId>
  <artifactId>a</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <versioning>
    <snapshot>
      <timestamp>20101206.200039</timestamp>

      <buildNumber>1</buildNumber>
    </snapshot>
    <lastUpdated>20101206200039</lastUpdated>
  </versioning>
</metadata>

run update dependencies (on machine B) in m2eclipse (embedded m3 final) -> local repository has snapshot.jar + snapshot-timestamp.jar :(

run package goal with external maven 2.2.1 -> local repository has snapshot.jar + snapshot-timestamp.jar :(

Ok, next try with maven 3.0.1 (after removing all traces of project a)

local repository on machine A looks better, only one one non-timestamped jar

only one timestamped jar in nexus, metadata reads:

  de.glauche
  a
  0.0.1-SNAPSHOT

<snapshot>
  <timestamp>20101206.201808</timestamp>
  <buildNumber>3</buildNumber>
</snapshot>
<lastUpdated>20101206201808</lastUpdated>
<snapshotVersions>
  <snapshotVersion>
    <extension>jar</extension>
    <value>0.0.1-20101206.201808-3</value>
    <updated>20101206201808</updated>
  </snapshotVersion>
  <snapshotVersion>
    <extension>pom</extension>
    <value>0.0.1-20101206.201808-3</value>
    <updated>20101206201808</updated>
  </snapshotVersion>
</snapshotVersions>

run update dependencies (on machine B) in m2eclipse (embedded m3 final) -> local repository has snapshot.jar + snapshot-timestamp.jar :(

run package goal with external maven 2.2.1 -> local repository has snapshot.jar + snapshot-timestamp.jar :(

So, to recap: The "deploy" goal in maven3 works better than in 2.2.1, the local repository on the creating machine looks fine.
But, the receiver always ends up with lots of timestamed versions ...

What am i doing wrong ?

Update 3

I also did test various other configurations, first replace nexus with artifactory -> same behaviour. Then use linux maven 3 clients to download the snapshots from the repository manager -> local repository still has timestamped snapshots :(


来源: stackexchange

问:
What does "~[]" do?
I saw the following line of code here .

```<code>puts("sigprocmask(SIG_UNBLOCK, ~[], []) = 0");
</code>```

I don't understand, what does empty array script([]) do?

Also, What is the purpose of ~[] in C?

答:
The linked program seems to be logging its actions in some invented semi-formalized language. This logging "language" is not C. The string literal in your question is just a line in that invented "language", which the program will send to standard output. Therefore the ~[] bit has notrhing to do with C and has no special meaning in C context.

After each (supposedly succesful) k_sigprocmask call the progrtam logs that call by sending such strings to the output.

For example, when the program outputs sigprocmask(SIG_SETMASK, [], NULL) = <something> it basically just tells the user "I just called k_sigprocmask function with first argument SIG_SETMASK, empty set of bits as the second argument and a null pointer as the third argument. And I received <something> as the error code."

[] stands for all-bits-zero bit mask (empty set). [HUP INT QUIT] stands for a mask with only HUP, INT and QUIT bits set to 1. ~[HUP] stands for a mask with all bits set to 1 except HUP bit.

~[] stands for a strange argument value new_set - 1, which does not immediately make sense to me (since new_set is a pointer). I presume it somehow results in a set with all elements included (all bits set to 1).

ContentLicense: CC BY-SA 3.0

Title: What does "~[]" do?

Body:
I saw the following line of code here .

puts("sigprocmask(SIG_UNBLOCK, ~[], []) = 0");

I don't understand, what does empty array script([]) do?

Also, What is the purpose of ~[] in C?


问:
Not able to get cookie value as Jmeter variable (HTTP cookie manager) which doens't have label
Not able to get cookie value as Jmeter variable (HTTP cookie manager) which doens't have label.

In our .Net application, there are 3 cookie values in the request as given below:

Cookie:ASP.NET_SessionId=1axjnxqp; xx yy Pvt. Ltd.; compNameSelected=xx yy Pvt. Ltd.

if observed, the middle value doesn't have label (xx yy pvt. ltd). This value is not being captured as cookie in subsequent requests though added HTTP cookie manager, updated user.properties file with CookieManager.save.cookies=true.

Used Debug sampler, only two ASP.NET and comNameSelected are shown.

Please suggest and guide.

答:
Follow @Dmitri T answer with a small change to make it work:

In the Regular Expression Extractor, On Field to check choose Request Headers

It will get cookie value from request.


问:
Use Realm Sync on UWP
I would like to use realm sync on uwp project.

```<code>var realmUrl = new Uri("realm://52.230.25.125:9080/~/default");
var authURL = new Uri("http://52.230.25.125:9080");
var credentials = Credentials.UsernamePassword(username, password, createUser: false);
var user = await User.LoginAsync(credentials, authURL);
var config = new SyncConfiguration(user, realmUrl);
var realm = Realm.GetInstance(config);
</code>```

When I debug my project, await User.LoginAsync(credentials, authURL) never return me the user instance.

I got some warning message. "The referced component 'C\Users\me.nuget\packages\realm\2.1.0\build..\native\ios\universal\librealm-wrappers.a'" could not be found

答: It seems you're using an incompatible combination of the Realm SDK and Realm Object Server. You need to upgrade your ROS instance to 2.x.</p>

Title: Use Realm Sync on UWP

Body:
I would like to use realm sync on uwp project.

var realmUrl = new Uri("realm://52.230.25.125:9080/~/default");
var authURL = new Uri("http://52.230.25.125:9080");
var credentials = Credentials.UsernamePassword(username, password, createUser: false);
var user = await User.LoginAsync(credentials, authURL);
var config = new SyncConfiguration(user, realmUrl);
var realm = Realm.GetInstance(config);

When I debug my project, await User.LoginAsync(credentials, authURL) never return me the user instance.

I got some warning message. "The referced component 'C\Users\me.nuget\packages\realm\2.1.0\build..\native\ios\universal\librealm-wrappers.a'" could not be found


问:
Fast-paced SpriteKit game has irregular CPU activity and is jittery/lags despite frame rate staying high - Swift
I'm having the issue on a simple but fast-paced SpriteKit game, but I've reduced my code just to a bouncing ball and still get the issue to a lesser extent:

```<code>override func didMove(to view: SKView) {
    super.didMove(to: view)

    physicsWorld.contactDelegate = self
    physicsWorld.speed = 1
    physicsWorld.gravity = CGVector(dx: 0.0, dy: 0.0)

    let borderBody = SKPhysicsBody(edgeLoopFrom: self.frame)
    borderBody.friction = 0
    self.physicsBody = borderBody
    borderBody.contactTestBitMask = BallCategory

    addBall()
}

func addBall() {
    let size = CGSize(width: 20, height: 20)
    let position = CGPoint(x: frame.width / 2, y: 50)

    let texture = SKTexture(image: #imageLiteral(resourceName: "whiteCircle"))
    let ball = SKSpriteNode(texture: texture, size: size)
    ball.position = position
    ball.physicsBody = SKPhysicsBody(circleOfRadius: size.width / 2)
    ball.fillColor = .white
    ball.lineWidth = 0
    addStandardProperties(node: ball, name: "ball", z: 5, contactTest: 0, category: BallCategory)
    ball.physicsBody?.isDynamic = true
    addChild(ball)
    launchBall()
}

func addStandardProperties(node: SKNode, name: String, z: CGFloat, contactTest: UInt32, category: UInt32) {

    node.name = name
    node.zPosition = z
    node.physicsBody?.isDynamic = false
    node.physicsBody?.affectedByGravity = false
    node.physicsBody?.mass = 0
    node.physicsBody?.restitution = 1
    node.physicsBody?.friction = 0
    node.physicsBody?.linearDamping = 0
    node.physicsBody?.angularDamping = 0
    node.physicsBody?.angularVelocity = 0
    node.physicsBody?.contactTestBitMask = contactTest
    node.physicsBody?.categoryBitMask = category

}

func launchBall() {
    let ball = childNode(withName: "ball")!
    ball.physicsBody?.velocity = CGVector(dx: 0, dy: 500)
}
</code>```

This code results in a ball (SKSpriteNode) bouncing up and down.  When I run this, CPU usage starts at around 10% on my iPhone 6s and then after increases to around 25-30% after maybe 30-60 seconds (no idea why it's increasing).  Throughout all of this, the frame rate stays very close to 60 FPS, usually going no lower than 58 FPS (it's the same way when I run the full game).

Almost any time an alert pops up (e.g., text messages, logging into Game Center, etc.), the lag shows up and shows up at random times when I'm running the full game.

I've also tried deleting and re-running the app, cleaning the project, deleting derived data and running in Release mode.  None of these worked permanently.

Should I give up on SpriteKit and try another framework?  If so, which?  Cocos2D?

Any help is appreciated.

答:
This is the result of Apple prioritising system calls over just about everything else.

When the system wants to know something, check something or otherwise do its thing it does so at the mercy of everything else.

No other engine will be able to help with this, there's no way to silence the system's constant activities through code.

You can get a slight improvement by putting on Flight Mode and turning off WIFI and Bluetooth. The system seems to be somewhat aware that it's in a quieter mode and does less because it's got no 4G or other connectivity it can go communicating with.

Further, there's been some pretty big changes to palm rejection in iOS 11 that's played havoc with the first round of iPad Pro models and creative software, creating multi-second rejection of all touch input. When this kind of thing can make it through to a GM you can be pretty sure they're slipping other messiness through.

Here's some complaints about iOS 11 performance: https://www.macrumors.com/2017/09/25/ios-11-app-slowdowns-performance-issues/

Body:
I'm having the issue on a simple but fast-paced SpriteKit game, but I've reduced my code just to a bouncing ball and still get the issue to a lesser extent:

override func didMove(to view: SKView) {
    super.didMove(to: view)

    physicsWorld.contactDelegate = self
    physicsWorld.speed = 1
    physicsWorld.gravity = CGVector(dx: 0.0, dy: 0.0)

    let borderBody = SKPhysicsBody(edgeLoopFrom: self.frame)
    borderBody.friction = 0
    self.physicsBody = borderBody
    borderBody.contactTestBitMask = BallCategory

    addBall()
}

func addBall() {
    let size = CGSize(width: 20, height: 20)
    let position = CGPoint(x: frame.width / 2, y: 50)

    let texture = SKTexture(image: #imageLiteral(resourceName: "whiteCircle"))
    let ball = SKSpriteNode(texture: texture, size: size)
    ball.position = position
    ball.physicsBody = SKPhysicsBody(circleOfRadius: size.width / 2)
    ball.fillColor = .white
    ball.lineWidth = 0
    addStandardProperties(node: ball, name: "ball", z: 5, contactTest: 0, category: BallCategory)
    ball.physicsBody?.isDynamic = true
    addChild(ball)
    launchBall()
}

func addStandardProperties(node: SKNode, name: String, z: CGFloat, contactTest: UInt32, category: UInt32) {

    node.name = name
    node.zPosition = z
    node.physicsBody?.isDynamic = false
    node.physicsBody?.affectedByGravity = false
    node.physicsBody?.mass = 0
    node.physicsBody?.restitution = 1
    node.physicsBody?.friction = 0
    node.physicsBody?.linearDamping = 0
    node.physicsBody?.angularDamping = 0
    node.physicsBody?.angularVelocity = 0
    node.physicsBody?.contactTestBitMask = contactTest
    node.physicsBody?.categoryBitMask = category

}

func launchBall() {
    let ball = childNode(withName: "ball")!
    ball.physicsBody?.velocity = CGVector(dx: 0, dy: 500)
}

This code results in a ball (SKSpriteNode) bouncing up and down.  When I run this, CPU usage starts at around 10% on my iPhone 6s and then after increases to around 25-30% after maybe 30-60 seconds (no idea why it's increasing).  Throughout all of this, the frame rate stays very close to 60 FPS, usually going no lower than 58 FPS (it's the same way when I run the full game).

Almost any time an alert pops up (e.g., text messages, logging into Game Center, etc.), the lag shows up and shows up at random times when I'm running the full game.

I've also tried deleting and re-running the app, cleaning the project, deleting derived data and running in Release mode.  None of these worked permanently.

Should I give up on SpriteKit and try another framework?  If so, which?  Cocos2D?

Any help is appreciated.


问:
Understanding the behavior of dbms_random.value in where clause
I have a table with two columns(Using oracle 11g database) : Country, IndexNumber. Table contains 10 rows(10 different cities and with its unique index number.)

For example:

```<code>Country      IndexNUmber
India         1
Australia     2
.             .
.             .
.             .
.             .
US            10
</code>```

Now i want to fetch a random row from above table by generating random number using dbms_random.value(1,10). To achieve that i am using below query:

```<code>select * from tab_name where indexnumber = dbms_random.value(1,10);
</code>```

I am not able to understand the output of this query as some time it is fetching one row, some time zero rows and some time more that one row.

Can someone please make me understand how oracle is evaluating this query.

Thanks
Ankit

答:
Since dbms_random.value is a nondeterministic PL/SQL function, it will be called once for each row evaluated by the query.

The function might return 4 when evaluating the first row, then it might return 8 on the second row, etc.

To compare each row to a single random number, you can turn the function call into a scalar subquery, e.g.:

```<code>select * from tab_name where indexnumber = (select dbms_random.value(1,10) from dual);
</code>```

Since the subquery is not correlated to the main query, Oracle will execute it only once (for the first row returned from the table) and remember the result for all subsequent rows. In particular, if a suitable index is on indexnumber the query will be able to use it more efficiently since it knows it is probing for a single value.

Body:
I have a table with two columns(Using oracle 11g database) : Country, IndexNumber. Table contains 10 rows(10 different cities and with its unique index number.)

For example:

Country      IndexNUmber
India         1
Australia     2
.             .
.             .
.             .
.             .
US            10

Now i want to fetch a random row from above table by generating random number using dbms_random.value(1,10). To achieve that i am using below query:

select * from tab_name where indexnumber = dbms_random.value(1,10);

I am not able to understand the output of this query as some time it is fetching one row, some time zero rows and some time more that one row.

Can someone please make me understand how oracle is evaluating this query.

Thanks
Ankit

Body:
Since dbms_random.value is a nondeterministic PL/SQL function, it will be called once for each row evaluated by the query.

The function might return 4 when evaluating the first row, then it might return 8 on the second row, etc.

To compare each row to a single random number, you can turn the function call into a scalar subquery, e.g.:

select * from tab_name where indexnumber = (select dbms_random.value(1,10) from dual);

Since the subquery is not correlated to the main query, Oracle will execute it only once (for the first row returned from the table) and remember the result for all subsequent rows. In particular, if a suitable index is on indexnumber the query will be able to use it more efficiently since it knows it is probing for a single value.


问:
Looping inside the json in stored proc DocumentDB
I have big json that I pass to stored procedure in Cosmos DB. I need to split the json document and create multiple documents. How do I loop to the json inside the stored procedure.

Example: Using Json below I need to create a separate document for each children and another one without Children nodes. A total of 3 documents. How can I loop and split it inside the stored procedure?

```<code>{
  "id": "d93af7d3706e4f28882920366c017cd7",
  "FamilyId": 989,
  "LastName": "Andersen",
  "Parents": [
    {
      "FamilyName": null,
      "FirstName": "Thomas"
    },
    {
      "FamilyName": null,
      "FirstName": "Mary Kay"
    }
  ],
  "Children": [
    {
      "ChildId":001,
      "FamilyName": null,
      "FirstName": "Henriette Thaulow",
      "Gender": "female",
      "Grade": 5,
      "Pets": [
        {
          "GivenName": "Fluffy"
        }
      ]
    },
    {
      "ChildId":002
      "FamilyName": null,
      "FirstName": "Maria Thaulow",
      "Gender": "female",
      "Grade": 12,
      "Pets": [
        {
          "GivenName": "Grizzly"
        }
      ]
    }
  ],
  "Address": {
    "State": "WA",
    "County": "King",
    "City": "Seattle"
  },
  "IsRegistered": false
}
</code>```

答:
Actually , you can implement bulk import data via Stored Procedure.

Please refer to the code from official tutorial.

```<code>function bulkImport(docs) {
    var collection = getContext().getCollection();
    var collectionLink = collection.getSelfLink();

    // The count of imported docs, also used as current doc index.
    var count = 0;

    // Validate input.
    if (!docs) throw new Error("The array is undefined or null.");

    var docsLength = docs.length;
    if (docsLength == 0) {
        getContext().getResponse().setBody(0);
    }

    // Call the create API to create a document.
    tryCreate(docs[count], callback);

    // Note that there are 2 exit conditions:
    // 1) The createDocument request was not accepted.
    //    In this case the callback will not be called, we just call setBody and we are done.
    // 2) The callback was called docs.length times.
    //    In this case all documents were created and we don’t need to call tryCreate anymore. Just call setBody and we are done.
    function tryCreate(doc, callback) {
        var isAccepted = collection.createDocument(collectionLink, doc, callback);

        // If the request was accepted, callback will be called.
        // Otherwise report current count back to the client,
        // which will call the script again with remaining set of docs.
        if (!isAccepted) getContext().getResponse().setBody(count);
    }

    // This is called when collection.createDocument is done in order to process the result.
    function callback(err, doc, options) {
        if (err) throw err;

        // One more document has been inserted, increment the count.
        count++;

        if (count >= docsLength) {
            // If we created all documents, we are done. Just set the response.
            getContext().getResponse().setBody(count);
        } else {
            // Create next document.
            tryCreate(docs[count], callback);
        }
    }
}
</code>```

When stored procedure is executed from client, RequestOptions specify the partition key, stored procedure will run in context of this partition and cannot operate (e.g. create) on docs that have different partition key value.

What you can do is to execute the stored procedure from client for each partition key. For instance, if stored procedure is to bulk-create documents, you can group the docs by partition key and send each group (can be done in parallel) to the stored procedure providing partition key value in RequestOptions.

Hope it helps you.

Body:
I have big json that I pass to stored procedure in Cosmos DB. I need to split the json document and create multiple documents. How do I loop to the json inside the stored procedure.

Example: Using Json below I need to create a separate document for each children and another one without Children nodes. A total of 3 documents. How can I loop and split it inside the stored procedure?

{
  "id": "d93af7d3706e4f28882920366c017cd7",
  "FamilyId": 989,
  "LastName": "Andersen",
  "Parents": [
    {
      "FamilyName": null,
      "FirstName": "Thomas"
    },
    {
      "FamilyName": null,
      "FirstName": "Mary Kay"
    }
  ],
  "Children": [
    {
      "ChildId":001,
      "FamilyName": null,
      "FirstName": "Henriette Thaulow",
      "Gender": "female",
      "Grade": 5,
      "Pets": [
        {
          "GivenName": "Fluffy"
        }
      ]
    },
    {
      "ChildId":002
      "FamilyName": null,
      "FirstName": "Maria Thaulow",
      "Gender": "female",
      "Grade": 12,
      "Pets": [
        {
          "GivenName": "Grizzly"
        }
      ]
    }
  ],
  "Address": {
    "State": "WA",
    "County": "King",
    "City": "Seattle"
  },
  "IsRegistered": false
}

Body:
Actually , you can implement bulk import data via Stored Procedure.

Please refer to the code from official tutorial.

function bulkImport(docs) {
    var collection = getContext().getCollection();
    var collectionLink = collection.getSelfLink();

    // The count of imported docs, also used as current doc index.
    var count = 0;

    // Validate input.
    if (!docs) throw new Error("The array is undefined or null.");

    var docsLength = docs.length;
    if (docsLength == 0) {
        getContext().getResponse().setBody(0);
    }

    // Call the create API to create a document.
    tryCreate(docs[count], callback);

    // Note that there are 2 exit conditions:
    // 1) The createDocument request was not accepted.
    //    In this case the callback will not be called, we just call setBody and we are done.
    // 2) The callback was called docs.length times.
    //    In this case all documents were created and we don’t need to call tryCreate anymore. Just call setBody and we are done.
    function tryCreate(doc, callback) {
        var isAccepted = collection.createDocument(collectionLink, doc, callback);

        // If the request was accepted, callback will be called.
        // Otherwise report current count back to the client,
        // which will call the script again with remaining set of docs.
        if (!isAccepted) getContext().getResponse().setBody(count);
    }

    // This is called when collection.createDocument is done in order to process the result.
    function callback(err, doc, options) {
        if (err) throw err;

        // One more document has been inserted, increment the count.
        count++;

        if (count >= docsLength) {
            // If we created all documents, we are done. Just set the response.
            getContext().getResponse().setBody(count);
        } else {
            // Create next document.
            tryCreate(docs[count], callback);
        }
    }
}

When stored procedure is executed from client, RequestOptions specify the partition key, stored procedure will run in context of this partition and cannot operate (e.g. create) on docs that have different partition key value.

What you can do is to execute the stored procedure from client for each partition key. For instance, if stored procedure is to bulk-create documents, you can group the docs by partition key and send each group (can be done in parallel) to the stored procedure providing partition key value in RequestOptions.

Hope it helps you.


问:
'ul li' hover color with hyperlink inside
Consider:

ul {
  list-style-position: inside;
}

ul li {
  border-radius: 7px;
  line-height: 21px;
  padding: 0 9px;
  letter-spacing: 0.5px;
}

ul li a {
  color: #555;
}

ul li:hover {
  background: #0099cc;
  color: white;
}

ul li a:hover {
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='titlewrap'>
  <ul>
    <li class='title'>lorem ipsum</li>
    <li class='title'>lorem ipsum</li>
    <li class='title'>lorem ipsum</li>
    <li class='title'>lorem ipsum</li>
  </ul>
</div></code>```

Hovering, li a color is changed to white, but when I move the pointer outside of a and still inside of li- color is again #555.

答:
Add this line too in your CSS:</p>

```<code>ul li:hover a{
    color: white;
}
</code>```

Body:
Consider:

ul {
  list-style-position: inside;
}

ul li {
  border-radius: 7px;
  line-height: 21px;
  padding: 0 9px;
  letter-spacing: 0.5px;
}

ul li a {
  color: #555;
}

ul li:hover {
  background: #0099cc;
  color: white;
}

ul li a:hover {
  color: white;
}

lorem ipsum

lorem ipsum

lorem ipsum

lorem ipsum

Hovering, li a color is changed to white, but when I move the pointer outside of a and still inside of li- color is again #555.

Body:
Add this line too in your CSS:

ul li:hover a{
    color: white;
}


问:
Django - collecting info per request
I want to collect data in each request (single request can cause several changes), and process the data at the end of the request.

So I'm using a singleton class to collect the data, and I'm processing the data in it on request_finished signal. Should it work or should I expect data loss/other issues?

singleton class:

```<code>class Singleton(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class DataManager(object, metaclass=Singleton):
     ....
</code>```

using it in other signal:

```<code>item_created = DataManager().ItemCreated(item)
DataManager().add_event_to_list(item_created)
</code>```

request finished signal:

```<code>@receiver(request_finished, dispatch_uid="request_finished")
def my_request_finished_handler(sender, **kwargs):
    DataManager().process_data()
</code>```

答:
Edited my answer, the first one was not well thought of.

After further thinking, it's not a good idea to use the request in the signals, neither by global nor by passing it down.

Django has two main paths: Views and Commands. Views are used for web requests, which is generating a 'request' object. Commands are used through the console and do not generate a 'request' object. Ideally, your models (thus, also signals) should be able to support both paths (for example: for data migrations during a project's lifespan). So it's inherently incorrect to tie down your signals to the request object.

It would be better to use something like a thread-local memory space and make sure your thread-global class does not rely on anything from the request. For example:
Is there a way to access the context from everywhere in Django?

Title: Django - collecting info per request

Body:
I want to collect data in each request (single request can cause several changes), and process the data at the end of the request.

So I'm using a singleton class to collect the data, and I'm processing the data in it on request_finished signal. Should it work or should I expect data loss/other issues?

singleton class:

class Singleton(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class DataManager(object, metaclass=Singleton):
     ....

using it in other signal:

item_created = DataManager().ItemCreated(item)
DataManager().add_event_to_list(item_created)

request finished signal:

@receiver(request_finished, dispatch_uid="request_finished")
def my_request_finished_handler(sender, **kwargs):
    DataManager().process_data()


问:
Dispose C# DLL marked for COM interop
I created a vanilla C# dll and marked it for COM inter op. The dll is a plain user form with no functionality as this is an experiment.

I registered the DLL and opened active x test container and instantiated my COM object. It shows up in the test container and i can view the exposed methods of the control - these are the default methods and not created by me.

i then exit from the active x test container and i noticed that test container was still lurking around in task manager and that i had to kill the process manually. This leads me to believe that the test container still holds a reference to my C# dll exposed for com inter op.

The default dispose method in the designer.cs is

```<code> protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);

   }
</code>```

When i used the test container with Quick time, it invoked quick time as expected and when i closed the test container it disposed correctly and did not leave a footprint in the task manager.

The question - is there a specific thing that i must do in my dispose method? Also, this may not be relevant, but when i create a test project and it launches my c# control and i click on the close button, it closes my test form but the test application ins still running in debug mode - the run button is disabled.

答: The MSDN has a quite comprehensive article on how to implement IDisposable.</p>

ContentLicense: CC BY-SA 2.5

Title: Dispose C# DLL marked for COM interop

Body:
I created a vanilla C# dll and marked it for COM inter op. The dll is a plain user form with no functionality as this is an experiment.

I registered the DLL and opened active x test container and instantiated my COM object. It shows up in the test container and i can view the exposed methods of the control - these are the default methods and not created by me.

i then exit from the active x test container and i noticed that test container was still lurking around in task manager and that i had to kill the process manually. This leads me to believe that the test container still holds a reference to my C# dll exposed for com inter op.

The default dispose method in the designer.cs is

 protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);

   }

When i used the test container with Quick time, it invoked quick time as expected and when i closed the test container it disposed correctly and did not leave a footprint in the task manager.

The question - is there a specific thing that i must do in my dispose method? Also, this may not be relevant, but when i create a test project and it launches my c# control and i click on the close button, it closes my test form but the test application ins still running in debug mode - the run button is disabled.

OwnerDisplayName: David Schmitt


问:
I want to animate, in fact fade, "within" drawRect
Is there a way to make drawRect animate FROM THE PREVIOUS SCENE to the next one?

(Amazingly) you can animate inside drawRect - try it.  You can fade, translate or animate any other property.

However, it starts "from fresh", from blank.  So for example if you put a fade-in animation block in drawRect, the previous scene with disappear and the new scene will fade up from white.

I want the screen to fade from the previous image (drawn in the previous cycle of drawRect) to the new image I have just drawn ... err, am drawing.

Is there a way to do that, perhaps trickily by manipulating what's going on with drawRect?

This would seem to be a very common use case - blending from one scene to the next.

Does anyone know the secret?

Of course, obviously this can be done in the core animation milieu or in many other ways, but having drawRect fade from one drawRect to the next is an obvious idea. Cheers.

Astounding update thanks to the genius of WrightCS.....

Thanks only to WrightCS, we now know that drawRect handles animations perfectly. Simply paste this code at the end of any drawRect and try it:

```<code>self.alpha = 0.0;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:2];
self.alpha = 1.0;
[UIView commitAnimations];
</code>```

it treats the entire drawRect, no matter how complex, as one enormous block and it wraps it in that animation.  Yes, it even includes painted in offscreen areas, bitmap rendering or anything else. Everything gets animated. Who knew?

The problem at hand - how to make it start the animation from the previous scene rather than start from blank?

答:
You can animate the alpha:</p>

```<code>[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:2.0];
myObject.alpha = 0.0;
[UIView commitAnimations];
</code>```

Body:
Is there a way to make drawRect animate FROM THE PREVIOUS SCENE to the next one?

(Amazingly) you can animate inside drawRect - try it.  You can fade, translate or animate any other property.

However, it starts "from fresh", from blank.  So for example if you put a fade-in animation block in drawRect, the previous scene with disappear and the new scene will fade up from white.

I want the screen to fade from the previous image (drawn in the previous cycle of drawRect) to the new image I have just drawn ... err, am drawing.

Is there a way to do that, perhaps trickily by manipulating what's going on with drawRect?

This would seem to be a very common use case - blending from one scene to the next.

Does anyone know the secret?

Of course, obviously this can be done in the core animation milieu or in many other ways, but having drawRect fade from one drawRect to the next is an obvious idea. Cheers.

Astounding update thanks to the genius of WrightCS.....

Thanks only to WrightCS, we now know that drawRect handles animations perfectly. Simply paste this code at the end of any drawRect and try it:

self.alpha = 0.0;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:2];
self.alpha = 1.0;
[UIView commitAnimations];

it treats the entire drawRect, no matter how complex, as one enormous block and it wraps it in that animation.  Yes, it even includes painted in offscreen areas, bitmap rendering or anything else. Everything gets animated. Who knew?

The problem at hand - how to make it start the animation from the previous scene rather than start from blank?

Body:
You can animate the alpha:

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:2.0];
myObject.alpha = 0.0;
[UIView commitAnimations];


问:
jsessionid passed in url if cookie and jsessionid stored by browser
My web application was passing jsessionid in URL while it was using cookie base session management in other browser and machine which is desired behavior.

To fix this issue, I deleted stored cookie and jsessionid from locale storage and then it start using cookie base session management instead of URL rewriting.

Can someone explain why this is happening, stored cookie and jsessionid stopping application to use cookie base management.I need only cookie base session management in application how I can do that.

Environment:

Chrome browser, Struts 2,Tomcat 7,Java 8

Thank in advance.

答:
jsessionid is special cookie used by Java application/web server to track user's session (to recognize user is old user eg. who has already logged in). For the first request to the server there will not be any cookies sent by the browser. So, server do not know whether the client supports cookie or not. For this server sends the jsessionid in cookie and in URL (URL Rewriting). But for the next request onwards the cookie will be available (from the previous request browser will store the cookie sent by the server and for the same context now it knows there is already it has cookie, so send it). That is why for next request onward you do not see jsessionid in URL. To force the server only use COOKIE based tracking, you will have add below fragment in web.xml

```<code><session-config>
  <!-- Only cookie based tracking -->
  <tracking-mode>COOKIE</tracking-mode>
</session-config>
</code>```

Body:
jsessionid is special cookie used by Java application/web server to track user's session (to recognize user is old user eg. who has already logged in). For the first request to the server there will not be any cookies sent by the browser. So, server do not know whether the client supports cookie or not. For this server sends the jsessionid in cookie and in URL (URL Rewriting). But for the next request onwards the cookie will be available (from the previous request browser will store the cookie sent by the server and for the same context now it knows there is already it has cookie, so send it). That is why for next request onward you do not see jsessionid in URL. To force the server only use COOKIE based tracking, you will have add below fragment in web.xml

<session-config>
  <!-- Only cookie based tracking -->
  <tracking-mode>COOKIE</tracking-mode>
</session-config>


问:
How to Trim the first two characters of a column in csv using groovy
```<code><taskdef  name="groovy" classname="org.codehaus.groovy.ant.Groovy"/>
     <groovy>
    newFile("C://RxBen//exports//Control_Exception__c_Exportupdated.csv").withWriter {
    new File("C://RxBen//exports//Control_Exception__c_Export.csv").splitEachLine(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*\$)") { ID, Don_t_Work__c,Forwarding_fax_number__c, No_Go__c  ->
     it.println "${ID},${Forwarding_fax_number__c}AAA,${s}"
     }
    }
    </groovy>
</code>```

答:
Updated:

Try with this code: which  Ozsaffer approached ...

```<code>@Grab('com.xlson.groovycsv:groovycsv:1.1')
import static com.xlson.groovycsv.CsvParser.parseCsv

df = new FileReader('filename.csv')

def data = parseCsv(df, readFirstLine: false)

for (def row : data){

println row.values[0].substring(2)  //row.values[0] means first column
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Updated:

Try with this code: which  Ozsaffer approached ...

@Grab('com.xlson.groovycsv:groovycsv:1.1')
import static com.xlson.groovycsv.CsvParser.parseCsv

df = new FileReader('filename.csv')

def data = parseCsv(df, readFirstLine: false)

for (def row : data){

println row.values[0].substring(2)  //row.values[0] means first column
}


问:
Keyboard shortcut to add block comment in Xcode 9?
I am adding documentation to project, but do not find any shortcut to add Block Comment. I have read Markup Formatting Reference guide but not able to find shortcut.

I am using Option ⌥ + Command ⌘ + / to add comment but it adding /// for every line.

```<code>    /// Initializer
    ///
    /// - Parameters:
    ///   - userId: User Id
    ///   - userName: User Name
    ///   - applicationVersion: Applicarion Version

    init(_ userId: String, withUserName userName: String, withApplicationVersion applicationVersion: String)
</code>```

I want to add Block Comment /** ....*/ as below:

```<code>/**
 - parameters:
   - cubes: The cubes available for allocation
   - people: The people that require cubes
 */
</code>```

答:
1.Create Automator service using AppleScript

2.Make sure "Output replaces selected text" is checked

3.Enter the following code:

```<code> on run {input, parameters}
 return "/*\n" & (input as string) & "*/"
 end run
</code>```

Now you can access that service through Xcode - Services menu or giving it a shortcut under System Preferences.

Body:
I am adding documentation to project, but do not find any shortcut to add Block Comment. I have read Markup Formatting Reference guide but not able to find shortcut.

I am using Option ⌥ + Command ⌘ + / to add comment but it adding /// for every line.

    /// Initializer
    ///
    /// - Parameters:
    ///   - userId: User Id
    ///   - userName: User Name
    ///   - applicationVersion: Applicarion Version

    init(_ userId: String, withUserName userName: String, withApplicationVersion applicationVersion: String)

I want to add Block Comment /** ....*/ as below:

/**
 - parameters:
   - cubes: The cubes available for allocation
   - people: The people that require cubes
 */

Body:
1.Create Automator service using AppleScript

2.Make sure "Output replaces selected text" is checked

3.Enter the following code:

 on run {input, parameters}
 return "/*\n" & (input as string) & "*/"
 end run

Now you can access that service through Xcode - Services menu or giving it a shortcut under System Preferences.


问:
How can I use the values_list in Wagtail (django)?
hi  sorry for my poor English

Why wagtail search  return PostgresSearchResult   after search ?

i want PageQuerySet

like Django postgres search backend  because I can not use  values_list after search

i want to get list of page path ( because i want to find pages parents(Category Page) by path )

and i can't use values_list before search because it does not work

i know, i can use Forloop  but this takes about 5 seconds for each run

My code is very simple :

Django Way : #Work

```<code>ProductPage.objects.filter(title__search="phone").values_list('path')
</code>```

Wagtail Way : #NotWork :(

```<code>ProductPage.objects.search(query).values_list('path')
</code>```

答:
It is a bit counter intuitive but you need to always put the search(query) call last.

Reading the Search docs, you will see a note:

The search() method will convert your QuerySet into an instance
of one of Wagtail’s SearchResults classes (depending on backend).
This means that you must perform filtering before calling search().

This means that to get a mostly equal set of results you will need to do the following:

```<code>query = 'phone'
ProductPage.objects.values_list('path').search(query)
</code>```

Note the search is the last call. The search will still function as expected, I have also tested a similar situation on my setup.

values(), values_list(), filter() all return QuerySets where as the Wagtail search() takes a QuerySet and returns a non-QuerySet object. The actual database querying only happens when you iterate (or use) a QuerySet so the order of the QuerySet functions do not matter.

Body:
hi  sorry for my poor English

Why wagtail search  return PostgresSearchResult   after search ?

i want PageQuerySet

like Django postgres search backend  because I can not use  values_list after search

i want to get list of page path ( because i want to find pages parents(Category Page) by path )

and i can't use values_list before search because it does not work

i know, i can use Forloop  but this takes about 5 seconds for each run

My code is very simple :

Django Way : #Work

ProductPage.objects.filter(title__search="phone").values_list('path')

Wagtail Way : #NotWork :(

ProductPage.objects.search(query).values_list('path')

Body:
It is a bit counter intuitive but you need to always put the search(query) call last.

Reading the Search docs, you will see a note:

The search() method will convert your QuerySet into an instance
of one of Wagtail’s SearchResults classes (depending on backend).
This means that you must perform filtering before calling search().

This means that to get a mostly equal set of results you will need to do the following:

query = 'phone'
ProductPage.objects.values_list('path').search(query)

Note the search is the last call. The search will still function as expected, I have also tested a similar situation on my setup.

values(), values_list(), filter() all return QuerySets where as the Wagtail search() takes a QuerySet and returns a non-QuerySet object. The actual database querying only happens when you iterate (or use) a QuerySet so the order of the QuerySet functions do not matter.


问:
could not get input field value in jquery
I am creating an input field using foreach loop like this

```<code><?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
</code>```

$data is Array

```<code>(
    [0] => Array
        (
            [asset_id] => abc-02
            [asset_name] => Freezer
        )

    [1] => Array
        (
            [asset_id] => xyz-01
            [asset_name] => Refrigerator
        )

    [2] => Array
        (
            [asset_id] => 300001
            [asset_name] => Generator
        )
)
</code>```

and in javascript, I am trying to get the value using this code but it always alerts first value of the input.

```<code><script type="text/javascript">
 $(document).ready(function () {
           var typename = $('#typename').val();
           alert(typename);
});
</script>
</code>```

i have to disable this input field when value is 'Generator'

答:
you fired with your id that's why it's fired only first element value.

this is how you can do that with your current code

```<code>$(document).ready(function () {
   $('input[name="model[]"]').each(function(){
       alert($(this).val());
    });
});
</code>```

However, it's highly recommended that you have to used unique id for each element otherwise used class to do what you want to.

Body:
I am creating an input field using foreach loop like this

<?php foreach($data as $key=>$val) { ?>

<input readonly class="form-control" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">

<?php } ?>

$data is Array

(
    [0] => Array
        (
            [asset_id] => abc-02
            [asset_name] => Freezer
        )

    [1] => Array
        (
            [asset_id] => xyz-01
            [asset_name] => Refrigerator
        )

    [2] => Array
        (
            [asset_id] => 300001
            [asset_name] => Generator
        )
)

and in javascript, I am trying to get the value using this code but it always alerts first value of the input.

i have to disable this input field when value is 'Generator'

Body:
you fired with your id that's why it's fired only first element value.

this is how you can do that with your current code

$(document).ready(function () {
   $('input[name="model[]"]').each(function(){
       alert($(this).val());
    });
});

However, it's highly recommended that you have to used unique id for each element otherwise used class to do what you want to.


问:
Regular expression string search in Java
I know this can be done in many ways but im curious as to what the regex would be to pick out all strings not containing a particular substring, say GDA from
strings like GADSA, GDSARTCC, , THGDAERY. </p>

答:
```<code>String regex = ".*GDA.*";

List<String> testStrings = populateStrings();

for (String s : testStrings)
{
    if (!s.matches(regex))
        System.out.println("String " + s + " does not match " + regex);
}
</code>```


问:
Remove tabindex attribute from hyperlink
I have an oracle apex page. I defined a tabscontainer region in it. There are two sub regions to this region. There is a hyper link inside each sub region, which is coded like

```<code><a class="t-Tabs-link" href="#SR_R1" role="presentation" tabindex="-1">
  <span>1</span>
</a>
</code>```

in first region and

```<code><a class="t-Tabs-link" href="#SR_R2" role="presentation" >
  <span>2</span>
</a>
</code>```

in second region.

I want to remove tabindex property of first region from this code using javascript and add property tabindex="-1" to second region.I can not add an id to this hyper link since oracle apex do not allow to edit default html attributes. How can I do this without assigning id ? or is there any way that I can assign id to this hyper link?

答:
Use Jquery removeAttr to remove the attribute from any element.

Select the first index element and simply remove attribute from it

```<code>$(".t-Tabs-link").eq(0).removeAttr("tabindex");
</code>```

You can also set attribute via Jquery attr() function

```<code>$(".t-Tabs-link").eq(1).attr("tabindex" , -1);
</code>```

example

Body:
I have an oracle apex page. I defined a tabscontainer region in it. There are two sub regions to this region. There is a hyper link inside each sub region, which is coded like

  1

in first region and

  2

in second region.

I want to remove tabindex property of first region from this code using javascript and add property tabindex="-1" to second region.I can not add an id to this hyper link since oracle apex do not allow to edit default html attributes. How can I do this without assigning id ? or is there any way that I can assign id to this hyper link?

Body:
Use Jquery removeAttr to remove the attribute from any element.

Select the first index element and simply remove attribute from it

$(".t-Tabs-link").eq(0).removeAttr("tabindex");

You can also set attribute via Jquery attr() function

$(".t-Tabs-link").eq(1).attr("tabindex" , -1);

example


问:
php registration do not push to db issue
I've got 2 classes - db.class.php and user.class.php. Within second one I have 2 methods associated with registration - register and registerValidation. db file is responsible for specifying db credentials and initializing connection. I do not really want to pollute my post so I will only give you db code as a link because I don't really think that the problem lays there.

The code of register method and validation method is:

```<code><?php

require_once 'token.php';

class User
{
    //db and table name
    private $conn;
    private $table_name = "users";

    // constructor with $db as database connection
    public function __construct($db)
    {
        $this->conn = $db;
    }

    public function registerValidation($nick,$email,$password)
    {
        if(
            (strlen($nick) < 5 || strlen($nick) > 20) ||
            (strlen($email) < 3 || strlen($email) > 100) ||
            (strlen($password) < 6 || strlen($password) > 50)
        )
        {
            //$error = 'nick or email or password is wrong length';
            //echo json_encode($error);
            return false;
        }
        else
        {
            // query to check if email already exists
            $query = "
                SELECT
                  *
                FROM
                  " . $this->table_name . "
                WHERE
                  id = ?
                  OR
                  email = ?
              ";

            // prepare query statement
            $stmt = $this->conn->prepare($query);

            // bind params
            $stmt->bindParam(1, $nick);
            $stmt->bindParam(2, $email);

            // execute query
            $stmt->execute();

            //count if there is same
            $num = $stmt->rowCount();

            if ($num > 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
    }

    public function register($nick,$email,$password)
    {
        try
        {
            $password = password_hash($password, PASSWORD_DEFAULT);

            $query = "
                INSERT INTO
                  users(user, user, user)
                VALUES
                  (?, ?, ?)";

            // prepare query statement
            $stmt = $this->conn->prepare($query);

            //bind values from user
            $stmt->bindparam(1, $nick);
            $stmt->bindparam(2, $email);
            $stmt->bindparam(3, $password);

            $stmt->execute();

            return $stmt;
        }
        catch(PDOException $e)
        {
            echo $e->getMessage();
        }
    }
</code>```

I also have file doRegister.php which is some kind of endpoint for client side:

```<code><?php

if(isset($_POST['submit']))
{
    if(!empty($_POST['nick'])
        && !empty($_POST['email'])
        && !empty($_POST['password']))
    {
        // instantiate database
        require_once '../config/database.php';
        $database = new Database();
        $db = $database->getConnection();

        require_once '../classes/user.php';
        $user = new User($db);

        if($user->registerValidation($_POST['nick'], $_POST['email'], $_POST['password']))
        {
            $user->register($_POST['nick'], $_POST['email'], $_POST['password']);
            http_response_code(201);
        }
        else
        {
            http_response_code(400);
        }
    }
    else
    {
        http_response_code(400);
    }
}
else
{
    http_response_code(400);
}
</code>```

When I send http POST request via postman I get 201(created) but when I go to localhost/phpmyadmin after that, there is no new record inside user table in my mysql db. Why?

答:
The register function is definitely returning false on execution of the insert statement. Also it looks like the columns are wrong.

```<code>        $query = "
            INSERT INTO
              users(nick, email , password)
            VALUES
              (?, ?, ?)";

#before returning true or false do a check on execute()
return $stmt->execute() === true ?  true  : false;
</code>```

Also before returning the header 201, do a check on the register function to verify that it was true and not false..

Body:
I've got 2 classes - db.class.php and user.class.php. Within second one I have 2 methods associated with registration - register and registerValidation. db file is responsible for specifying db credentials and initializing connection. I do not really want to pollute my post so I will only give you db code as a link because I don't really think that the problem lays there.

The code of register method and validation method is:

<?php

require_once 'token.php';

class User
{
    //db and table name
    private $conn;
    private $table_name = "users";

    // constructor with $db as database connection
    public function __construct($db)
    {
        $this->conn = $db;
    }

    public function registerValidation($nick,$email,$password)
    {
        if(
            (strlen($nick) < 5 || strlen($nick) > 20) ||
            (strlen($email) < 3 || strlen($email) > 100) ||
            (strlen($password) < 6 || strlen($password) > 50)
        )
        {
            //$error = 'nick or email or password is wrong length';
            //echo json_encode($error);
            return false;
        }
        else
        {
            // query to check if email already exists
            $query = "
                SELECT
                  *
                FROM
                  " . $this->table_name . "
                WHERE
                  id = ?
                  OR
                  email = ?
              ";

            // prepare query statement
            $stmt = $this->conn->prepare($query);

            // bind params
            $stmt->bindParam(1, $nick);
            $stmt->bindParam(2, $email);

            // execute query
            $stmt->execute();

            //count if there is same
            $num = $stmt->rowCount();

            if ($num > 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
    }

    public function register($nick,$email,$password)
    {
        try
        {
            $password = password_hash($password, PASSWORD_DEFAULT);

            $query = "
                INSERT INTO
                  users(user, user, user)
                VALUES
                  (?, ?, ?)";

            // prepare query statement
            $stmt = $this->conn->prepare($query);

            //bind values from user
            $stmt->bindparam(1, $nick);
            $stmt->bindparam(2, $email);
            $stmt->bindparam(3, $password);

            $stmt->execute();

            return $stmt;
        }
        catch(PDOException $e)
        {
            echo $e->getMessage();
        }
    }

I also have file doRegister.php which is some kind of endpoint for client side:

<?php

if(isset($_POST['submit']))
{
    if(!empty($_POST['nick'])
        && !empty($_POST['email'])
        && !empty($_POST['password']))
    {
        // instantiate database
        require_once '../config/database.php';
        $database = new Database();
        $db = $database->getConnection();

        require_once '../classes/user.php';
        $user = new User($db);

        if($user->registerValidation($_POST['nick'], $_POST['email'], $_POST['password']))
        {
            $user->register($_POST['nick'], $_POST['email'], $_POST['password']);
            http_response_code(201);
        }
        else
        {
            http_response_code(400);
        }
    }
    else
    {
        http_response_code(400);
    }
}
else
{
    http_response_code(400);
}

When I send http POST request via postman I get 201(created) but when I go to localhost/phpmyadmin after that, there is no new record inside user table in my mysql db. Why?

Body:
The register function is definitely returning false on execution of the insert statement. Also it looks like the columns are wrong.

        $query = "
            INSERT INTO
              users(nick, email , password)
            VALUES
              (?, ?, ?)";

#before returning true or false do a check on execute()
return $stmt->execute() === true ?  true  : false;

Also before returning the header 201, do a check on the register function to verify that it was true and not false..


问:
Data Mountaineer KCQL support for Json Arrays
i m new to kafka and i wanted to know whether KCQL queries has any support for json arrays?
I m planning to put data into influxdb
i will be getting stream of JSON arrays every second in the following format

```<code>[{"timestamp":"2017-10-24T12:43:39.359361982+05:30","namespace":"/intel/procfs/meminfo/high_free","data":0,"unit":"","tags":{"plugin_running_on":"AELAB110"},"version":4,"last_advertised_time":"2017-10-24T12:43:39.359519915+05:30"},{"timestamp":"2017-10-24T12:43:39.359406603+05:30","namespace":"/intel/procfs/meminfo/low_free","data":0,"unit":"","tags":{"plugin_running_on":"AELAB110"},"version":4,"last_advertised_time":"2017-10-24T12:43:39.359524142+05:30"},{"timestamp":"2017-10-24T12:43:39.359467873+05:30","namespace":"/intel/procfs/meminfo/shmem","data":35295232,"unit":"","tags":{"plugin_running_on":"AELAB110"},"version":4,"last_advertised_time":"2017-10-24T12:43:39.359526063+05:30"}]
</code>```

and i m trying to put this json array into influxdb.... is there any way for doing this?

答: You can ingest the data as-is into Kafka, and than use Kafka Streams and split each array into individual message via flatMap(). The result can than we exported to InfluxDB via Connect API.

Body:
i m new to kafka and i wanted to know whether KCQL queries has any support for json arrays?
I m planning to put data into influxdb
i will be getting stream of JSON arrays every second in the following format

[{"timestamp":"2017-10-24T12:43:39.359361982+05:30","namespace":"/intel/procfs/meminfo/high_free","data":0,"unit":"","tags":{"plugin_running_on":"AELAB110"},"version":4,"last_advertised_time":"2017-10-24T12:43:39.359519915+05:30"},{"timestamp":"2017-10-24T12:43:39.359406603+05:30","namespace":"/intel/procfs/meminfo/low_free","data":0,"unit":"","tags":{"plugin_running_on":"AELAB110"},"version":4,"last_advertised_time":"2017-10-24T12:43:39.359524142+05:30"},{"timestamp":"2017-10-24T12:43:39.359467873+05:30","namespace":"/intel/procfs/meminfo/shmem","data":35295232,"unit":"","tags":{"plugin_running_on":"AELAB110"},"version":4,"last_advertised_time":"2017-10-24T12:43:39.359526063+05:30"}]

and i m trying to put this json array into influxdb.... is there any way for doing this?


问:
How do I return the previous Sunday from 7 days ago using PHP date()?
Here is what I have so far:

```<code>$date = date('Y-m-d h:i:s', strtotime('-7 days'));
$start = date('Y-m-d h:i:s', strtotime($date,'previous Sunday'));
</code>```

When outputting $start, it returns: 1969-12-31 06:00:00

What am I doing wrong?

答:
Per php doc</p>

```<code>date('Y-m-d h:i:s', strtotime('last Sunday', $date));
</code>```

Body:
Here is what I have so far:

$date = date('Y-m-d h:i:s', strtotime('-7 days'));
$start = date('Y-m-d h:i:s', strtotime($date,'previous Sunday'));

When outputting $start, it returns: 1969-12-31 06:00:00

What am I doing wrong?

Body:
Per php doc

date('Y-m-d h:i:s', strtotime('last Sunday', $date));


问:
URL encoding in Swift
Im considering using Google Places API to fetch places nearby given coordinates. One example URL Google provides is the following: https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=500&type=restaurant&keyword=cruise&key=YOUR_API_KEY

What is the best and safest way to construct URL for such an endpoint? If I initialize URL with a String, do I need to worry about the numbers/coords being in string format? Does UrlComponents class handle this for me?

答:
You can use the URL(string: string) for this kind of url and set your values into the parameter. Like this:

```<code>let url = URL(string: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-\(lat),\(long)&radius=\(radius)&type=restaurant&keyword=cruise&key=\(apiKey)")
</code>```

If you for example want to hardcode the radius value you just do it like this instead:

```<code>let url = URL(string: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-\(lat),\(long)&radius=500&type=restaurant&keyword=cruise&key=\(apiKey)")
</code>```

Title: URL encoding in Swift

Body:
You can use the URL(string: string) for this kind of url and set your values into the parameter. Like this:

let url = URL(string: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-\(lat),\(long)&radius=\(radius)&type=restaurant&keyword=cruise&key=\(apiKey)")

If you for example want to hardcode the radius value you just do it like this instead:

let url = URL(string: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-\(lat),\(long)&radius=500&type=restaurant&keyword=cruise&key=\(apiKey)")


问:
Xamarin/Visual Studio on Mac - iPhone - Not able to list X509Store certificates
Environment
Device: . iPhone6s

Development Environment: .net Standard 1.5, Visual Studio on Mac Community Version 7.2.2 (build 7), Xamarin

I have the following code to get/list Certificates that are installed on my iPhone. I have not been successful so far – I get an empty collection when I use the code below.

I am running the code on the iPhone using a development provisioning profile.

I have 2 projects a portable Project and an iOS project. The Code listed below is in the Portable Class library.

```<code>using System;
using System.Collections.Generic;
using Xamarin.Forms;

using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

    X509Store paramStore

    paramStore  = new X509Store(StoreName.My, StoreLocation.CurrentUser)

    paramStore.Open(OpenFlags.ReadOnly);
    foreach (X509Certificate2 mCert in paramStore.Certificates)
    {
     numberOfCertificates = numberOfCertificates + 1;

    }
</code>```

I have also tried accessing StoreName.Root, StoreName.CertificateAuthority along with variations of OpenFlags e.g. .ReadWrite - same result no data.

Looking for input/thoughts.

答:
Unfortunately, it is not supported on iOS, here's the explanation from Apple side:

First, some clarifications:

Given that you’re talking about “client authentication” earlier, I presume you’re talking about digital identities rather than certificates.
  Note A digital identity is the combination of a private key and a certificate that contains the public key that matches that private key, and is what you need to present on the client side if you want the server to authenticate the client.

It seems that you care about digital identities installed via MDM.  Credentials installed that way are placed in an Apple keychain access group and, as such, are only accessible to Apple apps.  QA1745 Making Certificates and Keys Available To Your App discusses this in more detail.

Is there any way to check [whether a digital identity] is installed on [the device]?

Not in general.

More details, please refer to the related case in Apple Developer Forum: How to get Certificates list from iOS device?

Body:
Environment
Device: . iPhone6s

Development Environment: .net Standard 1.5, Visual Studio on Mac Community Version 7.2.2 (build 7), Xamarin

I have the following code to get/list Certificates that are installed on my iPhone. I have not been successful so far – I get an empty collection when I use the code below.

I am running the code on the iPhone using a development provisioning profile.

I have 2 projects a portable Project and an iOS project. The Code listed below is in the Portable Class library.

using System;
using System.Collections.Generic;
using Xamarin.Forms;

using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

    X509Store paramStore

    paramStore  = new X509Store(StoreName.My, StoreLocation.CurrentUser)

    paramStore.Open(OpenFlags.ReadOnly);
    foreach (X509Certificate2 mCert in paramStore.Certificates)
    {
     numberOfCertificates = numberOfCertificates + 1;

    }

I have also tried accessing StoreName.Root, StoreName.CertificateAuthority along with variations of OpenFlags e.g. .ReadWrite - same result no data.

Looking for input/thoughts.


问:
SQL How to restrict parent row from updates once child added?
I use foreign keys to prevent rows from being deleted in some SQL tables once a child uses the key.  However, now I want to be able to restrict any column of the parent table from updates once the child uses the key.

For example if the parent table is
[ID],[First Name],[Last Name]

And the child table is
[ListID],[Emp ID]

The foreign key prevents me from deleting or updating [ID] in the parent table however, it doesn't stop me from modifying [First Name].  Is there a way to set up foreign keys to prevent this?

Thanks.

答:
you could use instead of trigger.</p>

```<code>CREATE TABLE [dbo].[ParentTable]
(
ID INT, FirstName VARCHAR(50), LastName VARCHAR(50)
)
go

CREATE table ChildTable(EmpID INT)

go

CREATE TRIGGER [dbo].[ParentTable_InsteadOfUPDATE]
       ON [dbo].[ParentTable]
INSTEAD OF UPDATE
AS
BEGIN

       DECLARE @ID INT, @FirstName VARCHAR(50), @LastName VARCHAR(50)

       SELECT @ID = INSERTED.ID,
              @FirstName = INSERTED.FirstName,
              @LastName = INSERTED.LastName
       FROM INSERTED

    IF EXISTS(select top 1 1 from DBO.ChildTable Where EmpID=@ID )
    BEGIN

       IF UPDATE([ID]) OR UPDATE([FirstName]) OR UPDATE([LastName])
       BEGIN
              RAISERROR('These fields cannot be updated.', 16 ,1)
              ROLLBACK
       END
    END
    ELSE
    BEGIN
        Update [ParentTable] SET FirstName=@FirstName,LastName=@LastName Where ID=@ID;
    END
END
go
</code>```

Body:
you could use instead of trigger.

CREATE TABLE [dbo].[ParentTable]
(
ID INT, FirstName VARCHAR(50), LastName VARCHAR(50)
)
go

CREATE table ChildTable(EmpID INT)

go

CREATE TRIGGER [dbo].[ParentTable_InsteadOfUPDATE]
       ON [dbo].[ParentTable]
INSTEAD OF UPDATE
AS
BEGIN

       DECLARE @ID INT, @FirstName VARCHAR(50), @LastName VARCHAR(50)

       SELECT @ID = INSERTED.ID,
              @FirstName = INSERTED.FirstName,
              @LastName = INSERTED.LastName
       FROM INSERTED

    IF EXISTS(select top 1 1 from DBO.ChildTable Where EmpID=@ID )
    BEGIN

       IF UPDATE([ID]) OR UPDATE([FirstName]) OR UPDATE([LastName])
       BEGIN
              RAISERROR('These fields cannot be updated.', 16 ,1)
              ROLLBACK
       END
    END
    ELSE
    BEGIN
        Update [ParentTable] SET FirstName=@FirstName,LastName=@LastName Where ID=@ID;
    END
END
go


问:
How to add templates in meteor?
I am learning meteor framework. I am trying to render template but it throws this error:

```<code>Errors prevented startup:

While processing files with static-html (for target web.browser):
client/html/sidebar.html:1: Expected <head> or <body> tag
</code>```

my layout.html file is this:

```<code><body>

    {{> sidebar}}

</body>
</code>```

and sidebar.html file is this:

```<code><template name="sidebar">
        <h1>Hello</h1>
</template>
</code>```

Why its not rendering on layout.html??

答:
Looks like your issue is that you're using the static-html package and not blaze-html-templates, which means all the template code won't be processed

Do:

```<code>meteor remove static-html
meteor add blaze-html-templates
</code>```

In your project folder and see if that helps

Title: How to add templates in meteor?

Body:
I am learning meteor framework. I am trying to render template but it throws this error:

Errors prevented startup:

While processing files with static-html (for target web.browser):
client/html/sidebar.html:1: Expected  or  tag

my layout.html file is this:

    {{> sidebar}}

and sidebar.html file is this:

<template name="sidebar">

Hello

</template>

Why its not rendering on layout.html??

Body:
Looks like your issue is that you're using the static-html package and not blaze-html-templates, which means all the template code won't be processed

Do:

meteor remove static-html
meteor add blaze-html-templates

In your project folder and see if that helps


问:
How to use prepare_analogy_questions and check_analogy_accuracy functions in text2vec package?
Following code:

```<code>library(text2vec)
text8_file = "text8"
if (!file.exists(text8_file)) {
download.file("http://mattmahoney.net/dc/text8.zip", "text8.zip")
unzip ("text8.zip", files = "text8")
}
wiki = readLines(text8_file, n = 1, warn = FALSE)
# Create iterator over tokens
tokens <- space_tokenizer(wiki)
# Create vocabulary. Terms will be unigrams (simple words).
it = itoken(tokens, progressbar = FALSE)
vocab <- create_vocabulary(it)
vocab <- prune_vocabulary(vocab, term_count_min = 5L)
# Use our filtered vocabulary
vectorizer <- vocab_vectorizer(vocab)
# use window of 5 for context words
tcm <- create_tcm(it, vectorizer, skip_grams_window = 5L)
RcppParallel::setThreadOptions(numThreads = 4)
glove_model = GloVe$new(word_vectors_size = 50, vocabulary = vocab, x_max = 10, learning_rate = .25)
word_vectors_main = glove_model$fit_transform(tcm, n_iter = 20)
word_vectors_context = glove_model$components
word_vectors = word_vectors_main + t(word_vectors_context)
</code>```

causes error:

```<code>qlst <- prepare_analogy_questions("questions-words.txt", rownames(word_vectors))
> Error in (function (fmt, ...)  :
  invalid format '%d'; use format %s for character objects
</code>```

File questions-words.txt from word2vec sources https://github.com/nicholas-leonard/word2vec/blob/master/questions-words.txt

答:
This was a small bug in information message formatting (after introduction of futille.logger). Just fixed it and pushed to github.

You can install updated version of the package with devtools::install_github("dselivanov/text2vec"

Body:
Following code:

library(text2vec)
text8_file = "text8"
if (!file.exists(text8_file)) {
download.file("http://mattmahoney.net/dc/text8.zip", "text8.zip")
unzip ("text8.zip", files = "text8")
}
wiki = readLines(text8_file, n = 1, warn = FALSE)
# Create iterator over tokens
tokens <- space_tokenizer(wiki)
# Create vocabulary. Terms will be unigrams (simple words).
it = itoken(tokens, progressbar = FALSE)
vocab <- create_vocabulary(it)
vocab <- prune_vocabulary(vocab, term_count_min = 5L)
# Use our filtered vocabulary
vectorizer <- vocab_vectorizer(vocab)
# use window of 5 for context words
tcm <- create_tcm(it, vectorizer, skip_grams_window = 5L)
RcppParallel::setThreadOptions(numThreads = 4)
glove_model = GloVe$new(word_vectors_size = 50, vocabulary = vocab, x_max = 10, learning_rate = .25)
word_vectors_main = glove_model$fit_transform(tcm, n_iter = 20)
word_vectors_context = glove_model$components
word_vectors = word_vectors_main + t(word_vectors_context)

causes error:

qlst <- prepare_analogy_questions("questions-words.txt", rownames(word_vectors))
> Error in (function (fmt, ...)  :
  invalid format '%d'; use format %s for character objects

File questions-words.txt from word2vec sources https://github.com/nicholas-leonard/word2vec/blob/master/questions-words.txt


问:
C# Reflection Property.GetValue() Problem
I am having a problem with the following code:

```<code>int errorCount = 0;
foreach (var cinf in client.GetType().GetProperties())
{
    var vinf = viewModel.GetType().GetProperty(cinf.Name);
    if (vinf != null)
    {
        if (cinf.GetValue(client, null) != vinf.GetValue(viewModel, null))
        {
            errorCount++;
        }
    }
}
</code>```

It's for an automated test to see whether mapping a model object from a DTO has worked.  If I use the more cumbersome approch of writing this for each property:

```<code>Assert.AreEqual(viewModel.ClientCompanyID, client.ClientCompanyID);
</code>```

This works fine.

The problem is: the reflection code evaluates "if val1 != val2" statement incorrectly (or so it seems).  If I step through this code, the evaluation basically says "1 does not equal 1", and incorrectly adds an error.  Furthermore, if I test this with this code, I get the same seemingly false result:

```<code>var clientEx = client.GetType().GetProperty("ClientCompanyID");
var viewModelEx = viewModel.GetType().GetProperty("ClientCompanyID");
var clientVal = clientEx.GetValue(client, null);
var viewModelVal = viewModelEx.GetValue(viewModel, null);
bool test = (clientVal == viewModelVal);
</code>```

The bool returns false even when, stepping through the code, clientVal = 1 and viewModelVal = 1.  See attached picture.

Any help with this would be greatly appreciated!

Thanks guys.

Tim.

EDIT:  Could have given you all the answer.  Glad it was simple in the end.  Thanks alot for your help.  Cheers.

答:
You're comparing to different boxed integers by reference.

Change it to

```<code>if (!Equals(cinf.GetValue(client, null), vinf.GetValue(viewModel, null))
</code>```

This calls the static Object.Equals method, which will call the virtual Object.Equals method (after checking for null) to compare objects by value.

You'll see the same issue for strings.

Body:
I am having a problem with the following code:

int errorCount = 0;
foreach (var cinf in client.GetType().GetProperties())
{
    var vinf = viewModel.GetType().GetProperty(cinf.Name);
    if (vinf != null)
    {
        if (cinf.GetValue(client, null) != vinf.GetValue(viewModel, null))
        {
            errorCount++;
        }
    }
}

It's for an automated test to see whether mapping a model object from a DTO has worked.  If I use the more cumbersome approch of writing this for each property:

Assert.AreEqual(viewModel.ClientCompanyID, client.ClientCompanyID);

This works fine.

The problem is: the reflection code evaluates "if val1 != val2" statement incorrectly (or so it seems).  If I step through this code, the evaluation basically says "1 does not equal 1", and incorrectly adds an error.  Furthermore, if I test this with this code, I get the same seemingly false result:

var clientEx = client.GetType().GetProperty("ClientCompanyID");
var viewModelEx = viewModel.GetType().GetProperty("ClientCompanyID");
var clientVal = clientEx.GetValue(client, null);
var viewModelVal = viewModelEx.GetValue(viewModel, null);
bool test = (clientVal == viewModelVal);

The bool returns false even when, stepping through the code, clientVal = 1 and viewModelVal = 1.  See attached picture.

Any help with this would be greatly appreciated!

Thanks guys.

Tim.

EDIT:  Could have given you all the answer.  Glad it was simple in the end.  Thanks alot for your help.  Cheers.

Body:
You're comparing to different boxed integers by reference.

Change it to

if (!Equals(cinf.GetValue(client, null), vinf.GetValue(viewModel, null))

This calls the static Object.Equals method, which will call the virtual Object.Equals method (after checking for null) to compare objects by value.

You'll see the same issue for strings.


问:
Replace string that is separated by whitespace or other special character in PHP
I need to find a way to find part of the string in text and to replace it with ***

For example, I have text "Jumping fox jumps around the box"
in normal cases, I would use:

preg_replace('/\b(fox)\b/i', '****', "fox");

but I want to cover cases when we have text "Jumping f.o.x jumps around the box"
or "Jumping f o x jumps around the box"

So basically, I would need regex to support that kind of searches... to cover more special characters is even better

答:
This is final function.</p>

```<code>if (! function_exists('preg_replace_word')) {

    function preg_replace_word($search, $replace, $string)
    {
        $ignore = '[\s\._-]*';
        $regex = '/\b' . join($ignore, str_split($search)) . '\b/i';
        return preg_replace($regex, $replace, $string);
    }
}
</code>```

Body:
This is final function.

if (! function_exists('preg_replace_word')) {

    function preg_replace_word($search, $replace, $string)
    {
        $ignore = '[\s\._-]*';
        $regex = '/\b' . join($ignore, str_split($search)) . '\b/i';
        return preg_replace($regex, $replace, $string);
    }
}


问:
Java - TCP - Multithread server - How to handle multiple clients connection?
I'm doing a simple login/signup module using TCP with multithreaded server. I want to make my server possible to handle multiple access from client. My first idea was to use a list of client socket to keep track of which client is connecting: accept() a socket - if it's in the list then find it the list and pass it to function to proceed - if it's not, then add it to the list then pass it to function to proceed. It works for the first time access, but in the second time, it's jammed and the client never receive the result. Could you tell me what did I do wrong and what should I do to handle this kind of problem? Thanks!

Server run() method:

```<code>@Override
public void run() {
    Socket socket = new Socket();

    try {
        Socket clientSocket = myServer.accept();

        if (!listSocket.contains(clientSocket)) {
            socket = clientSocket;
            listSocket.add(clientSocket);
        } else {
            for (Socket s : listSocket) {
                if (s == clientSocket) {
                    socket = clientSocket;
                    break;
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    while (true) {
        ReceiveObject(socket);
    }
}
</code>```

ReceiveObject() method:

```<code>// Receive an object[2]
// the object[0] contains Account object
// the object[1] contains Customer object
// if the object[0] is not null and the object[1] is null => this is a login request
// if both object[0] and object[1] are not null => signup request

public void ReceiveObject(Socket clientSocket) {
    try {
        ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());
        Object o = ois.readObject();

        if (o instanceof Object[]) {
            Object[] arr = (Object[]) o;
            if (arr[0] != null && arr[0] instanceof Account && arr[1] == null) {
                Account acc = (Account) arr[0];
                if (CheckAccountExist(acc)) {
                    SendResult("OK", clientSocket);
                } else {
                    SendResult("FAILED", clientSocket);
                }
            } else if (arr[0] != null && arr[1] != null && arr[0] instanceof Account && arr[1] instanceof Customer) {
                Account acc = (Account) arr[0];
                Customer cus = (Customer) arr[1];

                String result = "";

                if (!CheckAccountExist(acc)) {
                    result = "OK";

                    if (AddAccount(acc)) {
                        if (!CheckCustomerExist(cus)) {
                            if (AddCustomer(cus)) {
                                SendResult(result, clientSocket);
                            } else {
                                result = "FAILED";
                                SendResult(result, clientSocket);
                            }
                        }
                    } else {
                        result = "FAILED";
                        SendResult(result, clientSocket);
                    }
                } else {
                    result = "FAILED";
                    SendResult(result, clientSocket);
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
</code>```

答:
My first idea was to use a list of client socket to keep track of which client is connecting: accept() a socket - if it's in the list then find it the list and pass it to function to proceed - if it's not, then add it to the list then pass it to function to proceed.

Why? It won't be in the list. It's a new connection. It can't possibly be in the list. So, therefore, what exactly is the list for? You don't need it. Just start a new and completely independent thread per accepted socket.

It works for the first time access, but in the second time, it's jammed and the client never receive the result. Could you tell me what did I do wrong and what should I do to handle this kind of problem? Thanks!

Throw it away and have a good look at the Custom Networking section of the Java Tutorial.

NB You should use the same object streams for the life of the socket. You shouldn't need methods with a Socket parameter: the Socket should be a member variable of the Runnable class that handles the connection. So should the object streams.

Body:
I'm doing a simple login/signup module using TCP with multithreaded server. I want to make my server possible to handle multiple access from client. My first idea was to use a list of client socket to keep track of which client is connecting: accept() a socket - if it's in the list then find it the list and pass it to function to proceed - if it's not, then add it to the list then pass it to function to proceed. It works for the first time access, but in the second time, it's jammed and the client never receive the result. Could you tell me what did I do wrong and what should I do to handle this kind of problem? Thanks!

Server run() method:

@Override
public void run() {
    Socket socket = new Socket();

    try {
        Socket clientSocket = myServer.accept();

        if (!listSocket.contains(clientSocket)) {
            socket = clientSocket;
            listSocket.add(clientSocket);
        } else {
            for (Socket s : listSocket) {
                if (s == clientSocket) {
                    socket = clientSocket;
                    break;
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    while (true) {
        ReceiveObject(socket);
    }
}

ReceiveObject() method:

// Receive an object[2]
// the object[0] contains Account object
// the object[1] contains Customer object
// if the object[0] is not null and the object[1] is null => this is a login request
// if both object[0] and object[1] are not null => signup request

public void ReceiveObject(Socket clientSocket) {
    try {
        ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());
        Object o = ois.readObject();

        if (o instanceof Object[]) {
            Object[] arr = (Object[]) o;
            if (arr[0] != null && arr[0] instanceof Account && arr[1] == null) {
                Account acc = (Account) arr[0];
                if (CheckAccountExist(acc)) {
                    SendResult("OK", clientSocket);
                } else {
                    SendResult("FAILED", clientSocket);
                }
            } else if (arr[0] != null && arr[1] != null && arr[0] instanceof Account && arr[1] instanceof Customer) {
                Account acc = (Account) arr[0];
                Customer cus = (Customer) arr[1];

                String result = "";

                if (!CheckAccountExist(acc)) {
                    result = "OK";

                    if (AddAccount(acc)) {
                        if (!CheckCustomerExist(cus)) {
                            if (AddCustomer(cus)) {
                                SendResult(result, clientSocket);
                            } else {
                                result = "FAILED";
                                SendResult(result, clientSocket);
                            }
                        }
                    } else {
                        result = "FAILED";
                        SendResult(result, clientSocket);
                    }
                } else {
                    result = "FAILED";
                    SendResult(result, clientSocket);
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}