问:
How to convert RDD[GenericRecord] to dataframe in scala?
I get tweets from kafka topic with Avro (serializer and deserializer).
Then i create a spark consumer which extracts tweets in Dstream of RDD[GenericRecord].
Now i want to convert each rdd to a dataframe to analyse these tweets via SQL.
Any solution to convert RDD[GenericRecord] to dataframe please ?</p>

答:
I spent some time trying to make this work (specially how deserialize the data properly but it looks like you already cover this)  ... UPDATED

```<code>  //Define function to convert from GenericRecord to Row
  def genericRecordToRow(record: GenericRecord, sqlType : SchemaConverters.SchemaType): Row = {
    val objectArray = new Array[Any](record.asInstanceOf[GenericRecord].getSchema.getFields.size)
    import scala.collection.JavaConversions._
    for (field <- record.getSchema.getFields) {
      objectArray(field.pos) = record.get(field.pos)
    }

    new GenericRowWithSchema(objectArray, sqlType.dataType.asInstanceOf[StructType])
  }

//Inside your stream foreachRDD
val yourGenericRecordRDD = ...
val schema = new Schema.Parser().parse(...) // your schema
val sqlType = SchemaConverters.toSqlType(new Schema.Parser().parse(strSchema))

var rowRDD = yourGeneircRecordRDD.map(record => genericRecordToRow(record, sqlType))
val df = sqlContext.createDataFrame(rowRDD , sqlType.dataType.asInstanceOf[StructType])
</code>```

As you see, I am using a SchemaConverter to get the dataframe structure from the schema that you used to deserialize (this could be more painful with schema registry). For this you need the following dependency

```<code>    <dependency>
        <groupId>com.databricks</groupId>
        <artifactId>spark-avro_2.11</artifactId>
        <version>3.2.0</version>
    </dependency>
</code>```

you will need to change your spark version depending on yours.

UPDATE: the code above only works for flat avro schemas.

For nested structures I used something different. You can copy the  class SchemaConverters, it has to be inside of com.databricks.spark.avro (it uses some protected classes from the databricks package) or you can try to use the spark-bigquery dependency.  The class will not be accessible by default, so you will need to create a class inside a package com.databricks.spark.avro to access the factory method.

```<code>package com.databricks.spark.avro

import com.databricks.spark.avro.SchemaConverters.createConverterToSQL
import org.apache.avro.Schema
import org.apache.spark.sql.types.StructType

class SchemaConverterUtils {

  def converterSql(schema : Schema, sqlType : StructType) = {
    createConverterToSQL(schema, sqlType)
  }

}
</code>```

After that you should be able to convert the data like

```<code>val schema = .. // your schema
val sqlType = SchemaConverters.toSqlType(schema).dataType.asInstanceOf[StructType]
....
//inside foreach RDD
var genericRecordRDD = deserializeAvroData(rdd)
///
var converter = SchemaConverterUtils.converterSql(schema, sqlType)
...
val rowRdd = genericRecordRDD.flatMap(record => {
        Try(converter(record).asInstanceOf[Row]).toOption
      })
//To DataFrame
 val df = sqlContext.createDataFrame(rowRdd, sqlType)
</code>```

Body:
I spent some time trying to make this work (specially how deserialize the data properly but it looks like you already cover this)  ... UPDATED

  //Define function to convert from GenericRecord to Row
  def genericRecordToRow(record: GenericRecord, sqlType : SchemaConverters.SchemaType): Row = {
    val objectArray = new Array[Any](record.asInstanceOf[GenericRecord].getSchema.getFields.size)
    import scala.collection.JavaConversions._
    for (field <- record.getSchema.getFields) {
      objectArray(field.pos) = record.get(field.pos)
    }

    new GenericRowWithSchema(objectArray, sqlType.dataType.asInstanceOf[StructType])
  }

//Inside your stream foreachRDD
val yourGenericRecordRDD = ...
val schema = new Schema.Parser().parse(...) // your schema
val sqlType = SchemaConverters.toSqlType(new Schema.Parser().parse(strSchema))

var rowRDD = yourGeneircRecordRDD.map(record => genericRecordToRow(record, sqlType))
val df = sqlContext.createDataFrame(rowRDD , sqlType.dataType.asInstanceOf[StructType])

As you see, I am using a SchemaConverter to get the dataframe structure from the schema that you used to deserialize (this could be more painful with schema registry). For this you need the following dependency

    <dependency>
        <groupId>com.databricks</groupId>
        <artifactId>spark-avro_2.11</artifactId>
        <version>3.2.0</version>
    </dependency>

you will need to change your spark version depending on yours.

UPDATE: the code above only works for flat avro schemas.

For nested structures I used something different. You can copy the  class SchemaConverters, it has to be inside of com.databricks.spark.avro (it uses some protected classes from the databricks package) or you can try to use the spark-bigquery dependency.  The class will not be accessible by default, so you will need to create a class inside a package com.databricks.spark.avro to access the factory method.

package com.databricks.spark.avro

import com.databricks.spark.avro.SchemaConverters.createConverterToSQL
import org.apache.avro.Schema
import org.apache.spark.sql.types.StructType

class SchemaConverterUtils {

  def converterSql(schema : Schema, sqlType : StructType) = {
    createConverterToSQL(schema, sqlType)
  }

}

After that you should be able to convert the data like

val schema = .. // your schema
val sqlType = SchemaConverters.toSqlType(schema).dataType.asInstanceOf[StructType]
....
//inside foreach RDD
var genericRecordRDD = deserializeAvroData(rdd)
///
var converter = SchemaConverterUtils.converterSql(schema, sqlType)
...
val rowRdd = genericRecordRDD.flatMap(record => {
        Try(converter(record).asInstanceOf[Row]).toOption
      })
//To DataFrame
 val df = sqlContext.createDataFrame(rowRdd, sqlType)


来源: stackexchange

问:
SoftLayer API: how to create a ticket
I am trying to create a SoftLayer ticket on behalf of customers, want to set assignedUserId and assignedEmployeeId, make the first update by employee id.

I tried to use client['Ticket'].createStandardTicket, but  assignedEmployeeId was not set properly. Do you know how to get this implemented? Thank you so much in advance.

答:
Unfortunately you won’t be able to  assign an employee id since this parameter isn’t available in: http://sldn.softlayer.com/reference/datatypes/SoftLayer_ticket http://sldn.softlayer.com/reference/services/SoftLayer_Ticket/createStandardTicket
http://sldn.softlayer.com/reference/services/SoftLayer_Ticket/createAdministrativeTicket

This kind of tasks are managed by employees and it is an internal subject.

ContentLicense: CC BY-SA 3.0

Title: SoftLayer API: how to create a ticket


问:
Converting Mathematica to Python - arccos and sqrt
I am attempting to convert the following Mathematica expression into Python. Somehow, Mathematica can easily deal with negative in the square root, and the argument of arcsec being outside of the domain.

Can someone help me make a Python expression that works? Or at least tell me how Mathematica (which I'm less familiar with) handles these issues?

Mathematica expression (to plot over 0.1-100)

```<code>LogLogPlot[(p0 rs^2 (Sqrt[(R - rs) (R + rs)] (-2 R rs + \[Pi] (R - rs) (R + rs))
- 2 (R^3 - 2 R rs^2) ArcSec[R/rs]))/(R ((R - rs) (R + rs))^(3/2)) /. {rs -> 1, p0 -> 10},
{R, 0.1, 100}]
</code>```

Python expression

```<code>rho0 * rs ** 2 * (np.pi * (R-rs)*(R+rs) - 2 *R *rs) /(R *(R-rs) *(R+rs)) - rho0 * rs **2
 * (2 *np.arccos(rs/R))*(R **3 - 2 *R *rs) / (R *((R-rs) *(R+rs)) **(3/2))
</code>```

When R < rs (which is of course the region I am interested in), I get undefined values for arccos, and nonsense values for the square root.

Any and all tips would be helpful!

答:
here is the mathematica formulation that does not use complex numbers.

```<code>f[R_, rs_, p0_] :=
   Which[R >= rs,
           (p0 rs^2 (Sqrt[(R - rs) (R +rs)]
           (-2 R rs + Pi (R - rs) (R + rs)) -
           2 (R^3 - 2 R rs^2) ArcSec[R/rs]))/
           R ((R - rs) (R + rs))^(3/2)),
         R < rs,
           (p0 rs^2 ( Sqrt[(rs - R ) (R + rs)]
           (-2 R rs + Pi (R - rs) (R + rs)) -
           2 (R^3 - 2 R rs^2) Log[rs/R + Sqrt[(rs/R)^2 - 1]]))/
           (-R ((rs - R) (R + rs))^(3/2) )]

  LogLogPlot[f[R, 1, 10], {R, 0.1, 100}]
</code>```

aside, both expressions blow up for R==rs exactly, however the limit exists:

```<code>Limit[(p0 rs^2 (Sqrt[(R - rs) (R +  rs)] (-2 R rs + \[Pi] (R - rs) (R + rs))
  2 (R^3 - 2 R rs^2)   ArcSec[R/rs]))/  (R ((R - rs) (R + rs))^(3/2)) ,
   R -> rs,  Assumptions -> {p0 > 0, R > 0, rs > 0}]
</code>```

p0 (-8 + 3 Pi) rs /3

```<code>%/. {rs->1,p0->10}
</code>```

4.74926

you can add that case to the conditional if needed.

Body:
I am attempting to convert the following Mathematica expression into Python. Somehow, Mathematica can easily deal with negative in the square root, and the argument of arcsec being outside of the domain.

Can someone help me make a Python expression that works? Or at least tell me how Mathematica (which I'm less familiar with) handles these issues?

Mathematica expression (to plot over 0.1-100)

LogLogPlot[(p0 rs^2 (Sqrt[(R - rs) (R + rs)] (-2 R rs + \[Pi] (R - rs) (R + rs))
- 2 (R^3 - 2 R rs^2) ArcSec[R/rs]))/(R ((R - rs) (R + rs))^(3/2)) /. {rs -> 1, p0 -> 10},
{R, 0.1, 100}]

Python expression

rho0 * rs ** 2 * (np.pi * (R-rs)*(R+rs) - 2 *R *rs) /(R *(R-rs) *(R+rs)) - rho0 * rs **2
 * (2 *np.arccos(rs/R))*(R **3 - 2 *R *rs) / (R *((R-rs) *(R+rs)) **(3/2))

When R < rs (which is of course the region I am interested in), I get undefined values for arccos, and nonsense values for the square root.

Any and all tips would be helpful!

Body:
here is the mathematica formulation that does not use complex numbers.

f[R_, rs_, p0_] :=
   Which[R >= rs,
           (p0 rs^2 (Sqrt[(R - rs) (R +rs)]
           (-2 R rs + Pi (R - rs) (R + rs)) -
           2 (R^3 - 2 R rs^2) ArcSec[R/rs]))/
           R ((R - rs) (R + rs))^(3/2)),
         R < rs,
           (p0 rs^2 ( Sqrt[(rs - R ) (R + rs)]
           (-2 R rs + Pi (R - rs) (R + rs)) -
           2 (R^3 - 2 R rs^2) Log[rs/R + Sqrt[(rs/R)^2 - 1]]))/
           (-R ((rs - R) (R + rs))^(3/2) )]

  LogLogPlot[f[R, 1, 10], {R, 0.1, 100}]

aside, both expressions blow up for R==rs exactly, however the limit exists:

Limit[(p0 rs^2 (Sqrt[(R - rs) (R +  rs)] (-2 R rs + \[Pi] (R - rs) (R + rs))
  2 (R^3 - 2 R rs^2)   ArcSec[R/rs]))/  (R ((R - rs) (R + rs))^(3/2)) ,
   R -> rs,  Assumptions -> {p0 > 0, R > 0, rs > 0}]

p0 (-8 + 3 Pi) rs /3

%/. {rs->1,p0->10}

4.74926

you can add that case to the conditional if needed.


问:
'read binary' on files vs. 'join' on strings in Python 2.7
I'm re-writing an older script which generates a lot of temporary files for saving and exchanging information/data between functions. I want to keep them  as variables, to avoid the overhead of generating files.

My problem: I encountered a function in which two files are merged on a binary level using this code:

```<code>with open(first_file, "ab") as file1, open(second_file, "rb") as file2:
        file1.write(file2.read())
</code>```

I would like to do the same, using strings and the '.join' function like this:

```<code>first_file = ''.join([first_file, second_file])
</code>```

My question: is the .join function equivalent to 'read binary'? Or does the 'read binary' mode even apply to .join?

The data I'm working on is binary, so the simple 'read' command would potentially alter the contents.

So far I found this info in the official Python documentation:

Python on Windows makes a distinction between text and binary files;
  the end-of-line characters in text files are automatically altered
  slightly when data is read or written. This behind-the-scenes
  modification to file data is fine for ASCII text files, but it’ll
  corrupt binary data like that in JPEG or EXE files.

答:
Making a small test:
a.txt contains 'Hello', 'b.txt' contains 'World'.

with open('a.txt', "ab") as file1, open('b.txt', "rb") as file2:
  file1.write(file2.read())
```

<p>Now <code>a.txt</code> contains <code>'HelloWorld'</code>.</p>

<p>Checking with the other snippet, after changing back <code>a.txt</code> to "Hello":</p>

<pre class="lang-python prettyprint-override"><code>with open('a.txt', "rb") as file1, open('b.txt', "rb") as file2:
  first_file = file1.read()
  second_file = file2.read()

first_file = b''.join([first_file, second_file])
with open('a.txt', 'wb') as fp:
  fp.write(first_file)
</code>```

Now the content of a.txt is again 'HelloWorld', so the two methods are equivalent (with respect to the result at least).
Obviously, though, the first method is more compact.

Body:
I'm re-writing an older script which generates a lot of temporary files for saving and exchanging information/data between functions. I want to keep them  as variables, to avoid the overhead of generating files.

My problem: I encountered a function in which two files are merged on a binary level using this code:

with open(first_file, "ab") as file1, open(second_file, "rb") as file2:
        file1.write(file2.read())

I would like to do the same, using strings and the '.join' function like this:

first_file = ''.join([first_file, second_file])

My question: is the .join function equivalent to 'read binary'? Or does the 'read binary' mode even apply to .join?

The data I'm working on is binary, so the simple 'read' command would potentially alter the contents.

So far I found this info in the official Python documentation:

Python on Windows makes a distinction between text and binary files;
  the end-of-line characters in text files are automatically altered
  slightly when data is read or written. This behind-the-scenes
  modification to file data is fine for ASCII text files, but it’ll
  corrupt binary data like that in JPEG or EXE files.

Body:
Making a small test:
a.txt contains 'Hello', 'b.txt' contains 'World'.

with open('a.txt', "ab") as file1, open('b.txt', "rb") as file2:
  file1.write(file2.read())

Now a.txt contains 'HelloWorld'.

Checking with the other snippet, after changing back a.txt to "Hello":

with open('a.txt', "rb") as file1, open('b.txt', "rb") as file2:
  first_file = file1.read()
  second_file = file2.read()

first_file = b''.join([first_file, second_file])
with open('a.txt', 'wb') as fp:
  fp.write(first_file)

Now the content of a.txt is again 'HelloWorld', so the two methods are equivalent (with respect to the result at least).
Obviously, though, the first method is more compact.


问:
Object in function is undefined js
I am trying to find out whether an object of my Object-Array CoilArray contains a certain value.

For this I am using the function hasValue

I want to be able to filter on two values and give back a filtered array, as you can see in the function filterArray

I have a problem in function hasValue.

The error message I am getting says:

obj is undefined

obj is obviously supposed to be the object that I am giving to the function.

Why is it undefined?

How can I define it?

hasValue itself seems to be working though

```<code>var CoilArray = [{
  id: "First Coil",
  systemId: ["System A", "System C"],
  fieldStr: ["Str A", "Str B"],
}, {
  id: "Second Coil",
  systemId: "System B",
  fieldStr: ["Str B", "Str C"],
}, {
  id: "Third Coil",
  systemId: "System C",
  fieldStr: "Str C",
}, ]

function hasValue(obj, key, value) {

  if (obj[key].indexOf(value) > -1) {
    return true;
  }
}

function filterArray(carray) {
  var arr = new Array();
  for (var i = 0; i <= carray.length; i++) {

    if (hasValue(carray[i], "systemId", "System A") &&
      hasValue(carray[i], "fieldStr", "Str B")) {

      arr.push(carray[i].id);
      console.log(carray[i].id);
    }
  }
  return arr;
}

hasValue(CoilArray[0], "fieldStr", "Str A");

filterArray(CoilArray);
</code>```

答:
Well you can trim all that down to this. And the check to see if the systemId is an array I referenced this answer

```<code>var filteredArray = CoilArray.filter(function (obj) {
  let isSystemA = false;
  let isStrB = false;

  // If Array then check if Array has value
  if (obj.systemId.constructor == Array) {
      isSystemA = obj.systemId.includes("System A") && isStrB;
  } else {
      isSystemA = obj.systemId === "System A";
  }

  if (obj.fieldStr.constructor == Array) {
      isStrB = obj.fieldStr.includes("Str B") && isStrB;
  } else {
      isStrB = obj.fieldStr === "Str B";
  }

  return isSystemA && isStrB;
});
</code>```

This uses the filter function

ContentLicense: CC BY-SA 4.0

Title: Object in function is undefined js

Body:
I am trying to find out whether an object of my Object-Array CoilArray contains a certain value.

For this I am using the function hasValue

I want to be able to filter on two values and give back a filtered array, as you can see in the function filterArray

I have a problem in function hasValue.

The error message I am getting says:

obj is undefined

obj is obviously supposed to be the object that I am giving to the function.

Why is it undefined?

How can I define it?

hasValue itself seems to be working though

var CoilArray = [{
  id: "First Coil",
  systemId: ["System A", "System C"],
  fieldStr: ["Str A", "Str B"],
}, {
  id: "Second Coil",
  systemId: "System B",
  fieldStr: ["Str B", "Str C"],
}, {
  id: "Third Coil",
  systemId: "System C",
  fieldStr: "Str C",
}, ]

function hasValue(obj, key, value) {

  if (obj[key].indexOf(value) > -1) {
    return true;
  }
}

function filterArray(carray) {
  var arr = new Array();
  for (var i = 0; i <= carray.length; i++) {

    if (hasValue(carray[i], "systemId", "System A") &&
      hasValue(carray[i], "fieldStr", "Str B")) {

      arr.push(carray[i].id);
      console.log(carray[i].id);
    }
  }
  return arr;
}

hasValue(CoilArray[0], "fieldStr", "Str A");

filterArray(CoilArray);

Body:
Well you can trim all that down to this. And the check to see if the systemId is an array I referenced this answer

var filteredArray = CoilArray.filter(function (obj) {
  let isSystemA = false;
  let isStrB = false;

  // If Array then check if Array has value
  if (obj.systemId.constructor == Array) {
      isSystemA = obj.systemId.includes("System A") && isStrB;
  } else {
      isSystemA = obj.systemId === "System A";
  }

  if (obj.fieldStr.constructor == Array) {
      isStrB = obj.fieldStr.includes("Str B") && isStrB;
  } else {
      isStrB = obj.fieldStr === "Str B";
  }

  return isSystemA && isStrB;
});

This uses the filter function


问:
bash : how to wait some time to avoid simultaneous run of a script?
My problem :

Each night, my crontab launches several nightly tests on a supercomputer working with PBS under CentOS 6.5. When launched, the jobs wait in the queue. When the scheduler allow to run, my jobs start. It is quite common than the scheduler launch all the jobs exaclty at the same time (even if my crontab lauched them at separated moments).

I can't modify the main part of the job (but I can add things before). Each job starts with an update of a common SVN repository. But, when the jobs start simultaneously, I have an error due to concurrent updates on the same repository. I want to avoid that.

What I expect :

When launched by the scheduler, the job could wait some seconds before starting. A solution could be wait a random time before starting, but the risk to have the same random time grow fast with the number of tests I perform in parallel. If I reduce this risk by choosing a big random number, I have to wait too long (locking unused resources on the supercomputer).

I suppose it's possible to store the information of "I will launch now, others have to wait for 1 minute" for each job, in a multi-thread-safe manner, but I don't know how. What I imagine is a kind of mutex but inducing only a delay and not a lock waiting the end.

A solution without MPI is prefered.

Of course, I'm open to other solutions. Any help is welcome.

答:
Call your script from a wrapper that attempts to obtain an exclusive lock on a lock file first. For example

```<code>{
    flock -s 200
    # your script/code here
} 200> /var/lock/myscript
</code>```

The name of the lock file doesn't really matter, as long as you have write permission to open it. When this wrapper runs, it will first attempt to get an exclusive lock on /var/lock/myscript. If another script already has the lock, it will block until the lock becomes available.

Note that there are no arbitrary wait times; each script will run as soon as possible, in the order in which they first attempt to obtain the lock. This means you can also start the jobs simultaneously; the operating system will manage the access to the lock and the ordering.

Body:
Call your script from a wrapper that attempts to obtain an exclusive lock on a lock file first. For example

{
    flock -s 200
    # your script/code here
} 200> /var/lock/myscript

The name of the lock file doesn't really matter, as long as you have write permission to open it. When this wrapper runs, it will first attempt to get an exclusive lock on /var/lock/myscript. If another script already has the lock, it will block until the lock becomes available.

Note that there are no arbitrary wait times; each script will run as soon as possible, in the order in which they first attempt to obtain the lock. This means you can also start the jobs simultaneously; the operating system will manage the access to the lock and the ordering.


问:
c++ C2509 in definition of instructor using try: - catch
In definition

```<code>A::A()
try: B()
{}
catch(Exception e) {}
</code>```

In this code, I have C2509 error.
When I try to go to definition(F12) in header file or (Ctrl+F12) in definition it doesn't work.

I tried

```<code>A::A()
{
 try
 { B();}
 catch(Exception e) {}
}
</code>```

but this is impossible because in class B there is a pure virtual function.

I'm confused with the difference between

```<code>try: {}
catch
</code>```

and

```<code>try{}
catch
</code>```

答:
I'm now assuming A derives from B. In which case 1) you can explicitly initalise an abstract base class but 2) you must instantiate it in the initialiser list, since it must be fully constructed before the body of A::A() is executed.

This works for me:

```<code>#include <stdexcept>

struct B
{
  B() { }
  virtual int f() = 0;
};

struct A : B
{
  A() try : B() { } catch(const std::exception&) { }

  int f() { return 0; }
};

int main()
{
  A a;
}
</code>```

using g++ 5.4. I'm guessing your error (which you haven't provided) is due to some other problem, e.g. not deriving A from B, or a mismatch between the virtual function definitions in the two classes.

Body:
In definition

A::A()
try: B()
{}
catch(Exception e) {}

In this code, I have C2509 error.
When I try to go to definition(F12) in header file or (Ctrl+F12) in definition it doesn't work.

I tried

A::A()
{
 try
 { B();}
 catch(Exception e) {}
}

but this is impossible because in class B there is a pure virtual function.

I'm confused with the difference between

try: {}
catch

and

try{}
catch

Body:
I'm now assuming A derives from B. In which case 1) you can explicitly initalise an abstract base class but 2) you must instantiate it in the initialiser list, since it must be fully constructed before the body of A::A() is executed.

This works for me:

#include <stdexcept>

struct B
{
  B() { }
  virtual int f() = 0;
};

struct A : B
{
  A() try : B() { } catch(const std::exception&) { }

  int f() { return 0; }
};

int main()
{
  A a;
}

using g++ 5.4. I'm guessing your error (which you haven't provided) is due to some other problem, e.g. not deriving A from B, or a mismatch between the virtual function definitions in the two classes.


问:
Calculate n-ary Cartesian Product
Given two lists, I can produce a list of all permutations the Cartesian Product of these two lists:

```<code>permute :: [a] -> [a] -> [[a]]
permute xs ys = [ [x, y] | x <- xs, y <- ys ]

Example> permute [1,2] [3,4] == [ [1,3], [1,4], [2,3], [2,4] ]
</code>```

How do I extend permute so that instead of taking two lists, it takes a list (length n) of lists and returns a list of lists (length n)

```<code>permute :: [[a]] -> [[a]]

Example> permute [ [1,2], [3,4], [5,6] ]
            == [ [1,3,5], [1,3,6], [1,4,5], [1,4,6] ] --etc
</code>```

I couldn't find anything relevant on Hoogle.. the only function matching the signature was transpose, which doesn't produce the desired output.

Edit: I think the 2-list version of this is essentially the Cartesian Product, but I can't wrap my head around implementing the n-ary Cartesian Product. Any pointers?

答:
You can do this in 2 ways:

Using list comprehension

```<code>  cp :: [[a]] -> [[a]]
  cp []       = [[]]
  cp (xs:xss) = [ x:ys | x <- xs, ys <- cp xss ]
</code>```

Using a fold

```<code>  cp1 :: [[a]] -> [[a]]
  cp1 xs = foldr f [[]] xs
        where f xs xss = [x:ys | x <- xs, ys <- xss]
</code>```

ContentLicense: CC BY-SA 2.5

Title: Calculate n-ary Cartesian Product

Body:
Given two lists, I can produce a list of all permutations the Cartesian Product of these two lists:

permute :: [a] -> [a] -> [[a]]
permute xs ys = [ [x, y] | x <- xs, y <- ys ]

Example> permute [1,2] [3,4] == [ [1,3], [1,4], [2,3], [2,4] ]

How do I extend permute so that instead of taking two lists, it takes a list (length n) of lists and returns a list of lists (length n)

permute :: [[a]] -> [[a]]

Example> permute [ [1,2], [3,4], [5,6] ]
            == [ [1,3,5], [1,3,6], [1,4,5], [1,4,6] ] --etc

I couldn't find anything relevant on Hoogle.. the only function matching the signature was transpose, which doesn't produce the desired output.

Edit: I think the 2-list version of this is essentially the Cartesian Product, but I can't wrap my head around implementing the n-ary Cartesian Product. Any pointers?

Body:
You can do this in 2 ways:

Using list comprehension

  cp :: [[a]] -> [[a]]
  cp []       = [[]]
  cp (xs:xss) = [ x:ys | x <- xs, ys <- cp xss ]

Using a fold

  cp1 :: [[a]] -> [[a]]
  cp1 xs = foldr f [[]] xs
        where f xs xss = [x:ys | x <- xs, ys <- xss]


问:
How to delete all datastore in Google App Engine?
Does anyone know how to delete all datastore in Google App Engine?</p>

答:
For Python, 1.3.8 includes an experimental admin built-in for this. They say: "enable the following builtin in your app.yaml file:"

```<code>builtins:
- datastore_admin: on
</code>```

"Datastore delete is currently available only with the Python runtime. Java applications, however, can still take advantage of this feature by creating a non-default Python application version that enables Datastore Admin in the app.yaml. Native support for Java will be included in an upcoming release."

OwnerDisplayName: manman

Body:
For Python, 1.3.8 includes an experimental admin built-in for this. They say: "enable the following builtin in your app.yaml file:"

builtins:
- datastore_admin: on

"Datastore delete is currently available only with the Python runtime. Java applications, however, can still take advantage of this feature by creating a non-default Python application version that enables Datastore Admin in the app.yaml. Native support for Java will be included in an upcoming release."


问:
Collecting data for two columns
I am trying to use data from ‘NCR’ on two columns in my CSV. However it overrides each other and only presented the data in the column called ‘YesterdayTime’.

Is there a way to use the data from ‘NCR’ in both columns called ’ExTime’ and ‘YesterdayTime’?

My Code

```<code>from datetime import datetime
from elasticsearch import Elasticsearch
import csv

es = Elasticsearch(["9200"])

res = es.search(index="search", body=
                {
                    "_source": ["VT","NCR","N","DT","RD"],
                    "query": {

                        "bool": {
                            "must": [{"range": {"VT": {
                                            "gte": "now/d",
                                            "lte": "now+1d/d"}}},

                                {"wildcard": {"user": "mike*"}},
                                {"wildcard": {"user": "jane*"}},
                                {"wildcard": {"user": "kate*"}},
                                {"wildcard": {"user": "dave*"}},
                                {"wildcard": {"user": "rich*"}}

]}}},size=10)

csv_file = 'File_' + str(datetime.now().strftime('%Y_%m_%d - %H.%M.%S')) + '.csv'

header_names = { 'VT': 'Date',  'NCR': 'ExTime', 'NCR': 'YesterdayTime', 'N': 'Name', 'DT': 'Party', ' RD ': 'Period'}

with open(csv_file, 'w', newline='') as f:
    w = csv.DictWriter(f, fieldnames=header_names.keys(), restval='', extrasaction='ignore')
    w.writerow(header_names,)
    for doc in res['hits']['hits']:
        my_dict = doc['_source']

             w.writerow(my_dict)
</code>```

Output - EX time is being replaced with YesterdayTime.

```<code>DATE         YesterdayTime      Name   Party   Period

20170512    12/05/2017 15:39    1001    0        0

20170512    12/05/2017 15:39    1001    0        0

20170908    08/09/2017 02:42    1001    0        0

20170908    08/09/2017 06:30    1001    0        0
</code>```

The correct Output that i want:

```<code>DATE       YesterdayTime     YesterdayTime       Name   Party   Period

20170512  12/05/2017 15:39   12/05/2017 15:39    1001     0        0

20170512  12/05/2017 15:39   12/05/2017 15:39    1001     0        0

20170908  08/09/2017 02:42   08/09/2017 02:42    1001     0        0

20170908  08/09/2017 06:30   08/09/2017 06:30    1001     0        0
</code>```

答: Python dictionaries does not support duplicate keys. Your last occurrence of 'NSC' in header_names dictionary is overwriting the first.</p>

Title: Collecting data for two columns

Body:
I am trying to use data from ‘NCR’ on two columns in my CSV. However it overrides each other and only presented the data in the column called ‘YesterdayTime’.

Is there a way to use the data from ‘NCR’ in both columns called ’ExTime’ and ‘YesterdayTime’?

My Code

from datetime import datetime
from elasticsearch import Elasticsearch
import csv

es = Elasticsearch(["9200"])

res = es.search(index="search", body=
                {
                    "_source": ["VT","NCR","N","DT","RD"],
                    "query": {

                        "bool": {
                            "must": [{"range": {"VT": {
                                            "gte": "now/d",
                                            "lte": "now+1d/d"}}},

                                {"wildcard": {"user": "mike*"}},
                                {"wildcard": {"user": "jane*"}},
                                {"wildcard": {"user": "kate*"}},
                                {"wildcard": {"user": "dave*"}},
                                {"wildcard": {"user": "rich*"}}

]}}},size=10)

csv_file = 'File_' + str(datetime.now().strftime('%Y_%m_%d - %H.%M.%S')) + '.csv'

header_names = { 'VT': 'Date',  'NCR': 'ExTime', 'NCR': 'YesterdayTime', 'N': 'Name', 'DT': 'Party', ' RD ': 'Period'}

with open(csv_file, 'w', newline='') as f:
    w = csv.DictWriter(f, fieldnames=header_names.keys(), restval='', extrasaction='ignore')
    w.writerow(header_names,)
    for doc in res['hits']['hits']:
        my_dict = doc['_source']

             w.writerow(my_dict)

Output - EX time is being replaced with YesterdayTime.

DATE         YesterdayTime      Name   Party   Period

20170512    12/05/2017 15:39    1001    0        0

20170512    12/05/2017 15:39    1001    0        0

20170908    08/09/2017 02:42    1001    0        0

20170908    08/09/2017 06:30    1001    0        0

The correct Output that i want:

DATE       YesterdayTime     YesterdayTime       Name   Party   Period

20170512  12/05/2017 15:39   12/05/2017 15:39    1001     0        0

20170512  12/05/2017 15:39   12/05/2017 15:39    1001     0        0

20170908  08/09/2017 02:42   08/09/2017 02:42    1001     0        0

20170908  08/09/2017 06:30   08/09/2017 06:30    1001     0        0


问:
Spring @value for system properties giving null
```<code>    public class RedisMessageListener implements MessageListener {

        @Value("#{systemProperties['pub']}")
        private String publisher;

        @Autowired
        private LoadMoedlsFromDB ld;

        @Override
        public void onMessage( final Message message, final byte[] pattern ) {
            System.out.println( "Publisher flag::" + publisher);
            ld.downloadModels();
                if("false".equals(publisher)) {
                System.out.println(message.toString());
                }
        }}
</code>```

This outputs Publisher flag::null

But the same config works in other classes, is this because this is a Redis listener class

答: The RedisMessageListener must be a spring bean. I don't know your spring configuration but if classpath scanning is enabled maybe it is enough to add @Component to your class.

Body:
    public class RedisMessageListener implements MessageListener {

        @Value("#{systemProperties['pub']}")
        private String publisher;

        @Autowired
        private LoadMoedlsFromDB ld;

        @Override
        public void onMessage( final Message message, final byte[] pattern ) {
            System.out.println( "Publisher flag::" + publisher);
            ld.downloadModels();
                if("false".equals(publisher)) {
                System.out.println(message.toString());
                }
        }}

This outputs Publisher flag::null

But the same config works in other classes, is this because this is a Redis listener class


问:
PHP Regex to Change New Line Characters between Specific Tags
How can I change new line characters to
 which are only between
 and
 tags...?

```<code>$text = preg_replace( '#<P>(.*?)\r\n(.*?)</P>#s', '<P>$1<BR>$2</P>', $text );
</code>```

This made only the first new line character to be
.

答:
Brief

This has H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͥͮ͟O̮̪̝͍ͮM̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ written all over it...

I will provide you with a regular expression (as this is what you're asking for) but I would urge you to take a look at the post I've linked above. Regex is not the best tool for this job.

Code

Version 1

If you really want a regex solution for this, you can use the following:

See regex in use here

```<code>(?:<p>|\G(?!\A))(?:(?!</p>).)*?\K\v(?=[\s\S]*?</p>)
</code>```

Version 2

Assuming you also want to catch
 where x represents some arbitrary number of attributes, you can use the following regex:

See regex in use here

```<code>(?:<p.*?>|\G(?!\A))(?:(?!</p>).)*?\K\v(?=[\s\S]*?</p>)
</code>```

This regex matches
 instead of simply
.

Results

Input

```<code><p>something

here</p>

<p>
Something else
here
</p>
</code>```

Output

```<code><p>something <br/><br/>here</p>

<p><br/>Something else<br/>here<br/></p>
</code>```

Explanation

(?:
|\G(?!\A)) Match either of the following

 Matches
 literally

\G(?!\A) Assert position at the end of the previous match or the start of the string for the first match, negating (using a negative lookahead) the start of the string for the first match (thus, this asserts position at the end of the previous match).

(?:(?!
).)*? Match the following any number of times, but as few as possible

(?!
). Negative lookahead ensuring what follows is not
 literally. Assuming the negative lookahead doesn't match, match any character (except newline character since the s modifier is not used).

\K Reset the starting point of the reported match. Any previously consumed characters are no longer included in the final match.

\v Match any vertical whitespace character

(?=[\s\S]*?
) Positive lookahead ensuring what follows matches the following

[\s\S]*? Match any character any number of times, but as few as possible

 Match
 literally

Body:
How can I change new line characters to
 which are only between
 and
 tags...?

$text = preg_replace( '#
(.*?)\r\n(.*?)
#s', '
$1
$2
', $text );

This made only the first new line character to be
.

Body:
Brief

This has H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͥͮ͟O̮̪̝͍ͮM̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ written all over it...

I will provide you with a regular expression (as this is what you're asking for) but I would urge you to take a look at the post I've linked above. Regex is not the best tool for this job.

Code

Version 1

If you really want a regex solution for this, you can use the following:

See regex in use here

(?:<p>|\G(?!\A))(?:(?!</p>).)*?\K\v(?=[\s\S]*?</p>)

Version 2

Assuming you also want to catch <p x> where x represents some arbitrary number of attributes, you can use the following regex:

See regex in use here

(?:<p.*?>|\G(?!\A))(?:(?!</p>).)*?\K\v(?=[\s\S]*?</p>)

This regex matches <p.*?> instead of simply <p>.

Results

Input

<p>something

here</p>

<p>
Something else
here
</p>

Output

<p>something <br/><br/>here</p>

<p><br/>Something else<br/>here<br/></p>

Explanation

(?:<p>|\G(?!\A)) Match either of the following

<p> Matches <p> literally

\G(?!\A) Assert position at the end of the previous match or the start of the string for the first match, negating (using a negative lookahead) the start of the string for the first match (thus, this asserts position at the end of the previous match).

(?:(?!</p>).)*? Match the following any number of times, but as few as possible

(?!</p>). Negative lookahead ensuring what follows is not <p> literally. Assuming the negative lookahead doesn't match, match any character (except newline character since the s modifier is not used).

\K Reset the starting point of the reported match. Any previously consumed characters are no longer included in the final match.

\v Match any vertical whitespace character

(?=[\s\S]*?</p>) Positive lookahead ensuring what follows matches the following

[\s\S]*? Match any character any number of times, but as few as possible

</p> Match </p> literally


问:
Creating objects during runtime in Python
I have a problem grasping the OOP concept when it comes to creating objects during runtime. All the educational code that I have looked into yet defines specific variables e.g. 'Bob' and assigns them to a new object instance. Bob = Person()

What I have trouble understanding now is how I would design a model that creates a new object during runtime? I'm aware that my phrasing is probably faulty since all objects are generated during runtime but what I mean is that if I were to start my application in a terminal or UI how would I create new objects and manage them. I can't really define new variable names on the fly right?

An example application where I run into this design issue would be a database storing people. The user gets a terminal menu which allows him to create a new user and assign a name, salary, position. How would you instantiate that object and later call it if you want to manage it, call functions, etc.? What's the design pattern here?

Please excuse my poor understanding of the OPP model. I'm currently reading up on classes and OOP but I feel like I need to understand what my error is here before moving on. Please let me know if there is anything I should clarify.

答:
I'll try to answer as best I can here:

What you're asking about is variable variable names - this isn't in Python. (I think it's in VB.Net but don't hold me to that)

The user gets a terminal menu which allows him to create a new user and assign a name, salary, position. How would you instantiate that object and later call it if you want to manage it, call functions, etc.? What's the design pattern here?

This is how I'd add a new person (Mickey-mouse example):

```<code># Looping until we get a "fin" message
while True:
    print "Enter name, or "fin" to finish:"
    new_name = raw_input()
    if new_name == "fin":
        break
    print "Enter salary:"
    new_salary = raw_input()
    print "Enter position:"
    new_pos = raw_input()

    # Dummy database - the insert method would post this customer to the database
    cnn = db.connect()
    insert(cnn, new_name, new_salary, new_pos)
    cnn.commit()
    cnn.close()
</code>```

Ok, so you want to now get a person from the database.

```<code>while True:
    print "Enter name of employee, or "fin" to finish:"
    emp_name = raw_input()
    if emp_name == "fin":
        break
    # Like above, the "select_employee" would retreive someone from a database
    cnn = db.connect()
    person = select_employee(cnn, emp_name)
    cnn.close()

    # Person is now a variable, holding the person you specified:
    print(person.name)
    print(person.salary)
    print(person.position)

    # It's up to you from here what you want to do
</code>```

This is just a basic, rough example, but I think you get what I mean.

Also, as you can see, I didn't use a class here. A class for something like this would pretty much always be a better idea, but this was just to demonstrate how you'd change and use a variable during runtime.

Body:
I'll try to answer as best I can here:

What you're asking about is variable variable names - this isn't in Python. (I think it's in VB.Net but don't hold me to that)

The user gets a terminal menu which allows him to create a new user and assign a name, salary, position. How would you instantiate that object and later call it if you want to manage it, call functions, etc.? What's the design pattern here?

This is how I'd add a new person (Mickey-mouse example):

# Looping until we get a "fin" message
while True:
    print "Enter name, or "fin" to finish:"
    new_name = raw_input()
    if new_name == "fin":
        break
    print "Enter salary:"
    new_salary = raw_input()
    print "Enter position:"
    new_pos = raw_input()

    # Dummy database - the insert method would post this customer to the database
    cnn = db.connect()
    insert(cnn, new_name, new_salary, new_pos)
    cnn.commit()
    cnn.close()

Ok, so you want to now get a person from the database.

while True:
    print "Enter name of employee, or "fin" to finish:"
    emp_name = raw_input()
    if emp_name == "fin":
        break
    # Like above, the "select_employee" would retreive someone from a database
    cnn = db.connect()
    person = select_employee(cnn, emp_name)
    cnn.close()

    # Person is now a variable, holding the person you specified:
    print(person.name)
    print(person.salary)
    print(person.position)

    # It's up to you from here what you want to do

This is just a basic, rough example, but I think you get what I mean.

Also, as you can see, I didn't use a class here. A class for something like this would pretty much always be a better idea, but this was just to demonstrate how you'd change and use a variable during runtime.


问:
Haskell Parse string of Ints to tuple (Int,Int)
I would like to parse a string in form 3 3 from input user to a tuple (3,3) is this possible?

```<code>stringtup :: String -> Maybe (Int, Int)
stringtup s = do
[(n, [c])] <- return $ reads s
return (n, c)
</code>```

this is my attempt but it does't work..

答:
reads only parses one value (if possible), and gives it back as well as the rest of the input string. So,

```<code>    [(n, _)] <- return $ reads s
</code>```

works and will, for "3 3" indeed have n≡3.

But the other number still needs to be parsed too. So what you'd actually do is first bind something like

```<code>    [(n, s')] <- return $ reads s
</code>```

and then parse the other number in the same fashion from s'.

Body:
I would like to parse a string in form 3 3 from input user to a tuple (3,3) is this possible?

stringtup :: String -> Maybe (Int, Int)
stringtup s = do
[(n, [c])] <- return $ reads s
return (n, c)

this is my attempt but it does't work..

Body:
reads only parses one value (if possible), and gives it back as well as the rest of the input string. So,

    [(n, _)] <- return $ reads s

works and will, for "3 3" indeed have n≡3.

But the other number still needs to be parsed too. So what you'd actually do is first bind something like

    [(n, s')] <- return $ reads s

and then parse the other number in the same fashion from s'.


问:
Is it possible to use ES6 Symbols in LocalStorage
When using a ES6 Symbol as the key for a key/value pair in LocalStorage, can we then still access it after reloading the page?

I found this tutorial that claims this to be possible when using Symbol.for, but so far I have no success and get an undefined when I try to retrieve the LocalStorage key/value pair.

As a side question: does it make sense to use Symbols over here?

答:
You can use Symbols as keys in an object - that's one of theirs purposes. But localStorage is not your typical object. It has an API to set/get values in the store, which the tutorial you have shared is not using: localStorage.{set,get}Item().

Unfortunately localStorage doesn't accept Symbols as keys, only strings. So the real answer is no, you can't use Symbols as keys in LocalStorage, but...

You could do the following. It isn't actually using a Symbol as the key, but the Symbols toString() representation:

```<code>const sym = Symbol.for('Hello').toString()
localStorage.setItem(sym, 'World')
document.write('Hello, ' + localStorage.getItem(sym))
</code>```

[ Check it out on jsbin.com ]

As a side question: does it make sense to use Symbols over here?

I suppose you could use reserved Symbols (e.g. Symbol.iterator) to extend the functionality of the localStorage global. But that's kind of besides the point.

Body:
You can use Symbols as keys in an object - that's one of theirs purposes. But localStorage is not your typical object. It has an API to set/get values in the store, which the tutorial you have shared is not using: localStorage.{set,get}Item().

Unfortunately localStorage doesn't accept Symbols as keys, only strings. So the real answer is no, you can't use Symbols as keys in LocalStorage, but...

You could do the following. It isn't actually using a Symbol as the key, but the Symbols toString() representation:

const sym = Symbol.for('Hello').toString()
localStorage.setItem(sym, 'World')
document.write('Hello, ' + localStorage.getItem(sym))

[ Check it out on jsbin.com ]

As a side question: does it make sense to use Symbols over here?

I suppose you could use reserved Symbols (e.g. Symbol.iterator) to extend the functionality of the localStorage global. But that's kind of besides the point.


问:
How to combine UPDATE query with subquery?
In my Mysql database I want to update a field fup for all records which I found using this select statement:

```<code>SELECT ic.hash
FROM incompany as ic, app
WHERE ic.id = app.ic_id;
</code>```

So I created the following combined query:

```<code>UPDATE incompany
SET fup = 'x'
WHERE hash IN (SELECT ic.hash
FROM incompany as ic, app
WHERE ic.id = app.ic_id);
</code>```

But this query gives me the following error:

You can't specify target table 'incompany' for update in FROM clause

Does anybody know how I can make this work? All tips are welcome!

答:
You seem to want a condition on two columns, so this is a bit tricky.  If I follow the logic correctly:</p>

```<code>UPDATE incompany ic JOIN
       (SELECT DISTINCT ic.hash
        FROM incompany ic JOIN
             app
             ON ic.id = app.ic_id
       ) ica
       ON ica.hash = ic.hash
    SET fup = 'x' ;
</code>```

Body:
In my Mysql database I want to update a field fup for all records which I found using this select statement:

SELECT ic.hash
FROM incompany as ic, app
WHERE ic.id = app.ic_id;

So I created the following combined query:

UPDATE incompany
SET fup = 'x'
WHERE hash IN (SELECT ic.hash
FROM incompany as ic, app
WHERE ic.id = app.ic_id);

But this query gives me the following error:

You can't specify target table 'incompany' for update in FROM clause

Does anybody know how I can make this work? All tips are welcome!

Body:
You seem to want a condition on two columns, so this is a bit tricky.  If I follow the logic correctly:

UPDATE incompany ic JOIN
       (SELECT DISTINCT ic.hash
        FROM incompany ic JOIN
             app
             ON ic.id = app.ic_id
       ) ica
       ON ica.hash = ic.hash
    SET fup = 'x' ;


问:
WordPress check_ajax_referer gives 403 forbidden when using inside AJAX action
I am making an AJAX call in WordPress to connect an API. For this I am trying to use a nonce in order to prevent any unauthorized or robot access. This is my code:

functions.php

```<code>add_action('wp_enqueue_scripts', 'yrc_cst_ajax_platform_script_enqueue');

function yrc_cst_ajax_platform_script_enqueue () {
    wp_enqueue_script(
        'platform',
        get_template_directory_uri(). '/includes/platform.js',
        array('jquery'), '1.0', true);

    wp_localize_script('platform', 'yrc_cst_platform', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'ajax_nonce' => wp_create_nonce('platform_security')
    ));
}

add_action('wp_ajax_save_platform_contact', 'yrc_cst_save_platform_contact');
</code>```

Inside AJAX action method I wrote this (functions.php):

```<code>function yrc_cst_save_platform_contact() {
   if ( check_ajax_referer( 'platform_security', $_POST['security'] ) ) {
      var_dump($_POST['security']);
   }
   ...
}
</code>```

And here is the AJAX call:

```<code>jQuery.ajax({
   url: yrc_cst_platform.ajax_url,
   type: 'post',
   data: {
      action: 'save_platform_contact',
      security: yrc_cst_platform.ajax_nonce,
      contact_email: client_email
   },
   success: function(response) {
      // Doing my stuff...
   }
});
</code>```

In the console I see this

Failed to load resource. The server responded with a status code: 403
  (Forbidden) /wp-admin/admin-ajax.php

If I remove the block check_ajax_referer(...), things are working OK. Everything is in my local. I am testing the cycle as a logged in user only.

I don't know how to fix it.

答:
try using wp_verify_nonce instead of check_ajax_referer as below:</p>

```<code>function yrc_cst_save_platform_contact() {
if ( wp_verify_nonce( $_POST['security'], 'platform_security' ) ) {
  var_dump($_POST['security']);
}
 ...
}
</code>```

Body:
I am making an AJAX call in WordPress to connect an API. For this I am trying to use a nonce in order to prevent any unauthorized or robot access. This is my code:

functions.php

add_action('wp_enqueue_scripts', 'yrc_cst_ajax_platform_script_enqueue');

function yrc_cst_ajax_platform_script_enqueue () {
    wp_enqueue_script(
        'platform',
        get_template_directory_uri(). '/includes/platform.js',
        array('jquery'), '1.0', true);

    wp_localize_script('platform', 'yrc_cst_platform', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'ajax_nonce' => wp_create_nonce('platform_security')
    ));
}

add_action('wp_ajax_save_platform_contact', 'yrc_cst_save_platform_contact');

Inside AJAX action method I wrote this (functions.php):

function yrc_cst_save_platform_contact() {
   if ( check_ajax_referer( 'platform_security', $_POST['security'] ) ) {
      var_dump($_POST['security']);
   }
   ...
}

And here is the AJAX call:

jQuery.ajax({
   url: yrc_cst_platform.ajax_url,
   type: 'post',
   data: {
      action: 'save_platform_contact',
      security: yrc_cst_platform.ajax_nonce,
      contact_email: client_email
   },
   success: function(response) {
      // Doing my stuff...
   }
});

In the console I see this

Failed to load resource. The server responded with a status code: 403
  (Forbidden) /wp-admin/admin-ajax.php

If I remove the block check_ajax_referer(...), things are working OK. Everything is in my local. I am testing the cycle as a logged in user only.

I don't know how to fix it.

Body:
try using wp_verify_nonce instead of check_ajax_referer as below:

function yrc_cst_save_platform_contact() {
if ( wp_verify_nonce( $_POST['security'], 'platform_security' ) ) {
  var_dump($_POST['security']);
}
 ...
}


问:
Change Text Field Font from Dropdown Selection
I am trying to allow a user to select a font from a dropdown list that will change the fontFamily applied to text they've entered in a form text field. I've tried several variations on the following, with no success on Safari or Chrome. I'd appreciate it if someone can point out what I'm doing wrong. Changing colors works. Changing the fontFamily does not.

    <form>
    Enter Text:
    <input type="text" id="inputText" name="name" placeholder="YourName" maxlength="8">

     <select name="textColor" id="selectedColor" onchange="setPreview();">
           <option value="black" selected="selected">Black</option>
           <option value="red">Red</option>
        </select>
        <select name="textFont" id="selectedFont" onchange="setPreview();">
           <option value="Arial" selected="selected">Arial</option>
           <option value="Impact">Impact</option>
           <option value="Times New Roman">Times New Roman</option>
        </select>
    </form>

    ```

答:
Running your code immediately produces an error in your console that:

```<code>document.getElementByID is not a function
</code>```

So, you should know that there is a problem with that. Fix your .getElementByID to: .getElementById.

Now, for best performanc:

Place your script near the end of the document (after the DOM has been parsed)
Cache your reference to the element(s) you will work with often
Don't set up a variable for a value that you are only going to use once

<form>
Enter Text:
<input type="text" id="inputText" name="name" placeholder="YourName" maxlength="8">

    <select name="textColor" id="selectedColor" onchange="setPreview();">
       <option value="black" selected="selected">Black</option>
       <option value="red">Red</option>
    </select>
    <select name="textFont" id="selectedFont" onchange="setPreview();">
       <option value="Arial" selected="selected">Arial</option>
       <option value="Impact">Impact</option>
       <option value="Times New Roman">Times New Roman</option>
    </select>
</form>

```

Body:
Running your code immediately produces an error in your console that:

document.getElementByID is not a function

So, you should know that there is a problem with that. Fix your .getElementByID to: .getElementById.

Now, for best performanc:

Place your script near the end of the document (after the DOM has been parsed)
Cache your reference to the element(s) you will work with often
Don't set up a variable for a value that you are only going to use once

<html>
<head>
</head>
<body>
<form>
<label for="uname">Enter Text: </label>
<input type="text" id="inputText" name="name" placeholder="YourName" maxlength="8">

    <select name="textColor" id="selectedColor" onchange="setPreview();">
       <option value="black" selected="selected">Black</option>
       <option value="red">Red</option>
    </select>
    <select name="textFont" id="selectedFont" onchange="setPreview();">
       <option value="Arial" selected="selected">Arial</option>
       <option value="Impact">Impact</option>
       <option value="Times New Roman">Times New Roman</option>
    </select>
</form>

<script>
var input = document.getElementById("inputText");
var lstColor = document.getElementById("selectedColor");
var lstFont = document.getElementById("selectedFont");

function setPreview() {
    input.style.color = lstColor.value;
    input.style.fontFamily = lstFont.value;
}
</script>
</body>
</html>


问:
Cleaning Excel Spreadsheet using Python
I have what seems to be a simple task - I am almost done, but have one pesky issue I should be able to get rid of, but it's being elusive.

I have a number of Excel .xls files. The file name is in the format .xls.  I created the filenames.txt file to iterate through to get the company names.
Each file has garbage data in the first 4 or so rows, so I need to remove those first four rows in all the files. I then need to add a column with the  in the first column position.

My code runs with no errors, but the output is not exactly what I need.
The only problems I am running into are:
1. I am getting a leading column added that I wasn't expecting with index numbers.
2. The strip command doesn't appear to be stripping the '.xls' - so what ends up being inserted into the column in Excel is .xls instead of just .
3. Because the '.xls' is not being stripped properly, the to_excel command is saving the file with a '.xls.xls' extension.

I read a few similar scenarios, so I have this code being used:

```<code>import pandas as pd
import os
path = os.chdir(r"C:\Users\mheitz\Documents\testing")

filenames = [names.strip('\n') for names in \
    open(r"C:\Users\mheitz\Documents\testing\filenames.txt",'r').readlines()]

for name in filenames:
    vendors = pd.read_excel(name, header = 11, skiprows =0-10)
    vendors.insert(0,'Vendor Name',(name[:-4]))
    vendors.to_excel(r"C:\Users\mheitz\Documents\testing\clean\clean" + name)
</code>```

答: again, thanks for your help... amazing what a good night's sleep and some coffee will do for your state of mind. I realized this morning that I was doing too much. I only needed ONE list, not two - to iterate through.  ;)  I'll post my final code above - the only thing I still need to resolve is the leading column it is inserting with the index #'s, but that should be an easy fix - at least I can get through the 86 excel files though!</p>

Title: Cleaning Excel Spreadsheet using Python

Body:
I have what seems to be a simple task - I am almost done, but have one pesky issue I should be able to get rid of, but it's being elusive.

I have a number of Excel .xls files. The file name is in the format .xls.  I created the filenames.txt file to iterate through to get the company names.
Each file has garbage data in the first 4 or so rows, so I need to remove those first four rows in all the files. I then need to add a column with the  in the first column position.

My code runs with no errors, but the output is not exactly what I need.
The only problems I am running into are:
1. I am getting a leading column added that I wasn't expecting with index numbers.
2. The strip command doesn't appear to be stripping the '.xls' - so what ends up being inserted into the column in Excel is .xls instead of just .
3. Because the '.xls' is not being stripped properly, the to_excel command is saving the file with a '.xls.xls' extension.

I read a few similar scenarios, so I have this code being used:

import pandas as pd
import os
path = os.chdir(r"C:\Users\mheitz\Documents\testing")

filenames = [names.strip('\n') for names in \
    open(r"C:\Users\mheitz\Documents\testing\filenames.txt",'r').readlines()]

for name in filenames:
    vendors = pd.read_excel(name, header = 11, skiprows =0-10)
    vendors.insert(0,'Vendor Name',(name[:-4]))
    vendors.to_excel(r"C:\Users\mheitz\Documents\testing\clean\clean" + name)


问:
Any VM supporting Process.supportsNormalTermination==true?
A new feature of Java 9 is that it can not only forcefully kill processes (in the meaning of SIGKILL) it had created but it may also support to send a SIGTERM (in Java called "normal termination").

According to the documentation of Process one can query if the implementation supports this:

public boolean supportsNormalTermination() Returns true if the
  implementation of destroy() is to normally terminate the process,
  Returns false if the implementation of destroy forcibly and
  immediately terminates the process. Invoking this method on Process
  objects returned by ProcessBuilder.start() and
  Runtime.exec(java.lang.String) return true or false depending on the
  platform implementation.

I made some tests using Oracle JRE 9.0.1 (Windows 64bit):

```<code>Process p = Runtime.getRuntime().exec("javaw -cp target/classes TestClassWait10Minutes");
p.waitFor(5, TimeUnit.SECONDS);
System.out.println(p.supportsNormalTermination());
</code>```

However it seems like Oracle JRE does not supports "normal termination" as I always get false.

As it depends on the "platform implementation" it seems that Java 9 defines it but does not implement it.

Does anybody know if the feature of "normal termination" is usable at all in any available Java VM?

答:
On Linux implementation, it seems to support normal termination. From the source of ProcessImpl:

```<code>// Linux platforms support a normal (non-forcible) kill signal.
static final boolean SUPPORTS_NORMAL_TERMINATION = true;

...

@Override

public boolean supportsNormalTermination() {
    return ProcessImpl.SUPPORTS_NORMAL_TERMINATION;
}
</code>```

Not the case on Windows.

Body:
A new feature of Java 9 is that it can not only forcefully kill processes (in the meaning of SIGKILL) it had created but it may also support to send a SIGTERM (in Java called "normal termination").

According to the documentation of Process one can query if the implementation supports this:

public boolean supportsNormalTermination() Returns true if the
  implementation of destroy() is to normally terminate the process,
  Returns false if the implementation of destroy forcibly and
  immediately terminates the process. Invoking this method on Process
  objects returned by ProcessBuilder.start() and
  Runtime.exec(java.lang.String) return true or false depending on the
  platform implementation.

I made some tests using Oracle JRE 9.0.1 (Windows 64bit):

Process p = Runtime.getRuntime().exec("javaw -cp target/classes TestClassWait10Minutes");
p.waitFor(5, TimeUnit.SECONDS);
System.out.println(p.supportsNormalTermination());

However it seems like Oracle JRE does not supports "normal termination" as I always get false.

As it depends on the "platform implementation" it seems that Java 9 defines it but does not implement it.

Does anybody know if the feature of "normal termination" is usable at all in any available Java VM?

Body:
On Linux implementation, it seems to support normal termination. From the source of ProcessImpl:

// Linux platforms support a normal (non-forcible) kill signal.
static final boolean SUPPORTS_NORMAL_TERMINATION = true;

...

@Override

public boolean supportsNormalTermination() {
    return ProcessImpl.SUPPORTS_NORMAL_TERMINATION;
}

Not the case on Windows.


答:
You have a typo

```<code>document.getElementByID("inputText").style.fontFamily = myFont;
</code>```

ID should be Id

updated:

function setPreview() {
  var myColor = document.getElementById("selectedColor").value;
  document.getElementById("inputText").style.color = myColor;

  var myFont = document.getElementById("selectedFont").value;
  document.getElementById("inputText").style.fontFamily = myFont;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label for="uname">Enter Text: </label>
<input type="text" id="inputText" name="name" placeholder="YourName" maxlength="8">

<select name="textColor" id="selectedColor" onchange="setPreview();">
   <option value="black" selected="selected">Black</option>
   <option value="red">Red</option>
</select>
<select name="textFont" id="selectedFont" onchange="setPreview();">
   <option value="Arial" selected="selected">Arial</option>
   <option value="Impact">Impact</option>
   <option value="Times New Roman">Times New Roman</option>
</select></code>```

Title: Change Text Field Font from Dropdown Selection

Body:
I am trying to allow a user to select a font from a dropdown list that will change the fontFamily applied to text they've entered in a form text field. I've tried several variations on the following, with no success on Safari or Chrome. I'd appreciate it if someone can point out what I'm doing wrong. Changing colors works. Changing the fontFamily does not.

    <form>
    Enter Text:
    <input type="text" id="inputText" name="name" placeholder="YourName" maxlength="8">

     <select name="textColor" id="selectedColor" onchange="setPreview();">
           <option value="black" selected="selected">Black</option>
           <option value="red">Red</option>
        </select>
        <select name="textFont" id="selectedFont" onchange="setPreview();">
           <option value="Arial" selected="selected">Arial</option>
           <option value="Impact">Impact</option>
           <option value="Times New Roman">Times New Roman</option>
        </select>
    </form>

Body:
You have a typo

document.getElementByID("inputText").style.fontFamily = myFont;

ID should be Id

updated:

function setPreview() {
  var myColor = document.getElementById("selectedColor").value;
  document.getElementById("inputText").style.color = myColor;

  var myFont = document.getElementById("selectedFont").value;
  document.getElementById("inputText").style.fontFamily = myFont;
}

<label for="uname">Enter Text: </label>
<input type="text" id="inputText" name="name" placeholder="YourName" maxlength="8">

<select name="textColor" id="selectedColor" onchange="setPreview();">
   <option value="black" selected="selected">Black</option>
   <option value="red">Red</option>
</select>
<select name="textFont" id="selectedFont" onchange="setPreview();">
   <option value="Arial" selected="selected">Arial</option>
   <option value="Impact">Impact</option>
   <option value="Times New Roman">Times New Roman</option>
</select>


问:
Command Prompt cannot find or run my Java File
New programmer here, in terms of actually using an editor and running it. I have created a simple program that states this.

```<code>public class HelloWorld {

    public static void main(String[] args) {
        // Prints "Hello, World" to the terminal window.
        System.out.println("Hello, World");
    }
}
</code>```

I have already set the path to "C:\Program Files\Java\jdk1.8.0_151\bin\".(current version"1.8.0_151"). In the cmd input, "java" and "javac" work until I attempt to find a file name either "HelloWorld.java" or "HelloWorld". How do I get cmd to find and run my java file? Thank you!

答:
One way to try it:

Open C:\Temp (or create if not exists)

Create new file called HelloWorld.java

Open cmd

Type cd /d C:\Temp

Type javac HelloWorld.java

Type java HelloWorld

Body:
New programmer here, in terms of actually using an editor and running it. I have created a simple program that states this.

public class HelloWorld {

    public static void main(String[] args) {
        // Prints "Hello, World" to the terminal window.
        System.out.println("Hello, World");
    }
}

I have already set the path to "C:\Program Files\Java\jdk1.8.0_151\bin\".(current version"1.8.0_151"). In the cmd input, "java" and "javac" work until I attempt to find a file name either "HelloWorld.java" or "HelloWorld". How do I get cmd to find and run my java file? Thank you!


问:
Freely convert between List<T> and IEnumerable<T>
How can I convert a List<MyObject> to an IEnumerable<MyObject> and then back again?

I want to do this in order to run a series of LINQ statements on the List, e. g. Sort()

答:
```<code>List<string> myList = new List<string>();
IEnumerable<string> myEnumerable = myList;
List<string> listAgain = myEnumerable.ToList();
</code>```

OwnerDisplayName: TK

OwnerDisplayName: DrJokepu


问:
Deprecation of the static keyword... no more?
In C++ it is possible to use the static keyword within a translation unit to affect the visibility of a symbol (either variable or function declaration).

In n3092, this was deprecated:

Annex D.2 [depr.static]

  The use of the static keyword is deprecated when declaring objects in namespace scope (see 3.3.6).

In n3225, this has been removed.

The only article I could find is somewhat informal.

It does underline though, that for compatibility with C (and the ability to compile C-programs as C++) the deprecation is annoying. However, compiling a C program directly as C++ can be a frustrating experience already, so I am unsure if it warrants consideration.

Does anyone know why it was changed ?

答:
In C++ Standard Core Language Defect Reports and Accepted Issues, Revision 94 under 1012. Undeprecating static they note:

Although 7.3.1.1 [namespace.unnamed] states that the use of the static keyword for declaring variables in namespace scope is deprecated because the unnamed namespace provides a superior alternative, it is unlikely that the feature will be removed at any point in the foreseeable future.

Basically this is saying that the deprecation of static doesn't really make sense. It won't ever be removed from C++.  It's still useful because you don't need the boilerplate code you would need with unnamed namespace's if you just want to declare a function or object with internal linkage.


问:
Loop for variables (Xcode 9 - swift 4)
I have I think a stupid question for you, but I start Xcode just one week ago and I have a problem with a loop condition.

```<code>for index in 1...4 {
    AvatarPlayer1.layer.borderWidth = 4
    AvatarPlayer1.layer.cornerRadius = 8
    AvatarPlayer1.layer.borderColor = UIColor.white.cgColor
    AvatarPlayer1.layer.masksToBounds = false
    AvatarPlayer1.clipsToBounds = true //Mask for picture
}
</code>```

How can I change the 1 value by for number in the loop.
I have try + , + \(index), + index.

答:
In addition to matt's answer, you could move the setup up stuff to the object init or setup method.

After that, you could use init(repeating:count:) for the list's init. See: https://developer.apple.com/documentation/swift/array/1641692-init

Title: Loop for variables (Xcode 9 - swift 4)

Body:
I have I think a stupid question for you, but I start Xcode just one week ago and I have a problem with a loop condition.

for index in 1...4 {
    AvatarPlayer1.layer.borderWidth = 4
    AvatarPlayer1.layer.cornerRadius = 8
    AvatarPlayer1.layer.borderColor = UIColor.white.cgColor
    AvatarPlayer1.layer.masksToBounds = false
    AvatarPlayer1.clipsToBounds = true //Mask for picture
}

How can I change the 1 value by for number in the loop.
I have try + , + \(index), + index.


问:
Generate same unique hash code for all anagrams
Recently, I attended an interview and faced a good question regarding hash collisions.

Question : Given a list of strings, print out the anagrams together.

Example :

i/p :              {act, god, animal, dog, cat}

o/p :                  act, cat, dog, god

I want to create hashmap and put the word as key and value as list of anagrams

To avoid collision, I want to generate unique hash code for anagrams instead of sorting and using the sorted word as key.

I am looking for hash algorithm which take care of collision other than using chaining. I want algorithm to generate same hash code for both act and cat... so that it will add next word to the value list

Can anyone suggest a good algorithm ?

答:
The complexity above seems very misplaced! You don't need prime numbers or hashes.  It's just three simple ops:

Map each OriginalWord to a Tuple of (SortedWord, OriginalWord).  Example: "cat" becomes ("act", "cat"); "dog" becomes ("dgo", "dog").  This is a simple sort on the chars of each OriginalWord.

Sort the Tuples by their first element.  Example: ("dgo", "dog"), ("act, "cat") sorts to ("act", "cat"), ("dgo", "dog").  This is a simple sort on the entire collection.

Iterate through the tuples (in order), emitting the OriginalWord.  Example: ("act", "cat"), ("dgo", "dog") emits "cat" "dog". This is a simple iteration.

Two iterations and two sorts are all it takes!

In Scala, it's exactly one line of code:

```<code>val words = List("act", "animal", "dog", "cat", "elvis", "lead", "deal", "lives", "flea", "silent", "leaf", "listen")

words.map(w => (w.toList.sorted.mkString, w)).sorted.map(_._2)
# Returns: List(animal, act, cat, deal, lead, flea, leaf, dog, listen, silent, elvis, lives)
</code>```

Or, as the original question implies, you only want cases where the count > 1, it's just a bit more:

```<code>scala> words.map(w => (w.toList.sorted.mkString, w)).groupBy(_._1).filter({case (k,v) => v.size > 1}).mapValues(_.map(_._2)).values.toList.sortBy(_.head)
res64: List[List[String]] = List(List(act, cat), List(elvis, lives), List(flea, leaf), List(lead, deal), List(silent, listen))
</code>```

Body:
The complexity above seems very misplaced! You don't need prime numbers or hashes.  It's just three simple ops:

Map each OriginalWord to a Tuple of (SortedWord, OriginalWord).  Example: "cat" becomes ("act", "cat"); "dog" becomes ("dgo", "dog").  This is a simple sort on the chars of each OriginalWord.

Sort the Tuples by their first element.  Example: ("dgo", "dog"), ("act, "cat") sorts to ("act", "cat"), ("dgo", "dog").  This is a simple sort on the entire collection.

Iterate through the tuples (in order), emitting the OriginalWord.  Example: ("act", "cat"), ("dgo", "dog") emits "cat" "dog". This is a simple iteration.

Two iterations and two sorts are all it takes!

In Scala, it's exactly one line of code:

val words = List("act", "animal", "dog", "cat", "elvis", "lead", "deal", "lives", "flea", "silent", "leaf", "listen")

words.map(w => (w.toList.sorted.mkString, w)).sorted.map(_._2)
# Returns: List(animal, act, cat, deal, lead, flea, leaf, dog, listen, silent, elvis, lives)

Or, as the original question implies, you only want cases where the count > 1, it's just a bit more:

scala> words.map(w => (w.toList.sorted.mkString, w)).groupBy(_._1).filter({case (k,v) => v.size > 1}).mapValues(_.map(_._2)).values.toList.sortBy(_.head)
res64: List[List[String]] = List(List(act, cat), List(elvis, lives), List(flea, leaf), List(lead, deal), List(silent, listen))


问:
How do I avoid "SEVERE: Duplicate ID" warnings for my autodoc'd modules in Sphinx?
I'm using rST/Sphinx to document my Python, however when building it's throwing warnings such as

```<code>...Code/doc/code.rst:3: SEVERE: Duplicate ID: "module-toast".
</code>```

My Python source files are documented like so:

```<code>#!/usr/bin/env python
'''
.. module:: toast
    :synopsis: Processes the blobs produced by :mod:`bread`.
'''
# my inline-rST documented code...
</code>```

And the rST files use the autodoc provided automodule directive to pull all the docstrings out and document all the members.

```<code>Toast
--------------------------------

.. automodule:: toast
    :members:
</code>```

The above combo seems to work just fine, but the error seems to imply there is a proper way to do this.  If I remove the module directive from the top of my source file the error goes away, but then I can't add a synopsis option in the source that's picked up by Sphinx.

答:
The :noindex: for automodule:: as written by simno helps but prevents the creation of perma-links and cross-links (e.g. :func:) won't work.
When adding :noindex: to module:: everything works as expected and you don't have to use currentmodule.

Body:
I'm using rST/Sphinx to document my Python, however when building it's throwing warnings such as

...Code/doc/code.rst:3: SEVERE: Duplicate ID: "module-toast".

My Python source files are documented like so:

#!/usr/bin/env python
'''
.. module:: toast
    :synopsis: Processes the blobs produced by :mod:`bread`.
'''
# my inline-rST documented code...

And the rST files use the autodoc provided automodule directive to pull all the docstrings out and document all the members.

Toast
--------------------------------

.. automodule:: toast
    :members:

The above combo seems to work just fine, but the error seems to imply there is a proper way to do this.  If I remove the module directive from the top of my source file the error goes away, but then I can't add a synopsis option in the source that's picked up by Sphinx.


问:
How to use 'in' keyword in Javascript
I have a question here. I know my code have plenty of problems and I need your help.
The problem is, To return an object which have numbers of repetition information of the string.
The given string is

```<code>var r = countFreq(["a", "b", "b", "c", "c", "c", "d"]);
</code>```

and the result have to be

```<code>{"a":1, "b":2, "c":3, "d":1 }
</code>```

by console.log(r);

All that I know is, key(properties) have to be element and value(value of property) have to be the number of repetition.
AND, I must use 'in' key world to solve this problem.

```<code>Like,
if('property' in 'object')  {
 //...
}else {
 //...
}
</code>```

(if there's no property initialize as 1, and if there's a same property, add 1 each time)

I really appreciate your help.
(This post may have grammatical errors. I really feel sorry about that...)

```<code>      function countFreq(array) {
        var i;
        for(i=0; i<array.length; i++)
        {
          if(array[i] in array)
          {
            return i += 1;
          }else
          {
            return i = 1;
          }
          console.log(array[i]+": "+i+", ");
        }
      }
      var r = countFreq(["a","b","c","c","c","d"]);
      console.log(r);
</code>```

答:
I think you are misunderstanding the in operator. In can be used in 2 cases, as a boolean operator to check for the presence of an index in an array or to iterate over the indexes of an array with a for loop. You are using it to check for the presence of a value in an array directly, which you cannot do. Also you are returning from the function after each iteration so you will only ever get 1 or 0.

I presume you want something like the following:

```<code>countFreq(array) {
    var results = { a: 0, b: 0, c: 0, d: 0 };
    for (var index in array) {
        results[array[index]] ++;
    }
    return results;
}
</code>```

Now you can access each result with results[‘a’] for instance, after calling countFreq. I think you need to read up on return and loops in JavaScript.

Title: How to use 'in' keyword in Javascript

Body:
I have a question here. I know my code have plenty of problems and I need your help.
The problem is, To return an object which have numbers of repetition information of the string.
The given string is

var r = countFreq(["a", "b", "b", "c", "c", "c", "d"]);

and the result have to be

{"a":1, "b":2, "c":3, "d":1 }

by console.log(r);

All that I know is, key(properties) have to be element and value(value of property) have to be the number of repetition.
AND, I must use 'in' key world to solve this problem.

Like,
if('property' in 'object')  {
 //...
}else {
 //...
}

(if there's no property initialize as 1, and if there's a same property, add 1 each time)

I really appreciate your help.
(This post may have grammatical errors. I really feel sorry about that...)

      function countFreq(array) {
        var i;
        for(i=0; i<array.length; i++)
        {
          if(array[i] in array)
          {
            return i += 1;
          }else
          {
            return i = 1;
          }
          console.log(array[i]+": "+i+", ");
        }
      }
      var r = countFreq(["a","b","c","c","c","d"]);
      console.log(r);

Body:
I think you are misunderstanding the in operator. In can be used in 2 cases, as a boolean operator to check for the presence of an index in an array or to iterate over the indexes of an array with a for loop. You are using it to check for the presence of a value in an array directly, which you cannot do. Also you are returning from the function after each iteration so you will only ever get 1 or 0.

I presume you want something like the following:

countFreq(array) {
    var results = { a: 0, b: 0, c: 0, d: 0 };
    for (var index in array) {
        results[array[index]] ++;
    }
    return results;
}

Now you can access each result with results[‘a’] for instance, after calling countFreq. I think you need to read up on return and loops in JavaScript.


问:
DialogFlow (API.AI) REST with php
I work on DialogFlow recently and I need to send a POST to my own web services.
It's a Rest services work with Symfony et PHP.

So I tried something and it didn't work.
In the tutorial it worked with Google Cloud, but I don't want to work with it.

I changed the URL of Webhook with my own. I didn't change anything else in DialogFlow because it was good with google. There it is :

```<code>/**
 * @Rest\View()
 * @Rest\Post("/testDialogBot")
 */
public function testDialogBotAction( Request $request )
{
    $re = "Test reponse";
    $response = new Response(json_encode( array( "speech" => $re, "displayText" => $re )));
    $response->headers->set('Content-Type', 'application/json');
    return $response;

}
</code>```

The JSON of DialogFlow return :

```<code>"status": {
  "code": 206,
  "errorType": "partial_content",
  "errorDetails": "Webhook call failed. Error: Request timeout."
},
</code>```

I'm sure it can work, I do something bad probably.

Thank's for help.

答:
According to the official docs the response "should" have the following fields: speech, displayText, data, contextOut adn source. You are only sending speech and displayText. Maybe adding the others will do the trick.

Also, the limits stated on the docs for the response are:

Timeout for service response – 5 seconds.   Data received in the
  response from the service – up to 64K.

Check if your server can send the response within those parameters

Title: DialogFlow (API.AI) REST with php

Body:
I work on DialogFlow recently and I need to send a POST to my own web services.
It's a Rest services work with Symfony et PHP.

So I tried something and it didn't work.
In the tutorial it worked with Google Cloud, but I don't want to work with it.

I changed the URL of Webhook with my own. I didn't change anything else in DialogFlow because it was good with google. There it is :

/**
 * @Rest\View()
 * @Rest\Post("/testDialogBot")
 */
public function testDialogBotAction( Request $request )
{
    $re = "Test reponse";
    $response = new Response(json_encode( array( "speech" => $re, "displayText" => $re )));
    $response->headers->set('Content-Type', 'application/json');
    return $response;

}

The JSON of DialogFlow return :

"status": {
  "code": 206,
  "errorType": "partial_content",
  "errorDetails": "Webhook call failed. Error: Request timeout."
},

I'm sure it can work, I do something bad probably.

Thank's for help.


问:
Any known Orchard CMS case studies?
We're looking into using Orchard CMS for a project. I know the CMS hasn't been around for a long time, but I was wondering if there were any known high profile and successful case studies using Orchard CMS or its predecessor Oxite?

Thanks.

答: The recently released Orchard Gallery is itself built using Orchard: http://orchardproject.net/gallery. Also, the NuGet gallery website is using the exact same code as the Orchard Gallery, with a different theme applied: http://nuget.org. What's more, the Orchard/NuGet gallery is mostly implemented as a custom Orchard module, and that code is open source. Check out http://orchardgallery.codeplex.com for more details.</p>

Title: Any known Orchard CMS case studies?


问:
ioutil.ReadAll fails miserably
I'm trying to get an io.Reader back from this weather it's a link or a path I'm given. For some context I'm using flags

```<code>func getString(link, path string) (io.Reader, error) {

    var dick io.ReadWriter

    if link != "" {
        resp, err := http.Get(link)
        if err != nil {
            return nil, err
        }

        io.Copy(dick, resp.Body)
    }

    if path != "" {
        file, err := os.Open(path)
        if err != nil {
            return nil, err
        }

        io.Copy(dick, file)
    }

    return dick, nil

}
</code>```

and boom

```<code>panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x20 pc=0x46e949]
</code>```

this bad boy comes along

答:
If you just want a Reader back from the function, it's much simpler than the other answers make it out to be. The io.Copy, buffer, etc is completely unnecessary:

```<code>func getString(link, path string) (io.Reader, error) {
    if link != "" {
        resp, err := http.Get(link)
        if err != nil {
            return nil, err
        }
        return resp.Body, err // http.Response.Body implements io.Reader
    }

    if path != "" {
        return os.Open(path) // os.File implements io.Reader
    }

    return nil, errors.New("No path or link given")
}
</code>```

You might want to return an io.ReadCloser so that the caller knows it needs to, and will be able to, close it once it finishes reading from it. Both Body and File implement ReadCloser so the only change needed would be the function's return signature.

Title: ioutil.ReadAll fails miserably

Body:
I'm trying to get an io.Reader back from this weather it's a link or a path I'm given. For some context I'm using flags

func getString(link, path string) (io.Reader, error) {

    var dick io.ReadWriter

    if link != "" {
        resp, err := http.Get(link)
        if err != nil {
            return nil, err
        }

        io.Copy(dick, resp.Body)
    }

    if path != "" {
        file, err := os.Open(path)
        if err != nil {
            return nil, err
        }

        io.Copy(dick, file)
    }

    return dick, nil

}

and boom

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x20 pc=0x46e949]

this bad boy comes along

Body:
If you just want a Reader back from the function, it's much simpler than the other answers make it out to be. The io.Copy, buffer, etc is completely unnecessary:

func getString(link, path string) (io.Reader, error) {
    if link != "" {
        resp, err := http.Get(link)
        if err != nil {
            return nil, err
        }
        return resp.Body, err // http.Response.Body implements io.Reader
    }

    if path != "" {
        return os.Open(path) // os.File implements io.Reader
    }

    return nil, errors.New("No path or link given")
}

You might want to return an io.ReadCloser so that the caller knows it needs to, and will be able to, close it once it finishes reading from it. Both Body and File implement ReadCloser so the only change needed would be the function's return signature.


问:
how to create Plugin for Kibana 5.6.3
I want to create a plugin for kibana version 5.6.3,due to this i follow the link "https://github.com/elastic/kibana/blob/master/CONTRIBUTING.md#contributing-code",the github provider the source code of the latest version kibana 7.0.0 https://github.com/elastic/kibana .but i need the kibana version 5.6.3 to create a plugin, where I get the source code </p>

答: The link that you provide will not help you develop plugin, look at the next video tutorial</p>

Title: how to create Plugin for Kibana 5.6.3


问:
How to display both icon and title of action inside ActionBar?
I need to display both icon and title of action inside ActionBar.

I've tried "withText" option, but it has no effect.

答:
You can add button in toolbar

```<code><android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:popupTheme="@style/AppTheme.PopupOverlay"
        app:title="title">

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:layout_marginRight="16dp"
            android:background="@color/transparent"
            android:drawableRight="@drawable/ic_your_icon"
            android:drawableTint="@drawable/btn_selector"
            android:text="@string/sort_by_credit"
            android:textColor="@drawable/btn_selector"
            />

    </android.support.v7.widget.Toolbar>
</code>```

create file btn_selector.xml in drawable

```<code><?xml version="1.0" encoding="utf-8" ?>
</code>```

<selector xmlns:android="http://schemas.android.com/apk/res/android">

```<code><item
    android:state_selected="true"
    android:color="@color/white"
    />
<item
    android:color="@color/white_30_opacity"
    />
</code>```

java:

private boolean isSelect = false;

OnClickListener for button:

```<code>private void myClick() {
    if (!isSelect) {
       //**your code**//
        isSelect = true;
    } else {//**your code**//
        isSelect = false;
    }
    sort.setSelected(isSelect);
}
</code>```

Body:
You can add button in toolbar

<android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:popupTheme="@style/AppTheme.PopupOverlay"
        app:title="title">

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:layout_marginRight="16dp"
            android:background="@color/transparent"
            android:drawableRight="@drawable/ic_your_icon"
            android:drawableTint="@drawable/btn_selector"
            android:text="@string/sort_by_credit"
            android:textColor="@drawable/btn_selector"
            />

    </android.support.v7.widget.Toolbar>

create file btn_selector.xml in drawable

<?xml version="1.0" encoding="utf-8" ?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item
    android:state_selected="true"
    android:color="@color/white"
    />
<item
    android:color="@color/white_30_opacity"
    />

java:

private boolean isSelect = false;

OnClickListener for button:

private void myClick() {
    if (!isSelect) {
       //**your code**//
        isSelect = true;
    } else {//**your code**//
        isSelect = false;
    }
    sort.setSelected(isSelect);
}


问:
Keeping dependencies quiet in Erlang
I am using chumak in an Erlang-based ZMQ server.  I am listening and spawning processes to accept connections:

```<code>          {ok, LSocket} = chumak:socket(rep),
          {ok, _} =  chumak:bind(LSocket, tcp, "0.0.0.0", ?PORT),
          spawn_link(fun() -> loop(LSocket, DBConn, RedisConn) end),
</code>```

That all works fine.  But there is one problem.  When something "unexpected" (from chumak's point of view) happens, such as a port scan connecting to its port, the process to accept data may die.  That's fine, because it restarts automatically.  What's not fine is that when this happens, chumak sprays its errors all over the console.  I don't care about them.

Is there any way to shut up a dependency library, in Erlang?

答:
chumak errors are emitted through error_logger. That means, to prevent them from being displayed you have to tell your error_logger handler not to display them.

I'll guess you're using sasl for that. If that's the case, what you need to do is to add this configuration to sasl environment: {sasl_error_logger, false}.

But be careful, you'll be disabling all error logs from displaying if you do so. I'm not sure if you can tell sasl to skip particular kinds of error reports instead. If that's possible, you will want not to print out error messages for bind_error reports.

Title: Keeping dependencies quiet in Erlang

Body:
I am using chumak in an Erlang-based ZMQ server.  I am listening and spawning processes to accept connections:

          {ok, LSocket} = chumak:socket(rep),
          {ok, _} =  chumak:bind(LSocket, tcp, "0.0.0.0", ?PORT),
          spawn_link(fun() -> loop(LSocket, DBConn, RedisConn) end),

That all works fine.  But there is one problem.  When something "unexpected" (from chumak's point of view) happens, such as a port scan connecting to its port, the process to accept data may die.  That's fine, because it restarts automatically.  What's not fine is that when this happens, chumak sprays its errors all over the console.  I don't care about them.

Is there any way to shut up a dependency library, in Erlang?


问:
RxJava2 chain commands with optional conditions
I'm still trying to figure out reactive programming and am trying to create a chain with RxJava2. The logic is as follows when creating an order (pseudocode).

```<code>void createOrder {
    R r1 = null, r2 = null, r3 = null;
    Order order = null;
    if (condition1) {
        then r1 = new R();
    } else if (condition2) {
        then r2 = new R();
    }

    if (condition3) {
        then r3 = new R();
    }

    if (r1 not null) {
        if (r3 not null) {
            create order with r1 + r3
        } else {
            create order with r1
        }
    } else if (r2 not null) {
        if (r3 not null) {
            create order with r2 + r3
        } else {
            create order with r2
        }
    } else {
        fail creating an order
    }
}
</code>```

I have created 4 Singles that do the work of creating r1, r2, r3 and the order but I can't figure out how to chain all of these together to make the entire sequence with the above logic.

I think we could use several Maybes for the if (condition) checks but am not sure how to chain them together with the Singles to achieve the above.

Any help with this is much appreciated.

答:
With some reordering of the logic it isn't that difficult to convert to a reactive chain.

What you need to do is observe what the possible end results are and what the requirements to reach those results are:

r1 or as backup r2 must have a value

if r3 has a value, merge with the previous result

if this value exists, turn into order.

Point 1. can be constructed by considering each variable a Maybe<R> object, then using Maybe.switchIfEmpty to calculate the value.

Point 2. can be implemented using the second flatmap implementation which allows for different reactions based on the result from r3.

Point 3. can be done in the flatmap as well, finalizing it with a Single<Order> that throws an error if the above steps did not yield a result.

This results in the following pseudo-implementation:

```<code>Maybe<R> r1 = Maybe.defer(() -> {
    if (condition1)
        return Maybe.just(new R());
    else
        return Maybe.empty();
});

Maybe<R> r2 = Maybe.defer(() -> {
    if (condition2)
        return Maybe.just(new R());
    else
        return Maybe.empty();
});

Maybe<R> r3 = Maybe.defer(() -> {
    if (condition3)
        return Maybe.just(new R());
    else
        return Maybe.empty();
});

return r1.switchIfEmpty(r2).flatMap((r1r2) -> {
    return r3.flatMap(
        (r3val) -> Maybe.just(create order with r1r2 + r3val),
        (err) -> Maybe.error(err),
        () -> Maybe.just(create order with r1r2)
    );
}).switchIfEmpty(Single.defer(() -> {
    return Single.error(fail creating an order);
}));
</code>```

The end result of this code will be Single<Order>.

Body:
I'm still trying to figure out reactive programming and am trying to create a chain with RxJava2. The logic is as follows when creating an order (pseudocode).

void createOrder {
    R r1 = null, r2 = null, r3 = null;
    Order order = null;
    if (condition1) {
        then r1 = new R();
    } else if (condition2) {
        then r2 = new R();
    }

    if (condition3) {
        then r3 = new R();
    }

    if (r1 not null) {
        if (r3 not null) {
            create order with r1 + r3
        } else {
            create order with r1
        }
    } else if (r2 not null) {
        if (r3 not null) {
            create order with r2 + r3
        } else {
            create order with r2
        }
    } else {
        fail creating an order
    }
}

I have created 4 Singles that do the work of creating r1, r2, r3 and the order but I can't figure out how to chain all of these together to make the entire sequence with the above logic.

I think we could use several Maybes for the if (condition) checks but am not sure how to chain them together with the Singles to achieve the above.

Any help with this is much appreciated.

Body:
With some reordering of the logic it isn't that difficult to convert to a reactive chain.

What you need to do is observe what the possible end results are and what the requirements to reach those results are:

r1 or as backup r2 must have a value

if r3 has a value, merge with the previous result

if this value exists, turn into order.

Point 1. can be constructed by considering each variable a Maybe<R> object, then using Maybe.switchIfEmpty to calculate the value.

Point 2. can be implemented using the second flatmap implementation which allows for different reactions based on the result from r3.

Point 3. can be done in the flatmap as well, finalizing it with a Single<Order> that throws an error if the above steps did not yield a result.

This results in the following pseudo-implementation:

Maybe<R> r1 = Maybe.defer(() -> {
    if (condition1)
        return Maybe.just(new R());
    else
        return Maybe.empty();
});

Maybe<R> r2 = Maybe.defer(() -> {
    if (condition2)
        return Maybe.just(new R());
    else
        return Maybe.empty();
});

Maybe<R> r3 = Maybe.defer(() -> {
    if (condition3)
        return Maybe.just(new R());
    else
        return Maybe.empty();
});

return r1.switchIfEmpty(r2).flatMap((r1r2) -> {
    return r3.flatMap(
        (r3val) -> Maybe.just(create order with r1r2 + r3val),
        (err) -> Maybe.error(err),
        () -> Maybe.just(create order with r1r2)
    );
}).switchIfEmpty(Single.defer(() -> {
    return Single.error(fail creating an order);
}));

The end result of this code will be Single<Order>.