问:
How to inject widgets between QHeaderView and QTableView?
I would like to display widgets between the QHeaderView and the rest of the QTableView, like in the example picture below (created with Photoshop), as this seems like a natural way to enable input for filtering columns.

Does anybody have any ideas of how to inject widgets inbetween?

答:
Below is a demo of a FilterHeader class that I wrote for one of my own projects. You will probably need to adapt it to suit your own needs, but it should already do most what you want. The padding around the filter boxes is unlikely to work the same on all platforms, so you may need to tweak the code in the adjustPositions method.

```<code>import sys
from PyQt4 import QtCore, QtGui

class FilterHeader(QtGui.QHeaderView):
    filterActivated = QtCore.pyqtSignal()

    def __init__(self, parent):
        super().__init__(QtCore.Qt.Horizontal, parent)
        self._editors = []
        self._padding = 4
        self.setStretchLastSection(True)
        self.setResizeMode(QtGui.QHeaderView.Stretch)
        self.setDefaultAlignment(
            QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
        self.setSortIndicatorShown(False)
        self.sectionResized.connect(self.adjustPositions)
        parent.horizontalScrollBar().valueChanged.connect(
            self.adjustPositions)

    def setFilterBoxes(self, count):
        while self._editors:
            editor = self._editors.pop()
            editor.deleteLater()
        for index in range(count):
            editor = QtGui.QLineEdit(self.parent())
            editor.setPlaceholderText('Filter')
            editor.returnPressed.connect(self.filterActivated.emit)
            self._editors.append(editor)
        self.adjustPositions()

    def sizeHint(self):
        size = super().sizeHint()
        if self._editors:
            height = self._editors[0].sizeHint().height()
            size.setHeight(size.height() + height + self._padding)
        return size

    def updateGeometries(self):
        if self._editors:
            height = self._editors[0].sizeHint().height()
            self.setViewportMargins(0, 0, 0, height + self._padding)
        else:
            self.setViewportMargins(0, 0, 0, 0)
        super().updateGeometries()
        self.adjustPositions()

    def adjustPositions(self):
        for index, editor in enumerate(self._editors):
            height = editor.sizeHint().height()
            editor.move(
                self.sectionPosition(index) - self.offset() + 2,
                height + (self._padding // 2))
            editor.resize(self.sectionSize(index), height)

    def filterText(self, index):
        if 0 <= index < len(self._editors):
            return self._editors[index].text()
        return ''

    def setFilterText(self, index, text):
        if 0 <= index < len(self._editors):
            self._editors[index].setText(text)

    def clearFilters(self):
        for editor in self._editors:
            editor.clear()

class Window(QtGui.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.view = QtGui.QTableView()
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.view)
        header = FilterHeader(self.view)
        self.view.setHorizontalHeader(header)
        model = QtGui.QStandardItemModel(self.view)
        model.setHorizontalHeaderLabels('One Two Three Four Five'.split())
        self.view.setModel(model)
        header.setFilterBoxes(model.columnCount())
        header.filterActivated.connect(self.handleFilterActivated)

    def handleFilterActivated(self):
        header = self.view.horizontalHeader()
        for index in range(header.count()):
            print((index, header.filterText(index)))

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(600, 100, 600, 300)
    window.show()
    sys.exit(app.exec_())
</code>```

Body:
Below is a demo of a FilterHeader class that I wrote for one of my own projects. You will probably need to adapt it to suit your own needs, but it should already do most what you want. The padding around the filter boxes is unlikely to work the same on all platforms, so you may need to tweak the code in the adjustPositions method.

import sys
from PyQt4 import QtCore, QtGui

class FilterHeader(QtGui.QHeaderView):
    filterActivated = QtCore.pyqtSignal()

    def __init__(self, parent):
        super().__init__(QtCore.Qt.Horizontal, parent)
        self._editors = []
        self._padding = 4
        self.setStretchLastSection(True)
        self.setResizeMode(QtGui.QHeaderView.Stretch)
        self.setDefaultAlignment(
            QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
        self.setSortIndicatorShown(False)
        self.sectionResized.connect(self.adjustPositions)
        parent.horizontalScrollBar().valueChanged.connect(
            self.adjustPositions)

    def setFilterBoxes(self, count):
        while self._editors:
            editor = self._editors.pop()
            editor.deleteLater()
        for index in range(count):
            editor = QtGui.QLineEdit(self.parent())
            editor.setPlaceholderText('Filter')
            editor.returnPressed.connect(self.filterActivated.emit)
            self._editors.append(editor)
        self.adjustPositions()

    def sizeHint(self):
        size = super().sizeHint()
        if self._editors:
            height = self._editors[0].sizeHint().height()
            size.setHeight(size.height() + height + self._padding)
        return size

    def updateGeometries(self):
        if self._editors:
            height = self._editors[0].sizeHint().height()
            self.setViewportMargins(0, 0, 0, height + self._padding)
        else:
            self.setViewportMargins(0, 0, 0, 0)
        super().updateGeometries()
        self.adjustPositions()

    def adjustPositions(self):
        for index, editor in enumerate(self._editors):
            height = editor.sizeHint().height()
            editor.move(
                self.sectionPosition(index) - self.offset() + 2,
                height + (self._padding // 2))
            editor.resize(self.sectionSize(index), height)

    def filterText(self, index):
        if 0 <= index < len(self._editors):
            return self._editors[index].text()
        return ''

    def setFilterText(self, index, text):
        if 0 <= index < len(self._editors):
            self._editors[index].setText(text)

    def clearFilters(self):
        for editor in self._editors:
            editor.clear()

class Window(QtGui.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.view = QtGui.QTableView()
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.view)
        header = FilterHeader(self.view)
        self.view.setHorizontalHeader(header)
        model = QtGui.QStandardItemModel(self.view)
        model.setHorizontalHeaderLabels('One Two Three Four Five'.split())
        self.view.setModel(model)
        header.setFilterBoxes(model.columnCount())
        header.filterActivated.connect(self.handleFilterActivated)

    def handleFilterActivated(self):
        header = self.view.horizontalHeader()
        for index in range(header.count()):
            print((index, header.filterText(index)))

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(600, 100, 600, 300)
    window.show()
    sys.exit(app.exec_())


来源: stackexchange

问:
How to run docker with experimental functions on Ubuntu 16.04
I have following question:

How to run docker with experimental features on (like image squashing docker build --squash=true... for reduce it size) on ubuntu 16.04 ?

答:
To turn on experimental docker functions create following file by:

sudo nano /etc/docker/daemon.json

and add below content to it

```<code>{
    "experimental": true
}
</code>```

and save file (by CTRL+X and Enter ) and exit. In terminal type:

sudo service docker restart

To check that experimental funcions are ON, type in terminal:

docker version

And you should see  Experimental: true

UPDATE

Instead of nano you can use this one-liner:

```<code>echo $'{\n    "experimental": true\n}' | sudo tee /etc/docker/daemon.json
</code>```

ContentLicense: CC BY-SA 3.0

Body:
To turn on experimental docker functions create following file by:

sudo nano /etc/docker/daemon.json

and add below content to it

{
    "experimental": true
}

and save file (by CTRL+X and Enter ) and exit. In terminal type:

sudo service docker restart

To check that experimental funcions are ON, type in terminal:

docker version

And you should see  Experimental: true

UPDATE

Instead of nano you can use this one-liner:

echo $'{\n    "experimental": true\n}' | sudo tee /etc/docker/daemon.json

ContentLicense: CC BY-SA 4.0


问:
postgresql update column from select
I am attempting to update a column from one table with a select query.

It runs and updates the entire type_ column as religious (text field).

I am trying to only update the rows where the religious geometry intersects the parcel geometry.

```<code>update wash_parcels_final
set    type_ = t.religious
from   (select wash_worship.religious
        from   wash_parcels_final
        join   wash_worship
        on     st_intersects(wash_worship.geom, wash_parcels_final.geom)) t
</code>```

答:
I think this is what you want:</p>

```<code>update wash_parcels_final
    set type_ = ww.religious
    from wash_worship ww
    where st_intersects(ww.geom, wash_parcels_final.geom);
</code>```

Title: postgresql update column from select

Body:
I am attempting to update a column from one table with a select query.

It runs and updates the entire type_ column as religious (text field).

I am trying to only update the rows where the religious geometry intersects the parcel geometry.

update wash_parcels_final
set    type_ = t.religious
from   (select wash_worship.religious
        from   wash_parcels_final
        join   wash_worship
        on     st_intersects(wash_worship.geom, wash_parcels_final.geom)) t

Body:
I think this is what you want:

update wash_parcels_final
    set type_ = ww.religious
    from wash_worship ww
    where st_intersects(ww.geom, wash_parcels_final.geom);


问:
prototype function missing when calling third party node package in Angular 2+
I am trying to use a third party Node module in an angular 2+ project.

installed with npm install --save ModuleName

The function in question is in a file named Foo.js and looks like this:

```<code>var foo = function(param1, param2) {
    ...
    this.init();
}

foo.protoype = {
    constructor: foo,

    init: function(){
        ...
    },
    ...
}

module.exports = foo;
</code>```

index.js for the node module looks like:

```<code>var ModuleName = require("./src/ModuleName");
ModuleName.foo = require("./src/Foo");

module.exports = ModuleName;
</code>```

I am trying to use the module in a Directive:

```<code>import { Directive, OnInit } from '@angular/core';
import { ModuleName } from "ModuleName"

@Directive({
  selector: '[customDirective]'
})
export class CustomDirective implements OnInit {
  constructor() {
    ...
  }

  ngOnInit() {
    let poorlyNamedVariable = ModuleName.foo(param1, param2);
  }
}
</code>```

When foo is called it produces ERROR TypeError: this.init is not a function

console.log(this) in foo shows an instance of ModuleName which, in turn, has an instance of foo, which has a prototype where init is defined.

I suspect the problem stems from some sort of scoping issue, but am still too new to both Angular and Node to untangle the mess.

答: Use import * as ModuleName from "ModuleName" for CommonJS modules.

Body:
I am trying to use a third party Node module in an angular 2+ project.

installed with npm install --save ModuleName

The function in question is in a file named Foo.js and looks like this:

var foo = function(param1, param2) {
    ...
    this.init();
}

foo.protoype = {
    constructor: foo,

    init: function(){
        ...
    },
    ...
}

module.exports = foo;

index.js for the node module looks like:

var ModuleName = require("./src/ModuleName");
ModuleName.foo = require("./src/Foo");

module.exports = ModuleName;

I am trying to use the module in a Directive:

import { Directive, OnInit } from '@angular/core';
import { ModuleName } from "ModuleName"

@Directive({
  selector: '[customDirective]'
})
export class CustomDirective implements OnInit {
  constructor() {
    ...
  }

  ngOnInit() {
    let poorlyNamedVariable = ModuleName.foo(param1, param2);
  }
}

When foo is called it produces ERROR TypeError: this.init is not a function

console.log(this) in foo shows an instance of ModuleName which, in turn, has an instance of foo, which has a prototype where init is defined.

I suspect the problem stems from some sort of scoping issue, but am still too new to both Angular and Node to untangle the mess.


问:
How should I loop through this JSON data?
Here is my code I want to print out "song" property from data. Link to JSON is -> http://starlord.hackerearth.com/sureify/cokestudio

```<code><script type="text/javascript">
    var requestURL = 'http://starlord.hackerearth.com/sureify/cokestudio';

    var request = new XMLHttpRequest();

    request.open('GET', requestURL);

    request.responseType = 'json';

    request.send();

    request.onload = function(){
        var myjsondata = request.response;
        showdata(myjsondata);
    }

    function showdata(data){
        var song_name = data;

        for (i = 0; i < 3; i++) {

            document.write(song_name);
            document.write("<br>");

        }
    }

</script>
</code>```

When I run it in browser I get [object Object],[object Object],[object Object],[object Object],[object Object] as OUTPUT or undefined.

答:
Your data looks like this:

```<code>[  //the array in data
{  //the first object, e. g. data[0]
  "song":"Afreen Afreen", // song => data[0].song
  "url":"http://hck.re/Rh8KTk",
  "artists":"Rahat Fateh Ali Khan, Momina Mustehsan",
  "cover_image":"http://hck.re/kWWxUI"
},
{
  "song":"Aik Alif",
  "url":"http://hck.re/ZeSJFd",
  "artists":"Saieen Zahoor, Noori",
  "cover_image":"http://hck.re/3Cm0IX"
},
{
  "song":"Tajdar e haram",
  "url":"http://hck.re/wxlUcX",
  "artists":"Atif Aslam",
  "cover_image":"http://hck.re/5dh4D5"
}]
</code>```

So to loop over one can do

```<code>var limit=Math.max(data.length,100);//max displayed number

for(var i=0;i<limit;i++){
 document.write(data[i].song+"<br>");
}
</code>```

Whole code:

    document.write("loading...");

    xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
      if (xhr.readyState == XMLHttpRequest.DONE) {
        var data= JSON.parse(xhr.responseText);
        var limit=Math.max(data.length,100);
        for(var i=0;i<limit;i++){
         document.write(data[i].song+"
");
        }
      }
    };

    xhr.open('GET', 'http://starlord.hackerearth.com/sureify/cokestudio', true);
    xhr.send(null);```

Body:
Here is my code I want to print out "song" property from data. Link to JSON is -> http://starlord.hackerearth.com/sureify/cokestudio

When I run it in browser I get [object Object],[object Object],[object Object],[object Object],[object Object] as OUTPUT or undefined.

Body:
Your data looks like this:

[  //the array in data
{  //the first object, e. g. data[0]
  "song":"Afreen Afreen", // song => data[0].song
  "url":"http://hck.re/Rh8KTk",
  "artists":"Rahat Fateh Ali Khan, Momina Mustehsan",
  "cover_image":"http://hck.re/kWWxUI"
},
{
  "song":"Aik Alif",
  "url":"http://hck.re/ZeSJFd",
  "artists":"Saieen Zahoor, Noori",
  "cover_image":"http://hck.re/3Cm0IX"
},
{
  "song":"Tajdar e haram",
  "url":"http://hck.re/wxlUcX",
  "artists":"Atif Aslam",
  "cover_image":"http://hck.re/5dh4D5"
}]

So to loop over one can do

var limit=Math.max(data.length,100);//max displayed number

for(var i=0;i<limit;i++){
 document.write(data[i].song+"<br>");
}

Whole code:

    document.write("loading...");

    xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
      if (xhr.readyState == XMLHttpRequest.DONE) {
        var data= JSON.parse(xhr.responseText);
        var limit=Math.max(data.length,100);
        for(var i=0;i<limit;i++){
         document.write(data[i].song+"<br>");
        }
      }
    };

    xhr.open('GET', 'http://starlord.hackerearth.com/sureify/cokestudio', true);
    xhr.send(null);


问:
Merging text nodes in XSLT
I have been trying to merge all the text nodes in books.xml if their attribute values matches. And these values shoud be seperated by any delimeter(EX: , etc..)

Here is the souce XML:

```<code><catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications
      with XML.</description>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world.</description>
   </book>
   <book id="bk103">
      <author>Corets, Eva</author>
      <title>Maeve Ascendant</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-11-17</publish_date>
      <description>After the collapse of a nanotechnology
      society in England, the young survivors lay the
      foundation for a new society.</description>
   </book>
   <book id="bk101">
      <author>Corets, Eva</author>
      <title>Oberon's Legacy</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2001-03-10</publish_date>
      <description>In post-apocalypse England, the mysterious
      agent known only as Oberon helps to create a new life
      for the inhabitants of London. Sequel to Maeve
      Ascendant.</description>
   </book>
   <book id="bk102">
      <author>Corets, Eva</author>
      <title>The Sundered Grail</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2001-09-10</publish_date>
      <description>The two daughters of Maeve, half-sisters,
      battle one another for control of England. Sequel to
      Oberon's Legacy.</description>
   </book>
   <book id="bk101">
      <author>Galos, Mike</author>
      <title>Visual Studio 7: A Comprehensive Guide</title>
      <genre>Computer</genre>
      <price>49.95</price>
      <publish_date>2001-04-16</publish_date>
      <description>Microsoft Visual Studio 7 is explored in depth,
      looking at how Visual Basic, Visual C++, C#, and ASP+ are
      integrated into a comprehensive development
      environment.</description>
   </book>
</catalog>
</code>```

This is the Desired Output:

```<code><catalog>
   <book id="bk101">
      <author>Gambardella, Matthew  Galos, Mike  Corets, Eva</author>
      <title>XML Developer's Guide  Visual Studio 7: A Comprehensive Guide  Oberon's Legacy</title>
      <genre>Computer  Computer</genre>
      <price>44.95  49.95  5.95</price>
      <publish_date>2000-10-01  2001-04-16  2001-03-10</publish_date>
      <description>An in-depth look at creating applications
      with XML. Microsoft Visual Studio 7 is explored in depth,
      looking at how Visual Basic, Visual C++, C#, and ASP+ are
      integrated into a comprehensive development
      environment.  In post-apocalypse England, the mysterious
      agent known only as Oberon helps to create a new life
      for the inhabitants of London. Sequel to Maeve
      Ascendant.</description>
   <book id="bk102">
      <author>Ralls, Kim  Corets, Eva</author>
      <title>Midnight Rain  The Sundered Grail</title>
      <genre>Fantasy  Fantasy</genre>
      <price>5.95  5.95</price>
      <publish_date>2000-12-16  2001-09-10</publish_date>
      <description>A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world.  The two daughters of Maeve, half-sisters,
      battle one another for control of England. Sequel to
      Oberon's Legacy.</description>
   </book>
   <book id="bk103">
      <author>Corets, Eva</author>
      <title>Maeve Ascendant</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-11-17</publish_date>
      <description>After the collapse of a nanotechnology
      society in England, the young survivors lay the
      foundation for a new society.</description>
   </book>
</catalog>
</code>```

This is the XSLT I have been trying:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">
    <xsl:output method="xml" indent="yes"/>
    <xsl:key name="Dbook" match="book" use="@id"/>

    <xsl:template match="/catalog">
       <xsl:copy>
        <xsl:for-each select="book[count(. | key('Dbook', @id)[1])=1]">
            <xsl:copy>
             <xsl:copy-of select="@*"/>
               <xsl:for-each select="key('Dbook',@id)">
                   <xsl:variable name="author" select="author"/>
                   <xsl:variable name="title" select="title"/>
                   <xsl:variable name="genre" select="genre"/>
                   <xsl:variable name="price" select="price"/>
                   <xsl:variable name="publish_date" select="publish_date"/>
                   <xsl:variable name="description" select="description"/>
                   <xsl:variable name="null"/>

                   <xsl:copy-of select="concat($author,$null)"/>
                   <xsl:copy-of select="concat($title,$null)"/>
                   <xsl:copy-of select="concat($genre,$null)"/>
                   <xsl:copy-of select="concat($price,$null)"/>
                   <xsl:copy-of select="concat($publish_date,$null)"/>
                   <xsl:copy-of select="concat($description,$null)"/>

               </xsl:for-each>
            </xsl:copy>
        </xsl:for-each>
       </xsl:copy>
    </xsl:template>

</xsl:stylesheet>
</code>```

答:
A simple (even if tedious) solution in XSLT 1.0 would look like this:

XSLT 1.0

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:key name="Dbook" match="book" use="@id"/>
<xsl:variable name="separator" select="' & '" />

<xsl:template match="/catalog">
    <xsl:copy>
        <xsl:for-each select="book[count(. | key('Dbook', @id)[1])=1]">
            <xsl:copy>
                <xsl:copy-of select="@*"/>
                <xsl:variable name="group" select="key('Dbook', @id)" />
                <author>
                    <xsl:for-each select="$group">
                        <xsl:value-of select="author"/>
                        <xsl:if test="position()!=last()">
                            <xsl:value-of select="$separator"/>
                        </xsl:if>
                    </xsl:for-each>
                </author>
                <title>
                    <xsl:for-each select="$group">
                        <xsl:value-of select="title"/>
                        <xsl:if test="position()!=last()">
                            <xsl:value-of select="$separator"/>
                        </xsl:if>
                    </xsl:for-each>
                </title>

                <!-- add more child elements here -->

            </xsl:copy>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>
</code>```

Result

```<code><?xml version="1.0" encoding="UTF-8"?>
<catalog>
  <book id="bk101">
    <author>Gambardella, Matthew & Corets, Eva & Galos, Mike</author>
    <title>XML Developer's Guide & Oberon's Legacy & Visual Studio 7: A Comprehensive Guide</title>
  </book>
  <book id="bk102">
    <author>Ralls, Kim & Corets, Eva</author>
    <title>Midnight Rain & The Sundered Grail</title>
  </book>
  <book id="bk103">
    <author>Corets, Eva</author>
    <title>Maeve Ascendant</title>
  </book>
</catalog>
</code>```

To eliminate the repetition of code for each child property of a book, you could define another key and use it as follows:

XSLT 1.0

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:key name="Dbook" match="book" use="@id"/>
<xsl:key name="book-property" match="book/*" use="concat(../@id, '|', name())"/>

<xsl:variable name="separator" select="' & '" />

<xsl:template match="/catalog">
    <xsl:copy>
        <xsl:for-each select="book[count(. | key('Dbook', @id)[1])=1]">
            <xsl:copy>
                <xsl:copy-of select="@*"/>
                <xsl:for-each select="*">
                    <xsl:copy>
                        <xsl:for-each select="key('book-property', concat(../@id, '|', name()))">
                            <xsl:value-of select="."/>
                            <xsl:if test="position()!=last()">
                                <xsl:value-of select="$separator"/>
                            </xsl:if>
                        </xsl:for-each>
                    </xsl:copy>
                </xsl:for-each>
            </xsl:copy>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>
</code>```

Result

```<code><?xml version="1.0" encoding="UTF-8"?>
<catalog>
  <book id="bk101">
    <author>Gambardella, Matthew & Corets, Eva & Galos, Mike</author>
    <title>XML Developer's Guide & Oberon's Legacy & Visual Studio 7: A Comprehensive Guide</title>
    <genre>Computer & Fantasy & Computer</genre>
    <price>44.95 & 5.95 & 49.95</price>
    <publish_date>2000-10-01 & 2001-03-10 & 2001-04-16</publish_date>
    <description>An in-depth look at creating applications
      with XML. & In post-apocalypse England, the mysterious
      agent known only as Oberon helps to create a new life
      for the inhabitants of London. Sequel to Maeve
      Ascendant. & Microsoft Visual Studio 7 is explored in depth,
      looking at how Visual Basic, Visual C++, C#, and ASP+ are
      integrated into a comprehensive development
      environment.</description>
  </book>
  <book id="bk102">
    <author>Ralls, Kim & Corets, Eva</author>
    <title>Midnight Rain & The Sundered Grail</title>
    <genre>Fantasy & Fantasy</genre>
    <price>5.95 & 5.95</price>
    <publish_date>2000-12-16 & 2001-09-10</publish_date>
    <description>A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world. & The two daughters of Maeve, half-sisters,
      battle one another for control of England. Sequel to
      Oberon's Legacy.</description>
  </book>
  <book id="bk103">
    <author>Corets, Eva</author>
    <title>Maeve Ascendant</title>
    <genre>Fantasy</genre>
    <price>5.95</price>
    <publish_date>2000-11-17</publish_date>
    <description>After the collapse of a nanotechnology
      society in England, the young survivors lay the
      foundation for a new society.</description>
  </book>
</catalog>
</code>```

Title: Merging text nodes in XSLT

Body:
I have been trying to merge all the text nodes in books.xml if their attribute values matches. And these values shoud be seperated by any delimeter(EX: , etc..)

Here is the souce XML:

<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications
      with XML.</description>
   </book>
   <book id="bk102">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world.</description>
   </book>
   <book id="bk103">
      <author>Corets, Eva</author>
      <title>Maeve Ascendant</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-11-17</publish_date>
      <description>After the collapse of a nanotechnology
      society in England, the young survivors lay the
      foundation for a new society.</description>
   </book>
   <book id="bk101">
      <author>Corets, Eva</author>
      <title>Oberon's Legacy</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2001-03-10</publish_date>
      <description>In post-apocalypse England, the mysterious
      agent known only as Oberon helps to create a new life
      for the inhabitants of London. Sequel to Maeve
      Ascendant.</description>
   </book>
   <book id="bk102">
      <author>Corets, Eva</author>
      <title>The Sundered Grail</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2001-09-10</publish_date>
      <description>The two daughters of Maeve, half-sisters,
      battle one another for control of England. Sequel to
      Oberon's Legacy.</description>
   </book>
   <book id="bk101">
      <author>Galos, Mike</author>
      <title>Visual Studio 7: A Comprehensive Guide</title>
      <genre>Computer</genre>
      <price>49.95</price>
      <publish_date>2001-04-16</publish_date>
      <description>Microsoft Visual Studio 7 is explored in depth,
      looking at how Visual Basic, Visual C++, C#, and ASP+ are
      integrated into a comprehensive development
      environment.</description>
   </book>
</catalog>

This is the Desired Output:

<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew  Galos, Mike  Corets, Eva</author>
      <title>XML Developer's Guide  Visual Studio 7: A Comprehensive Guide  Oberon's Legacy</title>
      <genre>Computer  Computer</genre>
      <price>44.95  49.95  5.95</price>
      <publish_date>2000-10-01  2001-04-16  2001-03-10</publish_date>
      <description>An in-depth look at creating applications
      with XML. Microsoft Visual Studio 7 is explored in depth,
      looking at how Visual Basic, Visual C++, C#, and ASP+ are
      integrated into a comprehensive development
      environment.  In post-apocalypse England, the mysterious
      agent known only as Oberon helps to create a new life
      for the inhabitants of London. Sequel to Maeve
      Ascendant.</description>
   <book id="bk102">
      <author>Ralls, Kim  Corets, Eva</author>
      <title>Midnight Rain  The Sundered Grail</title>
      <genre>Fantasy  Fantasy</genre>
      <price>5.95  5.95</price>
      <publish_date>2000-12-16  2001-09-10</publish_date>
      <description>A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world.  The two daughters of Maeve, half-sisters,
      battle one another for control of England. Sequel to
      Oberon's Legacy.</description>
   </book>
   <book id="bk103">
      <author>Corets, Eva</author>
      <title>Maeve Ascendant</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-11-17</publish_date>
      <description>After the collapse of a nanotechnology
      society in England, the young survivors lay the
      foundation for a new society.</description>
   </book>
</catalog>

This is the XSLT I have been trying:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">
    <xsl:output method="xml" indent="yes"/>
    <xsl:key name="Dbook" match="book" use="@id"/>

    <xsl:template match="/catalog">
       <xsl:copy>
        <xsl:for-each select="book[count(. | key('Dbook', @id)[1])=1]">
            <xsl:copy>
             <xsl:copy-of select="@*"/>
               <xsl:for-each select="key('Dbook',@id)">
                   <xsl:variable name="author" select="author"/>
                   <xsl:variable name="title" select="title"/>
                   <xsl:variable name="genre" select="genre"/>
                   <xsl:variable name="price" select="price"/>
                   <xsl:variable name="publish_date" select="publish_date"/>
                   <xsl:variable name="description" select="description"/>
                   <xsl:variable name="null"/>

                   <xsl:copy-of select="concat($author,$null)"/>
                   <xsl:copy-of select="concat($title,$null)"/>
                   <xsl:copy-of select="concat($genre,$null)"/>
                   <xsl:copy-of select="concat($price,$null)"/>
                   <xsl:copy-of select="concat($publish_date,$null)"/>
                   <xsl:copy-of select="concat($description,$null)"/>

               </xsl:for-each>
            </xsl:copy>
        </xsl:for-each>
       </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

Body:
A simple (even if tedious) solution in XSLT 1.0 would look like this:

XSLT 1.0

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:key name="Dbook" match="book" use="@id"/>
<xsl:variable name="separator" select="' &amp; '" />

<xsl:template match="/catalog">
    <xsl:copy>
        <xsl:for-each select="book[count(. | key('Dbook', @id)[1])=1]">
            <xsl:copy>
                <xsl:copy-of select="@*"/>
                <xsl:variable name="group" select="key('Dbook', @id)" />
                <author>
                    <xsl:for-each select="$group">
                        <xsl:value-of select="author"/>
                        <xsl:if test="position()!=last()">
                            <xsl:value-of select="$separator"/>
                        </xsl:if>
                    </xsl:for-each>
                </author>
                <title>
                    <xsl:for-each select="$group">
                        <xsl:value-of select="title"/>
                        <xsl:if test="position()!=last()">
                            <xsl:value-of select="$separator"/>
                        </xsl:if>
                    </xsl:for-each>
                </title>

                <!-- add more child elements here -->

            </xsl:copy>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Result

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
  <book id="bk101">
    <author>Gambardella, Matthew &amp; Corets, Eva &amp; Galos, Mike</author>
    <title>XML Developer's Guide &amp; Oberon's Legacy &amp; Visual Studio 7: A Comprehensive Guide</title>
  </book>
  <book id="bk102">
    <author>Ralls, Kim &amp; Corets, Eva</author>
    <title>Midnight Rain &amp; The Sundered Grail</title>
  </book>
  <book id="bk103">
    <author>Corets, Eva</author>
    <title>Maeve Ascendant</title>
  </book>
</catalog>

To eliminate the repetition of code for each child property of a book, you could define another key and use it as follows:

XSLT 1.0

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:key name="Dbook" match="book" use="@id"/>
<xsl:key name="book-property" match="book/*" use="concat(../@id, '|', name())"/>

<xsl:variable name="separator" select="' &amp; '" />

<xsl:template match="/catalog">
    <xsl:copy>
        <xsl:for-each select="book[count(. | key('Dbook', @id)[1])=1]">
            <xsl:copy>
                <xsl:copy-of select="@*"/>
                <xsl:for-each select="*">
                    <xsl:copy>
                        <xsl:for-each select="key('book-property', concat(../@id, '|', name()))">
                            <xsl:value-of select="."/>
                            <xsl:if test="position()!=last()">
                                <xsl:value-of select="$separator"/>
                            </xsl:if>
                        </xsl:for-each>
                    </xsl:copy>
                </xsl:for-each>
            </xsl:copy>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Result

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
  <book id="bk101">
    <author>Gambardella, Matthew &amp; Corets, Eva &amp; Galos, Mike</author>
    <title>XML Developer's Guide &amp; Oberon's Legacy &amp; Visual Studio 7: A Comprehensive Guide</title>
    <genre>Computer &amp; Fantasy &amp; Computer</genre>
    <price>44.95 &amp; 5.95 &amp; 49.95</price>
    <publish_date>2000-10-01 &amp; 2001-03-10 &amp; 2001-04-16</publish_date>
    <description>An in-depth look at creating applications
      with XML. &amp; In post-apocalypse England, the mysterious
      agent known only as Oberon helps to create a new life
      for the inhabitants of London. Sequel to Maeve
      Ascendant. &amp; Microsoft Visual Studio 7 is explored in depth,
      looking at how Visual Basic, Visual C++, C#, and ASP+ are
      integrated into a comprehensive development
      environment.</description>
  </book>
  <book id="bk102">
    <author>Ralls, Kim &amp; Corets, Eva</author>
    <title>Midnight Rain &amp; The Sundered Grail</title>
    <genre>Fantasy &amp; Fantasy</genre>
    <price>5.95 &amp; 5.95</price>
    <publish_date>2000-12-16 &amp; 2001-09-10</publish_date>
    <description>A former architect battles corporate zombies,
      an evil sorceress, and her own childhood to become queen
      of the world. &amp; The two daughters of Maeve, half-sisters,
      battle one another for control of England. Sequel to
      Oberon's Legacy.</description>
  </book>
  <book id="bk103">
    <author>Corets, Eva</author>
    <title>Maeve Ascendant</title>
    <genre>Fantasy</genre>
    <price>5.95</price>
    <publish_date>2000-11-17</publish_date>
    <description>After the collapse of a nanotechnology
      society in England, the young survivors lay the
      foundation for a new society.</description>
  </book>
</catalog>


问:
Reload/Update View In Swift
I'm busy making an app with an account page. I want that users can logon via that page and as soon as they have done so successfully that the page reloads to display their account information rather than the standard message stating that they have to logon to make use of the page.

However when I get sent back to the account page from logging on the view doesn't really update. So therefore I am wondering if I can't reload the view after certain buttons are pressed that can check again wether the user is logged on or not and deal accordingly.

答:
The Swift have really advanced itself and for many people if they don't know we can refresh the whole view with just one simple line of code.

viewWillAppear(true)

Title: Reload/Update View In Swift


问:
Invalid operands to binary expression error...when creating ratio
```<code>double profit_ratio = ((double) definitive_seller_profit) / ((double)definitive_buyer_profit);

        if(definitive_buyer_profit > definitive_seller_profit){

            if(definitive_buyer_move < 0 && definitive_seller_move < 0 && profit_ratio >= 0.50){ // give seller a chance if it's on the way and at least 50% profit ratio

                if((definitive_buyer_move < definitive_seller_move)){
                    *n = to_fuel_or_not_to_fuel(b, definitive_seller_move, fuel_ratio);
                } else {
                    *n = to_fuel_or_not_to_fuel(b, definitive_buyer_move, fuel_ratio);
                }
            }

            } else if(definitive_buyer_move > 0 && definitive_seller_move > 0 &&  && profit_ratio >= 0.50){

                if(definitive_buyer_move > definitive_seller_move){

                    *n = to_fuel_or_not_to_fuel(b, definitive_seller_move, fuel_ratio);
                }
                else {
                    *n = to_fuel_or_not_to_fuel(b, definitive_buyer_move, fuel_ratio);
                }

            } else{

                *n = to_fuel_or_not_to_fuel(b, definitive_buyer_move, fuel_ratio);

            }

        }
</code>```

So I'm getting invalid operands to binary expression ('void*'and 'double') in line:

else if(definitive_buyer_move > 0 && definitive_seller_move > 0 &&  && profit_ratio >= 0.50)

And I'm also getting...undeclared label 'profit_ratio.'

答:
Change this line :-

} else if(definitive_buyer_move > 0 && definitive_seller_move > 0 &&  && profit_ratio >= 0.50){

to

} else if(definitive_buyer_move > 0 && definitive_seller_move > 0 && profit_ratio >= 0.50){

You have 2 && && s

Also consider parenthesizing your logic for better readability:-

} else if((definitive_buyer_move > 0) && (definitive_seller_move > 0) && ( profit_ratio >= 0.50)){

Body:
double profit_ratio = ((double) definitive_seller_profit) / ((double)definitive_buyer_profit);

        if(definitive_buyer_profit > definitive_seller_profit){

            if(definitive_buyer_move < 0 && definitive_seller_move < 0 && profit_ratio >= 0.50){ // give seller a chance if it's on the way and at least 50% profit ratio

                if((definitive_buyer_move < definitive_seller_move)){
                    *n = to_fuel_or_not_to_fuel(b, definitive_seller_move, fuel_ratio);
                } else {
                    *n = to_fuel_or_not_to_fuel(b, definitive_buyer_move, fuel_ratio);
                }
            }

            } else if(definitive_buyer_move > 0 && definitive_seller_move > 0 &&  && profit_ratio >= 0.50){

                if(definitive_buyer_move > definitive_seller_move){

                    *n = to_fuel_or_not_to_fuel(b, definitive_seller_move, fuel_ratio);
                }
                else {
                    *n = to_fuel_or_not_to_fuel(b, definitive_buyer_move, fuel_ratio);
                }

            } else{

                *n = to_fuel_or_not_to_fuel(b, definitive_buyer_move, fuel_ratio);

            }

        }

So I'm getting invalid operands to binary expression ('void*'and 'double') in line:

else if(definitive_buyer_move > 0 && definitive_seller_move > 0 &&  && profit_ratio >= 0.50)

And I'm also getting...undeclared label 'profit_ratio.'


问:
WooCommerce Additional Information - if empty, hide
I'm working on an eCommerce project at the moment.  I'm using WooCommerce in WordPress.

I've got ridden of the product data tabs and displayed product descriptions and additional information within the summary section.

I would like to know how to hide the additional information section if it's empty? Or even, generate a text saying 'None'?

Any help would be appreciated.  Mille merci!

答:
```<code>add_filter( 'woocommerce_product_tabs', 'am_ninja_remove_product_tabs', 98 );

function am_ninja_remove_product_tabs( $tabs ) {

    global $product;
    $id = $product->get_id(); // change this to $product->id fro WC less than 2.7

    $my_custom_data = get_post_meta($id, 'am_ninja', true );

    if(empty($my_custom_data)) {
        unset( $tabs['additional_information'] );   // Remove the additional information tab
    }

    return $tabs;
}
</code>```

Check this code snippet

Body:
add_filter( 'woocommerce_product_tabs', 'am_ninja_remove_product_tabs', 98 );

function am_ninja_remove_product_tabs( $tabs ) {

    global $product;
    $id = $product->get_id(); // change this to $product->id fro WC less than 2.7

    $my_custom_data = get_post_meta($id, 'am_ninja', true );

    if(empty($my_custom_data)) {
        unset( $tabs['additional_information'] );   // Remove the additional information tab
    }

    return $tabs;
}

Check this code snippet


问:
Could not resolve active android dependency in Gradle when Active Android is included in library
I have a library project that includes active android using Gradle.
To get it to work I have to add

```<code>compile 'com.michaelpardo:activeandroid:3.1.0-SNAPSHOT'
</code>```

and add the repository for it like so:

```<code>repositories {
    maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
}
</code>```

However if I do this in the library project, I get the error:

```<code>Error:A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_debugCompile'.
   > Could not find com.michaelpardo:activeandroid:3.1.0-SNAPSHOT.
     Searched in the following locations:
         https://jcenter.bintray.com/com/michaelpardo/activeandroid/3.1.0-SNAPSHOT/maven-metadata.xml
         https://jcenter.bintray.com/com/michaelpardo/activeandroid/3.1.0-SNAPSHOT/activeandroid-3.1.0-SNAPSHOT.pom
         https://jcenter.bintray.com/com/michaelpardo/activeandroid/3.1.0-SNAPSHOT/activeandroid-3.1.0-SNAPSHOT.jar
         file:/Users/user/AndroidSDK/extras/android/m2repository/com/michaelpardo/activeandroid/3.1.0-SNAPSHOT/maven-metadata.xml
         file:/Users/user/AndroidSDK/extras/android/m2repository/com/michaelpardo/activeandroid/3.1.0-SNAPSHOT/activeandroid-3.1.0-SNAPSHOT.pom
         file:/Users/user/AndroidSDK/extras/android/m2repository/com/michaelpardo/activeandroid/3.1.0-SNAPSHOT/activeandroid-3.1.0-SNAPSHOT.jar
         file:/Users/user/AndroidSDK/extras/google/m2repository/com/michaelpardo/activeandroid/3.1.0-SNAPSHOT/maven-metadata.xml
         file:/Users/user/AndroidSDK/extras/google/m2repository/com/michaelpardo/activeandroid/3.1.0-SNAPSHOT/activeandroid-3.1.0-SNAPSHOT.pom
         file:/Users/user/AndroidSDK/extras/google/m2repository/com/michaelpardo/activeandroid/3.1.0-SNAPSHOT/activeandroid-3.1.0-SNAPSHOT.jar
     Required by:
         Condeco:app:unspecified > Condeco:common:unspecified
</code>```

I am adding my library module like so:

```<code>dependencies {
    compile project(':common')
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
}
</code>```

To remove this error I have to add the repository to the main app module as well in the same way:

```<code>repositories {
    maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
}
</code>```

When I do this the project compiles fine.

Can I get my project to compile with the repositories defined only in the library project without having to add the repository to the main app module? I just want to have the library module look after itself.

答:
I also faced this error, and the solution goes likes this.

You have to edit build.gradle of android app module.

```<code>apply plugin: 'com.android.application'

// Add this block
buildscript {
    repositories {

    }
    dependencies {
    }
}

repositories {
    mavenCentral()
    maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
}
// End of this block
android {
   compileSdkVersion 25
   buildToolsVersion "25.0.3"
   ..... //Replace dots with your code
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
    })
    .... //Replace dots with your code
    compile 'com.michaelpardo:activeandroid:3.1.0-SNAPSHOT' //Add this line
}
</code>```

Hope this helps.

Body:
I have a library project that includes active android using Gradle.
To get it to work I have to add

compile 'com.michaelpardo:activeandroid:3.1.0-SNAPSHOT'

and add the repository for it like so:

repositories {
    maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
}

However if I do this in the library project, I get the error:

Error:A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_debugCompile'.
   > Could not find com.michaelpardo:activeandroid:3.1.0-SNAPSHOT.
     Searched in the following locations:
         https://jcenter.bintray.com/com/michaelpardo/activeandroid/3.1.0-SNAPSHOT/maven-metadata.xml
         https://jcenter.bintray.com/com/michaelpardo/activeandroid/3.1.0-SNAPSHOT/activeandroid-3.1.0-SNAPSHOT.pom
         https://jcenter.bintray.com/com/michaelpardo/activeandroid/3.1.0-SNAPSHOT/activeandroid-3.1.0-SNAPSHOT.jar
         file:/Users/user/AndroidSDK/extras/android/m2repository/com/michaelpardo/activeandroid/3.1.0-SNAPSHOT/maven-metadata.xml
         file:/Users/user/AndroidSDK/extras/android/m2repository/com/michaelpardo/activeandroid/3.1.0-SNAPSHOT/activeandroid-3.1.0-SNAPSHOT.pom
         file:/Users/user/AndroidSDK/extras/android/m2repository/com/michaelpardo/activeandroid/3.1.0-SNAPSHOT/activeandroid-3.1.0-SNAPSHOT.jar
         file:/Users/user/AndroidSDK/extras/google/m2repository/com/michaelpardo/activeandroid/3.1.0-SNAPSHOT/maven-metadata.xml
         file:/Users/user/AndroidSDK/extras/google/m2repository/com/michaelpardo/activeandroid/3.1.0-SNAPSHOT/activeandroid-3.1.0-SNAPSHOT.pom
         file:/Users/user/AndroidSDK/extras/google/m2repository/com/michaelpardo/activeandroid/3.1.0-SNAPSHOT/activeandroid-3.1.0-SNAPSHOT.jar
     Required by:
         Condeco:app:unspecified > Condeco:common:unspecified

I am adding my library module like so:

dependencies {
    compile project(':common')
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
}

To remove this error I have to add the repository to the main app module as well in the same way:

repositories {
    maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
}

When I do this the project compiles fine.

Can I get my project to compile with the repositories defined only in the library project without having to add the repository to the main app module? I just want to have the library module look after itself.

Body:
I also faced this error, and the solution goes likes this.

You have to edit build.gradle of android app module.

apply plugin: 'com.android.application'

// Add this block
buildscript {
    repositories {

    }
    dependencies {
    }
}

repositories {
    mavenCentral()
    maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
}
// End of this block
android {
   compileSdkVersion 25
   buildToolsVersion "25.0.3"
   ..... //Replace dots with your code
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
    })
    .... //Replace dots with your code
    compile 'com.michaelpardo:activeandroid:3.1.0-SNAPSHOT' //Add this line
}

Hope this helps.


问:
Is WCF ready for real world?
As I read here http://arunatennakoon.blogspot.com/2010/11/things-i-learn-new-this-week.html

```<code>Friday, November 12, 2010
Things I learn new this week
1. Never ever use WCF.
---------------------

here is why
1. IIS 7 doesn't support .svc file format by default. So you need to
</code>```

install some extension files. so it's
  lot of work for a new product.

```<code>2. I found it very hard to configure security settings. when i
</code>```

tried to configure for the first time
  it threw all kind of errors.

```<code>3. After installing WCF in IIS, sometimes it's trowing an exception
</code>```

that refers to the temp directory. To
  solve this problem you have to re
  compile the application and
  re-distribute

```<code>and a lot more...
</code>```

So would you take the risk to use WCF ?

I'd like to hear about real world examples with hundred to billions of hit per year.

答:
i saw many articles about using WCF for the HPC world , so i guess we have to wait and find out :)

i'm cool with ASMX though

ContentLicense: CC BY-SA 2.5

Title: Is WCF ready for real world?

Body:
As I read here http://arunatennakoon.blogspot.com/2010/11/things-i-learn-new-this-week.html

Friday, November 12, 2010
Things I learn new this week
1. Never ever use WCF.
---------------------

here is why
1. IIS 7 doesn't support .svc file format by default. So you need to

install some extension files. so it's
  lot of work for a new product.

2. I found it very hard to configure security settings. when i

tried to configure for the first time
  it threw all kind of errors.

3. After installing WCF in IIS, sometimes it's trowing an exception

that refers to the temp directory. To
  solve this problem you have to re
  compile the application and
  re-distribute

and a lot more...

So would you take the risk to use WCF ?

I'd like to hear about real world examples with hundred to billions of hit per year.


问:
Pagination and MySQL ResultSet
I am developing a website in php/MySQL. Say this is a website for my students to check their course/subject results online of their respective semester. The logic is as follows.
The semester.php page lists semesters one through eight. The students clicks on the their semester link and are taken to courses.php where links to all the courses/subjects in that semester are given. When they click on any of their subject, subjectresult.php opens showing results of all the students in that subject.

I am passing semester and subject values as parameters in the URL as follows.

courses.php?semester=semestername

I am also using pagination to display only 10 results per page.

So far so good. The subjectresult.php shows only 10 results with pagination links at the bottom. Everything nice and tidy.

My problem is that when I click on page 2, everything goes away because the subject parameters is now no longer in the URL.
The two URLs as under:
course/subject URL: subjectresult.php?sub=subjectname
page # URL: subjectresult.php?page_no=pagenumber

The workaround that I have made is that I have changed the paging links logic and have added subject name as a second parameter. Now everything is working fine and the partial URL is as under:
subjectresult.php?sub=subjectname&page_no=pagenumber

Please note that I am a novice, still learning.

Now I have a few questions.
Am I doing it right? (Which I don't think so)
How to store my subject_result query result when the subjectresult.php page loads for the first time so that I don't have pass this again and again with each paging link?

Or in a Nutshell..How to do it correctly?

Thanks in advance.

答:
Your approch is ok.
If you want to store and reuse the subject value,
In PHP use a session variable.
Eg:

```<code>session_start();
// give the subject value to the session variable.
$_SESSION['subject'] = "subject";
// get the value from the session variable if needed.
</code>```

Like

```<code>session_start();
$subject = $_SESSION['subject'];
</code>```

for more about sessions please check here..

Title: Pagination and MySQL ResultSet

Body:
Your approch is ok.
If you want to store and reuse the subject value,
In PHP use a session variable.
Eg:

session_start();
// give the subject value to the session variable.
$_SESSION['subject'] = "subject";
// get the value from the session variable if needed.

Like

session_start();
$subject = $_SESSION['subject'];

for more about sessions please check here..


问:
Customising tags in Django to filter posts in Post model
Quick question - I'm not sure what would be the correct way to handle this. Essentially I wish to define a custom tag which handles some logic then returns all posts of model Post which has the is_featured field set to True. I have tried a number of avenues to get this working, but none have worked. My last coherant "guess" was the following:

templatetags/blog_tags.py:

```<code>@register.inclusion_tag('blog/post/featured_posts.html')
def show_featured_posts(count=4):
    """Return 4 of the most recent posts (of model: 'Post') that has the variable is_featured set to True."""
    if Post.is_featured:
        featured_posts = Post.published.order_by('-publish')[:count]

return { 'featured_posts': featured_posts}
</code>```

models.py (useful bits):

```<code>class PublishedManager(models.Manager):

    def get_queryset(self):
        return super(PublishedManager, self).get_queryset().filter(status='published')

class Post(models.Model):

    STATUS_CHOICES = (
        ('draft', 'Draft'),
        ('published', 'Published'),
    )

    POST_TYPES = (
        ('news', 'News'),
        ('feature', 'Feature'),
        ('review', 'Review'),
    )

    title = models.CharField(max_length=250)
    slug = models.SlugField(max_length=250, unique_for_date='publish')

    author = models.ForeignKey(UserProfile, related_name='blog_posts')

    body = models.TextField()
    lead_in = models.CharField(max_length=500, default='')

    #These next items shall contain our development information for game reviews - this is much like the lead_in:
    platform = models.CharField(max_length=1000, default='')
    publisher = models.CharField(max_length=1000, default='')
    developer = models.CharField(max_length=1000, default='')
    release = models.DateTimeField(default=timezone.now)
    is_featured = models.BooleanField(default=False)

    #Out blog layout dictates each featurette has up to three scrolling images associated to it:
    image_scroll_1 = models.ImageField(storage=site_media_upload_location, null=True, blank=True)
    image_scroll_2 = models.ImageField(storage=site_media_upload_location, null=True, blank=True)
    image_scroll_3 = models.ImageField(storage=site_media_upload_location, null=True, blank=True)

    type = models.CharField(max_length=10,choices=POST_TYPES,default='review')

    publish = models.DateTimeField(default=timezone.now)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=10,choices=STATUS_CHOICES,default='draft')
    rating = models.PositiveSmallIntegerField(default=10)

    wrap_header = models.CharField(max_length=250, default='')
    wrap_up = models.TextField(default='')
    disclaimer = models.TextField(default='')

    objects = models.Manager()
    published = PublishedManager()
    tags = TaggableManager()

    class Meta:
        ordering = ('-publish',)

    def __str__(self):
        """Return the state title of the post"""
        return self.title

    def get_absolute_url(self):
        """Get absolute_url path specific to this post."""
        return reverse('blog:post_detail', args = [self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug])

    def get_image(self):
        """Get upload_to path specific to this photo."""
        return self.image.url
</code>```

That is everything I think I need to include - I have the featured_posts.html template all ready to go so I don't think the issue lies with that. It's purely in the blog_tags.py file.

答:
replace the following code in blog_tags.py

```<code> if Post.is_featured:
        featured_posts = Post.published.order_by('-publish')[:count]
</code>```

to

```<code>featured_posts = Post.published.filter(is_featured=True).order_by('-publish')[:count]
</code>```

Body:
Quick question - I'm not sure what would be the correct way to handle this. Essentially I wish to define a custom tag which handles some logic then returns all posts of model Post which has the is_featured field set to True. I have tried a number of avenues to get this working, but none have worked. My last coherant "guess" was the following:

templatetags/blog_tags.py:

@register.inclusion_tag('blog/post/featured_posts.html')
def show_featured_posts(count=4):
    """Return 4 of the most recent posts (of model: 'Post') that has the variable is_featured set to True."""
    if Post.is_featured:
        featured_posts = Post.published.order_by('-publish')[:count]

return { 'featured_posts': featured_posts}

models.py (useful bits):

class PublishedManager(models.Manager):

    def get_queryset(self):
        return super(PublishedManager, self).get_queryset().filter(status='published')

class Post(models.Model):

    STATUS_CHOICES = (
        ('draft', 'Draft'),
        ('published', 'Published'),
    )

    POST_TYPES = (
        ('news', 'News'),
        ('feature', 'Feature'),
        ('review', 'Review'),
    )

    title = models.CharField(max_length=250)
    slug = models.SlugField(max_length=250, unique_for_date='publish')

    author = models.ForeignKey(UserProfile, related_name='blog_posts')

    body = models.TextField()
    lead_in = models.CharField(max_length=500, default='')

    #These next items shall contain our development information for game reviews - this is much like the lead_in:
    platform = models.CharField(max_length=1000, default='')
    publisher = models.CharField(max_length=1000, default='')
    developer = models.CharField(max_length=1000, default='')
    release = models.DateTimeField(default=timezone.now)
    is_featured = models.BooleanField(default=False)

    #Out blog layout dictates each featurette has up to three scrolling images associated to it:
    image_scroll_1 = models.ImageField(storage=site_media_upload_location, null=True, blank=True)
    image_scroll_2 = models.ImageField(storage=site_media_upload_location, null=True, blank=True)
    image_scroll_3 = models.ImageField(storage=site_media_upload_location, null=True, blank=True)

    type = models.CharField(max_length=10,choices=POST_TYPES,default='review')

    publish = models.DateTimeField(default=timezone.now)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=10,choices=STATUS_CHOICES,default='draft')
    rating = models.PositiveSmallIntegerField(default=10)

    wrap_header = models.CharField(max_length=250, default='')
    wrap_up = models.TextField(default='')
    disclaimer = models.TextField(default='')

    objects = models.Manager()
    published = PublishedManager()
    tags = TaggableManager()

    class Meta:
        ordering = ('-publish',)

    def __str__(self):
        """Return the state title of the post"""
        return self.title

    def get_absolute_url(self):
        """Get absolute_url path specific to this post."""
        return reverse('blog:post_detail', args = [self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug])

    def get_image(self):
        """Get upload_to path specific to this photo."""
        return self.image.url

That is everything I think I need to include - I have the featured_posts.html template all ready to go so I don't think the issue lies with that. It's purely in the blog_tags.py file.

Body:
replace the following code in blog_tags.py

 if Post.is_featured:
        featured_posts = Post.published.order_by('-publish')[:count]

to

featured_posts = Post.published.filter(is_featured=True).order_by('-publish')[:count]


答:
Add another column with distance between current row lat long and next row lat long. Put this in a if condition to check the trip number. Finally sum-it up.

First do this in excel and then transfer to your coding language.

Title: calculate distances between different trips in loops

Body:
I have a data frame called p.1 with 16 column of information for each of the points recorded by the Argos system, this are the important columns, date, lon (longitud), lat (latitud), trip is the number of the trip and the distance to the coast.

date               |   lon        |    lat        | trip |  distancetocoast
2014-06-11 19:02:00 -58,3508585     -51,88438373    1       2236,067977
2014-06-12 01:02:00 -58,35589725    -51,88349529    1       1000
2014-06-12 13:02:00 -58,27224941    -51,91903677    1       7211,102551
2014-06-12 19:02:00 -58,27974654    -51,90535003    1       5830,951895
2014-06-13 01:02:00 -58,32331901    -51,89410464    1       3605,551275
2014-06-13 07:02:00 -58,35833139    -51,88809227    1       1414,213562
2014-06-13 13:02:00 -58,35617673    -51,88156281    1       1000
2014-06-13 19:02:00 -58,34055711    -51,89002367    1       2236,067977
2014-06-14 01:02:00 -58,34982536    -51,8715761     2       1000
2014-06-14 13:02:00 -58,3073814     -51,92722937    2       7071,067812
2014-06-14 19:02:00 -58,34581314    -51,86761133    3       1000
2014-06-15 01:02:00 -58,34050624    -51,88382088    3       1414,213562
2014-06-15 13:02:00 -58,2974691     -51,91795326    3       6324,55532
2014-06-15 19:02:00 -58,19881901    -51,95172233    3       13000
2014-06-16 01:02:00 -58,1348416     -51,98673766    3       18788,29423
2014-06-16 07:02:00 -57,99399544    -52,06988191    3       28861,73938
2014-06-16 13:02:00 -58,00469754    -52,02795069    3       26627,05391
2014-06-16 19:02:00 -57,92758675    -52,02184666    3       29000
2014-06-17 01:02:00 -57,91658235    -51,99748699    3       28284,27125
2014-06-17 07:02:00 -57,77015528    -51,99031797    3       30805,8436
2014-06-17 13:02:00 -57,99601712    -51,91519551    3       17804,49381
2014-06-17 19:02:00 -58,06820013    -51,92972737    3       14866,06875
2014-06-18 01:02:00 -58,19845185    -51,89522513    3       7615,773106
2014-06-18 07:02:00 -58,35241361    -51,88015998    3       1000
2014-06-18 13:02:00 -58,35603546    -51,88336878    3       1000
2014-06-18 19:02:00 -58,33350332    -51,87308427    3       1000
2014-06-19 01:02:00 -58,33839581    -51,87846631    3       1414,213562
2014-06-19 07:02:00 -58,42661519    -51,80902388    4       0
2014-06-19 13:02:00 -58,30461883    -51,93745837    4       7810,249676
2014-06-19 19:02:00 -58,18362875    -51,96475914    4       14317,82106

In the beggining I just sumed the distance from coast of every trip with the next function:

tripID<-c(1:length(unique(p.1$trip)))
tripdistance<-aggregate(p.1$dist,by=list(unique.values=p.1$trip),FUN=sum)

This is clearly wrong, how can I calculate the distance traveled in each trip and start from 0 in the next trip?

I´ve been trying with other functions as: spDistsN1 and trackDistance but I can´t make it work.


问:
Amateur Coder File Testing
I am working on a project and have a great idea.
This is a very simple question and I've done this before, but it doesn't seem to be working.
In my idle, when I type:

```<code>f = open('a.txt', 'w')
f.write('hi')
</code>```

I get an output of 2.
It doesn't make sense to me beyond the fact that hi has a length of two... I want to add 'hi' to my file!!

答: you just need to use f.close() and the changes will commit

Title: Amateur Coder File Testing

Body:
I am working on a project and have a great idea.
This is a very simple question and I've done this before, but it doesn't seem to be working.
In my idle, when I type:

f = open('a.txt', 'w')
f.write('hi')

I get an output of 2.
It doesn't make sense to me beyond the fact that hi has a length of two... I want to add 'hi' to my file!!


问:
Google Play Games Realtime Multiplayer: How to get the participant id of the current user?
I am developing an Android game which uses Google Play Games Realtime Multiplayer.

 I would like to determine which device is the creator/initiator of the match, so that both devices would know which device is doing all the calculations, message sending, etc.

I haven't found any documentation on this - only ways to get the creator participant id, not actually compare it to the id of the user's phone.

 So essentially, I need to find a way to get the participant id of the user the code is executing on; I can handle the comparing the values from there.

答:
Use Games.Players api to get current player id and then you can get current participant id using Room api.

```<code>String playerId = Games.Players.getCurrentPlayerId(mGoogleApiClient);
String currentParticipantId = room.getParticipantId(playerId);
</code>```

where room is Room object and mGoogleApiClient is GoogleApiClient object.

Body:
Use Games.Players api to get current player id and then you can get current participant id using Room api.

String playerId = Games.Players.getCurrentPlayerId(mGoogleApiClient);
String currentParticipantId = room.getParticipantId(playerId);

where room is Room object and mGoogleApiClient is GoogleApiClient object.


问:
PHP error posting form data to database
I am trying to make a post-ad form add data to a database. The page keeps reloading and asking to fill in all the details. I cannot seem to find the error and i have done a lot of searching on google and youtube, all to no avail. Please help!!!

```<code><?php
    session_start();
    include'db.php';
    $name = $_POST['name'];
    $email = $_POST['email'];
    $phoneNumber = $_POST['mobile-num'];
    $photos = $_POST['fileselect'];
    $town = $_POST['location'];
    $category = $_POST['category'];
    $adTitle = $_POST['title'];
    $adDescription = $_POST['description'];

    if(isset($_SESSION['email']))
    {
        if($email != "" && $name != "" && $phoneNumber != "" && $photos != "" && $town != "" && $category != "" && $adTitle !="" && $adDescription != "")
        {
            $name = stripslashes($name);
            $email = stripslashes($email);
            $phoneNumber = stripslashes($phoneNumber);
            $photos = stripslashes($photos);
            $town = stripslashes($town);
            $adTitle = stripslashes($adTitle);
            $category = stripslashes($category);
            $adDescription = stripslashes($adDescription);

            $name = mysqli_real_escape_string($connection,$name);
            $email = mysqli_real_escape_string($connection,$email);
            $phoneNumber = mysqli_real_escape_string($connection,$phoneNumber);
            $photos = mysqli_real_escape_string($connection,$photos);
            $town = mysqli_real_escape_string($connection,$town);
            $adTitle = mysqli_real_escape_string($connection,$adTitle);
            $category = mysqli_real_escape_string($connection,$category);
            $adDescription = mysqli_real_escape_string($connection,$adDescription);
            $imagePath = "images/".basename($_FILES['fileselect']['MAX_FILE_SIZE']);
            $photo = $_FILES['fileselect']['MAX_FILE_SIZE'];
            $date = date("j F Y");

            if(filter_var($email,FILTER_VALIDATE_EMAIL))
            {
                mysqli_query($connection, "SELECT email,ad-title,ad-category,ad-description,Photos,Name,Mobile-Num,Town,date from ads");
                $insertQuery = mysqli_query($connection, "INSERT INTO ads(email,ad-title,ad-category,ad-description,Photos,Name,Mobile-Num,Town,date)
                                                            VALUES('$email','$adTitle','$category','$adDescription','$photo','$name','$phoneNumber','$town','$date')");
                header("Location: /profile.php");
            }
            else
                $_SESSION['errorMessage'] = "Please check email pattern";
                header("Location: /post-ad.php");
        }
        else
            $_SESSION['errorMessage'] = "Please input all the required details";
            header("Location: /post-ad.php");
    }
    else
        header("Location: /login.php");

?>
</code>```

That's the PHP code.
Since I am not very good with Stackoverflow, I am having issues formatting the html form code i wanted to post here. I will attach an image instead. Html form code for the post-ad form

答: Thanks Guys for the help. Sorry for putting you all through the stress. I went through my database structure and found a column with the wrong type that was preventing the sql insert query. My apologies....</p>

Title: PHP error posting form data to database

Body:
I am trying to make a post-ad form add data to a database. The page keeps reloading and asking to fill in all the details. I cannot seem to find the error and i have done a lot of searching on google and youtube, all to no avail. Please help!!!

<?php
    session_start();
    include'db.php';
    $name = $_POST['name'];
    $email = $_POST['email'];
    $phoneNumber = $_POST['mobile-num'];
    $photos = $_POST['fileselect'];
    $town = $_POST['location'];
    $category = $_POST['category'];
    $adTitle = $_POST['title'];
    $adDescription = $_POST['description'];

    if(isset($_SESSION['email']))
    {
        if($email != "" && $name != "" && $phoneNumber != "" && $photos != "" && $town != "" && $category != "" && $adTitle !="" && $adDescription != "")
        {
            $name = stripslashes($name);
            $email = stripslashes($email);
            $phoneNumber = stripslashes($phoneNumber);
            $photos = stripslashes($photos);
            $town = stripslashes($town);
            $adTitle = stripslashes($adTitle);
            $category = stripslashes($category);
            $adDescription = stripslashes($adDescription);

            $name = mysqli_real_escape_string($connection,$name);
            $email = mysqli_real_escape_string($connection,$email);
            $phoneNumber = mysqli_real_escape_string($connection,$phoneNumber);
            $photos = mysqli_real_escape_string($connection,$photos);
            $town = mysqli_real_escape_string($connection,$town);
            $adTitle = mysqli_real_escape_string($connection,$adTitle);
            $category = mysqli_real_escape_string($connection,$category);
            $adDescription = mysqli_real_escape_string($connection,$adDescription);
            $imagePath = "images/".basename($_FILES['fileselect']['MAX_FILE_SIZE']);
            $photo = $_FILES['fileselect']['MAX_FILE_SIZE'];
            $date = date("j F Y");

            if(filter_var($email,FILTER_VALIDATE_EMAIL))
            {
                mysqli_query($connection, "SELECT email,ad-title,ad-category,ad-description,Photos,Name,Mobile-Num,Town,date from ads");
                $insertQuery = mysqli_query($connection, "INSERT INTO ads(email,ad-title,ad-category,ad-description,Photos,Name,Mobile-Num,Town,date)
                                                            VALUES('$email','$adTitle','$category','$adDescription','$photo','$name','$phoneNumber','$town','$date')");
                header("Location: /profile.php");
            }
            else
                $_SESSION['errorMessage'] = "Please check email pattern";
                header("Location: /post-ad.php");
        }
        else
            $_SESSION['errorMessage'] = "Please input all the required details";
            header("Location: /post-ad.php");
    }
    else
        header("Location: /login.php");

?>

That's the PHP code.
Since I am not very good with Stackoverflow, I am having issues formatting the html form code i wanted to post here. I will attach an image instead. Html form code for the post-ad form


问:
How to determine whether a file has been closed
I'm writing a unit test, and I'm trying to find a way to test whether my class has properly closed a file handle (it uses old-style open() and close()). Ideally I'd like to be able to do it without having access to the actual handle - I want to be able to check a file in the file system and determine whether it is currently open elsewhere.

I've tried doing it through exclusive file locks, but I haven't had much luck. Besides, file locks are very much not cross-platform (this needs to work on Solaris, Linux and Windows).

Any suggestions?

答:
There is no way to check if a file handle is still open or not.

If you're using C++ you can simply always use RAII and you won't have to worry about unclosed file handles.

Otherwise you can never call the system APIs and instead call your wrapper APIs.  Every time you open you can add the path to a vector, everything you close you can remove that path.  At the end just check if you have a zero size on your vector.


问:
How to properly use sscanf in this context?
I have a file which structure is the following:

```<code>var1 2921
var2 0.5
var3 12
</code>```

I need a method that gets the name of the file and 3 empty variables. It should read the file and give a value for each variable. (This is what I have tried so far)

```<code>void get_input(char * filename, int * var1, double * var2, int * var3){
    FILE *file;
    char buf[1024];
    file=fopen(filename,"r");
    if(file == NULL){
        printf("ERROR");
        exit(0);
    }

    int i=0;

    if(file){
        while(fgets(buf,sizeof(buf),file)!=NULL){
            switch(i){
            case 0:
                sscanf(buf,"var1 %d",&var1);
                break;
            case 1:
                sscanf(buf,"var2 %f",&var2);
                break;
            case 2:
                sscanf(buf,"var3 %d",&var3);
                break;
            default:
                break;
            }

            i++;
        }
    }
}
</code>```

And the main:

```<code>int main()
{
    char filename[256];
    int var1,var3;
    double var2;

    snprintf(filename,256,"file.txt");

    get_input(filename,&var1,&var2,&var3);

    printf("%s %d","var1: ",var1);
    printf("%s %f","\nvar2: ",var2);
    printf("%s %d","\nvar3: ",var3);

    return 0;
}
</code>```

Output:

var1:  8

var2:  0.000000

var3:  2011837489

答:
For a double, you need to use %lf, not %f; in scanf as well as in printf. Alternatively, you could use float, that goes with %f.

You are passing the addresses of var1, 2, 3; so taking the address again in scanf is duplicate - you will get the address of the address.

Use var1 instead of &var1 inside the scanf.

Body:
I have a file which structure is the following:

var1 2921
var2 0.5
var3 12

I need a method that gets the name of the file and 3 empty variables. It should read the file and give a value for each variable. (This is what I have tried so far)

void get_input(char * filename, int * var1, double * var2, int * var3){
    FILE *file;
    char buf[1024];
    file=fopen(filename,"r");
    if(file == NULL){
        printf("ERROR");
        exit(0);
    }

    int i=0;

    if(file){
        while(fgets(buf,sizeof(buf),file)!=NULL){
            switch(i){
            case 0:
                sscanf(buf,"var1 %d",&var1);
                break;
            case 1:
                sscanf(buf,"var2 %f",&var2);
                break;
            case 2:
                sscanf(buf,"var3 %d",&var3);
                break;
            default:
                break;
            }

            i++;
        }
    }
}

And the main:

int main()
{
    char filename[256];
    int var1,var3;
    double var2;

    snprintf(filename,256,"file.txt");

    get_input(filename,&var1,&var2,&var3);

    printf("%s %d","var1: ",var1);
    printf("%s %f","\nvar2: ",var2);
    printf("%s %d","\nvar3: ",var3);

    return 0;
}

Output:

var1:  8

var2:  0.000000

var3:  2011837489


问:
Declaring same css for more than one id?
How do I do it.

```<code>#foo, #ball, #tree h1 {color: #892828;}
</code>```

Does not seem to work?

答: You could also assign the same class to each of those h1s and style using that class.</p>

Body:
How do I do it.

#foo, #ball, #tree h1 {color: #892828;}

Does not seem to work?


问:
RegEx to match all text between two strings that slightly alter
I am currently working on an AIR app and I'm trying to get a certain block of text from a website where that block of text is always between two specific strings that contain links that change from page to page.

It looks something like this:

```<code><p><a href="**changes**">Previous Chapter</a> <a href="**changes**"><span style="float: right">Next Chapter</span></a></p>
.
.
_desired content_
.
.
<p><a href="**changes**">Previous Chapter</a> <a href="**changes**"><span style="float: right">Next Chapter</span></a></p>
</code>```

*The two strings are identical

Now, I have tried several RegEx expressions but without success. I just can't get my head around Regex in general...

The last expression I've tried is: /(?<=
href=\".+\">Previous Chapter<\/a> href=\".+\">Next Chapter<\/a><\/span><\/p>)(.*)(?=
href=\".+\">Previous Chapter<\/a> href=\".+\">Next Chapter<\/a><\/span><\/p>)/gsi

but that one isn't even being recognized as a RegEx.

I would really appreciate any help with the subject.

Thanks in advance!

EDIT:

Thanks to Organis's help I managed to solve the problem, it was indeed easier and better NOT using RegEx.
This is what i ended up doing:

```<code>text=text.split("Next Chapter<\/span><\/a><\/p>")[1].split("Previous Chapter<\/a>")[0];
text=text.substring(0,text.lastIndexOf("<p><a href"));
</code>```

答:
Do not use RegEx. Read why: https://blog.codinghorror.com/parsing-html-the-cthulhu-way/.

Extract text between two fixed Next Chapter
, then cut finalizing
Previous Chapter href="**changes**"> off.

Body:
I am currently working on an AIR app and I'm trying to get a certain block of text from a website where that block of text is always between two specific strings that contain links that change from page to page.

It looks something like this:

Previous Chapter Next Chapter

.
.
_desired content_
.
.

Previous Chapter Next Chapter

*The two strings are identical

Now, I have tried several RegEx expressions but without success. I just can't get my head around Regex in general...

The last expression I've tried is: /(?<=
Previous Chapter<\/a> Next Chapter<\/a><\/span><\/p>)(.*)(?=
Previous Chapter<\/a> Next Chapter<\/a><\/span><\/p>)/gsi

but that one isn't even being recognized as a RegEx.

I would really appreciate any help with the subject.

Thanks in advance!

EDIT:

Thanks to Organis's help I managed to solve the problem, it was indeed easier and better NOT using RegEx.
This is what i ended up doing:

text=text.split("Next Chapter<\/span><\/a><\/p>")[1].split("Previous Chapter<\/a>")[0];
text=text.substring(0,text.lastIndexOf("
<a href"));

Body:
Do not use RegEx. Read why: https://blog.codinghorror.com/parsing-html-the-cthulhu-way/.

Extract text between two fixed <span style="float: right">Next Chapter</span></a></p>, then cut finalizing <p><a href="**changes**">Previous Chapter</a> <a href="**changes**"> off.


问:
How to get servers time
Okay so i need a countdown to the servers midnight because when the server reach midnight it will run a cronjob which is relevant to the users so they need to see how many hours that are left untill it is midnight on the server and not in their own timezone.

Sample page here

The date_default_timezone_get(); is europe/copenhagen

PHP

(The page the Ajax is requesting)

```<code>echo time() * 1000;
</code>```

Javascript

```<code>            (function () {
                var test = document.getElementById("test");
                var difference = document.getElementById("difference");

                var serverMilli = document.getElementById("serverMilli");
                var serverCountdown = document.getElementById("serverCountdown");

                var machineMilli = document.getElementById("machineMilli");
                var machineCountdown = document.getElementById("machineCountdown");

                let serverTime;
                var localTime;

                var http = new XMLHttpRequest();
                var url = "time.php";
                http.open("POST", url, true);
                http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                http.onreadystatechange = function () {
                    if (http.readyState === 4 && http.status === 200) {
                        serverTime = this.responseText;
                    }
                    ;
                };
                http.send();

                function countDownServer() {

                    var now = new Date();
                    var localTime = now.getTime();
                    var currentDiff = serverTime - localTime;
                    var currentTest = serverTime - currentDiff;

                    var currentTime = currentTest;
                    var eventDate = new Date();
                    eventDate.setDate(now.getDate() + 1);
                    eventDate.setHours(24);
                    eventDate.setMinutes(0);
                    eventDate.setSeconds(0);
                    eventDate.setMilliseconds(0);

                    var eventTime = eventDate.getTime();
                    var remainingTime = eventTime - currentTime;

                    var sekunder = Math.floor(remainingTime / 1000);
                    var minutter = Math.floor(sekunder / 60);
                    var timer = Math.floor(minutter / 60);

                    sekunder %= 60;
                    minutter %= 60;
                    timer %= 24;

                    sekunder = (sekunder < 10) ? "0" + sekunder : sekunder;
                    minutter = (minutter < 10) ? "0" + minutter : minutter;
                    timer = (timer < 10) ? "0" + timer : timer;

                    var testServer = timer + ":" + minutter + ":" + sekunder;
                    serverCountdown.textContent = testServer;
                    setTimeout(countDownServer, 1000);
                }
                countDownServer();
                })();
</code>```

Everything "kinda" works... the problem is if i change the timezone on my computer it will display longer hours untill midnight than it really is on the server?
How is this possible when the timezone on server is europe/copenhagen and i use time() ? should it not use the servers timezone?

答:
No as javascript executes in your browser, it will use the timezone of your computer.

You have to tell javascript which timezone you would like (if not your one)

I found this for you:

How to get Time of specific timezone using javascript?

Title: How to get servers time

Body:
Okay so i need a countdown to the servers midnight because when the server reach midnight it will run a cronjob which is relevant to the users so they need to see how many hours that are left untill it is midnight on the server and not in their own timezone.

Sample page here

The date_default_timezone_get(); is europe/copenhagen

PHP

(The page the Ajax is requesting)

echo time() * 1000;

Javascript

            (function () {
                var test = document.getElementById("test");
                var difference = document.getElementById("difference");

                var serverMilli = document.getElementById("serverMilli");
                var serverCountdown = document.getElementById("serverCountdown");

                var machineMilli = document.getElementById("machineMilli");
                var machineCountdown = document.getElementById("machineCountdown");

                let serverTime;
                var localTime;

                var http = new XMLHttpRequest();
                var url = "time.php";
                http.open("POST", url, true);
                http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                http.onreadystatechange = function () {
                    if (http.readyState === 4 && http.status === 200) {
                        serverTime = this.responseText;
                    }
                    ;
                };
                http.send();

                function countDownServer() {

                    var now = new Date();
                    var localTime = now.getTime();
                    var currentDiff = serverTime - localTime;
                    var currentTest = serverTime - currentDiff;

                    var currentTime = currentTest;
                    var eventDate = new Date();
                    eventDate.setDate(now.getDate() + 1);
                    eventDate.setHours(24);
                    eventDate.setMinutes(0);
                    eventDate.setSeconds(0);
                    eventDate.setMilliseconds(0);

                    var eventTime = eventDate.getTime();
                    var remainingTime = eventTime - currentTime;

                    var sekunder = Math.floor(remainingTime / 1000);
                    var minutter = Math.floor(sekunder / 60);
                    var timer = Math.floor(minutter / 60);

                    sekunder %= 60;
                    minutter %= 60;
                    timer %= 24;

                    sekunder = (sekunder < 10) ? "0" + sekunder : sekunder;
                    minutter = (minutter < 10) ? "0" + minutter : minutter;
                    timer = (timer < 10) ? "0" + timer : timer;

                    var testServer = timer + ":" + minutter + ":" + sekunder;
                    serverCountdown.textContent = testServer;
                    setTimeout(countDownServer, 1000);
                }
                countDownServer();
                })();

Everything "kinda" works... the problem is if i change the timezone on my computer it will display longer hours untill midnight than it really is on the server?
How is this possible when the timezone on server is europe/copenhagen and i use time() ? should it not use the servers timezone?


问:
How should I loop through this JSON data?
Here is my code I want to print out "song" property from data. Link to JSON is -> http://starlord.hackerearth.com/sureify/cokestudio

```<code><script type="text/javascript">
    var requestURL = 'http://starlord.hackerearth.com/sureify/cokestudio';

    var request = new XMLHttpRequest();

    request.open('GET', requestURL);

    request.responseType = 'json';

    request.send();

    request.onload = function(){
        var myjsondata = request.response;
        showdata(myjsondata);
    }

    function showdata(data){
        var song_name = data;

        for (i = 0; i < 3; i++) {

            document.write(song_name);
            document.write("<br>");

        }
    }

</script>
</code>```

When I run it in browser I get [object Object],[object Object],[object Object],[object Object],[object Object] as OUTPUT or undefined.

答:
You cannot write the whole song object to the document. You should map it first:

```<code>var songNames = data.map(function(item) { return item.song; });
</code>```

This will give you an array of all the names (strings), which you can write to the document:

```<code>songNames.forEach(function(songName) {
    document.write(songName + '<br>');
});
</code>```

Body:
Here is my code I want to print out "song" property from data. Link to JSON is -> http://starlord.hackerearth.com/sureify/cokestudio

When I run it in browser I get [object Object],[object Object],[object Object],[object Object],[object Object] as OUTPUT or undefined.

Body:
You cannot write the whole song object to the document. You should map it first:

var songNames = data.map(function(item) { return item.song; });

This will give you an array of all the names (strings), which you can write to the document:

songNames.forEach(function(songName) {
    document.write(songName + '<br>');
});


问:
Error putting a variable inside excel VBA function
```<code>Sub airtableCleaner()
    Dim x As Integer
    Dim argCounter As Integer
    Dim A As String
    Dim B As String
    Dim folderLocation As Variant
    Dim Answer As VbMsgBoxResult

'Ask user if they want to run macro
Answer = MsgBox("Do you want to run this macro? Please use airtable Download as CSV - Column 1: Primary key, Column 2: Airtable Linkz", vbYesNo, "Run Macro")
If Answer = vbYes Then

folderLocation = Application.InputBox("Enter a folder location where your image assets will be")

'Cleanup to just amazons3 dl.airtable links
Columns("B:B").Select
Selection.Replace What:="* ", Replacement:="", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False
Selection.Replace What:="(", Replacement:="", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False
Selection.Replace What:=")", Replacement:="", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

'Count Cells
Range("B2").Activate
Do
    If ActiveCell.Value = "" Then Exit Do
    ActiveCell.Offset(1, 0).Activate
    argCounter = argCounter + 1

Loop

'Copy Image Links to new cells to format in Column C
Columns("B:B").Select
Selection.Copy
Columns("C:C").Select
ActiveSheet.Paste
Application.CutCopyMode = False

'Clean up links to only have names in Column C
Selection.Replace What:="https://dl.airtable.com/", Replacement:="", _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:= _
False, ReplaceFormat:=False

'Create Batch on Column D
    Range("D2").Select
ActiveCell.FormulaR1C1 = _
    "=CONCATENATE(""COPY "",CHAR(34),RC[-1],CHAR(34),"" "", CHAR(34), [" & folderLocation & "],RC[-3],"".png"",CHAR(34))"
Range("D2").Select
Selection.AutoFill Destination:=Range("D2:D9")
Range("D2:D9").Select

'Delete header row 1 information
Rows("1:1").Select
Selection.Delete Shift:=xlUp

'Repaste values back into column D removing formulas
    Columns("D:D").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Application.CutCopyMode = False

End If
End Sub
</code>```

I have this set of excel VBA code. I'm getting an error

Run-time error '1004' Application-defined or object-defined error

At this line

"=CONCATENATE(""COPY "",CHAR(34),RC[-1],CHAR(34),"" "", CHAR(34), [" & folderLocation & "],RC[-3],"".png"",CHAR(34))"

I have been setting folderLocation variable value as c:\doge and making a file folder reflecting this

My code was working fine until I introduced a variable inside of an excel function

What am I doing wrong here?

EDIT

this was the original formula I was using

=CONCATENATE("COPY ",CHAR(34),C5,CHAR(34)," ", CHAR(34), "c:\doge\",A5,".png",CHAR(34))

where c:\doge\ was the place I wanted to input the user input at.

答:
Is this what you are trying?</p>

```<code>folderLocation = "c:\doge\"

Range("D2").Formula = "=CONCATENATE(""COPY "",CHAR(34),C5,CHAR(34),"" "", CHAR(34), " & _
                      Chr(34) & folderLocation & Chr(34) & ",A5,"".png"",CHAR(34))"
</code>```

Body:
Sub airtableCleaner()
    Dim x As Integer
    Dim argCounter As Integer
    Dim A As String
    Dim B As String
    Dim folderLocation As Variant
    Dim Answer As VbMsgBoxResult

'Ask user if they want to run macro
Answer = MsgBox("Do you want to run this macro? Please use airtable Download as CSV - Column 1: Primary key, Column 2: Airtable Linkz", vbYesNo, "Run Macro")
If Answer = vbYes Then

folderLocation = Application.InputBox("Enter a folder location where your image assets will be")

'Cleanup to just amazons3 dl.airtable links
Columns("B:B").Select
Selection.Replace What:="* ", Replacement:="", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False
Selection.Replace What:="(", Replacement:="", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False
Selection.Replace What:=")", Replacement:="", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

'Count Cells
Range("B2").Activate
Do
    If ActiveCell.Value = "" Then Exit Do
    ActiveCell.Offset(1, 0).Activate
    argCounter = argCounter + 1

Loop

'Copy Image Links to new cells to format in Column C
Columns("B:B").Select
Selection.Copy
Columns("C:C").Select
ActiveSheet.Paste
Application.CutCopyMode = False

'Clean up links to only have names in Column C
Selection.Replace What:="https://dl.airtable.com/", Replacement:="", _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:= _
False, ReplaceFormat:=False

'Create Batch on Column D
    Range("D2").Select
ActiveCell.FormulaR1C1 = _
    "=CONCATENATE(""COPY "",CHAR(34),RC[-1],CHAR(34),"" "", CHAR(34), [" & folderLocation & "],RC[-3],"".png"",CHAR(34))"
Range("D2").Select
Selection.AutoFill Destination:=Range("D2:D9")
Range("D2:D9").Select

'Delete header row 1 information
Rows("1:1").Select
Selection.Delete Shift:=xlUp

'Repaste values back into column D removing formulas
    Columns("D:D").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Application.CutCopyMode = False

End If
End Sub

I have this set of excel VBA code. I'm getting an error

Run-time error '1004' Application-defined or object-defined error

At this line

"=CONCATENATE(""COPY "",CHAR(34),RC[-1],CHAR(34),"" "", CHAR(34), [" & folderLocation & "],RC[-3],"".png"",CHAR(34))"

I have been setting folderLocation variable value as c:\doge and making a file folder reflecting this

My code was working fine until I introduced a variable inside of an excel function

What am I doing wrong here?

EDIT

this was the original formula I was using

=CONCATENATE("COPY ",CHAR(34),C5,CHAR(34)," ", CHAR(34), "c:\doge\",A5,".png",CHAR(34))

where c:\doge\ was the place I wanted to input the user input at.

Body:
Is this what you are trying?

folderLocation = "c:\doge\"

Range("D2").Formula = "=CONCATENATE(""COPY "",CHAR(34),C5,CHAR(34),"" "", CHAR(34), " & _
                      Chr(34) & folderLocation & Chr(34) & ",A5,"".png"",CHAR(34))"


问:
How can I select the first specific inner element?
Here is my HTML?

```<code><ul>
    <li>
        <a href="./link1">
            <div>something</div>
            <span><a href="./link2">link</a></span>
        </a>
    </li>
</ul>
</code>```

And this is my jQuery code:

```<code>$('li').on('click', function(){
    var link = $(this).find('a').attr('href');
})
</code>```

As you see, there is two  tags. And .find() refersh to both of them. While I just want to select the  which is right inside (one level) in the
 tag. So expected result is ./link.

What alternative should I use instead of .find() ?

答:
You can use the direct descendant selector.</p>

```<code>$('li').on('click', function(){ var link = $(this).find('> a').attr('href'); })
</code>```

Body:
Here is my HTML?

something

            link

And this is my jQuery code:

$('li').on('click', function(){
    var link = $(this).find('a').attr('href');
})

As you see, there is two  tags. And .find() refersh to both of them. While I just want to select the  which is right inside (one level) in the
 tag. So expected result is ./link.

What alternative should I use instead of .find() ?

Body:
You can use the direct descendant selector.

$('li').on('click', function(){ var link = $(this).find('> a').attr('href'); })