问:
Relative layout params in kotlin
I am trying to set relative layout params programmatically. I can set params using java but not know how to accomplish using kotlin. So what I have tried is as follows :

MainActivity class

```<code>    class MainActivity : AppCompatActivity() {

    lateinit var context : Context
    override fun onCreate(savedInstanceState: android.os.Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        context=this
        asdasd.text="finaly done";
   var  param:RelativeLayout.LayoutParams =//don't know what to do here
            val i:Int=1
            var temp :TextView = TextView(this);
            temp.id=i
            temp.layoutParams = param ;
            temp.text= "TextView"+i
            Log.e(ContentValues.TAG, "onCreate: " + i)

    }
}
</code>```

Any help is appreciated!

答:
```<code>    lateinit var r1: RelativeLayout
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
       r1= RelativeLayout(this)
       var rlp : RelativeLayout.LayoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT)

    }
</code>```

Title: Relative layout params in kotlin

Body:
I am trying to set relative layout params programmatically. I can set params using java but not know how to accomplish using kotlin. So what I have tried is as follows :

MainActivity class

    class MainActivity : AppCompatActivity() {

    lateinit var context : Context
    override fun onCreate(savedInstanceState: android.os.Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        context=this
        asdasd.text="finaly done";
   var  param:RelativeLayout.LayoutParams =//don't know what to do here
            val i:Int=1
            var temp :TextView = TextView(this);
            temp.id=i
            temp.layoutParams = param ;
            temp.text= "TextView"+i
            Log.e(ContentValues.TAG, "onCreate: " + i)

    }
}

Any help is appreciated!


来源: stackexchange

问:
Import private rsa key fail
I have used the below example for encrypting and decrypting some text in python and it works:

RSA encryption and decryption in Python

However when I write the private key to a file for future use and then import it to decrpyt some text I get:

"ValueError: RSA key format is not supported."

I have exported the private key to a file using:

```<code>privkey = key.exportKey()

f= open("/home/sam/samomate.pem","w+")
f.write(privkey)
f.close()
</code>```

Try to import it using:

```<code>pkey = f.read()
keyDER = b64decode(pkey)
privkey=RSA.importKey(keyDER, passphrase=None)
</code>```

I added the base64 decode on the back of googleing the error to no avail.

Any assistance on this or better alternatives would be greatly appreciated.

Cheers

答:
I tried running this code and to me it works.

I didn't use the b64decode, that is not expected.

I'm not sure you've omitted any lines of code but to read a file you should use:

```<code>pkey_file = open(filename, "r")
pkey = f.read()
</code>```

Then this line did not raise a ValueError:

```<code>privkey = RSA.importKey(pkey)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Import private rsa key fail

Body:
I have used the below example for encrypting and decrypting some text in python and it works:

RSA encryption and decryption in Python

However when I write the private key to a file for future use and then import it to decrpyt some text I get:

"ValueError: RSA key format is not supported."

I have exported the private key to a file using:

privkey = key.exportKey()

f= open("/home/sam/samomate.pem","w+")
f.write(privkey)
f.close()

Try to import it using:

pkey = f.read()
keyDER = b64decode(pkey)
privkey=RSA.importKey(keyDER, passphrase=None)

I added the base64 decode on the back of googleing the error to no avail.

Any assistance on this or better alternatives would be greatly appreciated.

Cheers

Body:
I tried running this code and to me it works.

I didn't use the b64decode, that is not expected.

I'm not sure you've omitted any lines of code but to read a file you should use:

pkey_file = open(filename, "r")
pkey = f.read()

Then this line did not raise a ValueError:

privkey = RSA.importKey(pkey)


问:
How can I define an interface for an array of objects?
I have the following interface and code. I thought I was doing the definitions correctly but I am getting an error:

```<code>interface IenumServiceGetOrderBy { id: number; label: string; key: any }[];
</code>```

and:

```<code>getOrderBy = (entity): IenumServiceGetOrderBy => {
        var result: IenumServiceGetOrderBy;
        switch (entity) {
            case "content":
                result =
                [
                    { id: 0, label: 'CId', key: 'contentId' },
                    { id: 1, label: 'Modified By', key: 'modifiedBy' },
                    { id: 2, label: 'Modified Date', key: 'modified' },
                    { id: 3, label: 'Status', key: 'contentStatusId' },
                    { id: 4, label: 'Status > Type', key: ['contentStatusId', 'contentTypeId'] },
                    { id: 5, label: 'Title', key: 'title' },
                    { id: 6, label: 'Type', key: 'contentTypeId' },
                    { id: 7, label: 'Type > Status', key: ['contentTypeId', 'contentStatusId'] }
                ];
                break;
        }
        return result;
    };
</code>```

Error:

```<code>Error   190 Cannot convert '{}[]' to 'IenumServiceGetOrderBy':
    Type '{}[]' is missing property 'id' from type 'IenumServiceGetOrderBy'
</code>```

答:
Easy option with no tslint errors ...</p>

```<code>export interface MyItem {
    id: number
    name: string
}

export type MyItemList = [MyItem]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following interface and code. I thought I was doing the definitions correctly but I am getting an error:

interface IenumServiceGetOrderBy { id: number; label: string; key: any }[];

and:

getOrderBy = (entity): IenumServiceGetOrderBy => {
        var result: IenumServiceGetOrderBy;
        switch (entity) {
            case "content":
                result =
                [
                    { id: 0, label: 'CId', key: 'contentId' },
                    { id: 1, label: 'Modified By', key: 'modifiedBy' },
                    { id: 2, label: 'Modified Date', key: 'modified' },
                    { id: 3, label: 'Status', key: 'contentStatusId' },
                    { id: 4, label: 'Status > Type', key: ['contentStatusId', 'contentTypeId'] },
                    { id: 5, label: 'Title', key: 'title' },
                    { id: 6, label: 'Type', key: 'contentTypeId' },
                    { id: 7, label: 'Type > Status', key: ['contentTypeId', 'contentStatusId'] }
                ];
                break;
        }
        return result;
    };

Error:

Error   190 Cannot convert '{}[]' to 'IenumServiceGetOrderBy':
    Type '{}[]' is missing property 'id' from type 'IenumServiceGetOrderBy'

Body:
Easy option with no tslint errors ...

export interface MyItem {
    id: number
    name: string
}

export type MyItemList = [MyItem]


问:
Can I use symbolic cross product operations in sympy

Hi,

I am trying to write a symbolic library for computing 3D polynomials
in an analytical fashion (the variable is a real value t, and the monomials of the polynomials are 3D vectors). In particular, I want to compute the cross product of two polynomials (in a follow up to that question ). In Sympy, I found that I can either:

Use explicit vector variables (with real values) from the sympy.physics.mechanics package, and in this case the cross product is defined.

Use matrix symbols, but the cross product is not defined for those.

Is there any way that I can represent symbolically the cross product in sympy?

edit: In particular, I am interested in nullifying the cross product of two identical vectors, and taking into account the anticommutative property when factorizing a polynomial in terms of one of the vectors.

new edit:
To make myself more clear, I want to stay on a "symbolic level". That is,
I don't want to develop the terms of my vector along each variable.

For instance, here is the code to compute a Bezier curve:

```<code>from sympy import *

init_printing(use_unicode=True)

from scipy.special import binom

#default control points of a Bezier curve
p_is = [symbols('p'+str(i))  for i in range(5)]

class Bezier:
    #eq is the equation of the curve, pis are the stored control point
    #for special purpose such as the derivatives
    def __init__(self, deg, eq = None, pis = None):
        assert(deg)
        self.deg = deg;
        n_pts = deg +1
        if pis == None:
            self.pis = p_is[:n_pts]
        else:
            self.pis = pis[:];
        if eq == None:
            #computing the bernstein polynoms for a given degree
            factors = [binom(deg,i) * t**i * (1-t)**(deg-i)*pis[i] for i in range(n_pts)]
            self.eq = sum(factors);
        else:
            self.eq = eq

    def __repr__(self):
        res  = "Degree : "        + str(self.deg)
        res += "\nEquation : "    + self.eq.__repr__()
        res += "\nwaypoints :\n"  + str(self.pis)
        return res

    def __str__(self):
        return self.__repr__()

b = Bezier(3)

print b
# Degree : 3
# Equation : 1.0*p0*(-t + 1)**3 + 3.0*p1*t*(-t + 1)**2 + 3.0*p2*t**2*(-t + 1) + 1.0*p3*t**3
# waypoints :
# [p0, p1, p2, p3]

print b.eq
# 1.0*p0*(-t + 1)**3 + 3.0*p1*t*(-t + 1)**2 + 3.0*p2*t**2*(-t + 1) + 1.0*p3*t**3
</code>```

As one can see, the fact that the variables p_is are vector is not really relevant, except in the case where the cross product appears.
If I were to compute the cross product of b with itself, then several terms would disappear because the some vectors would be crossed against themselves.

What I tried to do was to "emulate" the cross product with a simple multiplication, and then iterate over the resulting equation to remove all the squared terms (that correspond to zero). But this is not sufficient
because the product does not preserve the anticomutative aspect of the cross product.

What I would really like would be for the actual cross product sign (say X) appear in the equation. I hope I am clearer

Thanks a lot for your help

Steve

答:
I found a solution that works for my case (where I only apply cross product once, some reflexion is needed to consider an extension). The idea is to use additional symbols to represent the skew symmetric-matrix that achieves the cross product. For instance p0 ^ p1 will be written Cp0 * p1. I implemented a method that achieves this, and also makes sure that if pi ^ pi = 0.

To allow a better factorization, I introduced an arbitrary order of transformation based on the alphabetic order of the symbols.
This means that p2 ^ p1 will be written -Cp1 * p2
The reason for this is that otherwise simplifications such as Cp2 ^ p1 + Cp1 ^p2 = 0 will not be detected by sympy.

Anyway, this is rather hacky but in my case it allowed me to write my library, so here it is.

The method that performs the cross product is "cross", at the end of the file.

```<code>#declaring vector symbols variables
p_is = [symbols('p'+str(i))  for i in range(20)]
#the cross product will be represented
#by the skew symmetric matrix Cpi for a vector pi.
#Since in the resulting equation, symbols seem to appeer
#in alphabetic order, the matrix multiplication will be coherent
p_isX = [symbols('Cp'+str(i)+'')  for i in range(20)]

#achieves the cross product between two elements
#s0 and s1 are the considered vector symbols (here, two pis)
#e0 and e1 are the scalar multiplier of each term
def crossElement(s0,e0,s1,e1):
    if s0 == s1:
        return 0
    else:
        # here, take order of apparition into account to allow
        # future factorization. Otherwise
        # something like p0 X p1 + p1 X p0 will not be dientified as zero
        id0 = p_is.index(s0)
        id1 = p_is.index(s1)
        if(id0 < id1):
            return simplify(e1*e0*p_isX[id0]*s1)
        else:
            return simplify((-e1)*e0*p_isX[id1]*s0)

#retrieve all the pis and associate scalar factors
#from an equation
def getAllSymbols(eq):
    res = []
    for el in p_is:
        dic = eq.as_poly(el).as_dict()
        if(len(dic) > 1):
            res += [(el, dic[(1,)])]
    return res;

#generates the cross product of two equations,
#where each pi term is a vector, and others
#are scalar variable.
#cross product
def cross(eq1,eq2):
    decomp1 = getAllSymbols(eq1)
    decomp2 = getAllSymbols(eq2)
    res = 0
    #applies distributive cross product between
    #all terms of both equations
    for (s0, e0) in decomp1:
        for (s1, e1) in decomp2:
            res += crossElement(s0,e0,s1,e1)
    return res
</code>```

Body:
Hi,

I am trying to write a symbolic library for computing 3D polynomials
in an analytical fashion (the variable is a real value t, and the monomials of the polynomials are 3D vectors). In particular, I want to compute the cross product of two polynomials (in a follow up to that question ). In Sympy, I found that I can either:

Use explicit vector variables (with real values) from the sympy.physics.mechanics package, and in this case the cross product is defined.

Use matrix symbols, but the cross product is not defined for those.

Is there any way that I can represent symbolically the cross product in sympy?

edit: In particular, I am interested in nullifying the cross product of two identical vectors, and taking into account the anticommutative property when factorizing a polynomial in terms of one of the vectors.

new edit:
To make myself more clear, I want to stay on a "symbolic level". That is,
I don't want to develop the terms of my vector along each variable.

For instance, here is the code to compute a Bezier curve:

from sympy import *

init_printing(use_unicode=True)

from scipy.special import binom

#default control points of a Bezier curve
p_is = [symbols('p'+str(i))  for i in range(5)]

class Bezier:
    #eq is the equation of the curve, pis are the stored control point
    #for special purpose such as the derivatives
    def __init__(self, deg, eq = None, pis = None):
        assert(deg)
        self.deg = deg;
        n_pts = deg +1
        if pis == None:
            self.pis = p_is[:n_pts]
        else:
            self.pis = pis[:];
        if eq == None:
            #computing the bernstein polynoms for a given degree
            factors = [binom(deg,i) * t**i * (1-t)**(deg-i)*pis[i] for i in range(n_pts)]
            self.eq = sum(factors);
        else:
            self.eq = eq

    def __repr__(self):
        res  = "Degree : "        + str(self.deg)
        res += "\nEquation : "    + self.eq.__repr__()
        res += "\nwaypoints :\n"  + str(self.pis)
        return res

    def __str__(self):
        return self.__repr__()

b = Bezier(3)

print b
# Degree : 3
# Equation : 1.0*p0*(-t + 1)**3 + 3.0*p1*t*(-t + 1)**2 + 3.0*p2*t**2*(-t + 1) + 1.0*p3*t**3
# waypoints :
# [p0, p1, p2, p3]

print b.eq
# 1.0*p0*(-t + 1)**3 + 3.0*p1*t*(-t + 1)**2 + 3.0*p2*t**2*(-t + 1) + 1.0*p3*t**3

As one can see, the fact that the variables p_is are vector is not really relevant, except in the case where the cross product appears.
If I were to compute the cross product of b with itself, then several terms would disappear because the some vectors would be crossed against themselves.

What I tried to do was to "emulate" the cross product with a simple multiplication, and then iterate over the resulting equation to remove all the squared terms (that correspond to zero). But this is not sufficient
because the product does not preserve the anticomutative aspect of the cross product.

What I would really like would be for the actual cross product sign (say X) appear in the equation. I hope I am clearer

Thanks a lot for your help

Steve

Body:
I found a solution that works for my case (where I only apply cross product once, some reflexion is needed to consider an extension). The idea is to use additional symbols to represent the skew symmetric-matrix that achieves the cross product. For instance p0 ^ p1 will be written Cp0 * p1. I implemented a method that achieves this, and also makes sure that if pi ^ pi = 0.

To allow a better factorization, I introduced an arbitrary order of transformation based on the alphabetic order of the symbols.
This means that p2 ^ p1 will be written -Cp1 * p2
The reason for this is that otherwise simplifications such as Cp2 ^ p1 + Cp1 ^p2 = 0 will not be detected by sympy.

Anyway, this is rather hacky but in my case it allowed me to write my library, so here it is.

The method that performs the cross product is "cross", at the end of the file.

#declaring vector symbols variables
p_is = [symbols('p'+str(i))  for i in range(20)]
#the cross product will be represented
#by the skew symmetric matrix Cpi for a vector pi.
#Since in the resulting equation, symbols seem to appeer
#in alphabetic order, the matrix multiplication will be coherent
p_isX = [symbols('Cp'+str(i)+'')  for i in range(20)]

#achieves the cross product between two elements
#s0 and s1 are the considered vector symbols (here, two pis)
#e0 and e1 are the scalar multiplier of each term
def crossElement(s0,e0,s1,e1):
    if s0 == s1:
        return 0
    else:
        # here, take order of apparition into account to allow
        # future factorization. Otherwise
        # something like p0 X p1 + p1 X p0 will not be dientified as zero
        id0 = p_is.index(s0)
        id1 = p_is.index(s1)
        if(id0 < id1):
            return simplify(e1*e0*p_isX[id0]*s1)
        else:
            return simplify((-e1)*e0*p_isX[id1]*s0)

#retrieve all the pis and associate scalar factors
#from an equation
def getAllSymbols(eq):
    res = []
    for el in p_is:
        dic = eq.as_poly(el).as_dict()
        if(len(dic) > 1):
            res += [(el, dic[(1,)])]
    return res;

#generates the cross product of two equations,
#where each pi term is a vector, and others
#are scalar variable.
#cross product
def cross(eq1,eq2):
    decomp1 = getAllSymbols(eq1)
    decomp2 = getAllSymbols(eq2)
    res = 0
    #applies distributive cross product between
    #all terms of both equations
    for (s0, e0) in decomp1:
        for (s1, e1) in decomp2:
            res += crossElement(s0,e0,s1,e1)
    return res


问:
Incomplete implementation of my class?
```<code>//
//  Possession.m
//  RandomPossessions
//
//  Created by Paxton Harman on 1/14/11.
//  Copyright 2011 Santa Barbara City College. All rights reserved.
//

#import "Possession.h"

@implementation Possession
@synthesize possessionName, serialNumber, valueInDollars, dateCreated;
@end

- (id)initWithPossessionName:(NSString *)name;

valueindollars:(int)value
serialNumber:(NSString *)sNumber
{
    // Call the superclass's designated initializer
        self = [super init];
    // Did the superclass's designated initializer fail?
     if (!self)
         return nil;

    // Give the instance variables initial values
    [self setPossessionsName:name];
    [self setSerialNumber:sNumber];
    [self setValueInDollars:value];
    dateCreated = [[NSDate alloc] init];

    // Return the address of the newly initialized object
    return self;

}
- (id)initWithPossessionName:(NSString *)name
{
    return [self initWithossessionName:name
                        valueInDollars:0
                         serialnNumber:@""];
}
@end

- (NSString *)description {

    NSString *descriptionString =
        [[NSString alloc] initWithFormat:@"%@ (%@): Worth $%d, Recorded on %@",
                        possessionName,
                        serialNumber,
                        valueInDollars,
                        dateCreated];
    return descriptionString;
}

- (id)init {
    return [self initWithPossessionName:@"Possession"
                         valueInDollars:0
                           serialNumber:@""];
}

+(id)randomPossesion {

// Create two arrays with a list of possible adjectives and nouns
// Note: When using NSArray's arrayWithObjects;, you can pass as many
// objects as you like. At the end of that list, you put nil to
// signify that there are no more objects - otherwise you will crash.
// The nil value is not added to the array, but it used by the method
// to determine the end of the list.
    NSArray *randomAdjectiveList = [NSArray array WithObjects:@"Fluffy",
@"Rusty",
                                    @"Shiny", nil];
    NSArray *randomNounList = [NSArray arrayWithObjects:@"Bear",
@"Spork",
                               @"Mac", nil];

// Get the index of random adjective/noun from the lists
// Note: The % operator, called the modulo operator, gives
// you the remainder. So adjectiveIndex is a random number
// from 0 to 2 inclusive, in this case.
    int adjectiveIndex = random() % [randomAdjectiveList count];
    int nounIndex = random() % [randomNounList count];

    NSString *randomName = [NSString stringWithFormat:@"%@ %@",
                            [randomAdjectiveList objectAtIndex:adjectiveIndex],
                            [randomNounList objectAtIndex:nounIndex]];

    int randomValue = random() % 100;

    NSString *randomSerialNumber = [NSString stringWithFormat:@"%c%c%c%c%c",
'0' + random() % 10,
'A' + random() % 26,
'0' + random() % 10,
'A' + random() % 26,
                                    '0' + random() % 10];

// Once again, ignore the memory problems with this method
// We use "self" instead of the name of the class in class methods...
// Keep reading to find out why
Possession *newPossesion =
    [[self alloc] initWithPossessionName:randomName
                          valueInDollars:randomValue
                            serialNumber:randomSerialNumber];
    return newPossession;
}
</code>```

at line 14 and 19 it's giving me "incomplete implementation of possesion" and Expected '{' before 'valueindollars, respectfully. Any help?? new to cocoa

答:
You have two @end directives. Neither is in the right place. They should be at – suprise – the end of your implementation block.

In this method signature, remove the semicolon (and preferably the blank lines):

```<code>- (id)initWithPossessionName:(NSString *)name;

valueindollars:(int)value
serialNumber:(NSString *)sNumber
</code>```

This error is confusing Jacob Relkin and Adam Eberbach, causing them to try to fix things that aren’t actually there.

In the convenience initializers - (id)initWithPossessionName:(NSString *)name and -init, you’re calling a method that doesn’t exist – there are several typos in the selector you’re calling in one, and some capitalization problems in the one you’d actually be defining if it weren’t for the extra semicolon.

ContentLicense: CC BY-SA 2.5

Title: Incomplete implementation of my class?

Body:
//
//  Possession.m
//  RandomPossessions
//
//  Created by Paxton Harman on 1/14/11.
//  Copyright 2011 Santa Barbara City College. All rights reserved.
//

#import "Possession.h"

@implementation Possession
@synthesize possessionName, serialNumber, valueInDollars, dateCreated;
@end

- (id)initWithPossessionName:(NSString *)name;

valueindollars:(int)value
serialNumber:(NSString *)sNumber
{
    // Call the superclass's designated initializer
        self = [super init];
    // Did the superclass's designated initializer fail?
     if (!self)
         return nil;

    // Give the instance variables initial values
    [self setPossessionsName:name];
    [self setSerialNumber:sNumber];
    [self setValueInDollars:value];
    dateCreated = [[NSDate alloc] init];

    // Return the address of the newly initialized object
    return self;

}
- (id)initWithPossessionName:(NSString *)name
{
    return [self initWithossessionName:name
                        valueInDollars:0
                         serialnNumber:@""];
}
@end

- (NSString *)description {

    NSString *descriptionString =
        [[NSString alloc] initWithFormat:@"%@ (%@): Worth $%d, Recorded on %@",
                        possessionName,
                        serialNumber,
                        valueInDollars,
                        dateCreated];
    return descriptionString;
}

- (id)init {
    return [self initWithPossessionName:@"Possession"
                         valueInDollars:0
                           serialNumber:@""];
}

+(id)randomPossesion {

// Create two arrays with a list of possible adjectives and nouns
// Note: When using NSArray's arrayWithObjects;, you can pass as many
// objects as you like. At the end of that list, you put nil to
// signify that there are no more objects - otherwise you will crash.
// The nil value is not added to the array, but it used by the method
// to determine the end of the list.
    NSArray *randomAdjectiveList = [NSArray array WithObjects:@"Fluffy",
@"Rusty",
                                    @"Shiny", nil];
    NSArray *randomNounList = [NSArray arrayWithObjects:@"Bear",
@"Spork",
                               @"Mac", nil];

// Get the index of random adjective/noun from the lists
// Note: The % operator, called the modulo operator, gives
// you the remainder. So adjectiveIndex is a random number
// from 0 to 2 inclusive, in this case.
    int adjectiveIndex = random() % [randomAdjectiveList count];
    int nounIndex = random() % [randomNounList count];

    NSString *randomName = [NSString stringWithFormat:@"%@ %@",
                            [randomAdjectiveList objectAtIndex:adjectiveIndex],
                            [randomNounList objectAtIndex:nounIndex]];

    int randomValue = random() % 100;

    NSString *randomSerialNumber = [NSString stringWithFormat:@"%c%c%c%c%c",
'0' + random() % 10,
'A' + random() % 26,
'0' + random() % 10,
'A' + random() % 26,
                                    '0' + random() % 10];

// Once again, ignore the memory problems with this method
// We use "self" instead of the name of the class in class methods...
// Keep reading to find out why
Possession *newPossesion =
    [[self alloc] initWithPossessionName:randomName
                          valueInDollars:randomValue
                            serialNumber:randomSerialNumber];
    return newPossession;
}

at line 14 and 19 it's giving me "incomplete implementation of possesion" and Expected '{' before 'valueindollars, respectfully. Any help?? new to cocoa

Body:
You have two @end directives. Neither is in the right place. They should be at – suprise – the end of your implementation block.

In this method signature, remove the semicolon (and preferably the blank lines):

- (id)initWithPossessionName:(NSString *)name;

valueindollars:(int)value
serialNumber:(NSString *)sNumber

This error is confusing Jacob Relkin and Adam Eberbach, causing them to try to fix things that aren’t actually there.

In the convenience initializers - (id)initWithPossessionName:(NSString *)name and -init, you’re calling a method that doesn’t exist – there are several typos in the selector you’re calling in one, and some capitalization problems in the one you’d actually be defining if it weren’t for the extra semicolon.


问:
What would be a use case for Thread.Sleep(Timeout.Infinite)?
I happened to lay my eyes on an intellisense tool tip regarding the parameter passed to System.Threading.Thread.Sleep(int millisecondsTimeout), saying something like "(…) Specify System.Threading.Timeout.Infinite to block the thread indefinitely". And I am intrigued.

I can understand why one might include short inactive delays within a possibly endless loop, thus yielding processing power to other executing threads when no immediate action in the sleeping thread is required, although I typically prefer implementing such delays with EventWaitHandlers so that I can avoid waiting a full sleeping delay if I signal the thread to gracefully end its execution from a different thread.

But I cannot see when I might need to suspend a thread indefinitely, and in a way that, as far as I can tell, can only be interrupted through a rather ungraceful Thread.Abort()/ThreadAbortException pair.

So what would be a working scenario where I might want to suspend a thread indefinitely?

答:
It is a pretty long story and I have to wave my hands a bit to make it understandable.  Most programmers think that Thread.Sleep() puts the thread to sleep and prevents it from executing any code.  This is not accurate.  Thread.Sleep(Infinite) is equivalent to Application.Run().  No kidding.

This doesn't happen very often in real life, it is mostly relevant in custom hosting scenarios.  Getting code to run on a specific thread is in general an important feature to deal with code that is not thread-safe and the major reason why Application.Run() exists.  But Windows exposes another way to do at a much lower level, the underlying api for this is QueueUserAPC().  The .NET analogue of this function is BeginInvoke().

This requires the thread to co-operate, just like it does when it calls Application.Run().  The thread must be in an "alertable wait state", executing a blocking function that can be interrupted.  The CLR does not execute the sleep by itself, it passes the job to the CLR host.  Most hosts will simply execute SleepEx(), passing TRUE for the bAlertable argument.  The thread is now in a state to execute any requests posted by QueueUserAPC().  Just like it will be when it is actively executing inside the Application.Run() dispatcher loop.

The kernel feature is not otherwise exposed at all in the framework.  It is the kind of code that is very hard to get right, re-entrancy bugs are pretty nasty.  As most programmers that were bitten by Application.DoEvents() or a poorly placed MessageBox.Show() can attest.  It is however a valid scenario in a custom hosting scenario.  Where the host can get C# code to run on a specific thread, using this mechanism.  So it is possible to pass Infinite because the designers did not want to intentionally disable this scenario.  If this is made possible at all by the host author then they'd let you know about it.  I don't know of a practical example.

More practically, you do use this feature every day.  It is the way that System.Threading.Timer and System.Timers.Timer are implemented.  Done by a thread inside the CLR which is started as soon as you use any timer, it uses SleepEx(INFINITE, TRUE) at its core.


问:
How to use the latest sinon in ui5?
I am follow this guide to do Unit Test with QUnit and Sinon: Step 28: Unit Test with QUnit

Added sinon in unitTest.qunit.html:

```<code>        jQuery.sap.require("sap.ui.thirdparty.sinon");
        jQuery.sap.require("sap.ui.thirdparty.sinon-qunit");
</code>```

It seems ui5 still use Sinon.JS v1.14.1:
https://github.com/SAP/openui5/blob/master/src/sap.ui.core/src/sap/ui/thirdparty/sinon.js

Latest sinon is already v4.1.2: http://sinonjs.org/releases/

So how to require the latest sinon?

Because our pipeline use sinon v4.1.2, so function like var stub = sinon.stub(object, "method", func);is duplicated. But I can not use stub(obj, 'meth').callsFake(fn) in my ui5 project. http://sinonjs.org/releases/v4.1.2/stubs/

答:
integrate sinon.JS v4.1.2 as a third party library into the ui5 application:

create a sinon.js file in your project.

copy paste the code of the sinon.JS v4.1.2 into the sinon.js file.

put on the top of the sinon.js file a jQuery.sap.declare("yourPath/sinon").

put into the unitTests.qunit.html a jQuery.sap.require("yourPath/sinon").

Title: How to use the latest sinon in ui5?

Body:
I am follow this guide to do Unit Test with QUnit and Sinon: Step 28: Unit Test with QUnit

Added sinon in unitTest.qunit.html:

        jQuery.sap.require("sap.ui.thirdparty.sinon");
        jQuery.sap.require("sap.ui.thirdparty.sinon-qunit");

It seems ui5 still use Sinon.JS v1.14.1:
https://github.com/SAP/openui5/blob/master/src/sap.ui.core/src/sap/ui/thirdparty/sinon.js

Latest sinon is already v4.1.2: http://sinonjs.org/releases/

So how to require the latest sinon?

Because our pipeline use sinon v4.1.2, so function like var stub = sinon.stub(object, "method", func);is duplicated. But I can not use stub(obj, 'meth').callsFake(fn) in my ui5 project. http://sinonjs.org/releases/v4.1.2/stubs/


问:
How can I change document elements by webExtension when user click on extension icon in toolbar?
I want to create a webExtension and I want to have icon in toolbar for this extension.
In my manifest.json file I put this code:

```<code>{
"manifest_version": 2,
"name": "test",
"version": "1.0",
"description": "test",
"icons": {
    "48": "icons/icon48.png",
    "96": "icons/icon96.png"
},
"background": {
    "scripts": ["background.js"]
},
"permissions": [
    "activeTab",
    "contextMenus"
],

"browser_action": {
    "default_icon": {
        "19": "button/btn19.png",
        "38": "button/btn38.png"
    },
    "default_title": "test"
}
}
</code>```

When user click on this extension icon in toolbar, I want to get elements of current page and add  tag in document where I want. I put this java script code in background.js file. But these code doesn't execute.
How can I fix this?

background.js :

```<code>function change() {
var elems = document.body.getElementsByTagName("*");
var re = new RegExp(/abba\b/g);
for (var i = 0; i < elems.length; i++) {
    var str = elems[i].innerHTML;
    if (!str.match(/<[a-zA-Z0-9\s:./\"\'=\\;()-_]*>/) && re.test(str)) {
        var aTag = document.createElement("a");
        aTag.setAttribute('href', "test.php?t=" + str.match(/abba\b/)[0]);
        aTag.setAttribute('target', "_blank");
        aTag.innerHTML = " --**CHANGES**-- ";
        elems[i].appendChild(aTag);
    }
}
}
browser.browserAction.onClicked.addListener(change);
</code>```

答:
Background pages do not have access to the contents of the web page.

You need to use content scripts. Content scripts are injected into the page after page load on idle

Get more information from the documentation

to add a content script to your extension you can add this to manifest.json

```<code>"content_scripts": [{
    "matches": ["*://*/*"],
    "js": ["contentscript.js"]
 }]
</code>```

and then rename background.js to contentscript.js. This way the code is always executed on each page.

Or alternatively just create contentscript.js and move the contents change() function into it

contentscript.js:

```<code>var elems = document.body.getElementsByTagName("*");
var re = new RegExp(/abba\b/g);
for (var i = 0; i < elems.length; i++) {
    var str = elems[i].innerHTML;
    if (!str.match(/<[a-zA-Z0-9\s:./\"\'=\\;()-_]*>/) && re.test(str)) {
        var aTag = document.createElement("a");
        aTag.setAttribute('href', "test.php?t=" + str.match(/abba\b/)[0]);
        aTag.setAttribute('target', "_blank");
        aTag.innerHTML = " --**CHANGES**-- ";
        elems[i].appendChild(aTag);
    }
}
</code>```

then background.js will call tabs.executeScript() when browser action clicked.  This way it is only called when necessary

background.js:

```<code>browser.browserAction.onClicked.addListener(function(){
    browser.tabs.executeScript({file: "/contentscript.js"})
});
</code>```

Body:
I want to create a webExtension and I want to have icon in toolbar for this extension.
In my manifest.json file I put this code:

{
"manifest_version": 2,
"name": "test",
"version": "1.0",
"description": "test",
"icons": {
    "48": "icons/icon48.png",
    "96": "icons/icon96.png"
},
"background": {
    "scripts": ["background.js"]
},
"permissions": [
    "activeTab",
    "contextMenus"
],

"browser_action": {
    "default_icon": {
        "19": "button/btn19.png",
        "38": "button/btn38.png"
    },
    "default_title": "test"
}
}

When user click on this extension icon in toolbar, I want to get elements of current page and add  tag in document where I want. I put this java script code in background.js file. But these code doesn't execute.
How can I fix this?

background.js :

function change() {
var elems = document.body.getElementsByTagName("*");
var re = new RegExp(/abba\b/g);
for (var i = 0; i < elems.length; i++) {
    var str = elems[i].innerHTML;
    if (!str.match(/<[a-zA-Z0-9\s:./\"\'=\\;()-_]*>/) && re.test(str)) {
        var aTag = document.createElement("a");
        aTag.setAttribute('href', "test.php?t=" + str.match(/abba\b/)[0]);
        aTag.setAttribute('target', "_blank");
        aTag.innerHTML = " --**CHANGES**-- ";
        elems[i].appendChild(aTag);
    }
}
}
browser.browserAction.onClicked.addListener(change);

Body:
Background pages do not have access to the contents of the web page.

You need to use content scripts. Content scripts are injected into the page after page load on idle

Get more information from the documentation

to add a content script to your extension you can add this to manifest.json

"content_scripts": [{
    "matches": ["*://*/*"],
    "js": ["contentscript.js"]
 }]

and then rename background.js to contentscript.js. This way the code is always executed on each page.

Or alternatively just create contentscript.js and move the contents change() function into it

contentscript.js:

var elems = document.body.getElementsByTagName("*");
var re = new RegExp(/abba\b/g);
for (var i = 0; i < elems.length; i++) {
    var str = elems[i].innerHTML;
    if (!str.match(/<[a-zA-Z0-9\s:./\"\'=\\;()-_]*>/) && re.test(str)) {
        var aTag = document.createElement("a");
        aTag.setAttribute('href', "test.php?t=" + str.match(/abba\b/)[0]);
        aTag.setAttribute('target', "_blank");
        aTag.innerHTML = " --**CHANGES**-- ";
        elems[i].appendChild(aTag);
    }
}

then background.js will call tabs.executeScript() when browser action clicked.  This way it is only called when necessary

background.js:

browser.browserAction.onClicked.addListener(function(){
    browser.tabs.executeScript({file: "/contentscript.js"})
});


问:
Flex menu, first element on whole row after line break
Responsive flex menu (code bellow) is on smaller viewports arranged like this:

```    |first item| |item| |item| |item| |item| |item|
                    |last item|```

Last item is on whole line in the middle.
Is it possible to do this? :

```                     |first item|
    |item| |item| |item| |item| |item| |last item|```

Looking for common solution. Menu can has any number of items.

* {
 box-sizing: border-box;
}

html {
 background:#a0522d;
}
ul {
 border:5px solid #a0522d;
 display:flex;
 flex-wrap:wrap;
 max-width:75em;
 padding:0;
 margin:20px auto;
 justify-content: center;
 align-items: center
}
ul li {
 list-style:none;
 flex-grow:1;
}
ul li a         {
 line-height:1.5;
 padding:8px 16px;
 display:block;
 text-align:center;
 border-radius:0.313em;
 background:PaleGoldenrod;
 margin:2px;
}
.last, .almostlast {
 max-width:320px;
}
    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <ul>
     <li class="first">first item</li>
     <li>second item</li>
     <li>next item</li>
     <li>item</li>
     <li>pretty item</li>
     <li class="almostlast"><span>item</span></li>
     <li class="last">last item</li>
</ul></code>```

答:
Yes, by simply use order and a pseudo element, where the pseudo work as a delimiter, being 100% wide and take a row of its own.

With the order we then put the first item before the pseudo.

Updated based on a comment at another answer

Using a media query, so it only happens on narrower screens.

Stack snippet

* {
 box-sizing: border-box;
}

html {
 background:#a0522d;
}
ul {
 border:5px solid #a0522d;
 display:flex;
 flex-wrap:wrap;
 max-width:75em;
 padding:0;
 margin:20px auto;
 justify-content: center;
 align-items: center
}
ul li {
 list-style:none;
 flex-grow:1;
}

ul li a         {
 line-height:1.5;
 padding:8px 16px;
 display:block;
 text-align:center;
 border-radius:0.313em;
 background:PaleGoldenrod;
 margin:2px;
}
.last, .almostlast {
 max-width:320px;
}

@media (max-width: 800px) {
  ul::before {
   content: ' ';                         /*  added  */
   width:100%;                           /*  added, fill width and push the rest down  */
}
  .first {
   order: -1;                            /*  added, move before pseudo  */
   flex-grow:0;                          /*  changed, to not fill width  */
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
     <li class="first">first item</li>
     <li>second item</li>
     <li>next item</li>
     <li>item</li>
     <li>pretty item</li>
     <li class="almostlast"><span>item</span></li>
     <li class="last">last item</li>
</ul></code>```

With this little trick the other pseudo can do other cool stuff

Stack snippet

* {
 box-sizing: border-box;
}

html {
 background:#a0522d;
}
ul {
 border:5px solid #a0522d;
 display:flex;
 flex-wrap:wrap;
 max-width:75em;
 padding:0;
 margin:20px auto;
 justify-content: center;
 align-items: center
}
ul li {
 list-style:none;
 flex-grow:1;
}

ul li a         {
 line-height:1.5;
 padding:8px 16px;
 display:block;
 text-align:center;
 border-radius:0.313em;
 background:PaleGoldenrod;
 margin:2px;
}
.last, .almostlast {
 max-width:320px;
}

@media (max-width: 800px) {
  ul::before {
   content: ' ';                         /*  added  */
   width:100%;                           /*  added, fill width and push the rest down  */
}
  .first {
   order: -1;                            /*  added, move before pseudo  */
   flex-grow:0;                          /*  changed, to not fill width  */
  }
}

@media (max-width: 700px) {
  ul::after {
   content: ' ';
   order: 1;
   width:100%;
  }
  ul li:nth-child(-n+3) {
   flex-grow:0;
  }
  ul li:nth-child(n+4) {
   order: 2;
   flex-grow:0;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
     <li class="first">first item</li>
     <li>second item</li>
     <li>next item</li>
     <li>item</li>
     <li>pretty item</li>
     <li class="almostlast"><span>item</span></li>
     <li class="last">last item</li>
</ul></code>```

Update 2

In addition to Cons7an7ine's answer, by also combine row-reverse wrap-reverse with order, this can by done with existing markup, where one set enough nth-child to cover for n number of menu items.

```<code>ul {
 border:5px solid #a0522d;
 display:flex;
 flex-flow: row-reverse wrap-reverse;
 ...
}

ul li:nth-child(1)  { order: 100; }
ul li:nth-child(2)  { order:  99; }
ul li:nth-child(3)  { order:  98; }
...
</code>```

Fiddle demo

Stack snippet

* {
 box-sizing: border-box;
}

html {
 background:#a0522d;
}
ul {
 border:5px solid #a0522d;
 display:flex;
 flex-flow: row-reverse wrap-reverse;
 max-width:75em;
 padding:0;
 margin:20px auto;
 justify-content: center;
 align-items: center;
}
ul li {
 list-style:none;
 flex-grow:1;
 white-space: nowrap;
}

ul li a         {
 line-height:1.5;
 padding:8px 16px;
 display:block;
 text-align:center;
 border-radius:0.313em;
 background:PaleGoldenrod;
 margin:2px;
}
.last, .almostlast {
 max-width:320px;
}

ul li:nth-child(1)  { order: 100; }
ul li:nth-child(2)  { order:  99; }
ul li:nth-child(3)  { order:  98; }
ul li:nth-child(4)  { order:  97; }
ul li:nth-child(5)  { order:  96; }
ul li:nth-child(6)  { order:  95; }
ul li:nth-child(7)  { order:  94; }
ul li:nth-child(8)  { order:  93; }
ul li:nth-child(9)  { order:  92; }
ul li:nth-child(10) { order:  91; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
     <li class="first">first item</li>
     <li>second item</li>
     <li>next item</li>
     <li>item</li>
     <li>pretty item</li>
     <li class="almostlast"><span>item</span></li>
     <li class="last">last item</li>
</ul></code>```

And if none of the above is a viable solution, with a script one can do this in almost any possible wished outcome.

Body:
Responsive flex menu (code bellow) is on smaller viewports arranged like this:

    |first item| |item| |item| |item| |item| |item|
                    |last item|

Last item is on whole line in the middle.
Is it possible to do this? :

                     |first item|
    |item| |item| |item| |item| |item| |last item|

Looking for common solution. Menu can has any number of items.

* {
 box-sizing: border-box;
}

html {
 background:#a0522d;
}
ul {
 border:5px solid #a0522d;
 display:flex;
 flex-wrap:wrap;
 max-width:75em;
 padding:0;
 margin:20px auto;
 justify-content: center;
 align-items: center
}
ul li {
 list-style:none;
 flex-grow:1;
}
ul li a         {
 line-height:1.5;
 padding:8px 16px;
 display:block;
 text-align:center;
 border-radius:0.313em;
 background:PaleGoldenrod;
 margin:2px;
}
.last, .almostlast {
 max-width:320px;
}

first item

second item

next item

item

pretty item

item

last item

Body:
Yes, by simply use order and a pseudo element, where the pseudo work as a delimiter, being 100% wide and take a row of its own.

With the order we then put the first item before the pseudo.

Updated based on a comment at another answer

Using a media query, so it only happens on narrower screens.

Stack snippet

* {
 box-sizing: border-box;
}

html {
 background:#a0522d;
}
ul {
 border:5px solid #a0522d;
 display:flex;
 flex-wrap:wrap;
 max-width:75em;
 padding:0;
 margin:20px auto;
 justify-content: center;
 align-items: center
}
ul li {
 list-style:none;
 flex-grow:1;
}

ul li a         {
 line-height:1.5;
 padding:8px 16px;
 display:block;
 text-align:center;
 border-radius:0.313em;
 background:PaleGoldenrod;
 margin:2px;
}
.last, .almostlast {
 max-width:320px;
}

@media (max-width: 800px) {
  ul::before {
   content: ' ';                         /*  added  */
   width:100%;                           /*  added, fill width and push the rest down  */
}
  .first {
   order: -1;                            /*  added, move before pseudo  */
   flex-grow:0;                          /*  changed, to not fill width  */
  }
}

<ul>
     <li class="first"><a href="#">first item</a></li>
     <li><a href="#">second item</a></li>
     <li><a href="#">next item</a></li>
     <li><a href="#">item</a></li>
     <li><a href="#">pretty item</a></li>
     <li class="almostlast"><span><a href="#">item</a></span></li>
     <li class="last"><a href="#">last item</a></li>
</ul>

With this little trick the other pseudo can do other cool stuff

Stack snippet

* {
 box-sizing: border-box;
}

html {
 background:#a0522d;
}
ul {
 border:5px solid #a0522d;
 display:flex;
 flex-wrap:wrap;
 max-width:75em;
 padding:0;
 margin:20px auto;
 justify-content: center;
 align-items: center
}
ul li {
 list-style:none;
 flex-grow:1;
}

ul li a         {
 line-height:1.5;
 padding:8px 16px;
 display:block;
 text-align:center;
 border-radius:0.313em;
 background:PaleGoldenrod;
 margin:2px;
}
.last, .almostlast {
 max-width:320px;
}

@media (max-width: 800px) {
  ul::before {
   content: ' ';                         /*  added  */
   width:100%;                           /*  added, fill width and push the rest down  */
}
  .first {
   order: -1;                            /*  added, move before pseudo  */
   flex-grow:0;                          /*  changed, to not fill width  */
  }
}

@media (max-width: 700px) {
  ul::after {
   content: ' ';
   order: 1;
   width:100%;
  }
  ul li:nth-child(-n+3) {
   flex-grow:0;
  }
  ul li:nth-child(n+4) {
   order: 2;
   flex-grow:0;
  }
}

<ul>
     <li class="first"><a href="#">first item</a></li>
     <li><a href="#">second item</a></li>
     <li><a href="#">next item</a></li>
     <li><a href="#">item</a></li>
     <li><a href="#">pretty item</a></li>
     <li class="almostlast"><span><a href="#">item</a></span></li>
     <li class="last"><a href="#">last item</a></li>
</ul>

Update 2

In addition to Cons7an7ine's answer, by also combine row-reverse wrap-reverse with order, this can by done with existing markup, where one set enough nth-child to cover for n number of menu items.

ul {
 border:5px solid #a0522d;
 display:flex;
 flex-flow: row-reverse wrap-reverse;
 ...
}

ul li:nth-child(1)  { order: 100; }
ul li:nth-child(2)  { order:  99; }
ul li:nth-child(3)  { order:  98; }
...

Fiddle demo

Stack snippet

* {
 box-sizing: border-box;
}

html {
 background:#a0522d;
}
ul {
 border:5px solid #a0522d;
 display:flex;
 flex-flow: row-reverse wrap-reverse;
 max-width:75em;
 padding:0;
 margin:20px auto;
 justify-content: center;
 align-items: center;
}
ul li {
 list-style:none;
 flex-grow:1;
 white-space: nowrap;
}

ul li a         {
 line-height:1.5;
 padding:8px 16px;
 display:block;
 text-align:center;
 border-radius:0.313em;
 background:PaleGoldenrod;
 margin:2px;
}
.last, .almostlast {
 max-width:320px;
}

ul li:nth-child(1)  { order: 100; }
ul li:nth-child(2)  { order:  99; }
ul li:nth-child(3)  { order:  98; }
ul li:nth-child(4)  { order:  97; }
ul li:nth-child(5)  { order:  96; }
ul li:nth-child(6)  { order:  95; }
ul li:nth-child(7)  { order:  94; }
ul li:nth-child(8)  { order:  93; }
ul li:nth-child(9)  { order:  92; }
ul li:nth-child(10) { order:  91; }

<ul>
     <li class="first"><a href="#">first item</a></li>
     <li><a href="#">second item</a></li>
     <li><a href="#">next item</a></li>
     <li><a href="#">item</a></li>
     <li><a href="#">pretty item</a></li>
     <li class="almostlast"><span><a href="#">item</a></span></li>
     <li class="last"><a href="#">last item</a></li>
</ul>

And if none of the above is a viable solution, with a script one can do this in almost any possible wished outcome.


问:
download CSV file from a URL based on inputs from a ticker_list?
I am new to Python and I want to make a program that does the following:

Use this list = [aapl,goog,jnj,msft] as input

Go to the url "https://finance.google.com/finance/historical?q=goog&output=csv" and replace "goog" with tickers from list above

Finally save the CSV file onto the file system.

The image contains the code i have been able to think of

```<code>from urllib import request
ticker_list = "aapl"
response = request.urlretrieve("https://finance.google.com/finance/historical?q="+ticker_list+"&output=csv",'D:/LatestStockFile.csv')
#[aapl,goog,xom,ge,msft,bp,c,pg,wmt,pfe,tm,jnj]
# I want tickers from this list to append instead of ticker_list

# also if possible a different file name to save for each iteration of ticker
# example : say ticker = "aaple" then this "aapl" should be appended to url and path: "D:/Apple.csv"

def download_csv(ticker,path):
    response = request.urlretrieve(ticker,path)

def user_input():
 choice = input("enter choice: 1/2/3\n")
 if choice == 1:
  download_csv("aapl","D:/Apple.csv")
 elif choice == 2:
  download_csv=("goog","D:/Google.csv")
 elif choice == 3:
  download_csv("jnj","D:/Johnson.csv")

user_input()
</code>```

答:
How about doing it this way?

```<code>"""
"""
#in this file "C:/Users/rshuell001/Desktop/symbols/amex.txt"
#you have the following tickers
#ibm
#sbux
#msft
"""

import urllib
import re
import json

symbolslist = open("C:/Users/rshuell001/Desktop/symbols/amex.txt").read()
symbolslist = symbolslist.split("\n")

for symbol in symbolslist:
    myfile = open("C:/Users/rshuell001/Desktop/symbols/" +symbol +".txt", "w+")
    myfile.close()

    htmltext = urllib.urlopen("http://www.bloomberg.com/markets/chart/data/1D/"+ symbol+ ":US")
    data = json.load(htmltext)
    datapoints = data["data_values"]

    myfile = open("C:/Users/rshuell001/Desktop/symbols/" +symbol +".txt", "a")
    for point in datapoints:
        myfile.write(str(symbol+","+str(point[0])+","+str(point[1])+"\n"))
    myfile.close()
</code>```

Here is an option that is similar, but different (you are reading from a tuple not a text file).

```<code>import urllib2

listOfStocks = ["AAPL", "MSFT", "GOOG", "FB", "AMZN"]

urls = []

for company in listOfStocks:
    urls.append('http://real-chart.finance.yahoo.com/table.csv?s=' + company + '&d=6&e=28&f=2015&g=m&a=11&b=12&c=1980&ignore=.csv')

Output_File = open('C:/Users/rshuell001/Historical_Prices.csv','w')

New_Format_Data = ''

for counter in range(0, len(urls)):

    Original_Data = urllib2.urlopen(urls[counter]).read()

    if counter == 0:
        New_Format_Data = "Company," + urllib2.urlopen(urls[counter]).readline()

    rows = Original_Data.splitlines(1)

    for row in range(1, len(rows)):

        New_Format_Data = New_Format_Data + listOfStocks[counter] + ',' + rows[row]

Output_File.write(New_Format_Data)
Output_File.close()
</code>```

Body:
I am new to Python and I want to make a program that does the following:

Use this list = [aapl,goog,jnj,msft] as input

Go to the url "https://finance.google.com/finance/historical?q=goog&output=csv" and replace "goog" with tickers from list above

Finally save the CSV file onto the file system.

The image contains the code i have been able to think of

from urllib import request
ticker_list = "aapl"
response = request.urlretrieve("https://finance.google.com/finance/historical?q="+ticker_list+"&output=csv",'D:/LatestStockFile.csv')
#[aapl,goog,xom,ge,msft,bp,c,pg,wmt,pfe,tm,jnj]
# I want tickers from this list to append instead of ticker_list

# also if possible a different file name to save for each iteration of ticker
# example : say ticker = "aaple" then this "aapl" should be appended to url and path: "D:/Apple.csv"

def download_csv(ticker,path):
    response = request.urlretrieve(ticker,path)

def user_input():
 choice = input("enter choice: 1/2/3\n")
 if choice == 1:
  download_csv("aapl","D:/Apple.csv")
 elif choice == 2:
  download_csv=("goog","D:/Google.csv")
 elif choice == 3:
  download_csv("jnj","D:/Johnson.csv")

user_input()

Body:
How about doing it this way?

"""
"""
#in this file "C:/Users/rshuell001/Desktop/symbols/amex.txt"
#you have the following tickers
#ibm
#sbux
#msft
"""

import urllib
import re
import json

symbolslist = open("C:/Users/rshuell001/Desktop/symbols/amex.txt").read()
symbolslist = symbolslist.split("\n")

for symbol in symbolslist:
    myfile = open("C:/Users/rshuell001/Desktop/symbols/" +symbol +".txt", "w+")
    myfile.close()

    htmltext = urllib.urlopen("http://www.bloomberg.com/markets/chart/data/1D/"+ symbol+ ":US")
    data = json.load(htmltext)
    datapoints = data["data_values"]

    myfile = open("C:/Users/rshuell001/Desktop/symbols/" +symbol +".txt", "a")
    for point in datapoints:
        myfile.write(str(symbol+","+str(point[0])+","+str(point[1])+"\n"))
    myfile.close()

Here is an option that is similar, but different (you are reading from a tuple not a text file).

import urllib2

listOfStocks = ["AAPL", "MSFT", "GOOG", "FB", "AMZN"]

urls = []

for company in listOfStocks:
    urls.append('http://real-chart.finance.yahoo.com/table.csv?s=' + company + '&d=6&e=28&f=2015&g=m&a=11&b=12&c=1980&ignore=.csv')

Output_File = open('C:/Users/rshuell001/Historical_Prices.csv','w')

New_Format_Data = ''

for counter in range(0, len(urls)):

    Original_Data = urllib2.urlopen(urls[counter]).read()

    if counter == 0:
        New_Format_Data = "Company," + urllib2.urlopen(urls[counter]).readline()

    rows = Original_Data.splitlines(1)

    for row in range(1, len(rows)):

        New_Format_Data = New_Format_Data + listOfStocks[counter] + ',' + rows[row]

Output_File.write(New_Format_Data)
Output_File.close()


问:
Understaing the difference between two queries from performance point
I have this two version of the same query. Both produce same results (164 rows). But the second one takes .5 sec while the 1st one takes 17 sec. Can someone explain what's going on here?

```<code>TABLE organizations : 11988 ROWS
TABLE transaction_metas : 58232 ROWS
TABLE contracts_history : 219469 ROWS

# TAKES 17 SEC
SELECT contracts_history.buyer_id as id, org.name, SUM(transactions_count) as transactions_count, GROUP_CONCAT(DISTINCT(tm.value)) as balancing_authorities
From `contracts_history`
INNER JOIN `organizations` as `org`
ON `org`.`id` = `contracts_history`.`buyer_id`
LEFT JOIN `transaction_metas` as `tm`
ON `tm`.`contract_token` = `contracts_history`.`token` and `tm`.`field` = '1'
WHERE `contracts_history`.`seller_id` = '850'
GROUP BY `contracts_history`.`buyer_id` ORDER BY `balancing_authorities` DESC

# TAKES .6 SEC
SELECT contracts_history.buyer_id as id, org.name, SUM(transactions_count) as transactions_count, GROUP_CONCAT(DISTINCT(tm.value)) as balancing_authorities
From `contracts_history`
INNER JOIN `organizations` as `org`
ON `org`.`id` = `contracts_history`.`buyer_id`
left join (select * from `transaction_metas` where contract_token in (select token from `contracts_history` where seller_id = 850)) as `tm`
ON `tm`.`contract_token` = `contracts_history`.`token` and `tm`.`field` = '1'
WHERE `contracts_history`.`seller_id` = '850'
GROUP BY `contracts_history`.`buyer_id` ORDER BY `balancing_authorities` DESC
</code>```

Explain Results:
First Query: https://prnt.sc/hjtiw6

Second Query: https://prnt.sc/hjtjjg

As based on my debugging of the first query it was clear that left join to transaction_metas table was making it slow, So I tried to limit its rows instead of joining to the full table. It seems to work but I don't understand why.

答:
Join is a set of combinations from rows in your tables. That in mind, in the first query the engine combines all the results to filter just after. In second case one it applies the filter before it tries make the combinations.

The best case would make use of filter in JOIN clause without subquery.
Much like this:

```<code>SELECT contracts_history.buyer_id as id, org.name, SUM(transactions_count) as transactions_count, GROUP_CONCAT(DISTINCT(tm.value)) as balancing_authorities
From `contracts_history`
INNER JOIN `organizations` as `org`
ON `org`.`id` = `contracts_history`.`buyer_id`
  AND `contracts_history`.`seller_id` = '850'
LEFT JOIN `transaction_metas` as `tm`
ON `tm`.`contract_token` = `contracts_history`.`token`
  AND `tm`.`field` = 1
GROUP BY `contracts_history`.`buyer_id` ORDER BY `balancing_authorities` DESC
</code>```

Note: When you reduce the size of the join tables by filtering with subqueries, it may allow the rows fit into the buffer. Nice trick to small buffer limit.

A Better explication:
https://dev.mysql.com/doc/refman/5.5/en/explain-output.html

Body:
I have this two version of the same query. Both produce same results (164 rows). But the second one takes .5 sec while the 1st one takes 17 sec. Can someone explain what's going on here?

TABLE organizations : 11988 ROWS
TABLE transaction_metas : 58232 ROWS
TABLE contracts_history : 219469 ROWS

# TAKES 17 SEC
SELECT contracts_history.buyer_id as id, org.name, SUM(transactions_count) as transactions_count, GROUP_CONCAT(DISTINCT(tm.value)) as balancing_authorities
From `contracts_history`
INNER JOIN `organizations` as `org`
ON `org`.`id` = `contracts_history`.`buyer_id`
LEFT JOIN `transaction_metas` as `tm`
ON `tm`.`contract_token` = `contracts_history`.`token` and `tm`.`field` = '1'
WHERE `contracts_history`.`seller_id` = '850'
GROUP BY `contracts_history`.`buyer_id` ORDER BY `balancing_authorities` DESC

# TAKES .6 SEC
SELECT contracts_history.buyer_id as id, org.name, SUM(transactions_count) as transactions_count, GROUP_CONCAT(DISTINCT(tm.value)) as balancing_authorities
From `contracts_history`
INNER JOIN `organizations` as `org`
ON `org`.`id` = `contracts_history`.`buyer_id`
left join (select * from `transaction_metas` where contract_token in (select token from `contracts_history` where seller_id = 850)) as `tm`
ON `tm`.`contract_token` = `contracts_history`.`token` and `tm`.`field` = '1'
WHERE `contracts_history`.`seller_id` = '850'
GROUP BY `contracts_history`.`buyer_id` ORDER BY `balancing_authorities` DESC

Explain Results:
First Query: https://prnt.sc/hjtiw6

Second Query: https://prnt.sc/hjtjjg

As based on my debugging of the first query it was clear that left join to transaction_metas table was making it slow, So I tried to limit its rows instead of joining to the full table. It seems to work but I don't understand why.

Body:
Join is a set of combinations from rows in your tables. That in mind, in the first query the engine combines all the results to filter just after. In second case one it applies the filter before it tries make the combinations.

The best case would make use of filter in JOIN clause without subquery.
Much like this:

SELECT contracts_history.buyer_id as id, org.name, SUM(transactions_count) as transactions_count, GROUP_CONCAT(DISTINCT(tm.value)) as balancing_authorities
From `contracts_history`
INNER JOIN `organizations` as `org`
ON `org`.`id` = `contracts_history`.`buyer_id`
  AND `contracts_history`.`seller_id` = '850'
LEFT JOIN `transaction_metas` as `tm`
ON `tm`.`contract_token` = `contracts_history`.`token`
  AND `tm`.`field` = 1
GROUP BY `contracts_history`.`buyer_id` ORDER BY `balancing_authorities` DESC

Note: When you reduce the size of the join tables by filtering with subqueries, it may allow the rows fit into the buffer. Nice trick to small buffer limit.

A Better explication:
https://dev.mysql.com/doc/refman/5.5/en/explain-output.html


问:
Swift get associated value in enums without switch
I have enum:

```<code>enum RetailDemandReturnOperation {
    case salesReturn(value: MSRetailSalesReturnRealm)
    case demand(value: MSRetailDemandRealm)
}
</code>```

MSRetailDemandRealm and MSRetailDemandRealm are both implement same protocol, that have variables title and stats. I want to extract this values, but i don't care of which object actually stored in. Consider following:

```<code> switch data! {
        case .salesReturn(let object):
            titleString = object.title
            statistics = object.stats
        case .demand(let object):
            titleString = object.title
            statistics = object.stats
          break
        }
</code>```

I have to go in each enum value to get property of protocol. Is any way i can do it shorter and cleaner? Get associated value, no matter what it is, as long as it conforms to my protocol, and get protocol values?
Thanks.

答:
Since RetailDemandReturnOperation always has the associated value for MSRetailRealm, you can give it a new property of type RetailDemandReturnOperation. Then, you can get rid of the the associated value in your enum.

```<code>enum RetailDemandReturnOperation {
    case salesReturn
    case demand
}

protocol MSRetailRealm {
    var stats: Int { get set }
    var title: String { get set }
    var operation: RetailDemandReturnOperation { get }
}

struct MSRetailDemandRealm: MSRetailRealm {
    //.. your old code
    var operation: RetailDemandReturnOperation { return .demand }
}

struct MSRetailSalesReturnRealm: MSRetailRealm {
    //.. your old code
    var operation: RetailDemandReturnOperation { return .salesReturn }
}
</code>```

Now you can access stats and title no matter what operation it is. And if you care about the operation, simply access the operation property.

```<code>func example(object: MSRetailRealm) {
    let titleString = object.title
    switch object.operation {
        case .salesReturn:
            break
        case .demand:
            break
    }
}
</code>```

Body:
I have enum:

enum RetailDemandReturnOperation {
    case salesReturn(value: MSRetailSalesReturnRealm)
    case demand(value: MSRetailDemandRealm)
}

MSRetailDemandRealm and MSRetailDemandRealm are both implement same protocol, that have variables title and stats. I want to extract this values, but i don't care of which object actually stored in. Consider following:

 switch data! {
        case .salesReturn(let object):
            titleString = object.title
            statistics = object.stats
        case .demand(let object):
            titleString = object.title
            statistics = object.stats
          break
        }

I have to go in each enum value to get property of protocol. Is any way i can do it shorter and cleaner? Get associated value, no matter what it is, as long as it conforms to my protocol, and get protocol values?
Thanks.

Body:
Since RetailDemandReturnOperation always has the associated value for MSRetailRealm, you can give it a new property of type RetailDemandReturnOperation. Then, you can get rid of the the associated value in your enum.

enum RetailDemandReturnOperation {
    case salesReturn
    case demand
}

protocol MSRetailRealm {
    var stats: Int { get set }
    var title: String { get set }
    var operation: RetailDemandReturnOperation { get }
}

struct MSRetailDemandRealm: MSRetailRealm {
    //.. your old code
    var operation: RetailDemandReturnOperation { return .demand }
}

struct MSRetailSalesReturnRealm: MSRetailRealm {
    //.. your old code
    var operation: RetailDemandReturnOperation { return .salesReturn }
}

Now you can access stats and title no matter what operation it is. And if you care about the operation, simply access the operation property.

func example(object: MSRetailRealm) {
    let titleString = object.title
    switch object.operation {
        case .salesReturn:
            break
        case .demand:
            break
    }
}


问:
I have arrays stored in a json object, I send them using ajax call to the server side, how to access the data?

```<code>$scope.addQunatity = function(){

    var url="../php/mainPageFacture.php";

    // store data from user in the js arrays
    var quan_cls_crt=[$("#quan_cls_crt").val(),$("#quan_cls_crt2").val()];
    var quan_piece=[$("#quan_piece").val(),$("#quan_piece2").val()];
    var itemName=[$("#designList").val(),$("#designList2").val()];
    var dechargementNote=[$("#dechargementNote").val(),$("#dechargementNote2").val()];
    var itemIds=[78,75];

    var func="addQunatity";

    var data = {"function": func,
                "quan_cls_crt":quan_cls_crt,
                "itemId":itemIds,
                "dechargementNote":dechargementNote,
                "quan_piece":quan_piece};
    data = JSON.stringify(data);

    var options = {
            type : "get",
            url : url,
            data: {data:data},
            dataType: 'json',
            async : false,
            cache : false,
            success : function(response,status) {
                debugger;
                $scope.getAllItemNames();
                alert("success");
            },
            error:function(request,response,error){
                alert("Error: " + error + ". Please contact developer");
            }
        };
        $.ajax(options);
    }
</code>```

Here is my php code that will receive the Json object

```<code>           function addQunatity(){
              $quan_cls_crt = $_GET["quan_cls_crt"];
              $quan_piece = $_GET["quan_piece"];
              $itemId=$_GET['itemId'];
              $dechargementNote=$_GET['dechargementNote'];
            }
</code>```

I expect to receive the json arrays and store them in php variable in order to use the in the query later on, but i have no idea how to access the arrays in the json object

答:
Dont stringify the data. Use your same code and remove the stringify line.

```<code>var url="../php/mainPageFacture.php";

// store data from user in the js arrays
var quan_cls_crt=[$("#quan_cls_crt").val(),$("#quan_cls_crt2").val()];
var quan_piece=[$("#quan_piece").val(),$("#quan_piece2").val()];
var itemName=[$("#designList").val(),$("#designList2").val()];
var dechargementNote=[$("#dechargementNote").val(),$("#dechargementNote2").val()];
var itemIds=[78,75];

var func="addQunatity";

var data = {"function": func,
            "quan_cls_crt":quan_cls_crt,
            "itemId":itemIds,
            "dechargementNote":dechargementNote,
            "quan_piece":quan_piece};

var options = {
        type : "get",
        url : url,
        data: {data:data},
        dataType: 'json',
        async : false,
        cache : false,
        success : function(response,status) {
            debugger;
            $scope.getAllItemNames();
            alert("success");
        },
        error:function(request,response,error){
            alert("Error: " + error + ". Please contact developer");
        }
    };
    $.ajax(options);
}
</code>```

In the PHP side, like you have done -

```<code>          $quan_cls_crt = $_GET["quan_cls_crt"];
          $quan_piece = $_GET["quan_piece"];
          $itemId=$_GET['itemId'];
          $dechargementNote=$_GET['dechargementNote'];
</code>```

And to access each of the values from array you can simply do that with $quan_cls_crt[0] or $quan_cls_crt[1]

Body:
$scope.addQunatity = function(){

    var url="../php/mainPageFacture.php";

    // store data from user in the js arrays
    var quan_cls_crt=[$("#quan_cls_crt").val(),$("#quan_cls_crt2").val()];
    var quan_piece=[$("#quan_piece").val(),$("#quan_piece2").val()];
    var itemName=[$("#designList").val(),$("#designList2").val()];
    var dechargementNote=[$("#dechargementNote").val(),$("#dechargementNote2").val()];
    var itemIds=[78,75];

    var func="addQunatity";

    var data = {"function": func,
                "quan_cls_crt":quan_cls_crt,
                "itemId":itemIds,
                "dechargementNote":dechargementNote,
                "quan_piece":quan_piece};
    data = JSON.stringify(data);

    var options = {
            type : "get",
            url : url,
            data: {data:data},
            dataType: 'json',
            async : false,
            cache : false,
            success : function(response,status) {
                debugger;
                $scope.getAllItemNames();
                alert("success");
            },
            error:function(request,response,error){
                alert("Error: " + error + ". Please contact developer");
            }
        };
        $.ajax(options);
    }

Here is my php code that will receive the Json object

           function addQunatity(){
              $quan_cls_crt = $_GET["quan_cls_crt"];
              $quan_piece = $_GET["quan_piece"];
              $itemId=$_GET['itemId'];
              $dechargementNote=$_GET['dechargementNote'];
            }

I expect to receive the json arrays and store them in php variable in order to use the in the query later on, but i have no idea how to access the arrays in the json object

Body:
Dont stringify the data. Use your same code and remove the stringify line.

var url="../php/mainPageFacture.php";

// store data from user in the js arrays
var quan_cls_crt=[$("#quan_cls_crt").val(),$("#quan_cls_crt2").val()];
var quan_piece=[$("#quan_piece").val(),$("#quan_piece2").val()];
var itemName=[$("#designList").val(),$("#designList2").val()];
var dechargementNote=[$("#dechargementNote").val(),$("#dechargementNote2").val()];
var itemIds=[78,75];

var func="addQunatity";

var data = {"function": func,
            "quan_cls_crt":quan_cls_crt,
            "itemId":itemIds,
            "dechargementNote":dechargementNote,
            "quan_piece":quan_piece};

var options = {
        type : "get",
        url : url,
        data: {data:data},
        dataType: 'json',
        async : false,
        cache : false,
        success : function(response,status) {
            debugger;
            $scope.getAllItemNames();
            alert("success");
        },
        error:function(request,response,error){
            alert("Error: " + error + ". Please contact developer");
        }
    };
    $.ajax(options);
}

In the PHP side, like you have done -

          $quan_cls_crt = $_GET["quan_cls_crt"];
          $quan_piece = $_GET["quan_piece"];
          $itemId=$_GET['itemId'];
          $dechargementNote=$_GET['dechargementNote'];

And to access each of the values from array you can simply do that with $quan_cls_crt[0] or $quan_cls_crt[1]


问:
Background colour of line charts in chart.js
I would like to change the background colour of the line graph produced by chart.js. There doesn't appear to be an option for this, and the documentation doesn't help. Extensive searching on the interweb has yielded no results. Is this possible?

I must confess I don't really know much about the HTML5 canvas so I'm struggling a bit!

答:
Just to help others who are thinking how to add multiple background colors:
I modified a little bit @potatopeelings answer. First I checked how many columns there are

```<code>var columnCount = chart.data.datasets[0].data.length;
var width = chartArea.right - chartArea.left;
var columnWidth = width/columnCount;
</code>```

and then fill every other of them with background color

```<code>while (startPoint < chartArea.right) {
    ctx.fillRect(startPoint, chartArea.top, columnWidth, height);
    startPoint += columnWidth * 2;
}
</code>```

For my chart this works better but for this the July column is for some reason only part of it. Doesn't know how to fix that but hopefully you can get idea from here.

http://jsfiddle.net/e7oy6yk6/2

Body:
Just to help others who are thinking how to add multiple background colors:
I modified a little bit @potatopeelings answer. First I checked how many columns there are

var columnCount = chart.data.datasets[0].data.length;
var width = chartArea.right - chartArea.left;
var columnWidth = width/columnCount;

and then fill every other of them with background color

while (startPoint < chartArea.right) {
    ctx.fillRect(startPoint, chartArea.top, columnWidth, height);
    startPoint += columnWidth * 2;
}

For my chart this works better but for this the July column is for some reason only part of it. Doesn't know how to fix that but hopefully you can get idea from here.

http://jsfiddle.net/e7oy6yk6/2


问:
Horizontally align
's of varying line numbers
I've borrowed and modified this code from jsfiddle to the code snippet below.  I want to be able to wrap text in some arrows and not in others.  As you can see, a single line of text doesn't render in the same place and two lines.  I want the text centered in the
, How do I fix?

ul.money-class {
    /*margin: 20px 60px;*/
    margin-bottom: 0px
}

ul.money-class li {
    display: inline-block;
    height: 60px;
    line-height: 60px;
    width: 150px;
    margin: 5px 1px 0 0;
    text-indent: 35px;
    position: relative;

}

ul.money-class li:before {
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    left: 0px;
    border-style: solid;
    border-width: 30px 0 30px 30px;
    border-color: transparent transparent transparent #fff;
    z-index: 0;
}

ul.money-class li:first-child:before {
    /*border-color: transparent;*/
}

ul.money-class li a:after {
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    right: -30px;
    top: 0px;
    border-style: solid;
    border-width: 30px 0 30px 30px;
    border-color: transparent transparent transparent #ccc;
    z-index: 10;
    text-decoration: none;
}

ul.money-class li.active a {
    background: orange;
    z-index: 100;
}

ul.money-class li.active a:after {
    border-left-color: orange;
}

ul.money-class li a {
    display: block;
    background: #ccc;
}

ul.money-class li a:hover {
    background: pink;
}

ul.money-class li a:hover:after {
    border-color: transparent transparent transparent pink;
}

span {display: block; line-height: 30px;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="table">
    <tr>
        <td>
            <ul class="money-class">
                <li class="active"><span>Round 1</span><span>£100</span></li>
                <li><span>Round 2</span><span>£200</span></li>
                <li><span>Round 3</span><span>£300</span></li>
                <li><span>Round 4</span><span>£400</span></li>
                <li><span>Round 5</span><span>£500</span></li>
                <li>Prize Pot</li>
            </ul>
        </td>
    </tr>
</table></code>```

答:
You can add some inline style only for that line as in my comment

```<code><li style="vertical-align:top"><a href="#"><span style="line-height:60px; height:60px">Prize Pot</span></a></li>
</code>```

or
it could work by adding some css exception to the last li and its descendants, but it won't work if the single line is in a random position in the list...

ul.money-class {
    /*margin: 20px 60px;*/
    margin-bottom: 0px
}

ul.money-class li {
    display: inline-block;
    height: 60px;
    line-height: 60px;
    width: 150px;
    margin: 5px 1px 0 0;
    text-indent: 35px;
    position: relative;
}

ul.money-class li:before {
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    left: 0px;
    border-style: solid;
    border-width: 30px 0 30px 30px;
    border-color: transparent transparent transparent #fff;
    z-index: 0;
}

ul.money-class li:first-child:before {
    /*border-color: transparent;*/
}

ul.money-class li a:after {
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    right: -30px;
    top: 0px;
    border-style: solid;
    border-width: 30px 0 30px 30px;
    border-color: transparent transparent transparent #ccc;
    z-index: 10;
    text-decoration: none;
}

ul.money-class li.active a {
    background: orange;
    z-index: 100;
}

ul.money-class li.active a:after {
    border-left-color: orange;
}
ul.money-class li:last-child {vertical-align:top}
ul.money-class li:last-child a span {line-height:60px}
ul.money-class li a {
    display: block;
    background: #ccc;
}

ul.money-class li a:hover {
    background: pink;
}

ul.money-class li a:hover:after {
    border-color: transparent transparent transparent pink;
}

span {display: block; line-height: 30px;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="table">
    <tr>
        <td>
            <ul class="money-class">
                <li class="active"><span>Round 1</span><span>£100</span></li>
                <li><span>Round 2</span><span>£200</span></li>
                <li><span>Round 3</span><span>£300</span></li>
                <li><span>Round 4</span><span>£400</span></li>
                <li><span>Round 5</span><span>£500</span></li>
                <li>Prize Pot</li>
            </ul>
        </td>
    </tr>
</table></code>```

Title: Horizontally align <li>'s of varying line numbers

Body:
I've borrowed and modified this code from jsfiddle to the code snippet below.  I want to be able to wrap text in some arrows and not in others.  As you can see, a single line of text doesn't render in the same place and two lines.  I want the text centered in the
, How do I fix?

ul.money-class {
    /*margin: 20px 60px;*/
    margin-bottom: 0px
}

ul.money-class li {
    display: inline-block;
    height: 60px;
    line-height: 60px;
    width: 150px;
    margin: 5px 1px 0 0;
    text-indent: 35px;
    position: relative;

}

ul.money-class li:before {
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    left: 0px;
    border-style: solid;
    border-width: 30px 0 30px 30px;
    border-color: transparent transparent transparent #fff;
    z-index: 0;
}

ul.money-class li:first-child:before {
    /*border-color: transparent;*/
}

ul.money-class li a:after {
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    right: -30px;
    top: 0px;
    border-style: solid;
    border-width: 30px 0 30px 30px;
    border-color: transparent transparent transparent #ccc;
    z-index: 10;
    text-decoration: none;
}

ul.money-class li.active a {
    background: orange;
    z-index: 100;
}

ul.money-class li.active a:after {
    border-left-color: orange;
}

ul.money-class li a {
    display: block;
    background: #ccc;
}

ul.money-class li a:hover {
    background: pink;
}

ul.money-class li a:hover:after {
    border-color: transparent transparent transparent pink;
}

span {display: block; line-height: 30px;}

Round 1£100

Round 2£200

Round 3£300

Round 4£400

Round 5£500

Prize Pot

Body:
You can add some inline style only for that line as in my comment

<li style="vertical-align:top"><a href="#"><span style="line-height:60px; height:60px">Prize Pot</span></a></li>

or
it could work by adding some css exception to the last li and its descendants, but it won't work if the single line is in a random position in the list...

ul.money-class {
    /*margin: 20px 60px;*/
    margin-bottom: 0px
}

ul.money-class li {
    display: inline-block;
    height: 60px;
    line-height: 60px;
    width: 150px;
    margin: 5px 1px 0 0;
    text-indent: 35px;
    position: relative;
}

ul.money-class li:before {
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    left: 0px;
    border-style: solid;
    border-width: 30px 0 30px 30px;
    border-color: transparent transparent transparent #fff;
    z-index: 0;
}

ul.money-class li:first-child:before {
    /*border-color: transparent;*/
}

ul.money-class li a:after {
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    right: -30px;
    top: 0px;
    border-style: solid;
    border-width: 30px 0 30px 30px;
    border-color: transparent transparent transparent #ccc;
    z-index: 10;
    text-decoration: none;
}

ul.money-class li.active a {
    background: orange;
    z-index: 100;
}

ul.money-class li.active a:after {
    border-left-color: orange;
}
ul.money-class li:last-child {vertical-align:top}
ul.money-class li:last-child a span {line-height:60px}
ul.money-class li a {
    display: block;
    background: #ccc;
}

ul.money-class li a:hover {
    background: pink;
}

ul.money-class li a:hover:after {
    border-color: transparent transparent transparent pink;
}

span {display: block; line-height: 30px;}

<table class="table">
    <tr>
        <td>
            <ul class="money-class">
                <li class="active"><a href=""><span>Round 1</span><span>£100</span></a></li>
                <li><a href="#"><span>Round 2</span><span>£200</span></a></li>
                <li><a href="#"><span>Round 3</span><span>£300</span></a></li>
                <li><a href="#"><span>Round 4</span><span>£400</span></a></li>
                <li><a href="#"><span>Round 5</span><span>£500</span></a></li>
                <li><a href="#">Prize Pot</a></li>
            </ul>
        </td>
    </tr>
</table>


问:
Persistent BottomSheet below ActionBar
I have an app layout with a custom toolbar and a persistent BottomSheet - both inside of a CoordinatorLayout.

On a button click I want to show the BottomSheet. Right now the sheet is displayed fullscreen and overlays the toolbar. By setting the app theme to Theme.AppCompat.Light.DarkActionBar the BottomSheet stays below the ActionBar, but the bar cannot be customized.

Is there a way to limit the height of the persitent BottomSheet to fullscreen - ActionBar height?

This is my code in activity_main.xml

```<code><android.support.design.widget.CoordinatorLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:attrs="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.test.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        app:elevation="20dp"
        android:elevation="20dp"
        android:layout_height="?attr/actionBarSize">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            app:elevation="20dp"
            android:elevation="20dp"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"/>
    </android.support.design.widget.AppBarLayout>
    </LinearLayout>
    <include layout="@layout/bottom_sheet_additem"/>
</CoordinatorLayout>
</code>```

Here is the code of sheet_bottom.xml

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/bottomSheetLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorAccent"
    app:behavior_hideable="true"
    app:behavior_peekHeight="0dp"
    android:fitsSystemWindows="true"
    app:layout_behavior="@string/bottom_sheet_behavior">

    <TextView
        android:id="@+id/bottomsheet_text"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:text="Lorem Ipsum Dolor..."
        android:textColor="#FFFFFF" />
</RelativeLayout>
</code>```

The image on the left hand side shows the BottomSheet which stops below the Toolbar - which is not working with my current code. Currently it looks like the picture on the right.

答:
I had the same problem... I don't know if it's the best solution, but for now, worked for me.

Try to put your include inside another CoordinatorLayout in your activity_main.xml, with a marginTop like this:

```<code><android.support.design.widget.CoordinatorLayout
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:attrs="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context="com.test.MainActivity">

    <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:orientation="vertical">

        <android.support.design.widget.AppBarLayout
          android:layout_width="match_parent"
          app:elevation="20dp"
          android:elevation="20dp"
          android:layout_height="?attr/actionBarSize">

          <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            app:elevation="20dp"
            android:elevation="20dp"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"/>
        </android.support.design.widget.AppBarLayout>
    </LinearLayout>

    <android.support.design.widget.CoordinatorLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_marginTop="56dp">

      <include layout="@layout/bottom_sheet_additem"/>

    </android.support.design.widget.CoordinatorLayout>

</CoordinatorLayout>
</code>```

I hope it helps.

Title: Persistent BottomSheet below ActionBar

Body:
I have an app layout with a custom toolbar and a persistent BottomSheet - both inside of a CoordinatorLayout.

On a button click I want to show the BottomSheet. Right now the sheet is displayed fullscreen and overlays the toolbar. By setting the app theme to Theme.AppCompat.Light.DarkActionBar the BottomSheet stays below the ActionBar, but the bar cannot be customized.

Is there a way to limit the height of the persitent BottomSheet to fullscreen - ActionBar height?

This is my code in activity_main.xml

<android.support.design.widget.CoordinatorLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:attrs="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.test.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        app:elevation="20dp"
        android:elevation="20dp"
        android:layout_height="?attr/actionBarSize">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            app:elevation="20dp"
            android:elevation="20dp"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"/>
    </android.support.design.widget.AppBarLayout>
    </LinearLayout>
    <include layout="@layout/bottom_sheet_additem"/>
</CoordinatorLayout>

Here is the code of sheet_bottom.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/bottomSheetLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorAccent"
    app:behavior_hideable="true"
    app:behavior_peekHeight="0dp"
    android:fitsSystemWindows="true"
    app:layout_behavior="@string/bottom_sheet_behavior">

    <TextView
        android:id="@+id/bottomsheet_text"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:text="Lorem Ipsum Dolor..."
        android:textColor="#FFFFFF" />
</RelativeLayout>

The image on the left hand side shows the BottomSheet which stops below the Toolbar - which is not working with my current code. Currently it looks like the picture on the right.

Body:
I had the same problem... I don't know if it's the best solution, but for now, worked for me.

Try to put your include inside another CoordinatorLayout in your activity_main.xml, with a marginTop like this:

<android.support.design.widget.CoordinatorLayout
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:attrs="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context="com.test.MainActivity">

    <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:orientation="vertical">

        <android.support.design.widget.AppBarLayout
          android:layout_width="match_parent"
          app:elevation="20dp"
          android:elevation="20dp"
          android:layout_height="?attr/actionBarSize">

          <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            app:elevation="20dp"
            android:elevation="20dp"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"/>
        </android.support.design.widget.AppBarLayout>
    </LinearLayout>

    <android.support.design.widget.CoordinatorLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_marginTop="56dp">

      <include layout="@layout/bottom_sheet_additem"/>

    </android.support.design.widget.CoordinatorLayout>

</CoordinatorLayout>

I hope it helps.


问:
CSS images not copied to output folder in Webpack
I am using Webpack to bundle a number of js/css files in a site.  I am bundling bootstrap.css and chosen.css as part of my bundles.  In order to create the bundles, I have a main.js that I am using as an entry point to import all the other files that I will need.  I am using file-loader to process font and image files and move them to the appropriate directories.  I am using the ExtractTextPlugin with the css-loader and resolve-url-loader to create a separate css bundle from my js bundle.

My main.js is:

```<code>import 'bootstrap/dist/css/bootstrap.css';
import 'chosen-js/chosen.css';
import './datetimehelper.js';
import './deletelink.js';
import './dropdown.js';
</code>```

My webpack.config.js is:

```<code>var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry: './src/js/main.js',
  output: {
    filename: 'wwwroot/js/bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      },
      {
        test: /\.(png|jpg|gif)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: 'images/[name].[ext]',
              outputPath: 'wwwroot/'
            }
          }
        ]
      },
      {
        test: /\.(eot|svg|ttf|woff|woff2)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: 'fonts/[name].[ext]',
              outputPath: 'wwwroot/'
            }
          }
        ]
      },
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          use: ['css-loader?url=false', 'resolve-url-loader'],
          publicPath: '../'
        })
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin({
      filename: 'wwwroot/css/bundle.css'
    })
  ]
};
</code>```

With the above configuration, the font references in bootstrap.css are picked up, moved to the appropriate directory and the urls are fixed in the css bundle that is emitted.  However, the images that are referenced in chosen.css are not being picked up.  Can anyone tell me what I need to do to make the images work correctly?  I've tried replacing file-loader with url-loader and no change.  I've also tried importing the images in my main.js and they were moved, but the urls in the css bundle were not rewritten correctly.

答:
I finally figured it out.  In the rules, I had:

```<code>{
  test: /\.css$/,
  use: ExtractTextPlugin.extract('css-loader', 'resolve-url-loader')
}
</code>```

Instead, it should be:

```<code>{
  test: /\.css$/,
  loader: ExtratTextPlugin.extract('css-loader', 'resolve-url-loader')
}
</code>```

Not sure what the difference is between use and loader because I'm fairly new to Webpack, but in this case it makes all the difference.

Body:
I am using Webpack to bundle a number of js/css files in a site.  I am bundling bootstrap.css and chosen.css as part of my bundles.  In order to create the bundles, I have a main.js that I am using as an entry point to import all the other files that I will need.  I am using file-loader to process font and image files and move them to the appropriate directories.  I am using the ExtractTextPlugin with the css-loader and resolve-url-loader to create a separate css bundle from my js bundle.

My main.js is:

import 'bootstrap/dist/css/bootstrap.css';
import 'chosen-js/chosen.css';
import './datetimehelper.js';
import './deletelink.js';
import './dropdown.js';

My webpack.config.js is:

var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry: './src/js/main.js',
  output: {
    filename: 'wwwroot/js/bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      },
      {
        test: /\.(png|jpg|gif)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: 'images/[name].[ext]',
              outputPath: 'wwwroot/'
            }
          }
        ]
      },
      {
        test: /\.(eot|svg|ttf|woff|woff2)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: 'fonts/[name].[ext]',
              outputPath: 'wwwroot/'
            }
          }
        ]
      },
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          use: ['css-loader?url=false', 'resolve-url-loader'],
          publicPath: '../'
        })
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin({
      filename: 'wwwroot/css/bundle.css'
    })
  ]
};

With the above configuration, the font references in bootstrap.css are picked up, moved to the appropriate directory and the urls are fixed in the css bundle that is emitted.  However, the images that are referenced in chosen.css are not being picked up.  Can anyone tell me what I need to do to make the images work correctly?  I've tried replacing file-loader with url-loader and no change.  I've also tried importing the images in my main.js and they were moved, but the urls in the css bundle were not rewritten correctly.

Body:
I finally figured it out.  In the rules, I had:

{
  test: /\.css$/,
  use: ExtractTextPlugin.extract('css-loader', 'resolve-url-loader')
}

Instead, it should be:

{
  test: /\.css$/,
  loader: ExtratTextPlugin.extract('css-loader', 'resolve-url-loader')
}

Not sure what the difference is between use and loader because I'm fairly new to Webpack, but in this case it makes all the difference.