问:
Why does using a jQuery object as parameter in html() work?
I recently discovered quite by accident that using a jQuery object as a parameter in of html() works.  Accordin to the documentation, the only acceptable types are htmlString and function but for some reason the following still works:

var htmlString = 'hello world';
var jQueryObject = $(htmlString);
$('div').html(jQueryObject);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div></code>```

UPDATE:

Seems the mechanics of my snippet might have been misconstrued, so offering this to help clarify.  The html() will successfully take any jQuery object - regardless how it's constructed.  You can see below that I'm simply selecting the  element in the top div and moving it. In this case no htmlString is ever introduced.

$('button').on('click', function() {
  $('#fill-me').html($('#move-me span'));
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  height: 20px;
  width: 100%;
  border: 1px solid #000;
  margin: 5px;
  padding: 5px;
}

#move-me {
  color: red;
}

#fill-me {
  color: green;
}</code>```

Hello World

<button>Click to Move HTML</button>```

Why does this work counter to what the docs say is supported?  Did I miss something in the documentation?

答:
If you look at the jQuery source code, it implements the following logic (I've simplified a bit):

```<code>if (typeof value == 'string') {
    // assign the value to .innerHTML
} else {
    this.empty().append(value);
}
</code>```

So you can give .html() anything that's acceptable to .append(), and .append() can take a jQuery object.

This isn't an officially acceptable parameter type, it's simply an accident of implementation. There's no guarantee that it will continue to work in future versions. If you want to put a jQuery object in an element, use .append():

```<code>$('div').empty().append(jQueryObject);
</code>```

Body:
I recently discovered quite by accident that using a jQuery object as a parameter in of html() works.  Accordin to the documentation, the only acceptable types are htmlString and function but for some reason the following still works:

var htmlString = 'hello world';
var jQueryObject = $(htmlString);
$('div').html(jQueryObject);

UPDATE:

Seems the mechanics of my snippet might have been misconstrued, so offering this to help clarify.  The html() will successfully take any jQuery object - regardless how it's constructed.  You can see below that I'm simply selecting the  element in the top div and moving it. In this case no htmlString is ever introduced.

$('button').on('click', function() {
  $('#fill-me').html($('#move-me span'));
});

div {
  height: 20px;
  width: 100%;
  border: 1px solid #000;
  margin: 5px;
  padding: 5px;
}

#move-me {
  color: red;
}

#fill-me {
  color: green;
}

Hello World

<button>Click to Move HTML</button>

Why does this work counter to what the docs say is supported?  Did I miss something in the documentation?

Body:
If you look at the jQuery source code, it implements the following logic (I've simplified a bit):

if (typeof value == 'string') {
    // assign the value to .innerHTML
} else {
    this.empty().append(value);
}

So you can give .html() anything that's acceptable to .append(), and .append() can take a jQuery object.

This isn't an officially acceptable parameter type, it's simply an accident of implementation. There's no guarantee that it will continue to work in future versions. If you want to put a jQuery object in an element, use .append():

$('div').empty().append(jQueryObject);


来源: stackexchange

问:
Auto input answer for a terminal command within python script
I made a python script in which it runs a specified terminal command.

```<code>def main(my_list):
    for item in my_list:
        os.system("myCmd -s {0}".format(item))

    item_list = ['itemA', 'itemB', 'itemC']
    main(item_list)
</code>```

As the terminal command I am trying to use does not accepts a list in the -s argument, which is the reason that I make it into a python script.
While running the script, it works but I notice that it will prompts me with the following question:
Are you sure you want to continue (y/n)?

This means I will need to punch in the y on my keyboard, 3 times in the above example.
But in the event if my list is huge, and should I not be on my desk, is there any way that I can script to make it accept 'y' as my answer, without me to press anything on the keyboard?

答: Use the pexpect module.  It's basically expect used in shell scripts, for Python.

ContentLicense: CC BY-SA 3.0

Body:
I made a python script in which it runs a specified terminal command.

def main(my_list):
    for item in my_list:
        os.system("myCmd -s {0}".format(item))

    item_list = ['itemA', 'itemB', 'itemC']
    main(item_list)

As the terminal command I am trying to use does not accepts a list in the -s argument, which is the reason that I make it into a python script.
While running the script, it works but I notice that it will prompts me with the following question:
Are you sure you want to continue (y/n)?

This means I will need to punch in the y on my keyboard, 3 times in the above example.
But in the event if my list is huge, and should I not be on my desk, is there any way that I can script to make it accept 'y' as my answer, without me to press anything on the keyboard?


问:
Why instantiate a new list before recursion call?
```<code>public void dfsSearch (TreeNode root, List<String> curr, List<List<String>> res) {
        curr.add(String.valueOf(root.val));
        // a leaf node has been reached
        if (root.left == null && root.right == null) {
            res.add(curr);
            return;
        }
        if (root.left != null) {
            List<String> temp = new ArrayList<>(curr);
            dfsSearch(root.left, temp, res);
        }
        if (root.right != null) {
            List<String> temp = new ArrayList<>(curr);
            dfsSearch(root.right, temp, res);
        }
    }
</code>```

The code above is a a method using dfs to find all the paths from root to leaves in a binary tree, and my question is, in the two lines above the recursive call, why do I need to instantiate a new list and pass this temp list (temp) to the recursive call, why can't I just use the curr (the argument in the function)?

答: The copies are to prevent concurrent modification of curr when the dfsSearch method is called recursively. The first line curr.add(String.valueOf(root.val)); modifies the curr collection, and you can't loop through a collection while modifying it.

Body:
public void dfsSearch (TreeNode root, List<String> curr, List<List<String>> res) {
        curr.add(String.valueOf(root.val));
        // a leaf node has been reached
        if (root.left == null && root.right == null) {
            res.add(curr);
            return;
        }
        if (root.left != null) {
            List<String> temp = new ArrayList<>(curr);
            dfsSearch(root.left, temp, res);
        }
        if (root.right != null) {
            List<String> temp = new ArrayList<>(curr);
            dfsSearch(root.right, temp, res);
        }
    }

The code above is a a method using dfs to find all the paths from root to leaves in a binary tree, and my question is, in the two lines above the recursive call, why do I need to instantiate a new list and pass this temp list (temp) to the recursive call, why can't I just use the curr (the argument in the function)?


问:
How to find accuracy of model from hdf5 generated from keras?
I have trained a CNN model using keras and I saved its weight in HDF5 file.

Now I want to see accuracy of my model, how can I find it?

and how can I predict unlabled data using HDF5 ? Is it possible using h5 file?

Thanks

答:
Create your model and compile it using model.compile.Then, you can load the weight with :

model.load_weights('my_model_weights.h5')

then you can use model.evaluate on your testing set. Find more info on model.evaluate here : Model API


问:
Plot generation: stop for-loop if plot already exists
I'm using python and matplotlib to generate plots from a fairly large database of XY data (~1000 folder and growing). Every folder holds a single CSV file containing XY data that I want to generate a scatter plot of.
Since more data folders are periodically added to the root folder, I want to periodically run my script to keep the plots updated. Unfortunately this script now runs for ~10 minutes and I foresee that it will keep running longer and longer.

I would like to speed up the script by adding something to my code that skips searching the present folder for XY data if a .png file is present in the folder. What should I amend on the code below to reflect that?

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

# Find files containing XY data
for root, dirs, files in os.walk('D:/temp\\', topdown=False):
    for name in files:
       #find and check txt file
        if name.startswith('XY') and name.endswith('.txt'):
            # read data and store lines in list
            try:
                posX = list() #list of x-positions
                posY = list() #list of y-positions
                filepath = os.path.join(root, name)
                fp = open(filepath)
                for line in fp:
                    # make lists from the csv rows
                    content = line.split()
                    posX.append(float(content[0]))
                    posY.append(float(content[1]))
                fp.close()
                # prepare a scatter plot
                figure = plt.scatter(posX,posY)
                # save plot as png
                plt.savefig(root+'plot.png')
                # clear plot data for next for loop iteration
                plt.clf()
</code>```

Update:
using below answer I update the if statement inside the second for loop:

```<code>#find and check txt file
    if name.startswith('XY') and name.endswith('.txt') and not os.path.isfile(root+'plot.png'):
(...)
    else:
        print('no new data available')
</code>```

答:
All you need is to translate your original question from English into Python:</p>

```<code>if name.startswith('XY') and name.endswith('.txt') \
   and not os.path.isfile(root+'plot.png'): ...
</code>```

Body:
I'm using python and matplotlib to generate plots from a fairly large database of XY data (~1000 folder and growing). Every folder holds a single CSV file containing XY data that I want to generate a scatter plot of.
Since more data folders are periodically added to the root folder, I want to periodically run my script to keep the plots updated. Unfortunately this script now runs for ~10 minutes and I foresee that it will keep running longer and longer.

I would like to speed up the script by adding something to my code that skips searching the present folder for XY data if a .png file is present in the folder. What should I amend on the code below to reflect that?

import os
import matplotlib.pyplot as plt

# Find files containing XY data
for root, dirs, files in os.walk('D:/temp\\', topdown=False):
    for name in files:
       #find and check txt file
        if name.startswith('XY') and name.endswith('.txt'):
            # read data and store lines in list
            try:
                posX = list() #list of x-positions
                posY = list() #list of y-positions
                filepath = os.path.join(root, name)
                fp = open(filepath)
                for line in fp:
                    # make lists from the csv rows
                    content = line.split()
                    posX.append(float(content[0]))
                    posY.append(float(content[1]))
                fp.close()
                # prepare a scatter plot
                figure = plt.scatter(posX,posY)
                # save plot as png
                plt.savefig(root+'plot.png')
                # clear plot data for next for loop iteration
                plt.clf()

Update:
using below answer I update the if statement inside the second for loop:

#find and check txt file
    if name.startswith('XY') and name.endswith('.txt') and not os.path.isfile(root+'plot.png'):
(...)
    else:
        print('no new data available')

Body:
All you need is to translate your original question from English into Python:

if name.startswith('XY') and name.endswith('.txt') \
   and not os.path.isfile(root+'plot.png'): ...


问:
Minimizing the cost function for function that takes multiple arrays as inputs in Python
I have some function that takes in 4 1-D arrays as input and returns a single 1-D array as output.

```<code>def func(arr1,arr2,arr3,arr4):
    #function guts
    return answer
</code>```

I am trying to get the output array of this function to match a pre-known correct array answer. I have made a cost function that can compare the function output to the actual answer, and give me a value representing how close it is (a lower number is better)

```<code>def cost_function(guess, real_answer):
   #function guts
   return cost      #lower number means guess is close to real answer
</code>```

I would like a way to find the best values to use for the original input arrays to get close to the real answer. Presumably this will use the SciPy optimization package, but I am unsure where to start.

答:
If your function output varies smoothly (small changes in input yield small changes in output) in all of its arguments, you could consider a gradient decent approach.

however, as you can see here (scipy.optimize docs), there are also optimization methods you can select, that don't require prior knowledge, such as powell. What you will always need is a set of starting values and your function.

But consider: if you don't know much about #function guts and have a lot of parameters (your arr1-4 have high dimensionality) then this will take a while...

hope this helps

Body:
I have some function that takes in 4 1-D arrays as input and returns a single 1-D array as output.

def func(arr1,arr2,arr3,arr4):
    #function guts
    return answer

I am trying to get the output array of this function to match a pre-known correct array answer. I have made a cost function that can compare the function output to the actual answer, and give me a value representing how close it is (a lower number is better)

def cost_function(guess, real_answer):
   #function guts
   return cost      #lower number means guess is close to real answer

I would like a way to find the best values to use for the original input arrays to get close to the real answer. Presumably this will use the SciPy optimization package, but I am unsure where to start.


问:
Python: check regex expression
I generate my own regex expression and I would like to check if it is valid. For example if I have regex "[a-zA-Z0-9]" it will be valid but "[a-zA-Z0s-9]" not.</p>

答:
To check if regex is valid from inside python:

```<code>import re
re.compile('<regex>')
</code>```

This code will throw an error if it's invalid regex.

However, I find it much more useful to use regex tool, here's a few to choose from:

regexr

regex101

Title: Python: check regex expression

Body:
To check if regex is valid from inside python:

import re
re.compile('<regex>')

This code will throw an error if it's invalid regex.

However, I find it much more useful to use regex tool, here's a few to choose from:

regexr

regex101


问:
Converting class using an array of references to Point2d objects to using a java.util.ArrayList<Point2d>
```<code>package polygongeneric;

import java.util.ArrayList;

public class Polygon {

private ArrayList <Point2d> p = null;
private int points = 0;

public Polygon() { }

public Polygon(int numPoints) {
    p = new ArrayList<>();
}

public boolean addPoint(Point2d point) {
   p.add(points, point);
    points++;
    return true;
}

public boolean addPoint(double x, double y) {
   Point2d a = new Point2d(x,y);
   p.add(points, a);
   return true;
}

@Override
public String toString() {
    String s = "";
    for (int i=0; i<points; i++)
        s += p.get(i).toString() + "\n";
    return s;
}
</code>```

}

I'm trying to convert a class from using an array of references to Point2d objects as type Point2d. This is what I have so far but it's not outputting the answer that it's supposed to.

This is what my code outputs

```<code>(0.1,0.9)

(0.5,0.5)

(0.2,0.5)
</code>```

This is what it's supposed to output

```<code>(0.1,0.9)

(0.3,0.7)

(0.5,0.5)

(0.4,0.8)

(0.2,0.5)
</code>```

Do you guys have any idea. What I'm doing wrong?

This is my Point2d class

```<code>package polygongeneric;

public class Point2d {

private double x = 0, y = 0;

public Point2d() { }

public Point2d(double x, double y) {
    setX(x);
    setY(y);
}

public void setX(double initX) {
    if (initX >= 0 && initX <= 1)
        x = initX;
}

public void setY(double y) {
    if (y >= 0 && y <= 1)
        this.y = y;
}

public double getX() { return x; }

public double getY() { return y; }

public String toString() {
    return "(" + x + "," + y + ")";
}
</code>```

}

This is my main method

```<code>package polygongeneric;

public class PolygonGeneric {

public static void main(String[] args) {

    Polygon p = new Polygon(5);

    p.addPoint(new Point2d(.1, .9));
    p.addPoint(.3, .7);
    p.addPoint(new Point2d(.5, .5));
    p.addPoint(.4, .8);
    p.addPoint(new Point2d(.2, .5));

    System.out.println(p);
}

 }
</code>```

答:
Why not reuse the same method? and call the overloaded function
public boolean addPoint(Point2d point); instead of writing the same logic again and again.

```<code>public boolean addPoint(double x, double y) {
   Point2d a = new Point2d(x,y);
   return addPoint(a);
}
</code>```

Body:
package polygongeneric;

import java.util.ArrayList;

public class Polygon {

private ArrayList <Point2d> p = null;
private int points = 0;

public Polygon() { }

public Polygon(int numPoints) {
    p = new ArrayList<>();
}

public boolean addPoint(Point2d point) {
   p.add(points, point);
    points++;
    return true;
}

public boolean addPoint(double x, double y) {
   Point2d a = new Point2d(x,y);
   p.add(points, a);
   return true;
}

@Override
public String toString() {
    String s = "";
    for (int i=0; i<points; i++)
        s += p.get(i).toString() + "\n";
    return s;
}

}

I'm trying to convert a class from using an array of references to Point2d objects as type Point2d. This is what I have so far but it's not outputting the answer that it's supposed to.

This is what my code outputs

(0.1,0.9)

(0.5,0.5)

(0.2,0.5)

This is what it's supposed to output

(0.1,0.9)

(0.3,0.7)

(0.5,0.5)

(0.4,0.8)

(0.2,0.5)

Do you guys have any idea. What I'm doing wrong?

This is my Point2d class

package polygongeneric;

public class Point2d {

private double x = 0, y = 0;

public Point2d() { }

public Point2d(double x, double y) {
    setX(x);
    setY(y);
}

public void setX(double initX) {
    if (initX >= 0 && initX <= 1)
        x = initX;
}

public void setY(double y) {
    if (y >= 0 && y <= 1)
        this.y = y;
}

public double getX() { return x; }

public double getY() { return y; }

public String toString() {
    return "(" + x + "," + y + ")";
}

}

This is my main method

package polygongeneric;

public class PolygonGeneric {

public static void main(String[] args) {

    Polygon p = new Polygon(5);

    p.addPoint(new Point2d(.1, .9));
    p.addPoint(.3, .7);
    p.addPoint(new Point2d(.5, .5));
    p.addPoint(.4, .8);
    p.addPoint(new Point2d(.2, .5));

    System.out.println(p);
}

 }

Body:
Why not reuse the same method? and call the overloaded function
public boolean addPoint(Point2d point); instead of writing the same logic again and again.

public boolean addPoint(double x, double y) {
   Point2d a = new Point2d(x,y);
   return addPoint(a);
}


问:
TypeError when trying to Proxy a ES6 class constructor
I'm trying to Proxy a ES6 constructor (mostly trying to emulate Python's descriptors for fun and learning):

class _Record {
    constructor(data) {
        this._data = data;
    }
}

const constrProxyHandlers = {
    construct: function(target, args, cstr) {
        let instProxyHandler = {
            get: (target, prop) => {
                if(prop in target._data) { return target._data[prop] }
                return target[prop]
            },
            set: (target, prop, val) => {
                if(prop in target._data) {
                    target._data[prop] = val;
                } else {
                    target[prop] = val;
                }
                return true
            }
        }

        let obj = Object.create(cstr.prototype)
        cstr.apply(obj, args)
        return new Proxy(obj, instProxyHandler)
    }
}

const Record = new Proxy(_Record, constrProxyHandlers)

let rec = new Record({name: 'Vic', age: 25})
console.log([rec.name, rec.age])
rec.name = 'Viktor'
console.log(rec)```
</div>
</div>
</p>

<p>If you run this snippet, you'll get this error:</p>

```cstr.apply(obj, args)

TypeError: Class constructor _Record cannot be invoked without 'new'
```

If I replace cstr.apply with new cstr, the constructor quickly exhausts stack (apparently going into an infinite recursion).

This works if I replace the _Record class with a function (for example, this would work transpiled through Babel). Can I make it work with native ES6?

Thank you.

P. S. I'm currently checking these snippets on Node 7.7.4, if it matters.

答:
The part

```<code>let obj = Object.create(cstr.prototype)
cstr.apply(obj, args)
</code>```

does not work with ES6 classes. You need to use

```<code>let obj = Reflect.construct(target, args, cstr);
</code>```

(and not Reflect.construct(cstr, args) or new cstr(...args) that you were trying to do, which indeed recurses infinitely - IIRC target refers to _Record while cstr refers to Record or one of its subclasses).

Body:
I'm trying to Proxy a ES6 constructor (mostly trying to emulate Python's descriptors for fun and learning):

class _Record {
    constructor(data) {
        this._data = data;
    }
}

const constrProxyHandlers = {
    construct: function(target, args, cstr) {
        let instProxyHandler = {
            get: (target, prop) => {
                if(prop in target._data) { return target._data[prop] }
                return target[prop]
            },
            set: (target, prop, val) => {
                if(prop in target._data) {
                    target._data[prop] = val;
                } else {
                    target[prop] = val;
                }
                return true
            }
        }

        let obj = Object.create(cstr.prototype)
        cstr.apply(obj, args)
        return new Proxy(obj, instProxyHandler)
    }
}

const Record = new Proxy(_Record, constrProxyHandlers)

let rec = new Record({name: 'Vic', age: 25})
console.log([rec.name, rec.age])
rec.name = 'Viktor'
console.log(rec)

If you run this snippet, you'll get this error:

cstr.apply(obj, args)

TypeError: Class constructor _Record cannot be invoked without 'new'

If I replace cstr.apply with new cstr, the constructor quickly exhausts stack (apparently going into an infinite recursion).

This works if I replace the _Record class with a function (for example, this would work transpiled through Babel). Can I make it work with native ES6?

Thank you.

P. S. I'm currently checking these snippets on Node 7.7.4, if it matters.

Body:
The part

let obj = Object.create(cstr.prototype)
cstr.apply(obj, args)

does not work with ES6 classes. You need to use

let obj = Reflect.construct(target, args, cstr);

(and not Reflect.construct(cstr, args) or new cstr(...args) that you were trying to do, which indeed recurses infinitely - IIRC target refers to _Record while cstr refers to Record or one of its subclasses).


问:
MySQL sometimes not using the INDEX but sometimes it does
Sometimes my query is not using the index, but some time it does. Can you guys explain me why is it happening?

This is the table structure.

MariaDB [crm]> desc vtiger_project;
+------------------------+---------------+------+-----+---------+-------+
| Field                  | Type          | Null | Key | Default | Extra |
+------------------------+---------------+------+-----+---------+-------+
| projectid              | int(11)       | NO   | PRI | 0       |       |
| projectname            | varchar(100)  | YES  |     | NULL    |       |
| projecttype            | varchar(50)   | YES  |     | NULL    |       |
| siteaddress            | varchar(500)  | YES  |     | NULL    |       |
| state                  | varchar(100)  | YES  |     | NULL    |       |
| district               | varchar(100)  | YES  |     | NULL    |       |
| city                   | varchar(100)  | YES  |     | NULL    |       |
| pincode                | varchar(100)  | YES  |     | NULL    |       |
| phone                  | varchar(100)  | YES  |     | NULL    |       |
| startdate              | date          | YES  | MUL | NULL    |       |
| branch                 | varchar(100)  | YES  |     | NULL    |       |
| customer               | int(11)       | YES  | MUL | NULL    |       |
| dealer                 | int(11)       | YES  |     | NULL    |       |
| contractor             | int(11)       | YES  | MUL | NULL    |       |
| architect              | int(11)       | YES  | MUL | NULL    |       |
| carpenter              | int(11)       | YES  | MUL | NULL    |       |
| productcategory        | varchar(100)  | YES  |     | NULL    |       |
| brand_preferred        | varchar(100)  | YES  |     | NULL    |       |
| formal_spec_check      | varchar(3)    | YES  |     | NULL    |       |
| formal_spec_details    | varchar(250)  | YES  |     | NULL    |       |
| projectstatus          | varchar(25)   | YES  |     | NULL    |       |
| project_reason_loosing | varchar(100)  | YES  |     | NULL    |       |
| reason_loosing_deatils | varchar(250)  | YES  |     | NULL    |       |
| reason_winning_deatils | varchar(250)  | YES  |     | NULL    |       |
| adjustment             | decimal(25,8) | YES  |     | NULL    |       |
| exciseduty             | decimal(25,3) | YES  |     | NULL    |       |
| total                  | decimal(25,8) | YES  |     | NULL    |       |
| subtotal               | decimal(25,8) | YES  |     | NULL    |       |
| taxtype                | varchar(25)   | YES  |     | NULL    |       |
| discount_percent       | decimal(25,3) | YES  |     | NULL    |       |
| discount_amount        | decimal(25,8) | YES  |     | NULL    |       |
| s_h_amount             | decimal(25,8) | YES  |     | NULL    |       |
| currency_id            | int(19)       | NO   |     | 1       |       |
| conversion_rate        | decimal(10,3) | NO   |     | 1.000   |       |
| actual_sale            | varchar(255)  | YES  |     | NULL    |       |
| expected_sale_in_na    | varchar(255)  | YES  |     | NULL    |       |
| primary_decision_maker | varchar(100)  | YES  |     | NULL    |       |
+------------------------+---------------+------+-----+---------+-------+
```

<p>As you can see below output the first query does hitting the index, but the second one not, the only change i made on that query is <strong>startdate</strong> part.
What am i doing wrong?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>MariaDB [crm]> explain SELECT
    ->     COUNT(projectid)
    -> FROM
    ->     vtiger_project
    -> WHERE
    ->     82582 IN (customer , contractor, architect, carpenter)
    ->         AND projectstatus NOT IN ('Supplied' , 'Closed As Complete', 'Closed As Lost')
    ->         AND actual_sale IS NULL
    ->         AND startdate > NOW()
    -> ;
+------+-------------+----------------+-------+---------------+---------------+---------+------+------+------------------------------------+
| id   | select_type | table          | type  | possible_keys | key           | key_len | ref  | rows | Extra                              |
+------+-------------+----------------+-------+---------------+---------------+---------+------+------+------------------------------------+
|    1 | SIMPLE      | vtiger_project | range | startdate_idx | startdate_idx | 4       | NULL |  352 | Using index condition; Using where |
+------+-------------+----------------+-------+---------------+---------------+---------+------+------+------------------------------------+
1 row in set (0.00 sec)

MariaDB [crm]> explain SELECT
    ->     COUNT(projectid)
    -> FROM
    ->     vtiger_project
    -> WHERE
    ->     82582 IN (customer , contractor, architect, carpenter)
    ->         AND projectstatus NOT IN ('Supplied' , 'Closed As Complete', 'Closed As Lost')
    ->         AND actual_sale IS NULL
    ->         AND startdate < NOW()
    -> ;
+------+-------------+----------------+------+---------------+------+---------+------+-------+-------------+
| id   | select_type | table          | type | possible_keys | key  | key_len | ref  | rows  | Extra       |
+------+-------------+----------------+------+---------------+------+---------+------+-------+-------------+
|    1 | SIMPLE      | vtiger_project | ALL  | startdate_idx | NULL | NULL    | NULL | 15779 | Using where |
+------+-------------+----------------+------+---------------+------+---------+------+-------+-------------+</code>```

答:
(sqlbot's comment answers the question.)

Further optimization might be available with this composite index:

```<code>INDEX(actual_sale, startdate)
</code>```

But, that would probably work well only actual_sale is not NULL 'too often'.  Otherwise, a full table scan would be better, but the Optimizer might not figure that out.

Many of your columns seen to be excessively large.  Such excesses can lead to performance problems.

Body:
Sometimes my query is not using the index, but some time it does. Can you guys explain me why is it happening?

This is the table structure.

MariaDB [crm]> desc vtiger_project;
+------------------------+---------------+------+-----+---------+-------+
| Field                  | Type          | Null | Key | Default | Extra |
+------------------------+---------------+------+-----+---------+-------+
| projectid              | int(11)       | NO   | PRI | 0       |       |
| projectname            | varchar(100)  | YES  |     | NULL    |       |
| projecttype            | varchar(50)   | YES  |     | NULL    |       |
| siteaddress            | varchar(500)  | YES  |     | NULL    |       |
| state                  | varchar(100)  | YES  |     | NULL    |       |
| district               | varchar(100)  | YES  |     | NULL    |       |
| city                   | varchar(100)  | YES  |     | NULL    |       |
| pincode                | varchar(100)  | YES  |     | NULL    |       |
| phone                  | varchar(100)  | YES  |     | NULL    |       |
| startdate              | date          | YES  | MUL | NULL    |       |
| branch                 | varchar(100)  | YES  |     | NULL    |       |
| customer               | int(11)       | YES  | MUL | NULL    |       |
| dealer                 | int(11)       | YES  |     | NULL    |       |
| contractor             | int(11)       | YES  | MUL | NULL    |       |
| architect              | int(11)       | YES  | MUL | NULL    |       |
| carpenter              | int(11)       | YES  | MUL | NULL    |       |
| productcategory        | varchar(100)  | YES  |     | NULL    |       |
| brand_preferred        | varchar(100)  | YES  |     | NULL    |       |
| formal_spec_check      | varchar(3)    | YES  |     | NULL    |       |
| formal_spec_details    | varchar(250)  | YES  |     | NULL    |       |
| projectstatus          | varchar(25)   | YES  |     | NULL    |       |
| project_reason_loosing | varchar(100)  | YES  |     | NULL    |       |
| reason_loosing_deatils | varchar(250)  | YES  |     | NULL    |       |
| reason_winning_deatils | varchar(250)  | YES  |     | NULL    |       |
| adjustment             | decimal(25,8) | YES  |     | NULL    |       |
| exciseduty             | decimal(25,3) | YES  |     | NULL    |       |
| total                  | decimal(25,8) | YES  |     | NULL    |       |
| subtotal               | decimal(25,8) | YES  |     | NULL    |       |
| taxtype                | varchar(25)   | YES  |     | NULL    |       |
| discount_percent       | decimal(25,3) | YES  |     | NULL    |       |
| discount_amount        | decimal(25,8) | YES  |     | NULL    |       |
| s_h_amount             | decimal(25,8) | YES  |     | NULL    |       |
| currency_id            | int(19)       | NO   |     | 1       |       |
| conversion_rate        | decimal(10,3) | NO   |     | 1.000   |       |
| actual_sale            | varchar(255)  | YES  |     | NULL    |       |
| expected_sale_in_na    | varchar(255)  | YES  |     | NULL    |       |
| primary_decision_maker | varchar(100)  | YES  |     | NULL    |       |
+------------------------+---------------+------+-----+---------+-------+

As you can see below output the first query does hitting the index, but the second one not, the only change i made on that query is startdate part.
What am i doing wrong?

MariaDB [crm]> explain SELECT
    ->     COUNT(projectid)
    -> FROM
    ->     vtiger_project
    -> WHERE
    ->     82582 IN (customer , contractor, architect, carpenter)
    ->         AND projectstatus NOT IN ('Supplied' , 'Closed As Complete', 'Closed As Lost')
    ->         AND actual_sale IS NULL
    ->         AND startdate > NOW()
    -> ;
+------+-------------+----------------+-------+---------------+---------------+---------+------+------+------------------------------------+
| id   | select_type | table          | type  | possible_keys | key           | key_len | ref  | rows | Extra                              |
+------+-------------+----------------+-------+---------------+---------------+---------+------+------+------------------------------------+
|    1 | SIMPLE      | vtiger_project | range | startdate_idx | startdate_idx | 4       | NULL |  352 | Using index condition; Using where |
+------+-------------+----------------+-------+---------------+---------------+---------+------+------+------------------------------------+
1 row in set (0.00 sec)

MariaDB [crm]> explain SELECT
    ->     COUNT(projectid)
    -> FROM
    ->     vtiger_project
    -> WHERE
    ->     82582 IN (customer , contractor, architect, carpenter)
    ->         AND projectstatus NOT IN ('Supplied' , 'Closed As Complete', 'Closed As Lost')
    ->         AND actual_sale IS NULL
    ->         AND startdate < NOW()
    -> ;
+------+-------------+----------------+------+---------------+------+---------+------+-------+-------------+
| id   | select_type | table          | type | possible_keys | key  | key_len | ref  | rows  | Extra       |
+------+-------------+----------------+------+---------------+------+---------+------+-------+-------------+
|    1 | SIMPLE      | vtiger_project | ALL  | startdate_idx | NULL | NULL    | NULL | 15779 | Using where |
+------+-------------+----------------+------+---------------+------+---------+------+-------+-------------+

Body:
(sqlbot's comment answers the question.)

Further optimization might be available with this composite index:

INDEX(actual_sale, startdate)

But, that would probably work well only actual_sale is not NULL 'too often'.  Otherwise, a full table scan would be better, but the Optimizer might not figure that out.

Many of your columns seen to be excessively large.  Such excesses can lead to performance problems.


问:
Python wildcard in the middle of a string
I have a directory with a number of files which all have the same basic filename format (below is a sample)

```<code>roll_0_oe_2008-03-24_AAA.XNGS
roll_0_oe_2008-03-24_AAB.XNGS
roll_1_oe_2008-03-31_AAC.XNGS
roll_1_oe_2008-03-31_AAG.XNGS
roll_2_oe_2008-04-07_AAR.XNGS
roll_2_oe_2008-04-07_AAJ.XNGS
</code>```

I am trying to select a file based on using:

```<code>filename = 'roll_'+str(roll)'_'*ID
</code>```

where roll is an int that I convert to a string and ID is a string.  I'm using the wildcard * for the _oe_date element as i don't care about this part. I however get the following error:

```<code>TypeError: can't multiply sequence by non-int of type 'str'
</code>```

How can I construct a filename using  wildcard in the middle?

答:
You have to embed the wild card as a character, and make sure that you're file search interface accepts wild cards.

```<code>filename = 'roll_'+str(roll)'_*'+ID
</code>```

However, note that this does not identify a specific file name: to do that, you need a system command (there are several to search and fetch file names).  The Python open function does not accept wild cards.

ContentLicense: CC BY-SA 4.0

Body:
I have a directory with a number of files which all have the same basic filename format (below is a sample)

roll_0_oe_2008-03-24_AAA.XNGS
roll_0_oe_2008-03-24_AAB.XNGS
roll_1_oe_2008-03-31_AAC.XNGS
roll_1_oe_2008-03-31_AAG.XNGS
roll_2_oe_2008-04-07_AAR.XNGS
roll_2_oe_2008-04-07_AAJ.XNGS

I am trying to select a file based on using:

filename = 'roll_'+str(roll)'_'*ID

where roll is an int that I convert to a string and ID is a string.  I'm using the wildcard * for the _oe_date element as i don't care about this part. I however get the following error:

TypeError: can't multiply sequence by non-int of type 'str'

How can I construct a filename using  wildcard in the middle?

Body:
You have to embed the wild card as a character, and make sure that you're file search interface accepts wild cards.

filename = 'roll_'+str(roll)'_*'+ID

However, note that this does not identify a specific file name: to do that, you need a system command (there are several to search and fetch file names).  The Python open function does not accept wild cards.


问:
What is a Pythonic way to remove doubled duplicates in a list but allow triplets/greater?
I have a list in Python

```<code>list1 = [0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1]
</code>```

There are "groupings" of consecutive 1's and 0's. For my purposes, I am only interested in the consecutive 1's. Let's say if there is a solitary 1, e.g.

```<code> ... 0, 0, 1, 0, 0 ...
</code>```

I would like it to be changed into a 0. Similarly, if there are only pairs of 1's, these should become 0s as well. e.g.

```<code>.... 0, 0, 1, 1, 0, 0...
</code>```

should become

```<code>.... 0, 0, 0, 0, 0, 0...
</code>```

But "triplets" of consecutive ones or higher are ok.

I considered keeping track of the counts of 1s via a dictionary, but this feels too complex. The idea would be to iterate through the list, keeping track of the count of consecutive 1s in a list. But, how do you "go back" and switch the 1s to 0s?

```<code>counter_list = []
for i in list1:
    if i == 1:
        counter_list = counter_list + 1
            if len(counter_list)==1 or len(counter_list)==2:
                # now I don't know how to "go back" to change these elements into 0s
</code>```

Body:
I have a list in Python

list1 = [0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1]

There are "groupings" of consecutive 1's and 0's. For my purposes, I am only interested in the consecutive 1's. Let's say if there is a solitary 1, e.g.

 ... 0, 0, 1, 0, 0 ...

I would like it to be changed into a 0. Similarly, if there are only pairs of 1's, these should become 0s as well. e.g.

.... 0, 0, 1, 1, 0, 0...

should become

.... 0, 0, 0, 0, 0, 0...

But "triplets" of consecutive ones or higher are ok.

I considered keeping track of the counts of 1s via a dictionary, but this feels too complex. The idea would be to iterate through the list, keeping track of the count of consecutive 1s in a list. But, how do you "go back" and switch the 1s to 0s?

counter_list = []
for i in list1:
    if i == 1:
        counter_list = counter_list + 1
            if len(counter_list)==1 or len(counter_list)==2:
                # now I don't know how to "go back" to change these elements into 0s

Body:
You could turn it into a string and use a regular expression to substitute short runs of '1' with equivalent runs of '0', then turn it back into a list:

>>> import re
>>> list1 = [0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1]
>>> ''.join(map(str, list1))
'0001110011000111111'
>>> re.sub(r'(?<!1)1{,2}(?!1)', lambda x: len(x.group())*'0', _)
'0001110000000111111'
>>> list(map(int, _))
[0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]


问:
Is it possible to get Windows 10 style buttons in Tkinter? (Python 3.5.2)
I have a small Python GUI that is simply a smaller and less advanced version of Microsoft's Notepad. It allows the loading and saving of files and such, and a few other basic menu options such as exiting.

Tkinter works generally well for creating such programs, but I would like to know whether it is possible to use the much nicer looking Windows 10 buttons than to be stuck with the rather ugly looking Tkinter ones. (see difference below, Tkinter is the top picture, Windows is the lower one).

I know it's a bit of an obscure problem, but if anyone knows whether this is possible I'd be very pleased. Nothing makes me happier than a clean looking program :) I have my doubts though...

Below is the code used for my current buttons (I am aware of how awkward .place is, but it works for me at the minute) :)

```<code>yes = Button(confirmation, text = "Yes", command = ProgramTerminate, width = 5, height = 1)
yes.place(x = 100, y = 25)

no = Button(confirmation, text = "No", command = confirmation.destroy, width = 5, height = 1)
no.place(x = 150, y = 25)
</code>```

答:
No. You can get at windows 7ish look by using ttk:

```<code>from tkinter import ttk
yes = ttk.Button(confirmation, text = "Yes", command = ProgramTerminate, width = 5, height = 1)
</code>```

However, I see you are making a yes / no message box. You can call the system's version of that using messagebox.askyesno:

```<code>from tkinter import messagebox

response = messagebox.askyesno("Really Quit?", "Are you sure you want to quit?")
if response:
   ProgramTerminate()
</code>```

Body:
I have a small Python GUI that is simply a smaller and less advanced version of Microsoft's Notepad. It allows the loading and saving of files and such, and a few other basic menu options such as exiting.

Tkinter works generally well for creating such programs, but I would like to know whether it is possible to use the much nicer looking Windows 10 buttons than to be stuck with the rather ugly looking Tkinter ones. (see difference below, Tkinter is the top picture, Windows is the lower one).

I know it's a bit of an obscure problem, but if anyone knows whether this is possible I'd be very pleased. Nothing makes me happier than a clean looking program :) I have my doubts though...

Below is the code used for my current buttons (I am aware of how awkward .place is, but it works for me at the minute) :)

yes = Button(confirmation, text = "Yes", command = ProgramTerminate, width = 5, height = 1)
yes.place(x = 100, y = 25)

no = Button(confirmation, text = "No", command = confirmation.destroy, width = 5, height = 1)
no.place(x = 150, y = 25)

Body:
No. You can get at windows 7ish look by using ttk:

from tkinter import ttk
yes = ttk.Button(confirmation, text = "Yes", command = ProgramTerminate, width = 5, height = 1)

However, I see you are making a yes / no message box. You can call the system's version of that using messagebox.askyesno:

from tkinter import messagebox

response = messagebox.askyesno("Really Quit?", "Are you sure you want to quit?")
if response:
   ProgramTerminate()


答:
You'd need to use a pipe, that way you can actually write to that pipe an answer, don't forget to close the pipe once you're done with it.

```<code>p = os.popen("myCmd -s {0}".format(item), "w")
p.write("y\n")
</code>```

popen documentation

Title: Auto input answer for a terminal command within python script

Body:
I made a python script in which it runs a specified terminal command.

def main(my_list):
    for item in my_list:
        os.system("myCmd -s {0}".format(item))

    item_list = ['itemA', 'itemB', 'itemC']
    main(item_list)

As the terminal command I am trying to use does not accepts a list in the -s argument, which is the reason that I make it into a python script.
While running the script, it works but I notice that it will prompts me with the following question:
Are you sure you want to continue (y/n)?

This means I will need to punch in the y on my keyboard, 3 times in the above example.
But in the event if my list is huge, and should I not be on my desk, is there any way that I can script to make it accept 'y' as my answer, without me to press anything on the keyboard?

Body:
You'd need to use a pipe, that way you can actually write to that pipe an answer, don't forget to close the pipe once you're done with it.

p = os.popen("myCmd -s {0}".format(item), "w")
p.write("y\n")

popen documentation


问:
Build errors when multi-targeting in csproj file
I'm trying to build a class library that multi-targets both .NET 4.5.1 and .NET Standard 1.3. According to the documentation, I should be able to do this:

```<code><PropertyGroup>
  <TargetFrameworks>net451;netstandard1.3</TargetFrameworks>
</PropertyGroup>
</code>```

However, when I try to build, I get these odd errors:

Cannot infer TargetFrameworkIdentifier and/or TargetFrameworkVersion from TargetFramework='net451'. They must be specified explicitly.

MSB3645   .NET Framework v3.5 Service Pack 1 was not found. In order to target ".NETFramework,Version=v1.3", .NET Framework v3.5 Service Pack 1 or later must be installed.

MSB3644   The reference assemblies for framework ".NETFramework,Version=v1.3" were not found. To resolve this, install the SDK or Targeting Pack for this framework version or retarget your application to a version of the framework for which you have the SDK or Targeting Pack installed. Note that assemblies will be resolved from the Global Assembly Cache (GAC) and will be used in place of reference assemblies. Therefore your assembly may not be correctly targeted for the framework you intend.

If I specify the target framework identifiers manually, it builds fine:

```<code><PropertyGroup>
  <TargetFrameworks>net451;netstandard1.3</TargetFrameworks>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)' == 'net451'">
  <TargetFrameworkIdentifier>.NETFramework</TargetFrameworkIdentifier>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)' == 'netstandard1.3'">
  <TargetFrameworkIdentifier>.NETStandard</TargetFrameworkIdentifier>
</PropertyGroup>
</code>```

I'm using Visual Studio 2017 Community. Am I doing something wrong here?

答:
Have you definitely written

<TargetFrameworks>net451;netstandard1.3</TargetFrameworks>

and not

<TargetFramework>net451;netstandard1.3</TargetFramework>

?

I was getting the same error until I added the missing s

Body:
I'm trying to build a class library that multi-targets both .NET 4.5.1 and .NET Standard 1.3. According to the documentation, I should be able to do this:

<PropertyGroup>
  <TargetFrameworks>net451;netstandard1.3</TargetFrameworks>
</PropertyGroup>

However, when I try to build, I get these odd errors:

Cannot infer TargetFrameworkIdentifier and/or TargetFrameworkVersion from TargetFramework='net451'. They must be specified explicitly.

MSB3645   .NET Framework v3.5 Service Pack 1 was not found. In order to target ".NETFramework,Version=v1.3", .NET Framework v3.5 Service Pack 1 or later must be installed.

MSB3644   The reference assemblies for framework ".NETFramework,Version=v1.3" were not found. To resolve this, install the SDK or Targeting Pack for this framework version or retarget your application to a version of the framework for which you have the SDK or Targeting Pack installed. Note that assemblies will be resolved from the Global Assembly Cache (GAC) and will be used in place of reference assemblies. Therefore your assembly may not be correctly targeted for the framework you intend.

If I specify the target framework identifiers manually, it builds fine:

<PropertyGroup>
  <TargetFrameworks>net451;netstandard1.3</TargetFrameworks>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)' == 'net451'">
  <TargetFrameworkIdentifier>.NETFramework</TargetFrameworkIdentifier>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)' == 'netstandard1.3'">
  <TargetFrameworkIdentifier>.NETStandard</TargetFrameworkIdentifier>
</PropertyGroup>

I'm using Visual Studio 2017 Community. Am I doing something wrong here?


问:
Keep some lines of code private in a public GitHub repository
I am currently developing a kind of small web-application which I would like to put on GitHub in a public repository. I want to do this to make it open source but I would also like to use the advantages of git while developing it. Now since I am using PHP and MySQL to develop it I sometimes have a line in my code where I create a new object of the class $PDO in which I also have to write my username and password for my MySQL database. Now I would like to know if there is a way to still upload my scripts to GitHub and to also use Git while keeping those lines private.
Have a nice day.</p>

答:
Place your credentials in a separate file and add this file to .gitignore

See https://git-scm.com/docs/gitignore


问:
Cognitive Service Recommendation API Create/Trigger Build
I have uploaded both catalog and usage data in model.But when creating buil d using Create/Trigger build API.Its causing following error:

{
  "error": {
    "code": "BadArgument",
    "message": "(EXT-0108) Passed argument is invalid.",
    "innerError": {
      "code": "EXT-0131",
      "message": "Model newmodel does not have any usage data."
    }
  }
}

Please help.

答:
I got the same error for several days and I was able to visualize two important aspects in the use of this api.

Currently the preview is enabled for Dynamics CRM that are created in the United States.

When generating the versions, they will take the records of the selected entities that are in an end state (for example the opportunities marked as won). There must be a range of records that meet the number of products in dynamics CRM, for example if there are 30 Products, there must be Quotes, Orders and offers that combine these 30 products as these systems are trained with historical data to be able to predict. If in your case you are trying to perform a spike of functionality, I recommend that you mark several of your products as unpublished and try to make as many offers, orders and quotes depending on your case that covers the largest quantity of products.


问:
WordPress Custom Post Type Hierarchy
I use the custom post type "events". I make a custom page template page-events.php.

I make a page "Events" (slug events) as archive page.
Select "Events" as page template.

Nothing will show, but when I switch over to default page template insteed of "Events" everythings works fine.

The WP body class shows events-template-default single single-events

So, I don't really why?

My settings:

page-events.php

```<code><?php
/*
Template Name: Events
*/
?>
...

<?php
$args = array(
    'post_type'              => array( 'events' ),
    'posts_per_page'         => '-1',
    'order' => 'ASC'
);

$news_query = new WP_Query( $args );
if ( $news_query->have_posts() ) : ?>

    <?php while ( $news_query->have_posts() ) : ?>
    <?php $news_query->the_post(); ?>

...

<?php endwhile; endif; wp_reset_postdata(); ?>
</code>```

functions.php

```<code><?php

// Register Custom Post Type "Events"
function cpt_events() {
    $labels = array(
        'name'                => _x( 'Events', 'Post Type General Name', 'theme_mmm' ),
        'singular_name'       => _x( 'Events', 'Post Type Singular Name', 'theme_mmm' ),
        'menu_name'           => __( 'Events', 'theme_mmm' ),
        'name_admin_bar'      => __( 'Events', 'theme_mmm' ),
        'parent_item_colon'   => __( 'Events:', 'theme_mmm' ),
        'all_items'           => __( 'Alle Events', 'theme_mmm' ),
        'add_new_item'        => __( 'Event hinzufügen', 'theme_mmm' ),
        'add_new'             => __( 'Event hinzufügen', 'theme_mmm' ),
        'new_item'            => __( 'Event hinzufügen', 'theme_mmm' ),
        'edit_item'           => __( 'Event bearbeiten', 'theme_mmm' ),
        'update_item'         => __( 'Aktualisieren', 'theme_mmm' ),
        'view_item'           => __( 'Events ansehen', 'theme_mmm' ),
        'search_items'        => __( 'Suchen', 'theme_mmm' ),
        'not_found'           => __( 'Keine Treffer', 'theme_mmm' ),
        'not_found_in_trash'  => __( 'Keine Treffer', 'theme_mmm' ),
    );

    $args = array(
        'label'               => __( 'Events', 'theme_mmm' ),
        'description'         => __( 'Beschreibung', 'theme_mmm' ),
        'labels'              => $labels,
        'supports'            => array( 'title', 'editor' ),
        'taxonomies'          => array(''),
        'hierarchical'        => false,
        'public'              => true,
        'show_ui'             => true,
        'show_in_menu'        => true,
        'menu_icon'           => 'dashicons-calendar-alt',
        'menu_position'       => 5,
        'show_in_admin_bar'   => true,
        'show_in_nav_menus'   => true,
        'can_export'          => true,
        'has_archive'         => false,
        'exclude_from_search' => false,
        'publicly_queryable'  => true,
        'rewrite'             => true,
        'capability_type'     => 'page',
    );
    register_post_type( 'events', $args );

}
add_action( 'init', 'cpt_events', 0 );

?>
</code>```

答:
If you're trying to make an archive page for your post type events, copy stock archive.php of your theme, rename it to archive-events.php and modify it from there to suit your needs.

If you're trying to make a template for a single page of events post type, copy stock single of your theme, rename it to single-events.php and modify it from there.

P.S. You've name your post type events. It's usually a good practice to use singular form instead of plural one, so event in your case

Refer to this image to see how Wordpress selects correct template and this page for hierarchy related information.

Title: WordPress Custom Post Type Hierarchy

Body:
I use the custom post type "events". I make a custom page template page-events.php.

I make a page "Events" (slug events) as archive page.
Select "Events" as page template.

Nothing will show, but when I switch over to default page template insteed of "Events" everythings works fine.

The WP body class shows events-template-default single single-events

So, I don't really why?

My settings:

page-events.php

<?php
/*
Template Name: Events
*/
?>
...

<?php
$args = array(
    'post_type'              => array( 'events' ),
    'posts_per_page'         => '-1',
    'order' => 'ASC'
);

$news_query = new WP_Query( $args );
if ( $news_query->have_posts() ) : ?>

    <?php while ( $news_query->have_posts() ) : ?>
    <?php $news_query->the_post(); ?>

...

<?php endwhile; endif; wp_reset_postdata(); ?>

functions.php

<?php

// Register Custom Post Type "Events"
function cpt_events() {
    $labels = array(
        'name'                => _x( 'Events', 'Post Type General Name', 'theme_mmm' ),
        'singular_name'       => _x( 'Events', 'Post Type Singular Name', 'theme_mmm' ),
        'menu_name'           => __( 'Events', 'theme_mmm' ),
        'name_admin_bar'      => __( 'Events', 'theme_mmm' ),
        'parent_item_colon'   => __( 'Events:', 'theme_mmm' ),
        'all_items'           => __( 'Alle Events', 'theme_mmm' ),
        'add_new_item'        => __( 'Event hinzufügen', 'theme_mmm' ),
        'add_new'             => __( 'Event hinzufügen', 'theme_mmm' ),
        'new_item'            => __( 'Event hinzufügen', 'theme_mmm' ),
        'edit_item'           => __( 'Event bearbeiten', 'theme_mmm' ),
        'update_item'         => __( 'Aktualisieren', 'theme_mmm' ),
        'view_item'           => __( 'Events ansehen', 'theme_mmm' ),
        'search_items'        => __( 'Suchen', 'theme_mmm' ),
        'not_found'           => __( 'Keine Treffer', 'theme_mmm' ),
        'not_found_in_trash'  => __( 'Keine Treffer', 'theme_mmm' ),
    );

    $args = array(
        'label'               => __( 'Events', 'theme_mmm' ),
        'description'         => __( 'Beschreibung', 'theme_mmm' ),
        'labels'              => $labels,
        'supports'            => array( 'title', 'editor' ),
        'taxonomies'          => array(''),
        'hierarchical'        => false,
        'public'              => true,
        'show_ui'             => true,
        'show_in_menu'        => true,
        'menu_icon'           => 'dashicons-calendar-alt',
        'menu_position'       => 5,
        'show_in_admin_bar'   => true,
        'show_in_nav_menus'   => true,
        'can_export'          => true,
        'has_archive'         => false,
        'exclude_from_search' => false,
        'publicly_queryable'  => true,
        'rewrite'             => true,
        'capability_type'     => 'page',
    );
    register_post_type( 'events', $args );

}
add_action( 'init', 'cpt_events', 0 );

?>


问:
How to split a sequence in F# based on another sequence in an idiomatic way
I have, in F#, 2 sequences, each containing distinct integers, strictly in ascending order: listMaxes and numbers.

If not Seq.isEmpty numbers, then it is guaranteed that not Seq.isEmpty listMaxes and Seq.last listMaxes >= Seq.last numbers.

I would like to implement in F# a function that returns a list of list of integers, whose List.length equals Seq.length listMaxes, containing the elements of numbers divided in lists, where the elements of listMaxes limit each group.

For example: called with the arguments

```<code>listMaxes = seq [ 25; 56; 65; 75; 88 ]
numbers = seq [ 10; 11; 13; 16; 20; 25; 31; 38; 46; 55; 65; 76; 88 ]
</code>```

this function should return

```<code>[ [10; 11; 13; 16; 20; 25]; [31; 38; 46; 55]; [65]; List.empty; [76; 88] ]
</code>```

I can implement this function, iterating over numbers only once:

```<code>let groupByListMaxes listMaxes numbers =
    if Seq.isEmpty numbers then
        List.replicate (Seq.length listMaxes) List.empty
    else
        List.ofSeq (seq {
            use nbe = numbers.GetEnumerator ()
            ignore (nbe.MoveNext ())
            for lmax in listMaxes do
                yield List.ofSeq (seq {
                    if nbe.Current <= lmax then
                        yield nbe.Current
                    while nbe.MoveNext () && nbe.Current <= lmax do
                        yield nbe.Current
                })
        })
</code>```

But this code feels unclean, ugly, imperative, and very un-F#-y.

Is there any functional / F#-idiomatic way to achieve this?

答:
I have found a better implementation myself. Tips for improvements are still welcome.

Dealing with 2 sequences is really a pain. And I really do want to iterate over numbers only once without turning that sequence into a list. But then I realized that turning listMaxes (generally the shorter of the sequences) is less costly. That way only 1 sequence remains, and I can use Seq.fold over numbers.

What should be the state that we want to keep and change while iterating with Seq.fold over numbers? First, it should definitely include the remaining of the listMaxes, yet the previous maxes that we already have surpassed are no longer of interest. Second, the accumulated lists so far, although, like in the other answers, these can be kept in reverse order. More to the point: the state is a couple which has as second element a reversed list of reversed lists of the numbers so far.

```<code>let groupByListMaxes listMaxes numbers =
    let rec folder state number =
        match state with
            | m :: maxes, _ when number > m ->
                folder (maxes, List.empty :: snd state) number
            | m :: maxes, [] ->
                fst state, List.singleton (List.singleton number)
            | m :: maxes, h :: t ->
                fst state, (number :: h) :: t
            | [], _ ->
                failwith "Guaranteed not to happen"
    let listMaxesList = List.ofSeq listMaxes
    let initialState = listMaxesList, List.empty
    let reversed = snd (Seq.fold folder initialState numbers)
    let temp = List.rev (List.map List.rev reversed)
    let extraLength = List.length listMaxesList - List.length temp
    let extra = List.replicate extraLength List.empty
    List.concat [temp; extra]
</code>```

Body:
I have, in F#, 2 sequences, each containing distinct integers, strictly in ascending order: listMaxes and numbers.

If not Seq.isEmpty numbers, then it is guaranteed that not Seq.isEmpty listMaxes and Seq.last listMaxes >= Seq.last numbers.

I would like to implement in F# a function that returns a list of list of integers, whose List.length equals Seq.length listMaxes, containing the elements of numbers divided in lists, where the elements of listMaxes limit each group.

For example: called with the arguments

listMaxes = seq [ 25; 56; 65; 75; 88 ]
numbers = seq [ 10; 11; 13; 16; 20; 25; 31; 38; 46; 55; 65; 76; 88 ]

this function should return

[ [10; 11; 13; 16; 20; 25]; [31; 38; 46; 55]; [65]; List.empty; [76; 88] ]

I can implement this function, iterating over numbers only once:

let groupByListMaxes listMaxes numbers =
    if Seq.isEmpty numbers then
        List.replicate (Seq.length listMaxes) List.empty
    else
        List.ofSeq (seq {
            use nbe = numbers.GetEnumerator ()
            ignore (nbe.MoveNext ())
            for lmax in listMaxes do
                yield List.ofSeq (seq {
                    if nbe.Current <= lmax then
                        yield nbe.Current
                    while nbe.MoveNext () && nbe.Current <= lmax do
                        yield nbe.Current
                })
        })

But this code feels unclean, ugly, imperative, and very un-F#-y.

Is there any functional / F#-idiomatic way to achieve this?

Body:
I have found a better implementation myself. Tips for improvements are still welcome.

Dealing with 2 sequences is really a pain. And I really do want to iterate over numbers only once without turning that sequence into a list. But then I realized that turning listMaxes (generally the shorter of the sequences) is less costly. That way only 1 sequence remains, and I can use Seq.fold over numbers.

What should be the state that we want to keep and change while iterating with Seq.fold over numbers? First, it should definitely include the remaining of the listMaxes, yet the previous maxes that we already have surpassed are no longer of interest. Second, the accumulated lists so far, although, like in the other answers, these can be kept in reverse order. More to the point: the state is a couple which has as second element a reversed list of reversed lists of the numbers so far.

let groupByListMaxes listMaxes numbers =
    let rec folder state number =
        match state with
            | m :: maxes, _ when number > m ->
                folder (maxes, List.empty :: snd state) number
            | m :: maxes, [] ->
                fst state, List.singleton (List.singleton number)
            | m :: maxes, h :: t ->
                fst state, (number :: h) :: t
            | [], _ ->
                failwith "Guaranteed not to happen"
    let listMaxesList = List.ofSeq listMaxes
    let initialState = listMaxesList, List.empty
    let reversed = snd (Seq.fold folder initialState numbers)
    let temp = List.rev (List.map List.rev reversed)
    let extraLength = List.length listMaxesList - List.length temp
    let extra = List.replicate extraLength List.empty
    List.concat [temp; extra]


问:
Find on remote and rsync find results to a local directory
```<code>ssh user@remote find /var/ -type f -name \*option\*  -print0 | xargs -J d11:% -0 rsync -aP % oo/.
</code>```

As you can see, i am running find on remote, getting the list of files, and now i am trying to copy them over; the second part of my command, after the pipeline seems incorrect.

答:
Your command seems off a bit. The -J and d11:% options I can't find a reference for plus your rsync cmd needs a destination. Here is my attempt at your command.

"ssh user@remote find /folder/ -type f -name 'option' -print0 | xargs -0 -I% rsync -aP % dest_machine:/path"

Body:
ssh user@remote find /var/ -type f -name \*option\*  -print0 | xargs -J d11:% -0 rsync -aP % oo/.

As you can see, i am running find on remote, getting the list of files, and now i am trying to copy them over; the second part of my command, after the pipeline seems incorrect.


答:
You can use

```<code>import os
os.path.isfile(fname)
</code>```

If your plot exists, you know that a file called

```<code>root + 'plot.png'
</code>```

must be in your current directory.
You can thus add that to your if-sentence:

```<code>if name.startswith('XY') and name.endswith('.txt') and not os.path.isfile(root + 'plot.png'):
</code>```

If you want to break out of your for-loops use the keyword

```<code>break
</code>```

Title: Plot generation: stop for-loop if plot already exists

Body:
I'm using python and matplotlib to generate plots from a fairly large database of XY data (~1000 folder and growing). Every folder holds a single CSV file containing XY data that I want to generate a scatter plot of.
Since more data folders are periodically added to the root folder, I want to periodically run my script to keep the plots updated. Unfortunately this script now runs for ~10 minutes and I foresee that it will keep running longer and longer.

I would like to speed up the script by adding something to my code that skips searching the present folder for XY data if a .png file is present in the folder. What should I amend on the code below to reflect that?

import os
import matplotlib.pyplot as plt

# Find files containing XY data
for root, dirs, files in os.walk('D:/temp\\', topdown=False):
    for name in files:
       #find and check txt file
        if name.startswith('XY') and name.endswith('.txt'):
            # read data and store lines in list
            try:
                posX = list() #list of x-positions
                posY = list() #list of y-positions
                filepath = os.path.join(root, name)
                fp = open(filepath)
                for line in fp:
                    # make lists from the csv rows
                    content = line.split()
                    posX.append(float(content[0]))
                    posY.append(float(content[1]))
                fp.close()
                # prepare a scatter plot
                figure = plt.scatter(posX,posY)
                # save plot as png
                plt.savefig(root+'plot.png')
                # clear plot data for next for loop iteration
                plt.clf()

Update:
using below answer I update the if statement inside the second for loop:

#find and check txt file
    if name.startswith('XY') and name.endswith('.txt') and not os.path.isfile(root+'plot.png'):
(...)
    else:
        print('no new data available')

Body:
You can use

import os
os.path.isfile(fname)

If your plot exists, you know that a file called

root + 'plot.png'

must be in your current directory.
You can thus add that to your if-sentence:

if name.startswith('XY') and name.endswith('.txt') and not os.path.isfile(root + 'plot.png'):

If you want to break out of your for-loops use the keyword

break


问:
How to get progress on BQ file load
When importing a large csv (or other type) file to BigQuery, how can we get the progress of the import? For example, if we have a 1TB file and use the import csv command, I don't just want to wait there ten hours for the file to import. How can we get the progress, or is this not possible?

https://cloud.google.com/bigquery/loading-data

Right now, we're not able to get it until the csv file has been loaded

Regarding progress bar:

Load Task specific statistics is never returned while task is in progress. Statistics only contain start/end time and Java API parses it into CopyStatistics class instead.

```<code>{
 "kind": "bigquery#job",
 "etag": "\"smpMas70-D1-zV2oEH0ud6qY21c/crKHebm6x2NXA6pCjE8znB7dp-E\"",
 "id": "YYY:job_l9TWVQ64YjKx7BgDufu2gReMEL0",
 "selfLink": "https://www.googleapis.com/bigquery/v2/projects/YYY/jobs/job_l9TWVQ64YjKx7BgDufu2gReMEL0",
 "jobReference": {
  "projectId": "YYY",
  "jobId": "job_l9TWVQ64YjKx7BgDufu2gReMEL0"
 },
 "configuration": {
  "load": {
   "sourceUris": [
    "gs://datadocs/afdfb50f-cbc2-47d4-985e-080cadefc963"
   ],
   "schema": {
    "fields": [
       ...
    ]
   },
   "destinationTable": {
    "projectId": "YYY",
    "datasetId": "1aaf1682dbc2403e92a0a0ed8534581f",
    "tableId": "ORIGIN"
   },
   "createDisposition": "CREATE_IF_NEEDED",
   "writeDisposition": "WRITE_EMPTY",
   "fieldDelimiter": ",",
   "skipLeadingRows": 1,
   "quote": "\"",
   "maxBadRecords": 1000,
   "allowQuotedNewlines": true,
   "sourceFormat": "CSV"
  }
 },
 "status": {
  "state": "RUNNING"
 },
 "statistics": {
  "creationTime": "1490868448431",
  "startTime": "1490868449147"
 },
 "user_email": "YYY@appspot.gserviceaccount.com"
}
</code>```

Load statistics is only returned in the end, when whole CSV file has been imported.

How do we get the progress while it's being uploaded?

答:
Check out statistics.load.outputBytes

Per documentation - while a load job is in the running state, this
  value may change

You can experiment with it - if this can be used as progress metric via call to Jobs: get

Title: How to get progress on BQ file load

Body:
When importing a large csv (or other type) file to BigQuery, how can we get the progress of the import? For example, if we have a 1TB file and use the import csv command, I don't just want to wait there ten hours for the file to import. How can we get the progress, or is this not possible?

https://cloud.google.com/bigquery/loading-data

Right now, we're not able to get it until the csv file has been loaded

Regarding progress bar:

Load Task specific statistics is never returned while task is in progress. Statistics only contain start/end time and Java API parses it into CopyStatistics class instead.

{
 "kind": "bigquery#job",
 "etag": "\"smpMas70-D1-zV2oEH0ud6qY21c/crKHebm6x2NXA6pCjE8znB7dp-E\"",
 "id": "YYY:job_l9TWVQ64YjKx7BgDufu2gReMEL0",
 "selfLink": "https://www.googleapis.com/bigquery/v2/projects/YYY/jobs/job_l9TWVQ64YjKx7BgDufu2gReMEL0",
 "jobReference": {
  "projectId": "YYY",
  "jobId": "job_l9TWVQ64YjKx7BgDufu2gReMEL0"
 },
 "configuration": {
  "load": {
   "sourceUris": [
    "gs://datadocs/afdfb50f-cbc2-47d4-985e-080cadefc963"
   ],
   "schema": {
    "fields": [
       ...
    ]
   },
   "destinationTable": {
    "projectId": "YYY",
    "datasetId": "1aaf1682dbc2403e92a0a0ed8534581f",
    "tableId": "ORIGIN"
   },
   "createDisposition": "CREATE_IF_NEEDED",
   "writeDisposition": "WRITE_EMPTY",
   "fieldDelimiter": ",",
   "skipLeadingRows": 1,
   "quote": "\"",
   "maxBadRecords": 1000,
   "allowQuotedNewlines": true,
   "sourceFormat": "CSV"
  }
 },
 "status": {
  "state": "RUNNING"
 },
 "statistics": {
  "creationTime": "1490868448431",
  "startTime": "1490868449147"
 },
 "user_email": "YYY@appspot.gserviceaccount.com"
}

Load statistics is only returned in the end, when whole CSV file has been imported.

How do we get the progress while it's being uploaded?


问:
select related to max field
I have 3 tables: laptop, pc, printer with model and price fields.

I need to get max price among all products in these all tables.

I did union to get max price & model field for each table:

```<code>SELECT model,price
FROM  (SELECT model, price
       FROM pc
       WHERE price = (SELECT MAX(price) FROM pc)
       UNION
       SELECT model, price
       FROM laptop
       WHERE price = (SELECT MAX(price) FROM laptop)
       UNION
       SELECT model, price
       FROM printer WHERE price = (SELECT MAX(price) FROM printer)
      ) AS X
</code>```

As a result of this, I received

model   |   price

```<code> 1233  | 980.0000
 1276  | 400.0000
 1288  | 400.0000
 1750  | 1200.0000
</code>```

And now I'm stuck getting only model (in this case it will be '1750') with max price.

答:
How about using order by and top?

```<code>SELECT TOP 1 model, price
FROM  (SELECT model, price
       FROM pc
       UNION ALL
       SELECT model, price
       FROM laptop
       UNION ALL
       SELECT model, price
       FROM printer
      ) t
ORDER BY price DESC;
</code>```

Note:  If you have indexes, this is probably not the most efficient way to get the information you want.  You would need to provide more information about the design of the tables and their data if performance is an issue.

Title: select related to max field

Body:
I have 3 tables: laptop, pc, printer with model and price fields.

I need to get max price among all products in these all tables.

I did union to get max price & model field for each table:

SELECT model,price
FROM  (SELECT model, price
       FROM pc
       WHERE price = (SELECT MAX(price) FROM pc)
       UNION
       SELECT model, price
       FROM laptop
       WHERE price = (SELECT MAX(price) FROM laptop)
       UNION
       SELECT model, price
       FROM printer WHERE price = (SELECT MAX(price) FROM printer)
      ) AS X

As a result of this, I received

model   |   price

 1233  | 980.0000
 1276  | 400.0000
 1288  | 400.0000
 1750  | 1200.0000

And now I'm stuck getting only model (in this case it will be '1750') with max price.

Body:
How about using order by and top?

SELECT TOP 1 model, price
FROM  (SELECT model, price
       FROM pc
       UNION ALL
       SELECT model, price
       FROM laptop
       UNION ALL
       SELECT model, price
       FROM printer
      ) t
ORDER BY price DESC;

Note:  If you have indexes, this is probably not the most efficient way to get the information you want.  You would need to provide more information about the design of the tables and their data if performance is an issue.


问:
Version of the C++ compiler on a Linux distro
On a Linux distribution, is there a way to find out the version of the c++ compiler.
I tried running the following commands: </p>

```<code>./opt/intel/bin/iccvars.sh intel64

icc -v
</code>```

<p>but on issuing the first command it returned no such file or directory. </p>

答:
If you are using the gcc:

```<code>gcc --version
</code>```

the above command should work.

If using g++ (for C++11 standard):

```<code>g++ --version
</code>```

You can take a look at this for more information: https://gcc.gnu.org/projects/cxx-status.html#cxx11

Body:
On a Linux distribution, is there a way to find out the version of the c++ compiler.
I tried running the following commands:

./opt/intel/bin/iccvars.sh intel64

icc -v

but on issuing the first command it returned no such file or directory.

Body:
If you are using the gcc:

gcc --version

the above command should work.

If using g++ (for C++11 standard):

g++ --version

You can take a look at this for more information: https://gcc.gnu.org/projects/cxx-status.html#cxx11


问:
How do I dynamically access a property inside an angularjs directive?
I have a directive when given an array it creates check boxes for that list of items using the Name as the label for the checkbox.

Html

```<code><div>
<a style="float:right; margin-bottom: 5px;" ng-click="selectNone()" href="#">Select None</a>
<a style="float:right; margin-bottom: 5px;margin-left: 10px" ng-click="selectAll()" href="#">Select All</a>

<div class="cleared"></div>

<div class="form-input form-list">
    <label ng-repeat="item in valuelist | orderBy:'Name'">
        <input type="checkbox" checklist-model="model" checklist-value="item" /> {{item.Name}}<br />
    </label>
</div>
</code>```

JS

```<code>    'use strict';

growllApp.directive('checkboxlist', [function () {
    return {
        restrict: 'E',
        templateUrl: 'scripts/modules/checkboxlist.template.html',
        controller: 'checkboxlistController',
        scope: {
            model: "=",
            value: "=",
            valuelist: "="
        }
    }
}]);

growllApp.controller('checkboxlistController', ['$scope', '$routeParams', '$location', '$cookieStore', function ($scope, $routeParams, $location, $cookieStore) {
    $scope.selectAll = function () {
        $scope.model = angular.copy($scope.valuelist);
    };

    $scope.selectNone = function () {
        $scope.model = [];
    };
}]);
</code>```

Using the directive

```<code><checkboxlist ng-show="applyToProducts" model="coupon.Products" value="Name" valuelist="productsList"></checkboxlist>
</code>```

All this works fine in most scenarios.  However, I have a scenario where the array I'm passing in has objects in it that do not have the property "Name" but instead have the property "Title".

How do I use the attribute I have in the directive called "value" for the part that determines the label.

So in the directive html instead of saying {{item.Name}} how can I specify {{item.Title}} by passing in that the property name is title in certain cases?

答:
You could try using a ternary operator:

```<code>{{ item.Name ? item.Name : item.Title }}
</code>```

You would probably need to use a custom comparator for the orderBy then.

Body:
I have a directive when given an array it creates check boxes for that list of items using the Name as the label for the checkbox.

Html

Select None
Select All

        <input type="checkbox" checklist-model="model" checklist-value="item" /> {{item.Name}}

JS

    'use strict';

growllApp.directive('checkboxlist', [function () {
    return {
        restrict: 'E',
        templateUrl: 'scripts/modules/checkboxlist.template.html',
        controller: 'checkboxlistController',
        scope: {
            model: "=",
            value: "=",
            valuelist: "="
        }
    }
}]);

growllApp.controller('checkboxlistController', ['$scope', '$routeParams', '$location', '$cookieStore', function ($scope, $routeParams, $location, $cookieStore) {
    $scope.selectAll = function () {
        $scope.model = angular.copy($scope.valuelist);
    };

    $scope.selectNone = function () {
        $scope.model = [];
    };
}]);

Using the directive

<checkboxlist ng-show="applyToProducts" model="coupon.Products" value="Name" valuelist="productsList"></checkboxlist>

All this works fine in most scenarios.  However, I have a scenario where the array I'm passing in has objects in it that do not have the property "Name" but instead have the property "Title".

How do I use the attribute I have in the directive called "value" for the part that determines the label.

So in the directive html instead of saying {{item.Name}} how can I specify {{item.Title}} by passing in that the property name is title in certain cases?

Body:
You could try using a ternary operator:

{{ item.Name ? item.Name : item.Title }}

You would probably need to use a custom comparator for the orderBy then.


问:
Generate random string/characters in JavaScript
I want a 5 character string composed of characters picked randomly from the set [a-zA-Z0-9].

What's the best way to do this with JavaScript?

答: I use var randId = 'rand' + new Date().getTime();


问:
What's jQuery’s Data Method? How & Why is it used?
What's jQuery’s Data Method? How & Why is it used?</p>

答:
jQuery’s data method gives us the ability to associate arbitrary data with DOM nodes and JavaScript objects. This makes our code more concise and clean. As of jQuery 1.4.3 we also have the ability to use the method on regular JavaScript objects and listen for changes, which opens the doors to some quite interesting applications.

Check out the complete blog post here: jQuery's Data Method

ContentLicense: CC BY-SA 2.5


问:
Calling a webservice in camel having the soap request as String
I want to call a Web Service using Apache Camel and I have the SOAP message in the form of String. Can anyone kindly let me know how to send SOAP request in form of String in Camel?</p>

答:
Here is a simple example. If you need to perform some modifications of SOAP request string you can just change "constant" to something like "spel"</p>

```<code><setBody><constant><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header/>
<soapenv:Body>
  <MyAction>
     <myparam>ABC</myparam>
  </MyAction>
</soapenv:Body>
</soapenv:Envelope>]]></constant></setBody>
<setHeader headerName="SOAPAction"><constant>MySOAPAction</constant></setHeader>
<setHeader headerName="CamelHttpMethod"><constant>POST</constant></setHeader>
<setHeader headerName="Content-Type"><constant>text/xml;charset=UTF-8</constant></setHeader>
<to uri="http://myserver:1234" />
</code>```

Body:
Here is a simple example. If you need to perform some modifications of SOAP request string you can just change "constant" to something like "spel"

<setBody><constant><![CDATA[<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header/>
<soapenv:Body>
  <MyAction>
     <myparam>ABC</myparam>
  </MyAction>
</soapenv:Body>
</soapenv:Envelope>]]></constant></setBody>
<setHeader headerName="SOAPAction"><constant>MySOAPAction</constant></setHeader>
<setHeader headerName="CamelHttpMethod"><constant>POST</constant></setHeader>
<setHeader headerName="Content-Type"><constant>text/xml;charset=UTF-8</constant></setHeader>
<to uri="http://myserver:1234" />


问:
Auto-convert tab to 4 spaces in TextWrangler?
Is there a preference in Textwrangler to redefine a tab as 4 spaces? In Vim this is set expandtab in the vimrc, but I don't know how to set it in TW besides clicking "Detab" when I'm done editing the document.

Thanks,
Kevin

答: For Mac, another easy way to check and enable "Auto-expand tabs" is to hit the gear button on top left.


问:
Crontab Not Working with Bash on Ubuntu on Windows
I am trying to schedule a bash script to run with Bash on Ubuntu on Windows in Windows 10. Every time that I to write the cron, I get the following error messages in the terminal:

```<code>crontab: installing new crontab
/var/spool/cron/: mkstemp: Permission denied
crontab: edits left in /tmp/crontab.4q0z3i/crontab
</code>```

Here is what the crontab entry looks like:

```<code># m h  dom mon dow   command
27 10 * * * /home/admin/test.sh > /home/admin/logs/test.log 2>&1
</code>```

What exactly is going on here?

答:
There is workaround mentioned on the github bug for this one, can't seem to find it now! </p>

```<code>sudo crontab -u $USER -e
</code>```

Body:
I am trying to schedule a bash script to run with Bash on Ubuntu on Windows in Windows 10. Every time that I to write the cron, I get the following error messages in the terminal:

crontab: installing new crontab
/var/spool/cron/: mkstemp: Permission denied
crontab: edits left in /tmp/crontab.4q0z3i/crontab

Here is what the crontab entry looks like:

# m h  dom mon dow   command
27 10 * * * /home/admin/test.sh > /home/admin/logs/test.log 2>&1

What exactly is going on here?

Body:
There is workaround mentioned on the github bug for this one, can't seem to find it now!

sudo crontab -u $USER -e


问:
How can I make odoo service run with certain flags?
I'm trying to set the configuration file of my odoo server to certain file, I know that running odoo with the -c <path> or --config <path> will do the work, but I'm running it in the server like a service so I can't do this, neither adding the configs to /etc/odoo/odoo.conf because I need 2 configuration files.

Does someone knows how can I can make odoo service run with certain flags(-c and --load)

Here's my config at /etc/odoo/odoo.conf

```<code>[options]
addons_path = /usr/lib/python2.7/distpackages/odoo/addons,/opt/odoo/addons/odoodoto
admin_passwd = XXXXXXXXXXXX
data_dir = /var/lib/odoo
db_host = False
db_name = False
db_password = False
db_port = 5432
db_user = False
demo = {}
log_level = warn
logfile = /var/log/odoo/odoo-server.log
logrotate = True
proxy_mode = False
</code>```

And my second config:

```<code>[connector-options]
workers = 4
export ODOO_CONNECTOR_CHANNELS=root:5
export ODOO_CONNECTOR_PORT=8069
log-level = warn
</code>```

And the --load=web,connector is the other flag I need

答:
Without getting into many details of the init systems of Ubuntu, you should have a bash script inside /etc/init.d (probably /etc/init.d/odoo-server).

Inside that file insert a line:

DAEMON_OPTS="-c /etc/odoo/odoo.conf"

Use commas to pass more parameters

Body:
I'm trying to set the configuration file of my odoo server to certain file, I know that running odoo with the -c <path> or --config <path> will do the work, but I'm running it in the server like a service so I can't do this, neither adding the configs to /etc/odoo/odoo.conf because I need 2 configuration files.

Does someone knows how can I can make odoo service run with certain flags(-c and --load)

Here's my config at /etc/odoo/odoo.conf

[options]
addons_path = /usr/lib/python2.7/distpackages/odoo/addons,/opt/odoo/addons/odoodoto
admin_passwd = XXXXXXXXXXXX
data_dir = /var/lib/odoo
db_host = False
db_name = False
db_password = False
db_port = 5432
db_user = False
demo = {}
log_level = warn
logfile = /var/log/odoo/odoo-server.log
logrotate = True
proxy_mode = False

And my second config:

[connector-options]
workers = 4
export ODOO_CONNECTOR_CHANNELS=root:5
export ODOO_CONNECTOR_PORT=8069
log-level = warn

And the --load=web,connector is the other flag I need


问:
NodeJS socket.io socket does not emit
I'm working using socket.io on NodeJS to create bots for MooMoo.io. Everything seems to work fine except the bots will not accept a clan invitation.

Here is the part that is broken:

```<code>socket.emit("11", a, 1); // a = player ID
</code>```

Here's my code:

```<code>const io = require("socket.io-client");
var socket = io.connect("http://52.39.43.139:" + (5006) + '', {
    reconnection: false,
    query: "man=1"
});
var n = 0;

function spawn(i) {
    n++;
    if (n >= 10) return null;
    socket = io.connect("http://52.39.43.139:" + (5000 + i % 11) + '', {
        reconnection: false,
        query: "man=1"
    });
    socket.once("connect", () => {
        socket.emit("1", {name: "ME"}); // spawn
        socket.emit("10", "ME"); // request to join clan
    });
}
socket.once("connect", () => {
    socket.emit("1", {
        name: "ME"
    }); // spawn
    socket.emit("8", "ME"); // create clan
    console.log("Clan created");
});

team = [];

var i = 0;
setInterval(() => spawn(i), 3000);
socket.on("an", (a, name) => { // player requests to join clan event
    socket.emit("11", a, 1); // accept invite
    console.log(`${name} successfully joined :)`);
    team.push(a);
    console.log(team);
});
socket.on("ad", (a) => { // player leaves clan event
    for (var c = team.length - 1; c >= 0; c--)
        if (team[c].sid == a) {
            team.splice(c, 1);
            console.log(team[c].name + ' has left');
        }
    console.log(team);
});
socket.on("11", () => { // respawn event
    console.log("I have died, respawning...")
    socket.emit("1", { // spawn event
        name: "ME"
    });
});
</code>```

答: Turns out the server limited one connection per port. Fixed by using different ports.</p>

Title: NodeJS socket.io socket does not emit

Body:
I'm working using socket.io on NodeJS to create bots for MooMoo.io. Everything seems to work fine except the bots will not accept a clan invitation.

Here is the part that is broken:

socket.emit("11", a, 1); // a = player ID

Here's my code:

const io = require("socket.io-client");
var socket = io.connect("http://52.39.43.139:" + (5006) + '', {
    reconnection: false,
    query: "man=1"
});
var n = 0;

function spawn(i) {
    n++;
    if (n >= 10) return null;
    socket = io.connect("http://52.39.43.139:" + (5000 + i % 11) + '', {
        reconnection: false,
        query: "man=1"
    });
    socket.once("connect", () => {
        socket.emit("1", {name: "ME"}); // spawn
        socket.emit("10", "ME"); // request to join clan
    });
}
socket.once("connect", () => {
    socket.emit("1", {
        name: "ME"
    }); // spawn
    socket.emit("8", "ME"); // create clan
    console.log("Clan created");
});

team = [];

var i = 0;
setInterval(() => spawn(i), 3000);
socket.on("an", (a, name) => { // player requests to join clan event
    socket.emit("11", a, 1); // accept invite
    console.log(`${name} successfully joined :)`);
    team.push(a);
    console.log(team);
});
socket.on("ad", (a) => { // player leaves clan event
    for (var c = team.length - 1; c >= 0; c--)
        if (team[c].sid == a) {
            team.splice(c, 1);
            console.log(team[c].name + ' has left');
        }
    console.log(team);
});
socket.on("11", () => { // respawn event
    console.log("I have died, respawning...")
    socket.emit("1", { // spawn event
        name: "ME"
    });
});


问:
JavaScript script doesn't work in Firefox
I have an old function which is missing lines for Mozilla/Firefox and thus JavaScript is not working properly in it. The function tracks mouse-coordinates, so that I can position windows.

How to make the code work in Firefox as well?

```<code>Xoffset = -60; // modify these values to ...
Yoffset = 20; // change the popup position.
var old, skn, iex = (document.all),
    yyy = -1000;

var ns4 = document.layers
var ns6 = document.getElementById && !document.all
var ie4 = document.all

if (ns4) skn = document.dek
else if (ns6) skn = document.getElementById("dek").style
else if (ie4) skn = document.all.dek.style
if (ns4) document.captureEvents(Event.MOUSEMOVE);
else {
  skn.visibility = "visible"
  skn.display = "none"
}
document.onmousemove = get_mouse;

function popup(msg, bak) {
  var content =
      "<TABLE  WIDTH=150 BORDER=1 BORDERCOLOR=black CELLPADDING=2" +
      "CELLSPACING=0 " + "BGCOLOR=" + bak + "><TD ALIGN=center>" +
      "<FONT COLOR=black SIZE=2>" + msg + "</FONT></TD></TABLE>";
  yyy = Yoffset;
  if (ns4) {
    skn.document.write(content);
    skn.document.close();
    skn.visibility = "visible"
  }
  if (ns6) {
    document.getElementById("dek").innerHTML = content;
    skn.display = ''
  }
  if (ie4) {
    document.all("dek").innerHTML = content;
    skn.display = ''
  }
}

function get_mouse(e) {
  var x = (ns4 || ns6) ? event.pageX : event.x + document.body.scrollLeft;
  skn.left = x + Xoffset;
  var y = (ns4 || ns6) ? event.pageY : event.y + document.body.scrollTop;
  if (document.documentElement &&  // IE6 +4.01 but no scrolling going on
     !document.documentElement.scrollTop) {
    y = event.y + document.documentElement.scrollTop;
  }
  else if (document.documentElement && // IE6 +4.01 and user has scrolled
           document.documentElement.scrollTop) {
    y = event.y + document.documentElement.scrollTop;
  }
  else if (document.body && document.body.scrollTop) { // IE5 or DTD 3.2
    y = event.y + document.document.body.scrollTop;
  }

  skn.top = y + yyy;
}

function kill() {
  yyy = -1000;
  if (ns4) {
    skn.visibility = "hidden";
  }
  else if (ns6 || ie4) skn.display = "none"
}
</code>```

I am getting this error:

"event is not defined"

Works ok in IE.

答:
Instead of testing for browsers, I would test to see if the object / property exists. For example:

```<code>var x = e.pageX ? e.pageX : e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
</code>```

I think there may be an easier way to do this, such as

```<code>var x = e.pageX || e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
</code>```

but I'm not sure that will work. Test it out and see what you get. Also, for more detail, review: quirksmode.org/js/events_properties.html

Also note that I changed "event" to "e", since the parameter you're passing into the function is "e". If you want to still use event, rewrite the parameter to:

```<code>function get_mouse(event)
</code>```

While I don't believe "event" is a reserved word for JS, a lot of browsers use it, so I would suggest sticking to "e".

Body:
I have an old function which is missing lines for Mozilla/Firefox and thus JavaScript is not working properly in it. The function tracks mouse-coordinates, so that I can position windows.

How to make the code work in Firefox as well?

Xoffset = -60; // modify these values to ...
Yoffset = 20; // change the popup position.
var old, skn, iex = (document.all),
    yyy = -1000;

var ns4 = document.layers
var ns6 = document.getElementById && !document.all
var ie4 = document.all

if (ns4) skn = document.dek
else if (ns6) skn = document.getElementById("dek").style
else if (ie4) skn = document.all.dek.style
if (ns4) document.captureEvents(Event.MOUSEMOVE);
else {
  skn.visibility = "visible"
  skn.display = "none"
}
document.onmousemove = get_mouse;

function popup(msg, bak) {
  var content =
      "
" +
      "" + msg + "
";
  yyy = Yoffset;
  if (ns4) {
    skn.document.write(content);
    skn.document.close();
    skn.visibility = "visible"
  }
  if (ns6) {
    document.getElementById("dek").innerHTML = content;
    skn.display = ''
  }
  if (ie4) {
    document.all("dek").innerHTML = content;
    skn.display = ''
  }
}

function get_mouse(e) {
  var x = (ns4 || ns6) ? event.pageX : event.x + document.body.scrollLeft;
  skn.left = x + Xoffset;
  var y = (ns4 || ns6) ? event.pageY : event.y + document.body.scrollTop;
  if (document.documentElement &&  // IE6 +4.01 but no scrolling going on
     !document.documentElement.scrollTop) {
    y = event.y + document.documentElement.scrollTop;
  }
  else if (document.documentElement && // IE6 +4.01 and user has scrolled
           document.documentElement.scrollTop) {
    y = event.y + document.documentElement.scrollTop;
  }
  else if (document.body && document.body.scrollTop) { // IE5 or DTD 3.2
    y = event.y + document.document.body.scrollTop;
  }

  skn.top = y + yyy;
}

function kill() {
  yyy = -1000;
  if (ns4) {
    skn.visibility = "hidden";
  }
  else if (ns6 || ie4) skn.display = "none"
}

I am getting this error:

"event is not defined"

Works ok in IE.

Body:
Instead of testing for browsers, I would test to see if the object / property exists. For example:

var x = e.pageX ? e.pageX : e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;

I think there may be an easier way to do this, such as

var x = e.pageX || e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;

but I'm not sure that will work. Test it out and see what you get. Also, for more detail, review: quirksmode.org/js/events_properties.html

Also note that I changed "event" to "e", since the parameter you're passing into the function is "e". If you want to still use event, rewrite the parameter to:

function get_mouse(event)

While I don't believe "event" is a reserved word for JS, a lot of browsers use it, so I would suggest sticking to "e".