问:
Combine: Publisher sometimes loses value and completes
I have a simple Deferred Publisher that reads data from disk and I display the data in a SwiftUI List, the Publisher works well most of the time, but sometimes it doesn't behave well, it just loses its value (which's an array of Model objects) and completes with finished message. I've tried a workaround mentioned here to use the buffer operator to keep the value in buffer because I believe the Combine's Publisher by design won't pass the data downstream if there is no demand requested by subscribers and hence dropping this data and completes, however using buffer didn't solve the issue.

The code I have:

```<code>enum FileError: Error {
    case someError
}

class ViewModel: ObservableObject {
    @Published var modelArray = [Model]()
    private var subscriptions = Set<AnyCancellable>()
    func readData() {
        DataSource()
            .readFromBundle(resource: "Sample", type: "json")
            .receive(on: DispatchQueue.main)
            .sink(receiveCompletion: { completion in
                print("Completion: \(completion)")
            }) { array in
                self.modelArray = array
        }.store(in: &subscriptions)
    }
}
struct ContentView: View {
    @ObservedObject var viewModel: ViewModel

    var body: some View {
        VStack {
            List(self.viewModel.modelArray) { model in
                Text("\(model.name)")
            }
        }
        .onAppear {
            self.viewModel.readData()
        }
    }
}

struct Model: Codable, Identifiable {
    var id: Int
    var name: String
}

class DataSource {
    private let readQueue = DispatchQueue(label: "ReadQueue", qos: .default, attributes: .concurrent)

    func readFromBundle (resource: String, type:String) -> AnyPublisher<[Model], FileError> {
            Deferred {
                 Future { promise in
                    guard let url = Bundle.main.url(forResource: "Sample", withExtension: "json"),
                      let data = try? Data(contentsOf: url),
                      let modelArray = try? JSONDecoder().decode([Model].self, from: data)
                      else {
                        promise(.failure(.someError))
                        return
                    }
                      promise(.success(modelArray))
                }
            }
           .receive(on: self.readQueue)
           .eraseToAnyPublisher()
        }
}
</code>```

This is a link to download a working sample project.

EDIT:

Environment: Xcode 11.3.1, iOS 13.3 iPhone 11 Pro Max simulator and device.

gif screenshot (notice the console output)

EDIT2:

if I add any downstream publishers, like combineLatest for example just before sink in the consumer function readData() then a new behavior introduced, which's chaining an async publisher (readFromBundle) with a sync publisher (combineLatest) will result in the value will not deliver at all on iOS 13.3+ devices and will sometimes deliver on devices below iOS 13.3, as stated on this link.

答:
Let see the documentation about .receive(on:)

Specifies the scheduler on which to receive elements from the publisher.
Declaration

```<code>func receive<S>(on scheduler: S, options: S.SchedulerOptions? = nil) -> Publishers.ReceiveOn<Publishers.SubscribeOn<Deferred<Future<[Model], FileError>>, DispatchQueue>, S> where S : Scheduler
</code>```

Discussion

You use the receive(on:options:) operator to receive results on a specific scheduler, such as performing UI work on the main run loop. In contrast with subscribe(on:options:), which affects upstream messages, receive(on:options:) changes the execution context of downstream messages. In the following example, requests to jsonPublisher are performed on backgroundQueue, but elements received from it are performed on RunLoop.main.

```<code>let jsonPublisher = MyJSONLoaderPublisher() // Some publisher.
let labelUpdater = MyLabelUpdateSubscriber() // Some subscriber that updates the UI.

jsonPublisher
    .subscribe(on: backgroundQueue)
    .receiveOn(on: RunLoop.main)
    .subscribe(labelUpdater)
</code>```

Parameters

scheduler

The scheduler the publisher is to use for element delivery.
options
Scheduler options that customize the element delivery.
Returns

A publisher that delivers elements using the specified scheduler.

in your case it means

```<code>import SwiftUI
import Combine

enum FileError: Error {
    case someError
}

class ViewModel: ObservableObject {
    @Published var modelArray = [Model]()
    private var subscriptions = Set<AnyCancellable>()
    func readData() {
        DataSource()
            .readFromBundle(resource: "Sample", type: "json")
            .sink(receiveCompletion: { completion in
                print("Completion: \(completion)")
            }) { array in
                print("received value")
                self.modelArray = array
        }.store(in: &subscriptions)
    }
}
struct ContentView: View {
    @ObservedObject var viewModel: ViewModel

    var body: some View {
        VStack {
            List(self.viewModel.modelArray) { model in
                Text("\(model.name)")
            }
        }
        .onAppear {
            self.viewModel.readData()
        }
    }
}

struct Model: Codable, Identifiable {
    var id: Int
    var name: String
}

class DataSource {
    private let readQueue = DispatchQueue(label: "ReadQueue", qos: .default, attributes: .concurrent)

    func readFromBundle (resource: String, type:String) -> AnyPublisher<[Model], FileError> {
            Deferred {
                 Future { promise in
                    guard let url = Bundle.main.url(forResource: "Sample", withExtension: "json"),
                      let data = try? Data(contentsOf: url),
                      let modelArray = try? JSONDecoder().decode([Model].self, from: data)
                      else {
                        promise(.failure(.someError))
                        return
                    }
                      promise(.success(modelArray))
                }
            }
            .subscribe(on: readQueue)
            .receive(on: RunLoop.main)
           .eraseToAnyPublisher()
        }
}
</code>```

which explain, why Asperi's solution works. The difference is, that there is not necessary to call .receive(on:) again in readData()

the difference between DispatchQueue.main and RunLoop.main are not significant in your example.

Body:
I have a simple Deferred Publisher that reads data from disk and I display the data in a SwiftUI List, the Publisher works well most of the time, but sometimes it doesn't behave well, it just loses its value (which's an array of Model objects) and completes with finished message. I've tried a workaround mentioned here to use the buffer operator to keep the value in buffer because I believe the Combine's Publisher by design won't pass the data downstream if there is no demand requested by subscribers and hence dropping this data and completes, however using buffer didn't solve the issue.

The code I have:

enum FileError: Error {
    case someError
}

class ViewModel: ObservableObject {
    @Published var modelArray = [Model]()
    private var subscriptions = Set<AnyCancellable>()
    func readData() {
        DataSource()
            .readFromBundle(resource: "Sample", type: "json")
            .receive(on: DispatchQueue.main)
            .sink(receiveCompletion: { completion in
                print("Completion: \(completion)")
            }) { array in
                self.modelArray = array
        }.store(in: &subscriptions)
    }
}
struct ContentView: View {
    @ObservedObject var viewModel: ViewModel

    var body: some View {
        VStack {
            List(self.viewModel.modelArray) { model in
                Text("\(model.name)")
            }
        }
        .onAppear {
            self.viewModel.readData()
        }
    }
}

struct Model: Codable, Identifiable {
    var id: Int
    var name: String
}

class DataSource {
    private let readQueue = DispatchQueue(label: "ReadQueue", qos: .default, attributes: .concurrent)

    func readFromBundle (resource: String, type:String) -> AnyPublisher<[Model], FileError> {
            Deferred {
                 Future { promise in
                    guard let url = Bundle.main.url(forResource: "Sample", withExtension: "json"),
                      let data = try? Data(contentsOf: url),
                      let modelArray = try? JSONDecoder().decode([Model].self, from: data)
                      else {
                        promise(.failure(.someError))
                        return
                    }
                      promise(.success(modelArray))
                }
            }
           .receive(on: self.readQueue)
           .eraseToAnyPublisher()
        }
}

This is a link to download a working sample project.

EDIT:

Environment: Xcode 11.3.1, iOS 13.3 iPhone 11 Pro Max simulator and device.

gif screenshot (notice the console output)

EDIT2:

if I add any downstream publishers, like combineLatest for example just before sink in the consumer function readData() then a new behavior introduced, which's chaining an async publisher (readFromBundle) with a sync publisher (combineLatest) will result in the value will not deliver at all on iOS 13.3+ devices and will sometimes deliver on devices below iOS 13.3, as stated on this link.

Body:
Let see the documentation about .receive(on:)

Specifies the scheduler on which to receive elements from the publisher.
Declaration

func receive<S>(on scheduler: S, options: S.SchedulerOptions? = nil) -> Publishers.ReceiveOn<Publishers.SubscribeOn<Deferred<Future<[Model], FileError>>, DispatchQueue>, S> where S : Scheduler

Discussion

You use the receive(on:options:) operator to receive results on a specific scheduler, such as performing UI work on the main run loop. In contrast with subscribe(on:options:), which affects upstream messages, receive(on:options:) changes the execution context of downstream messages. In the following example, requests to jsonPublisher are performed on backgroundQueue, but elements received from it are performed on RunLoop.main.

let jsonPublisher = MyJSONLoaderPublisher() // Some publisher.
let labelUpdater = MyLabelUpdateSubscriber() // Some subscriber that updates the UI.

jsonPublisher
    .subscribe(on: backgroundQueue)
    .receiveOn(on: RunLoop.main)
    .subscribe(labelUpdater)

Parameters

scheduler

The scheduler the publisher is to use for element delivery.
options
Scheduler options that customize the element delivery.
Returns

A publisher that delivers elements using the specified scheduler.

in your case it means

import SwiftUI
import Combine

enum FileError: Error {
    case someError
}

class ViewModel: ObservableObject {
    @Published var modelArray = [Model]()
    private var subscriptions = Set<AnyCancellable>()
    func readData() {
        DataSource()
            .readFromBundle(resource: "Sample", type: "json")
            .sink(receiveCompletion: { completion in
                print("Completion: \(completion)")
            }) { array in
                print("received value")
                self.modelArray = array
        }.store(in: &subscriptions)
    }
}
struct ContentView: View {
    @ObservedObject var viewModel: ViewModel

    var body: some View {
        VStack {
            List(self.viewModel.modelArray) { model in
                Text("\(model.name)")
            }
        }
        .onAppear {
            self.viewModel.readData()
        }
    }
}

struct Model: Codable, Identifiable {
    var id: Int
    var name: String
}

class DataSource {
    private let readQueue = DispatchQueue(label: "ReadQueue", qos: .default, attributes: .concurrent)

    func readFromBundle (resource: String, type:String) -> AnyPublisher<[Model], FileError> {
            Deferred {
                 Future { promise in
                    guard let url = Bundle.main.url(forResource: "Sample", withExtension: "json"),
                      let data = try? Data(contentsOf: url),
                      let modelArray = try? JSONDecoder().decode([Model].self, from: data)
                      else {
                        promise(.failure(.someError))
                        return
                    }
                      promise(.success(modelArray))
                }
            }
            .subscribe(on: readQueue)
            .receive(on: RunLoop.main)
           .eraseToAnyPublisher()
        }
}

which explain, why Asperi's solution works. The difference is, that there is not necessary to call .receive(on:) again in readData()

the difference between DispatchQueue.main and RunLoop.main are not significant in your example.


来源: stackexchange

问:
Python add quotes to comma-delimited string?
Im using python3,
How can i make this string :

```<code>a = "a,b"
</code>```

To:

```<code>a = "'a','b'"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Im using python3,
How can i make this string :

a = "a,b"

To:

a = "'a','b'"

Body:
>>> s = "a,b"
>>> ','.join(f"'{e}'" for e in s.split(','))
"'a','b'"


问:
Why the result of this program is 3 "born"?And 4 dead
This is main.cpp:

int main() {

    Person arr[2] = {
        Person(18,180),
        Person(20,173)
    };
    arr[0]+arr[1];

    return 0;
}
```

<p>This is Person.h:</p>

<pre class="lang-cpp prettyprint-override"><code>class Person
{
private:
    int age;
    int height;
public:
    Person(int age=20,int height=180);
    ~Person();
    void operator+(Person);
};
</code>```

And this is Person.cpp:

Person::Person(int age,int height) {
    (*this).age = age;
    (*this).height = height;
    cout << "I'm born.\n";
}

Person::~Person() {
    cout << "I'm dead.\n";
}

void Person::operator+(Person a) {
    Person result;
    result.age = (*this).age + a.age;
    result.height = (*this).height + a.height;
    cout << result.age << endl;
    cout << result.height << endl;
}
```

Why the result of this program is 3 "born"?And 4 dead?
What are the procedures of initializing the array of objects 'arr'?

答:
The missing born person is a clone! Note operator+ take an argument by value, so the copy constructor is called (the default one in this case). To see this add

```<code>Person::Person(const Person &p) {
    this->age = p.age;
    this->height = p.height;
    cout << "I'm a clone.\n";
}
</code>```

to your code - then it is clear why there are 4 people dead in the end. A better idea is you have your odd operator to have this signature to avoid copies and be explicit:

```<code>void Person::operator+(const Person &a) const;
</code>```

Also, no point in using *this when you have the arrow operator.

Body:
This is main.cpp:

int main() {

    Person arr[2] = {
        Person(18,180),
        Person(20,173)
    };
    arr[0]+arr[1];

    return 0;
}

This is Person.h:

class Person
{
private:
    int age;
    int height;
public:
    Person(int age=20,int height=180);
    ~Person();
    void operator+(Person);
};

And this is Person.cpp:

Person::Person(int age,int height) {
    (*this).age = age;
    (*this).height = height;
    cout << "I'm born.\n";
}

Person::~Person() {
    cout << "I'm dead.\n";
}

void Person::operator+(Person a) {
    Person result;
    result.age = (*this).age + a.age;
    result.height = (*this).height + a.height;
    cout << result.age << endl;
    cout << result.height << endl;
}

Why the result of this program is 3 "born"?And 4 dead?
What are the procedures of initializing the array of objects 'arr'?

Body:
The missing born person is a clone! Note operator+ take an argument by value, so the copy constructor is called (the default one in this case). To see this add

Person::Person(const Person &p) {
    this->age = p.age;
    this->height = p.height;
    cout << "I'm a clone.\n";
}

to your code - then it is clear why there are 4 people dead in the end. A better idea is you have your odd operator to have this signature to avoid copies and be explicit:

void Person::operator+(const Person &a) const;

Also, no point in using *this when you have the arrow operator.


问:
How to sort a mysql table in a specific way
I have the following table as a result of a query:

```<code>    SELECT f.id, f.parent_id, f.name, f.fullpath,
    FROM folders f
    WHERE fullpath LIKE CONCAT("%", 'fs-3', "%")
    ORDER BY fullpath ASC, name ASC;
</code>```

```<code>id      parent_id       name        fullpath
-----------------------------------------------------------------
fs-3    null            root        fs-3
fs-d    fs-3            test        fs-3/fs-d
fs-5    fs-d            test        fs-3/fs-d/fs-5
fs-g    fs-3            test3       fs-3/fs-g
fs-2    fs-g            test        fs-3/fs-g/fs-2
fs-s    fs-2            test        fs-3/fs-g/fs-2/fs-s
fs-y    fs-3            test2       fs-3/fs-y
fs-4    fs-y            test        fs-3/fs-y/fs-4
</code>```

The table is sorted by

```<code>ORDER BY fullpath ASC, name ASC
</code>```

The desired outcome is that name column gets sorted in a manner where test3 comes after test2 while keeping the fullpath sorting. But I don't know how to achieve this?

```<code>id      parent_id       name        fullpath
-----------------------------------------------------------------
fs-3    null            root        fs-3
fs-d    fs-3            test        fs-3/fs-d
fs-5    fs-d            test        fs-3/fs-d/fs-5
fs-y    fs-3            test2       fs-3/fs-y
fs-4    fs-y            test        fs-3/fs-y/fs-4
fs-g    fs-3            test3       fs-3/fs-g
fs-2    fs-g            test        fs-3/fs-g/fs-2
fs-s    fs-2            test        fs-3/fs-g/fs-2/fs-s
</code>```

答:
You can do it with conditional sorting:

```<code>select f.*
from folders f
where fullpath like concat("%", 'fs-3', "%")
order by
  case
    when exists (
      select 1 from folders
      where name = 'test2'
      and f.fullpath like concat(fullpath, '%')
    ) then 1
    when exists (
      select 1 from folders
      where name = 'test3'
      and f.fullpath like concat(fullpath, '%')
    ) then 2
  end,
  f.fullpath,
  f.name
</code>```

See the demo.

Results:

```<code>| id   | parent_id | name  | fullpath            |
| ---- | --------- | ----- | ------------------- |
| fs-3 | null      | root  | fs-3                |
| fs-d | fs-3      | test  | fs-3/fs-d           |
| fs-5 | fs-d      | test  | fs-3/fs-d/fs-5      |
| fs-y | fs-3      | test2 | fs-3/fs-y           |
| fs-4 | fs-y      | test  | fs-3/fs-y/fs-4      |
| fs-g | fs-3      | test3 | fs-3/fs-g           |
| fs-2 | fs-g      | test  | fs-3/fs-g/fs-2      |
| fs-s | fs-2      | test  | fs-3/fs-g/fs-2/fs-s |
</code>```

Body:
I have the following table as a result of a query:

    SELECT f.id, f.parent_id, f.name, f.fullpath,
    FROM folders f
    WHERE fullpath LIKE CONCAT("%", 'fs-3', "%")
    ORDER BY fullpath ASC, name ASC;

id      parent_id       name        fullpath
-----------------------------------------------------------------
fs-3    null            root        fs-3
fs-d    fs-3            test        fs-3/fs-d
fs-5    fs-d            test        fs-3/fs-d/fs-5
fs-g    fs-3            test3       fs-3/fs-g
fs-2    fs-g            test        fs-3/fs-g/fs-2
fs-s    fs-2            test        fs-3/fs-g/fs-2/fs-s
fs-y    fs-3            test2       fs-3/fs-y
fs-4    fs-y            test        fs-3/fs-y/fs-4

The table is sorted by

ORDER BY fullpath ASC, name ASC

The desired outcome is that name column gets sorted in a manner where test3 comes after test2 while keeping the fullpath sorting. But I don't know how to achieve this?

id      parent_id       name        fullpath
-----------------------------------------------------------------
fs-3    null            root        fs-3
fs-d    fs-3            test        fs-3/fs-d
fs-5    fs-d            test        fs-3/fs-d/fs-5
fs-y    fs-3            test2       fs-3/fs-y
fs-4    fs-y            test        fs-3/fs-y/fs-4
fs-g    fs-3            test3       fs-3/fs-g
fs-2    fs-g            test        fs-3/fs-g/fs-2
fs-s    fs-2            test        fs-3/fs-g/fs-2/fs-s

Body:
You can do it with conditional sorting:

select f.*
from folders f
where fullpath like concat("%", 'fs-3', "%")
order by
  case
    when exists (
      select 1 from folders
      where name = 'test2'
      and f.fullpath like concat(fullpath, '%')
    ) then 1
    when exists (
      select 1 from folders
      where name = 'test3'
      and f.fullpath like concat(fullpath, '%')
    ) then 2
  end,
  f.fullpath,
  f.name

See the demo.

Results:

| id   | parent_id | name  | fullpath            |
| ---- | --------- | ----- | ------------------- |
| fs-3 | null      | root  | fs-3                |
| fs-d | fs-3      | test  | fs-3/fs-d           |
| fs-5 | fs-d      | test  | fs-3/fs-d/fs-5      |
| fs-y | fs-3      | test2 | fs-3/fs-y           |
| fs-4 | fs-y      | test  | fs-3/fs-y/fs-4      |
| fs-g | fs-3      | test3 | fs-3/fs-g           |
| fs-2 | fs-g      | test  | fs-3/fs-g/fs-2      |
| fs-s | fs-2      | test  | fs-3/fs-g/fs-2/fs-s |


答: In the operator+ the second argument of the addition, which is the first parameter, is passed by value, and so is called the copy constructor (which is not redefined and so you are not taking track of the object build with it) in order to build it, and so at the end of the function call that object is destructed (and so this is your 4th "hidden" dead person)

Title: Why the result of this program is 3 "born"?And 4 dead


问:
Javascript Syntax Differences
What is the difference between these two?

```<code>collapse: function(fold)
{
...
...
}
</code>```

and

```<code>function collapse(fold)
{
...
...
}
</code>```

答:
The first one outside of the context of an object literal is a syntax error.

However, I believe you are asking about the difference between a function expression and a function declaration.

Your first one is a function expression. You assign an anonymous function to a variable. Its variable definition is hoisted to the top of its scope, but not the assignment of the function.

The second is the function declaration. Its entire body is hoisted to the top of the scope.

In general, a function expression is often used as it is more expressive. You can give it a name if you need to call it recursively (or for better detailed stack traces), but remember IE leaks this name to the outer scope.

Further Reading.

ContentLicense: CC BY-SA 3.0

Title: Javascript Syntax Differences

Body:
What is the difference between these two?

collapse: function(fold)
{
...
...
}

and

function collapse(fold)
{
...
...
}


问:
Django Form Wizard - Using an image formset for a related post model
So I'm using the Django Form Wizard to split a simplified PostForm. In one of the steps, visitors can upload different images related to the Post.

Within the done method for the SessionWizardView, I'm saving the instance first and then check for the images within the formset.

However I get the following error message;

save() prohibited to prevent data loss due to unsaved related object

I tried setting the related Post id for the formset but I'm missing something here, formsets are still something I can't really follow.. Any help is appreciated!

models.py

```<code>class Post(models.Model)
    title = models.CharField(max_length=200)
    description = models.TextField(max_length=1000)

    def __str__(self):
        return self.title

class Image(models.Model):
    post = models.ForeignKey('Post', on_delete=models.SET_NULL, null=True)
    file = models.ImageField(upload_to='images/', null=True, blank=True)
    alt = models.CharField(max_length=200, blank=True)
</code>```

views.py

```<code>FORMS = [
    ('title', PostCreateForm),
    ('image', ImageFormset)
]

TEMPLATES = {
    'title': 'post_form_title.html',
    'image': 'post_form_image.html'
}

class PostWizardView(SessionWizardView):
    form_list = FORMS
    file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'temp/'))

    def get_template_names(self):
        return [TEMPLATES[self.steps.current]]

    def done(self, form_list, form_dict, **kwargs):
        instance = Post()

        for form in form_list:
            instance = construct_instance(form, instance)
        instance.save()
        post_id = instance.pk

        if 'image' in form_dict:
            formset = form_dict['image']
            if formset.is_valid():
                formset.save(commit=False)
                for form in formset:
                    form.post = post_id
                    formset.save()
</code>```

forms.py

```<code>class PostCreateForm(forms.ModelForm):

    class Meta:
        model = Image
        fields = '__all__'

ImageFormset = inlineformset_factory(
    Post,
    Image,
    form = PostCreateForm,
    min_num=1,
    can_delete=True
)
</code>```

答:
You should save the individual forms as you loop through them:</p>

```<code>if formset.is_valid():
    for form in formset:
        if form.is_valid():
            f = form.save(commit=False)
            f.post = post_id
            f.save()
</code>```

Body:
So I'm using the Django Form Wizard to split a simplified PostForm. In one of the steps, visitors can upload different images related to the Post.

Within the done method for the SessionWizardView, I'm saving the instance first and then check for the images within the formset.

However I get the following error message;

save() prohibited to prevent data loss due to unsaved related object

I tried setting the related Post id for the formset but I'm missing something here, formsets are still something I can't really follow.. Any help is appreciated!

models.py

class Post(models.Model)
    title = models.CharField(max_length=200)
    description = models.TextField(max_length=1000)

    def __str__(self):
        return self.title

class Image(models.Model):
    post = models.ForeignKey('Post', on_delete=models.SET_NULL, null=True)
    file = models.ImageField(upload_to='images/', null=True, blank=True)
    alt = models.CharField(max_length=200, blank=True)

views.py

FORMS = [
    ('title', PostCreateForm),
    ('image', ImageFormset)
]

TEMPLATES = {
    'title': 'post_form_title.html',
    'image': 'post_form_image.html'
}

class PostWizardView(SessionWizardView):
    form_list = FORMS
    file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'temp/'))

    def get_template_names(self):
        return [TEMPLATES[self.steps.current]]

    def done(self, form_list, form_dict, **kwargs):
        instance = Post()

        for form in form_list:
            instance = construct_instance(form, instance)
        instance.save()
        post_id = instance.pk

        if 'image' in form_dict:
            formset = form_dict['image']
            if formset.is_valid():
                formset.save(commit=False)
                for form in formset:
                    form.post = post_id
                    formset.save()

forms.py

class PostCreateForm(forms.ModelForm):

    class Meta:
        model = Image
        fields = '__all__'

ImageFormset = inlineformset_factory(
    Post,
    Image,
    form = PostCreateForm,
    min_num=1,
    can_delete=True
)

Body:
You should save the individual forms as you loop through them:

if formset.is_valid():
    for form in formset:
        if form.is_valid():
            f = form.save(commit=False)
            f.post = post_id
            f.save()


问:
Google Ads interrupt the app. Slow down fps
I use AdView mAdView and the last updated libraries.

I placed the AdView into my layout (as shown in the examples):

```<code><com.google.android.gms.ads.AdView
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/adView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    ads:adSize="BANNER"
    ads:adUnitId="@string/banner_ad_unit_id">
</com.google.android.gms.ads.AdView>
</code>```

Then I identify it and try to load a new ad in the onCreate() method:

```<code>AdView mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
</code>```

But my layout has some animated objects. This animation is freezing (skipping some frames) while new ad is become visible.

We can't catch the same problem with the disabled Internet (it disables ads and not affect lags).

I'm trying to show the problem with my own record (GIF can't show that completely):

https://www.youtube.com/watch?v=adH2Mn79O7w

How can I remove ads' lags and make the user experience better?

答:
This is a known issue, which has been discussed many times on the net, is enough to search by the words "AdMob fps drop" and the like.

The root of the problem here, most likely, is that running AdMob requires significant resources, which is why the animation starts to stall. As one solution, you can show ads with some delay:

```<code>Handler handler = new Handler ();
handler.postDelayed (new Runnable () {
     @Override
     public void run () {
          AdRequest bannerRequest = new AdRequest.Builder (). Build ();
          mAdView.loadAd (bannerRequest);
     }
}, 2000);
</code>```

You can make the delay not fixed, but bind it to user actions. For example, start downloading ads the moment after the user has stopped scrolling the screen.

Another solution is to disable graphics acceleration for ads by manipulating the LAYER_TYPE_SOFTWARE property.

```<code>mAdView.setAdListener(new AdListener(){
    @Override
    public void onAdLoaded(){
        runOnWebView(mAdView, new WebViewAction(){
            @Override
            public void run(WebView view){
                view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
                view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
            }
        });
    }
});
</code>```

For such a solution, it is necessary to implement the following interface:

```<code>private void runOnWebView (View view, WebViewAction action) {
    if (view instanceof WebView){
        action.run((WebView)view);
        return;
    }

    if (view instanceof ViewGroup) {
        final ViewGroup parent = (ViewGroup)view;

        for (int i = 0; i < parent.getChildCount(); i++) {
            runOnWebView(parent.getChildAt(i), action);
        }
    }
}

private interface WebViewAction{
    void run(WebView view);
}
</code>```

Similarly, you can turn off the acceleration for some Activity:

```<code><activity
    android:hardwareAccelerated = "false"
    android:softwareAccelerated = "false" />
</code>```

Body:
I use AdView mAdView and the last updated libraries.

I placed the AdView into my layout (as shown in the examples):

<com.google.android.gms.ads.AdView
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/adView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    ads:adSize="BANNER"
    ads:adUnitId="@string/banner_ad_unit_id">
</com.google.android.gms.ads.AdView>

Then I identify it and try to load a new ad in the onCreate() method:

AdView mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);

But my layout has some animated objects. This animation is freezing (skipping some frames) while new ad is become visible.

We can't catch the same problem with the disabled Internet (it disables ads and not affect lags).

I'm trying to show the problem with my own record (GIF can't show that completely):

https://www.youtube.com/watch?v=adH2Mn79O7w

How can I remove ads' lags and make the user experience better?

Body:
This is a known issue, which has been discussed many times on the net, is enough to search by the words "AdMob fps drop" and the like.

The root of the problem here, most likely, is that running AdMob requires significant resources, which is why the animation starts to stall. As one solution, you can show ads with some delay:

Handler handler = new Handler ();
handler.postDelayed (new Runnable () {
     @Override
     public void run () {
          AdRequest bannerRequest = new AdRequest.Builder (). Build ();
          mAdView.loadAd (bannerRequest);
     }
}, 2000);

You can make the delay not fixed, but bind it to user actions. For example, start downloading ads the moment after the user has stopped scrolling the screen.

Another solution is to disable graphics acceleration for ads by manipulating the LAYER_TYPE_SOFTWARE property.

mAdView.setAdListener(new AdListener(){
    @Override
    public void onAdLoaded(){
        runOnWebView(mAdView, new WebViewAction(){
            @Override
            public void run(WebView view){
                view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
                view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
            }
        });
    }
});

For such a solution, it is necessary to implement the following interface:

private void runOnWebView (View view, WebViewAction action) {
    if (view instanceof WebView){
        action.run((WebView)view);
        return;
    }

    if (view instanceof ViewGroup) {
        final ViewGroup parent = (ViewGroup)view;

        for (int i = 0; i < parent.getChildCount(); i++) {
            runOnWebView(parent.getChildAt(i), action);
        }
    }
}

private interface WebViewAction{
    void run(WebView view);
}

Similarly, you can turn off the acceleration for some Activity:

<activity
    android:hardwareAccelerated = "false"
    android:softwareAccelerated = "false" />


问:
Calling shared_ptr object method
This seems like a pretty dumb question, so please bear with me. I am using smart pointers in place of raw pointers in my programs. I am advised against using raw pointers or mixing the two as much as possible. I understand that as well. I am also aware that pointers should be used only went necessary.

```<code>class Foo{
  private: int val;
  public:
    Foo(int v) :val(v){}
    int getvalue() const { return val; }
};

std::shared_ptr<Foo> foo = std::make_shared(Foo(10));

int v;

//Option I
v=foo->getvalue();

//Option II
v=foo.get()->getvalue();
</code>```

I feel option I is more correct as option II utilizes raw pointer. But using raw pointer may not hurt here as I am not allocating or deallocating.

Often I get confused with these two options. Which one is preferable? Are they just same? Thanks.

答:
There is no functional difference between

```<code>//Option I
v=foo->getvalue();
</code>```

And

```<code>//Option II
v=foo.get()->getvalue();
</code>```

But option II is more typing, so why?

Both constructs do exactly the same in this situation.

This has nothing to do with smart pointers vs raw pointers. The problem with raw pointers is purely with raw owning pointers. There's nothing wrong with raw non-ownining pointers.

Title: Calling shared_ptr object method

Body:
This seems like a pretty dumb question, so please bear with me. I am using smart pointers in place of raw pointers in my programs. I am advised against using raw pointers or mixing the two as much as possible. I understand that as well. I am also aware that pointers should be used only went necessary.

class Foo{
  private: int val;
  public:
    Foo(int v) :val(v){}
    int getvalue() const { return val; }
};

std::shared_ptr<Foo> foo = std::make_shared(Foo(10));

int v;

//Option I
v=foo->getvalue();

//Option II
v=foo.get()->getvalue();

I feel option I is more correct as option II utilizes raw pointer. But using raw pointer may not hurt here as I am not allocating or deallocating.

Often I get confused with these two options. Which one is preferable? Are they just same? Thanks.

Body:
There is no functional difference between

//Option I
v=foo->getvalue();

And

//Option II
v=foo.get()->getvalue();

But option II is more typing, so why?

Both constructs do exactly the same in this situation.

This has nothing to do with smart pointers vs raw pointers. The problem with raw pointers is purely with raw owning pointers. There's nothing wrong with raw non-ownining pointers.


问:
Why do I have to initialise variable?
My code is checking if a given string is in a certain format. The first char of the string has to be an uppercase letter and the rest of the string has to be any number that is from 1 to given dimension.

If the first char of the string contains a string from the alphabet array, then the code checks if the rest of the string contains a number from the numbers array. To be a valid coordinate both conditions must be true, if one of them is false it is not a valid coordinate. I want to return the boolean isValidCoordinate but however IntelliJ is telling me that I have to initialise isValid coordinate. Why do I have to initialise it, the boolean expression depends on the 'if' conditions.

Thanks.

```<code>public static boolean validCoordinate(String coordinate, int dimension) {
        boolean isValidCoordinate;
        String [] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
        int [] numbers = new int [dimension];
        int one = 1;
        for(int i = 0; i < dimension; i++){
            numbers[i] = one + i;
        }
        for(int i = 0; i < dimension; i++){
            if((Character.toString(coordinate.charAt(0))).contains(alphabet[i])) {
                for(int j = 0; j < dimension; j++) {
                    if ((coordinate.substring(1)).contains(Integer.toString(numbers[j]))) {
                        isValidCoordinate = true;
                    }
                    else {
                        isValidCoordinate = false;
                    }
                }

            }
            else {
                isValidCoordinate = false;
            }

        }

        return isValidCoordinate;
    }
</code>```

This is my final code:

```<code>public static boolean validCoordinate(String coordinate, int dimension) {
        boolean isValidCoordinate;
        String [] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
        int [] numbers = new int [dimension];
        int one = 1;
        for(int i = 0; i < dimension; i++){
            numbers[i] = one + i;
        }
        for(int i = 0; i < dimension; i++){
            if((Character.toString(coordinate.charAt(0))).contains(alphabet[i])) {
                for(int j = 0; j < dimension; j++) {
                    if ((coordinate.substring(1)).contains(Integer.toString(numbers[j]))) {
                        isValidCoordinate = true;
                    }
                    else {
                        isValidCoordinate = false;
                    }
                }

            }
            else {
                isValidCoordinate = false;
            }

        }

        return true;
    }
</code>```

答:
```<code>import java.util.regex.*;

public static boolean validCoordinate(String coordinate, int dimension)
{
    Pattern p = Pattern.compile("[A-Z]+");
    Matcher m = p.matcher(coordinate);
    return m.matches();
}
</code>```

Title: Why do I have to initialise variable?

Body:
My code is checking if a given string is in a certain format. The first char of the string has to be an uppercase letter and the rest of the string has to be any number that is from 1 to given dimension.

If the first char of the string contains a string from the alphabet array, then the code checks if the rest of the string contains a number from the numbers array. To be a valid coordinate both conditions must be true, if one of them is false it is not a valid coordinate. I want to return the boolean isValidCoordinate but however IntelliJ is telling me that I have to initialise isValid coordinate. Why do I have to initialise it, the boolean expression depends on the 'if' conditions.

Thanks.

public static boolean validCoordinate(String coordinate, int dimension) {
        boolean isValidCoordinate;
        String [] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
        int [] numbers = new int [dimension];
        int one = 1;
        for(int i = 0; i < dimension; i++){
            numbers[i] = one + i;
        }
        for(int i = 0; i < dimension; i++){
            if((Character.toString(coordinate.charAt(0))).contains(alphabet[i])) {
                for(int j = 0; j < dimension; j++) {
                    if ((coordinate.substring(1)).contains(Integer.toString(numbers[j]))) {
                        isValidCoordinate = true;
                    }
                    else {
                        isValidCoordinate = false;
                    }
                }

            }
            else {
                isValidCoordinate = false;
            }

        }

        return isValidCoordinate;
    }

This is my final code:

public static boolean validCoordinate(String coordinate, int dimension) {
        boolean isValidCoordinate;
        String [] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
        int [] numbers = new int [dimension];
        int one = 1;
        for(int i = 0; i < dimension; i++){
            numbers[i] = one + i;
        }
        for(int i = 0; i < dimension; i++){
            if((Character.toString(coordinate.charAt(0))).contains(alphabet[i])) {
                for(int j = 0; j < dimension; j++) {
                    if ((coordinate.substring(1)).contains(Integer.toString(numbers[j]))) {
                        isValidCoordinate = true;
                    }
                    else {
                        isValidCoordinate = false;
                    }
                }

            }
            else {
                isValidCoordinate = false;
            }

        }

        return true;
    }


答:
Raw pointers are not the enemy. We can't write any useful program in C++ without them in one shape or form. The problem is owning raw pointers. They don't have a clear ownership semantic associated with their type, and so it fall to the programmer to do the arduous task of managing the lifetime by hand. Don't fear passing a raw pointer around as a handle, if you need to.

Which brings us to the next point. Both methods you demonstrated rely on raw pointers. An overloaded operator-> must return a raw pointer (eventually) for us to apply member access on the object. In essence, the first version is equivalent to

```<code>v = foo.operator->() -> getvalue();
</code>```

It operates exactly the same as the second form, just with syntactic sugar on top.

You should prefer the first form because it is shorter and readable. But it doesn't avoid raw pointers, that's impossible to avoid.

Title: Calling shared_ptr object method

Body:
Raw pointers are not the enemy. We can't write any useful program in C++ without them in one shape or form. The problem is owning raw pointers. They don't have a clear ownership semantic associated with their type, and so it fall to the programmer to do the arduous task of managing the lifetime by hand. Don't fear passing a raw pointer around as a handle, if you need to.

Which brings us to the next point. Both methods you demonstrated rely on raw pointers. An overloaded operator-> must return a raw pointer (eventually) for us to apply member access on the object. In essence, the first version is equivalent to

v = foo.operator->() -> getvalue();

It operates exactly the same as the second form, just with syntactic sugar on top.

You should prefer the first form because it is shorter and readable. But it doesn't avoid raw pointers, that's impossible to avoid.


答: Both option will probably get the same result in the assembled code. The first option foo->getvalue() is the prefered option, because this gives a better readability.

Title: Calling shared_ptr object method


问:
Auto-run a command on saving in Sublime Text
Is it possible to run eslint automatically when I save either a .js or .jsx file in Sublime Text?

I'm using the ESLint sublime package right now but I have to manually run it each time using Cmd + Option + e.

Thanks!

答:
Yes this can be done with a simple event driven plugin like the one I've written below.

The plugin has been tested but not with the eslint command since I did not want to install that package. Clearly any command could be run instead of eslint in the plugin's run_command("eslint") line. If the desired command takes args then they can be specified like this: run_command("command", {"arg_1": val, "arg_2": val}).

The on_post_save_async(self, view) method (in my plugin below) will be called after the view, i.e. the active buffer, has been saved - note that this includes auto-saves. on_post_save_async() runs in a separate thread and does not block the application. You could alter the plugin to use a similar method depending of whether you want eslint called before or after the file save has taken place and whether the method should block the application or be run in its own non-blocking thread. These are the 4 alternatives:

on_pre_save(self, view): Called just before a view is saved. It blocks the application until the method returns.

on_pre_save_async(self, view): Called just before a view is saved. Runs in a separate thread, and does not block the application.

on_post_save(self, view): Called after a view has been saved. It blocks the application until the method returns.

on_post_save_async(self, view): Called after a view has been saved. Runs in a separate thread, and does not block the application. [Currently used in the plugin below.]

The Sublime Text EventListener documentation is located here - there are on load methods too.

Save the plugin below somewhere in in your Sublime Text packages hierarchy with a .py extension. e.g. ~/.config/sublime-text-3/Packages/User/AutoRunESLintOnSave.py and it should work straight away.

import sublime, sublime_plugin

class AutoRunESLintOnSave(sublime_plugin.EventListener):
    """ A class to listen for events triggered by ST. """

    def on_post_save_async(self, view):
        """
        This is called after a view has been saved. It runs in a separate thread
        and does not block the application.
        """

        file_path = view.file_name()
        if not file_path:
            return
        NOT_FOUND = -1
        pos_dot = file_path.rfind(".")
        if pos_dot == NOT_FOUND:
            return
        file_extension = file_path[pos_dot:]
        if file_extension.lower() in [".js", ".jsx"]:
            view.window().run_command("eslint")

            # Slight variations are needed for an ApplicationCommand,
            # a WindowCommand, or a TextCommand.
            #
            # view.run_command("text_command")
            # view.window().run_command("window_command")
            # sublime.run_command("application_command")
            #
            # Need args? Use this:
            #
            # view.run_command("command", {"arg_1": val, "arg_2": val})
```

<p>Instead of using file extensions to trigger running the <code>eslint</code> command you could use the buffer's syntax, the code is even more concise.</p>

<pre class="lang-py prettyprint-override"><code>    def on_post_save_async(self, view):
        """ Syntax version. """

        current_syntax = view.settings().get("syntax")
        if ("JavaScript.sublime-syntax" in current_syntax
                or "JSX.sublime-syntax" in current_syntax):
            view.window().run_command("eslint")

        # You could, of course, use an exact match:
        #
        # current_syntax = view.settings().get("syntax")
        # if current_syntax == "Packages/JavaScript/JavaScript.sublime-syntax":
        #     view.window().run_command("eslint")
        #
        # Run `view.settings().get("syntax")` in the console for the active syntax path.
</code>```

Body:
Yes this can be done with a simple event driven plugin like the one I've written below.

The plugin has been tested but not with the eslint command since I did not want to install that package. Clearly any command could be run instead of eslint in the plugin's run_command("eslint") line. If the desired command takes args then they can be specified like this: run_command("command", {"arg_1": val, "arg_2": val}).

The on_post_save_async(self, view) method (in my plugin below) will be called after the view, i.e. the active buffer, has been saved - note that this includes auto-saves. on_post_save_async() runs in a separate thread and does not block the application. You could alter the plugin to use a similar method depending of whether you want eslint called before or after the file save has taken place and whether the method should block the application or be run in its own non-blocking thread. These are the 4 alternatives:

on_pre_save(self, view): Called just before a view is saved. It blocks the application until the method returns.

on_pre_save_async(self, view): Called just before a view is saved. Runs in a separate thread, and does not block the application.

on_post_save(self, view): Called after a view has been saved. It blocks the application until the method returns.

on_post_save_async(self, view): Called after a view has been saved. Runs in a separate thread, and does not block the application. [Currently used in the plugin below.]

The Sublime Text EventListener documentation is located here - there are on load methods too.

Save the plugin below somewhere in in your Sublime Text packages hierarchy with a .py extension. e.g. ~/.config/sublime-text-3/Packages/User/AutoRunESLintOnSave.py and it should work straight away.

import sublime, sublime_plugin

class AutoRunESLintOnSave(sublime_plugin.EventListener):
    """ A class to listen for events triggered by ST. """

    def on_post_save_async(self, view):
        """
        This is called after a view has been saved. It runs in a separate thread
        and does not block the application.
        """

        file_path = view.file_name()
        if not file_path:
            return
        NOT_FOUND = -1
        pos_dot = file_path.rfind(".")
        if pos_dot == NOT_FOUND:
            return
        file_extension = file_path[pos_dot:]
        if file_extension.lower() in [".js", ".jsx"]:
            view.window().run_command("eslint")

            # Slight variations are needed for an ApplicationCommand,
            # a WindowCommand, or a TextCommand.
            #
            # view.run_command("text_command")
            # view.window().run_command("window_command")
            # sublime.run_command("application_command")
            #
            # Need args? Use this:
            #
            # view.run_command("command", {"arg_1": val, "arg_2": val})

Instead of using file extensions to trigger running the eslint command you could use the buffer's syntax, the code is even more concise.

    def on_post_save_async(self, view):
        """ Syntax version. """

        current_syntax = view.settings().get("syntax")
        if ("JavaScript.sublime-syntax" in current_syntax
                or "JSX.sublime-syntax" in current_syntax):
            view.window().run_command("eslint")

        # You could, of course, use an exact match:
        #
        # current_syntax = view.settings().get("syntax")
        # if current_syntax == "Packages/JavaScript/JavaScript.sublime-syntax":
        #     view.window().run_command("eslint")
        #
        # Run `view.settings().get("syntax")` in the console for the active syntax path.


问:
"code ." is not working in on the command line for Visual Studio Code on OS X/Mac
The command code . doesn't work in this manual.

All the other steps before that worked. How can I call the Visual Studio Code in an OS X terminal?

```<code>pwd
</code>```

/Users/mona/nodejs/myExpressApp

```<code>code .
</code>```

-bash: code: command not found

I ended up opening it from within Visual Code Studio by changing the workspace, but why won't that command code . part work?

答:
I've tried the "Install add code" command to PATH with Visual Studio Code's command panel, but it's disabled after restarting Bash. If you want it be consolidated, just create a code file in your PATH;
I create a code file in usr/local/bin and add

```<code>#!/usr/bin/env bash
function realpath() { python -c "import os,sys;print(os.path.realpath(sys.argv[1]))" "$0"; }
CONTENTS="/Applications/Visual Studio Code.app/Contents"
ELECTRON="$CONTENTS/MacOS/Electron"
CLI="$CONTENTS/Resources/app/out/cli.js"
ELECTRON_RUN_AS_NODE=1 "$ELECTRON" "$CLI" "$@"
exit $?
</code>```

Just replace this CONTENTS with your Visual Studio Code's installed path. And don't forget make it executable with chmod +x /usr/local/bin/code.

Body:
The command code . doesn't work in this manual.

All the other steps before that worked. How can I call the Visual Studio Code in an OS X terminal?

pwd

/Users/mona/nodejs/myExpressApp

code .

-bash: code: command not found

I ended up opening it from within Visual Code Studio by changing the workspace, but why won't that command code . part work?

Body:
I've tried the "Install add code" command to PATH with Visual Studio Code's command panel, but it's disabled after restarting Bash. If you want it be consolidated, just create a code file in your PATH;
I create a code file in usr/local/bin and add

#!/usr/bin/env bash
function realpath() { python -c "import os,sys;print(os.path.realpath(sys.argv[1]))" "$0"; }
CONTENTS="/Applications/Visual Studio Code.app/Contents"
ELECTRON="$CONTENTS/MacOS/Electron"
CLI="$CONTENTS/Resources/app/out/cli.js"
ELECTRON_RUN_AS_NODE=1 "$ELECTRON" "$CLI" "$@"
exit $?

Just replace this CONTENTS with your Visual Studio Code's installed path. And don't forget make it executable with chmod +x /usr/local/bin/code.


问:
Properties of nested static class
I have this nested static class

```<code>public static class UserRoles
{
    public static class Administrator
    {
        public static string Code => "ADMIN";
        public static string Title => "Administrator";
    }

    public static class ClientUser
    {
        public static string Code => "CU";
        public static string Title => "Client User";
    }

    public static class Driver
    {
        public static string Code => "DR";
        public static string Title => "Driver";
    }
}
</code>```

I am trying iterating over the properties of UserRoles but failed miserably. I've tried using System.Reflection which i think is the only suitable approach for the problem.

I've already tried using GetFields with bindings and GetProperties but unfortunately it is not working.

```<code>var fields = myType.GetFields(BindingFlags.Static | BindingFlags.NonPublic);
</code>```

I've checked other questions already but i don't find any that is specific to this very basic and common case. Please let me know if this is a duplicate of anything.

Any help would be truly appreciated.

答:
You can use GetNestedTypes method for that

var userRoles = typeof(UserRoles).GetNestedTypes().SelectMany(t => t.GetProperties());
```

<p>The code above returns enumeration of properties for every nested class in <code>UserRoles</code> class.</p>

<p>But if you want to store some information like set of keys and values, <code>Dictionary<TKey,TValue></code> is better choice, rather than static nested classes. Have a look at example below</p>

<pre class="lang-cs prettyprint-override"><code>public enum UserType
{
    Administrator,
    ClientUser,
    Driver
}

public class UserInfo
{
    public string Code { get; set; }
    public string Title { get; set; }
}
...
var roles = new Dictionary<UserType, UserInfo>
{
    { UserType.Administrator, new UserInfo { Code = "ADMIN", Title = "Administrator" } },
    { UserType.Driver, new UserInfo { Code = "DR", Title = "Driver" } }
    //and so on
};
//get admin title
var title = roles[UserType.Administrator].Title;
</code>```

Title: Properties of nested static class

Body:
I have this nested static class

public static class UserRoles
{
    public static class Administrator
    {
        public static string Code => "ADMIN";
        public static string Title => "Administrator";
    }

    public static class ClientUser
    {
        public static string Code => "CU";
        public static string Title => "Client User";
    }

    public static class Driver
    {
        public static string Code => "DR";
        public static string Title => "Driver";
    }
}

I am trying iterating over the properties of UserRoles but failed miserably. I've tried using System.Reflection which i think is the only suitable approach for the problem.

I've already tried using GetFields with bindings and GetProperties but unfortunately it is not working.

var fields = myType.GetFields(BindingFlags.Static | BindingFlags.NonPublic);

I've checked other questions already but i don't find any that is specific to this very basic and common case. Please let me know if this is a duplicate of anything.

Any help would be truly appreciated.

Body:
You can use GetNestedTypes method for that

var userRoles = typeof(UserRoles).GetNestedTypes().SelectMany(t => t.GetProperties());

The code above returns enumeration of properties for every nested class in UserRoles class.

But if you want to store some information like set of keys and values, Dictionary<TKey,TValue> is better choice, rather than static nested classes. Have a look at example below

public enum UserType
{
    Administrator,
    ClientUser,
    Driver
}

public class UserInfo
{
    public string Code { get; set; }
    public string Title { get; set; }
}
...
var roles = new Dictionary<UserType, UserInfo>
{
    { UserType.Administrator, new UserInfo { Code = "ADMIN", Title = "Administrator" } },
    { UserType.Driver, new UserInfo { Code = "DR", Title = "Driver" } }
    //and so on
};
//get admin title
var title = roles[UserType.Administrator].Title;


答:
Let;s count together the number of constructor and destructor calls.

In thsi declaration of an array

```<code>Person arr[2] = {
    Person(18,180),
    Person(20,173)
};
</code>```

the constructor is called two times because two objects of the class are being created. Here is taken place the elision of calls of the copy constructor.

In this call

```<code>arr[0]+arr[1];
</code>```

there is used the following function

```<code>void Person::operator+(Person a) {
    Person result;
    result.age = (*this).age + a.age;
    result.height = (*this).height + a.height;
    cout << result.age << endl;
    cout << result.height << endl;
}
</code>```

The argument arr[1] is passed to the function by value calling the implicitly defined copy constructor. So a third object of the class is created.

Within the function there is created a fourth object in this declaration

```<code>    Person result;
</code>```

So four objects were created three of them using the constructor with parameters and one with the copy constructor. So as a result four destructors were also called.

The operator should be declared and defined at least like

```<code>Person Person::operator +( const Person &a) const {
    return Person( age + a.age, height + a.height );
}
</code>```

On the other hand it is better to make the constructor explicit. For example

```<code>explicit Person(int age=20,int height=180) : age( age ), height( height )
{
}
</code>```

Body:
This is main.cpp:

int main() {

    Person arr[2] = {
        Person(18,180),
        Person(20,173)
    };
    arr[0]+arr[1];

    return 0;
}

This is Person.h:

class Person
{
private:
    int age;
    int height;
public:
    Person(int age=20,int height=180);
    ~Person();
    void operator+(Person);
};

And this is Person.cpp:

Person::Person(int age,int height) {
    (*this).age = age;
    (*this).height = height;
    cout << "I'm born.\n";
}

Person::~Person() {
    cout << "I'm dead.\n";
}

void Person::operator+(Person a) {
    Person result;
    result.age = (*this).age + a.age;
    result.height = (*this).height + a.height;
    cout << result.age << endl;
    cout << result.height << endl;
}

Why the result of this program is 3 "born"?And 4 dead?
What are the procedures of initializing the array of objects 'arr'?

Body:
Let;s count together the number of constructor and destructor calls.

In thsi declaration of an array

Person arr[2] = {
    Person(18,180),
    Person(20,173)
};

the constructor is called two times because two objects of the class are being created. Here is taken place the elision of calls of the copy constructor.

In this call

arr[0]+arr[1];

there is used the following function

void Person::operator+(Person a) {
    Person result;
    result.age = (*this).age + a.age;
    result.height = (*this).height + a.height;
    cout << result.age << endl;
    cout << result.height << endl;
}

The argument arr[1] is passed to the function by value calling the implicitly defined copy constructor. So a third object of the class is created.

Within the function there is created a fourth object in this declaration

    Person result;

So four objects were created three of them using the constructor with parameters and one with the copy constructor. So as a result four destructors were also called.

The operator should be declared and defined at least like

Person Person::operator +( const Person &a) const {
    return Person( age + a.age, height + a.height );
}

On the other hand it is better to make the constructor explicit. For example

explicit Person(int age=20,int height=180) : age( age ), height( height )
{
}


问:
Chefspec: override attribute doesn't work
I'm trying to check my spec test with bundle exec rspec for the following test

```<code>require 'spec_helper'

describe 'my_recipe::default' do
  windows_platforms = {
    windows: %w(2008R2 2012 2012R2 2016 2019)
  }

  windows_platforms.each do |platform, versions|
    versions.each do |version|
      context "When all attributes are default, on #{platform} #{version}" do
        let(:chef_run) do
          runner = ChefSpec::ServerRunner.new(platform: platform.to_s, version: version) do |node|
            node.override['domain'] = 'mydomain.com'
          end
          runner.converge(described_recipe)
        end

        it 'converges successfully' do
          expect { chef_run }.to_not raise_error
        end
      end
    end
  end
end
</code>```

Here's example of my default attribute file:

```<code>default['wsus'] =
  case node['domain']
  when 'mydomain.com'
    "do something"
  else
    raise 'Domain cannot be determined.'
  end
</code>```

From what I understand 'mydomain.com' should be assigned as default['domain'] but seems like this isn't the case.

Here's the error I get:

```<code>expected no Exception, got #<RuntimeError: Domain cannot be determined.> with backtrace:
</code>```

Does anyone have suggestion why the test won't take the overridden attribute?

p.s. If I'm not making sense, please excuse me. This is my first post on stackoverflow :(

答:
Your code is well, and it should be working as expected with many other attributes, but not domain. Point is - domain is special - it is automatic attribute set by Ohai (or in test case by Fauxhai) and it has maximum priority, which cannot be overwritten by override attribute. To mock automatic attributes you need automatic key.

```<code>runner = ChefSpec::ServerRunner.new(platform: platform.to_s, version: version) do |node|
  node.automatic['domain'] = 'mydomain.com'
end
</code>```

The whole list of automatic attributes is available in Chef docs on Ohai.

Body:
I'm trying to check my spec test with bundle exec rspec for the following test

require 'spec_helper'

describe 'my_recipe::default' do
  windows_platforms = {
    windows: %w(2008R2 2012 2012R2 2016 2019)
  }

  windows_platforms.each do |platform, versions|
    versions.each do |version|
      context "When all attributes are default, on #{platform} #{version}" do
        let(:chef_run) do
          runner = ChefSpec::ServerRunner.new(platform: platform.to_s, version: version) do |node|
            node.override['domain'] = 'mydomain.com'
          end
          runner.converge(described_recipe)
        end

        it 'converges successfully' do
          expect { chef_run }.to_not raise_error
        end
      end
    end
  end
end

Here's example of my default attribute file:

default['wsus'] =
  case node['domain']
  when 'mydomain.com'
    "do something"
  else
    raise 'Domain cannot be determined.'
  end

From what I understand 'mydomain.com' should be assigned as default['domain'] but seems like this isn't the case.

Here's the error I get:

expected no Exception, got #<RuntimeError: Domain cannot be determined.> with backtrace:

Does anyone have suggestion why the test won't take the overridden attribute?

p.s. If I'm not making sense, please excuse me. This is my first post on stackoverflow :(

Body:
Your code is well, and it should be working as expected with many other attributes, but not domain. Point is - domain is special - it is automatic attribute set by Ohai (or in test case by Fauxhai) and it has maximum priority, which cannot be overwritten by override attribute. To mock automatic attributes you need automatic key.

runner = ChefSpec::ServerRunner.new(platform: platform.to_s, version: version) do |node|
  node.automatic['domain'] = 'mydomain.com'
end

The whole list of automatic attributes is available in Chef docs on Ohai.


问:
Wait for image to be fully loaded before displayed on page?
I am designing a website for a client and am trying to figure out how to tell the current browser viewing the page to wait until the background image is fully loaded before it is displayed on the page. It is a large background image (bytes-wise) and would like it to load once loaded. I also want to do the exact same with the logo, but am stumped.

To be quite honest with all of you, I know very little JavaScript and jQuery, which is why I ask, please someone help me it would make the page a lot more attractive. The reason why I stated that above is because I know this may only be done in JavaScript.

答:
What comes to mind without actually used or tested it is wrapping the image. I'll use jQuery for the sample

```<code><div class="loading"><img/></div>
</code>```

CSS could be

```<code>.loading { display: inline-block; }
.ie6 .loading, .ie7 .loading { display: inline; } /* these could be set by http://www.modernizr.com/ */
.loading img {
     visibility: hidden;
     background: url('path/to/loading.gif') center center no-repeat transparent;
     vertical-align: bottom; /* or display: block; to kill the inline white space */
}
</code>```

JavaScript (jQuery)

```<code>  $(function(){
    $('.loading img').load(function(){
         $(this).css('visibility','visible');
    });
   });
</code>```

Body:
What comes to mind without actually used or tested it is wrapping the image. I'll use jQuery for the sample

<div class="loading"><img/></div>

CSS could be

.loading { display: inline-block; }
.ie6 .loading, .ie7 .loading { display: inline; } /* these could be set by http://www.modernizr.com/ */
.loading img {
     visibility: hidden;
     background: url('path/to/loading.gif') center center no-repeat transparent;
     vertical-align: bottom; /* or display: block; to kill the inline white space */
}

JavaScript (jQuery)

  $(function(){
    $('.loading img').load(function(){
         $(this).css('visibility','visible');
    });
   });


问:
jQuery coundown of days not working in Edge
I have written a small function to display the number of days left between a date and today. It's working in all browsers except Edge, where its returning NaN.

I originally thought it could be due to Date.parse, but this doesn't seem to be an issue in Edge, elsewhere.  Can anyone see what the issue could be?

function countdown() {
  var endTime = new Date("23 May 2020 13:00 GMT+01:00");
  endTime = (Date.parse(endTime) / 1000);

  var now = new Date();
  now = (Date.parse(now) / 1000);

  var timeLeft = endTime - now;
  var days = Math.floor(timeLeft / 86400);
  $(".to-go span").html(days);
};
countdown();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="to-go"><span></span></div></code>```

Here is a JS fiddle: https://jsfiddle.net/yg6weqs4/2/

答:
The issue in Edge is because it cannot parse the "23 May 2020 13:00 GMT+01:00" string to a date. I'd suggest changing this to an ISO8601 formatted date string, eg:

```<code>var endTime = new Date("2020-05-23T13:00:00+01:00");
</code>```

Working example

Body:
I have written a small function to display the number of days left between a date and today. It's working in all browsers except Edge, where its returning NaN.

I originally thought it could be due to Date.parse, but this doesn't seem to be an issue in Edge, elsewhere.  Can anyone see what the issue could be?

function countdown() {
  var endTime = new Date("23 May 2020 13:00 GMT+01:00");
  endTime = (Date.parse(endTime) / 1000);

  var now = new Date();
  now = (Date.parse(now) / 1000);

  var timeLeft = endTime - now;
  var days = Math.floor(timeLeft / 86400);
  $(".to-go span").html(days);
};
countdown();

Here is a JS fiddle: https://jsfiddle.net/yg6weqs4/2/

Body:
The issue in Edge is because it cannot parse the "23 May 2020 13:00 GMT+01:00" string to a date. I'd suggest changing this to an ISO8601 formatted date string, eg:

var endTime = new Date("2020-05-23T13:00:00+01:00");

Working example


问:
C++ double free or corruption(out)
I came across this error when I was using iterators with vector STL.

Code:-

```<code>#include <iostream>
#include <vector>

void print_vec(std::vector<int> vec)
{
    auto itr = vec.begin();
    while (itr != vec.end())
        std::cout << *itr++ << " ";
    std::cout << std::endl;
}

int main(int argc, char* argv[])
{
    std::vector<int> vals = { 1, 2, 3, 4, 5, 6 };
    print_vec(vals);
    auto it = vals.begin();
    vals.insert(it, 100);
    print_vec(vals);
    it += 4;
    std::cout << *it << "\n";
    vals.insert(it, 200);
    print_vec(vals);
    return 0;
}
</code>```

Output:-

```<code>1 2 3 4 5 6
100 1 2 3 4 5 6
5
0 100 1 2 3 4 5 6
double free or corruption (out)
Aborted (core dumped)
</code>```

I do not understand why this is happening: is it an issue with the iterator after the vector is modified? I think that my intuition regarding iterators is flawed.

答:
...is it an issue with the iterator after the vector is modified?

Yes!

From the cppreference page on std::vector.insert() (bolding mine):

Causes reallocation if the new size() is greater than the old
  capacity(). If the new size() is greater than capacity(), all
  iterators and references are invalidated. Otherwise, only the
  iterators and references before the insertion point remain valid. The
  past-the-end iterator is also invalidated.

Title: C++ double free or corruption(out)

Body:
I came across this error when I was using iterators with vector STL.

Code:-

#include <iostream>
#include <vector>

void print_vec(std::vector<int> vec)
{
    auto itr = vec.begin();
    while (itr != vec.end())
        std::cout << *itr++ << " ";
    std::cout << std::endl;
}

int main(int argc, char* argv[])
{
    std::vector<int> vals = { 1, 2, 3, 4, 5, 6 };
    print_vec(vals);
    auto it = vals.begin();
    vals.insert(it, 100);
    print_vec(vals);
    it += 4;
    std::cout << *it << "\n";
    vals.insert(it, 200);
    print_vec(vals);
    return 0;
}

Output:-

1 2 3 4 5 6
100 1 2 3 4 5 6
5
0 100 1 2 3 4 5 6
double free or corruption (out)
Aborted (core dumped)

I do not understand why this is happening: is it an issue with the iterator after the vector is modified? I think that my intuition regarding iterators is flawed.


问:
Sorting array alphabetically with number
```<code>myArray = [Step 6, Step 12, Step 5, Step 14, Step 4, Step 11, Step 16, Step 9,
Step 3, Step 13, Step 8, Step 2, Step 10, Step 7, Step 1, Step 15]
</code>```

How can I sort this array above in this way?

```<code>[Step 1, Step 2, Step 3, Step 4, ....]
</code>```

I used this function in swift sort(&myArray,{ $0 < $1 }) but it was sorted this way

```<code>[Step 1, Step 10, Step 11, Step 12, Step 13, Step 14, Step 15, Step 16, Step 2,
 Step 3, Step 4, Step 5, Step 6, Step 7, Step 8, Step 9]
</code>```

答:
let myArray = ["Step 6", "Step 12", "Step 10"]

let sortedArray = myArray.sorted(by: { x, y in
        return x.field.name.compare(y.field.name, options: .numeric, range: nil, locale: nil) == .orderedAscending
       })

Body:
myArray = [Step 6, Step 12, Step 5, Step 14, Step 4, Step 11, Step 16, Step 9,
Step 3, Step 13, Step 8, Step 2, Step 10, Step 7, Step 1, Step 15]

How can I sort this array above in this way?

[Step 1, Step 2, Step 3, Step 4, ....]

I used this function in swift sort(&myArray,{ $0 < $1 }) but it was sorted this way

[Step 1, Step 10, Step 11, Step 12, Step 13, Step 14, Step 15, Step 16, Step 2,
 Step 3, Step 4, Step 5, Step 6, Step 7, Step 8, Step 9]


问:
Core Data Entity Unique Constraint Does Not Work
I am trying to set a constraint in core data with the new Entity Constraints inspector (To make the name of the item unique).  All that I've read says it's pretty simple - Set the constraint and handle the error. I don't get any errors and can add the same entry as many times as I want.

The app does require IOS 9.0, Xcode tools requirement is set to 7.0

The constraint, category1Name, is a String.

My addItem code is:

```<code>func addNewRecord() {

    //check to be sure the entry is not empty
    if (categoryTextField.text == "") {

        //prompt requiring a name
        let ac = UIAlertController(title: nil, message: "Name Required", preferredStyle: .Alert)
        ac.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
        self.presentViewController(ac, animated: true, completion: nil)

    } else {

    let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName("Category1", inManagedObjectContext: kAppDelegate.managedObjectContext) as! Category1

    newManagedObject.category1Name = categoryTextField.text
    newManagedObject.category1Description = categoryTextView.text

    //bunch more items...

    //save it
    kAppDelegate.saveContext()
    makeEntryFieldsEnabledNO()
    performSegueWithIdentifier("unwindToCategoriesTableViewController", sender: self)

    }//if  else

}//addNewRecord
</code>```

The AppDelegate save is standard:

```<code>func saveContext () {
    if managedObjectContext.hasChanges {
        do {
            try managedObjectContext.save()
        } catch {

            //insert your standard error alert stuff here
            let nserror = error as NSError
            print("From the print line: Unresolved error \(nserror), \(nserror.userInfo)")

            abort()
        }//do catch
    }//if moc
}//saveContext
</code>```

Here's the Core Data constraint:

This app is iCloud enabled.

The managedObjectContext merge policy is set to NSMergeByPropertyObjectTrumpMergePolicy

```<code>lazy var managedObjectContext: NSManagedObjectContext = {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
    let coordinator = self.persistentStoreCoordinator
    var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
    managedObjectContext.persistentStoreCoordinator = coordinator
    managedObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
    return managedObjectContext

}()//var managedObjectContext
</code>```

Any guidance would be appreciated.

答:
It would appear Apple have finally fixed the crazy Xcode problem where changes you make in a data model file don't actually change.

Putting that aside, the current formula seems to be:

in your core data singleton ...

```<code>    container = NSPersistentContainer(name: _nom)

    // during development, right HERE likely delete the sql database file
    // and start fresh, as described here stackoverflow.com/a/60040554/294884

    container.loadPersistentStores { storeDescription, error in
        if let error = error {
            print("\n ERROR LOADING STORES! \(error) \n")
        }
        else {
            print("\n  STORES LOADED! \(storeDescription) \n")
        }

        self.container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
        self.container.viewContext.automaticallyMergesChangesFromParent = true
    }
</code>```

You must use merge policy and automatically merges.

Then in your data model file

Don't bother unless every relationship has an inverse, with

"to one or many" correctly set

and (almost certainly, except in very unusual source data) your unique id for each entity is indicated as a constraint

Then when you add new data, you must

use the new background context supplied by the handy core data function which does that

so, never try to make your own separate thread

double-check you have done (1) and (2) !

when you do add a few entities, you must do that inside a perform

and when you have finished adding entities (ie on the new thread) you must while still in the perform ...

do a performAndWait which does two things

save the new items (on the new child thread), and then

save the new items (on the main view thread)

naturally for both 7 and 8, you have to check .hasChanges before saving

Easy right?

So something like

```<code>let pm = core.container.newBackgroundContext()
pm.perform {
    for onePerson in someNewData {
        ... create your new CDPerson entity ...
    }
    pm.bake()
}
</code>```

Note that the bake routine is within the perform block,

and it looks like this:

```<code>func bake() {
    self.performAndWait {
        if self.hasChanges {
            do {
                try self.save()
            }
            catch {
                print("bake disaster type 1 \(error)")
            }
        }

        // OPTIONALLY, SEE BELOW
        if core.container.viewContext.hasChanges {
            do {
                try core.container.viewContext.save()
            }
            catch {
                print("bake disaster type 2 \(error)")
            }
        }
        // OPTIONALLY, SEE BELOW
    }
}
</code>```

To be clear, notice the pm.bake ... in the function bake(), the self in the first half is indeed that newBackgroundContext which is created for the loop inside the perform.

Note that these days you don't even need to save to the main context

Nowadays automaticallyMergesChangesFromParent seems to work perfectly, if you "do everything in the long list above".

• In the bake above, add a couple print lines to see what is saved to the viewContext. You'll see that nothing, at all, is ever saved. It's all done properly by the child/whatever relationships in the engine

• So in fact, in reality you can just omit that passage of the code. All you have to do is

```<code>func bake() {
    self.performAndWait {
        if self.hasChanges {
            do {
                try self.save()
            }
            catch {
                print("bake disaster type 1 \(error)")
            }
        }
}
</code>```

Body:
I am trying to set a constraint in core data with the new Entity Constraints inspector (To make the name of the item unique).  All that I've read says it's pretty simple - Set the constraint and handle the error. I don't get any errors and can add the same entry as many times as I want.

The app does require IOS 9.0, Xcode tools requirement is set to 7.0

The constraint, category1Name, is a String.

My addItem code is:

func addNewRecord() {

    //check to be sure the entry is not empty
    if (categoryTextField.text == "") {

        //prompt requiring a name
        let ac = UIAlertController(title: nil, message: "Name Required", preferredStyle: .Alert)
        ac.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
        self.presentViewController(ac, animated: true, completion: nil)

    } else {

    let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName("Category1", inManagedObjectContext: kAppDelegate.managedObjectContext) as! Category1

    newManagedObject.category1Name = categoryTextField.text
    newManagedObject.category1Description = categoryTextView.text

    //bunch more items...

    //save it
    kAppDelegate.saveContext()
    makeEntryFieldsEnabledNO()
    performSegueWithIdentifier("unwindToCategoriesTableViewController", sender: self)

    }//if  else

}//addNewRecord

The AppDelegate save is standard:

func saveContext () {
    if managedObjectContext.hasChanges {
        do {
            try managedObjectContext.save()
        } catch {

            //insert your standard error alert stuff here
            let nserror = error as NSError
            print("From the print line: Unresolved error \(nserror), \(nserror.userInfo)")

            abort()
        }//do catch
    }//if moc
}//saveContext

Here's the Core Data constraint:

This app is iCloud enabled.

The managedObjectContext merge policy is set to NSMergeByPropertyObjectTrumpMergePolicy

lazy var managedObjectContext: NSManagedObjectContext = {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
    let coordinator = self.persistentStoreCoordinator
    var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
    managedObjectContext.persistentStoreCoordinator = coordinator
    managedObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
    return managedObjectContext

}()//var managedObjectContext

Any guidance would be appreciated.

Body:
It would appear Apple have finally fixed the crazy Xcode problem where changes you make in a data model file don't actually change.

Putting that aside, the current formula seems to be:

in your core data singleton ...

    container = NSPersistentContainer(name: _nom)

    // during development, right HERE likely delete the sql database file
    // and start fresh, as described here stackoverflow.com/a/60040554/294884

    container.loadPersistentStores { storeDescription, error in
        if let error = error {
            print("\n ERROR LOADING STORES! \(error) \n")
        }
        else {
            print("\n  STORES LOADED! \(storeDescription) \n")
        }

        self.container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
        self.container.viewContext.automaticallyMergesChangesFromParent = true
    }

You must use merge policy and automatically merges.

Then in your data model file

Don't bother unless every relationship has an inverse, with

"to one or many" correctly set

and (almost certainly, except in very unusual source data) your unique id for each entity is indicated as a constraint

Then when you add new data, you must

use the new background context supplied by the handy core data function which does that

so, never try to make your own separate thread

double-check you have done (1) and (2) !

when you do add a few entities, you must do that inside a perform

and when you have finished adding entities (ie on the new thread) you must while still in the perform ...

do a performAndWait which does two things

save the new items (on the new child thread), and then

save the new items (on the main view thread)

naturally for both 7 and 8, you have to check .hasChanges before saving

Easy right?

So something like

let pm = core.container.newBackgroundContext()
pm.perform {
    for onePerson in someNewData {
        ... create your new CDPerson entity ...
    }
    pm.bake()
}

Note that the bake routine is within the perform block,

and it looks like this:

func bake() {
    self.performAndWait {
        if self.hasChanges {
            do {
                try self.save()
            }
            catch {
                print("bake disaster type 1 \(error)")
            }
        }

        // OPTIONALLY, SEE BELOW
        if core.container.viewContext.hasChanges {
            do {
                try core.container.viewContext.save()
            }
            catch {
                print("bake disaster type 2 \(error)")
            }
        }
        // OPTIONALLY, SEE BELOW
    }
}

To be clear, notice the pm.bake ... in the function bake(), the self in the first half is indeed that newBackgroundContext which is created for the loop inside the perform.

Note that these days you don't even need to save to the main context

Nowadays automaticallyMergesChangesFromParent seems to work perfectly, if you "do everything in the long list above".

• In the bake above, add a couple print lines to see what is saved to the viewContext. You'll see that nothing, at all, is ever saved. It's all done properly by the child/whatever relationships in the engine

• So in fact, in reality you can just omit that passage of the code. All you have to do is

func bake() {
    self.performAndWait {
        if self.hasChanges {
            do {
                try self.save()
            }
            catch {
                print("bake disaster type 1 \(error)")
            }
        }
}


问:
Twillio Studio Send and receive text message
i am new to twillio studio and can send texts one way, but want to be able to do the following.

Recieve a text from a twillio number to my cell

Reply to the text from my cell back to the twilio number path

I can find info and get a project working for step 1 , but am having a issue wil info on step 2.

Any suggestions.

Thanks
Tom

答:
It sounds like you are using the Twilio Studio REST API Trigger of your Studio Flow, can you confirm?

Trigger a Twilio Studio Flow Execution via the REST API

If that is the case, just have the Trigger Widget REST API path follow into a Send and Wait for Reply Widget. This is all you need to do to satisfy #1 and #2 above.


问:
getResources().getDrawable(rippleResourceId, null) return rippleDrawable with the wrong color
I use android resourceId android.R.attr.actionBarItemBackground to set ripple.

On one item it works fine. On anther item I change the RippleDrawable radius, but then the ripple color changes to pink.

```<code>    int rippleResourceId = // android.R.attr.actionBarItemBackground from current context
    if (VERSION.SDK_INT >= VERSION_CODES.M) {
      RippleDrawable drawable =
          (RippleDrawable) getResources().getDrawable(rippleResourceId, null);
      drawable.setRadius(
          getContext()
              .getResources()
              .getDimensionPixelSize(R.dimen.ripple_radius));
 myFrameLayout.setBackground(drawable);
    } else {
       myFrameLayout.setBackgroundResource(discRippleResourceId);
    }
</code>```

Anyhow had this problem?

答:
sending a null theme caused this difference

getDrawable(rippleResourceId, null);

Body:
I use android resourceId android.R.attr.actionBarItemBackground to set ripple.

On one item it works fine. On anther item I change the RippleDrawable radius, but then the ripple color changes to pink.

    int rippleResourceId = // android.R.attr.actionBarItemBackground from current context
    if (VERSION.SDK_INT >= VERSION_CODES.M) {
      RippleDrawable drawable =
          (RippleDrawable) getResources().getDrawable(rippleResourceId, null);
      drawable.setRadius(
          getContext()
              .getResources()
              .getDimensionPixelSize(R.dimen.ripple_radius));
 myFrameLayout.setBackground(drawable);
    } else {
       myFrameLayout.setBackgroundResource(discRippleResourceId);
    }

Anyhow had this problem?


问:
List all EBS volumes in an AWS Account
I am trying to get a list of all the EBS volumes in an AWS account. I'm using Python 3 and boto3 version 1.10.34.

I found this post with some suggestions but neither of them work.

I'm setting the ec2_client like this:
    import boto3
    session = boto3.Session(profile_name=aws_account,region_name='us-east-1')
    ec2_client = session.client('ec2')

If I try volumes = ec2_client.volumes.all() I get back AttributeError: 'EC2' object has no attribute 'volumes'.

If I try volumes = ec2_client.get_all_volumes()I get back AttributeError: 'EC2' object has no attribute 'get_all_volumes'.

How can I do this correctly?

答:
I suggest you use paginator when you need to describe "all" volumes.

If you have more than 1000 volumes, describe_volumes() will not describe all volumes, just the first 1000.

Let me quote the reference documentation below.

Some AWS operations return results that are incomplete and require
  subsequent requests in order to attain the entire result set. The
  process of sending subsequent requests to continue where a previous
  request left off is called pagination. For example, the list_objects
  operation of Amazon S3 returns up to 1000 objects at a time, and you
  must send subsequent requests with the appropriate Marker in order to
  retrieve the next page of results.

Paginators are a feature of boto3 that act as an abstraction over the
  process of iterating over an entire result set of a truncated API
  operation.

Reference: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/paginators.html

See an snippet below:

```<code>def get_all_volumes(session):
    volumes = []

    ec2 = session.client("ec2")
    # Get all Volumes using paginator
    paginator = ec2.get_paginator("describe_volumes")
    page_iterator = paginator.paginate()
    for page in page_iterator:
        volumes.extend(page["Volumes"])
    return volumes
</code>```

Title: List all EBS volumes in an AWS Account

Body:
I suggest you use paginator when you need to describe "all" volumes.

If you have more than 1000 volumes, describe_volumes() will not describe all volumes, just the first 1000.

Let me quote the reference documentation below.

Some AWS operations return results that are incomplete and require
  subsequent requests in order to attain the entire result set. The
  process of sending subsequent requests to continue where a previous
  request left off is called pagination. For example, the list_objects
  operation of Amazon S3 returns up to 1000 objects at a time, and you
  must send subsequent requests with the appropriate Marker in order to
  retrieve the next page of results.

Paginators are a feature of boto3 that act as an abstraction over the
  process of iterating over an entire result set of a truncated API
  operation.

Reference: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/paginators.html

See an snippet below:

def get_all_volumes(session):
    volumes = []

    ec2 = session.client("ec2")
    # Get all Volumes using paginator
    paginator = ec2.get_paginator("describe_volumes")
    page_iterator = paginator.paginate()
    for page in page_iterator:
        volumes.extend(page["Volumes"])
    return volumes


问:
Javascript Syntax Differences
What is the difference between these two?

```<code>collapse: function(fold)
{
...
...
}
</code>```

and

```<code>function collapse(fold)
{
...
...
}
</code>```

答:
The first code is only valid to produce a property inside an object definition, like so:

```<code>var obj = {
    collapse: function(fold)
    {
    ...
    ...
    }
};
</code>```

That function would be called by calling obj.collapse(fold);

The second function is simply called using collapse(fold);

As for the difference between var name = function() { ... } and function name() { ... } see: var functionName = function() {} vs function functionName() {}

Title: Javascript Syntax Differences

Body:
What is the difference between these two?

collapse: function(fold)
{
...
...
}

and

function collapse(fold)
{
...
...
}

Body:
The first code is only valid to produce a property inside an object definition, like so:

var obj = {
    collapse: function(fold)
    {
    ...
    ...
    }
};

That function would be called by calling obj.collapse(fold);

The second function is simply called using collapse(fold);

As for the difference between var name = function() { ... } and function name() { ... } see: var functionName = function() {} vs function functionName() {}