问:
XPath Query to find supplier name through an XML table
I am trying to find out the cities where there is a supplier with the name of Herman. We are using XPath through Microsoft SQL Server Management Studio.

I am not a CIS major and I have no idea where to start. So that's why I'm asking for help...

I have the following table created:

```<code>CREATE TABLE Tb_Supplier(
XMLColumn XML)
GO

INSERT Tb_Supplier VALUES(
    '<SuppliersList>
      <Supplier name="Joe">
        <City>Paris</City>
        <Product name="Airplane"/>
        <Product name="Milk"/>
        <Product name="TV"/>
        <Product name="Orange"/>
     </Supplier>
      <Supplier name="Herman">
        <City>Chicago</City>
        <Product name="Orange"/>
     </Supplier>
     <Supplier name="Bernstein">
        <City>Madison</City>
        <Product name="Truck"/>
        <Product name="TV"/>
      </Supplier>
     <Supplier name="Hunter">
        <City>Wausau</City>
      </Supplier>
      <Supplier name="Mayer">
        <City>Madison</City>
      </Supplier>
      <Supplier name="Rosenfeld">
        <City>Chicago</City>
        <Product name="Computer"/>
        <Product name="Book"/>
        <Product name="Truck"/>
      </Supplier>
    </SuppliersList>');
</code>```

The output is supposed to show:

```<code><City>Chicago</City>
</code>```

I got the it to work by the following:

```<code>SELECT XMLColumn.query('/SuppliersList/Supplier[@name="Herman"]/City')
FROM Tb_Suppliers
</code>```

I am kind of getting the grasp of things.
Currently I am having trouble how to find out the following:
List the products are TV's, and are offered in Madison.
Obviously the output will be  since it is looking for TV.

I have this so far, I don't know what I'm doing wrong as this makes the most sense to me.

```<code>SELECT XMLColumn.query('/SuppliersList/Supplier/Product[@name="TV"]/../City[@name="Madison"]/../Product')
FROM Tb_Suppliers
</code>```

答:
No good to tell you how to do it, but I'll give you some hints.     https://msdn.microsoft.com/en-us/library/ms189075%28SQL.90%29.aspx?f=255&MSPPError=-2147217396

```<code>/* find Supplier who have truck-product */
    SELECT XMLColumn.query('/SuppliersList/Supplier/Product[@name="Truck"]/..') from Tb_Supplier
</code>```

@ sign means "attribute".  The url shows how to query element-values (a slightly different syntax than attributes).

"/" means navigate down (or sometimes up) the hierarchy.

".." means "back UP the hierarchy one level".

That should be enough to get you going.

Body:
I am trying to find out the cities where there is a supplier with the name of Herman. We are using XPath through Microsoft SQL Server Management Studio.

I am not a CIS major and I have no idea where to start. So that's why I'm asking for help...

I have the following table created:

CREATE TABLE Tb_Supplier(
XMLColumn XML)
GO

INSERT Tb_Supplier VALUES(
    '<SuppliersList>
      <Supplier name="Joe">
        <City>Paris</City>
        <Product name="Airplane"/>
        <Product name="Milk"/>
        <Product name="TV"/>
        <Product name="Orange"/>
     </Supplier>
      <Supplier name="Herman">
        <City>Chicago</City>
        <Product name="Orange"/>
     </Supplier>
     <Supplier name="Bernstein">
        <City>Madison</City>
        <Product name="Truck"/>
        <Product name="TV"/>
      </Supplier>
     <Supplier name="Hunter">
        <City>Wausau</City>
      </Supplier>
      <Supplier name="Mayer">
        <City>Madison</City>
      </Supplier>
      <Supplier name="Rosenfeld">
        <City>Chicago</City>
        <Product name="Computer"/>
        <Product name="Book"/>
        <Product name="Truck"/>
      </Supplier>
    </SuppliersList>');

The output is supposed to show:

<City>Chicago</City>

I got the it to work by the following:

SELECT XMLColumn.query('/SuppliersList/Supplier[@name="Herman"]/City')
FROM Tb_Suppliers

I am kind of getting the grasp of things.
Currently I am having trouble how to find out the following:
List the products are TV's, and are offered in Madison.
Obviously the output will be  since it is looking for TV.

I have this so far, I don't know what I'm doing wrong as this makes the most sense to me.

SELECT XMLColumn.query('/SuppliersList/Supplier/Product[@name="TV"]/../City[@name="Madison"]/../Product')
FROM Tb_Suppliers

Body:
No good to tell you how to do it, but I'll give you some hints.     https://msdn.microsoft.com/en-us/library/ms189075%28SQL.90%29.aspx?f=255&MSPPError=-2147217396

/* find Supplier who have truck-product */
    SELECT XMLColumn.query('/SuppliersList/Supplier/Product[@name="Truck"]/..') from Tb_Supplier

@ sign means "attribute".  The url shows how to query element-values (a slightly different syntax than attributes).

"/" means navigate down (or sometimes up) the hierarchy.

".." means "back UP the hierarchy one level".

That should be enough to get you going.


来源: stackexchange

问:
Downloading Files with Python Urllib, Urllib2
I am trying to download files from a website using urllib as described in this thread: link text

```<code>import urllib
urllib.urlretrieve ("http://www.example.com/songs/mp3.mp3", "mp3.mp3")
</code>```

I am able to download the files (mostly pdf) but all I get is corrupted files that cannot open. I suspect it's because the website requires a login.

How can the above function be modified to handle cookies? I already know the names of the form fields that carry the username & password information. When I print the return values of urlretrieve I get messages like:

```<code>a, b = urllib.urlretrieve ("http://www.example.com/songs/mp3.mp3", "mp3.mp3")
print a, b

>> **cache-control:** no-cache, no-store, must-revalidate, s-maxage=300, proxy-revalida
te

>> **connection:** close
</code>```

I am able to manually download the files if I enter their urls in the browser. Thanks

答:
First urllib2 actually supports cookies and cookie handling should be easy, second of all you can check what kind of file you have downloaded. E.g. AFAIK all mp3 starts with the bytes "ID3"</p>

```<code>import cookielib, urllib2
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to download files from a website using urllib as described in this thread: link text

import urllib
urllib.urlretrieve ("http://www.example.com/songs/mp3.mp3", "mp3.mp3")

I am able to download the files (mostly pdf) but all I get is corrupted files that cannot open. I suspect it's because the website requires a login.

How can the above function be modified to handle cookies? I already know the names of the form fields that carry the username & password information. When I print the return values of urlretrieve I get messages like:

a, b = urllib.urlretrieve ("http://www.example.com/songs/mp3.mp3", "mp3.mp3")
print a, b

>> **cache-control:** no-cache, no-store, must-revalidate, s-maxage=300, proxy-revalida
te

>> **connection:** close

I am able to manually download the files if I enter their urls in the browser. Thanks

Body:
First urllib2 actually supports cookies and cookie handling should be easy, second of all you can check what kind of file you have downloaded. E.g. AFAIK all mp3 starts with the bytes "ID3"

import cookielib, urllib2
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")


问:
Problems with exporting Java program to a JAR file
So, the software is working properly and everything is fine. I did find some answers to my question online but I can't seem to fix my problem. Everything seems to be okay in my Build Path and in order.
The error I'm getting:

```<code>    Exception in thread "main" java.lang.NoClassDefFoundError: org/hibernate/service/ServiceRegistry
        at java.base/java.lang.Class.forName0(Native Method)
        at java.base/java.lang.Class.forName(Unknown Source)
        at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:56)
Caused by: java.lang.ClassNotFoundException: org.hibernate.service.ServiceRegistry
        at java.base/java.net.URLClassLoader.findClass(Unknown Source)
        at java.base/java.lang.ClassLoader.loadClass(Unknown Source)
        at java.base/java.lang.ClassLoader.loadClass(Unknown Source)
        ... 3 more
</code>```

I need to export my project to a JAR file, please help me, I'm desperate. And thanks to anyone that cares to answer in advance.

答:
Building a jar-with-dependencies will solve your problem.

Add the following to your pom.xml file:

```<code><build>
  <plugins>
    <plugin>
      <artifactId>maven-assembly-plugin</artifactId>
      <configuration>
        <archive>
          <manifest>
            <mainClass>com.main.Main</mainClass>
          </manifest>
        </archive>
        <descriptorRefs>
          <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
      </configuration>
    </plugin>
  </plugins>
</build>
</code>```

Run mvn clean compile assembly:single

Then you will be able to run java -jar name-with-dependencies.jar

ContentLicense: CC BY-SA 3.0

Body:
So, the software is working properly and everything is fine. I did find some answers to my question online but I can't seem to fix my problem. Everything seems to be okay in my Build Path and in order.
The error I'm getting:

    Exception in thread "main" java.lang.NoClassDefFoundError: org/hibernate/service/ServiceRegistry
        at java.base/java.lang.Class.forName0(Native Method)
        at java.base/java.lang.Class.forName(Unknown Source)
        at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:56)
Caused by: java.lang.ClassNotFoundException: org.hibernate.service.ServiceRegistry
        at java.base/java.net.URLClassLoader.findClass(Unknown Source)
        at java.base/java.lang.ClassLoader.loadClass(Unknown Source)
        at java.base/java.lang.ClassLoader.loadClass(Unknown Source)
        ... 3 more

I need to export my project to a JAR file, please help me, I'm desperate. And thanks to anyone that cares to answer in advance.

Body:
Building a jar-with-dependencies will solve your problem.

Add the following to your pom.xml file:

<build>
  <plugins>
    <plugin>
      <artifactId>maven-assembly-plugin</artifactId>
      <configuration>
        <archive>
          <manifest>
            <mainClass>com.main.Main</mainClass>
          </manifest>
        </archive>
        <descriptorRefs>
          <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
      </configuration>
    </plugin>
  </plugins>
</build>

Run mvn clean compile assembly:single

Then you will be able to run java -jar name-with-dependencies.jar


问:
MVC - dbcontext database connection string
i've created a MVC project and the database was created through dbcontext on localdb... later i changed my database location and i added this string connection pointing to the place that i pasted the database copy. My problem is that instead of using the database, MVC created a new one with the same name on same location, what am i doing wrong?
see here my connection string , my class context and solution explorer and visual studio SSOE ...

PS: i have not installed sql server, im using visual studio SSOE.

Thanks you...

答:
Try explicitly telling EF what connection string to use by adding a constructor and passing it in:</p>

```<code>public class cl_Context: DbContext
{
    public cl_Context()
        : base("cl_Context")
    {
    }
}
</code>```

Body:
Try explicitly telling EF what connection string to use by adding a constructor and passing it in:

public class cl_Context: DbContext
{
    public cl_Context()
        : base("cl_Context")
    {
    }
}


问:
Convert graphviz.dot.Digraph to networkx.Graph

Question

How do I convert a graphviz.dot.Digraph into a networkx.Graph (or any subclass of it)?

Motivation

LightGBM, an implementation of a tree-based algorithm, has a function returning a graphviz.dot.Digraph object. This type of object can represent any directed graph, but my graph is specifically a tree, and thus can be represented in JSON via a simpler nested structure:

```<code>var tree = {
    "name": "parent",
    "children": [
         {
         "name": "child_1"
         }
         {
         "name": "child_2"
         }
    [
}
</code>```

Another, longer example of the above JSON structure is here. I use this JSON format to create a tree visualization using d3 in javascript.

In total, I need to convert this graphviz.dot.Digraph object to the above nested-JSON format.

If I can convert this graphviz.dot.Digraph object into a networkx.Graph object, I can use this method to convert it to the required JSON format. This intermediate conversion has been problematic for me. It seems I need another conversion to something networkx can use.

答:
One method of converting graphviz.dot.Digraph to a networkx.Graph is to convert it to a pydotplus.graphviz.Dot object, and convert that into a networkx.classes.multidigraph.MultiDiGraph object which inherets from graph.

```<code>#--------------------
# Do whatever it is you do to create the graphviz.Digraph object
import lightgbm as lgbm

# .......
digraph = lgbm.create_tree_digraph(model)
print(type(digraph)) # prints <class 'graphviz.dot.Digraph'>

#--------------------
# Perform the conversion to networkx
import pydotplus
import networkx

dotplus = pydotplus.graph_from_dot_data(digraph.source)
print(type(dotplus)) # prints <class 'pydotplus.graphviz.Dot'>
# if graph doesn't have multiedges, use dotplus.set_strict(true)
nx_graph = networkx.nx_pydot.from_pydot(dotplus)
print(type(nx_graph)) # prints <class 'networkx.classes.multidigraph.MultiDiGraph'>
</code>```

The rest is just for people considering conversion to JSON

```<code>#--------------------
# Optionally, convert to json
import json

# must specify whatever node is the root of the tree, here its 'split0'
#     or you can try list(graph)[0] if you're not sure.
data = networkx.readwrite.json_graph.tree_data(nx_graph,root='split0')
# data is just a dictionary. Dump results in proper json format.
json.dump(data,open(file_path,'w'))
</code>```

Later I found out LightGBM actually has a dump_model method that shortcuts all of this...but I'll leave this here.

Body:
Question

How do I convert a graphviz.dot.Digraph into a networkx.Graph (or any subclass of it)?

Motivation

LightGBM, an implementation of a tree-based algorithm, has a function returning a graphviz.dot.Digraph object. This type of object can represent any directed graph, but my graph is specifically a tree, and thus can be represented in JSON via a simpler nested structure:

var tree = {
    "name": "parent",
    "children": [
         {
         "name": "child_1"
         }
         {
         "name": "child_2"
         }
    [
}

Another, longer example of the above JSON structure is here. I use this JSON format to create a tree visualization using d3 in javascript.

In total, I need to convert this graphviz.dot.Digraph object to the above nested-JSON format.

If I can convert this graphviz.dot.Digraph object into a networkx.Graph object, I can use this method to convert it to the required JSON format. This intermediate conversion has been problematic for me. It seems I need another conversion to something networkx can use.

Body:
One method of converting graphviz.dot.Digraph to a networkx.Graph is to convert it to a pydotplus.graphviz.Dot object, and convert that into a networkx.classes.multidigraph.MultiDiGraph object which inherets from graph.

#--------------------
# Do whatever it is you do to create the graphviz.Digraph object
import lightgbm as lgbm

# .......
digraph = lgbm.create_tree_digraph(model)
print(type(digraph)) # prints <class 'graphviz.dot.Digraph'>

#--------------------
# Perform the conversion to networkx
import pydotplus
import networkx

dotplus = pydotplus.graph_from_dot_data(digraph.source)
print(type(dotplus)) # prints <class 'pydotplus.graphviz.Dot'>
# if graph doesn't have multiedges, use dotplus.set_strict(true)
nx_graph = networkx.nx_pydot.from_pydot(dotplus)
print(type(nx_graph)) # prints <class 'networkx.classes.multidigraph.MultiDiGraph'>

The rest is just for people considering conversion to JSON

#--------------------
# Optionally, convert to json
import json

# must specify whatever node is the root of the tree, here its 'split0'
#     or you can try list(graph)[0] if you're not sure.
data = networkx.readwrite.json_graph.tree_data(nx_graph,root='split0')
# data is just a dictionary. Dump results in proper json format.
json.dump(data,open(file_path,'w'))

Later I found out LightGBM actually has a dump_model method that shortcuts all of this...but I'll leave this here.


问:
What happens to the task that is initiated if the web api returns the response
I am trying to implement a task in fire and forget manner.

Lets look at the below piece of code.

```<code>public IHttpActionResult Update(int id)
{
   var updatedResult = _updater.update(id);

   // fire and forget a task

   sendEmailToUser();

   return ok();

}

private async Task sendEmailToUser()
{
   var httpclient = new HttpClient();

   // assume the client is initiated with required url and other headers

  await httpclient.postasync("some url");

}
</code>```

Given the above code, can i safely assume that whenever Update endpoint is called, sendEmailToUser task is triggered and will be run to completion ?

答:
Under normal conditions, it's reasonable to expect that the task will run to completion. It will go on independently.

Your biggest concerns, in this case, should be about the web API not being terminated, and the task not throwing an exception.

But if OP needs to be 100% sure, there are other safer ways to code that.

Body:
I am trying to implement a task in fire and forget manner.

Lets look at the below piece of code.

public IHttpActionResult Update(int id)
{
   var updatedResult = _updater.update(id);

   // fire and forget a task

   sendEmailToUser();

   return ok();

}

private async Task sendEmailToUser()
{
   var httpclient = new HttpClient();

   // assume the client is initiated with required url and other headers

  await httpclient.postasync("some url");

}

Given the above code, can i safely assume that whenever Update endpoint is called, sendEmailToUser task is triggered and will be run to completion ?


问:
How to prevent jquery from importing twice with webpack & typescript?
I am getting this error

```<code>Uncaught TypeError: $(...).dialog is not a function
</code>```

The reason seems to be because I am importing jquery twice. I couldn't find a way to come over this problem.

Here is my complete error where it says something about bootstrap.

```<code>PopupSelectCard.ts:44 Uncaught TypeError: $(...).dialog is not a function
    at Object.PopupSelectCard (PopupSelectCard.ts:44)
    at Object.defineProperty.value (Index.ts:21)
    at __webpack_require__ (bootstrap 92cf533…:19)
    at Object.defineProperty.value (bootstrap 92cf533…:62)
    at bootstrap 92cf533…:62
PopupSelectCard @   PopupSelectCard.ts:44
Object.defineProperty.value @   Index.ts:21
__webpack_require__ @   bootstrap 92cf533…:19
Object.defineProperty.value @   bootstrap 92cf533…:62
(anonymous) @   bootstrap 92cf533…:62
</code>```

This is my webpack.config.js

```<code>var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');

module.exports = {
    context: __dirname,//another dir +"/app"
    // devtool: debug ? "inline-sourcemap" : null,

    // Enable sourcemaps for debugging webpack's output.
    devtool: "source-map",

    entry: "./code/client/scripts/Index.ts",
    output: {
        path: __dirname + "/code/client/views",
        filename: "scripts.min.js"
    },
    plugins: debug ? [] : [
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin({mangle: false, sourcemap: false}),
        new webpack.IgnorePlugin(/fs/),
    ],
    node: {
        fs: 'empty',
        child_process: 'empty',
    },

    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        alias: {
            vue: 'vue/dist/vue.esm.js'
        },
        extensions: [".ts", ".tsx", ".js", ".json"]
    },

    module: {
        rules: [
            // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
            { test: /\.tsx?$/, loader: "awesome-typescript-loader" },

            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            { enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
        ]
    },
};
</code>```

This is how I'm importing in my ts file

```<code>import * as $ from "jquery";
import 'jquery-ui';
</code>```

If I don't import jquery I get compiler errors.

```<code>Cannot find name '$'.
</code>```

How can I solve this?

答:
So I had to do a couple of things.

First of all npm install jquery-ui command doesn't install jquery-ui in a usable way. It needs to be compiled. So instead I used npm install jquery-ui-dist.

Secondly only importing the files doesn't work. I needed the reference path in all of my .ts files that used jqueryui

```<code>///<reference path="../../../../node_modules/@types/jqueryui/index.d.ts"/>
import * as $ from "jquery";
import 'jquery-ui';
</code>```

Third: I added the below code to my webpack.config.ts file.

```<code>var webpack = require('webpack');

module.exports = {
    ...
    plugins: debug ? [] : [
        new webpack.ProvidePlugin({
            jQuery: 'jquery',
            $: 'jquery',
            jquery: 'jquery'
        })
    ],
    resolve: {
        alias: {
            'jquery-ui': 'jquery-ui-dist/jquery-ui.js'
        }
    }
    ...
};
</code>```

Forth I also added the typings npm install @types/jquery & npm install @types/jqueryui

I'm not sure which part was the problem, I did all of this a couple time in different versions until it worked. So if anyone wants to edit my answer to clarify each part be my guest.

Body:
I am getting this error

Uncaught TypeError: $(...).dialog is not a function

The reason seems to be because I am importing jquery twice. I couldn't find a way to come over this problem.

Here is my complete error where it says something about bootstrap.

PopupSelectCard.ts:44 Uncaught TypeError: $(...).dialog is not a function
    at Object.PopupSelectCard (PopupSelectCard.ts:44)
    at Object.defineProperty.value (Index.ts:21)
    at __webpack_require__ (bootstrap 92cf533…:19)
    at Object.defineProperty.value (bootstrap 92cf533…:62)
    at bootstrap 92cf533…:62
PopupSelectCard @   PopupSelectCard.ts:44
Object.defineProperty.value @   Index.ts:21
__webpack_require__ @   bootstrap 92cf533…:19
Object.defineProperty.value @   bootstrap 92cf533…:62
(anonymous) @   bootstrap 92cf533…:62

This is my webpack.config.js

var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');

module.exports = {
    context: __dirname,//another dir +"/app"
    // devtool: debug ? "inline-sourcemap" : null,

    // Enable sourcemaps for debugging webpack's output.
    devtool: "source-map",

    entry: "./code/client/scripts/Index.ts",
    output: {
        path: __dirname + "/code/client/views",
        filename: "scripts.min.js"
    },
    plugins: debug ? [] : [
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin({mangle: false, sourcemap: false}),
        new webpack.IgnorePlugin(/fs/),
    ],
    node: {
        fs: 'empty',
        child_process: 'empty',
    },

    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        alias: {
            vue: 'vue/dist/vue.esm.js'
        },
        extensions: [".ts", ".tsx", ".js", ".json"]
    },

    module: {
        rules: [
            // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
            { test: /\.tsx?$/, loader: "awesome-typescript-loader" },

            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            { enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
        ]
    },
};

This is how I'm importing in my ts file

import * as $ from "jquery";
import 'jquery-ui';

If I don't import jquery I get compiler errors.

Cannot find name '$'.

How can I solve this?

Body:
So I had to do a couple of things.

First of all npm install jquery-ui command doesn't install jquery-ui in a usable way. It needs to be compiled. So instead I used npm install jquery-ui-dist.

Secondly only importing the files doesn't work. I needed the reference path in all of my .ts files that used jqueryui

///<reference path="../../../../node_modules/@types/jqueryui/index.d.ts"/>
import * as $ from "jquery";
import 'jquery-ui';

Third: I added the below code to my webpack.config.ts file.

var webpack = require('webpack');

module.exports = {
    ...
    plugins: debug ? [] : [
        new webpack.ProvidePlugin({
            jQuery: 'jquery',
            $: 'jquery',
            jquery: 'jquery'
        })
    ],
    resolve: {
        alias: {
            'jquery-ui': 'jquery-ui-dist/jquery-ui.js'
        }
    }
    ...
};

Forth I also added the typings npm install @types/jquery & npm install @types/jqueryui

I'm not sure which part was the problem, I did all of this a couple time in different versions until it worked. So if anyone wants to edit my answer to clarify each part be my guest.


问:
Looping through nested arrays and converting to objects
I want to convert an group of nested arrays into an array of objects with the collected information from the nested arrays:

BEFORE:

```<code>var employeeData = [
  [
    ['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']
  ],
  [
    ['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']
  ]
]
</code>```

AFTER:

```<code>[
  {firstName: 'Bob', lastName: 'Lob', age: 22, role: 'salesperson'},
  {firstName: 'Mary', lastName: 'Joe', age: 32, role: 'director'}
]
</code>```

Here is the function I wrote to solve this but I can't quite see where the loop is going wrong:

    var employeeData = [
      [
        ['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']
      ],
      [
        ['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']
      ]
    ]

    function transformData(employeeData) {
      let newObject = {};
      let newArr = [];

      for (var i = 0; i < employeeData.length; i++) {
        for (var x = 0; x < employeeData[i].length; x++) {
          for (var y = 0; y < employeeData[i][y].length; y++) {
            newObject[employeeData[i][y][0]] = employeeData[i][y][1];
          }
        }
        newArr.push(newObject);
        newObject = {};
      }
      return newArr;
    }

    console.log(transformData(employeeData));```

Thanks in advance.

答:
The issue is your use of the variables x and y

For one thing, there's the line

```<code>for (var y = 0; y < employeeData[i][y].length; y++)
</code>```

Perhaps you meant instead to use employeeData[i][x].length, because as you have it here, it is going to behave very strangely.

However, you can entirely eliminate the variable y if you replace it with x (which, in your implementation is never even used)

Here's my suggested edits to your function:

```<code>function transformData(employeeData) {
  let newObject = {};
  let newArr = [];

  for (var i = 0; i < employeeData.length; i++) {
    for (var x = 0; x < employeeData[i].length; x++) {
      newObject[employeeData[i][x][0]] = employeeData[i][x][1];
    }
    newArr.push(newObject);
    newObject = {};
  }
  return newArr;
}
</code>```

Running your example with these changes I got correct output:

```<code>[
  {
    firstName: 'Bob',
    lastName: 'Lob',
    age: 22,
    role: 'salesperson'
  },
  {
    firstName: 'Mary',
    lastName: 'Joe',
    age: 32,
    role: 'director'
  }
]
</code>```

Body:
I want to convert an group of nested arrays into an array of objects with the collected information from the nested arrays:

BEFORE:

var employeeData = [
  [
    ['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']
  ],
  [
    ['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']
  ]
]

AFTER:

[
  {firstName: 'Bob', lastName: 'Lob', age: 22, role: 'salesperson'},
  {firstName: 'Mary', lastName: 'Joe', age: 32, role: 'director'}
]

Here is the function I wrote to solve this but I can't quite see where the loop is going wrong:

    var employeeData = [
      [
        ['firstName', 'Bob'], ['lastName', 'Lob'], ['age', 22], ['role', 'salesperson']
      ],
      [
        ['firstName', 'Mary'], ['lastName', 'Joe'], ['age', 32], ['role', 'director']
      ]
    ]

    function transformData(employeeData) {
      let newObject = {};
      let newArr = [];

      for (var i = 0; i < employeeData.length; i++) {
        for (var x = 0; x < employeeData[i].length; x++) {
          for (var y = 0; y < employeeData[i][y].length; y++) {
            newObject[employeeData[i][y][0]] = employeeData[i][y][1];
          }
        }
        newArr.push(newObject);
        newObject = {};
      }
      return newArr;
    }

    console.log(transformData(employeeData));

Thanks in advance.

Body:
The issue is your use of the variables x and y

For one thing, there's the line

for (var y = 0; y < employeeData[i][y].length; y++)

Perhaps you meant instead to use employeeData[i][x].length, because as you have it here, it is going to behave very strangely.

However, you can entirely eliminate the variable y if you replace it with x (which, in your implementation is never even used)

Here's my suggested edits to your function:

function transformData(employeeData) {
  let newObject = {};
  let newArr = [];

  for (var i = 0; i < employeeData.length; i++) {
    for (var x = 0; x < employeeData[i].length; x++) {
      newObject[employeeData[i][x][0]] = employeeData[i][x][1];
    }
    newArr.push(newObject);
    newObject = {};
  }
  return newArr;
}

Running your example with these changes I got correct output:

[
  {
    firstName: 'Bob',
    lastName: 'Lob',
    age: 22,
    role: 'salesperson'
  },
  {
    firstName: 'Mary',
    lastName: 'Joe',
    age: 32,
    role: 'director'
  }
]


问:
TFS: Cloaking multiple elements from command line
Suppose we have a folder $/myProject/myFolder on the TFS server which contains some files and sub-folders.

Is there any possibility to iteratively cloak every element under this folder (not recursively) using the tf.exe command line utility?

I can't simply cloak the root folder $/myProject/myFolder because I need to decloak some of its elements afterwards which seems only to be possible, if each element has been cloaked independently.

In the end, I want to achieve that all elements below a specific root folder are cloaked except of some predefined ones.

答:
In PowerShell, it's safe and easy:

    PS> $folders = Get-ChildItem
    # filter $folders as needed
    PS> $folders | ForEach-Object { tf workfold /cloak $_.Name }
```

ContentLicense: CC BY-SA 4.0


问:
How to use Gnupg's passphrase-fd argument?
I would like to use GnuPG´s decrypt command without any user interation. The script's --passphrase-fd argument seems exactly what I need. But I don't know how it works - haven't found examples.

Could anyone give me an example of such a command, on both Windows and UNIX environments?

(FYI, I'm using GnuPG 2).

Thanks already :)

答:
Using GPG4win/gpg 2.2.3: to use the passphrase-fd 0 and bypass the prompt, I can confirm that the following works:

```<code>--pinentry-mode loopback
</code>```

Body:
Using GPG4win/gpg 2.2.3: to use the passphrase-fd 0 and bypass the prompt, I can confirm that the following works:

--pinentry-mode loopback


问:
How to center HTML code while using Bootstrap
Part of my code sticks to the left side of the page. I can not figure out a way to put these buttons in the middle of the website. Just trying to make look better if I add center or text block center it does not work it only ads the radio button symbol above the text or it shifts just the symbol to the middle.

```<code>    <div class="jumbotron">
    <h1 class="jumbotron-heading"><center>Bazár Bez Havárie</center></h1>
    <p class="lead text-muted"><center>Vitajte v Bazáry Bez Havárie. Vyberte
    si svoje auto.</center></p><br>
    <h2 class="jumbotron-heading"><center><b>Objednávkový formulár.</b>
    </center></h1><br>
    <form class="form-horizontal" role="form" method="get"
    action="objednavka.php">
    <div class="form-group">
    <label for="name" class="col-sm-2 control-label"><center>Meno</center>
    </label>
    <div class="col-sm-12">
    <input type="text" class="form-control" id="name" name="name"
    placeholder="" value="">
    </div>
    </div>
    <div class="form-group">
    <label for="email" class="col-sm-2 control-label"><center>Email</center>
    </label>
    <div class="col-sm-12">
    <input type="email" class="form-control" id="email" name="email"
    placeholder="" value="">
    </div>
    </div>
    <div class="form-group">
    <label for="adress" class="col-sm-2 control-label">
    <center>Adresa</center></label>
    <div class="col-sm-12">
    <input type="adress" class="form-control" id="address" name="address"
    placeholder="" value="">
    </div>
    </div>

    <h2><b>Auto na vyber</b></h2><br>

   <div class="btn-group" data-toggle="buttons">

   <label class="btn btn-light">
   <input type="radio" name="options" id="option1" value="Ferrari GTC4Lusso"
   autocomplete="off"><center> Ferrari GTC4Lusso </center>
   </label>

   <label class="btn btn-light">
   <input type="radio" name="options" id="option2" value="Porsche Carrera
   GT" autocomplete="off"> <center>Porsche Carrera GT </center>
   </label>

   </div>
   <br><br>
   <h2><b>Farba auta</b></h2><br> <div class="btn-group" data-
   toggle="buttons">
</code>```

Here in the middle

```<code>   <label class="btn btn-sample">
   <label class="btn btn-cierna btn-lg btn-lg">
   <input type="radio" name="tlacidla" id="tlacidla2" value="Čierna"
   autocomplete="off"><center> Čierna </center>
   </label>
   <label class="btn btn-cervena btn-lg btn-lg">
   <input type="radio" name="tlacidla" id="tlacidla3" value="Červená"
    autocomplete="off"><center> Červená </center>
</code>```

Ends here

```<code>   </label>
   </div><br><br>
   <div class="form-group">
</code>```

And this one below too.

```<code>   <input type="submit" name="submit"  value="Potvrdit Objednavku"
    class="btn btn-outline-danger">
    </div>
   </form>
   </div>
</code>```

答:
Change the HTML to:

```<code> <div class="form-group align-items-center mx-auto">
    <input type="radio" class="form-control">
    <label for="exampleInputEmail1">Ferrari GTC4Lusso</label>
  </div>
</code>```

And add the following CSS:

```<code>.form-group {
  width: 100px;
    display: inline-block;
    margin: 5px;
}
.form-group label {
   display:block;
    width: 100px;
    text-align: center;
}
.form-group input {
   width: 20px;
    display: block;
    margin: 0px auto;
}
</code>```

JSFiddle: https://jsfiddle.net/vf7qfghc/

.form-group {
  width: 100px;
    display: inline-block;
    margin: 5px;
}
.form-group label {
   display:block;
    width: 100px;
    text-align: center;
}
.form-group input {
   width: 20px;
    display: block;
    margin: 0px auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

<div class="form-group align-items-center mx-auto">

    <input type="radio" class="form-control">
   <label for="exampleInputEmail1">Ferrari GTC4Lusso</label>
  </div></code>```

Body:
Part of my code sticks to the left side of the page. I can not figure out a way to put these buttons in the middle of the website. Just trying to make look better if I add center or text block center it does not work it only ads the radio button symbol above the text or it shifts just the symbol to the middle.

Bazár Bez Havárie

Vitajte v Bazáry Bez Havárie. Vyberte
    si svoje auto.

Objednávkový formulár.

    <form class="form-horizontal" role="form" method="get"
    action="objednavka.php">

    Meno

    <input type="text" class="form-control" id="name" name="name"
    placeholder="" value="">

    Email

    <input type="email" class="form-control" id="email" name="email"
    placeholder="" value="">

    Adresa

    <input type="adress" class="form-control" id="address" name="address"
    placeholder="" value="">

Auto na vyber

   <input type="radio" name="options" id="option1" value="Ferrari GTC4Lusso"
   autocomplete="off"> Ferrari GTC4Lusso

   <input type="radio" name="options" id="option2" value="Porsche Carrera
   GT" autocomplete="off"> Porsche Carrera GT

Farba auta

Here in the middle

   <input type="radio" name="tlacidla" id="tlacidla2" value="Čierna"
   autocomplete="off"> Čierna

   <input type="radio" name="tlacidla" id="tlacidla3" value="Červená"
    autocomplete="off"> Červená

Ends here

And this one below too.

   <input type="submit" name="submit"  value="Potvrdit Objednavku"
    class="btn btn-outline-danger">

   </form>

Body:
Change the HTML to:

 <div class="form-group align-items-center mx-auto">
    <input type="radio" class="form-control">
    <label for="exampleInputEmail1">Ferrari GTC4Lusso</label>
  </div>

And add the following CSS:

.form-group {
  width: 100px;
    display: inline-block;
    margin: 5px;
}
.form-group label {
   display:block;
    width: 100px;
    text-align: center;
}
.form-group input {
   width: 20px;
    display: block;
    margin: 0px auto;
}

JSFiddle: https://jsfiddle.net/vf7qfghc/

.form-group {
  width: 100px;
    display: inline-block;
    margin: 5px;
}
.form-group label {
   display:block;
    width: 100px;
    text-align: center;
}
.form-group input {
   width: 20px;
    display: block;
    margin: 0px auto;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

<div class="form-group align-items-center mx-auto">

    <input type="radio" class="form-control">
   <label for="exampleInputEmail1">Ferrari GTC4Lusso</label>
  </div>


问:
Using Oracle Path Expressions on JSON arrays
I am attempting to write a simple query with path expressions against an Oracle JSON data structure that will return the Student Name and the the name of their CS220 teacher (if they are taking that class).

The JSON:

```<code>{
  'studentName': 'John Smith',
  'classes': [
    {
      'className': 'CS115',
      'teacherName': 'Sally Wilson'
    },
    {
      'className': 'CS220',
      'teacherName': 'Jason Wu'
    }
  ]
}
</code>```

Expected Output

```<code>Student Name      Professor
John Smith        Jason Wu
Jane Doe                             << Not taking CS220
Ajay Kumar        Robert Kroll
</code>```

The query I would hope to write:

```<code>Select
    jsonfield.studentName,
    jsonfield.classes.<some path expression to find the CS220 professor here>
from mytable
</code>```

The only solution I have found is to project out the nested 'classes' into a table and join that to the query above to get the professor.  I would have thought that Oracle's json path implementation would be able to solve this without the overhead/complexity of a second query.

答:
In 12cR1 you could do something like:

```<code>select jt.studentname,
  max(case when jt.classname = 'CS220' then jt.teachername end) as teachername
from mytable mt
cross join json_table (
  mt.jsonfield,
  '$'
  columns (
    studentname varchar2(30) path '$.studentName',
    nested path '$.classes[*]' columns (
      classname varchar2(30) path '$.className',
      teachername varchar2(30) path '$.teacherName'
    )
  )
) jt
group by jt.studentname;
</code>```

The json_table() splits the JSON into relational columns; the nested path means you get one row per class (per student), with the relevant class names and teacher names.

The select list then uses a case expression to change the teacher name to null for any other classes - so John Smith gets one row with CS220 and Jason Wu, and one row with CS115 and null. Aggregating that with max() collapses those so all the irrelevant teachers are ignored.

With some expanded sample data:

```<code>create table mytable (jsonfield clob check (jsonfield is json));
insert into mytable a(jsonfield) values (q'#{
  'studentName': 'John Smith',
  'classes': [
    {
      'className': 'CS115',
      'teacherName': 'Sally Wilson'
    },
    {
      'className': 'CS220',
      'teacherName': 'Jason Wu'
    }
  ]
}#');
insert into mytable a(jsonfield) values (q'#{
  'studentName': 'Jane Doe',
  'classes': [
    {
      'className': 'CS115',
      'teacherName': 'Sally Wilson'
    }
  ]
}#');
insert into mytable a(jsonfield) values (q'#{
  'studentName': 'Ajay Kumar',
  'classes': [
    {
      'className': 'CS220',
      'teacherName': 'Robert Kroll'
    }
  ]
}#');
</code>```

the basic json_table() call gets:

```<code>select jt.*,
  case when jt.classname = 'CS220' then jt.teachername end as adjusted_teachername
from mytable mt
cross join json_table (
  mt.jsonfield,
  '$'
  columns (
    studentname varchar2(30) path '$.studentName',
    nested path '$.classes[*]' columns (
      classname varchar2(30) path '$.className',
      teachername varchar2(30) path '$.teacherName'
    )
  )
) jt;

STUDENTNAME                    CLASSNAME                      TEACHERNAME                    ADJUSTED_TEACHERNAME
------------------------------ ------------------------------ ------------------------------ ------------------------------
John Smith                     CS115                          Sally Wilson
John Smith                     CS220                          Jason Wu                       Jason Wu
Jane Doe                       CS115                          Sally Wilson
Ajay Kumar                     CS220                          Robert Kroll                   Robert Kroll
</code>```

Adding the aggregation step gets:

```<code>select jt.studentname,
  max(case when jt.classname = 'CS220' then jt.teachername end) as teachername
from mytable mt
cross join json_table (
  mt.jsonfield,
  '$'
  columns (
    studentname varchar2(30) path '$.studentName',
    nested path '$.classes[*]' columns (
      classname varchar2(30) path '$.className',
      teachername varchar2(30) path '$.teacherName'
    )
  )
) jt
group by jt.studentname;

STUDENTNAME                    TEACHERNAME
------------------------------ ------------------------------
John Smith                     Jason Wu
Jane Doe
Ajay Kumar                     Robert Kroll
</code>```

In 12cR2 I think thought you might be able to do something like this instead, with a filter inside the JSON path (which isn't allowed in 12cR1):

```<code>select jt.*
from mytable mt
cross join json_table (
  mt.jsonfield,
  '$'
  columns (
    studentname varchar2(30) path '$.studentName',
    nested path '$.classes[*]?(@.className=="CS220")' columns (
      teachername varchar2(30) path '$.teacherName'
    )
  )
) jt;
</code>```

... but I don't have a suitable DB to test that against.

... but it turns out that gets "ORA-40553: path expression with predicates not supported in this operation" and "Only JSON_EXISTS supports predicates".

Body:
I am attempting to write a simple query with path expressions against an Oracle JSON data structure that will return the Student Name and the the name of their CS220 teacher (if they are taking that class).

The JSON:

{
  'studentName': 'John Smith',
  'classes': [
    {
      'className': 'CS115',
      'teacherName': 'Sally Wilson'
    },
    {
      'className': 'CS220',
      'teacherName': 'Jason Wu'
    }
  ]
}

Expected Output

Student Name      Professor
John Smith        Jason Wu
Jane Doe                             << Not taking CS220
Ajay Kumar        Robert Kroll

The query I would hope to write:

Select
    jsonfield.studentName,
    jsonfield.classes.<some path expression to find the CS220 professor here>
from mytable

The only solution I have found is to project out the nested 'classes' into a table and join that to the query above to get the professor.  I would have thought that Oracle's json path implementation would be able to solve this without the overhead/complexity of a second query.

Body:
In 12cR1 you could do something like:

select jt.studentname,
  max(case when jt.classname = 'CS220' then jt.teachername end) as teachername
from mytable mt
cross join json_table (
  mt.jsonfield,
  '$'
  columns (
    studentname varchar2(30) path '$.studentName',
    nested path '$.classes[*]' columns (
      classname varchar2(30) path '$.className',
      teachername varchar2(30) path '$.teacherName'
    )
  )
) jt
group by jt.studentname;

The json_table() splits the JSON into relational columns; the nested path means you get one row per class (per student), with the relevant class names and teacher names.

The select list then uses a case expression to change the teacher name to null for any other classes - so John Smith gets one row with CS220 and Jason Wu, and one row with CS115 and null. Aggregating that with max() collapses those so all the irrelevant teachers are ignored.

With some expanded sample data:

create table mytable (jsonfield clob check (jsonfield is json));
insert into mytable a(jsonfield) values (q'#{
  'studentName': 'John Smith',
  'classes': [
    {
      'className': 'CS115',
      'teacherName': 'Sally Wilson'
    },
    {
      'className': 'CS220',
      'teacherName': 'Jason Wu'
    }
  ]
}#');
insert into mytable a(jsonfield) values (q'#{
  'studentName': 'Jane Doe',
  'classes': [
    {
      'className': 'CS115',
      'teacherName': 'Sally Wilson'
    }
  ]
}#');
insert into mytable a(jsonfield) values (q'#{
  'studentName': 'Ajay Kumar',
  'classes': [
    {
      'className': 'CS220',
      'teacherName': 'Robert Kroll'
    }
  ]
}#');

the basic json_table() call gets:

select jt.*,
  case when jt.classname = 'CS220' then jt.teachername end as adjusted_teachername
from mytable mt
cross join json_table (
  mt.jsonfield,
  '$'
  columns (
    studentname varchar2(30) path '$.studentName',
    nested path '$.classes[*]' columns (
      classname varchar2(30) path '$.className',
      teachername varchar2(30) path '$.teacherName'
    )
  )
) jt;

STUDENTNAME                    CLASSNAME                      TEACHERNAME                    ADJUSTED_TEACHERNAME
------------------------------ ------------------------------ ------------------------------ ------------------------------
John Smith                     CS115                          Sally Wilson
John Smith                     CS220                          Jason Wu                       Jason Wu
Jane Doe                       CS115                          Sally Wilson
Ajay Kumar                     CS220                          Robert Kroll                   Robert Kroll

Adding the aggregation step gets:

select jt.studentname,
  max(case when jt.classname = 'CS220' then jt.teachername end) as teachername
from mytable mt
cross join json_table (
  mt.jsonfield,
  '$'
  columns (
    studentname varchar2(30) path '$.studentName',
    nested path '$.classes[*]' columns (
      classname varchar2(30) path '$.className',
      teachername varchar2(30) path '$.teacherName'
    )
  )
) jt
group by jt.studentname;

STUDENTNAME                    TEACHERNAME
------------------------------ ------------------------------
John Smith                     Jason Wu
Jane Doe
Ajay Kumar                     Robert Kroll

In 12cR2 I think thought you might be able to do something like this instead, with a filter inside the JSON path (which isn't allowed in 12cR1):

select jt.*
from mytable mt
cross join json_table (
  mt.jsonfield,
  '$'
  columns (
    studentname varchar2(30) path '$.studentName',
    nested path '$.classes[*]?(@.className=="CS220")' columns (
      teachername varchar2(30) path '$.teacherName'
    )
  )
) jt;

... but I don't have a suitable DB to test that against.

... but it turns out that gets "ORA-40553: path expression with predicates not supported in this operation" and "Only JSON_EXISTS supports predicates".


问:
How to pass Global variables to classes in PHP?
How can I pass the global variables to the classes I want to use without declare them as GLOBAL in every method of the class ?

example :

```<code>$admin = "admin_area";

if($_POST['login']){
      $user = new Administrator;
      $user->auth($pass,$username);
    }
</code>```

in the class Administrator I want the variable $admin be accessible in all methods of the class without doing this :

```<code>class Administrator{

   public function auth($pass,$user){

     global $admin;
     .....

  }
  public function logout(){
    global $admin;

    .....
}

}
</code>```

答:
Try passing the variable that you want to be global to the object as an argument, and then use the __constructor() method to make it a class property.

You can find more info and examples here:
In php when initializing a class how would one pass a variable to that class to be used in its functions?

Body:
How can I pass the global variables to the classes I want to use without declare them as GLOBAL in every method of the class ?

example :

$admin = "admin_area";

if($_POST['login']){
      $user = new Administrator;
      $user->auth($pass,$username);
    }

in the class Administrator I want the variable $admin be accessible in all methods of the class without doing this :

class Administrator{

   public function auth($pass,$user){

     global $admin;
     .....

  }
  public function logout(){
    global $admin;

    .....
}

}


问:
Invoke-WebRequest SSL fails?
When I try to use Invoke-WebRequest I'm getting some weird error:

```<code>Invoke-WebRequest -Uri "https://idp.safenames.com/"

Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send.
</code>```

I'm not sure what's causing it, as the website itself seems fine.

Even with all the "ignore ssl errors" functions around stackoverflow, it's still not working, making me wonder if it's related to SSL at all.

答:
This can be permanently changed as well</p>

```<code># set strong cryptography on 32 bit .Net Framework (version 4 and above)
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
# set strong cryptography on 64 bit .Net Framework (version 4 and above)
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
</code>```

Title: Invoke-WebRequest SSL fails?

Body:
When I try to use Invoke-WebRequest I'm getting some weird error:

Invoke-WebRequest -Uri "https://idp.safenames.com/"

Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send.

I'm not sure what's causing it, as the website itself seems fine.

Even with all the "ignore ssl errors" functions around stackoverflow, it's still not working, making me wonder if it's related to SSL at all.

Body:
This can be permanently changed as well

# set strong cryptography on 32 bit .Net Framework (version 4 and above)
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord
# set strong cryptography on 64 bit .Net Framework (version 4 and above)
Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\.NetFramework\v4.0.30319' -Name 'SchUseStrongCrypto' -Value '1' -Type DWord


问:
Python 3: Returning a new child class instance from an inherited method, when child constructor has more arguments than parent constructor
Suppose I have a parent class and multiple child classes, which extend the parent class by including more specific information about the ideas they represent.  For example:

```<code>class Shape:
    def __init__(self, center):
        self.center = center

class Square(Shape):
    def __init__(self, center, side_length):
        super().__init__(self, center)
        self.side_length = side_length
        self.area = side_length ** 2

class Circle(Shape):
    def __init__(self, center, radius):
        super().__init__(self, center)
        self.radius = radius
        self.area = 3.14 * (radius ** 2)
</code>```

Suppose I want to implement a method such as translate(new_center) in the parent class, which would return a new object with a different center location than the original object.  Because all child classes should behave the same way (i.e. the attribute self.center should change), it makes sense to implement translate() as a method of the parent class Shape.

If I want to return a new object of type Shape every time translate() is called, we can simply define translate() as a method of Shape like so:

```<code>    def translate(self, new_center):
        return Shape(new_center)
</code>```

However, if any child class instances call this method, the result will be of type Shape, and thus any additional state information contained by the original instance, such as side_length and area for a Square, will be lost.  Additionally, translate() cannot be defined as

```<code>    def translate(self, new_center):
        return self.__class__(new_center)
</code>```

because the constructors for each of the child classes require additional arguments that the parent class constructor doesn't.  How can I implement this without having to override the parent method in each of the child classes (avoiding which was the entire point of defining the parent method)?

答:
You could copy the object and modify the copy:</p>

```<code>import copy

class Shape():
  def __init__(self, center):
    self.center = center

  def translate(self, new_center):
    new_shape = copy.copy(self) # Replace with deepcopy if needed
    new_shape.center = new_center

...
</code>```

Body:
Suppose I have a parent class and multiple child classes, which extend the parent class by including more specific information about the ideas they represent.  For example:

class Shape:
    def __init__(self, center):
        self.center = center

class Square(Shape):
    def __init__(self, center, side_length):
        super().__init__(self, center)
        self.side_length = side_length
        self.area = side_length ** 2

class Circle(Shape):
    def __init__(self, center, radius):
        super().__init__(self, center)
        self.radius = radius
        self.area = 3.14 * (radius ** 2)

Suppose I want to implement a method such as translate(new_center) in the parent class, which would return a new object with a different center location than the original object.  Because all child classes should behave the same way (i.e. the attribute self.center should change), it makes sense to implement translate() as a method of the parent class Shape.

If I want to return a new object of type Shape every time translate() is called, we can simply define translate() as a method of Shape like so:

    def translate(self, new_center):
        return Shape(new_center)

However, if any child class instances call this method, the result will be of type Shape, and thus any additional state information contained by the original instance, such as side_length and area for a Square, will be lost.  Additionally, translate() cannot be defined as

    def translate(self, new_center):
        return self.__class__(new_center)

because the constructors for each of the child classes require additional arguments that the parent class constructor doesn't.  How can I implement this without having to override the parent method in each of the child classes (avoiding which was the entire point of defining the parent method)?

Body:
You could copy the object and modify the copy:

import copy

class Shape():
  def __init__(self, center):
    self.center = center

  def translate(self, new_center):
    new_shape = copy.copy(self) # Replace with deepcopy if needed
    new_shape.center = new_center

...


问:
Wrap
 tags with
 tag in RTE text
I have an RTE text which is formatted as below:

```<code><li> text </li>
<li> text </li>
<p>  text </p>
<p>  text </p>
<li> text </li>
<li> text </li>
</code>```

The problem here is, The "li" tags are not wraped within "ul" tag. I want to achieve this using Java since I am writing a migration script. I found answers in Jquery but it is hard to find in solution like this in Java.

Note: not sure if it's important or not but this is an RTE text given by the client in Excel sheet for migration.

The desired result from above text is below:

```<code><ul>
   <li> text </li>
   <li> text </li>
</ul>
   <p>  text </p>
   <p>  text </p>
<ul>
   <li> text </li>
   <li> text </li>
</ul>
</code>```

答:
If you are just getting it back as a string, here is a regex solution that should work or at least serve as a good starting point.

```<code>String pattern1 = "(?<!</li>\\s{0,100})(<li>)";
String replace1 = "<ul><li>";

String pattern2 = "</li>(?!\\s{0,100}<li>)";
String replace2 = "</li></ul>";
</code>```

The pattern looks for
 tags that aren't preceded by an
 tag (ignoring any white space in between them) then replaces them with an opening

 tag.

Then it looks for any
 tags that aren't followed by a
 tag and replaces with a

 tag

Full code below, or here is a live example

```<code>import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatches {

   public static void main( String args[] ) {
      // String to be scanned to find the pattern.
      String input = "<li> text </li> <li> text </li> <p>  text </p> <p>  text </p><li> text<span>more test</span> </li><li> text </li>";
      String pattern1 = "(?<!</li>\\s{0,100})(<li>)";
      String replace1 = "<ul><li>";

      String pattern2 = "</li>(?!\\s{0,100}<li>)";
      String replace2 = "</li></ul>";

      // Create a Pattern object
      Pattern r1 = Pattern.compile(pattern1);
      Pattern r2 = Pattern.compile(pattern2);
      // Now create matcher object.
      Matcher m1 = r1.matcher(input);

      input = m1.replaceAll(replace1);

      Matcher m2 = r2.matcher(input);
      input = m2.replaceAll(replace2);
      System.out.println(input);

   }
}
</code>```

Title: Wrap <li> tags with <ul> tag in RTE text

Body:
I have an RTE text which is formatted as below:

 text

 text

  text

  text

 text

 text

The problem here is, The "li" tags are not wraped within "ul" tag. I want to achieve this using Java since I am writing a migration script. I found answers in Jquery but it is hard to find in solution like this in Java.

Note: not sure if it's important or not but this is an RTE text given by the client in Excel sheet for migration.

The desired result from above text is below:

 text

 text

  text

  text

 text

 text

Body:
If you are just getting it back as a string, here is a regex solution that should work or at least serve as a good starting point.

String pattern1 = "(?<!</li>\\s{0,100})(<li>)";
String replace1 = "<ul><li>";

String pattern2 = "</li>(?!\\s{0,100}<li>)";
String replace2 = "</li></ul>";

The pattern looks for <li> tags that aren't preceded by an </li> tag (ignoring any white space in between them) then replaces them with an opening <ul><li> tag.

Then it looks for any </li> tags that aren't followed by a <li> tag and replaces with a </li></ul> tag

Full code below, or here is a live example

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexMatches {

   public static void main( String args[] ) {
      // String to be scanned to find the pattern.
      String input = "<li> text </li> <li> text </li> <p>  text </p> <p>  text </p><li> text<span>more test</span> </li><li> text </li>";
      String pattern1 = "(?<!</li>\\s{0,100})(<li>)";
      String replace1 = "<ul><li>";

      String pattern2 = "</li>(?!\\s{0,100}<li>)";
      String replace2 = "</li></ul>";

      // Create a Pattern object
      Pattern r1 = Pattern.compile(pattern1);
      Pattern r2 = Pattern.compile(pattern2);
      // Now create matcher object.
      Matcher m1 = r1.matcher(input);

      input = m1.replaceAll(replace1);

      Matcher m2 = r2.matcher(input);
      input = m2.replaceAll(replace2);
      System.out.println(input);

   }
}


问:
Tensorflow NaN bug?
I'm using TensorFlow and I modified the tutorial example to take my RGB images.

The algorithm works flawlessly out of the box on the new image set, until suddenly (still converging, it's around 92% accuracy usually), it crashes with the error that ReluGrad received non-finite values. Debugging shows that nothing unusual happens with the numbers until very suddenly, for unknown reason, the error is thrown. Adding

```<code>print "max W vales: %g %g %g %g"%(tf.reduce_max(tf.abs(W_conv1)).eval(),tf.reduce_max(tf.abs(W_conv2)).eval(),tf.reduce_max(tf.abs(W_fc1)).eval(),tf.reduce_max(tf.abs(W_fc2)).eval())
print "max b vales: %g %g %g %g"%(tf.reduce_max(tf.abs(b_conv1)).eval(),tf.reduce_max(tf.abs(b_conv2)).eval(),tf.reduce_max(tf.abs(b_fc1)).eval(),tf.reduce_max(tf.abs(b_fc2)).eval())
</code>```

as debug code to each loop, yields the following output:

```<code>Step 8600
max W vales: 0.759422 0.295087 0.344725 0.583884
max b vales: 0.110509 0.111748 0.115327 0.124324
Step 8601
max W vales: 0.75947 0.295084 0.344723 0.583893
max b vales: 0.110516 0.111753 0.115322 0.124332
Step 8602
max W vales: 0.759521 0.295101 0.34472 0.5839
max b vales: 0.110521 0.111747 0.115312 0.124365
Step 8603
max W vales: -3.40282e+38 -3.40282e+38 -3.40282e+38 -3.40282e+38
max b vales: -3.40282e+38 -3.40282e+38 -3.40282e+38 -3.40282e+38
</code>```

Since none of my values is very high, the only way a NaN can happen is by a badly handled 0/0, but since this tutorial code doesn't do any divisions or similar operations, I see no other explanation than that this comes from the internal TF code.

I'm clueless on what to do with this. Any suggestions? The algorithm is converging nicely, its accuracy on my validation set was steadily climbing and just reached 92.5% at iteration 8600.

答:
I used LSTM for long sequences and got nan gradients. None of these answers helped me. But I came up with three own solutions. I hope they will be useful for some other people who came here from google search.

Gradient clipping didn't help me because gradients turned nan in one batch update. In this case, you can replace nans with zeros with such lines:

```<code>opt = tf.train.AdamOptimizer(args.lr)
grads = opt.compute_gradients(loss)
grads2 = [(tf.where(tf.is_nan(grad), tf.zeros(grad.shape), grad), var) for grad, var in grads]
opt_op = opt.apply_gradients(grads2)
</code>```

If you want to track if nans appeared you can use this code:

```<code>was_nan = tf.reduce_any(tf.convert_to_tensor([tf.reduce_any(tf.is_nan(g)) for g in grads]))
</code>```

Replace LSTMCell with LayerNormBasicLSTMCell - an LSTM cell with layer norm - something similar to batch norm between timesteps.

If you use regular recurrent state dropout you can replace it with "Recurrent Dropout without Memory Loss". Code:

```<code>LayerNormBasicLSTMCell(neurons, dropout_keep_prob=0.8)
</code>```

Note that you can also turn on the dropout feature alone without layer normalization:

```<code>LayerNormBasicLSTMCell(neurons, layer_norm=False, dropout_keep_prob=0.8)
</code>```

Title: Tensorflow NaN bug?

Body:
I'm using TensorFlow and I modified the tutorial example to take my RGB images.

The algorithm works flawlessly out of the box on the new image set, until suddenly (still converging, it's around 92% accuracy usually), it crashes with the error that ReluGrad received non-finite values. Debugging shows that nothing unusual happens with the numbers until very suddenly, for unknown reason, the error is thrown. Adding

print "max W vales: %g %g %g %g"%(tf.reduce_max(tf.abs(W_conv1)).eval(),tf.reduce_max(tf.abs(W_conv2)).eval(),tf.reduce_max(tf.abs(W_fc1)).eval(),tf.reduce_max(tf.abs(W_fc2)).eval())
print "max b vales: %g %g %g %g"%(tf.reduce_max(tf.abs(b_conv1)).eval(),tf.reduce_max(tf.abs(b_conv2)).eval(),tf.reduce_max(tf.abs(b_fc1)).eval(),tf.reduce_max(tf.abs(b_fc2)).eval())

as debug code to each loop, yields the following output:

Step 8600
max W vales: 0.759422 0.295087 0.344725 0.583884
max b vales: 0.110509 0.111748 0.115327 0.124324
Step 8601
max W vales: 0.75947 0.295084 0.344723 0.583893
max b vales: 0.110516 0.111753 0.115322 0.124332
Step 8602
max W vales: 0.759521 0.295101 0.34472 0.5839
max b vales: 0.110521 0.111747 0.115312 0.124365
Step 8603
max W vales: -3.40282e+38 -3.40282e+38 -3.40282e+38 -3.40282e+38
max b vales: -3.40282e+38 -3.40282e+38 -3.40282e+38 -3.40282e+38

Since none of my values is very high, the only way a NaN can happen is by a badly handled 0/0, but since this tutorial code doesn't do any divisions or similar operations, I see no other explanation than that this comes from the internal TF code.

I'm clueless on what to do with this. Any suggestions? The algorithm is converging nicely, its accuracy on my validation set was steadily climbing and just reached 92.5% at iteration 8600.

Body:
I used LSTM for long sequences and got nan gradients. None of these answers helped me. But I came up with three own solutions. I hope they will be useful for some other people who came here from google search.

Gradient clipping didn't help me because gradients turned nan in one batch update. In this case, you can replace nans with zeros with such lines:

opt = tf.train.AdamOptimizer(args.lr)
grads = opt.compute_gradients(loss)
grads2 = [(tf.where(tf.is_nan(grad), tf.zeros(grad.shape), grad), var) for grad, var in grads]
opt_op = opt.apply_gradients(grads2)

If you want to track if nans appeared you can use this code:

was_nan = tf.reduce_any(tf.convert_to_tensor([tf.reduce_any(tf.is_nan(g)) for g in grads]))

Replace LSTMCell with LayerNormBasicLSTMCell - an LSTM cell with layer norm - something similar to batch norm between timesteps.

If you use regular recurrent state dropout you can replace it with "Recurrent Dropout without Memory Loss". Code:

LayerNormBasicLSTMCell(neurons, dropout_keep_prob=0.8)

Note that you can also turn on the dropout feature alone without layer normalization:

LayerNormBasicLSTMCell(neurons, layer_norm=False, dropout_keep_prob=0.8)


问:
Inno Setup - npm program added to PATH by subinstaller is not recognized in a batch file executed from installer
I have created a Windows installer using Inno Setup for an app I have made. As part of the installer I have included the installation of some third party applications followed by a batch file, to execute a number of npm command operable program or batch file.

Everything installs okay but when the batch file runs I get the message

'npm' is not recognized as an internal or external command

The commands don't run and so the app won't open.  However, if I leave everything as it is and just rerun the batch file again after the installation, the commands execute and the app works fine.  How can I get the batch file to run properly as part of the installation?

Inno Setup Run Section

[Run]
Filename: "{tmp}\Git-2.15.0-64-bit.exe";  Flags: waituntilterminated
Filename: "{tmp}\rubyinstaller-2.3.3-x64.exe";  Flags: waituntilterminated
Filename: "{tmp}\visualcppbuildtools_full.exe";  Flags: waituntilterminated
Filename: "msiexec.exe"; Parameters: "/i ""{tmp}\mongodb-win32-x86_64-2008plus-ssl-3.4.10-signed.msi"; WorkingDir: {tmp}; Flags: waituntilterminated
Filename: "msiexec.exe"; Parameters: "/i ""{tmp}\node-v6.11.0-x64.msi"; WorkingDir: {tmp}; Flags: waituntilterminated
Filename: "{tmp}\setup.bat";
Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: shellexec postinstall skipifsilent
```

<p><strong>Batch File</strong></p>

<pre class="lang-none prettyprint-override"><code>cd C:/Users/%USERNAME%/Documents/myApp/api/
call npm install -g bower
call npm install -g grunt
call npm install -g grunt-cli
call npm config set msvs_version 2015 -global
call npm install bcrypt -save
call npm install
cd ../admin/
call npm install -g bower
call npm install -g grunt
call npm install -g grunt-cli
echo 1 | call gem install compass
call bower install
call npm install
</code>```

答: I'm guessing the installer doesn't modify the PATH for you, so npm isn't being aliased as a command. If you invoke npm by using the absolute path to the executable, it should work as expected.</p>

Body:
I have created a Windows installer using Inno Setup for an app I have made. As part of the installer I have included the installation of some third party applications followed by a batch file, to execute a number of npm command operable program or batch file.

Everything installs okay but when the batch file runs I get the message

'npm' is not recognized as an internal or external command

The commands don't run and so the app won't open.  However, if I leave everything as it is and just rerun the batch file again after the installation, the commands execute and the app works fine.  How can I get the batch file to run properly as part of the installation?

Inno Setup Run Section

[Run]
Filename: "{tmp}\Git-2.15.0-64-bit.exe";  Flags: waituntilterminated
Filename: "{tmp}\rubyinstaller-2.3.3-x64.exe";  Flags: waituntilterminated
Filename: "{tmp}\visualcppbuildtools_full.exe";  Flags: waituntilterminated
Filename: "msiexec.exe"; Parameters: "/i ""{tmp}\mongodb-win32-x86_64-2008plus-ssl-3.4.10-signed.msi"; WorkingDir: {tmp}; Flags: waituntilterminated
Filename: "msiexec.exe"; Parameters: "/i ""{tmp}\node-v6.11.0-x64.msi"; WorkingDir: {tmp}; Flags: waituntilterminated
Filename: "{tmp}\setup.bat";
Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: shellexec postinstall skipifsilent

Batch File

cd C:/Users/%USERNAME%/Documents/myApp/api/
call npm install -g bower
call npm install -g grunt
call npm install -g grunt-cli
call npm config set msvs_version 2015 -global
call npm install bcrypt -save
call npm install
cd ../admin/
call npm install -g bower
call npm install -g grunt
call npm install -g grunt-cli
echo 1 | call gem install compass
call bower install
call npm install


问:
CSS Animation isn't hidden at beginning
I want to have a div, with a word inside.  This word should appear with animation when the div is hovered over. This is animating and behaving the way I want, EXCEPT... the word "hello" is visible when the page loads.  I want it to be hidden, and then animate into view.  What do I need to fix?

#test{
  border: 1px solid #000;
}
#hello {
    animation-name: hello;
    animation-duration: 0.5s;
    animation-fill-mode: backwards;
    animation-play-state: paused;
}
#hello:hover {
   animation-fill-mode: forwards;
    animation-play-state: running;
    visibility: visible;
}

@keyframes hello {
    0%      {visibility:(hidden);transform:scale(0.5); opacity:(0.0);}
    1%      {visibility:(visible);}
    50%     {transform:scale(1.2); opacity:(0.5);}
    100%    {transform:scale(1.0); opacity:(1.0);}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="test">
  <div id="hello">
    Hello!
  </div>
</div></code>```

答:
You need to simply remove () from the values of properties as it make them invalid. Also it's better to change the opacity in the 1% of the animation to be able to see the scale effect.

You may also remove the visiblity property from the CSS as it's useless since you are using opacity

#test {
  border: 1px solid #000;
  background:#fff;
  overflow:hidden; /* added this to avoid the scroll to appear and disappear*/
}

#hello {
  animation-name: hello;
  animation-duration: 0.5s;
  animation-fill-mode: backwards;
  animation-play-state: paused;
}

#test:hover #hello {
  animation-fill-mode: forwards;
  animation-play-state: running;
  /*visibility: visible; can be removed*/
}

@keyframes hello {
  0% {
    /*visibility: hidden; can be removed*/
    transform: scale(0.5);
    opacity: 0;
  }
  1% {
    /*visibility: visible; can be removed*/
    opacity:0.3;
  }
  50% {
    transform: scale(1.2);
    opacity:0.5;
  }
  100% {
    transform: scale(1.0);
    opacity:1.0;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="test">
  <div id="hello">
    Hello!
  </div>
</div></code>```

Title: CSS Animation isn't hidden at beginning

Body:
I want to have a div, with a word inside.  This word should appear with animation when the div is hovered over. This is animating and behaving the way I want, EXCEPT... the word "hello" is visible when the page loads.  I want it to be hidden, and then animate into view.  What do I need to fix?

#test{
  border: 1px solid #000;
}
#hello {
    animation-name: hello;
    animation-duration: 0.5s;
    animation-fill-mode: backwards;
    animation-play-state: paused;
}
#hello:hover {
   animation-fill-mode: forwards;
    animation-play-state: running;
    visibility: visible;
}

@keyframes hello {
    0%      {visibility:(hidden);transform:scale(0.5); opacity:(0.0);}
    1%      {visibility:(visible);}
    50%     {transform:scale(1.2); opacity:(0.5);}
    100%    {transform:scale(1.0); opacity:(1.0);}
}

    Hello!

Body:
You need to simply remove () from the values of properties as it make them invalid. Also it's better to change the opacity in the 1% of the animation to be able to see the scale effect.

You may also remove the visiblity property from the CSS as it's useless since you are using opacity

#test {
  border: 1px solid #000;
  background:#fff;
  overflow:hidden; /* added this to avoid the scroll to appear and disappear*/
}

#hello {
  animation-name: hello;
  animation-duration: 0.5s;
  animation-fill-mode: backwards;
  animation-play-state: paused;
}

#test:hover #hello {
  animation-fill-mode: forwards;
  animation-play-state: running;
  /*visibility: visible; can be removed*/
}

@keyframes hello {
  0% {
    /*visibility: hidden; can be removed*/
    transform: scale(0.5);
    opacity: 0;
  }
  1% {
    /*visibility: visible; can be removed*/
    opacity:0.3;
  }
  50% {
    transform: scale(1.2);
    opacity:0.5;
  }
  100% {
    transform: scale(1.0);
    opacity:1.0;
  }
}

<div id="test">
  <div id="hello">
    Hello!
  </div>
</div>


问:
How to get JDK 8 default XML transformer to emit "'" for apostrophes
I have a third-party webservice that can only parse XML requests where apostrophes in attributes are encoded as '. It rejects raw apostrophes like '. This webservice does not care for your argument that the XML standards allow apostophes in attribute values that are delimited by double-quotes. It wants '.

I want to use the standard Java XML transformer to generate the XML for these requests. It does not encode ' as '. How can I make it do that?

Sample program:

```<code>class test {
    public static void main(String args[]) throws Exception {
        final org.w3c.dom.Document doc = javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        final org.w3c.dom.Element tag = doc.createElement("fedora");
        tag.setAttribute("tip", "m'lady");
        doc.appendChild(tag);
        doc.setXmlStandalone(true);
        final javax.xml.transform.Transformer t = javax.xml.transform.TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(javax.xml.transform.OutputKeys.VERSION, "1.0");
        t.setOutputProperty(javax.xml.transform.OutputKeys.ENCODING, "UTF-8");
        t.setOutputProperty(javax.xml.transform.OutputKeys.STANDALONE, "yes");
        t.transform(new javax.xml.transform.dom.DOMSource(doc),
                    new javax.xml.transform.stream.StreamResult(new java.io.PrintWriter(System.out)));
    }
}
</code>```

What it emits: <?xml version="1.0" encoding="UTF-8" standalone="no"?><fedora tip="m'lady"/>

What I want it to emit: <?xml version="1.0" encoding="UTF-8" standalone="no"?><fedora tip="m'lady"/>

答:
XSLT 2.0 Solution

In XSLT 2.0+, you can use character maps:

```<code><xsl:character-map name="aposCharMap">
  <xsl:output-character character="'" string="&apos;"/>
</xsl:character-map>
</code>```

This will substitute ' for ' during serialization.

Body:
I have a third-party webservice that can only parse XML requests where apostrophes in attributes are encoded as '. It rejects raw apostrophes like '. This webservice does not care for your argument that the XML standards allow apostophes in attribute values that are delimited by double-quotes. It wants '.

I want to use the standard Java XML transformer to generate the XML for these requests. It does not encode ' as '. How can I make it do that?

Sample program:

class test {
    public static void main(String args[]) throws Exception {
        final org.w3c.dom.Document doc = javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        final org.w3c.dom.Element tag = doc.createElement("fedora");
        tag.setAttribute("tip", "m'lady");
        doc.appendChild(tag);
        doc.setXmlStandalone(true);
        final javax.xml.transform.Transformer t = javax.xml.transform.TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(javax.xml.transform.OutputKeys.VERSION, "1.0");
        t.setOutputProperty(javax.xml.transform.OutputKeys.ENCODING, "UTF-8");
        t.setOutputProperty(javax.xml.transform.OutputKeys.STANDALONE, "yes");
        t.transform(new javax.xml.transform.dom.DOMSource(doc),
                    new javax.xml.transform.stream.StreamResult(new java.io.PrintWriter(System.out)));
    }
}

What it emits: <?xml version="1.0" encoding="UTF-8" standalone="no"?><fedora tip="m'lady"/>

What I want it to emit: <?xml version="1.0" encoding="UTF-8" standalone="no"?><fedora tip="m'lady"/>

Body:
XSLT 2.0 Solution

In XSLT 2.0+, you can use character maps:

<xsl:character-map name="aposCharMap">
  <xsl:output-character character="'" string="&amp;apos;"/>
</xsl:character-map>

This will substitute &apos; for ' during serialization.


问:
Bulma icon not showing up?
I am trying to use bulma icons following the docs here, but the icon doesn't show up:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.1/css/bulma.min.css">

  ICON

```

Also see the fiddle here, what could be the problem?

答:
You also need to include the bulma.min.css file, not just the .map.

Edit

Per the Bulma docs:

If you want to use icons with Bulma, don't forget to include Font Awesome:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

Update 3/19/2019

As @Akshay has pointed out below, the documentation has changed and the proper way to include Font Awesome is now

```<code><script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>
</code>```

Title: Bulma icon not showing up?

Body:
I am trying to use bulma icons following the docs here, but the icon doesn't show up:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.1/css/bulma.min.css">

  ICON

Also see the fiddle here, what could be the problem?

Body:
You also need to include the bulma.min.css file, not just the .map.

Edit

Per the Bulma docs:

If you want to use icons with Bulma, don't forget to include Font Awesome:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

Update 3/19/2019

As @Akshay has pointed out below, the documentation has changed and the proper way to include Font Awesome is now

<script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>


问:
MS Access Update Query with Date columns
I am using a staging table in ms access to catch an excel report with daily labor information. Its just a bulk upload form and a button with a click event. With every upload the staging table gets deleted and recreated. The first 3 headers are the same for every report. The date fields store hours worked for the day, but since this is a weekly report the fields for the dates change.

ChargeNumber,p_code,e_ID,date1,date2,date3,date4,date5

I've managed to write an update query in ms access to update a labor table from a staging table, but I have to manually change the columns for the dates. I've considered capturing the header information into an array and parsing out the information, but my coding strengths are limited to TSQL and my TSQL skills are still improving....I am sure there is a better way to dynamically handle this....I am just not seeing it.

INSERT INTO Labor2 ( ChargeNumber, e_ID, dateworked, p_Code, hoursworked )
SELECT I.ChargeNumber, I.e_ID, "2017-11-07" AS dateworked, I.p_code, I.[2017-11-07]
FROM tbl_Import AS I
WHERE (((I.[2017-11-07]) Is Not Null));

I am not looking for anyone to answer my question with a solution. I am looking for a path to traverse so I can figure out my own problem. Any help will be greatly appreciated. Hope this makes sense.

答:
If you always have exactly five columns, you can use

```<code>INSERT INTO Labor2 ( ChargeNumber, e_ID, dateworked, p_Code, hoursworked )
select *
from tbl_Import
</code>```

and then filter in the next step instead. A bit dirty, but simple.

Body:
If you always have exactly five columns, you can use

INSERT INTO Labor2 ( ChargeNumber, e_ID, dateworked, p_Code, hoursworked )
select *
from tbl_Import

and then filter in the next step instead. A bit dirty, but simple.


问:
JQUERY $(function() { initialisation
I've been working with JQuery for some time now and I've always used the following to initalise my javascript:

```<code>$(document).ready( function() {
// Initalisation logic
});
</code>```

However, recently I've noticed a lot of examples using the following:

```<code>$(function() {

});
</code>```

Whats the difference?

Thanks

答:
Basically, there isn't one. The $(...) format is a shortcut. See the API docs for jQuery() for details.

I like to use it like this:

```<code>jQuery(function($) {
    // ...all of my jQuery-specific code here...
});
</code>```

...because then if I need to, I can use noConflict if I end up having to mix something into the page that also wants the $ symbol, but I can still use $ in my code (because jQuery passes itself into the callback as the first argument, and as you can see I'm accepting that argument as $ in my callback function — and so that shadows any global $ symbol that another library might be using). The above also has the advantage that I can have symbols global to my code (vars within the anonymous function) that are not actually globals.

Title: JQUERY $(function() { initialisation

Body:
I've been working with JQuery for some time now and I've always used the following to initalise my javascript:

$(document).ready( function() {
// Initalisation logic
});

However, recently I've noticed a lot of examples using the following:

$(function() {

});

Whats the difference?

Thanks

Body:
Basically, there isn't one. The $(...) format is a shortcut. See the API docs for jQuery() for details.

I like to use it like this:

jQuery(function($) {
    // ...all of my jQuery-specific code here...
});

...because then if I need to, I can use noConflict if I end up having to mix something into the page that also wants the $ symbol, but I can still use $ in my code (because jQuery passes itself into the callback as the first argument, and as you can see I'm accepting that argument as $ in my callback function — and so that shadows any global $ symbol that another library might be using). The above also has the advantage that I can have symbols global to my code (vars within the anonymous function) that are not actually globals.


问:
Python cx_freeze Create dirs for included files in build
Is it possible to create dirs(folders) on cx_freeze build output, cause i include(include_files) many databases files and i want these to be in specific folder etc. I can take them easily from my folders.....

```<code>"include_files": ["databases/nations.txt","databases/newafrica.txt",
                    "databases/neweeurope.txt","databases/neweurope.txt","databases/newmeast.txt","graph.py",
                    "databases/newnamerica.txt","databases/plates.txt",
                    "databases/ACN/rigidA.txt","databases/ACN/rigidB.txt",
                    "databases/ACN/rigidC.txt","databases/ACN/rigidD.txt","databases/ACN/flexibleA.txt",
                    "databases/ACN/flexibleB.txt","databases/ACN/flexibleC.txt",
                    "databases/ACN/flexibleD.txt","alternates.xlsx",
</code>```

but this will just copy all of them in exe build dir and its a mess.
Thanks in advance.

答:
There are several ways you can go around solving the problem.

Method 1 - Using include_files

Rather than ask for each individual text file you could just put the file name in the setup script and leave out the individual text files. In your case it would be like this:

```<code>"include_files": ["databases"]
</code>```

This would copy the entire databases folder with everything in it into you build folder.

Absolute file paths work as well.

If you are going to use the installer feature (bdist_msi) this is the method to use.

You can copy sub folders only using "include_files": ["databases/ACN"]

Method 2 - Manually

Ok it's rather un-pythonic but the one way to do it is to copy it manually into the build folder.

Method 3 - Using the os module

Much the same as method two it would copy the folder into your build folder but instead of coping it manually it would use Python.  You also have the option of using additional Python features as well.

Hope I was helpful.

Body:
Is it possible to create dirs(folders) on cx_freeze build output, cause i include(include_files) many databases files and i want these to be in specific folder etc. I can take them easily from my folders.....

"include_files": ["databases/nations.txt","databases/newafrica.txt",
                    "databases/neweeurope.txt","databases/neweurope.txt","databases/newmeast.txt","graph.py",
                    "databases/newnamerica.txt","databases/plates.txt",
                    "databases/ACN/rigidA.txt","databases/ACN/rigidB.txt",
                    "databases/ACN/rigidC.txt","databases/ACN/rigidD.txt","databases/ACN/flexibleA.txt",
                    "databases/ACN/flexibleB.txt","databases/ACN/flexibleC.txt",
                    "databases/ACN/flexibleD.txt","alternates.xlsx",

but this will just copy all of them in exe build dir and its a mess.
Thanks in advance.

Body:
There are several ways you can go around solving the problem.

Method 1 - Using include_files

Rather than ask for each individual text file you could just put the file name in the setup script and leave out the individual text files. In your case it would be like this:

"include_files": ["databases"]

This would copy the entire databases folder with everything in it into you build folder.

Absolute file paths work as well.

If you are going to use the installer feature (bdist_msi) this is the method to use.

You can copy sub folders only using "include_files": ["databases/ACN"]

Method 2 - Manually

Ok it's rather un-pythonic but the one way to do it is to copy it manually into the build folder.

Method 3 - Using the os module

Much the same as method two it would copy the folder into your build folder but instead of coping it manually it would use Python.  You also have the option of using additional Python features as well.

Hope I was helpful.


问:
join and group by not working properly in laravel
I have a blog with 2 table. First posts table with a key category_id and categories table. In a page I want to show all categories with count of their posts. I write this query but it have a problem. It did not show categories with no posts. in other word categories with 0 posts did not appear in the results.

And can you help to write this in eloquent system in laravel

```<code>SELECT categories.* , Count(posts.total) as total
FROM categories
LEFT JOIN
(
    SELECT * , COUNT(*) as total from posts GROUP By posts.id
) as posts
ON posts.category_id = categories.id
</code>```

答:
Try following query:</p>

```<code>SELECT categories.* , IFNULL(Count(posts.id),0) as total
FROM categories
LEFT JOIN
posts
ON posts.category_id = categories.id
Group by categories.id;
</code>```

Body:
I have a blog with 2 table. First posts table with a key category_id and categories table. In a page I want to show all categories with count of their posts. I write this query but it have a problem. It did not show categories with no posts. in other word categories with 0 posts did not appear in the results.

And can you help to write this in eloquent system in laravel

SELECT categories.* , Count(posts.total) as total
FROM categories
LEFT JOIN
(
    SELECT * , COUNT(*) as total from posts GROUP By posts.id
) as posts
ON posts.category_id = categories.id

Body:
Try following query:

SELECT categories.* , IFNULL(Count(posts.id),0) as total
FROM categories
LEFT JOIN
posts
ON posts.category_id = categories.id
Group by categories.id;


问:
Calling a library function. Exceeded maximum stack depth
Seems to me the easier way to call a library function in google sheets is to do this:

```<code>function mylibfunction() {
    Identifier.mylibfunction();
}
</code>```

However, it prompts an error "Exceeded maximum stack depth"

This does not happen when I run my code as a script without calling from the library. Why is this so? Is there some iterative restriction imposed on library functions?

答:
I have used both the Firebase and moment script libraries, the moment call looks like this.

```<code>var moment = Moment.load();
</code>```

And the Firebase call looks like this.

```<code> var firebaseUrl = "https://script-examples.firebaseio.com/";
 var base = FirebaseApp.getDatabaseByUrl(firebaseUrl);
</code>```

Notice the capital letters for each of Moment.load() and FirebaseApp.getDatabaseByUrl() this suggest they are classes available globally from the Library. Similar to DriveApp or SpreadsheetApp.

About your function it is possible you are doing a recursive function call somehow. Perhaps, change the name of the wrapping function.

Body:
Seems to me the easier way to call a library function in google sheets is to do this:

function mylibfunction() {
    Identifier.mylibfunction();
}

However, it prompts an error "Exceeded maximum stack depth"

This does not happen when I run my code as a script without calling from the library. Why is this so? Is there some iterative restriction imposed on library functions?

Body:
I have used both the Firebase and moment script libraries, the moment call looks like this.

var moment = Moment.load();

And the Firebase call looks like this.

 var firebaseUrl = "https://script-examples.firebaseio.com/";
 var base = FirebaseApp.getDatabaseByUrl(firebaseUrl);

Notice the capital letters for each of Moment.load() and FirebaseApp.getDatabaseByUrl() this suggest they are classes available globally from the Library. Similar to DriveApp or SpreadsheetApp.

About your function it is possible you are doing a recursive function call somehow. Perhaps, change the name of the wrapping function.


问:
firebase dynamic link created programmatically in swift doesn't work, no domain
I have configured firebase project with dynamic link, I have domain for DL. But when I creating shroten link programmatically then I get an error. This error I receive for target test and debug of project, but same code is using for release app and for it dynamic link works. Each project target have own firebase project and domain. I don't know why works only release version ?</p>

```<code>Your project does not own Dynamic Links domain
</code>```

答:
```<code>curl -X POST --dump-header - -H "X-Ios-Bundle-Identifier: com.debugbundlefromanotherfirebaseproject.debug" -H "Accept: application/json" -H "Content-Type: application/json" -d "{\"longDynamicLink\":\"https:\/\/RELEASE_DOMAIN.app.goo.gl\/?link=https%3A%2F%2Fwww%2Egoogle%2Ecom%3Fq%3Djump\",\"suffix\":{\"option\":\"UNGUESSABLE\"}}" "https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=API_KEY_RELEASE"
{
  "shortLink": "https://RELEASE_DOMAIN.app.goo.gl/EDKuPWwaXrFzfs4S2",
  "warning": [
    {
      "warningCode": "UNRECOGNIZED_PARAM",
      "warningMessage": "Android app 'android.com.releaseandroidid' lacks SHA256. AppLinks is not enabled for the app. [https://firebase.google.com/docs/dynamic-links/debug#android-sha256-absent]"
    },
    {
      "warningCode": "UNRECOGNIZED_PARAM",
      "warningMessage": "Android app 'android.com.debugeandroididfromanotherfirebaseproject' lacks SHA256. AppLinks is not enabled for the app. [https://firebase.google.com/docs/dynamic-links/debug#android-sha256-absent]"
    }
  ],
  "previewLink": "https://RELEASE_DOMAIN.app.goo.gl/EDKuPWwaXrFzfs4S2?d=1"
}
</code>```

I think that could be problem in Firebase. Because for release project domain POST work although request have mistake bundle id, additional in result warnings contain one warning with android ID from another Firebase project. I am waiting for response from firebase. Example above.

Body:
I have configured firebase project with dynamic link, I have domain for DL. But when I creating shroten link programmatically then I get an error. This error I receive for target test and debug of project, but same code is using for release app and for it dynamic link works. Each project target have own firebase project and domain. I don't know why works only release version ?

Your project does not own Dynamic Links domain

Body:
curl -X POST --dump-header - -H "X-Ios-Bundle-Identifier: com.debugbundlefromanotherfirebaseproject.debug" -H "Accept: application/json" -H "Content-Type: application/json" -d "{\"longDynamicLink\":\"https:\/\/RELEASE_DOMAIN.app.goo.gl\/?link=https%3A%2F%2Fwww%2Egoogle%2Ecom%3Fq%3Djump\",\"suffix\":{\"option\":\"UNGUESSABLE\"}}" "https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=API_KEY_RELEASE"
{
  "shortLink": "https://RELEASE_DOMAIN.app.goo.gl/EDKuPWwaXrFzfs4S2",
  "warning": [
    {
      "warningCode": "UNRECOGNIZED_PARAM",
      "warningMessage": "Android app 'android.com.releaseandroidid' lacks SHA256. AppLinks is not enabled for the app. [https://firebase.google.com/docs/dynamic-links/debug#android-sha256-absent]"
    },
    {
      "warningCode": "UNRECOGNIZED_PARAM",
      "warningMessage": "Android app 'android.com.debugeandroididfromanotherfirebaseproject' lacks SHA256. AppLinks is not enabled for the app. [https://firebase.google.com/docs/dynamic-links/debug#android-sha256-absent]"
    }
  ],
  "previewLink": "https://RELEASE_DOMAIN.app.goo.gl/EDKuPWwaXrFzfs4S2?d=1"
}

I think that could be problem in Firebase. Because for release project domain POST work although request have mistake bundle id, additional in result warnings contain one warning with android ID from another Firebase project. I am waiting for response from firebase. Example above.


问:
MongoDB toArray performance
I'm trying to build a category tree from a term collection in Mongo/Node, but first I select all tree elements using $in:

```<code>console.time('termsCol.find');
var terms = await termsCol.find({term_id: {'$in': flatTree}});
console.timeEnd('termsCol.find');

console.time('termsCol.toArray');
terms = await terms.toArray();
console.timeEnd('termsCol.toArray');
</code>```

This performs:

```<code>termsCol.find: 0.162ms
termsCol.toArray: 30.910ms
</code>```

I've read posts about toArray performance on SO, but would like to know if anything has changed, because this takes most of my time during page request.

I have an index on that collection and it returns 300 terms within ~0.15ms, but that doesn't help me when I have to wait another 30ms to use that data further down in js.

If there's no way to improve this toArray business, I'll probably create a cache collection and store the complete term trees there (hope they fit 16MB).

答:
reference http://mongodb.github.io/node-mongodb-native/2.0/tutorials/streams/
you can stream results one by one and can make array of ids.

```<code>var MongoClient = require('mongodb').MongoClient
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
    console.log("Connected correctly to server");
 var col = db.collection('terms');
    var ids = []
    var findCursor = col.find({term_id: {'$in': flatTree}});
    findCursor.on("data", function(data) {
       ids.push(data._id)
    });
    findCursor.on("end", function(data) {
      // let's finish
      console.log(ids)
    });
});
</code>```

i didn't check time but sure it should less then (termsCol.find: 0.162ms +
termsCol.toArray: 30.910ms)

Title: MongoDB toArray performance

Body:
I'm trying to build a category tree from a term collection in Mongo/Node, but first I select all tree elements using $in:

console.time('termsCol.find');
var terms = await termsCol.find({term_id: {'$in': flatTree}});
console.timeEnd('termsCol.find');

console.time('termsCol.toArray');
terms = await terms.toArray();
console.timeEnd('termsCol.toArray');

This performs:

termsCol.find: 0.162ms
termsCol.toArray: 30.910ms

I've read posts about toArray performance on SO, but would like to know if anything has changed, because this takes most of my time during page request.

I have an index on that collection and it returns 300 terms within ~0.15ms, but that doesn't help me when I have to wait another 30ms to use that data further down in js.

If there's no way to improve this toArray business, I'll probably create a cache collection and store the complete term trees there (hope they fit 16MB).

Body:
reference http://mongodb.github.io/node-mongodb-native/2.0/tutorials/streams/
you can stream results one by one and can make array of ids.

var MongoClient = require('mongodb').MongoClient
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
    console.log("Connected correctly to server");
 var col = db.collection('terms');
    var ids = []
    var findCursor = col.find({term_id: {'$in': flatTree}});
    findCursor.on("data", function(data) {
       ids.push(data._id)
    });
    findCursor.on("end", function(data) {
      // let's finish
      console.log(ids)
    });
});

i didn't check time but sure it should less then (termsCol.find: 0.162ms +
termsCol.toArray: 30.910ms)