问:
rsync: difference between --size-only and --ignore-times
I'm trying to understand what the difference is between two options

```<code>rsync --size-only
</code>```

and

```<code>rsync --ignore-times
</code>```

It is my understanding that by default rsync will compare both the timestamps and the file sizes in order to decide whether or not a file should be synchronized or not. The options above allow the user to influence this behavior.

Both options seem, at least verbally to result in the same thing: comparing by size only.

Am I missing something subtle here?

答:
The short answer is that --ignore-times does more than its name implies. It ignores both the time and size.
In contrast, --size-only does exactly what it says.

The long answer is that rsync has three ways to decide if a file is outdated:

Compare the size of source and destination.

Compare the timestamp of source and destination.

Compare the static checksum of source and destination.

These checks are performed before transferring data. Notably, this means the static checksum is distinct from the stream checksum - the later is computed while transferring data.

By default, rsync uses only 1 and 2. Both 1 and 2 can be acquired together by a single stat, whereas 3 requires reading the entire file (this is independent from reading the file for transfer). Assuming only one modifier is specified, that means the following:

By using --size-only, only 1 is performed - timestamps and checksum are ignored. A file is copied unless its size is identical on both ends.

By using --ignore-times, neither of 1, 2 or 3 is performed. A file is always copied.

By using --checksum, 3 is used in addition to 1, but 2 is not performed. A file is copied unless size and checksum match. The checksum is only computed if size matches.

Body:
I'm trying to understand what the difference is between two options

rsync --size-only

and

rsync --ignore-times

It is my understanding that by default rsync will compare both the timestamps and the file sizes in order to decide whether or not a file should be synchronized or not. The options above allow the user to influence this behavior.

Both options seem, at least verbally to result in the same thing: comparing by size only.

Am I missing something subtle here?


来源: stackexchange

问:
Is it possible to have multiple strings in one position of an array?
For example if my array is

```<code>var cars = ["Saab", "Volvo", "BMW"];
var answer = cars[1];
</code>```

and I create a function where if I type 'Volvo' it says 'Correct'. Is it possible to do something like this:

```<code>var cars = ["Saab", "Volvo|volkswagen", "BMW"];
</code>```

So when I type what is at position 1, I can type Volvo or volkswagen and it will say 'correct'? (But not both)

答:
You define a multi dimensional array.</p>

```<code>var cars = [["Saab"], ["Volvo", "volkswagen"], ["BMW"]];
if(cars[1].includes(val)){

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
For example if my array is

var cars = ["Saab", "Volvo", "BMW"];
var answer = cars[1];

and I create a function where if I type 'Volvo' it says 'Correct'. Is it possible to do something like this:

var cars = ["Saab", "Volvo|volkswagen", "BMW"];

So when I type what is at position 1, I can type Volvo or volkswagen and it will say 'correct'? (But not both)

Body:
You define a multi dimensional array.

var cars = [["Saab"], ["Volvo", "volkswagen"], ["BMW"]];
if(cars[1].includes(val)){

}


问:
Save List<Object> to instance state with Parcelable
I have the following models:

GitItem:

```<code>    public class GitItem implements Serializable, Parcelable {
        public int id;
        public String name;
        public String full_name;
        public GitOwner owner;

        public GitItem() {
        }

        public GitItem(Parcel in) {
            id = in.readInt();
            name = in.readString();
            full_name = in.readString();
        }

        public int describeContents() {
            return 0;
        }

        public void writeToParcel(Parcel out, int flags){
            out.writeInt(id);
            out.writeString(name);
            out.writeString(full_name);
        }

        public static final Parcelable.Creator<GitItem> CREATOR = new Parcelable.Creator<GitItem>(){

            @Override
            public GitItem createFromParcel(Parcel source) {
                return new GitItem(source);
            }

            @Override
            public GitItem[] newArray(int size) {
                return new GitItem[size];
            }
        };
    }
</code>```

and GitOwner:

```<code>public class GitOwner implements Serializable, Parcelable {
    public String avatar_url;

    public GitOwner(Parcel in) {
        avatar_url = in.readString();
    }

    public GitOwner() {
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {

    }

    public static final Parcelable.Creator<GitOwner> CREATOR = new Parcelable.Creator<GitOwner>(){

        @Override
        public GitOwner createFromParcel(Parcel source) {
            return  new GitOwner(source);
        }

        @Override
        public GitOwner[] newArray(int size) {
            return new GitOwner[size];
        }
    };
}
</code>```

and then in MainActivity.java I have a List<GitItem> data; which is bound to my RecyclerView.

Basically what I am trying to achieve, is to store current state of my List<GitItem> when I change Activity or simply rotate device. Unfortunately, even though I have implemented Parcelable (as suggested by other posts), I was unable to store the instance.

Any help in this matter would be highly appreciated.

答:
You have not implemented the complete body of Parcelable functions i.e writeToParcel in GitOwner and GitItem class

In GitOwner class

```<code>@Override
public void writeToParcel(Parcel dest, int flags) {
     dest.writeString(avatar_url);
     // add this line
}
</code>```

and inside GitItem use writeParcelable to write and readParcelable to read GitItem object otherwise it won't be persisted and restored

```<code>    public GitItem(Parcel in) {
        id = in.readInt();
        name = in.readString();
        full_name = in.readString();
        owner = in.readParcelable(GitItem.class.getClassLoader());
        // Add line to read owner object
    }

    public void writeToParcel(Parcel out, int flags){
        out.writeInt(id);
        out.writeString(name);
        out.writeString(full_name);
        out.writeParcelable(owner , flags);
        // Add line to write owner object
    }
</code>```

Body:
I have the following models:

GitItem:

    public class GitItem implements Serializable, Parcelable {
        public int id;
        public String name;
        public String full_name;
        public GitOwner owner;

        public GitItem() {
        }

        public GitItem(Parcel in) {
            id = in.readInt();
            name = in.readString();
            full_name = in.readString();
        }

        public int describeContents() {
            return 0;
        }

        public void writeToParcel(Parcel out, int flags){
            out.writeInt(id);
            out.writeString(name);
            out.writeString(full_name);
        }

        public static final Parcelable.Creator<GitItem> CREATOR = new Parcelable.Creator<GitItem>(){

            @Override
            public GitItem createFromParcel(Parcel source) {
                return new GitItem(source);
            }

            @Override
            public GitItem[] newArray(int size) {
                return new GitItem[size];
            }
        };
    }

and GitOwner:

public class GitOwner implements Serializable, Parcelable {
    public String avatar_url;

    public GitOwner(Parcel in) {
        avatar_url = in.readString();
    }

    public GitOwner() {
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {

    }

    public static final Parcelable.Creator<GitOwner> CREATOR = new Parcelable.Creator<GitOwner>(){

        @Override
        public GitOwner createFromParcel(Parcel source) {
            return  new GitOwner(source);
        }

        @Override
        public GitOwner[] newArray(int size) {
            return new GitOwner[size];
        }
    };
}

and then in MainActivity.java I have a List<GitItem> data; which is bound to my RecyclerView.

Basically what I am trying to achieve, is to store current state of my List<GitItem> when I change Activity or simply rotate device. Unfortunately, even though I have implemented Parcelable (as suggested by other posts), I was unable to store the instance.

Any help in this matter would be highly appreciated.

Body:
You have not implemented the complete body of Parcelable functions i.e writeToParcel in GitOwner and GitItem class

In GitOwner class

@Override
public void writeToParcel(Parcel dest, int flags) {
     dest.writeString(avatar_url);
     // add this line
}

and inside GitItem use writeParcelable to write and readParcelable to read GitItem object otherwise it won't be persisted and restored

    public GitItem(Parcel in) {
        id = in.readInt();
        name = in.readString();
        full_name = in.readString();
        owner = in.readParcelable(GitItem.class.getClassLoader());
        // Add line to read owner object
    }

    public void writeToParcel(Parcel out, int flags){
        out.writeInt(id);
        out.writeString(name);
        out.writeString(full_name);
        out.writeParcelable(owner , flags);
        // Add line to write owner object
    }


问:
Insert Authorization Header field with kingfisher lib
I'm using Kingfisher to show image from url, but my endpoint requires a Authorization header.
How to use these kind of url with Kingfisher or SDWebImage in iOS?</p>

答:
With Kingfisher you need to make a request modifier (of type AnyModifier) and pass it as a parameter in the options part of the .kf.setImage method, and then use the trailing closure to actually set the image.

Example:

```<code>import Kingfisher

let modifier = AnyModifier { request in
    var r = request
    // replace "Access-Token" with the field name you need, it's just an example
    r.setValue(<YOUR_TOKEN>, forHTTPHeaderField: "Access-Token")
    return r
}

let url = URL(string: <YOUR_URL>)

let iView = <YOUR_IMAGEVIEW>

iView.kf.setImage(with: url, options: [.requestModifier(modifier)]) { (image, error, type, url) in
    if error == nil && image != nil {
        // here the downloaded image is cached, now you need to set it to the imageView
        DispatchQueue.main.async {
            iView.image = image
        }
    } else {
        // handle the failure
        print(error)
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
With Kingfisher you need to make a request modifier (of type AnyModifier) and pass it as a parameter in the options part of the .kf.setImage method, and then use the trailing closure to actually set the image.

Example:

import Kingfisher

let modifier = AnyModifier { request in
    var r = request
    // replace "Access-Token" with the field name you need, it's just an example
    r.setValue(<YOUR_TOKEN>, forHTTPHeaderField: "Access-Token")
    return r
}

let url = URL(string: <YOUR_URL>)

let iView = <YOUR_IMAGEVIEW>

iView.kf.setImage(with: url, options: [.requestModifier(modifier)]) { (image, error, type, url) in
    if error == nil && image != nil {
        // here the downloaded image is cached, now you need to set it to the imageView
        DispatchQueue.main.async {
            iView.image = image
        }
    } else {
        // handle the failure
        print(error)
    }
}


问:
Current user object in class without create Service
After login, I want current user object in my class without creating service. Becauase I had already create current user pluggin and helper.

So If i need current user object in my class then How to get current user object.

i.e,

```<code>class CoreFunction
{
    public static curentUserData()
    {
       // i want user object here
    }

}
</code>```

In Zend Framework 2, I just used:

```<code>class CoreFunction
{
    public static curentUserData() {
        $authService = $this->getServiceLocator()
                    ->get('Zend\Authentication\AuthenticationService')
                    ->getIdentity();
    }
}
</code>```

How can I do this in Zend Framework 3?

答:
As in ZF2, you should have access to controller plugin identity and use it like $this->identity()

```<code>// From the doc.
public function testAction()
{
    if ($user = $this->identity()) {
         // someone is logged !
    } else {
         // not logged in
    }
}
</code>```

If you want to use it in other class than controller, than you need to inject it, as in ZF2.

Body:
After login, I want current user object in my class without creating service. Becauase I had already create current user pluggin and helper.

So If i need current user object in my class then How to get current user object.

i.e,

class CoreFunction
{
    public static curentUserData()
    {
       // i want user object here
    }

}

In Zend Framework 2, I just used:

class CoreFunction
{
    public static curentUserData() {
        $authService = $this->getServiceLocator()
                    ->get('Zend\Authentication\AuthenticationService')
                    ->getIdentity();
    }
}

How can I do this in Zend Framework 3?

Body:
As in ZF2, you should have access to controller plugin identity and use it like $this->identity()

// From the doc.
public function testAction()
{
    if ($user = $this->identity()) {
         // someone is logged !
    } else {
         // not logged in
    }
}

If you want to use it in other class than controller, than you need to inject it, as in ZF2.


答:
You could use an object instead of an array for fast lookup (which includes and indexOf do not do):

```<code>var cars = {
    "Saab": 0,
    "Volvo": 1,
    "volkswagen": 1,
    "BMW": 2
};
</code>```

Your check would run in constant time:

```<code>if (cars[answer] === 1) // ...
</code>```

Title: Is it possible to have multiple strings in one position of an array?

Body:
You could use an object instead of an array for fast lookup (which includes and indexOf do not do):

var cars = {
    "Saab": 0,
    "Volvo": 1,
    "volkswagen": 1,
    "BMW": 2
};

Your check would run in constant time:

if (cars[answer] === 1) // ...


问:
Repeat animation with new animated api
React-native introduce new Animated API, I want to make a loop animation such as a bubble scale up then scale down and repeat that progress.

However I can not figure it out. I've tried write some code like below

```<code>class TestProject extends React.Component {

  constructor(): void {
    super();
    this.state = {
      bounceValue: new Animated.Value(0),
      v: 1,
    };
  }

  componentDidMount() {
    this.state.bounceValue.setValue(1.5);

    let animation = Animated.timing(this.state.bounceValue, {
      toValue: this.state.v,
    });

    setInterval(() => {
      animation.stop();

      if (this.state.flag) {
        this.state.v = 0.5;
        this.state.bounceValue.setValue(0.5);
      }
      else {
        this.state.v = 1.5;
        this.state.bounceValue.setValue(1.5);
      }

      animation.start();
    }, 5000);

  }

  render(): ReactElement {
    return (
      <View style={styles.imageContainer}>
        <Image
          style={styles.image}
          source={{uri: 'http://image142-c.poco.cn/best_pocoers/20130517/91062013051716553599334223.jpg'}}
        />
        <Animated.Text
          style={[
            styles.test,
            {transform: [
              {scale: this.state.bounceValue},
            ],}
          ]
          }>
          haha
        </Animated.Text>
      </View>
    );
  }

}
</code>```

but not works very well.

Any suggestion will be appreciate.

答:
There's now loop animation available:

Animated.loop(
  Animated.sequence([
    Animated.timing(this.state.animatedStartValue, {
      toValue: 1,
      duration: 500,
      delay: 1000
    }),
    Animated.timing(this.state.animatedStartValue, {
      toValue: 0,
      duration: 500
    })
  ]),
  {
    iterations: 4
  }
).start()
```

Title: Repeat animation with new animated api

Body:
React-native introduce new Animated API, I want to make a loop animation such as a bubble scale up then scale down and repeat that progress.

However I can not figure it out. I've tried write some code like below

class TestProject extends React.Component {

  constructor(): void {
    super();
    this.state = {
      bounceValue: new Animated.Value(0),
      v: 1,
    };
  }

  componentDidMount() {
    this.state.bounceValue.setValue(1.5);

    let animation = Animated.timing(this.state.bounceValue, {
      toValue: this.state.v,
    });

    setInterval(() => {
      animation.stop();

      if (this.state.flag) {
        this.state.v = 0.5;
        this.state.bounceValue.setValue(0.5);
      }
      else {
        this.state.v = 1.5;
        this.state.bounceValue.setValue(1.5);
      }

      animation.start();
    }, 5000);

  }

  render(): ReactElement {
    return (
      <View style={styles.imageContainer}>
        <Image
          style={styles.image}
          source={{uri: 'http://image142-c.poco.cn/best_pocoers/20130517/91062013051716553599334223.jpg'}}
        />
        <Animated.Text
          style={[
            styles.test,
            {transform: [
              {scale: this.state.bounceValue},
            ],}
          ]
          }>
          haha
        </Animated.Text>
      </View>
    );
  }

}

but not works very well.

Any suggestion will be appreciate.


问:
What I found so far the blinking text isnt working
I would like to have blinking email link and also the line that says Hello Professor. What i have found so far hasnt worked. Any help would be great. This is what I have tried so far text-decoration:blink; with no luck</p>

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>Randy's first html web page !</title>
<style type="text/css">
body
{background-image:url('Koala.gif');}
h1
{
text-align:center;
font-size:500%;
}
h2
{
text-align:center;
font-size:250%;
}
p
{
text-align:center;
font-size:200%;
color:#00fff0;
}
div
{
background-color:#efffff;
}
a
{
text-align:center;
}
th
{
background-color:green;
}
tr
{
background-color:green;
}
table
{
width: 200px;
margin-left: auto;
margin-right: auto;
}
#google-link
{
margin: 0 auto;
display: block;
font-size:250%;
color:#00ff00;
}
#Mail-link
{
margin: 0 auto;
display: block;
font-size:250%;
color:#00ff00;
text-decoration:blink;
}
</style>
</head>
<h1> Hello Professor</h1>
<h2> By: Randy White</h2>
<P> It's getting better as the term goes on.</P>
<P>Week 2</P>
<P><img src="Hydrangeas.jpg" width="150" height="100" alt="Hydrangeas.jpg"></P>
<table border="1">
<tr>
<th>Month</th>
<th>Day</th>
<th>Year</th>
</tr>
<tr>
<td>December</td>
<td>13</td>
<td>2010</td>
</tr>
</table>
<a id="google-link" href="http://www.google.com">Visit Google!</a>
<a id="Mail-link" href="mailto:randywhite30@neb.rr.com"> Contact Me!</a>
</body>
</html>
</code>```

答:
I think you may be looking for the <annoy-the-crap-out-of-the-user> tag :-)

But, seriously, if a browser doesn't support it, you have a couple of options.

The first is the relatively easy, don't support that browser. And, though easy, it may not be feasible.

The second is just as easy, don't use blinking text - that would be my preference but I'm going to assume you have a real need for it. However, you should take everyone's advice and at least look into a different way of doing this.

The third is with Javascript (I'd go jQuery myself) where you can set up timers to blink the text yourself. Not pretty but sometimes kludges are necessary.

ContentLicense: CC BY-SA 2.5

Body:
I would like to have blinking email link and also the line that says Hello Professor. What i have found so far hasnt worked. Any help would be great. This is what I have tried so far text-decoration:blink; with no luck

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">

<title>Randy's first html web page !</title>

 Hello Professor

 By: Randy White

 It's getting better as the term goes on.

Week 2

Month
Day
Year

December
13
2010

Visit Google!
 Contact Me!


答:
You could create an hash object:

var cars = ["Saab", "Volvo|volkswagen", "BMW"];

cars=cars.reduce(function(obj,el,i){
    obj[i]=el.split("|");
    return obj;
},{});

console.log("cars is",cars);

var guess=prompt("what is at 1?");

if(cars[1].includes(guess)){
  alert("right");
}else{
    alert("wrong");
}```
</div>
</div>
</p>

<p>So now cars is like:</p>

```cars[1]===["Volvo","volkswagen"];
```

So you can check if this Array has "volkswagen in it...

Body:
You could create an hash object:

var cars = ["Saab", "Volvo|volkswagen", "BMW"];

cars=cars.reduce(function(obj,el,i){
    obj[i]=el.split("|");
    return obj;
},{});

console.log("cars is",cars);

var guess=prompt("what is at 1?");

if(cars[1].includes(guess)){
  alert("right");
}else{
    alert("wrong");
}

So now cars is like:

cars[1]===["Volvo","volkswagen"];

So you can check if this Array has "volkswagen in it...


答:
You can have the second array inside the first one:</p>

```<code>var cars = ["Saab", ["Volvo", "Volkswagen"], "BMW"];
</code>```

Body:
You can have the second array inside the first one:

var cars = ["Saab", ["Volvo", "Volkswagen"], "BMW"];


问:
Using `std::min` as an algorithm parameter
So I ran into this problem: I need to replace every element of the std::vector<int> with the minimum of whatever came before it (inclusive).

Naturally std::partial_sum comes to mind - if I could pass std::min as the BinaryOp, it would do the job.

Well turns out I can't do that because std::min<int> is an overloaded function - it works for both int and initializer_list<int> and partial_sum template can't be instantiated with the unknown type.

Usually this is resolved by having a class with a templated operator(), like std::plus<void> etc, but standard library doesn't seem to have one for min and max.

I feel like I either have to implement my own T min<T>(T,T), which will be an exact clone of std::min with the exception of not having an initializer_list overload, or to implement my own class min akin to std::plus. Both feel kinda wrong because one would expect standard library to have such a basic thing, and also basic things are often tricky to implement:)

So here are my questions:

Is there any proper way to solve the problem in question? i.e. without introducing new vague constructs/writing more than a couple of lines of code.

Is it correct to assume that this became a problem in C++11, after initializer_list overload of min was introduced? So C++11 broke the code that relied on explicitly instantiated std::min?

Thank you!

答:
Wrap it in a lambda:</p>

```<code>std::partial_sum(v.begin(), v.end(), v.begin(), [](auto& a, auto& b) {
    return std::min(a, b);
});
</code>```

Body:
Wrap it in a lambda:

std::partial_sum(v.begin(), v.end(), v.begin(), [](auto& a, auto& b) {
    return std::min(a, b);
});


问:
What is the best rich textarea editor for jQuery?
Something like this one on the Stackoverflow site would be nice!

Or something non-jQuery that doesn't conflict with jQuery $() tags would be great.

答: Tiny MCE is the best IMHO - I have tired a ton of them and Tiny has the best over features, easy to create content templates, easy to set which CSS is shown in the editor and used to display it, very large API, great skins, ect...</p>

OwnerDisplayName: Edward Tanguay

OwnerDisplayName: Max Fraser


问:
c# easy way to create new db when new customer is added
what can be a easy way to create new db when we create new customer record?

Scenario:

I have list of customers [may be upto 500 customers] in master database

Whenever I add new customer in my application, I would like to create new separate database to each client [just to separate respective clients' data entirely from each other]

Application will connect to master database and respective client db as per login credential.

No of customers may be upto 500,

I am planning to add only 50 dbs per server instance, after that again will be adding to next server instance

Options I have selected:

Use Code first approach of ef6.0 to create and seed primary data of each client when new client is added

Use Custom "Create database script" and import seed data from custom script.sql file

答:
Copy SQL Server database in code would be a reasonable option for backing up and restoring an existing 'vanilla' (i.e. with no customer data in it) database.

Of course you only need to backup once - you just restore for each new customer.


问:
Where does each type of neural network (RNN, CNN, LSTM, etc.) excel?
For instance, I know CNN excel at analyzing images.

Where do other types excel?

答:
Not a very thorough answer, but you have to understand two things first:

FNN and RNN are network types

FNN is a feed forward neural network and RNN is a recurrent neural network. These aren't architectures themselves.

> Recurrent Neural Networks

Recurrent neural networks are generally good for data where there is a relation between previous inputs and the current input.

LSTM - great for detecting/predicting patterns that occur over long time spans

GRU - same as LSTM

Hopfield - great for remembering trained patterns, not for detecting them

NARX - great for detecting/predicting patterns over a fixed time span

> Feed Forward Neural Networks

Feed forward neural networks cannot detect relationships between previous inputs and the current input.

CNN -  Great for data with dimensionality, also great for data where the 'location' of neurons matter

MLP - A regular fully connected network, can basically map any function

Last note

Most of these 'architectures' get combined often: for example, if you want to detect emotion in a video, you will most likely need to use a combination between CNN and LSTM.


问:
Unable to access shared preference inside Service - Android
Hi I am using the GCMListener service to listen to incoming messages. I am trying to access my shared preference in the service, with the help of TinyDB.

I get the following error when trying to access the shared preference.

```<code>java.lang.RuntimeException: Unable to instantiate service com.artqueen.aahaan.GCM.MyGcmListenerService: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
            at android.app.ActivityThread.handleCreateService(ActivityThread.java:3271)
            at android.app.ActivityThread.access$1900(ActivityThread.java:182)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1558)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:6141)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
            at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:184)
            at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:369)
            at com.artqueen.aahaan.Helper.TinyDB.<init>(TinyDB.java:31)
            at com.artqueen.aahaan.GCM.MyGcmListenerService.<init>(MyGcmListenerService.java:40)
            at java.lang.reflect.Constructor.newInstance(Native Method)
            at java.lang.Class.newInstance(Class.java:1650)
            at android.app.ActivityThread.handleCreateService(ActivityThread.java:3268)
            at android.app.ActivityThread.access$1900(ActivityThread.java:182)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1558)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:6141)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
</code>```

I am using the GCMListenerService like this

```<code>public class MyGcmListenerService extends GcmListenerService {

    private static final String TAG = "MyGcmListenerService";

    TinyDB tinyDB = new TinyDB(MyGcmListenerService.this);

    @Override
    public void onMessageReceived(String from, Bundle data) {
        String message = data.getString("message");

        String user = data.getString("user","");
        Log.e("user = "," "+user);

        ArrayList<String> blockList = tinyDB.getListString("blockList");

       if(blockList.contains(user)){
           //dont show notification
       }else {
           //show notification
           sendNotification(user);
       }
    }
</code>```

And for your reference, the TinyDB class looks like this

```<code>public class TinyDB {

    private SharedPreferences preferences;
    private String DEFAULT_APP_IMAGEDATA_DIRECTORY;
    private String lastImagePath = "";

    public TinyDB(Context appContext) {
        preferences = PreferenceManager.getDefaultSharedPreferences(appContext);
    }

    /**
     * Decodes the Bitmap from 'path' and returns it
     * @param path image path
     * @return the Bitmap from 'path'
     */
    public Bitmap getImage(String path) {
        Bitmap bitmapFromPath = null;
        try {
            bitmapFromPath = BitmapFactory.decodeFile(path);

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

        return bitmapFromPath;
    }

    /**
     * Returns the String path of the last saved image
     * @return string path of the last saved image
     */
    public String getSavedImagePath() {
        return lastImagePath;
    }

    /**
     * Saves 'theBitmap' into folder 'theFolder' with the name 'theImageName'
     * @param theFolder the folder path dir you want to save it to e.g "DropBox/WorkImages"
     * @param theImageName the name you want to assign to the image file e.g "MeAtLunch.png"
     * @param theBitmap the image you want to save as a Bitmap
     * @return true if image was saved, false otherwise
     */
    public boolean putImage(String theFolder, String theImageName, Bitmap theBitmap) {
        if (theFolder == null || theImageName == null || theBitmap == null)
            return false;

        this.DEFAULT_APP_IMAGEDATA_DIRECTORY = theFolder;
        String mFullPath = setupFullPath(theImageName);

        if (!mFullPath.equals("")) {
            lastImagePath = mFullPath;
            return saveBitmap(mFullPath, theBitmap);
        }

        return false;
    }

    /**
     * Saves 'theBitmap' into 'fullPath'
     * @param fullPath full path of the image file e.g. "Images/MeAtLunch.png"
     * @param theBitmap the image you want to save as a Bitmap
     * @return true if image was saved, false otherwise
     */
    public boolean putImageWithFullPath(String fullPath, Bitmap theBitmap) {
        return !(fullPath == null || theBitmap == null) && saveBitmap(fullPath, theBitmap);
    }

    /**
     * Creates the path for the image with name 'imageName' in DEFAULT_APP.. directory
     * @param imageName name of the image
     * @return the full path of the image. If it failed to create directory, return empty string
     */
    private String setupFullPath(String imageName) {
        File mFolder = new File(Environment.getExternalStorageDirectory(), DEFAULT_APP_IMAGEDATA_DIRECTORY);

        if (isExternalStorageReadable() && isExternalStorageWritable() && !mFolder.exists()) {
            if (!mFolder.mkdirs()) {
                Log.e("ERROR", "Failed to setup folder");
                return "";
            }
        }

        return mFolder.getPath() + '/' + imageName;
    }

    /**
     * Saves the Bitmap as a PNG file at path 'fullPath'
     * @param fullPath path of the image file
     * @param bitmap the image as a Bitmap
     * @return true if it successfully saved, false otherwise
     */
    private boolean saveBitmap(String fullPath, Bitmap bitmap) {
        if (fullPath == null || bitmap == null)
            return false;

        boolean fileCreated = false;
        boolean bitmapCompressed = false;
        boolean streamClosed = false;

        File imageFile = new File(fullPath);

        if (imageFile.exists())
            if (!imageFile.delete())
                return false;

        try {
            fileCreated = imageFile.createNewFile();

        } catch (IOException e) {
            e.printStackTrace();
        }

        FileOutputStream out = null;
        try {
            out = new FileOutputStream(imageFile);
            bitmapCompressed = bitmap.compress(CompressFormat.PNG, 100, out);

        } catch (Exception e) {
            e.printStackTrace();
            bitmapCompressed = false;

        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                    streamClosed = true;

                } catch (IOException e) {
                    e.printStackTrace();
                    streamClosed = false;
                }
            }
        }

        return (fileCreated && bitmapCompressed && streamClosed);
    }

    // Getters

    /**
     * Get int value from SharedPreferences at 'key'. If key not found, return 'defaultValue'
     * @param key SharedPreferences key
     * @param defaultValue int value returned if key was not found
     * @return int value at 'key' or 'defaultValue' if key not found
     */
    public int getInt(String key, int defaultValue) {
        return preferences.getInt(key, defaultValue);
    }

    /**
     * Get parsed ArrayList of Integers from SharedPreferences at 'key'
     * @param key SharedPreferences key
     * @return ArrayList of Integers
     */
    public ArrayList<Integer> getListInt(String key) {
        String[] myList = TextUtils.split(preferences.getString(key, ""), "‚‗‚");
        ArrayList<String> arrayToList = new ArrayList<String>(Arrays.asList(myList));
        ArrayList<Integer> newList = new ArrayList<Integer>();

        for (String item : arrayToList)
            newList.add(Integer.parseInt(item));

        return newList;
    }

    /**
     * Get long value from SharedPreferences at 'key'. If key not found, return 'defaultValue'
     * @param key SharedPreferences key
     * @param defaultValue long value returned if key was not found
     * @return long value at 'key' or 'defaultValue' if key not found
     */
    public long getLong(String key, long defaultValue) {
        return preferences.getLong(key, defaultValue);
    }

    /**
     * Get float value from SharedPreferences at 'key'. If key not found, return 'defaultValue'
     * @param key SharedPreferences key
     * @param defaultValue float value returned if key was not found
     * @return float value at 'key' or 'defaultValue' if key not found
     */
    public float getFloat(String key, float defaultValue) {
        return preferences.getFloat(key, defaultValue);
    }

    /**
     * Get double value from SharedPreferences at 'key'. If exception thrown, return 'defaultValue'
     * @param key SharedPreferences key
     * @param defaultValue double value returned if exception is thrown
     * @return double value at 'key' or 'defaultValue' if exception is thrown
     */
    public double getDouble(String key, double defaultValue) {
        String number = getString(key);

        try {
            return Double.parseDouble(number);

        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }

    /**
     * Get parsed ArrayList of Double from SharedPreferences at 'key'
     * @param key SharedPreferences key
     * @return ArrayList of Double
     */
    public ArrayList<Double> getListDouble(String key) {
        String[] myList = TextUtils.split(preferences.getString(key, ""), "â€šâ€—â€š");
        ArrayList<String> arrayToList = new ArrayList<String>(Arrays.asList(myList));
        ArrayList<Double> newList = new ArrayList<Double>();

        for (String item : arrayToList)
            newList.add(Double.parseDouble(item));

        return newList;
    }

    /**
     * Get String value from SharedPreferences at 'key'. If key not found, return ""
     * @param key SharedPreferences key
     * @return String value at 'key' or "" (empty String) if key not found
     */
    public String getString(String key) {
        return preferences.getString(key, "");
    }

    /**
     * Get parsed ArrayList of String from SharedPreferences at 'key'
     * @param key SharedPreferences key
     * @return ArrayList of String
     */
    public ArrayList<String> getListString(String key) {
        return new ArrayList<String>(Arrays.asList(TextUtils.split(preferences.getString(key, ""), "‚‗‚")));
    }

    /**
     * Get boolean value from SharedPreferences at 'key'. If key not found, return 'defaultValue'
     * @param key SharedPreferences key
     * @param defaultValue boolean value returned if key was not found
     * @return boolean value at 'key' or 'defaultValue' if key not found
     */
    public boolean getBoolean(String key, boolean defaultValue) {
        return preferences.getBoolean(key, defaultValue);
    }

    /**
     * Get parsed ArrayList of Boolean from SharedPreferences at 'key'
     * @param key SharedPreferences key
     * @return ArrayList of Boolean
     */
    public ArrayList<Boolean> getListBoolean(String key) {
        ArrayList<String> myList = getListString(key);
        ArrayList<Boolean> newList = new ArrayList<Boolean>();

        for (String item : myList) {
            if (item.equals("true")) {
                newList.add(true);
            } else {
                newList.add(false);
            }
        }

        return newList;
    }

    // Put methods

    /**
     * Put int value into SharedPreferences with 'key' and save
     * @param key SharedPreferences key
     * @param value int value to be added
     */
    public void putInt(String key, int value) {
        preferences.edit().putInt(key, value).apply();
    }

    /**
     * Put ArrayList of Integer into SharedPreferences with 'key' and save
     * @param key SharedPreferences key
     * @param intList ArrayList of Integer to be added
     */
    public void putListInt(String key, ArrayList<Integer> intList) {
        Integer[] myIntList = intList.toArray(new Integer[intList.size()]);
        preferences.edit().putString(key, TextUtils.join("‚‗‚", myIntList)).apply();
    }

    /**
     * Put long value into SharedPreferences with 'key' and save
     * @param key SharedPreferences key
     * @param value long value to be added
     */
    public void putLong(String key, long value) {
        preferences.edit().putLong(key, value).apply();
    }

    /**
     * Put float value into SharedPreferences with 'key' and save
     * @param key SharedPreferences key
     * @param value float value to be added
     */
    public void putFloat(String key, float value) {
        preferences.edit().putFloat(key, value).apply();
    }

    /**
     * Put double value into SharedPreferences with 'key' and save
     * @param key SharedPreferences key
     * @param value double value to be added
     */
    public void putDouble(String key, double value) {
        putString(key, String.valueOf(value));
    }

    /**
     * Put ArrayList of Double into SharedPreferences with 'key' and save
     * @param key SharedPreferences key
     * @param doubleList ArrayList of Double to be added
     */
    public void putListDouble(String key, ArrayList<Double> doubleList) {
        Double[] myDoubleList = doubleList.toArray(new Double[doubleList.size()]);
        preferences.edit().putString(key, TextUtils.join("â€šâ€—â€š", myDoubleList)).apply();
    }

    /**
     * Put String value into SharedPreferences with 'key' and save
     * @param key SharedPreferences key
     * @param value String value to be added
     */
    public void putString(String key, String value) {
        preferences.edit().putString(key, value).apply();
    }

    /**
     * Put ArrayList of String into SharedPreferences with 'key' and save
     * @param key SharedPreferences key
     * @param stringList ArrayList of String to be added
     */
    public void putListString(String key, ArrayList<String> stringList) {
        String[] myStringList = stringList.toArray(new String[stringList.size()]);
        preferences.edit().putString(key, TextUtils.join("‚‗‚", myStringList)).apply();
    }

    /**
     * Put boolean value into SharedPreferences with 'key' and save
     * @param key SharedPreferences key
     * @param value boolean value to be added
     */
    public void putBoolean(String key, boolean value) {
        preferences.edit().putBoolean(key, value).apply();
    }

    /**
     * Put ArrayList of Boolean into SharedPreferences with 'key' and save
     * @param key SharedPreferences key
     * @param boolList ArrayList of Boolean to be added
     */
    public void putListBoolean(String key, ArrayList<Boolean> boolList) {
        ArrayList<String> newList = new ArrayList<String>();

        for (Boolean item : boolList) {
            if (item) {
                newList.add("true");
            } else {
                newList.add("false");
            }
        }

        putListString(key, newList);
    }

    /**
     * Remove SharedPreferences item with 'key'
     * @param key SharedPreferences key
     */
    public void remove(String key) {
        preferences.edit().remove(key).apply();
    }

    /**
     * Delete image file at 'path'
     * @param path path of image file
     * @return true if it successfully deleted, false otherwise
     */
    public boolean deleteImage(String path) {
        return new File(path).delete();
    }

    /**
     * Clear SharedPreferences (remove everything)
     */
    public void clear() {
        preferences.edit().clear().apply();
    }

    /**
     * Retrieve all values from SharedPreferences. Do not modify collection return by method
     * @return a Map representing a list of key/value pairs from SharedPreferences
     */
    public Map<String, ?> getAll() {
        return preferences.getAll();
    }

    /**
     * Register SharedPreferences change listener
     * @param listener listener object of OnSharedPreferenceChangeListener
     */
    public void registerOnSharedPreferenceChangeListener(
            SharedPreferences.OnSharedPreferenceChangeListener listener) {

        preferences.registerOnSharedPreferenceChangeListener(listener);
    }

    /**
     * Unregister SharedPreferences change listener
     * @param listener listener object of OnSharedPreferenceChangeListener to be unregistered
     */
    public void unregisterOnSharedPreferenceChangeListener(
            SharedPreferences.OnSharedPreferenceChangeListener listener) {

        preferences.unregisterOnSharedPreferenceChangeListener(listener);
    }

    /**
     * Check if external storage is writable or not
     * @return true if writable, false otherwise
     */
    public static boolean isExternalStorageWritable() {
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
    }

    /**
     * Check if external storage is readable or not
     * @return true if readable, false otherwise
     */
    public static boolean isExternalStorageReadable() {
        String state = Environment.getExternalStorageState();

        return Environment.MEDIA_MOUNTED.equals(state) ||
                Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
    }
}
</code>```

I am not able to figure out why I am not able to access my shared preference inside the service. Please help me out. Thanks in advance.

答:
Most probably problem is not to call SharedPreferences  in right place. If we use a run thread (inside our Service class) we should call it inside it, or if you need it in your onCreate() then call it inside onCreate() method of your Service class</p>

```<code>SharedPreferences shp = getApplicationContext().getSharedPreferences("sam", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = shp.edit();
</code>```

Body:
Hi I am using the GCMListener service to listen to incoming messages. I am trying to access my shared preference in the service, with the help of TinyDB.

I get the following error when trying to access the shared preference.

java.lang.RuntimeException: Unable to instantiate service com.artqueen.aahaan.GCM.MyGcmListenerService: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
            at android.app.ActivityThread.handleCreateService(ActivityThread.java:3271)
            at android.app.ActivityThread.access$1900(ActivityThread.java:182)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1558)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:6141)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
            at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:184)
            at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:369)
            at com.artqueen.aahaan.Helper.TinyDB.<init>(TinyDB.java:31)
            at com.artqueen.aahaan.GCM.MyGcmListenerService.<init>(MyGcmListenerService.java:40)
            at java.lang.reflect.Constructor.newInstance(Native Method)
            at java.lang.Class.newInstance(Class.java:1650)
            at android.app.ActivityThread.handleCreateService(ActivityThread.java:3268)
            at android.app.ActivityThread.access$1900(ActivityThread.java:182)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1558)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:6141)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

I am using the GCMListenerService like this

public class MyGcmListenerService extends GcmListenerService {

    private static final String TAG = "MyGcmListenerService";

    TinyDB tinyDB = new TinyDB(MyGcmListenerService.this);

    @Override
    public void onMessageReceived(String from, Bundle data) {
        String message = data.getString("message");

        String user = data.getString("user","");
        Log.e("user = "," "+user);

        ArrayList<String> blockList = tinyDB.getListString("blockList");

       if(blockList.contains(user)){
           //dont show notification
       }else {
           //show notification
           sendNotification(user);
       }
    }

And for your reference, the TinyDB class looks like this

public class TinyDB {

    private SharedPreferences preferences;
    private String DEFAULT_APP_IMAGEDATA_DIRECTORY;
    private String lastImagePath = "";

    public TinyDB(Context appContext) {
        preferences = PreferenceManager.getDefaultSharedPreferences(appContext);
    }

    /**
     * Decodes the Bitmap from 'path' and returns it
     * @param path image path
     * @return the Bitmap from 'path'
     */
    public Bitmap getImage(String path) {
        Bitmap bitmapFromPath = null;
        try {
            bitmapFromPath = BitmapFactory.decodeFile(path);

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

        return bitmapFromPath;
    }

    /**
     * Returns the String path of the last saved image
     * @return string path of the last saved image
     */
    public String getSavedImagePath() {
        return lastImagePath;
    }

    /**
     * Saves 'theBitmap' into folder 'theFolder' with the name 'theImageName'
     * @param theFolder the folder path dir you want to save it to e.g "DropBox/WorkImages"
     * @param theImageName the name you want to assign to the image file e.g "MeAtLunch.png"
     * @param theBitmap the image you want to save as a Bitmap
     * @return true if image was saved, false otherwise
     */
    public boolean putImage(String theFolder, String theImageName, Bitmap theBitmap) {
        if (theFolder == null || theImageName == null || theBitmap == null)
            return false;

        this.DEFAULT_APP_IMAGEDATA_DIRECTORY = theFolder;
        String mFullPath = setupFullPath(theImageName);

        if (!mFullPath.equals("")) {
            lastImagePath = mFullPath;
            return saveBitmap(mFullPath, theBitmap);
        }

        return false;
    }

    /**
     * Saves 'theBitmap' into 'fullPath'
     * @param fullPath full path of the image file e.g. "Images/MeAtLunch.png"
     * @param theBitmap the image you want to save as a Bitmap
     * @return true if image was saved, false otherwise
     */
    public boolean putImageWithFullPath(String fullPath, Bitmap theBitmap) {
        return !(fullPath == null || theBitmap == null) && saveBitmap(fullPath, theBitmap);
    }

    /**
     * Creates the path for the image with name 'imageName' in DEFAULT_APP.. directory
     * @param imageName name of the image
     * @return the full path of the image. If it failed to create directory, return empty string
     */
    private String setupFullPath(String imageName) {
        File mFolder = new File(Environment.getExternalStorageDirectory(), DEFAULT_APP_IMAGEDATA_DIRECTORY);

        if (isExternalStorageReadable() && isExternalStorageWritable() && !mFolder.exists()) {
            if (!mFolder.mkdirs()) {
                Log.e("ERROR", "Failed to setup folder");
                return "";
            }
        }

        return mFolder.getPath() + '/' + imageName;
    }

    /**
     * Saves the Bitmap as a PNG file at path 'fullPath'
     * @param fullPath path of the image file
     * @param bitmap the image as a Bitmap
     * @return true if it successfully saved, false otherwise
     */
    private boolean saveBitmap(String fullPath, Bitmap bitmap) {
        if (fullPath == null || bitmap == null)
            return false;

        boolean fileCreated = false;
        boolean bitmapCompressed = false;
        boolean streamClosed = false;

        File imageFile = new File(fullPath);

        if (imageFile.exists())
            if (!imageFile.delete())
                return false;

        try {
            fileCreated = imageFile.createNewFile();

        } catch (IOException e) {
            e.printStackTrace();
        }

        FileOutputStream out = null;
        try {
            out = new FileOutputStream(imageFile);
            bitmapCompressed = bitmap.compress(CompressFormat.PNG, 100, out);

        } catch (Exception e) {
            e.printStackTrace();
            bitmapCompressed = false;

        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                    streamClosed = true;

                } catch (IOException e) {
                    e.printStackTrace();
                    streamClosed = false;
                }
            }
        }

        return (fileCreated && bitmapCompressed && streamClosed);
    }

    // Getters

    /**
     * Get int value from SharedPreferences at 'key'. If key not found, return 'defaultValue'
     * @param key SharedPreferences key
     * @param defaultValue int value returned if key was not found
     * @return int value at 'key' or 'defaultValue' if key not found
     */
    public int getInt(String key, int defaultValue) {
        return preferences.getInt(key, defaultValue);
    }

    /**
     * Get parsed ArrayList of Integers from SharedPreferences at 'key'
     * @param key SharedPreferences key
     * @return ArrayList of Integers
     */
    public ArrayList<Integer> getListInt(String key) {
        String[] myList = TextUtils.split(preferences.getString(key, ""), "‚‗‚");
        ArrayList<String> arrayToList = new ArrayList<String>(Arrays.asList(myList));
        ArrayList<Integer> newList = new ArrayList<Integer>();

        for (String item : arrayToList)
            newList.add(Integer.parseInt(item));

        return newList;
    }

    /**
     * Get long value from SharedPreferences at 'key'. If key not found, return 'defaultValue'
     * @param key SharedPreferences key
     * @param defaultValue long value returned if key was not found
     * @return long value at 'key' or 'defaultValue' if key not found
     */
    public long getLong(String key, long defaultValue) {
        return preferences.getLong(key, defaultValue);
    }

    /**
     * Get float value from SharedPreferences at 'key'. If key not found, return 'defaultValue'
     * @param key SharedPreferences key
     * @param defaultValue float value returned if key was not found
     * @return float value at 'key' or 'defaultValue' if key not found
     */
    public float getFloat(String key, float defaultValue) {
        return preferences.getFloat(key, defaultValue);
    }

    /**
     * Get double value from SharedPreferences at 'key'. If exception thrown, return 'defaultValue'
     * @param key SharedPreferences key
     * @param defaultValue double value returned if exception is thrown
     * @return double value at 'key' or 'defaultValue' if exception is thrown
     */
    public double getDouble(String key, double defaultValue) {
        String number = getString(key);

        try {
            return Double.parseDouble(number);

        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }

    /**
     * Get parsed ArrayList of Double from SharedPreferences at 'key'
     * @param key SharedPreferences key
     * @return ArrayList of Double
     */
    public ArrayList<Double> getListDouble(String key) {
        String[] myList = TextUtils.split(preferences.getString(key, ""), "â€šâ€—â€š");
        ArrayList<String> arrayToList = new ArrayList<String>(Arrays.asList(myList));
        ArrayList<Double> newList = new ArrayList<Double>();

        for (String item : arrayToList)
            newList.add(Double.parseDouble(item));

        return newList;
    }

    /**
     * Get String value from SharedPreferences at 'key'. If key not found, return ""
     * @param key SharedPreferences key
     * @return String value at 'key' or "" (empty String) if key not found
     */
    public String getString(String key) {
        return preferences.getString(key, "");
    }

    /**
     * Get parsed ArrayList of String from SharedPreferences at 'key'
     * @param key SharedPreferences key
     * @return ArrayList of String
     */
    public ArrayList<String> getListString(String key) {
        return new ArrayList<String>(Arrays.asList(TextUtils.split(preferences.getString(key, ""), "‚‗‚")));
    }

    /**
     * Get boolean value from SharedPreferences at 'key'. If key not found, return 'defaultValue'
     * @param key SharedPreferences key
     * @param defaultValue boolean value returned if key was not found
     * @return boolean value at 'key' or 'defaultValue' if key not found
     */
    public boolean getBoolean(String key, boolean defaultValue) {
        return preferences.getBoolean(key, defaultValue);
    }

    /**
     * Get parsed ArrayList of Boolean from SharedPreferences at 'key'
     * @param key SharedPreferences key
     * @return ArrayList of Boolean
     */
    public ArrayList<Boolean> getListBoolean(String key) {
        ArrayList<String> myList = getListString(key);
        ArrayList<Boolean> newList = new ArrayList<Boolean>();

        for (String item : myList) {
            if (item.equals("true")) {
                newList.add(true);
            } else {
                newList.add(false);
            }
        }

        return newList;
    }

    // Put methods

    /**
     * Put int value into SharedPreferences with 'key' and save
     * @param key SharedPreferences key
     * @param value int value to be added
     */
    public void putInt(String key, int value) {
        preferences.edit().putInt(key, value).apply();
    }

    /**
     * Put ArrayList of Integer into SharedPreferences with 'key' and save
     * @param key SharedPreferences key
     * @param intList ArrayList of Integer to be added
     */
    public void putListInt(String key, ArrayList<Integer> intList) {
        Integer[] myIntList = intList.toArray(new Integer[intList.size()]);
        preferences.edit().putString(key, TextUtils.join("‚‗‚", myIntList)).apply();
    }

    /**
     * Put long value into SharedPreferences with 'key' and save
     * @param key SharedPreferences key
     * @param value long value to be added
     */
    public void putLong(String key, long value) {
        preferences.edit().putLong(key, value).apply();
    }

    /**
     * Put float value into SharedPreferences with 'key' and save
     * @param key SharedPreferences key
     * @param value float value to be added
     */
    public void putFloat(String key, float value) {
        preferences.edit().putFloat(key, value).apply();
    }

    /**
     * Put double value into SharedPreferences with 'key' and save
     * @param key SharedPreferences key
     * @param value double value to be added
     */
    public void putDouble(String key, double value) {
        putString(key, String.valueOf(value));
    }

    /**
     * Put ArrayList of Double into SharedPreferences with 'key' and save
     * @param key SharedPreferences key
     * @param doubleList ArrayList of Double to be added
     */
    public void putListDouble(String key, ArrayList<Double> doubleList) {
        Double[] myDoubleList = doubleList.toArray(new Double[doubleList.size()]);
        preferences.edit().putString(key, TextUtils.join("â€šâ€—â€š", myDoubleList)).apply();
    }

    /**
     * Put String value into SharedPreferences with 'key' and save
     * @param key SharedPreferences key
     * @param value String value to be added
     */
    public void putString(String key, String value) {
        preferences.edit().putString(key, value).apply();
    }

    /**
     * Put ArrayList of String into SharedPreferences with 'key' and save
     * @param key SharedPreferences key
     * @param stringList ArrayList of String to be added
     */
    public void putListString(String key, ArrayList<String> stringList) {
        String[] myStringList = stringList.toArray(new String[stringList.size()]);
        preferences.edit().putString(key, TextUtils.join("‚‗‚", myStringList)).apply();
    }

    /**
     * Put boolean value into SharedPreferences with 'key' and save
     * @param key SharedPreferences key
     * @param value boolean value to be added
     */
    public void putBoolean(String key, boolean value) {
        preferences.edit().putBoolean(key, value).apply();
    }

    /**
     * Put ArrayList of Boolean into SharedPreferences with 'key' and save
     * @param key SharedPreferences key
     * @param boolList ArrayList of Boolean to be added
     */
    public void putListBoolean(String key, ArrayList<Boolean> boolList) {
        ArrayList<String> newList = new ArrayList<String>();

        for (Boolean item : boolList) {
            if (item) {
                newList.add("true");
            } else {
                newList.add("false");
            }
        }

        putListString(key, newList);
    }

    /**
     * Remove SharedPreferences item with 'key'
     * @param key SharedPreferences key
     */
    public void remove(String key) {
        preferences.edit().remove(key).apply();
    }

    /**
     * Delete image file at 'path'
     * @param path path of image file
     * @return true if it successfully deleted, false otherwise
     */
    public boolean deleteImage(String path) {
        return new File(path).delete();
    }

    /**
     * Clear SharedPreferences (remove everything)
     */
    public void clear() {
        preferences.edit().clear().apply();
    }

    /**
     * Retrieve all values from SharedPreferences. Do not modify collection return by method
     * @return a Map representing a list of key/value pairs from SharedPreferences
     */
    public Map<String, ?> getAll() {
        return preferences.getAll();
    }

    /**
     * Register SharedPreferences change listener
     * @param listener listener object of OnSharedPreferenceChangeListener
     */
    public void registerOnSharedPreferenceChangeListener(
            SharedPreferences.OnSharedPreferenceChangeListener listener) {

        preferences.registerOnSharedPreferenceChangeListener(listener);
    }

    /**
     * Unregister SharedPreferences change listener
     * @param listener listener object of OnSharedPreferenceChangeListener to be unregistered
     */
    public void unregisterOnSharedPreferenceChangeListener(
            SharedPreferences.OnSharedPreferenceChangeListener listener) {

        preferences.unregisterOnSharedPreferenceChangeListener(listener);
    }

    /**
     * Check if external storage is writable or not
     * @return true if writable, false otherwise
     */
    public static boolean isExternalStorageWritable() {
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
    }

    /**
     * Check if external storage is readable or not
     * @return true if readable, false otherwise
     */
    public static boolean isExternalStorageReadable() {
        String state = Environment.getExternalStorageState();

        return Environment.MEDIA_MOUNTED.equals(state) ||
                Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
    }
}

I am not able to figure out why I am not able to access my shared preference inside the service. Please help me out. Thanks in advance.

Body:
Most probably problem is not to call SharedPreferences  in right place. If we use a run thread (inside our Service class) we should call it inside it, or if you need it in your onCreate() then call it inside onCreate() method of your Service class

SharedPreferences shp = getApplicationContext().getSharedPreferences("sam", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = shp.edit();


问:
Build database with .sql file with PHP
Ok, i have searched high and low and have been unable to find an answer that works for what i am trying to do.  I have two databases, we'll call them DB1 and DB2.  I have a cron job that runs every night at 4am that backs up DB1 and stores its data in a SQL file archive, we'll call this file db_backup.sql.  The file is stored in a folder on the server, we'll call it ROOT/backups/db_backup.sql.

Info

```<code>database names: DB1 and DB2
backup filename: db_backup.sql
backup file path: ROOT/backups/db_backup.sql
</code>```

What i'm trying to do:

I want to use the db_backup.sql file to build DB2.  I am basically trying to set up database replication where i replicate DB1 out to DB2.  Don't know of any other way to do this on shared hosting servers than what i'm trying to explain.  I am trying to use php to import the db_backup.sql file into DB2.

My Environment:

The website and databases are on a shared hosting account with godaddy (yes, i would love to get dedicated servers to set up real replication, but can't afford it for now).  The databases are mysql in phpmyadmin.

Is this something that is possible? Any help would be greatly appreciated!  Let me know if you have any questions as well.

答:
Should be as simple as, setting up a CRON job on server 2 to call a script on Server 1 which dishes out the SQL file, then that cron job script would import / rebuild the DB.

Make sure to require a hash (via get or post) before giving out the DB SQL on server 1, or else anyone could read it / have your database dump.

Title: Build database with .sql file with PHP

Body:
Ok, i have searched high and low and have been unable to find an answer that works for what i am trying to do.  I have two databases, we'll call them DB1 and DB2.  I have a cron job that runs every night at 4am that backs up DB1 and stores its data in a SQL file archive, we'll call this file db_backup.sql.  The file is stored in a folder on the server, we'll call it ROOT/backups/db_backup.sql.

Info

database names: DB1 and DB2
backup filename: db_backup.sql
backup file path: ROOT/backups/db_backup.sql

What i'm trying to do:

I want to use the db_backup.sql file to build DB2.  I am basically trying to set up database replication where i replicate DB1 out to DB2.  Don't know of any other way to do this on shared hosting servers than what i'm trying to explain.  I am trying to use php to import the db_backup.sql file into DB2.

My Environment:

The website and databases are on a shared hosting account with godaddy (yes, i would love to get dedicated servers to set up real replication, but can't afford it for now).  The databases are mysql in phpmyadmin.

Is this something that is possible? Any help would be greatly appreciated!  Let me know if you have any questions as well.


问:
How to set diferent levels of logging for each file in module?
How do you choose the level of logging in modules?

I have an application with various files,
I worked for understand the logging module, and drop print()
My goals with logging is flexibility switching logging levels from diferents part of the code (modules)
I do it only from the main entry point function:

Here is what i have:

```<code>APP/PartA/Script1.py
APP/PartA/Script2.py
APP/Other/Tools.py
APP/main.py
</code>```

First module:

```<code>#/PartA/Script1.py
import logging
from PartA.Script2 import *

logger = logging.getLogger(__name__)
# Logger Always on debug level:
logger.setLevel(logging.DEBUG)

handler1 = logging.StreamHandler()
handler1.setFormatter(logging.Formatter('\n%(levelname)s  %(name)s'))

logger.addHandler(handler1)

def add_ten(n)
    ten_added = add_five(n) + 5
    return ten_added
</code>```

Second module:

```<code>#/PartA/Script2.py
import logging

logger = logging.getLogger(__name__)
# Logger Always on debug level:
logger.setLevel(logging.DEBUG)

handler2 = logging.StreamHandler()
handler2.setFormatter(logging.Formatter('\n%(levelname)s  %(name)s %(funcName)s %(lineno)s \n%(message)s'))

logger.addHandler(handler2)

def add_five(n):
    return n + 5
</code>```

Main entry point:

```<code>#main.py
import logging
from PartA.Script1 import *
from PartA.Script2 import *

logger = logging.getLogger(__name__)
# Logger is always on debug mode..
logger.setLevel(logging.DEBUG)

# Mainhandler:
handler = logging.StreamHandler()

handler.setLevel(logging.INFO)

# Here i control the logs levels from the other modules:
handler2.setLevel(logging.DEBUG)
handler1.setLevel(logging.ERROR)
</code>```

Thats working , as i just have to change the handlers setlevels in the main function, but i dont think it is very pythonic, having to set all the loggers on DEBUG level always seems strange,
And very repetitive code to do it for any new .py file..

答:
it is best practice in python to not configure any logging handlers/formatters inside your module, just use the NullHandler. The configuration of handlers is done inside the application using the module.

So the following should be sufficient inside the module.

```<code>import logging

logger = logging.getLogger(__name__)
</code>```

Body:
How do you choose the level of logging in modules?

I have an application with various files,
I worked for understand the logging module, and drop print()
My goals with logging is flexibility switching logging levels from diferents part of the code (modules)
I do it only from the main entry point function:

Here is what i have:

APP/PartA/Script1.py
APP/PartA/Script2.py
APP/Other/Tools.py
APP/main.py

First module:

#/PartA/Script1.py
import logging
from PartA.Script2 import *

logger = logging.getLogger(__name__)
# Logger Always on debug level:
logger.setLevel(logging.DEBUG)

handler1 = logging.StreamHandler()
handler1.setFormatter(logging.Formatter('\n%(levelname)s  %(name)s'))

logger.addHandler(handler1)

def add_ten(n)
    ten_added = add_five(n) + 5
    return ten_added

Second module:

#/PartA/Script2.py
import logging

logger = logging.getLogger(__name__)
# Logger Always on debug level:
logger.setLevel(logging.DEBUG)

handler2 = logging.StreamHandler()
handler2.setFormatter(logging.Formatter('\n%(levelname)s  %(name)s %(funcName)s %(lineno)s \n%(message)s'))

logger.addHandler(handler2)

def add_five(n):
    return n + 5

Main entry point:

#main.py
import logging
from PartA.Script1 import *
from PartA.Script2 import *

logger = logging.getLogger(__name__)
# Logger is always on debug mode..
logger.setLevel(logging.DEBUG)

# Mainhandler:
handler = logging.StreamHandler()

handler.setLevel(logging.INFO)

# Here i control the logs levels from the other modules:
handler2.setLevel(logging.DEBUG)
handler1.setLevel(logging.ERROR)

Thats working , as i just have to change the handlers setlevels in the main function, but i dont think it is very pythonic, having to set all the loggers on DEBUG level always seems strange,
And very repetitive code to do it for any new .py file..

Body:
it is best practice in python to not configure any logging handlers/formatters inside your module, just use the NullHandler. The configuration of handlers is done inside the application using the module.

So the following should be sufficient inside the module.

import logging

logger = logging.getLogger(__name__)


问:
Searching for MYSQLI record across multiple tables with AJAX
I am adding search functionality to my website, currently the user can search for a item by model name, for example '100D' however they cannot search for brand, in this case it would be 'Canon'. I would like to allow the user to search for 'canon 100d' and the result shows up, where as currently the user can only search '100d'

I have 2 tables, one being 'brands' and one being 'models', this allows me to store the brand information separately from the models because there is one 'brand' to-many 'models'. Because of this I only store the brand 'id' within the models table.

Here is my 'fetch.php' file, this is called in via AJAX from the search form, here is the query where I search for the model based of the input in the search form:

```<code>$model_search_query = $cameras_pdo->prepare("SELECT * FROM models WHERE model LIKE :search");
    $model_search_query->execute(array(':search' => "%" . $_POST['search'] . "%"));

    while ($model_search = $model_search_query->fetch(PDO::FETCH_ASSOC)) {
        $brand_search_query = "SELECT brand FROM brands WHERE id =" . $model_search['brand'];
        $brand_search = mysqli_fetch_assoc(mysqli_query($cameras, $brand_search_query));

        // OUTPUT SEARCH RESULTS HERE

    }

?>
</code>```

This above code allows for the user to search '100d' and then the result 'Canon 100D' shows because I have another query in the while loop that finds the brand name based of the input.

I want the user to be able to search the string 'canon 100d' and even though the brand name is stored in a different table to the model, it still returns the result.

I have attempted to do this by creating another query that searches the the brands based of the input however and then returns the ID of the brand in the brands table, then then can be used in the model search query... this does not work, if anyone knows a way to solve my issue, it would be greatly appreciated. Thankyou

答:
I have not tested this but it seems you need a JOIN, try this query

```<code>$search_query   = explode(" ", $_POST['search']);
$model_search_query = $cameras_pdo->prepare("SELECT m.id,m.model,b.brand FROM models m INNER JOIN brands b ON b.id = m.brand WHERE (m.model LIKE :model AND b.brand LIKE :brand) OR m.model LIKE :model");
$model_search_query->execute(array(':model' => "%" . $search_query[1] . "%", ':brand'=>"%" . $search_query[0] . "%"));

while ($model_search = $model_search_query->fetch(PDO::FETCH_ASSOC)) {

    // OUTPUT SEARCH RESULTS HERE

}
</code>```

Body:
I am adding search functionality to my website, currently the user can search for a item by model name, for example '100D' however they cannot search for brand, in this case it would be 'Canon'. I would like to allow the user to search for 'canon 100d' and the result shows up, where as currently the user can only search '100d'

I have 2 tables, one being 'brands' and one being 'models', this allows me to store the brand information separately from the models because there is one 'brand' to-many 'models'. Because of this I only store the brand 'id' within the models table.

Here is my 'fetch.php' file, this is called in via AJAX from the search form, here is the query where I search for the model based of the input in the search form:

$model_search_query = $cameras_pdo->prepare("SELECT * FROM models WHERE model LIKE :search");
    $model_search_query->execute(array(':search' => "%" . $_POST['search'] . "%"));

    while ($model_search = $model_search_query->fetch(PDO::FETCH_ASSOC)) {
        $brand_search_query = "SELECT brand FROM brands WHERE id =" . $model_search['brand'];
        $brand_search = mysqli_fetch_assoc(mysqli_query($cameras, $brand_search_query));

        // OUTPUT SEARCH RESULTS HERE

    }

?>

This above code allows for the user to search '100d' and then the result 'Canon 100D' shows because I have another query in the while loop that finds the brand name based of the input.

I want the user to be able to search the string 'canon 100d' and even though the brand name is stored in a different table to the model, it still returns the result.

I have attempted to do this by creating another query that searches the the brands based of the input however and then returns the ID of the brand in the brands table, then then can be used in the model search query... this does not work, if anyone knows a way to solve my issue, it would be greatly appreciated. Thankyou

Body:
I have not tested this but it seems you need a JOIN, try this query

$search_query   = explode(" ", $_POST['search']);
$model_search_query = $cameras_pdo->prepare("SELECT m.id,m.model,b.brand FROM models m INNER JOIN brands b ON b.id = m.brand WHERE (m.model LIKE :model AND b.brand LIKE :brand) OR m.model LIKE :model");
$model_search_query->execute(array(':model' => "%" . $search_query[1] . "%", ':brand'=>"%" . $search_query[0] . "%"));

while ($model_search = $model_search_query->fetch(PDO::FETCH_ASSOC)) {

    // OUTPUT SEARCH RESULTS HERE

}


问:
get the annotation information at runtime
I wonder if there is any way I can get the annotation information of a class at runtime? Since I want to get the properties that sepcifily annotated.

Example:

```<code>class TestMain {
    @Field(
            store = Store.NO)
    private String  name;
    private String  password;
    @Field(
            store = Store.YES)
    private int     age;

    //..........getter and setter
}
</code>```

The annotations come from the hibernate-search,and now what I want is get which property of the "TestMain" is annotated as a 'field'(in the example,they are [name,age]),and which is 'stored(store=store.yes)'(in the example,they are [age]) at runtime.

Any ideas?

UPDATe:

```<code>public class FieldUtil {
public static List<String> getAllFieldsByClass(Class<?> clazz) {
    Field[] fields = clazz.getDeclaredFields();
    ArrayList<String> fieldList = new ArrayList<String>();
    ArrayList<String> storedList=new ArrayList<String>();
    String tmp;
    for (int i = 0; i < fields.length; i++) {
        Field fi = fields[i];
        tmp = fi.getName();
        if (tmp.equalsIgnoreCase("serialVersionUID"))
            continue;
        if (fi.isAnnotationPresent(org.hibernate.search.annotations.Field.class)) {
            //it is a "field",add it to list.
            fieldList.add(tmp);

            //make sure if it is stored also
            Annotation[] ans = fi.getAnnotations();
            for (Annotation an : ans) {
                //here,how to get the detail annotation information
                //I print the value of an,it is something like this:
                //@org.hibernate.search.annotations.Field(termVector=NO, index=UN_TOKENIZED, store=NO, name=, boost=@org.hibernate.search.annotations.Boost(value=1.0), analyzer=@org.hibernate.search.annotations.Analyzer(impl=void, definition=), bridge=@org.hibernate.search.annotations.FieldBridge(impl=void, params=[]))

                //how to get the parameter value of this an? using the string method?split?
            }
        }

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

}

答:
Yes, of course. Your code sample does not actually get annotation information for class, but for fields, but code is similar. You just need to get Class, Method or Field you are interested in, then call "getAnnotation(AnnotationClass.class)" on it.

The only other thing to notice is that annotation definition must use proper RetentionPolicy so that annotation information is stored in byte code. Something like:

```<code>@Target({ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation { ... }
</code>```

Body:
I wonder if there is any way I can get the annotation information of a class at runtime? Since I want to get the properties that sepcifily annotated.

Example:

class TestMain {
    @Field(
            store = Store.NO)
    private String  name;
    private String  password;
    @Field(
            store = Store.YES)
    private int     age;

    //..........getter and setter
}

The annotations come from the hibernate-search,and now what I want is get which property of the "TestMain" is annotated as a 'field'(in the example,they are [name,age]),and which is 'stored(store=store.yes)'(in the example,they are [age]) at runtime.

Any ideas?

UPDATe:

public class FieldUtil {
public static List<String> getAllFieldsByClass(Class<?> clazz) {
    Field[] fields = clazz.getDeclaredFields();
    ArrayList<String> fieldList = new ArrayList<String>();
    ArrayList<String> storedList=new ArrayList<String>();
    String tmp;
    for (int i = 0; i < fields.length; i++) {
        Field fi = fields[i];
        tmp = fi.getName();
        if (tmp.equalsIgnoreCase("serialVersionUID"))
            continue;
        if (fi.isAnnotationPresent(org.hibernate.search.annotations.Field.class)) {
            //it is a "field",add it to list.
            fieldList.add(tmp);

            //make sure if it is stored also
            Annotation[] ans = fi.getAnnotations();
            for (Annotation an : ans) {
                //here,how to get the detail annotation information
                //I print the value of an,it is something like this:
                //@org.hibernate.search.annotations.Field(termVector=NO, index=UN_TOKENIZED, store=NO, name=, boost=@org.hibernate.search.annotations.Boost(value=1.0), analyzer=@org.hibernate.search.annotations.Analyzer(impl=void, definition=), bridge=@org.hibernate.search.annotations.FieldBridge(impl=void, params=[]))

                //how to get the parameter value of this an? using the string method?split?
            }
        }

    }
    return fieldList;
}

}

Body:
Yes, of course. Your code sample does not actually get annotation information for class, but for fields, but code is similar. You just need to get Class, Method or Field you are interested in, then call "getAnnotation(AnnotationClass.class)" on it.

The only other thing to notice is that annotation definition must use proper RetentionPolicy so that annotation information is stored in byte code. Something like:

@Target({ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation { ... }


问:
delete elements from canvas graphics in p5js
I using canvas graphics to draw objects and need to undo the last drawn object, but could not find any option to delete last object from graphics, please suggest how to delete last object (i.e. creating undo function)

below is the code to in setup() -

```<code>    canvas=createCanvas(1000,1000);
    canvsGraphics = createGraphics(1000,1000);
</code>```

Below is the object created in mouseDragged() function -

```<code>noStroke();
        fill(R,G,B);
        rectMode(CENTER);
        rect(mouseX,mouseY,20,20);

    //CREATES BUFFER
    canvsGraphics.noStroke();
    canvsGraphics.fill(R,G,B);
    canvsGraphics.rectMode(CENTER);
    canvsGraphics.rect(mouseX,mouseY,20,20);
</code>```

答:
You can't just delete an object once it's drawn.

But you can clear out all of the objects using the background() function, and then redraw all of the objects that you still want to see.

You might consider creating a data structure that holds all of the objects. Then each frame, loop through that data structure and draw each object. To delete an object, simply remove it from the data structure.

Body:
I using canvas graphics to draw objects and need to undo the last drawn object, but could not find any option to delete last object from graphics, please suggest how to delete last object (i.e. creating undo function)

below is the code to in setup() -

    canvas=createCanvas(1000,1000);
    canvsGraphics = createGraphics(1000,1000);

Below is the object created in mouseDragged() function -

noStroke();
        fill(R,G,B);
        rectMode(CENTER);
        rect(mouseX,mouseY,20,20);

    //CREATES BUFFER
    canvsGraphics.noStroke();
    canvsGraphics.fill(R,G,B);
    canvsGraphics.rectMode(CENTER);
    canvsGraphics.rect(mouseX,mouseY,20,20);


问:
Use python return parameter to command line
I want to build a connection between batch file and python program.

I want to use python to get a parameter which is "abc", and let the batch file use the parameter "abc" to do other thing.

How can I return a parameter to command line in python ?

Thanks for your help.

答:
In shell you could always use -c switch to execute any command for single run. To explain better,it executes the string in form of python script. So in short it runs the python terminal , does the execution and then terminates the python terminal. Simple as that. Now let me give you some examples for clarification

Have in mind that i use Windows 10 machine with cmd terminal

```<code>python -c "print(__name__)"
</code>```

Returns __main__ value since i am currently in command prompt. Now this is awesome, since python supports multiliners with ; after each line so you could theoretically write the whole script as textual file and than execute it with python -c with correct version of python installed.

So, in that way you could easily do python -c "import sys;sys.stdout.write('abc')" if you wanted.

Now to save it into command variable , i've figured out only 1 way which is bad but if anyone has another. Please comment.

```<code>python -c "import string;print(dir(string))" >> text.txt
set /p drStr= < text.txt
del text.txt
</code>```

Or in massive oneliner :

```<code>python -c "import string;print(dir(string))" >> text.txt && set /p drStr= <text.txt && del text.txt
</code>```

now just type set drStr to printout the variable and there you go.

Body:
In shell you could always use -c switch to execute any command for single run. To explain better,it executes the string in form of python script. So in short it runs the python terminal , does the execution and then terminates the python terminal. Simple as that. Now let me give you some examples for clarification

Have in mind that i use Windows 10 machine with cmd terminal

python -c "print(__name__)"

Returns __main__ value since i am currently in command prompt. Now this is awesome, since python supports multiliners with ; after each line so you could theoretically write the whole script as textual file and than execute it with python -c with correct version of python installed.

So, in that way you could easily do python -c "import sys;sys.stdout.write('abc')" if you wanted.

Now to save it into command variable , i've figured out only 1 way which is bad but if anyone has another. Please comment.

python -c "import string;print(dir(string))" >> text.txt
set /p drStr= < text.txt
del text.txt

Or in massive oneliner :

python -c "import string;print(dir(string))" >> text.txt && set /p drStr= <text.txt && del text.txt

now just type set drStr to printout the variable and there you go.


问:
How can we execute messages at a particular time daily in nodejs?
I want to execute the message daily at 10'o clock  5 minutes  25 seconds but I tried the program  I got an error:

```<code>ERROR OCCURED:
  throw patterns[5] + ' is a invalid expression for week day';
      ^
 is a invalid expression for week day
</code>```

Code:

```<code>var cron = require('node-cron');
cron.schedule('25 05 10 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 January,February,March,April,May,June,July,August,September,October,November,December   Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday ', function(){
    console.log('Time for breakfast');
});
</code>```

答:
The cron syntax is as described in the node-cron library page:

```<code>┌────────────── second (optional)
│ ┌──────────── minute
│ │ ┌────────── hour
│ │ │ ┌──────── day of month
│ │ │ │ ┌────── month
│ │ │ │ │ ┌──── day of week
│ │ │ │ │ │
│ │ │ │ │ │
* * * * * *
</code>```

So, for executing the task every day at 10:05:25, try
25 5 10 * * *

```<code>cron.schedule('25 5 10 * * *', function() {
  console.log('Time for breakfast');
});
</code>```

Body:
I want to execute the message daily at 10'o clock  5 minutes  25 seconds but I tried the program  I got an error:

ERROR OCCURED:
  throw patterns[5] + ' is a invalid expression for week day';
      ^
 is a invalid expression for week day

Code:

var cron = require('node-cron');
cron.schedule('25 05 10 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31 January,February,March,April,May,June,July,August,September,October,November,December   Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday ', function(){
    console.log('Time for breakfast');
});

Body:
The cron syntax is as described in the node-cron library page:

┌────────────── second (optional)
│ ┌──────────── minute
│ │ ┌────────── hour
│ │ │ ┌──────── day of month
│ │ │ │ ┌────── month
│ │ │ │ │ ┌──── day of week
│ │ │ │ │ │
│ │ │ │ │ │
* * * * * *

So, for executing the task every day at 10:05:25, try
25 5 10 * * *

cron.schedule('25 5 10 * * *', function() {
  console.log('Time for breakfast');
});


问:
Python `ctypes` - How to copy buffer returned by C function into a bytearray
A pointer to buffer of type POINTER(c_ubyte) is returned by the C function (the image_data variable in the following code). I want this data to be managed by Python, so I want to copy it into a bytearray. Here's the function call

```<code>image_data = stb_image.stbi_load(filename_cstr, byref(width),
                                 byref(height), byref(num_channels),
                                 c_int(expected_num_channels))
</code>```

We get to know the width and height of the image only after that call, so can't pre-allocate a bytearray.

I would have used

```<code> array_type = c.c_ubyte * (num_channels.value * width.value * height.value)

 image_data_bytearray = bytearray(cast(image_data, array_type))
</code>```

But the type to cast to must be a pointer, not array, so I get an error.

```<code>TypeError: cast() argument 2 must be a pointer type, not c_ubyte_Array_262144
</code>```

What should I do?

答:
OK, reading the answer to the question linked to in the comments (thanks, @"John Zwinck" and @"eryksun"), there are two ways of storing the data, either in a bytearray or a numpy.array. In all these snippets, image_data is of type POINTER(c_ubyte), and we have array_type defined as -

```<code>array_type = c_ubyte * num_channels * width * height
</code>```

We can create a bytearray first and then loop over and set the bytes

```<code>arr_bytes = bytearray(array_size)
for i in range(array_size):
    arr_bytes[i] = image_data[i]
</code>```

Or a better way is to create a C array instance using from_address and then initialize a bytearray with it -

```<code>image_data_carray = array_type.from_address(addressof(image_data.contents))

# Copy into bytearray
image_data_bytearray = bytearray(image_data_carray)
</code>```

And during writing the image (didn't ask this question, just sharing for completeness), we can obtain pointer to the bytearray data like this and give it to stbi_write_png

```<code>image_data_carray = array_type.from_buffer(image_data_bytearray)
image_data = cast(image_data_carray, POINTER(c_ubyte))
</code>```

The numpy based way of doing it is as answered in the linked question

```<code>address = addressof(image_data.contents)
image_data_ptr = np.ctypeslib.as_array(array_type.from_address(address))
</code>```

This alone however only points to the memory returned by the C function, doesn't copy into a Python-managed array object. We can copy by creating a numpy array as

```<code>image_data = np.array(image_data_ptr)
</code>```

To confirm I have done an assert all(arr_np == arr_bytes) there. And arr_np.dtype is uint8.

And during writing the image, we can obtain a pointer to the numpy array's data like this

```<code>image_data = image_data_numpy.ctypes.data_as(POINTER(c_ubyte))
</code>```

Body:
A pointer to buffer of type POINTER(c_ubyte) is returned by the C function (the image_data variable in the following code). I want this data to be managed by Python, so I want to copy it into a bytearray. Here's the function call

image_data = stb_image.stbi_load(filename_cstr, byref(width),
                                 byref(height), byref(num_channels),
                                 c_int(expected_num_channels))

We get to know the width and height of the image only after that call, so can't pre-allocate a bytearray.

I would have used

 array_type = c.c_ubyte * (num_channels.value * width.value * height.value)

 image_data_bytearray = bytearray(cast(image_data, array_type))

But the type to cast to must be a pointer, not array, so I get an error.

TypeError: cast() argument 2 must be a pointer type, not c_ubyte_Array_262144

What should I do?

Body:
OK, reading the answer to the question linked to in the comments (thanks, @"John Zwinck" and @"eryksun"), there are two ways of storing the data, either in a bytearray or a numpy.array. In all these snippets, image_data is of type POINTER(c_ubyte), and we have array_type defined as -

array_type = c_ubyte * num_channels * width * height

We can create a bytearray first and then loop over and set the bytes

arr_bytes = bytearray(array_size)
for i in range(array_size):
    arr_bytes[i] = image_data[i]

Or a better way is to create a C array instance using from_address and then initialize a bytearray with it -

image_data_carray = array_type.from_address(addressof(image_data.contents))

# Copy into bytearray
image_data_bytearray = bytearray(image_data_carray)

And during writing the image (didn't ask this question, just sharing for completeness), we can obtain pointer to the bytearray data like this and give it to stbi_write_png

image_data_carray = array_type.from_buffer(image_data_bytearray)
image_data = cast(image_data_carray, POINTER(c_ubyte))

The numpy based way of doing it is as answered in the linked question

address = addressof(image_data.contents)
image_data_ptr = np.ctypeslib.as_array(array_type.from_address(address))

This alone however only points to the memory returned by the C function, doesn't copy into a Python-managed array object. We can copy by creating a numpy array as

image_data = np.array(image_data_ptr)

To confirm I have done an assert all(arr_np == arr_bytes) there. And arr_np.dtype is uint8.

And during writing the image, we can obtain a pointer to the numpy array's data like this

image_data = image_data_numpy.ctypes.data_as(POINTER(c_ubyte))


问:
Animating strike-through on a TextView
I have been searching a lot on how to animate the strike-through affect on a TextView to no results. Only thing I am getting on forums and StackOverflow is:

```<code>some_text_view.setPaintFlags(some_text_view.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG)
</code>```

What I want to do is, animate the strike-through affect like in todo apps on Play Store e.g. Any.do has it on an item left-to-right swipe.

答:
```<code>private fun TextView.startStrikeThroughAnimation(): ValueAnimator {
val span = SpannableString(text)
val strikeSpan = StrikethroughSpan()
val animator = ValueAnimator.ofInt(text.length)
animator.addUpdateListener {
    span.setSpan(strikeSpan, 0, it.animatedValue as Int, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    text = span
    invalidate()
}
animator.start()
return animator
</code>```

}

```<code>private fun TextView.reverseStrikeThroughAnimation(): ValueAnimator {
val span = SpannableString(text.toString())
val strikeSpan = StrikethroughSpan()
val animator = ValueAnimator.ofInt(text.length, 0)
animator.addUpdateListener {
    span.setSpan(strikeSpan, 0, it.animatedValue as Int, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    text = span
    invalidate()
}
animator.start()
return animator
</code>```

}

Title: Animating strike-through on a TextView

Body:
I have been searching a lot on how to animate the strike-through affect on a TextView to no results. Only thing I am getting on forums and StackOverflow is:

some_text_view.setPaintFlags(some_text_view.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG)

What I want to do is, animate the strike-through affect like in todo apps on Play Store e.g. Any.do has it on an item left-to-right swipe.

Body:
private fun TextView.startStrikeThroughAnimation(): ValueAnimator {
val span = SpannableString(text)
val strikeSpan = StrikethroughSpan()
val animator = ValueAnimator.ofInt(text.length)
animator.addUpdateListener {
    span.setSpan(strikeSpan, 0, it.animatedValue as Int, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    text = span
    invalidate()
}
animator.start()
return animator

}

private fun TextView.reverseStrikeThroughAnimation(): ValueAnimator {
val span = SpannableString(text.toString())
val strikeSpan = StrikethroughSpan()
val animator = ValueAnimator.ofInt(text.length, 0)
animator.addUpdateListener {
    span.setSpan(strikeSpan, 0, it.animatedValue as Int, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    text = span
    invalidate()
}
animator.start()
return animator

}