问:
How to retrive value using viper with golang from intellij
I wanna retrive variant a from intellij ,but failed.

```<code>func main(){
    a:=viper.GetString("a")
    fmt.println(a)
}
</code>```

答: You need to add -a=2, just as you would add any normal parameter to the command line

Body:
I wanna retrive variant a from intellij ,but failed.

func main(){
    a:=viper.GetString("a")
    fmt.println(a)
}


来源: stackexchange

问:
How to overlay HTML text/buttons on three.js?
Ok, very new to three.js here but I am trying to achieve what Google has with https://beinternetawesome.withgoogle.com/interland

See - they have their FULL SCREEN Three.js scene and their text, buttons (which are clearly HTML divs, not generated via JS) overlaid perfectly on top.

I have looked at
https://discourse.threejs.org/t/trying-to-overlay-a-button-and-text-on-top-of-a-three-js-scene/390/2

and similar Questions but can't understand the proper way to do this. I don't want to generate my UI elements in Three.js - I just want to use HTML.

What I have so far is I generate my Three.js canvas and add it to my document so that it gets and STAYS the full width/height of my window:

```<code>var controls, camera, renderer, scene, container, w, h;
renderer    = new THREE.WebGLRenderer()
// container = document.getElementById('canvas');
container = window;
w = container.innerWidth;
h = container.innerHeight;
renderer.setSize(w, h)
renderer.setPixelRatio( window.devicePixelRatio );
document.body.appendChild(renderer.domElement);
</code>```

And then with my existing HTML:

```<code><body>
    <div id="ui">
    <p id="message">Test to change</p>
</div>
</code>```

I get the UI div stuck on top, no matter how I play with the CSS or the z index of the UI div:

How can I achieve the Google effect with HTML overlaid over my three.js scene? What am I doing wrong?

I need my canvas to fill the whole window just as Google's does and can't achieve that it seems making the canvas HTML element beforehand and trying to attach everything in JS.

答:
Creativity is up to you, as there are many ways to achieve the desired result.

You can start from looking at the source code of examples from the official web site of Three.js. There you can see how the info section of an example sets on a web page.

var buttons = document.getElementsByTagName("button");
for (let i = 0; i < buttons.length; i++) {
  buttons[i].addEventListener("click", onButtonClick, false);
};

function onButtonClick(event) {
  alert(event.target.id);
}

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var controls = new THREE.OrbitControls(camera, renderer.domElement);

var geometry = new THREE.BoxGeometry(1, 1, 1);
var material = new THREE.MeshBasicMaterial({
  color: 0x00ff00,
  wireframe: true
});
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);

camera.position.z = 5;

var animate = function() {
  requestAnimationFrame(animate);
  renderer.render(scene, camera);
};

animate();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  overflow: hidden;
  margin: 0;
}

.ui {
  position: absolute;
}

button{
  margin: 20px;
}</code>```

Info header

<button style="top:0" id="fire" class="ui">Fire</button>
<button style="bottom:0" id="spell" class="ui">Spell</button>
<button style="right:0" id="health" class="ui">Health</button>
<button style="right:0; bottom:0;" id="shield" class="ui">Shield</button>```

ContentLicense: CC BY-SA 3.0

Body:
Ok, very new to three.js here but I am trying to achieve what Google has with https://beinternetawesome.withgoogle.com/interland

See - they have their FULL SCREEN Three.js scene and their text, buttons (which are clearly HTML divs, not generated via JS) overlaid perfectly on top.

I have looked at
https://discourse.threejs.org/t/trying-to-overlay-a-button-and-text-on-top-of-a-three-js-scene/390/2

and similar Questions but can't understand the proper way to do this. I don't want to generate my UI elements in Three.js - I just want to use HTML.

What I have so far is I generate my Three.js canvas and add it to my document so that it gets and STAYS the full width/height of my window:

var controls, camera, renderer, scene, container, w, h;
renderer    = new THREE.WebGLRenderer()
// container = document.getElementById('canvas');
container = window;
w = container.innerWidth;
h = container.innerHeight;
renderer.setSize(w, h)
renderer.setPixelRatio( window.devicePixelRatio );
document.body.appendChild(renderer.domElement);

And then with my existing HTML:

Test to change

I get the UI div stuck on top, no matter how I play with the CSS or the z index of the UI div:

How can I achieve the Google effect with HTML overlaid over my three.js scene? What am I doing wrong?

I need my canvas to fill the whole window just as Google's does and can't achieve that it seems making the canvas HTML element beforehand and trying to attach everything in JS.

Body:
Creativity is up to you, as there are many ways to achieve the desired result.

You can start from looking at the source code of examples from the official web site of Three.js. There you can see how the info section of an example sets on a web page.

var buttons = document.getElementsByTagName("button");
for (let i = 0; i < buttons.length; i++) {
  buttons[i].addEventListener("click", onButtonClick, false);
};

function onButtonClick(event) {
  alert(event.target.id);
}

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var controls = new THREE.OrbitControls(camera, renderer.domElement);

var geometry = new THREE.BoxGeometry(1, 1, 1);
var material = new THREE.MeshBasicMaterial({
  color: 0x00ff00,
  wireframe: true
});
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);

camera.position.z = 5;

var animate = function() {
  requestAnimationFrame(animate);
  renderer.render(scene, camera);
};

animate();

body {
  overflow: hidden;
  margin: 0;
}

.ui {
  position: absolute;
}

button{
  margin: 20px;
}

<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>

<div style="width:100%;height:50px;text-align: center; color:white;" class="ui">Info header</div>
<button style="top:0" id="fire" class="ui">Fire</button>
<button style="bottom:0" id="spell" class="ui">Spell</button>
<button style="right:0" id="health" class="ui">Health</button>
<button style="right:0; bottom:0;" id="shield" class="ui">Shield</button>

ContentLicense: CC BY-SA 4.0


问:
SOLR search is not working with @ symbol
When we try to search Solr with @ in the term it does not return any result.

Suppose in there is an entry with text abc@ac.in.

```<code>When I search abc@ac.in it works.
When I search abc@ it works.
When I search abc@a it FAILS and returns no result.
</code>```

Can anyone please suggest?

答:
Most likely, for this field, you're using solr.StandardTokenizerFactory, which is splitting text into tokens by different symbols, and one of them is @, so if you put abc@ac.in you will get something like abc ac in as a tokens.

For emails, I would recommend to use solr.KeywordTokenizerFactory, which is saving tokens as it is. It could be fine, if your field contains just email address.

But, if your field is a text field, where you want to preserve emails - you should use solr.ClassicTokenizerFactory, which recognizes email addresses and domain names and do not split on them

Body:
When we try to search Solr with @ in the term it does not return any result.

Suppose in there is an entry with text abc@ac.in.

When I search abc@ac.in it works.
When I search abc@ it works.
When I search abc@a it FAILS and returns no result.

Can anyone please suggest?


问:
Resolving relative paths when using ph-schematron
I'm using ph-schematron, a Java library that validates XML documents via ISO Schematron:

This library provides 2 ways of XML document validation:

Validation via XSLT

Validation via Pure Schematron

I would love to use the second type, but my Schematron files contain XSLT functions so we MUST use the validation using XSLT and not the pure one.

I have a validation method that has two input paramters:

The XSLT representation of the schematron file

The XML document to validate

Now my XSLT file contains lines like this:

```<code><xsl:when test="count(hl7:confidentialityCode[concat(@code,@codeSystem)=doc('include/voc-1.3.6.1.4.1.12559.11.10.1.3.1.42.31-DYNAMIC.xml')//valueSet[1]/conceptList/concept/concat(@code,@codeSystem) or @nullFlavor])>=1" />
</code>```

And the doc function looks for a folder called 'include' in the home directory of my project instead of the folder relative to the XSLT document (which would be more logic).

Now I got exceptions like:

```<code>java.io.FileNotFoundException: C:\LocalData\Development\projectname\include\voc-1.3.6.1.4.1.12559.11.10.1.3.1.42.31-DYNAMIC.xml (The system cannot find the path specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at sun.net.www.protocol.file.FileURLConnection.connect(FileURLConnection.java:90)
at sun.net.www.protocol.file.FileURLConnection.getInputStream(FileURLConnection.java:188)
at org.apache.xerces.impl.XMLEntityManager.setupCurrentEntity(Unknown Source)
at org.apache.xerces.impl.XMLVersionDetector.determineDocVersion(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at net.sf.saxon.event.Sender.sendSAXSource(Sender.java:451)
at net.sf.saxon.event.Sender.send(Sender.java:153)
at net.sf.saxon.functions.DocumentFn.makeDoc(DocumentFn.java:330)
at net.sf.saxon.functions.Doc.call(Doc.java:138)
at net.sf.saxon.functions.Doc.call(Doc.java:24)
at net.sf.saxon.expr.FunctionCall.iterate(FunctionCall.java:546)
at net.sf.saxon.expr.Expression.evaluateItem(Expression.java:773)
at net.sf.saxon.expr.SimpleStepExpression.iterate(SimpleStepExpression.java:108)
at net.sf.saxon.expr.SlashExpression.iterate(SlashExpression.java:868)
at net.sf.saxon.expr.SlashExpression.iterate(SlashExpression.java:868)
at net.sf.saxon.expr.SlashExpression.iterate(SlashExpression.java:868)
at net.sf.saxon.expr.SlashExpression.iterate(SlashExpression.java:868)
at net.sf.saxon.value.MemoClosure.iterate(MemoClosure.java:109)
at net.sf.saxon.expr.VariableReference.iterate(VariableReference.java:482)
at net.sf.saxon.expr.GeneralComparison.effectiveBooleanValue(GeneralComparison.java:621)
at net.sf.saxon.expr.OrExpression.effectiveBooleanValue(OrExpression.java:131)
at net.sf.saxon.expr.FilterIterator$NonNumeric.matches(FilterIterator.java:198)
at net.sf.saxon.expr.FilterIterator.getNextMatchingItem(FilterIterator.java:81)
at net.sf.saxon.expr.FilterIterator.next(FilterIterator.java:64)
at net.sf.saxon.functions.Exists$1.effectiveBooleanValue(Exists.java:67)
at net.sf.saxon.expr.instruct.Choose.choose(Choose.java:865)
at net.sf.saxon.expr.instruct.Choose.processLeavingTail(Choose.java:840)
at net.sf.saxon.expr.instruct.Block.processLeavingTail(Block.java:653)
at net.sf.saxon.expr.instruct.TemplateRule.applyLeavingTail(TemplateRule.java:353)
at net.sf.saxon.trans.Mode.applyTemplates(Mode.java:456)
at net.sf.saxon.trans.TextOnlyCopyRuleSet.process(TextOnlyCopyRuleSet.java:65)
at net.sf.saxon.trans.Mode.applyTemplates(Mode.java:433)
at net.sf.saxon.expr.instruct.ApplyTemplates.apply(ApplyTemplates.java:298)
at net.sf.saxon.expr.instruct.ApplyTemplates.processLeavingTail(ApplyTemplates.java:255)
at net.sf.saxon.expr.instruct.Block.processLeavingTail(Block.java:653)
at net.sf.saxon.expr.instruct.Instruction.process(Instruction.java:149)
at net.sf.saxon.expr.instruct.ElementCreator.processLeavingTail(ElementCreator.java:364)
at net.sf.saxon.expr.instruct.ElementCreator.processLeavingTail(ElementCreator.java:311)
at net.sf.saxon.expr.instruct.TemplateRule.applyLeavingTail(TemplateRule.java:353)
at net.sf.saxon.trans.Mode.applyTemplates(Mode.java:456)
at net.sf.saxon.Controller.transformDocument(Controller.java:2321)
at net.sf.saxon.Controller.transform(Controller.java:1892)
at net.sf.saxon.s9api.XsltTransformer.transform(XsltTransformer.java:579)
at net.sf.saxon.jaxp.TransformerImpl.transform(TransformerImpl.java:185)
at com.helger.schematron.xslt.AbstractSchematronXSLTBasedResource.applySchematronValidation(AbstractSchematronXSLTBasedResource.java:273)
at com.helger.schematron.xslt.AbstractSchematronXSLTBasedResource.applySchematronValidationToSVRL(AbstractSchematronXSLTBasedResource.java:288)
at com.helger.schematron.xslt.AbstractSchematronXSLTBasedResource.getSchematronValidity(AbstractSchematronXSLTBasedResource.java:197)
at com.helger.schematron.AbstractSchematronResource.getSchematronValidity(AbstractSchematronResource.java:210)
at epsos.ccd.posam.tm.util.NewSchematronValidator.doValidate(NewSchematronValidator.java:47)
at epsos.ccd.posam.tm.util.NewSchematronValidator.validate(NewSchematronValidator.java:39)
at epsos.ccd.posam.tm.util.SchematronValidatorTest.testValidationNew(SchematronValidatorTest.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
</code>```

How can I force the doc function to look at the include folder in the same directory as the XSLT file and not in the root of my Java Project?

答:
I found a solution:

I defined my own implementation of an URIResolver, that will be used as an XSLT processor internally by ph-schematron:

```<code>class ClasspathResourceURIResolver implements URIResolver {

    @Override
    public Source resolve(String href, String base) throws TransformerException {
        return new StreamSource(this.getClass().getClassLoader().getResourceAsStream(href));
}
</code>```

This URIResolver is then set to the SchematronResourceXSLT:

```<code>IReadableResource readableResource = new ReadableResourceInputStream(new FileInputStream(schematronFile));
SchematronResourceXSLT schematronResourceXslt = new SchematronResourceXSLT(readableResource);
schematronResourceXslt.setURIResolver(new ClasspathResourceURIResolver());
</code>```

Next we can check if the schematron file is valid and check the validity of an XML document:

```<code> if (!schematronResourceXslt.isValidSchematron())
        throw new IllegalArgumentException ("Invalid Schematron!");
 final StreamSource xmlSource = new StreamSource(xmlFile);
 final EValidity schematronValidity = schematronResourceXslt.getSchematronValidity(xmlSource);
</code>```

And now he manages to retrieve the relative paths in the XSLT file.

Hope this can help someone else

Body:
I'm using ph-schematron, a Java library that validates XML documents via ISO Schematron:

This library provides 2 ways of XML document validation:

Validation via XSLT

Validation via Pure Schematron

I would love to use the second type, but my Schematron files contain XSLT functions so we MUST use the validation using XSLT and not the pure one.

I have a validation method that has two input paramters:

The XSLT representation of the schematron file

The XML document to validate

Now my XSLT file contains lines like this:

<xsl:when test="count(hl7:confidentialityCode[concat(@code,@codeSystem)=doc('include/voc-1.3.6.1.4.1.12559.11.10.1.3.1.42.31-DYNAMIC.xml')//valueSet[1]/conceptList/concept/concat(@code,@codeSystem) or @nullFlavor])>=1" />

And the doc function looks for a folder called 'include' in the home directory of my project instead of the folder relative to the XSLT document (which would be more logic).

Now I got exceptions like:

java.io.FileNotFoundException: C:\LocalData\Development\projectname\include\voc-1.3.6.1.4.1.12559.11.10.1.3.1.42.31-DYNAMIC.xml (The system cannot find the path specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at sun.net.www.protocol.file.FileURLConnection.connect(FileURLConnection.java:90)
at sun.net.www.protocol.file.FileURLConnection.getInputStream(FileURLConnection.java:188)
at org.apache.xerces.impl.XMLEntityManager.setupCurrentEntity(Unknown Source)
at org.apache.xerces.impl.XMLVersionDetector.determineDocVersion(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at net.sf.saxon.event.Sender.sendSAXSource(Sender.java:451)
at net.sf.saxon.event.Sender.send(Sender.java:153)
at net.sf.saxon.functions.DocumentFn.makeDoc(DocumentFn.java:330)
at net.sf.saxon.functions.Doc.call(Doc.java:138)
at net.sf.saxon.functions.Doc.call(Doc.java:24)
at net.sf.saxon.expr.FunctionCall.iterate(FunctionCall.java:546)
at net.sf.saxon.expr.Expression.evaluateItem(Expression.java:773)
at net.sf.saxon.expr.SimpleStepExpression.iterate(SimpleStepExpression.java:108)
at net.sf.saxon.expr.SlashExpression.iterate(SlashExpression.java:868)
at net.sf.saxon.expr.SlashExpression.iterate(SlashExpression.java:868)
at net.sf.saxon.expr.SlashExpression.iterate(SlashExpression.java:868)
at net.sf.saxon.expr.SlashExpression.iterate(SlashExpression.java:868)
at net.sf.saxon.value.MemoClosure.iterate(MemoClosure.java:109)
at net.sf.saxon.expr.VariableReference.iterate(VariableReference.java:482)
at net.sf.saxon.expr.GeneralComparison.effectiveBooleanValue(GeneralComparison.java:621)
at net.sf.saxon.expr.OrExpression.effectiveBooleanValue(OrExpression.java:131)
at net.sf.saxon.expr.FilterIterator$NonNumeric.matches(FilterIterator.java:198)
at net.sf.saxon.expr.FilterIterator.getNextMatchingItem(FilterIterator.java:81)
at net.sf.saxon.expr.FilterIterator.next(FilterIterator.java:64)
at net.sf.saxon.functions.Exists$1.effectiveBooleanValue(Exists.java:67)
at net.sf.saxon.expr.instruct.Choose.choose(Choose.java:865)
at net.sf.saxon.expr.instruct.Choose.processLeavingTail(Choose.java:840)
at net.sf.saxon.expr.instruct.Block.processLeavingTail(Block.java:653)
at net.sf.saxon.expr.instruct.TemplateRule.applyLeavingTail(TemplateRule.java:353)
at net.sf.saxon.trans.Mode.applyTemplates(Mode.java:456)
at net.sf.saxon.trans.TextOnlyCopyRuleSet.process(TextOnlyCopyRuleSet.java:65)
at net.sf.saxon.trans.Mode.applyTemplates(Mode.java:433)
at net.sf.saxon.expr.instruct.ApplyTemplates.apply(ApplyTemplates.java:298)
at net.sf.saxon.expr.instruct.ApplyTemplates.processLeavingTail(ApplyTemplates.java:255)
at net.sf.saxon.expr.instruct.Block.processLeavingTail(Block.java:653)
at net.sf.saxon.expr.instruct.Instruction.process(Instruction.java:149)
at net.sf.saxon.expr.instruct.ElementCreator.processLeavingTail(ElementCreator.java:364)
at net.sf.saxon.expr.instruct.ElementCreator.processLeavingTail(ElementCreator.java:311)
at net.sf.saxon.expr.instruct.TemplateRule.applyLeavingTail(TemplateRule.java:353)
at net.sf.saxon.trans.Mode.applyTemplates(Mode.java:456)
at net.sf.saxon.Controller.transformDocument(Controller.java:2321)
at net.sf.saxon.Controller.transform(Controller.java:1892)
at net.sf.saxon.s9api.XsltTransformer.transform(XsltTransformer.java:579)
at net.sf.saxon.jaxp.TransformerImpl.transform(TransformerImpl.java:185)
at com.helger.schematron.xslt.AbstractSchematronXSLTBasedResource.applySchematronValidation(AbstractSchematronXSLTBasedResource.java:273)
at com.helger.schematron.xslt.AbstractSchematronXSLTBasedResource.applySchematronValidationToSVRL(AbstractSchematronXSLTBasedResource.java:288)
at com.helger.schematron.xslt.AbstractSchematronXSLTBasedResource.getSchematronValidity(AbstractSchematronXSLTBasedResource.java:197)
at com.helger.schematron.AbstractSchematronResource.getSchematronValidity(AbstractSchematronResource.java:210)
at epsos.ccd.posam.tm.util.NewSchematronValidator.doValidate(NewSchematronValidator.java:47)
at epsos.ccd.posam.tm.util.NewSchematronValidator.validate(NewSchematronValidator.java:39)
at epsos.ccd.posam.tm.util.SchematronValidatorTest.testValidationNew(SchematronValidatorTest.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

How can I force the doc function to look at the include folder in the same directory as the XSLT file and not in the root of my Java Project?

Body:
I found a solution:

I defined my own implementation of an URIResolver, that will be used as an XSLT processor internally by ph-schematron:

class ClasspathResourceURIResolver implements URIResolver {

    @Override
    public Source resolve(String href, String base) throws TransformerException {
        return new StreamSource(this.getClass().getClassLoader().getResourceAsStream(href));
}

This URIResolver is then set to the SchematronResourceXSLT:

IReadableResource readableResource = new ReadableResourceInputStream(new FileInputStream(schematronFile));
SchematronResourceXSLT schematronResourceXslt = new SchematronResourceXSLT(readableResource);
schematronResourceXslt.setURIResolver(new ClasspathResourceURIResolver());

Next we can check if the schematron file is valid and check the validity of an XML document:

 if (!schematronResourceXslt.isValidSchematron())
        throw new IllegalArgumentException ("Invalid Schematron!");
 final StreamSource xmlSource = new StreamSource(xmlFile);
 final EValidity schematronValidity = schematronResourceXslt.getSchematronValidity(xmlSource);

And now he manages to retrieve the relative paths in the XSLT file.

Hope this can help someone else


问:
How do get optional parameter value using javascript in MVC
I have following url

http://MySite.com/MyGame/Play/1

Now i wanted to get id 1 (e.g. 1 which is after play) of url using javascript or jquery.

I am using MVC 4.0 C# application.

答:
Adeel and Jeff's solutions will fail if there is no id - like in my case. So i extended it a little bit for my usage. GetIdIfExists function will return the id if there is one. Else, it will return null.

EDIT: Assuming id is always numeric.

```<code>function isNumeric(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

function GetIdIfExists() {
    var parts = document.location.href.split("/");
    var id = parts[parts.length - 1];

    if (isNumeric(id)) {
        return parseInt(id);
    } else {
        return null;
    }
}
</code>```

Results:

```<code>//url = https://stackoverflow.com/questions/15761950/how-do-get-optional-parameter-value-using-javascript-in-mvc
> GetIdIfExists()
< null

//url = https://stackoverflow.com/questions/15761950/how-do-get-optional-parameter-value-using-javascript-in-mvc/0
> GetIdIfExists()
< 0
</code>```

Body:
Adeel and Jeff's solutions will fail if there is no id - like in my case. So i extended it a little bit for my usage. GetIdIfExists function will return the id if there is one. Else, it will return null.

EDIT: Assuming id is always numeric.

function isNumeric(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

function GetIdIfExists() {
    var parts = document.location.href.split("/");
    var id = parts[parts.length - 1];

    if (isNumeric(id)) {
        return parseInt(id);
    } else {
        return null;
    }
}

Results:

//url = https://stackoverflow.com/questions/15761950/how-do-get-optional-parameter-value-using-javascript-in-mvc
> GetIdIfExists()
< null

//url = https://stackoverflow.com/questions/15761950/how-do-get-optional-parameter-value-using-javascript-in-mvc/0
> GetIdIfExists()
< 0


问:
How to increment date up to a certain date for inserting data?
I have a prepared statement like the one below inserting it to a postgres database:

```<code> String InsertQuery="INSERT INTO public.user_daily_activity (id,user,day,time)
 values (?,?,?,?)";
 String date="2017-11-16";
try{
   jtmTemplate.update(InsertQuery, new PreparedStatementSetter() {
   public void setValues(PreparedStatement preparedStatement) throws SQLException {
   preparedStatement.setInt(1, id);
   preparedStatement.setString(2, user);
   preparedStatement.setDate(3, java.sql.Date.valueOf(date));
   preparedStatement.setInt(4, time);

}
</code>```

So now depending on the date I need to increment it from the start date to November 30. For example if date="2017-11-16" then I need to insert from "2017-11-16" to "2017-11-30". If date="2017-11-27" then I need to insert from "2017-11-27" to  "2017-11-30".

Any help is appreciated.

答:
Well, here you have a solution using pre-java8 Date and Calendar:

```<code>public void incrementDate() {
    int dayLimit = 30;
    // month is zero-based index
    int monthLimit = 10;
    String startStringDate = "2017-11-16";
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Calendar calendar = Calendar.getInstance();
    Date startDate;
    java.sql.Date sqlDate;
    try {
        startDate = dateFormat.parse(startStringDate);
        calendar.setTime(startDate);
        while(calendar.get(Calendar.DAY_OF_MONTH) <= dayLimit && calendar.get(Calendar.MONTH) <= monthLimit) {
            sqlDate = new java.sql.Date(startDate.getTime());
            // here just use sqlDate in your prepared statement
            //...
            //e.g. preparedStatement.setDate(3, sqlDate);
            // ...
            System.out.println("Using sql date : " + sqlDate);
            calendar.setTime(startDate);
            calendar.add(Calendar.DATE, 1);
            startDate = calendar.getTime();
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
}
</code>```

Body:
I have a prepared statement like the one below inserting it to a postgres database:

 String InsertQuery="INSERT INTO public.user_daily_activity (id,user,day,time)
 values (?,?,?,?)";
 String date="2017-11-16";
try{
   jtmTemplate.update(InsertQuery, new PreparedStatementSetter() {
   public void setValues(PreparedStatement preparedStatement) throws SQLException {
   preparedStatement.setInt(1, id);
   preparedStatement.setString(2, user);
   preparedStatement.setDate(3, java.sql.Date.valueOf(date));
   preparedStatement.setInt(4, time);

}

So now depending on the date I need to increment it from the start date to November 30. For example if date="2017-11-16" then I need to insert from "2017-11-16" to "2017-11-30". If date="2017-11-27" then I need to insert from "2017-11-27" to  "2017-11-30".

Any help is appreciated.

Body:
Well, here you have a solution using pre-java8 Date and Calendar:

public void incrementDate() {
    int dayLimit = 30;
    // month is zero-based index
    int monthLimit = 10;
    String startStringDate = "2017-11-16";
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Calendar calendar = Calendar.getInstance();
    Date startDate;
    java.sql.Date sqlDate;
    try {
        startDate = dateFormat.parse(startStringDate);
        calendar.setTime(startDate);
        while(calendar.get(Calendar.DAY_OF_MONTH) <= dayLimit && calendar.get(Calendar.MONTH) <= monthLimit) {
            sqlDate = new java.sql.Date(startDate.getTime());
            // here just use sqlDate in your prepared statement
            //...
            //e.g. preparedStatement.setDate(3, sqlDate);
            // ...
            System.out.println("Using sql date : " + sqlDate);
            calendar.setTime(startDate);
            calendar.add(Calendar.DATE, 1);
            startDate = calendar.getTime();
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
}


问:
git hooks / pre-receive - how to get all the commit messages on a newly created branch?
i' d like to get all the commit messages (like with git log --format=%s) on a newly created branch. Let' s suppose i' ve 2 commits:

```<code>abcd - from yesterday
bcde - from today
</code>```

. With this code:

```<code>while read old new ref; do
    ....
done
</code>```

old will be 40 zeros, and new will be bcde. How can i get all the commit messages in this case?

Usecase:

```<code>git checkout master
git checkout -b new_branch
some_work
git add; git commit
some_other_work
git add; git commit
git push origin new_branch
</code>```

.

Many thanks.

答:
If i understand well, you want something like this :</p>

```<code>while read old new ref; do
    if [[ "${old}" =~ ^0+$ ]]; then
        range="${new}"
    else
        range="${old}..${new}"
    fi
    git log --format=%s "${range}"
done
</code>```

Body:
i' d like to get all the commit messages (like with git log --format=%s) on a newly created branch. Let' s suppose i' ve 2 commits:

abcd - from yesterday
bcde - from today

. With this code:

while read old new ref; do
    ....
done

old will be 40 zeros, and new will be bcde. How can i get all the commit messages in this case?

Usecase:

git checkout master
git checkout -b new_branch
some_work
git add; git commit
some_other_work
git add; git commit
git push origin new_branch

.

Many thanks.

Body:
If i understand well, you want something like this :

while read old new ref; do
    if [[ "${old}" =~ ^0+$ ]]; then
        range="${new}"
    else
        range="${old}..${new}"
    fi
    git log --format=%s "${range}"
done


问:
Python input validation?
I have a simple input validation code asking the user for either ACT or SAT.

```<code>test=input("Are you taking SAT or ACT?..")
while test!=("SAT" or "ACT"):
    print("error")
    test=input("Are you taking SAT or ACT?..")
</code>```

It seems to work correctly for "SAT" which is in front on line 2, but not ACT! When I type in ACT in the module it will print "error" like it was false. What is my flaw here? Logic? Syntax? Semantic? What can I do to fix it?

Thank you.

答: Teverse the condition from test!=("SAT" or "ACT") to test==("SAT" or "ACT") or you can use IN as explained by Kshitij Saraogi.

Title: Python input validation?

Body:
I have a simple input validation code asking the user for either ACT or SAT.

test=input("Are you taking SAT or ACT?..")
while test!=("SAT" or "ACT"):
    print("error")
    test=input("Are you taking SAT or ACT?..")

It seems to work correctly for "SAT" which is in front on line 2, but not ACT! When I type in ACT in the module it will print "error" like it was false. What is my flaw here? Logic? Syntax? Semantic? What can I do to fix it?

Thank you.


问:
slidetoggle empty div should not work

$('.cat').click(function(){
    if ($(this).next().text() == '') {
        return false;
    }

    $(this).next().slideToggle();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='themea cat'>lorem ipsum</div>
<div class='titlewrap'>
    <ul></ul>
</div>
<div class='themea cat'>lorem ipsum</div></code>```

next to cat is titlewrap and has no text. Still, click on cat is trying to slideToggle it.

答:
You need to trim the string to avoid whitespace.

$('.cat').click(function() {
  if ($(this).next().text().trim() == '') {
    return false;
  }
  $(this).next().slideToggle();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='themea cat'>lorem ipsum</div>
<div class='titlewrap'>
  <ul>
  </ul>
</div>

<div class='themea cat'>lorem ipsum</div></code>```

Title: slidetoggle empty div should not work

Body:
$('.cat').click(function(){
    if ($(this).next().text() == '') {
        return false;
    }

    $(this).next().slideToggle();
});

lorem ipsum

lorem ipsum

next to cat is titlewrap and has no text. Still, click on cat is trying to slideToggle it.

Body:
You need to trim the string to avoid whitespace.

$('.cat').click(function() {
  if ($(this).next().text().trim() == '') {
    return false;
  }
  $(this).next().slideToggle();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='themea cat'>lorem ipsum</div>
<div class='titlewrap'>
  <ul>
  </ul>
</div>

<div class='themea cat'>lorem ipsum</div>


问:
Regular expression for some match in php
I've a following regular expression

```<code>[^|]+(|[^|]+){15}
</code>```

for the following line

```<code>|     1 |  2567 | Алма-атинська(І) вул.                     | 2     | 2      |5678     |Типовий лічил-|Санвузол          | 15.12.2016 | 10.11.2016 | 10.11.2020 | 23.10.2017 |            |    43.00 |bot       |
</code>```

Its work fine, and I got all text between '|', but how can I pass any strings for these matches? For example, trim all backspaces, or delete some subsring.

答:
You can explode(), followed by trim() to remove additional spaces, etc. And finally use array_filter to remove blank values from the array:

```<code>$str = '|     1 |  2567 | Алма-атинська(І) вул.                     | 2     | 2      |5678     |Типовий лічил-|Санвузол          | 15.12.2016 | 10.11.2016 | 10.11.2020 | 23.10.2017 |            |    43.00 |bot       |';
$arr = array_filter(array_map(function($value){return trim($value);},explode('|', $str)));
print_r($arr);
</code>```

Output:

```<code>Array ( [1] => 1 [2] => 2567 [3] => Алма-атинська(І) вул. [4] => 2 [5] => 2 [6] => 5678 [7] => Типовий лічил- [8] => Санвузол [9] => 15.12.2016 [10] => 10.11.2016 [11] => 10.11.2020 [12] => 23.10.2017 [14] => 43.00 [15] => bot )
</code>```

Body:
I've a following regular expression

[^|]+(|[^|]+){15}

for the following line

|     1 |  2567 | Алма-атинська(І) вул.                     | 2     | 2      |5678     |Типовий лічил-|Санвузол          | 15.12.2016 | 10.11.2016 | 10.11.2020 | 23.10.2017 |            |    43.00 |bot       |

Its work fine, and I got all text between '|', but how can I pass any strings for these matches? For example, trim all backspaces, or delete some subsring.

Body:
You can explode(), followed by trim() to remove additional spaces, etc. And finally use array_filter to remove blank values from the array:

$str = '|     1 |  2567 | Алма-атинська(І) вул.                     | 2     | 2      |5678     |Типовий лічил-|Санвузол          | 15.12.2016 | 10.11.2016 | 10.11.2020 | 23.10.2017 |            |    43.00 |bot       |';
$arr = array_filter(array_map(function($value){return trim($value);},explode('|', $str)));
print_r($arr);

Output:

Array ( [1] => 1 [2] => 2567 [3] => Алма-атинська(І) вул. [4] => 2 [5] => 2 [6] => 5678 [7] => Типовий лічил- [8] => Санвузол [9] => 15.12.2016 [10] => 10.11.2016 [11] => 10.11.2020 [12] => 23.10.2017 [14] => 43.00 [15] => bot )


问:
Android: Get XML from SAX Element
Can I get a string of XML from a SAX Element class in Android? For example, in DOM parsing in .NET, we can get the OuterXml or InnerXml of a node. Unless I'm overlooking something, it seems that there is no way to do that either using SAX or DOM parsing in Android. Am I right about that (I hope not)?

Using SAX, we can do something like:

```<code>Element childElt = rootElt.getChild(CHILD_ELT_NAME);
if(childElt != null) {
 childElt.setEndTextElementListener(new EndTextElementListener() {
  @Override
  public void end(String body) {
   //Do something with the body string
  }
 });
}
</code>```

That will allow us to get at the "value" of the child element. Is there anything similar that will allow us to get at the XML representation of the element and its children?

Thank you.

答: With VTD-XML, you can get the token index and convert them to string for further processing, if simplicity is what you look for.</p>

ContentLicense: CC BY-SA 2.5

Title: Android: Get XML from SAX Element

Body:
Can I get a string of XML from a SAX Element class in Android? For example, in DOM parsing in .NET, we can get the OuterXml or InnerXml of a node. Unless I'm overlooking something, it seems that there is no way to do that either using SAX or DOM parsing in Android. Am I right about that (I hope not)?

Using SAX, we can do something like:

Element childElt = rootElt.getChild(CHILD_ELT_NAME);
if(childElt != null) {
 childElt.setEndTextElementListener(new EndTextElementListener() {
  @Override
  public void end(String body) {
   //Do something with the body string
  }
 });
}

That will allow us to get at the "value" of the child element. Is there anything similar that will allow us to get at the XML representation of the element and its children?

Thank you.


问:
Getting text inside p element inside div
I have following rendered html

```<code><div class="footer text-center">
  <p>By signing up, you agree to abc's <b>Terms of Service</b>, <b>Cookie Policy</b>, <b>Privacy Policy and Content Policies.</b></p>
</div>
</code>```

I am trying following to validate text is appearing as expected.
But getAttribute('value') returns Null and hence test failing.

```<code>element(by.tagName('p')).getAttribute('value').then(function (text) {
    expect(text).toBe("By signing up, you agree to abc's Terms of Service, Cookie Policy, Privacy Policy and Content Policies.");
});
</code>```

答:
As you try to getText() as nicely formatted string, you should indeed use getText() as described in Protractor API. It will remove the -tags and will also i.e. remove double-spaces.

Further because getText() returns a promise and because expect() will then resolve the promise, there is no need to use then() in your case.

Overall here is how your code should look like:

```<code>expect(element(by.tagName('p')).getText()).toBe("By signing up, you agree to abc's Terms of Service, Cookie Policy, Privacy Policy and Content Policies.");
</code>```

Now some more valuable infos:

about the differences between getAttribute('value') and getText()

about innerText vs textContent

Body:
I have following rendered html

By signing up, you agree to abc's Terms of Service, Cookie Policy, Privacy Policy and Content Policies.

I am trying following to validate text is appearing as expected.
But getAttribute('value') returns Null and hence test failing.

element(by.tagName('p')).getAttribute('value').then(function (text) {
    expect(text).toBe("By signing up, you agree to abc's Terms of Service, Cookie Policy, Privacy Policy and Content Policies.");
});

Body:
As you try to getText() as nicely formatted string, you should indeed use getText() as described in Protractor API. It will remove the <b>-tags and will also i.e. remove double-spaces.

Further because getText() returns a promise and because expect() will then resolve the promise, there is no need to use then() in your case.

Overall here is how your code should look like:

expect(element(by.tagName('p')).getText()).toBe("By signing up, you agree to abc's Terms of Service, Cookie Policy, Privacy Policy and Content Policies.");

Now some more valuable infos:

about the differences between getAttribute('value') and getText()

about innerText vs textContent


问:
Ranged Solr Queries on timestamp field
I'm trying to build a solr query for timecode values with the following format:

```<code>run_time:

00:25:00

00:30:00

01:00:00
</code>```

I'd like to filter a range of timecodes. Everything 30 minutes or under, for example.

I've tried a couple of queries with no success.

```<code>run_time:[* TO 00:30:00]

run_time:[* TO 00\:30\:00]

run_time:[* TO *00:31:00Z]
</code>```

Any thoughts?

答:
Your use case appears to be searching for processes which ran for 30 minutes or less. Date field will not be the right fit here.
A better approach would be to store the run time information in a number field.

```<code>run_time:
25
30
60
</code>```

The you can use a range query on this field to get desired results.

```<code>runtime:[0 TO 30]
</code>```

This will fetch records having runtime between 0 to 30minutes including 0,30

Title: Ranged Solr Queries on timestamp field

Body:
I'm trying to build a solr query for timecode values with the following format:

run_time:

00:25:00

00:30:00

01:00:00

I'd like to filter a range of timecodes. Everything 30 minutes or under, for example.

I've tried a couple of queries with no success.

run_time:[* TO 00:30:00]

run_time:[* TO 00\:30\:00]

run_time:[* TO *00:31:00Z]

Any thoughts?

Body:
Your use case appears to be searching for processes which ran for 30 minutes or less. Date field will not be the right fit here.
A better approach would be to store the run time information in a number field.

run_time:
25
30
60

The you can use a range query on this field to get desired results.

runtime:[0 TO 30]

This will fetch records having runtime between 0 to 30minutes including 0,30


问:
Moving from one tab to other using fragments
I have a tab layout having 4 tabs, the view pager is replaced with fragments, i have one button in tab 3 (i mean in fragment 3). On clicking of that button i should go to fragment 1 (inside tab 1), how to achieve this ?
 I am just able to replacing the fragment 3 with fragment 1. but the tabs also should change .</p>

答:
Try this use ViewPager.setCurrentItem(int position)

void setCurrentItem (int item)

Set the currently selected page. If the ViewPager has already been through its first layout with its current adapter there will be a smooth animated transition between the current item and the specified item.

```<code> tv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            ((MainActivity)getActivity()).mViewPager.setCurrentItem(0)
        }
    });
</code>```

Body:
Try this use ViewPager.setCurrentItem(int position)

void setCurrentItem (int item)

Set the currently selected page. If the ViewPager has already been through its first layout with its current adapter there will be a smooth animated transition between the current item and the specified item.

 tv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            ((MainActivity)getActivity()).mViewPager.setCurrentItem(0)
        }
    });


问:
Remove all databases from my application except the specified database
I want to remove all other databases and shared pref from my application except the one I am specifying by providing name, say XYZ.

I want to keep only newly created database in my application and delete older databases with whatever names. So i know only my database name (the one i want to keep in application) and delete other databases (do not have names of databases those i want to delete).

答:
I have not used this. But hope this may help you.</p>

```<code> for (int i = 0; i < databaseList().length; i++) {
                    String db_name = databaseList()[i];
                    deleteDatabase(db_name);
                }
</code>```

Body:
I have not used this. But hope this may help you.

 for (int i = 0; i < databaseList().length; i++) {
                    String db_name = databaseList()[i];
                    deleteDatabase(db_name);
                }


问:
Auto add a coupon discount only when cart items are from 3 different product categories
IN WooCommerce I would like to add 10% of discount with WooCommerce Coupon feature, only when customer purchases products from 3 different product categories (like Category1, Category2, Category3).

How this can be done with WooCommerce Coupon feature?

Any help on this will be appreciated.

Update note: I only 3 parent product categories with no sub categories. Each product is assigned to one category. Some products are variable and some others are simple.

答:
Here's a solution that is not using coupon codes that I recycled from this previous question.</p>

```<code>add_action( 'woocommerce_cart_calculate_fees' , 'add_multiple_category_discount' );

function add_multiple_category_discount( $cart ){
    if( $cart->cart_contents_count < 3 ){
        return;
    }

    $product_cats = array();

    foreach( $cart->get_cart() as $item ) {
        $product = wc_get_product( $item['product_id'] );

        foreach( $product->get_category_ids() as $key => $cat_id ) {
            if( ! in_array( $cat_id, $product_cats ) )
                $product_cats[] = $cat_id;
        }
    }

    // If we have 3 distinct categories then apply a discount
    if( count( $product_cats ) >= 3 ) {
        // Add a 10% discount
        $discount = $cart->subtotal * 0.1;
        $cart->add_fee( 'You have 3 different product categories in your cart, a 10% discount has been added.', -$discount );
    }
}
</code>```

Body:
Here's a solution that is not using coupon codes that I recycled from this previous question.

add_action( 'woocommerce_cart_calculate_fees' , 'add_multiple_category_discount' );

function add_multiple_category_discount( $cart ){
    if( $cart->cart_contents_count < 3 ){
        return;
    }

    $product_cats = array();

    foreach( $cart->get_cart() as $item ) {
        $product = wc_get_product( $item['product_id'] );

        foreach( $product->get_category_ids() as $key => $cat_id ) {
            if( ! in_array( $cat_id, $product_cats ) )
                $product_cats[] = $cat_id;
        }
    }

    // If we have 3 distinct categories then apply a discount
    if( count( $product_cats ) >= 3 ) {
        // Add a 10% discount
        $discount = $cart->subtotal * 0.1;
        $cart->add_fee( 'You have 3 different product categories in your cart, a 10% discount has been added.', -$discount );
    }
}


问:
How to use the express response.send in callback functions (used by mysqljs in nodejs for example)
I am using express and mysqljs in express.If i request my database to add a user,i have to define a callback function to handle response. Unfortunately i have no access to express res.send in callback function.I want to send insertID to the res.send method.How i do this?. Here is my code.</p>

```<code>app.post("/adduser", (req, res) => {
  const con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "customer"
  });
  const name = req.body.name;
  const age = req.body.age;

const users = { name: name, age: age };
  const query = "INSERT INTO users SET ?";
  con.query(query, users, (err, res) => {
    if (err) throw err;
    console.log("Last insert ID:", res.insertId);
    // want to send res.insertId to server
    // res.send() here
  });

});
</code>```

答:
I guess you are using the same variable name 'res' for both 'response' and 'result'.

AS the documentation says, con.query returns 'result' not 'res'.
https://github.com/mysqljs/mysql#performing-queries

```<code>app.post("/adduser", (req, res) => {
    const con = mysql.createConnection({
          host: "localhost",
          user: "root",
          password: "",
          database: "customer"
    });
    const name = req.body.name;
    const age = req.body.age;

    const users = { name: name, age: age };
    const query = "INSERT INTO users SET ?";
    con.query(query, users, (err, result) => {
      if (err) throw err;
      console.log("Last insert ID:", result.insertId);
      // want to send result.insertId to server
      // res.send() here

      // res.send(result.insertId); // gives an error
      res.send(result.insertId.toString());
    });

});
</code>```

Body:
I am using express and mysqljs in express.If i request my database to add a user,i have to define a callback function to handle response. Unfortunately i have no access to express res.send in callback function.I want to send insertID to the res.send method.How i do this?. Here is my code.

app.post("/adduser", (req, res) => {
  const con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "customer"
  });
  const name = req.body.name;
  const age = req.body.age;

const users = { name: name, age: age };
  const query = "INSERT INTO users SET ?";
  con.query(query, users, (err, res) => {
    if (err) throw err;
    console.log("Last insert ID:", res.insertId);
    // want to send res.insertId to server
    // res.send() here
  });

});

Body:
I guess you are using the same variable name 'res' for both 'response' and 'result'.

AS the documentation says, con.query returns 'result' not 'res'.
https://github.com/mysqljs/mysql#performing-queries

app.post("/adduser", (req, res) => {
    const con = mysql.createConnection({
          host: "localhost",
          user: "root",
          password: "",
          database: "customer"
    });
    const name = req.body.name;
    const age = req.body.age;

    const users = { name: name, age: age };
    const query = "INSERT INTO users SET ?";
    con.query(query, users, (err, result) => {
      if (err) throw err;
      console.log("Last insert ID:", result.insertId);
      // want to send result.insertId to server
      // res.send() here

      // res.send(result.insertId); // gives an error
      res.send(result.insertId.toString());
    });

});


问:
Download HTML String content in android
I have String with html format, not url, that send through from api. Those include image and bootstrap css. I would like to download those things to show in offline including image and css to show right format.

Is there any library to download html string content?

答:
All You Have to do is get your Json Data convert Json to String json.toString();
and pass it to data=json.String();
and check if data is already stored or not in Shared Preferences

```<code> DataBaseHelper DB;
     if(DB.getHTMLStoredData(context)){
    data=DB.getHTMLStoredData(context)
    }else{
    data=json.String();
    }

    //data == html data which you want to load
         WebView webview = (WebView)this.findViewById(R.id.webview);
         webview.getSettings().setJavaScriptEnabled(true);
         webview.loadDataWithBaseURL("", data, "text/html", "UTF-8", "");
</code>```

Title: Download HTML String content in android

Body:
All You Have to do is get your Json Data convert Json to String json.toString();
and pass it to data=json.String();
and check if data is already stored or not in Shared Preferences

 DataBaseHelper DB;
     if(DB.getHTMLStoredData(context)){
    data=DB.getHTMLStoredData(context)
    }else{
    data=json.String();
    }

    //data == html data which you want to load
         WebView webview = (WebView)this.findViewById(R.id.webview);
         webview.getSettings().setJavaScriptEnabled(true);
         webview.loadDataWithBaseURL("", data, "text/html", "UTF-8", "");


问:
It's possible to replace existing html code with jQuery
Example current html code

```<code><a rel="tag" title="see questions tagged 'php'" href="/tags/php/" class="tag-link-php">php</a>
</code>```

I want use jQuery to replace it to be

```<code><a href="http://php.net/"><img src="/images/tags/php.gif" height="16" width="16" alt="php" /></a><a rel="tag" title="see questions tagged 'php'" href="/tags/php/" class="tag-link-php">php</a>
</code>```

Let me know

答:
You  can also use replaceWith:

http://api.jquery.com/replaceWith/

Body:
Example current html code

php

I want use jQuery to replace it to be

php

Let me know


问:
Running multiple launch configurations at once
I have several launch configurations in Eclipse each launching the same Java program but with different parameters.

Now is it possible to run all of these at once (with one mouse click) instead of selecting each of it separately and launching it?

答:
Since Eclipse Oxygen (4.7.0) you can use a run configuration of the type Launch Group for that.

This short video shows how to use a Launch Group.


问:
editing a JSON file
First of all yes I did check other options, questions and answers but sadly those didn't work for me.

So I'm currently working on a small project including a shopping cart system.
The shopping cart system is created by a PHP session and everything works fine. Products can be added, rows can be deleted and the cart can be cleared completely.

Now I would like to add some functions like counting the items in the cart, calculating the total price and VAT prices. Since the session is stored as a JSON object I'm able to use angularjs and $http.get() to read the JSON cart object and redefine the data so it's usable in an ng-repeat for the view.

So when the visitor clicks on the "add to cart" button the following code is creating the session:

```<code>session_start();

$product_id = $_REQUEST['product_id'];
$product_name = $_REQUEST['product_name'];
$product_price = round($_REQUEST['product_price'], 2);
$product_size = $_REQUEST['product_size'];
$product_quantity = $_REQUEST['product_quantity'];
$total_product_price = $product_price*$product_quantity;
round($total_product_price, 2);
// Add new item to session
$cartProduct = array(
    "id" => $product_id,
    "name" => $product_name,
    "price" => $product_price,
    "size" => $product_size,
    "quantity" => $product_quantity,
    "total_product_price" => $total_product_price,
    "total_items" => 0
);

/*
 * check if the 'cart' session array was created
 * if it is NOT, create the 'cart' session array
 */
if(empty($_SESSION['cart']["cartItems"])){
    $_SESSION['cart']["cartItems"] = array();
}

// check if the item is in the array, if it is, do not add
if(array_key_exists($product_id and $product_size, $_SESSION['cart'])){
    // redirect to product list and tell the user it was added to cart
    echo "<script> alert('Dit product staat al in de winkelwagen')</script>])";
}

// else, add the item to the array
else{
    $_SESSION['cart']["cartItems"][$product_id]=$cartProduct;
}
</code>```

So my first attempt was to add the following to the section "add the item to the array"

```<code>    $arr = json_decode($_SESSION['cart']['cartItems'][$product_id], true);
    $total_items['total_items'] = count($_SESSION['cart']);
    array_push($arr['cartItems'], $total_items);
</code>```

But sadly this didn't work. I also tried adding this to the getCart section.

```<code>session_start();

$json = json_encode($_SESSION['cart']["cartItems"]);
echo($json);
</code>```

Sadly also without any result.

So my question is how am I able to add the total_items calculation to the array. And how am I able to calculate the total price, VAT prices etc?

PS: the JSON outcome of one product:

```<code>{"16":{"id":"16","name":"TestDatumProduct","price":1000,"size":"M","quantity":"4","total_product_price":4000,"total_items":0}}
</code>```

UPDATE

So an update to combine the progress of the last few days:

So currently my code is based on the answer of @devionNL since i like the action method and the answer of @FranciscoRodríguez was barely an answer since he only adviced me about the counting method, (didn't work)

So using the action examples from @devionNL i've made some small changes and came up with the following code.

```<code><?php
session_start();
$cartItemID = $_REQUEST['cartItem_id'];
$product_id = $_REQUEST['product_id'];
$product_name = $_REQUEST['product_name'];
$product_price = round($_REQUEST['product_price'], 2);
$product_size = $_REQUEST['product_size'];
$product_quantity = $_REQUEST['product_quantity'];
$total_product_price = $product_price*$product_quantity;
round($total_product_price, 2);

// Add new item to session
$cartProduct = array(
    "id" => $product_id,
    "name" => $product_name,
    "price" => $product_price,
    "size" => $product_size,
    "quantity" => $product_quantity,
    "total_product_price" => $total_product_price
);

// If the session is empty create an empty array
if(empty($_SESSION['cart']["cartItems"])){
    $_SESSION['cart']["cartItems"] = array();
}

// Add to cart
if ($_REQUEST['action'] == 'addToCart')
{
    if (array_key_exists($product_id, $_SESSION['cart']['cartItems']))
    {
        $_SESSION['cart']['cartItems']['totalItems']++;
    }
    else
    {
        $_SESSION['cart']['cartItems']['totalItems']++;
        array_push($_SESSION['cart']['cartItems'], $cartProduct );
    }
}

// RemoveRow
else if ($_REQUEST['action'] == 'removeRow') // If you want a delete action
{
    if (array_key_exists($product_id, $_SESSION['cart']['cartItems']))
    {
        if ($_SESSION['cart']['cartItems']['totalItems'] > 1)
        {
            foreach ($cartDecode as $key => $cartItem)
            {
                // IF THE TITLE MATCHES THE SIGNAL STRING
                if ($cartItem->{"id"} == $cartItemID)
                {
                    // REMOVE THIS OBJECT
                    unset($cartDecode[$key]);
                }

            }
            $_SESSION['cart']['cartItems']['totalItems']--; // Deduct by 1.
        }
    else
        {
            $_SESSION['cart']['cartItems'] = $cartProduct;
        }
    }

    $_SESSION['cart']['cartItems']['totalPrice'] = array_sum(array_map(function($item) {
        return $item['price'] * $item['totalItems'];
    },
        $_SESSION['cart']['cartItems']));

}
$cart = json_encode($_SESSION['cart']['cartItems']);
echo ($cart);
</code>```

So adding to the cart, and calculating the cartItems is working as expected. But i still can't find the way of removing a row. inside the cart. Next to that i'm still struggling with getting the total price of the cart. The JSON outcome is as following:

```<code>{"totalItems":2,"0":{"id":"7","name":"Bedrukt jurkje van chiffon","price":20.5,"size":"M","quantity":"3","total_product_price":61.5},"1":{"id":"5","name":"Bedrukte Zomerjurk","price":30.5,"size":"M","quantity":"3","total_product_price":91.5}}
</code>```

The full cart in JSON would then be:

```<code>{"cartItems":{"totalItems":2,"0":{"id":"7","name":"Bedrukt jurkje van chiffon","price":20.5,"size":"M","quantity":"3","total_product_price":61.5},"1":{"id":"5","name":"Bedrukte Zomerjurk","price":30.5,"size":"M","quantity":"3","total_product_price":91.5}}}
</code>```

So my questions are?
1. How am i able to delete a single row (ID == "", Then delete)
2. How am i able to calculate the full price of the cart?
3. For placing the order inside the dabatase, how would i be able to select each row? (id, name, etc). I was thinking in the way of using a foreach() statement?

If there are any questions please ask them in the comments.

As always, Thanks in advance!

答:
I got a bit lost in here so forgive me if I'm wrong, hopefully it has the expected result :

```<code><?php
session_start();
//unset($_SESSION['cart']);
var_dump($_SESSION['cart']['cartItems']);
$cartItemID = $Req['cartItem_id'];
$product_id = $Req['product_id'];
$product_name = $Req['product_name'];
$product_price = round($Req['product_price'], 2);
$product_size = $Req['product_size'];
$product_quantity = $Req['product_quantity'];
$total_product_price = $product_price*$product_quantity;
round($total_product_price, 2);

// Add new item to session
$cartProduct = array(
    "id" => $product_id,
    "name" => $product_name,
    "price" => $product_price,
    "size" => $product_size,
    "quantity" => $product_quantity,
    "total_product_price" => $total_product_price
);

// If the session is empty create an empty array
if(empty($_SESSION['cart']["cartItems"])){
    $_SESSION['cart']["cartItems"] = array();
    $_SESSION['cart']["cartItems"]["totalitems"] = 0;
    $_SESSION['cart']["cartItems"]["totalprice"] = 0;

}

// Add to cart
if ($Req['action'] == 'addToCart') {
    if (!isset($_SESSION['cart']["cartItems"][$cartItemID])) {
        $_SESSION['cart']["cartItems"][$cartItemID] = $cartProduct;
        $_SESSION['cart']["totalitems"]++;
        $_SESSION['cart']["totalprice"] += $total_product_price;
    }
}

// RemoveRow
else if ($Req['action'] == 'removeRow') // If you want a delete action
{
    if (isset($_SESSION['cart']["cartItems"][$cartItemID])) {
        $_SESSION['cart']["totalitems"]--;
        $_SESSION['cart']["totalprice"] -= $_SESSION['cart']["cartItems"][$cartItemID];
        unset($_SESSION['cart']["cartItems"][$cartItemID]);
    }

}
$cart = json_encode($_SESSION['cart']['cartItems']);
echo ($cart);
</code>```

So to explain this. Use the "cartItemID" as the key for the "cartProduct". and have two more key in the "cart" array for the total item count and the total price. And to answer your questions :

The total price of the cart gonna be in "$_SESSION['cart']["totalprice"]"

To insert them into a database you can simply foreach the $_SESSION['cart']["cartItems"] array.

Title: editing a JSON file

Body:
First of all yes I did check other options, questions and answers but sadly those didn't work for me.

So I'm currently working on a small project including a shopping cart system.
The shopping cart system is created by a PHP session and everything works fine. Products can be added, rows can be deleted and the cart can be cleared completely.

Now I would like to add some functions like counting the items in the cart, calculating the total price and VAT prices. Since the session is stored as a JSON object I'm able to use angularjs and $http.get() to read the JSON cart object and redefine the data so it's usable in an ng-repeat for the view.

So when the visitor clicks on the "add to cart" button the following code is creating the session:

session_start();

$product_id = $_REQUEST['product_id'];
$product_name = $_REQUEST['product_name'];
$product_price = round($_REQUEST['product_price'], 2);
$product_size = $_REQUEST['product_size'];
$product_quantity = $_REQUEST['product_quantity'];
$total_product_price = $product_price*$product_quantity;
round($total_product_price, 2);
// Add new item to session
$cartProduct = array(
    "id" => $product_id,
    "name" => $product_name,
    "price" => $product_price,
    "size" => $product_size,
    "quantity" => $product_quantity,
    "total_product_price" => $total_product_price,
    "total_items" => 0
);

/*
 * check if the 'cart' session array was created
 * if it is NOT, create the 'cart' session array
 */
if(empty($_SESSION['cart']["cartItems"])){
    $_SESSION['cart']["cartItems"] = array();
}

// check if the item is in the array, if it is, do not add
if(array_key_exists($product_id and $product_size, $_SESSION['cart'])){
    // redirect to product list and tell the user it was added to cart
    echo "])";
}

// else, add the item to the array
else{
    $_SESSION['cart']["cartItems"][$product_id]=$cartProduct;
}

So my first attempt was to add the following to the section "add the item to the array"

    $arr = json_decode($_SESSION['cart']['cartItems'][$product_id], true);
    $total_items['total_items'] = count($_SESSION['cart']);
    array_push($arr['cartItems'], $total_items);

But sadly this didn't work. I also tried adding this to the getCart section.

session_start();

$json = json_encode($_SESSION['cart']["cartItems"]);
echo($json);

Sadly also without any result.

So my question is how am I able to add the total_items calculation to the array. And how am I able to calculate the total price, VAT prices etc?

PS: the JSON outcome of one product:

{"16":{"id":"16","name":"TestDatumProduct","price":1000,"size":"M","quantity":"4","total_product_price":4000,"total_items":0}}

UPDATE

So an update to combine the progress of the last few days:

So currently my code is based on the answer of @devionNL since i like the action method and the answer of @FranciscoRodríguez was barely an answer since he only adviced me about the counting method, (didn't work)

So using the action examples from @devionNL i've made some small changes and came up with the following code.

<?php
session_start();
$cartItemID = $_REQUEST['cartItem_id'];
$product_id = $_REQUEST['product_id'];
$product_name = $_REQUEST['product_name'];
$product_price = round($_REQUEST['product_price'], 2);
$product_size = $_REQUEST['product_size'];
$product_quantity = $_REQUEST['product_quantity'];
$total_product_price = $product_price*$product_quantity;
round($total_product_price, 2);

// Add new item to session
$cartProduct = array(
    "id" => $product_id,
    "name" => $product_name,
    "price" => $product_price,
    "size" => $product_size,
    "quantity" => $product_quantity,
    "total_product_price" => $total_product_price
);

// If the session is empty create an empty array
if(empty($_SESSION['cart']["cartItems"])){
    $_SESSION['cart']["cartItems"] = array();
}

// Add to cart
if ($_REQUEST['action'] == 'addToCart')
{
    if (array_key_exists($product_id, $_SESSION['cart']['cartItems']))
    {
        $_SESSION['cart']['cartItems']['totalItems']++;
    }
    else
    {
        $_SESSION['cart']['cartItems']['totalItems']++;
        array_push($_SESSION['cart']['cartItems'], $cartProduct );
    }
}

// RemoveRow
else if ($_REQUEST['action'] == 'removeRow') // If you want a delete action
{
    if (array_key_exists($product_id, $_SESSION['cart']['cartItems']))
    {
        if ($_SESSION['cart']['cartItems']['totalItems'] > 1)
        {
            foreach ($cartDecode as $key => $cartItem)
            {
                // IF THE TITLE MATCHES THE SIGNAL STRING
                if ($cartItem->{"id"} == $cartItemID)
                {
                    // REMOVE THIS OBJECT
                    unset($cartDecode[$key]);
                }

            }
            $_SESSION['cart']['cartItems']['totalItems']--; // Deduct by 1.
        }
    else
        {
            $_SESSION['cart']['cartItems'] = $cartProduct;
        }
    }

    $_SESSION['cart']['cartItems']['totalPrice'] = array_sum(array_map(function($item) {
        return $item['price'] * $item['totalItems'];
    },
        $_SESSION['cart']['cartItems']));

}
$cart = json_encode($_SESSION['cart']['cartItems']);
echo ($cart);

So adding to the cart, and calculating the cartItems is working as expected. But i still can't find the way of removing a row. inside the cart. Next to that i'm still struggling with getting the total price of the cart. The JSON outcome is as following:

{"totalItems":2,"0":{"id":"7","name":"Bedrukt jurkje van chiffon","price":20.5,"size":"M","quantity":"3","total_product_price":61.5},"1":{"id":"5","name":"Bedrukte Zomerjurk","price":30.5,"size":"M","quantity":"3","total_product_price":91.5}}

The full cart in JSON would then be:

{"cartItems":{"totalItems":2,"0":{"id":"7","name":"Bedrukt jurkje van chiffon","price":20.5,"size":"M","quantity":"3","total_product_price":61.5},"1":{"id":"5","name":"Bedrukte Zomerjurk","price":30.5,"size":"M","quantity":"3","total_product_price":91.5}}}

So my questions are?
1. How am i able to delete a single row (ID == "", Then delete)
2. How am i able to calculate the full price of the cart?
3. For placing the order inside the dabatase, how would i be able to select each row? (id, name, etc). I was thinking in the way of using a foreach() statement?

If there are any questions please ask them in the comments.

As always, Thanks in advance!

Body:
I got a bit lost in here so forgive me if I'm wrong, hopefully it has the expected result :

<?php
session_start();
//unset($_SESSION['cart']);
var_dump($_SESSION['cart']['cartItems']);
$cartItemID = $Req['cartItem_id'];
$product_id = $Req['product_id'];
$product_name = $Req['product_name'];
$product_price = round($Req['product_price'], 2);
$product_size = $Req['product_size'];
$product_quantity = $Req['product_quantity'];
$total_product_price = $product_price*$product_quantity;
round($total_product_price, 2);

// Add new item to session
$cartProduct = array(
    "id" => $product_id,
    "name" => $product_name,
    "price" => $product_price,
    "size" => $product_size,
    "quantity" => $product_quantity,
    "total_product_price" => $total_product_price
);

// If the session is empty create an empty array
if(empty($_SESSION['cart']["cartItems"])){
    $_SESSION['cart']["cartItems"] = array();
    $_SESSION['cart']["cartItems"]["totalitems"] = 0;
    $_SESSION['cart']["cartItems"]["totalprice"] = 0;

}

// Add to cart
if ($Req['action'] == 'addToCart') {
    if (!isset($_SESSION['cart']["cartItems"][$cartItemID])) {
        $_SESSION['cart']["cartItems"][$cartItemID] = $cartProduct;
        $_SESSION['cart']["totalitems"]++;
        $_SESSION['cart']["totalprice"] += $total_product_price;
    }
}

// RemoveRow
else if ($Req['action'] == 'removeRow') // If you want a delete action
{
    if (isset($_SESSION['cart']["cartItems"][$cartItemID])) {
        $_SESSION['cart']["totalitems"]--;
        $_SESSION['cart']["totalprice"] -= $_SESSION['cart']["cartItems"][$cartItemID];
        unset($_SESSION['cart']["cartItems"][$cartItemID]);
    }

}
$cart = json_encode($_SESSION['cart']['cartItems']);
echo ($cart);

So to explain this. Use the "cartItemID" as the key for the "cartProduct". and have two more key in the "cart" array for the total item count and the total price. And to answer your questions :

The total price of the cart gonna be in "$_SESSION['cart']["totalprice"]"

To insert them into a database you can simply foreach the $_SESSION['cart']["cartItems"] array.


问:
npm ERR! code ENOENT when adding cordova plugins (cordova deletes the file it's looking for)
I am trapped in a somewhat infinite loop of struggles! Please help xD

No matter what phonegap or cordova cli commands I run, cordova seems to delete the very files it's looking for previous to looking for them.

Here are just a few known commands which trigger the error for me:

$ cordova plugin add <plugin name>

$ phonegap plugin add <plugin name>

$ cordova platform update <platform name>

$ phonegap platform update <platform name>

$ cordova platform remove <platform name>

$ phonegap platform remove <platform name>

See below terminal output which shows the output I get when running these commands. I am really unsure why cordova is deleting the very file it's trying to rename before it tries to rename it. Very frustrating!

Step 1 (check to ensure we have a clean git head and no changes in our working set)

```<code>apple@Child-2:~/projects/infiniteinternet/prodmode/prodmode-client-mobile-builds/phonegap * feature-barcode-scanner$ git status
# On branch feature-barcode-scanner
nothing to commit, working directory clean
</code>```

Step 2 (attempt plugin add)

```<code>apple@Child-2:~/projects/infiniteinternet/prodmode/prodmode-client-mobile-builds/phonegap * feature-barcode-scanner$ cordova plugin add phonegap-plugin-barcodescanner --variable CAMERA_USAGE_DESCRIPTION="To scan barcodes"
Unmet project requirements for latest version of phonegap-plugin-barcodescanner:
cordova-android (6.2.3 in project, >=6.3.0 required)
Fetching highest version of phonegap-plugin-barcodescanner that this project supports: 6.0.8 (latest is 7.0.0)
Error: Failed to fetch plugin phonegap-plugin-barcodescanner@6.0.8 via registry.
Probably this is either a connection problem, or plugin spec is incorrect.
Check your connection and plugin name/version/URL.
Error: npm: Command failed with exit code 254 Error output:
npm WARN cordova-plugin-file-transfer@1.5.1 requires a peer of cordova-plugin-file@^3.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN cordova-plugin-media-capture@1.2.0 requires a peer of cordova-plugin-file@^3.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN com.prodmod.mobileclient@1.0.0 No repository field.
npm WARN com.prodmod.mobileclient@1.0.0 No license field.

npm ERR! path prodmode-client-mobile-builds/phonegap/node_modules/cordova-ios/node_modules/simple-plist/node_modules/base64-js
npm ERR! code ENOENT
npm ERR! errno -2
npm ERR! syscall rename
npm ERR! enoent ENOENT: no such file or directory, rename 'prodmode-client-mobile-builds/phonegap/node_modules/cordova-ios/node_modules/simple-plist/node_modules/base64-js' -> 'prodmode-client-mobile-builds/phonegap/node_modules/cordova-ios/node_modules/simple-plist/node_modules/.base64-js.DELETE'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

┌──────────────────────────────────────────────────────────┐
│                 npm update check failed                  │
│           Try running with sudo or get access            │
│           to the local update config store via           │
│ sudo chown -R $USER:$(id -gn $USER) /Users/apple/.config │
└──────────────────────────────────────────────────────────┘

npm ERR! A complete log of this run can be found in:
npm ERR! .npm/_logs/2017-11-10T00_23_21_467Z-debug.log
</code>```

Step 3 (check git changes caused by the command in step 2)

Okay, so it failed. Let's find out what happened to the supposed missing file. Well, apparently cordova deleted the file before it looked for it?

```<code>apple@Child-2:~/projects/infiniteinternet/prodmode/prodmode-client-mobile-builds/phonegap * feature-barcode-scanner$ git status
# On branch feature-barcode-scanner
# Changes not staged for commit:
#   (use "git add/rm <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/base64-js/.npmignore
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/base64-js/.travis.yml
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/base64-js/LICENSE.MIT
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/base64-js/README.md
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/base64-js/base64js.min.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/base64-js/bower.json
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/base64-js/lib/b64.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/base64-js/package.json
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/base64-js/test/big-data.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/base64-js/test/convert.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/base64-js/test/url-safe.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/plist/.jshintrc
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/plist/.travis.yml
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/plist/History.md
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/plist/LICENSE
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/plist/Makefile
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/plist/README.md
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/plist/dist/plist-build.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/plist/dist/plist-parse.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/plist/dist/plist.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/plist/examples/browser/index.html
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/plist/index.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/plist/lib/build.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/plist/lib/parse.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/plist/package.json
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/.npmignore
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/CHANGELOG.md
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/LICENSE
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/README.md
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/Utility.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLAttribute.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLCData.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLComment.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLDTDAttList.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLDTDElement.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLDTDEntity.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLDTDNotation.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLDeclaration.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLDocType.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLDocument.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLDocumentCB.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLElement.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLNode.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLProcessingInstruction.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLRaw.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLStreamWriter.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLStringWriter.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLStringifier.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLText.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLWriterBase.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/index.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/package.json
#
no changes added to commit (use "git add" and/or "git commit -a")
</code>```

If anyone has any suggestions on how to fix this issue, I'd be super grateful. I'm not sure what caused it or when it took effect, but it's been a couple weeks now that I haven't been able to add plugins to my project.

Thanks in advance!

EDIT:
Environment settings:

```<code>apple@Child-2:/ $ cordova --version
7.0.1

┌──────────────────────────────────────────┐
│ Update available: 7.1.0 (current: 7.0.1) │
│ Run npm install -g cordova to update.    │
└──────────────────────────────────────────┘

apple@Child-2:/ $ phonegap --version
7.1.1
apple@Child-2:/ $ node --version
v6.11.1
apple@Child-2:/ $ npm --version
5.4.2
</code>```

答:
I really don't know where is a problem in your project but I had similar behavior when I upgraded cordova version and migrated my project from Eclipse to Android Studio.

Adding some plugin causes to multiple deletions and all my project doesn't work.

I tried a lot of ways to fix it but failed, every time with other Exceptions.

So I solved it by creating new project from scratch. Added all plugins one by one and after, copied all www folder from old project.

It took me about 30 min but it worth it.

Tip:   I would put node_modules folder to .gitignore file. You don't need push all dependancies  to git. Users can clone the project and just run $ npm install from root project.

Body:
I am trapped in a somewhat infinite loop of struggles! Please help xD

No matter what phonegap or cordova cli commands I run, cordova seems to delete the very files it's looking for previous to looking for them.

Here are just a few known commands which trigger the error for me:

$ cordova plugin add <plugin name>

$ phonegap plugin add <plugin name>

$ cordova platform update <platform name>

$ phonegap platform update <platform name>

$ cordova platform remove <platform name>

$ phonegap platform remove <platform name>

See below terminal output which shows the output I get when running these commands. I am really unsure why cordova is deleting the very file it's trying to rename before it tries to rename it. Very frustrating!

Step 1 (check to ensure we have a clean git head and no changes in our working set)

apple@Child-2:~/projects/infiniteinternet/prodmode/prodmode-client-mobile-builds/phonegap * feature-barcode-scanner$ git status
# On branch feature-barcode-scanner
nothing to commit, working directory clean

Step 2 (attempt plugin add)

apple@Child-2:~/projects/infiniteinternet/prodmode/prodmode-client-mobile-builds/phonegap * feature-barcode-scanner$ cordova plugin add phonegap-plugin-barcodescanner --variable CAMERA_USAGE_DESCRIPTION="To scan barcodes"
Unmet project requirements for latest version of phonegap-plugin-barcodescanner:
cordova-android (6.2.3 in project, >=6.3.0 required)
Fetching highest version of phonegap-plugin-barcodescanner that this project supports: 6.0.8 (latest is 7.0.0)
Error: Failed to fetch plugin phonegap-plugin-barcodescanner@6.0.8 via registry.
Probably this is either a connection problem, or plugin spec is incorrect.
Check your connection and plugin name/version/URL.
Error: npm: Command failed with exit code 254 Error output:
npm WARN cordova-plugin-file-transfer@1.5.1 requires a peer of cordova-plugin-file@^3.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN cordova-plugin-media-capture@1.2.0 requires a peer of cordova-plugin-file@^3.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN com.prodmod.mobileclient@1.0.0 No repository field.
npm WARN com.prodmod.mobileclient@1.0.0 No license field.

npm ERR! path prodmode-client-mobile-builds/phonegap/node_modules/cordova-ios/node_modules/simple-plist/node_modules/base64-js
npm ERR! code ENOENT
npm ERR! errno -2
npm ERR! syscall rename
npm ERR! enoent ENOENT: no such file or directory, rename 'prodmode-client-mobile-builds/phonegap/node_modules/cordova-ios/node_modules/simple-plist/node_modules/base64-js' -> 'prodmode-client-mobile-builds/phonegap/node_modules/cordova-ios/node_modules/simple-plist/node_modules/.base64-js.DELETE'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

┌──────────────────────────────────────────────────────────┐
│                 npm update check failed                  │
│           Try running with sudo or get access            │
│           to the local update config store via           │
│ sudo chown -R $USER:$(id -gn $USER) /Users/apple/.config │
└──────────────────────────────────────────────────────────┘

npm ERR! A complete log of this run can be found in:
npm ERR! .npm/_logs/2017-11-10T00_23_21_467Z-debug.log

Step 3 (check git changes caused by the command in step 2)

Okay, so it failed. Let's find out what happened to the supposed missing file. Well, apparently cordova deleted the file before it looked for it?

apple@Child-2:~/projects/infiniteinternet/prodmode/prodmode-client-mobile-builds/phonegap * feature-barcode-scanner$ git status
# On branch feature-barcode-scanner
# Changes not staged for commit:
#   (use "git add/rm <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/base64-js/.npmignore
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/base64-js/.travis.yml
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/base64-js/LICENSE.MIT
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/base64-js/README.md
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/base64-js/base64js.min.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/base64-js/bower.json
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/base64-js/lib/b64.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/base64-js/package.json
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/base64-js/test/big-data.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/base64-js/test/convert.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/base64-js/test/url-safe.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/plist/.jshintrc
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/plist/.travis.yml
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/plist/History.md
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/plist/LICENSE
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/plist/Makefile
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/plist/README.md
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/plist/dist/plist-build.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/plist/dist/plist-parse.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/plist/dist/plist.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/plist/examples/browser/index.html
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/plist/index.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/plist/lib/build.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/plist/lib/parse.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/plist/package.json
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/.npmignore
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/CHANGELOG.md
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/LICENSE
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/README.md
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/Utility.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLAttribute.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLCData.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLComment.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLDTDAttList.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLDTDElement.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLDTDEntity.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLDTDNotation.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLDeclaration.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLDocType.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLDocument.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLDocumentCB.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLElement.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLNode.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLProcessingInstruction.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLRaw.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLStreamWriter.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLStringWriter.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLStringifier.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLText.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/XMLWriterBase.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/lib/index.js
#   deleted:    node_modules/cordova-ios/node_modules/simple-plist/node_modules/xmlbuilder/package.json
#
no changes added to commit (use "git add" and/or "git commit -a")

If anyone has any suggestions on how to fix this issue, I'd be super grateful. I'm not sure what caused it or when it took effect, but it's been a couple weeks now that I haven't been able to add plugins to my project.

Thanks in advance!

EDIT:
Environment settings:

apple@Child-2:/ $ cordova --version
7.0.1

┌──────────────────────────────────────────┐
│ Update available: 7.1.0 (current: 7.0.1) │
│ Run npm install -g cordova to update.    │
└──────────────────────────────────────────┘

apple@Child-2:/ $ phonegap --version
7.1.1
apple@Child-2:/ $ node --version
v6.11.1
apple@Child-2:/ $ npm --version
5.4.2


问:
isset() does not work correctly
Why isset($_POST['string']) works the same for php 5.3 and php 5.4?
After all, article http://php.net/manual/en/migration54.incompatible.php says that isset() will now work differently.

答:
As the description says:

Non-numeric string offsets - e.g. $a['foo'] where $a is a string - now return false on isset() and true on empty(), and produce a E_WARNING if you try to use them.

Offsets of types double, bool and null produce a E_NOTICE.

Numeric strings (e.g. $a['2']) still work as before. Note that offsets like '12.3' and '5 foobar' are considered non-numeric and produce a E_WARNING, but are converted to 12 and 5 respectively, for backward compatibility reasons.

Note: Following code returns different result.

```<code>$str='abc';var_dump(isset($str['x']));
// false for PHP 5.4 or later, but true for 5.3 or less
</code>```

It is only changed for strings treated as char arrays. For example:

```<code>$test = "str";
</code>```

is equal to

```<code>$test = ['s','t','r'];
</code>```

when being accessed with indexes.

Before PHP 5.4,

```<code>$test[2] will return 'r'
$test["2"] will also return 'r'
$test[2.3] will also return 'r'
$test["a"] will return false
isset($test["a"]) will return true
empty($test["a"]) will return false
</code>```

After PHP 5.4

```<code>$test[2] will return 'r'
$test["2"] will also return 'r'
$test[2.3] will also return 'r', but with a warning
$test["a"] will return false and produce a warning
isset($test["a"]) will return false
empty($test["a"]) will return true
</code>```

So,

$_POST is a real array, and string is a real key, it didn't change the way isset and empty acts on this.

Title: isset() does not work correctly

Body:
As the description says:

Non-numeric string offsets - e.g. $a['foo'] where $a is a string - now return false on isset() and true on empty(), and produce a E_WARNING if you try to use them.

Offsets of types double, bool and null produce a E_NOTICE.

Numeric strings (e.g. $a['2']) still work as before. Note that offsets like '12.3' and '5 foobar' are considered non-numeric and produce a E_WARNING, but are converted to 12 and 5 respectively, for backward compatibility reasons.

Note: Following code returns different result.

$str='abc';var_dump(isset($str['x']));
// false for PHP 5.4 or later, but true for 5.3 or less

It is only changed for strings treated as char arrays. For example:

$test = "str";

is equal to

$test = ['s','t','r'];

when being accessed with indexes.

Before PHP 5.4,

$test[2] will return 'r'
$test["2"] will also return 'r'
$test[2.3] will also return 'r'
$test["a"] will return false
isset($test["a"]) will return true
empty($test["a"]) will return false

After PHP 5.4

$test[2] will return 'r'
$test["2"] will also return 'r'
$test[2.3] will also return 'r', but with a warning
$test["a"] will return false and produce a warning
isset($test["a"]) will return false
empty($test["a"]) will return true

So,

$_POST is a real array, and string is a real key, it didn't change the way isset and empty acts on this.


问:
PyStan example program plot not showing
In trying the Stan 8 school example program the output is not plotting when using fit.plot().
https://pystan.readthedocs.io/en/latest/getting_started.html

I've installed matplotlib and the examples they provide plot.
I'm running it from macOS iterm.

答:
It was missing plt.show().
I've pasted the full code below. </p>

```<code>import pystan
import matplotlib.pyplot as plt

schools_code = """
data {
    int<lower=0> J; // number of schools
    real y[J]; // estimated treatment effects
    real<lower=0> sigma[J]; // s.e. of effect estimates
}
parameters {
    real mu;
    real<lower=0> tau;
    real eta[J];
}
transformed parameters {
    real theta[J];
    for (j in 1:J)
    theta[j] = mu + tau * eta[j];
}
model {
    eta ~ normal(0, 1);
    y ~ normal(theta, sigma);
}
"""

schools_dat = {'J': 8,
               'y': [28,  8, -3,  7, -1,  1, 18, 12],
               'sigma': [15, 10, 16, 11,  9, 11, 10, 18]}

sm = pystan.StanModel(model_code=schools_code)
fit = sm.sampling(data=schools_dat, iter=1000, chains=4)
print(fit)
fit.plot()

plt.show()
</code>```

Title: PyStan example program plot not showing

Body:
It was missing plt.show().
I've pasted the full code below.

import pystan
import matplotlib.pyplot as plt

schools_code = """
data {
    int<lower=0> J; // number of schools
    real y[J]; // estimated treatment effects
    real<lower=0> sigma[J]; // s.e. of effect estimates
}
parameters {
    real mu;
    real<lower=0> tau;
    real eta[J];
}
transformed parameters {
    real theta[J];
    for (j in 1:J)
    theta[j] = mu + tau * eta[j];
}
model {
    eta ~ normal(0, 1);
    y ~ normal(theta, sigma);
}
"""

schools_dat = {'J': 8,
               'y': [28,  8, -3,  7, -1,  1, 18, 12],
               'sigma': [15, 10, 16, 11,  9, 11, 10, 18]}

sm = pystan.StanModel(model_code=schools_code)
fit = sm.sampling(data=schools_dat, iter=1000, chains=4)
print(fit)
fit.plot()

plt.show()