问:
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>```

答:
Using a simple for-loop. Not sure it is the most efficient way, but it does the trick.</p>

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

counter_list = []
for i,elem in enumerate(list1):
    if elem==1:
        counter_list.append(i)
    else:
        if len(counter_list)>0 and len(counter_list)<=2:
            for e in counter_list:
                list1[e] = 0
        counter_list= []
print(list1)
</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:
Using a simple for-loop. Not sure it is the most efficient way, but it does the trick.

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

counter_list = []
for i,elem in enumerate(list1):
    if elem==1:
        counter_list.append(i)
    else:
        if len(counter_list)>0 and len(counter_list)<=2:
            for e in counter_list:
                list1[e] = 0
        counter_list= []
print(list1)


来源: stackexchange

问:
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>```

答:
You are not incrementing the position in your addPoint(double x, double y), so basically, you are replacing the existing point with a new point, so you are missing few point values and you need to correct the correct the code as shown below:

```<code>public boolean addPoint(double x, double y) {
        Point2d a = new Point2d(x, y);
        p.add(points, a);
        points++;
        return true;
    }
</code>```

Because you are simply adding the point at the end of the list, I suggest you can directly use arraylist.add(point); so that you will not get into these increment/other issues.

Also, you can change your constructor of Polygon class (which accepts int) as follows because you are not using the numPoints variable or else use an array with numPoints as the size instead of ArrayList.

```<code>public Polygon() {
    p = new ArrayList<>();
}
</code>```

ContentLicense: CC BY-SA 3.0

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:
You are not incrementing the position in your addPoint(double x, double y), so basically, you are replacing the existing point with a new point, so you are missing few point values and you need to correct the correct the code as shown below:

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

Because you are simply adding the point at the end of the list, I suggest you can directly use arraylist.add(point); so that you will not get into these increment/other issues.

Also, you can change your constructor of Polygon class (which accepts int) as follows because you are not using the numPoints variable or else use an array with numPoints as the size instead of ArrayList.

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


问:
Selenium Webdriver not clicking on element
I am setting up webdrivers to scrape reporting numbers from a couple of sites I use at work. All of them are password protected which hasn't been a problem until now. Here is the login screen I am trying to interact with:

https://ssp.vertamedia.com/

I am using the Selenium webdriver with Python 3.6 in Firefox.

With this site, the webdriver needs to input the user name, then interact with the "next" button before the password input and submit button are visible. I am able to fill in the username, but so far have not been able to get the webdriver to interact with the "next" button.

Below is a snippet of the button html from the site:

```<code><a class="x-btn attached-btn blue x-unselectable x-box-item x-btn-attached-btn-small x-item-disabled x-btn-disabled" style="height: 40px; right: auto; left: 282px; top: 0px; margin: 0px;" hidefocus="on" unselectable="on" role="button" aria-hidden="false" aria-disabled="true" id="button-1021" data-componentid="button-1021">
    <span id="button-1021-btnWrap" data-ref="btnWrap" role="presentation" unselectable="on" style="" class="x-btn-wrap x-btn-wrap-attached-btn-small ">
        <span id="button-1021-btnEl" data-ref="btnEl" role="presentation" unselectable="on" style="height:auto;" class="x-btn-button x-btn-button-attached-btn-small x-btn-text    x-btn-button-center ">
            <span id="button-1021-btnIconEl" data-ref="btnIconEl" role="presentation" unselectable="on" class="x-btn-icon-el x-btn-icon-el-attached-btn-small  " style=""></span>
            <span id="button-1021-btnInnerEl" data-ref="btnInnerEl" unselectable="on" class="x-btn-inner x-btn-inner-attached-btn-small">next</span>
        </span>
    </span>
</a>
</code>```

I have tried using class name, id, and css Selector and so far haven't been successful. Below is the python snippet:

```<code>def exe(self):
    browser = webdriver.Firefox()
    wait = WebDriverWait(browser, 15)
    yesterday = date.today() - timedelta(1)
    browser.get("https://ssp.vertamedia.com")

    try:
        userElement = wait.until(EC.visibility_of_element_located((By.ID,'textfield-1020-inputEl')))
        userElement.send_keys(self.cred.pop('User'))
        browser.find_element_by_id('button-1021').click()
        passElement = wait.until(EC.visibility_of_element_located((By.ID, 'textfield-1027-inputEl')))
        passElement.send_keys(self.cred.pop('Password'))
        browser.find_element_by_id('button-1028').click()

    except TimeoutException:
        self.cred['Impression'] = "Login error"
        self.cred['Revenue'] = "Login error"
        self.cred['Date'] = yesterday.strftime('%m%d%y')
</code>```

Essentially when it hits the passElement section where I am inputting the password, it hits an "Element is not visible" error.

Any suggestions on how to get it to interact with the next button would be appreciated!

答:
Thanks again to SDBot for the help with wait().

With this particular site, something weird happens and the driver isn't able to tell that the "next" button is visible and ready to be clicked on. The same thing happens with the "login" button. I managed to get it working by inserting time.sleep() again between filling in the user name and login. I tried several different expected conditions but wasn't able to get it to work. http://selenium-python.readthedocs.io/api.html?highlight=expected%20conditions#selenium.webdriver.support.expected_conditions.frame_to_be_available_and_switch_to_it

```<code>def exe(self):
    browser = webdriver.Firefox()
    wait = WebDriverWait(browser, 15)
    yesterday = date.today() - timedelta(1)
    browser.get("https://ssp.vertamedia.com")

    try:
        userElement = wait.until(EC.visibility_of_element_located((By.ID,'textfield-1020-inputEl')))
        userElement.send_keys(self.cred.pop('User'))
        time.sleep(# insert seconds)
        wait.until(EC.visibility_of_element_located((By.ID,'button-1021-btnInnerEl'))).click()
        passElement = wait.until(EC.visibility_of_element_located((By.ID, 'textfield-1027-inputEl')))
        passElement.send_keys(self.cred.pop('Password'))
        time.sleep(# insert seconds5)
        wait.until(EC.visibility_of_element_located((By.ID,'button-1028'))).click()

    except TimeoutException:
        self.cred['Impression'] = "Login error"
        self.cred['Revenue'] = "Login error"
        self.cred['Date'] = yesterday.strftime('%m%d%y')
</code>```

Body:
I am setting up webdrivers to scrape reporting numbers from a couple of sites I use at work. All of them are password protected which hasn't been a problem until now. Here is the login screen I am trying to interact with:

https://ssp.vertamedia.com/

I am using the Selenium webdriver with Python 3.6 in Firefox.

With this site, the webdriver needs to input the user name, then interact with the "next" button before the password input and submit button are visible. I am able to fill in the username, but so far have not been able to get the webdriver to interact with the "next" button.

Below is a snippet of the button html from the site:

            next

I have tried using class name, id, and css Selector and so far haven't been successful. Below is the python snippet:

def exe(self):
    browser = webdriver.Firefox()
    wait = WebDriverWait(browser, 15)
    yesterday = date.today() - timedelta(1)
    browser.get("https://ssp.vertamedia.com")

    try:
        userElement = wait.until(EC.visibility_of_element_located((By.ID,'textfield-1020-inputEl')))
        userElement.send_keys(self.cred.pop('User'))
        browser.find_element_by_id('button-1021').click()
        passElement = wait.until(EC.visibility_of_element_located((By.ID, 'textfield-1027-inputEl')))
        passElement.send_keys(self.cred.pop('Password'))
        browser.find_element_by_id('button-1028').click()

    except TimeoutException:
        self.cred['Impression'] = "Login error"
        self.cred['Revenue'] = "Login error"
        self.cred['Date'] = yesterday.strftime('%m%d%y')

Essentially when it hits the passElement section where I am inputting the password, it hits an "Element is not visible" error.

Any suggestions on how to get it to interact with the next button would be appreciated!

Body:
Thanks again to SDBot for the help with wait().

With this particular site, something weird happens and the driver isn't able to tell that the "next" button is visible and ready to be clicked on. The same thing happens with the "login" button. I managed to get it working by inserting time.sleep() again between filling in the user name and login. I tried several different expected conditions but wasn't able to get it to work. http://selenium-python.readthedocs.io/api.html?highlight=expected%20conditions#selenium.webdriver.support.expected_conditions.frame_to_be_available_and_switch_to_it

def exe(self):
    browser = webdriver.Firefox()
    wait = WebDriverWait(browser, 15)
    yesterday = date.today() - timedelta(1)
    browser.get("https://ssp.vertamedia.com")

    try:
        userElement = wait.until(EC.visibility_of_element_located((By.ID,'textfield-1020-inputEl')))
        userElement.send_keys(self.cred.pop('User'))
        time.sleep(# insert seconds)
        wait.until(EC.visibility_of_element_located((By.ID,'button-1021-btnInnerEl'))).click()
        passElement = wait.until(EC.visibility_of_element_located((By.ID, 'textfield-1027-inputEl')))
        passElement.send_keys(self.cred.pop('Password'))
        time.sleep(# insert seconds5)
        wait.until(EC.visibility_of_element_located((By.ID,'button-1028'))).click()

    except TimeoutException:
        self.cred['Impression'] = "Login error"
        self.cred['Revenue'] = "Login error"
        self.cred['Date'] = yesterday.strftime('%m%d%y')


问:
django complex query for interdependant tables
Django Models

```<code>class Product(models.Model):
    product_name = models.CharField(max_length=50)
    category = models.CharField(max_length=50)
    desc = models.CharField(max_length=120)
    company_name = models.CharField(max_length=50, default=None)
    timestamp = models.DateTimeField(auto_now_add = True, auto_now = False)
    updated = models.DateTimeField(auto_now_add = False, auto_now = True)

    def __unicode__(self):
        return self.product_name

class ProductDetails(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    batch = models.CharField(max_length=50)
    quantity = models.IntegerField()
    cost = models.FloatField(null=True, blank=True, default=None)
    mfg = models.DateTimeField()
    exp = models.DateTimeField()
    timestamp = models.DateTimeField(auto_now_add = True, auto_now = False)
    updated = models.DateTimeField(auto_now_add = False, auto_now = True)

    def __unicode__(self):
        return self.batch

class product_barcode(models.Model):
    batch = models.ForeignKey(ProductDetails, on_delete=models.CASCADE)
    barcode = models.BigIntegerField()
    flag = models.IntegerField()

    timestamp = models.DateTimeField(auto_now_add = True, auto_now = False)
    updated = models.DateTimeField(auto_now_add = False, auto_now = True)

    def __unicode__(self):
        return self.barcode
</code>```

I want to calculate number of barcodes generated by company_name

I tried some some code like

```<code>w=Product.objects.all().filter(company_name="company name")
print "w>>>",w
pid = []
for Pdata in w:
    pid.append(Pdata.id)
print "pid>>>",pid
</code>```

Here I find ids of product name which belong to a specific company but after that I want to find batch codes(at ProductDetails) that belong to product ids, after that I need to count all barcodes that belong to batch codes.

in simple words

company ['company name']

products ['product1','product2','product3'] where company = 'company name'

Batch codes where products = ['product1','product2','product3']

product1 ['bxyz','b2xyz','b3xyz']

product2 ['b1xyz','b4xyz','b3xyz']

product3 ['b9xyz','b6xyz','b3xyz']

count Barcodes where batch codes ['bxyz','b2xyz','b3xyz']['b1xyz','b4xyz','b3xyz']['b9xyz','b6xyz','b3xyz']

答:
I hope, I understand well what you wanna do so what about something like:

```<code>count = product_barcode.objects.filter(batch__product__company_name='company name').count()
</code>```

This should return number of barcodes for all products where company name is equal to 'company name'.

Two underscores are used for joining tables, like using JOIN in SQL. Based on PEP you should change name of the barcode class (ProductBarcode). It is really better start with it for the future.

Body:
Django Models

class Product(models.Model):
    product_name = models.CharField(max_length=50)
    category = models.CharField(max_length=50)
    desc = models.CharField(max_length=120)
    company_name = models.CharField(max_length=50, default=None)
    timestamp = models.DateTimeField(auto_now_add = True, auto_now = False)
    updated = models.DateTimeField(auto_now_add = False, auto_now = True)

    def __unicode__(self):
        return self.product_name

class ProductDetails(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    batch = models.CharField(max_length=50)
    quantity = models.IntegerField()
    cost = models.FloatField(null=True, blank=True, default=None)
    mfg = models.DateTimeField()
    exp = models.DateTimeField()
    timestamp = models.DateTimeField(auto_now_add = True, auto_now = False)
    updated = models.DateTimeField(auto_now_add = False, auto_now = True)

    def __unicode__(self):
        return self.batch

class product_barcode(models.Model):
    batch = models.ForeignKey(ProductDetails, on_delete=models.CASCADE)
    barcode = models.BigIntegerField()
    flag = models.IntegerField()

    timestamp = models.DateTimeField(auto_now_add = True, auto_now = False)
    updated = models.DateTimeField(auto_now_add = False, auto_now = True)

    def __unicode__(self):
        return self.barcode

I want to calculate number of barcodes generated by company_name

I tried some some code like

w=Product.objects.all().filter(company_name="company name")
print "w>>>",w
pid = []
for Pdata in w:
    pid.append(Pdata.id)
print "pid>>>",pid

Here I find ids of product name which belong to a specific company but after that I want to find batch codes(at ProductDetails) that belong to product ids, after that I need to count all barcodes that belong to batch codes.

in simple words

company ['company name']

products ['product1','product2','product3'] where company = 'company name'

Batch codes where products = ['product1','product2','product3']

product1 ['bxyz','b2xyz','b3xyz']

product2 ['b1xyz','b4xyz','b3xyz']

product3 ['b9xyz','b6xyz','b3xyz']

count Barcodes where batch codes ['bxyz','b2xyz','b3xyz']['b1xyz','b4xyz','b3xyz']['b9xyz','b6xyz','b3xyz']

Body:
I hope, I understand well what you wanna do so what about something like:

count = product_barcode.objects.filter(batch__product__company_name='company name').count()

This should return number of barcodes for all products where company name is equal to 'company name'.

Two underscores are used for joining tables, like using JOIN in SQL. Based on PEP you should change name of the barcode class (ProductBarcode). It is really better start with it for the future.


问:
Remove HTML Tags in Javascript with Regex
I am trying to remove all the html tags out of a string in Javascript.
Heres what I have... I can't figure out why its not working....any know what I am doing wrong?

```<code><script type="text/javascript">

var regex = "/<(.|\n)*?>/";
var body = "<p>test</p>";
var result = body.replace(regex, "");
alert(result);

</script>
</code>```

Thanks a lot!

答:
Here is how TextAngular (WYSISYG Editor) is doing it. I also found this to be the most consistent answer, which is NO REGEX.</p>

```<code>@license textAngular
Author : Austin Anderson
License : 2013 MIT
Version 1.5.16
// turn html into pure text that shows visiblity
function stripHtmlToText(html)
{
    var tmp = document.createElement("DIV");
    tmp.innerHTML = html;
    var res = tmp.textContent || tmp.innerText || '';
    res.replace('\u200B', ''); // zero width space
    res = res.trim();
    return res;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to remove all the html tags out of a string in Javascript.
Heres what I have... I can't figure out why its not working....any know what I am doing wrong?

Thanks a lot!

Body:
Here is how TextAngular (WYSISYG Editor) is doing it. I also found this to be the most consistent answer, which is NO REGEX.

@license textAngular
Author : Austin Anderson
License : 2013 MIT
Version 1.5.16
// turn html into pure text that shows visiblity
function stripHtmlToText(html)
{
    var tmp = document.createElement("DIV");
    tmp.innerHTML = html;
    var res = tmp.textContent || tmp.innerText || '';
    res.replace('\u200B', ''); // zero width space
    res = res.trim();
    return res;
}


问:
How to convert NSString to Int so I can add in swift 3.0
I have a value which seems to be an Int but when I do type(of: value) it returns Optional<Any> and after trying many things I figure that data type NSString.

```<code>let sum = data[0]["total1"] + data[0]["total2"]
</code>```

I have two values like that and I want to add them but it does not let me do it with saying

binary operator + cannot be applied to two "Any" operands

or

Value of type "Any" has no member 'intValue'

How do I convert this Any to Int so I can add them?

答:
Since the underlying objects are NSString, you can also do:

```<code>if let num1 = (data[0]["total1"] as? NSString)?.intValue,
   let num2 = (data[0]["total2"] as? NSString)?.intValue {
    let sum = num1 + num2
}
</code>```

As @rmaddy pointed out in the comments, if a value is not an integer (such as "hello"), it will convert to 0.  Depending on your knowledge of the data your app is receiving and what you want to happen in this case, that result may or may not be appropriate.

.intValue is more forgiving of the string data format compared to Int(str).  Leading and trailing spaces are ignored and a floating point value such as 13.1 will be converted to an integer.  Again, it depends on what you want to happen in your app.

ContentLicense: CC BY-SA 4.0

Body:
I have a value which seems to be an Int but when I do type(of: value) it returns Optional<Any> and after trying many things I figure that data type NSString.

let sum = data[0]["total1"] + data[0]["total2"]

I have two values like that and I want to add them but it does not let me do it with saying

binary operator + cannot be applied to two "Any" operands

or

Value of type "Any" has no member 'intValue'

How do I convert this Any to Int so I can add them?

Body:
Since the underlying objects are NSString, you can also do:

if let num1 = (data[0]["total1"] as? NSString)?.intValue,
   let num2 = (data[0]["total2"] as? NSString)?.intValue {
    let sum = num1 + num2
}

As @rmaddy pointed out in the comments, if a value is not an integer (such as "hello"), it will convert to 0.  Depending on your knowledge of the data your app is receiving and what you want to happen in this case, that result may or may not be appropriate.

.intValue is more forgiving of the string data format compared to Int(str).  Leading and trailing spaces are ignored and a floating point value such as 13.1 will be converted to an integer.  Again, it depends on what you want to happen in your app.


问:
One dimensional convolutional variational autoencoder in keras
I am trying to adapt this example from the git repo, basically by using their other example from the same repo here (which uses deconvolution).

I cannot quite figure out where I am going wrong, but it seems very basic. Here we are:

```<code>import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
# Keras uses TensforFlow backend as default
from keras.layers import Input, Dense, Lambda, Flatten, Reshape
from keras.layers import Conv1D,UpSampling1D
from keras.models import Model
from keras import backend as K
from keras import metrics
from keras.datasets import mnist

# Input image dimensions
steps, original_dim = 1, 28*28 # Take care here since we are changing this according to the data
# Number of convolutional filters to use
filters = 64
# Convolution kernel size
num_conv = 6
# Set batch size
batch_size = 100
# Decoder output dimensionality
decOutput = 10

latent_dim = 20
intermediate_dim = 256
epsilon_std = 1.0
epochs = 5

x = Input(batch_shape=(batch_size,steps,original_dim))
# Play around with padding here, not sure what to go with.
conv_1 = Conv1D(1,
                kernel_size=num_conv,
                padding='same',
                activation='relu')(x)
conv_2 = Conv1D(filters,
                kernel_size=num_conv,
                padding='same',
                activation='relu',
                strides=1)(conv_1)
flat = Flatten()(conv_2) # Since we are passing flat data anyway, we probably don't need this.
hidden = Dense(intermediate_dim, activation='relu')(flat)
z_mean = Dense(latent_dim)(hidden)
z_log_var = Dense(latent_dim)(hidden)

def sampling(args):
    z_mean, z_log_var = args
    epsilon = K.random_normal(shape=(batch_size, latent_dim),
                              mean=0., stddev=epsilon_std)
    return z_mean + K.exp(z_log_var ) * epsilon # the original VAE divides z_log_var with two -- why?

# note that "output_shape" isn't necessary with the TensorFlow backend
# so you could write `Lambda(sampling)([z_mean, z_log_var])`
z = Lambda(sampling, output_shape=(latent_dim,))([z_mean, z_log_var])

# we instantiate these layers separately so as to reuse them later
decoder_h = Dense(intermediate_dim, activation='relu')
decoder_mean = Dense(original_dim, activation='sigmoid')

h_decoded = decoder_h(z)
x_decoded_mean = decoder_mean(h_decoded)

def vae_loss(x, x_decoded_mean):
    xent_loss = original_dim * metrics.binary_crossentropy(x, x_decoded_mean)
    kl_loss = - 0.5 * K.sum(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1) # Double check wtf this is supposed to be
    return xent_loss + kl_loss

vae = Model(x, x_decoded_mean)
vae.compile(optimizer='adam', loss=vae_loss) # 'rmsprop'
vae.summary()
</code>```

Which comes out as:

```<code>____________________________________________________________________________________________________
Layer (type)                     Output Shape          Param #     Connected to
====================================================================================================
input_31 (InputLayer)            (100, 1, 784)         0
____________________________________________________________________________________________________
conv1d_87 (Conv1D)               (100, 1, 1)           4705
____________________________________________________________________________________________________
conv1d_88 (Conv1D)               (100, 1, 64)          448
____________________________________________________________________________________________________
flatten_29 (Flatten)             (100, 64)             0
____________________________________________________________________________________________________
dense_134 (Dense)                (100, 256)            16640
____________________________________________________________________________________________________
dense_135 (Dense)                (100, 20)             5140
____________________________________________________________________________________________________
dense_136 (Dense)                (100, 20)             5140
____________________________________________________________________________________________________
lambda_24 (Lambda)               (100, 20)             0
____________________________________________________________________________________________________
dense_137 (Dense)                (100, 256)            5376
____________________________________________________________________________________________________
dense_138 (Dense)                (100, 784)            201488
====================================================================================================
Total params: 238,937.0
Trainable params: 238,937.0
Non-trainable params: 0.0
</code>```

Then if I try to run this, as so:

```<code>from keras.datasets import mnist

img_rows, img_cols = 1,28*28
original_img_size = (img_rows, img_cols)

# train the VAE on MNIST digits
(x_train, _), (x_test, y_test) = mnist.load_data()

x_train = x_train.astype('float32') / 255.
x_train = x_train.reshape((x_train.shape[0],) + original_img_size)

print('x_train.shape:', x_train.shape)

N = 1000
epochs = 2
batch_size = int(N/10)
vae.fit(x_train[0:N,:], x_train[0:N,:],
        shuffle=True,
        epochs=epochs,
        batch_size=batch_size)
</code>```

I get this error, but I cannot quite figure out how to get past it. It has something to with going from Conv1D to Dense...

```<code>ValueError: Cannot feed value of shape (100, 1, 784) for Tensor u'dense_138_target:0', which has shape '(?, ?)'
</code>```

答:
Try reshaping x_decoded_mean to your input shape since x_train[0:N,:] is shaped (1,784) but your output is (784,)
something like

```<code>x_decoded_mean = Reshape([1,784])(x_decoded_mean)
</code>```

Body:
I am trying to adapt this example from the git repo, basically by using their other example from the same repo here (which uses deconvolution).

I cannot quite figure out where I am going wrong, but it seems very basic. Here we are:

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
# Keras uses TensforFlow backend as default
from keras.layers import Input, Dense, Lambda, Flatten, Reshape
from keras.layers import Conv1D,UpSampling1D
from keras.models import Model
from keras import backend as K
from keras import metrics
from keras.datasets import mnist

# Input image dimensions
steps, original_dim = 1, 28*28 # Take care here since we are changing this according to the data
# Number of convolutional filters to use
filters = 64
# Convolution kernel size
num_conv = 6
# Set batch size
batch_size = 100
# Decoder output dimensionality
decOutput = 10

latent_dim = 20
intermediate_dim = 256
epsilon_std = 1.0
epochs = 5

x = Input(batch_shape=(batch_size,steps,original_dim))
# Play around with padding here, not sure what to go with.
conv_1 = Conv1D(1,
                kernel_size=num_conv,
                padding='same',
                activation='relu')(x)
conv_2 = Conv1D(filters,
                kernel_size=num_conv,
                padding='same',
                activation='relu',
                strides=1)(conv_1)
flat = Flatten()(conv_2) # Since we are passing flat data anyway, we probably don't need this.
hidden = Dense(intermediate_dim, activation='relu')(flat)
z_mean = Dense(latent_dim)(hidden)
z_log_var = Dense(latent_dim)(hidden)

def sampling(args):
    z_mean, z_log_var = args
    epsilon = K.random_normal(shape=(batch_size, latent_dim),
                              mean=0., stddev=epsilon_std)
    return z_mean + K.exp(z_log_var ) * epsilon # the original VAE divides z_log_var with two -- why?

# note that "output_shape" isn't necessary with the TensorFlow backend
# so you could write `Lambda(sampling)([z_mean, z_log_var])`
z = Lambda(sampling, output_shape=(latent_dim,))([z_mean, z_log_var])

# we instantiate these layers separately so as to reuse them later
decoder_h = Dense(intermediate_dim, activation='relu')
decoder_mean = Dense(original_dim, activation='sigmoid')

h_decoded = decoder_h(z)
x_decoded_mean = decoder_mean(h_decoded)

def vae_loss(x, x_decoded_mean):
    xent_loss = original_dim * metrics.binary_crossentropy(x, x_decoded_mean)
    kl_loss = - 0.5 * K.sum(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1) # Double check wtf this is supposed to be
    return xent_loss + kl_loss

vae = Model(x, x_decoded_mean)
vae.compile(optimizer='adam', loss=vae_loss) # 'rmsprop'
vae.summary()

Which comes out as:

____________________________________________________________________________________________________
Layer (type)                     Output Shape          Param #     Connected to
====================================================================================================
input_31 (InputLayer)            (100, 1, 784)         0
____________________________________________________________________________________________________
conv1d_87 (Conv1D)               (100, 1, 1)           4705
____________________________________________________________________________________________________
conv1d_88 (Conv1D)               (100, 1, 64)          448
____________________________________________________________________________________________________
flatten_29 (Flatten)             (100, 64)             0
____________________________________________________________________________________________________
dense_134 (Dense)                (100, 256)            16640
____________________________________________________________________________________________________
dense_135 (Dense)                (100, 20)             5140
____________________________________________________________________________________________________
dense_136 (Dense)                (100, 20)             5140
____________________________________________________________________________________________________
lambda_24 (Lambda)               (100, 20)             0
____________________________________________________________________________________________________
dense_137 (Dense)                (100, 256)            5376
____________________________________________________________________________________________________
dense_138 (Dense)                (100, 784)            201488
====================================================================================================
Total params: 238,937.0
Trainable params: 238,937.0
Non-trainable params: 0.0

Then if I try to run this, as so:

from keras.datasets import mnist

img_rows, img_cols = 1,28*28
original_img_size = (img_rows, img_cols)

# train the VAE on MNIST digits
(x_train, _), (x_test, y_test) = mnist.load_data()

x_train = x_train.astype('float32') / 255.
x_train = x_train.reshape((x_train.shape[0],) + original_img_size)

print('x_train.shape:', x_train.shape)

N = 1000
epochs = 2
batch_size = int(N/10)
vae.fit(x_train[0:N,:], x_train[0:N,:],
        shuffle=True,
        epochs=epochs,
        batch_size=batch_size)

I get this error, but I cannot quite figure out how to get past it. It has something to with going from Conv1D to Dense...

ValueError: Cannot feed value of shape (100, 1, 784) for Tensor u'dense_138_target:0', which has shape '(?, ?)'

Body:
Try reshaping x_decoded_mean to your input shape since x_train[0:N,:] is shaped (1,784) but your output is (784,)
something like

x_decoded_mean = Reshape([1,784])(x_decoded_mean)


问:
Why are my UITableViewCell's repeating?
When I scroll offscreen I get some repeating cells. How can I fix this?</p>

```<code>// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    switch (indexPath.row) {
        case 0:
            cell.textLabel.text = [NSString stringWithFormat:@"Bar Cafe",indexPath.row];
            break;
        case 1:
            cell.textLabel.text = [NSString stringWithFormat:@"Boutique Hester",indexPath.row];
            break;
        case 2:
            cell.textLabel.text = [NSString stringWithFormat:@"Boutique Hester Shoes",indexPath.row];
            break;
        case 3:
            cell.textLabel.text = [NSString stringWithFormat:@"Local Advice - Paulina",indexPath.row];
            break;
        case 4:
            cell.textLabel.text = [NSString stringWithFormat:@"Museum Brileyeglass",indexPath.row];
            break;
        case 5:
            cell.textLabel.text = [NSString stringWithFormat:@"Redlight Swans",indexPath.row];
            break;
        case 6:
            cell.textLabel.text = [NSString stringWithFormat:@"Reefer Flying Dutchman",indexPath.row];
            break;
        case 7:
            cell.textLabel.text = [NSString stringWithFormat:@"Reefer Tiani Hempshop",indexPath.row];
            break;

        default:
            break;
    }

    // Configure the cell...
    //cell.textLabel.text = [NSString stringWithFormat:@"Featured Event %d",indexPath.row];
    //cell.detailTextLabel.text = [NSString stringWithFormat:@"Description %d", indexPath.row];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;
}
</code>```

答:
```<code>- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 8;
}
</code>```

<p>this is the right implementaion of numberOfRowsInSection method if you return more than 8 then problem of repeating rows starts. </p>

Title: Why are my UITableViewCell's repeating?

Body:
When I scroll offscreen I get some repeating cells. How can I fix this?

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    switch (indexPath.row) {
        case 0:
            cell.textLabel.text = [NSString stringWithFormat:@"Bar Cafe",indexPath.row];
            break;
        case 1:
            cell.textLabel.text = [NSString stringWithFormat:@"Boutique Hester",indexPath.row];
            break;
        case 2:
            cell.textLabel.text = [NSString stringWithFormat:@"Boutique Hester Shoes",indexPath.row];
            break;
        case 3:
            cell.textLabel.text = [NSString stringWithFormat:@"Local Advice - Paulina",indexPath.row];
            break;
        case 4:
            cell.textLabel.text = [NSString stringWithFormat:@"Museum Brileyeglass",indexPath.row];
            break;
        case 5:
            cell.textLabel.text = [NSString stringWithFormat:@"Redlight Swans",indexPath.row];
            break;
        case 6:
            cell.textLabel.text = [NSString stringWithFormat:@"Reefer Flying Dutchman",indexPath.row];
            break;
        case 7:
            cell.textLabel.text = [NSString stringWithFormat:@"Reefer Tiani Hempshop",indexPath.row];
            break;

        default:
            break;
    }

    // Configure the cell...
    //cell.textLabel.text = [NSString stringWithFormat:@"Featured Event %d",indexPath.row];
    //cell.detailTextLabel.text = [NSString stringWithFormat:@"Description %d", indexPath.row];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;
}

Body:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 8;
}

this is the right implementaion of numberOfRowsInSection method if you return more than 8 then problem of repeating rows starts.


问:
Why are my props undefined when I use a Route?
I'm confused when re-passing props to children (particularly when inside a Route). For example:

```<code>class App extends Component {
    constructor(props) {
        this.sayHi = this.sayHi.bind(this);
    }

    sayHi() {
        console.log('hi')
    }

    render() {
        return (
          <Router>
            <Route path="/projects" component={(props, state, params) =>
              <ProjectList
                sayHi={this.sayHi}
              {...props} />}
            />
          </Router>
        )
    }
}

const ProjectList = (props) => {
    return (
        <Route path={`${props.match.url}/:id`} component={(props, state, params) =>
          <ProjectDetail
            sayHi={props.sayHi}
          {...props} />}
        />
    )
}

const ProjectDetail = (props) => {
    console.log(props)
}
</code>```

Within the ProjectList component, I have no problem accessing the sayHi method (I can attach it to an onClick event within this component), but in the ProjectDetail component, I get an undefined for props.sayHi.

How am I incorrectly passing this prop?

答:
You've just a problem with parameters of the same name. In your ProjectList component:

```<code><Route path={`${props.match.url}/:id`} component={(props, state, params) =>
    <ProjectDetail
         sayHi={props.sayHi}
    {...props} />}
/>
</code>```

When you are creating a ProjectDetail element and pass the sayHi prop, you have to access ProjectList's props, not the props of the arrow function (the props Route passes). The parameters are "overriding" each other because they are under the same name, props. So, try:

```<code>const ProjectList = (props) => {
    return (
        <Route path={`${props.match.url}/:id`} component={(routeProps, state, params) => // use name "routeProps" instead of "props"
            <ProjectDetail
                sayHi={props.sayHi}
            {...props} />}
        />
    )
}
</code>```

We rename the props in the component prop's arrow function to routeProps which will get rid of the name conflict. This way, the props of ProjectList are passed to ProjectDetail, not the props that Route passes.

Body:
I'm confused when re-passing props to children (particularly when inside a Route). For example:

class App extends Component {
    constructor(props) {
        this.sayHi = this.sayHi.bind(this);
    }

    sayHi() {
        console.log('hi')
    }

    render() {
        return (
          <Router>
            <Route path="/projects" component={(props, state, params) =>
              <ProjectList
                sayHi={this.sayHi}
              {...props} />}
            />
          </Router>
        )
    }
}

const ProjectList = (props) => {
    return (
        <Route path={`${props.match.url}/:id`} component={(props, state, params) =>
          <ProjectDetail
            sayHi={props.sayHi}
          {...props} />}
        />
    )
}

const ProjectDetail = (props) => {
    console.log(props)
}

Within the ProjectList component, I have no problem accessing the sayHi method (I can attach it to an onClick event within this component), but in the ProjectDetail component, I get an undefined for props.sayHi.

How am I incorrectly passing this prop?

Body:
You've just a problem with parameters of the same name. In your ProjectList component:

<Route path={`${props.match.url}/:id`} component={(props, state, params) =>
    <ProjectDetail
         sayHi={props.sayHi}
    {...props} />}
/>

When you are creating a ProjectDetail element and pass the sayHi prop, you have to access ProjectList's props, not the props of the arrow function (the props Route passes). The parameters are "overriding" each other because they are under the same name, props. So, try:

const ProjectList = (props) => {
    return (
        <Route path={`${props.match.url}/:id`} component={(routeProps, state, params) => // use name "routeProps" instead of "props"
            <ProjectDetail
                sayHi={props.sayHi}
            {...props} />}
        />
    )
}

We rename the props in the component prop's arrow function to routeProps which will get rid of the name conflict. This way, the props of ProjectList are passed to ProjectDetail, not the props that Route passes.


问:
copy paste excel vba
I have those sheets.
The second sheet is how I would it to be.
I am now trying for hours how I would do this.
Please can anyone help me on the right track.

I am copying from sheet 7(pic1) to sheet 9(pic2).
The lastrow to look for should be range F.

But I always end up like in pic3.

答:
I can't see the pictures unfortunately, so I'm not sure how on the mark I am.

In general, you want to start something like this:

```<code>Sheets("Sheet 7").Activate
Range("A1:N8").Copy
Sheets("Sheet 9").Activate
Range("A1").Paste
</code>```

To select your data, and move it over. Now let's get a bit fancy.

```<code>Dim I as long
Dim J as long
Dum K as long
Dim L as long

Dim O as long
Dim P as long
I = WorkSheetFunction.Vlookup(you know how a vlookup works)
J = WorksheetFunction.Sum(You really should know this one)
.....
P = 7
Sheets("Sheet 7").Activate
Range(I&J:O&P).Copy
Sheets("Sheet 9").Activate
Range(K&L).Paste
</code>```

Where you can specify the starting and ending corner of your copy range, and the starting cell of your pasting range. Use macro recorder to find out exactly how a paste values, or other type of fancy paste works.

Title: copy paste excel vba

Body:
I can't see the pictures unfortunately, so I'm not sure how on the mark I am.

In general, you want to start something like this:

Sheets("Sheet 7").Activate
Range("A1:N8").Copy
Sheets("Sheet 9").Activate
Range("A1").Paste

To select your data, and move it over. Now let's get a bit fancy.

Dim I as long
Dim J as long
Dum K as long
Dim L as long

Dim O as long
Dim P as long
I = WorkSheetFunction.Vlookup(you know how a vlookup works)
J = WorksheetFunction.Sum(You really should know this one)
.....
P = 7
Sheets("Sheet 7").Activate
Range(I&J:O&P).Copy
Sheets("Sheet 9").Activate
Range(K&L).Paste

Where you can specify the starting and ending corner of your copy range, and the starting cell of your pasting range. Use macro recorder to find out exactly how a paste values, or other type of fancy paste works.


问:
Getting previous day datetime from arrow
I can get current datetime from arrow like this:

```<code>arrow.utcnow().date()
</code>```

or

```<code>arrow.get('2017-02-01').date()
</code>```

How can I get the previous day datetime? This does not work:

```<code>arrow.utcnow().date() - 1
</code>```

or

```<code> arrow.get('2017-02-01').date() - 1
</code>```

答:
thanks kayluhb. update is to use shift:

```<code>arrow.utcnow().shift(days=-1)
</code>```

you can use replace:

```<code> arrow.utcnow().replace(days=-1)
</code>```

Body:
I can get current datetime from arrow like this:

arrow.utcnow().date()

or

arrow.get('2017-02-01').date()

How can I get the previous day datetime? This does not work:

arrow.utcnow().date() - 1

or

 arrow.get('2017-02-01').date() - 1

Body:
thanks kayluhb. update is to use shift:

arrow.utcnow().shift(days=-1)

you can use replace:

 arrow.utcnow().replace(days=-1)


问:
Reverse white and black colors in a PDF
Given a black and white PDF, how do I reverse the colors such that background is black and everything else is white?

Adobe Reader does it (Preferences -> Accessibility) for viewing purposes only in the program. But does not change the document inherently such that the colors are reversed also in other PDF readers.

How to reverse colors permanently?

答: If you have the Adobe PDF printer installed, you go to Print -> Adobe PDF -> Advanced... -> Output area and select the "Invert" checkbox. Your printed PDF file will then be inverted permanently.</p>

Title: Reverse white and black colors in a PDF


问:
Is there an equivalent of the python built in function `all` in pandas?
I'm quyering a pandas dataframe df like this.

```<code>df = df[
    (df.value1 >= threshold1) &
    (df.value2 >= threshold2) &
    (df.value3.isin(list3))
    ]
</code>```

Python has the built in function all, which allows this syntax:

```<code>if all([
    value1 > threshold1,
    value2 > threshold2,
    value3 in list3,
    ]):
</code>```

Instead of this:

```<code>if (
    value1 > threshold1 and
    value2 > threshold2 and
    value3 in list3,
    ):
</code>```

Does Pandas have something similar to all in Python? Thanks.

Also, is this the fastest way of subsetting a Pandas dataframe based on multiple conditions?

答:
@juanpa.arrivillaga already gave you a very good explanation about boolean indexing in Pandas.

I'd like to give you a bit nicer alternative - DataFrame.query() method:

```<code>df.query("value1 > @threshold1 and value2 > @threshold2 and value3 in @list3")
</code>```

Demo:

```<code>In [138]: df = pd.DataFrame(np.random.randint(1, 10, (10, 3)),
                            columns=['value1','value2','value3'])

In [139]: df
Out[139]:
   value1  value2  value3
0       7       9       1
1       4       1       3
2       3       8       8
3       2       8       9
4       9       2       7
5       5       8       9
6       4       2       9
7       7       2       5
8       6       3       5
9       9       1       5

In [140]: threshold1 = 2

In [141]: threshold2 = 4

In [142]: list3 = [1,9]

In [143]: df.query("value1 > @threshold1 and value2 > @threshold2 and value3 in @list3")
Out[143]:
   value1  value2  value3
0       7       9       1
5       5       8       9
</code>```

Body:
I'm quyering a pandas dataframe df like this.

df = df[
    (df.value1 >= threshold1) &
    (df.value2 >= threshold2) &
    (df.value3.isin(list3))
    ]

Python has the built in function all, which allows this syntax:

if all([
    value1 > threshold1,
    value2 > threshold2,
    value3 in list3,
    ]):

Instead of this:

if (
    value1 > threshold1 and
    value2 > threshold2 and
    value3 in list3,
    ):

Does Pandas have something similar to all in Python? Thanks.

Also, is this the fastest way of subsetting a Pandas dataframe based on multiple conditions?

Body:
@juanpa.arrivillaga already gave you a very good explanation about boolean indexing in Pandas.

I'd like to give you a bit nicer alternative - DataFrame.query() method:

df.query("value1 > @threshold1 and value2 > @threshold2 and value3 in @list3")

Demo:

In [138]: df = pd.DataFrame(np.random.randint(1, 10, (10, 3)),
                            columns=['value1','value2','value3'])

In [139]: df
Out[139]:
   value1  value2  value3
0       7       9       1
1       4       1       3
2       3       8       8
3       2       8       9
4       9       2       7
5       5       8       9
6       4       2       9
7       7       2       5
8       6       3       5
9       9       1       5

In [140]: threshold1 = 2

In [141]: threshold2 = 4

In [142]: list3 = [1,9]

In [143]: df.query("value1 > @threshold1 and value2 > @threshold2 and value3 in @list3")
Out[143]:
   value1  value2  value3
0       7       9       1
5       5       8       9


问:
WSDL to PHP with Basic Auth
I need to build php classes from a WSDL that is behind basic auth.

It has tons of namespaces so it looks burdensome to do this by hand.

I have tried a few tools but looks like the auth session isn't presistent.

答:
i’ve been trying to resolve this issue, but from what i understand, soap client connections to ssl+httpauth web services are more pain. I’ve googled and from what i understand, with my problem being solved, you can use the example below to solve your problem too(by using HttpAuth infos in both url and soapClient setup).</p>

```<code>$username="test";
$password="test";
$url = "https://".urlencode($username).":".urlencode($password)."@example.com/service.asmx?WSDL";

$context = stream_context_create([
'ssl' => [
// set some SSL/TLS specific options
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true,
]]);

$client = new SoapClient($url, [
'location' => $url,
'uri' => $url,
'stream_context' => $context,
'login' => $username,
'password' => $password
]);

$params=array(
'operation'=>’arguments',
'and’=>'other bull',
'goes’=>'here'
);

$response = $client->__soapCall('OperationName', array($params));
</code>```

Title: WSDL to PHP with Basic Auth

Body:
i’ve been trying to resolve this issue, but from what i understand, soap client connections to ssl+httpauth web services are more pain. I’ve googled and from what i understand, with my problem being solved, you can use the example below to solve your problem too(by using HttpAuth infos in both url and soapClient setup).

$username="test";
$password="test";
$url = "https://".urlencode($username).":".urlencode($password)."@example.com/service.asmx?WSDL";

$context = stream_context_create([
'ssl' => [
// set some SSL/TLS specific options
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true,
]]);

$client = new SoapClient($url, [
'location' => $url,
'uri' => $url,
'stream_context' => $context,
'login' => $username,
'password' => $password
]);

$params=array(
'operation'=>’arguments',
'and’=>'other bull',
'goes’=>'here'
);

$response = $client->__soapCall('OperationName', array($params));


问:
C# .NET include file
I searched a way to include a file in a web application (like a menu, so I won't have to edit it on all pages when applying changes), but haven't found something as simple as

```<code><?php include "Menu.html"; ?>
</code>```

Can you please help?

答:
Methods (C#)

Executable code:

Page include

```<code><!--#include file="a.aspx"-->
</code>```

Execute independently inside a page

```<code><% Server.Execute("a.aspx"); %>
</code>```

Non-executable code:

```<code><% Response.WriteFile("a.inc"); %>
</code>```

Title: C# .NET include file

Body:
I searched a way to include a file in a web application (like a menu, so I won't have to edit it on all pages when applying changes), but haven't found something as simple as

<?php include "Menu.html"; ?>

Can you please help?

Body:
Methods (C#)

Executable code:

Page include

<!--#include file="a.aspx"-->

Execute independently inside a page

<% Server.Execute("a.aspx"); %>

Non-executable code:

<% Response.WriteFile("a.inc"); %>


问:
Python: writing to CSV in a for-loop, conditionally adding value in particular column
Here's an example of the contents of my CSV file:

```<code>Fruit, colour, ripe,

apple, green,,
banana, yellow,,
pineapple, green,,
plum, purple,,
</code>```

I want to loop through the contents of the CSV file and according to a test (extrinsic to the CSV data, using an input value supplied to the enclosing function), end up with something like this:

```<code>Fruit, colour, ripe,

apple, green, true,
banana, yellow,,
pineapple, green,,
plum, purple, true,
</code>```

My current code looks like this:

```<code>csv_data = csv.reader(open('./data/fruit_data.csv', 'r'))
for row in csv_data:
    fruit = row[0]
    if fruit == input:
    # Here, write 'true' in the 'ripe' column.
</code>```

It's easy enough to add new data in one go, using the CSV module or pandas, but here I need to add the data iteratively. It seems that I can't change the CSV file in place(?), but if I write out to a different CSV file, it's going to overwrite on each match within the loop, so it'll only reflect that value.

答:
In order to make the changes, you have to add your new data to a location such as a list. This list will contain the results of your processing.

```<code>fruit_details= list()
csv_data = csv.reader(open('./data/fruit_data.csv', 'r'))
for row in csv_data:
    fruit = row[0]
    if fruit == input:
       fruit_details.append([row[0],row[1],'true'])
</code>```

The resulting list fruit_details, will then contain the fruits with true in the "ripe" column. If you one to append the non-fruit items, add and else statement which either puts false or row[2] as necessary.

Body:
Here's an example of the contents of my CSV file:

Fruit, colour, ripe,

apple, green,,
banana, yellow,,
pineapple, green,,
plum, purple,,

I want to loop through the contents of the CSV file and according to a test (extrinsic to the CSV data, using an input value supplied to the enclosing function), end up with something like this:

Fruit, colour, ripe,

apple, green, true,
banana, yellow,,
pineapple, green,,
plum, purple, true,

My current code looks like this:

csv_data = csv.reader(open('./data/fruit_data.csv', 'r'))
for row in csv_data:
    fruit = row[0]
    if fruit == input:
    # Here, write 'true' in the 'ripe' column.

It's easy enough to add new data in one go, using the CSV module or pandas, but here I need to add the data iteratively. It seems that I can't change the CSV file in place(?), but if I write out to a different CSV file, it's going to overwrite on each match within the loop, so it'll only reflect that value.

Body:
In order to make the changes, you have to add your new data to a location such as a list. This list will contain the results of your processing.

fruit_details= list()
csv_data = csv.reader(open('./data/fruit_data.csv', 'r'))
for row in csv_data:
    fruit = row[0]
    if fruit == input:
       fruit_details.append([row[0],row[1],'true'])

The resulting list fruit_details, will then contain the fruits with true in the "ripe" column. If you one to append the non-fruit items, add and else statement which either puts false or row[2] as necessary.


问:
Understanding SAS output data sets
SAS has several forms it uses to create output data sets from within a procedure.  It is not always clear whether or not a particular procedure can generate a data set and, if it seems to be able to, it's not always clear how.

Off the top of my head, here are some examples of how widely the syntax can differ.

Example 1

```<code>proc sort data = sashelp.baseball out = baseball_sorted;
  by
    league
    division
  ;
run;
</code>```

Example 2

```<code>proc means noprint data = baseball_sorted;
  by
    league
    division
  ;
  var nHits;
  output
    out = baseball_avg_hits (drop = _TYPE_ _FREQ_)
    mean = mean_hits
  ;
run;
</code>```

Example 3

```<code>ods exclude all;
ods output
  statistics  = baseball_statistics
  equality    = baseball_ftest
;
proc ttest data = baseball_sorted;
  class league;
  var nHits;
run;
ods exclude none;
</code>```

Example 4

The PROC ANOVA OUTSTAT= option.

It seems almost as if SAS has implemented each of these willy-nilly.  Is the SAS syntax dictating how to create a data set directed by some consistent approach I am not seeing or is it truly capricious and arbitrary?

答:
For PROC code, the syntax for outputting data is often specific to that procedure, which often feels willy-nilly.  (Your examples 1, 2, 4)  I think PROC developers are given a lot of freedom, and remember that many of these PROCS are 30+ years old.

The great thing about the Output Delivery System (ODS, your example 3) is it provides a single syntax for outputting data, regardless of the procedure.  So you can use the ODS OUTPUT statement with (almost?) any PROC.  The names and structures of the output objects will of course vary between PROCs.  So if you are looking for a consistent approach, I would focus on using ODS OUTPUT.  ODS was added in V7 (I think).

It would be interesting to try to find an example of an output dataset which could be made by a PROC but could not be made by ODS OUTPUT.  I hope there aren't any.  If that is the case, you could consider the range of OUTPUT statements/options within PROCs as legacy code.

Title: Understanding SAS output data sets

Body:
SAS has several forms it uses to create output data sets from within a procedure.  It is not always clear whether or not a particular procedure can generate a data set and, if it seems to be able to, it's not always clear how.

Off the top of my head, here are some examples of how widely the syntax can differ.

Example 1

proc sort data = sashelp.baseball out = baseball_sorted;
  by
    league
    division
  ;
run;

Example 2

proc means noprint data = baseball_sorted;
  by
    league
    division
  ;
  var nHits;
  output
    out = baseball_avg_hits (drop = _TYPE_ _FREQ_)
    mean = mean_hits
  ;
run;

Example 3

ods exclude all;
ods output
  statistics  = baseball_statistics
  equality    = baseball_ftest
;
proc ttest data = baseball_sorted;
  class league;
  var nHits;
run;
ods exclude none;

Example 4

The PROC ANOVA OUTSTAT= option.

It seems almost as if SAS has implemented each of these willy-nilly.  Is the SAS syntax dictating how to create a data set directed by some consistent approach I am not seeing or is it truly capricious and arbitrary?


问:
New input placeholder behavior in Safari 10 - no longer hides on change via JavaScript
Safari 10.0 in macOS Sierra seems to have changed the way the placeholder in an input behaves when the input value is changed via JavaScript. It now also differs from what Chrome (53.0.2785.116) is doing.

Until now, when setting an input value via JavaScript the placeholder would disappear. After setting the value back to empty via JavaScript, the placeholder would reappear.

Now, setting the input value via JavaScript does not hide the placeholder, until the input gains focus afterwards (e.g. by being clicked on).

Check this JS Bin for a demo: https://jsbin.com/rogoludahu/edit?html,js,output

Is this the intended behavior? If so, is there a clever workaround for hiding/unhiding the placeholder after a change via JavaScript?

Edit: This has now been filed at rdar://28412751 for Safari 10 and the Safari Technology Preview.

答: I ran into this problem earlier today. As far as I've seen, there is no good solution. My hacky workaround was to call .focus() and then .blur() on the element as soon as the value was given to it.


问:
Action Script 3 - Events between Spark and Custom Components
We are building an interface for a game.

The interface has a tabbed menu at the bottom of the screen, with each tab displaying different aspects of an object (called a node).

When you click on one of these parts, it becomes the focus, and we download it's details in XML, including all it's sub-nodes and parent nodes and then update the tab display accordingly, or at least that's what we'd like to happen.

What we have:

MainInterface.mxml

```<code><s:Application...
<fx:Script>
  <![CDATA[
    public var currentNode:Node = new Node();

    protected function selectNodeHandler(event:Event):void
      {
        loader = new URLLoader(new URLRequest(ourWebSite + event.target.id + ".xml"))
        //the xmlDownloaded function below is what changes the contents of currentNode
        loader.addEventListener(Event.COMPLETE, xmlDownloaded);
...
<s:SkinnableContainer  id="dashBoard"..
  <mx:TabNavigator...
    <s:NavigatorContent...
      <s:SkinnableDataContainer ...
        dataProvider="{currentNode.children}"
        itemRenderer="renderers.NodeRenderer">
</code>```

Node.as (valueObjects.Node)

```<code>...
  [Bindable] public var id:String;
  [Bindable] public var name:String;
  [Bindable] public var children:ArrayCollection = new ArrayCollection();
  [Bindable] public var parents:ArrayCollection = new ArrayCollection();
...
</code>```

NodeRenderer.mxml (renderers.NodeRenderer)

```<code><s:ItemRenderer ... click="nodeRenderer_clickHandler(event)">
<fx:Script>
  <![CDATA[
    protected function nodeRenderer_clickHandler(event:MouseEvent):void
    {
      var eventObject:Event = new Event ("nodeSelected");
      dispatchEvent(eventObject);
    }
 ...
 <s:Label text = "{data.name}"/>
</code>```

We tried adding an event listener for "selectNode" to the dashBoard:SkinnableContainer you see see above, but it didn't seem to want to take. We suspect this is because dashBoard is from a spark component and the dispatcher for "selectNode" is on of our own custom components, but we weren't sure... in any case that's what the code assist seemed to indicate as we had to write it in by hand.

We're not sure how to pick up the Events in FlashBuilder 4's debugger, so we're having trouble working out where it's going wrong. Basically, when someone clicks on the label of a child or parent node (that is displayed by the itemRenderer), we want a URLRequest sent to our website, with the url specific to the node clicked on. We then want a URLLoader listening for the return which will update public variable 'currentNode' when xmlDownloaded is called by the loader.

If you could clarify how the click event should be dispatched, what should be listening for it then sending the URLRequest and where the URLLoader that is listening for the xml data to return should be that would solve our problems. Alternatively, if there is a better (more conventional) way to be doing what we're trying to do that would also help, as we're relatively new to actionscript and flex.

答:
```<code> protected function selectNodeHandler(url:String):void
  {
    loader = new URLLoader(new URLRequest(url));

    //consider identifying the loader, for instance
    loader.name = url; // you could also pass a second parameter
    //to the function and assign it to the name property of the loader.

    //the xmlDownloaded function below is what changes the contents of currentNode
    loader.addEventListener(Event.COMPLETE, xmlDownloaded);
  }

 protected function nodeRenderer_clickHandler(event:MouseEvent):void
 {
     var url:String = ourWebSite + event.currentTarget.id + ".xml";
     selectNodeHandler( url );
 }

 protected function xmlDownloaded( event:Event ):void
 {
      //identify the target here with the name property
      var id:String = event.target.name;
 }
</code>```

Body:
We are building an interface for a game.

The interface has a tabbed menu at the bottom of the screen, with each tab displaying different aspects of an object (called a node).

When you click on one of these parts, it becomes the focus, and we download it's details in XML, including all it's sub-nodes and parent nodes and then update the tab display accordingly, or at least that's what we'd like to happen.

What we have:

MainInterface.mxml

<s:Application...
<fx:Script>
  <![CDATA[
    public var currentNode:Node = new Node();

    protected function selectNodeHandler(event:Event):void
      {
        loader = new URLLoader(new URLRequest(ourWebSite + event.target.id + ".xml"))
        //the xmlDownloaded function below is what changes the contents of currentNode
        loader.addEventListener(Event.COMPLETE, xmlDownloaded);
...
<s:SkinnableContainer  id="dashBoard"..
  <mx:TabNavigator...
    <s:NavigatorContent...
      <s:SkinnableDataContainer ...
        dataProvider="{currentNode.children}"
        itemRenderer="renderers.NodeRenderer">

Node.as (valueObjects.Node)

...
  [Bindable] public var id:String;
  [Bindable] public var name:String;
  [Bindable] public var children:ArrayCollection = new ArrayCollection();
  [Bindable] public var parents:ArrayCollection = new ArrayCollection();
...

NodeRenderer.mxml (renderers.NodeRenderer)

<s:ItemRenderer ... click="nodeRenderer_clickHandler(event)">
<fx:Script>
  <![CDATA[
    protected function nodeRenderer_clickHandler(event:MouseEvent):void
    {
      var eventObject:Event = new Event ("nodeSelected");
      dispatchEvent(eventObject);
    }
 ...
 <s:Label text = "{data.name}"/>

We tried adding an event listener for "selectNode" to the dashBoard:SkinnableContainer you see see above, but it didn't seem to want to take. We suspect this is because dashBoard is from a spark component and the dispatcher for "selectNode" is on of our own custom components, but we weren't sure... in any case that's what the code assist seemed to indicate as we had to write it in by hand.

We're not sure how to pick up the Events in FlashBuilder 4's debugger, so we're having trouble working out where it's going wrong. Basically, when someone clicks on the label of a child or parent node (that is displayed by the itemRenderer), we want a URLRequest sent to our website, with the url specific to the node clicked on. We then want a URLLoader listening for the return which will update public variable 'currentNode' when xmlDownloaded is called by the loader.

If you could clarify how the click event should be dispatched, what should be listening for it then sending the URLRequest and where the URLLoader that is listening for the xml data to return should be that would solve our problems. Alternatively, if there is a better (more conventional) way to be doing what we're trying to do that would also help, as we're relatively new to actionscript and flex.


问:
How would the process tree look having a code using fork()-C
I have the following code written in C and I would like to know how the process tree drawing looked like.</p>

```<code>#include <stdio.h>

int main(void) {
    // your code goes here
    for(int i=0;i<=1;i++){
    for(int j=0;j<=1;j++){
        fork();
        printf("Hello");
    }

    }
    return 0;
}
</code>```

答:
Why don't you just use 'ps' (on linux) or 'tasklist' (on windows) command to check? For example,

ps -ef f

Body:
I have the following code written in C and I would like to know how the process tree drawing looked like.

#include <stdio.h>

int main(void) {
    // your code goes here
    for(int i=0;i<=1;i++){
    for(int j=0;j<=1;j++){
        fork();
        printf("Hello");
    }

    }
    return 0;
}


问:
Excel - Get Value from 'Column A' Based on MAX of 'Column L'
I have values in column L which are the number of calls an agent has made. The agents name is in column A.

I am trying to get the max value from column L and display the name of that agent.

Here's an example of my data:

```<code> Column A  |  Column B |  Column C | ... | Column L
Agent Name | 25-Mar-17 | 26-Mar-17 | ... |  Totals
---------------------------------------------------
   Kelly         5           9       ...      14
  Bryson         7           4       ...      11
 Brittany        3          14       ...      17
</code>```

I would want the calculation to display Brittany, as she has the highest total.

答:
Use INDEX/MATCH:

```<code>=INDEX(A:A,MATCH(MAX(L:L),L:L,0))
</code>```

Body:
I have values in column L which are the number of calls an agent has made. The agents name is in column A.

I am trying to get the max value from column L and display the name of that agent.

Here's an example of my data:

 Column A  |  Column B |  Column C | ... | Column L
Agent Name | 25-Mar-17 | 26-Mar-17 | ... |  Totals
---------------------------------------------------
   Kelly         5           9       ...      14
  Bryson         7           4       ...      11
 Brittany        3          14       ...      17

I would want the calculation to display Brittany, as she has the highest total.

Body:
Use INDEX/MATCH:

=INDEX(A:A,MATCH(MAX(L:L),L:L,0))


问:
Remove newline in textarea generated by HAML / Form Builder
I have a very simple Rails form.:

```<code>= form_for @object :remote => true do |form|
   = form.text_area :text, :class => 'form-control'
</code>```

For a new object, with a nil text attribute, this generates:

<textarea class="form-control" name="object[text]" id="object_text">    </textarea>

The blank space in that is a newline:

```<code>(byebug) form.text_area :text, :class => 'form-control'
"<textarea class=\"form-control\" name=\"user_deactivation[reason_text]\" id=\"user_deactivation_reason_text\">\n</textarea>"
</code>```

I strip out the leading and trailing spaces on save, so data wise, its not a big deal, but when the user clicks on this field, it appears indented.

Relevant software versions:

Rails 5.02

haml-4.0.7

The text area is in a bootstrap 3 dialog

Why is this newline being generated and how can I stop it?

答:
This is not an ideal answer, but it does work.  I would like something better:

```<code> = find_and_preserve(form.text_area :text, :class => 'form-control')
</code>```

Can that be automatic?  Is there a way to have the text_area helper not insert a newline?

Body:
I have a very simple Rails form.:

= form_for @object :remote => true do |form|
   = form.text_area :text, :class => 'form-control'

For a new object, with a nil text attribute, this generates:

<textarea class="form-control" name="object[text]" id="object_text">    </textarea>

The blank space in that is a newline:

(byebug) form.text_area :text, :class => 'form-control'
"<textarea class=\"form-control\" name=\"user_deactivation[reason_text]\" id=\"user_deactivation_reason_text\">\n</textarea>"

I strip out the leading and trailing spaces on save, so data wise, its not a big deal, but when the user clicks on this field, it appears indented.

Relevant software versions:

Rails 5.02

haml-4.0.7

The text area is in a bootstrap 3 dialog

Why is this newline being generated and how can I stop it?

Body:
This is not an ideal answer, but it does work.  I would like something better:

 = find_and_preserve(form.text_area :text, :class => 'form-control')

Can that be automatic?  Is there a way to have the text_area helper not insert a newline?


问:
Creating a table of counts by some factor level in R
I have some data of foods eaten on different days.

```<code>day <- c(1,1,1,1,2,2,2,3,3,3,3,3)
food <- c('pizza','pizza','taco','snake','snake','taco','taco','pizza','taco','pizza','taco','snake')
all <- data.frame(day, food)
</code>```

I'd like to create a table with food on the x axis, day on the y axis, and the number of foods per day in the matrices such that

```<code>food.list <- unique(all$food)
 day.list <- unique(all$day )
output <- data.frame(c(2,1,1),c(0,2,1),c(2,2,1))
output
      1 2 3
pizza 2 0 2
taco  1 2 2
snake 1 1 1
</code>```

What is a straightforward way to solve this problem?

答:
You could also do this using xtabs:

```<code>xtabs(col~food+day, cbind(all, col=1))

# OR

xtabs(col~food+day, transform(all, col=1))

# OR

xtabs(~food+day, all) # thanks to user20650

#      day
#food    1 2 3
#  pizza 2 0 2
#  snake 1 1 1
#  taco  1 2 2
</code>```

Body:
I have some data of foods eaten on different days.

day <- c(1,1,1,1,2,2,2,3,3,3,3,3)
food <- c('pizza','pizza','taco','snake','snake','taco','taco','pizza','taco','pizza','taco','snake')
all <- data.frame(day, food)

I'd like to create a table with food on the x axis, day on the y axis, and the number of foods per day in the matrices such that

food.list <- unique(all$food)
 day.list <- unique(all$day )
output <- data.frame(c(2,1,1),c(0,2,1),c(2,2,1))
output
      1 2 3
pizza 2 0 2
taco  1 2 2
snake 1 1 1

What is a straightforward way to solve this problem?

Body:
You could also do this using xtabs:

xtabs(col~food+day, cbind(all, col=1))

# OR

xtabs(col~food+day, transform(all, col=1))

# OR

xtabs(~food+day, all) # thanks to user20650

#      day
#food    1 2 3
#  pizza 2 0 2
#  snake 1 1 1
#  taco  1 2 2


问:
Is this a limitation of the Idris totality checker, or am I missing something?
Idris claims the following code is not total:

```<code>data Foo = Bar (Maybe Foo)

foos : Foo -> List Foo
foos (Bar (Just foo)) = foo :: (foos foo)
foos (Bar Nothing) = Nil
</code>```

Instead I can do

```<code>foos t@(Bar (Just foo)) = foo :: foos (assert_smaller t foo)
</code>```

but this seems unnecessary.  Obviously the first Foo I create must be constructed as Bar Nothing, and subsequent constructions can only be constructed in the same way or from existing terms, and so this should always terminate.

Is there some similar case where totality cannot be decided, or is Idris not yet able to handle this type of situation?

答: You are correct. Idris is not yet able to handle this type of situation.</p>

Body:
Idris claims the following code is not total:

data Foo = Bar (Maybe Foo)

foos : Foo -> List Foo
foos (Bar (Just foo)) = foo :: (foos foo)
foos (Bar Nothing) = Nil

Instead I can do

foos t@(Bar (Just foo)) = foo :: foos (assert_smaller t foo)

but this seems unnecessary.  Obviously the first Foo I create must be constructed as Bar Nothing, and subsequent constructions can only be constructed in the same way or from existing terms, and so this should always terminate.

Is there some similar case where totality cannot be decided, or is Idris not yet able to handle this type of situation?


问:
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 could use format():

```<code>filename = 'roll_{}_{}'.format(roll, ID)
</code>```

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 could use format():

filename = 'roll_{}_{}'.format(roll, ID)


问:
ActiveRecord::Enum - PG::InvalidTextRepresentation: ERROR: invalid input syntax for integer:
I am having a strange error and was hoping someone could point me in the right direction. I have a model called Organizations, and a attribute called department, see the excerpt from the schema below:

```<code>t.integer  "department",  default: 0
</code>```

Inside my model have defined my enums for this attribute, as I am using ActiveRecord::Enum, like below:

```<code>enum department: [:conferences, :design_teams, :services, :clubs, :events, :communications]
</code>```

But when I query, JobPosting.joins(job: :organization).where(organizations: { department: 'conferences' }) I get an error that reads:

PG::InvalidTextRepresentation: ERROR:  invalid input syntax for integer: "conferences"

FYI: An Organization has_many Jobs, and Job has_many JobPostings.

But when I query Organization.where(department: 'conferences') it works.

Any help would be greatly appreciated.

答:
Other way is to set text-based enums. In my opinion it is the best way for enum:

```<code>DEPARTMENTS_ENUM = [:conferences, :design_teams, :services, :clubs, :events, :communications]
enum department: Hash[*DEPARTMENTS_ENUM.collect{|v| [v, v]}.flatten()]
</code>```

It will work after department column type will change.

```<code>Organization.where(department: 'conferences')
</code>```

Will work too

Body:
I am having a strange error and was hoping someone could point me in the right direction. I have a model called Organizations, and a attribute called department, see the excerpt from the schema below:

t.integer  "department",  default: 0

Inside my model have defined my enums for this attribute, as I am using ActiveRecord::Enum, like below:

enum department: [:conferences, :design_teams, :services, :clubs, :events, :communications]

But when I query, JobPosting.joins(job: :organization).where(organizations: { department: 'conferences' }) I get an error that reads:

PG::InvalidTextRepresentation: ERROR:  invalid input syntax for integer: "conferences"

FYI: An Organization has_many Jobs, and Job has_many JobPostings.

But when I query Organization.where(department: 'conferences') it works.

Any help would be greatly appreciated.

Body:
Other way is to set text-based enums. In my opinion it is the best way for enum:

DEPARTMENTS_ENUM = [:conferences, :design_teams, :services, :clubs, :events, :communications]
enum department: Hash[*DEPARTMENTS_ENUM.collect{|v| [v, v]}.flatten()]

It will work after department column type will change.

Organization.where(department: 'conferences')

Will work too


问:
JavaScript Sort compare function fails in Internet Explorer
I have a function which orders dates based on a pivot. Note that this function ignores the year of the supplied dates. For example, given a pivot date of 1-July, all dates will be ordered from 1-July to 31-June.  The problem seems to be with my sort compare function which works perfectly fine in Chrome and Firefox, however fails in IE.  The resulting statsDataPoints (Array) does not get sorted.

This is what the dates array looks like:

[{"Min":"6.0", "Mean":"10.8", "Max":"32.1", "StdDev":"7.5", "LowerPercentile":"6.7", "Median":"8.0", "UpperPercentile":"11.2", "_Name":"30-Mar"}, {"Min":"6.0", "Mean":"11.1", "Max":"31.7", "StdDev":"7.4", "LowerPercentile":"7.3", "Median":"8.7", "UpperPercentile":"11.1", "_Name":"31-Mar"}, {"Min":"6.0", "Mean":"10.9", "Max":"31.4", "StdDev":"7.3", "LowerPercentile":"7.2", "Median":"8.4", "UpperPercentile":"11.0", "_Name":" 1-Apr"}, ... ]```
</div>
</div>
</p>

<p>This is my function:</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-js lang-js prettyprint-override"><code>/**
 * Returns a function which orders dates based on a pivot. Note that this function ignores the year of the
 * supplied dates. It is easiest to illustrate how this function works with an example:
 * Given a pivot date of 1-July, all dates will be ordered from 1-July to 31-June.
 *
 * @param {Array}  dates    An array of objects containing a date key.
 * @param {String} pivot    The pivot date we are sorting from (should be in the same format as dateKey)
 */

var dummyYear = 2000;
var pivot = moment(readingStartDate).format("DD-MMM");
pivot = moment(pivot, "DD-MMM").year(dummyYear);

statsDataPoints.sort(function(aDate, bDate) {

 var a = moment(aDate["_Name"], "DD-MMM").year(dummyYear).toDate();
 var b = moment(bDate["_Name"], "DD-MMM").year(dummyYear).toDate();

 if (((a < pivot) && (pivot < b)) || (a > b)) {
  return 1;
 } else if (((b < pivot) && (pivot < a)) || (a < b)) {
  return -1;
 }
 return 0;

});</code>```

答:
Your comparison function is inconsistent: Assuming x=1, y=3 and pivot=2 you get compare(x, y) == 1 but also  compare(y, x) == 1 because of the || in the first condition.

I suspect you meant to use

```<code>if ((a < pivot) && (pivot < b))
    return 1;
if ((b < pivot) && (pivot < a))
    return -1;
if (a > b) {
    return 1;
if (a < b)
    return -1;
return 0;
</code>```

Body:
I have a function which orders dates based on a pivot. Note that this function ignores the year of the supplied dates. For example, given a pivot date of 1-July, all dates will be ordered from 1-July to 31-June.  The problem seems to be with my sort compare function which works perfectly fine in Chrome and Firefox, however fails in IE.  The resulting statsDataPoints (Array) does not get sorted.

This is what the dates array looks like:

[{"Min":"6.0", "Mean":"10.8", "Max":"32.1", "StdDev":"7.5", "LowerPercentile":"6.7", "Median":"8.0", "UpperPercentile":"11.2", "_Name":"30-Mar"}, {"Min":"6.0", "Mean":"11.1", "Max":"31.7", "StdDev":"7.4", "LowerPercentile":"7.3", "Median":"8.7", "UpperPercentile":"11.1", "_Name":"31-Mar"}, {"Min":"6.0", "Mean":"10.9", "Max":"31.4", "StdDev":"7.3", "LowerPercentile":"7.2", "Median":"8.4", "UpperPercentile":"11.0", "_Name":" 1-Apr"}, ... ]

This is my function:

/**
 * Returns a function which orders dates based on a pivot. Note that this function ignores the year of the
 * supplied dates. It is easiest to illustrate how this function works with an example:
 * Given a pivot date of 1-July, all dates will be ordered from 1-July to 31-June.
 *
 * @param {Array}  dates    An array of objects containing a date key.
 * @param {String} pivot    The pivot date we are sorting from (should be in the same format as dateKey)
 */

var dummyYear = 2000;
var pivot = moment(readingStartDate).format("DD-MMM");
pivot = moment(pivot, "DD-MMM").year(dummyYear);

statsDataPoints.sort(function(aDate, bDate) {

 var a = moment(aDate["_Name"], "DD-MMM").year(dummyYear).toDate();
 var b = moment(bDate["_Name"], "DD-MMM").year(dummyYear).toDate();

 if (((a < pivot) && (pivot  b)) {
  return 1;
 } else if (((b < pivot) && (pivot < a)) || (a < b)) {
  return -1;
 }
 return 0;

});

Body:
Your comparison function is inconsistent: Assuming x=1, y=3 and pivot=2 you get compare(x, y) == 1 but also  compare(y, x) == 1 because of the || in the first condition.

I suspect you meant to use

if ((a < pivot) && (pivot < b))
    return 1;
if ((b < pivot) && (pivot < a))
    return -1;
if (a > b) {
    return 1;
if (a < b)
    return -1;
return 0;


问:
How to display output of tasks of an Ansible playbook without using the '-v' option
I have the following task to print out the current version of jenkins that is installed on some servers:

```<code>---
- hosts: all
  remote_user: user
  tasks:
      - name: Printing the Jenkins version running on the masters
        yum:
          name: jenkins
        register: version

      - debug: var=version
</code>```

I am trying to avoid using the -v option when running the playbook with hopes to keep the output as clean as possible.

If the playbook is run without the -v option the output looks like this:

```<code>TASK [Printing the jenkins version that is installed on each of the servers]***************
ok: [Server1]
ok: [Server2]
ok: [Server3]

TASK [debug] *******************************************************************    ok: [Server1] => {
"changed": false,
"version": "VARIABLE IS NOT DEFINED!"
}

ok: [Server1] => {
"changed": false,
"version": "VARIABLE IS NOT DEFINED!"
}

ok: [Server1] => {
"changed": false,
"version": "VARIABLE IS NOT DEFINED!"
}
</code>```

However it returns that version is not defined. I am confused as to why this is happening because I have done the printing the same way for a bunch of other tasks without any problems. Any suggestions are greatly appreciated.

答:
You can acheive this using the shell and debug</p>

```<code>---
- hosts: all
  remote_user: user
  become: True
  become_method: sudo
  tasks:
      - name: Printing the Jenkins version running on the masters
        shell: cat /var/lib/jenkins/config.xml | grep '<version>'
        register: version

      - debug: var={{ version['stdout'] }}
</code>```

Body:
I have the following task to print out the current version of jenkins that is installed on some servers:

---
- hosts: all
  remote_user: user
  tasks:
      - name: Printing the Jenkins version running on the masters
        yum:
          name: jenkins
        register: version

      - debug: var=version

I am trying to avoid using the -v option when running the playbook with hopes to keep the output as clean as possible.

If the playbook is run without the -v option the output looks like this:

TASK [Printing the jenkins version that is installed on each of the servers]***************
ok: [Server1]
ok: [Server2]
ok: [Server3]

TASK [debug] *******************************************************************    ok: [Server1] => {
"changed": false,
"version": "VARIABLE IS NOT DEFINED!"
}

ok: [Server1] => {
"changed": false,
"version": "VARIABLE IS NOT DEFINED!"
}

ok: [Server1] => {
"changed": false,
"version": "VARIABLE IS NOT DEFINED!"
}

However it returns that version is not defined. I am confused as to why this is happening because I have done the printing the same way for a bunch of other tasks without any problems. Any suggestions are greatly appreciated.

Body:
You can acheive this using the shell and debug

---
- hosts: all
  remote_user: user
  become: True
  become_method: sudo
  tasks:
      - name: Printing the Jenkins version running on the masters
        shell: cat /var/lib/jenkins/config.xml | grep '<version>'
        register: version

      - debug: var={{ version['stdout'] }}


问:
Override parents z-index in child
I have a part of DOM like this

```<code><div class="parent">
   <a class="link">Link me </a>
</div>
</code>```

CSS :

```<code>.parent {
   z-index: -2;
}
.link {
 z-index:9999;
}
</code>```

I want a part of "parent" to wrap overlap/wrap under the previous div. So, I am using z-index -2. No matter what z-index I use for link, its not clickable. Any suggestions.

PS: I cant use larger z-index for parent's predecessor div. Because "parent" has 3 siblings (columns) that do not need to go under the predecessor.

答:
That's because of the parent/child relationship. I f the parent is behind another element, also its child will be.

But you can add pointer-events: none to the previous (to be overlapped) DIV if it doesn't contain any links itself. This will allow to "click through it".

Note: IF the previous DIV contain links, that won't work, since those links won't work anymore.

Title: Override parents z-index in child

Body:
I have a part of DOM like this

   Link me

CSS :

.parent {
   z-index: -2;
}
.link {
 z-index:9999;
}

I want a part of "parent" to wrap overlap/wrap under the previous div. So, I am using z-index -2. No matter what z-index I use for link, its not clickable. Any suggestions.

PS: I cant use larger z-index for parent's predecessor div. Because "parent" has 3 siblings (columns) that do not need to go under the predecessor.


问:
SQL single table with two columns
I have a single table: Checking, with two columns: ID, Memo

ID is the primary key.

I would like a query that returns both columns: ID, Memo BUT only where Memo is DISTINCT

I can do the following to get the distinct values from Memo:

```<code>SELECT DISTINCT(memo)
FROM checking
</code>```

How do I return those Memo values and their values from the ID column?

I've run in circles trying inner and outer joins but I'm failing.

Thanks for your help

Sample data:

```<code>ID        Memo
1         a
2         c
3         e
4         g
5         a
6         c
</code>```

The desired return:

```<code>1,a
2,c
3,e
4,g
</code>```

5 and 6 would not be included because they have duplicate memo values.

Thanks again for your help.

答:
SELECT  min(id), memo
FROM checking
group by memo</p>

Title: SQL single table with two columns

Body:
I have a single table: Checking, with two columns: ID, Memo

ID is the primary key.

I would like a query that returns both columns: ID, Memo BUT only where Memo is DISTINCT

I can do the following to get the distinct values from Memo:

SELECT DISTINCT(memo)
FROM checking

How do I return those Memo values and their values from the ID column?

I've run in circles trying inner and outer joins but I'm failing.

Thanks for your help

Sample data:

ID        Memo
1         a
2         c
3         e
4         g
5         a
6         c

The desired return:

1,a
2,c
3,e
4,g

5 and 6 would not be included because they have duplicate memo values.

Thanks again for your help.


问:
How to Make Bootstrap 3 Button Text Responsive
Can you please take a look at This Demo and let me know how I can make only the text inside the buttons responsive to the size of the button?

```<code><div class="container"><div class="well">
    <button type="button" class="btn btn-default btn-lg btn-block">Make Me Responsive!</button>
</div></div>
</code>```

As you can see from the demo the buttons test font size stays same as the initial times on resizing the windows. Can you please let  me know how I can update id without using the body element?

Thanks,

答:
I tried a different solution and it worked. I share it here:</p>

```<code>  <button type="button" class="enviaPedido btn btn-primary btn-sm">
    <span class="visible-xs-block">Pedido</span>
    <span class="hidden-xs">Convertir en pedido</span>
  </button>
</code>```

Body:
Can you please take a look at This Demo and let me know how I can make only the text inside the buttons responsive to the size of the button?

    <button type="button" class="btn btn-default btn-lg btn-block">Make Me Responsive!</button>

As you can see from the demo the buttons test font size stays same as the initial times on resizing the windows. Can you please let  me know how I can update id without using the body element?

Thanks,

Body:
I tried a different solution and it worked. I share it here:

  <button type="button" class="enviaPedido btn btn-primary btn-sm">
    <span class="visible-xs-block">Pedido</span>
    <span class="hidden-xs">Convertir en pedido</span>
  </button>


问:
R subset of data frame for cohort analysis
I have following data in the data frame df

```<code>persons  year
personA  2015
personB  2016
personC  2015
personB  2015
</code>```

how do I use subset function in R to filter personB who is in 2015 and 2016
I am using following Code, but does not work

```<code>df1 <- subset(df, (year==2015 & year ==2016))
</code>```

答:
```<code>df2 <- df[(df$year== 2015 | df$year== 2016),][1]

## get each person and the number of his appearence in the dataframe
t <- table(df2)
#
# personA personB personC
# 1       2       1

t[t>1]
# personB
# 2
</code>```

The dataframe

```<code>df <- data.frame("persons" = c("personA","personB","personC","personB"),
 "year" = c(2015,2016,2015,2015))
</code>```

EDIT

Another solution using duplicated

```<code> duplicated(df$persons)
#[1] FALSE FALSE FALSE  TRUE
 df[duplicated(df$persons),1]
# personB
</code>```

Body:
I have following data in the data frame df

persons  year
personA  2015
personB  2016
personC  2015
personB  2015

how do I use subset function in R to filter personB who is in 2015 and 2016
I am using following Code, but does not work

df1 <- subset(df, (year==2015 & year ==2016))

Body:
df2 <- df[(df$year== 2015 | df$year== 2016),][1]

## get each person and the number of his appearence in the dataframe
t <- table(df2)
#
# personA personB personC
# 1       2       1

t[t>1]
# personB
# 2

The dataframe

df <- data.frame("persons" = c("personA","personB","personC","personB"),
 "year" = c(2015,2016,2015,2015))

EDIT

Another solution using duplicated

 duplicated(df$persons)
#[1] FALSE FALSE FALSE  TRUE
 df[duplicated(df$persons),1]
# personB