问:
Passing extra Intent information from Activity to View
I have an activity that is launched from another activity through an intent. The intent carries an extra "id" information. Now, the launched activity has a custom view (actually, a extension of LinearLayout class). I want to access the "id" information in the custom view. Can the activity pass that value to its contained view? Or can the view get a handle to the activity?</p>

答:
YES,

First you have pass id with the intent  like

```<code>Intent i=new Intent(getApplicationContext(), sample.class);
i.putExtra("id", id);
startActivity();
</code>```

it pass the value to sample class

here

```<code>String i=getIntent().getExtras().getSerializable("id").toString();
</code>```

& you can use this id in your custom view

Body:
YES,

First you have pass id with the intent  like

Intent i=new Intent(getApplicationContext(), sample.class);
i.putExtra("id", id);
startActivity();

it pass the value to sample class

here

String i=getIntent().getExtras().getSerializable("id").toString();

& you can use this id in your custom view


来源: stackexchange

问:
Connecting to RDS Postgres from Heroku
I'm in the process of migrating my Heroku app database from Heroku to AWS RDS Postgres.

On my computer, I can connect to my RDS DB using:

```<code>psql -d "postgres://user:password@XXX.rds.amazonaws.com/mydb?sslrootcert=config/amazon-rds-ca-cert.pem&sslmode=require"
</code>```

However, the same psql command run from within my heroku server just hangs forever.

Also, config/amazon-rds-ca-cert.pem is the RDS certificate that I added to my package as mentioned in the documentation https://devcenter.heroku.com/articles/amazon-rds#authorizing-access-to-rds-instance and here https://stackoverflow.com/a/29467638/943524 (I did combine certificates as I am using a eu-central-1 instance).

Would someone have an idea what is blocking the connection here ?

答: From the sound of it, your Network ACL or Security Groups are blocking your access. It looks like they allow your computer (perhaps your entire company’s IP) but not Heroku. Check out the NACLs and Security Groups and you should find your answer (i.e. add Heroku IP range to your NACLs and/or Security Groups).</p>

ContentLicense: CC BY-SA 3.0

Title: Connecting to RDS Postgres from Heroku

Body:
I'm in the process of migrating my Heroku app database from Heroku to AWS RDS Postgres.

On my computer, I can connect to my RDS DB using:

psql -d "postgres://user:password@XXX.rds.amazonaws.com/mydb?sslrootcert=config/amazon-rds-ca-cert.pem&sslmode=require"

However, the same psql command run from within my heroku server just hangs forever.

Also, config/amazon-rds-ca-cert.pem is the RDS certificate that I added to my package as mentioned in the documentation https://devcenter.heroku.com/articles/amazon-rds#authorizing-access-to-rds-instance and here https://stackoverflow.com/a/29467638/943524 (I did combine certificates as I am using a eu-central-1 instance).

Would someone have an idea what is blocking the connection here ?


问:
Hibernate validation: give the ability to user to only enter a digits(number) not instead
I have a jsf form and I have an input which normally accept only number(integer) .
I want to custom the error message when the user enter a string or char in this field. I want the validation in the data layer thats mean with hibernate annotation.
I don't want use this default message if the user enter a string instead of integer,  I want using my custom error message.

: '10S' must be a number between -2147483648 and 2147483647 Example:
  9346

Please the attached image can explain well.
How could I achieve this please.

Thank you in advance.

答:
You can achieve this with the @Range annotation</p>

```<code>@Range(min = -2147483648, max = 2147483647, message= ": '10S' must be a number between -2147483648 and 2147483647 Example: 9346")
long value;
</code>```

Body:
You can achieve this with the @Range annotation

@Range(min = -2147483648, max = 2147483647, message= ": '10S' must be a number between -2147483648 and 2147483647 Example: 9346")
long value;


问:
CurrencyConverter in python . Error 'amounts' not defined , why ? . Also is there a shorter or more compact way of writing this code?
```<code>from currency_converter import CurrencyConverter
</code>```

I tried globalling amounts to fix my error but it didn't help

```<code>global amounts

c = CurrencyConverter()

currency = input('What ?')
currency = currency.split()
</code>```

list of currency's to choose from , dictionary

```<code>currencys = {"pounds":"GBP" , "dollars":"USD" , "euros":"EUR"}
WCurrency = ' '
</code>```

This is where it recognises what the sentence is

```<code>if 'what' in currency:
    next_word = currency[currency.index('what') + 1]
    if next_word == 'is':
</code>```

long if statements I would like to be shortened if possible

```<code>        if 'pounds' in currency:
                amounts = currency[currency.index('pounds') - 1]
                WCurrency = currencys['pounds']
        if 'euros' in currency:
                amounts = currency[currency.index('euros') - 1]
                WCurrency = currencys['euros']

        if 'dollars' in currency:
                amounts = currency[currency.index('dollars') - 1]
                WCurrency = currencys['dollars']
        if 'in' in currency:
                next_word = currency[currency.index('in') + 1]
        if next_word == 'dollars':
                W2Currency = currencys['dollars']
        if next_word == 'pounds':
                W2Currency = currencys['pounds']
        if next_word == 'euros':
                W2Currency = currencys['euros']
</code>```

This lets you input the sentence in a different format

```<code>if 'how' in currency:
    next_word = currency[currency.index('how') + 1]
    if next_word == 'many':
</code>```

long if statements I would like to be shortened if possible

```<code>        if 'pounds' in currency:
            W2Currency = currencys['pounds']
        if 'euros' in currency:
            W2Currency = currencys['euros']
        if 'dollars' in currency:
            W2Currency = currencys['dollars']
        if 'is' in currency:
            next_word = currency[currency.index('is') + 1]
        if next_word == 'dollars':
            amounts = currency[currency.index('dollars') - 1]
            WCurrency = currencys['dollars']
        if next_word == 'pounds':
            amounts = currency[currency.index('pounds') - 1]
            WCurrency = currencys['pounds']
        if next_word == 'euros':
            amounts = currency[currency.index('euros') - 1]
            WCurrency = currencys['euros']

def convertCurrency(amount, currency, targertCurrency):

    try:
        return c.convert(amount , currency , targertCurrency)
    except:
        print('Invalid currency or amounts!')

print(convertCurrency(amounts, str(WCurrency), str(W2Currency)))
</code>```

答:
use elif this prevents dollars from being recognized again. Also it's good practice. i.e.

```<code>    if 'pounds' in currency:
            amounts = currency[currency.index('pounds') - 1]
            WCurrency = currencys['pounds']
    elif 'euros' in currency:
            amounts = currency[currency.index('euros') - 1]
            WCurrency = currencys['euros']

    elif 'dollars' in currency:
            amounts = currency[currency.index('dollars') - 1]
            WCurrency = currencys['dollars']
    elif 'in' in currency:
            next_word = currency[currency.index('in') + 1]
    elif next_word == 'dollars':
            W2Currency = currencys['dollars']
    elif next_word == 'pounds':
            W2Currency = currencys['pounds']
    elif next_word == 'euros':
            W2Currency = currencys['euros']
</code>```

this means that if dollars and pounds are in the sentance it will recognise the first one. Alas this code is very messy and I would suggest using a for loop. i.e

```<code>for word in sentance:
    if word is in [list, of, currencies] and isdigit(sentance(word.index() - 1)):
        currency = word
</code>```

and so on...

Body:
from currency_converter import CurrencyConverter

I tried globalling amounts to fix my error but it didn't help

global amounts

c = CurrencyConverter()

currency = input('What ?')
currency = currency.split()

list of currency's to choose from , dictionary

currencys = {"pounds":"GBP" , "dollars":"USD" , "euros":"EUR"}
WCurrency = ' '

This is where it recognises what the sentence is

if 'what' in currency:
    next_word = currency[currency.index('what') + 1]
    if next_word == 'is':

long if statements I would like to be shortened if possible

        if 'pounds' in currency:
                amounts = currency[currency.index('pounds') - 1]
                WCurrency = currencys['pounds']
        if 'euros' in currency:
                amounts = currency[currency.index('euros') - 1]
                WCurrency = currencys['euros']

        if 'dollars' in currency:
                amounts = currency[currency.index('dollars') - 1]
                WCurrency = currencys['dollars']
        if 'in' in currency:
                next_word = currency[currency.index('in') + 1]
        if next_word == 'dollars':
                W2Currency = currencys['dollars']
        if next_word == 'pounds':
                W2Currency = currencys['pounds']
        if next_word == 'euros':
                W2Currency = currencys['euros']

This lets you input the sentence in a different format

if 'how' in currency:
    next_word = currency[currency.index('how') + 1]
    if next_word == 'many':

long if statements I would like to be shortened if possible

        if 'pounds' in currency:
            W2Currency = currencys['pounds']
        if 'euros' in currency:
            W2Currency = currencys['euros']
        if 'dollars' in currency:
            W2Currency = currencys['dollars']
        if 'is' in currency:
            next_word = currency[currency.index('is') + 1]
        if next_word == 'dollars':
            amounts = currency[currency.index('dollars') - 1]
            WCurrency = currencys['dollars']
        if next_word == 'pounds':
            amounts = currency[currency.index('pounds') - 1]
            WCurrency = currencys['pounds']
        if next_word == 'euros':
            amounts = currency[currency.index('euros') - 1]
            WCurrency = currencys['euros']

def convertCurrency(amount, currency, targertCurrency):

    try:
        return c.convert(amount , currency , targertCurrency)
    except:
        print('Invalid currency or amounts!')

print(convertCurrency(amounts, str(WCurrency), str(W2Currency)))

Body:
use elif this prevents dollars from being recognized again. Also it's good practice. i.e.

    if 'pounds' in currency:
            amounts = currency[currency.index('pounds') - 1]
            WCurrency = currencys['pounds']
    elif 'euros' in currency:
            amounts = currency[currency.index('euros') - 1]
            WCurrency = currencys['euros']

    elif 'dollars' in currency:
            amounts = currency[currency.index('dollars') - 1]
            WCurrency = currencys['dollars']
    elif 'in' in currency:
            next_word = currency[currency.index('in') + 1]
    elif next_word == 'dollars':
            W2Currency = currencys['dollars']
    elif next_word == 'pounds':
            W2Currency = currencys['pounds']
    elif next_word == 'euros':
            W2Currency = currencys['euros']

this means that if dollars and pounds are in the sentance it will recognise the first one. Alas this code is very messy and I would suggest using a for loop. i.e

for word in sentance:
    if word is in [list, of, currencies] and isdigit(sentance(word.index() - 1)):
        currency = word

and so on...


问:
how to convert text file to adjancency matrix in python
I have text file which includes:

1 2

1 5

2 3

2 5

3 4

I am new in python, How can I convert those data from .txt into adjacency matrix in python? Many thanks in advance.

答:
I'm guessing you're attempting to solve some graph problem. Read all the lines and create a square matrix with rows=columns=max number in the list

Then depending on whether the graph is directional or not you should fill in the locations in the matrix with a 1.

For example

```<code>Matrix = [[0 for x in range(n)] for y in range(n)]
</code>```

where n is the maximum number of nodes in the graph.

Then your first line should be assigned to

```<code>Matrix[0][1] = 1
Matrix[1][0] = 1 //this line if graph is not directional
</code>```

Body:
I'm guessing you're attempting to solve some graph problem. Read all the lines and create a square matrix with rows=columns=max number in the list

Then depending on whether the graph is directional or not you should fill in the locations in the matrix with a 1.

For example

Matrix = [[0 for x in range(n)] for y in range(n)]

where n is the maximum number of nodes in the graph.

Then your first line should be assigned to

Matrix[0][1] = 1
Matrix[1][0] = 1 //this line if graph is not directional


问:
How to reference a combination of dict() and list() in Python3?
This is an example of a complexe data structure. The depth of the structure is not fixed. To reference a specific datum in the structure I need a unknown number of indices (for list()) and keys (for dict()).

```<code>>>> x = [{'child': [{'text': 'ass'}, {'group': 'wef'}]}]
>>> x[0]['child'][0]['text']
'ass'
</code>```

Now I want to have single keys for the values like this.

```<code>keys = {'ID01': [0]['child'][0]['text'],
        'ID02': [1]['group']}
</code>```

But this is not possible. Is there another pythonic way?

答:
I think you need a couple of things here.  First is a custom lookup function:

```<code>def lookup(obj, keys):
    for k in keys:
        obj = obj[k]
    return obj
</code>```

Then a dictionary of keys to key list tuples:

```<code>keys = {'ID01': (0,'child',0,'text'),
        'ID02': (1,'group')}
</code>```

then you can do this:

```<code>lookup(x, keys['ID01']) # returns 'ass'
</code>```

Body:
This is an example of a complexe data structure. The depth of the structure is not fixed. To reference a specific datum in the structure I need a unknown number of indices (for list()) and keys (for dict()).

>>> x = [{'child': [{'text': 'ass'}, {'group': 'wef'}]}]
>>> x[0]['child'][0]['text']
'ass'

Now I want to have single keys for the values like this.

keys = {'ID01': [0]['child'][0]['text'],
        'ID02': [1]['group']}

But this is not possible. Is there another pythonic way?

Body:
I think you need a couple of things here.  First is a custom lookup function:

def lookup(obj, keys):
    for k in keys:
        obj = obj[k]
    return obj

Then a dictionary of keys to key list tuples:

keys = {'ID01': (0,'child',0,'text'),
        'ID02': (1,'group')}

then you can do this:

lookup(x, keys['ID01']) # returns 'ass'


问:
Why is it legal to borrow a temporary?
Coming from C++, I'm rather surprised that this code is valid in Rust:

```<code>let x = &mut String::new();
x.push_str("Hello!");
</code>```

In C++, you can't take the address of a temporary, and a temporary won't outlive the expression it appears in.

How long does the temporary live in Rust?  And since x is only a borrow, who is the owner of the string?

答:
Rust's MIR provides some insight on the nature of temporaries; consider the following simplified case:

```<code>fn main() {
    let foo = &String::new();
}
</code>```

and the MIR it produces (standard comments replaced with mine):

```<code>fn main() -> () {
    let mut _0: ();
    scope 1 {
        let _1: &std::string::String; // the reference is declared
    }
    scope 2 {
    }
    let mut _2: std::string::String; // the owner is declared

    bb0: {
        StorageLive(_1); // the reference becomes applicable
        StorageLive(_2); // the owner becomes applicable
        _2 = const std::string::String::new() -> bb1; // the owner gets a value; go to basic block 1
    }

    bb1: {
        _1 = &_2; // the reference now points to the owner
        _0 = ();
        StorageDead(_1); // the reference is no longer applicable
        drop(_2) -> bb2; // the owner's value is dropped; go to basic block 2
    }

    bb2: {
        StorageDead(_2); // the owner is no longer applicable
        return;
    }
}
</code>```

You can see that an "invisible" owner receives a value before a reference is assigned to it and that the reference is dropped before the owner, as expected.

What I'm not sure about is why there is a seemingly useless scope 2 and why the owner is not put inside any scope; I'm suspecting that MIR just isn't 100% ready yet.

Title: Why is it legal to borrow a temporary?

Body:
Coming from C++, I'm rather surprised that this code is valid in Rust:

let x = &mut String::new();
x.push_str("Hello!");

In C++, you can't take the address of a temporary, and a temporary won't outlive the expression it appears in.

How long does the temporary live in Rust?  And since x is only a borrow, who is the owner of the string?

Body:
Rust's MIR provides some insight on the nature of temporaries; consider the following simplified case:

fn main() {
    let foo = &String::new();
}

and the MIR it produces (standard comments replaced with mine):

fn main() -> () {
    let mut _0: ();
    scope 1 {
        let _1: &std::string::String; // the reference is declared
    }
    scope 2 {
    }
    let mut _2: std::string::String; // the owner is declared

    bb0: {
        StorageLive(_1); // the reference becomes applicable
        StorageLive(_2); // the owner becomes applicable
        _2 = const std::string::String::new() -> bb1; // the owner gets a value; go to basic block 1
    }

    bb1: {
        _1 = &_2; // the reference now points to the owner
        _0 = ();
        StorageDead(_1); // the reference is no longer applicable
        drop(_2) -> bb2; // the owner's value is dropped; go to basic block 2
    }

    bb2: {
        StorageDead(_2); // the owner is no longer applicable
        return;
    }
}

You can see that an "invisible" owner receives a value before a reference is assigned to it and that the reference is dropped before the owner, as expected.

What I'm not sure about is why there is a seemingly useless scope 2 and why the owner is not put inside any scope; I'm suspecting that MIR just isn't 100% ready yet.


问:
Using virtual objects with shared_ptr/unique_ptr in a container class
I am fairly new to C++ (coming from Java/PHP). Basically, I need to create a container class that will hold a reference of a unique/shared pointer to a virtual class instance (Base class). I am unable to get this piece of code to compile (I am using MSVC 2015).

The compiler error is:

```<code>error C2280: 'std::unique_ptr<Base,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)': attempting to reference a deleted function
</code>```

Here is a sample application to reproduce the issue:

```<code>#include <iostream>
#include <memory>

class Base {
    public:
        virtual void foo() const = 0;
        virtual void bar() const = 0;
};

class Derived : public Base {
    public:
        void foo() const override {
            std::cout << "foo" << std::endl;

        };

        void bar() const override{
            std::cout << "bar" << std::endl;
        };
};

class ContainerUnique {
    public:
        ContainerUnique() {
            ptr = nullptr;
        }

        void assignPtr(const Base &instance) {
            auto ptr = std::make_unique<Base>(instance);
            ptr.swap(ptr);
        };

        std::unique_ptr<Base> getPtr() {
            return ptr;
        };

    private:
        std::unique_ptr<Base> ptr;
};

class ContainerShared {
    public:
        ContainerShared() {
            ptr = nullptr;
        }

        void assignPtr(const Base &instance) {
            auto ptr = std::make_shared<Base>(instance);
            ptr.swap(ptr);
        };

        std::shared_ptr<Base> getPtr() {
            return ptr;
        };

    private:
        std::shared_ptr<Base> ptr;
};

int main() {
    Derived derived1 = Derived();
    Derived derived2 = Derived();

    ContainerUnique cu = ContainerUnique();
    ContainerShared cs = ContainerShared();

    cu.assignPtr(derived1);
    cs.assignPtr(derived2);

    std::unique_ptr<Base> uptr = cu.getPtr();
    std::shared_ptr<Base> sptr = cs.getPtr();

    return 0;
}
</code>```

Please advice

答:
You should think about object ownership, and where objects live (stack or heap), neither of which you may have had to focus on in Java.

Because ContainerUnique has a unique_ptr member, I infer that it is intended to own the pointed-to object. It is being given the obligation to delete it. This is inconsistent with the rest, because derived1 is on the stack, so has no need to be owned by anything, and cannot be deleted. Instead, suppose we created derived1 on the heap:

```<code>auto derived1 = std::make_unique<Derived>();
</code>```

That creates it on the heap, so that it needs managing, and identifies us as owning the object by storing its pointer in a unique_ptr. To transfer ownership with a unique_ptr, we have to tweak the interface:

```<code>// Interface
void ContainerUnique::assignPtr(std::unique_ptr<Base> instance);
// Call site
cu.assignPtr(std::move(derived1));
</code>```

If we take a raw reference or pointer, there is nothing in the interface or the call site to reflect the intended change in ownership. If we take a reference-to-Base, and call std::make_unique we are making a copy, and making a copy of a Base (losing any Derived data). Taking a unique_ptr is probably the clearest way to communicate ownership transfer.

Putting it together:

```<code>#include <memory>

struct Base {
    virtual void foo() const = 0;
    virtual void bar() const = 0;
};

struct Derived : Base {
    void foo() const override { }
    void bar() const override { }
};

class ContainerUnique {
    public:
        void assignPtr(std::unique_ptr<Base> instance) {
            ptr.swap(instance);
        };

        std::unique_ptr<Base> getPtr() {
            return std::move(ptr);
        };

    private:
        std::unique_ptr<Base> ptr;
};

int main() {
    auto derived1 = std::make_unique<Derived>();
    auto cu = ContainerUnique();
    cu.assignPtr(std::move(derived1));
    auto uptr = cu.getPtr();
}
</code>```

Body:
I am fairly new to C++ (coming from Java/PHP). Basically, I need to create a container class that will hold a reference of a unique/shared pointer to a virtual class instance (Base class). I am unable to get this piece of code to compile (I am using MSVC 2015).

The compiler error is:

error C2280: 'std::unique_ptr<Base,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)': attempting to reference a deleted function

Here is a sample application to reproduce the issue:

#include <iostream>
#include <memory>

class Base {
    public:
        virtual void foo() const = 0;
        virtual void bar() const = 0;
};

class Derived : public Base {
    public:
        void foo() const override {
            std::cout << "foo" << std::endl;

        };

        void bar() const override{
            std::cout << "bar" << std::endl;
        };
};

class ContainerUnique {
    public:
        ContainerUnique() {
            ptr = nullptr;
        }

        void assignPtr(const Base &instance) {
            auto ptr = std::make_unique<Base>(instance);
            ptr.swap(ptr);
        };

        std::unique_ptr<Base> getPtr() {
            return ptr;
        };

    private:
        std::unique_ptr<Base> ptr;
};

class ContainerShared {
    public:
        ContainerShared() {
            ptr = nullptr;
        }

        void assignPtr(const Base &instance) {
            auto ptr = std::make_shared<Base>(instance);
            ptr.swap(ptr);
        };

        std::shared_ptr<Base> getPtr() {
            return ptr;
        };

    private:
        std::shared_ptr<Base> ptr;
};

int main() {
    Derived derived1 = Derived();
    Derived derived2 = Derived();

    ContainerUnique cu = ContainerUnique();
    ContainerShared cs = ContainerShared();

    cu.assignPtr(derived1);
    cs.assignPtr(derived2);

    std::unique_ptr<Base> uptr = cu.getPtr();
    std::shared_ptr<Base> sptr = cs.getPtr();

    return 0;
}

Please advice

Body:
You should think about object ownership, and where objects live (stack or heap), neither of which you may have had to focus on in Java.

Because ContainerUnique has a unique_ptr member, I infer that it is intended to own the pointed-to object. It is being given the obligation to delete it. This is inconsistent with the rest, because derived1 is on the stack, so has no need to be owned by anything, and cannot be deleted. Instead, suppose we created derived1 on the heap:

auto derived1 = std::make_unique<Derived>();

That creates it on the heap, so that it needs managing, and identifies us as owning the object by storing its pointer in a unique_ptr. To transfer ownership with a unique_ptr, we have to tweak the interface:

// Interface
void ContainerUnique::assignPtr(std::unique_ptr<Base> instance);
// Call site
cu.assignPtr(std::move(derived1));

If we take a raw reference or pointer, there is nothing in the interface or the call site to reflect the intended change in ownership. If we take a reference-to-Base, and call std::make_unique we are making a copy, and making a copy of a Base (losing any Derived data). Taking a unique_ptr is probably the clearest way to communicate ownership transfer.

Putting it together:

#include <memory>

struct Base {
    virtual void foo() const = 0;
    virtual void bar() const = 0;
};

struct Derived : Base {
    void foo() const override { }
    void bar() const override { }
};

class ContainerUnique {
    public:
        void assignPtr(std::unique_ptr<Base> instance) {
            ptr.swap(instance);
        };

        std::unique_ptr<Base> getPtr() {
            return std::move(ptr);
        };

    private:
        std::unique_ptr<Base> ptr;
};

int main() {
    auto derived1 = std::make_unique<Derived>();
    auto cu = ContainerUnique();
    cu.assignPtr(std::move(derived1));
    auto uptr = cu.getPtr();
}


问:
Asp.net mvc3: How to pull data from database and fill view model in one goal?
I need to pull the data from DB and fill the view model, is there any better way to do this?
Currently I'm doing something like this.</p>

```<code>ViewModel vm = new ViewModel();
var recentBill = context.Money.Take(10);
foreach (var r in recnetBill)
{
    vm.lst.Add(r);
}
</code>```

答:
IEnumerable has the ToList() function which returns a list of said type.

```<code>vm.lst = context.Money.Take(10).ToList(); // returns a List<Money>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I need to pull the data from DB and fill the view model, is there any better way to do this?
Currently I'm doing something like this.

ViewModel vm = new ViewModel();
var recentBill = context.Money.Take(10);
foreach (var r in recnetBill)
{
    vm.lst.Add(r);
}

Body:
IEnumerable has the ToList() function which returns a list of said type.

vm.lst = context.Money.Take(10).ToList(); // returns a List<Money>


问:
For-loop yielding partially correct result
So here is my code, I am trying to calculate the area of a wave:

```<code>public class coefficient {
public static void main (String[] args) {

    double f[] = {14.0,18.7,9,4.1,6.7,6,6.3,8.4,4,2.9};
    double T = 10;
    double area = 0;
    int n = 5;

    double w = 2 * Math.PI / T;

    for (int i = 1; i <= n; i++) {

        System.out.println("n = " + i);

            for (int t = 0; t < f.length; t++) {
                System.out.println("T = " + t + " .......... " + f[t] * Math.cos(i*(w * t)));
                area += f[t] * Math.cos(i*(w * t));
            }

        System.out.printf("\nTotal Area: \t\t%.2f\n", area);
        System.out.printf("Calculated area: \t%.2f\n\n", (2/T)*area);

    }

}

}
</code>```

So my outputs are correct, except for my total and calculated areas, which are RIGHT when i=1, but after that they don't give me the right answer.

Here's the thing though - when I manually input "i":

```<code>area += f[t] * Math.cos(1*(w * t)); OR
area += f[t] * Math.cos(2*(w * t));
</code>```

I get the right areas! So I think there's something wrong with my for-loop, but I'm not sure what...

So when i = 1, my area output = 15.11. That is correct. Now, when i = 2 in my loop, I SHOULD get 10.06 but instead I'm getting 25.17. I get the correct answer when I manually change i, so i isn't being defined in that line. But it is in the line above it.

答:
Maybe it's because you aren't setting area back to 0 after each iteration. Move the declaration of area into the for loop, and see if that workd.

```<code>double f[] = {14.0,18.7,9,4.1,6.7,6,6.3,8.4,4,2.9};
double T = 10;
int n = 5;

double w = 2 * Math.PI / T;

for (int i = 1; i <= n; i++) {
    double area = 0;

    System.out.println("n = " + i);

    for (int t = 0; t < f.length; t++) {
        System.out.println("T = " + t + " .......... " + f[t] * Math.cos(i*(w * t)));
        area += f[t] * Math.cos(i*(w * t));
    }

    System.out.printf("\nTotal Area: \t\t%.2f\n", area);
    System.out.printf("Calculated area: \t%.2f\n\n", (2/T)*area);

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
So here is my code, I am trying to calculate the area of a wave:

public class coefficient {
public static void main (String[] args) {

    double f[] = {14.0,18.7,9,4.1,6.7,6,6.3,8.4,4,2.9};
    double T = 10;
    double area = 0;
    int n = 5;

    double w = 2 * Math.PI / T;

    for (int i = 1; i <= n; i++) {

        System.out.println("n = " + i);

            for (int t = 0; t < f.length; t++) {
                System.out.println("T = " + t + " .......... " + f[t] * Math.cos(i*(w * t)));
                area += f[t] * Math.cos(i*(w * t));
            }

        System.out.printf("\nTotal Area: \t\t%.2f\n", area);
        System.out.printf("Calculated area: \t%.2f\n\n", (2/T)*area);

    }

}

}

So my outputs are correct, except for my total and calculated areas, which are RIGHT when i=1, but after that they don't give me the right answer.

Here's the thing though - when I manually input "i":

area += f[t] * Math.cos(1*(w * t)); OR
area += f[t] * Math.cos(2*(w * t));

I get the right areas! So I think there's something wrong with my for-loop, but I'm not sure what...

So when i = 1, my area output = 15.11. That is correct. Now, when i = 2 in my loop, I SHOULD get 10.06 but instead I'm getting 25.17. I get the correct answer when I manually change i, so i isn't being defined in that line. But it is in the line above it.

Body:
Maybe it's because you aren't setting area back to 0 after each iteration. Move the declaration of area into the for loop, and see if that workd.

double f[] = {14.0,18.7,9,4.1,6.7,6,6.3,8.4,4,2.9};
double T = 10;
int n = 5;

double w = 2 * Math.PI / T;

for (int i = 1; i <= n; i++) {
    double area = 0;

    System.out.println("n = " + i);

    for (int t = 0; t < f.length; t++) {
        System.out.println("T = " + t + " .......... " + f[t] * Math.cos(i*(w * t)));
        area += f[t] * Math.cos(i*(w * t));
    }

    System.out.printf("\nTotal Area: \t\t%.2f\n", area);
    System.out.printf("Calculated area: \t%.2f\n\n", (2/T)*area);

}


问:
Creating OnDragListener for Google Map v2 Fragment
I’m trying to setup an onDrag Listener for a google map fragment, but can’t get the drag event to fire. Since the map doesn't support drag events directly, I'm trying to implement a drag listener for the View. I know about the onMarkerDrag event, but that does me no good since I'm not trying to move markers around.

The reason for trapping map drag events is twofold:

First to detect if the user has panned the map. If they haven't, I like to keep their location on the screen, and animate to their location if it's not on the map. If they have panned the map, I assume they know what they want to see and force the location on the screen. (this seems like something that should be included in the API)

The second reason for trapping is to allow users to draw lines and polygons on the map. I can do this with onTap events(adding points), but I'd like to be able to let them freehand it as well.

My code looks like this:

mainActivity:

```<code>    mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    setUpMapIfNeeded();
    mMapView = findViewById(R.id.map);
    myMapDragListener = new MapDragListener();
    mMapView.setOnDragListener(myMapDragListener);
</code>```

The Listener:

```<code>public class MapDragListener implements OnDragListener {
    /**
     *
     */
    public MapDragListener() {
        super();
        say.logCat("MapDragListener: I'm ALIVE!!!!");
    }

    private AkamaiAnnounce say = new AkamaiAnnounce();
    private boolean inDrag;
    private boolean hasPanned=false;

    @Override
    public boolean onDrag(View v, DragEvent event) {
        say.logCat("MapDragListener.onDrag: " + event.toString());
        //String dotTAG = (String) getTag();
        if (event.getLocalState() != this) {
          return false;
        }
        boolean myResult = true;
        int action = event.getAction();
        float x = event.getX();
        float y = event.getY();
        switch (action) {
        case DragEvent.ACTION_DRAG_STARTED:
          inDrag = true;
          break;
        case DragEvent.ACTION_DRAG_LOCATION:
          break;
        case DragEvent.ACTION_DRAG_ENTERED:
          break;
        case DragEvent.ACTION_DRAG_EXITED:
          break;
        case DragEvent.ACTION_DROP:
          myResult = false;
          break;
        case DragEvent.ACTION_DRAG_ENDED:
          inDrag = false; // change color of original dot back
          hasPanned=true;
          break;
        default:
          myResult = false;
          break;
        }
        return false;
        //return myResult;

    }

    public boolean hasPanned() {
        return hasPanned;
    }

    public void setHasPanned(boolean hasPanned) {
        this.hasPanned = hasPanned;
    }

}
</code>```

The map works fine. The listener instantiates, but my onDrag event never fires. Any ideas?

答:
I did something like similar using a BehaviorSubject to tell if the map was dirty (moved by user)</p>

```<code>    storeMap.setOnCameraMoveStartedListener(new GoogleMap.OnCameraMoveStartedListener() {
        @Override
        public void onCameraMoveStarted(int reason) {
            if (reason == REASON_GESTURE) {
                mapIsDirty.onNext(true);
            }
        }
    });
    storeMap.setOnCameraIdleListener(new OnCameraIdleListener() {
        @Override
        public void onCameraIdle() {
            if(mapIsDirty.getValue()) {
            // Do happy things
            mapIsDirty.onNext(false);
            }
        }
    });
</code>```

Body:
I’m trying to setup an onDrag Listener for a google map fragment, but can’t get the drag event to fire. Since the map doesn't support drag events directly, I'm trying to implement a drag listener for the View. I know about the onMarkerDrag event, but that does me no good since I'm not trying to move markers around.

The reason for trapping map drag events is twofold:

First to detect if the user has panned the map. If they haven't, I like to keep their location on the screen, and animate to their location if it's not on the map. If they have panned the map, I assume they know what they want to see and force the location on the screen. (this seems like something that should be included in the API)

The second reason for trapping is to allow users to draw lines and polygons on the map. I can do this with onTap events(adding points), but I'd like to be able to let them freehand it as well.

My code looks like this:

mainActivity:

    mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    setUpMapIfNeeded();
    mMapView = findViewById(R.id.map);
    myMapDragListener = new MapDragListener();
    mMapView.setOnDragListener(myMapDragListener);

The Listener:

public class MapDragListener implements OnDragListener {
    /**
     *
     */
    public MapDragListener() {
        super();
        say.logCat("MapDragListener: I'm ALIVE!!!!");
    }

    private AkamaiAnnounce say = new AkamaiAnnounce();
    private boolean inDrag;
    private boolean hasPanned=false;

    @Override
    public boolean onDrag(View v, DragEvent event) {
        say.logCat("MapDragListener.onDrag: " + event.toString());
        //String dotTAG = (String) getTag();
        if (event.getLocalState() != this) {
          return false;
        }
        boolean myResult = true;
        int action = event.getAction();
        float x = event.getX();
        float y = event.getY();
        switch (action) {
        case DragEvent.ACTION_DRAG_STARTED:
          inDrag = true;
          break;
        case DragEvent.ACTION_DRAG_LOCATION:
          break;
        case DragEvent.ACTION_DRAG_ENTERED:
          break;
        case DragEvent.ACTION_DRAG_EXITED:
          break;
        case DragEvent.ACTION_DROP:
          myResult = false;
          break;
        case DragEvent.ACTION_DRAG_ENDED:
          inDrag = false; // change color of original dot back
          hasPanned=true;
          break;
        default:
          myResult = false;
          break;
        }
        return false;
        //return myResult;

    }

    public boolean hasPanned() {
        return hasPanned;
    }

    public void setHasPanned(boolean hasPanned) {
        this.hasPanned = hasPanned;
    }

}

The map works fine. The listener instantiates, but my onDrag event never fires. Any ideas?

Body:
I did something like similar using a BehaviorSubject to tell if the map was dirty (moved by user)

    storeMap.setOnCameraMoveStartedListener(new GoogleMap.OnCameraMoveStartedListener() {
        @Override
        public void onCameraMoveStarted(int reason) {
            if (reason == REASON_GESTURE) {
                mapIsDirty.onNext(true);
            }
        }
    });
    storeMap.setOnCameraIdleListener(new OnCameraIdleListener() {
        @Override
        public void onCameraIdle() {
            if(mapIsDirty.getValue()) {
            // Do happy things
            mapIsDirty.onNext(false);
            }
        }
    });


问:
Create a singleton class with react native
I found different topics explain how to create a singleton, but none of them worked for me. This is an example taken from this post

```<code>export default class Credentials {

    static myInstance = null;

    _userID = "";

    static getInstance() {
        if (myInstance == null) {
            myInstance = new Credentials();
        }

        return myInstance;
    }

    getUserID() {
        return this._userID;
    }

    setUserID(id) {
        this._userID = id;
    }
}
</code>```

when I call Credentials.getInstance() I get a warning

Can't find variable myInstance

答:
This should be enough for any kind of single ton instance in JS.

Now, wherever you import this the same instance will be used. You can cross check by adding a date inside the class and accessing it at various places where you imported this.

```<code>import { SomeClass } from 'some-class'

let singletonInstance;

if (!singletonInstance) {
  singletonInstance = new SomeClass();
  // singletonInstance.time = new Date();
}

export default singletonInstance;
</code>```

Then import it using

import singletonInstance from './above-code-file'

Body:
I found different topics explain how to create a singleton, but none of them worked for me. This is an example taken from this post

export default class Credentials {

    static myInstance = null;

    _userID = "";

    static getInstance() {
        if (myInstance == null) {
            myInstance = new Credentials();
        }

        return myInstance;
    }

    getUserID() {
        return this._userID;
    }

    setUserID(id) {
        this._userID = id;
    }
}

when I call Credentials.getInstance() I get a warning

Can't find variable myInstance

Body:
This should be enough for any kind of single ton instance in JS.

Now, wherever you import this the same instance will be used. You can cross check by adding a date inside the class and accessing it at various places where you imported this.

import { SomeClass } from 'some-class'

let singletonInstance;

if (!singletonInstance) {
  singletonInstance = new SomeClass();
  // singletonInstance.time = new Date();
}

export default singletonInstance;

Then import it using

import singletonInstance from './above-code-file'


问:
How do I make sure there are no repeated numbers when using random()?
I have this code that displays 100 random numbers, then adds a break for every 10 numbers. How would I ensure that these 100 random numbers do not have repeats? I know maybe there's something to do with more if statements?

Thanks,
J

<!DOCTYPE html>

Random Numbers and Breaks (for loops)

This will display 100 numbers and insert a break in 10-number intervals:

```

答:
I think this is what you want, if you don't know what something does, please research it. Do not simply copy and paste.

      var text= '';
      var i = 0;
      var counter = 0;
      var nums = []; // Created array
      var numbers;
      for (; i < 100; i++ , counter++) {
        numbers = Math.floor((Math.random() * 100) + 1);
        while (nums.includes(numbers))
          numbers = Math.floor((Math.random() * 100) + 1);
        // While nums array includes numbers, reroll.
        nums.push(numbers); // Push the number to the array
        text += numbers + "  " + "
";
        if (i % 10 === 9) text += "
"
      // If the rightmost digit is a 9, add the br tag
    }
    document.getElementById("demo").innerHTML = text;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <h1><font color = "blue">Random Numbers and Breaks (for loops)</font></h1>
  <p><font color="red">This will display 100 numbers and insert a break in 10-number intervals:</font></p>
  <div id="demo"> </div>
  <body>
  </body>
</html></code>```

Body:
I think this is what you want, if you don't know what something does, please research it. Do not simply copy and paste.

      var text= '';
      var i = 0;
      var counter = 0;
      var nums = []; // Created array
      var numbers;
      for (; i < 100; i++ , counter++) {
        numbers = Math.floor((Math.random() * 100) + 1);
        while (nums.includes(numbers))
          numbers = Math.floor((Math.random() * 100) + 1);
        // While nums array includes numbers, reroll.
        nums.push(numbers); // Push the number to the array
        text += numbers + "  " + "<br>";
        if (i % 10 === 9) text += "<br>"
      // If the rightmost digit is a 9, add the br tag
    }
    document.getElementById("demo").innerHTML = text;

<!DOCTYPE html>
<html>
  <h1><font color = "blue">Random Numbers and Breaks (for loops)</font></h1>
  <p><font color="red">This will display 100 numbers and insert a break in 10-number intervals:</font></p>
  <div id="demo"> </div>
  <body>
  </body>
</html>


问:
Tensorflow _lstm_ops.dll not found
I am trying to build an LSTM model that I downloaded from Github, using Tensorflow and Python 3.6. The link for the model is https://github.com/adeshpande3/LSTM-Sentiment-Analysis.

When the following command is executed

lstmCell = tf.contrib.rnn.BasicLSTMCell(lstmUnits)

I am receiving the error

NotFoundError: D:\Anaconda3\lib\site-packages\tensorflow\contrib\rnn\python\ops_lstm_ops.dll not found

As you may have notices, the path has no non-ASCII codes!!

Any suggestion?

答: According to the project's Github page, the code runs on TensorFlow 1.1, and won't work with TensorFlow 1.2 or higher. If you're using a current version of TensorFlow, that's your problem. </p>

Title: Tensorflow _lstm_ops.dll not found


问:
Can i use KXML framework?
Can i use KXML framework for android application?</p>

答: Android supports KXML. I used KXML for android application. Its working fine.</p>

Title: Can i use KXML framework?


问:
Launch .NET Framework console app into a new window from inside a .NET Core Console app
I have a .NET Core console app (a TCP client) that needs to launch a .NET Framework console app (a TCP Server). I'm using System.Diagnostics.Process.Start(server); and it starts, but both console apps are in the same window. How can I get the server to run in a separate window?

答:
If you set the process properties as follows. You will get it in a new window.</p>

```<code>ProcessStartInfo p = new ProcessStartInfo(fileName, arg);
p.UseShellExecute=true;
Process processChild = Process.Start(p); // separate window;
</code>```

Body:
If you set the process properties as follows. You will get it in a new window.

ProcessStartInfo p = new ProcessStartInfo(fileName, arg);
p.UseShellExecute=true;
Process processChild = Process.Start(p); // separate window;


问:
conditionally add new xml element after specific sibling node
I am trying to add a new XML element at a specific place using the Identity Transformation and a predicate match of a child node within the context node. I can successfully add the elements however the order of the XML is important and my current xsl script is placing the new elements within the context node of my template matching statement, essentially placing the new element as an 'out of sequence' sibling node. Below is my source XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
   <CstmrCdtTrfInitn>
      <PmtInf>
         <CdtTrfTxInf>
            <CdtrAgt>
               <FinInstnId>
                  <Nm>Exciting Place</Nm>
               </FinInstnId>
               <BrnchId>
                  <Nm>Big Building</Nm>
                  <PstlAdr>
                     <Ctry>BR</Ctry>
                  </PstlAdr>
               </BrnchId>
            </CdtrAgt>
            <Cdtr>
               <Nm>/POP:Other</Nm>
            </Cdtr>
            <CdtrAcct>
               <Id>
                  <IBAN>123456789123456789</IBAN>
               </Id>
               <Ccy>USD</Ccy>
               <Nm>Winston Churchill</Nm>
            </CdtrAcct>
            <Tax>
               <TaxId>100</TaxId>
            </Tax>
            <RmtInf>
               <Ustrd>Test</Ustrd>
            </RmtInf>
         </CdtTrfTxInf>
      </PmtInf>
   </CstmrCdtTrfInitn>
</Document>
</code>```

I need to add the elements "Purp/Cd" to the XML document following the "Tax" node ONLY when the "CdtAgt/BrnchId/Ctry" sibling node has a value of "BR". I have tried the following XSL script but it places the elements in the wrong location; I have attempted to adjust the predicate[] matching statement without any luck.  Here is my script:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xpath-default-namespace="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03"
    exclude-result-prefixes="xs xsl"
    version="2.0">

    <xsl:output indent="yes"/>

    <!-- Generic identity template -->
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="@*"/>
            <xsl:apply-templates/>
        </xsl:copy>
    </xsl:template>

    <!-- Copy the children of the current node -->
    <xsl:template name="copy-children">
        <xsl:copy-of select="./*"/>
    </xsl:template>

    <xsl:template match="*/CdtTrfTxInf[CdtrAgt/BrnchId/PstlAdr/Ctry[text() = 'BR']]">
        <xsl:copy>

            <xsl:element name="Purp" namespace="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
                <xsl:element name="Cd" namespace="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
                    <xsl:value-of select="'P1019'"/>
                </xsl:element>
            </xsl:element>
            <xsl:call-template name="copy-children"/>

        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>
</code>```

This stylesheet produces an improperly aligned XML document in which the "Purp/Cd" nodes immediately follow the "CstmrCdtTrfInitn/PmtInf" node instead of the desired location following the "Tax" node; undesirable output below:

```<code> <?xml version="1.0" encoding="UTF-8"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
   <CstmrCdtTrfInitn>
      <PmtInf>
         <CdtTrfTxInf>
            <Purp>
               <Cd>P1019</Cd>
            </Purp>
            <CdtrAgt>
               <FinInstnId>
                  <Nm>Exciting Place</Nm>
               </FinInstnId>
               <BrnchId>
                  <Nm>Big Building</Nm>
                  <PstlAdr>
                     <Ctry>BR</Ctry>
                  </PstlAdr>
               </BrnchId>
            </CdtrAgt>
            <Cdtr>
               <Nm>/POP:Other</Nm>
            </Cdtr>
            <CdtrAcct>
               <Id>
                  <IBAN>123456789123456789</IBAN>
               </Id>
               <Ccy>USD</Ccy>
               <Nm>Winston Churchill</Nm>
            </CdtrAcct>
            <Tax>
               <TaxId>100</TaxId>
            </Tax>
            <RmtInf>
               <Ustrd>Test</Ustrd>
            </RmtInf>
         </CdtTrfTxInf>
      </PmtInf>
   </CstmrCdtTrfInitn>
</Document>
</code>```

I need the new nodes to be place after the "Tax" node but do not know how to produce the correct result while also using a predicate match at the context node level; I imagine this is my issue but do not know how to adjust my script.  Your suggestions are greatly appreciated.

Desired output below:

```<code><?xml version="1.0" encoding="utf-8"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
   <CstmrCdtTrfInitn>
      <PmtInf>
         <CdtTrfTxInf>
            <CdtrAgt>
               <FinInstnId>
                  <Nm>Exciting Place</Nm>
               </FinInstnId>
               <BrnchId>
                  <Nm>Big Building</Nm>
                  <PstlAdr>
                     <Ctry>BR</Ctry>
                  </PstlAdr>
               </BrnchId>
            </CdtrAgt>
            <Cdtr>
               <Nm>/POP:Other</Nm>
            </Cdtr>
            <CdtrAcct>
               <Id>
                  <IBAN>123456789123456789</IBAN>
               </Id>
               <Ccy>USD</Ccy>
               <Nm>Winston Churchill</Nm>
            </CdtrAcct>
            <Tax>
               <TaxId>100</TaxId>
            </Tax>
            <Purp>
               <Cd>P1019</Cd>
            </Purp>
            <RmtInf>
               <Ustrd>Test</Ustrd>
            </RmtInf>
         </CdtTrfTxInf>
      </PmtInf>
   </CstmrCdtTrfInitn>
</Document>
</code>```

答:
If you want to place your new node after the Tax element, you should change your template to match the Tax element....

```<code> <xsl:template match="CdtTrfTxInf[CdtrAgt/BrnchId/PstlAdr/Ctry[text() = 'BR']]/Tax">
</code>```

Then, inside this you can copy the Tax node exactly (using xsl:next-match as you are using XSLT 2.0), then create your new node after it.

Try this XSLT, which I have simplified a bit more by using a default namespace to output the new elements.

```<code><xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xpath-default-namespace="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03"
    xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03"
    exclude-result-prefixes="xs xsl"
    version="2.0">

    <xsl:output indent="yes"/>

    <!-- Generic identity template -->
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="CdtTrfTxInf[CdtrAgt/BrnchId/PstlAdr/Ctry[text() = 'BR']]/Tax">
        <xsl:next-match />
        <Purp>
            <Cd>
                <xsl:text>P1019</xsl:text>
            </Cd>
        </Purp>
    </xsl:template>
</xsl:stylesheet>
</code>```

Body:
I am trying to add a new XML element at a specific place using the Identity Transformation and a predicate match of a child node within the context node. I can successfully add the elements however the order of the XML is important and my current xsl script is placing the new elements within the context node of my template matching statement, essentially placing the new element as an 'out of sequence' sibling node. Below is my source XML:

<?xml version="1.0" encoding="utf-8"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
   <CstmrCdtTrfInitn>
      <PmtInf>
         <CdtTrfTxInf>
            <CdtrAgt>
               <FinInstnId>
                  <Nm>Exciting Place</Nm>
               </FinInstnId>
               <BrnchId>
                  <Nm>Big Building</Nm>
                  <PstlAdr>
                     <Ctry>BR</Ctry>
                  </PstlAdr>
               </BrnchId>
            </CdtrAgt>
            <Cdtr>
               <Nm>/POP:Other</Nm>
            </Cdtr>
            <CdtrAcct>
               <Id>
                  <IBAN>123456789123456789</IBAN>
               </Id>
               <Ccy>USD</Ccy>
               <Nm>Winston Churchill</Nm>
            </CdtrAcct>
            <Tax>
               <TaxId>100</TaxId>
            </Tax>
            <RmtInf>
               <Ustrd>Test</Ustrd>
            </RmtInf>
         </CdtTrfTxInf>
      </PmtInf>
   </CstmrCdtTrfInitn>
</Document>

I need to add the elements "Purp/Cd" to the XML document following the "Tax" node ONLY when the "CdtAgt/BrnchId/Ctry" sibling node has a value of "BR". I have tried the following XSL script but it places the elements in the wrong location; I have attempted to adjust the predicate[] matching statement without any luck.  Here is my script:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xpath-default-namespace="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03"
    exclude-result-prefixes="xs xsl"
    version="2.0">

    <xsl:output indent="yes"/>

    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="@*"/>
            <xsl:apply-templates/>
        </xsl:copy>
    </xsl:template>

    <xsl:template name="copy-children">
        <xsl:copy-of select="./*"/>
    </xsl:template>

    <xsl:template match="*/CdtTrfTxInf[CdtrAgt/BrnchId/PstlAdr/Ctry[text() = 'BR']]">
        <xsl:copy>

            <xsl:element name="Purp" namespace="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
                <xsl:element name="Cd" namespace="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
                    <xsl:value-of select="'P1019'"/>
                </xsl:element>
            </xsl:element>
            <xsl:call-template name="copy-children"/>

        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

This stylesheet produces an improperly aligned XML document in which the "Purp/Cd" nodes immediately follow the "CstmrCdtTrfInitn/PmtInf" node instead of the desired location following the "Tax" node; undesirable output below:

 <?xml version="1.0" encoding="UTF-8"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
   <CstmrCdtTrfInitn>
      <PmtInf>
         <CdtTrfTxInf>
            <Purp>
               <Cd>P1019</Cd>
            </Purp>
            <CdtrAgt>
               <FinInstnId>
                  <Nm>Exciting Place</Nm>
               </FinInstnId>
               <BrnchId>
                  <Nm>Big Building</Nm>
                  <PstlAdr>
                     <Ctry>BR</Ctry>
                  </PstlAdr>
               </BrnchId>
            </CdtrAgt>
            <Cdtr>
               <Nm>/POP:Other</Nm>
            </Cdtr>
            <CdtrAcct>
               <Id>
                  <IBAN>123456789123456789</IBAN>
               </Id>
               <Ccy>USD</Ccy>
               <Nm>Winston Churchill</Nm>
            </CdtrAcct>
            <Tax>
               <TaxId>100</TaxId>
            </Tax>
            <RmtInf>
               <Ustrd>Test</Ustrd>
            </RmtInf>
         </CdtTrfTxInf>
      </PmtInf>
   </CstmrCdtTrfInitn>
</Document>

I need the new nodes to be place after the "Tax" node but do not know how to produce the correct result while also using a predicate match at the context node level; I imagine this is my issue but do not know how to adjust my script.  Your suggestions are greatly appreciated.

Desired output below:

<?xml version="1.0" encoding="utf-8"?>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
   <CstmrCdtTrfInitn>
      <PmtInf>
         <CdtTrfTxInf>
            <CdtrAgt>
               <FinInstnId>
                  <Nm>Exciting Place</Nm>
               </FinInstnId>
               <BrnchId>
                  <Nm>Big Building</Nm>
                  <PstlAdr>
                     <Ctry>BR</Ctry>
                  </PstlAdr>
               </BrnchId>
            </CdtrAgt>
            <Cdtr>
               <Nm>/POP:Other</Nm>
            </Cdtr>
            <CdtrAcct>
               <Id>
                  <IBAN>123456789123456789</IBAN>
               </Id>
               <Ccy>USD</Ccy>
               <Nm>Winston Churchill</Nm>
            </CdtrAcct>
            <Tax>
               <TaxId>100</TaxId>
            </Tax>
            <Purp>
               <Cd>P1019</Cd>
            </Purp>
            <RmtInf>
               <Ustrd>Test</Ustrd>
            </RmtInf>
         </CdtTrfTxInf>
      </PmtInf>
   </CstmrCdtTrfInitn>
</Document>

Body:
If you want to place your new node after the Tax element, you should change your template to match the Tax element....

 <xsl:template match="CdtTrfTxInf[CdtrAgt/BrnchId/PstlAdr/Ctry[text() = 'BR']]/Tax">

Then, inside this you can copy the Tax node exactly (using xsl:next-match as you are using XSLT 2.0), then create your new node after it.

Try this XSLT, which I have simplified a bit more by using a default namespace to output the new elements.

<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xpath-default-namespace="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03"
    xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03"
    exclude-result-prefixes="xs xsl"
    version="2.0">

    <xsl:output indent="yes"/>

    <!-- Generic identity template -->
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="CdtTrfTxInf[CdtrAgt/BrnchId/PstlAdr/Ctry[text() = 'BR']]/Tax">
        <xsl:next-match />
        <Purp>
            <Cd>
                <xsl:text>P1019</xsl:text>
            </Cd>
        </Purp>
    </xsl:template>
</xsl:stylesheet>


问:
Using the apply function in combination with the shift function
I'm trying to iterate thru a dataframe. My goal would be to increase the value in the column loop when in the column rpm the previous row and the actual row aren't equal.

```<code>df = pd.DataFrame({'rpm': [5000, 5000, 10000, 10000, 15000, 15000],
                    'temp': [23, 23, 24, 23, 24, 25]})
df['loop'] = 0

def loop_no(x,y):
    if x.rpm != y.rpm:
        val = y.loop + 1
    else:
        val = x.loop
    return val

df['loop'] = df.apply(lambda x: loop_no(x, x.shift(-1)))
</code>```

At this point, I get this error:

```<code>AttributeError: ("'Series' object has no attribute 'rpm'", u'occurred at index rpm').
</code>```

When I use axis=1, I don't get an error. But obviously it shifts then in column direction. So, I don't get the previous line.

```<code>df['loop'] = df.apply(lambda x: loop_no(x, x.shift(-1)), axis=1)
</code>```

Body:
I'm trying to iterate thru a dataframe. My goal would be to increase the value in the column loop when in the column rpm the previous row and the actual row aren't equal.

df = pd.DataFrame({'rpm': [5000, 5000, 10000, 10000, 15000, 15000],
                    'temp': [23, 23, 24, 23, 24, 25]})
df['loop'] = 0

def loop_no(x,y):
    if x.rpm != y.rpm:
        val = y.loop + 1
    else:
        val = x.loop
    return val

df['loop'] = df.apply(lambda x: loop_no(x, x.shift(-1)))

At this point, I get this error:

AttributeError: ("'Series' object has no attribute 'rpm'", u'occurred at index rpm').

When I use axis=1, I don't get an error. But obviously it shifts then in column direction. So, I don't get the previous line.

df['loop'] = df.apply(lambda x: loop_no(x, x.shift(-1)), axis=1)

Body:
IIUC

(df.rpm!=df.rpm.shift(-1)).cumsum()
Out[796]:
0    0
1    1
2    1
3    2
4    2
5    3
Name: rpm, dtype: int32

More info

df['loop']=(df.rpm!=df.rpm.shift(-1)).cumsum()
df
Out[799]:
     rpm  temp  loop
0   5000    23     0
1   5000    23     1
2  10000    24     1
3  10000    23     2
4  15000    24     2
5  15000    25     3


问:
Parallel overlap with OMP and back updating arrays in Fortran?
The below is a slightly altered code snippet I am working on for my project and I am having a strange parallel problem with the test1,2,3 routines in which the numbers are sometimes wrong:

```<code>  integer, parameter :: N=6
  integer, parameter :: chunk_size=3
  integer, dimension(1:N) :: a,b,c

contains

  subroutine array_setup
    implicit none
    integer :: i

    do i=1,N
       a(i)=2*i
       b(i)=i*i
       c(i)=i*i-i+2
    end do

    return
  end subroutine array_setup

  subroutine test1
    implicit none
    integer :: i

    !$OMP parallel do private(i) shared(a,b,c) schedule(static,chunk_size)
    do i=2,N
       a(i-1)=b(i)
       c(i)=a(i)
    end do
    !$OMP end parallel do

    return
  end subroutine test1

  subroutine test2
    implicit none
    integer :: i

    !$OMP parallel do private(i) shared(a,b,c) schedule(static,chunk_size)
    do i=2,N
       a(i-1)=b(i)
       a(i)=c(i)
    end do
    !$OMP end parallel do

    return
  end subroutine test2

  subroutine test3
    implicit none
    integer :: i

    !$OMP parallel do private(i) shared(a,b,c) schedule(static,chunk_size)
    do i=2,N
       b(i)=a(i-1)
       a(i)=c(i)
    end do
    !$OMP end parallel do

    return
  end subroutine test3

end program vectorize_test
</code>```

Below is a sample of the output when OMP_NUM_THREADS=1 which is correct:

```<code> after setup
           1           2           1           2
           2           4           4           4
           3           6           9           8
           4           8          16          14
           5          10          25          22
           6          12          36          32
 after test1
           1           4           1           2
           2           9           4           4
           3          16           9           6
           4          25          16           8
           5          36          25          10
           6          12          36          12
 after test2
           1           4           1           2
           2           9           4           4
           3          16           9           8
           4          25          16          14
           5          36          25          22
           6          32          36          32
 after test3
           1           2           1           2
           2           4           2           4
           3           8           4           8
           4          14           8          14
           5          22          14          22
           6          32          22          32
</code>```

However, when I increase the thread count to above 1, I get strange numbers changing in each of the columns making the output incorrect, where am I going wrong with this, and what can I do to fix it?

答:
When you do

```<code>!$OMP parallel do private(i) shared(a,b,c) schedule(static,chunk_size)
do i=2,N
   a(i-1)=b(i)
   c(i)=a(i)
end do
!$OMP end parallel do
</code>```

you can have one thread reading value of a(i) which wasn't computed yet because it is scheduled for some other thread. The loop iterations are dependent on the previous one. You can't parallelize it it this way. You can also have one thread reading the same a(i) location which some other thread is just writing. That is also an error (race condition).

In loop

```<code>!$OMP parallel do private(i) shared(a,b,c) schedule(static,chunk_size)
do i=2,N
   a(i-1)=b(i)
   a(i)=c(i)
end do
!$OMP end parallel do
</code>```

the iterations are also not independent. Note that most of the locattions of a(i) will get overwritten in the next iteration. Again two threads may clash in the order these two operations should be done. Yiu can safely rewrite this as

```<code>a(1) = b(2)
!$OMP parallel do private(i) shared(a,b,c) schedule(static,chunk_size)
do i=2,N
   a(i)=c(i)
end do
!$OMP end parallel do
</code>```

The third loop

```<code>!$OMP parallel do private(i) shared(a,b,c) schedule(static,chunk_size)
do i=2,N
   b(i)=a(i-1)
   a(i)=c(i)
end do
!$OMP end parallel do
</code>```

has the same problem as the first loop. Each iteration depends on the previous iteration's value. This cannot be easily parallelized. You must find a way how to rewrite the algorithm so that the iterations do not depend on each other.

Note that there is no nead for the return in each subroutine. You also don't need implicit none in each subroutine if you have it in the parent scope.

Body:
The below is a slightly altered code snippet I am working on for my project and I am having a strange parallel problem with the test1,2,3 routines in which the numbers are sometimes wrong:

  integer, parameter :: N=6
  integer, parameter :: chunk_size=3
  integer, dimension(1:N) :: a,b,c

contains

  subroutine array_setup
    implicit none
    integer :: i

    do i=1,N
       a(i)=2*i
       b(i)=i*i
       c(i)=i*i-i+2
    end do

    return
  end subroutine array_setup

  subroutine test1
    implicit none
    integer :: i

    !$OMP parallel do private(i) shared(a,b,c) schedule(static,chunk_size)
    do i=2,N
       a(i-1)=b(i)
       c(i)=a(i)
    end do
    !$OMP end parallel do

    return
  end subroutine test1

  subroutine test2
    implicit none
    integer :: i

    !$OMP parallel do private(i) shared(a,b,c) schedule(static,chunk_size)
    do i=2,N
       a(i-1)=b(i)
       a(i)=c(i)
    end do
    !$OMP end parallel do

    return
  end subroutine test2

  subroutine test3
    implicit none
    integer :: i

    !$OMP parallel do private(i) shared(a,b,c) schedule(static,chunk_size)
    do i=2,N
       b(i)=a(i-1)
       a(i)=c(i)
    end do
    !$OMP end parallel do

    return
  end subroutine test3

end program vectorize_test

Below is a sample of the output when OMP_NUM_THREADS=1 which is correct:

 after setup
           1           2           1           2
           2           4           4           4
           3           6           9           8
           4           8          16          14
           5          10          25          22
           6          12          36          32
 after test1
           1           4           1           2
           2           9           4           4
           3          16           9           6
           4          25          16           8
           5          36          25          10
           6          12          36          12
 after test2
           1           4           1           2
           2           9           4           4
           3          16           9           8
           4          25          16          14
           5          36          25          22
           6          32          36          32
 after test3
           1           2           1           2
           2           4           2           4
           3           8           4           8
           4          14           8          14
           5          22          14          22
           6          32          22          32

However, when I increase the thread count to above 1, I get strange numbers changing in each of the columns making the output incorrect, where am I going wrong with this, and what can I do to fix it?

Body:
When you do

!$OMP parallel do private(i) shared(a,b,c) schedule(static,chunk_size)
do i=2,N
   a(i-1)=b(i)
   c(i)=a(i)
end do
!$OMP end parallel do

you can have one thread reading value of a(i) which wasn't computed yet because it is scheduled for some other thread. The loop iterations are dependent on the previous one. You can't parallelize it it this way. You can also have one thread reading the same a(i) location which some other thread is just writing. That is also an error (race condition).

In loop

!$OMP parallel do private(i) shared(a,b,c) schedule(static,chunk_size)
do i=2,N
   a(i-1)=b(i)
   a(i)=c(i)
end do
!$OMP end parallel do

the iterations are also not independent. Note that most of the locattions of a(i) will get overwritten in the next iteration. Again two threads may clash in the order these two operations should be done. Yiu can safely rewrite this as

a(1) = b(2)
!$OMP parallel do private(i) shared(a,b,c) schedule(static,chunk_size)
do i=2,N
   a(i)=c(i)
end do
!$OMP end parallel do

The third loop

!$OMP parallel do private(i) shared(a,b,c) schedule(static,chunk_size)
do i=2,N
   b(i)=a(i-1)
   a(i)=c(i)
end do
!$OMP end parallel do

has the same problem as the first loop. Each iteration depends on the previous iteration's value. This cannot be easily parallelized. You must find a way how to rewrite the algorithm so that the iterations do not depend on each other.

Note that there is no nead for the return in each subroutine. You also don't need implicit none in each subroutine if you have it in the parent scope.


问:
Testing methods that eventually throw an exception in RSpec
I've got a method as follows:

```<code> if response.fetch('ok')
    response.fetch(response_key) { [] }
  elsif response.fetch('error') == 'token_revoked'
    ErrorReporter.increment('access_revoked', source: { account_id: account_id }, sporadic: true)
    fail(RemoteService::AccessRevoked, 'Our access to your account was revoked, please re-authorize.')
  else
    ErrorReporter.increment(
      'bad_request',
      source: {
        account_id: account_id
        error: response.fetch('error')
      },
      sporadic: true
    )
    fail(RemoteService::InvalidRequest, 'Something went wrong communicating with the remote service, please try again')
  end
</code>```

And I'm trying to test the scenario when the request returns with the token_revoked error.  I'd like to ensure the test specifies that in this scenario, that we report the error to our ErrorReporting service.

So, my spec looks like this:

```<code>it 'records the failure with our error reporting service' do
  expect(ErrorReporter).to receive(:increment).with(
    'bad_request',
     source: {
       account_id:  1
     },
     sporadic: true
   )

   available_channels.fetch
end
</code>```

However, this spec always fails, because after the call is made to the ErrorReporter, the code immediately calls fail which makes my spec fail.  Does anyone have any idea how I can verify that the call to my error reporter is made while handling the inevitable exception that I know the code is now going to throw?

答:
You can expect errors to be raised in code. In order for the exception to be caught by RSpec, you need to use a block as follows:</p>

```<code>it 'records the failure with our error reporting service' do
  expect(ErrorReporter).to receive(:increment).with(
    'bad_request',
    source: {
      account_id:  1
    },
    sporadic: true
  )

  expect { available_channels.fetch }
    .to raise_error RemoteService::InvalidRequest
end
</code>```

Body:
I've got a method as follows:

 if response.fetch('ok')
    response.fetch(response_key) { [] }
  elsif response.fetch('error') == 'token_revoked'
    ErrorReporter.increment('access_revoked', source: { account_id: account_id }, sporadic: true)
    fail(RemoteService::AccessRevoked, 'Our access to your account was revoked, please re-authorize.')
  else
    ErrorReporter.increment(
      'bad_request',
      source: {
        account_id: account_id
        error: response.fetch('error')
      },
      sporadic: true
    )
    fail(RemoteService::InvalidRequest, 'Something went wrong communicating with the remote service, please try again')
  end

And I'm trying to test the scenario when the request returns with the token_revoked error.  I'd like to ensure the test specifies that in this scenario, that we report the error to our ErrorReporting service.

So, my spec looks like this:

it 'records the failure with our error reporting service' do
  expect(ErrorReporter).to receive(:increment).with(
    'bad_request',
     source: {
       account_id:  1
     },
     sporadic: true
   )

   available_channels.fetch
end

However, this spec always fails, because after the call is made to the ErrorReporter, the code immediately calls fail which makes my spec fail.  Does anyone have any idea how I can verify that the call to my error reporter is made while handling the inevitable exception that I know the code is now going to throw?

Body:
You can expect errors to be raised in code. In order for the exception to be caught by RSpec, you need to use a block as follows:

it 'records the failure with our error reporting service' do
  expect(ErrorReporter).to receive(:increment).with(
    'bad_request',
    source: {
      account_id:  1
    },
    sporadic: true
  )

  expect { available_channels.fetch }
    .to raise_error RemoteService::InvalidRequest
end


问:
Unable to add more than one function to Test Class in Laravel
I am developing a Web Application using Laravel. I would like to Unit Test some logic. So I created a Unit Test class like below.

```<code>class AcceptationTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testCountUpWhenDifferenceIsOverOneWeek()
    {
        $acceptationRepo = new AcceptationRepo;
        //must count up on 5/12/2017
        $need_count_up = $acceptationRepo->shouldCountUpTwoDWeek("11-28-2017");
        $this->assertTrue($need_count_up);
    }

}
</code>```

I run the Unit Test from Terminal and it is working. Then I added another test function. So my test class will look like this.

```<code>class AcceptationTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testCountUpWhenDifferenceIsOverOneWeek()
    {
        $acceptationRepo = new AcceptationRepo;
        //must count up on 5/12/2017
        $need_count_up = $acceptationRepo->shouldCountUpTwoDWeek("11-28-2017");
        $this->assertTrue($need_count_up);
    }

    public function testNotCountUpIfDifferenceIsExactlySeven(){
        $acceptationRepo = new AcceptationRepo;
        //must count up on 5/12/2017
        $need_count_up = $acceptationRepo->shouldCountUpTwoDWeek("11-29-2017");
        $this->assertTrue(!$need_count_up);

    }
}
</code>```

When I run the test from the Terminal, it is showing this error.

I checked my second function carefully and there is no error. To make sure I removed the first function and run the second function alone. So my test class will look like this.

```<code>class AcceptationTest extends TestCase
{

    public function testNotCountUpIfDifferenceIsExactlySeven(){
        $acceptationRepo = new AcceptationRepo;
        //must count up on 5/12/2017
        $need_count_up = $acceptationRepo->shouldCountUpTwoDWeek("11-29-2017");
        $this->assertTrue(!$need_count_up);

    }
}
</code>```

As you can see there is only one function in the test class and that is the newly added function. I run the test from the terminal again and now it is working without throwing any error. I found out the problem is adding more than one functions. But I need to do it. I read the error message from the terminal and it is not dealing with the Unit Test at all.

I tried adding these two properties

```<code>protected $preserveGlobalState = FALSE;
protected $runTestInSeparateProcess = TRUE;
</code>```

When I run, it is giving me this error

答:
One option would be to remove constants from your code.  You should be able to reference env variables or config variables in most places where you are using constants.

Other option is to use these flags to ensure each test gets it's own process:

```<code>class AcceptationTest extends TestCase
{

  protected $preserveGlobalState = FALSE;
  protected $runTestInSeparateProcess = TRUE;
</code>```

Finally, you could add a test to wherever you're defining your constant

```<code>if (!defined('SITE_NAME')) define('SITE_NAME', 'foobar');
</code>```

Body:
I am developing a Web Application using Laravel. I would like to Unit Test some logic. So I created a Unit Test class like below.

class AcceptationTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testCountUpWhenDifferenceIsOverOneWeek()
    {
        $acceptationRepo = new AcceptationRepo;
        //must count up on 5/12/2017
        $need_count_up = $acceptationRepo->shouldCountUpTwoDWeek("11-28-2017");
        $this->assertTrue($need_count_up);
    }

}

I run the Unit Test from Terminal and it is working. Then I added another test function. So my test class will look like this.

class AcceptationTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testCountUpWhenDifferenceIsOverOneWeek()
    {
        $acceptationRepo = new AcceptationRepo;
        //must count up on 5/12/2017
        $need_count_up = $acceptationRepo->shouldCountUpTwoDWeek("11-28-2017");
        $this->assertTrue($need_count_up);
    }

    public function testNotCountUpIfDifferenceIsExactlySeven(){
        $acceptationRepo = new AcceptationRepo;
        //must count up on 5/12/2017
        $need_count_up = $acceptationRepo->shouldCountUpTwoDWeek("11-29-2017");
        $this->assertTrue(!$need_count_up);

    }
}

When I run the test from the Terminal, it is showing this error.

I checked my second function carefully and there is no error. To make sure I removed the first function and run the second function alone. So my test class will look like this.

class AcceptationTest extends TestCase
{

    public function testNotCountUpIfDifferenceIsExactlySeven(){
        $acceptationRepo = new AcceptationRepo;
        //must count up on 5/12/2017
        $need_count_up = $acceptationRepo->shouldCountUpTwoDWeek("11-29-2017");
        $this->assertTrue(!$need_count_up);

    }
}

As you can see there is only one function in the test class and that is the newly added function. I run the test from the terminal again and now it is working without throwing any error. I found out the problem is adding more than one functions. But I need to do it. I read the error message from the terminal and it is not dealing with the Unit Test at all.

I tried adding these two properties

protected $preserveGlobalState = FALSE;
protected $runTestInSeparateProcess = TRUE;

When I run, it is giving me this error

Body:
One option would be to remove constants from your code.  You should be able to reference env variables or config variables in most places where you are using constants.

Other option is to use these flags to ensure each test gets it's own process:

class AcceptationTest extends TestCase
{

  protected $preserveGlobalState = FALSE;
  protected $runTestInSeparateProcess = TRUE;

Finally, you could add a test to wherever you're defining your constant

if (!defined('SITE_NAME')) define('SITE_NAME', 'foobar');


问:
PiCamera pictures inconsistent
I am working with a Raspberry pi with a camera module (Raspberry pi Camera) mounted on a drone and programmed to take pictures after a fixed interval. However, the images seem to be a bit inconsistent as seen below .

Images 4 and 8 appear to have slightly more 'colored' as compared to other images and appear to have more saturation. However, as the default saturation is 0 and my code is not changing that, I believe it is something else. My python script is as below

```<code>def calibrate(t):
    with picamera.PiCamera() as camera:
       time.sleep(t)
       camera.shutter_speed = camera.exposure_speed
       ss=camera.shutter_speed
       camera.still_stats = 'true'
       camera.exposure_mode = 'off'
       g = camera.awb_gains
       camera.awb_mode = 'off'
       camera.awb_gains = g
       camera.close()
       return ss,g

def capture(ss,g,stream):
    with picamera.PiCamera() as camera:
       camera.resolution = (3280,2464)
       camera.shutter_speed = ss
       camera.still_stats
       camera.exposure_mode = 'off'
       camera.awb_mode = 'off'
       camera.awb_gains = g
       camera.still_stats = 'true'
       camera.capture(stream,format='jpeg')
       camera.close()
</code>```

I call the calibrate function before taking any pictures that calibrate the camera. After calibrating, I take the pictures and get this problem. Does anyone know how to solve this?

答:
From the docs:

Enabling the still statistics pass will override fixed white balance
  gains (set via awb_gains and awb_mode).

I would bet that awb_mode gets set back to something other than off when you change still_stats. Exact same problem seems to be reported here.

Title: PiCamera pictures inconsistent

Body:
I am working with a Raspberry pi with a camera module (Raspberry pi Camera) mounted on a drone and programmed to take pictures after a fixed interval. However, the images seem to be a bit inconsistent as seen below .

Images 4 and 8 appear to have slightly more 'colored' as compared to other images and appear to have more saturation. However, as the default saturation is 0 and my code is not changing that, I believe it is something else. My python script is as below

def calibrate(t):
    with picamera.PiCamera() as camera:
       time.sleep(t)
       camera.shutter_speed = camera.exposure_speed
       ss=camera.shutter_speed
       camera.still_stats = 'true'
       camera.exposure_mode = 'off'
       g = camera.awb_gains
       camera.awb_mode = 'off'
       camera.awb_gains = g
       camera.close()
       return ss,g

def capture(ss,g,stream):
    with picamera.PiCamera() as camera:
       camera.resolution = (3280,2464)
       camera.shutter_speed = ss
       camera.still_stats
       camera.exposure_mode = 'off'
       camera.awb_mode = 'off'
       camera.awb_gains = g
       camera.still_stats = 'true'
       camera.capture(stream,format='jpeg')
       camera.close()

I call the calibrate function before taking any pictures that calibrate the camera. After calibrating, I take the pictures and get this problem. Does anyone know how to solve this?