问:
Refresh a view when the children of an object are changed in SwiftUI
I am working on a CoreData application with two entities MyList and MyListItem. MyList can have many MyListItem (one to many). When the app is launched, I can see all the lists. I can tap on a list to go to the list items. On that screen, I tap a button to add an item to the selected list. After, adding the item when I go back to the all lists screen I cannot see the number of items reflected in the count. The reason is that MyListsView is not rendered again since the number of lists have not changed.

The complete code is shown below:

```<code>import SwiftUI
import CoreData

extension MyList {

    static var all: NSFetchRequest<MyList> {
        let request = MyList.fetchRequest()
        request.sortDescriptors = []
        return request
    }
}

struct DetailView: View {

    @Environment(\.managedObjectContext) var viewContext
    let myList: MyList

    var body: some View {
        VStack {
            Text("Detail View")
            Button("Add List Item") {

                let myListP = viewContext.object(with: myList.objectID) as! MyList

                let myListItem = MyListItem(context: viewContext)
                myListItem.name = randomString()
                myListItem.myList = myListP

                try? viewContext.save()

            }
        }
    }

    func randomString(length: Int = 8) -> String {
        let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        return String((0..<length).map{ _ in letters.randomElement()! })
    }
}

class ViewModel: NSObject, ObservableObject {

    @Published var myLists: [MyList] = []

    private var fetchedResultsController: NSFetchedResultsController<MyList>
    private(set) var context: NSManagedObjectContext

    override init() {
        self.context = CoreDataManager.shared.context

        fetchedResultsController = NSFetchedResultsController(fetchRequest: MyList.all, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
        super.init()
        fetchedResultsController.delegate = self

        do {
            try fetchedResultsController.performFetch()
            guard let myLists = fetchedResultsController.fetchedObjects else { return }
            self.myLists = myLists

        }  catch {
            print(error)
        }
    }
}

extension ViewModel: NSFetchedResultsControllerDelegate {
    func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        guard let myLists = controller.fetchedObjects as? [MyList] else { return }
        self.myLists = myLists
    }
}

struct MyListsView: View {

    let myLists: [MyList]

    var body: some View {
        List(myLists) { myList in
            NavigationLink {
                DetailView(myList: myList)
            } label: {
                HStack {
                    Text(myList.name ?? "")
                    Spacer()

                    Text("\((myList.items ?? []).count)")
                }
            }
        }
    }
}

struct ContentView: View {

    @StateObject private var vm = ViewModel()
    @Environment(\.managedObjectContext) var viewContext

    var body: some View {
        NavigationView {
            VStack {

                // when adding an item to the list the MyListView view is
                // not re-rendered
                MyListsView(myLists: vm.myLists)

                Button("Change List") {

                }
            }
        }
    }

    func randomString(length: Int = 8) -> String {
        let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        return String((0..<length).map{ _ in letters.randomElement()! })
    }
}
</code>```

Inside ContentView there is a view called "MyListsView". That view is not rendered when the items are added. Since, according to that view nothing changed since the number of lists are still the same.

How do you solve this problem?

UPDATE:

What happens if I add one more level of views like for ListCellView as shown below:

```<code>struct MyListCellView: View {

    @StateObject var vm: ListCellViewModel

    init(vm: ListCellViewModel) {
        _vm = StateObject(wrappedValue: vm)
    }

    var body: some View {
        HStack {
            Text(vm.name)
            Spacer()

            Text("\((vm.items).count)")
        }
    }
}

@MainActor
class ListCellViewModel: ObservableObject {

    let myList: MyList

    init(myList: MyList) {
        self.myList = myList
        self.name = myList.name ?? ""
        self.items = myList.items!.allObjects as! [MyListItem]
        print(self.items.count)
    }

    @Published var name: String = ""
    @Published var items: [MyListItem] = []
}

struct MyListsView: View {

    @StateObject var vm: ViewModel

    init(vm: ViewModel) {
        _vm = StateObject(wrappedValue: vm)
    }

    var body: some View {
        let _ = Self._printChanges()
        List(vm.myLists) { myList in
            NavigationLink {
                DetailView(myList: myList)
            } label: {
                MyListCellView(vm: ListCellViewModel(myList: myList))
            }
        }
    }
}
</code>```

Now the count is again not being updated.

答:
We don't need MVVM in SwiftUI, the View data structs already fill that role and property wrappers make them behave like objects giving best of both worlds. In your case use the @FetchRequest property wrapper for the list and @ObservedObject for the detail and body will be called on any changes to the model data. Examine the code in the app template in Xcode with Core Data checked. It looks like this:

```<code>struct ContentView: View {
    @Environment(\.managedObjectContext) private var viewContext

    @FetchRequest(
        sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],
        animation: .default)
    private var items: FetchedResults<Item>

    var body: some View {
        NavigationView {

            List {
                ForEach(items) { item in
                    NavigationLink {
                        DetailView(item: item)
                    } label: {
                        Text(item.timestamp!, formatter: itemFormatter)
                    }
                }
                .onDelete(perform: deleteItems)
            }
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    EditButton()
                }
                ToolbarItem {
                    Button(action: addItem) {
                        Label("Add Item", systemImage: "plus")
                    }
                }
            }
            Text("Select an item")
        }
    }
...
struct DetailView: View {
    @ObservedObject var item: Item

    var body: some View {
        Text("Item at \(item.timestamp!, formatter: itemFormatter)")
</code>```

Body:
I am working on a CoreData application with two entities MyList and MyListItem. MyList can have many MyListItem (one to many). When the app is launched, I can see all the lists. I can tap on a list to go to the list items. On that screen, I tap a button to add an item to the selected list. After, adding the item when I go back to the all lists screen I cannot see the number of items reflected in the count. The reason is that MyListsView is not rendered again since the number of lists have not changed.

The complete code is shown below:

import SwiftUI
import CoreData

extension MyList {

    static var all: NSFetchRequest<MyList> {
        let request = MyList.fetchRequest()
        request.sortDescriptors = []
        return request
    }
}

struct DetailView: View {

    @Environment(\.managedObjectContext) var viewContext
    let myList: MyList

    var body: some View {
        VStack {
            Text("Detail View")
            Button("Add List Item") {

                let myListP = viewContext.object(with: myList.objectID) as! MyList

                let myListItem = MyListItem(context: viewContext)
                myListItem.name = randomString()
                myListItem.myList = myListP

                try? viewContext.save()

            }
        }
    }

    func randomString(length: Int = 8) -> String {
        let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        return String((0..<length).map{ _ in letters.randomElement()! })
    }
}

class ViewModel: NSObject, ObservableObject {

    @Published var myLists: [MyList] = []

    private var fetchedResultsController: NSFetchedResultsController<MyList>
    private(set) var context: NSManagedObjectContext

    override init() {
        self.context = CoreDataManager.shared.context

        fetchedResultsController = NSFetchedResultsController(fetchRequest: MyList.all, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
        super.init()
        fetchedResultsController.delegate = self

        do {
            try fetchedResultsController.performFetch()
            guard let myLists = fetchedResultsController.fetchedObjects else { return }
            self.myLists = myLists

        }  catch {
            print(error)
        }
    }
}

extension ViewModel: NSFetchedResultsControllerDelegate {
    func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        guard let myLists = controller.fetchedObjects as? [MyList] else { return }
        self.myLists = myLists
    }
}

struct MyListsView: View {

    let myLists: [MyList]

    var body: some View {
        List(myLists) { myList in
            NavigationLink {
                DetailView(myList: myList)
            } label: {
                HStack {
                    Text(myList.name ?? "")
                    Spacer()

                    Text("\((myList.items ?? []).count)")
                }
            }
        }
    }
}

struct ContentView: View {

    @StateObject private var vm = ViewModel()
    @Environment(\.managedObjectContext) var viewContext

    var body: some View {
        NavigationView {
            VStack {

                // when adding an item to the list the MyListView view is
                // not re-rendered
                MyListsView(myLists: vm.myLists)

                Button("Change List") {

                }
            }
        }
    }

    func randomString(length: Int = 8) -> String {
        let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        return String((0..<length).map{ _ in letters.randomElement()! })
    }
}

Inside ContentView there is a view called "MyListsView". That view is not rendered when the items are added. Since, according to that view nothing changed since the number of lists are still the same.

How do you solve this problem?

UPDATE:

What happens if I add one more level of views like for ListCellView as shown below:

struct MyListCellView: View {

    @StateObject var vm: ListCellViewModel

    init(vm: ListCellViewModel) {
        _vm = StateObject(wrappedValue: vm)
    }

    var body: some View {
        HStack {
            Text(vm.name)
            Spacer()

            Text("\((vm.items).count)")
        }
    }
}

@MainActor
class ListCellViewModel: ObservableObject {

    let myList: MyList

    init(myList: MyList) {
        self.myList = myList
        self.name = myList.name ?? ""
        self.items = myList.items!.allObjects as! [MyListItem]
        print(self.items.count)
    }

    @Published var name: String = ""
    @Published var items: [MyListItem] = []
}

struct MyListsView: View {

    @StateObject var vm: ViewModel

    init(vm: ViewModel) {
        _vm = StateObject(wrappedValue: vm)
    }

    var body: some View {
        let _ = Self._printChanges()
        List(vm.myLists) { myList in
            NavigationLink {
                DetailView(myList: myList)
            } label: {
                MyListCellView(vm: ListCellViewModel(myList: myList))
            }
        }
    }
}

Now the count is again not being updated.

Body:
We don't need MVVM in SwiftUI, the View data structs already fill that role and property wrappers make them behave like objects giving best of both worlds. In your case use the @FetchRequest property wrapper for the list and @ObservedObject for the detail and body will be called on any changes to the model data. Examine the code in the app template in Xcode with Core Data checked. It looks like this:

struct ContentView: View {
    @Environment(\.managedObjectContext) private var viewContext

    @FetchRequest(
        sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],
        animation: .default)
    private var items: FetchedResults<Item>

    var body: some View {
        NavigationView {

            List {
                ForEach(items) { item in
                    NavigationLink {
                        DetailView(item: item)
                    } label: {
                        Text(item.timestamp!, formatter: itemFormatter)
                    }
                }
                .onDelete(perform: deleteItems)
            }
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    EditButton()
                }
                ToolbarItem {
                    Button(action: addItem) {
                        Label("Add Item", systemImage: "plus")
                    }
                }
            }
            Text("Select an item")
        }
    }
...
struct DetailView: View {
    @ObservedObject var item: Item

    var body: some View {
        Text("Item at \(item.timestamp!, formatter: itemFormatter)")


来源: stackexchange

问:
Android Room: How to auto generate primary id, without using "autoGenerate = true" (To avoid SQLite keyword AUTOINCREMENT)?

Background

Just recently, I learn that using AUTOINCREMENT in SQLite is not encouraged.

https://www.sqlite.org/autoinc.html

The keyword AUTOINCREMENT is in fact confusing. As, what it really mean is the algorithm method for generating id automatically.

Even if we do not use the keyword AUTOINCREMENT, and do not provide an id during insertion, the id will still be auto generated.

For instance,

```<code>DROP TABLE cities;

CREATE TABLE cities (
   id INTEGER NOT NULL PRIMARY KEY,
   name TEXT NOT NULL
);

INSERT INTO cities (name)
VALUES( 'San Jose');

INSERT INTO cities (name)
VALUES( 'New York');
</code>```

The following table will still be generated even without AUTOINCREMENT keyword

```<code>id  name
========
1   San Jose
2   New York
</code>```

I want to achieve the same behavior in Android Room

Instead of using the following (which will apply SQLite AUTOINCREMENT)

```<code>@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
private long id;
</code>```

I use in my entity class

```<code>@PrimaryKey
@ColumnInfo(name = "id")
private long id;
</code>```

However, I notice that I need to explicitly assign a non zero positive value to id, only the insertion will be success.

If the value for id is 0 or -1, then the insertion will not succeed

I expect we need not to assign id manually, even without using Room autoGenerate = true.

But, it seems like that doesn't work as expected. May I know why it is so?

答:
I expect we need not to assign id manually, even without using Room autoGenerate = true.

It is not necessary to use autogenerate = true, and have the same generation of values. You can use (another way is shown later):-

```<code>@PrimaryKey
@ColumnInfo(name = "id")
private Long id; /* or private Long = null; */
</code>```

Noting the use of the Long object rather than the long primitive. You then set id to null for a value to be generated or have suitable constructors.

Room sees the null, in the case of PRIMARY KEY and a non-primitive integer type, and omits the column from the generated SQL.

As an example based upon your schema consider :-

```<code>@Entity
class Cities {
   @PrimaryKey
   private Long id;
   private String name;

   @Ignore
   public Cities(String name) {
      this.name = name;
   }
   @Ignore
   public Cities(Long id, String name) {
      this.id = id;
      this.name = name;
   }
   public Cities(){}

   public Long getId() {
      return id;
   }

   public void setId(Long id) {
      this.id = id;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }
}
</code>```

With a convenience @Insert e.g. :-

```<code>@Dao
interface CitiesDao {
    @Insert
    long insert(Cities city);
}
</code>```

Alternately you could utilise an @Query to utilise an INSERT SQL that suits. e.g. the following will insert a row just given the name with a generated id. :-

```<code>@Query("INSERT INTO cities (name) VALUES(:name)")
long insert(String name);
</code>```

The important factor is including the specific column(s) without the id column.

An example of using the above (2 methods) :-

```<code>    citiesdao.insert(new Cities("San Jose"));
    citiesdao.insert(new Cities("New York"));
    citiesdao.insert(new Cities(100L,"San Francisco"));
    citiesdao.insert(new Cities("Nevada"));
    citiesdao.insert("Dallas");
</code>```

you probably would not want to  use the third that inserts with a specific id (or could perhaps use onConflict = IGNORE).

The above results in (via App Inspection) :-

ContentLicense: CC BY-SA 4.0

Body:
Background

Just recently, I learn that using AUTOINCREMENT in SQLite is not encouraged.

https://www.sqlite.org/autoinc.html

The keyword AUTOINCREMENT is in fact confusing. As, what it really mean is the algorithm method for generating id automatically.

Even if we do not use the keyword AUTOINCREMENT, and do not provide an id during insertion, the id will still be auto generated.

For instance,

DROP TABLE cities;

CREATE TABLE cities (
   id INTEGER NOT NULL PRIMARY KEY,
   name TEXT NOT NULL
);

INSERT INTO cities (name)
VALUES( 'San Jose');

INSERT INTO cities (name)
VALUES( 'New York');

The following table will still be generated even without AUTOINCREMENT keyword

id  name
========
1   San Jose
2   New York

I want to achieve the same behavior in Android Room

Instead of using the following (which will apply SQLite AUTOINCREMENT)

@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
private long id;

I use in my entity class

@PrimaryKey
@ColumnInfo(name = "id")
private long id;

However, I notice that I need to explicitly assign a non zero positive value to id, only the insertion will be success.

If the value for id is 0 or -1, then the insertion will not succeed

I expect we need not to assign id manually, even without using Room autoGenerate = true.

But, it seems like that doesn't work as expected. May I know why it is so?

Body:
I expect we need not to assign id manually, even without using Room autoGenerate = true.

It is not necessary to use autogenerate = true, and have the same generation of values. You can use (another way is shown later):-

@PrimaryKey
@ColumnInfo(name = "id")
private Long id; /* or private Long = null; */

Noting the use of the Long object rather than the long primitive. You then set id to null for a value to be generated or have suitable constructors.

Room sees the null, in the case of PRIMARY KEY and a non-primitive integer type, and omits the column from the generated SQL.

As an example based upon your schema consider :-

@Entity
class Cities {
   @PrimaryKey
   private Long id;
   private String name;

   @Ignore
   public Cities(String name) {
      this.name = name;
   }
   @Ignore
   public Cities(Long id, String name) {
      this.id = id;
      this.name = name;
   }
   public Cities(){}

   public Long getId() {
      return id;
   }

   public void setId(Long id) {
      this.id = id;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }
}

With a convenience @Insert e.g. :-

@Dao
interface CitiesDao {
    @Insert
    long insert(Cities city);
}

Alternately you could utilise an @Query to utilise an INSERT SQL that suits. e.g. the following will insert a row just given the name with a generated id. :-

@Query("INSERT INTO cities (name) VALUES(:name)")
long insert(String name);

The important factor is including the specific column(s) without the id column.

An example of using the above (2 methods) :-

    citiesdao.insert(new Cities("San Jose"));
    citiesdao.insert(new Cities("New York"));
    citiesdao.insert(new Cities(100L,"San Francisco"));
    citiesdao.insert(new Cities("Nevada"));
    citiesdao.insert("Dallas");

you probably would not want to  use the third that inserts with a specific id (or could perhaps use onConflict = IGNORE).

The above results in (via App Inspection) :-


问:
Finding average and max value per account from a list
so I've got this data of a type 'list' (this is just a fraction of it to illustrate the point) stored in a variable called sorted_trans (I have pre-sorted it to group accountIds together):

```<code>Transaction(transactionId='T000664', accountId='A1', transactionDay=21, category='GG', transactionAmount=364.69), Transaction(transactionId='T000776', accountId='A1', transactionDay=24, category='GG', transactionAmount=329.63), Transaction(transactionId='T000313', accountId='A10', transactionDay=8, category='AA', transactionAmount=960.56), Transaction(transactionId='T000472', accountId='A10', transactionDay=12, category='AA', transactionAmount=707.74), Transaction(transactionId='T000596', accountId='A10', transactionDay=18, category='AA', transactionAmount=156.77), Transaction(transactionId='T000730', accountId='A10', transactionDay=23, category='AA', transactionAmount=577.76)
</code>```

My task is to sort this data by 'accountId' for the last 5 days (I'm using the rolling window) and calculate: total 'transactionAmount' per 'accountId', average 'transactionAmount' per 'accountId' and return the maximum 'transactionAmount' per 'accountId'

To capture data for the last five days (excluding the current day), I'm using a normal for-loop

```<code>for i in range(day-window_size, day):
</code>```

I suspect I would need to use some sort of a comprehension to group and calculate the right values. The output should contain one line per day per account id and each line should contain each of the calculated statistics, for example: Output examle.
I've managed to get everything but the average and max.

For example, I've calculated total value per category AA (same for other categories) with this code:

```<code>trans_AA = []
trans_AA.append([(x.accountId, x.transactionAmount) for x in sorted_trans  if x.category == "AA"])
</code>```

Generic method to calculate total transactionAmount per category

```<code>def totals_per_cat(transactions):

    for accountId, transactionAmount in chain.from_iterable(transactions):
                 d[accountId] += transactionAmount
    trans_res = list(d.values())
    return trans_res
</code>```

How to calculate average and max per accountId for the past 5 days?

答:
This will hopefully get you most of the way there:</p>
```<code>from collections import defaultdict
from dataclasses import dataclass, fields
from csv import DictReader
from statistics import mean
from typing import Dict, List

@dataclass
class Transaction:
    transactionId: str
    accountId: str
    transactionDay: int
    category: str
    transactionAmount: float

def load_transactions(file_path: str) -> List[Transaction]:
    with open(file_path) as csv_file:
        return [
            Transaction(**{
                field.name: field.type(row[field.name])
                for field in fields(Transaction)
            }) for row in DictReader(csv_file)
        ]

transactions = load_transactions('transactions.txt')
min_day = min(xact.transactionDay for xact in transactions)
max_day = max(xact.transactionDay for xact in transactions)
window_size = 5

xact_by_acct: Dict[str, List[Transaction]] = defaultdict(list)
for xact in transactions:
    xact_by_acct[xact.accountId].append(xact)

for day in range(min_day + window_size, max_day + 1):
    for acct, xacts in xact_by_acct.items():
        amts = [
            xact.transactionAmount for xact in xacts
            if xact.transactionDay in range(day - window_size, day)
        ]  # all amounts within the window
        try:
            print(
                f"Day: {day}\tAccount: {acct}\t"
                f"Max: {max(amts)}\tAverage: {mean(amts)}"
            )
        except ValueError:
            # No transactions in the window for this account.
            pass
</code>```

Body:
so I've got this data of a type 'list' (this is just a fraction of it to illustrate the point) stored in a variable called sorted_trans (I have pre-sorted it to group accountIds together):

Transaction(transactionId='T000664', accountId='A1', transactionDay=21, category='GG', transactionAmount=364.69), Transaction(transactionId='T000776', accountId='A1', transactionDay=24, category='GG', transactionAmount=329.63), Transaction(transactionId='T000313', accountId='A10', transactionDay=8, category='AA', transactionAmount=960.56), Transaction(transactionId='T000472', accountId='A10', transactionDay=12, category='AA', transactionAmount=707.74), Transaction(transactionId='T000596', accountId='A10', transactionDay=18, category='AA', transactionAmount=156.77), Transaction(transactionId='T000730', accountId='A10', transactionDay=23, category='AA', transactionAmount=577.76)

My task is to sort this data by 'accountId' for the last 5 days (I'm using the rolling window) and calculate: total 'transactionAmount' per 'accountId', average 'transactionAmount' per 'accountId' and return the maximum 'transactionAmount' per 'accountId'

To capture data for the last five days (excluding the current day), I'm using a normal for-loop

for i in range(day-window_size, day):

I suspect I would need to use some sort of a comprehension to group and calculate the right values. The output should contain one line per day per account id and each line should contain each of the calculated statistics, for example: Output examle.
I've managed to get everything but the average and max.

For example, I've calculated total value per category AA (same for other categories) with this code:

trans_AA = []
trans_AA.append([(x.accountId, x.transactionAmount) for x in sorted_trans  if x.category == "AA"])

Generic method to calculate total transactionAmount per category

def totals_per_cat(transactions):

    for accountId, transactionAmount in chain.from_iterable(transactions):
                 d[accountId] += transactionAmount
    trans_res = list(d.values())
    return trans_res

How to calculate average and max per accountId for the past 5 days?

Body:
This will hopefully get you most of the way there:

from collections import defaultdict
from dataclasses import dataclass, fields
from csv import DictReader
from statistics import mean
from typing import Dict, List

@dataclass
class Transaction:
    transactionId: str
    accountId: str
    transactionDay: int
    category: str
    transactionAmount: float

def load_transactions(file_path: str) -> List[Transaction]:
    with open(file_path) as csv_file:
        return [
            Transaction(**{
                field.name: field.type(row[field.name])
                for field in fields(Transaction)
            }) for row in DictReader(csv_file)
        ]

transactions = load_transactions('transactions.txt')
min_day = min(xact.transactionDay for xact in transactions)
max_day = max(xact.transactionDay for xact in transactions)
window_size = 5

xact_by_acct: Dict[str, List[Transaction]] = defaultdict(list)
for xact in transactions:
    xact_by_acct[xact.accountId].append(xact)

for day in range(min_day + window_size, max_day + 1):
    for acct, xacts in xact_by_acct.items():
        amts = [
            xact.transactionAmount for xact in xacts
            if xact.transactionDay in range(day - window_size, day)
        ]  # all amounts within the window
        try:
            print(
                f"Day: {day}\tAccount: {acct}\t"
                f"Max: {max(amts)}\tAverage: {mean(amts)}"
            )
        except ValueError:
            # No transactions in the window for this account.
            pass


问:
Sharing data across processes on linux
In my application, I have a process which forks off a child, say child1, and this child process writes a huge binary file on the disk and exits. The parent process then forks off another child process, child2, which reads in this huge file to do further processing.

The file dumping and re-loading is making my application slow and I'm thinking of possible
ways of avoiding disk I/O completely. Possible ways I have identified are ram-disk or tmpfs.
Can I somehow implement ram-disk or tmpfs from within my application? Or is there any other
way by which I can avoid disk I/O completely and send data across processes reliably.

答: You can pass data between processes, using pipes. Here is a good synopsis and example implementation.</p>

ContentLicense: CC BY-SA 3.0

Title: Sharing data across processes on linux


问:
Erlang: supervisor:terminate_child return error even in latest version
I'm trying to use a supervisor with simple_one_for_one RestartStrategy, and I think I have the latest version of Erlang, but still when I try to execute supervisor:terminate_child it ends up with {error,simple_one_for_one}. According to this answer, it should work if my Erlang is version is greater than R14B03 but I can't seem to find the version starting with 'R' anywhere. When I try erlang:system_info(otp_release) in the Erlang shell, it return with "24", which I think is the latest version released in May 2021, but I could see no other reason for this issue. Here is how my supervisor looks:

```<code>-module(a_sup).
-behaviour(supervisor).

%% API
-export([start_link/0, init/1]).

start_link() ->
  {ok, supervisor:start_link({local,?MODULE}, ?MODULE, [])}.

init(_Args) ->
  RestartStrategy = {simple_one_for_one, 5, 3600},
  ChildSpec = {
    a_gen_server,
    {a_gen_server, start_link, []},
    permanent,
    brutal_kill,
    worker,
    [a_gen_server]
  },
  {ok, {RestartStrategy,[ChildSpec]}}.
</code>```

答:
You don't show your code for terminating a child, but are you indicating the child to terminate using an identifier instead of a pid? The terminate_child/2 documentation says:

If the supervisor is simple_one_for_one, Id must be the pid() of the
child process. If the specified process is alive, but is not a child
of the specified supervisor, the function returns {error,not_found}.
If the child specification identifier is specified instead of a pid(),
the function returns {error,simple_one_for_one}.

Regarding the version issue: 24.2 is the current Erlang/OTP version at the time of this writing. Version numbers used to start with 'R' but that ended at Erlang/OTP 17.0.

Body:
I'm trying to use a supervisor with simple_one_for_one RestartStrategy, and I think I have the latest version of Erlang, but still when I try to execute supervisor:terminate_child it ends up with {error,simple_one_for_one}. According to this answer, it should work if my Erlang is version is greater than R14B03 but I can't seem to find the version starting with 'R' anywhere. When I try erlang:system_info(otp_release) in the Erlang shell, it return with "24", which I think is the latest version released in May 2021, but I could see no other reason for this issue. Here is how my supervisor looks:

-module(a_sup).
-behaviour(supervisor).

%% API
-export([start_link/0, init/1]).

start_link() ->
  {ok, supervisor:start_link({local,?MODULE}, ?MODULE, [])}.

init(_Args) ->
  RestartStrategy = {simple_one_for_one, 5, 3600},
  ChildSpec = {
    a_gen_server,
    {a_gen_server, start_link, []},
    permanent,
    brutal_kill,
    worker,
    [a_gen_server]
  },
  {ok, {RestartStrategy,[ChildSpec]}}.


问:
What is the easiest way to generate a String of n repeated characters?
Given a character c and a number n, how can I create a String that consists of n repetitions of c? Doing it manually is too cumbersome:

```<code>StringBuilder sb = new StringBuilder(n);
for (int i = 0; i < n; ++i)
{
    sb.append(c);
}
String result = sb.toString();
</code>```

Surely there is some static library function that already does this for me?

答:
Just add it to your own...

```<code>public static String generateRepeatingString(char c, Integer n) {
    StringBuilder b = new StringBuilder();
    for (Integer x = 0; x < n; x++)
        b.append(c);
    return b.toString();
}
</code>```

Or Apache commons has a utility class you can add.

Body:
Given a character c and a number n, how can I create a String that consists of n repetitions of c? Doing it manually is too cumbersome:

StringBuilder sb = new StringBuilder(n);
for (int i = 0; i < n; ++i)
{
    sb.append(c);
}
String result = sb.toString();

Surely there is some static library function that already does this for me?

Body:
Just add it to your own...

public static String generateRepeatingString(char c, Integer n) {
    StringBuilder b = new StringBuilder();
    for (Integer x = 0; x < n; x++)
        b.append(c);
    return b.toString();
}

Or Apache commons has a utility class you can add.


问:
Get.changeTheme does not work on real Device
I'm trying to change theme dynamically using GetX library., it works perfectly on iOS simulator, but it does not work on real device.

I'm using this code:

```<code>Get.changeTheme(AppThemes.darkTheme);
</code>```

darkTheme is the custom theme I want to switch to.

答:
I resolved GetX dynamic change theme issue by referencing ThemeMode as per code below instead of the GetX code sample using ThemeData.

In my case this fixed issue where the default device system dark mode would not dynamically update to my ThemeData.light mode.

```<code>          //Get.changeTheme(Get.isDarkMode ? ThemeData.light() : ThemeData.dark()); //Code from GetX change theme documentation did not work

            Get.changeThemeMode(Get.isDarkMode ? ThemeMode.light : ThemeMode.dark); //Modified successfully by referencing ThemeMode
           setState(() {
           });
</code>```

Body:
I'm trying to change theme dynamically using GetX library., it works perfectly on iOS simulator, but it does not work on real device.

I'm using this code:

Get.changeTheme(AppThemes.darkTheme);

darkTheme is the custom theme I want to switch to.

Body:
I resolved GetX dynamic change theme issue by referencing ThemeMode as per code below instead of the GetX code sample using ThemeData.

In my case this fixed issue where the default device system dark mode would not dynamically update to my ThemeData.light mode.

          //Get.changeTheme(Get.isDarkMode ? ThemeData.light() : ThemeData.dark()); //Code from GetX change theme documentation did not work

            Get.changeThemeMode(Get.isDarkMode ? ThemeMode.light : ThemeMode.dark); //Modified successfully by referencing ThemeMode
           setState(() {
           });


问:
How to retry 104 connection reset by peer connection errors in python requests library without try except
I have the following Session object :

```<code>    import requests
    from requests.adapters import Retry, HTTPAdapter
    from requests.sessions import Session

    retry_strategy: Retry = Retry(
        total=5,
        status_forcelist=[429, 500, 502, 503, 504],
        allowed_methods=["HEAD", "GET", "OPTIONS", "POST"],
        backoff_factor=1
    )
    http_adapter = HTTPAdapter(max_retries=retry_strategy)
    session = requests.Session()
    session.mount("https://", http_adapter)
</code>```

and once in a while the server seems to break the connection with an RST TCP-packet resulting in the following Error:

```<code>{"isError": true,
 "type": "ConnectionError",
 "message": "[Errno 104] Connection reset by peer",
 "traceback": "...  omitted for brevity ...
    File "/var/task/requests/sessions.py", line 590, in post
    return self.request('POST', url, data=data, json=json, **kwargs)
    File "/var/task/requests/sessions.py", line 542, in request
    resp = self.send(prep, **send_kwargs)
    File "/var/task/requests/sessions.py", line 655, in send
    r = adapter.send(request, **kwargs)
    File "/var/task/requests/adapters.py", line 498, in send
    raise ConnectionError(err, request=request)"

</code>```

Is it possible to inject a Retry object in a Session object so that this particular ConnectionError is automatically retried?

Is there any other way to retry automatically without any additional custom logic such as wrapping it in a try... except statement or creating a custom HTTPAdapter?

I have seen multiple posts regarding 104 connection reset by peer errors, but no one asking how to retry it automatically. Why is that? I assume I won't be the only one with this problem?

答:
You would need to provide the "connect" argument:

```<code>  from requests import adapters
  import urllib3

  sync_session = requests.Session()
  retry_adapter = adapters.HTTPAdapter(max_retries=urllib3.Retry(total=1, connect=1))
  session.mount('https://', retry_adapter)
  session.mount('http://', retry_adapter)
</code>```

Test:

```<code>class AdapterTest(unittest.TestCase):

  @mock.patch.object(urllib3.connectionpool.HTTPConnectionPool, '_make_request',
                     side_effect=ConnectionResetError)
  def test_adapter(self, mocked):

    s = requests_extensions.HookableSession()
    try:
      s.mount('http://', adapters.HTTPAdapter(max_retries=urllib3.Retry(total=1, connect=1)))
      s.request('GET', 'http://www.test.com')
    except requests.ConnectionError:
      pass

    self.assertEqual(mocked.call_count, 2)
</code>```

Body:
I have the following Session object :

    import requests
    from requests.adapters import Retry, HTTPAdapter
    from requests.sessions import Session

    retry_strategy: Retry = Retry(
        total=5,
        status_forcelist=[429, 500, 502, 503, 504],
        allowed_methods=["HEAD", "GET", "OPTIONS", "POST"],
        backoff_factor=1
    )
    http_adapter = HTTPAdapter(max_retries=retry_strategy)
    session = requests.Session()
    session.mount("https://", http_adapter)

and once in a while the server seems to break the connection with an RST TCP-packet resulting in the following Error:

{"isError": true,
 "type": "ConnectionError",
 "message": "[Errno 104] Connection reset by peer",
 "traceback": "...  omitted for brevity ...
    File "/var/task/requests/sessions.py", line 590, in post
    return self.request('POST', url, data=data, json=json, **kwargs)
    File "/var/task/requests/sessions.py", line 542, in request
    resp = self.send(prep, **send_kwargs)
    File "/var/task/requests/sessions.py", line 655, in send
    r = adapter.send(request, **kwargs)
    File "/var/task/requests/adapters.py", line 498, in send
    raise ConnectionError(err, request=request)"

Is it possible to inject a Retry object in a Session object so that this particular ConnectionError is automatically retried?

Is there any other way to retry automatically without any additional custom logic such as wrapping it in a try... except statement or creating a custom HTTPAdapter?

I have seen multiple posts regarding 104 connection reset by peer errors, but no one asking how to retry it automatically. Why is that? I assume I won't be the only one with this problem?

Body:
You would need to provide the "connect" argument:

  from requests import adapters
  import urllib3

  sync_session = requests.Session()
  retry_adapter = adapters.HTTPAdapter(max_retries=urllib3.Retry(total=1, connect=1))
  session.mount('https://', retry_adapter)
  session.mount('http://', retry_adapter)

Test:

class AdapterTest(unittest.TestCase):

  @mock.patch.object(urllib3.connectionpool.HTTPConnectionPool, '_make_request',
                     side_effect=ConnectionResetError)
  def test_adapter(self, mocked):

    s = requests_extensions.HookableSession()
    try:
      s.mount('http://', adapters.HTTPAdapter(max_retries=urllib3.Retry(total=1, connect=1)))
      s.request('GET', 'http://www.test.com')
    except requests.ConnectionError:
      pass

    self.assertEqual(mocked.call_count, 2)


问:
Dynamically create AWS S3 buckets in multiple regions
Is there a way to create terraform aws_s3_bucket resources dynamically in different regions? Argument region is no longer supported, creating provider aliases in different regions dynamically is also not supported. Is there a way to do this?

答:
Yes - you can use Provider Aliasing and regions are reported as supported per the AWS provider documentation

I suggest keeping your terraform cleanly modularized when using aliasing to keep the copy/paste code per region to a minimum

Check out this other answer already addressing this for an implementation example (the latest answer 2021)


问:
My firebird query plan does not use correct index
I have a problem with indexes in my firebird query.

Below is my query.

```<code>SELECT a.objid,
       b.running_qty,
       b.running_qty2,
       b.running_totalcost,
       b.running_lastcost
FROM mm_itrghd a,
     mm_itrgdt b
WHERE (a.objid = b.header_id)
AND   (b.item_id = 1200)
AND   (b.wh_id = 1)
AND   ((a.postdate < '2010-09-05 00:00:00')  OR ((a.postdate = '2010-09-05 00:00:00') AND (a.objid < 50000)))
ORDER BY a.postdate desc,
         a.objid desc,
         b.calctyp desc,
         b.objid desc
</code>```

As you see, in order by section, we use desc. I have an descending index, but my query plan does not use it.
It only use index Table A (a.objid) and Table B (b.item_id, b.wh_id)
Is there something i missed? What index do you think should i create?

Index for Table A (mm_itrghd)

(TR_CODE, DOC_ID) Ascending
(OBJID) Ascending
(TR_CODE) Ascending
(POSTDATE) Ascending
(POSTDATE, OBJID) Ascending
(POSTDATE, OBJID) Descending

Index for Table B (mm_itrgdt)

(HEADER_ID) Ascending
(ITEM_ID) Ascending
(WH_ID) Ascending
(LOT_NO) Ascending
(SERIAL_NO, ITEM_ID) Ascending
(HEADER_ID, ITEM_ID, WH_ID, SERIAL_NO, LOT_NO) Ascending
(HEADER_ID, ITEM_ID, WH_ID) Ascending
(CALCTYP, OBJID) Ascending
(ITEM_ID, WH_ID) Ascending
(CALCTYP, OBJID, ITEM_ID, WH_ID) Ascending
(CALCTYP, OBJID) Descending
(OBJID, ITEM_ID, WH_ID) Descending
(OBJID) Descending

Thanks in advance

Regards,
Reynaldi

答:
First of all update indices statistics because Firebird relay on it when choosing what index to use and what not. Either do backup-restore cycle for database or execute following code:

```<code>EXECUTE BLOCK
AS
  DECLARE VARIABLE IDX VARCHAR(31);
BEGIN
  FOR
    SELECT rdb$index_name FROM rdb$indices
    WHERE NOT rdb$index_name LIKE 'RDB$%'
    INTO :idx
  DO BEGIN
    EXECUTE STATEMENT 'update statistics ' || :idx
    WITH AUTONOMOUS TRANSACTION;
  END
END
</code>```

Check the query plan after that. If index is not used it is because Firebird thinks that its usage will do more harm then help. You can either specify plan for query manually or try to rewrite it.

In your case you can get rid of OR condition using UNION operator:

```<code>select
  a.postdate,
  a.objid,
  b.calctyp,
  b.objid,
  b.running_qty,
  b.running_qty2,
  b.running_totalcost,
  b.running_lastcost
from
  mm_itrghd a join mm_itrgdt b
    on a.objid=b.header_id
where
  (b.item_id=1200)
  and (b.wh_id=1)
  and (a.postdate<'2010-09-05 00:00:00')

union all

select
  a.postdate,
  a.objid,
  b.calctyp,
  b.objid,
  b.running_qty,
  b.running_qty2,
  b.running_totalcost,
  b.running_lastcost
from
  mm_itrghd a join mm_itrgdt b
    on a.objid=b.header_id
where
  (b.item_id=1200)
  and (b.wh_id=1)
  and (a.postdate='2010-09-05 00:00:00')
  and (a.objid<50000)

order by
  1 desc, 2 desc, 3 desc, 4 desc
</code>```

Body:
I have a problem with indexes in my firebird query.

Below is my query.

SELECT a.objid,
       b.running_qty,
       b.running_qty2,
       b.running_totalcost,
       b.running_lastcost
FROM mm_itrghd a,
     mm_itrgdt b
WHERE (a.objid = b.header_id)
AND   (b.item_id = 1200)
AND   (b.wh_id = 1)
AND   ((a.postdate < '2010-09-05 00:00:00')  OR ((a.postdate = '2010-09-05 00:00:00') AND (a.objid < 50000)))
ORDER BY a.postdate desc,
         a.objid desc,
         b.calctyp desc,
         b.objid desc

As you see, in order by section, we use desc. I have an descending index, but my query plan does not use it.
It only use index Table A (a.objid) and Table B (b.item_id, b.wh_id)
Is there something i missed? What index do you think should i create?

Index for Table A (mm_itrghd)

(TR_CODE, DOC_ID) Ascending
(OBJID) Ascending
(TR_CODE) Ascending
(POSTDATE) Ascending
(POSTDATE, OBJID) Ascending
(POSTDATE, OBJID) Descending

Index for Table B (mm_itrgdt)

(HEADER_ID) Ascending
(ITEM_ID) Ascending
(WH_ID) Ascending
(LOT_NO) Ascending
(SERIAL_NO, ITEM_ID) Ascending
(HEADER_ID, ITEM_ID, WH_ID, SERIAL_NO, LOT_NO) Ascending
(HEADER_ID, ITEM_ID, WH_ID) Ascending
(CALCTYP, OBJID) Ascending
(ITEM_ID, WH_ID) Ascending
(CALCTYP, OBJID, ITEM_ID, WH_ID) Ascending
(CALCTYP, OBJID) Descending
(OBJID, ITEM_ID, WH_ID) Descending
(OBJID) Descending

Thanks in advance

Regards,
Reynaldi

Body:
First of all update indices statistics because Firebird relay on it when choosing what index to use and what not. Either do backup-restore cycle for database or execute following code:

EXECUTE BLOCK
AS
  DECLARE VARIABLE IDX VARCHAR(31);
BEGIN
  FOR
    SELECT rdb$index_name FROM rdb$indices
    WHERE NOT rdb$index_name LIKE 'RDB$%'
    INTO :idx
  DO BEGIN
    EXECUTE STATEMENT 'update statistics ' || :idx
    WITH AUTONOMOUS TRANSACTION;
  END
END

Check the query plan after that. If index is not used it is because Firebird thinks that its usage will do more harm then help. You can either specify plan for query manually or try to rewrite it.

In your case you can get rid of OR condition using UNION operator:

select
  a.postdate,
  a.objid,
  b.calctyp,
  b.objid,
  b.running_qty,
  b.running_qty2,
  b.running_totalcost,
  b.running_lastcost
from
  mm_itrghd a join mm_itrgdt b
    on a.objid=b.header_id
where
  (b.item_id=1200)
  and (b.wh_id=1)
  and (a.postdate<'2010-09-05 00:00:00')

union all

select
  a.postdate,
  a.objid,
  b.calctyp,
  b.objid,
  b.running_qty,
  b.running_qty2,
  b.running_totalcost,
  b.running_lastcost
from
  mm_itrghd a join mm_itrgdt b
    on a.objid=b.header_id
where
  (b.item_id=1200)
  and (b.wh_id=1)
  and (a.postdate='2010-09-05 00:00:00')
  and (a.objid<50000)

order by
  1 desc, 2 desc, 3 desc, 4 desc


问:
SQL Query Across Partitioned Database (by Day)
So in the past 3 months, we have gone from a Google Sheets with 5 tabs, up to a connected BigQuery DB referencing the Google Sheets with 5 tables and writing queries.  Today, we just upgraded again to a full daily partitioned database.

I am struggling to figure out how to write my queries across multiple days of data.

When I go to start the query it defaults to today.

```<code>SELECT order_number
FROM `project-123456.client_name.orders`
WHERE DATE(submitted_date) = "2022-02-10"
LIMIT 1000
</code>```

I am trying to figure out the syntax for the month of January for example (and I know this isn't right)

```<code>WHERE DATE(submitted_date) = Jan 1 - Jan 31.
</code>```

Any suggestions would be great, I am learning SQL at an alarming pace but in this case, I think I just don't know the right question to ask.

答:
Another option:</p>
```<code>where date_trunc(date(submitted_date), month) = '2022-01-01'
</code>```

Body:
So in the past 3 months, we have gone from a Google Sheets with 5 tabs, up to a connected BigQuery DB referencing the Google Sheets with 5 tables and writing queries.  Today, we just upgraded again to a full daily partitioned database.

I am struggling to figure out how to write my queries across multiple days of data.

When I go to start the query it defaults to today.

SELECT order_number
FROM `project-123456.client_name.orders`
WHERE DATE(submitted_date) = "2022-02-10"
LIMIT 1000

I am trying to figure out the syntax for the month of January for example (and I know this isn't right)

WHERE DATE(submitted_date) = Jan 1 - Jan 31.

Any suggestions would be great, I am learning SQL at an alarming pace but in this case, I think I just don't know the right question to ask.

Body:
Another option:

where date_trunc(date(submitted_date), month) = '2022-01-01'


问:
The difference between the two initialization?
What are the differential factors between these two transformation initialization constructs?</p>
```<code>int main()
{
     VectorXYZ NewLocation = VectorXYZ(30, 30, 0);
     SetLocation(NewLocation);

// and

     SetLocation(VectorXYZ(30, 30, 0));
}
</code>```

答:
If the function SetLocation is declared for example like

```<code>void SetLocation( VectorXYZ & );
</code>```

then  you may it call like

```<code>SetLocation(NewLocation);
</code>```

but may not call it like

```<code> SetLocation(VectorXYZ(30, 30, 0));
</code>```

because you may not bind a temporary object with a non constant lvalue reference.

On the other hand, if the function is declared like

```<code>void SetLocation( VectorXYZ && );
</code>```

then you may call it like

```<code> SetLocation(VectorXYZ(30, 30, 0));
</code>```

but you may not call it like

```<code>SetLocation(NewLocation);
</code>```

If the function is declared like

```<code>void SetLocation( const VectorXYZ & );
</code>```

or like

```<code>void SetLocation( VectorXYZ );
</code>```

then the both calls are valid.

Body:
What are the differential factors between these two transformation initialization constructs?

int main()
{
     VectorXYZ NewLocation = VectorXYZ(30, 30, 0);
     SetLocation(NewLocation);

// and

     SetLocation(VectorXYZ(30, 30, 0));
}

Body:
If the function SetLocation is declared for example like

void SetLocation( VectorXYZ & );

then  you may it call like

SetLocation(NewLocation);

but may not call it like

 SetLocation(VectorXYZ(30, 30, 0));

because you may not bind a temporary object with a non constant lvalue reference.

On the other hand, if the function is declared like

void SetLocation( VectorXYZ && );

then you may call it like

 SetLocation(VectorXYZ(30, 30, 0));

but you may not call it like

SetLocation(NewLocation);

If the function is declared like

void SetLocation( const VectorXYZ & );

or like

void SetLocation( VectorXYZ );

then the both calls are valid.


问:
Visual Studio Asp.net Website Compilation error: Child nodes not allowed
"Child nodes not allowed" seems to be notorious compilation error on Asp.net website if you do some googling.

Environment: WinXp, VS2008 and VS2008 SP1, .NET 3.5 SP1

Behavior: create a brand new Asp.net website (not web application), then just build it, you got compilation error "Child nodes not allowed" on the Web.config on line where it says providerOption name="CompilerVersion" value="v3.5"/>

I got this problem after I re-installed vs2008.  Now, a lot of people are suggesting fixes but none worked for us.  Only one guy mentioned he successfully got rid of this problem by re-installing windows, but we don't want to go that far if we don't have to.  There is another person who opened a ticket to MS but hasn't gotten back a response yet.

If there is anyone out there who has similar environment like us and know how to get around this problem, we'd really appreciate it!!!

Edit  The weirdest part of all this is that I don't know how I got it.  It is a brand new box and brand new installation.

答:
I haven't got that specific error, but try the following (if you haven't already):

Since you re-installed the vs 2008, try re-applying the SP1

Clear all the asp.net temporary folders it generates for the web sites.

LastEditorDisplayName: moocha

OwnerDisplayName: Freddy Rios

ContentLicense: CC BY-SA 2.5


问:
How to Git Ignore Contain "tiu" Word Files
the category like:

```<code>/Script/tiu_adfsfdfdsff.js
/Script/tiu_adfsfdfdsff.js
...
/CSS/tiu_adfsfdfdsff.css
/CSS/tiu_adfsfdfdsff.css
...
</code>```

i want to ignore contain "tiu" files

my .gitignore files is:

```<code>CSS/tiu*.css
Script/tiu*.js
</code>```

but it don't work?

答:
If they're already added to the repository, you need to remove them from the repo without deleting the files. Do that with:

```<code>git rm --cached /Script/tiu*
</code>```

That will remove the objects from the repo and the index, but leave the working directory alone. From then on, they should be happily ignored by git status and git add (and by extension git commit -a).

Body:
the category like:

/Script/tiu_adfsfdfdsff.js
/Script/tiu_adfsfdfdsff.js
...
/CSS/tiu_adfsfdfdsff.css
/CSS/tiu_adfsfdfdsff.css
...

i want to ignore contain "tiu" files

my .gitignore files is:

CSS/tiu*.css
Script/tiu*.js

but it don't work?

Body:
If they're already added to the repository, you need to remove them from the repo without deleting the files. Do that with:

git rm --cached /Script/tiu*

That will remove the objects from the repo and the index, but leave the working directory alone. From then on, they should be happily ignored by git status and git add (and by extension git commit -a).


问:
Intersecting two sets, retaining all (up to) three parts efficiently
If you have two sets a and b and intersect them, there are three interesting parts (which may be empty): h(ead) elements of a not in b, i(ntersection) elements in both a and b, and t(ail) elements of b not in a.

For example: {1, 2, 3} & {2, 3, 4} -> h:{1}, i:{2, 3}, t:{4} (not actual Python code, clearly)

One very clean way to code that in Python:

```<code>h, i, t = a - b, a & b, b - a
</code>```

I figure that this can be slightly more efficient though:

```<code>h, t = a - (i := a & b), b - i
</code>```

Since it first computes the intersection and then subtracts only that from a and then b, which would help if i is small and a and b are large - although I suppose it depends on the implementation of the subtraction whether it's truly faster. It's not likely to be worse, as far as I can tell.

I was unable to find such an operator or function, but since I can imagine efficient implementations that would perform the three-way split of a and b into h, i, and t in fewer iterations, am I missing something like this, which may already exist?

```<code>from magical_set_stuff import hit

h, i, t = hit(a, b)
</code>```

答:
It's not in Python, and I haven't seen such a thing in a 3rd-party library either.

Here's a perhaps unexpected approach that's largely insensitive to which sets are bigger than others, and to how much overlap among inputs there may be. I dreamed it up when facing a related problem: suppose you had 3 input sets, and wanted to derive the 7 interesting sets of overlaps (in A only, B only, C only, both A and B, both A and C, both B and C, or in all 3). This version strips that down to the 2-input case. In general, assign a unique power of 2 to each input, and use those as bit flags:

```<code>def hit(a, b):
    x2flags = defaultdict(int)
    for x in a:
        x2flags[x] = 1
    for x in b:
        x2flags[x] |= 2
    result = [None, set(), set(), set()]
    for x, flag in x2flags.items():
        result[flag].add(x)
    return result[1], result[3], result[2]
</code>```

Body:
If you have two sets a and b and intersect them, there are three interesting parts (which may be empty): h(ead) elements of a not in b, i(ntersection) elements in both a and b, and t(ail) elements of b not in a.

For example: {1, 2, 3} & {2, 3, 4} -> h:{1}, i:{2, 3}, t:{4} (not actual Python code, clearly)

One very clean way to code that in Python:

h, i, t = a - b, a & b, b - a

I figure that this can be slightly more efficient though:

h, t = a - (i := a & b), b - i

Since it first computes the intersection and then subtracts only that from a and then b, which would help if i is small and a and b are large - although I suppose it depends on the implementation of the subtraction whether it's truly faster. It's not likely to be worse, as far as I can tell.

I was unable to find such an operator or function, but since I can imagine efficient implementations that would perform the three-way split of a and b into h, i, and t in fewer iterations, am I missing something like this, which may already exist?

from magical_set_stuff import hit

h, i, t = hit(a, b)

Body:
It's not in Python, and I haven't seen such a thing in a 3rd-party library either.

Here's a perhaps unexpected approach that's largely insensitive to which sets are bigger than others, and to how much overlap among inputs there may be. I dreamed it up when facing a related problem: suppose you had 3 input sets, and wanted to derive the 7 interesting sets of overlaps (in A only, B only, C only, both A and B, both A and C, both B and C, or in all 3). This version strips that down to the 2-input case. In general, assign a unique power of 2 to each input, and use those as bit flags:

def hit(a, b):
    x2flags = defaultdict(int)
    for x in a:
        x2flags[x] = 1
    for x in b:
        x2flags[x] |= 2
    result = [None, set(), set(), set()]
    for x, flag in x2flags.items():
        result[flag].add(x)
    return result[1], result[3], result[2]


问:
Odoo 11: How to correctly implement @api.onchange?
I want to compute a telephone number, if the number in the 8 position is either "0" or "1" I want to print  just the last 4 numbers with a  "(3)" before them, otherwise just print the 4 numbers, but what is happening is that my code is printing "0.0" and I don't know why, I'll appreciate your help...

This is my python code:

class Employee(models.Model):
    _inherit = "hr.employee"

    marcado_rapido = fields.Float("MarcadoRapido",compute='_compute_marcado_rapido')
    @api.onchange("emp.marcado_rapido")
    def onchange_compute_marcado_rapido(self):
        for num in self:
            num = "809-257-1457"
            if num[8] in ('0','1'):
                "(3)"+num[8:]
```
<p>This is my xml code:</p>
<pre class="lang-xml prettyprint-override"><code><td>
    <t t-foreach="env['hr.employee'].search([('department_id', '=', dep.id)])" t-as="emp">
        <div class="contact_form">
            <img t-if="emp.image" t-att-src="'data:image/png;base64,%s' % to_text(emp.image)"/>
            <div class="bloqueP">
                <div class="bloque" t-field="emp.marcado_rapido"/>
            </div>
        </div>
    </t>
</td>
</code>```

答:
You should use compute decoration instead of onchange, but compute method aproach always depend in someone else field. My sugestion is use a another computed field, something like this:

```<code>class Employee(models.Model):
    _inherit = 'hr.employee'

    # If your number contains special characters(like '-') you should use `Char` insted of `float`
    num_telefono = fields.Char('Num. Telefono')
    marcado_rapido = fields.Char('MarcadoRapido', compute='_compute_marcado_rapido')

    @api.depends('num_telefono')
    def _compute_marcado_rapido(self):
        for rec in self:
            num = rec.num_telefono[-4:]
            rec.marcado_rapido = '(3){}'.format(num) if num[:1] in ('0','1') else num
</code>```

Now you can call marcado_rapido from your XML.

I hope this answer can be helful for you.

Body:
I want to compute a telephone number, if the number in the 8 position is either "0" or "1" I want to print  just the last 4 numbers with a  "(3)" before them, otherwise just print the 4 numbers, but what is happening is that my code is printing "0.0" and I don't know why, I'll appreciate your help...

This is my python code:

class Employee(models.Model):
    _inherit = "hr.employee"

    marcado_rapido = fields.Float("MarcadoRapido",compute='_compute_marcado_rapido')
    @api.onchange("emp.marcado_rapido")
    def onchange_compute_marcado_rapido(self):
        for num in self:
            num = "809-257-1457"
            if num[8] in ('0','1'):
                "(3)"+num[8:]

This is my xml code:

    <t t-foreach="env['hr.employee'].search([('department_id', '=', dep.id)])" t-as="emp">

    </t>

Body:
You should use compute decoration instead of onchange, but compute method aproach always depend in someone else field. My sugestion is use a another computed field, something like this:

class Employee(models.Model):
    _inherit = 'hr.employee'

    # If your number contains special characters(like '-') you should use `Char` insted of `float`
    num_telefono = fields.Char('Num. Telefono')
    marcado_rapido = fields.Char('MarcadoRapido', compute='_compute_marcado_rapido')

    @api.depends('num_telefono')
    def _compute_marcado_rapido(self):
        for rec in self:
            num = rec.num_telefono[-4:]
            rec.marcado_rapido = '(3){}'.format(num) if num[:1] in ('0','1') else num

Now you can call marcado_rapido from your XML.

I hope this answer can be helful for you.


问:
SUMMARIZECOLUMNS handling multiple columns with the same name
For debugging purpose I want to create a DAX table using SUMMERIZECOLUMNS fuction which selects the same column names of two different tables.

```<code>Tab = SUMMERIZECOLUMNS ( Sales[Product_ID], Product[Product_ID] )
</code>```

It raises an error:

The Column with the name of 'Product_ID' already exists in the 'Tab'
Table

Replacing Product[Product_ID] with: SELECTCOLUMNS( Product, Product[Product_ID] ) does not solve the problem as it produces error:

A single value for column 'Product[Product_ID]' in table 'Product'
cannot be determined. This can happen when a measure formula refers to
a column that contains many values without specifying an aggregation
such as min, max, count, or sum to get a single result.

答:
We can handle renaming the same column names of different tables with SUMMARIZE. With SELECTCOLUMNS we can refer to both table and column.</p>
```<code>SELECTCOLUMNS(
    SUMMARIZE(
        Sales,
        Sales[Product_ID],
        Product[Product_ID]
    ),
    "Col1", Sales[Product_ID],
    "Col2", Product[Product_ID]
)
</code>```

Body:
For debugging purpose I want to create a DAX table using SUMMERIZECOLUMNS fuction which selects the same column names of two different tables.

Tab = SUMMERIZECOLUMNS ( Sales[Product_ID], Product[Product_ID] )

It raises an error:

The Column with the name of 'Product_ID' already exists in the 'Tab'
Table

Replacing Product[Product_ID] with: SELECTCOLUMNS( Product, Product[Product_ID] ) does not solve the problem as it produces error:

A single value for column 'Product[Product_ID]' in table 'Product'
cannot be determined. This can happen when a measure formula refers to
a column that contains many values without specifying an aggregation
such as min, max, count, or sum to get a single result.

Body:
We can handle renaming the same column names of different tables with SUMMARIZE. With SELECTCOLUMNS we can refer to both table and column.

SELECTCOLUMNS(
    SUMMARIZE(
        Sales,
        Sales[Product_ID],
        Product[Product_ID]
    ),
    "Col1", Sales[Product_ID],
    "Col2", Product[Product_ID]
)


问:
Google Search Console API not returning enough data
https://developers.google.com/webmaster-tools/search-console-api-original/v3/searchanalytics/query

Google Analytics tells me ~20k pages were visited from Google search, but the Google Search Console API returns just under 5k urls. Changing startRow doesn't help.

What's really odd is I've connected Google Search Console to Google Analytics, and when viewing GSC data in GA (Acquisition -> Search Console -> Landing Pages) the GSC data there also gives me ~20k rows.

How do I get all ~20k rows out of the Google Search Console API?

```<code>date_str = '2017-12-20'
start_index = 0
row_limit = 5000
next_index = 5000
rows = []
while next_index == row_limit:
  req = webmasters_service.searchanalytics().query(
      siteUrl='https://tenor.com/',
      fields='responseAggregationType,rows',
      body={
          "startDate": date_str,
          "endDate": date_str,
          "searchType": search_type,
          "dimensions": [
              "page",
          ],
          "rowLimit": row_limit,
          "startRow": start_index,
      },
  )
  try:
      resp = req.execute()
      next_rows = resp['rows']
      rows += next_rows
      next_index = len(next_rows)
      start_index += next_index
  except Exception as e:
      print(e)
      break
return rows
</code>```

答:
For anyone else viewing this post:

When I view 'Search Results' under 'Performance' in the sidebar of the google search console webpage, at the end of the url there is a variable 'resource_id=sc-domain%3example.com'. I recommend using this resource_id variable as your siteURL.

Body:
https://developers.google.com/webmaster-tools/search-console-api-original/v3/searchanalytics/query

Google Analytics tells me ~20k pages were visited from Google search, but the Google Search Console API returns just under 5k urls. Changing startRow doesn't help.

What's really odd is I've connected Google Search Console to Google Analytics, and when viewing GSC data in GA (Acquisition -> Search Console -> Landing Pages) the GSC data there also gives me ~20k rows.

How do I get all ~20k rows out of the Google Search Console API?

date_str = '2017-12-20'
start_index = 0
row_limit = 5000
next_index = 5000
rows = []
while next_index == row_limit:
  req = webmasters_service.searchanalytics().query(
      siteUrl='https://tenor.com/',
      fields='responseAggregationType,rows',
      body={
          "startDate": date_str,
          "endDate": date_str,
          "searchType": search_type,
          "dimensions": [
              "page",
          ],
          "rowLimit": row_limit,
          "startRow": start_index,
      },
  )
  try:
      resp = req.execute()
      next_rows = resp['rows']
      rows += next_rows
      next_index = len(next_rows)
      start_index += next_index
  except Exception as e:
      print(e)
      break
return rows


问:
Cast $event.target to HTMLInputElement within Angular's HTML template
From within a template's input element, I wish to pass $event.target's value to an onChange() function.

<input (input)="onChange($event.target?.value)">
```

This leads to an error: Property 'value' does not exist on type 'EventTarget'.ngtsc(2339). My thoughts are that $event.target by default has an EventTarget type and should be somehow cast to HTMLInputElement type, but I can't find a way to achieve this. All examples I've found suggest to pass $event itself and make a cast within a component's code. Disabling or lowering strictness is also not an option for me. Is there a way to set type directly within a template?

Thanks in advance.

答:
Passing $event is a dubious practice!

use a template reference variable to get the user's input. It's easier to get to the input data with the template reference variable than to go through the $event object.

```<code>@Component({
  selector: 'app-component',
  template: `
    <input #myInput (input)="onChange(myInput.value)">
  `
})
export class AppComponent {
   values = '';
   onChange(value: string) {
      this.values += value;
   }
}
</code>```

Body:
From within a template's input element, I wish to pass $event.target's value to an onChange() function.

<input (input)="onChange($event.target?.value)">

This leads to an error: Property 'value' does not exist on type 'EventTarget'.ngtsc(2339). My thoughts are that $event.target by default has an EventTarget type and should be somehow cast to HTMLInputElement type, but I can't find a way to achieve this. All examples I've found suggest to pass $event itself and make a cast within a component's code. Disabling or lowering strictness is also not an option for me. Is there a way to set type directly within a template?

Thanks in advance.

Body:
Passing $event is a dubious practice!

use a template reference variable to get the user's input. It's easier to get to the input data with the template reference variable than to go through the $event object.

@Component({
  selector: 'app-component',
  template: `
    <input #myInput (input)="onChange(myInput.value)">
  `
})
export class AppComponent {
   values = '';
   onChange(value: string) {
      this.values += value;
   }
}


问:
useSelector does not work when I set two state inside?
Why doesn't my code work? I am trying to separate these two things into one, but useSelector does not work.

This code works

```<code>  const st = useSelector((state) =>
     state.or.st
   );

   const ter = useSelector(
     ({ main }) => main.st.ter
  );
</code>```

This code does not work

I want to put these two things in one useSelector and not in two?

答:
Issue 1: Incorrect Function Usage

The useSelector hook expects a function that takes a single parameter state.

state is the whole state held by redux.

This would mean that your combine function should look more like the following:

```<code>const { units, organistationTerminology } = useSelector(state => {
    organistationTerminology = state.main.organisation.terminology;

    units = state.organisationStructure.units.sort(
        (a, b) => a.sortOrder - b.sortOrder
    );

    return {
        organistationTerminology,
        units
    }
});
</code>```

Issue 2: Changing Reference

The combined selector function returns a new object which will have a difference reference each time the selector function is computed.

The default comparison used by useSelector to detect a change between values is a reference comparison.

This will result in your component being rerendered on any store change regardless of whether state.main.organisation.terminology or state.organisationStructure.units is updated.

Issue 3: Computation in Selector

Selectors will run on each store change and the resulting value will be compared with the previous value to determine whether a component rerender needs to be triggered.

This means that even if state.organisationStructure.units never changes you will still be running a sort on every store change.

Computations should, where possible, be preformed outside of the selector function.

Issue 4: Sort on State Value

sort() sorts the array in place which would be mutating your state.

Conclusion

Selector functions should be kept as simple / quick as possible as they will be run on every store change.

Pulling multiple values from separate sections of state in one selector usually adds more complexity than it is worth.

My suggestion would be to keep it simple:

```<code>const units = useSelector(state => state.organisationStructure.units);

const organistationTerminology = useSelector(state => state.main.organisation.terminology);

const sortedUnits = [...units].sort();

// OR the sort can be memoized using units as a dependency;
const sortedUnits = useMemo(() => [...units].sort(), [units]);
</code>```

If this is something you will be reusing in a number of components you could wrap it up in a custom hook:

```<code>const useTerminologyAndSortedUnits = () => {
    const units = useSelector(state => state.organisationStructure.units);

    const terminology = useSelector(state => state.main.organisation.terminology);

    const sortedUnits = useMemo(() => [...units].sort(), [units]);

    return {
        units: sortedUnits,
        terminology
    }
};

// The following can then be used in any of your function components
const { units, terminology } = useTerminologyAndSortedUnits()
</code>```

Body:
Why doesn't my code work? I am trying to separate these two things into one, but useSelector does not work.

This code works

  const st = useSelector((state) =>
     state.or.st
   );

   const ter = useSelector(
     ({ main }) => main.st.ter
  );

This code does not work

I want to put these two things in one useSelector and not in two?

Body:
Issue 1: Incorrect Function Usage

The useSelector hook expects a function that takes a single parameter state.

state is the whole state held by redux.

This would mean that your combine function should look more like the following:

const { units, organistationTerminology } = useSelector(state => {
    organistationTerminology = state.main.organisation.terminology;

    units = state.organisationStructure.units.sort(
        (a, b) => a.sortOrder - b.sortOrder
    );

    return {
        organistationTerminology,
        units
    }
});

Issue 2: Changing Reference

The combined selector function returns a new object which will have a difference reference each time the selector function is computed.

The default comparison used by useSelector to detect a change between values is a reference comparison.

This will result in your component being rerendered on any store change regardless of whether state.main.organisation.terminology or state.organisationStructure.units is updated.

Issue 3: Computation in Selector

Selectors will run on each store change and the resulting value will be compared with the previous value to determine whether a component rerender needs to be triggered.

This means that even if state.organisationStructure.units never changes you will still be running a sort on every store change.

Computations should, where possible, be preformed outside of the selector function.

Issue 4: Sort on State Value

sort() sorts the array in place which would be mutating your state.

Conclusion

Selector functions should be kept as simple / quick as possible as they will be run on every store change.

Pulling multiple values from separate sections of state in one selector usually adds more complexity than it is worth.

My suggestion would be to keep it simple:

const units = useSelector(state => state.organisationStructure.units);

const organistationTerminology = useSelector(state => state.main.organisation.terminology);

const sortedUnits = [...units].sort();

// OR the sort can be memoized using units as a dependency;
const sortedUnits = useMemo(() => [...units].sort(), [units]);

If this is something you will be reusing in a number of components you could wrap it up in a custom hook:

const useTerminologyAndSortedUnits = () => {
    const units = useSelector(state => state.organisationStructure.units);

    const terminology = useSelector(state => state.main.organisation.terminology);

    const sortedUnits = useMemo(() => [...units].sort(), [units]);

    return {
        units: sortedUnits,
        terminology
    }
};

// The following can then be used in any of your function components
const { units, terminology } = useTerminologyAndSortedUnits()


问:
AWX - Can't accept github fingerprint
I freshly installed awx 19.5.1, on minikube, and i justed wanted to try to add a project linked to a private github repository. but i can't synchronize the project using the url git@github.com:myproject.git, because i can't accept the fingerprint, and the https url refused the cred.

```<code>TASK [update project using git] ************************************************
The authenticity of host 'github.com (140.82.121.4)' can't be established.
ECDSA key fingerprint is SHA256:p2QAMXNIC1TJYWeIOttrVc98/R1BUFWu3/LiyKgUfQM.
</code>```

Any advices ?

答:
You can download the keys from https://api.github.com/meta and insert them into either ~/.ssh/known_hosts by prefixing them with github.com and a space or into /etc/ssh/ssh_known_hosts if you control that on the system.

Alternately, you can write them into any file with suitable permissions, and use GIT_SSH_COMMAND="ssh -oUserKnownHostsFile=path/to/my/file".

Title: AWX - Can't accept github fingerprint

Body:
I freshly installed awx 19.5.1, on minikube, and i justed wanted to try to add a project linked to a private github repository. but i can't synchronize the project using the url git@github.com:myproject.git, because i can't accept the fingerprint, and the https url refused the cred.

TASK [update project using git] ************************************************
The authenticity of host 'github.com (140.82.121.4)' can't be established.
ECDSA key fingerprint is SHA256:p2QAMXNIC1TJYWeIOttrVc98/R1BUFWu3/LiyKgUfQM.

Any advices ?


问:
How do I make my NW.js application *start* in fullscreen?
I know how to enter fullscreen once it's already loaded in a window. This causes an ugly effect where, when I click its icon, briefly flashes a windowed window which immediately goes fullscreen. I hate that effect.

How do I make it actually start, right away, in fullscreen, without ever being in windowed mode even for a split second?

答:
I'm not a JS pro but I code in python and i think if you made a function like this one it would work idk though

function onstart(){
 if (boolean == true):
// Fullscreen code
}
// Your code here
onstart()
```


问:
Changing the xoff coordinates of the mesh after changing the angle to pan in correct direction
I am struggling with setting up coordinates
so that when you change the angle, the mesh moves like a mouse.
So if I move the mouse up, the mesh also goes up and not at the angle I changed. I will be grateful for any hints. Thanks.
This is my code:</p>
```<code>let angle = 0.0;
let dim = 10
let sz;
let xoff;
let yoff;
function setup() {
  createCanvas(400, 400);
  sz = width/ dim;
}

function mouseDragged() {
  xoff += (mouseX - pmouseX)/10;
  yoff += (mouseY - pmouseY)/10;
}

function draw() {
  background(255);

  for (let i = 0; i < dim+2; i++) {
    for (let j = 0; j < dim+2; j++) {

      let x = ((pmouseX + j * sz) % (width+sz)) - sz;
      if (x < -sz) x += width+sz;

      let y = ((pmouseY + i * sz) % (height+sz)) - sz;
      if (y < -sz) y += height+sz;
push();
imageMode(CENTER);
rectMode(CENTER);
translate( width / 2  , height / 2  );
rotate(angle);
translate( -width / 2 , -height / 2  );
      rect(x, y, sz, sz);
      text(i * 10 + j, x + sz/2, y + sz/2);
      pop();
    }
  }
}
</code>```

答:
If I understand your problem correctly I think you can just transform the mouse position into the frame of reference that you are drawing in by rotating the mouse position vector in the reverse direction from the rotation you apply before drawing:

// let angle = 0.0;
let dim = 10;
let sz;
let xoff;
let yoff;

let angleSlider;

function setup() {
  createCanvas(400, 400);
  sz = width / dim;

  angleSlider = createSlider(-180, 180, 0);
  angleSlider.position(10, 10);

  angleMode(DEGREES);
}

function mouseDragged() {
  xoff += (mouseX - pmouseX) / 10;
  yoff += (mouseY - pmouseY) / 10;
}

function draw() {
  background(255);

  let mousePos = createVector(mouseX, mouseY).rotate(-angleSlider.value());
  for (let i = 0; i < dim + 2; i++) {
    for (let j = 0; j < dim + 2; j++) {
      let x = ((mousePos.x + j * sz) % (width + sz)) - sz;
      if (x < -sz) x += width + sz;

      let y = ((mousePos.y + i * sz) % (height + sz)) - sz;
      if (y < -sz) y += height + sz;
      push();
      imageMode(CENTER);
      rectMode(CENTER);
      translate(width / 2, height / 2);
      rotate(angleSlider.value());
      translate(-width / 2, -height / 2);
      rect(x, y, sz, sz);
      text(i * 10 + j, x + sz / 2, y + sz / 2);
      pop();
    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script></code>```

Body:
I am struggling with setting up coordinates
so that when you change the angle, the mesh moves like a mouse.
So if I move the mouse up, the mesh also goes up and not at the angle I changed. I will be grateful for any hints. Thanks.
This is my code:

let angle = 0.0;
let dim = 10
let sz;
let xoff;
let yoff;
function setup() {
  createCanvas(400, 400);
  sz = width/ dim;
}

function mouseDragged() {
  xoff += (mouseX - pmouseX)/10;
  yoff += (mouseY - pmouseY)/10;
}

function draw() {
  background(255);

  for (let i = 0; i < dim+2; i++) {
    for (let j = 0; j < dim+2; j++) {

      let x = ((pmouseX + j * sz) % (width+sz)) - sz;
      if (x < -sz) x += width+sz;

      let y = ((pmouseY + i * sz) % (height+sz)) - sz;
      if (y < -sz) y += height+sz;
push();
imageMode(CENTER);
rectMode(CENTER);
translate( width / 2  , height / 2  );
rotate(angle);
translate( -width / 2 , -height / 2  );
      rect(x, y, sz, sz);
      text(i * 10 + j, x + sz/2, y + sz/2);
      pop();
    }
  }
}

Body:
If I understand your problem correctly I think you can just transform the mouse position into the frame of reference that you are drawing in by rotating the mouse position vector in the reverse direction from the rotation you apply before drawing:

// let angle = 0.0;
let dim = 10;
let sz;
let xoff;
let yoff;

let angleSlider;

function setup() {
  createCanvas(400, 400);
  sz = width / dim;

  angleSlider = createSlider(-180, 180, 0);
  angleSlider.position(10, 10);

  angleMode(DEGREES);
}

function mouseDragged() {
  xoff += (mouseX - pmouseX) / 10;
  yoff += (mouseY - pmouseY) / 10;
}

function draw() {
  background(255);

  let mousePos = createVector(mouseX, mouseY).rotate(-angleSlider.value());
  for (let i = 0; i < dim + 2; i++) {
    for (let j = 0; j < dim + 2; j++) {
      let x = ((mousePos.x + j * sz) % (width + sz)) - sz;
      if (x < -sz) x += width + sz;

      let y = ((mousePos.y + i * sz) % (height + sz)) - sz;
      if (y < -sz) y += height + sz;
      push();
      imageMode(CENTER);
      rectMode(CENTER);
      translate(width / 2, height / 2);
      rotate(angleSlider.value());
      translate(-width / 2, -height / 2);
      rect(x, y, sz, sz);
      text(i * 10 + j, x + sz / 2, y + sz / 2);
      pop();
    }
  }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>


问:
Error in opening text file from src folder in Java
I am making a Java program and want to open a text(notepad) file ,that i have saved in src folder in my Java Program, I have tried to do it by the following code , but it is giving error. "The method exec(String) in the type Runtime is not applicable for the arguments
(InputStream) , Any suggestions ? Thanks

```<code>Runtime runtime = Runtime.getRuntime();
InputStream lic = this.getClass().getClassLoader().getResourceAsStream("MyFile.txt");
Process process = runtime.exec(lic);
</code>```

答:
None of the Runtime.exec methods accept an InputStream

http://download.oracle.com/javase/6/docs/api/java/lang/Runtime.html

To read a file from an InputStream, use a BufferedReader

```<code>BufferedReader reader = new BufferedReader(new InputStreamReader(lic));

String line = reader.readLine()
while(line != null){
    System.out.println(line);
    line = reader.readLine();
}
</code>```

Body:
I am making a Java program and want to open a text(notepad) file ,that i have saved in src folder in my Java Program, I have tried to do it by the following code , but it is giving error. "The method exec(String) in the type Runtime is not applicable for the arguments
(InputStream) , Any suggestions ? Thanks

Runtime runtime = Runtime.getRuntime();
InputStream lic = this.getClass().getClassLoader().getResourceAsStream("MyFile.txt");
Process process = runtime.exec(lic);

Body:
None of the Runtime.exec methods accept an InputStream

http://download.oracle.com/javase/6/docs/api/java/lang/Runtime.html

To read a file from an InputStream, use a BufferedReader

BufferedReader reader = new BufferedReader(new InputStreamReader(lic));

String line = reader.readLine()
while(line != null){
    System.out.println(line);
    line = reader.readLine();
}


问:
What percentage of customers live between 2 & 5 miles from the HQ
I have a table of distances from headquarters in 2 dp. I am trying to find the percentage of customers within 2 and 5 miles.

```<code>SELECT COUNT(DISTANCE) AS COUNT
FROM CUSTOMERS
WHERE DISTANCE BETWEEN 2 AND 5
</code>```

lets me know the number customer within the mile but i'm struggling to percentage, need help please.

```<code>SELECT (a.COUNT / COUNT(DISTANCE)) * 100
FROM (
  SELECT COUNT(DISTANCE) AS COUNT
  FROM CUSTOMERS
  WHERE DISTANCE BETWEEN 2 AND 5
) AS a, CUSTOMERS;
</code>```

this is the query i wrote but its not working

答:
The simplest method may be to use conditional aggregation:

SELECT COUNT(CASE WHEN distance BETWEEN 2 AND 5 THEN 1 END)
       / COUNT(*)
       * 100 AS percentage
FROM   CUSTOMERS
```
<p>Which would find the percentage of customers between 2 and 5 miles out of the total number of customers.</p>
<p>Or you can use:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT COUNT(CASE WHEN distance BETWEEN 2 AND 5 THEN 1 END)
       / COUNT(distance)
       * 100 AS percentage
FROM   CUSTOMERS
</code>```

Which would find the percentage of customers between 2 and 5 miles out of the total number of customers where their distance is known (non-NULL).

Body:
I have a table of distances from headquarters in 2 dp. I am trying to find the percentage of customers within 2 and 5 miles.

SELECT COUNT(DISTANCE) AS COUNT
FROM CUSTOMERS
WHERE DISTANCE BETWEEN 2 AND 5

lets me know the number customer within the mile but i'm struggling to percentage, need help please.

SELECT (a.COUNT / COUNT(DISTANCE)) * 100
FROM (
  SELECT COUNT(DISTANCE) AS COUNT
  FROM CUSTOMERS
  WHERE DISTANCE BETWEEN 2 AND 5
) AS a, CUSTOMERS;

this is the query i wrote but its not working

Body:
The simplest method may be to use conditional aggregation:

SELECT COUNT(CASE WHEN distance BETWEEN 2 AND 5 THEN 1 END)
       / COUNT(*)
       * 100 AS percentage
FROM   CUSTOMERS

Which would find the percentage of customers between 2 and 5 miles out of the total number of customers.

Or you can use:

SELECT COUNT(CASE WHEN distance BETWEEN 2 AND 5 THEN 1 END)
       / COUNT(distance)
       * 100 AS percentage
FROM   CUSTOMERS

Which would find the percentage of customers between 2 and 5 miles out of the total number of customers where their distance is known (non-NULL).


问:
SwiftUI - Get data in remote JSON data to refresh on App startup
I am a noob (and my code/model currently will show it so please go easy on me!).

I’m taking a first whack at creating a recipes style (cenotes) app.

So that I can update the data I have a remote json file, so users won't have to reinstall to get the updated data.

The app successfully retrieves and parses the data (that’s a win!), but only when first installed.

It is not subsequently refreshing the data when it is changed online.   I have tried using .onAppear and also .refreshable unsuccessfully.   I need to delete the App and re-install for it to go and fetch the updated data.

Below are some the redacted versions of my files:  Can anybody help?  I think that I just have a @StateObject/@EnvironmentObject or something similar incorrect, but can’t spot the error.

Locations.swift

```<code>import Foundation

class Locations: ObservableObject {
    @Published var locations = [Location]()

    init() {
        load()
    }

    func load() {
        let url = URL(string: "https://www.i-love-tulum.com/cenotes/locations.json")!
               URLSession.shared.dataTask(with: url) {(data,response,error) in
                   do {
                       if let d = data {
                           let data = try JSONDecoder().decode([Location].self, from: d)
                           DispatchQueue.main.async {
                               self.locations = data
                           }
                       } else {
                           print("No Data")
                       }
                   } catch {
                       print ("Error")
                   }
               }.resume()
    } }
</code>```

Location.swift - VM

```<code>import Foundation

struct Location: Codable, Identifiable {
    var id: String
    let heroPicture: String
    }
</code>```

App.swift - The App opens to this tab view

```<code>import SwiftUI

@main struct App: App {
    @StateObject var locations = Locations()
    @State private var selection = 1

    var body: some Scene {
        WindowGroup {
            TabView (selection:$selection) {
                NavigationView {
                    ListView()
                }
                .tabItem {
                    Image(systemName: "drop.circle")
                    Text("Cenotes")
                } .tag(1)
            }
            .environmentObject(locations)
        }
    } }
</code>```

ListView.swift - The first selected tab is this view - these locations are not updating after the initial install:

```<code>import SwiftUI import MapKit

struct ListView: View {
    @EnvironmentObject var locations: Locations

    var body: some View {
        VStack {
            GeometryReader { geo in
                ScrollView {
                    LazyVStack (alignment: .leading) {
                        ForEach (locations: locations.locations) { location in
                               NavigationLink (
                                    destination: ContentView(location: location),
                                    label: {
                    Image(location.heroPicture)
                    }
            .navigationTitle("Cenotes")
            .navigationBarTitleDisplayMode(.inline)
    } }
</code>```

答:
Try this to reload every time and skip all caches:

UPDATE, now working :)

```<code>func load() {
    let url = URL(string: "https://www.i-love-tulum.com/cenotes/locations.json")!

    let config = URLSessionConfiguration.default
    config.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData

    let session = URLSession.init(configuration: config)
    session.dataTask(with: url) {(data,response,error) in
        do {
            if let d = data {
                let data = try JSONDecoder().decode([Location].self, from: d)
                DispatchQueue.main.async {
                    self.locations = data
                }
            } else {
                print("No Data")
            }
        } catch {
            print ("Error")
        }
    }.resume()
</code>```

Body:
I am a noob (and my code/model currently will show it so please go easy on me!).

I’m taking a first whack at creating a recipes style (cenotes) app.

So that I can update the data I have a remote json file, so users won't have to reinstall to get the updated data.

The app successfully retrieves and parses the data (that’s a win!), but only when first installed.

It is not subsequently refreshing the data when it is changed online.   I have tried using .onAppear and also .refreshable unsuccessfully.   I need to delete the App and re-install for it to go and fetch the updated data.

Below are some the redacted versions of my files:  Can anybody help?  I think that I just have a @StateObject/@EnvironmentObject or something similar incorrect, but can’t spot the error.

Locations.swift

import Foundation

class Locations: ObservableObject {
    @Published var locations = [Location]()

    init() {
        load()
    }

    func load() {
        let url = URL(string: "https://www.i-love-tulum.com/cenotes/locations.json")!
               URLSession.shared.dataTask(with: url) {(data,response,error) in
                   do {
                       if let d = data {
                           let data = try JSONDecoder().decode([Location].self, from: d)
                           DispatchQueue.main.async {
                               self.locations = data
                           }
                       } else {
                           print("No Data")
                       }
                   } catch {
                       print ("Error")
                   }
               }.resume()
    } }

Location.swift - VM

import Foundation

struct Location: Codable, Identifiable {
    var id: String
    let heroPicture: String
    }

App.swift - The App opens to this tab view

import SwiftUI

@main struct App: App {
    @StateObject var locations = Locations()
    @State private var selection = 1

    var body: some Scene {
        WindowGroup {
            TabView (selection:$selection) {
                NavigationView {
                    ListView()
                }
                .tabItem {
                    Image(systemName: "drop.circle")
                    Text("Cenotes")
                } .tag(1)
            }
            .environmentObject(locations)
        }
    } }

ListView.swift - The first selected tab is this view - these locations are not updating after the initial install:

import SwiftUI import MapKit

struct ListView: View {
    @EnvironmentObject var locations: Locations

    var body: some View {
        VStack {
            GeometryReader { geo in
                ScrollView {
                    LazyVStack (alignment: .leading) {
                        ForEach (locations: locations.locations) { location in
                               NavigationLink (
                                    destination: ContentView(location: location),
                                    label: {
                    Image(location.heroPicture)
                    }
            .navigationTitle("Cenotes")
            .navigationBarTitleDisplayMode(.inline)
    } }

Body:
Try this to reload every time and skip all caches:

UPDATE, now working :)

func load() {
    let url = URL(string: "https://www.i-love-tulum.com/cenotes/locations.json")!

    let config = URLSessionConfiguration.default
    config.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData

    let session = URLSession.init(configuration: config)
    session.dataTask(with: url) {(data,response,error) in
        do {
            if let d = data {
                let data = try JSONDecoder().decode([Location].self, from: d)
                DispatchQueue.main.async {
                    self.locations = data
                }
            } else {
                print("No Data")
            }
        } catch {
            print ("Error")
        }
    }.resume()


问:
GDB no debugging symbols found, after assembling with -g -F options
i'm very new in assembly (nasm x86_64), and i run into a problem while i tried to use gdb, which says "no debugging symbols found" after assembling with -g -F dwarf options.
I know that the problem can be caused by using .txt instead of .text, but i have corrected it and it didn't really help. I tried to google it, but i haven't found a solution. My .asm and makefile are on the
screenshot.
P.S. sorry my poor english.

答:
Your linking command
ld ‑m elf_x86_64 ‑s $(source).o ‑o $(source)
will remove the generated DWARF debugging information.
‑s is short for ‑‑strip‑all.
Remove this flag for a debuggable executable.

If you wanted to keep just the debugging information, call strip(1) with ‑‑only‑keep‑debug after the linking step.


问:
Python: hiding input characters with Stars
I am requesting user input. I am asking for username then password.
EG

username = input('Please enter a Username:\n')
password = input('Please enter a Password:\n')
```
<p>When run this will of course appear like this:</p>
```Please enter a Username:
Iain
Please enter a Password:
Iain
```
<p>What I want is this:</p>
```Please enter a Username:
Iain
Please enter a Password:
****
```

答:
You can use a library called pwinput.

You can install it using pip: pip3 install pwinput.

And use it as follows:

```<code>import pwinput
password = pwinput.pwinput()
</code>```

This would open a prompt like this:

```<code>Password: ****
</code>```

If you want to remove the text 'Password:', you can do:

```<code>password = pwinput.pwinput(prompt='')
</code>```

Body:
I am requesting user input. I am asking for username then password.
EG

username = input('Please enter a Username:\n')
password = input('Please enter a Password:\n')

When run this will of course appear like this:

Please enter a Username:
Iain
Please enter a Password:
Iain

What I want is this:

Please enter a Username:
Iain
Please enter a Password:
****

Body:
You can use a library called pwinput.

You can install it using pip: pip3 install pwinput.

And use it as follows:

import pwinput
password = pwinput.pwinput()

This would open a prompt like this:

Password: ****

If you want to remove the text 'Password:', you can do:

password = pwinput.pwinput(prompt='')


问:
Skipping chunk of a big file with bash
Using bash, how to awk/grep from the middle of a given file and skip 1Gig for instance?  In other words, I don't want awk/grep to search through the first 1Gig of the file but want to start my search in the middle of the file.</p>

答:
If you know the full size of the file (lets say 5 million lines) you can do this:

```<code>tail -2000000 filename|grep "yourfilter"
</code>```

This way you will do whatever editing, or printing, starting below the first 3 million lines

Title: Skipping chunk of a big file with bash

Body:
If you know the full size of the file (lets say 5 million lines) you can do this:

tail -2000000 filename|grep "yourfilter"

This way you will do whatever editing, or printing, starting below the first 3 million lines


问:
Firebase Storage track size of uploaded user files with Cloud Storage triggers
I want to keep track of the size of the uploaded files from users.
Every user has his own folder (named after the uid) to upload the files with subfolders for projects. For my understanding it's not easy to get the total filesize for a folder with subfolders in firebase storage. So I found the Cloud Storage triggers (https://firebase.google.com/docs/functions/gcp-storage-events?hl=en) and thought if this would be a great solution to keep the total filesize up to date.
I would update the userdata in firestore with the used storage size when a document is added/edited/deleted from a user.
Is this really a good way?

The examples just show code for image manipulation and download, I couldn't find simple code for jsut getting the metadata filesize and then update a userrecord. Can someone help me here?

Big Thanks!

答:
Managed it so far with:</p>
```<code>exports.storageSizeNewFile = functions.storage.object().onFinalize(async (object) => {
    if (object.name == null) object.name = ""
    var user = { uid: object.name.split("/")[0] }
    var userData: any

    admin.firestore().collection('users').doc(user.uid).get().then(doc => {

        userData = doc.data()
        if (userData.storage == null) userData.storage = { count: 0 }
        userData.storage.count = userData.storage.count + parseInt(object.size)

        admin.firestore().collection('users').doc(user.uid).set({
            storage: userData.storage
        }, { merge: true });

})
</code>```

Body:
Managed it so far with:

exports.storageSizeNewFile = functions.storage.object().onFinalize(async (object) => {
    if (object.name == null) object.name = ""
    var user = { uid: object.name.split("/")[0] }
    var userData: any

    admin.firestore().collection('users').doc(user.uid).get().then(doc => {

        userData = doc.data()
        if (userData.storage == null) userData.storage = { count: 0 }
        userData.storage.count = userData.storage.count + parseInt(object.size)

        admin.firestore().collection('users').doc(user.uid).set({
            storage: userData.storage
        }, { merge: true });

})